Skip to main content

adk_auth/
audit.rs

1//! Enterprise audit logging for access control and platform operations.
2//!
3//! Provides structured audit events with multi-tenant context, extensible event
4//! types, multiple sink backends, batch logging, cryptographic chaining, and
5//! query/retention APIs.
6//!
7//! # Enterprise Features
8//!
9//! - **Multi-tenant context**: `workspace_id`, `tenant_id`, `request_id` fields
10//! - **Extensible event types**: 15 built-in types + `Custom(String)` for platform extensions
11//! - **Multiple outcomes**: 9 outcome variants covering full lifecycle
12//! - **Batch logging**: `log_batch()` for high-throughput scenarios
13//! - **Cryptographic chaining**: Optional SHA-256 hash chain for append-only integrity
14//! - **Query interface**: `AuditFilter` for searching audit logs from the UI
15//! - **Retention API**: `purge_before()` for compliance-driven data lifecycle
16//! - **Multiple sinks**: File (JSONL), PostgreSQL, OpenTelemetry export
17
18use 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/// Type of audit event.
29///
30/// Covers access control, resource lifecycle, configuration changes, and
31/// platform-specific operations. Use `Custom(String)` for platform extensions
32/// without forking the crate.
33#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
34#[serde(rename_all = "snake_case")]
35pub enum AuditEventType {
36    /// Tool access attempt.
37    ToolAccess,
38    /// Agent access attempt.
39    AgentAccess,
40    /// Permission check.
41    PermissionCheck,
42    /// Authentication event (login, token refresh, logout).
43    Authentication,
44    /// Authorization decision (role/policy evaluation).
45    Authorization,
46    /// Resource created (agent, workspace, project).
47    ResourceCreated,
48    /// Resource updated.
49    ResourceUpdated,
50    /// Resource deleted.
51    ResourceDeleted,
52    /// Configuration changed (settings, feature flags).
53    ConfigChanged,
54    /// Secret accessed (read from vault).
55    SecretAccessed,
56    /// Secret rotated (key rotation event).
57    SecretRotated,
58    /// Payment executed (billing event).
59    PaymentExecuted,
60    /// Policy evaluated (guardrail, rate limit).
61    PolicyEvaluated,
62    /// Session started.
63    SessionStarted,
64    /// Session ended.
65    SessionEnded,
66    /// Platform-specific custom event type.
67    Custom(String),
68}
69
70/// Outcome of an audit event.
71///
72/// Covers the full lifecycle of access decisions and resource operations.
73#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
74#[serde(rename_all = "snake_case")]
75pub enum AuditOutcome {
76    /// Access was allowed.
77    Allowed,
78    /// Access was denied.
79    Denied,
80    /// An error occurred during the operation.
81    Error,
82    /// Resource was created successfully.
83    Created,
84    /// Resource was updated successfully.
85    Updated,
86    /// Resource was deleted successfully.
87    Deleted,
88    /// Operation was blocked by a policy or guardrail.
89    Blocked,
90    /// Operation was paused (awaiting approval).
91    Paused,
92    /// Operation was escalated to a higher authority.
93    Escalated,
94}
95
96/// An audit event with enterprise multi-tenant context.
97///
98/// All fields beyond `timestamp`, `user`, `event_type`, `resource`, and `outcome`
99/// are optional for backward compatibility. Enterprise platforms populate the
100/// additional context fields for multi-tenancy, tracing, and compliance.
101#[derive(Debug, Clone, Serialize, Deserialize)]
102pub struct AuditEvent {
103    /// Timestamp of the event.
104    pub timestamp: DateTime<Utc>,
105    /// User ID (email, subject, or system identifier).
106    pub user: String,
107    /// Session ID (if available).
108    #[serde(skip_serializing_if = "Option::is_none")]
109    pub session_id: Option<String>,
110    /// Type of event.
111    pub event_type: AuditEventType,
112    /// Resource being accessed (tool name, agent name, or descriptive path).
113    pub resource: String,
114    /// Outcome of the operation.
115    pub outcome: AuditOutcome,
116    /// Additional metadata (arbitrary JSON).
117    #[serde(skip_serializing_if = "Option::is_none")]
118    pub metadata: Option<serde_json::Value>,
119
120    // ── Enterprise context fields ───────────────────────────────
121    /// Workspace ID for multi-tenant scoping.
122    #[serde(skip_serializing_if = "Option::is_none")]
123    pub workspace_id: Option<String>,
124    /// Tenant ID for multi-tenant scoping (higher level than workspace).
125    #[serde(skip_serializing_if = "Option::is_none")]
126    pub tenant_id: Option<String>,
127    /// Request ID for distributed tracing correlation.
128    #[serde(skip_serializing_if = "Option::is_none")]
129    pub request_id: Option<String>,
130    /// Client IP address.
131    #[serde(skip_serializing_if = "Option::is_none")]
132    pub ip_address: Option<String>,
133    /// Resource UUID (distinct from the human-readable `resource` name).
134    #[serde(skip_serializing_if = "Option::is_none")]
135    pub resource_id: Option<String>,
136    /// Action verb (e.g., "read", "write", "delete", "execute").
137    #[serde(skip_serializing_if = "Option::is_none")]
138    pub action: Option<String>,
139    /// SHA-256 hash of the previous event (for cryptographic chaining).
140    #[serde(skip_serializing_if = "Option::is_none")]
141    pub prev_hash: Option<String>,
142    /// Stable id of the agent that acted ([`AgentId`](adk_core::AgentId)).
143    #[serde(default, skip_serializing_if = "Option::is_none")]
144    pub agent_id: Option<String>,
145    /// The person or service the agent acted for.
146    #[serde(default, skip_serializing_if = "Option::is_none")]
147    pub on_behalf_of: Option<adk_core::SubjectRef>,
148}
149
150impl AuditEvent {
151    /// Create a new audit event with the given type, user, resource, and outcome.
152    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    /// Create a new tool access event.
179    pub fn tool_access(user: &str, tool_name: &str, outcome: AuditOutcome) -> Self {
180        Self::new(AuditEventType::ToolAccess, user, tool_name, outcome)
181    }
182
183    /// Create a new agent access event.
184    pub fn agent_access(user: &str, agent_name: &str, outcome: AuditOutcome) -> Self {
185        Self::new(AuditEventType::AgentAccess, user, agent_name, outcome)
186    }
187
188    /// Create an authentication event.
189    pub fn authentication(user: &str, outcome: AuditOutcome) -> Self {
190        Self::new(AuditEventType::Authentication, user, "auth", outcome)
191    }
192
193    /// Create a resource lifecycle event.
194    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    /// Create a secret access event.
205    pub fn secret_accessed(user: &str, secret_name: &str, outcome: AuditOutcome) -> Self {
206        Self::new(AuditEventType::SecretAccessed, user, secret_name, outcome)
207    }
208
209    /// Create a configuration change event.
210    pub fn config_changed(user: &str, config_key: &str, outcome: AuditOutcome) -> Self {
211        Self::new(AuditEventType::ConfigChanged, user, config_key, outcome)
212    }
213
214    /// Create a custom event type for platform extensions.
215    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    /// Set the session ID.
220    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    /// Set metadata.
226    pub fn with_metadata(mut self, metadata: serde_json::Value) -> Self {
227        self.metadata = Some(metadata);
228        self
229    }
230
231    /// Set workspace ID for multi-tenant scoping.
232    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    /// Set tenant ID for multi-tenant scoping.
238    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    /// Set request ID for distributed tracing.
244    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    /// Set client IP address.
250    pub fn with_ip_address(mut self, ip: impl Into<String>) -> Self {
251        self.ip_address = Some(ip.into());
252        self
253    }
254
255    /// Set resource UUID.
256    pub fn with_resource_id(mut self, id: impl Into<String>) -> Self {
257        self.resource_id = Some(id.into());
258        self
259    }
260
261    /// Set the acting agent's id.
262    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    /// Records the acting agent, the subject it acted for, and its tenant.
268    ///
269    /// Sets [`agent_id`](Self::agent_id) and [`on_behalf_of`](Self::on_behalf_of), and
270    /// [`tenant_id`](Self::tenant_id) from the principal's tenant when no tenant is set.
271    ///
272    /// # Example
273    ///
274    /// ```rust
275    /// use adk_auth::{AuditEvent, AuditOutcome};
276    /// use adk_core::{ActingContext, SubjectRef};
277    ///
278    /// let acting =
279    ///     ActingContext::derived("shop", "cashier", "alice", adk_core::SubjectKind::Human);
280    /// let event = AuditEvent::tool_access("alice", "refund", AuditOutcome::Allowed)
281    ///     .with_acting_context(&acting);
282    /// assert_eq!(event.agent_id.as_deref(), Some("urn:adk:agent:shop/cashier"));
283    /// assert_eq!(event.on_behalf_of, Some(SubjectRef::human("alice")));
284    /// ```
285    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    /// Set action verb.
295    pub fn with_action(mut self, action: impl Into<String>) -> Self {
296        self.action = Some(action.into());
297        self
298    }
299
300    /// Compute and set the cryptographic hash chain link.
301    ///
302    /// The hash is SHA-256 of the JSON-serialized previous event.
303    /// Call this before logging to maintain an append-only chain.
304    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    /// Serialize this event to JSON (for hash chaining).
312    pub fn to_json(&self) -> Result<String, serde_json::Error> {
313        serde_json::to_string(self)
314    }
315}
316
317/// Filter for querying audit events.
318///
319/// All fields are optional — only non-None fields are used as filter criteria.
320/// Multiple fields are combined with AND logic.
321#[derive(Debug, Clone, Default, Serialize, Deserialize)]
322pub struct AuditFilter {
323    /// Filter by user ID.
324    #[serde(skip_serializing_if = "Option::is_none")]
325    pub user: Option<String>,
326    /// Filter by workspace ID.
327    #[serde(skip_serializing_if = "Option::is_none")]
328    pub workspace_id: Option<String>,
329    /// Filter by tenant ID.
330    #[serde(skip_serializing_if = "Option::is_none")]
331    pub tenant_id: Option<String>,
332    /// Filter by event type.
333    #[serde(skip_serializing_if = "Option::is_none")]
334    pub event_type: Option<AuditEventType>,
335    /// Filter by outcome.
336    #[serde(skip_serializing_if = "Option::is_none")]
337    pub outcome: Option<AuditOutcome>,
338    /// Filter by resource name (literal substring match; `%` and `_` are not wildcards).
339    #[serde(skip_serializing_if = "Option::is_none")]
340    pub resource: Option<String>,
341    /// Filter by resource UUID.
342    #[serde(skip_serializing_if = "Option::is_none")]
343    pub resource_id: Option<String>,
344    /// Filter by acting agent id.
345    #[serde(default, skip_serializing_if = "Option::is_none")]
346    pub agent_id: Option<String>,
347    /// Events after this timestamp.
348    #[serde(skip_serializing_if = "Option::is_none")]
349    pub after: Option<DateTime<Utc>>,
350    /// Events before this timestamp.
351    #[serde(skip_serializing_if = "Option::is_none")]
352    pub before: Option<DateTime<Utc>>,
353    /// Maximum number of results to return.
354    #[serde(skip_serializing_if = "Option::is_none")]
355    pub limit: Option<usize>,
356    /// Offset for pagination.
357    #[serde(skip_serializing_if = "Option::is_none")]
358    pub offset: Option<usize>,
359}
360
361impl AuditFilter {
362    /// Check if an event matches this filter.
363    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/// Trait for audit sinks.
419///
420/// Implementations persist audit events to a storage backend. The trait supports
421/// single-event logging, batch logging for high throughput, querying for UI
422/// display, and retention management for compliance.
423#[async_trait::async_trait]
424pub trait AuditSink: Send + Sync {
425    /// Log a single audit event.
426    async fn log(&self, event: AuditEvent) -> Result<(), crate::AuthError>;
427
428    /// Log a batch of audit events atomically.
429    ///
430    /// Default implementation logs events sequentially. Override for
431    /// high-throughput backends that support batch inserts.
432    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    /// Query audit events matching the given filter.
440    ///
441    /// Default implementation returns an empty vec (not all sinks support queries).
442    /// Override for queryable backends (PostgreSQL, in-memory).
443    async fn query(&self, _filter: &AuditFilter) -> Result<Vec<AuditEvent>, crate::AuthError> {
444        Ok(Vec::new())
445    }
446
447    /// Purge events older than the given cutoff timestamp.
448    ///
449    /// Returns the number of events purged. Default returns 0 (not all sinks
450    /// support retention management).
451    async fn purge_before(&self, _cutoff: DateTime<Utc>) -> Result<u64, crate::AuthError> {
452        Ok(0)
453    }
454
455    /// Flush any buffered events to the underlying storage.
456    ///
457    /// Default is a no-op. Override for buffered sinks.
458    async fn flush(&self) -> Result<(), crate::AuthError> {
459        Ok(())
460    }
461}
462
463/// A shared sink is a sink, so one sink (such as a signed audit log) can serve several
464/// guards and keep a handle for checkpoints or queries.
465#[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
488/// What a guarded tool does when its audit sink fails to record an access decision.
489///
490/// [`ProtectedTool`](crate::ProtectedTool), [`ScopedTool`](crate::ScopedTool), and the
491/// guards that build them default to [`Block`](AuditFailureMode::Block). The same type
492/// governs the runtime's [`AuditTrail`](adk_core::audit_log::AuditTrail).
493pub use adk_core::audit_log::AuditFailureMode;
494
495/// Records one access decision, refusing the call when the sink fails in `Block` mode.
496pub(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
525/// Link from one chained line to the next: SHA-256, or HMAC-SHA256 under `key`, of the
526/// previous line's exact text, hex-encoded.
527fn 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
539/// Reads the last non-empty line of `path` without reading the whole file.
540fn 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
573/// File-based audit sink that writes JSONL (one JSON line per event).
574///
575/// With chaining, each event carries in `prev_hash` the SHA-256 (or, with
576/// [`with_hmac_chaining`](Self::with_hmac_chaining), the HMAC-SHA256) of the previous
577/// line's exact text. Opening a chained file resumes from its last line, so the chain
578/// survives restarts, and [`verify`](Self::verify) detects a line that was edited,
579/// inserted, reordered, or removed before the newest line. Without a key anyone who can
580/// write the file can recompute the chain; the HMAC chain cannot be forged without the
581/// key. Neither detects an edit to the newest line or lines cut from the end; anchor the
582/// newest line elsewhere for that.
583///
584/// # Example
585///
586/// ```rust,no_run
587/// use adk_auth::{AuditEvent, AuditOutcome, AuditSink, FileAuditSink};
588///
589/// # async fn demo() -> Result<(), adk_auth::AuthError> {
590/// let sink = FileAuditSink::with_hmac_chaining("/var/log/adk/audit.jsonl", b"audit-key".to_vec())?;
591/// sink.log(AuditEvent::tool_access("alice", "search", AuditOutcome::Allowed)).await?;
592/// let events = sink.verify()?;
593/// # let _ = events;
594/// # Ok(())
595/// # }
596/// ```
597pub struct FileAuditSink {
598    writer: Mutex<BufWriter<File>>,
599    path: PathBuf,
600    /// Exact text of the last line written, which the next event links to.
601    last_event_json: Mutex<Option<String>>,
602    /// Whether to enable cryptographic hash chaining.
603    chain_enabled: bool,
604    /// Key for the HMAC chain; `None` chains with plain SHA-256.
605    chain_key: Option<Zeroizing<Vec<u8>>>,
606}
607
608impl FileAuditSink {
609    /// Create a new file audit sink.
610    pub fn new(path: impl Into<PathBuf>) -> Result<Self, std::io::Error> {
611        Self::open(path.into(), false, None)
612    }
613
614    /// Create a new file audit sink with SHA-256 hash chaining enabled.
615    ///
616    /// Each event carries in `prev_hash` the SHA-256 of the previous line, resuming
617    /// from the file's last line when it already exists.
618    pub fn with_chaining(path: impl Into<PathBuf>) -> Result<Self, std::io::Error> {
619        Self::open(path.into(), true, None)
620    }
621
622    /// Create a new file audit sink whose chain links are HMAC-SHA256 under `key`.
623    ///
624    /// The chain cannot be recomputed without `key`, so an edit by someone who can write
625    /// the file but does not hold the key fails [`verify`](Self::verify).
626    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    /// Get the path to the audit log file.
650    pub fn path(&self) -> &PathBuf {
651        &self.path
652    }
653
654    /// Verifies this sink's chain and returns the number of events in the file.
655    ///
656    /// # Errors
657    ///
658    /// Returns [`AuthError::AuditError`](crate::AuthError::AuditError) naming the first
659    /// line whose link does not match, or an I/O error when the file cannot be read.
660    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    /// Verifies a chained audit file without opening it for writing.
666    ///
667    /// Pass the key the file was written with, or `None` for a SHA-256 chain. The first
668    /// event must carry no `prev_hash`; every later event must link to the line before it.
669    ///
670    /// # Errors
671    ///
672    /// Returns [`AuthError::AuditError`](crate::AuthError::AuditError) naming the first
673    /// line that is not an audit event or whose link does not match, or an I/O error.
674    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        // Held across the write so concurrent events link in the order they are written.
706        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            // Advanced only after the write, so a failed write does not break the chain.
723            *last = Some(line);
724        }
725        Ok(())
726    }
727}
728
729/// In-memory audit sink for testing and development.
730///
731/// Stores all events in a `Vec` behind a `RwLock`. Supports querying and
732/// purging. Not suitable for production — use `FileAuditSink` or a database
733/// sink instead.
734pub struct InMemoryAuditSink {
735    events: tokio::sync::RwLock<Vec<AuditEvent>>,
736}
737
738impl InMemoryAuditSink {
739    /// Create a new in-memory audit sink.
740    pub fn new() -> Self {
741        Self { events: tokio::sync::RwLock::new(Vec::new()) }
742    }
743
744    /// Get the number of stored events.
745    pub async fn len(&self) -> usize {
746        self.events.read().await.len()
747    }
748
749    /// Check if the sink is empty.
750    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        // Apply offset
779        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        // Apply limit
788        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        // Verify JSON serialization includes enterprise fields
841        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        // SHA-256 hex is 64 chars
932        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        // Old-style event without enterprise fields should still deserialize
956        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        // Query by user
986        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        // Query by workspace
993        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        // Query by outcome
1000        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        // Purge everything before now+1s (should purge all)
1018        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}