Audit Log

adk-auth (feature signed-audit) writes a signed, verifiable audit log. Each replica appends records to its own log; the log signs checkpoints of a Merkle tree over the records, and anyone holding the public key can verify an export offline, with adk_auth::signed_audit::verify or adk-rust audit verify.

LayerMechanismDetects
RecordAuditRecord, canonicalized with RFC 8785 (JCS)Any change to a field
Chainprev_hash is the previous record's leaf hashA deleted, inserted, or reordered record
TreeRFC 9162 Merkle tree, leaf SHA-256(0x00 ‖ record), with inclusion and consistency proofsA record outside the signed tree; a rewritten prefix
CheckpointC2SP tlog checkpoint in a signed note, Ed25519A rewrite by anyone without the signing key
AnchorOptional publication of checkpoints outside the logA rewrite by the key holder

Checkpoint notes use the format and key encoding of Go's golang.org/x/mod/sumdb/note, so standard signed-note verifiers and witnesses accept them.

Setup

[dependencies]
adk-auth = { version = "3.0.0", features = ["signed-audit"] }
adk-core = "3.0.0"
adk-session = { version = "3.0.0", features = ["postgres"] }
use std::sync::Arc;
use std::time::Duration;

use adk_auth::signed_audit::{AuditLog, Ed25519Signer, FileCheckpointAnchor};
use adk_core::audit_log::{AuditActor, AuditDecision, AuditRecordDraft, AuditRecordKind};
use adk_session::PostgresAuditLogStore;

async fn open_audit_log(instance: &str) -> adk_core::Result<Arc<AuditLog>> {
    let store = PostgresAuditLogStore::new("postgres://localhost/app").await?;
    store.migrate().await?;

    let key = std::fs::read_to_string("/etc/adk/audit.key").expect("signer key");
    let signer = Arc::new(Ed25519Signer::from_note_key(key.trim()).expect("valid key"));

    let log = AuditLog::builder(Arc::new(store), format!("audit/{instance}"), signer)
        .origin(format!("audit.example.com/{instance}"))
        .checkpoint_every(256)
        .checkpoint_interval(Duration::from_secs(60))
        .anchor(Arc::new(FileCheckpointAnchor::new("/mnt/worm/audit-checkpoints.jsonl")))
        .open()
        .await?;
    let log = Arc::new(log);
    log.spawn_checkpoint_timer();

    log.append(
        AuditRecordDraft::new(AuditRecordKind::ToolCall, "transfer")
            .actor(AuditActor::default())
            .decision(AuditDecision::Allowed)
            .args_digest(adk_auth::signed_audit::json_sha256(&serde_json::json!({ "amount": 50 }))?),
    )
    .await?;
    Ok(log)
}

AuditLog implements AuditSink, so ProtectedTool, ScopedTool, and AuthMiddleware write their access decisions into the signed log with no other change:

use std::sync::Arc;

use adk_auth::{AccessControl, AuthMiddleware};
use adk_auth::signed_audit::AuditLog;

fn middleware(access: AccessControl, log: Arc<AuditLog>) -> AuthMiddleware {
    AuthMiddleware::with_audit(access, log)
}

The adapter maps the event type to the record kind, the event's user to actor.onBehalfOf, and the outcome to decision or outcome; the remaining event fields become ext entries.

What the runtime records

Give the runner an audit log and every run records its governed actions — no tool, callback, or plugin needs to write a record itself:

use std::sync::Arc;

use adk_auth::signed_audit::AuditLog;
use adk_core::audit_log::AuditFailureMode;
use adk_core::{Agent, DeclarativePolicy, Result};
use adk_runner::Runner;
use adk_session::SessionService;

fn audited_runner(
    agent: Arc<dyn Agent>,
    sessions: Arc<dyn SessionService>,
    log: Arc<AuditLog>,
) -> Result<Runner> {
    Runner::builder()
        .app_name("bank")
        .agent(agent)
        .session_service(sessions)
        .tool_policy(Arc::new(
            DeclarativePolicy::builder()
                .name("bank-v1")
                .allow("search")
                .require_approval("transfer", "transfers need a person")
                .build(),
        ))
        .audit_log(log)
        .audit_failure_mode(AuditFailureMode::Block)
        .build()
}

