diff --git a/src/audit-export.test.ts b/src/audit-export.test.ts new file mode 100644 index 00000000..e8a2b615 --- /dev/null +++ b/src/audit-export.test.ts @@ -0,0 +1,61 @@ +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { toCef, toSyslog, exportAudit } from "./audit-export.js"; +import type { AuditEvent } from "./audit.js"; + +const ev: AuditEvent = { + timestamp: "2026-06-23T10:00:00.000Z", + agent_id: "agent-1", + agent_name: "Agent One", + operation: "secrets.rotate", + environment: "prod", + success: false, + duration_ms: 42, + error: "denied | because reasons", +}; + +describe("toCef", () => { + it("emits a well-formed CEF header + extensions", () => { + const line = toCef(ev); + assert.ok(line.startsWith("CEF:0|kit|kit|1|secrets.rotate|secrets.rotate|7|")); + assert.match(line, /outcome=failure/); + assert.match(line, /suser=Agent One/); + assert.match(line, /cs1Label=environment cs1=prod/); + assert.match(line, /cn1Label=durationMs cn1=42/); + assert.match(line, /rt=\d+/); + }); + + it("escapes `=` and pipes/newlines in values", () => { + const line = toCef(ev); + // the error contained a pipe + would-be `=`; newlines/`=` are escaped in ext + assert.match(line, /msg=denied \\?\| because reasons/); + assert.ok(!line.includes("denied | because reasons\n")); + }); + + it("ranks success lower (sev 3) than failure (sev 7)", () => { + assert.ok(toCef({ ...ev, success: true }).includes("|3|")); + assert.ok(toCef({ ...ev, success: false }).includes("|7|")); + }); +}); + +describe("toSyslog", () => { + it("wraps the CEF line in an RFC 5424 frame", () => { + const line = toSyslog(ev, "host1"); + assert.ok(line.startsWith("<13>1 2026-06-23T10:00:00.000Z host1 kit - audit - CEF:0|kit|kit|")); + }); +}); + +describe("exportAudit", () => { + it("renders one record per line for each format", () => { + const out = exportAudit([ev, { ...ev, operation: "check", success: true }], "cef"); + const lines = out.split("\n"); + assert.equal(lines.length, 2); + assert.ok(lines[0].includes("secrets.rotate")); + assert.ok(lines[1].includes("|3|")); // second is success + }); + + it("json format round-trips", () => { + const out = exportAudit([ev], "json"); + assert.deepEqual(JSON.parse(out), ev); + }); +}); diff --git a/src/audit-export.ts b/src/audit-export.ts new file mode 100644 index 00000000..4d8cb13b --- /dev/null +++ b/src/audit-export.ts @@ -0,0 +1,66 @@ +/** + * Export audit events in SIEM-friendly formats. + * + * `kit audit export` lets a regulated/air-gapped deployment ship its local + * `.kit-audit.jsonl` into a SIEM. ArcSight **CEF** is the lingua franca; the CEF + * line is commonly carried over syslog, so `--format syslog` wraps each CEF line + * in an RFC 5424 frame. Pure string formatting — no I/O — so it is fully tested. + */ +import type { AuditEvent } from "./audit.js"; + +/** CEF header fields escape `\` and `|`. */ +function cefHeader(value: string): string { + return value.replace(/\\/g, "\\\\").replace(/\|/g, "\\|"); +} + +/** CEF extension values escape `\`, `=`, and newlines. */ +function cefExt(value: string): string { + return value.replace(/\\/g, "\\\\").replace(/=/g, "\\=").replace(/\r?\n/g, " "); +} + +/** + * One ArcSight CEF line per event. + * `CEF:0|kit|kit|||||` + */ +export function toCef(event: AuditEvent, productVersion = "1"): string { + const sev = event.success ? 3 : 7; // failures rank higher for SIEM triage + const sig = event.operation || "operation"; + const header = `CEF:0|kit|kit|${cefHeader(productVersion)}|${cefHeader(sig)}|${cefHeader(sig)}|${sev}`; + + const ext: string[] = []; + const epoch = Date.parse(event.timestamp); + if (Number.isFinite(epoch)) ext.push(`rt=${epoch}`); + ext.push(`outcome=${event.success ? "success" : "failure"}`); + const user = event.agent_name || event.agent_id; + if (user) ext.push(`suser=${cefExt(user)}`); + if (event.environment) ext.push(`cs1Label=environment cs1=${cefExt(event.environment)}`); + if (typeof event.duration_ms === "number") + ext.push(`cn1Label=durationMs cn1=${event.duration_ms}`); + if (event.error) ext.push(`msg=${cefExt(event.error)}`); + + return `${header}|${ext.join(" ")}`; +} + +/** RFC 5424 syslog frame around a message. PRI 13 = facility 1 (user), severity 5 (notice). */ +export function toSyslog(event: AuditEvent, host = "kit"): string { + const ts = event.timestamp || new Date().toISOString(); + // VERSION TIMESTAMP HOSTNAME APP-NAME PROCID MSGID STRUCTURED-DATA MSG + return `<13>1 ${ts} ${host} kit - audit - ${toCef(event)}`; +} + +export type AuditExportFormat = "cef" | "syslog" | "json"; + +/** Render a batch of events in the chosen format, one record per line. */ +export function exportAudit(events: AuditEvent[], format: AuditExportFormat): string { + const lines = events.map((e) => { + switch (format) { + case "cef": + return toCef(e); + case "syslog": + return toSyslog(e); + case "json": + return JSON.stringify(e); + } + }); + return lines.join("\n"); +} diff --git a/src/commands/audit.ts b/src/commands/audit.ts index 8cf8fec1..4d39650d 100644 --- a/src/commands/audit.ts +++ b/src/commands/audit.ts @@ -108,6 +108,30 @@ export async function cmdAudit(): Promise { return false; } + // Sub-sub: kit audit export [--format cef|syslog|json] — emit for a SIEM + if (args[0] === "export") { + const fmt = (flagValue(args, "--format") ?? "cef") as "cef" | "syslog" | "json"; + if (!["cef", "syslog", "json"].includes(fmt)) { + console.error(`${c.red}unknown --format "${fmt}" (use cef | syslog | json)${c.reset}`); + return false; + } + let exportLog = ".kit-audit.jsonl"; + try { + const config = await loadConfig(resolveConfigPath()); + if (config.governance?.audit?.log_file) exportLog = config.governance.audit.log_file; + } catch { + /* default */ + } + const { exportAudit } = await import("../audit-export.js"); + const events = await readAuditLog(exportLog, 1_000_000); + if (events.length === 0) { + console.error(`${c.dim}no audit log at ${exportLog}${c.reset}`); + return true; + } + process.stdout.write(exportAudit(events, fmt) + "\n"); + return true; + } + // Parse --limit N let limit = 20; const limitIdx = args.indexOf("--limit");