Blog

A tamper-evident audit log for AI agent actions: hash chains, checkpoints and their limits

How Neurouter records every MCP tool call in a hash-chained log with HMAC checkpoints, how to verify it with 40 lines of code you control, what redaction and retention do, what an attacker with database access can still do, and how it relates to EU AI Act, ISO 27001 and SOC 2 logging.

Neurouter team · Published · Markdown · Feed

When an AI agent changes something in your systems, you'll be asked three questions: what happened, on whose behalf, and how do you know the record is complete and unaltered? Ordinary application logs answer the first two. The third needs design, because the people who can change a database include the people whose actions you may need to examine.

Neurouter's audit log is built to make tampering detectable, to get the evidence out of the database it protects, and to be explicit about what it can't prove. We say tamper-evident, never tamper-proof. This post explains the construction, shows how to check it without our code, and maps it, carefully, to the logging expectations in the EU AI Act, ISO/IEC 27001 and SOC 2.

What one record contains

Every tool call through the gateway produces one row: time, user, agent, OAuth client or API key, client name and version, protocol version, server and tool, the decision (allowed; denied with a reason; approval pending, approved, denied or timed out), the input parameters after redaction, output size and hash, status, latency, error, trace ID and session. Tool searches, admin and configuration changes, sign-ins and verification runs are recorded in the same log.

Audit event detail with redacted input parameters, output hash and hash-chain fields
An audit event in the live demo (simulated data): who, which agent and client, the decision, the redacted input, the output size and hash, and the row's place in the hash chain.

Redaction happens before hashing

Tool arguments contain secrets surprisingly often. Neurouter applies redaction rules before a row is stored or hashed, so the chain covers exactly what's stored, and a redacted value can't be found by search later. The built-in rules match sensitive key names (password, token, api_key, authorization, cookie, session, iban and similar) and value patterns: JWTs, Bearer headers, PEM blocks, AWS access key IDs, GitHub and Slack tokens, Neurouter's own nr_ tokens, and card numbers that pass a Luhn check. An e-mail rule exists but is off by default. A matched key becomes {"$redacted": "<rule>"}; a partial match inside a string becomes [REDACTED:<rule>]. Admins can add their own rules.

Outputs are stored as their size and a SHA-256 hash of the canonical JSON by default, so you can later prove that a given output was the one returned without keeping it. Storing full outputs (redacted, up to 64 KiB per call by default) is an opt-in setting.

Pattern-based redaction has two failure modes, and you'll meet both. It misses secrets in shapes it doesn't know, such as a password passed in a field called q. And it over-matches: in our own test run, a settings change was recorded with "sessions": {"$redacted": "sensitive-key"} because the key name contains session. Review the rules against the tools you actually expose.

The chain

Rows get a contiguous sequence number and are linked by hash:

genesis_prev = sha256("neurouter-audit-genesis:" + install_id)
entry_body   = JCS({ seq, id, ts, kind, …, session_id, ip, user_agent })   # 36 fields, nulls explicit
hash(n)      = sha256( bytes(prev_hash) ‖ 0x1E ‖ utf8(entry_body) )

JCS is RFC 8785 canonical JSON, so the hash doesn't depend on key order or on how a database returns JSON. There's one chain per deployment, across all replicas: events are queued in memory and written in batches (every 200 ms or 200 events) under a PostgreSQL advisory lock, or a write transaction on SQLite, which assigns seq and computes the hashes.

Changing a field in any row changes its hash, which breaks the link from the next row. Deleting a row leaves a gap in seq.

Checkpoints

A chain alone doesn't stop someone with database write access: they can edit a row and recompute every hash after it. So Neurouter periodically writes a checkpoint that seals the current head:

mac_key    = HKDF-SHA256(KEK, salt = "", info = "neurouter:audit-checkpoint-mac")
checkpoint = { seq, hash, kind, key_id, mac = HMAC-SHA256(mac_key, "ckpt|seq|hash|kind") }

The KEK is one of your key-encryption keys (NEUROUTER_MASTER_KEYS), which never live in the database. A checkpoint is written once 10,000 rows or 5 minutes have passed since the last one (checked every minute), before every key rotation and before every retention cut. Without the KEK, a forger can recompute hashes but not MACs, so a rewritten history stops matching at the next checkpoint.

