Skip to main content

adk_auth/signed_audit/
log.rs

1//! The signed audit log writer.
2
3use std::path::PathBuf;
4use std::sync::Arc;
5use std::time::Duration;
6
7use adk_core::audit_log::{
8    AuditActor, AuditAppend, AuditCheckpoint, AuditDecision, AuditHash, AuditLogEntry,
9    AuditLogStore, AuditRecord, AuditRecordDraft, AuditRecordKind, AuditRecordOutcome,
10};
11use adk_core::principal::SubjectRef;
12use adk_core::{AdkError, Clock, ErrorCategory, ErrorComponent, Result, SystemClock};
13use async_trait::async_trait;
14use chrono::{DateTime, Utc};
15use sha2::{Digest, Sha256};
16use tokio::sync::Mutex;
17
18use super::jcs::canonicalize;
19use super::merkle::{
20    Frontier, consistency_ranges, fold_range, inclusion_ranges, leaf_hash, range_nodes,
21};
22use super::note::{AuditSigner, CheckpointBody, sign_note};
23use crate::audit::{AuditEvent, AuditEventType, AuditOutcome, AuditSink};
24
25/// Default number of records between checkpoints.
26pub const DEFAULT_CHECKPOINT_EVERY: u64 = 256;
27/// Default time between checkpoints while records keep arriving.
28pub const DEFAULT_CHECKPOINT_INTERVAL: Duration = Duration::from_secs(60);
29
30fn audit_error(category: ErrorCategory, code: &'static str, message: String) -> AdkError {
31    AdkError::new(ErrorComponent::Auth, category, code, message)
32}
33
34/// Returns `sha256:<hex>` of the RFC 8785 canonical form of `value`, the digest format
35/// for `args_digest` and `payload_ref`.
36///
37/// # Example
38///
39/// ```rust
40/// use adk_auth::signed_audit::json_sha256;
41/// use serde_json::json;
42///
43/// let a = json_sha256(&json!({ "to": "acct-1", "amount": 5 })).unwrap();
44/// let b = json_sha256(&json!({ "amount": 5, "to": "acct-1" })).unwrap();
45/// assert_eq!(a, b);
46/// assert!(a.starts_with("sha256:"));
47/// ```
48///
49/// # Errors
50///
51/// `audit_log.not_canonical` when `value` holds an integer outside ±2^53.
52pub fn json_sha256(value: &serde_json::Value) -> Result<String> {
53    let canonical = canonicalize(value).map_err(|e| {
54        audit_error(ErrorCategory::InvalidInput, "audit_log.not_canonical", e.to_string())
55    })?;
56    Ok(format!("sha256:{}", AuditHash(Sha256::digest(canonical.as_bytes()).into())))
57}
58
59/// Publishes signed checkpoints somewhere the log's operator cannot rewrite: a witness,
60/// a transparency log, a timestamp authority, or a write-once file.
61///
62/// Anchors are optional. A failing anchor is logged and does not fail the append.
63#[async_trait]
64pub trait CheckpointAnchor: Send + Sync {
65    /// A short name for logs.
66    fn name(&self) -> &str;
67
68    /// Publishes `checkpoint`.
69    ///
70    /// # Errors
71    ///
72    /// Returns an error when the checkpoint could not be published.
73    async fn anchor(&self, checkpoint: &AuditCheckpoint) -> Result<()>;
74}
75
76/// A [`CheckpointAnchor`] that appends each checkpoint as a JSON line to a file, such as
77/// one on a write-once mount or a separately administered host.
78///
79/// [`read`](Self::read) returns the checkpoints for [`verify`](super::verify), which
80/// detects a log rewritten after the anchored checkpoints were written.
81///
82/// # Example
83///
84/// ```rust,no_run
85/// use adk_auth::signed_audit::FileCheckpointAnchor;
86///
87/// let anchor = FileCheckpointAnchor::new("/mnt/worm/audit-checkpoints.jsonl");
88/// let checkpoints = FileCheckpointAnchor::read("/mnt/worm/audit-checkpoints.jsonl").unwrap();
89/// # let _ = (anchor, checkpoints);
90/// ```
91#[derive(Debug)]
92pub struct FileCheckpointAnchor {
93    path: PathBuf,
94    lock: Mutex<()>,
95}
96
97impl FileCheckpointAnchor {
98    /// Anchors to the file at `path`, creating it on first write.
99    pub fn new(path: impl Into<PathBuf>) -> Self {
100        Self { path: path.into(), lock: Mutex::new(()) }
101    }
102
103    /// Reads every checkpoint the anchor wrote.
104    ///
105    /// # Errors
106    ///
107    /// Returns an error when the file cannot be read or a line is not a checkpoint.
108    pub fn read(path: impl AsRef<std::path::Path>) -> Result<Vec<AuditCheckpoint>> {
109        let text = std::fs::read_to_string(path).map_err(|e| {
110            audit_error(ErrorCategory::Unavailable, "audit_log.anchor_failed", e.to_string())
111        })?;
112        text.lines()
113            .filter(|line| !line.trim().is_empty())
114            .map(|line| {
115                serde_json::from_str(line).map_err(|e| {
116                    audit_error(
117                        ErrorCategory::InvalidInput,
118                        "audit_log.anchor_failed",
119                        format!("anchor line is not a checkpoint: {e}"),
120                    )
121                })
122            })
123            .collect()
124    }
125}
126
127#[async_trait]
128impl CheckpointAnchor for FileCheckpointAnchor {
129    fn name(&self) -> &str {
130        "file"
131    }
132
133    async fn anchor(&self, checkpoint: &AuditCheckpoint) -> Result<()> {
134        use std::io::Write;
135        let line = serde_json::to_string(checkpoint).map_err(|e| {
136            audit_error(ErrorCategory::Internal, "audit_log.anchor_failed", e.to_string())
137        })?;
138        let _guard = self.lock.lock().await;
139        std::fs::OpenOptions::new()
140            .create(true)
141            .append(true)
142            .open(&self.path)
143            .and_then(|mut file| {
144                writeln!(file, "{line}")?;
145                file.sync_data()
146            })
147            .map_err(|e| {
148                audit_error(ErrorCategory::Unavailable, "audit_log.anchor_failed", e.to_string())
149            })
150    }
151}
152
153struct WriterState {
154    frontier: Frontier,
155    last_leaf: Option<AuditHash>,
156    signer: Arc<dyn AuditSigner>,
157    checkpointed_size: u64,
158    checkpointed_at: DateTime<Utc>,
159    // Set while a store append is in flight. A caller dropped at that await leaves it set with
160    // the store possibly ahead of `frontier`, so the next append reloads the frontier.
161    append_unsettled: bool,
162}
163
164/// Reads the frontier and last leaf hash of `log_id` from what the store holds.
165async fn stored_frontier(
166    store: &dyn AuditLogStore,
167    log_id: &str,
168) -> Result<(Frontier, Option<AuditHash>)> {
169    let size = store.size(log_id).await?;
170    let mut hashes = Vec::new();
171    for (level, index) in range_nodes(0..size) {
172        hashes.push(stored_hash(store, log_id, level, index).await?);
173    }
174    let last_leaf = match size {
175        0 => None,
176        _ => Some(stored_hash(store, log_id, 0, size - 1).await?),
177    };
178    Ok((Frontier { size, hashes }, last_leaf))
179}
180
181/// A signed, Merkle-hashed, append-only audit log for one replica.
182///
183/// Each appended record is canonicalized with RFC 8785, linked to the previous record
184/// through `prev_hash`, and added as a leaf to an RFC 9162 Merkle tree. Every
185/// `checkpoint_every` records, or once `checkpoint_interval` has passed since the last
186/// checkpoint, the log signs a C2SP checkpoint of the tree, stores it, and hands it to
187/// the configured anchors.
188///
189/// `AuditLog` is an [`AuditSink`], so it can back [`ProtectedTool`](crate::ProtectedTool)
190/// and [`ScopedTool`](crate::ScopedTool) directly.
191///
192/// # Example
193///
194/// ```rust
195/// use std::sync::Arc;
196/// use adk_auth::signed_audit::{AuditLog, Ed25519Signer};
197/// use adk_core::audit_log::{AuditDecision, AuditRecordDraft, AuditRecordKind, InMemoryAuditLogStore};
198///
199/// # async fn demo() -> adk_core::Result<()> {
200/// let signer = Arc::new(Ed25519Signer::generate("audit.example.com").unwrap());
201/// let log = AuditLog::builder(Arc::new(InMemoryAuditLogStore::new()), "replica-1", signer)
202///     .checkpoint_every(100)
203///     .open()
204///     .await?;
205/// log.append(AuditRecordDraft::new(AuditRecordKind::ToolCall, "transfer").decision(AuditDecision::Allowed))
206///     .await?;
207/// let checkpoint = log.checkpoint().await?;
208/// assert_eq!(checkpoint.size, 1);
209/// # Ok(())
210/// # }
211/// ```
212pub struct AuditLog {
213    store: Arc<dyn AuditLogStore>,
214    log_id: String,
215    origin: String,
216    clock: Arc<dyn Clock>,
217    checkpoint_every: u64,
218    checkpoint_interval: Duration,
219    anchors: Vec<Arc<dyn CheckpointAnchor>>,
220    state: Mutex<WriterState>,
221}
222
223impl std::fmt::Debug for AuditLog {
224    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
225        f.debug_struct("AuditLog")
226            .field("log_id", &self.log_id)
227            .field("origin", &self.origin)
228            .finish_non_exhaustive()
229    }
230}
231
232/// Builds an [`AuditLog`].
233pub struct AuditLogBuilder {
234    store: Arc<dyn AuditLogStore>,
235    log_id: String,
236    signer: Arc<dyn AuditSigner>,
237    origin: Option<String>,
238    clock: Arc<dyn Clock>,
239    checkpoint_every: u64,
240    checkpoint_interval: Duration,
241    anchors: Vec<Arc<dyn CheckpointAnchor>>,
242}
243
244impl AuditLogBuilder {
245    /// Sets the checkpoint origin line. Defaults to `adk-audit/<log_id>`.
246    pub fn origin(mut self, origin: impl Into<String>) -> Self {
247        self.origin = Some(origin.into());
248        self
249    }
250
251    /// Sets the clock that stamps records and paces checkpoints.
252    pub fn clock(mut self, clock: Arc<dyn Clock>) -> Self {
253        self.clock = clock;
254        self
255    }
256
257    /// Signs a checkpoint after this many records (minimum 1).
258    pub fn checkpoint_every(mut self, records: u64) -> Self {
259        self.checkpoint_every = records.max(1);
260        self
261    }
262
263    /// Signs a checkpoint on the first append after this much time.
264    pub fn checkpoint_interval(mut self, interval: Duration) -> Self {
265        self.checkpoint_interval = interval;
266        self
267    }
268
269    /// Adds an anchor that receives every checkpoint.
270    pub fn anchor(mut self, anchor: Arc<dyn CheckpointAnchor>) -> Self {
271        self.anchors.push(anchor);
272        self
273    }
274
275    /// Opens the log, resuming from what the store holds.
276    ///
277    /// # Errors
278    ///
279    /// `audit_log.invalid_config` for an origin with a newline; `audit_log.corrupt` when
280    /// a stored subtree hash is missing or the latest checkpoint's root does not match
281    /// the stored tree; store errors otherwise.
282    pub async fn open(self) -> Result<AuditLog> {
283        let origin = self.origin.unwrap_or_else(|| format!("adk-audit/{}", self.log_id));
284        if origin.is_empty() || origin.contains('\n') || self.log_id.is_empty() {
285            return Err(audit_error(
286                ErrorCategory::InvalidInput,
287                "audit_log.invalid_config",
288                "log_id and origin must be non-empty and the origin a single line".into(),
289            ));
290        }
291        let (frontier, last_leaf) = stored_frontier(self.store.as_ref(), &self.log_id).await?;
292        let latest = self.store.latest_checkpoint(&self.log_id).await?;
293        if let Some(checkpoint) = &latest {
294            let root = subtree_root(self.store.as_ref(), &self.log_id, 0..checkpoint.size).await?;
295            if root != checkpoint.root_hash {
296                return Err(audit_error(
297                    ErrorCategory::Internal,
298                    "audit_log.corrupt",
299                    format!(
300                        "audit log '{}' no longer matches its checkpoint at size {}; \
301                         stop writing and verify the log",
302                        self.log_id, checkpoint.size
303                    ),
304                ));
305            }
306        }
307        let now = self.clock.now();
308        Ok(AuditLog {
309            state: Mutex::new(WriterState {
310                frontier,
311                last_leaf,
312                signer: self.signer,
313                checkpointed_size: latest.as_ref().map_or(0, |c| c.size),
314                checkpointed_at: latest.map_or(now, |c| c.created_at),
315                append_unsettled: false,
316            }),
317            store: self.store,
318            log_id: self.log_id,
319            origin,
320            clock: self.clock,
321            checkpoint_every: self.checkpoint_every,
322            checkpoint_interval: self.checkpoint_interval,
323            anchors: self.anchors,
324        })
325    }
326}
327
328async fn stored_hash(
329    store: &dyn AuditLogStore,
330    log_id: &str,
331    level: u8,
332    index: u64,
333) -> Result<AuditHash> {
334    store.hash_at(log_id, level, index).await?.ok_or_else(|| {
335        audit_error(
336            ErrorCategory::Internal,
337            "audit_log.corrupt",
338            format!(
339                "audit log '{log_id}' is missing the subtree hash at level {level}, index {index}"
340            ),
341        )
342    })
343}
344
345async fn subtree_root(
346    store: &dyn AuditLogStore,
347    log_id: &str,
348    range: std::ops::Range<u64>,
349) -> Result<AuditHash> {
350    let mut hashes = Vec::new();
351    for (level, index) in range_nodes(range) {
352        hashes.push(stored_hash(store, log_id, level, index).await?);
353    }
354    Ok(fold_range(&hashes))
355}
356
357impl AuditLog {
358    /// Starts building a log over `store` with id `log_id`, signing with `signer`.
359    ///
360    /// Give every replica its own `log_id`; a second writer on the same id is refused
361    /// with `audit_log.seq_conflict`.
362    pub fn builder(
363        store: Arc<dyn AuditLogStore>,
364        log_id: impl Into<String>,
365        signer: Arc<dyn AuditSigner>,
366    ) -> AuditLogBuilder {
367        AuditLogBuilder {
368            store,
369            log_id: log_id.into(),
370            signer,
371            origin: None,
372            clock: Arc::new(SystemClock),
373            checkpoint_every: DEFAULT_CHECKPOINT_EVERY,
374            checkpoint_interval: DEFAULT_CHECKPOINT_INTERVAL,
375            anchors: Vec::new(),
376        }
377    }
378
379    /// The log id.
380    pub fn log_id(&self) -> &str {
381        &self.log_id
382    }
383
384    /// The checkpoint origin line.
385    pub fn origin(&self) -> &str {
386        &self.origin
387    }
388
389    /// The store the log writes to.
390    pub fn store(&self) -> &Arc<dyn AuditLogStore> {
391        &self.store
392    }
393
394    /// Number of records in the log.
395    pub async fn size(&self) -> u64 {
396        self.state.lock().await.frontier.size
397    }
398
399    /// The verifier key of the current signer.
400    pub async fn verifier_key(&self) -> String {
401        self.state.lock().await.signer.verifier_key()
402    }
403
404    /// Appends one record and signs a checkpoint when one is due.
405    ///
406    /// # Errors
407    ///
408    /// `audit_log.not_canonical` when an extension value is not I-JSON; store errors,
409    /// including `audit_log.seq_conflict` when another writer uses this `log_id`.
410    pub async fn append(&self, draft: AuditRecordDraft) -> Result<AuditRecord> {
411        let mut records = self.append_batch(vec![draft]).await?;
412        Ok(records.pop().expect("one draft yields one record"))
413    }
414
415    /// Appends records atomically and signs a checkpoint when one is due.
416    ///
417    /// # Errors
418    ///
419    /// As [`append`](Self::append).
420    pub async fn append_batch(&self, drafts: Vec<AuditRecordDraft>) -> Result<Vec<AuditRecord>> {
421        let mut state = self.state.lock().await;
422        let records = self.append_locked(&mut state, drafts).await?;
423        let due = state.frontier.size - state.checkpointed_size >= self.checkpoint_every
424            || self.interval_elapsed(&state);
425        if due && state.frontier.size > state.checkpointed_size {
426            let signers = vec![state.signer.clone()];
427            if let Err(error) = self.checkpoint_locked(&mut state, &signers).await {
428                // The records are durable; the next append or `checkpoint` retries.
429                tracing::warn!(audit.log_id = %self.log_id, error = %error, "audit checkpoint failed");
430            }
431        }
432        Ok(records)
433    }
434
435    fn interval_elapsed(&self, state: &WriterState) -> bool {
436        let elapsed = self.clock.now().signed_duration_since(state.checkpointed_at);
437        elapsed.to_std().is_ok_and(|elapsed| elapsed >= self.checkpoint_interval)
438    }
439
440    async fn append_locked(
441        &self,
442        state: &mut WriterState,
443        drafts: Vec<AuditRecordDraft>,
444    ) -> Result<Vec<AuditRecord>> {
445        if drafts.is_empty() {
446            return Ok(Vec::new());
447        }
448        if state.append_unsettled {
449            let (frontier, last_leaf) = stored_frontier(self.store.as_ref(), &self.log_id).await?;
450            state.frontier = frontier;
451            state.last_leaf = last_leaf;
452            state.append_unsettled = false;
453        }
454        let ts = self.clock.now();
455        let mut frontier = state.frontier.clone();
456        let mut prev = state.last_leaf;
457        let mut records = Vec::with_capacity(drafts.len());
458        let mut entries = Vec::with_capacity(drafts.len());
459        let mut nodes = Vec::new();
460        for draft in drafts {
461            let record = draft.into_record(&self.log_id, frontier.size, ts, prev);
462            let value = serde_json::to_value(&record).map_err(|e| {
463                audit_error(ErrorCategory::Internal, "audit_log.not_canonical", e.to_string())
464            })?;
465            let canonical = canonicalize(&value).map_err(|e| {
466                audit_error(ErrorCategory::InvalidInput, "audit_log.not_canonical", e.to_string())
467            })?;
468            let leaf = leaf_hash(canonical.as_bytes());
469            entries.push(AuditLogEntry {
470                seq: record.seq,
471                leaf_hash: leaf,
472                record: Some(canonical),
473            });
474            nodes.extend(frontier.push(leaf));
475            prev = Some(leaf);
476            records.push(record);
477        }
478        state.append_unsettled = true;
479        let appended =
480            self.store.append(AuditAppend { log_id: self.log_id.clone(), entries, nodes }).await;
481        // A sequence conflict is a second writer on this log_id, which stays refused; any other
482        // failure may have written the batch, so the flag stays set.
483        if let Err(error) = appended {
484            state.append_unsettled = error.code != "audit_log.seq_conflict";
485            return Err(error);
486        }
487        state.append_unsettled = false;
488        state.frontier = frontier;
489        state.last_leaf = prev;
490        Ok(records)
491    }
492
493    async fn checkpoint_locked(
494        &self,
495        state: &mut WriterState,
496        signers: &[Arc<dyn AuditSigner>],
497    ) -> Result<AuditCheckpoint> {
498        let body = CheckpointBody {
499            origin: self.origin.clone(),
500            size: state.frontier.size,
501            root_hash: state.frontier.root(),
502        };
503        let note = sign_note(&body.to_text(), signers).await.map_err(|e| {
504            audit_error(ErrorCategory::Unavailable, "audit_log.signing_failed", e.to_string())
505        })?;
506        let checkpoint = AuditCheckpoint {
507            log_id: self.log_id.clone(),
508            size: body.size,
509            root_hash: body.root_hash,
510            note,
511            created_at: self.clock.now(),
512        };
513        self.store.put_checkpoint(checkpoint.clone()).await?;
514        state.checkpointed_size = checkpoint.size;
515        state.checkpointed_at = checkpoint.created_at;
516        for anchor in &self.anchors {
517            if let Err(error) = anchor.anchor(&checkpoint).await {
518                tracing::warn!(
519                    audit.log_id = %self.log_id,
520                    audit.anchor = anchor.name(),
521                    error = %error,
522                    "audit checkpoint anchor failed"
523                );
524            }
525        }
526        Ok(checkpoint)
527    }
528
529    /// Signs and stores a checkpoint of the current tree, even when nothing changed.
530    ///
531    /// # Errors
532    ///
533    /// `audit_log.signing_failed` when the signer fails; store errors otherwise.
534    pub async fn checkpoint(&self) -> Result<AuditCheckpoint> {
535        let mut state = self.state.lock().await;
536        let signers = vec![state.signer.clone()];
537        self.checkpoint_locked(&mut state, &signers).await
538    }
539
540    /// Signs a checkpoint when records were appended since the last one and the
541    /// interval has passed. Returns the checkpoint when one was signed.
542    ///
543    /// # Errors
544    ///
545    /// As [`checkpoint`](Self::checkpoint).
546    pub async fn checkpoint_if_due(&self) -> Result<Option<AuditCheckpoint>> {
547        let mut state = self.state.lock().await;
548        if state.frontier.size == state.checkpointed_size || !self.interval_elapsed(&state) {
549            return Ok(None);
550        }
551        let signers = vec![state.signer.clone()];
552        self.checkpoint_locked(&mut state, &signers).await.map(Some)
553    }
554
555    /// Spawns a task that calls [`checkpoint_if_due`](Self::checkpoint_if_due) every
556    /// `checkpoint_interval`, so an idle log's last records are still checkpointed.
557    pub fn spawn_checkpoint_timer(self: &Arc<Self>) -> tokio::task::JoinHandle<()> {
558        let log = Arc::clone(self);
559        tokio::spawn(async move {
560            let mut ticker =
561                tokio::time::interval(log.checkpoint_interval.max(Duration::from_millis(10)));
562            ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
563            loop {
564                ticker.tick().await;
565                if let Err(error) = log.checkpoint_if_due().await {
566                    tracing::warn!(audit.log_id = %log.log_id, error = %error, "audit checkpoint failed");
567                }
568            }
569        })
570    }
571
572    /// Rotates the checkpoint signing key.
573    ///
574    /// Appends a `key_rotated` record naming both verifier keys, signs the next
575    /// checkpoint with the old and the new key, and signs later checkpoints with the
576    /// new key only. A verifier that trusts the old key learns the new one from that
577    /// dual-signed checkpoint.
578    ///
579    /// # Errors
580    ///
581    /// As [`append`](Self::append) and [`checkpoint`](Self::checkpoint). When the
582    /// checkpoint fails, the old key stays active; call `rotate_signer` again.
583    pub async fn rotate_signer(
584        &self,
585        next: Arc<dyn AuditSigner>,
586        actor: AuditActor,
587    ) -> Result<AuditCheckpoint> {
588        let mut state = self.state.lock().await;
589        let previous = state.signer.clone();
590        let draft = AuditRecordDraft::new(AuditRecordKind::KeyRotated, "rotate_checkpoint_key")
591            .actor(actor)
592            .ext("previousKey", serde_json::Value::String(previous.verifier_key()))
593            .ext("nextKey", serde_json::Value::String(next.verifier_key()));
594        self.append_locked(&mut state, vec![draft]).await?;
595        let checkpoint = self.checkpoint_locked(&mut state, &[previous, next.clone()]).await?;
596        state.signer = next;
597        Ok(checkpoint)
598    }
599
600    /// The RFC 9162 inclusion proof for record `seq` in the tree of `size` records.
601    ///
602    /// # Errors
603    ///
604    /// `audit_log.out_of_range` when `seq >= size` or `size` exceeds the log.
605    pub async fn inclusion_proof(&self, seq: u64, size: u64) -> Result<Vec<AuditHash>> {
606        self.check_size(size).await?;
607        if seq >= size {
608            return Err(adk_core::audit_log::out_of_range_error(&self.log_id, size, seq));
609        }
610        let mut proof = Vec::new();
611        for range in inclusion_ranges(seq, size) {
612            proof.push(subtree_root(self.store.as_ref(), &self.log_id, range).await?);
613        }
614        Ok(proof)
615    }
616
617    /// The RFC 9162 consistency proof from the tree of `old` records to that of `new`.
618    ///
619    /// # Errors
620    ///
621    /// `audit_log.out_of_range` when `old > new` or `new` exceeds the log.
622    pub async fn consistency_proof(&self, old: u64, new: u64) -> Result<Vec<AuditHash>> {
623        self.check_size(new).await?;
624        if old > new {
625            return Err(adk_core::audit_log::out_of_range_error(&self.log_id, new, old));
626        }
627        let mut proof = Vec::new();
628        for range in consistency_ranges(old, new) {
629            proof.push(subtree_root(self.store.as_ref(), &self.log_id, range).await?);
630        }
631        Ok(proof)
632    }
633
634    /// The root hash of the tree over the first `size` records.
635    ///
636    /// # Errors
637    ///
638    /// `audit_log.out_of_range` when `size` exceeds the log.
639    pub async fn root_at(&self, size: u64) -> Result<AuditHash> {
640        self.check_size(size).await?;
641        subtree_root(self.store.as_ref(), &self.log_id, 0..size).await
642    }
643
644    async fn check_size(&self, size: u64) -> Result<()> {
645        let current = self.size().await;
646        if size > current {
647            return Err(adk_core::audit_log::out_of_range_error(&self.log_id, current, size));
648        }
649        Ok(())
650    }
651}
652
653/// Maps an [`AuditEvent`] onto a record draft. The event's type becomes the record kind,
654/// its user the `on_behalf_of` subject, and its context fields extension fields.
655fn draft_from_event(event: AuditEvent) -> AuditRecordDraft {
656    let kind = match &event.event_type {
657        AuditEventType::ToolAccess
658        | AuditEventType::AgentAccess
659        | AuditEventType::PermissionCheck => AuditRecordKind::Access,
660        AuditEventType::Authentication => AuditRecordKind::Authentication,
661        AuditEventType::ConfigChanged => AuditRecordKind::Configuration,
662        AuditEventType::PaymentExecuted => AuditRecordKind::Payment,
663        AuditEventType::PolicyEvaluated | AuditEventType::Authorization => {
664            AuditRecordKind::Governance
665        }
666        AuditEventType::ResourceCreated => AuditRecordKind::Other("resource_created".into()),
667        AuditEventType::ResourceUpdated => AuditRecordKind::Other("resource_updated".into()),
668        AuditEventType::ResourceDeleted => AuditRecordKind::Other("resource_deleted".into()),
669        AuditEventType::SecretAccessed => AuditRecordKind::Other("secret_accessed".into()),
670        AuditEventType::SecretRotated => AuditRecordKind::Other("secret_rotated".into()),
671        AuditEventType::SessionStarted => AuditRecordKind::Other("session_started".into()),
672        AuditEventType::SessionEnded => AuditRecordKind::Other("session_ended".into()),
673        AuditEventType::Custom(name) => AuditRecordKind::Other(name.clone()),
674    };
675    let (decision, outcome) = match event.outcome {
676        AuditOutcome::Allowed => (Some(AuditDecision::Allowed), None),
677        AuditOutcome::Denied | AuditOutcome::Blocked => (Some(AuditDecision::Denied), None),
678        AuditOutcome::Paused | AuditOutcome::Escalated => {
679            (Some(AuditDecision::ApprovalRequired), None)
680        }
681        AuditOutcome::Error => (None, Some(AuditRecordOutcome::Failed)),
682        AuditOutcome::Created | AuditOutcome::Updated | AuditOutcome::Deleted => {
683            (None, Some(AuditRecordOutcome::Succeeded))
684        }
685    };
686    let mut draft =
687        AuditRecordDraft::new(kind, event.action.clone().unwrap_or_else(|| event.resource.clone()))
688            .actor(AuditActor::subject(SubjectRef::human(event.user)));
689    draft.decision = decision;
690    draft.outcome = outcome;
691    draft.ext.insert("resource".into(), serde_json::Value::String(event.resource));
692    let optional = [
693        ("eventOutcome", serde_json::to_value(&event.outcome).ok()),
694        ("sessionId", event.session_id.map(serde_json::Value::String)),
695        ("workspaceId", event.workspace_id.map(serde_json::Value::String)),
696        ("tenantId", event.tenant_id.map(serde_json::Value::String)),
697        ("requestId", event.request_id.map(serde_json::Value::String)),
698        ("resourceId", event.resource_id.map(serde_json::Value::String)),
699        ("ipAddress", event.ip_address.map(serde_json::Value::String)),
700        ("metadata", event.metadata),
701    ];
702    for (key, value) in optional {
703        if let Some(value) = value {
704            draft.ext.insert(key.into(), value);
705        }
706    }
707    draft
708}
709
710/// The runtime's audit hook: the runner's `audit_log` setting and
711/// [`AuditTrail`](adk_core::audit_log::AuditTrail) record governed actions here.
712///
713/// Digests are [`json_sha256`]; a value with an integer outside ±2^53, which RFC 8785
714/// cannot canonicalize, is digested as `sha256-json:<hex>` over its compact JSON text.
715#[async_trait]
716impl adk_core::audit_log::AuditRecorder for AuditLog {
717    fn digest(&self, value: &serde_json::Value) -> String {
718        json_sha256(value).unwrap_or_else(|_| {
719            let text = serde_json::to_string(value).unwrap_or_default();
720            format!("sha256-json:{}", AuditHash(Sha256::digest(text.as_bytes()).into()))
721        })
722    }
723
724    async fn record(&self, draft: AuditRecordDraft) -> Result<()> {
725        self.append(draft).await.map(drop)
726    }
727
728    /// Signs a checkpoint over the records appended since the last one, without waiting
729    /// for `checkpoint_every` or `checkpoint_interval`; does nothing when every record is
730    /// already signed.
731    async fn seal(&self) -> Result<()> {
732        let mut state = self.state.lock().await;
733        if state.frontier.size == state.checkpointed_size {
734            return Ok(());
735        }
736        let signers = vec![state.signer.clone()];
737        self.checkpoint_locked(&mut state, &signers).await.map(drop)
738    }
739}
740
741#[async_trait]
742impl AuditSink for AuditLog {
743    async fn log(&self, event: AuditEvent) -> std::result::Result<(), crate::AuthError> {
744        self.append(draft_from_event(event))
745            .await
746            .map(drop)
747            .map_err(|e| crate::AuthError::AuditError(e.to_string()))
748    }
749
750    async fn log_batch(
751        &self,
752        events: Vec<AuditEvent>,
753    ) -> std::result::Result<(), crate::AuthError> {
754        self.append_batch(events.into_iter().map(draft_from_event).collect())
755            .await
756            .map(drop)
757            .map_err(|e| crate::AuthError::AuditError(e.to_string()))
758    }
759
760    /// Signs a checkpoint when records were appended since the last one.
761    async fn flush(&self) -> std::result::Result<(), crate::AuthError> {
762        let mut state = self.state.lock().await;
763        if state.frontier.size == state.checkpointed_size {
764            return Ok(());
765        }
766        let signers = vec![state.signer.clone()];
767        self.checkpoint_locked(&mut state, &signers)
768            .await
769            .map(drop)
770            .map_err(|e| crate::AuthError::AuditError(e.to_string()))
771    }
772}