diff --git a/CHANGELOG.md b/CHANGELOG.md index 3cade7ac..54a5ae8a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,25 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/). ## [Unreleased] -## [3.0.0] - 2026-06-30 +### Added + +- **External timestamp anchor (command transport) — closes the same-machine + forge gap.** The keyless chain + machine-local HMAC anchor proves *what + happened on this machine*, but anyone with that machine's anchor key (UID) can + re-seal a rewritten log undetectably. `kit audit anchor --external` now folds + an **external authority's receipt** into the seal: the documented + `resolveExternalAnchor()` extension point is implemented via a command + transport — set `KIT_EXTERNAL_ANCHOR_CMD` to any program (an RFC3161 TSA + client, an append-only log writer, a notary) and kit pipes the tip/count/log + path to it via `KIT_ANCHOR_TIP`/`KIT_ANCHOR_COUNT`/`KIT_ANCHOR_LOGPATH`, + expecting a JSON receipt `{ token, authority?, timestamp? }` on stdout. The + receipt is stored on the anchor record (`external`). kit still ships **no + network client** (no-egress default) — the operator wires the authority. +- **`kit audit verify --require-external`** fails any seal that carries only an + HMAC anchor (no external receipt), so a policy can demand third-party + countersignature on every seal. Fail-closed throughout: `--external` with no + command configured, a non-zero exit, non-JSON output, or a missing `token` all + hard-error rather than silently degrading to HMAC-only. kit 3.0 — from a provable local floor to an org-governed control plane: machine **identity** (Ed25519) + **signable, distributable policy-as-code**, **governed diff --git a/src/audit-anchor.test.ts b/src/audit-anchor.test.ts index a4341962..4c7af505 100644 --- a/src/audit-anchor.test.ts +++ b/src/audit-anchor.test.ts @@ -20,6 +20,7 @@ import { tryReadAuditAnchorKey, tryAdvanceAnchorOnAppend, resolveExternalAnchor, + commandExternalAnchor, type AnchorVerifyResult, type AnchorRecord, } from "./audit-anchor.js"; @@ -504,8 +505,101 @@ describe("audit anchor - hasAnyAnchoredLogs", () => { }); }); -describe("audit anchor - external anchor extension point", () => { - it("resolveExternalAnchor returns null until an enclave wires one up", () => { - assert.equal(resolveExternalAnchor(), null); +describe("audit anchor - external anchor (command transport, fail-closed)", () => { + const withCmd = async (cmd: string | undefined, fn: () => T | Promise): Promise => { + const prev = process.env.KIT_EXTERNAL_ANCHOR_CMD; + if (cmd === undefined) delete process.env.KIT_EXTERNAL_ANCHOR_CMD; + else process.env.KIT_EXTERNAL_ANCHOR_CMD = cmd; + try { + return await fn(); + } finally { + if (prev === undefined) delete process.env.KIT_EXTERNAL_ANCHOR_CMD; + else process.env.KIT_EXTERNAL_ANCHOR_CMD = prev; + } + }; + + it("resolveExternalAnchor: null without env, command-anchor with it", async () => { + await withCmd(undefined, () => assert.equal(resolveExternalAnchor(), null)); + await withCmd("true", () => assert.ok(resolveExternalAnchor() !== null)); + }); + + it("commandExternalAnchor parses a JSON receipt and passes the tip via env", async () => { + // The command echoes a receipt that embeds the tip it received → proves wiring. + const a = commandExternalAnchor( + `printf '{"token":"tok-%s","authority":"test-tsa"}' "$KIT_ANCHOR_TIP"`, + ); + const r = await a.anchor({ tip: "deadbeef", count: 3, logPath: "/x" }); + assert.equal(r.token, "tok-deadbeef"); + assert.equal(r.authority, "test-tsa"); + assert.ok(r.timestamp); // defaulted when absent + }); + + it("is FAIL-CLOSED: non-zero exit / non-JSON / missing token all throw", async () => { + await assert.rejects( + commandExternalAnchor("exit 7").anchor({ tip: "a", count: 1, logPath: "/x" }), + /failed/, + ); + await assert.rejects( + commandExternalAnchor("echo not-json").anchor({ tip: "a", count: 1, logPath: "/x" }), + /valid JSON receipt/, + ); + await assert.rejects( + commandExternalAnchor("echo {}").anchor({ tip: "a", count: 1, logPath: "/x" }), + /token/, + ); + }); + + it("anchorAuditLog --external stores the receipt; requested-but-unconfigured throws", async () => { + const cwd = mkdtempSync(join(tmpdir(), "kit-ext-log-")); + const dir = mkdtempSync(join(tmpdir(), "kit-ext-home-")); + try { + const content = await buildChain(cwd, 2); + const logPath = join(cwd, ".kit-audit.jsonl"); + // configured → receipt stored on the record + await withCmd(`echo '{"token":"abc","authority":"acme-tsa"}'`, async () => { + const rec = await anchorAuditLog(logPath, content, dir, { external: true }); + assert.equal(rec.external?.token, "abc"); + assert.equal(rec.external?.authority, "acme-tsa"); + }); + // requested but no command configured → fail-closed throw + await withCmd(undefined, async () => { + await assert.rejects( + anchorAuditLog(logPath, content, dir, { external: true }), + /none configured/, + ); + }); + } finally { + rmSync(cwd, { recursive: true, force: true }); + rmSync(dir, { recursive: true, force: true }); + } + }); + + it("decideAnchorVerdict --require-external fails an HMAC-only seal, passes one with a receipt", () => { + const base: AnchorVerifyResult = { + status: "anchored-ok", + entries: 2, + expected: 2, + newSinceAnchor: 0, + }; + const noExt = decideAnchorVerdict({ + result: base, + strict: false, + machineHasAnchors: true, + requireExternal: true, + }); + assert.equal(noExt.ok, false); + assert.match(noExt.message, /external anchor REQUIRED/); + + const withExt = decideAnchorVerdict({ + result: { + ...base, + externalReceipt: { token: "t", authority: "tsa", timestamp: "2026-01-01" }, + }, + strict: false, + machineHasAnchors: true, + requireExternal: true, + }); + assert.equal(withExt.ok, true); + assert.match(withExt.message, /external anchor \(tsa\)/); }); }); diff --git a/src/audit-anchor.ts b/src/audit-anchor.ts index e0c012e8..f0b90090 100644 --- a/src/audit-anchor.ts +++ b/src/audit-anchor.ts @@ -36,6 +36,7 @@ * verifies as "legacy (unanchored)" - a warning, not a hard failure. */ import { readFile, writeFile, mkdir, stat } from "node:fs/promises"; +import { execSync } from "node:child_process"; import { join } from "node:path"; import { homedir } from "node:os"; import { createHmac, timingSafeEqual, randomBytes } from "node:crypto"; @@ -245,6 +246,13 @@ export interface AnchorRecord { keyFingerprint?: string; /** Anchor record schema version. */ version?: number; + /** + * Receipt from an EXTERNAL timestamp anchor (RFC3161 TSA / append-only log), + * present only when sealed with `kit audit anchor --external`. This is what + * closes the same-UID gap: a local principal who can read the 0600 key still + * cannot forge a fresh external receipt. Absent ⇒ HMAC-only seal. + */ + external?: ExternalAnchorReceipt; } type AnchorStore = Record; @@ -312,6 +320,7 @@ export async function anchorAuditLog( logPath: string, content: string, dir?: string, + opts: { external?: boolean } = {}, ): Promise { const seals = lineSeals(content); if (seals === null) { @@ -326,6 +335,19 @@ export async function anchorAuditLog( keyFingerprint: anchorKeyFingerprint(key), version: ANCHOR_RECORD_VERSION, }; + // Optional EXTERNAL timestamp anchor. Fail-closed by contract: if the operator + // asked for `--external` we refuse to write a seal unless a real receipt comes + // back — a missing config or a failed/unreachable authority THROWS rather than + // silently producing an HMAC-only seal that would later look externally sealed. + if (opts.external) { + const ext = resolveExternalAnchor(); + if (!ext) { + throw new Error( + "external anchoring requested but none configured — set KIT_EXTERNAL_ANCHOR_CMD", + ); + } + rec.external = await ext.anchor({ tip: rec.tip, count: rec.count, logPath }); + } const store = await readStore(dir); store[logPath] = rec; await writeStore(store, dir); @@ -349,6 +371,8 @@ export interface AnchorVerifyResult { expected?: number; /** Entries appended since the last anchor (status "anchored-ok"). */ newSinceAnchor?: number; + /** The external-anchor receipt on the record, if any (for require-external checks). */ + externalReceipt?: ExternalAnchorReceipt; reason?: string; } @@ -422,6 +446,7 @@ export function verifyAgainstAnchor( entries, expected: anchor.count, newSinceAnchor: entries - anchor.count, + externalReceipt: anchor.external, }; } @@ -440,6 +465,12 @@ export interface AnchorVerdictInput { * it pass green. #fix2 */ machineHasAnchors: boolean; + /** + * Require an EXTERNAL anchor receipt: `kit audit verify --require-external`. An + * HMAC-only seal (no external receipt) then FAILS — for regulated enclaves that + * must defeat even a same-UID forger. Independent of `strict`. + */ + requireExternal?: boolean; } export interface AnchorVerdict { @@ -456,10 +487,21 @@ export interface AnchorVerdict { * authoritative decision point. #fix2 #fix3 #fix4 */ export function decideAnchorVerdict(input: AnchorVerdictInput): AnchorVerdict { - const { result, strict, machineHasAnchors } = input; + const { result, strict, machineHasAnchors, requireExternal } = input; const failClosed = strict || machineHasAnchors; switch (result.status) { case "anchored-ok": { + // External-anchor requirement: an HMAC-only seal can be forged by a same-UID + // principal who reads the 0600 key; require-external refuses it. Checked + // before the tail check so the strongest requirement wins. + if (requireExternal && !result.externalReceipt) { + return { + ok: false, + level: "error", + message: + "external anchor REQUIRED but this seal has none (HMAC-only) — re-seal with 'kit audit anchor --external'.", + }; + } const tail = result.newSinceAnchor ?? 0; if (tail > 0) { // Unsealed tail = unauthenticated entries appended past the seal. Loud @@ -469,10 +511,13 @@ export function decideAnchorVerdict(input: AnchorVerdictInput): AnchorVerdict { ? { ok: false, level: "error", message: msg } : { ok: true, level: "warn", message: msg }; } + const extNote = result.externalReceipt + ? ` + external anchor (${result.externalReceipt.authority})` + : ""; return { ok: true, level: "ok", - message: `HMAC anchor verified (${result.expected} sealed entries).`, + message: `HMAC anchor verified (${result.expected} sealed entries)${extNote}.`, }; } case "no-anchor": { @@ -575,10 +620,61 @@ export interface ExternalTimestampAnchor { } /** - * Resolve a configured external anchor. Returns null until an enclave wires one - * up - kit ships no default network client by design. Present so call sites and - * docs can reference a stable extension point. + * A command-backed external anchor. kit ships NO network client (that would + * break the local-first / no-egress default); instead the operator supplies a + * command via `KIT_EXTERNAL_ANCHOR_CMD` that timestamps the tip however they + * choose (an RFC3161 TSA submit, a post to a remote append-only log, …). The tip + * + count + log path are passed as env (`KIT_ANCHOR_TIP`/`_COUNT`/`_LOGPATH`), + * and the command MUST print a JSON receipt `{ token, authority?, timestamp? }` + * on stdout. FAIL-CLOSED: a non-zero exit, a missing `token`, or unparseable + * output throws — kit never fabricates a receipt. + */ +export function commandExternalAnchor(cmd: string): ExternalTimestampAnchor { + return { + async anchor({ tip, count, logPath }) { + let out: string; + try { + out = execSync(cmd, { + env: { + ...process.env, + KIT_ANCHOR_TIP: tip, + KIT_ANCHOR_COUNT: String(count), + KIT_ANCHOR_LOGPATH: logPath, + }, + encoding: "utf-8", + stdio: ["ignore", "pipe", "pipe"], + timeout: 30_000, + }); + } catch (e) { + throw new Error(`external anchor command failed: ${(e as Error).message}`); + } + let parsed: unknown; + try { + parsed = JSON.parse(out.trim()); + } catch { + throw new Error("external anchor command did not emit a valid JSON receipt on stdout"); + } + const r = (parsed ?? {}) as Partial; + if (typeof r.token !== "string" || !r.token) { + throw new Error("external anchor receipt is missing a non-empty `token`"); + } + return { + token: r.token, + authority: typeof r.authority === "string" && r.authority ? r.authority : "command", + timestamp: + typeof r.timestamp === "string" && r.timestamp ? r.timestamp : new Date().toISOString(), + }; + }, + }; +} + +/** + * Resolve a configured external anchor, or null when none is wired (the default — + * kit ships no network client by design). Today the only built-in binding is the + * command transport (`KIT_EXTERNAL_ANCHOR_CMD`); the interface stays open for an + * in-process implementation an enclave links itself. */ export function resolveExternalAnchor(): ExternalTimestampAnchor | null { - return null; + const cmd = (process.env.KIT_EXTERNAL_ANCHOR_CMD ?? "").trim(); + return cmd ? commandExternalAnchor(cmd) : null; } diff --git a/src/cli.ts b/src/cli.ts index 4e20348a..428a77a9 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -5270,9 +5270,9 @@ export const COMMAND_HELP: Record = { "Diff two prescan reports — surface new regressions + fixed findings since baseline", "audit secrets": "Forensics: who/what touched each key + when (reads audit log)", "audit verify": - "Verify the audit log's keyless hash chain + the external HMAC anchor (exit 1 on break/forge/truncation)", + "Verify the audit log's keyless hash chain + HMAC anchor (--require-external demands a TSA receipt; exit 1 on break/forge/truncation)", "audit anchor": - "Seal the audit log with the machine-local HMAC key so a key-less rewrite or truncation is detectable", + "Seal the audit log with the machine-local HMAC key (--external also gets a receipt from KIT_EXTERNAL_ANCHOR_CMD — closes the same-UID gap)", "audit export": "Emit the audit log for a SIEM (--format cef|syslog|json)", auth: "TOTP-gated elevation for destructive secret ops (elevate|status|revoke|setup-totp)", "auth elevate": "Mint elevation marker for destructive secret ops (TOTP/yes-prompt)", diff --git a/src/commands/audit.ts b/src/commands/audit.ts index 98207fc8..2eec49f7 100644 --- a/src/commands/audit.ts +++ b/src/commands/audit.ts @@ -185,6 +185,7 @@ async function cmdAuditVerify(): Promise { result: a, strict: strictFlag || requireAnchor, machineHasAnchors, + requireExternal: hasFlag(args, "--require-external"), }); if (verdict.level === "ok") { console.log(`${c.green}✓ ${verdict.message}${c.reset}`); @@ -220,14 +221,21 @@ async function cmdAuditAnchor(): Promise { ); return false; } + const external = hasFlag(process.argv.slice(3), "--external"); try { - const rec = await anchorAuditLog(logPath, content); + const rec = await anchorAuditLog(logPath, content, undefined, { external }); console.log( `${c.green}✓ audit log anchored${c.reset} ${c.dim}${rec.count} entries sealed (${rec.algo})${c.reset}`, ); - console.log( - `${c.dim}Note: the anchor resists a tamperer who cannot read the 0600 anchor key. A same-UID attacker who can read ~/.kit can still forge; close that with an external TSA anchor.${c.reset}`, - ); + if (rec.external) { + console.log( + `${c.green}✓ external anchor receipt${c.reset} ${c.dim}${rec.external.authority} @ ${rec.external.timestamp}${c.reset}`, + ); + } else { + console.log( + `${c.dim}Note: HMAC-only seal resists a tamperer who cannot read the 0600 anchor key. A same-UID attacker who can read ~/.kit can still forge; close that with \`kit audit anchor --external\` (set KIT_EXTERNAL_ANCHOR_CMD).${c.reset}`, + ); + } return true; } catch (err) { console.error(`${c.red}✗ could not anchor: ${(err as Error).message}${c.reset}`);