diff --git a/apps/server/src/kin/approvals/Audit.test.ts b/apps/server/src/kin/approvals/Audit.test.ts new file mode 100644 index 0000000000000..90a2a5c9193b2 --- /dev/null +++ b/apps/server/src/kin/approvals/Audit.test.ts @@ -0,0 +1,586 @@ +import { assert, describe, it } from "@effect/vitest"; +import { + AuthSessionId, + AuthStandardClientScopes, + KinActionId, + KinEventId, + KinKeyThumbprint, + KinOrgId, + KinPersonId, + type KinAuditEntry, + type KinAuditEvent, + type KinAuditListInput, + type KinPendingAction, +} from "@t3tools/contracts"; +import { stableStringify } from "@t3tools/shared/relaySigning"; +import * as ConfigProvider from "effect/ConfigProvider"; +import * as Context from "effect/Context"; +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 SqlClient from "effect/sql/SqlClient"; +import * as TestClock from "effect/testing/TestClock"; + +import type { AuthenticatedSession } from "../../auth/EnvironmentAuth.ts"; +import * as Sqlite from "../../persistence/Sqlite.ts"; +import { KinIdentity } from "../chat/KinIdentity.ts"; +import * as Kin from "../layer.ts"; +import * as KinPersistence from "../persistence/KinPersistence.ts"; +import { KinAudit, kinAuditHash, layer as auditLayer } from "./Audit.ts"; +import { + KinPendingActions, + layer as pendingActionsLayer, + type KinPendingActionCreateInput, +} from "./PendingActions.ts"; +import { makeKinApprovalHandlers } from "./rpcHandlers.ts"; + +const database = Layer.provideMerge(KinPersistence.layer, Sqlite.layerMemory); +const layer = pendingActionsLayer.pipe( + Layer.provideMerge(auditLayer), + Layer.provideMerge(database), +); + +const org = Schema.decodeSync(KinOrgId)("org_01"); +const otherOrg = Schema.decodeSync(KinOrgId)("org_02"); +const defaultOrg = Schema.decodeSync(KinOrgId)("kin-default"); +const unknownOrg = Schema.decodeSync(KinOrgId)("org_unknown"); +const missingAction = Schema.decodeSync(KinActionId)("act_missing"); +const decodeEventId = Schema.decodeSync(KinEventId); +const owner = Schema.decodeSync(KinPersonId)("h_owner"); +const member = Schema.decodeSync(KinPersonId)("kin-default-member"); +const kid = Schema.decodeSync(KinKeyThumbprint)("Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E"); +const sessionId = AuthSessionId.make("phone-session"); +const headSha = "a".repeat(40); +const mergeSha = "f".repeat(40); + +const request = { + 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, + base: "main", + head: "kin/fix-212", + title: "Fix 212", + additions: 3, + deletions: 1, + files: 1, + checks: [{ name: "ci", required: true, status: "passed" }], + }, + targetDigest: "1".repeat(64), + reason: "CI is green.", + requestedBy: { agentId: "lead", threadId: "thread-lead" }, + provenance: { startedBy: "github", startedByRole: "none", chain: [] }, + source: decodeEventId("webhook-delivery-1"), +} as unknown as KinPendingActionCreateInput; + +const grant = (action: KinPendingAction, jti: string) => ({ + orgId: action.orgId, + actionId: action.id, + revision: action.revision, + nonce: action.nonce, + jti, + approverHumanId: owner, + keyThumbprint: kid, + compact: `compact-${jti}`, + iat: 0, + exp: 600, + sessionId, + deviceLabel: "Owner's iPhone", +}); + +const seed = Effect.gen(function* () { + 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'), + ('org_02', 'Other', '2026-11-07T00:00:00.000Z')`; + return yield* KinAudit; +}); + +// Tests that read entries back expect none to be corrupt. +const listIntact = (audit: KinAudit["Service"], input: KinAuditListInput) => + audit.list(input).pipe( + Effect.map((page) => ({ + ...page, + entries: page.entries.filter((entry): entry is KinAuditEntry => !("corrupt" in entry)), + })), + ); + +// The append-only triggers refuse every edit; tamper cases drop them to play the attacker. +const allowTampering = (sql: SqlClient.SqlClient) => + Effect.gen(function* () { + yield* sql`DROP TRIGGER kin_audit_no_update`; + yield* sql`DROP TRIGGER kin_audit_no_delete`; + }); + +// Five entries in org_01, so each tamper case has a row in the middle to break. +const seedChain = Effect.gen(function* () { + const audit = yield* seed; + for (const event of [ + "key_registered", + "key_confirmed", + "grant_rejected", + "key_revoked", + "credential_check_failed", + ] as const) { + yield* audit.append({ orgId: org, event, result: event }); + } + return audit; +}); + +describe("KinAudit", () => { + it.effect("the audit chain detects an edited row", () => + Effect.gen(function* () { + const audit = yield* seedChain; + const sql = yield* SqlClient.SqlClient; + assert.deepStrictEqual(yield* audit.verify({ orgId: org }), { + ok: true, + checked: 5, + firstBadSeq: null, + }); + + // Editing the canonical entry, as someone hiding a failure would. + yield* allowTampering(sql); + yield* sql`UPDATE kin_audit SET entry_json = replace(entry_json, '"result":"grant_rejected"', + '"result":"grant_accepted"') WHERE org_id = ${org} AND seq = 3`; + assert.deepStrictEqual(yield* audit.verify({ orgId: org }), { + ok: false, + checked: 2, + firstBadSeq: 3, + }); + }).pipe(Effect.provide(layer)), + ); + + it.effect.each([ + { + name: "an edited column", + tamper: (sql: SqlClient.SqlClient) => + sql`UPDATE kin_audit SET event = 'grant_accepted' WHERE org_id = ${org} AND seq = 3`, + }, + { + name: "a rehashed edit", + // The edited row's own hash is recomputed, so only the next row's prevHash gives it away. + tamper: (sql: SqlClient.SqlClient) => + Effect.gen(function* () { + const [row] = yield* sql<{ entry_json: string }>` + SELECT entry_json FROM kin_audit WHERE org_id = ${org} AND seq = 3`; + const { hash: _hash, ...unhashed } = JSON.parse(row!.entry_json); + const edited = { ...unhashed, result: "grant_accepted" }; + const hash = kinAuditHash(edited); + yield* sql`UPDATE kin_audit SET entry_json = ${stableStringify({ ...edited, hash })}, + hash = ${hash} WHERE org_id = ${org} AND seq = 3`; + }), + firstBadSeq: 4, + }, + { + name: "a deleted row", + tamper: (sql: SqlClient.SqlClient) => + sql`DELETE FROM kin_audit WHERE org_id = ${org} AND seq = 3`, + }, + { + name: "reordered rows", + tamper: (sql: SqlClient.SqlClient) => + Effect.gen(function* () { + yield* sql`UPDATE kin_audit SET seq = 100 WHERE org_id = ${org} AND seq = 3`; + yield* sql`UPDATE kin_audit SET seq = 3 WHERE org_id = ${org} AND seq = 4`; + yield* sql`UPDATE kin_audit SET seq = 4 WHERE org_id = ${org} AND seq = 100`; + }), + }, + { + name: "an inserted row", + // A forged entry chained correctly onto seq 2, with every later row shifted down by one. + tamper: (sql: SqlClient.SqlClient) => + Effect.gen(function* () { + const [prev] = yield* sql<{ hash: string }>` + SELECT hash FROM kin_audit WHERE org_id = ${org} AND seq = 2`; + yield* sql`UPDATE kin_audit SET seq = seq + 100 WHERE org_id = ${org} AND seq >= 3`; + yield* sql`UPDATE kin_audit SET seq = seq - 99 WHERE org_id = ${org} AND seq >= 103`; + const unhashed = { + id: "aud_forged", + orgId: org, + seq: 3, + at: "2026-11-08T00:00:00.000Z", + event: "grant_accepted", + prevHash: prev!.hash, + }; + const hash = kinAuditHash(unhashed); + yield* sql`INSERT INTO kin_audit (id, org_id, seq, at, event, entry_json, prev_hash, hash) + VALUES ('aud_forged', ${org}, 3, ${Date.parse(unhashed.at)}, 'grant_accepted', + ${stableStringify({ ...unhashed, hash })}, ${prev!.hash}, ${hash})`; + }), + firstBadSeq: 4, + }, + ])("verify catches $name", ({ tamper, firstBadSeq = 3 }) => + Effect.gen(function* () { + const audit = yield* seedChain; + const sql = yield* SqlClient.SqlClient; + yield* audit.append({ orgId: otherOrg, event: "key_registered" }); + yield* allowTampering(sql); + yield* tamper(sql); + assert.deepStrictEqual(yield* audit.verify({ orgId: org }), { + ok: false, + checked: firstBadSeq - 1, + firstBadSeq, + }); + // Chains are per org: the other org's stays intact. + assert.deepStrictEqual(yield* audit.verify({ orgId: otherOrg }), { + ok: true, + checked: 1, + firstBadSeq: null, + }); + }).pipe(Effect.provide(layer)), + ); + + it.effect("the database refuses to update or delete audit rows", () => + Effect.gen(function* () { + const audit = yield* seedChain; + const sql = yield* SqlClient.SqlClient; + for (const edit of [ + sql`UPDATE kin_audit SET event = 'grant_accepted' WHERE org_id = ${org} AND seq = 3`, + sql`DELETE FROM kin_audit WHERE org_id = ${org} AND seq = 3`, + ]) { + const failure = yield* Effect.flip(edit); + assert.include(String(failure.reason.cause), "kin_audit is append-only"); + } + assert.deepStrictEqual(yield* audit.verify({ orgId: org }), { + ok: true, + checked: 5, + firstBadSeq: null, + }); + }).pipe(Effect.provide(layer)), + ); + + it.effect("concurrent appends form one gapless chain per org", () => + Effect.gen(function* () { + const audit = yield* seed; + const appended = yield* Effect.all( + Array.from({ length: 40 }, (_, index) => + audit.append({ orgId: index % 2 === 0 ? org : otherOrg, event: "key_registered" }), + ), + { concurrency: "unbounded" }, + ); + for (const orgId of [org, otherOrg]) { + const seqs = appended + .filter((entry) => entry.orgId === orgId) + .map((entry) => entry.seq) + .toSorted((left, right) => left - right); + assert.deepStrictEqual( + seqs, + Array.from({ length: 20 }, (_, index) => index + 1), + ); + assert.deepStrictEqual(yield* audit.verify({ orgId }), { + ok: true, + checked: 20, + firstBadSeq: null, + }); + } + }).pipe(Effect.provide(layer)), + ); + + it.effect("lists entries a page at a time", () => + Effect.gen(function* () { + const audit = yield* seedChain; + const first = yield* listIntact(audit, { orgId: org, limit: 2 }); + assert.deepStrictEqual( + first.entries.map((entry) => entry.seq), + [1, 2], + ); + assert.isTrue(first.hasMore); + const last = yield* listIntact(audit, { orgId: org, afterSeq: 4, limit: 2 }); + assert.deepStrictEqual( + last.entries.map((entry) => entry.event), + ["credential_check_failed"], + ); + assert.isFalse(last.hasMore); + const all = (yield* listIntact(audit, { orgId: org, limit: 200 })).entries; + assert.strictEqual(last.entries[0]!.prevHash, all[3]!.hash); + assert.deepStrictEqual( + (yield* listIntact(audit, { orgId: otherOrg, limit: 10 })).entries, + [], + ); + }).pipe(Effect.provide(layer)), + ); + + it.effect("a corrupt row lists as a marker instead of failing the page", () => + Effect.gen(function* () { + const audit = yield* seedChain; + const sql = yield* SqlClient.SqlClient; + yield* allowTampering(sql); + yield* sql`UPDATE kin_audit SET entry_json = '{not json' WHERE org_id = ${org} AND seq = 3`; + const { entries } = yield* audit.list({ orgId: org, limit: 10 }); + assert.deepStrictEqual( + entries.map((entry) => ("corrupt" in entry ? `corrupt:${entry.seq}` : entry.event)), + ["key_registered", "key_confirmed", "corrupt:3", "key_revoked", "credential_check_failed"], + ); + }).pipe(Effect.provide(layer)), + ); +}); + +describe("KinPendingActions audit trail", () => { + it.effect("a merge leaves a complete trail: request, grant, device, SHA and merge commit", () => + Effect.gen(function* () { + const audit = yield* seed; + const actions = yield* KinPendingActions; + const { action } = yield* actions.create(request); + yield* actions.create(request); // replayed webhook: no second entry + const refreshed = Option.getOrThrow( + yield* actions.refresh({ + orgId: org, + actionId: action.id, + revision: 0, + resolved: { ...request.resolved, headSha: "b".repeat(40) } as typeof request.resolved, + targetDigest: "2".repeat(64), + }), + ); + assert.deepStrictEqual(yield* actions.approve(grant(action, "jti-old")), { _tag: "stale" }); + const approved = yield* actions.approve(grant(refreshed, "jti-1")); + assert.strictEqual(approved._tag, "approved"); + if (approved._tag !== "approved") return; + assert.isTrue( + yield* actions.claim({ + orgId: org, + actionId: action.id, + revision: 1, + grantId: approved.grant.id, + }), + ); + assert.isTrue( + yield* actions.finish({ + orgId: org, + actionId: action.id, + outcome: "succeeded", + mergeCommitSha: mergeSha, + }), + ); + + const { entries } = yield* listIntact(audit, { orgId: org, limit: 50 }); + assert.deepStrictEqual( + entries.map((entry) => entry.event), + [ + "action_requested", + "action_refreshed", + "grant_rejected", + "grant_accepted", + "execution_started", + "execution_finished", + ] satisfies ReadonlyArray, + ); + const [requested, refreshedEntry, rejected, accepted, started, finished] = entries; + assert.deepStrictEqual(requested!.target, request.target); + assert.deepStrictEqual(requested!.provenance, request.provenance); + assert.strictEqual(requested!.headSha, headSha); + assert.strictEqual(refreshedEntry!.headSha, "b".repeat(40)); + assert.include(rejected!, { grantJti: "jti-old", result: "stale", sessionId }); + assert.include(accepted!, { + actionId: action.id, + kind: "merge_pull_request", + headSha: "b".repeat(40), + grantJti: "jti-1", + keyThumbprint: kid, + sessionId, + deviceLabel: "Owner's iPhone", + }); + assert.include(started!, { grantJti: "jti-1", headSha: "b".repeat(40) }); + assert.strictEqual(finished!.result, mergeSha); + // The audit holds the jti and thumbprint, never the signed token. + assert.notInclude(JSON.stringify(entries), "compact-jti"); + assert.deepStrictEqual(yield* audit.verify({ orgId: org }), { + ok: true, + checked: 6, + firstBadSeq: null, + }); + }).pipe(Effect.provide(layer)), + ); + + it.effect("terminal moves, the sweep and reconciliation each leave their own entry", () => + Effect.gen(function* () { + const audit = yield* seed; + const actions = yield* KinPendingActions; + const create = (source: string) => + actions + .create({ ...request, source: decodeEventId(source) }) + .pipe(Effect.map(({ action }) => action)); + const rejected = yield* create("a"); + const cancelled = yield* create("b"); + const reconciled = yield* create("c"); + const waiting = yield* create("d"); + const lapsing = yield* create("e"); + const ref = (action: KinPendingAction) => ({ + orgId: org, + actionId: action.id, + revision: 0, + }); + assert.isTrue(yield* actions.transition({ ...ref(rejected), to: "rejected", sessionId })); + assert.isTrue(yield* actions.transition({ ...ref(cancelled), to: "cancelled" })); + assert.isFalse(yield* actions.transition({ ...ref(cancelled), to: "rejected" })); + const approved = yield* actions.approve(grant(reconciled, "jti-r")); + if (approved._tag !== "approved") return assert.fail("not approved"); + yield* actions.claim({ ...ref(reconciled), grantId: approved.grant.id }); + yield* actions.finish({ + orgId: org, + actionId: reconciled.id, + outcome: "interrupted", + error: "still open after restart", + reconciled: true, + }); + + assert.strictEqual((yield* actions.approve(grant(lapsing, "jti-l")))._tag, "approved"); + yield* TestClock.adjust("8 days"); + const swept = yield* actions.sweep(); + assert.strictEqual(swept.expired.length + swept.voided.length, 2); + + const { entries } = yield* listIntact(audit, { orgId: org, limit: 50 }); + const byAction = (action: KinPendingAction) => + entries.filter((entry) => entry.actionId === action.id).map((entry) => entry.event); + assert.deepStrictEqual(byAction(rejected), ["action_requested", "action_rejected"]); + assert.deepStrictEqual(byAction(cancelled), ["action_requested", "action_cancelled"]); + assert.deepStrictEqual(byAction(reconciled), [ + "action_requested", + "grant_accepted", + "execution_started", + "execution_reconciled", + ]); + assert.deepStrictEqual(byAction(waiting), ["action_requested", "action_expired"]); + assert.deepStrictEqual(byAction(lapsing), [ + "action_requested", + "grant_accepted", + "action_voided", + ]); + assert.strictEqual( + entries.find((entry) => entry.event === "execution_reconciled")!.result, + "interrupted: still open after restart", + ); + assert.strictEqual( + entries.find((entry) => entry.event === "action_voided")!.result, + "grant_expired", + ); + assert.strictEqual( + entries.find((entry) => entry.event === "action_rejected")!.sessionId, + sessionId, + ); + }).pipe(Effect.provide(layer)), + ); + + it.effect("a grant for an unknown org or action stays stale and writes no entry", () => + Effect.gen(function* () { + const audit = yield* seed; + const actions = yield* KinPendingActions; + const { action } = yield* actions.create(request); + for (const forged of [ + { ...grant(action, "jti-org"), orgId: unknownOrg }, + { ...grant(action, "jti-cross"), orgId: otherOrg }, + { ...grant(action, "jti-missing"), actionId: missingAction }, + ]) { + assert.deepStrictEqual(yield* actions.approve(forged), { _tag: "stale" }); + } + for (const orgId of [org, otherOrg, unknownOrg]) { + const { entries } = yield* listIntact(audit, { orgId, limit: 10 }); + assert.deepStrictEqual( + entries.filter((entry) => entry.event === "grant_rejected"), + [], + ); + } + }).pipe(Effect.provide(layer)), + ); + + it.effect("a transition rolls back when its audit entry can't be written", () => + Effect.gen(function* () { + yield* seed; + const actions = yield* KinPendingActions; + const sql = yield* SqlClient.SqlClient; + const { action } = yield* actions.create(request); + yield* sql`CREATE TRIGGER kin_audit_refuse BEFORE INSERT ON kin_audit + BEGIN SELECT RAISE(ABORT, 'audit refused'); END`; + const failure = yield* actions + .transition({ orgId: org, actionId: action.id, revision: 0, to: "rejected" }) + .pipe(Effect.flip); + assert.strictEqual(failure._tag, "PersistenceSqlError"); + assert.strictEqual( + Option.getOrThrow(yield* actions.get({ orgId: org, actionId: action.id })).state, + "awaiting_approval", + ); + // A refused grant stays refused when only its trace can't be written. + assert.deepStrictEqual( + yield* actions.approve(grant({ ...action, revision: 7 }, "jti-unwritten")), + { _tag: "stale" }, + ); + }).pipe(Effect.provide(layer)), + ); +}); + +describe("kin.audit RPCs", () => { + it.effect("only the org owner can list or verify the audit", () => + Effect.gen(function* () { + const kin = yield* Kin.KinServer.pipe( + Effect.provide( + Kin.layer.pipe( + Layer.provide(ConfigProvider.layer(ConfigProvider.fromUnknown({ KIN_ENABLED: true }))), + ), + ), + ); + if (Option.isNone(kin.services)) return assert.fail("Kin services missing"); + const services = kin.services.value; + const handlersFor = (scopes: AuthenticatedSession["scopes"], kinServices = kin.services) => + makeKinApprovalHandlers( + { sessionId, subject: "browser", method: "browser-session-cookie", scopes }, + kinServices, + ); + const ownerHandlers = yield* handlersFor(AuthStandardClientScopes); + assert.deepStrictEqual(yield* ownerHandlers["kin.audit.verify"]({ orgId: defaultOrg }), { + ok: true, + checked: 0, + firstBadSeq: null, + }); + assert.include( + yield* ownerHandlers["kin.audit.list"]({ orgId: otherOrg, limit: 10 }).pipe(Effect.flip), + { reason: "not_owner" }, + ); + const anonymousHandlers = yield* handlersFor([]); + assert.include( + yield* anonymousHandlers["kin.audit.verify"]({ orgId: defaultOrg }).pipe(Effect.flip), + { reason: "not_owner" }, + ); + + // A real non-owner person in the owner's org: membership alone must not open the audit. + const sql = yield* SqlClient.SqlClient; + yield* sql`INSERT INTO kin_people (person_id, org_id, handle, display_name, github_login, created_at) + VALUES (${member}, ${defaultOrg}, 'member', 'Member', NULL, '2026-11-08T00:00:00.000Z')`; + const identity = Context.get(services, KinIdentity); + const asMember = Option.some( + Context.add(services, KinIdentity, { + ...identity, + resolve: () => + Effect.succeed([{ _tag: "person" as const, orgId: defaultOrg, personId: member }]), + }), + ); + const memberHandlers = yield* handlersFor(AuthStandardClientScopes, asMember); + assert.include( + yield* memberHandlers["kin.audit.verify"]({ orgId: defaultOrg }).pipe(Effect.flip), + { reason: "not_owner" }, + ); + assert.include( + yield* memberHandlers["kin.audit.list"]({ orgId: defaultOrg, limit: 10 }).pipe(Effect.flip), + { reason: "not_owner" }, + ); + + const kinOff = yield* handlersFor(AuthStandardClientScopes, Option.none()); + assert.include(yield* kinOff["kin.audit.verify"]({ orgId: defaultOrg }).pipe(Effect.flip), { + reason: "disabled", + }); + yield* sql`ALTER TABLE kin_audit RENAME TO kin_audit_gone`; + assert.include( + yield* ownerHandlers["kin.audit.list"]({ orgId: defaultOrg, limit: 10 }).pipe(Effect.flip), + { reason: "unavailable" }, + ); + }).pipe(Effect.provide(Sqlite.layerMemory)), + ); +}); diff --git a/apps/server/src/kin/approvals/Audit.ts b/apps/server/src/kin/approvals/Audit.ts new file mode 100644 index 0000000000000..4a095ed4d489a --- /dev/null +++ b/apps/server/src/kin/approvals/Audit.ts @@ -0,0 +1,198 @@ +// @effect-diagnostics nodeBuiltinImport:off -- a synchronous SHA-256 for the hash chain. +import * as NodeCrypto from "node:crypto"; + +import { + KinAuditEntry, + type KinAuditListInput, + type KinAuditListResult, + type KinAuditVerifyResult, + type KinOrgId, +} from "@t3tools/contracts"; +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 SqlClient from "effect/sql/SqlClient"; + +import { + PersistenceDecodeError, + type PersistenceSqlError, + toPersistenceSqlError, +} from "../../persistence/Errors.ts"; + +/** `prevHash` of each org's first entry. */ +const KIN_AUDIT_GENESIS_HASH = "0".repeat(64); +const VERIFY_PAGE = 500; + +export type KinAuditAppendInput = Omit; +type Errors = PersistenceSqlError | PersistenceDecodeError; + +const { hash: _hash, ...unhashedFields } = KinAuditEntry.fields; +const encodeUnhashed = Schema.encodeEffect(Schema.Struct(unhashedFields)); +const decodeEntry = Schema.decodeUnknownEffect(KinAuditEntry); +const decodeEntryOption = Schema.decodeUnknownOption(KinAuditEntry); + +/** Spec section 11: sha256(prevHash ‖ stableStringify(entry without hash)). */ +export const kinAuditHash = (unhashed: { readonly prevHash: string }): string => + NodeCrypto.createHash("sha256") + .update(unhashed.prevHash + stableStringify(unhashed)) + .digest("hex"); + +type AuditRow = { + readonly id: string; + readonly org_id: string; + readonly seq: number; + readonly at: number; + readonly event: string; + readonly entry_json: string; + readonly prev_hash: string; + readonly hash: string; +}; + +const parseJson = (text: string): unknown => { + try { + return JSON.parse(text); + } catch { + return undefined; + } +}; + +// One row against its predecessor: canonical bytes, columns, position and both hashes. +const rowIsIntact = (row: AuditRow, expectedSeq: number, prevHash: string): boolean => { + const parsed = parseJson(row.entry_json); + if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return false; + if (stableStringify(parsed) !== row.entry_json) return false; + const decoded = decodeEntryOption(parsed); + if (Option.isNone(decoded)) return false; + const entry = decoded.value; + const { hash, ...unhashed } = parsed as typeof KinAuditEntry.Encoded; + return ( + row.seq === expectedSeq && + entry.seq === row.seq && + entry.id === row.id && + entry.orgId === row.org_id && + entry.event === row.event && + entry.at.epochMilliseconds === row.at && + entry.prevHash === prevHash && + row.prev_hash === prevHash && + hash === row.hash && + kinAuditHash(unhashed) === row.hash + ); +}; + +export class KinAudit extends Context.Service< + KinAudit, + { + /** + * Appends one entry to the org's chain. Joins the caller's transaction when there is one, + * so a transition and its entry commit or roll back together. Server code only: no RPC or + * MCP tool reaches it. + */ + readonly append: (input: KinAuditAppendInput) => Effect.Effect; + readonly list: (input: KinAuditListInput) => Effect.Effect; + /** Recomputes the chain from seq 1 and reports the first entry that doesn't hold. */ + readonly verify: (input: { + readonly orgId: KinOrgId; + }) => Effect.Effect; + } +>()("t3/kin/approvals/Audit/KinAudit") {} + +export const make = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + const append = Effect.fn("KinAudit.append")( + function* (input: KinAuditAppendInput) { + // The writer runs BEGIN IMMEDIATE behind one permit, so reading the head and inserting + // the next seq can't interleave with another append; UNIQUE(org_id, seq) backs that up. + return yield* sql.withTransaction( + Effect.gen(function* () { + const now = yield* Clock.currentTimeMillis; + const [head] = yield* sql<{ seq: number; hash: string }>` + SELECT seq, hash FROM kin_audit WHERE org_id = ${input.orgId} + ORDER BY seq DESC LIMIT 1`; + const prevHash = head?.hash ?? KIN_AUDIT_GENESIS_HASH; + const unhashed = yield* encodeUnhashed({ + ...input, + id: `aud_${SecureRandom.ulidUnsafe()}`, + seq: (head?.seq ?? 0) + 1, + at: DateTime.makeUnsafe(now), + prevHash, + }); + const hash = kinAuditHash(unhashed); + const encoded = { ...unhashed, hash }; + yield* sql`INSERT INTO kin_audit ${sql.insert({ + id: encoded.id, + org_id: encoded.orgId, + seq: encoded.seq, + at: now, + event: encoded.event, + entry_json: stableStringify(encoded), + prev_hash: prevHash, + hash, + })}`; + return yield* decodeEntry(encoded); + }), + ); + }, + Effect.mapError(toError("KinAudit.append")), + ); + + const list = Effect.fn("KinAudit.list")( + function* (input: KinAuditListInput) { + const rows = yield* sql<{ seq: number; entry_json: string }>` + SELECT seq, entry_json FROM kin_audit + WHERE org_id = ${input.orgId} AND seq > ${input.afterSeq ?? 0} + ORDER BY seq LIMIT ${input.limit + 1}`; + // One bad row becomes a marker instead of failing every page that includes it. + const entries = rows.slice(0, input.limit).map((row) => + Option.getOrElse(decodeEntryOption(parseJson(row.entry_json)), () => ({ + seq: row.seq, + corrupt: true as const, + })), + ); + return { entries, hasMore: rows.length > input.limit }; + }, + Effect.mapError(toError("KinAudit.list")), + ); + + const verify = Effect.fn("KinAudit.verify")( + function* (input: { readonly orgId: KinOrgId }) { + let checked = 0; + let prevHash = KIN_AUDIT_GENESIS_HASH; + while (true) { + // Every verified row has seq === checked, so this resumes right after the last one. + const rows = yield* sql`SELECT * FROM kin_audit + WHERE org_id = ${input.orgId} AND seq > ${checked} + ORDER BY seq LIMIT ${VERIFY_PAGE}`; + if (rows.length === 0) return { ok: true, checked, firstBadSeq: null }; + for (const row of rows) { + if (!rowIsIntact(row, checked + 1, prevHash)) { + return { ok: false, checked, firstBadSeq: checked + 1 }; + } + checked += 1; + prevHash = row.hash; + } + } + }, + Effect.mapError(toError("KinAudit.verify")), + ); + + return KinAudit.of({ append, list, verify }); +}); + +const isDecodeError = Schema.is(PersistenceDecodeError); +function toError(operation: string) { + return (cause: unknown): Errors => + isDecodeError(cause) + ? cause + : Schema.isSchemaError(cause) + ? PersistenceDecodeError.fromSchemaError(operation, cause) + : toPersistenceSqlError(operation)(cause); +} + +export const layer = Layer.effect(KinAudit, make); diff --git a/apps/server/src/kin/approvals/PendingActions.test.ts b/apps/server/src/kin/approvals/PendingActions.test.ts index e38619b39dc17..8c3fd74f778d7 100644 --- a/apps/server/src/kin/approvals/PendingActions.test.ts +++ b/apps/server/src/kin/approvals/PendingActions.test.ts @@ -22,9 +22,13 @@ import { layer as pendingActionsLayer, type KinPendingActionCreateInput, } from "./PendingActions.ts"; +import * as Audit from "./Audit.ts"; const database = Layer.provideMerge(KinPersistence.layer, Sqlite.layerMemory); -const layer = pendingActionsLayer.pipe(Layer.provideMerge(database)); +const layer = pendingActionsLayer.pipe( + Layer.provideMerge(Audit.layer), + Layer.provideMerge(database), +); const decodeEventId = Schema.decodeSync(KinEventId); const owner = Schema.decodeSync(KinPersonId)("h_owner"); diff --git a/apps/server/src/kin/approvals/PendingActions.ts b/apps/server/src/kin/approvals/PendingActions.ts index 56832538d5688..db1aaff750892 100644 --- a/apps/server/src/kin/approvals/PendingActions.ts +++ b/apps/server/src/kin/approvals/PendingActions.ts @@ -14,6 +14,7 @@ import { KinProvenance, KinResolvedTarget, ThreadId, + type AuthSessionId, type Hex64, type KinKeyThumbprint, } from "@t3tools/contracts"; @@ -34,6 +35,7 @@ import { type PersistenceSqlError, toPersistenceSqlError, } from "../../persistence/Errors.ts"; +import { KinAudit } from "./Audit.ts"; const AWAITING_TTL_MS = 7 * 24 * 60 * 60 * 1000; // A grant lapses at min(exp, acceptedAt + 15 min) (approvals spec section 5). @@ -142,6 +144,24 @@ const toAction = (row: ActionRow) => expiresAt: iso(row.expires_at), }); +type FactsRow = { action_id: string; kind: string; resolved_json: string }; +const decodeFacts = Schema.decodeUnknownEffect( + Schema.Struct({ + actionId: KinActionId, + kind: KinActionKind, + resolved: StoredAction.fields.resolved, + }), +); +// What every audit entry about an action carries, read from the row the statement touched. +const auditFacts = (row: FactsRow) => + decodeFacts({ actionId: row.action_id, kind: row.kind, resolved: row.resolved_json }).pipe( + Effect.map(({ actionId, kind, resolved }) => ({ + actionId, + kind, + ...(resolved._tag === "none" ? {} : { headSha: resolved.headSha }), + })), + ); + class Rollback extends Schema.TaggedError()("Rollback", {}) {} export class KinPendingActions extends Context.Service< @@ -164,6 +184,7 @@ export class KinPendingActions extends Context.Service< input: RevisionRef & { readonly to: "rejected" | "cancelled" | "expired" | "voided"; readonly reason?: string; + readonly sessionId?: AuthSessionId; }, ) => Effect.Effect; /** Check 10: the grant row and `awaiting_approval → approved` in one transaction. */ @@ -176,6 +197,8 @@ export class KinPendingActions extends Context.Service< readonly compact: string; readonly iat: number; readonly exp: number; + readonly sessionId?: AuthSessionId; + readonly deviceLabel?: string; }, ) => Effect.Effect; /** The executor's single claim: the `kin_executions` insert plus `approved → executing`. */ @@ -188,6 +211,8 @@ export class KinPendingActions extends Context.Service< readonly githubRequestId?: string; readonly mergeCommitSha?: string; readonly error?: string; + /** Startup reconciliation decided the outcome, not a live run. */ + readonly reconciled?: boolean; }, ) => Effect.Effect; /** Expires unapproved actions past `expiresAt` and voids approvals whose grant lapsed. */ @@ -200,6 +225,7 @@ export class KinPendingActions extends Context.Service< const make = Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; + const audit = yield* KinAudit; const select = (ref: ActionRef) => sql`SELECT * FROM kin_pending_actions @@ -242,11 +268,24 @@ const make = Effect.gen(function* () { }; // Decoding the full record validates it before it reaches the table. const action = yield* toAction(row); - const inserted = yield* sql` - INSERT INTO kin_pending_actions ${sql.insert(row)} - ON CONFLICT (org_id, idempotency_key) DO NOTHING - RETURNING action_id`; - if (inserted.length > 0) return { action, created: true }; + const created = yield* sql.withTransaction( + Effect.gen(function* () { + const inserted = yield* sql` + INSERT INTO kin_pending_actions ${sql.insert(row)} + ON CONFLICT (org_id, idempotency_key) DO NOTHING + RETURNING action_id`; + if (inserted.length === 0) return false; + yield* audit.append({ + orgId: action.orgId, + event: "action_requested", + ...(yield* auditFacts(row)), + target: action.target, + provenance: action.provenance, + }); + return true; + }), + ); + if (created) return { action, created: true }; const [existing] = yield* sql`SELECT * FROM kin_pending_actions WHERE org_id = ${input.orgId} AND idempotency_key = ${idempotencyKey}`; if (existing === undefined) { @@ -265,14 +304,25 @@ const make = Effect.gen(function* () { input: RevisionRef & { readonly resolved: KinResolvedTarget; readonly targetDigest: Hex64 }, ) { const now = yield* Clock.currentTimeMillis; - const [row] = yield* sql`UPDATE kin_pending_actions - SET resolved_json = ${yield* encodeResolved(input.resolved)}, target_digest = ${input.targetDigest}, - nonce = ${newNonce()}, revision = revision + 1, updated_at = ${now} - WHERE org_id = ${input.orgId} AND action_id = ${input.actionId} - AND state = 'awaiting_approval' AND revision = ${input.revision} - AND expires_at > ${now} - RETURNING *`; - return row === undefined ? Option.none() : Option.some(yield* toAction(row)); + const resolvedJson = yield* encodeResolved(input.resolved); + return yield* sql.withTransaction( + Effect.gen(function* () { + const [row] = yield* sql`UPDATE kin_pending_actions + SET resolved_json = ${resolvedJson}, target_digest = ${input.targetDigest}, + nonce = ${newNonce()}, revision = revision + 1, updated_at = ${now} + WHERE org_id = ${input.orgId} AND action_id = ${input.actionId} + AND state = 'awaiting_approval' AND revision = ${input.revision} + AND expires_at > ${now} + RETURNING *`; + if (row === undefined) return Option.none(); + yield* audit.append({ + orgId: input.orgId, + event: "action_refreshed", + ...(yield* auditFacts(row)), + }); + return Option.some(yield* toAction(row)); + }), + ); }, Effect.mapError(toError("KinPendingActions.refresh")), ); @@ -282,17 +332,30 @@ const make = Effect.gen(function* () { input: RevisionRef & { readonly to: "rejected" | "cancelled" | "expired" | "voided"; readonly reason?: string; + readonly sessionId?: AuthSessionId; }, ) { const from = input.to === "voided" ? "approved" : "awaiting_approval"; const now = yield* Clock.currentTimeMillis; - const rows = yield* sql`UPDATE kin_pending_actions - SET state = ${input.to}, state_reason = ${input.reason ?? null}, updated_at = ${now} - WHERE org_id = ${input.orgId} AND action_id = ${input.actionId} - AND state = ${from} AND revision = ${input.revision} - AND (${input.to} != 'expired' OR expires_at <= ${now}) - RETURNING action_id`; - return rows.length > 0; + return yield* sql.withTransaction( + Effect.gen(function* () { + const [row] = yield* sql`UPDATE kin_pending_actions + SET state = ${input.to}, state_reason = ${input.reason ?? null}, updated_at = ${now} + WHERE org_id = ${input.orgId} AND action_id = ${input.actionId} + AND state = ${from} AND revision = ${input.revision} + AND (${input.to} != 'expired' OR expires_at <= ${now}) + RETURNING action_id, kind, resolved_json`; + if (row === undefined) return false; + yield* audit.append({ + orgId: input.orgId, + event: `action_${input.to}`, + ...(yield* auditFacts(row)), + ...(input.sessionId === undefined ? {} : { sessionId: input.sessionId }), + ...(input.reason === undefined ? {} : { result: input.reason }), + }); + return true; + }), + ); }, Effect.mapError(toError("KinPendingActions.transition")), ); @@ -307,11 +370,19 @@ const make = Effect.gen(function* () { readonly compact: string; readonly iat: number; readonly exp: number; + readonly sessionId?: AuthSessionId; + readonly deviceLabel?: string; }, ) { const now = yield* Clock.currentTimeMillis; const grantId = `grt_${SecureRandom.ulidUnsafe()}`; - return yield* sql + const who = { + grantJti: input.jti, + keyThumbprint: input.keyThumbprint, + ...(input.sessionId === undefined ? {} : { sessionId: input.sessionId }), + ...(input.deviceLabel === undefined ? {} : { deviceLabel: input.deviceLabel }), + }; + const result = yield* sql .withTransaction( Effect.gen(function* () { const [inserted] = yield* sql` @@ -331,13 +402,19 @@ const make = Effect.gen(function* () { ? { _tag: "stale" as const } : { _tag: "replayed" as const }; } - const won = yield* sql`UPDATE kin_pending_actions + const [won] = yield* sql`UPDATE kin_pending_actions SET state = 'approved', updated_at = ${now} WHERE org_id = ${input.orgId} AND action_id = ${input.actionId} AND state = 'awaiting_approval' AND revision = ${input.revision} AND nonce = ${input.nonce} AND expires_at > ${now} AND ${input.exp} * 1000 > ${now} - RETURNING action_id`; - if (won.length === 0) return yield* new Rollback(); + RETURNING action_id, kind, resolved_json`; + if (won === undefined) return yield* new Rollback(); + yield* audit.append({ + orgId: input.orgId, + event: "grant_accepted", + ...(yield* auditFacts(won)), + ...who, + }); const grant = yield* decodeGrant({ id: grantId, orgId: input.orgId, @@ -356,6 +433,32 @@ const make = Effect.gen(function* () { }), ) .pipe(Effect.catchTags({ Rollback: () => Effect.succeed({ _tag: "stale" as const }) })); + // A refused grant still leaves a trace (spec section 11), but only on the chain of the org + // that owns the action: an unknown org or action stays `stale` and writes nothing. + if (result._tag !== "approved") { + yield* sql + .withTransaction( + Effect.gen(function* () { + const [owned] = yield* sql`SELECT 1 FROM kin_pending_actions + WHERE org_id = ${input.orgId} AND action_id = ${input.actionId}`; + if (owned === undefined) return; + yield* audit.append({ + orgId: input.orgId, + event: "grant_rejected", + actionId: input.actionId, + ...who, + result: result._tag, + }); + }), + ) + .pipe( + // The refusal is already decided; a lost trace must not turn it into an error. + Effect.catch((error) => + Effect.logWarning("Kin audit: grant_rejected not written", error), + ), + ); + } + return result; }, Effect.mapError(toError("KinPendingActions.approve")), ); @@ -376,13 +479,23 @@ const make = Effect.gen(function* () { ON CONFLICT DO NOTHING RETURNING action_id`; if (claimed.length === 0) return false; - const won = yield* sql`UPDATE kin_pending_actions + const [won] = yield* sql`UPDATE kin_pending_actions SET state = 'executing', updated_at = ${now} WHERE org_id = ${input.orgId} AND action_id = ${input.actionId} AND state = 'approved' AND revision = ${input.revision} - RETURNING action_id`; - if (won.length === 0) return yield* new Rollback(); - yield* sql`UPDATE kin_grants SET consumed_at = ${now} WHERE grant_id = ${input.grantId}`; + RETURNING action_id, kind, resolved_json`; + if (won === undefined) return yield* new Rollback(); + const [grant] = yield* sql<{ jti: string; key_thumbprint: KinKeyThumbprint }>` + UPDATE kin_grants SET consumed_at = ${now} WHERE grant_id = ${input.grantId} + RETURNING jti, key_thumbprint`; + if (grant === undefined) return yield* new Rollback(); + yield* audit.append({ + orgId: input.orgId, + event: "execution_started", + ...(yield* auditFacts(won)), + grantJti: grant.jti, + keyThumbprint: grant.key_thumbprint, + }); return true; }), ) @@ -398,17 +511,18 @@ const make = Effect.gen(function* () { readonly githubRequestId?: string; readonly mergeCommitSha?: string; readonly error?: string; + readonly reconciled?: boolean; }, ) { const now = yield* Clock.currentTimeMillis; return yield* sql .withTransaction( Effect.gen(function* () { - const won = yield* sql`UPDATE kin_pending_actions + const [won] = yield* sql`UPDATE kin_pending_actions SET state = ${input.outcome}, state_reason = ${input.error ?? null}, updated_at = ${now} WHERE org_id = ${input.orgId} AND action_id = ${input.actionId} AND state = 'executing' - RETURNING action_id`; - if (won.length === 0) return false; + RETURNING action_id, kind, resolved_json`; + if (won === undefined) return false; const recorded = yield* sql`UPDATE kin_executions SET finished_at = ${now}, outcome = ${input.outcome}, github_request_id = ${input.githubRequestId ?? null}, @@ -416,6 +530,15 @@ const make = Effect.gen(function* () { WHERE org_id = ${input.orgId} AND action_id = ${input.actionId} AND finished_at IS NULL RETURNING action_id`; if (recorded.length === 0) return yield* new Rollback(); + yield* audit.append({ + orgId: input.orgId, + event: input.reconciled === true ? "execution_reconciled" : "execution_finished", + ...(yield* auditFacts(won)), + result: + input.outcome === "succeeded" + ? (input.mergeCommitSha ?? "succeeded") + : `${input.outcome}: ${input.error ?? "no reason given"}`, + }); return true; }), ) @@ -429,12 +552,13 @@ const make = Effect.gen(function* () { const now = yield* Clock.currentTimeMillis; return yield* sql.withTransaction( Effect.gen(function* () { - const expired = yield* sql<{ org_id: KinOrgId; action_id: KinActionId }>` + type SweptRow = FactsRow & { org_id: KinOrgId; action_id: KinActionId }; + const expired = yield* sql` UPDATE kin_pending_actions SET state = 'expired', state_reason = 'expired', updated_at = ${now} WHERE state = 'awaiting_approval' AND expires_at <= ${now} - RETURNING org_id, action_id`; - const voided = yield* sql<{ org_id: KinOrgId; action_id: KinActionId }>` + RETURNING org_id, action_id, kind, resolved_json`; + const voided = yield* sql` UPDATE kin_pending_actions SET state = 'voided', state_reason = 'grant_expired', updated_at = ${now} WHERE state = 'approved' AND EXISTS ( @@ -442,8 +566,21 @@ const make = Effect.gen(function* () { WHERE g.action_id = kin_pending_actions.action_id AND g.revision = kin_pending_actions.revision AND g.consumed_at IS NULL AND MIN(g.exp_s * 1000, g.accepted_at + ${GRANT_ACCEPTED_TTL_MS}) <= ${now}) - RETURNING org_id, action_id`; - const refs = (rows: ReadonlyArray<{ org_id: KinOrgId; action_id: KinActionId }>) => + RETURNING org_id, action_id, kind, resolved_json`; + const record = (event: "action_expired" | "action_voided", result: string) => + Effect.forEach( + event === "action_expired" ? expired : voided, + (row) => + auditFacts(row).pipe( + Effect.flatMap((facts) => + audit.append({ orgId: row.org_id, event, ...facts, result }), + ), + ), + { discard: true }, + ); + yield* record("action_expired", "expired"); + yield* record("action_voided", "grant_expired"); + const refs = (rows: ReadonlyArray) => rows.map((row) => ({ orgId: row.org_id, actionId: row.action_id })); return { expired: refs(expired), voided: refs(voided) }; }), diff --git a/apps/server/src/kin/approvals/rpcHandlers.ts b/apps/server/src/kin/approvals/rpcHandlers.ts index 0b07100bddb46..3a9ba24e48a4f 100644 --- a/apps/server/src/kin/approvals/rpcHandlers.ts +++ b/apps/server/src/kin/approvals/rpcHandlers.ts @@ -1,30 +1,64 @@ -import { KinApprovalError, KinApprovalRpcs } from "@t3tools/contracts"; +import { KinApprovalError, KinApprovalRpcs, type KinOrgId } from "@t3tools/contracts"; +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 RpcGroup from "effect/rpc/RpcGroup"; import type { AuthenticatedSession } from "../../auth/EnvironmentAuth.ts"; +import { KinIdentity } from "../chat/KinIdentity.ts"; +import * as Audit from "./Audit.ts"; const group = RpcGroup.make(...KinApprovalRpcs); -// Every method refuses until its task lands (APPR-3, -4, -5, -10); nothing here can approve. +// Every method refuses until its task lands (APPR-3, -4, -5); nothing here can approve. const unavailable = Effect.fail( new KinApprovalError({ reason: "unavailable", message: "Kin approvals are unavailable." }), ); +const disabled = new KinApprovalError({ + reason: "disabled", + message: "Kin is not running on this host.", +}); +const failed = () => + new KinApprovalError({ reason: "unavailable", message: "Kin audit is unavailable." }); -export const makeKinApprovalHandlers = (_session: AuthenticatedSession) => - Effect.sync(() => - group.of({ - "kin.approvals.list": () => Stream.fromEffect(unavailable), - "kin.approvals.get": () => unavailable, - "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.audit.list": () => unavailable, - "kin.audit.verify": () => unavailable, - }), - ); +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>, +) { + const audit = yield* Audit.make; + // 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; + const identity = Context.get(kin.value, KinIdentity); + const people = yield* identity.resolve(session); + const { owner } = identity; + const isOwner = people.some( + (person) => person.orgId === owner.orgId && person.personId === owner.personId, + ); + if (owner.orgId !== orgId || !isOwner) { + return yield* new KinApprovalError({ reason: "not_owner", message: "Owner only." }); + } + return audit; + }); + return group.of({ + "kin.approvals.list": () => Stream.fromEffect(unavailable), + "kin.approvals.get": () => unavailable, + "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.audit.list": (input) => + asOwner(input.orgId).pipe( + Effect.flatMap((owner) => owner.list(input).pipe(Effect.mapError(failed))), + ), + "kin.audit.verify": (input) => + asOwner(input.orgId).pipe( + Effect.flatMap((owner) => owner.verify(input).pipe(Effect.mapError(failed))), + ), + }); +}); diff --git a/apps/server/src/kin/chat/KinIdentity.ts b/apps/server/src/kin/chat/KinIdentity.ts index 0ebd03cccca45..287dca14a70b4 100644 --- a/apps/server/src/kin/chat/KinIdentity.ts +++ b/apps/server/src/kin/chat/KinIdentity.ts @@ -65,6 +65,8 @@ type AgentThreadInput = { export class KinIdentity extends Context.Service< KinIdentity, { + /** The org owner bootstrapped at startup; the only person allowed owner-only actions. */ + readonly owner: PersonIdentity; readonly resolve: ( session: AuthenticatedSession, ) => Effect.Effect>; @@ -94,6 +96,7 @@ export class KinIdentity extends Context.Service< ); const lock = yield* Semaphore.make(1); return KinIdentity.of({ + owner: { _tag: "person", orgId: owner.orgId, personId: owner.personId }, resolve: Effect.fn("KinIdentity.resolve")(function (session) { return Effect.succeed( AuthStandardClientScopes.every((scope) => session.scopes.includes(scope)) diff --git a/apps/server/src/kin/chat/rpcHandlers.test.ts b/apps/server/src/kin/chat/rpcHandlers.test.ts index 4ddce515971bb..b495ef921b23b 100644 --- a/apps/server/src/kin/chat/rpcHandlers.test.ts +++ b/apps/server/src/kin/chat/rpcHandlers.test.ts @@ -619,7 +619,7 @@ it.effect("denies settings-only sessions before Kin handlers execute", () => (yield* client["kin.orgs.list"]({}).pipe(Effect.flip))._tag, "EnvironmentAuthorizationError", ); - }), + }).pipe(Effect.provide(Sqlite.layerMemory)), ); it.effect("drops a failed waiting read without ending the chat list stream", () => diff --git a/apps/server/src/kin/lead/WakeupRunner.test.ts b/apps/server/src/kin/lead/WakeupRunner.test.ts index c1fe6b1eda17c..b81282c9df2bd 100644 --- a/apps/server/src/kin/lead/WakeupRunner.test.ts +++ b/apps/server/src/kin/lead/WakeupRunner.test.ts @@ -12,9 +12,9 @@ import { EnvironmentId, MessageId, KinWakeupId, - KinPersonId, KinEvent, KinAgentId, + KinPersonId, ThreadId, RunId, RunAttemptId, @@ -1101,7 +1101,12 @@ describe("WakeupRunner", () => { return Effect.gen(function* () { yield* seed; const failing = KinLead.layer.pipe( - Layer.provide(Layer.mock(KinIdentity.KinIdentity)({ isAgentThread: () => false })), + Layer.provide( + Layer.mock(KinIdentity.KinIdentity)({ + owner: { _tag: "person", orgId, personId: KinPersonId.make("owner") }, + isAgentThread: () => false, + }), + ), Layer.provide( Layer.mergeAll( Layer.mock(ChatService.KinChatService)({}), diff --git a/apps/server/src/kin/rpcHandlers.ts b/apps/server/src/kin/rpcHandlers.ts index 021c3023c8712..a5d340b15ef77 100644 --- a/apps/server/src/kin/rpcHandlers.ts +++ b/apps/server/src/kin/rpcHandlers.ts @@ -1,9 +1,11 @@ import { KinRpcs } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; import * as RpcGroup from "effect/rpc/RpcGroup"; import type { AuthenticatedSession } from "../auth/EnvironmentAuth.ts"; import { makeKinApprovalHandlers } from "./approvals/rpcHandlers.ts"; import { makeKinChatHandlers } from "./chat/rpcHandlers.ts"; +import { KinServer } from "./KinServer.ts"; import { makeKinWebhookHandlers } from "./triggers/webhookRpcHandlers.ts"; const group = RpcGroup.make(...KinRpcs); @@ -11,9 +13,13 @@ const group = RpcGroup.make(...KinRpcs); export const makeKinHandlers = Effect.fn("makeKinHandlers")(function* ( session: AuthenticatedSession, ) { + const kin = yield* Effect.serviceOption(KinServer); return group.of({ ...(yield* makeKinChatHandlers(session)), - ...(yield* makeKinApprovalHandlers(session)), + ...(yield* makeKinApprovalHandlers( + session, + Option.flatMap(kin, (kin) => kin.services), + )), ...(yield* makeKinWebhookHandlers(session)), }); }); diff --git a/docs/kin/specs/approvals.md b/docs/kin/specs/approvals.md index dcb464d686fe5..1aaabb9033abd 100644 --- a/docs/kin/specs/approvals.md +++ b/docs/kin/specs/approvals.md @@ -423,6 +423,8 @@ export const KinAuditEntry = Schema.Struct({ "grant_accepted", "grant_rejected", "action_rejected", + "action_cancelled", + "action_expired", "action_voided", "execution_started", "execution_finished", @@ -447,7 +449,11 @@ export const KinAuditEntry = Schema.Struct({ }); ``` -Append-only (`kin_audit`, no `UPDATE` or `DELETE` statements in the repository code). The hash chain makes edits visible; `kin.audit.verify` recomputes it. Rejected grants are audited with their failure reason and the sending session, so a forged approval leaves a trace. `kin.audit.list` is owner-only. The audit stores the grant's `jti` and the key thumbprint, never tokens or keychain contents. +Append-only: `BEFORE UPDATE` and `BEFORE DELETE` triggers on `kin_audit` abort every edit, and the repository code has no such statements. The hash chain makes edits that bypass the triggers visible; `kin.audit.verify` recomputes it. Rejected grants are audited with their failure reason and the sending session, so a forged approval leaves a trace. `kin.audit.list` and `kin.audit.verify` are owner-only: the session must resolve to the org's owner, not just a person in the org. `list` returns a row that no longer decodes as `{ seq, corrupt: true }` instead of failing the page. The audit stores the grant's `jti` and the key thumbprint, never tokens or keychain contents. + +`apps/server/src/kin/approvals/Audit.ts` (`KinAudit`) is the only writer. `append` joins the caller's transaction, so `PendingActions.ts` writes each transition's entry atomically with the transition: `action_requested` on insert (not on an idempotent replay), `action_refreshed`, `grant_accepted`, the four terminal `action_*` moves (the sweep included), `execution_started` with the claim, and `execution_finished`, or `execution_reconciled` when startup reconciliation decides the outcome. `approve` also writes `grant_rejected` for `stale` and `replayed`, after its transaction ends: when no grant row was inserted the transaction commits empty, and only a lost compare-and-set on the action rolls the inserted grant back. The entry goes on the chain of the org that owns the action; a grant naming an unknown org or action stays `stale` and writes nothing. Rejections decided before `approve` (checks 1–9), key events and `credential_check_failed` are written by APPR-4, APPR-5 and APPR-8 through `KinAudit.append`. No RPC or MCP tool writes or deletes entries. + +Each org has its own chain. The first entry's `prevHash` is 64 zeros, and `seq` counts from 1 with no gaps. Appends are serialized by SQLite's single `BEGIN IMMEDIATE` writer, with `UNIQUE(org_id, seq)` as a backstop. `entry_json` holds `stableStringify` of the whole entry. `verify` walks the chain in `seq` order and reports the first entry whose bytes, columns, position, `prevHash` or `hash` don't hold, which catches an edited, deleted, reordered or inserted row. The chain has no secret and no outside anchor, so it can't show a truncated tail or a chain recomputed from the edit onward by someone with write access to the database. It catches tampering, not a compromised server. ### 12. Credential hygiene check diff --git a/packages/contracts/src/kinApprovals.ts b/packages/contracts/src/kinApprovals.ts index 22cf0a9f596c5..322a0335b3167 100644 --- a/packages/contracts/src/kinApprovals.ts +++ b/packages/contracts/src/kinApprovals.ts @@ -361,6 +361,8 @@ export const KinAuditEvent = Schema.Literals([ "grant_accepted", "grant_rejected", "action_rejected", + "action_cancelled", + "action_expired", "action_voided", "execution_started", "execution_finished", @@ -492,8 +494,14 @@ export const KinAuditListInput = Schema.Struct({ limit: PositiveInt.check(Schema.isLessThanOrEqualTo(200)), }); export type KinAuditListInput = typeof KinAuditListInput.Type; +/** A stored row that no longer decodes; `kin.audit.verify` reports where the chain breaks. */ +export const KinAuditCorruptEntry = Schema.Struct({ + seq: PositiveInt, + corrupt: Schema.Literal(true), +}); +export type KinAuditCorruptEntry = typeof KinAuditCorruptEntry.Type; export const KinAuditListResult = Schema.Struct({ - entries: Schema.Array(KinAuditEntry), + entries: Schema.Array(Schema.Union([KinAuditEntry, KinAuditCorruptEntry])), hasMore: Schema.Boolean, }); export type KinAuditListResult = typeof KinAuditListResult.Type;