Skip to main content

Overview

The audit log records what agents do. By default nothing stops someone with database write access from editing or deleting a row afterwards. Turn on the hash chain and every new row stores the hash of the row before it, so an edit, a deletion or a reorder shows up the next time you verify. It is off by default and additive. Rows written before you enable it are left alone and are reported as unchained.

What gets recorded

With agents.auditAll on (the default), every decision about a known agent writes one row, allowed or denied. That includes a request from an agent that is revoked or expired. Those rows have result: "denied" and a stable reason code, so you can filter for them: The reason string on the returned result is unchanged (for example Agent "deploy-bot" is revoked). The row stores the short code. The row never stores the token. It stores the action, resource, arguments, IP and user agent, like any other row, and it goes through the same writer, so with tamperEvident on it joins the agent’s chain like any other row. Policy decisions from theauth.policy.evaluate() write a row too, with result: "escalated" when the outcome is escalate. Delegation and approval events write rows as well (delegation.create and delegation.revoke, and the approval request and answer, which carries the approver_id). Every row names what happened in its event column; see event vocabulary. Some denials write no row:
  • Unknown agent id (authorize("no-such-agent")). There is no agent to attach a row or a chain to, and the audit table requires a real agent. Writing rows keyed by arbitrary ids would let a caller fill the table with junk.
  • Unknown token (authorizeByToken with a token that matches no agent). Same reason. Nothing identifies an agent.
  • Blocked by a beforeAuthorize hook. The hook runs before any database work by design. Use onViolation to log these.
  • agents.auditAll: false. No rows are written for any decision, including these.
When no row is written, auditId on the result is an empty string. A failed audit write on one of these denials does not change the outcome. The call still returns allowed: false and does not throw, and auditId is empty. This differs from an allow or a permission denial, where a failed audit insert propagates as an error. A caller holding a revoked token can produce one row per attempt. Use audit.cleanup({ retentionDays }) and your gateway’s rate limiting if that matters for you.

Fields on each row

Besides the action, resource, arguments and result, a row can carry: input_provenance is filled when you supply labels to the tool guard (see taint guard) or pass it to recordAuditEvent. The SDK does not infer provenance by itself, so an empty value does not mean the inputs were trusted.

Write failures

Audit writes from recordAuditEvent (policy decisions, delegation, approval and SCIM events) are best effort. They do not throw and do not fail the operation they describe. Each failure is counted: read the total with getAuditWriteFailures(db), or pass audit.onAuditError to be called with { error, pendingFailures, totalFailures }. The next successful write is preceded by an audit.write_failed row that records how many writes were lost, so a gap in the log is visible.

How the chain works

There is one chain per agent. Each row gets chain_seq (1, 2, 3…), prev_hash and hash. The hash is SHA-256 over the canonical JSON (sorted keys) of the row fields, the sequence number and prev_hash. With hmacKey it is HMAC-SHA256 instead. Why per agent and not per tenant or global: writers for different agents never contend, a replay is exactly one chain, and a single unique index on (agent_id, chain_seq) is enough to stop a fork. Concurrent writers do not need a transaction or a lock. A writer reads the chain head, computes the next hash and inserts. If another writer took that sequence number first, the unique index rejects the insert and the writer re-reads the head and retries. This behaves the same on SQLite, Postgres, MySQL and D1. Writers inside one process also queue per agent, so retries only happen across processes. Timestamps are hashed at one-second precision, because that is what the SQLite column stores.

Pseudonymized ids and erasure

Rows with hash_version 2 hash keyed pseudonyms of user_id, agent_id, subject_id, actor_id and approver_id instead of the raw ids, and store the pseudonyms on the row. The key is audit.hmacKey when set, otherwise a random secret stored in theauth_audit_secrets. GDPR erasure (deleteUser) can then blank or replace the raw ids and the row hash still verifies. Rows written before this format (hash_version null or 1) hash the raw ids, so rewriting them would break the hash. For those rows, and for rows deleted outright, erasure appends an audit.erasure record to the chain naming each affected row with its stored hash, and signs each entry with the audit key. verifyAuditChain reports them in an erased count instead of as tampering. A record without a valid signature, or one that is not on the chain, is reported as erasure_forged or erasure_unchained and excuses nothing. A pseudonym is linkable by whoever holds the key, so this is pseudonymization, not anonymization. Destroying the key is not implemented. The erasure path rewrites rows with SQLite-specific statements.

Input provenance