"Signed checkpoint" means an HMAC, a symmetric MAC, not a public-key signature. Verifying one requires the same key material that creates it, so you can't hand a checkpoint to an outside party and have them verify it without trusting them with a secret derived from your KEK. Keep retired KEKs configured for as long as you want to verify the checkpoints they sealed.

Verifying it

In the console, Audit log → Verify integrity recomputes the chain over the retained log and checks every checkpoint. Through the API, an Auditor or Admin starts a job:

POST /api/audit/verify
Content-Type: application/json

{ "from": "2026-11-01T00:00:00Z", "to": "2026-11-25T00:00:00Z" }

Both fields are optional; without them the whole retained log is checked. The response is 202 {"jobId": "…"}; poll GET /api/jobs/:id. To test it, we edited the action column of one row directly in a local SQLite database and ran it again:

{ "ok": false, "checked": 2, "firstSeq": 1, "lastSeq": 8, "checkpointsVerified": 0,
  "brokenAt": { "seq": 3, "reason": "hash_mismatch",
                "expected": "0508a0fa…5182", "actual": "1cffc100…7835" } }

reason is one of hash_mismatch, broken_link, gap, bad_checkpoint_mac or checkpoint_mismatch. Each verification run is itself written to the log.

Audit chain verification dialog reporting every entry verified
The Verify dialog in the live demo. The entry count and duration come from simulated data and are not a benchmark.

Offline, with your own code

You shouldn't have to trust our verifier to trust our log. The NDJSON export (Export in the console, or GET /api/audit/export?format=json&from=…&to=…, up to 31 days per request) and the audit webhook carry every chained field plus prev_hash and hash; the webhook also sends checkpoints as {"type":"checkpoint", …} lines. This script uses only Node.js built-ins and shares no code with Neurouter:

// node verify-audit.mjs export.ndjson [KEK_BASE64]
import { createHash, createHmac, hkdfSync } from 'node:crypto';
import { readFileSync } from 'node:fs';

const FIELDS = ['seq', 'id', 'ts', 'kind', 'request_id', 'user_id', 'agent_id', 'api_key_id',
  'oauth_client_id', 'client_name', 'client_version', 'protocol_version', 'client_era', 'server_id',
  'tool_id', 'tool_name', 'action', 'target_type', 'target_id', 'decision', 'decision_reason',
  'status', 'params_redacted', 'changes', 'output_size', 'output_hash', 'output_full', 'latency_ms',
  'upstream_latency_ms', 'error_code', 'error_message', 'trace_id', 'span_id', 'session_id', 'ip',
  'user_agent'];

// RFC 8785 for the values Neurouter stores (strings, integers, booleans, null, objects, arrays)
const jcs = (v) => v === null || typeof v !== 'object' ? JSON.stringify(v)
  : Array.isArray(v) ? `[${v.map(jcs).join(',')}]`
  : `{${Object.keys(v).sort().map((k) => `${JSON.stringify(k)}:${jcs(v[k])}`).join(',')}}`;

const rowHash = (r) => {
  const entry = Object.fromEntries(FIELDS.map((f) => [f, f === 'ts' ? r.ts_ms : (r[f] ?? null)]));
  return createHash('sha256').update(Buffer.from(r.prev_hash, 'hex'))
    .update(Buffer.from([0x1e])).update(jcs(entry), 'utf8').digest('hex');
};

const lines = readFileSync(process.argv[2], 'utf8').split('\n').filter(Boolean).map((l) => JSON.parse(l));
const rows = lines.filter((x) => x.type !== 'checkpoint').sort((a, b) => a.seq - b.seq);
const checkpoints = lines.filter((x) => x.type === 'checkpoint');
const bySeq = new Map(rows.map((r) => [r.seq, r]));

for (const [i, r] of rows.entries()) {
  const prev = rows[i - 1];
  if (prev && r.seq !== prev.seq + 1) throw new Error(`gap before seq ${r.seq}`);
  if (prev && r.prev_hash !== prev.hash) throw new Error(`broken link at seq ${r.seq}`);
  if (rowHash(r) !== r.hash) throw new Error(`hash mismatch at seq ${r.seq}`);
}

