diff --git a/src/audit.test.ts b/src/audit.test.ts index 7e27b70e..1384ada3 100644 --- a/src/audit.test.ts +++ b/src/audit.test.ts @@ -1,9 +1,16 @@ import { describe, it, afterEach } from "node:test"; import assert from "node:assert/strict"; import { readFile, unlink } from "node:fs/promises"; +import { mkdtempSync, rmSync, readFileSync } from "node:fs"; import { join } from "node:path"; import { tmpdir } from "node:os"; -import { logAuditEvent, readAuditLog, formatAuditLog } from "./audit.js"; +import { + logAuditEvent, + readAuditLog, + formatAuditLog, + appendAuditEventDirect, + verifyAuditChain, +} from "./audit.js"; import type { GovernanceConfig } from "./config.js"; describe("logAuditEvent", () => { @@ -329,3 +336,121 @@ describe("formatAuditLog", () => { assert.ok(formatted.includes("Error: Missing API key")); }); }); + +describe("verifyAuditChain (tamper-evidence)", () => { + async function writeEvents(dir: string, n: number): Promise { + for (let i = 0; i < n; i++) { + const ok = await appendAuditEventDirect( + { operation: `op-${i}`, environment: "dev", success: true }, + { cwd: dir }, + ); + assert.equal(ok, true); + } + } + + it("accepts an empty log", () => { + assert.deepEqual(verifyAuditChain(""), { ok: true, entries: 0 }); + }); + + it("verifies a chain produced by appendAuditEventDirect", async () => { + const dir = mkdtempSync(join(tmpdir(), "kit-audit-c-")); + try { + await writeEvents(dir, 4); + const r = verifyAuditChain(readFileSync(join(dir, ".kit-audit.jsonl"), "utf8")); + assert.equal(r.ok, true); + assert.equal(r.entries, 4); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + it("detects tampered content (hash mismatch)", async () => { + const dir = mkdtempSync(join(tmpdir(), "kit-audit-t-")); + try { + await writeEvents(dir, 3); + const lines = readFileSync(join(dir, ".kit-audit.jsonl"), "utf8").trim().split("\n"); + const mid = JSON.parse(lines[1]); + mid.operation = "tampered-after-the-fact"; + lines[1] = JSON.stringify(mid); + const r = verifyAuditChain(lines.join("\n") + "\n"); + assert.equal(r.ok, false); + assert.equal(r.brokenAt, 1); + assert.match(r.reason!, /tampered/); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + it("detects a deleted entry (broken prev-link)", async () => { + const dir = mkdtempSync(join(tmpdir(), "kit-audit-d-")); + try { + await writeEvents(dir, 4); + const lines = readFileSync(join(dir, ".kit-audit.jsonl"), "utf8").trim().split("\n"); + lines.splice(1, 1); + const r = verifyAuditChain(lines.join("\n") + "\n"); + assert.equal(r.ok, false); + assert.equal(r.brokenAt, 1); + assert.match(r.reason!, /inserted, removed, or reordered/); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + it("flags an unchained (legacy) entry", () => { + const legacy = JSON.stringify({ + timestamp: "t", + operation: "x", + environment: "dev", + success: true, + }); + const r = verifyAuditChain(legacy + "\n"); + assert.equal(r.ok, false); + assert.match(r.reason!, /missing hash/); + }); +}); + +describe("logAuditEvent return value (fail-closed signal)", () => { + function cfg(logFile: string): any { + return { + enabled: true, + environment: "dev", + access: {}, + agent: { id: "a", name: "A" }, + audit: { enabled: true, log_file: logFile, include_secrets: false }, + approval: {}, + secrets: {}, + revocation: {}, + }; + } + + it("returns true when the local append succeeds", async () => { + const dir = mkdtempSync(join(tmpdir(), "kit-audit-ok-")); + try { + const ok = await logAuditEvent(cfg(join(dir, ".kit-audit.jsonl")), { + operation: "x", + environment: "dev", + success: true, + }); + assert.equal(ok, true); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + it("returns false when the local append fails (unwritable path)", async () => { + const bad = join(tmpdir(), `kit-audit-nope-${process.pid}`, "deep", ".kit-audit.jsonl"); + const ok = await logAuditEvent(cfg(bad), { + operation: "x", + environment: "dev", + success: true, + }); + assert.equal(ok, false); + }); + + it("returns true when audit is disabled (nothing to gate)", async () => { + const c = cfg("/whatever"); + c.audit.enabled = false; + const ok = await logAuditEvent(c, { operation: "x", environment: "dev", success: true }); + assert.equal(ok, true); + }); +}); diff --git a/src/audit.ts b/src/audit.ts index add46749..64965c32 100644 --- a/src/audit.ts +++ b/src/audit.ts @@ -1,7 +1,90 @@ import { appendFile, readFile, writeFile, rename } from "node:fs/promises"; import { resolve } from "node:path"; +import { createHash } from "node:crypto"; import type { GovernanceConfig } from "./config.js"; +// ── Tamper-evident hash chain ─────────────────────────────────────────────── +// Each appended line carries `prev` (the previous line's hash) and `hash` +// (sha256 over the line's canonical pre-hash JSON). Any edit, insertion, +// deletion, or reorder breaks the chain and is caught by verifyAuditChain — +// the integrity property a regulated/air-gapped enclave needs from its audit +// trail. (Note: cross-process concurrent appends can fork the chain; external +// tampering is still detected.) +const GENESIS_HASH = "0".repeat(64); + +function hashLine(preHashJson: string): string { + return createHash("sha256").update(preHashJson).digest("hex"); +} + +/** Read the last entry's hash to chain onto, or GENESIS for a fresh/legacy log. */ +async function lastChainHash(logPath: string): Promise { + try { + const content = await readFile(logPath, "utf-8"); + const lines = content.split("\n").filter((l) => l.trim().length > 0); + if (lines.length === 0) return GENESIS_HASH; + const last = JSON.parse(lines[lines.length - 1]) as { hash?: unknown }; + return typeof last.hash === "string" ? last.hash : GENESIS_HASH; + } catch { + return GENESIS_HASH; + } +} + +/** Append an event as a hash-chained line. Throws on write failure. */ +async function appendChained(logPath: string, event: AuditEvent): Promise { + const prev = await lastChainHash(logPath); + const preHash = JSON.stringify({ ...event, prev }); + const hash = hashLine(preHash); + await appendFile(logPath, JSON.stringify({ ...event, prev, hash }) + "\n", "utf-8"); +} + +export interface ChainVerifyResult { + ok: boolean; + entries: number; + /** 0-based index of the first broken entry, when !ok. */ + brokenAt?: number; + reason?: string; +} + +/** + * Re-walk a `.kit-audit.jsonl` body and verify the hash chain end to end. + * Detects content tampering (hash mismatch) and insertion/deletion/reorder + * (prev-link mismatch). Pure — fully testable. + */ +export function verifyAuditChain(content: string): ChainVerifyResult { + const lines = content.split("\n").filter((l) => l.trim().length > 0); + let prev = GENESIS_HASH; + for (let i = 0; i < lines.length; i++) { + let obj: Record; + try { + obj = JSON.parse(lines[i]) as Record; + } catch { + return { ok: false, entries: i, brokenAt: i, reason: "unparseable line" }; + } + const { hash, ...rest } = obj; + if (typeof hash !== "string") { + return { ok: false, entries: i, brokenAt: i, reason: "missing hash (unchained entry)" }; + } + if (rest.prev !== prev) { + return { + ok: false, + entries: i, + brokenAt: i, + reason: "broken link — an entry was inserted, removed, or reordered", + }; + } + if (hashLine(JSON.stringify(rest)) !== hash) { + return { + ok: false, + entries: i, + brokenAt: i, + reason: "hash mismatch — entry content tampered", + }; + } + prev = hash; + } + return { ok: true, entries: lines.length }; +} + const PENDING_QUEUE_FILE = ".kit-audit.pending"; const MAX_PENDING_ENTRIES = 500; const RETRY_BACKOFF_MS = [250, 1_000, 4_000]; @@ -40,7 +123,7 @@ export async function appendAuditEventDirect( const logFile = opts.logFile ?? ".kit-audit.jsonl"; const logPath = resolve(opts.cwd ?? process.cwd(), logFile); try { - await appendFile(logPath, JSON.stringify(auditEvent) + "\n", "utf-8"); + await appendChained(logPath, auditEvent); return true; } catch (error) { console.error(`[kit] audit-log append failed: ${error}`); @@ -181,9 +264,10 @@ export async function logAuditEvent( config: Required, event: Omit, companyId?: string, -): Promise { +): Promise { + // Audit disabled by config → nothing to write, nothing to gate on. if (!config.audit.enabled) { - return; + return true; } const auditEvent: AuditEvent = { @@ -198,13 +282,16 @@ export async function logAuditEvent( auditEvent.metadata = sanitizeMetadata(auditEvent.metadata); } - // Write to local JSONL file - const logLine = JSON.stringify(auditEvent) + "\n"; + // Write to local JSONL file (hash-chained for tamper-evidence). The boolean + // return lets fail-closed callers (e.g. destructive ops in withGovernance) + // refuse to proceed when the local audit append fails. const logFile = config.audit.log_file || ".kit-audit.jsonl"; const logPath = resolve(process.cwd(), logFile); + let wroteLocal = false; try { - await appendFile(logPath, logLine, "utf-8"); + await appendChained(logPath, auditEvent); + wroteLocal = true; } catch (error) { console.error(`Failed to write audit log: ${error}`); } @@ -217,6 +304,9 @@ export async function logAuditEvent( warnFirstRemotePush(companyId); await sendToRemoteAPI(auditEvent, companyId); } + + // Auditability is the local append; remote is best-effort and does not gate. + return wroteLocal; } /** diff --git a/src/commands/audit.ts b/src/commands/audit.ts index 674aca26..8cf8fec1 100644 --- a/src/commands/audit.ts +++ b/src/commands/audit.ts @@ -1,6 +1,7 @@ // `kit audit` commands — extracted from cli.ts (split step 4). import { readSecretAuditEvents, groupBySecret, summarize } from "../audit-secrets.js"; import { readAuditLog } from "../audit.js"; +import { resolve } from "node:path"; import { printAuditTable } from "../output.js"; import { loadConfig } from "../config.js"; import { resolveConfigPath } from "../cli-shared.js"; @@ -76,6 +77,37 @@ export async function cmdAudit(): Promise { return cmdAuditSecrets(); } + // Sub-sub: kit audit verify — check the tamper-evident hash chain + if (args[0] === "verify") { + let logFile = ".kit-audit.jsonl"; + try { + const config = await loadConfig(resolveConfigPath()); + if (config.governance?.audit?.log_file) logFile = config.governance.audit.log_file; + } catch { + /* default */ + } + const { verifyAuditChain } = await import("../audit.js"); + const { readFile } = await import("node:fs/promises"); + let content = ""; + try { + content = await readFile(resolve(process.cwd(), logFile), "utf-8"); + } catch { + console.log(`${c.dim}no audit log at ${logFile}${c.reset}`); + return true; + } + const r = verifyAuditChain(content); + if (r.ok) { + console.log( + `${c.green}✓ audit chain intact${c.reset} ${c.dim}${r.entries} entries${c.reset}`, + ); + return true; + } + console.error( + `${c.red}✗ audit chain BROKEN at entry ${r.brokenAt}: ${r.reason}${c.reset} ${c.dim}(verified ${r.entries} entries before the break)${c.reset}`, + ); + return false; + } + // Parse --limit N let limit = 20; const limitIdx = args.indexOf("--limit"); diff --git a/src/governance-middleware.ts b/src/governance-middleware.ts index 1d37ae79..2fb9268d 100644 --- a/src/governance-middleware.ts +++ b/src/governance-middleware.ts @@ -130,6 +130,22 @@ export async function withGovernance( } } + // Fail-closed auditability for DESTRUCTIVE ops: persist an authorization entry + // BEFORE executing and refuse if it can't be written. The post-execution + // success log alone is fail-open (the op would run unlogged if the audit + // append failed) — this closes that gap for the operations that matter most. + if (context.destructive) { + const logged = await logAuditEvent(governanceConfig, { + operation: context.operation, + environment: governanceConfig.environment, + success: true, + metadata: { ...context.metadata, phase: "authorized" }, + }); + if (!logged) { + throw new Error("audit-log unavailable; refusing destructive operation (fail-closed)"); + } + } + // Execute the operation let error: string | undefined; let result: T;