1use 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
43pub const AUDIT_RECORD_VERSION: u32 = 1;
45
46#[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 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#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
130#[error("invalid audit hash: {0}")]
131pub struct InvalidAuditHash(String);
132
133#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
136#[serde(from = "String", into = "String")]
137#[non_exhaustive]
138pub enum AuditRecordKind {
139 ToolCall,
141 Approval,
143 Governance,
145 Payment,
147 Access,
149 Authentication,
151 Configuration,
153 KeyRotated,
155 Erasure,
158 SessionHistory,
161 Other(String),
163}
164
165impl AuditRecordKind {
166 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
213#[serde(rename_all = "snake_case")]
214#[non_exhaustive]
215pub enum AuditDecision {
216 Allowed,
218 Denied,
220 ApprovalRequired,
222 Approved,
224 Rejected,
226}
227
228#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
230#[serde(rename_all = "snake_case")]
231#[non_exhaustive]
232pub enum AuditRecordOutcome {
233 Succeeded,
235 Failed,
237 OutcomeUnknown,
239 NotRun,
241}
242
243#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
255#[serde(rename_all = "camelCase")]
256pub struct AuditActor {
257 #[serde(default, skip_serializing_if = "Option::is_none")]
259 pub agent: Option<AgentId>,
260 #[serde(default, skip_serializing_if = "Option::is_none")]
262 pub tenant: Option<String>,
263 #[serde(default, skip_serializing_if = "Option::is_none")]
265 pub instance: Option<String>,
266 #[serde(default, skip_serializing_if = "Option::is_none")]
268 pub on_behalf_of: Option<SubjectRef>,
269 #[serde(default, skip_serializing_if = "Vec::is_empty")]
271 pub delegation_chain: Vec<SubjectRef>,
272 #[serde(default, skip_serializing_if = "Option::is_none")]
274 pub invocation_id: Option<String>,
275}
276
277impl AuditActor {
278 pub fn subject(subject: SubjectRef) -> Self {
280 Self { on_behalf_of: Some(subject), ..Self::default() }
281 }
282}
283
284impl AuditActor {
285 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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
318#[serde(rename_all = "camelCase")]
319pub struct AuditRecord {
320 pub v: u32,
322 pub log_id: String,
324 pub seq: u64,
326 pub ts: DateTime<Utc>,
328 #[serde(default, skip_serializing_if = "Option::is_none")]
330 pub prev_hash: Option<AuditHash>,
331 pub actor: AuditActor,
333 pub kind: AuditRecordKind,
335 pub action: String,
337 #[serde(default, skip_serializing_if = "Option::is_none")]
339 pub args_digest: Option<String>,
340 #[serde(default, skip_serializing_if = "Option::is_none")]
342 pub decision: Option<AuditDecision>,
343 #[serde(default, skip_serializing_if = "Option::is_none")]
345 pub outcome: Option<AuditRecordOutcome>,
346 #[serde(default, skip_serializing_if = "Option::is_none")]
348 pub policy_ref: Option<String>,
349 #[serde(default, skip_serializing_if = "Option::is_none")]
351 pub payload_ref: Option<String>,
352 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
354 pub ext: BTreeMap<String, serde_json::Value>,
355}
356
357#[derive(Debug, Clone, PartialEq)]
370pub struct AuditRecordDraft {
371 pub actor: AuditActor,
373 pub kind: AuditRecordKind,
375 pub action: String,
377 pub args_digest: Option<String>,
379 pub decision: Option<AuditDecision>,
381 pub outcome: Option<AuditRecordOutcome>,
383 pub policy_ref: Option<String>,
385 pub payload_ref: Option<String>,
387 pub ext: BTreeMap<String, serde_json::Value>,
389}
390
391impl AuditRecordDraft {
392 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 pub fn actor(mut self, actor: AuditActor) -> Self {
409 self.actor = actor;
410 self
411 }
412
413 pub fn args_digest(mut self, digest: impl Into<String>) -> Self {
415 self.args_digest = Some(digest.into());
416 self
417 }
418
419 pub fn decision(mut self, decision: AuditDecision) -> Self {
421 self.decision = Some(decision);
422 self
423 }
424
425 pub fn outcome(mut self, outcome: AuditRecordOutcome) -> Self {
427 self.outcome = Some(outcome);
428 self
429 }
430
431 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 pub fn payload_ref(mut self, digest: impl Into<String>) -> Self {
439 self.payload_ref = Some(digest.into());
440 self
441 }
442
443 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 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
478#[serde(rename_all = "camelCase")]
479pub struct AuditLogEntry {
480 pub seq: u64,
482 pub leaf_hash: AuditHash,
484 #[serde(default, skip_serializing_if = "Option::is_none")]
486 pub record: Option<String>,
487}
488
489#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
492#[serde(rename_all = "camelCase")]
493pub struct AuditTreeNode {
494 pub level: u8,
496 pub index: u64,
498 pub hash: AuditHash,
500}
501
502#[derive(Debug, Clone, PartialEq, Eq)]
504pub struct AuditAppend {
505 pub log_id: String,
507 pub entries: Vec<AuditLogEntry>,
509 pub nodes: Vec<AuditTreeNode>,
511}
512
513#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
515#[serde(rename_all = "camelCase")]
516pub struct AuditCheckpoint {
517 pub log_id: String,
519 pub size: u64,
521 pub root_hash: AuditHash,
523 pub note: String,
525 pub created_at: DateTime<Utc>,
527}
528
529#[async_trait]
557pub trait AuditLogStore: Send + Sync {
558 async fn append(&self, batch: AuditAppend) -> Result<Range<u64>>;
566
567 async fn size(&self, log_id: &str) -> Result<u64>;
569
570 async fn read(&self, log_id: &str, range: Range<u64>) -> Result<Vec<AuditLogEntry>>;
576
577 async fn hash_at(&self, log_id: &str, level: u8, index: u64) -> Result<Option<AuditHash>>;
580
581 async fn put_checkpoint(&self, checkpoint: AuditCheckpoint) -> Result<()>;
589
590 async fn latest_checkpoint(&self, log_id: &str) -> Result<Option<AuditCheckpoint>>;
592
593 async fn checkpoints(&self, log_id: &str) -> Result<Vec<AuditCheckpoint>>;
595
596 async fn prune(&self, log_id: &str, before_seq: u64) -> Result<u64>;
603
604 async fn logs(&self) -> Result<Vec<String>>;
606
607 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
629pub 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
647pub 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
659pub 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
668pub 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
688pub 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
730pub 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#[derive(Debug, Clone, Default)]
765pub struct InMemoryAuditLogStore {
766 logs: Arc<tokio::sync::RwLock<HashMap<String, MemoryLog>>>,
767}
768
769impl InMemoryAuditLogStore {
770 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
901pub enum AuditFailureMode {
902 #[default]
904 Block,
905 Warn,
907}
908
909#[async_trait]
934pub trait AuditRecorder: Send + Sync {
935 fn digest(&self, value: &serde_json::Value) -> String;
938
939 async fn record(&self, draft: AuditRecordDraft) -> Result<()>;
945
946 async fn seal(&self) -> Result<()> {
954 Ok(())
955 }
956}
957
958#[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 pub fn new(recorder: Arc<dyn AuditRecorder>) -> Self {
990 Self { recorder, failure_mode: AuditFailureMode::Block }
991 }
992
993 #[must_use]
995 pub fn with_failure_mode(mut self, mode: AuditFailureMode) -> Self {
996 self.failure_mode = mode;
997 self
998 }
999
1000 pub fn failure_mode(&self) -> AuditFailureMode {
1002 self.failure_mode
1003 }
1004
1005 pub fn recorder(&self) -> &Arc<dyn AuditRecorder> {
1007 &self.recorder
1008 }
1009
1010 pub fn digest(&self, value: &serde_json::Value) -> String {
1012 self.recorder.digest(value)
1013 }
1014
1015 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 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 pub fn for_context(ctx: &dyn crate::ReadonlyContext) -> Self {
1086 Self::new(&ctx.acting_context(), ctx.invocation_id())
1087 }
1088}
1089
1090#[derive(Debug, Clone, Default)]
1104pub struct InMemoryAuditRecorder {
1105 records: Arc<std::sync::Mutex<Vec<AuditRecordDraft>>>,
1106}
1107
1108impl InMemoryAuditRecorder {
1109 pub fn new() -> Self {
1111 Self::default()
1112 }
1113
1114 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#[derive(Clone)]
1165pub struct FileAuditRecorder {
1166 path: std::path::PathBuf,
1167 log_id: String,
1168 state: Arc<std::sync::Mutex<FileAuditState>>,
1169}
1170
1171#[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
1200fn 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 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 #[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 pub fn path(&self) -> &std::path::Path {
1241 &self.path
1242 }
1243
1244 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 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 fn append(&self, draft: AuditRecordDraft) -> Result<()> {
1283 use std::io::{Read as _, Seek as _, SeekFrom, Write as _};
1284
1285 let path = &self.path;
1286 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 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 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 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}