1use chrono::{DateTime, Utc};
19use hmac::{Hmac, Mac};
20use serde::{Deserialize, Serialize};
21use sha2::{Digest, Sha256};
22use std::fs::{File, OpenOptions};
23use std::io::{BufRead, BufReader, BufWriter, Read, Seek, SeekFrom, Write};
24use std::path::{Path, PathBuf};
25use std::sync::Mutex;
26use zeroize::Zeroizing;
27
28#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
34#[serde(rename_all = "snake_case")]
35pub enum AuditEventType {
36 ToolAccess,
38 AgentAccess,
40 PermissionCheck,
42 Authentication,
44 Authorization,
46 ResourceCreated,
48 ResourceUpdated,
50 ResourceDeleted,
52 ConfigChanged,
54 SecretAccessed,
56 SecretRotated,
58 PaymentExecuted,
60 PolicyEvaluated,
62 SessionStarted,
64 SessionEnded,
66 Custom(String),
68}
69
70#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
74#[serde(rename_all = "snake_case")]
75pub enum AuditOutcome {
76 Allowed,
78 Denied,
80 Error,
82 Created,
84 Updated,
86 Deleted,
88 Blocked,
90 Paused,
92 Escalated,
94}
95
96#[derive(Debug, Clone, Serialize, Deserialize)]
102pub struct AuditEvent {
103 pub timestamp: DateTime<Utc>,
105 pub user: String,
107 #[serde(skip_serializing_if = "Option::is_none")]
109 pub session_id: Option<String>,
110 pub event_type: AuditEventType,
112 pub resource: String,
114 pub outcome: AuditOutcome,
116 #[serde(skip_serializing_if = "Option::is_none")]
118 pub metadata: Option<serde_json::Value>,
119
120 #[serde(skip_serializing_if = "Option::is_none")]
123 pub workspace_id: Option<String>,
124 #[serde(skip_serializing_if = "Option::is_none")]
126 pub tenant_id: Option<String>,
127 #[serde(skip_serializing_if = "Option::is_none")]
129 pub request_id: Option<String>,
130 #[serde(skip_serializing_if = "Option::is_none")]
132 pub ip_address: Option<String>,
133 #[serde(skip_serializing_if = "Option::is_none")]
135 pub resource_id: Option<String>,
136 #[serde(skip_serializing_if = "Option::is_none")]
138 pub action: Option<String>,
139 #[serde(skip_serializing_if = "Option::is_none")]
141 pub prev_hash: Option<String>,
142 #[serde(default, skip_serializing_if = "Option::is_none")]
144 pub agent_id: Option<String>,
145 #[serde(default, skip_serializing_if = "Option::is_none")]
147 pub on_behalf_of: Option<adk_core::SubjectRef>,
148}
149
150impl AuditEvent {
151 pub fn new(
153 event_type: AuditEventType,
154 user: impl Into<String>,
155 resource: impl Into<String>,
156 outcome: AuditOutcome,
157 ) -> Self {
158 Self {
159 timestamp: Utc::now(),
160 user: user.into(),
161 session_id: None,
162 event_type,
163 resource: resource.into(),
164 outcome,
165 metadata: None,
166 workspace_id: None,
167 tenant_id: None,
168 request_id: None,
169 ip_address: None,
170 resource_id: None,
171 action: None,
172 prev_hash: None,
173 agent_id: None,
174 on_behalf_of: None,
175 }
176 }
177
178 pub fn tool_access(user: &str, tool_name: &str, outcome: AuditOutcome) -> Self {
180 Self::new(AuditEventType::ToolAccess, user, tool_name, outcome)
181 }
182
183 pub fn agent_access(user: &str, agent_name: &str, outcome: AuditOutcome) -> Self {
185 Self::new(AuditEventType::AgentAccess, user, agent_name, outcome)
186 }
187
188 pub fn authentication(user: &str, outcome: AuditOutcome) -> Self {
190 Self::new(AuditEventType::Authentication, user, "auth", outcome)
191 }
192
193 pub fn resource_event(
195 event_type: AuditEventType,
196 user: &str,
197 resource: &str,
198 resource_id: &str,
199 outcome: AuditOutcome,
200 ) -> Self {
201 Self::new(event_type, user, resource, outcome).with_resource_id(resource_id)
202 }
203
204 pub fn secret_accessed(user: &str, secret_name: &str, outcome: AuditOutcome) -> Self {
206 Self::new(AuditEventType::SecretAccessed, user, secret_name, outcome)
207 }
208
209 pub fn config_changed(user: &str, config_key: &str, outcome: AuditOutcome) -> Self {
211 Self::new(AuditEventType::ConfigChanged, user, config_key, outcome)
212 }
213
214 pub fn custom(event_type: &str, user: &str, resource: &str, outcome: AuditOutcome) -> Self {
216 Self::new(AuditEventType::Custom(event_type.to_string()), user, resource, outcome)
217 }
218
219 pub fn with_session(mut self, session_id: impl Into<String>) -> Self {
221 self.session_id = Some(session_id.into());
222 self
223 }
224
225 pub fn with_metadata(mut self, metadata: serde_json::Value) -> Self {
227 self.metadata = Some(metadata);
228 self
229 }
230
231 pub fn with_workspace(mut self, workspace_id: impl Into<String>) -> Self {
233 self.workspace_id = Some(workspace_id.into());
234 self
235 }
236
237 pub fn with_tenant(mut self, tenant_id: impl Into<String>) -> Self {
239 self.tenant_id = Some(tenant_id.into());
240 self
241 }
242
243 pub fn with_request_id(mut self, request_id: impl Into<String>) -> Self {
245 self.request_id = Some(request_id.into());
246 self
247 }
248
249 pub fn with_ip_address(mut self, ip: impl Into<String>) -> Self {
251 self.ip_address = Some(ip.into());
252 self
253 }
254
255 pub fn with_resource_id(mut self, id: impl Into<String>) -> Self {
257 self.resource_id = Some(id.into());
258 self
259 }
260
261 pub fn with_agent_id(mut self, agent_id: impl Into<String>) -> Self {
263 self.agent_id = Some(agent_id.into());
264 self
265 }
266
267 pub fn with_acting_context(mut self, acting: &adk_core::ActingContext) -> Self {
286 self.agent_id = Some(acting.agent.id.to_string());
287 self.on_behalf_of = acting.on_behalf_of.clone();
288 if self.tenant_id.is_none() {
289 self.tenant_id = acting.agent.tenant.clone();
290 }
291 self
292 }
293
294 pub fn with_action(mut self, action: impl Into<String>) -> Self {
296 self.action = Some(action.into());
297 self
298 }
299
300 pub fn with_prev_hash(mut self, prev_event_json: &str) -> Self {
305 let mut hasher = Sha256::new();
306 hasher.update(prev_event_json.as_bytes());
307 self.prev_hash = Some(hex::encode(hasher.finalize()));
308 self
309 }
310
311 pub fn to_json(&self) -> Result<String, serde_json::Error> {
313 serde_json::to_string(self)
314 }
315}
316
317#[derive(Debug, Clone, Default, Serialize, Deserialize)]
322pub struct AuditFilter {
323 #[serde(skip_serializing_if = "Option::is_none")]
325 pub user: Option<String>,
326 #[serde(skip_serializing_if = "Option::is_none")]
328 pub workspace_id: Option<String>,
329 #[serde(skip_serializing_if = "Option::is_none")]
331 pub tenant_id: Option<String>,
332 #[serde(skip_serializing_if = "Option::is_none")]
334 pub event_type: Option<AuditEventType>,
335 #[serde(skip_serializing_if = "Option::is_none")]
337 pub outcome: Option<AuditOutcome>,
338 #[serde(skip_serializing_if = "Option::is_none")]
340 pub resource: Option<String>,
341 #[serde(skip_serializing_if = "Option::is_none")]
343 pub resource_id: Option<String>,
344 #[serde(default, skip_serializing_if = "Option::is_none")]
346 pub agent_id: Option<String>,
347 #[serde(skip_serializing_if = "Option::is_none")]
349 pub after: Option<DateTime<Utc>>,
350 #[serde(skip_serializing_if = "Option::is_none")]
352 pub before: Option<DateTime<Utc>>,
353 #[serde(skip_serializing_if = "Option::is_none")]
355 pub limit: Option<usize>,
356 #[serde(skip_serializing_if = "Option::is_none")]
358 pub offset: Option<usize>,
359}
360
361impl AuditFilter {
362 pub fn matches(&self, event: &AuditEvent) -> bool {
364 if let Some(ref user) = self.user
365 && &event.user != user
366 {
367 return false;
368 }
369 if let Some(ref ws) = self.workspace_id
370 && event.workspace_id.as_ref() != Some(ws)
371 {
372 return false;
373 }
374 if let Some(ref tid) = self.tenant_id
375 && event.tenant_id.as_ref() != Some(tid)
376 {
377 return false;
378 }
379 if let Some(ref et) = self.event_type
380 && &event.event_type != et
381 {
382 return false;
383 }
384 if let Some(ref oc) = self.outcome
385 && &event.outcome != oc
386 {
387 return false;
388 }
389 if let Some(ref res) = self.resource
390 && !event.resource.contains(res.as_str())
391 {
392 return false;
393 }
394 if let Some(ref rid) = self.resource_id
395 && event.resource_id.as_ref() != Some(rid)
396 {
397 return false;
398 }
399 if let Some(ref agent) = self.agent_id
400 && event.agent_id.as_ref() != Some(agent)
401 {
402 return false;
403 }
404 if let Some(after) = self.after
405 && event.timestamp <= after
406 {
407 return false;
408 }
409 if let Some(before) = self.before
410 && event.timestamp >= before
411 {
412 return false;
413 }
414 true
415 }
416}
417
418#[async_trait::async_trait]
424pub trait AuditSink: Send + Sync {
425 async fn log(&self, event: AuditEvent) -> Result<(), crate::AuthError>;
427
428 async fn log_batch(&self, events: Vec<AuditEvent>) -> Result<(), crate::AuthError> {
433 for event in events {
434 self.log(event).await?;
435 }
436 Ok(())
437 }
438
439 async fn query(&self, _filter: &AuditFilter) -> Result<Vec<AuditEvent>, crate::AuthError> {
444 Ok(Vec::new())
445 }
446
447 async fn purge_before(&self, _cutoff: DateTime<Utc>) -> Result<u64, crate::AuthError> {
452 Ok(0)
453 }
454
455 async fn flush(&self) -> Result<(), crate::AuthError> {
459 Ok(())
460 }
461}
462
463#[async_trait::async_trait]
466impl<T: AuditSink + ?Sized> AuditSink for std::sync::Arc<T> {
467 async fn log(&self, event: AuditEvent) -> Result<(), crate::AuthError> {
468 (**self).log(event).await
469 }
470
471 async fn log_batch(&self, events: Vec<AuditEvent>) -> Result<(), crate::AuthError> {
472 (**self).log_batch(events).await
473 }
474
475 async fn query(&self, filter: &AuditFilter) -> Result<Vec<AuditEvent>, crate::AuthError> {
476 (**self).query(filter).await
477 }
478
479 async fn purge_before(&self, cutoff: DateTime<Utc>) -> Result<u64, crate::AuthError> {
480 (**self).purge_before(cutoff).await
481 }
482
483 async fn flush(&self) -> Result<(), crate::AuthError> {
484 (**self).flush().await
485 }
486}
487
488pub use adk_core::audit_log::AuditFailureMode;
494
495pub(crate) async fn record_decision(
497 sink: &dyn AuditSink,
498 event: AuditEvent,
499 mode: AuditFailureMode,
500 tool_name: &str,
501) -> adk_core::Result<()> {
502 let Err(error) = sink.log(event).await else {
503 return Ok(());
504 };
505 match mode {
506 AuditFailureMode::Block => {
507 tracing::error!(tool.name = %tool_name, error = %error, "audit sink failed; refusing the call");
508 Err(adk_core::AdkError::new(
509 adk_core::ErrorComponent::Auth,
510 adk_core::ErrorCategory::Unavailable,
511 "auth.audit_failed",
512 format!(
513 "tool '{tool_name}' refused: the access decision could not be audited ({error}). \
514 Restore the audit sink, or set AuditFailureMode::Warn to run without a record"
515 ),
516 ))
517 }
518 AuditFailureMode::Warn => {
519 tracing::warn!(tool.name = %tool_name, error = %error, "audit sink failed; continuing without a record");
520 Ok(())
521 }
522 }
523}
524
525fn chain_link(key: Option<&[u8]>, previous_line: &str) -> String {
528 match key {
529 Some(key) => {
530 let mut mac = <Hmac<Sha256> as Mac>::new_from_slice(key)
531 .expect("HMAC-SHA256 accepts keys of any length");
532 mac.update(previous_line.as_bytes());
533 hex::encode(mac.finalize().into_bytes())
534 }
535 None => hex::encode(Sha256::digest(previous_line.as_bytes())),
536 }
537}
538
539fn read_last_line(path: &Path) -> std::io::Result<Option<String>> {
541 const BLOCK: u64 = 8 * 1024;
542 let mut file = match File::open(path) {
543 Ok(file) => file,
544 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
545 Err(error) => return Err(error),
546 };
547 let mut end = file.metadata()?.len();
548 let mut tail: Vec<u8> = Vec::new();
549 while end > 0 {
550 let start = end.saturating_sub(BLOCK);
551 let mut block = vec![0u8; usize::try_from(end - start).unwrap_or(0)];
552 file.seek(SeekFrom::Start(start))?;
553 file.read_exact(&mut block)?;
554 block.extend_from_slice(&tail);
555 tail = block;
556 end = start;
557 let content_end =
558 tail.iter().rposition(|byte| !matches!(byte, b'\n' | b'\r')).map_or(0, |at| at + 1);
559 tail.truncate(content_end);
560 if let Some(newline) = tail.iter().rposition(|byte| *byte == b'\n') {
561 tail.drain(..=newline);
562 break;
563 }
564 }
565 if tail.is_empty() {
566 return Ok(None);
567 }
568 String::from_utf8(tail)
569 .map(Some)
570 .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))
571}
572
573pub struct FileAuditSink {
598 writer: Mutex<BufWriter<File>>,
599 path: PathBuf,
600 last_event_json: Mutex<Option<String>>,
602 chain_enabled: bool,
604 chain_key: Option<Zeroizing<Vec<u8>>>,
606}
607
608impl FileAuditSink {
609 pub fn new(path: impl Into<PathBuf>) -> Result<Self, std::io::Error> {
611 Self::open(path.into(), false, None)
612 }
613
614 pub fn with_chaining(path: impl Into<PathBuf>) -> Result<Self, std::io::Error> {
619 Self::open(path.into(), true, None)
620 }
621
622 pub fn with_hmac_chaining(
627 path: impl Into<PathBuf>,
628 key: impl Into<Vec<u8>>,
629 ) -> Result<Self, std::io::Error> {
630 Self::open(path.into(), true, Some(Zeroizing::new(key.into())))
631 }
632
633 fn open(
634 path: PathBuf,
635 chain_enabled: bool,
636 chain_key: Option<Zeroizing<Vec<u8>>>,
637 ) -> Result<Self, std::io::Error> {
638 let last_event_json = if chain_enabled { read_last_line(&path)? } else { None };
639 let file = OpenOptions::new().create(true).append(true).open(&path)?;
640 Ok(Self {
641 writer: Mutex::new(BufWriter::new(file)),
642 path,
643 last_event_json: Mutex::new(last_event_json),
644 chain_enabled,
645 chain_key,
646 })
647 }
648
649 pub fn path(&self) -> &PathBuf {
651 &self.path
652 }
653
654 pub fn verify(&self) -> Result<u64, crate::AuthError> {
661 self.writer.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).flush()?;
662 Self::verify_file(&self.path, self.chain_key.as_deref().map(Vec::as_slice))
663 }
664
665 pub fn verify_file(
675 path: impl AsRef<Path>,
676 hmac_key: Option<&[u8]>,
677 ) -> Result<u64, crate::AuthError> {
678 let reader = BufReader::new(File::open(path)?);
679 let mut previous: Option<String> = None;
680 let mut events = 0u64;
681 for (index, line) in reader.lines().enumerate() {
682 let line = line?;
683 let number = index + 1;
684 let event: AuditEvent = serde_json::from_str(&line).map_err(|error| {
685 crate::AuthError::AuditError(format!(
686 "audit chain broken at line {number}: not an audit event ({error})"
687 ))
688 })?;
689 let expected = previous.as_deref().map(|previous| chain_link(hmac_key, previous));
690 if event.prev_hash != expected {
691 return Err(crate::AuthError::AuditError(format!(
692 "audit chain broken at line {number}: prev_hash does not match the line before it"
693 )));
694 }
695 previous = Some(line);
696 events += 1;
697 }
698 Ok(events)
699 }
700}
701
702#[async_trait::async_trait]
703impl AuditSink for FileAuditSink {
704 async fn log(&self, mut event: AuditEvent) -> Result<(), crate::AuthError> {
705 let mut last = self.last_event_json.lock().unwrap_or_else(|p| p.into_inner());
707 if self.chain_enabled {
708 event.prev_hash = last
709 .as_deref()
710 .map(|previous| chain_link(self.chain_key.as_deref().map(Vec::as_slice), previous));
711 }
712 let line = serde_json::to_string(&event)
713 .map_err(|e| crate::AuthError::AuditError(e.to_string()))?;
714
715 let mut writer = self.writer.lock().unwrap_or_else(|poisoned| {
716 tracing::warn!(path = %self.path.display(), "audit writer lock poisoned, recovering");
717 poisoned.into_inner()
718 });
719 writeln!(writer, "{line}")?;
720 writer.flush()?;
721 if self.chain_enabled {
722 *last = Some(line);
724 }
725 Ok(())
726 }
727}
728
729pub struct InMemoryAuditSink {
735 events: tokio::sync::RwLock<Vec<AuditEvent>>,
736}
737
738impl InMemoryAuditSink {
739 pub fn new() -> Self {
741 Self { events: tokio::sync::RwLock::new(Vec::new()) }
742 }
743
744 pub async fn len(&self) -> usize {
746 self.events.read().await.len()
747 }
748
749 pub async fn is_empty(&self) -> bool {
751 self.events.read().await.is_empty()
752 }
753}
754
755impl Default for InMemoryAuditSink {
756 fn default() -> Self {
757 Self::new()
758 }
759}
760
761#[async_trait::async_trait]
762impl AuditSink for InMemoryAuditSink {
763 async fn log(&self, event: AuditEvent) -> Result<(), crate::AuthError> {
764 self.events.write().await.push(event);
765 Ok(())
766 }
767
768 async fn log_batch(&self, events: Vec<AuditEvent>) -> Result<(), crate::AuthError> {
769 self.events.write().await.extend(events);
770 Ok(())
771 }
772
773 async fn query(&self, filter: &AuditFilter) -> Result<Vec<AuditEvent>, crate::AuthError> {
774 let events = self.events.read().await;
775 let mut results: Vec<AuditEvent> =
776 events.iter().filter(|e| filter.matches(e)).cloned().collect();
777
778 if let Some(offset) = filter.offset {
780 if offset < results.len() {
781 results = results[offset..].to_vec();
782 } else {
783 results.clear();
784 }
785 }
786
787 if let Some(limit) = filter.limit {
789 results.truncate(limit);
790 }
791
792 Ok(results)
793 }
794
795 async fn purge_before(&self, cutoff: DateTime<Utc>) -> Result<u64, crate::AuthError> {
796 let mut events = self.events.write().await;
797 let before_len = events.len();
798 events.retain(|e| e.timestamp >= cutoff);
799 Ok((before_len - events.len()) as u64)
800 }
801}
802
803#[cfg(test)]
804mod tests {
805 use super::*;
806
807 #[test]
808 fn test_audit_event_serialization() {
809 let event = AuditEvent::tool_access("alice", "search", AuditOutcome::Allowed);
810 let json = serde_json::to_string(&event).unwrap();
811 assert!(json.contains("\"user\":\"alice\""));
812 assert!(json.contains("\"resource\":\"search\""));
813 assert!(json.contains("\"outcome\":\"allowed\""));
814 }
815
816 #[test]
817 fn test_audit_event_with_session() {
818 let event = AuditEvent::tool_access("bob", "exec", AuditOutcome::Denied)
819 .with_session("session-123");
820 assert_eq!(event.session_id, Some("session-123".to_string()));
821 }
822
823 #[test]
824 fn test_enterprise_context_fields() {
825 let event = AuditEvent::tool_access("alice", "search", AuditOutcome::Allowed)
826 .with_workspace("ws_123")
827 .with_tenant("tenant_abc")
828 .with_request_id("req_456")
829 .with_ip_address("192.168.1.1")
830 .with_resource_id("550e8400-e29b-41d4-a716-446655440000")
831 .with_action("execute");
832
833 assert_eq!(event.workspace_id, Some("ws_123".to_string()));
834 assert_eq!(event.tenant_id, Some("tenant_abc".to_string()));
835 assert_eq!(event.request_id, Some("req_456".to_string()));
836 assert_eq!(event.ip_address, Some("192.168.1.1".to_string()));
837 assert_eq!(event.resource_id, Some("550e8400-e29b-41d4-a716-446655440000".to_string()));
838 assert_eq!(event.action, Some("execute".to_string()));
839
840 let json = serde_json::to_string(&event).unwrap();
842 assert!(json.contains("\"workspace_id\":\"ws_123\""));
843 assert!(json.contains("\"tenant_id\":\"tenant_abc\""));
844 assert!(json.contains("\"request_id\":\"req_456\""));
845 }
846
847 #[test]
848 fn test_custom_event_type() {
849 let event =
850 AuditEvent::custom("deployment_triggered", "ci-bot", "agent-v2", AuditOutcome::Created);
851 let json = serde_json::to_string(&event).unwrap();
852 assert!(json.contains("deployment_triggered"));
853 assert!(json.contains("\"outcome\":\"created\""));
854 }
855
856 #[test]
857 fn test_new_outcomes() {
858 for outcome in [
859 AuditOutcome::Created,
860 AuditOutcome::Updated,
861 AuditOutcome::Deleted,
862 AuditOutcome::Blocked,
863 AuditOutcome::Paused,
864 AuditOutcome::Escalated,
865 ] {
866 let event =
867 AuditEvent::new(AuditEventType::ResourceCreated, "user", "res", outcome.clone());
868 let json = serde_json::to_string(&event).unwrap();
869 let deserialized: AuditEvent = serde_json::from_str(&json).unwrap();
870 assert_eq!(deserialized.outcome, outcome);
871 }
872 }
873
874 #[test]
875 fn test_new_event_types() {
876 let types = vec![
877 AuditEventType::Authentication,
878 AuditEventType::Authorization,
879 AuditEventType::ResourceCreated,
880 AuditEventType::ResourceUpdated,
881 AuditEventType::ResourceDeleted,
882 AuditEventType::ConfigChanged,
883 AuditEventType::SecretAccessed,
884 AuditEventType::SecretRotated,
885 AuditEventType::PaymentExecuted,
886 AuditEventType::PolicyEvaluated,
887 AuditEventType::SessionStarted,
888 AuditEventType::SessionEnded,
889 AuditEventType::Custom("my_event".to_string()),
890 ];
891
892 for event_type in types {
893 let event =
894 AuditEvent::new(event_type.clone(), "user", "resource", AuditOutcome::Allowed);
895 let json = serde_json::to_string(&event).unwrap();
896 let deserialized: AuditEvent = serde_json::from_str(&json).unwrap();
897 assert_eq!(deserialized.event_type, event_type);
898 }
899 }
900
901 #[test]
902 fn last_line_is_read_across_block_boundaries() {
903 let path = std::env::temp_dir().join(format!(
904 "adk-audit-last-line-{}-{}.jsonl",
905 std::process::id(),
906 Utc::now().timestamp_nanos_opt().unwrap_or_default()
907 ));
908 assert_eq!(read_last_line(&path).unwrap(), None);
909
910 std::fs::write(&path, "").unwrap();
911 assert_eq!(read_last_line(&path).unwrap(), None);
912
913 let long = "x".repeat(20_000);
914 std::fs::write(&path, format!("first\n{long}\n\n")).unwrap();
915 assert_eq!(read_last_line(&path).unwrap(), Some(long.clone()));
916
917 std::fs::write(&path, &long).unwrap();
918 assert_eq!(read_last_line(&path).unwrap(), Some(long));
919 std::fs::remove_file(&path).unwrap();
920 }
921
922 #[test]
923 fn test_hash_chaining() {
924 let event1 = AuditEvent::tool_access("alice", "search", AuditOutcome::Allowed);
925 let json1 = event1.to_json().unwrap();
926
927 let event2 =
928 AuditEvent::tool_access("bob", "exec", AuditOutcome::Denied).with_prev_hash(&json1);
929
930 assert!(event2.prev_hash.is_some());
931 assert_eq!(event2.prev_hash.as_ref().unwrap().len(), 64);
933 }
934
935 #[test]
936 fn test_audit_filter_matches() {
937 let event = AuditEvent::tool_access("alice", "search", AuditOutcome::Allowed)
938 .with_workspace("ws_1");
939
940 let filter = AuditFilter { user: Some("alice".to_string()), ..Default::default() };
941 assert!(filter.matches(&event));
942
943 let filter = AuditFilter { user: Some("bob".to_string()), ..Default::default() };
944 assert!(!filter.matches(&event));
945
946 let filter = AuditFilter { workspace_id: Some("ws_1".to_string()), ..Default::default() };
947 assert!(filter.matches(&event));
948
949 let filter = AuditFilter { workspace_id: Some("ws_2".to_string()), ..Default::default() };
950 assert!(!filter.matches(&event));
951 }
952
953 #[test]
954 fn test_backward_compatible_serialization() {
955 let old_json = r#"{"timestamp":"2026-01-01T00:00:00Z","user":"alice","event_type":"tool_access","resource":"search","outcome":"allowed"}"#;
957 let event: AuditEvent = serde_json::from_str(old_json).unwrap();
958 assert_eq!(event.user, "alice");
959 assert_eq!(event.workspace_id, None);
960 assert_eq!(event.tenant_id, None);
961 }
962
963 #[tokio::test]
964 async fn test_in_memory_sink_query() {
965 let sink = InMemoryAuditSink::new();
966
967 sink.log(
968 AuditEvent::tool_access("alice", "search", AuditOutcome::Allowed)
969 .with_workspace("ws_1"),
970 )
971 .await
972 .unwrap();
973 sink.log(
974 AuditEvent::tool_access("bob", "exec", AuditOutcome::Denied).with_workspace("ws_1"),
975 )
976 .await
977 .unwrap();
978 sink.log(
979 AuditEvent::tool_access("alice", "deploy", AuditOutcome::Allowed)
980 .with_workspace("ws_2"),
981 )
982 .await
983 .unwrap();
984
985 let results = sink
987 .query(&AuditFilter { user: Some("alice".to_string()), ..Default::default() })
988 .await
989 .unwrap();
990 assert_eq!(results.len(), 2);
991
992 let results = sink
994 .query(&AuditFilter { workspace_id: Some("ws_1".to_string()), ..Default::default() })
995 .await
996 .unwrap();
997 assert_eq!(results.len(), 2);
998
999 let results = sink
1001 .query(&AuditFilter { outcome: Some(AuditOutcome::Denied), ..Default::default() })
1002 .await
1003 .unwrap();
1004 assert_eq!(results.len(), 1);
1005 assert_eq!(results[0].user, "bob");
1006 }
1007
1008 #[tokio::test]
1009 async fn test_in_memory_sink_purge() {
1010 let sink = InMemoryAuditSink::new();
1011
1012 sink.log(AuditEvent::tool_access("alice", "search", AuditOutcome::Allowed)).await.unwrap();
1013 sink.log(AuditEvent::tool_access("bob", "exec", AuditOutcome::Denied)).await.unwrap();
1014
1015 assert_eq!(sink.len().await, 2);
1016
1017 let cutoff = Utc::now() + chrono::Duration::seconds(1);
1019 let purged = sink.purge_before(cutoff).await.unwrap();
1020 assert_eq!(purged, 2);
1021 assert!(sink.is_empty().await);
1022 }
1023
1024 #[tokio::test]
1025 async fn test_in_memory_sink_batch() {
1026 let sink = InMemoryAuditSink::new();
1027
1028 let events = vec![
1029 AuditEvent::tool_access("alice", "a", AuditOutcome::Allowed),
1030 AuditEvent::tool_access("bob", "b", AuditOutcome::Denied),
1031 AuditEvent::tool_access("carol", "c", AuditOutcome::Allowed),
1032 ];
1033
1034 sink.log_batch(events).await.unwrap();
1035 assert_eq!(sink.len().await, 3);
1036 }
1037}