diff --git a/apps/server/src/kin/KinServer.ts b/apps/server/src/kin/KinServer.ts index 4bdba5b04f269..b8fdc2b0822c0 100644 --- a/apps/server/src/kin/KinServer.ts +++ b/apps/server/src/kin/KinServer.ts @@ -7,6 +7,7 @@ import { KinChatService } from "./chat/KinChatService.ts"; import { KinChatHub } from "./chat/KinChatHub.ts"; import { KinBudget } from "./lead/KinBudget.ts"; import { KinEventQueue } from "./lead/KinEventQueue.ts"; +import { ApproverKeys } from "./approvals/ApproverKeys.ts"; import { KinStop } from "./lead/KinStop.ts"; import type { KinGithubWebhookLock } from "./triggers/githubWebhooks.ts"; @@ -17,7 +18,8 @@ export type Services = | KinEventQueue | KinChatHub | KinStop - | KinGithubWebhookLock; + | KinGithubWebhookLock + | ApproverKeys; export class KinServer extends Context.Service< KinServer, diff --git a/apps/server/src/kin/approvals/ApproverKeys.test.ts b/apps/server/src/kin/approvals/ApproverKeys.test.ts new file mode 100644 index 0000000000000..5d3d6b47f63f8 --- /dev/null +++ b/apps/server/src/kin/approvals/ApproverKeys.test.ts @@ -0,0 +1,526 @@ +import { assert, describe, it } from "@effect/vitest"; +import { + AuthSessionId, + KinEventId, + KinOrgId, + KinPersonId, + type KinApprovalError, + type KinApprovalsRegisterKeyInput, + type KinPendingAction, +} from "@t3tools/contracts"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; +import * as TestClock from "effect/testing/TestClock"; + +import * as SessionStore from "../../auth/SessionStore.ts"; +import * as Sqlite from "../../persistence/Sqlite.ts"; +import { layerKinAuthTest, repairProofKey } from "../auth/ProofKeySessions.testkit.ts"; +import * as KinPersistence from "../persistence/KinPersistence.ts"; +import { + ApproverKeys, + kinKeyConfirmationCode, + layer as approverKeysLayer, + type KinKeyCaller, + type KinKeyConnection, +} from "./ApproverKeys.ts"; +import * as Audit from "./Audit.ts"; +import { KinAttestationTrust } from "./attestation/AttestationTrust.ts"; +import { androidChain, makeTrustFixture } from "./attestation/testFixtures.ts"; +import { makeRegisterApproverKeyHandler } from "./handlers/registerApproverKey.ts"; +import { + KinPendingActions, + layer as pendingActionsLayer, + type KinPendingActionCreateInput, +} from "./PendingActions.ts"; + +const NOW = Date.parse("2026-11-08T00:00:00Z"); +const fixture = makeTrustFixture(); +const trustLayer = Layer.succeed(KinAttestationTrust, { + load: () => Effect.succeed(fixture.trust), +}); +const database = Layer.provideMerge(KinPersistence.layer, Sqlite.layerMemory); +const layer = approverKeysLayer.pipe( + Layer.provideMerge(pendingActionsLayer), + Layer.provideMerge(Audit.layer), + Layer.provide(trustLayer), + Layer.provideMerge(database), +); + +// Real T3 auth with Kin's proof key hooks, so revocations write what #54 writes. +const relayLayer = approverKeysLayer.pipe( + Layer.provideMerge(pendingActionsLayer), + Layer.provideMerge(Audit.layer), + Layer.provide(trustLayer), + Layer.provideMerge(KinPersistence.layer), + Layer.provideMerge(layerKinAuthTest("kin-approver-keys-")), +); + +const orgId = Schema.decodeSync(KinOrgId)("org_01"); +const owner = Schema.decodeSync(KinPersonId)("h_owner"); +const sessionId = Schema.decodeSync(AuthSessionId); +const decodeEventId = Schema.decodeSync(KinEventId); +const loopback: KinKeyConnection = { remoteAddress: "127.0.0.1", headers: {} }; + +const caller = (id: string, subject: string, connection?: KinKeyConnection): KinKeyCaller => ({ + session: { sessionId: sessionId(id), subject, method: "bearer-access-token", scopes: [] }, + people: [{ _tag: "person", orgId, personId: owner }], + connection: Option.fromUndefinedOr(connection), +}); +const phone = caller("sess-phone", "phone", { remoteAddress: "192.168.1.20", headers: {} }); +const desktop = caller("sess-desktop", "desktop-bootstrap", loopback); + +const seed = Effect.gen(function* () { + yield* TestClock.setTime(NOW); + const sql = yield* SqlClient.SqlClient; + yield* sql`INSERT INTO kin_orgs (org_id, name, created_at) + VALUES ('org_01', 'Kin', '2026-11-07T00:00:00.000Z')`; + for (const [id, subject, ip] of [ + ["sess-phone", "phone", "192.168.1.20"], + ["sess-desktop", "desktop-bootstrap", "127.0.0.1"], + ["sess-desktop-remote", "desktop-bootstrap", "100.101.102.103"], + // A browser, or a tunnel's local process, on the Kin host itself. + ["sess-local-browser", "browser", "127.0.0.1"], + ] as const) { + yield* sql`INSERT INTO auth_sessions (session_id, subject, scopes, method, client_ip_address, + issued_at, expires_at) + VALUES (${id}, ${subject}, '[]', 'bearer-access-token', ${ip}, + '2026-11-07T00:00:00.000Z', '2026-12-07T00:00:00.000Z')`; + } + return { keys: yield* ApproverKeys, actions: yield* KinPendingActions, sql }; +}); + +/** A relay phone: a DPoP session that renews hourly under a new id with the same proof key. */ +const relayPhone = (id: AuthSessionId, proofKeyThumbprint: string): KinKeyCaller => ({ + session: { + sessionId: id, + subject: "phone", + method: "dpop-access-token", + scopes: [], + proofKeyThumbprint, + }, + people: [{ _tag: "person", orgId, personId: owner }], + connection: Option.some({ remoteAddress: "100.64.0.9", headers: {} }), +}); + +const seedRelay = Effect.gen(function* () { + yield* TestClock.setTime(NOW); + const sql = yield* SqlClient.SqlClient; + yield* sql`INSERT INTO kin_orgs (org_id, name, created_at) + VALUES ('org_01', 'Kin', '2026-11-07T00:00:00.000Z')`; + const sessions = yield* SessionStore.SessionStore; + const relay = (proofKey: string) => + sessions + .issue({ proofKeyThumbprint: proofKey, ttl: Duration.hours(1) }) + .pipe(Effect.map((issued) => relayPhone(issued.sessionId, proofKey))); + return { keys: yield* ApproverKeys, sessions, relay }; +}); + +const registerAndroid = ( + keys: ApproverKeys["Service"], + from: KinKeyCaller = phone, + spec: Partial[1]> = {}, +) => + Effect.gen(function* () { + const { challenge } = yield* keys.keyChallenge(from); + const bytes = new Uint8Array(Buffer.from(challenge, "base64url")); + const chain = androidChain(fixture, { challenge: bytes, ...spec }); + const input = { + orgId, + publicJwk: chain.publicJwk, + platform: "android", + challenge, + attestation: { format: "android-key", certificateChain: chain.certificateChain }, + deviceLabel: "Pixel 9", + } satisfies KinApprovalsRegisterKeyInput; + return { ...(yield* keys.registerKey(from, input)), input }; + }); + +const reasonOf = (exit: Exit.Exit) => + Exit.isFailure(exit) && exit.cause.reasons[0]?._tag === "Fail" + ? (exit.cause.reasons[0].error as KinApprovalError).reason + : "success"; + +const mergeRequest = (source: string) => + ({ + orgId: "org_01", + kind: "merge_pull_request", + target: { + _tag: "pull_request", + host: "github.com", + repo: "GLDRoger/t3code", + number: 212, + mergeMethod: "squash", + deleteBranchAfter: false, + }, + resolved: { + _tag: "pull_request", + headSha: "a".repeat(40), + base: "main", + head: "kin/fix-212", + title: "Fix 212", + additions: 3, + deletions: 1, + files: 1, + checks: [], + }, + targetDigest: "1".repeat(64), + reason: "CI is green.", + requestedBy: { agentId: "lead", threadId: "thread-lead" }, + provenance: { startedBy: "github", startedByRole: "none", chain: [], ceilingBelowOwner: true }, + source: decodeEventId(source), + }) as unknown as KinPendingActionCreateInput; + +const approveWith = ( + actions: KinPendingActions["Service"], + action: KinPendingAction, + thumbprint: KinPendingAction["targetDigest"], + jti: string, +) => + actions.approve({ + orgId: action.orgId, + actionId: action.id, + revision: action.revision, + nonce: action.nonce, + jti, + approverHumanId: owner, + keyThumbprint: thumbprint as never, + compact: `compact-${jti}`, + iat: NOW / 1000, + exp: NOW / 1000 + 600, + }); + +const confirmFirst = (keys: ApproverKeys["Service"]) => + Effect.gen(function* () { + const registered = yield* registerAndroid(keys); + yield* keys.confirmKey(desktop, { + orgId, + thumbprint: registered.key.thumbprint, + code: registered.code, + }); + return registered; + }); + +describe("ApproverKeys", () => { + it.effect("the first approver key can't be confirmed from a remote session", () => + Effect.gen(function* () { + const { keys } = yield* seed; + const { key, code } = yield* registerAndroid(keys); + assert.strictEqual(key.state, "pending"); + assert.strictEqual(key.hardware, "strongbox"); + assert.isTrue(key.attested); + const input = { orgId, thumbprint: key.thumbprint, code }; + const remote: ReadonlyArray = [ + phone, + caller("sess-phone", "phone", loopback), + caller("sess-local-browser", "browser", loopback), + caller("sess-desktop", "desktop-bootstrap", { remoteAddress: "100.64.0.9", headers: {} }), + caller("sess-desktop", "desktop-bootstrap", { + remoteAddress: "127.0.0.1", + headers: { "x-forwarded-for": "100.64.0.9" }, + }), + caller("sess-desktop", "desktop-bootstrap", { + remoteAddress: "127.0.0.1", + headers: { "tailscale-user-login": "someone@example.com" }, + }), + caller("sess-desktop", "desktop-bootstrap"), + caller("sess-desktop-remote", "desktop-bootstrap", loopback), + ]; + for (const from of remote) { + assert.strictEqual(reasonOf(yield* Effect.exit(keys.confirmKey(from, input))), "not_local"); + } + const wrong = code === "000000" ? "000001" : "000000"; + assert.strictEqual( + reasonOf(yield* Effect.exit(keys.confirmKey(desktop, { ...input, code: wrong }))), + "bad_code", + ); + const confirmed = yield* keys.confirmKey(desktop, input); + assert.strictEqual(confirmed.state, "active"); + assert.deepStrictEqual(yield* keys.requireActive(key), confirmed); + }).pipe(Effect.provide(layer)), + ); + + it.effect( + "a grant signed by a revoked key is rejected, and revoking voids approved actions it signed", + () => + Effect.gen(function* () { + const { keys, actions } = yield* seed; + const { key } = yield* confirmFirst(keys); + const signed = (yield* actions.create(mergeRequest("evt-1"))).action; + const waiting = (yield* actions.create(mergeRequest("evt-2"))).action; + assert.strictEqual( + (yield* approveWith(actions, signed, key.thumbprint, "jti-1"))._tag, + "approved", + ); + + const revoked = yield* keys.revokeKey(phone, key); + assert.strictEqual(revoked.state, "revoked"); + assert.strictEqual(reasonOf(yield* Effect.exit(keys.requireActive(key))), "revoked_key"); + const voided = yield* actions.get({ orgId, actionId: signed.id }); + assert.strictEqual(Option.getOrThrow(voided).state, "voided"); + assert.strictEqual(Option.getOrThrow(voided).stateReason, "key_revoked"); + const untouched = yield* actions.get({ orgId, actionId: waiting.id }); + assert.strictEqual(Option.getOrThrow(untouched).state, "awaiting_approval"); + // Revoking is idempotent and never brings a key back. + assert.strictEqual((yield* keys.revokeKey(phone, key)).state, "revoked"); + }).pipe(Effect.provide(layer)), + ); + + it.effect("revoking the T3 session a key was registered from revokes the key", () => + Effect.gen(function* () { + const { keys, actions, sql } = yield* seed; + const { key } = yield* confirmFirst(keys); + const signed = (yield* actions.create(mergeRequest("evt-1"))).action; + yield* approveWith(actions, signed, key.thumbprint, "jti-1"); + yield* sql`UPDATE auth_sessions SET revoked_at = '2026-11-08T00:00:00.000Z' + WHERE session_id = 'sess-phone'`; + + assert.strictEqual(reasonOf(yield* Effect.exit(keys.requireActive(key))), "revoked_key"); + const { keys: listed } = yield* keys.listKeys(desktop, { orgId }); + assert.deepStrictEqual( + listed.map((listedKey) => listedKey.state), + ["revoked"], + ); + const voided = Option.getOrThrow(yield* actions.get({ orgId, actionId: signed.id })); + assert.strictEqual(voided.stateReason, "session_revoked"); + }).pipe(Effect.provide(layer)), + ); + + it.effect( + "revoking a renewed relay session revokes the key registered under an earlier one", + () => + Effect.gen(function* () { + const { keys, sessions, relay } = yield* seedRelay; + const { key } = yield* registerAndroid(keys, yield* relay("phone-a")); + yield* TestClock.adjust(Duration.minutes(61)); + const renewed = yield* relay("phone-a"); + yield* sessions.revoke(renewed.session.sessionId); + assert.strictEqual(Option.getOrThrow(yield* keys.get(key)).state, "revoked"); + }).pipe(Effect.provide(relayLayer)), + ); + + it.effect("signing out other devices from a phone keeps its own key and revokes the others", () => + Effect.gen(function* () { + const { keys, sessions, relay } = yield* seedRelay; + const own = yield* registerAndroid(keys, yield* relay("phone-a")); + const other = yield* registerAndroid(keys, yield* relay("phone-b")); + yield* TestClock.adjust(Duration.minutes(30)); + // Both renew early; the phone's first session is still live when it signs the others out. + const current = yield* relay("phone-a"); + yield* relay("phone-b"); + yield* sessions.revokeAllExcept(current.session.sessionId); + assert.strictEqual(Option.getOrThrow(yield* keys.get(own.key)).state, "pending"); + assert.strictEqual(Option.getOrThrow(yield* keys.get(other.key)).state, "revoked"); + }).pipe(Effect.provide(relayLayer)), + ); + + it.effect("signing out other devices revokes a phone whose sessions had all expired", () => + Effect.gen(function* () { + const { keys, sessions, relay } = yield* seedRelay; + const other = yield* registerAndroid(keys, yield* relay("phone-b")); + yield* TestClock.adjust(Duration.minutes(61)); + const current = yield* relay("phone-a"); + yield* sessions.revokeAllExcept(current.session.sessionId); + assert.strictEqual(Option.getOrThrow(yield* keys.get(other.key)).state, "revoked"); + }).pipe(Effect.provide(relayLayer)), + ); + + it.effect("revoking a session after it expired leaves its key alone", () => + Effect.gen(function* () { + const { keys, sessions, relay } = yield* seedRelay; + const phoneA = yield* relay("phone-a"); + const { key } = yield* registerAndroid(keys, phoneA); + yield* TestClock.adjust(Duration.minutes(61)); + yield* sessions.revoke(phoneA.session.sessionId); + assert.strictEqual(Option.getOrThrow(yield* keys.get(key)).state, "pending"); + }).pipe(Effect.provide(relayLayer)), + ); + + it.effect("a proof key registers an approver key once every revocation of it is repaired", () => + Effect.gen(function* () { + const { keys, sessions, relay } = yield* seedRelay; + const signedOut = yield* relay("phone-a"); + yield* sessions.revoke(signedOut.session.sessionId); + // A call that authenticated just before the revocation landed. + assert.strictEqual( + reasonOf(yield* Effect.exit(registerAndroid(keys, signedOut))), + "invalid_state", + ); + const repaired = yield* repairProofKey("phone-a"); + yield* TestClock.adjust(Duration.minutes(1)); + const { key } = yield* registerAndroid(keys, relayPhone(repaired.sessionId, "phone-a")); + // Reconcile doesn't count the repaired revocation from before the key existed. + assert.strictEqual(Option.getOrThrow(yield* keys.get(key)).state, "pending"); + }).pipe(Effect.provide(relayLayer)), + ); + + it.effect("a revocation after a key registered revokes it for good, even once repaired", () => + Effect.gen(function* () { + const { keys, sessions, relay } = yield* seedRelay; + const phoneA = yield* relay("phone-a"); + const first = yield* registerAndroid(keys, phoneA); + yield* TestClock.adjust(Duration.minutes(1)); + // No key read between the revocation and the repair, so only `created_at` can catch it. + yield* sessions.revoke(phoneA.session.sessionId); + const repaired = yield* repairProofKey("phone-a"); + yield* TestClock.adjust(Duration.minutes(1)); + assert.strictEqual(Option.getOrThrow(yield* keys.get(first.key)).state, "revoked"); + const second = yield* registerAndroid(keys, relayPhone(repaired.sessionId, "phone-a")); + assert.strictEqual(Option.getOrThrow(yield* keys.get(second.key)).state, "pending"); + assert.strictEqual(Option.getOrThrow(yield* keys.get(first.key)).state, "revoked"); + }).pipe(Effect.provide(relayLayer)), + ); + + it.effect("the server never activates an unattested key", () => + Effect.gen(function* () { + const { keys } = yield* seed; + const { challenge } = yield* keys.keyChallenge(phone); + const ios = yield* keys.registerKey(phone, { + orgId, + publicJwk: androidChain(fixture, { challenge: new Uint8Array(32) }).publicJwk, + platform: "ios", + challenge, + deviceLabel: "iPhone", + }); + assert.strictEqual(ios.key.attested, false); + assert.strictEqual(ios.key.hardware, "software"); + const failed = yield* registerAndroid(keys, phone, { deviceLocked: false }); + assert.strictEqual(failed.key.attested, false); + // Re-registering an attested key's public key without attestation can't downgrade it. + const attested = yield* registerAndroid(keys); + const replay = yield* keys.keyChallenge(phone); + const downgrade = yield* Effect.exit( + keys.registerKey(phone, { + orgId, + publicJwk: attested.input.publicJwk, + platform: "ios", + challenge: replay.challenge, + deviceLabel: "iPhone", + }), + ); + assert.strictEqual(reasonOf(downgrade), "invalid_state"); + assert.isTrue(Option.getOrThrow(yield* keys.get(attested.key)).attested); + for (const { key, code } of [ios, failed]) { + const exit = yield* Effect.exit( + keys.confirmKey(desktop, { orgId, thumbprint: key.thumbprint, code }), + ); + assert.strictEqual(reasonOf(exit), "unattested"); + assert.isFalse(yield* keys.activateByGrant(key)); + } + }).pipe(Effect.provide(layer)), + ); + + it.effect("a key challenge is single-use, bound to its session and expires in 5 minutes", () => + Effect.gen(function* () { + const { keys } = yield* seed; + const { challenge } = yield* keys.keyChallenge(desktop); + const other = yield* Effect.exit(registerAndroidWith(keys, phone, challenge)); + assert.strictEqual(reasonOf(other), "bad_challenge"); + + const first = yield* keys.keyChallenge(phone); + yield* registerAndroidWith(keys, phone, first.challenge); + const reused = yield* Effect.exit(registerAndroidWith(keys, phone, first.challenge)); + assert.strictEqual(reasonOf(reused), "bad_challenge"); + + const late = yield* keys.keyChallenge(phone); + yield* TestClock.adjust("5 minutes"); + const expired = yield* Effect.exit(registerAndroidWith(keys, phone, late.challenge)); + assert.strictEqual(reasonOf(expired), "bad_challenge"); + }).pipe(Effect.provide(layer)), + ); + + it.effect("five wrong codes end the confirmation", () => + Effect.gen(function* () { + const { keys } = yield* seed; + const { key, code, input } = yield* registerAndroid(keys); + assert.strictEqual( + code, + kinKeyConfirmationCode( + key.thumbprint, + new Uint8Array(Buffer.from(input.challenge, "base64url")), + ), + ); + const wrong = code === "000000" ? "000001" : "000000"; + for (let attempt = 0; attempt < 5; attempt++) { + yield* Effect.exit( + keys.confirmKey(desktop, { orgId, thumbprint: key.thumbprint, code: wrong }), + ); + } + const exit = yield* Effect.exit( + keys.confirmKey(desktop, { orgId, thumbprint: key.thumbprint, code }), + ); + assert.strictEqual(reasonOf(exit), "bad_code"); + }).pipe(Effect.provide(layer)), + ); + + it.effect("a later key needs a register_approver_key grant from an active key", () => + Effect.gen(function* () { + const { keys, actions, sql } = yield* seed; + const first = yield* confirmFirst(keys); + const second = yield* registerAndroid(keys, phone, { attestationLevel: 1, keyMintLevel: 1 }); + const desktopConfirm = yield* Effect.exit( + keys.confirmKey(desktop, { orgId, thumbprint: second.key.thumbprint, code: second.code }), + ); + assert.strictEqual(reasonOf(desktopConfirm), "invalid_state"); + + const [row] = yield* sql<{ action_id: string }>`SELECT action_id FROM kin_pending_actions + WHERE kind = 'register_approver_key' AND state = 'awaiting_approval'`; + const action = Option.getOrThrow( + yield* actions.get({ orgId, actionId: row!.action_id as KinPendingAction["id"] }), + ); + assert.deepStrictEqual(action.target, { + _tag: "device_key", + thumbprint: second.key.thumbprint, + hardware: "tee", + attested: true, + }); + assert.deepStrictEqual(action.provenance.startedBy, { humanId: owner }); + + const approved = yield* approveWith(actions, action, first.key.thumbprint, "jti-key"); + assert.strictEqual(approved._tag, "approved"); + if (approved._tag !== "approved") return; + const handler = yield* makeRegisterApproverKeyHandler; + assert.strictEqual(yield* handler.reconcile(action), "not_done"); + // The stored key must still be what the card described. + yield* sql`UPDATE kin_approver_keys SET hardware = 'strongbox' WHERE thumbprint = ${second.key.thumbprint}`; + assert.isTrue(Exit.isFailure(yield* Effect.exit(handler.run(action, approved.grant)))); + yield* sql`UPDATE kin_approver_keys SET hardware = 'tee' WHERE thumbprint = ${second.key.thumbprint}`; + assert.strictEqual(yield* handler.run(action, approved.grant), "succeeded"); + assert.strictEqual(yield* handler.reconcile(action), "done"); + assert.strictEqual((yield* keys.requireActive(second.key)).state, "active"); + // A second run finds nothing pending. + assert.isTrue(Exit.isFailure(yield* Effect.exit(handler.run(action, approved.grant)))); + + const third = yield* registerAndroid(keys); + yield* keys.revokeKey(phone, third.key); + const [cancelled] = yield* sql<{ state: string }>`SELECT state FROM kin_pending_actions + WHERE kind = 'register_approver_key' + AND json_extract(target_json, '$.thumbprint') = ${third.key.thumbprint}`; + assert.strictEqual(cancelled?.state, "cancelled"); + + yield* sql`ALTER TABLE kin_approver_keys RENAME TO kin_approver_keys_gone`; + assert.strictEqual( + reasonOf(yield* Effect.exit(keys.listKeys(phone, { orgId }))), + "unavailable", + ); + }).pipe(Effect.provide(layer)), + ); +}); + +function registerAndroidWith(keys: ApproverKeys["Service"], from: KinKeyCaller, challenge: string) { + const chain = androidChain(fixture, { + challenge: new Uint8Array(Buffer.from(challenge, "base64url")), + }); + return keys.registerKey(from, { + orgId, + publicJwk: chain.publicJwk, + platform: "android", + challenge, + attestation: { format: "android-key", certificateChain: chain.certificateChain }, + deviceLabel: "Pixel 9", + }); +} diff --git a/apps/server/src/kin/approvals/ApproverKeys.ts b/apps/server/src/kin/approvals/ApproverKeys.ts new file mode 100644 index 0000000000000..4c19b4abb87c8 --- /dev/null +++ b/apps/server/src/kin/approvals/ApproverKeys.ts @@ -0,0 +1,552 @@ +// @effect-diagnostics nodeBuiltinImport:off -- synchronous SHA-256 and constant-time compares. +import * as NodeCrypto from "node:crypto"; + +import { + KinActionTarget, + KinAgentId, + KinApprovalError, + KinApproverKey, + KinEventId, + ThreadId, + type AuthSessionId, + type Hex64, + type KinActionKind, + type KinApprovalsConfirmKeyInput, + type KinApprovalsKeyChallengeResult, + type KinApprovalsKeyInput, + type KinApprovalsListKeysResult, + type KinApprovalsOrgInput, + type KinApprovalsRegisterKeyInput, + type KinApprovalsRegisterKeyResult, + type KinKeyThumbprint, + type KinOrgId, +} from "@t3tools/contracts"; +import { computeDpopJwkThumbprint } from "@t3tools/shared/dpop"; +import { isLocalLoopbackHost } from "@t3tools/shared/hostClassification"; +import { stableStringify } from "@t3tools/shared/relaySigning"; +import * as Clock from "effect/Clock"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as Base64Url from "effect/encoding/Base64Url"; +import * as SqlClient from "effect/sql/SqlClient"; + +import { toPersistenceSqlError } from "../../persistence/Errors.ts"; + +import type { AuthenticatedSession } from "../../auth/EnvironmentAuth.ts"; +import { proofKeyRevoked, revokedBySession } from "../auth/ProofKeySessions.ts"; +import type { PersonIdentity } from "../chat/KinIdentity.ts"; +import { KinAttestationTrust } from "./attestation/AttestationTrust.ts"; +import { + verifyAndroidKeyAttestation, + verifyAppleAppAttest, + type AttestationResult, +} from "./attestation/verify.ts"; +import { KIN_APPROVER_KEYS_REQUESTER, KinPendingActions } from "./PendingActions.ts"; + +const CHALLENGE_TTL_MS = 5 * 60 * 1000; +const CONFIRM_TTL_MS = 10 * 60 * 1000; +const MAX_CODE_ATTEMPTS = 5; +// The desktop app's own credential; CloudLink trusts the same subject as "this machine". +const DESKTOP_SUBJECT = "desktop-bootstrap"; +const FORWARDING_HEADERS = [ + "forwarded", + "x-forwarded-for", + "x-forwarded-host", + "x-forwarded-proto", + "x-real-ip", + "cf-connecting-ip", + "tailscale-user-login", +]; + +/** The live socket a call arrived on, read when the WS connection was set up. */ +export type KinKeyConnection = { + readonly remoteAddress: string | undefined; + readonly headers: Readonly>; +}; + +export type KinKeyCaller = { + readonly session: AuthenticatedSession; + readonly people: ReadonlyArray; + readonly connection: Option.Option; +}; + +type KeyRef = { readonly orgId: KinOrgId; readonly thumbprint: KinKeyThumbprint }; + +type KeyRow = { + readonly thumbprint: string; + readonly org_id: string; + readonly public_jwk_json: string; + readonly human_id: string; + readonly device_label: string; + readonly platform: string; + readonly hardware: string; + readonly attested: number; + readonly session_id: string | null; + readonly proof_key_thumbprint: string | null; + readonly state: string; + readonly created_at: number; + readonly confirmed_at: number | null; + readonly revoked_at: number | null; +}; + +const iso = (ms: number) => DateTime.formatIso(DateTime.makeUnsafe(ms)); +const decodeKey = Schema.decodeUnknownEffect(KinApproverKey); +const decodeEventId = Schema.decodeEffect(KinEventId); +const decodeTarget = Schema.decodeUnknownEffect(KinActionTarget); +const isKinApprovalError = Schema.is(KinApprovalError); + +const SERVER_REQUESTER = { + agentId: Schema.decodeSync(KinAgentId)(KIN_APPROVER_KEYS_REQUESTER), + threadId: Schema.decodeSync(ThreadId)(KIN_APPROVER_KEYS_REQUESTER), +}; + +const fail = (reason: KinApprovalError["reason"], message: string) => + Effect.fail(new KinApprovalError({ reason, message })); + +const sameBytes = (a: string, b: string) => { + const left = Buffer.from(a); + const right = Buffer.from(b); + return left.length === right.length && NodeCrypto.timingSafeEqual(left, right); +}; + +/** Spec section 4: six digits from `sha256(thumbprint ‖ serverNonce)`; the nonce is the challenge. */ +export const kinKeyConfirmationCode = (thumbprint: string, challenge: Uint8Array) => { + const digest = NodeCrypto.createHash("sha256").update(thumbprint).update(challenge).digest(); + return String(digest.readUInt32BE(0) % 1_000_000).padStart(6, "0"); +}; + +/** `sha256(stableStringify({kind, target, headSha?, base?}))`, approvals spec section 3. */ +const kinTargetDigest = (kind: KinActionKind, target: KinActionTarget): Hex64 => + NodeCrypto.createHash("sha256").update(stableStringify({ kind, target })).digest("hex"); + +const toKey = (row: KeyRow) => + decodeKey({ + orgId: row.org_id, + thumbprint: row.thumbprint, + publicJwk: JSON.parse(row.public_jwk_json), + humanId: row.human_id, + deviceLabel: row.device_label, + platform: row.platform, + hardware: row.hardware, + attested: row.attested === 1, + ...(row.session_id === null ? {} : { sessionId: row.session_id }), + state: row.state, + createdAt: iso(row.created_at), + ...(row.confirmed_at === null ? {} : { confirmedAt: iso(row.confirmed_at) }), + ...(row.revoked_at === null ? {} : { revokedAt: iso(row.revoked_at) }), + }); + +/** Only `ws` connections from this machine with no proxy in between. */ +const isLoopbackConnection = (connection: KinKeyConnection) => + connection.remoteAddress !== undefined && + isLocalLoopbackHost(connection.remoteAddress.replace(/^::ffff:/i, "")) && + FORWARDING_HEADERS.every((name) => connection.headers[name] === undefined); + +export class ApproverKeys extends Context.Service< + ApproverKeys, + { + readonly keyChallenge: ( + caller: KinKeyCaller, + ) => Effect.Effect; + readonly registerKey: ( + caller: KinKeyCaller, + input: KinApprovalsRegisterKeyInput, + ) => Effect.Effect; + /** The first key in an org, on the desktop app on this machine, with the phone's code. */ + readonly confirmKey: ( + caller: KinKeyCaller, + input: KinApprovalsConfirmKeyInput, + ) => Effect.Effect; + readonly listKeys: ( + caller: KinKeyCaller, + input: KinApprovalsOrgInput, + ) => Effect.Effect; + readonly revokeKey: ( + caller: KinKeyCaller, + input: KinApprovalsKeyInput, + ) => Effect.Effect; + /** What grant verification and the executor trust: the key, after session revocations. */ + readonly get: (ref: KeyRef) => Effect.Effect, KinApprovalError>; + /** Grant check 2: an `active` key in the org, else `unknown_key` or `revoked_key`. */ + readonly requireActive: (ref: KeyRef) => Effect.Effect; + /** The `register_approver_key` handler's step, only after a verified grant. */ + readonly activateByGrant: (ref: KeyRef) => Effect.Effect; + /** Revokes keys whose T3 session was revoked. Returns how many. */ + /** One org, or every org at startup: sessions are environment-local (the `kin_auth_*` exception). */ + readonly reconcileSessions: ( + orgId: KinOrgId | undefined, + ) => Effect.Effect; + } +>()("t3/kin/approvals/ApproverKeys") {} + +const make = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const trust = yield* KinAttestationTrust; + const actions = yield* KinPendingActions; + // Single-use, session-bound, short-lived: memory is enough, and a restart only means retrying. + const challenges = new Map< + AuthSessionId, + { readonly challenge: string; readonly expiresAt: number } + >(); + const confirmations = new Map< + string, + { readonly code: string; readonly expiresAt: number; attempts: number } + >(); + const slot = (ref: KeyRef) => `${ref.orgId}\u0000${ref.thumbprint}`; + + // Callers see a plain refusal; the cause is logged through the persistence error shape. + const internal = (operation: string) => (cause: unknown) => + isKinApprovalError(cause) + ? Effect.fail(cause) + : Effect.logWarning(`${operation} failed`, toPersistenceSqlError(operation)(cause)).pipe( + Effect.andThen( + Effect.fail( + new KinApprovalError({ reason: "unavailable", message: `${operation} failed.` }), + ), + ), + ); + + const personIn = (caller: KinKeyCaller, orgId: KinOrgId) => { + const person = caller.people.find((candidate) => candidate.orgId === orgId); + return person === undefined + ? fail("not_owner", "Only a person in this org can manage its approver keys.") + : Effect.succeed(person); + }; + + const select = (ref: KeyRef) => + sql`SELECT * FROM kin_approver_keys + WHERE org_id = ${ref.orgId} AND thumbprint = ${ref.thumbprint}`.pipe( + Effect.map((rows) => rows[0]), + ); + + const hasActiveKey = (orgId: KinOrgId) => + sql`SELECT 1 FROM kin_approver_keys WHERE org_id = ${orgId} AND state = 'active' LIMIT 1`.pipe( + Effect.map((rows) => rows.length > 0), + ); + + /** Sets `revoked`, voids approved actions this key signed, cancels its pending registration. */ + const revokeRow = (ref: KeyRef, reason: string) => + sql.withTransaction( + Effect.gen(function* () { + const now = yield* Clock.currentTimeMillis; + const [row] = yield* sql`UPDATE kin_approver_keys + SET state = 'revoked', revoked_at = ${now} + WHERE org_id = ${ref.orgId} AND thumbprint = ${ref.thumbprint} AND state != 'revoked' + RETURNING *`; + if (row === undefined) return undefined; + yield* sql`UPDATE kin_pending_actions + SET state = 'voided', state_reason = ${reason}, updated_at = ${now} + WHERE org_id = ${ref.orgId} AND state = 'approved' AND EXISTS ( + SELECT 1 FROM kin_grants g + WHERE g.action_id = kin_pending_actions.action_id + AND g.revision = kin_pending_actions.revision + AND g.key_thumbprint = ${ref.thumbprint} AND g.consumed_at IS NULL)`; + yield* sql`UPDATE kin_pending_actions + SET state = 'cancelled', state_reason = ${reason}, updated_at = ${now} + WHERE org_id = ${ref.orgId} AND kind = 'register_approver_key' + AND state = 'awaiting_approval' + AND json_extract(target_json, '$.thumbprint') = ${ref.thumbprint}`; + confirmations.delete(slot(ref)); + return row; + }), + ); + + // T3 revokes sessions in SessionStore (revokeClient, revokeOtherClients, managed policy). + // Reading its table here keeps auth free of Kin hooks, and runs before every key is trusted. + // Relay sessions renew under new ids, so the DPoP key's own revocations count too (spec section 4). + const reconcileSessions = Effect.fn("ApproverKeys.reconcileSessions")( + function* (orgId: KinOrgId | undefined) { + const rows = yield* sql<{ org_id: KinOrgId; thumbprint: KinKeyThumbprint }>` + SELECT k.org_id, k.thumbprint FROM kin_approver_keys k + WHERE k.state != 'revoked' AND ${orgId === undefined ? sql`1 = 1` : sql`k.org_id = ${orgId}`} + AND ${revokedBySession( + sql, + { sessionId: sql`k.session_id`, proofKey: sql`k.proof_key_thumbprint` }, + { since: sql`k.created_at` }, + )} + ORDER BY k.org_id, k.thumbprint`; + for (const row of rows) { + yield* revokeRow({ orgId: row.org_id, thumbprint: row.thumbprint }, "session_revoked"); + } + return rows.length; + }, + Effect.catch(internal("ApproverKeys.reconcileSessions")), + ); + + const keyChallenge = Effect.fn("ApproverKeys.keyChallenge")(function* (caller: KinKeyCaller) { + if (caller.people.length === 0) + return yield* fail("not_owner", "Only a person can register an approver key."); + const now = yield* Clock.currentTimeMillis; + for (const [sessionId, entry] of challenges) { + if (entry.expiresAt <= now) challenges.delete(sessionId); + } + const challenge = Base64Url.encode(SecureRandom.randomBytesUnsafe(32)); + const expiresAt = now + CHALLENGE_TTL_MS; + challenges.set(caller.session.sessionId, { challenge, expiresAt }); + return { challenge, expiresAt: DateTime.makeUnsafe(expiresAt) }; + }); + + const attest = Effect.fn("ApproverKeys.attest")(function* ( + input: KinApprovalsRegisterKeyInput, + challenge: Uint8Array, + ) { + const attestation = input.attestation; + const format = input.platform === "android" ? "android-key" : "apple-app-attest"; + if (attestation === undefined || attestation.format !== format) + return { attested: false, reason: `no ${format} attestation` } satisfies AttestationResult; + const loaded = yield* trust + .load(input.platform) + .pipe( + Effect.mapError( + (error) => new KinApprovalError({ reason: "unavailable", message: error.message }), + ), + ); + const now = yield* Clock.currentTimeMillis; + const common = { challenge, publicJwk: input.publicJwk, trust: loaded, now }; + return attestation.format === "android-key" + ? verifyAndroidKeyAttestation({ ...common, certificateChain: attestation.certificateChain }) + : verifyAppleAppAttest({ + ...common, + keyId: attestation.keyId, + attestationObject: attestation.attestationObject, + }); + }); + + const registerKey = Effect.fn("ApproverKeys.registerKey")( + function* (caller: KinKeyCaller, input: KinApprovalsRegisterKeyInput) { + const person = yield* personIn(caller, input.orgId); + const now = yield* Clock.currentTimeMillis; + const issued = challenges.get(caller.session.sessionId); + challenges.delete(caller.session.sessionId); + if ( + issued === undefined || + issued.expiresAt <= now || + !sameBytes(issued.challenge, input.challenge) + ) + return yield* fail("bad_challenge", "Ask for a new key challenge on this connection."); + const challenge = new Uint8Array(Buffer.from(input.challenge, "base64url")); + yield* reconcileSessions(input.orgId); + // Mobile keeps one DPoP key per install, so a repaired revocation must not lock it out. + const proofKey = caller.session.proofKeyThumbprint; + if (proofKey !== undefined) { + const [seen] = yield* sql<{ + revoked: number; + }>`SELECT ${proofKeyRevoked(sql, proofKey)} AS revoked`; + if (seen?.revoked === 1) + return yield* fail( + "invalid_state", + "This phone was signed out. Ask the owner to restore it, then try again.", + ); + } + + const thumbprint = computeDpopJwkThumbprint(input.publicJwk) as KinKeyThumbprint; + const ref = { orgId: input.orgId, thumbprint }; + const result = yield* attest(input, challenge); + if (!result.attested) { + yield* Effect.logWarning("Kin approver key isn't attested; it can't be activated.", { + platform: input.platform, + reason: result.reason, + }); + } + const row = { + thumbprint, + org_id: input.orgId, + public_jwk_json: stableStringify(input.publicJwk), + human_id: person.personId, + device_label: input.deviceLabel, + platform: input.platform, + hardware: result.attested ? result.hardware : "software", + attested: result.attested ? 1 : 0, + session_id: caller.session.sessionId, + // Relay sessions renew hourly under a new id; this DPoP key stays (spec section 4). + proof_key_thumbprint: caller.session.proofKeyThumbprint ?? null, + state: "pending", + created_at: now, + confirmed_at: null, + revoked_at: null, + }; + const key = yield* toKey(row); + // An attestation is bound to the challenge given when the key was made, so a key never + // registers twice; refusing keeps anyone from rewriting a pending key's record. + const inserted = yield* sql`INSERT INTO kin_approver_keys ${sql.insert(row)} + ON CONFLICT (org_id, thumbprint) DO NOTHING RETURNING thumbprint`; + if (inserted.length === 0) + return yield* fail( + "invalid_state", + "This key is already registered; make a new key on the phone.", + ); + const code = kinKeyConfirmationCode(thumbprint, challenge); + if (!result.attested) return { key, code }; + + confirmations.set(slot(ref), { code, expiresAt: now + CONFIRM_TTL_MS, attempts: 0 }); + if (yield* hasActiveKey(input.orgId)) { + // Later keys need a grant from an existing key (spec section 4, step 3). + const target = yield* decodeTarget({ + _tag: "device_key", + thumbprint, + hardware: result.hardware, + attested: true, + }); + yield* actions.create({ + orgId: input.orgId, + kind: "register_approver_key", + target, + resolved: { _tag: "none" }, + targetDigest: kinTargetDigest("register_approver_key", target), + reason: `Add approver key for "${input.deviceLabel}".`, + requestedBy: SERVER_REQUESTER, + provenance: { + startedBy: { humanId: person.personId }, + // `KinIdentity.resolve` yields only the org owner until CHAT-11 adds roles (spec, Interfaces). + startedByRole: "owner", + chain: [{ kind: "approver_key", id: thumbprint, authorRole: "owner" }], + ceilingBelowOwner: false, + }, + source: yield* decodeEventId(`approver_key:${thumbprint}:${input.challenge}`), + }); + } + return { key, code }; + }, + Effect.catch(internal("ApproverKeys.registerKey")), + ); + + const isLocalDesktop = Effect.fn("ApproverKeys.isLocalDesktop")(function* (caller: KinKeyCaller) { + if (caller.session.subject !== DESKTOP_SUBJECT) return false; + if (Option.isNone(caller.connection) || !isLoopbackConnection(caller.connection.value)) + return false; + const [issued] = yield* sql<{ client_ip_address: string | null }>` + SELECT client_ip_address FROM auth_sessions + WHERE session_id = ${caller.session.sessionId} AND revoked_at IS NULL`; + return ( + issued?.client_ip_address != null && + isLocalLoopbackHost(issued.client_ip_address.replace(/^::ffff:/i, "")) + ); + }); + + const confirmKey = Effect.fn("ApproverKeys.confirmKey")( + function* (caller: KinKeyCaller, input: KinApprovalsConfirmKeyInput) { + const person = yield* personIn(caller, input.orgId); + if (!(yield* isLocalDesktop(caller))) + return yield* fail( + "not_local", + "Confirm the first approver key in the desktop app on the Kin host.", + ); + yield* reconcileSessions(input.orgId); + const ref = { orgId: input.orgId, thumbprint: input.thumbprint }; + const row = yield* select(ref); + if (row === undefined) return yield* fail("not_found", "No such approver key."); + if (row.state !== "pending") + return yield* fail("invalid_state", "This key isn't waiting for confirmation."); + if (row.attested !== 1) + return yield* fail( + "unattested", + "This device couldn't prove its key is in secure hardware.", + ); + if (row.human_id !== person.personId) + return yield* fail("not_owner", "Only the key's owner can confirm it."); + if (yield* hasActiveKey(input.orgId)) + return yield* fail("invalid_state", "Approve this key from a device that already has one."); + const now = yield* Clock.currentTimeMillis; + const pending = confirmations.get(slot(ref)); + if (pending === undefined || pending.expiresAt <= now) + return yield* fail("bad_code", "The code expired; make a new key on the phone."); + if (!sameBytes(pending.code, input.code)) { + pending.attempts += 1; + if (pending.attempts >= MAX_CODE_ATTEMPTS) confirmations.delete(slot(ref)); + return yield* fail("bad_code", "The code doesn't match the phone."); + } + const [active] = yield* sql`UPDATE kin_approver_keys + SET state = 'active', confirmed_at = ${now} + WHERE org_id = ${ref.orgId} AND thumbprint = ${ref.thumbprint} + AND state = 'pending' AND attested = 1 + AND NOT EXISTS (SELECT 1 FROM kin_approver_keys + WHERE org_id = ${ref.orgId} AND state = 'active') + RETURNING *`; + if (active === undefined) + return yield* fail("invalid_state", "Another key was confirmed first."); + confirmations.delete(slot(ref)); + return yield* toKey(active); + }, + Effect.catch(internal("ApproverKeys.confirmKey")), + ); + + const listKeys = Effect.fn("ApproverKeys.listKeys")( + function* (caller: KinKeyCaller, input: KinApprovalsOrgInput) { + yield* personIn(caller, input.orgId); + yield* reconcileSessions(input.orgId); + const rows = yield* sql`SELECT * FROM kin_approver_keys + WHERE org_id = ${input.orgId} ORDER BY created_at, thumbprint`; + return { keys: yield* Effect.forEach(rows, toKey) }; + }, + Effect.catch(internal("ApproverKeys.listKeys")), + ); + + const revokeKey = Effect.fn("ApproverKeys.revokeKey")( + function* (caller: KinKeyCaller, input: KinApprovalsKeyInput) { + const person = yield* personIn(caller, input.orgId); + const row = yield* select(input); + if (row === undefined) return yield* fail("not_found", "No such approver key."); + if (row.human_id !== person.personId) + return yield* fail("not_owner", "Only the key's owner can revoke it."); + const revoked = yield* revokeRow(input, "key_revoked"); + return yield* toKey(revoked ?? row); + }, + Effect.catch(internal("ApproverKeys.revokeKey")), + ); + + const get = Effect.fn("ApproverKeys.get")( + function* (ref: KeyRef) { + yield* reconcileSessions(ref.orgId); + const row = yield* select(ref); + return row === undefined ? Option.none() : Option.some(yield* toKey(row)); + }, + Effect.catch(internal("ApproverKeys.get")), + ); + + const requireActive = Effect.fn("ApproverKeys.requireActive")(function* (ref: KeyRef) { + const key = yield* get(ref); + if (Option.isNone(key) || key.value.state === "pending") + return yield* fail("unknown_key", "No active approver key with this id."); + if (key.value.state === "revoked") + return yield* fail("revoked_key", "This approver key was revoked."); + return key.value; + }); + + const activateByGrant = Effect.fn("ApproverKeys.activateByGrant")( + function* (ref: KeyRef) { + yield* reconcileSessions(ref.orgId); + const now = yield* Clock.currentTimeMillis; + const rows = yield* sql`UPDATE kin_approver_keys + SET state = 'active', confirmed_at = ${now} + WHERE org_id = ${ref.orgId} AND thumbprint = ${ref.thumbprint} + AND state = 'pending' AND attested = 1 + RETURNING thumbprint`; + if (rows.length > 0) confirmations.delete(slot(ref)); + return rows.length > 0; + }, + Effect.catch(internal("ApproverKeys.activateByGrant")), + ); + + yield* reconcileSessions(undefined).pipe( + Effect.catch((error) => Effect.logError("Kin approver key reconciliation failed.", error)), + ); + + return ApproverKeys.of({ + keyChallenge, + registerKey, + confirmKey, + listKeys, + revokeKey, + get, + requireActive, + activateByGrant, + reconcileSessions, + }); +}); + +export const layer = Layer.effect(ApproverKeys, make); diff --git a/apps/server/src/kin/approvals/PendingActions.test.ts b/apps/server/src/kin/approvals/PendingActions.test.ts index 5950042b4d41a..c9429ae559a85 100644 --- a/apps/server/src/kin/approvals/PendingActions.test.ts +++ b/apps/server/src/kin/approvals/PendingActions.test.ts @@ -8,6 +8,7 @@ import { } from "@t3tools/contracts"; import * as Clock from "effect/Clock"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; @@ -111,6 +112,19 @@ describe("KinPendingActions", () => { } as unknown as KinPendingActionCreateInput); assert.isFalse(withExtra.created); assert.strictEqual(withExtra.action.id, first.action.id); + // Key registration's requester id is reserved, so an agent can't pose as the phone. + for (const requestedBy of [ + { agentId: "kin-approver-keys", threadId: "thread-lead" }, + { agentId: "kin-approver-keys", threadId: "kin-approver-keys" }, + ]) { + const posing = yield* Effect.exit( + actions.create({ + ...request("webhook-delivery-2"), + requestedBy, + } as unknown as KinPendingActionCreateInput), + ); + assert.isTrue(Exit.isFailure(posing)); + } const twice = yield* Effect.all( [ diff --git a/apps/server/src/kin/approvals/PendingActions.ts b/apps/server/src/kin/approvals/PendingActions.ts index db1aaff750892..dd9711c3bee51 100644 --- a/apps/server/src/kin/approvals/PendingActions.ts +++ b/apps/server/src/kin/approvals/PendingActions.ts @@ -41,6 +41,8 @@ const AWAITING_TTL_MS = 7 * 24 * 60 * 60 * 1000; // A grant lapses at min(exp, acceptedAt + 15 min) (approvals spec section 5). const GRANT_ACCEPTED_TTL_MS = 15 * 60 * 1000; +/** `registerKey`'s requester: the phone asked, not an agent, so no agent may use this id. */ +export const KIN_APPROVER_KEYS_REQUESTER = "kin-approver-keys"; const CreateInput = Schema.Struct({ orgId: KinOrgId, kind: KinActionKind, @@ -51,7 +53,16 @@ const CreateInput = Schema.Struct({ requestedBy: Schema.Struct({ agentId: KinAgentId, threadId: ThreadId }), provenance: KinProvenance, source: KinEventId, -}); +}).check( + Schema.makeFilter( + ({ kind, requestedBy: { agentId, threadId } }) => + (agentId !== KIN_APPROVER_KEYS_REQUESTER && threadId !== KIN_APPROVER_KEYS_REQUESTER) || + (kind === "register_approver_key" && + agentId === KIN_APPROVER_KEYS_REQUESTER && + threadId === KIN_APPROVER_KEYS_REQUESTER), + { expected: `a requester other than the reserved ${KIN_APPROVER_KEYS_REQUESTER}` }, + ), +); export type KinPendingActionCreateInput = typeof CreateInput.Type; const decodeCreateInput = Schema.decodeEffect(CreateInput); const StoredAction = Schema.Struct({ diff --git a/apps/server/src/kin/approvals/attestation/AttestationTrust.ts b/apps/server/src/kin/approvals/attestation/AttestationTrust.ts new file mode 100644 index 0000000000000..dc72e2fe9168c --- /dev/null +++ b/apps/server/src/kin/approvals/attestation/AttestationTrust.ts @@ -0,0 +1,110 @@ +// @effect-diagnostics nodeBuiltinImport:off -- X509Certificate for the pinned roots. +import * as NodeCrypto from "node:crypto"; + +import type { KinApproverKeyPlatform } from "@t3tools/contracts"; +import * as Clock from "effect/Clock"; +import * as Config from "effect/Config"; +import * as Context from "effect/Context"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Ref from "effect/Ref"; +import * as Schema from "effect/Schema"; +import * as HttpClient from "effect/http/HttpClient"; +import * as HttpClientResponse from "effect/http/HttpClientResponse"; + +import { APPLE_APP_ATTEST_ROOT, GOOGLE_HARDWARE_ATTESTATION_ROOTS } from "./roots.ts"; +import type { AttestationTrust } from "./verify.ts"; + +const STATUS_URL = "https://android.googleapis.com/attestation/status"; +const STATUS_TTL = Duration.hours(1); +const StatusList = Schema.Struct({ + entries: Schema.Record(Schema.String, Schema.Struct({ status: Schema.String })), +}); + +export class KinAttestationTrustError extends Schema.TaggedError()( + "KinAttestationTrustError", + { message: Schema.String }, +) {} + +export class KinAttestationTrust extends Context.Service< + KinAttestationTrust, + { + /** Android fails rather than trust a chain it couldn't check for revocation. */ + readonly load: ( + platform: KinApproverKeyPlatform, + ) => Effect.Effect; + } +>()("t3/kin/approvals/attestation/AttestationTrust/KinAttestationTrust") {} + +const hexList = (name: string) => + Config.String(name).pipe( + Config.withDefault(""), + Config.map((value) => + value + .split(",") + .map((entry) => entry.trim().toLowerCase().replaceAll(":", "")) + .filter((entry) => entry.length > 0), + ), + ); + +/** Production trust: pinned roots, the release app identity from config, Google's status list. */ +export const layer = Layer.effect( + KinAttestationTrust, + Effect.gen(function* () { + const config = yield* Config.all({ + androidPackage: Config.String("KIN_ANDROID_PACKAGE").pipe(Config.option), + androidSigners: hexList("KIN_ANDROID_SIGNING_CERT_SHA256"), + appleAppId: Config.String("KIN_IOS_APP_ID").pipe(Config.option), + appleDevelopment: Config.Boolean("KIN_IOS_APP_ATTEST_DEVELOPMENT").pipe( + Config.withDefault(false), + ), + }); + const http = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk); + const cache = yield* Ref.make(Option.none<{ at: number; serials: ReadonlySet }>()); + const fixed = { + googleRoots: GOOGLE_HARDWARE_ATTESTATION_ROOTS.map( + (pem) => new NodeCrypto.X509Certificate(pem), + ), + appleRoot: new NodeCrypto.X509Certificate(APPLE_APP_ATTEST_ROOT), + androidApps: Option.isSome(config.androidPackage) + ? [{ packageName: config.androidPackage.value, signingCertSha256: config.androidSigners }] + : [], + appleAppIds: Option.isSome(config.appleAppId) ? [config.appleAppId.value] : [], + appleEnvironments: config.appleDevelopment + ? (["production", "development"] as const) + : (["production"] as const), + }; + const revoked = Effect.gen(function* () { + const now = yield* Clock.currentTimeMillis; + const cached = yield* Ref.get(cache); + if (Option.isSome(cached) && now - cached.value.at < Duration.toMillis(STATUS_TTL)) + return cached.value.serials; + const list = yield* http + .get(STATUS_URL) + .pipe(Effect.flatMap(HttpClientResponse.schemaBodyJson(StatusList)), Effect.scoped); + const serials = new Set( + Object.entries(list.entries) + .filter(([, entry]) => entry.status === "REVOKED" || entry.status === "SUSPENDED") + .map(([serial]) => serial.toLowerCase().replace(/^0+(?=.)/, "")), + ); + yield* Ref.set(cache, Option.some({ at: now, serials })); + return serials as ReadonlySet; + }).pipe( + Effect.timeout(Duration.seconds(10)), + Effect.mapError( + () => + new KinAttestationTrustError({ + message: "Couldn't load Google's attestation revocation list.", + }), + ), + ); + return KinAttestationTrust.of({ + load: Effect.fn("KinAttestationTrust.load")(function* (platform: KinApproverKeyPlatform) { + const androidRevokedSerials = platform === "ios" ? new Set() : yield* revoked; + return { ...fixed, androidRevokedSerials }; + }), + }); + }), +); diff --git a/apps/server/src/kin/approvals/attestation/der.ts b/apps/server/src/kin/approvals/attestation/der.ts new file mode 100644 index 0000000000000..1c9fc0c21628a --- /dev/null +++ b/apps/server/src/kin/approvals/attestation/der.ts @@ -0,0 +1,159 @@ +// @effect-diagnostics extendsNativeError:off -- thrown and caught inside the pure parsers only. +/** + * A strict DER reader for the few structures attestation needs. Node's X509Certificate verifies + * signatures but doesn't expose extensions. Anything not canonical DER throws. + */ +export class DerError extends Error {} + +export type Tlv = { + /** 0 universal, 1 application, 2 context, 3 private. */ + readonly cls: number; + readonly constructed: boolean; + readonly tag: number; + readonly value: Uint8Array; + /** The whole element, header included. */ + readonly raw: Uint8Array; +}; + +const UNIVERSAL = 0; +export const CONTEXT = 2; +const T_BOOLEAN = 1; +const T_INTEGER = 2; +const T_OCTET_STRING = 4; +const T_OID = 6; +const T_ENUMERATED = 10; +const T_SEQUENCE = 16; +export const T_SET = 17; + +const fail = (message: string): never => { + throw new DerError(message); +}; + +function readOne(bytes: Uint8Array, start: number): { tlv: Tlv; end: number } { + let offset = start; + const next = () => (offset < bytes.length ? bytes[offset++]! : fail("truncated DER")); + const first = next(); + const cls = first >> 6; + const constructed = (first & 0x20) !== 0; + let tag = first & 0x1f; + if (tag === 0x1f) { + tag = 0; + let byte = next(); + if (byte === 0x80) fail("non-minimal tag"); + for (;;) { + tag = tag * 128 + (byte & 0x7f); + if (tag > 0xffff) fail("tag too large"); + if ((byte & 0x80) === 0) break; + byte = next(); + } + if (tag < 0x1f) fail("non-minimal tag"); + } + const lengthByte = next(); + let length = lengthByte; + if (lengthByte === 0x80) fail("indefinite length"); + if (lengthByte > 0x80) { + const count = lengthByte & 0x7f; + if (count > 4) fail("length too large"); + length = 0; + for (let i = 0; i < count; i++) length = length * 256 + next(); + if (length < 0x80 || (count > 1 && length < 256 ** (count - 1))) fail("non-minimal length"); + } + const end = offset + length; + if (end > bytes.length) fail("truncated DER"); + return { + tlv: { + cls, + constructed, + tag, + value: bytes.subarray(offset, end), + raw: bytes.subarray(start, end), + }, + end, + }; +} + +/** Exactly one element filling `bytes`. */ +export function parse(bytes: Uint8Array): Tlv { + const { tlv, end } = readOne(bytes, 0); + if (end !== bytes.length) fail("trailing bytes after DER"); + return tlv; +} + +export function children(tlv: Tlv): ReadonlyArray { + if (!tlv.constructed) fail("expected a constructed element"); + const out: Tlv[] = []; + let offset = 0; + while (offset < tlv.value.length) { + const { tlv: child, end } = readOne(tlv.value, offset); + out.push(child); + offset = end; + } + return out; +} + +export function expect(tlv: Tlv | undefined, tag: number, cls = UNIVERSAL): Tlv { + if (tlv === undefined) return fail(`missing element with tag ${tag}`); + if (tlv.cls !== cls || tlv.tag !== tag) + fail(`expected tag ${cls}:${tag}, got ${tlv.cls}:${tlv.tag}`); + return tlv; +} + +export function sequence(tlv: Tlv | undefined): ReadonlyArray { + return children(expect(tlv, T_SEQUENCE)); +} + +/** INTEGER or ENUMERATED as a safe non-negative number. */ +export function integer(tlv: Tlv | undefined, tag = T_INTEGER): number { + const { value, constructed } = expect(tlv, tag); + if (constructed || value.length === 0) fail("bad integer"); + if (value.length > 1 && value[0] === 0 && (value[1]! & 0x80) === 0) fail("non-minimal integer"); + if (value.length > 1 && value[0] === 0xff && (value[1]! & 0x80) !== 0) + fail("non-minimal integer"); + if ((value[0]! & 0x80) !== 0) fail("negative integer"); + let n = 0; + for (const byte of value) n = n * 256 + byte; + if (!Number.isSafeInteger(n)) fail("integer too large"); + return n; +} + +export function enumerated(tlv: Tlv | undefined): number { + return integer(tlv, T_ENUMERATED); +} + +export function octets(tlv: Tlv | undefined): Uint8Array { + const element = expect(tlv, T_OCTET_STRING); + if (element.constructed) fail("constructed octet string"); + return element.value; +} + +export function boolean(tlv: Tlv | undefined): boolean { + const { value } = expect(tlv, T_BOOLEAN); + if (value.length !== 1 || (value[0] !== 0 && value[0] !== 0xff)) fail("bad boolean"); + return value[0] === 0xff; +} + +/** An OID's content bytes in hex, for comparison with constants. */ +function oidHex(tlv: Tlv | undefined): string { + return Buffer.from(expect(tlv, T_OID).value).toString("hex"); +} + +export type Extension = { readonly critical: boolean; readonly value: Uint8Array }; + +/** `tbsCertificate.extensions` keyed by OID content hex. Duplicate OIDs throw. */ +export function certificateExtensions(certificateDer: Uint8Array): ReadonlyMap { + const [tbs] = sequence(parse(certificateDer)); + const fields = sequence(tbs); + const wrapper = fields.find((field) => field.cls === CONTEXT && field.tag === 3); + const out = new Map(); + if (wrapper === undefined) return out; + const [list] = children(wrapper); + for (const extension of sequence(list)) { + const parts = sequence(extension); + const oid = oidHex(parts[0]); + const critical = parts.length === 3 ? boolean(parts[1]) : false; + if (parts.length !== 2 && parts.length !== 3) fail("bad extension"); + if (out.has(oid)) fail("duplicate extension"); + out.set(oid, { critical, value: octets(parts[parts.length - 1]) }); + } + return out; +} diff --git a/apps/server/src/kin/approvals/attestation/roots.ts b/apps/server/src/kin/approvals/attestation/roots.ts new file mode 100644 index 0000000000000..a10258c2fe858 --- /dev/null +++ b/apps/server/src/kin/approvals/attestation/roots.ts @@ -0,0 +1,64 @@ +// Fetched 2026-11-08 from https://android.googleapis.com/attestation/root and +// https://www.apple.com/certificateauthority/Apple_App_Attestation_Root_CA.pem. SHA-256: Google RSA +// CE:DB:1C:B6…80:0D:FC, Google EC (Key Attestation CA1) 6D:9D:B4:CE…A4:BC:C0, Apple 1C:B9:82:3B…C9:32. +export const GOOGLE_HARDWARE_ATTESTATION_ROOTS = [ + `-----BEGIN CERTIFICATE----- +MIIFHDCCAwSgAwIBAgIJAPHBcqaZ6vUdMA0GCSqGSIb3DQEBCwUAMBsxGTAXBgNV +BAUTEGY5MjAwOWU4NTNiNmIwNDUwHhcNMjIwMzIwMTgwNzQ4WhcNNDIwMzE1MTgw +NzQ4WjAbMRkwFwYDVQQFExBmOTIwMDllODUzYjZiMDQ1MIICIjANBgkqhkiG9w0B +AQEFAAOCAg8AMIICCgKCAgEAr7bHgiuxpwHsK7Qui8xUFmOr75gvMsd/dTEDDJdS +Sxtf6An7xyqpRR90PL2abxM1dEqlXnf2tqw1Ne4Xwl5jlRfdnJLmN0pTy/4lj4/7 +tv0Sk3iiKkypnEUtR6WfMgH0QZfKHM1+di+y9TFRtv6y//0rb+T+W8a9nsNL/ggj +nar86461qO0rOs2cXjp3kOG1FEJ5MVmFmBGtnrKpa73XpXyTqRxB/M0n1n/W9nGq +C4FSYa04T6N5RIZGBN2z2MT5IKGbFlbC8UrW0DxW7AYImQQcHtGl/m00QLVWutHQ +oVJYnFPlXTcHYvASLu+RhhsbDmxMgJJ0mcDpvsC4PjvB+TxywElgS70vE0XmLD+O +JtvsBslHZvPBKCOdT0MS+tgSOIfga+z1Z1g7+DVagf7quvmag8jfPioyKvxnK/Eg +sTUVi2ghzq8wm27ud/mIM7AY2qEORR8Go3TVB4HzWQgpZrt3i5MIlCaY504LzSRi +igHCzAPlHws+W0rB5N+er5/2pJKnfBSDiCiFAVtCLOZ7gLiMm0jhO2B6tUXHI/+M +RPjy02i59lINMRRev56GKtcd9qO/0kUJWdZTdA2XoS82ixPvZtXQpUpuL12ab+9E +aDK8Z4RHJYYfCT3Q5vNAXaiWQ+8PTWm2QgBR/bkwSWc+NpUFgNPN9PvQi8WEg5Um +AGMCAwEAAaNjMGEwHQYDVR0OBBYEFDZh4QB8iAUJUYtEbEf/GkzJ6k8SMB8GA1Ud +IwQYMBaAFDZh4QB8iAUJUYtEbEf/GkzJ6k8SMA8GA1UdEwEB/wQFMAMBAf8wDgYD +VR0PAQH/BAQDAgIEMA0GCSqGSIb3DQEBCwUAA4ICAQB8cMqTllHc8U+qCrOlg3H7 +174lmaCsbo/bJ0C17JEgMLb4kvrqsXZs01U3mB/qABg/1t5Pd5AORHARs1hhqGIC +W/nKMav574f9rZN4PC2ZlufGXb7sIdJpGiO9ctRhiLuYuly10JccUZGEHpHSYM2G +tkgYbZba6lsCPYAAP83cyDV+1aOkTf1RCp/lM0PKvmxYN10RYsK631jrleGdcdkx +oSK//mSQbgcWnmAEZrzHoF1/0gso1HZgIn0YLzVhLSA/iXCX4QT2h3J5z3znluKG +1nv8NQdxei2DIIhASWfu804CA96cQKTTlaae2fweqXjdN1/v2nqOhngNyz1361mF +mr4XmaKH/ItTwOe72NI9ZcwS1lVaCvsIkTDCEXdm9rCNPAY10iTunIHFXRh+7KPz +lHGewCq/8TOohBRn0/NNfh7uRslOSZ/xKbN9tMBtw37Z8d2vvnXq/YWdsm1+JLVw +n6yYD/yacNJBlwpddla8eaVMjsF6nBnIgQOf9zKSe06nSTqvgwUHosgOECZJZ1Eu +zbH4yswbt02tKtKEFhx+v+OTge/06V+jGsqTWLsfrOCNLuA8H++z+pUENmpqnnHo +vaI47gC+TNpkgYGkkBT6B/m/U01BuOBBTzhIlMEZq9qkDWuM2cA5kW5V3FJUcfHn +w1IdYIg2Wxg7yHcQZemFQg== +-----END CERTIFICATE-----`, + `-----BEGIN CERTIFICATE----- +MIICIjCCAaigAwIBAgIRAISp0Cl7DrWK5/8OgN52BgUwCgYIKoZIzj0EAwMwUjEc +MBoGA1UEAwwTS2V5IEF0dGVzdGF0aW9uIENBMTEQMA4GA1UECwwHQW5kcm9pZDET +MBEGA1UECgwKR29vZ2xlIExMQzELMAkGA1UEBhMCVVMwHhcNMjUwNzE3MjIzMjE4 +WhcNMzUwNzE1MjIzMjE4WjBSMRwwGgYDVQQDDBNLZXkgQXR0ZXN0YXRpb24gQ0Ex +MRAwDgYDVQQLDAdBbmRyb2lkMRMwEQYDVQQKDApHb29nbGUgTExDMQswCQYDVQQG +EwJVUzB2MBAGByqGSM49AgEGBSuBBAAiA2IABCPaI3FO3z5bBQo8cuiEas4HjqCt +G/mLFfRT0MsIssPBEEU5Cfbt6sH5yOAxqEi5QagpU1yX4HwnGb7OtBYpDTB57uH5 +Eczm34A5FNijV3s0/f0UPl7zbJcTx6xwqMIRq6NCMEAwDwYDVR0TAQH/BAUwAwEB +/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFFIyuyz7RkOb3NaBqQ5lZuA0QepA +MAoGCCqGSM49BAMDA2gAMGUCMETfjPO/HwqReR2CS7p0ZWoD/LHs6hDi422opifH +EUaYLxwGlT9SLdjkVpz0UUOR5wIxAIoGyxGKRHVTpqpGRFiJtQEOOTp/+s1GcxeY +uR2zh/80lQyu9vAFCj6E4AXc+osmRg== +-----END CERTIFICATE-----`, +] as const; + +export const APPLE_APP_ATTEST_ROOT = `-----BEGIN CERTIFICATE----- +MIICITCCAaegAwIBAgIQC/O+DvHN0uD7jG5yH2IXmDAKBggqhkjOPQQDAzBSMSYw +JAYDVQQDDB1BcHBsZSBBcHAgQXR0ZXN0YXRpb24gUm9vdCBDQTETMBEGA1UECgwK +QXBwbGUgSW5jLjETMBEGA1UECAwKQ2FsaWZvcm5pYTAeFw0yMDAzMTgxODMyNTNa +Fw00NTAzMTUwMDAwMDBaMFIxJjAkBgNVBAMMHUFwcGxlIEFwcCBBdHRlc3RhdGlv +biBSb290IENBMRMwEQYDVQQKDApBcHBsZSBJbmMuMRMwEQYDVQQIDApDYWxpZm9y +bmlhMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAERTHhmLW07ATaFQIEVwTtT4dyctdh +NbJhFs/Ii2FdCgAHGbpphY3+d8qjuDngIN3WVhQUBHAoMeQ/cLiP1sOUtgjqK9au +Yen1mMEvRq9Sk3Jm5X8U62H+xTD3FE9TgS41o0IwQDAPBgNVHRMBAf8EBTADAQH/ +MB0GA1UdDgQWBBSskRBTM72+aEH/pwyp5frq5eWKoTAOBgNVHQ8BAf8EBAMCAQYw +CgYIKoZIzj0EAwMDaAAwZQIwQgFGnByvsiVbpTKwSga0kP0e8EeDS4+sQmTvb7vn +53O5+FRXgeLhpJ06ysC5PrOyAjEAp5U4xDgEgllF7En3VcE3iexZZtKeYnpqtijV +oyFraWVIyd/dganmrduC1bmTBGwD +-----END CERTIFICATE-----`; diff --git a/apps/server/src/kin/approvals/attestation/testFixtures.ts b/apps/server/src/kin/approvals/attestation/testFixtures.ts new file mode 100644 index 0000000000000..0720494c3a853 --- /dev/null +++ b/apps/server/src/kin/approvals/attestation/testFixtures.ts @@ -0,0 +1,376 @@ +// @effect-diagnostics nodeBuiltinImport:off -- test certificates are built and signed with node:crypto. +import * as NodeCrypto from "node:crypto"; + +import type { KinApproverPublicJwk } from "@t3tools/contracts"; + +import type { AttestationTrust } from "./verify.ts"; + +const length = (n: number) => + n < 0x80 + ? [n] + : n < 0x100 + ? [0x81, n] + : n < 0x10000 + ? [0x82, n >> 8, n & 0xff] + : [0x83, n >> 16, (n >> 8) & 0xff, n & 0xff]; +const tlv = (identifier: ReadonlyArray, content: Uint8Array) => + new Uint8Array([...identifier, ...length(content.length), ...content]); +const concat = (parts: ReadonlyArray) => + new Uint8Array(parts.flatMap((part) => [...part])); + +const der = { + seq: (...parts: ReadonlyArray) => tlv([0x30], concat(parts)), + set: (...parts: ReadonlyArray) => tlv([0x31], concat(parts)), + int: (n: number) => { + const bytes: number[] = []; + let rest = n; + do { + bytes.unshift(rest % 256); + rest = Math.floor(rest / 256); + } while (rest > 0); + if (bytes[0]! & 0x80) bytes.unshift(0); + return tlv([0x02], new Uint8Array(bytes)); + }, + serial: (bytes: Uint8Array) => + tlv([0x02], bytes[0]! & 0x80 ? new Uint8Array([0, ...bytes]) : bytes), + enumerated: (n: number) => tlv([0x0a], new Uint8Array([n])), + bool: (value: boolean) => tlv([0x01], new Uint8Array([value ? 0xff : 0])), + null: () => tlv([0x05], new Uint8Array()), + octet: (bytes: Uint8Array) => tlv([0x04], bytes), + utf8: (text: string) => tlv([0x0c], new Uint8Array(Buffer.from(text))), + bits: (bytes: Uint8Array) => tlv([0x03], new Uint8Array([0, ...bytes])), + utcTime: (text: string) => tlv([0x17], new Uint8Array(Buffer.from(text))), + oid: (dotted: string) => { + const [a, b, ...rest] = dotted.split(".").map(Number); + const out = [a! * 40 + b!]; + for (const arc of rest) { + const chunk = [arc & 0x7f]; + let value = arc >> 7; + while (value > 0) { + chunk.unshift((value & 0x7f) | 0x80); + value >>= 7; + } + out.push(...chunk); + } + return tlv([0x06], new Uint8Array(out)); + }, + /** `[tag] EXPLICIT`, high tag numbers included. */ + explicit: (tag: number, inner: Uint8Array) => { + if (tag < 31) return tlv([0xa0 | tag], inner); + const digits = [tag & 0x7f]; + for (let value = tag >> 7; value > 0; value >>= 7) digits.unshift((value & 0x7f) | 0x80); + return tlv([0xbf, ...digits], inner); + }, +}; + +type KeyPair = { + readonly publicKey: NodeCrypto.KeyObject; + readonly privateKey: NodeCrypto.KeyObject; +}; +export const newKey = (): KeyPair => NodeCrypto.generateKeyPairSync("ec", { namedCurve: "P-256" }); + +// A positive, minimally encoded INTEGER: no leading zero byte. +const randomSerial = () => { + const bytes = new Uint8Array(NodeCrypto.randomBytes(8)); + bytes[0] = (bytes[0]! & 0x7f) | 0x01; + return bytes; +}; +const name = (cn: string) => der.seq(der.set(der.seq(der.oid("2.5.4.3"), der.utf8(cn)))); +const ECDSA_SHA256 = der.seq(der.oid("1.2.840.10045.4.3.2")); + +export type CertificateSpec = { + readonly subject: string; + readonly issuer: string; + readonly subjectKey: NodeCrypto.KeyObject; + readonly issuerKey: NodeCrypto.KeyObject; + readonly ca?: boolean; + readonly extensions?: ReadonlyArray<{ readonly oid: string; readonly value: Uint8Array }>; + readonly notBefore?: string; + readonly notAfter?: string; + readonly serial?: Uint8Array; +}; + +export function certificate(spec: CertificateSpec): Uint8Array { + const extensions = [ + ...(spec.ca + ? [der.seq(der.oid("2.5.29.19"), der.bool(true), der.octet(der.seq(der.bool(true))))] + : []), + ...(spec.extensions ?? []).map((extension) => + der.seq(der.oid(extension.oid), der.octet(extension.value)), + ), + ]; + const tbs = der.seq( + der.explicit(0, der.int(2)), + der.serial(spec.serial ?? randomSerial()), + ECDSA_SHA256, + name(spec.issuer), + der.seq( + der.utcTime(spec.notBefore ?? "250101000000Z"), + der.utcTime(spec.notAfter ?? "400101000000Z"), + ), + name(spec.subject), + new Uint8Array(spec.subjectKey.export({ type: "spki", format: "der" })), + ...(extensions.length > 0 ? [der.explicit(3, der.seq(...extensions))] : []), + ); + const signature = NodeCrypto.sign("sha256", tbs, spec.issuerKey); + return der.seq(tbs, ECDSA_SHA256, der.bits(new Uint8Array(signature))); +} + +const publicJwkOf = (key: NodeCrypto.KeyObject): KinApproverPublicJwk => { + const jwk = key.export({ format: "jwk" }); + return { kty: "EC", crv: "P-256", x: jwk.x!, y: jwk.y! }; +}; +const point = (key: NodeCrypto.KeyObject) => { + const jwk = key.export({ format: "jwk" }); + return new Uint8Array([ + 4, + ...Buffer.from(jwk.x!, "base64url"), + ...Buffer.from(jwk.y!, "base64url"), + ]); +}; +const sha256 = (...parts: ReadonlyArray) => { + const hash = NodeCrypto.createHash("sha256"); + for (const part of parts) hash.update(part); + return new Uint8Array(hash.digest()); +}; +const b64 = (bytes: Uint8Array) => Buffer.from(bytes).toString("base64"); + +const ANDROID_PACKAGE = "com.gldroger.kin"; +const ANDROID_SIGNER = "ab".repeat(32); +const APPLE_APP_ID = "TEAM123456.com.gldroger.kin"; + +export function makeTrustFixture() { + const googleRoot = newKey(); + const appleRoot = newKey(); + const googleRootDer = certificate({ + subject: "Test Google Root", + issuer: "Test Google Root", + subjectKey: googleRoot.publicKey, + issuerKey: googleRoot.privateKey, + ca: true, + }); + const appleRootDer = certificate({ + subject: "Test Apple Root", + issuer: "Test Apple Root", + subjectKey: appleRoot.publicKey, + issuerKey: appleRoot.privateKey, + ca: true, + }); + const trust: AttestationTrust = { + googleRoots: [new NodeCrypto.X509Certificate(googleRootDer)], + androidRevokedSerials: new Set(), + androidApps: [{ packageName: ANDROID_PACKAGE, signingCertSha256: [ANDROID_SIGNER] }], + appleRoot: new NodeCrypto.X509Certificate(appleRootDer), + appleAppIds: [APPLE_APP_ID], + appleEnvironments: ["production"], + }; + return { trust, googleRoot, googleRootDer, appleRoot }; +} +export type TrustFixture = ReturnType; + +export type KeyDescriptionSpec = { + readonly attestationLevel?: number; + readonly keyMintLevel?: number; + readonly challenge: Uint8Array; + readonly purposes?: ReadonlyArray; + readonly algorithm?: number; + readonly ecCurve?: number; + readonly digests?: ReadonlyArray; + readonly userAuthType?: number; + readonly authTimeout?: number; + readonly noAuthRequiredInSoftware?: boolean; + readonly allApplications?: boolean; + readonly omitKeySize?: boolean; + readonly origin?: number; + readonly deviceLocked?: boolean; + readonly bootState?: number; + readonly packages?: ReadonlyArray; + readonly signers?: ReadonlyArray; +}; + +function keyDescription(spec: KeyDescriptionSpec): Uint8Array { + const appId = der.seq( + der.set( + ...(spec.packages ?? [ANDROID_PACKAGE]).map((pkg) => + der.seq(der.octet(new Uint8Array(Buffer.from(pkg))), der.int(7)), + ), + ), + der.set( + ...(spec.signers ?? [ANDROID_SIGNER]).map((hex) => + der.octet(new Uint8Array(Buffer.from(hex, "hex"))), + ), + ), + ); + const software = der.seq( + ...(spec.noAuthRequiredInSoftware ? [der.explicit(503, der.null())] : []), + der.explicit(709, der.octet(appId)), + ); + const hardware = der.seq( + der.explicit(1, der.set(...(spec.purposes ?? [2]).map(der.int))), + der.explicit(2, der.int(spec.algorithm ?? 3)), + ...(spec.omitKeySize ? [] : [der.explicit(3, der.int(256))]), + der.explicit(5, der.set(...(spec.digests ?? [4]).map(der.int))), + der.explicit(10, der.int(spec.ecCurve ?? 1)), + der.explicit(504, der.int(spec.userAuthType ?? 2)), + ...(spec.authTimeout === undefined ? [] : [der.explicit(505, der.int(spec.authTimeout))]), + ...(spec.allApplications ? [der.explicit(600, der.null())] : []), + der.explicit(702, der.int(spec.origin ?? 0)), + der.explicit( + 704, + der.seq( + der.octet(new Uint8Array(32)), + der.bool(spec.deviceLocked ?? true), + der.enumerated(spec.bootState ?? 0), + der.octet(new Uint8Array(32)), + ), + ), + ); + return der.seq( + der.int(300), + der.enumerated(spec.attestationLevel ?? 2), + der.int(300), + der.enumerated(spec.keyMintLevel ?? 2), + der.octet(spec.challenge), + der.octet(new Uint8Array()), + software, + hardware, + ); +} + +export type AndroidChainSpec = KeyDescriptionSpec & { + /** The approval key the leaf certifies; a fresh one when omitted. */ + readonly approvalKey?: KeyPair; + readonly descriptionInIntermediate?: boolean; + readonly leafSignedByStranger?: boolean; + readonly leafNotAfter?: string; + readonly leafSerial?: Uint8Array; + readonly root?: KeyPair; +}; + +export function androidChain(fixture: TrustFixture, spec: AndroidChainSpec) { + const approvalKey = spec.approvalKey ?? newKey(); + const root = spec.root ?? fixture.googleRoot; + const rootDer = spec.root + ? certificate({ + subject: "Other Root", + issuer: "Other Root", + subjectKey: root.publicKey, + issuerKey: root.privateKey, + ca: true, + }) + : fixture.googleRootDer; + const intermediate = newKey(); + const description = { oid: "1.3.6.1.4.1.11129.2.1.17", value: keyDescription(spec) }; + const intermediateDer = certificate({ + subject: "Test Attestation Intermediate", + issuer: spec.root ? "Other Root" : "Test Google Root", + subjectKey: intermediate.publicKey, + issuerKey: root.privateKey, + ca: true, + ...(spec.descriptionInIntermediate ? { extensions: [description] } : {}), + }); + const leafDer = certificate({ + subject: "Android Keystore Key", + issuer: "Test Attestation Intermediate", + subjectKey: approvalKey.publicKey, + issuerKey: spec.leafSignedByStranger ? newKey().privateKey : intermediate.privateKey, + extensions: [description], + ...(spec.leafNotAfter ? { notAfter: spec.leafNotAfter } : {}), + ...(spec.leafSerial ? { serial: spec.leafSerial } : {}), + }); + return { + publicJwk: publicJwkOf(approvalKey.publicKey), + approvalKey, + certificateChain: [leafDer, intermediateDer, rootDer].map(b64), + }; +} + +const cborHead = (major: number, n: number) => + n < 24 + ? [(major << 5) | n] + : n < 0x100 + ? [(major << 5) | 24, n] + : [(major << 5) | 25, n >> 8, n & 0xff]; +const cbor = { + bytes: (value: Uint8Array) => new Uint8Array([...cborHead(2, value.length), ...value]), + text: (value: string) => { + const bytes = Buffer.from(value); + return new Uint8Array([...cborHead(3, bytes.length), ...bytes]); + }, + array: (items: ReadonlyArray) => + new Uint8Array([...cborHead(4, items.length), ...concat(items)]), + map: (entries: ReadonlyArray) => + new Uint8Array([ + ...cborHead(5, entries.length), + ...concat(entries.flatMap(([key, value]) => [cbor.text(key), value])), + ]), +}; + +export type AppleSpec = { + readonly challenge: Uint8Array; + readonly approvalKey?: KeyPair; + /** The key the nonce binds, when it differs from the registered one. */ + readonly boundKey?: KeyPair; + readonly appId?: string; + readonly counter?: number; + readonly aaguid?: string; + readonly wrongKeyId?: boolean; + readonly root?: KeyPair; +}; + +export function appleAttestation(fixture: TrustFixture, spec: AppleSpec) { + const approvalKey = spec.approvalKey ?? newKey(); + const appAttestKey = newKey(); + const keyId = sha256(point(appAttestKey.publicKey)); + const aaguid = Buffer.alloc(16); + Buffer.from(spec.aaguid ?? "appattest").copy(aaguid); + const counter = Buffer.alloc(4); + counter.writeUInt32BE(spec.counter ?? 0); + const authData = new Uint8Array([ + ...sha256(Buffer.from(spec.appId ?? APPLE_APP_ID)), + 0x40, + ...counter, + ...aaguid, + 0, + 32, + ...keyId, + 0xa0, + ]); + const clientDataHash = sha256(spec.challenge, point((spec.boundKey ?? approvalKey).publicKey)); + const nonce = sha256(authData, clientDataHash); + const root = spec.root ?? fixture.appleRoot; + const intermediate = newKey(); + const intermediateDer = certificate({ + subject: "Test App Attest CA", + issuer: "Test Apple Root", + subjectKey: intermediate.publicKey, + issuerKey: root.privateKey, + ca: true, + }); + const credCert = certificate({ + subject: "App Attest Key", + issuer: "Test App Attest CA", + subjectKey: appAttestKey.publicKey, + issuerKey: intermediate.privateKey, + extensions: [ + { oid: "1.2.840.113635.100.8.2", value: der.seq(der.explicit(1, der.octet(nonce))) }, + ], + }); + const attestationObject = cbor.map([ + ["fmt", cbor.text("apple-appattest")], + [ + "attStmt", + cbor.map([ + ["x5c", cbor.array([cbor.bytes(credCert), cbor.bytes(intermediateDer)])], + ["receipt", cbor.bytes(new Uint8Array([1]))], + ]), + ], + ["authData", cbor.bytes(authData)], + ]); + return { + publicJwk: publicJwkOf(approvalKey.publicKey), + approvalKey, + keyId: b64(spec.wrongKeyId ? sha256(keyId) : keyId), + attestationObject: b64(attestationObject), + }; +} diff --git a/apps/server/src/kin/approvals/attestation/verify.test.ts b/apps/server/src/kin/approvals/attestation/verify.test.ts new file mode 100644 index 0000000000000..7376bc60ed3cf --- /dev/null +++ b/apps/server/src/kin/approvals/attestation/verify.test.ts @@ -0,0 +1,203 @@ +// @effect-diagnostics nodeBuiltinImport:off -- random challenges for fixtures. +import * as NodeCrypto from "node:crypto"; + +import { assert, describe, it } from "@effect/vitest"; + +import { + androidChain, + appleAttestation, + certificate, + makeTrustFixture, + newKey, + type AndroidChainSpec, + type AppleSpec, +} from "./testFixtures.ts"; +import { verifyAndroidKeyAttestation, verifyAppleAppAttest } from "./verify.ts"; + +const NOW = Date.parse("2026-11-08T00:00:00Z"); +const challenge = new Uint8Array(NodeCrypto.randomBytes(32)); + +describe("Android key attestation", () => { + const fixture = makeTrustFixture(); + const verify = (spec: Partial = {}, trust = fixture.trust) => { + const chain = androidChain(fixture, { challenge, ...spec }); + return verifyAndroidKeyAttestation({ + certificateChain: chain.certificateChain, + challenge, + publicJwk: chain.publicJwk, + trust, + now: NOW, + }); + }; + + it("accepts a StrongBox key and reads the hardware from the attestation", () => { + assert.deepStrictEqual(verify(), { attested: true, hardware: "strongbox" }); + assert.deepStrictEqual(verify({ attestationLevel: 1, keyMintLevel: 1 }), { + attested: true, + hardware: "tee", + }); + }); + + const rejections: ReadonlyArray, string]> = [ + ["another root", { root: newKey() }, "Google hardware attestation root"], + ["a forged leaf", { leafSignedByStranger: true }, "isn't signed by the next one"], + ["an expired leaf", { leafNotAfter: "260101000000Z" }, "outside its validity"], + ["another challenge", { challenge: new Uint8Array(32) }, "challenge mismatch"], + ["a software key", { attestationLevel: 0 }, "secure hardware"], + ["software KeyMint", { keyMintLevel: 0 }, "secure hardware"], + ["an encrypting key", { purposes: [0, 2] }, "SIGN only"], + ["an RSA key", { algorithm: 1 }, "algorithm"], + ["another curve", { ecCurve: 2 }, "P-256"], + ["no key size", { omitKeySize: true }, "missing element"], + ["a key for every app", { allApplications: true }, "every app"], + ["a SHA-1 digest", { digests: [2] }, "SHA-256"], + ["a PIN-gated key", { userAuthType: 1 }, "biometric only"], + ["an auth timeout", { authTimeout: 30 }, "auth timeout"], + ["no auth required", { noAuthRequiredInSoftware: true }, "needs no auth"], + ["an imported key", { origin: 2 }, "generated in hardware"], + ["an unlocked bootloader", { deviceLocked: false }, "unlocked"], + ["unverified boot", { bootState: 2 }, "Verified"], + ["another app", { packages: ["com.evil.app"] }, "package"], + ["two apps", { packages: ["com.gldroger.kin", "com.evil.app"] }, "more than one package"], + ["another signer", { signers: ["cd".repeat(32)] }, "signing certificates"], + ["an extra signer", { signers: ["ab".repeat(32), "cd".repeat(32)] }, "signing certificates"], + ["a key description above the leaf", { descriptionInIntermediate: true }, "outside the leaf"], + ]; + it.each(rejections)("refuses %s", (_name, spec, reason) => { + const result = verify(spec); + assert.isFalse(result.attested); + assert.include(result.attested ? "" : result.reason, reason); + }); + + it("refuses a chain with a revoked certificate", () => { + const serial = new Uint8Array([0x0f, 0x1e, 0x2d]); + const result = verify( + { leafSerial: serial }, + { ...fixture.trust, androidRevokedSerials: new Set(["f1e2d"]) }, + ); + assert.deepStrictEqual(result, { + attested: false, + reason: "a certificate in the chain is revoked", + }); + }); + + it("refuses a repeated signing digest when the allowlist has two", () => { + const signers = ["ab".repeat(32), "cd".repeat(32)]; + const trust = { + ...fixture.trust, + androidApps: [{ packageName: "com.gldroger.kin", signingCertSha256: signers }], + }; + assert.isTrue(verify({ signers }, trust).attested); + const result = verify({ signers: [signers[0]!, signers[0]!] }, trust); + assert.deepStrictEqual(result, { + attested: false, + reason: "signing certificates don't match the allowlist", + }); + }); + + it("checks links and validity against the pinned root, not the copy the chain sends", () => { + // Google reissued its RSA root under the same key, so a device may send either copy. + const reissue = (notAfter: string) => + Buffer.from( + certificate({ + subject: "Test Google Root", + issuer: "Test Google Root", + subjectKey: fixture.googleRoot.publicKey, + issuerKey: fixture.googleRoot.privateKey, + ca: true, + notBefore: "200101000000Z", + notAfter, + }), + ).toString("base64"); + const chain = androidChain(fixture, { challenge }); + const base = { challenge, publicJwk: chain.publicJwk, now: NOW }; + const expiredPin = verifyAndroidKeyAttestation({ + ...base, + certificateChain: chain.certificateChain, + trust: { + ...fixture.trust, + googleRoots: [ + new NodeCrypto.X509Certificate(Buffer.from(reissue("260601000000Z"), "base64")), + ], + }, + }); + assert.deepStrictEqual(expiredPin, { + attested: false, + reason: "certificate 2 is outside its validity", + }); + const expiredCopy = verifyAndroidKeyAttestation({ + ...base, + certificateChain: [...chain.certificateChain.slice(0, -1), reissue("260601000000Z")], + trust: fixture.trust, + }); + assert.deepStrictEqual(expiredCopy, { attested: true, hardware: "strongbox" }); + }); + + it("refuses a chain for another key and malformed input", () => { + const chain = androidChain(fixture, { challenge }); + const other = androidChain(fixture, { challenge }); + const base = { challenge, trust: fixture.trust, now: NOW }; + const swapped = verifyAndroidKeyAttestation({ + ...base, + certificateChain: chain.certificateChain, + publicJwk: other.publicJwk, + }); + assert.deepStrictEqual(swapped, { + attested: false, + reason: "attested key isn't the registered key", + }); + const garbage = verifyAndroidKeyAttestation({ + ...base, + certificateChain: ["bm90IGEgY2VydA==", chain.certificateChain[1]!], + publicJwk: chain.publicJwk, + }); + assert.isFalse(garbage.attested); + const short = verifyAndroidKeyAttestation({ + ...base, + certificateChain: chain.certificateChain.slice(0, 1), + publicJwk: chain.publicJwk, + }); + assert.deepStrictEqual(short, { attested: false, reason: "attestation chain is too short" }); + }); +}); + +describe("Apple App Attest", () => { + const fixture = makeTrustFixture(); + const verify = (spec: Partial = {}, trust = fixture.trust) => { + const attestation = appleAttestation(fixture, { challenge, ...spec }); + return verifyAppleAppAttest({ + keyId: attestation.keyId, + attestationObject: attestation.attestationObject, + challenge, + publicJwk: attestation.publicJwk, + trust, + now: NOW, + }); + }; + + it("accepts an attestation over the challenge and the new key", () => { + assert.deepStrictEqual(verify(), { attested: true, hardware: "secure_enclave" }); + assert.deepStrictEqual( + verify( + { aaguid: "appattestdevelop" }, + { ...fixture.trust, appleEnvironments: ["development"] }, + ), + { attested: true, hardware: "secure_enclave" }, + ); + }); + + const rejections: ReadonlyArray, string]> = [ + ["another root", { root: newKey() }, "Apple App Attest root"], + ["another challenge", { challenge: new Uint8Array(32) }, "nonce"], + ["a nonce over another approval key", { boundKey: newKey() }, "nonce"], + ["another app", { appId: "TEAM999999.com.evil" }, "allowlist"], + ["a used App Attest key", { counter: 1 }, "counter"], + ["a development build", { aaguid: "appattestdevelop" }, "environment"], + ["a keyId for another key", { wrongKeyId: true }, "keyId"], + ]; + it.each(rejections)("refuses %s", (_name, spec, reason) => { + const result = verify(spec); + assert.isFalse(result.attested); + assert.include(result.attested ? "" : result.reason, reason); + }); +}); diff --git a/apps/server/src/kin/approvals/attestation/verify.ts b/apps/server/src/kin/approvals/attestation/verify.ts new file mode 100644 index 0000000000000..146725e05d705 --- /dev/null +++ b/apps/server/src/kin/approvals/attestation/verify.ts @@ -0,0 +1,365 @@ +// @effect-diagnostics nodeBuiltinImport:off extendsNativeError:off -- node:crypto X.509; errors stay inside `run`. +import * as NodeCrypto from "node:crypto"; + +import type { KinApproverKeyHardware, KinApproverPublicJwk } from "@t3tools/contracts"; + +import * as Der from "./der.ts"; + +/** Pinned roots, allowlists and Google's revocation list (approvals spec section 4). */ +export type AttestationTrust = { + readonly googleRoots: ReadonlyArray; + /** Lowercase hex serials without leading zeros, as Google's status list keys them. */ + readonly androidRevokedSerials: ReadonlySet; + readonly androidApps: ReadonlyArray<{ + readonly packageName: string; + /** Lowercase hex SHA-256 of each release signing certificate. */ + readonly signingCertSha256: ReadonlyArray; + }>; + readonly appleRoot: NodeCrypto.X509Certificate; + /** `.`. */ + readonly appleAppIds: ReadonlyArray; + readonly appleEnvironments: ReadonlyArray<"production" | "development">; +}; + +export type AttestationResult = + | { readonly attested: true; readonly hardware: Exclude } + | { readonly attested: false; readonly reason: string }; + +class Refused extends Error {} +const refuse = (reason: string): never => { + throw new Refused(reason); +}; +const check = (condition: boolean, reason: string) => { + if (!condition) refuse(reason); +}; + +const run = (body: () => AttestationResult): AttestationResult => { + try { + return body(); + } catch (error) { + if (error instanceof Refused) return { attested: false, reason: error.message }; + if (error instanceof Der.DerError) + return { attested: false, reason: `malformed: ${error.message}` }; + return { attested: false, reason: "malformed attestation" }; + } +}; + +const sha256 = (...parts: ReadonlyArray) => { + const hash = NodeCrypto.createHash("sha256"); + for (const part of parts) hash.update(part); + return new Uint8Array(hash.digest()); +}; +const equalBytes = (a: Uint8Array, b: Uint8Array) => + a.length === b.length && NodeCrypto.timingSafeEqual(a, b); +const spki = (certificate: NodeCrypto.X509Certificate) => + new Uint8Array(certificate.publicKey.export({ type: "spki", format: "der" })); +const decodeBase64 = (value: string) => { + check(/^[A-Za-z0-9+/]+={0,2}$/.test(value) && value.length % 4 === 0, "certificate isn't base64"); + return new Uint8Array(Buffer.from(value, "base64")); +}; +const parseCertificate = (der: Uint8Array) => { + try { + return new NodeCrypto.X509Certificate(der); + } catch { + return refuse("certificate doesn't parse"); + } +}; +const withinValidity = (certificate: NodeCrypto.X509Certificate, now: number) => + Date.parse(certificate.validFrom) <= now && now <= Date.parse(certificate.validTo); + +/** Each certificate is signed by the next one. */ +function verifyLinks(chain: ReadonlyArray, now: number) { + for (const [index, certificate] of chain.entries()) { + check(withinValidity(certificate, now), `certificate ${index} is outside its validity`); + const issuer = chain[index + 1]; + if (issuer === undefined) continue; + check( + certificate.checkIssued(issuer) && certificate.verify(issuer.publicKey), + `certificate ${index} isn't signed by the next one`, + ); + } +} + +const pointBytes = (jwk: { readonly x?: string; readonly y?: string }) => { + check(typeof jwk.x === "string" && typeof jwk.y === "string", "not an EC key"); + return new Uint8Array([ + 0x04, + ...Buffer.from(jwk.x!, "base64url"), + ...Buffer.from(jwk.y!, "base64url"), + ]); +}; +const jwkPoint = (jwk: KinApproverPublicJwk) => pointBytes(jwk); +const certificatePoint = (certificate: NodeCrypto.X509Certificate) => { + const jwk = certificate.publicKey.export({ format: "jwk" }); + check(jwk.kty === "EC" && jwk.crv === "P-256", "attested key isn't P-256"); + return pointBytes(jwk); +}; + +/** 1.3.6.1.4.1.11129.2.1.17 */ +const KEY_DESCRIPTION_OID = "2b06010401d679020111"; +const SECURITY_LEVEL = { trustedEnvironment: 1, strongBox: 2 } as const; +const TAG = { + purpose: 1, + algorithm: 2, + keySize: 3, + digest: 5, + ecCurve: 10, + noAuthRequired: 503, + userAuthType: 504, + authTimeout: 505, + allApplications: 600, + origin: 702, + rootOfTrust: 704, + attestationApplicationId: 709, +} as const; +const PURPOSE_SIGN = 2; +const ALGORITHM_EC = 3; +const DIGEST_SHA_2_256 = 4; +const EC_CURVE_P_256 = 1; +const AUTH_FINGERPRINT = 2; +const ORIGIN_GENERATED = 0; +const BOOT_VERIFIED = 0; + +function authorizationList(tlv: Der.Tlv | undefined): ReadonlyMap { + const out = new Map(); + for (const entry of Der.sequence(tlv)) { + check(entry.cls === Der.CONTEXT && entry.constructed, "malformed authorization list"); + check(!out.has(entry.tag), "duplicate authorization tag"); + const inner = Der.children(entry); + check(inner.length === 1, "malformed authorization entry"); + out.set(entry.tag, inner[0]!); + } + return out; +} + +const integerSet = (tlv: Der.Tlv | undefined) => + Der.children(Der.expect(tlv, Der.T_SET)).map((element) => Der.integer(element)); +const exactly = (values: ReadonlyArray, expected: number) => + values.length === 1 && values[0] === expected; + +const normalizeSerial = (serial: string) => serial.toLowerCase().replace(/^0+(?=.)/, ""); + +export function verifyAndroidKeyAttestation(input: { + readonly certificateChain: ReadonlyArray; + readonly challenge: Uint8Array; + readonly publicJwk: KinApproverPublicJwk; + readonly trust: AttestationTrust; + /** Epoch milliseconds. */ + readonly now: number; +}): AttestationResult { + return run(() => { + const ders = input.certificateChain.map(decodeBase64); + check(ders.length >= 2, "attestation chain is too short"); + const chain = ders.map(parseCertificate); + // The sent root only names a pinned key: Google reissued roots with the same key, so the + // pinned certificate, with its own validity, takes its place before the links are checked. + const rootKey = spki(chain[chain.length - 1]!); + const pinned = input.trust.googleRoots.find((root) => equalBytes(spki(root), rootKey)); + check(pinned !== undefined, "chain doesn't end at a Google hardware attestation root"); + verifyLinks([...chain.slice(0, -1), pinned!], input.now); + for (const certificate of chain) { + check( + !input.trust.androidRevokedSerials.has(normalizeSerial(certificate.serialNumber)), + "a certificate in the chain is revoked", + ); + } + check( + equalBytes(certificatePoint(chain[0]!), jwkPoint(input.publicJwk)), + "attested key isn't the registered key", + ); + const descriptions = ders.map((der) => Der.certificateExtensions(der).get(KEY_DESCRIPTION_OID)); + check(descriptions[0] !== undefined, "leaf has no key description"); + check( + descriptions.slice(1).every((extension) => extension === undefined), + "key description outside the leaf", + ); + + const fields = Der.sequence(Der.parse(descriptions[0]!.value)); + check(fields.length >= 8, "malformed key description"); + const attestationLevel = Der.enumerated(fields[1]); + const keyMintLevel = Der.enumerated(fields[3]); + const hardwareLevels: ReadonlyArray = [ + SECURITY_LEVEL.trustedEnvironment, + SECURITY_LEVEL.strongBox, + ]; + check( + hardwareLevels.includes(attestationLevel) && hardwareLevels.includes(keyMintLevel), + "attestation isn't from secure hardware", + ); + check(equalBytes(Der.octets(fields[4]), input.challenge), "attestation challenge mismatch"); + const software = authorizationList(fields[6]); + const hardware = authorizationList(fields[7]); + + check(exactly(integerSet(hardware.get(TAG.purpose)), PURPOSE_SIGN), "purpose isn't SIGN only"); + check(Der.integer(hardware.get(TAG.algorithm)) === ALGORITHM_EC, "algorithm isn't EC"); + check(Der.integer(hardware.get(TAG.ecCurve)) === EC_CURVE_P_256, "curve isn't P-256"); + check(Der.integer(hardware.get(TAG.keySize)) === 256, "key size isn't 256"); + check(exactly(integerSet(hardware.get(TAG.digest)), DIGEST_SHA_2_256), "digest isn't SHA-256"); + check( + Der.integer(hardware.get(TAG.userAuthType)) === AUTH_FINGERPRINT, + "user auth isn't biometric only", + ); + for (const list of [software, hardware]) { + check(!list.has(TAG.authTimeout), "key has an auth timeout"); + check(!list.has(TAG.noAuthRequired), "key needs no auth"); + check(!list.has(TAG.allApplications), "key is usable by every app"); + } + check( + Der.integer(hardware.get(TAG.origin)) === ORIGIN_GENERATED, + "key wasn't generated in hardware", + ); + const rootOfTrust = Der.sequence(hardware.get(TAG.rootOfTrust)); + check(rootOfTrust.length >= 3, "malformed root of trust"); + check(Der.boolean(rootOfTrust[1]), "bootloader is unlocked"); + check(Der.enumerated(rootOfTrust[2]) === BOOT_VERIFIED, "verified boot state isn't Verified"); + + // Keystore, not KeyMint, fills this in, so it is usually software-enforced. + const applicationId = + hardware.get(TAG.attestationApplicationId) ?? software.get(TAG.attestationApplicationId); + const [packages, digests] = Der.sequence(Der.parse(Der.octets(applicationId))); + const packageInfos = Der.children(Der.expect(packages, Der.T_SET)); + check(packageInfos.length === 1, "attestation names more than one package"); + const packageName = Buffer.from(Der.octets(Der.sequence(packageInfos[0])[0])).toString("utf8"); + const app = input.trust.androidApps.find((candidate) => candidate.packageName === packageName); + check(app !== undefined, "package isn't on the allowlist"); + const signers = Der.children(Der.expect(digests, Der.T_SET)).map((digest) => + Buffer.from(Der.octets(digest)).toString("hex"), + ); + const allowed = new Set(app!.signingCertSha256); + check( + allowed.size > 0 && + new Set(signers).size === signers.length && + signers.length === allowed.size && + signers.every((digest) => allowed.has(digest)), + "signing certificates don't match the allowlist", + ); + + return { + attested: true, + hardware: attestationLevel === SECURITY_LEVEL.strongBox ? "strongbox" : "tee", + }; + }); +} + +/** 1.2.840.113635.100.8.2 */ +const APPLE_NONCE_OID = "2a864886f763640802"; +const AAGUID = { + production: new Uint8Array([...Buffer.from("appattest"), 0, 0, 0, 0, 0, 0, 0]), + development: new Uint8Array(Buffer.from("appattestdevelop")), +} as const; + +type Cbor = number | string | Uint8Array | ReadonlyArray | ReadonlyMap; + +/** Definite-length unsigned ints, byte and text strings, arrays and maps: all App Attest uses. */ +function decodeCbor(bytes: Uint8Array): Cbor { + let offset = 0; + const take = (count: number) => { + check(offset + count <= bytes.length, "malformed: truncated CBOR"); + const out = bytes.subarray(offset, offset + count); + offset += count; + return out; + }; + const argument = (info: number): number => { + if (info < 24) return info; + const width = + info === 24 ? 1 : info === 25 ? 2 : info === 26 ? 4 : refuse("malformed: CBOR length"); + let n = 0; + for (const byte of take(width)) n = n * 256 + byte; + return n; + }; + const item = (depth: number): Cbor => { + check(depth < 8, "malformed: CBOR too deep"); + const [initial] = take(1); + const major = initial! >> 5; + const value = argument(initial! & 0x1f); + switch (major) { + case 0: + return value; + case 2: + return take(value); + case 3: + return new TextDecoder("utf-8", { fatal: true }).decode(take(value)); + case 4: + return Array.from({ length: value }, () => item(depth + 1)); + case 5: { + const map = new Map(); + for (let i = 0; i < value; i++) { + const key = item(depth + 1); + check(typeof key === "string" && !map.has(key), "malformed: CBOR map key"); + map.set(key, item(depth + 1)); + } + return map; + } + default: + return refuse("malformed: unsupported CBOR"); + } + }; + const out = item(0); + check(offset === bytes.length, "malformed: trailing CBOR"); + return out; +} + +const field = (map: Cbor, key: string) => + map instanceof Map ? (map.get(key) as Cbor | undefined) : refuse("malformed: expected a map"); +const bytesOf = (value: Cbor | undefined) => + value instanceof Uint8Array ? value : refuse("malformed: expected bytes"); + +export function verifyAppleAppAttest(input: { + readonly keyId: string; + readonly attestationObject: string; + readonly challenge: Uint8Array; + readonly publicJwk: KinApproverPublicJwk; + readonly trust: AttestationTrust; + /** Epoch milliseconds. */ + readonly now: number; +}): AttestationResult { + return run(() => { + const keyId = decodeBase64(input.keyId); + check(keyId.length === 32, "keyId isn't a SHA-256"); + const object = decodeCbor(decodeBase64(input.attestationObject)); + check(field(object, "fmt") === "apple-appattest", "attestation format isn't apple-appattest"); + const statement = field(object, "attStmt"); + const x5c = field(statement ?? 0, "x5c"); + check(Array.isArray(x5c) && x5c.length >= 2, "attestation chain is too short"); + const chain = (x5c as ReadonlyArray).map((der) => parseCertificate(bytesOf(der))); + verifyLinks(chain, input.now); + const top = chain[chain.length - 1]!; + const root = input.trust.appleRoot; + check( + withinValidity(root, input.now) && top.checkIssued(root) && top.verify(root.publicKey), + "chain doesn't end at the Apple App Attest root", + ); + + const authData = bytesOf(field(object, "authData")); + check(authData.length >= 55, "authenticator data is too short"); + const clientDataHash = sha256(input.challenge, jwkPoint(input.publicJwk)); + const nonce = sha256(authData, clientDataHash); + const credCert = bytesOf((x5c as ReadonlyArray)[0]); + const extension = Der.certificateExtensions(credCert).get(APPLE_NONCE_OID); + check(extension !== undefined, "credential certificate has no nonce"); + const [wrapped] = Der.sequence(Der.parse(extension!.value)); + check(wrapped?.cls === Der.CONTEXT && wrapped.tag === 1, "malformed nonce extension"); + const [nonceElement] = Der.children(wrapped!); + check(equalBytes(Der.octets(nonceElement), nonce), "nonce doesn't bind this key and challenge"); + check(equalBytes(sha256(certificatePoint(chain[0]!)), keyId), "keyId isn't the attested key"); + + const rpIdHash = authData.subarray(0, 32); + check( + input.trust.appleAppIds.some((appId) => equalBytes(sha256(Buffer.from(appId)), rpIdHash)), + "app isn't on the allowlist", + ); + const counter = Buffer.from(authData.subarray(33, 37)).readUInt32BE(0); + check(counter === 0, "attestation counter isn't 0"); + const aaguid = authData.subarray(37, 53); + check( + input.trust.appleEnvironments.some((environment) => equalBytes(AAGUID[environment], aaguid)), + "App Attest environment isn't allowed", + ); + const credentialIdLength = Buffer.from(authData.subarray(53, 55)).readUInt16BE(0); + check( + equalBytes(authData.subarray(55, 55 + credentialIdLength), keyId), + "credential id isn't keyId", + ); + return { attested: true, hardware: "secure_enclave" }; + }); +} diff --git a/apps/server/src/kin/approvals/handlers/registerApproverKey.ts b/apps/server/src/kin/approvals/handlers/registerApproverKey.ts new file mode 100644 index 0000000000000..57113acdb860d --- /dev/null +++ b/apps/server/src/kin/approvals/handlers/registerApproverKey.ts @@ -0,0 +1,59 @@ +import { KinApprovalError, type KinGrant, type KinPendingAction } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; + +import { ApproverKeys } from "../ApproverKeys.ts"; + +const refuse = (message: string) => + Effect.fail(new KinApprovalError({ reason: "invalid_state", message })); + +/** + * Activates a later approver key once an existing key's grant for it is verified and claimed. + * Shaped as spec section 6's `KinActionHandler`; APPR-9 registers it with the executor. + */ +export const makeRegisterApproverKeyHandler = Effect.gen(function* () { + const keys = yield* ApproverKeys; + + const pendingKey = Effect.fn("registerApproverKey.pendingKey")(function* ( + action: KinPendingAction, + ) { + if (action.kind !== "register_approver_key" || action.target._tag !== "device_key") + return yield* refuse("Not an approver key registration."); + const target = action.target; + const key = yield* keys.get({ orgId: action.orgId, thumbprint: target.thumbprint }); + if (Option.isNone(key)) return yield* refuse("The key to add no longer exists."); + return { target, key: key.value }; + }); + + const precheck = Effect.fn("registerApproverKey.precheck")(function* (action: KinPendingAction) { + const { target, key } = yield* pendingKey(action); + if (key.state !== "pending") return yield* refuse("The key isn't waiting to be added."); + // The card showed the target; the stored key must still be what it described. + if (!key.attested || key.hardware !== target.hardware) + return yield* refuse("The key doesn't match what was approved."); + }); + + const run = Effect.fn("registerApproverKey.run")(function* ( + action: KinPendingAction, + grant: KinGrant, + ) { + yield* precheck(action); + const { target } = yield* pendingKey(action); + if (grant.keyThumbprint === target.thumbprint) + return yield* refuse("A key can't approve itself."); + const activated = yield* keys.activateByGrant({ + orgId: action.orgId, + thumbprint: target.thumbprint, + }); + return activated ? ("succeeded" as const) : yield* refuse("The key couldn't be activated."); + }); + + const reconcile = Effect.fn("registerApproverKey.reconcile")(function* ( + action: KinPendingAction, + ) { + const { key } = yield* pendingKey(action); + return key.state === "active" ? ("done" as const) : ("not_done" as const); + }); + + return { kind: "register_approver_key" as const, precheck, run, reconcile }; +}); diff --git a/apps/server/src/kin/approvals/layer.ts b/apps/server/src/kin/approvals/layer.ts new file mode 100644 index 0000000000000..bda5a056badf5 --- /dev/null +++ b/apps/server/src/kin/approvals/layer.ts @@ -0,0 +1,14 @@ +import * as Layer from "effect/Layer"; +import * as FetchHttpClient from "effect/http/FetchHttpClient"; + +import * as KinPersistence from "../persistence/KinPersistence.ts"; +import * as ApproverKeys from "./ApproverKeys.ts"; +import * as Audit from "./Audit.ts"; +import * as AttestationTrust from "./attestation/AttestationTrust.ts"; +import * as PendingActions from "./PendingActions.ts"; + +export const layer = ApproverKeys.layer.pipe( + Layer.provide(PendingActions.layer.pipe(Layer.provide(Audit.layer))), + Layer.provide(AttestationTrust.layer.pipe(Layer.provide(FetchHttpClient.layer))), + Layer.provide(KinPersistence.layer), +); diff --git a/apps/server/src/kin/approvals/rpcHandlers.test.ts b/apps/server/src/kin/approvals/rpcHandlers.test.ts new file mode 100644 index 0000000000000..c2cdc2333cf3a --- /dev/null +++ b/apps/server/src/kin/approvals/rpcHandlers.test.ts @@ -0,0 +1,50 @@ +import { assert, it } from "@effect/vitest"; +import { AuthSessionId, AuthStandardClientScopes, KinOrgId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as HttpServerRequest from "effect/http/HttpServerRequest"; + +import * as Sqlite from "../../persistence/Sqlite.ts"; +import { connectionOf, makeKinApprovalHandlers } from "./rpcHandlers.ts"; + +it.effect("reads the call's socket and headers from the upgrade request", () => + Effect.gen(function* () { + const upgrade = HttpServerRequest.fromWeb( + new Request("http://127.0.0.1/ws", { headers: { "X-Forwarded-For": "203.0.113.9" } }), + ).modify({ remoteAddress: Option.some("::ffff:127.0.0.1") }); + const read = (request: HttpServerRequest.HttpServerRequest) => + connectionOf.pipe(Effect.provideService(HttpServerRequest.HttpServerRequest, request)); + + const direct = Option.getOrThrow(yield* read(upgrade)); + assert.strictEqual(direct.remoteAddress, "::ffff:127.0.0.1"); + assert.strictEqual(direct.headers["x-forwarded-for"], "203.0.113.9"); + // A proxy-rewritten remote address hides the real socket, so there's no connection to trust. + const rewritten = upgrade.modify({ + remoteAddress: Option.some("127.0.0.1"), + peerAddress: Option.some("10.0.0.5"), + }); + assert.isTrue(Option.isNone(yield* read(rewritten))); + assert.isTrue(Option.isNone(yield* connectionOf)); + }), +); + +it.effect("key methods refuse as disabled when Kin is off", () => + Effect.gen(function* () { + const handlers = yield* makeKinApprovalHandlers( + { + sessionId: AuthSessionId.make("session"), + subject: "browser", + method: "browser-session-cookie", + scopes: AuthStandardClientScopes, + }, + Option.none(), + ); + const orgId = KinOrgId.make("org_01"); + assert.include(yield* handlers["kin.approvals.listKeys"]({ orgId }).pipe(Effect.flip), { + reason: "disabled", + }); + assert.include(yield* handlers["kin.approvals.keyChallenge"]().pipe(Effect.flip), { + reason: "disabled", + }); + }).pipe(Effect.provide(Sqlite.layerMemory)), +); diff --git a/apps/server/src/kin/approvals/rpcHandlers.ts b/apps/server/src/kin/approvals/rpcHandlers.ts index 3a9ba24e48a4f..70dd5fb3470b5 100644 --- a/apps/server/src/kin/approvals/rpcHandlers.ts +++ b/apps/server/src/kin/approvals/rpcHandlers.ts @@ -3,14 +3,16 @@ import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Stream from "effect/Stream"; +import * as HttpServerRequest from "effect/http/HttpServerRequest"; import * as RpcGroup from "effect/rpc/RpcGroup"; import type { AuthenticatedSession } from "../../auth/EnvironmentAuth.ts"; import { KinIdentity } from "../chat/KinIdentity.ts"; +import { ApproverKeys, type KinKeyCaller } from "./ApproverKeys.ts"; import * as Audit from "./Audit.ts"; const group = RpcGroup.make(...KinApprovalRpcs); -// Every method refuses until its task lands (APPR-3, -4, -5); nothing here can approve. +// Every method refuses until its task lands (APPR-3, -4); nothing here can approve. const unavailable = Effect.fail( new KinApprovalError({ reason: "unavailable", message: "Kin approvals are unavailable." }), ); @@ -21,12 +23,32 @@ const disabled = new KinApprovalError({ const failed = () => new KinApprovalError({ reason: "unavailable", message: "Kin audit is unavailable." }); +// The WS upgrade request, so `confirmKey` can tell a loopback socket from a proxied one. +export const connectionOf = Effect.serviceOption(HttpServerRequest.HttpServerRequest).pipe( + Effect.map( + Option.flatMap((request) => { + const peer = Option.getOrUndefined(request.peerAddress); + const remote = Option.getOrUndefined(request.remoteAddress); + if (peer !== undefined && remote !== undefined && peer !== remote) return Option.none(); + return Option.some({ remoteAddress: peer ?? remote, headers: request.headers }); + }), + ), +); + export const makeKinApprovalHandlers = Effect.fn("makeKinApprovalHandlers")(function* ( session: AuthenticatedSession, // Passed in rather than read from `KinServer`, whose service union reaches the judge. - kin: Option.Option>, + kin: Option.Option>, ) { + const connection = yield* connectionOf; const audit = yield* Audit.make; + const keys = Effect.gen(function* () { + if (Option.isNone(kin)) return yield* disabled; + const services = kin.value; + const people = yield* Context.get(services, KinIdentity).resolve(session); + const caller: KinKeyCaller = { session, people, connection }; + return { keys: Context.get(services, ApproverKeys), caller }; + }); // Owner-only (spec section 11): membership in the org is not enough. const asOwner = Effect.fn("KinApprovals.asOwner")(function* (orgId: KinOrgId) { if (Option.isNone(kin)) return yield* disabled; @@ -47,11 +69,16 @@ export const makeKinApprovalHandlers = Effect.fn("makeKinApprovalHandlers")(func "kin.approvals.challenge": () => unavailable, "kin.approvals.submitGrant": () => unavailable, "kin.approvals.reject": () => unavailable, - "kin.approvals.keyChallenge": () => unavailable, - "kin.approvals.registerKey": () => unavailable, - "kin.approvals.confirmKey": () => unavailable, - "kin.approvals.listKeys": () => unavailable, - "kin.approvals.revokeKey": () => unavailable, + "kin.approvals.keyChallenge": () => + keys.pipe(Effect.flatMap(({ keys, caller }) => keys.keyChallenge(caller))), + "kin.approvals.registerKey": (input) => + keys.pipe(Effect.flatMap(({ keys, caller }) => keys.registerKey(caller, input))), + "kin.approvals.confirmKey": (input) => + keys.pipe(Effect.flatMap(({ keys, caller }) => keys.confirmKey(caller, input))), + "kin.approvals.listKeys": (input) => + keys.pipe(Effect.flatMap(({ keys, caller }) => keys.listKeys(caller, input))), + "kin.approvals.revokeKey": (input) => + keys.pipe(Effect.flatMap(({ keys, caller }) => keys.revokeKey(caller, input))), "kin.audit.list": (input) => asOwner(input.orgId).pipe( Effect.flatMap((owner) => owner.list(input).pipe(Effect.mapError(failed))), diff --git a/apps/server/src/kin/auth/ProofKeySessions.test.ts b/apps/server/src/kin/auth/ProofKeySessions.test.ts index 219a3d96b5d7f..2672a1b606338 100644 --- a/apps/server/src/kin/auth/ProofKeySessions.test.ts +++ b/apps/server/src/kin/auth/ProofKeySessions.test.ts @@ -450,9 +450,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Kin proof key se Effect.gen(function* () { const sessions = yield* SessionStore.SessionStore; const sql = yield* SqlClient.SqlClient; - // TEMP shadows the real kin_approver_keys that K020_Approvals creates. - yield* sql`CREATE TEMP TABLE kin_approver_keys (org_id TEXT, thumbprint TEXT, proof_key_thumbprint TEXT, state TEXT)`; - yield* sql`INSERT INTO kin_approver_keys VALUES ('org', 'signing-key', 'device', 'active'), ('org', 'other-signing-key', 'other', 'active')`; const original = yield* sessions.issue({ proofKeyThumbprint: "device", ttl: Duration.hours(1), @@ -466,12 +463,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Kin proof key se const renewed = yield* sessions.issue({ proofKeyThumbprint: "device" }); yield* TestClock.adjust(Duration.minutes(2)); yield* sessions.revoke(renewed.sessionId); - expect( - yield* sql`SELECT DISTINCT k.org_id, k.thumbprint FROM kin_approver_keys k - JOIN kin_auth_session_keys m ON m.proof_key_thumbprint = k.proof_key_thumbprint - JOIN auth_sessions s ON s.session_id = m.session_id - WHERE k.state != 'revoked' AND s.revoked_at IS NOT NULL`, - ).toEqual([{ org_id: "org", thumbprint: "signing-key" }]); + const revoked = (proofKey: string) => + sql`SELECT ${ProofKeySessions.proofKeyRevoked(sql, proofKey)} AS revoked`; + expect(yield* revoked("device")).toEqual([{ revoked: 1 }]); + expect(yield* revoked("other")).toEqual([{ revoked: 0 }]); expect( yield* sql`SELECT * FROM kin_auth_session_keys WHERE session_id = ${unbound.sessionId}`, ).toEqual([]); diff --git a/apps/server/src/kin/auth/ProofKeySessions.testkit.ts b/apps/server/src/kin/auth/ProofKeySessions.testkit.ts new file mode 100644 index 0000000000000..dbc6e5add5d7f --- /dev/null +++ b/apps/server/src/kin/auth/ProofKeySessions.testkit.ts @@ -0,0 +1,50 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as ConfigProvider from "effect/ConfigProvider"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as SqlClient from "effect/sql/SqlClient"; + +import * as EnvironmentAuth from "../../auth/EnvironmentAuth.ts"; +import * as SessionStore from "../../auth/SessionStore.ts"; +import * as ServerConfig from "../../config.ts"; +import * as Sqlite from "../../persistence/Sqlite.ts"; +import * as ManagedPolicy from "../../policy/ManagedPolicy.ts"; +import { layerAuth } from "../../server.ts"; + +/** T3 auth with Kin on, so session issue and revoke write the proof key marks #54 defines. */ +export const layerKinAuthTest = (prefix: string) => + layerAuth.pipe( + Layer.provide(ManagedPolicy.layerTest()), + Layer.provide( + Layer.succeed( + ConfigProvider.ConfigProvider, + ConfigProvider.fromEnv({ env: { KIN_ENABLED: "true" } }), + ), + ), + Layer.provideMerge(Sqlite.layerConfig), + Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix })), + Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ); + +/** The owner's `--repair-proof-key` pairing, exchanged by the phone holding that key. */ +export const repairProofKey = Effect.fn("ProofKeySessions.testkit.repairProofKey")(function* ( + thumbprint: string, +) { + const auth = yield* EnvironmentAuth.EnvironmentAuth; + const sessions = yield* SessionStore.SessionStore; + const sql = yield* SqlClient.SqlClient; + const link = yield* auth.createPairingLink({ + subject: "one-time-token", + proofKeyThumbprint: thumbprint, + }); + yield* sql`INSERT INTO kin_auth_key_repairs (thumbprint, pairing_link_id, created_at) + VALUES (${thumbprint}, ${link.id}, 0)`; + const exchanged = yield* auth.exchangeBootstrapCredentialForAccessToken( + link.credential, + undefined, + { deviceType: "mobile" }, + { proofKeyThumbprint: thumbprint }, + ); + return yield* sessions.verify(exchanged.access_token); +}); diff --git a/apps/server/src/kin/auth/ProofKeySessions.ts b/apps/server/src/kin/auth/ProofKeySessions.ts index 880e4ca452c34..de40a46d51dc2 100644 --- a/apps/server/src/kin/auth/ProofKeySessions.ts +++ b/apps/server/src/kin/auth/ProofKeySessions.ts @@ -3,6 +3,7 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import type * as Context from "effect/Context"; import * as SqlClient from "effect/sql/SqlClient"; +import type * as Statement from "effect/sql/Statement"; import type { AuthSessionId } from "@t3tools/contracts"; import * as SessionStore from "../../auth/SessionStore.ts"; import * as Ref from "effect/Ref"; @@ -11,24 +12,68 @@ import * as KinEnabled from "../KinEnabled.ts"; import * as KinPersistence from "../persistence/KinPersistence.ts"; import { SessionHooks } from "./sessionHooks.ts"; +type Column = Statement.Fragment | string | number; +/** + * Repaired revocations don't count, except ones at or after `since` (epoch ms): a repair re-trusts + * a proof key, never an approver key registered before the revocation (approvals spec section 4). + */ +type RevocationOptions = { readonly since?: Column }; + // `individually_revoked`: 0 none; 1 blocks only if `revoked_at <= expires_at`; 2 blocks unconditionally // (bulk sign-out, or a revoke that killed an active session). const GUARDED_BLOCK = 1; const UNCONDITIONAL_BLOCK = 2; +// `auth_sessions` stores ISO-8601 UTC text; Kin stores integer milliseconds. +const epochMillis = (sql: SqlClient.SqlClient, iso: Statement.Fragment) => + sql`CAST(ROUND((julianday(${iso}) - 2440587.5) * 86400000) AS INTEGER)`; + +const unrepaired = (sql: SqlClient.SqlClient, options: RevocationOptions) => + options.since === undefined + ? sql`m.repaired_at IS NULL` + : sql`(m.repaired_at IS NULL OR ${epochMillis(sql, sql`s.revoked_at`)} >= ${options.since})`; + +// Readers of `individually_revoked` test `!= 0` and apply the expiry guard only to 1. +const marked = (sql: SqlClient.SqlClient, options: RevocationOptions) => + sql`m.individually_revoked != 0 AND ${unrepaired(sql, options)} + AND (m.individually_revoked != ${GUARDED_BLOCK} OR s.revoked_at <= s.expires_at)`; + +/** + * A revocation reaches a proof key when its mapping is marked (bulk sign-out never marks the + * caller's own key), passes the expiry guard for 1, and isn't repaired (see `RevocationOptions`). + */ +export const proofKeyRevoked = ( + sql: SqlClient.SqlClient, + proofKey: Column, + options: RevocationOptions = {}, +) => + sql`EXISTS (SELECT 1 FROM kin_auth_session_keys m JOIN auth_sessions s ON s.session_id = m.session_id + WHERE m.proof_key_thumbprint = ${proofKey} AND s.revoked_at IS NOT NULL AND ${marked(sql, options)})`; + +/** + * Whether a revocation reached something registered from `sessionId` under `proofKey`: that + * session's own (an unmapped one counts unless after expiry), or any of its proof key's. + */ +export const revokedBySession = ( + sql: SqlClient.SqlClient, + row: { readonly sessionId: Column; readonly proofKey: Column }, + options: RevocationOptions = {}, +) => + sql`(EXISTS (SELECT 1 FROM auth_sessions s LEFT JOIN kin_auth_session_keys m ON m.session_id = s.session_id + WHERE s.session_id = ${row.sessionId} AND s.revoked_at IS NOT NULL + AND ((m.session_id IS NULL AND s.revoked_at <= s.expires_at) OR (${marked(sql, options)}))) + OR ${proofKeyRevoked(sql, row.proofKey, options)})`; + const enabled = Layer.effect( SessionHooks, Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; const blocked = Effect.fn("ProofKeySessions.blocked")( function* (thumbprint: string) { - // Readers of `individually_revoked` test `!= 0` and apply the expiry guard only to 1. - const rows = - yield* sql`SELECT 1 FROM kin_auth_session_keys m JOIN auth_sessions s ON s.session_id = m.session_id - WHERE m.proof_key_thumbprint = ${thumbprint} AND m.repaired_at IS NULL AND s.revoked_at IS NOT NULL - AND m.individually_revoked != 0 - AND (m.individually_revoked != ${GUARDED_BLOCK} OR s.revoked_at <= s.expires_at) LIMIT 1`; - return rows.length > 0; + const [row] = yield* sql<{ + blocked: number; + }>`SELECT ${proofKeyRevoked(sql, thumbprint)} AS blocked`; + return row?.blocked === 1; }, Effect.mapError(toPersistenceSqlError("ProofKeySessions.blocked")), ); diff --git a/apps/server/src/kin/layer.ts b/apps/server/src/kin/layer.ts index 4b9c0944a4d1d..714515fceb77b 100644 --- a/apps/server/src/kin/layer.ts +++ b/apps/server/src/kin/layer.ts @@ -9,6 +9,7 @@ import * as Layer from "effect/Layer"; import * as HttpRouter from "effect/http/HttpRouter"; import * as Option from "effect/Option"; import * as KinChat from "./chat/layer.ts"; +import * as KinApprovals from "./approvals/layer.ts"; import { KinChatHub } from "./chat/KinChatHub.ts"; import { KinServer, type Services } from "./KinServer.ts"; @@ -34,7 +35,7 @@ const enabled = Layer.effect( subscribeForViewer: Option.some(hub.subscribeForViewer), }; }), -).pipe(Layer.provide(Layer.merge(KinChat.layer, GithubWebhooks.lockLayer))); +).pipe(Layer.provide(Layer.mergeAll(KinChat.layer, KinApprovals.layer, GithubWebhooks.lockLayer))); const disabled = Layer.succeed(KinServer, { taskCardUpdater: Layer.empty, services: Option.none(), diff --git a/docs/kin/specs/approvals.md b/docs/kin/specs/approvals.md index 3e7999a07e4f4..e77c6aec23839 100644 --- a/docs/kin/specs/approvals.md +++ b/docs/kin/specs/approvals.md @@ -204,24 +204,26 @@ export const KinApproverKey = Schema.Struct({ Registration: -1. The phone calls `kin.approvals.keyChallenge()` (`access:write`), which returns a single-use 32-byte nonce bound to that session and valid for 5 minutes. It passes the nonce to `createKey`, then calls `kin.approvals.registerKey({publicJwk, platform, challenge, attestation?, deviceLabel})` over the same session. The server consumes the nonce, stores the key as `pending` and returns a 6-digit code derived from `sha256(thumbprint ‖ serverNonce)`. - - **Android:** `attestation.certificateChain` is required. The server checks it offline: the chain verifies up to one of Google's two hardware attestation roots (the legacy RSA root and the newer ECDSA root), each pinned by its public key, and no certificate is on Google's attestation revocation list; the leaf's public key equals `publicJwk` and is EC P-256; the KeyDescription is read from the leaf only, and a chain where any other certificate carries one is refused; the leaf's KeyDescription has `attestationChallenge` equal to the nonce, `attestationSecurityLevel` and `keyMintSecurityLevel` (`keymasterSecurityLevel` before KeyMint) of `TrustedEnvironment` or `StrongBox`, and in `hardwareEnforced`: purpose `SIGN`, algorithm EC with `ecCurve` P-256 and `keySize` 256, digest SHA-256, `userAuthType` biometric only (`FINGERPRINT`, the value Keystore uses for every strong biometric), no `authTimeout`, no `noAuthRequired`, `origin` `GENERATED`, and `rootOfTrust` with `verifiedBootState` `Verified` and `deviceLocked` true; `allApplications` absent from both authorization lists; `attestationApplicationId` names exactly one package, the release package, whose set of signing-certificate SHA-256 digests equals the server's allowlist. Invalidation on biometric re-enrolment is checked only on the client (`KeyInfo` after creation, README); attestation can't prove it. All pass: `attested: true`, and `hardware` is `strongbox` or `tee` from the attestation security level. Any check fails: `attested: false`, `hardware: "software"`. The client never supplies `hardware`. - - **iOS:** `attestation` is `{format: "apple-app-attest", keyId, attestationObject}`. `createKey` makes it natively: a fresh App Attest key, attested over the client data hash `sha256(challenge ‖ 0x04 ‖ x ‖ y)` of the Secure Enclave key it just made. The module computes that hash itself, so JS can't get an attestation over a key or data it chose. The server follows Apple's documented verification: the `x5c` chain verifies to the pinned Apple App Attest root; the nonce extension (OID `1.2.840.113635.100.8.2`) equals `sha256(authData ‖ clientDataHash)`, where the server recomputes `clientDataHash` from the nonce it issued and `publicJwk`; the credential certificate's public key hashes to `keyId`; `authData`'s RP ID hash is `sha256(".")` for the Kin bundle id; the counter is 0; the aaguid is `appattest` followed by seven zero bytes for production builds, and `appattestdevelop` only on a server configured to accept development builds; the credential id equals `keyId`. All pass: `attested: true`, `hardware: "secure_enclave"`. No attestation (a simulator or an unsupported device) or any failed check: `attested: false`, `hardware: "software"`. The attestation object's `fmt` must be `apple-appattest` (the CBOR field, distinct from the client's `format` label `apple-app-attest`). `keyId` is `sha256` of the credential certificate's public key as the 65-byte X9.63 point, not its SPKI. Every certificate in `x5c` must be valid at verification time. The App Attest key is used only here; nothing later asserts with it, so the attestation's receipt isn't needed. App Attest proves the app, not its version: once several native builds have shipped, the server keeps a minimum native build (or a version allowlist) and refuses registration from older ones. +1. The phone calls `kin.approvals.keyChallenge()` (`access:write`), which returns a single-use 32-byte nonce bound to that session and valid for 5 minutes. It passes the nonce to `createKey`, then calls `kin.approvals.registerKey({publicJwk, platform, challenge, attestation?, deviceLabel})` over the same session. The server consumes the nonce, stores the key as `pending` and returns a 6-digit code derived from `sha256(thumbprint ‖ serverNonce)`, where `serverNonce` is that challenge. Challenges and codes live in server memory: a code is good for 10 minutes and five tries, and after a restart the phone makes and registers a new key. A thumbprint registers only once. + - **Android:** `attestation.certificateChain` is required. The server checks it offline: the chain verifies up to one of Google's two hardware attestation roots (the legacy RSA root and the newer ECDSA root), each pinned by its public key, and no certificate is on Google's attestation revocation list; the leaf's public key equals `publicJwk` and is EC P-256; the KeyDescription is read from the leaf only, and a chain where any other certificate carries one is refused; the leaf's KeyDescription has `attestationChallenge` equal to the nonce, `attestationSecurityLevel` and `keyMintSecurityLevel` (`keymasterSecurityLevel` before KeyMint) of `TrustedEnvironment` or `StrongBox`, and in `hardwareEnforced`: purpose `SIGN`, algorithm EC with `ecCurve` P-256 and `keySize` 256, digest SHA-256, `userAuthType` biometric only (`FINGERPRINT`, the value Keystore uses for every strong biometric), no `authTimeout`, no `noAuthRequired`, `origin` `GENERATED`, and `rootOfTrust` with `verifiedBootState` `Verified` and `deviceLocked` true; `allApplications` absent from both authorization lists; `attestationApplicationId` names exactly one package, the release package, with exactly the allowlisted signing-certificate SHA-256s, each once. The chain's last certificate only has to carry a pinned root's key, since Google reissued its RSA root under the same key; the pinned certificate takes its place, so its own validity and its signature on the next certificate are what count. Invalidation on biometric re-enrolment is checked only on the client (`KeyInfo` after creation, README); attestation can't prove it. All pass: `attested: true`, and `hardware` is `strongbox` or `tee` from the attestation security level. Any check fails: `attested: false`, `hardware: "software"`. The client never supplies `hardware`. + - **iOS:** `attestation` is `{format: "apple-app-attest", keyId, attestationObject}`. `createKey` makes it natively: a fresh App Attest key, attested over the client data hash `sha256(challenge ‖ 0x04 ‖ x ‖ y)` of the Secure Enclave key it just made. The module computes that hash itself, so JS can't get an attestation over a key or data it chose. The server follows Apple's documented verification: the `x5c` chain verifies to the pinned Apple App Attest root; the nonce extension (OID `1.2.840.113635.100.8.2`) equals `sha256(authData ‖ clientDataHash)`, where the server recomputes `clientDataHash` from the nonce it issued and `publicJwk`; the credential certificate's public key hashes to `keyId`; `authData`'s RP ID hash is `sha256(".")` for the Kin bundle id; the counter is 0; the aaguid is `appattest` followed by seven zero bytes for production builds, and `appattestdevelop` only on a server configured to accept development builds; the credential id equals `keyId`. All pass: `attested: true`, `hardware: "secure_enclave"`. No attestation (a simulator or an unsupported device) or any failed check: `attested: false`, `hardware: "software"`. The attestation object's `fmt` must be `apple-appattest` (the CBOR field, distinct from the client's `format` label `apple-app-attest`). `keyId` is `sha256` of the credential certificate's public key as the 65-byte X9.63 point, not its SPKI. Every certificate in `x5c` must be valid at verification time. The App Attest key is used only here; nothing later asserts with it, so the attestation's receipt isn't needed. App Attest proves the app, not its version: once several native builds have shipped, the server keeps a minimum native build (or a version allowlist) and refuses registration from older ones. On iOS `attested: true` means a genuine Kin app instance asked for this public key. It does not prove the approver key is in the Secure Enclave or gated by biometrics, and it does not detect a jailbroken phone; Android's attestation does prove hardware storage and a verified, locked boot. The owner accepted this weaker meaning for phase 1 (2026-11-09), since without it no iPhone could approve. `hardware: "secure_enclave"` is claimed by the platform, not proven. - **Either platform:** the server never makes a key with `attested: false` `active`. It is listed as "can't be used for approvals" and can only be revoked; `confirmKey` refuses it, and no `register_approver_key` action can be requested for it. This is what stops tampered JS from deleting the hardware key, making a P-256 key in JS and registering it: the 6-digit code would match, because it derives from whatever key was registered, but that key can't be attested. -2. **First key in an org:** confirmed on the Mac running the server, in the desktop app's local session (loopback only), where the owner checks the code shown on both screens. No remote path can confirm the first key. -3. **Later keys:** confirmed by a grant of kind `register_approver_key` signed by an existing active key. Its `device_key` target carries the new key's `hardware` and `attested` from the server's record, so the phone's prompt shows them (`Add approver key NzbLsXh8uDCcd-6MNwXF4W_7noWXFZAfHkxZsRGC9Xs (Secure Enclave, attested)`), and the module refuses a target that isn't attested. -4. Revoking (`kin.approvals.revokeKey`, from settings or the desktop) sets `revoked` and voids every `approved` action whose grant that key signed. Revoking a T3 device session (`revokeClient`) also revokes keys registered from it. +2. **First key in an org:** confirmed on the Mac running the server, in the desktop app's local session (loopback only), where the owner checks the code shown on both screens. No remote path can confirm the first key. "Local" means all of: the session's subject is `desktop-bootstrap` (only the desktop app holds that credential), the session was issued to a loopback address, and the call's own socket is loopback with no `Forwarded`, `X-Forwarded-*`, `X-Real-IP`, `CF-Connecting-IP` or `Tailscale-User-Login` header. A browser or tunnel process on the same Mac fails the first check; a desktop on WSL fails the second, so it can't confirm keys. The subject and the issuance address are the real guard. The socket check is defence in depth, since a proxy on the same Mac connects over loopback and can drop those headers. `confirmKey` works only while the org has no active key. +3. **Later keys:** confirmed by a grant of kind `register_approver_key` signed by an existing active key. Its `device_key` target carries the new key's `hardware` and `attested` from the server's record, so the phone's prompt shows them (`Add approver key NzbLsXh8uDCcd-6MNwXF4W_7noWXFZAfHkxZsRGC9Xs (Secure Enclave, attested)`), and the module refuses a target that isn't attested. When an attested key registers in an org that already has an active key, `registerKey` opens that pending action itself (requester `kin-approver-keys`, provenance started by the registering person). That requester id is reserved: `KinPendingActions.create` refuses it for any other kind, and as an agent or thread id, and the handler activates the key only if it is still `pending`, attested and on the hardware the card showed. +4. Revoking (`kin.approvals.revokeKey`, from settings or the desktop) sets `revoked` and voids every `approved` action whose grant that key signed. Revoking a T3 device session (`revokeClient`) also revokes keys registered from it. Kin reads `auth_sessions.revoked_at` at startup and before it trusts, lists or activates a key, rather than hooking T3's auth code. Revoking also cancels a pending `register_approver_key` action for the key. Expiry is not revocation: a key outlives the session that registered it. A DPoP relay session renews hourly under a new session id but the same DPoP key, so each key also stores that key's thumbprint (`proof_key_thumbprint`), and revoking any session of that DPoP key revokes the key (below). + +The server's attestation allowlist comes from `KIN_ANDROID_PACKAGE`, `KIN_ANDROID_SIGNING_CERT_SHA256` (comma-separated hex), `KIN_IOS_APP_ID` (`.`) and `KIN_IOS_APP_ATTEST_DEVELOPMENT` (accept `appattestdevelop`; default false). With none set, every key registers unattested. Google's roots and Apple's App Attest root are pinned in `apps/server/src/kin/approvals/attestation/roots.ts`. Google's revocation list is fetched from `https://android.googleapis.com/attestation/status` and cached for an hour. If it can't be fetched, Android registration fails and the phone retries; it never stores a key whose chain went unchecked. #### Device session revocation (lane B integration) -PR #54 must land before or with #42. Keep the registering `session_id` reconcile alongside this exact-thumbprint fallback: +`ApproverKeys.reconcileSessions` revokes a key when either of these holds (`revokedBySession` in `apps/server/src/kin/auth/ProofKeySessions.ts`, which grant check 10 also uses): -```sql -SELECT DISTINCT k.org_id, k.thumbprint FROM kin_approver_keys k -JOIN kin_auth_session_keys m ON m.proof_key_thumbprint = k.proof_key_thumbprint -JOIN auth_sessions s ON s.session_id = m.session_id -WHERE k.state != 'revoked' AND s.revoked_at IS NOT NULL -``` +- Its registering session was revoked, and that session either has no `kin_auth_session_keys` row and was revoked before it expired, or is marked by `individually_revoked` (see below). +- Any session mapped to the key's `proof_key_thumbprint` is marked by `individually_revoked`. This is how a renewed relay session's revocation reaches a key registered under an earlier id. + +A mapping is marked when `individually_revoked != 0 AND (individually_revoked != 1 OR s.revoked_at <= s.expires_at)`: 1 is a revoke that counts only before expiry, 2 an unconditional block (bulk sign-out, or a revoke that killed an active session). + +"Sign out other devices" revokes every other session and blocks every other mapped proof key, even one whose sessions had all expired, but never the caller's own key, so the caller's own key and its earlier renewals keep their approver keys. Revoking only an expired, disconnected session of a phone doesn't reach its key; revoke that phone's key itself. Either revocation counts against a key unless it was repaired and landed before the key's `created_at` (integer milliseconds; `auth_sessions.revoked_at` is ISO-8601 text, converted to milliseconds before comparing). So a revocation after a key registered revokes it for good, even once repaired, and a repair never restores an approver key; the phone registers a new one. `registerKey` refuses (`invalid_state`) a proof key with any unrepaired revocation and allows one whose revocations are all repaired, because mobile keeps one DPoP key per install and can't pair with a fresh one. The exchange block below uses the same proof key rule, where every repaired revocation stops counting. There is no backfill: historical `jkt` values exist only in signed tokens, not stored sessions. The mapping is environment-local, not org-owned; the approver table supplies org isolation. K015_AuthSessionKeys owns this environment-local exception; these auth tables intentionally have no org_id. @@ -229,7 +231,7 @@ With Kin enabled, an individually revoked mapped session blocks fresh exchanges The server owner can deliberately re-pair the same key with `t3 auth pairing create --repair-proof-key ` against the target environment's home directory, with Kin enabled or with Kin off when that database already has the Kin auth tables; the repair is consumed once Kin is on. The flag accepts only canonical 43-character base64url SHA-256 thumbprints. The CLI preserves upstream's `one-time-token` subject and records a key-bound repair in `kin_auth_key_repairs` with its pairing link id and integer-millisecond creation/consumption timestamps. Exchanges atomically consume that exact repair and acknowledge existing individual and bulk blocks; cloud mints, unbound links, another key and replay cannot acknowledge them. A later individual revocation or bulk sign-out blocks again and voids that key's unconsumed repairs, so a repair link issued before the block cannot lift it. Repair consumption and acknowledgement precede session insertion in a separate transaction because upstream resolves/consumes bootstrap grants before issuing a session; the post-insert check covers intervening revocation. If session issuance fails after consumption, the repair is spent and the key is already unblocked; a fresh ordinary pairing can retry unless a later revocation blocks it again. Repair never restores sessions or approver keys or bypasses registration/confirmation. -Lane B (#42) must keep the registering-session reconcile and exact-key fallback, and exclude sessions whose mapped thumbprint matches the caller's during `revokeAllExcept`. It must read the mapping's `individually_revoked` column by this rule: 0 means not revoked, 1 means a revoke that blocks only if `s.revoked_at <= s.expires_at`, and 2 means an unconditional block (bulk sign-out, or a revoke that killed an active session). Test `individually_revoked != 0` and apply the expiry guard only to 1, as in `m.individually_revoked != 0 AND (m.individually_revoked != 1 OR s.revoked_at <= s.expires_at)`; a partial index uses `WHERE individually_revoked != 0`. Reading `= 1` treats every unconditional block as not revoked. Its historical join still sees repaired revocations: use a fresh proof key for new approver registration unless lane B implements repair-aware registration. These approver-key reconciliation changes remain lane B's responsibility, not #54. Nishchay's sign-off on the environment-local auth-table exception is still required. +Nishchay's sign-off on the environment-local auth-table exception is still required. A key's role isn't stored on the key. It is read at verify time from org membership (chat spec), so demoting a person takes effect at once. @@ -580,6 +582,8 @@ RPCs and scopes: `kin.approvals.list` (stream) and `get` → `orchestration:read - **Lead:** registry of lead threads (for `request_action`), `KinEvent.id` (idempotency) and provenance, the stop switch (executor checks it), levels (`set_level` handler, `ceilingAllows`), `change_rules` handler. - **Triggers:** `pull_request` synchronize/closed webhooks → `refreshAction(actionId)`; `pull_request_review` → enables a card waiting on a GitHub review; `memory_purge` handler; Kin host setup (bot `gh` login, keychain items, hygiene check passing); upstream contract test for `GitHubRequestPolicy.credential` and `verifyDpopProof`. - **Mobile:** renders `ApprovalCard` inside the chat screens; this spec ships the card, the native module and the signing hook. +- **T3 auth (lane A), open hand-offs:** + - `KinIdentity.resolve` returns each person's org role once members exist (CHAT-11). `registerKey` then refuses anyone but the owner and takes `startedByRole` from that role. Until then, `resolve` returns only the org owner, so the literal `"owner"` is accurate. ## Security tests (named, all in `apps/server/src/kin/approvals/*.test.ts` unless noted) diff --git a/packages/contracts/src/kinApprovals.test.ts b/packages/contracts/src/kinApprovals.test.ts index 6457e4a7173b0..ee7c6aabfe7b4 100644 --- a/packages/contracts/src/kinApprovals.test.ts +++ b/packages/contracts/src/kinApprovals.test.ts @@ -1,7 +1,12 @@ import { describe, expect, it } from "@effect/vitest"; import * as Schema from "effect/Schema"; -import { BranchName, KinApprovalsRegisterKeyInput, KinContentPath } from "./kinApprovals.ts"; +import { + BranchName, + KinApprovalsRegisterKeyInput, + KinApproverPublicJwk, + KinContentPath, +} from "./kinApprovals.ts"; const accepts = (schema: Schema.Top, value: unknown) => Schema.is(schema as Schema.Codec)(value); @@ -36,10 +41,15 @@ describe("approval names", () => { it("caps each attestation certificate", () => { const input = (cert: string) => ({ orgId: "org_01", - publicJwk: { kty: "EC", crv: "P-256", x: "x".repeat(43), y: "y".repeat(43) }, + publicJwk: { + kty: "EC", + crv: "P-256", + x: "f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU", + y: "x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0", + }, platform: "android", challenge: "abc", - attestation: { certificateChain: [cert] }, + attestation: { format: "android-key", certificateChain: [cert] }, deviceLabel: "Phone", }); const decode = Schema.decodeUnknownExit(KinApprovalsRegisterKeyInput); @@ -47,3 +57,18 @@ describe("approval names", () => { expect(decode(input("A".repeat(8193)))._tag).toBe("Failure"); }); }); + +describe("KinApproverPublicJwk", () => { + it("accepts only the canonical spelling of each coordinate", () => { + const is = Schema.is(KinApproverPublicJwk); + const jwk = { + kty: "EC", + crv: "P-256", + x: "f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU", + y: "x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0", + }; + expect(is(jwk)).toBe(true); + // "U" and "V" differ only in a padding bit: the same 32 bytes under a second thumbprint. + expect(is({ ...jwk, x: `${jwk.x.slice(0, 42)}V` })).toBe(false); + }); +}); diff --git a/packages/contracts/src/kinApprovals.ts b/packages/contracts/src/kinApprovals.ts index 695f57b0d69f8..f115281acd023 100644 --- a/packages/contracts/src/kinApprovals.ts +++ b/packages/contracts/src/kinApprovals.ts @@ -221,11 +221,16 @@ export const KinPendingAction = Schema.Struct({ }); export type KinPendingAction = typeof KinPendingAction.Type; +// 43 characters carry 258 bits; the last two must be zero, so a key has one spelling and one thumbprint. +const P256Coordinate = pattern( + /^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/, + "a canonical base64url P-256 coordinate", +); export const KinApproverPublicJwk = Schema.Struct({ kty: Schema.Literal("EC"), crv: Schema.Literal("P-256"), - x: pattern(/^[A-Za-z0-9_-]{43}$/, "a base64url P-256 coordinate"), - y: pattern(/^[A-Za-z0-9_-]{43}$/, "a base64url P-256 coordinate"), + x: P256Coordinate, + y: P256Coordinate, }); export type KinApproverPublicJwk = typeof KinApproverPublicJwk.Type; @@ -454,19 +459,31 @@ export const KinApprovalsKeyChallengeResult = Schema.Struct({ expiresAt: CanonicalUtcTimestamp, }); export type KinApprovalsKeyChallengeResult = typeof KinApprovalsKeyChallengeResult.Type; +const Base64Blob = Schema.String.check(Schema.isMaxLength(16_384)); +export const KinApproverKeyAttestation = Schema.Union([ + Schema.Struct({ + format: Schema.Literal("android-key"), + /** Base64 DER certificates, leaf first. */ + certificateChain: Schema.Array(Schema.String.check(Schema.isMaxLength(8192))).check( + Schema.isMaxLength(10), + ), + }), + Schema.Struct({ + format: Schema.Literal("apple-app-attest"), + /** Base64 SHA-256 of the App Attest key's public key. */ + keyId: Base64Blob, + /** Base64 CBOR from `DCAppAttestService.attestKey` over `sha256(challenge ‖ 0x04 ‖ x ‖ y)`. */ + attestationObject: Base64Blob, + }), +]); +export type KinApproverKeyAttestation = typeof KinApproverKeyAttestation.Type; export const KinApprovalsRegisterKeyInput = Schema.Struct({ orgId: KinOrgId, publicJwk: KinApproverPublicJwk, platform: KinApproverKeyPlatform, challenge: Base64UrlString, - // Base64 DER certificates, leaf first. Required on Android; the server derives `hardware`. - attestation: Schema.optional( - Schema.Struct({ - certificateChain: Schema.Array(Schema.String.check(Schema.isMaxLength(8192))).check( - Schema.isMaxLength(10), - ), - }), - ), + // Without one the key is stored unattested and can never be activated. The server derives `hardware`. + attestation: Schema.optional(KinApproverKeyAttestation), deviceLabel: KinTrimmedText.check(Schema.isMaxLength(80)), }); export type KinApprovalsRegisterKeyInput = typeof KinApprovalsRegisterKeyInput.Type; @@ -527,6 +544,7 @@ export class KinApprovalError extends Schema.TaggedError()("Ki "bad_challenge", "bad_code", "not_local", + "unattested", ]), ]), message: Schema.String, diff --git a/packages/contracts/src/kinChat.test.ts b/packages/contracts/src/kinChat.test.ts index 2b0df3143b928..4b5ec7745a6e2 100644 --- a/packages/contracts/src/kinChat.test.ts +++ b/packages/contracts/src/kinChat.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from "@effect/vitest"; import * as Schema from "effect/Schema"; import * as Kin from "./kinChat.ts"; +import { KinCheckRun } from "./kinApprovals.ts"; const at = "2026-11-07T00:00:00.000Z"; const person = { @@ -266,6 +267,7 @@ describe("Kin chat contracts", () => { schema: Kin.KinTaskCardState, value: { ...task, [field]: "a\u0000b" }, })), + { schema: KinCheckRun, value: { name: "a\u0000b", required: true, status: "passed" } }, ])("rejects NUL text %#", ({ schema, value }) => { const codec: Schema.Codec = schema; expect(() => Schema.decodeSync(codec)(value)).toThrow();