const kek = process.argv[3] && Buffer.from(process.argv[3], 'base64');
const macKey = kek && Buffer.from(hkdfSync('sha256', kek, Buffer.alloc(0), 'neurouter:audit-checkpoint-mac', 32));
for (const c of checkpoints) {
  const r = bySeq.get(c.seq);
  if (r && r.hash !== c.hash) throw new Error(`checkpoint ${c.seq} does not match the row hash`);
  if (macKey && createHmac('sha256', macKey).update(`ckpt|${c.seq}|${c.hash}|${c.kind}`).digest('hex') !== c.mac)
    throw new Error(`bad MAC on checkpoint ${c.seq}`);
}
console.log(`ok: ${rows.length} rows (seq ${rows[0]?.seq}–${rows.at(-1)?.seq}), ${checkpoints.length} checkpoints`);

We ran it against exports from Neurouter 0.1.1: it accepted an untouched export and a checkpoint with the right KEK, and rejected a copy with one field changed (hash mismatch at seq 3) and the checkpoint under a wrong key (bad MAC on checkpoint 5). Two caveats: the export doesn't include the install ID, so this checks the continuity of the range you exported rather than the link back to genesis; and the shortcut JCS above is correct for the values Neurouter stores, not for arbitrary floating-point JSON. A packaged verifier is on our list; this script is the specification in the meantime.

The threat model

Someone…Detected?
edits a row in the databaseYes: hash_mismatch
edits a row and recomputes every later hashYes, at the next checkpoint, unless they also hold your KEK
deletes rows in the middleYes: gap
deletes the newest rows, after the last checkpointNot from the database alone. Only a copy outside it shows what's missing
deletes the log and the checkpointsOnly external copies help
holds the database and the KEKThey can rewrite history; only external copies help

The conclusion is the same in every bad case: send the events somewhere your database administrators don't control. The webhook sink posts NDJSON batches signed with X-Neurouter-Signature (HMAC-SHA256 over timestamp and body); the OpenTelemetry sink exports events and checkpoints as OTLP logs to your SIEM.

One more property to know: writes are asynchronous. A tool call doesn't wait for its own row to commit. If the queue of unwritten events reaches 10,000, new tool calls are refused until it drains (fail-closed is the default and a setting), and the depth is exported as neurouter_audit_queue_depth. A crash can lose events still in the queue, which is normally well under a second's worth.

Retention without breaking the chain

Retention defaults to 90 days. Once a day, the retention job writes a retention_cut checkpoint at the last row it will delete, archives those rows when AUDIT_ARCHIVE_URL is set (local file, S3, Google Cloud Storage or Azure Blob; gzip NDJSON per UTC day plus a manifest with the file's SHA-256 and the checkpoint), and only then deletes them. If the upload fails, nothing is deleted. The remaining log verifies from the cut checkpoint. AUDIT_DATABASE_URL puts the audit log in its own database.

What this helps with, and what it doesn't

No log makes an organization compliant. Here's how this one relates to the texts auditors will cite; our fuller mapping is on the compliance page.

  • EU AI Act. For high-risk AI systems, Regulation (EU) 2024/1689 requires that they "technically allow for the automatic recording of events (logs) over the lifetime of the system" (Art. 12), and that providers (Art. 19) and deployers (Art. 26(6)) keep those logs, to the extent they control them, "for a period appropriate to the intended purpose of the high-risk AI system, of at least six months", unless other law says otherwise. If you're in scope, Neurouter's 90-day default is too short: raise it or archive. Whether a system is high-risk depends on its use, and the Digital Omnibus on AI moved the application date for stand-alone high-risk systems to 2 December 2027. A gateway log covers the tool calls an AI system makes; it isn't a complete Article 12 log of the system.
  • ISO/IEC 27001:2022. Annex A includes a logging control (8.15). A verifiable log with defined retention and an off-database copy is the kind of evidence an auditor samples for it. The control, and how you meet it, is yours.
  • SOC 2. A SOC 2 report is an auditor's opinion on your controls against the AICPA's Trust Services Criteria. Agent activity records and verification runs are evidence for the monitoring and logical-access criteria; they aren't controls by themselves.

Known gaps

  • Checkpoints aren't anchored outside your infrastructure yet (for example to a WORM bucket or an RFC 3161 timestamping service); your SIEM copy is the anchor today.
  • The KEK is configured through environment variables; external secret managers aren't supported yet.
  • The log sees tool calls, not model inputs and outputs that never become a call.
  • The gateway records what it saw. "Status ok" means the upstream server said so.

Try it

Open the audit log and run Verify integrity in the live demo (simulated data, in your browser), or read the implementation in apps/server/src/audit on GitHub. Operational details are in the audit log documentation.