diff --git a/CHANGELOG.md b/CHANGELOG.md index d2f780d2..b54c546b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,26 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/). ### Added +- **`kit audit verify --all` — the union view over every audit log this machine sealed.** + `kit audit verify` answers for one working tree, correctly: a git worktree IS a distinct + working tree, so it gets its own chain. On a machine running several — the normal case + under a worktree-per-session agent harness — that produced N green verdicts and no + whole-machine answer. The data was already on disk and unread: `~/.kit/audit-anchor.json` + keys the HMAC tip per log path and is shared by every tree (15 paths on the machine that + filed #470); the only reader outside `audit-anchor.ts` looked up one path. + + Four outcomes, because collapsing them is what makes such a report unreadable: `verified`; + `stalled` (the log is there but its seal no longer covers it — an unsealed tail, or a + rotated anchor key); `missing` (the log path is gone — a temp dir or deleted clone, which + is most of those 15 paths and never a finding); `failed` (chain break, truncation, tip + mismatch, or a seal that could not be checked at all). Exit 1 on any `failed`; a `stalled` + seal warns and fails under `--strict` / `[governance.audit].require_anchor` — deliberately + the same policy `decideAnchorVerdict` already applies to a single tree, since the same + evidence must not verify green in one command and red in the other. `--json` for machines. + + Exit codes stay `[0, 1]`: `public-surface.ts` declares that set for every stable command, + so the missing/stalled distinction is carried by the report, not by a third code. + - **`self-audit` now checks documentation in both directions.** The existing docs-claims rules prove no doc names something kit lacks; they are structurally incapable of catching the reverse, because an undocumented command has no doc reference to check. The new diff --git a/docs/COMMANDS.md b/docs/COMMANDS.md index f2cd7177..01415e10 100644 --- a/docs/COMMANDS.md +++ b/docs/COMMANDS.md @@ -290,6 +290,7 @@ fixture credentials at run time) so nothing new accumulates. | `kit audit` | Print recent `.kit-audit.jsonl` entries. | | `kit audit secrets [--key ] [--since-days ]` | Forensics: who/what touched each key + when. | | `kit audit verify [--strict]` | Verify the keyless hash chain + the external HMAC anchor (tip mismatch = keyless rewrite, count mismatch = truncation; exit 1 on break/forge). `--strict` / `[governance.audit].require_anchor` makes an unanchored log / unreadable key / unsealed tail a hard fail. | +| `kit audit verify --all [--json]` | **Union view** over every audit log this machine has sealed (`~/.kit/audit-anchor.json` keys the tip per log path, so it spans every working tree; plain `kit audit verify` answers for `cwd` only). Outcomes: `verified`; `stalled` (log present, entries past its seal or a rotated anchor key — re-seal there); `missing` (log path gone: temp dir / deleted clone, never a finding); `failed` (chain break, truncation, tip mismatch, or a seal that could not be checked). Exit 1 on any `failed`; `stalled` warns and fails under `--strict` / `[governance.audit].require_anchor`. | | `kit audit anchor` | Seal the log with the machine-local anchor key (`~/.kit/audit-anchor.key`, `0600`) so a keyless rewrite/truncation is detectable. Append path stays keyless; not tamper-proof against a same-UID key reader. | | `kit audit export [--format cef\|syslog\|json]` | Emit the audit log for a SIEM. | | `kit whoami [--json]` | Show current agent / user identity, active environment, and budget usage. | diff --git a/src/audit-anchor-all.test.ts b/src/audit-anchor-all.test.ts new file mode 100644 index 00000000..43da9ace --- /dev/null +++ b/src/audit-anchor-all.test.ts @@ -0,0 +1,406 @@ +/** + * The union view has to be right about the machine, not about a fixture. + * + * Trap 5 from the enforcement arc applies directly here: a correct classifier with no + * caller is not a working control, and #470 is *itself* an instance of that — the + * anchor record was correct, complete, 0600, and read by nothing. So the pure-function + * tests below are followed by end-to-end runs of the compiled CLI against a real + * `~/.kit`-shaped anchor dir holding real hash-chained logs in four states, asserting + * on the command's own stdout and exit code. + * + * The four states are the ones that matter for readability: a sealed tree that + * verifies, a tree with entries appended past its seal (`stalled`), a log path that no + * longer exists (`missing` — the common case on a dev machine, 12 of the 15 paths + * measured in #470), and a log whose sealed prefix was replaced by a differently-keyed + * valid chain (`failed`). If `missing` and `stalled` ever collapse into one outcome the + * report stops being readable, so that split is asserted explicitly. + */ + +import { describe, it, beforeEach, afterEach } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync, readFileSync, writeFileSync, realpathSync } from "node:fs"; +import { execFile } from "node:child_process"; +import { promisify } from "node:util"; +import { tmpdir } from "node:os"; +import { join, resolve, dirname } from "node:path"; +import { fileURLToPath } from "node:url"; + +import { appendAuditEventDirect } from "./audit.js"; +import { anchorAuditLog, getAuditAnchorKey, type AnchorRecord } from "./audit-anchor.js"; +import { + classifyAnchoredLog, + summarizeAnchoredLogs, + verifyAnchoredLogs, + readLogForUnion, + type AnchoredLogStatus, + type LogRead, +} from "./audit-anchor-all.js"; + +const exec = promisify(execFile); +const CLI_PATH = resolve(dirname(fileURLToPath(import.meta.url)), "cli.js"); +const LOG = ".kit-audit.jsonl"; + +const record = (over: Partial = {}): AnchorRecord => ({ + tip: "00".repeat(32), + count: 2, + algo: "hmac-sha256", + updatedAt: "2026-08-20T00:00:00.000Z", + version: 3, + ...over, +}); + +const gone: LogRead = { ok: false, gone: true }; +const unreadable: LogRead = { ok: false, gone: false }; + +/** Build a real hash-chained log in `cwd` without auto-anchoring (KIT_AUDIT_ANCHOR=0). */ +async function buildChain(cwd: string, n: number, tag = "op"): Promise { + for (let i = 0; i < n; i++) { + const ok = await appendAuditEventDirect( + { operation: `${tag}-${i}`, environment: "dev", success: true }, + { cwd }, + ); + assert.equal(ok, true); + } + return readFileSync(join(cwd, LOG), "utf-8"); +} + +describe("audit union view - classification", () => { + let dirs: string[] = []; + const mk = (): string => { + const d = realpathSync(mkdtempSync(join(tmpdir(), "kit-union-"))); + dirs.push(d); + return d; + }; + + beforeEach(() => { + dirs = []; + }); + afterEach(() => { + for (const d of dirs) rmSync(d, { recursive: true, force: true }); + }); + + it("a log path that is gone reads as missing, never as a finding", () => { + const s = classifyAnchoredLog("/tmp/kit-test-1234/.kit-audit.jsonl", record(), gone, null); + assert.equal(s.outcome, "missing"); + assert.equal(s.detail, "log-gone"); + assert.equal(s.sealed, 2); + assert.equal(s.sealedAt, "2026-08-20T00:00:00.000Z"); + // The message has to say why it is not an alarm, or the reader treats it as one. + assert.match(s.message, /temp dir|deleted clone/); + }); + + it("a log that exists but cannot be read fails closed, distinct from gone", () => { + const s = classifyAnchoredLog("/root/locked/.kit-audit.jsonl", record(), unreadable, null); + assert.equal(s.outcome, "failed"); + assert.equal(s.detail, "unreadable"); + assert.match(s.message, /could not be read/); + }); + + it("a sealed log with nothing past the seal verifies", async () => { + const anchorHome = mk(); + const tree = mk(); + const content = await buildChain(tree, 3); + const rec = await anchorAuditLog(join(tree, LOG), content, anchorHome); + const key = await getAuditAnchorKey(anchorHome); + + const s = classifyAnchoredLog(join(tree, LOG), rec, { ok: true, content }, key); + assert.equal(s.outcome, "verified"); + assert.equal(s.detail, "verified"); + assert.equal(s.entries, 3); + assert.equal(s.sealed, 3); + assert.equal(s.unsealed, 0); + }); + + it("entries appended past the seal read as stalled, with the tail counted", async () => { + const anchorHome = mk(); + const tree = mk(); + const sealed = await buildChain(tree, 2); + const rec = await anchorAuditLog(join(tree, LOG), sealed, anchorHome); + const key = await getAuditAnchorKey(anchorHome); + const grown = await buildChain(tree, 3, "later"); + + const s = classifyAnchoredLog(join(tree, LOG), rec, { ok: true, content: grown }, key); + assert.equal(s.outcome, "stalled"); + assert.equal(s.detail, "unsealed-tail"); + assert.equal(s.sealed, 2); + assert.equal(s.entries, 5); + assert.equal(s.unsealed, 3); + assert.match(s.message, /kit audit anchor/); + }); + + it("a broken hash chain fails as chain-broken, before any tip comparison", async () => { + const anchorHome = mk(); + const tree = mk(); + const content = await buildChain(tree, 3); + const rec = await anchorAuditLog(join(tree, LOG), content, anchorHome); + const key = await getAuditAnchorKey(anchorHome); + + const lines = content.trim().split("\n"); + const edited = JSON.parse(lines[1]) as Record; + edited.operation = "rewritten-in-place"; + lines[1] = JSON.stringify(edited); + + const s = classifyAnchoredLog( + join(tree, LOG), + rec, + { ok: true, content: lines.join("\n") }, + key, + ); + assert.equal(s.outcome, "failed"); + assert.equal(s.detail, "chain-broken"); + assert.equal(s.sealed, 3); + }); + + it("a shorter log than the seal covers fails as truncated", async () => { + const anchorHome = mk(); + const tree = mk(); + const content = await buildChain(tree, 4); + const rec = await anchorAuditLog(join(tree, LOG), content, anchorHome); + const key = await getAuditAnchorKey(anchorHome); + const rolledBack = content.trim().split("\n").slice(0, 2).join("\n") + "\n"; + + const s = classifyAnchoredLog(join(tree, LOG), rec, { ok: true, content: rolledBack }, key); + assert.equal(s.outcome, "failed"); + assert.equal(s.detail, "truncated"); + }); + + it("a valid chain that is not the sealed one fails as tip-mismatch", async () => { + const anchorHome = mk(); + const treeA = mk(); + const treeB = mk(); + const sealedContent = await buildChain(treeA, 3, "real"); + const rec = await anchorAuditLog(join(treeA, LOG), sealedContent, anchorHome); + const key = await getAuditAnchorKey(anchorHome); + // A writer-only attacker re-chains a substitute history: chain verifies, tip cannot. + const forged = await buildChain(treeB, 3, "forged"); + + const s = classifyAnchoredLog(join(treeA, LOG), rec, { ok: true, content: forged }, key); + assert.equal(s.outcome, "failed"); + assert.equal(s.detail, "tip-mismatch"); + }); + + it("an unreadable anchor key fails closed instead of reporting verified", async () => { + const anchorHome = mk(); + const tree = mk(); + const content = await buildChain(tree, 2); + const rec = await anchorAuditLog(join(tree, LOG), content, anchorHome); + + const s = classifyAnchoredLog(join(tree, LOG), rec, { ok: true, content }, null); + assert.equal(s.outcome, "failed"); + assert.equal(s.detail, "key-unavailable"); + }); + + it("a rotated anchor key reads as stalled (re-seal), not as tamper", async () => { + const anchorHome = mk(); + const tree = mk(); + const content = await buildChain(tree, 2); + const rec = await anchorAuditLog(join(tree, LOG), content, anchorHome); + const otherKey = Buffer.alloc(32, 9); + + const s = classifyAnchoredLog(join(tree, LOG), rec, { ok: true, content }, otherKey); + assert.equal(s.outcome, "stalled"); + assert.equal(s.detail, "anchor-key-changed"); + }); + + it("readLogForUnion splits gone from present", async () => { + const tree = mk(); + await buildChain(tree, 1); + const present = await readLogForUnion(join(tree, LOG)); + assert.equal(present.ok, true); + const absent = await readLogForUnion(join(tree, "no-such-log.jsonl")); + assert.equal(absent.ok, false); + assert.equal(absent.ok === false && absent.gone, true); + }); +}); + +describe("audit union view - verdict policy", () => { + const status = (over: Partial): AnchoredLogStatus => ({ + logPath: "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/x/.kit-audit.jsonl", + outcome: "verified", + detail: "verified", + message: "ok", + ...over, + }); + + it("missing paths never fail the verdict, at any count", () => { + const many = Array.from({ length: 12 }, (_, i) => + status({ logPath: `/tmp/t-${i}/.kit-audit.jsonl`, outcome: "missing", detail: "log-gone" }), + ); + for (const strict of [false, true]) { + const r = summarizeAnchoredLogs([...many, status({})], strict); + assert.equal(r.ok, true, `strict=${strict}`); + assert.equal(r.counts.missing, 12); + assert.equal(r.counts.verified, 1); + } + }); + + it("a stalled seal warns by default and fails under strict", () => { + const rows = [status({}), status({ outcome: "stalled", detail: "unsealed-tail" })]; + assert.equal(summarizeAnchoredLogs(rows, false).ok, true); + assert.equal(summarizeAnchoredLogs(rows, true).ok, false); + }); + + it("one failed path fails the verdict even among verified ones", () => { + const rows = [status({}), status({ outcome: "failed", detail: "tip-mismatch" }), status({})]; + assert.equal(summarizeAnchoredLogs(rows, false).ok, false); + assert.equal(summarizeAnchoredLogs(rows, false).counts.failed, 1); + }); + + it("an empty machine is not a pass claim (no counts, ok by absence of evidence)", () => { + const r = summarizeAnchoredLogs([], false); + assert.deepEqual(r.counts, { verified: 0, stalled: 0, missing: 0, failed: 0 }); + assert.equal(r.ok, true); + }); + + it("verifyAnchoredLogs walks every input and reports the union", async () => { + const seen: string[] = []; + const r = await verifyAnchoredLogs( + [ + { logPath: "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/a/.kit-audit.jsonl", record: record() }, + { logPath: "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/b/.kit-audit.jsonl", record: record() }, + ], + null, + async (p) => { + seen.push(p); + return gone; + }, + ); + assert.deepEqual(seen, ["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/a/.kit-audit.jsonl", "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/b/.kit-audit.jsonl"]); + assert.equal(r.counts.missing, 2); + assert.equal(r.strict, false); + }); +}); + +/** + * End-to-end: the command, not the classifier. #470's defect was a correct data + * structure nobody read, so these assert on what `kit audit verify --all` actually + * prints and exits with, against a real anchor dir shared by four trees. + */ +describe("kit audit verify --all (compiled CLI)", () => { + let anchorHome = ""; + let trees: string[] = []; + + const runCli = async ( + args: string[], + cwd: string, + ): Promise<{ exitCode: number; stdout: string; stderr: string }> => { + try { + const { stdout, stderr } = await exec(process.execPath, [CLI_PATH, ...args], { + cwd, + env: { + ...process.env, + KIT_AUDIT_ANCHOR_DIR: anchorHome, + // Keep incidental appends from advancing seals mid-assertion. + KIT_AUDIT_ANCHOR: "0", + KIT_HIDE_HOOK_SKIP_BANNER: "1", + }, + timeout: 60_000, + }); + return { exitCode: 0, stdout: stdout ?? "", stderr: stderr ?? "" }; + } catch (err: unknown) { + const e = err as { code?: number; stdout?: string; stderr?: string }; + return { + exitCode: typeof e.code === "number" ? e.code : 1, + stdout: e.stdout ?? "", + stderr: e.stderr ?? "", + }; + } + }; + + const mkTree = (): string => { + const d = realpathSync(mkdtempSync(join(tmpdir(), "kit-union-cli-"))); + trees.push(d); + return d; + }; + + beforeEach(() => { + anchorHome = realpathSync(mkdtempSync(join(tmpdir(), "kit-union-home-"))); + trees = []; + }); + afterEach(() => { + rmSync(anchorHome, { recursive: true, force: true }); + for (const d of trees) rmSync(d, { recursive: true, force: true }); + }); + + it("reports nothing sealed as a warning, not a green verdict", async () => { + const tree = mkTree(); + const r = await runCli(["audit", "verify", "--all"], tree); + assert.equal(r.exitCode, 0); + assert.match(r.stderr + r.stdout, /sealed no audit log yet/); + assert.doesNotMatch(r.stdout, /✓ 0 anchored/); + }); + + it("iterates every anchored path and separates missing from stalled", async () => { + const verifiedTree = mkTree(); + const stalledTree = mkTree(); + const goneTree = mkTree(); + + const vContent = await buildChain(verifiedTree, 2, "v"); + await anchorAuditLog(join(verifiedTree, LOG), vContent, anchorHome); + + const sSealed = await buildChain(stalledTree, 2, "s"); + await anchorAuditLog(join(stalledTree, LOG), sSealed, anchorHome); + await buildChain(stalledTree, 2, "s-later"); + + const gContent = await buildChain(goneTree, 1, "g"); + await anchorAuditLog(join(goneTree, LOG), gContent, anchorHome); + rmSync(goneTree, { recursive: true, force: true }); + + const r = await runCli(["audit", "verify", "--all", "--json"], verifiedTree); + const report = JSON.parse(r.stdout) as { + counts: Record; + ok: boolean; + results: Array<{ logPath: string; outcome: string; detail: string; unsealed?: number }>; + }; + + assert.equal(report.results.length, 3, "all three anchored paths must be enumerated"); + const byPath = new Map(report.results.map((x) => [x.logPath, x])); + assert.equal(byPath.get(join(verifiedTree, LOG))?.outcome, "verified"); + assert.equal(byPath.get(join(stalledTree, LOG))?.outcome, "stalled"); + assert.equal(byPath.get(join(stalledTree, LOG))?.unsealed, 2); + assert.equal(byPath.get(join(goneTree, LOG))?.outcome, "missing"); + assert.deepEqual(report.counts, { verified: 1, stalled: 1, missing: 1, failed: 0 }); + // A vanished temp dir must not turn the whole machine red. + assert.equal(report.ok, true); + assert.equal(r.exitCode, 0); + }); + + it("--strict turns a stalled seal into a non-zero exit", async () => { + const tree = mkTree(); + const sealed = await buildChain(tree, 1, "x"); + await anchorAuditLog(join(tree, LOG), sealed, anchorHome); + await buildChain(tree, 1, "x-later"); + + const lax = await runCli(["audit", "verify", "--all"], tree); + assert.equal(lax.exitCode, 0); + assert.match(lax.stdout + lax.stderr, /stalled/); + + const strict = await runCli(["audit", "verify", "--all", "--strict"], tree); + assert.equal(strict.exitCode, 1); + }); + + it("a rewritten sealed prefix in ANOTHER tree fails the union verdict", async () => { + const cwdTree = mkTree(); + const victim = mkTree(); + const forger = mkTree(); + + const clean = await buildChain(cwdTree, 1, "clean"); + await anchorAuditLog(join(cwdTree, LOG), clean, anchorHome); + + const sealed = await buildChain(victim, 3, "real"); + await anchorAuditLog(join(victim, LOG), sealed, anchorHome); + const forged = await buildChain(forger, 3, "forged"); + writeFileSync(join(victim, LOG), forged); + + // The cwd tree is clean: `kit audit verify` there passes and says nothing about + // the victim. That green is exactly what #470 is about. + const single = await runCli(["audit", "verify"], cwdTree); + assert.equal(single.exitCode, 0); + assert.doesNotMatch(single.stdout + single.stderr, new RegExp(victim.replace(/\+/g, "\\+"))); + + const all = await runCli(["audit", "verify", "--all"], cwdTree); + assert.equal(all.exitCode, 1); + assert.match(all.stdout + all.stderr, /tip-mismatch/); + assert.match(all.stdout + all.stderr, /1 failed/); + }); +}); diff --git a/src/audit-anchor-all.ts b/src/audit-anchor-all.ts new file mode 100644 index 00000000..c2db8f7b --- /dev/null +++ b/src/audit-anchor-all.ts @@ -0,0 +1,283 @@ +/** + * The union view over every audit log this machine has sealed. + * + * `kit audit verify` answers for ONE working tree — correctly: `logAuditEvent` + * resolves the log against the cwd it was handed, and a git worktree IS a distinct + * working tree, so each one gets its own chain. On a machine running several (one + * per agent session, which is what worktree-per-session harnesses produce) that + * yields N independent green verdicts and no way to ask the question a reviewer + * actually asks: what did the agents do to this repo today? + * + * The data to answer it was already on disk, unread. `~/.kit/audit-anchor.json` + * keys the HMAC tip PER LOG PATH and lives in the home dir, shared by every working + * tree on the machine. Measured on the machine that filed #470 it held 15 log paths + * across 15 directories, and the only reader outside `audit-anchor.ts` looked up a + * single path (`hints.ts`). This module iterates it. + * + * Why `missing` and `stalled` cannot share one outcome: most of those 15 paths are + * short-lived test temp dirs, so a command that alarms on a vanished log is a command + * nobody reads — and an unread report is the failure mode #470 is about, one level up. + * A log that is GONE is expected attrition. A log that is STILL THERE with entries + * past its seal is an unauthenticated tail, which is what deserves the attention. + * Same evidence, two verdicts, so: two outcomes. + * + * The exit policy is deliberately the one `decideAnchorVerdict` already applies to a + * single tree — an unsealed tail warns, and fails only under `--strict` / + * `[governance.audit].require_anchor`. Diverging would mean the same log verifies + * green in one command and red in the other, which is its own false verdict. + */ + +import { verifyAuditChain } from "./audit.js"; +import { verifyAgainstAnchor, type AnchorRecord } from "./audit-anchor.js"; + +/** + * Four outcomes, ranked by what a reader must do about them: + * verified — sealed prefix reproduces the tip and nothing is past the seal. + * stalled — the log is there but the seal no longer covers it (unsealed tail, + * or a rotated anchor key): re-seal it where it lives. + * missing — the log path is gone (temp dir, deleted clone). Attrition, not a finding. + * failed — the chain or the seal does not reconcile, or it cannot be checked at + * all. Coverage that could not run counts here, never as verified. + */ +export type AnchoredLogOutcome = "verified" | "stalled" | "missing" | "failed"; + +/** + * Machine-stable reason slug, so a `--json` consumer never has to parse prose. + * Mirrors `AnchorVerifyStatus` where the cause comes from the anchor check, and adds + * the causes that only exist when iterating paths kit did not just write. + */ +export type AnchoredLogDetail = + | "verified" + | "log-gone" + | "unsealed-tail" + | "anchor-key-changed" + | "chain-broken" + | "truncated" + | "tip-mismatch" + | "unparseable" + | "key-unavailable" + | "anchor-vanished" + | "unreadable"; + +export interface AnchoredLogStatus { + logPath: string; + outcome: AnchoredLogOutcome; + detail: AnchoredLogDetail; + /** One human sentence: what is true, and what to do about it. */ + message: string; + /** Entries currently in the log (absent when it could not be read). */ + entries?: number; + /** Entries the anchor sealed. */ + sealed?: number; + /** Entries appended past the seal. */ + unsealed?: number; + /** ISO time the anchor was last advanced, straight off the record. */ + sealedAt?: string; +} + +export interface AnchoredLogsReport { + results: AnchoredLogStatus[]; + counts: Record; + /** + * Whether the command should exit 0. `missing` never fails. `stalled` fails only + * under strict — the same policy `decideAnchorVerdict` applies to one tree. + */ + ok: boolean; + /** Echoed back so a `--json` reader can tell which policy produced `ok`. */ + strict: boolean; +} + +/** What a log path yielded: content, or why not. */ +export type LogRead = { ok: true; content: string } | { ok: false; gone: boolean }; + +/** Injected so the classifier stays pure and the missing/unreadable split is testable. */ +export type LogReader = (logPath: string) => Promise; + +export interface AnchoredLogInput { + logPath: string; + record: AnchorRecord; +} + +/** + * Classify ONE anchored log. Pure given (record, read, key) so every branch — + * including the ones that need a root-only or permission-denied filesystem to + * reproduce for real — is reachable in a unit test. + */ +export function classifyAnchoredLog( + logPath: string, + record: AnchorRecord, + read: LogRead, + key: Buffer | null, +): AnchoredLogStatus { + const sealedAt = record.updatedAt; + const base = { logPath, sealed: record.count, sealedAt }; + + if (!read.ok) { + return read.gone + ? { + ...base, + outcome: "missing", + detail: "log-gone", + message: `log no longer exists (sealed ${record.count} entr${ + record.count === 1 ? "y" : "ies" + } at ${sealedAt}) — expected for a temp dir or a deleted clone; the anchor entry is pruned on the next seal`, + } + : { + ...base, + outcome: "failed", + detail: "unreadable", + message: + "log exists but could not be read here, so its seal could not be checked — a chain that cannot be verified is unknown, not verified", + }; + } + + // The keyless chain comes first: the anchor vouches for a sound log, so a broken + // chain is the finding and the tip comparison below would only describe it worse. + const chain = verifyAuditChain(read.content); + if (!chain.ok) { + return { + ...base, + outcome: "failed", + detail: "chain-broken", + entries: chain.entries, + message: `hash chain BROKEN at entry ${chain.brokenAt}: ${ + chain.reason ?? "unchained entry" + } (${chain.entries} entries verified before the break)`, + }; + } + + const a = verifyAgainstAnchor(read.content, record, key); + const common = { ...base, entries: a.entries }; + switch (a.status) { + case "anchored-ok": { + const tail = a.newSinceAnchor ?? 0; + if (tail > 0) { + return { + ...common, + outcome: "stalled", + detail: "unsealed-tail", + unsealed: tail, + message: `${a.expected} sealed, ${tail} entr${ + tail === 1 ? "y" : "ies" + } BEYOND the seal and unauthenticated — run 'kit audit anchor' in that tree to re-seal`, + }; + } + return { + ...common, + outcome: "verified", + detail: "verified", + unsealed: 0, + message: `HMAC anchor verified (${a.expected} sealed entr${ + a.expected === 1 ? "y" : "ies" + })${a.externalReceipt ? ` + external anchor (${a.externalReceipt.authority})` : ""}`, + }; + } + // A rotated key invalidates every anchor it sealed, by design. That is a re-seal, + // not a tamper, so it reads as stalled — with its own detail so the two reasons a + // seal stopped covering a log never collapse into one line. + case "anchor-key-changed": + return { + ...common, + outcome: "stalled", + detail: "anchor-key-changed", + message: + a.reason ?? + "the anchor key that sealed this log is not the current one (rotated/replaced) — re-run 'kit audit anchor' there", + }; + case "key-unavailable": + return { + ...common, + outcome: "failed", + detail: "key-unavailable", + message: + "the anchor key is unreadable here, so no seal on this machine can be checked — failing closed rather than reporting a chain as verified", + }; + // Defensive: the path came OUT of the anchor store, so a null anchor means the + // record was removed underneath the iteration. Verified-by-absence is the exact + // false green the anchor exists to prevent. + case "no-anchor": + return { + ...common, + outcome: "failed", + detail: "anchor-vanished", + message: + "the anchor record for this path disappeared while it was being read — refusing to report an unanchored log as verified", + }; + case "truncated": + return { + ...common, + outcome: "failed", + detail: "truncated", + message: a.reason ?? `log has ${a.entries} entries but the anchor sealed ${a.expected}`, + }; + case "tip-mismatch": + return { + ...common, + outcome: "failed", + detail: "tip-mismatch", + message: a.reason ?? "anchored prefix HMAC does not match — the log was rewritten", + }; + case "unparseable": + return { + ...common, + outcome: "failed", + detail: "unparseable", + message: a.reason ?? "log is unparseable — cannot reconcile with the anchor", + }; + } +} + +/** + * Classify every anchored log the record knows about. + * + * Reads are sequential on purpose: the point of the command is a readable union + * report over a handful of paths, and a bounded, ordered walk keeps the output stable + * across runs (which is what makes it diffable in CI). + */ +export async function verifyAnchoredLogs( + inputs: readonly AnchoredLogInput[], + key: Buffer | null, + read: LogReader, + opts: { strict?: boolean } = {}, +): Promise { + const strict = opts.strict === true; + const results: AnchoredLogStatus[] = []; + for (const { logPath, record } of inputs) { + results.push(classifyAnchoredLog(logPath, record, await read(logPath), key)); + } + return summarizeAnchoredLogs(results, strict); +} + +/** + * Fold per-path outcomes into the verdict. Exported separately so the exit policy is + * one testable decision, the way `decideAnchorVerdict` is for a single tree. + */ +export function summarizeAnchoredLogs( + results: readonly AnchoredLogStatus[], + strict: boolean, +): AnchoredLogsReport { + const counts: Record = { + verified: 0, + stalled: 0, + missing: 0, + failed: 0, + }; + for (const r of results) counts[r.outcome]++; + return { + results: [...results], + counts, + ok: counts.failed === 0 && (!strict || counts.stalled === 0), + strict, + }; +} + +/** Read a log for the union walk, splitting "gone" from "there but unreadable". */ +export async function readLogForUnion(logPath: string): Promise { + const { readFile } = await import("node:fs/promises"); + try { + return { ok: true, content: await readFile(logPath, "utf-8") }; + } catch (err) { + const code = (err as { code?: string }).code; + return { ok: false, gone: code === "ENOENT" || code === "ENOTDIR" }; + } +} diff --git a/src/audit-anchor.ts b/src/audit-anchor.ts index c33b3a1f..a345bcc4 100644 --- a/src/audit-anchor.ts +++ b/src/audit-anchor.ts @@ -312,6 +312,23 @@ export async function readAnchorRecord( return store[logPath] ?? null; } +/** + * Every log path this machine has sealed, with its record — the union view's oracle. + * + * The store keys the tip PER LOG PATH and lives in the home dir, so it already spans + * every working tree on the machine; until `kit audit verify --all` nothing enumerated + * it (see audit-anchor-all.ts and #470). Sorted so the report is stable across runs + * and therefore diffable in CI. + */ +export async function listAnchoredLogs( + dir?: string, +): Promise> { + const store = await readStore(dir); + return Object.keys(store) + .sort() + .map((logPath) => ({ logPath, record: store[logPath] })); +} + /** * True when this machine has sealed ANY audit log. Used by `kit audit verify` * to fail closed: once anchoring is in use, a log that presents as unanchored diff --git a/src/commands/audit.ts b/src/commands/audit.ts index b1aee720..d38c51da 100644 --- a/src/commands/audit.ts +++ b/src/commands/audit.ts @@ -84,6 +84,83 @@ async function resolveAuditLogPath(): Promise { return resolve(process.cwd(), logFile); } +/** + * `kit audit verify --all` - the union view over every audit log this machine has + * sealed, not just the one in `cwd`. + * + * Why it exists: `kit audit verify` is correct for one working tree, and a git + * worktree is a distinct working tree, so N trees produce N green verdicts and no + * whole-machine answer (#470). `~/.kit/audit-anchor.json` already keyed the tip per + * log path across every tree; nothing enumerated it. + * + * `missing` (log path gone) and `stalled` (log there, entries past its seal) print as + * distinct outcomes and only the second one counts toward the verdict: most anchored + * paths on a dev machine are short-lived test temp dirs, and a report that alarms on + * those is a report nobody reads. + */ +async function cmdAuditVerifyAll(strict: boolean, jsonMode: boolean): Promise { + const { listAnchoredLogs, tryReadAuditAnchorKey, anchorRecordPath } = + await import("../audit-anchor.js"); + const { verifyAnchoredLogs, readLogForUnion } = await import("../audit-anchor-all.js"); + + const inputs = await listAnchoredLogs(); + const key = await tryReadAuditAnchorKey(); + const report = await verifyAnchoredLogs(inputs, key, readLogForUnion, { strict }); + + if (jsonMode) { + console.log(JSON.stringify({ anchorRecord: anchorRecordPath(), ...report }, null, 2)); + return report.ok; + } + + console.log(`${c.bold}${c.cyan}kit audit verify --all${c.reset}`); + console.log(`${c.dim}${anchorRecordPath()}${c.reset}`); + console.log(`${c.dim}${"─".repeat(50)}${c.reset}`); + + if (inputs.length === 0) { + // Not a pass dressed up as one: an empty record means nothing has ever been + // sealed here, so there is no evidence either way. + console.warn( + `${c.yellow}! this machine has sealed no audit log yet — nothing to verify (run 'kit audit anchor' in a repo)${c.reset}`, + ); + return true; + } + + // Findings first, attrition last: the ordering IS the readability fix. + const order = ["failed", "stalled", "verified", "missing"] as const; + for (const outcome of order) { + for (const r of report.results.filter((x) => x.outcome === outcome)) { + const icon = + outcome === "failed" + ? `${c.red}✗` + : outcome === "stalled" + ? `${c.yellow}!` + : outcome === "verified" + ? `${c.green}✓` + : `${c.dim}·`; + const label = outcome.padEnd(8); + console.log( + ` ${icon} ${label}${c.reset} ${r.logPath}\n ${c.dim}${r.detail}: ${r.message}${c.reset}`, + ); + } + } + + const k = report.counts; + const summary = `${inputs.length} anchored log(s): ${k.verified} verified · ${k.stalled} stalled · ${k.missing} missing · ${k.failed} failed`; + console.log(); + if (report.ok && k.stalled === 0) { + console.log(`${c.green}✓ ${summary}${c.reset}`); + } else if (report.ok) { + // Exits 0 by the same policy `decideAnchorVerdict` applies to one tree: an + // unsealed tail warns, and fails under --strict / require_anchor. + console.warn( + `${c.yellow}! ${summary}${c.reset} ${c.dim}(stalled seals warn; --strict makes them fail)${c.reset}`, + ); + } else { + console.error(`${c.red}✗ ${summary}${c.reset}`); + } + return report.ok; +} + /** * `kit audit verify` - verify the keyless hash chain, then the external HMAC * anchor (key + sealed count) when one exists. See audit-anchor.ts for the @@ -108,6 +185,11 @@ async function cmdAuditVerify(): Promise { } catch { /* default: not required */ } + // The union view answers for the machine, so it must run BEFORE this function + // resolves a cwd-relative log — "no log here" is not an answer to "--all". + if (hasFlag(args, "--all")) { + return cmdAuditVerifyAll(strictFlag || requireAnchor, hasFlag(args, "--json")); + } const logPath = await resolveAuditLogPath(); let content: string; try {