audit_log takes any AuditRecorder; AuditLog is one, FileAuditRecorder appends each record to a file as one line of JSON, and InMemoryAuditRecorder keeps drafts in memory for tests. FileAuditRecorder numbers the file's records from 0 without a gap, also when several processes append to one file, cuts a line a crash left unfinished, and reads the file back with FileAuditRecorder::read; its records are durable but neither hash-chained nor signed, which AuditLog adds. The runner installs the trail on each run's RunConfig::audit (set it there to audit a single run) and attaches it to the runner's kill switch.

EventWherekindactiondecision / outcomepolicyRef
Tool call allowedGoverned path, before executetool_callTool nameallowedtool_policy[:<name>], confirmation, or absent with no policy
Tool call deniedGoverned pathtool_callTool namedenied / not_runtool_policy[:<name>], guardrail, governance (frozen, also while the call waited for a decision), confirmation
Tool call held for approvalGoverned pathtool_callTool nameapproval_required / not_runtool_policy[:<name>] or confirmation
Approval decision appliedGoverned path, before the call's decisionapprovalTool nameapproved or rejected—
Approver decisionStoreApprovalService::with_audit, before the decision is storedapprovalTool nameapproved (approve, edit) or rejected (reject, respond)—
Freeze, unfreezeGovernanceControlgovernancegovernance.freeze, governance.unfreeze— / succeeded—
Run resumed after a freezeDurableWorker, before the claim adds the resume notice to a freeze-parked run's sessiongovernancegovernance.run_resumed— / succeeded—
Payment decisionPayment tools (ACP checkout, AP2 mandate)paymentpayment.create_checkout, payment.complete_checkout, payment.execute_paymentallowed, approved, denied, approval_required, rejectedpayment_policy
Payment outcomePayment tools, after the backend returnspaymentAs abovesucceeded or failedpayment_policy
Outcome unknownAgents (timeout, panic, replay of a begun call), runner (cancelled run)tool_callTool nameoutcome_unknown—
Tool call answered before authorizationLlmAgent, when a BeforeToolCallback, a run-wide before_tool plugin, or an enhanced plugin's ShortCircuit answers the calltool_calltool.short_circuit— / not_run—

Every record names the acting agent and the subject it acts for in actor: the agent id urn:adk:agent:<app>/<agent>, onBehalfOf the session's user, and the invocation id. Records never carry arguments: argsDigest is sha256:<hex> of the call's final arguments (the cart for a payment). ext holds the call ID, the tool's declared effect, the session ID, the tool's toolSource and declarationDigest (its ToolOrigin, on governed records and short-circuit records whose tool is known), the evidenceDigests of a call held with evidence and of the approval decisions made on it, the policy's reason for a denial or hold, an approval's source (call_id, fingerprint, approval_store, handler, handler_timeout), a short-circuited call's toolName, agentName, and answeredBy (before_tool_callback, invocation_hook, enhanced_plugin), an unknown outcome's cause (interrupted, began_without_outcome, cancelled), and a payment's transaction ID, merchant, total, and the guardrails that spoke. A guardrail screen's refusal text can quote the arguments, so it stays out of the record.

DeclarativePolicyBuilder::name names a policy, and a custom ToolPolicy names itself by overriding policy_ref; records then cite it as tool_policy:<name>.

Failure mode

AuditFailureModeA record cannot be written
Block (default)The action does not happen: the governed call is not executed and the run ends with audit.record_failed, as it does when a call a callback or plugin answered cannot be recorded; an allowed payment is refused before the backend is reached; unfreeze_recorded leaves execution frozen
WarnThe failure is logged and the action proceeds without a record

A record that follows an action that already happened cannot refuse it: a freeze holds even when its record fails, and a payment's outcome record, a refusal's record, and a cancelled run's outcome-unknown records are logged on failure.

An approver's decision through the approval service names the approver as the actor, with the delegator they acted for in delegationChain, and carries approvalId, approvalAction, and the digest of any edited arguments; under Block a decision that cannot be recorded is refused. When the run later applies the stored decision, the governed path writes its own approval record with source approval_store.

GovernanceControl::freeze_recorded and unfreeze_recorded take the acting administrator and wait for the record; on a mirrored control they write the shared governance store, as freeze_replicated and unfreeze_replicated do, with the administrator as the issuer; the POST /api/admin/freeze and unfreeze endpoints use them with the authenticated user, and an unrecordable unfreeze answers 503. freeze and unfreeze record in the background.

Spend-ledger commits are not recorded: the spend ledger is itself the durable record of spend, a model call commits on every turn, and a refused reservation ends the run with ResourceExhausted before any action happens.