Each audit row can say where the inputs of the call came from. Declare the sources on the request context and authorize, authorizeByToken and policy.evaluate record them in input_provenance:
The kinds are user_message, tool_output, retrieved_document and agent. Only a hash of the content is stored: an HMAC-SHA-256 under a subkey derived from the audit key (pass content and it is hashed and dropped, or pass a hash you computed), plus the optional id. The record is { sources: [{ kind, id?, hash, hv? }], keys: ["<kind>:<hash>"] }, where hv is 2 for the keyed hash and absent on older rows with a plain SHA-256 and merges with the taint labels when a policy supplies them. On version 2 rows it is covered by the chain hash. For tools, guardTool(theauth, { inputs: (args) => [...] }, tool) does the same on every call. Provenance is read only from the trusted context, never from tool arguments. The argument name inputProvenance is reserved (see the reserved key rules in src/audit/reserved.ts), so an argument cannot plant or forge a source. Filter on it with the audit query:
kind, hash and content can be combined or used alone. content is hashed by the server with the audit key and matches both keyed and older plain hashes. hash must be 64 lowercase hex characters, exactly as stored. See input provenance for the HTTP header, gateway, MCP and CLI forms. Verification, replay and export carry the record unchanged.

Rotating pseudonyms

By default a subject has one stable pseudonym, which the key holder can link across all time. Set audit.pseudonymRotation to change that:
Each period (whole days since the epoch) gets its own random secret in theauth_audit_secrets, and the pseudonyms on a row are keyed by that secret and stamped with the period number. One subject therefore has a different pseudonym in every period. The period secret is not derived from audit.hmacKey, because that would let the key holder recompute every period. The first write of a new period deletes the secrets older than retainPeriods periods behind it (default 1). After that nobody, the operator included, can link a subject across those periods. shredPseudonymPeriods(db, currentPeriod, retainPeriods) does the same on demand. The chain hash covers the stored pseudonyms, not the secrets, so shredding keeps the chain valid, and verifyAuditChain and exports work as before. The tradeoff is that a raw id still present on a row of a shredded period can no longer be compared with its pseudonym. Rows written before rotation was turned on keep their stable pseudonym.

Migration

createTables adds the three nullable columns and the unique index to an existing theauth_audit_logs table. The statements are idempotent (Postgres uses ADD COLUMN IF NOT EXISTS, SQLite and MySQL tolerate “already exists”). If you run with skipMigrations: true, apply this yourself:
Without the unique index, concurrent writers can fork a chain.

Verify

Break reasons: hash_mismatch (a row was edited), seq_gap (a row was deleted), prev_hash_mismatch (rows were reordered or relinked), missing_hash, truncated, pseudonym_mismatch (a raw id was edited after the row was written), truncated_prefix (the oldest rows are gone with no signed anchor), anchor_mismatch, erasure_unchained, erasure_forged and version_downgrade (see audit receipts). The result also reports unchained and erased counts. Retention cleanup (audit.cleanup) writes a signed audit.checkpoint row recording where the chain was cut, so removing the oldest rows on purpose does not read as a break. For a chain cut some other way, run theauth.audit.checkpoint() once to anchor its current start. Deleting the newest rows of a chain leaves a shorter chain that still verifies. To catch that, keep a chain head somewhere the database owner cannot edit (an export manifest works) and pass it back:

Replay an agent

The timeline merges audit rows (action when allowed, decision when denied or rate limited), delegations the agent gave or received, approval requests and answers, and token cost events, ordered by time. Only audit rows are covered by the chain, and each event says whether it is chained. The userId filter applies to audit rows and approvals.

Export for compliance

The manifest holds the SHA-256 of the file, the row count, the range, the chain head per agent, whether the chain verified, and an HMAC signature over all of that. It is signed with audit.hmacKey (or signingKey if you pass one); export fails with NO_SIGNING_KEY otherwise. Check an export later without a database:
Exports are capped at 100,000 rows; narrow the range for more.

CLI

Both exit 1 when the chain is broken. --db <url> overrides DATABASE_URL. The commands never write.

Limits

  • Tail truncation is only detectable against a saved head (see above).
  • Anyone holding hmacKey and database write access can forge a chain. Keep the key outside the database host.
  • Retention cleanup and GDPR erasure remove or rewrite rows. Cleanup leaves a checkpoint row and erasure leaves an audit.erasure record. Rewriting a row in the middle by other means is flagged.
  • A pseudonym is linkable by whoever holds the key (audit.hmacKey or the stored secret).
  • input_provenance records the sources you declare (context.inputs, or the inputs option of guardTool) as kind, id and content hash. The SDK does not infer where an input came from. Hashes written before the keyed hash are plain SHA-256, so short or guessable text in those rows can be confirmed by anyone who guesses it.
  • Under pseudonym rotation, a raw id that is still present in a period whose secret was shredded cannot be checked against its pseudonym. The chain hash is still verified.
  • Audit writes for policy decisions, delegation, approval and SCIM events are best effort. Failures are counted and followed by an audit.write_failed row (with the count and the first and last failure times), but a write that fails is not retried.
Last modified on October 19, 2026