Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
100 changes: 97 additions & 3 deletions src/audit-anchor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
tryReadAuditAnchorKey,
tryAdvanceAnchorOnAppend,
resolveExternalAnchor,
commandExternalAnchor,
type AnchorVerifyResult,
type AnchorRecord,
} from "./audit-anchor.js";
Expand Down Expand Up @@ -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 <T>(cmd: string | undefined, fn: () => T | Promise<T>): Promise<T> => {
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\)/);
});
});
108 changes: 102 additions & 6 deletions src/audit-anchor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -245,6 +246,13 @@
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<string, AnchorRecord>;
Expand Down Expand Up @@ -312,6 +320,7 @@
logPath: string,
content: string,
dir?: string,
opts: { external?: boolean } = {},
): Promise<AnchorRecord> {
const seals = lineSeals(content);
if (seals === null) {
Expand All @@ -326,6 +335,19 @@
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);
Expand All @@ -349,6 +371,8 @@
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;
}

Expand Down Expand Up @@ -422,6 +446,7 @@
entries,
expected: anchor.count,
newSinceAnchor: entries - anchor.count,
externalReceipt: anchor.external,
};
}

Expand All @@ -440,6 +465,12 @@
* 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 {
Expand All @@ -455,11 +486,22 @@
* three review attacks (path-repoint, forged tail, key-rotation) have a single
* authoritative decision point. #fix2 #fix3 #fix4
*/
export function decideAnchorVerdict(input: AnchorVerdictInput): AnchorVerdict {

Check warning on line 489 in src/audit-anchor.ts

View workflow job for this annotation

GitHub Actions / build-and-test

Function 'decideAnchorVerdict' has a complexity of 22. Maximum allowed is 20
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
Expand All @@ -469,10 +511,13 @@
? { 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": {
Expand Down Expand Up @@ -575,10 +620,61 @@
}

/**
* 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<ExternalAnchorReceipt>;
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;
}
4 changes: 2 additions & 2 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5270,9 +5270,9 @@ export const COMMAND_HELP: Record<string, string> = {
"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)",
Expand Down
16 changes: 12 additions & 4 deletions src/commands/audit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,7 @@ async function cmdAuditVerify(): Promise<boolean> {
result: a,
strict: strictFlag || requireAnchor,
machineHasAnchors,
requireExternal: hasFlag(args, "--require-external"),
});
if (verdict.level === "ok") {
console.log(`${c.green}✓ ${verdict.message}${c.reset}`);
Expand Down Expand Up @@ -220,14 +221,21 @@ async function cmdAuditAnchor(): Promise<boolean> {
);
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}`);
Expand Down
Loading