Records

FieldSet byMeaning
vwriterSchema version, 1
logIdwriterThe replica's log
seqwriterPosition, from 0 with no gaps
tswriterAppend time, from the configured Clock
prevHashwriterLeaf hash of the previous record; absent for seq 0
actorcallerAgent id, tenant, instance, onBehalfOf, delegation chain, invocation id — AuditActor::new(&ActingContext, invocation_id)
kindcallertool_call, approval, governance, payment, access, authentication, configuration, key_rotated, or any other name
actioncallerTool name or operation
argsDigestcallersha256:<hex> of the canonical arguments (json_sha256)
decisioncallerallowed, denied, approval_required, approved, rejected
outcomecallersucceeded, failed, outcome_unknown, not_run
policyRefcallerThe deciding policy rule or version
payloadRefcallerDigest of a payload stored outside the log
extcallerExtension fields; integers must stay within ±2^53 (I-JSON)

Personal and large data

Keep personal data and large payloads out of records. Store the payload in a separate store, ideally encrypted under a per-subject key, and record only its digest in payloadRef:

  1. Compute json_sha256(&payload) and store the payload under that digest.
  2. Append the record with payload_ref(digest).
  3. To erase a subject, delete the payload or destroy its key (crypto-shredding). The record, the chain, and every checkpoint stay verifiable because they hold only the digest.

AuditLogStore::prune(log_id, before_seq) drops record bodies older than a position and keeps their leaf hashes, so a pruned log still verifies; the report counts pruned entries.

Subjects in records

Records name the subject an agent acts for in actor.onBehalfOf and actor.delegationChain. Two mechanisms keep those names from outliving a subject's erasure:

MechanismCoversEffect
adk_core::subject::PseudonymousRecorderRecords written from now onWraps the recorder and replaces covered subjects (visitors by default; for_every_subject() adds humans and services) with their SubjectRegistry pseudonym, psn:…. Erasure deletes the pseudonym, so the records stay and no longer lead back to the person
AuditLogStore::redact(log_id, seqs) with adk_core::subject::AuditLogSubjectDataRecords already written with a subject's idThe adapter finds every record whose actor names the subject's id (any kind but an agent) and redacts its body; leaf hashes stay, so checkpoints and proofs verify, and the report counts redacted entries as pruned

Every store backend implements redact, proven by the conformance case redaction_keeps_hashes. adk_auth::PseudonymousAuditSink does the same for adk_auth::AuditEvent: it pseudonymises user and on_behalf_of and drops ip_address before the wrapped sink chains the event.

use std::sync::Arc;

use adk_core::audit_log::{AuditTrail, InMemoryAuditRecorder};
use adk_core::subject::{InMemorySubjectRegistry, PseudonymousRecorder};

let registry = Arc::new(InMemorySubjectRegistry::new());
let recorder = PseudonymousRecorder::new(Arc::new(InMemoryAuditRecorder::new()), registry);
let trail = AuditTrail::new(Arc::new(recorder));

Checkpoints and keys

A checkpoint is signed every checkpoint_every records (default 256), on the first append after checkpoint_interval (default 60 seconds) has passed since the last checkpoint, on checkpoint(), and on AuditSink::flush and AuditRecorder::seal, which sign the records not yet signed. spawn_checkpoint_timer signs idle logs on the interval.

Who seals the logWhen
Harness::closeAfter the runner closes: the REPL, code and goal of adk-rust, and the REPL and goal of a HarnessLauncher app, when they end
HarnessLauncher::run_serve_directlyOnce the server, and on up the kernel, have stopped: serve and up of adk-rust and of a HarnessLauncher app after Ctrl-C or SIGTERM

Until a checkpoint signs them, adk-rust audit verify reports a log's records as unanchored and the result INVALID. A process killed before its log was sealed leaves its last records unsigned; the next process on the same log signs them with its own checkpoints.

audit.example.com/replica-1
1024
zwu4qZLzhb2lbYJkhqUVd7RS2SAPmggiFWFGeL5A3gc=

