Skip to main content

adk_core/
audit_log.rs

1//! Append-only audit log records and the store that holds them.
2//!
3//! An [`AuditRecord`](crate::audit_log::AuditRecord) is one entry in a per-replica log identified by `log_id`. A
4//! writer (`adk_auth::signed_audit::AuditLog`) canonicalizes each record, hashes it into
5//! a Merkle tree, and signs checkpoints of the tree. The
6//! [`AuditLogStore`](crate::audit_log::AuditLogStore) persists the
7//! result and computes nothing itself:
8//!
9//! | Data | Stored as |
10//! |------|-----------|
11//! | Record | Canonical JSON text plus its leaf hash, addressed by `(log_id, seq)` |
12//! | Tree node | Hash of a complete subtree, addressed by `(log_id, level, index)` |
13//! | Checkpoint | A signed note over `(size, root)`, addressed by `(log_id, size)` |
14//!
15//! Each replica writes its own log, so no shared sequencer is needed. `append` is a
16//! compare-and-swap on the log size: a second writer using the same `log_id` gets
17//! `audit_log.seq_conflict` instead of forking the log. Pruning drops record bodies
18//! and keeps their hashes, so signed checkpoints and proofs stay verifiable.
19//!
20//! [`InMemoryAuditLogStore`](crate::audit_log::InMemoryAuditLogStore) is the reference implementation; `adk-session` ships SQLite,
21//! PostgreSQL, Redis, MongoDB, Neo4j, and Firestore ones. Every backend passes the same
22//! conformance suite (`adk_core::audit_log_store_conformance_tests!`, `conformance` feature).
23//!
24//! The runtime writes records through an [`AuditRecorder`](crate::audit_log::AuditRecorder)
25//! wrapped in an [`AuditTrail`](crate::audit_log::AuditTrail), set on
26//! [`RunConfig::audit`](crate::RunConfig::audit): the governed path records every tool and
27//! approval decision, the kill switch its freezes, payment tools their payments, and agents
28//! every call answered with an unknown outcome.
29
30use std::collections::{BTreeMap, HashMap};
31use std::fmt;
32use std::ops::Range;
33use std::str::FromStr;
34use std::sync::Arc;
35
36use async_trait::async_trait;
37use chrono::{DateTime, Utc};
38use serde::{Deserialize, Serialize};
39
40use crate::principal::{ActingContext, AgentId, SubjectRef};
41use crate::{AdkError, ErrorCategory, ErrorComponent, Result};
42
43/// Version of the [`AuditRecord`] schema this crate writes.
44pub const AUDIT_RECORD_VERSION: u32 = 1;
45
46/// A SHA-256 hash, written as 64 lowercase hex characters.
47///
48/// # Example
49///
50/// ```rust
51/// use adk_core::audit_log::AuditHash;
52///
53/// let hash: AuditHash = "00".repeat(32).parse().unwrap();
54/// assert_eq!(hash, AuditHash([0; 32]));
55/// assert_eq!(hash.to_string(), "00".repeat(32));
56/// ```
57#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
58#[serde(try_from = "String", into = "String")]
59pub struct AuditHash(pub [u8; 32]);
60
61impl AuditHash {
62    /// Returns the raw bytes.
63    pub fn as_bytes(&self) -> &[u8; 32] {
64        &self.0
65    }
66}
67
68impl fmt::Display for AuditHash {
69    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70        for byte in self.0 {
71            write!(f, "{byte:02x}")?;
72        }
73        Ok(())
74    }
75}
76
77impl fmt::Debug for AuditHash {
78    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79        write!(f, "AuditHash({self})")
80    }
81}
82
83impl FromStr for AuditHash {
84    type Err = InvalidAuditHash;
85
86    fn from_str(text: &str) -> std::result::Result<Self, Self::Err> {
87        let bytes = text.as_bytes();
88        if bytes.len() != 64 {
89            return Err(InvalidAuditHash(format!(
90                "expected 64 hex characters, got {}",
91                bytes.len()
92            )));
93        }
94        let mut out = [0u8; 32];
95        for (index, pair) in bytes.chunks_exact(2).enumerate() {
96            let digit = |c: u8| match c {
97                b'0'..=b'9' => Some(c - b'0'),
98                b'a'..=b'f' => Some(c - b'a' + 10),
99                _ => None,
100            };
101            match (digit(pair[0]), digit(pair[1])) {
102                (Some(high), Some(low)) => out[index] = (high << 4) | low,
103                _ => {
104                    return Err(InvalidAuditHash(
105                        "expected lowercase hex characters (0-9, a-f)".to_string(),
106                    ));
107                }
108            }
109        }
110        Ok(Self(out))
111    }
112}
113
114impl TryFrom<String> for AuditHash {
115    type Error = InvalidAuditHash;
116
117    fn try_from(value: String) -> std::result::Result<Self, Self::Error> {
118        value.parse()
119    }
120}
121
122impl From<AuditHash> for String {
123    fn from(value: AuditHash) -> Self {
124        value.to_string()
125    }
126}
127
128/// Text that is not a hex-encoded SHA-256 hash.
129#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
130#[error("invalid audit hash: {0}")]
131pub struct InvalidAuditHash(String);
132
133/// What an [`AuditRecord`] is about. Serialized as a snake_case string; names this
134/// enum does not know round-trip through [`Other`](Self::Other).
135#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
136#[serde(from = "String", into = "String")]
137#[non_exhaustive]
138pub enum AuditRecordKind {
139    /// A tool call and its governance decision.
140    ToolCall,
141    /// An approval requested, granted, or refused.
142    Approval,
143    /// A governance change such as a freeze.
144    Governance,
145    /// A payment.
146    Payment,
147    /// An access-control decision.
148    Access,
149    /// An authentication event.
150    Authentication,
151    /// A configuration change.
152    Configuration,
153    /// The log's checkpoint signing key changed.
154    KeyRotated,
155    /// A subject's data was erased. The record names the subject by pseudonym only, with
156    /// each store's outcome.
157    Erasure,
158    /// A session was forked, rewound, or had its events edited. The record names events by ID
159    /// and carries a digest of the changed events, never their content.
160    SessionHistory,
161    /// Any other kind.
162    Other(String),
163}
164
165impl AuditRecordKind {
166    /// Returns the wire name.
167    pub fn as_str(&self) -> &str {
168        match self {
169            Self::ToolCall => "tool_call",
170            Self::Approval => "approval",
171            Self::Governance => "governance",
172            Self::Payment => "payment",
173            Self::Access => "access",
174            Self::Authentication => "authentication",
175            Self::Configuration => "configuration",
176            Self::KeyRotated => "key_rotated",
177            Self::Erasure => "erasure",
178            Self::SessionHistory => "session_history",
179            Self::Other(name) => name,
180        }
181    }
182}
183
184impl From<String> for AuditRecordKind {
185    fn from(value: String) -> Self {
186        match value.as_str() {
187            "tool_call" => Self::ToolCall,
188            "approval" => Self::Approval,
189            "governance" => Self::Governance,
190            "payment" => Self::Payment,
191            "access" => Self::Access,
192            "authentication" => Self::Authentication,
193            "configuration" => Self::Configuration,
194            "key_rotated" => Self::KeyRotated,
195            "erasure" => Self::Erasure,
196            "session_history" => Self::SessionHistory,
197            _ => Self::Other(value),
198        }
199    }
200}
201
202impl From<AuditRecordKind> for String {
203    fn from(value: AuditRecordKind) -> Self {
204        match value {
205            AuditRecordKind::Other(name) => name,
206            known => known.as_str().to_string(),
207        }
208    }
209}
210
211/// The authorization decision an [`AuditRecord`] records.
212#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
213#[serde(rename_all = "snake_case")]
214#[non_exhaustive]
215pub enum AuditDecision {
216    /// The action was allowed.
217    Allowed,
218    /// The action was denied.
219    Denied,
220    /// The action needs approval and was held.
221    ApprovalRequired,
222    /// An approver granted the action.
223    Approved,
224    /// An approver refused the action.
225    Rejected,
226}
227
228/// What happened when the recorded action ran.
229#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
230#[serde(rename_all = "snake_case")]
231#[non_exhaustive]
232pub enum AuditRecordOutcome {
233    /// The action completed.
234    Succeeded,
235    /// The action failed.
236    Failed,
237    /// The action may or may not have taken effect (timeout, crash).
238    OutcomeUnknown,
239    /// The action was not run.
240    NotRun,
241}
242
243/// Who acted: the agent and the subject it acted for, taken from an [`ActingContext`].
244///
245/// # Example
246///
247/// ```rust
248/// use adk_core::audit_log::AuditActor;
249/// use adk_core::principal::SubjectRef;
250///
251/// let actor = AuditActor::subject(SubjectRef::human("alice"));
252/// assert!(actor.agent.is_none());
253/// ```
254#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
255#[serde(rename_all = "camelCase")]
256pub struct AuditActor {
257    /// The acting agent.
258    #[serde(default, skip_serializing_if = "Option::is_none")]
259    pub agent: Option<AgentId>,
260    /// The tenant the agent runs for.
261    #[serde(default, skip_serializing_if = "Option::is_none")]
262    pub tenant: Option<String>,
263    /// The deployment or replica.
264    #[serde(default, skip_serializing_if = "Option::is_none")]
265    pub instance: Option<String>,
266    /// The subject the agent acted on behalf of.
267    #[serde(default, skip_serializing_if = "Option::is_none")]
268    pub on_behalf_of: Option<SubjectRef>,
269    /// The delegation chain, outermost first.
270    #[serde(default, skip_serializing_if = "Vec::is_empty")]
271    pub delegation_chain: Vec<SubjectRef>,
272    /// The invocation the action belongs to.
273    #[serde(default, skip_serializing_if = "Option::is_none")]
274    pub invocation_id: Option<String>,
275}
276
277impl AuditActor {
278    /// An actor that is a subject with no agent, such as a human administrator.
279    pub fn subject(subject: SubjectRef) -> Self {
280        Self { on_behalf_of: Some(subject), ..Self::default() }
281    }
282}
283
284impl AuditActor {
285    /// The actor for `context` acting in `invocation_id`.
286    ///
287    /// # Example
288    ///
289    /// ```rust
290    /// use adk_core::audit_log::AuditActor;
291    /// use adk_core::{ActingContext, SubjectKind};
292    ///
293    /// let acting = ActingContext::derived("shop", "cashier", "alice", SubjectKind::Human);
294    /// let actor = AuditActor::new(&acting, "inv-1");
295    /// assert_eq!(actor.invocation_id.as_deref(), Some("inv-1"));
296    /// assert_eq!(actor.agent, Some(acting.agent.id));
297    /// ```
298    pub fn new(context: &ActingContext, invocation_id: impl Into<String>) -> Self {
299        let invocation_id = invocation_id.into();
300        Self {
301            agent: Some(context.agent.id.clone()),
302            tenant: context.agent.tenant.clone(),
303            instance: context.agent.instance.clone(),
304            on_behalf_of: context.on_behalf_of.clone(),
305            delegation_chain: context.delegation_chain.clone(),
306            invocation_id: (!invocation_id.is_empty()).then_some(invocation_id),
307        }
308    }
309}
310
311/// One entry in an audit log.
312///
313/// The writer fills `v`, `log_id`, `seq`, `ts`, and `prev_hash`; callers supply the
314/// rest as an [`AuditRecordDraft`]. Personal or large data does not belong in the
315/// record: store it elsewhere and put its digest in `payload_ref`, so deleting the
316/// payload (crypto-shredding) leaves the chain verifiable.
317#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
318#[serde(rename_all = "camelCase")]
319pub struct AuditRecord {
320    /// Schema version, [`AUDIT_RECORD_VERSION`].
321    pub v: u32,
322    /// The log this record belongs to, one per replica.
323    pub log_id: String,
324    /// Position in the log, from 0 with no gaps.
325    pub seq: u64,
326    /// When the writer appended the record.
327    pub ts: DateTime<Utc>,
328    /// Leaf hash of the previous record; absent for `seq` 0.
329    #[serde(default, skip_serializing_if = "Option::is_none")]
330    pub prev_hash: Option<AuditHash>,
331    /// Who acted.
332    pub actor: AuditActor,
333    /// What the record is about.
334    pub kind: AuditRecordKind,
335    /// The action, such as a tool name or an operation.
336    pub action: String,
337    /// Digest of the action's canonical arguments, such as `sha256:<hex>`.
338    #[serde(default, skip_serializing_if = "Option::is_none")]
339    pub args_digest: Option<String>,
340    /// The authorization decision.
341    #[serde(default, skip_serializing_if = "Option::is_none")]
342    pub decision: Option<AuditDecision>,
343    /// What happened when the action ran.
344    #[serde(default, skip_serializing_if = "Option::is_none")]
345    pub outcome: Option<AuditRecordOutcome>,
346    /// The policy rule or version that decided.
347    #[serde(default, skip_serializing_if = "Option::is_none")]
348    pub policy_ref: Option<String>,
349    /// Digest of a payload stored outside the log.
350    #[serde(default, skip_serializing_if = "Option::is_none")]
351    pub payload_ref: Option<String>,
352    /// Extension fields. Values must be I-JSON: integers within ±2^53.
353    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
354    pub ext: BTreeMap<String, serde_json::Value>,
355}
356
357/// The caller-supplied part of an [`AuditRecord`].
358///
359/// # Example
360///
361/// ```rust
362/// use adk_core::audit_log::{AuditDecision, AuditRecordDraft, AuditRecordKind};
363///
364/// let draft = AuditRecordDraft::new(AuditRecordKind::ToolCall, "transfer")
365///     .decision(AuditDecision::Allowed)
366///     .args_digest("sha256:00");
367/// assert_eq!(draft.action, "transfer");
368/// ```
369#[derive(Debug, Clone, PartialEq)]
370pub struct AuditRecordDraft {
371    /// Who acted.
372    pub actor: AuditActor,
373    /// What the record is about.
374    pub kind: AuditRecordKind,
375    /// The action.
376    pub action: String,
377    /// Digest of the canonical arguments.
378    pub args_digest: Option<String>,
379    /// The authorization decision.
380    pub decision: Option<AuditDecision>,
381    /// What happened.
382    pub outcome: Option<AuditRecordOutcome>,
383    /// The deciding policy.
384    pub policy_ref: Option<String>,
385    /// Digest of an out-of-log payload.
386    pub payload_ref: Option<String>,
387    /// Extension fields.
388    pub ext: BTreeMap<String, serde_json::Value>,
389}
390
391impl AuditRecordDraft {
392    /// Starts a draft for `action` of `kind` with an empty actor.
393    pub fn new(kind: AuditRecordKind, action: impl Into<String>) -> Self {
394        Self {
395            actor: AuditActor::default(),
396            kind,
397            action: action.into(),
398            args_digest: None,
399            decision: None,
400            outcome: None,
401            policy_ref: None,
402            payload_ref: None,
403            ext: BTreeMap::new(),
404        }
405    }
406
407    /// Sets the actor.
408    pub fn actor(mut self, actor: AuditActor) -> Self {
409        self.actor = actor;
410        self
411    }
412
413    /// Sets the argument digest.
414    pub fn args_digest(mut self, digest: impl Into<String>) -> Self {
415        self.args_digest = Some(digest.into());
416        self
417    }
418
419    /// Sets the decision.
420    pub fn decision(mut self, decision: AuditDecision) -> Self {
421        self.decision = Some(decision);
422        self
423    }
424
425    /// Sets the outcome.
426    pub fn outcome(mut self, outcome: AuditRecordOutcome) -> Self {
427        self.outcome = Some(outcome);
428        self
429    }
430
431    /// Sets the policy reference.
432    pub fn policy_ref(mut self, policy_ref: impl Into<String>) -> Self {
433        self.policy_ref = Some(policy_ref.into());
434        self
435    }
436
437    /// Sets the payload digest.
438    pub fn payload_ref(mut self, digest: impl Into<String>) -> Self {
439        self.payload_ref = Some(digest.into());
440        self
441    }
442
443    /// Adds an extension field.
444    pub fn ext(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
445        self.ext.insert(key.into(), value);
446        self
447    }
448
449    /// Completes the record with the fields the writer assigns.
450    pub fn into_record(
451        self,
452        log_id: impl Into<String>,
453        seq: u64,
454        ts: DateTime<Utc>,
455        prev_hash: Option<AuditHash>,
456    ) -> AuditRecord {
457        AuditRecord {
458            v: AUDIT_RECORD_VERSION,
459            log_id: log_id.into(),
460            seq,
461            ts,
462            prev_hash,
463            actor: self.actor,
464            kind: self.kind,
465            action: self.action,
466            args_digest: self.args_digest,
467            decision: self.decision,
468            outcome: self.outcome,
469            policy_ref: self.policy_ref,
470            payload_ref: self.payload_ref,
471            ext: self.ext,
472        }
473    }
474}
475
476/// A stored log entry: the record's canonical JSON and its leaf hash.
477#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
478#[serde(rename_all = "camelCase")]
479pub struct AuditLogEntry {
480    /// Position in the log.
481    pub seq: u64,
482    /// `SHA-256(0x00 ‖ record)`, the RFC 9162 leaf hash.
483    pub leaf_hash: AuditHash,
484    /// The record's canonical JSON text; `None` once pruned.
485    #[serde(default, skip_serializing_if = "Option::is_none")]
486    pub record: Option<String>,
487}
488
489/// The hash of a complete Merkle subtree covering leaves
490/// `[index << level, (index + 1) << level)`.
491#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
492#[serde(rename_all = "camelCase")]
493pub struct AuditTreeNode {
494    /// Height above the leaves; leaves are level 0 and are stored with their entries.
495    pub level: u8,
496    /// Position within the level.
497    pub index: u64,
498    /// The subtree hash.
499    pub hash: AuditHash,
500}
501
502/// Entries to append to one log, with the tree nodes they complete.
503#[derive(Debug, Clone, PartialEq, Eq)]
504pub struct AuditAppend {
505    /// The log to append to.
506    pub log_id: String,
507    /// Entries with contiguous `seq`, the first equal to the log's current size.
508    pub entries: Vec<AuditLogEntry>,
509    /// Subtree nodes (level 1 and above) these entries complete.
510    pub nodes: Vec<AuditTreeNode>,
511}
512
513/// A signed checkpoint of a log: its size and root hash in a signed note.
514#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
515#[serde(rename_all = "camelCase")]
516pub struct AuditCheckpoint {
517    /// The log this checkpoint covers.
518    pub log_id: String,
519    /// Number of records covered.
520    pub size: u64,
521    /// The RFC 9162 root hash over the first `size` records.
522    pub root_hash: AuditHash,
523    /// The C2SP signed note carrying the checkpoint and its signatures.
524    pub note: String,
525    /// When the writer signed it.
526    pub created_at: DateTime<Utc>,
527}
528
529/// Persistence for append-only, Merkle-hashed audit logs.
530///
531/// The store holds what a writer computed and never derives hashes itself. Its
532/// guarantees:
533///
534/// - `append` is atomic and succeeds only when the first entry's `seq` equals the log's
535///   size; otherwise `audit_log.seq_conflict`. Two writers on one `log_id` cannot fork it.
536/// - A checkpoint never claims more records than the log holds, and a second checkpoint
537///   at the same size with a different root is refused (`audit_log.checkpoint_conflict`).
538///   One with the same root replaces the note, which adds cosignatures.
539/// - `prune` removes record bodies and keeps every hash.
540///
541/// # Example
542///
543/// ```rust
544/// use adk_core::audit_log::{AuditAppend, AuditHash, AuditLogEntry, AuditLogStore, InMemoryAuditLogStore};
545///
546/// # async fn demo() -> adk_core::Result<()> {
547/// let store = InMemoryAuditLogStore::new();
548/// let entry = AuditLogEntry { seq: 0, leaf_hash: AuditHash([1; 32]), record: Some("{}".into()) };
549/// let range = store
550///     .append(AuditAppend { log_id: "replica-1".into(), entries: vec![entry], nodes: vec![] })
551///     .await?;
552/// assert_eq!(range, 0..1);
553/// # Ok(())
554/// # }
555/// ```
556#[async_trait]
557pub trait AuditLogStore: Send + Sync {
558    /// Appends a batch and returns the sequence range it occupies.
559    ///
560    /// # Errors
561    ///
562    /// `audit_log.seq_conflict` when the first `seq` is not the log's size;
563    /// `audit_log.invalid_batch` when the batch is empty, not contiguous, holds a pruned
564    /// entry, or names a node outside the appended range.
565    async fn append(&self, batch: AuditAppend) -> Result<Range<u64>>;
566
567    /// Returns the number of records in the log; 0 for a log never written.
568    async fn size(&self, log_id: &str) -> Result<u64>;
569
570    /// Returns the entries in `range`, in order.
571    ///
572    /// # Errors
573    ///
574    /// `audit_log.out_of_range` when `range` extends past the log's size.
575    async fn read(&self, log_id: &str, range: Range<u64>) -> Result<Vec<AuditLogEntry>>;
576
577    /// Returns the hash of the complete subtree at `(level, index)`, or `None` when the
578    /// log has no such subtree yet. Level 0 returns leaf hashes.
579    async fn hash_at(&self, log_id: &str, level: u8, index: u64) -> Result<Option<AuditHash>>;
580
581    /// Stores a signed checkpoint.
582    ///
583    /// # Errors
584    ///
585    /// `audit_log.out_of_range` when `size` exceeds the log's size;
586    /// `audit_log.checkpoint_conflict` when a checkpoint of the same size has a
587    /// different root.
588    async fn put_checkpoint(&self, checkpoint: AuditCheckpoint) -> Result<()>;
589
590    /// Returns the checkpoint with the largest size.
591    async fn latest_checkpoint(&self, log_id: &str) -> Result<Option<AuditCheckpoint>>;
592
593    /// Returns every checkpoint of the log, smallest size first.
594    async fn checkpoints(&self, log_id: &str) -> Result<Vec<AuditCheckpoint>>;
595
596    /// Drops the bodies of records with `seq < before_seq`, keeping their hashes, and
597    /// returns how many bodies it dropped.
598    ///
599    /// # Errors
600    ///
601    /// `audit_log.out_of_range` when `before_seq` exceeds the log's size.
602    async fn prune(&self, log_id: &str, before_seq: u64) -> Result<u64>;
603
604    /// Returns the ids of every log in the store, sorted.
605    async fn logs(&self) -> Result<Vec<String>>;
606
607    /// Drops the bodies of the records at `seqs`, keeping their hashes, and returns how many
608    /// bodies it dropped; a body already pruned or redacted is not counted.
609    ///
610    /// Signed checkpoints and inclusion proofs still verify, since they cover leaf hashes
611    /// only. [`AuditLogSubjectData`](crate::subject::AuditLogSubjectData) redacts the records
612    /// that name a subject being erased.
613    ///
614    /// # Errors
615    ///
616    /// `audit_log.out_of_range` when a position is past the log's end, checked before any
617    /// body is dropped ([`check_redaction`]). The default returns
618    /// `audit_log.redact_unsupported`.
619    async fn redact(&self, log_id: &str, seqs: &[u64]) -> Result<u64> {
620        let _ = seqs;
621        Err(audit_error(
622            ErrorCategory::Unsupported,
623            "audit_log.redact_unsupported",
624            format!("the audit log store holding '{log_id}' cannot redact single records"),
625        ))
626    }
627}
628
629/// Checks that every position in `seqs` is inside a log of `size` records. Every backend
630/// calls this before [`AuditLogStore::redact`] drops a body, so all of them refuse the same
631/// requests.
632///
633/// # Errors
634///
635/// `audit_log.out_of_range` naming the first position past the end.
636pub fn check_redaction(log_id: &str, seqs: &[u64], size: u64) -> Result<()> {
637    match seqs.iter().find(|seq| **seq >= size) {
638        Some(seq) => Err(out_of_range_error(log_id, size, *seq)),
639        None => Ok(()),
640    }
641}
642
643fn audit_error(category: ErrorCategory, code: &'static str, message: String) -> AdkError {
644    AdkError::new(ErrorComponent::Auth, category, code, message)
645}
646
647/// The error a store returns when `append` does not start at the log's size.
648pub fn seq_conflict_error(log_id: &str, expected: u64, got: u64) -> AdkError {
649    audit_error(
650        ErrorCategory::Conflict,
651        "audit_log.seq_conflict",
652        format!(
653            "audit log '{log_id}' has {expected} records but the append starts at {got}. \
654             Another writer is using this log_id; give each replica its own log_id"
655        ),
656    )
657}
658
659/// The error a store returns when a read, prune, or checkpoint passes the log's end.
660pub fn out_of_range_error(log_id: &str, size: u64, requested: u64) -> AdkError {
661    audit_error(
662        ErrorCategory::NotFound,
663        "audit_log.out_of_range",
664        format!("audit log '{log_id}' has {size} records; position {requested} is past its end"),
665    )
666}
667
668/// The error a store returns when a checkpoint would equivocate.
669pub fn checkpoint_conflict_error(log_id: &str, size: u64) -> AdkError {
670    audit_error(
671        ErrorCategory::Conflict,
672        "audit_log.checkpoint_conflict",
673        format!(
674            "audit log '{log_id}' already has a checkpoint at size {size} with a different root; \
675             the log has forked and must be investigated before it is checkpointed again"
676        ),
677    )
678}
679
680fn invalid_batch(log_id: &str, reason: &str) -> AdkError {
681    audit_error(
682        ErrorCategory::InvalidInput,
683        "audit_log.invalid_batch",
684        format!("audit log '{log_id}': {reason}"),
685    )
686}
687
688/// Checks an append against the log's current size and returns the range it occupies.
689/// Every backend calls this inside its transaction, so all of them refuse the same batches.
690///
691/// # Errors
692///
693/// `audit_log.seq_conflict` or `audit_log.invalid_batch`, as [`AuditLogStore::append`].
694pub fn validate_append(batch: &AuditAppend, size: u64) -> Result<Range<u64>> {
695    let log_id = batch.log_id.as_str();
696    let Some(first) = batch.entries.first() else {
697        return Err(invalid_batch(log_id, "the batch has no entries"));
698    };
699    if first.seq != size {
700        return Err(seq_conflict_error(log_id, size, first.seq));
701    }
702    for (offset, entry) in batch.entries.iter().enumerate() {
703        if entry.seq != size + offset as u64 {
704            return Err(invalid_batch(log_id, "entry sequence numbers are not contiguous"));
705        }
706        if entry.record.is_none() {
707            return Err(invalid_batch(log_id, "an appended entry has no record"));
708        }
709    }
710    let end = size + batch.entries.len() as u64;
711    for node in &batch.nodes {
712        let covers = node
713            .index
714            .checked_add(1)
715            .and_then(|next| next.checked_shl(u32::from(node.level)))
716            .filter(|_| node.level >= 1 && node.level < 64);
717        match covers {
718            Some(node_end) if node_end <= end && node_end > size => {}
719            _ => {
720                return Err(invalid_batch(
721                    log_id,
722                    "a tree node is not completed by the appended entries",
723                ));
724            }
725        }
726    }
727    Ok(size..end)
728}
729
730/// Checks a checkpoint against the log's size and an existing checkpoint at its size.
731///
732/// Returns `true` when an existing checkpoint should be replaced by this one.
733///
734/// # Errors
735///
736/// As [`AuditLogStore::put_checkpoint`].
737pub fn validate_checkpoint(
738    checkpoint: &AuditCheckpoint,
739    size: u64,
740    existing_root: Option<AuditHash>,
741) -> Result<bool> {
742    if checkpoint.size > size {
743        return Err(out_of_range_error(&checkpoint.log_id, size, checkpoint.size));
744    }
745    match existing_root {
746        Some(root) if root != checkpoint.root_hash => {
747            Err(checkpoint_conflict_error(&checkpoint.log_id, checkpoint.size))
748        }
749        Some(_) => Ok(true),
750        None => Ok(false),
751    }
752}
753
754#[derive(Debug, Default)]
755struct MemoryLog {
756    entries: Vec<AuditLogEntry>,
757    nodes: HashMap<(u8, u64), AuditHash>,
758    checkpoints: BTreeMap<u64, AuditCheckpoint>,
759}
760
761/// In-memory [`AuditLogStore`] for tests and single-process development.
762///
763/// Clones share the same logs.
764#[derive(Debug, Clone, Default)]
765pub struct InMemoryAuditLogStore {
766    logs: Arc<tokio::sync::RwLock<HashMap<String, MemoryLog>>>,
767}
768
769impl InMemoryAuditLogStore {
770    /// Creates an empty store.
771    pub fn new() -> Self {
772        Self::default()
773    }
774}
775
776#[async_trait]
777impl AuditLogStore for InMemoryAuditLogStore {
778    async fn append(&self, batch: AuditAppend) -> Result<Range<u64>> {
779        let mut logs = self.logs.write().await;
780        let size = logs.get(&batch.log_id).map_or(0, |log| log.entries.len() as u64);
781        let range = validate_append(&batch, size)?;
782        let log = logs.entry(batch.log_id).or_default();
783        log.entries.extend(batch.entries);
784        for node in batch.nodes {
785            log.nodes.insert((node.level, node.index), node.hash);
786        }
787        Ok(range)
788    }
789
790    async fn size(&self, log_id: &str) -> Result<u64> {
791        Ok(self.logs.read().await.get(log_id).map_or(0, |log| log.entries.len() as u64))
792    }
793
794    async fn read(&self, log_id: &str, range: Range<u64>) -> Result<Vec<AuditLogEntry>> {
795        let logs = self.logs.read().await;
796        let entries = logs.get(log_id).map_or(&[][..], |log| log.entries.as_slice());
797        let size = entries.len() as u64;
798        if range.end > size {
799            return Err(out_of_range_error(log_id, size, range.end));
800        }
801        if range.start >= range.end {
802            return Ok(Vec::new());
803        }
804        Ok(entries[range.start as usize..range.end as usize].to_vec())
805    }
806
807    async fn hash_at(&self, log_id: &str, level: u8, index: u64) -> Result<Option<AuditHash>> {
808        let logs = self.logs.read().await;
809        let Some(log) = logs.get(log_id) else {
810            return Ok(None);
811        };
812        if level == 0 {
813            return Ok(usize::try_from(index)
814                .ok()
815                .and_then(|at| log.entries.get(at))
816                .map(|entry| entry.leaf_hash));
817        }
818        Ok(log.nodes.get(&(level, index)).copied())
819    }
820
821    async fn put_checkpoint(&self, checkpoint: AuditCheckpoint) -> Result<()> {
822        let mut logs = self.logs.write().await;
823        let log = logs.get(&checkpoint.log_id);
824        let size = log.map_or(0, |log| log.entries.len() as u64);
825        let existing =
826            log.and_then(|log| log.checkpoints.get(&checkpoint.size)).map(|c| c.root_hash);
827        validate_checkpoint(&checkpoint, size, existing)?;
828        logs.entry(checkpoint.log_id.clone())
829            .or_default()
830            .checkpoints
831            .insert(checkpoint.size, checkpoint);
832        Ok(())
833    }
834
835    async fn latest_checkpoint(&self, log_id: &str) -> Result<Option<AuditCheckpoint>> {
836        let logs = self.logs.read().await;
837        Ok(logs.get(log_id).and_then(|log| log.checkpoints.values().next_back().cloned()))
838    }
839
840    async fn checkpoints(&self, log_id: &str) -> Result<Vec<AuditCheckpoint>> {
841        let logs = self.logs.read().await;
842        Ok(logs
843            .get(log_id)
844            .map(|log| log.checkpoints.values().cloned().collect())
845            .unwrap_or_default())
846    }
847
848    async fn prune(&self, log_id: &str, before_seq: u64) -> Result<u64> {
849        let mut logs = self.logs.write().await;
850        let size = logs.get(log_id).map_or(0, |log| log.entries.len() as u64);
851        if before_seq > size {
852            return Err(out_of_range_error(log_id, size, before_seq));
853        }
854        let Some(log) = logs.get_mut(log_id) else {
855            return Ok(0);
856        };
857        let mut pruned = 0;
858        for entry in &mut log.entries[..before_seq as usize] {
859            if entry.record.take().is_some() {
860                pruned += 1;
861            }
862        }
863        Ok(pruned)
864    }
865
866    async fn logs(&self) -> Result<Vec<String>> {
867        let mut ids: Vec<String> = self.logs.read().await.keys().cloned().collect();
868        ids.sort();
869        Ok(ids)
870    }
871
872    async fn redact(&self, log_id: &str, seqs: &[u64]) -> Result<u64> {
873        let mut logs = self.logs.write().await;
874        let size = logs.get(log_id).map_or(0, |log| log.entries.len() as u64);
875        check_redaction(log_id, seqs, size)?;
876        let Some(log) = logs.get_mut(log_id) else { return Ok(0) };
877        let mut redacted = 0;
878        for seq in seqs {
879            if log.entries[*seq as usize].record.take().is_some() {
880                redacted += 1;
881            }
882        }
883        Ok(redacted)
884    }
885}
886
887// ---------------------------------------------------------------------------
888// Runtime recording
889// ---------------------------------------------------------------------------
890
891/// What the runtime does when its [`AuditRecorder`] cannot record an action.
892///
893/// # Example
894///
895/// ```rust
896/// use adk_core::audit_log::AuditFailureMode;
897///
898/// assert_eq!(AuditFailureMode::default(), AuditFailureMode::Block);
899/// ```
900#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
901pub enum AuditFailureMode {
902    /// Refuse the action: an action whose record cannot be written does not happen.
903    #[default]
904    Block,
905    /// Log the failure and continue without a record.
906    Warn,
907}
908
909/// Where the runtime writes audit records: governed tool decisions, approval decisions,
910/// kill-switch changes, payments, and calls whose outcome is unknown.
911///
912/// `adk_auth::signed_audit::AuditLog` implements it with a signed, Merkle-hashed log;
913/// [`InMemoryAuditRecorder`] keeps drafts in memory for tests. The trait carries no
914/// cryptography, so `adk-core` stays free of it: the recorder also computes the argument
915/// digests that records carry in place of arguments.
916///
917/// # Example
918///
919/// ```rust
920/// use std::sync::Arc;
921/// use adk_core::audit_log::{AuditRecordDraft, AuditRecordKind, AuditRecorder, InMemoryAuditRecorder};
922///
923/// # futures::executor::block_on(async {
924/// let recorder = InMemoryAuditRecorder::new();
925/// let digest = recorder.digest(&serde_json::json!({ "amount": 5 }));
926/// recorder
927///     .record(AuditRecordDraft::new(AuditRecordKind::ToolCall, "transfer").args_digest(digest))
928///     .await?;
929/// assert_eq!(recorder.records().len(), 1);
930/// # Ok::<(), adk_core::AdkError>(())
931/// # }).unwrap();
932/// ```
933#[async_trait]
934pub trait AuditRecorder: Send + Sync {
935    /// Digest of `value`'s canonical JSON, such as `sha256:<hex>`, for
936    /// [`AuditRecord::args_digest`].
937    fn digest(&self, value: &serde_json::Value) -> String;
938
939    /// Appends one record.
940    ///
941    /// # Errors
942    ///
943    /// Returns the recorder's error when the record cannot be written.
944    async fn record(&self, draft: AuditRecordDraft) -> Result<()>;
945
946    /// Makes every record written so far verifiable without a later write, such as by
947    /// signing a checkpoint over them. A process calls it when it stops cleanly; a
948    /// recorder that wraps another forwards it. The default does nothing.
949    ///
950    /// # Errors
951    ///
952    /// Returns the recorder's error when the records cannot be sealed.
953    async fn seal(&self) -> Result<()> {
954        Ok(())
955    }
956}
957
958/// An [`AuditRecorder`] with the [`AuditFailureMode`] that governs it.
959///
960/// Set on [`RunConfig::audit`](crate::RunConfig::audit) (usually through the runner
961/// builder's `audit_log`), attached to a [`GovernanceControl`](crate::GovernanceControl),
962/// or given to a payment caller. Clones share the recorder.
963///
964/// # Example
965///
966/// ```rust
967/// use std::sync::Arc;
968/// use adk_core::audit_log::{AuditFailureMode, AuditTrail, InMemoryAuditRecorder};
969///
970/// let trail = AuditTrail::new(Arc::new(InMemoryAuditRecorder::new()))
971///     .with_failure_mode(AuditFailureMode::Warn);
972/// assert_eq!(trail.failure_mode(), AuditFailureMode::Warn);
973/// ```
974#[derive(Clone)]
975pub struct AuditTrail {
976    recorder: Arc<dyn AuditRecorder>,
977    failure_mode: AuditFailureMode,
978}
979
980impl fmt::Debug for AuditTrail {
981    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
982        f.debug_struct("AuditTrail").field("failure_mode", &self.failure_mode).finish()
983    }
984}
985
986impl AuditTrail {
987    /// Records through `recorder`, refusing actions it cannot record
988    /// ([`AuditFailureMode::Block`]).
989    pub fn new(recorder: Arc<dyn AuditRecorder>) -> Self {
990        Self { recorder, failure_mode: AuditFailureMode::Block }
991    }
992
993    /// Sets what happens when the recorder fails.
994    #[must_use]
995    pub fn with_failure_mode(mut self, mode: AuditFailureMode) -> Self {
996        self.failure_mode = mode;
997        self
998    }
999
1000    /// The failure mode.
1001    pub fn failure_mode(&self) -> AuditFailureMode {
1002        self.failure_mode
1003    }
1004
1005    /// The recorder.
1006    pub fn recorder(&self) -> &Arc<dyn AuditRecorder> {
1007        &self.recorder
1008    }
1009
1010    /// Digest of `value` by the recorder.
1011    pub fn digest(&self, value: &serde_json::Value) -> String {
1012        self.recorder.digest(value)
1013    }
1014
1015    /// Records `draft`, applying the failure mode.
1016    ///
1017    /// # Errors
1018    ///
1019    /// Under [`AuditFailureMode::Block`], `audit.record_failed` when the recorder fails;
1020    /// the caller refuses the action. Under [`AuditFailureMode::Warn`], never.
1021    pub async fn record(&self, draft: AuditRecordDraft) -> Result<()> {
1022        let action = draft.action.clone();
1023        let Err(error) = self.recorder.record(draft).await else {
1024            return Ok(());
1025        };
1026        match self.failure_mode {
1027            AuditFailureMode::Block => {
1028                tracing::error!(audit.action = %action, error = %error, "audit record failed; refusing the action");
1029                Err(AdkError::new(
1030                    ErrorComponent::Auth,
1031                    ErrorCategory::Unavailable,
1032                    "audit.record_failed",
1033                    format!(
1034                        "'{action}' refused: its audit record could not be written ({error}). \
1035                         Restore the audit log, or set AuditFailureMode::Warn to continue \
1036                         without a record"
1037                    ),
1038                ))
1039            }
1040            AuditFailureMode::Warn => {
1041                tracing::warn!(audit.action = %action, error = %error, "audit record failed; continuing without a record");
1042                Ok(())
1043            }
1044        }
1045    }
1046}
1047
1048impl AuditActor {
1049    /// The actor for an agent of `app_name` running in `invocation_id` for `user_id`,
1050    /// when the run configures no acting context: the agent id is
1051    /// `urn:adk:agent:<app>/<agent>` and the subject is `user_id` as a human.
1052    ///
1053    /// # Example
1054    ///
1055    /// ```rust
1056    /// use adk_core::audit_log::AuditActor;
1057    /// use adk_core::principal::SubjectRef;
1058    ///
1059    /// let actor = AuditActor::for_invocation("shop", "cashier", "alice", "inv-1");
1060    /// assert_eq!(actor.agent.unwrap().as_str(), "urn:adk:agent:shop/cashier");
1061    /// assert_eq!(actor.on_behalf_of, Some(SubjectRef::human("alice")));
1062    /// ```
1063    pub fn for_invocation(
1064        app_name: &str,
1065        agent_name: &str,
1066        user_id: &str,
1067        invocation_id: &str,
1068    ) -> Self {
1069        Self::new(
1070            &ActingContext::derived(app_name, agent_name, user_id, crate::SubjectKind::Human),
1071            invocation_id,
1072        )
1073    }
1074
1075    /// The actor of the agent running in `ctx`: its
1076    /// [acting context](crate::ReadonlyContext::acting_context), which is the run's
1077    /// configured agent principal and subject, or the derived identity of
1078    /// [`for_invocation`](Self::for_invocation) when the run configures none.
1079    ///
1080    /// # Example
1081    ///
1082    /// ```rust,ignore
1083    /// let actor = AuditActor::for_context(tool_ctx.as_ref());
1084    /// ```
1085    pub fn for_context(ctx: &dyn crate::ReadonlyContext) -> Self {
1086        Self::new(&ctx.acting_context(), ctx.invocation_id())
1087    }
1088}
1089
1090/// An [`AuditRecorder`] that keeps drafts in memory, for tests.
1091///
1092/// Its digest is the non-cryptographic [`json_digest`](crate::json_digest); a
1093/// production recorder uses SHA-256.
1094///
1095/// # Example
1096///
1097/// ```rust
1098/// use adk_core::audit_log::InMemoryAuditRecorder;
1099///
1100/// let recorder = InMemoryAuditRecorder::new();
1101/// assert!(recorder.records().is_empty());
1102/// ```
1103#[derive(Debug, Clone, Default)]
1104pub struct InMemoryAuditRecorder {
1105    records: Arc<std::sync::Mutex<Vec<AuditRecordDraft>>>,
1106}
1107
1108impl InMemoryAuditRecorder {
1109    /// Creates an empty recorder.
1110    pub fn new() -> Self {
1111        Self::default()
1112    }
1113
1114    /// The drafts recorded so far, in order.
1115    pub fn records(&self) -> Vec<AuditRecordDraft> {
1116        self.records.lock().unwrap_or_else(|e| e.into_inner()).clone()
1117    }
1118}
1119
1120#[async_trait]
1121impl AuditRecorder for InMemoryAuditRecorder {
1122    fn digest(&self, value: &serde_json::Value) -> String {
1123        crate::json_digest(value)
1124    }
1125
1126    async fn record(&self, draft: AuditRecordDraft) -> Result<()> {
1127        self.records.lock().unwrap_or_else(|e| e.into_inner()).push(draft);
1128        Ok(())
1129    }
1130}
1131
1132/// An [`AuditRecorder`] that appends each record to a file as one line of JSON, so the
1133/// records survive a restart (spec 3.5 §7.9, §9.3).
1134///
1135/// Each line is an [`AuditRecord`] whose `seq` counts the file's records from 0 and whose
1136/// `ts` is the time it was appended. Several processes may append to one file: each append
1137/// takes an exclusive lock on it and counts the records another process added since its
1138/// last append, so `seq` has no gap and no repeat. A line a crash left unfinished is cut
1139/// before the next append, and [`read`](Self::read) leaves it out. Every append is flushed
1140/// to disk before [`record`](AuditRecorder::record) returns.
1141///
1142/// The records are not hash-chained or signed; `adk_auth::signed_audit::AuditLog` over a
1143/// durable [`AuditLogStore`] keeps a tamper-evident log. The digest is `sha256:` and the hex
1144/// SHA-256 of the value's canonical JSON.
1145///
1146/// # Example
1147///
1148/// ```rust
1149/// use adk_core::audit_log::{AuditRecordDraft, AuditRecordKind, AuditRecorder, FileAuditRecorder};
1150///
1151/// # #[tokio::main(flavor = "current_thread")]
1152/// # async fn main() -> adk_core::Result<()> {
1153/// let dir = std::env::temp_dir().join(format!("adk-audit-{}", uuid::Uuid::new_v4()));
1154/// let path = dir.join("audit.jsonl");
1155/// let recorder = FileAuditRecorder::open(&path)?;
1156/// recorder.record(AuditRecordDraft::new(AuditRecordKind::Other("site".into()), "site.release.built")).await?;
1157///
1158/// let records = FileAuditRecorder::read(&path)?;
1159/// assert_eq!((records[0].seq, records[0].action.as_str()), (0, "site.release.built"));
1160/// # std::fs::remove_dir_all(dir).ok();
1161/// # Ok(())
1162/// # }
1163/// ```
1164#[derive(Clone)]
1165pub struct FileAuditRecorder {
1166    path: std::path::PathBuf,
1167    log_id: String,
1168    state: Arc<std::sync::Mutex<FileAuditState>>,
1169}
1170
1171/// What the recorder knows of its file: the length it last saw and the records before it.
1172#[derive(Debug, Default)]
1173struct FileAuditState {
1174    len: u64,
1175    records: u64,
1176}
1177
1178impl fmt::Debug for FileAuditRecorder {
1179    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1180        f.debug_struct("FileAuditRecorder")
1181            .field("path", &self.path)
1182            .field("log_id", &self.log_id)
1183            .finish_non_exhaustive()
1184    }
1185}
1186
1187fn file_audit_error(path: &std::path::Path, action: &str, error: impl fmt::Display) -> AdkError {
1188    AdkError::new(
1189        ErrorComponent::Auth,
1190        ErrorCategory::Unavailable,
1191        "audit.file_failed",
1192        format!(
1193            "could not {action} the audit file {}: {error}. Check that the directory exists \
1194             and is writable, and that the disk has space",
1195            path.display()
1196        ),
1197    )
1198}
1199
1200/// The number of complete lines in `bytes` and the length up to the last one.
1201fn complete_lines(bytes: &[u8]) -> (u64, u64) {
1202    let lines = bytes.iter().filter(|byte| **byte == b'\n').count() as u64;
1203    let end = bytes.iter().rposition(|byte| *byte == b'\n').map_or(0, |at| at as u64 + 1);
1204    (lines, end)
1205}
1206
1207impl FileAuditRecorder {
1208    /// Appends to the file at `path`, creating it and its directory when missing; the log
1209    /// id is `file:` and the path.
1210    ///
1211    /// # Errors
1212    ///
1213    /// `audit.file_failed` when the directory cannot be created or the file opened.
1214    pub fn open(path: impl Into<std::path::PathBuf>) -> Result<Self> {
1215        let path = path.into();
1216        if let Some(parent) = path.parent().filter(|parent| !parent.as_os_str().is_empty()) {
1217            std::fs::create_dir_all(parent)
1218                .map_err(|error| file_audit_error(&path, "create the directory of", error))?;
1219        }
1220        std::fs::OpenOptions::new()
1221            .create(true)
1222            .append(true)
1223            .open(&path)
1224            .map_err(|error| file_audit_error(&path, "open", error))?;
1225        Ok(Self {
1226            log_id: format!("file:{}", path.display()),
1227            path,
1228            state: Arc::new(std::sync::Mutex::new(FileAuditState::default())),
1229        })
1230    }
1231
1232    /// Names the log the records belong to, such as the site's domain.
1233    #[must_use]
1234    pub fn with_log_id(mut self, log_id: impl Into<String>) -> Self {
1235        self.log_id = log_id.into();
1236        self
1237    }
1238
1239    /// The file.
1240    pub fn path(&self) -> &std::path::Path {
1241        &self.path
1242    }
1243
1244    /// The records in the file at `path`, in order; none when it does not exist.
1245    ///
1246    /// # Errors
1247    ///
1248    /// `audit.file_failed` when the file cannot be read or a complete line is not a record.
1249    pub fn read(path: impl AsRef<std::path::Path>) -> Result<Vec<AuditRecord>> {
1250        let path = path.as_ref();
1251        let bytes = match std::fs::read(path) {
1252            Ok(bytes) => bytes,
1253            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
1254            Err(error) => return Err(file_audit_error(path, "read", error)),
1255        };
1256        let (_, end) = complete_lines(&bytes);
1257        bytes[..end as usize]
1258            .split(|byte| *byte == b'\n')
1259            .filter(|line| !line.is_empty())
1260            .enumerate()
1261            .map(|(index, line)| {
1262                serde_json::from_slice(line).map_err(|error| {
1263                    file_audit_error(path, &format!("read record {index} of"), error)
1264                })
1265            })
1266            .collect()
1267    }
1268
1269    /// The records this recorder's file holds, in order.
1270    ///
1271    /// # Errors
1272    ///
1273    /// As [`read`](Self::read).
1274    pub async fn records(&self) -> Result<Vec<AuditRecord>> {
1275        let path = self.path.clone();
1276        tokio::task::spawn_blocking(move || Self::read(path))
1277            .await
1278            .map_err(|error| file_audit_error(&self.path, "read", error))?
1279    }
1280
1281    /// Appends `draft` as the next record under the file's lock.
1282    fn append(&self, draft: AuditRecordDraft) -> Result<()> {
1283        use std::io::{Read as _, Seek as _, SeekFrom, Write as _};
1284
1285        let path = &self.path;
1286        // Written at the end under the exclusive lock rather than in append mode: an
1287        // append-only handle cannot cut an unfinished line on Windows.
1288        let mut file = std::fs::OpenOptions::new()
1289            .create(true)
1290            .truncate(false)
1291            .read(true)
1292            .write(true)
1293            .open(path)
1294            .map_err(|error| file_audit_error(path, "open", error))?;
1295        file.lock().map_err(|error| file_audit_error(path, "lock", error))?;
1296        let mut state = self.state.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
1297        let len = file.metadata().map_err(|error| file_audit_error(path, "inspect", error))?.len();
1298        if len != state.len {
1299            // Another process appended, or the file is new to this recorder: count the
1300            // records from where this recorder last stopped, or from the start.
1301            let from = if len > state.len { state.len } else { 0 };
1302            if from == 0 {
1303                state.records = 0;
1304            }
1305            let mut tail = Vec::new();
1306            file.seek(SeekFrom::Start(from))
1307                .and_then(|_| file.read_to_end(&mut tail))
1308                .map_err(|error| file_audit_error(path, "read", error))?;
1309            let (lines, end) = complete_lines(&tail);
1310            state.records += lines;
1311            state.len = from + end;
1312            if state.len < len {
1313                // A line a crash left unfinished never completed; cut it.
1314                file.set_len(state.len).map_err(|error| file_audit_error(path, "repair", error))?;
1315            }
1316        }
1317        let record = AuditRecord {
1318            v: AUDIT_RECORD_VERSION,
1319            log_id: self.log_id.clone(),
1320            seq: state.records,
1321            ts: Utc::now(),
1322            prev_hash: None,
1323            actor: draft.actor,
1324            kind: draft.kind,
1325            action: draft.action,
1326            args_digest: draft.args_digest,
1327            decision: draft.decision,
1328            outcome: draft.outcome,
1329            policy_ref: draft.policy_ref,
1330            payload_ref: draft.payload_ref,
1331            ext: draft.ext,
1332        };
1333        let mut line = serde_json::to_vec(&record)
1334            .map_err(|error| file_audit_error(path, "encode a record for", error))?;
1335        line.push(b'\n');
1336        file.seek(SeekFrom::Start(state.len))
1337            .and_then(|_| file.write_all(&line))
1338            .and_then(|()| file.sync_data())
1339            .map_err(|error| file_audit_error(path, "append to", error))?;
1340        state.len += line.len() as u64;
1341        state.records += 1;
1342        Ok(())
1343    }
1344}
1345
1346#[async_trait]
1347impl AuditRecorder for FileAuditRecorder {
1348    fn digest(&self, value: &serde_json::Value) -> String {
1349        use sha2::{Digest as _, Sha256};
1350        use std::fmt::Write as _;
1351
1352        let mut canonical = String::new();
1353        crate::context::write_canonical(value, &mut canonical);
1354        let mut digest = String::with_capacity(7 + 64);
1355        digest.push_str("sha256:");
1356        for byte in Sha256::digest(canonical.as_bytes()) {
1357            let _ = write!(digest, "{byte:02x}");
1358        }
1359        digest
1360    }
1361
1362    async fn record(&self, draft: AuditRecordDraft) -> Result<()> {
1363        let recorder = self.clone();
1364        tokio::task::spawn_blocking(move || recorder.append(draft))
1365            .await
1366            .map_err(|error| file_audit_error(&self.path, "append to", error))?
1367    }
1368}
1369
1370#[cfg(test)]
1371mod tests {
1372    use super::*;
1373
1374    fn draft(action: &str) -> AuditRecordDraft {
1375        AuditRecordDraft::new(AuditRecordKind::Other("site".into()), action)
1376            .ext("releaseSeq", serde_json::json!(7))
1377    }
1378
1379    #[tokio::test]
1380    async fn a_file_recorder_keeps_its_records_across_a_reopen() {
1381        let dir = std::env::temp_dir().join(format!("adk-audit-{}", uuid::Uuid::new_v4()));
1382        let path = dir.join("nested").join("audit.jsonl");
1383        let recorder = FileAuditRecorder::open(&path).unwrap().with_log_id("example.com");
1384        recorder.record(draft("site.release.built")).await.unwrap();
1385        recorder.record(draft("site.release.signed")).await.unwrap();
1386        drop(recorder);
1387
1388        // A second process opens the same file, and the first appends again after it.
1389        let first = FileAuditRecorder::open(&path).unwrap().with_log_id("example.com");
1390        let second = FileAuditRecorder::open(&path).unwrap().with_log_id("example.com");
1391        first.record(draft("awp.keys.rotated")).await.unwrap();
1392        second.record(draft("awp.keys.delegated")).await.unwrap();
1393        first.record(draft("site.content.published")).await.unwrap();
1394
1395        let records = first.records().await.unwrap();
1396        let read: Vec<(u64, &str)> = records.iter().map(|r| (r.seq, r.action.as_str())).collect();
1397        assert_eq!(
1398            read,
1399            vec![
1400                (0, "site.release.built"),
1401                (1, "site.release.signed"),
1402                (2, "awp.keys.rotated"),
1403                (3, "awp.keys.delegated"),
1404                (4, "site.content.published"),
1405            ]
1406        );
1407        assert!(records.iter().all(|r| r.log_id == "example.com" && r.v == AUDIT_RECORD_VERSION));
1408        assert_eq!(records[0].ext["releaseSeq"], 7);
1409        std::fs::remove_dir_all(dir).ok();
1410    }
1411
1412    #[tokio::test]
1413    async fn an_unfinished_line_is_cut_and_never_read() {
1414        use std::io::Write as _;
1415
1416        let dir = std::env::temp_dir().join(format!("adk-audit-{}", uuid::Uuid::new_v4()));
1417        let path = dir.join("audit.jsonl");
1418        let recorder = FileAuditRecorder::open(&path).unwrap();
1419        recorder.record(draft("site.content.approved")).await.unwrap();
1420        std::fs::OpenOptions::new()
1421            .append(true)
1422            .open(&path)
1423            .unwrap()
1424            .write_all(b"{\"v\":1,\"logId\":\"torn")
1425            .unwrap();
1426        assert_eq!(FileAuditRecorder::read(&path).unwrap().len(), 1, "the torn line is left out");
1427
1428        let reopened = FileAuditRecorder::open(&path).unwrap();
1429        reopened.record(draft("site.content.withdrawn")).await.unwrap();
1430        let records = FileAuditRecorder::read(&path).unwrap();
1431        assert_eq!(
1432            records.iter().map(|r| (r.seq, r.action.as_str())).collect::<Vec<_>>(),
1433            vec![(0, "site.content.approved"), (1, "site.content.withdrawn")]
1434        );
1435        std::fs::remove_dir_all(dir).ok();
1436    }
1437
1438    #[test]
1439    fn the_file_digest_is_sha256_of_the_canonical_json() {
1440        let dir = std::env::temp_dir().join(format!("adk-audit-{}", uuid::Uuid::new_v4()));
1441        let recorder = FileAuditRecorder::open(dir.join("audit.jsonl")).unwrap();
1442        let a = recorder.digest(&serde_json::json!({ "b": 1, "a": [1, 2] }));
1443        let b = recorder.digest(&serde_json::json!({ "a": [1, 2], "b": 1 }));
1444        assert_eq!(a, b);
1445        assert!(a.starts_with("sha256:") && a.len() == 7 + 64, "{a}");
1446        std::fs::remove_dir_all(dir).ok();
1447    }
1448
1449    #[test]
1450    fn hash_rejects_bad_text() {
1451        assert!("ab".parse::<AuditHash>().is_err());
1452        assert!("G".repeat(64).parse::<AuditHash>().is_err());
1453        assert!("AB".repeat(32).parse::<AuditHash>().is_err());
1454    }
1455
1456    #[test]
1457    fn kind_round_trips_unknown_names() {
1458        let kind: AuditRecordKind = serde_json::from_str("\"deploy\"").unwrap();
1459        assert_eq!(kind, AuditRecordKind::Other("deploy".into()));
1460        assert_eq!(serde_json::to_string(&AuditRecordKind::KeyRotated).unwrap(), "\"key_rotated\"");
1461        assert_eq!(serde_json::to_string(&kind).unwrap(), "\"deploy\"");
1462    }
1463}