— audit.example.com EO0LDO4YVlTf02uEtzCDXE+PCs0w3LJgo57v2QVSBz+Lns0lo...
TaskHow
Generate a keyadk-rust audit keygen audit.example.com --out audit writes audit.key (mode 0600 on Unix, a DACL granting only its owner access on Windows) and audit.vkey
Load a keyEd25519Signer::from_note_key(...); implement AuditSigner to sign with a KMS or HSM
Rotate a keylog.rotate_signer(next, actor) appends a key_rotated record naming both verifier keys and signs the next checkpoint with both
Trust after rotationA verifier that trusts the old key learns the new one from the dual-signed checkpoint and retires the old one for later checkpoints

CheckpointAnchor publishes each checkpoint outside the operator's control. The crate ships FileCheckpointAnchor, which appends checkpoints to a file on a write-once mount or another host; implement the trait for a witness, an RFC 3161 timestamp authority, or a transparency log. An anchor failure is logged and does not fail the append.

Stores

AuditLogStore persists what the writer computes: entries (canonical record and leaf hash), complete-subtree hashes, and signed checkpoints. It never computes hashes itself.

BackendTypeFeature
In memoryadk_core::audit_log::InMemoryAuditLogStoreadk-core
SQLiteadk_session::SqliteAuditLogStoresqlite
PostgreSQLadk_session::PostgresAuditLogStorepostgres
Redisadk_session::RedisAuditLogStoreredis
MongoDBadk_session::MongoAuditLogStoremongodb
Neo4jadk_session::Neo4jAuditLogStoreneo4j
Firestoreadk_session::FirestoreAuditLogStorefirestore
BackendHow two writers on one log_id are serialized
SQLiteBEGIN IMMEDIATE takes the write lock before the size is read
PostgreSQLSELECT ... FOR UPDATE on the log's size row
RedisOne Lua script compares the first seq with the size and writes entries, nodes, and size together
MongoDBA conditional update on the log document claims the size and parks the batch; a writer that finds a parked batch completes it first
Neo4jA transaction write-locks the log node before it reads the size
FirestoreA read-write transaction reads the log document and creates entries with an Exists(false) precondition

Give every replica its own log_id; no shared sequencer is needed. append is a compare-and-swap on the log size, so a second writer on one log_id gets audit_log.seq_conflict instead of forking the log. A second checkpoint at one size with a different root is refused with audit_log.checkpoint_conflict. Every backend passes audit_log_store_conformance_tests! (see Durable Stores).

Verifying

Export a log and verify it with the keys you trust:

adk-rust audit export --database-url postgres://localhost/app --log-id audit/replica-1 --out audit.jsonl
adk-rust audit verify audit.jsonl --key "$(cat audit.vkey)" --checkpoints /mnt/worm/audit-checkpoints.jsonl

audit verify and audit keygen need the audit feature of adk-cli, which is on by default; audit export needs audit-sql. audit verify exits 0 when the log verifies and 1 when it does not; --json prints the report as JSON.

use adk_auth::signed_audit::{AuditExport, NoteVerifier};

fn check(export_jsonl: &str, verifier_key: &str) -> bool {
    let export = AuditExport::from_jsonl(export_jsonl).expect("valid export");
    let trusted: NoteVerifier = verifier_key.parse().expect("valid verifier key");
    let report = export.verify(&[trusted]);
    println!("{report}");
    report.is_valid()
}
FailureRaised when
leaf_hash_mismatchA record's text does not hash to its leaf hash (a flipped byte)
chain_brokenprevHash does not match the previous leaf (an edited record with a recomputed hash, a deletion, a reorder)
sequence_brokenEntries are missing, duplicated, or out of order
root_mismatchA checkpoint's root differs from the tree over the records
truncatedA checkpoint covers more records than the export holds
forkTwo signed checkpoints of one size disagree, such as a rewritten log against its anchored checkpoints
untrusted_checkpointNo valid signature from a trusted, unretired key
rotation_not_dual_signedThe checkpoint after a key_rotated record lacks either key's signature
not_canonical, malformed, log_id_mismatch, origin_mismatch, unsupported_versionThe export is not a well-formed log
unanchoredRecords exist but no checkpoint signs them

Note: Records after the last checkpoint are reported as unsignedTail. Removing them is not detectable until a later checkpoint or an anchor covers them; a short checkpoint_interval and an anchor bound that window. A key holder can rewrite and re-sign the whole log; anchored checkpoints expose that as a fork.

AuditLog::inclusion_proof and AuditLog::consistency_proof return RFC 9162 proofs, and signed_audit::merkle::verify_inclusion and verify_consistency check them, so a client can confirm one record, or that a newer checkpoint extends an older one, without the full log.