cortexai-audit 0.1.0

Audit logging for AI agents — tool calls, LLM requests, and compliance tracking
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
//! Audit logger traits and configuration.
//!
//! This module defines the core `AuditLogger` trait that all backends implement,
//! along with configuration types and utilities.

use crate::error::AuditError;
use crate::types::{AuditEvent, AuditLevel};
use async_trait::async_trait;
use std::sync::Arc;

/// Configuration for audit logging.
#[derive(Debug, Clone)]
pub struct AuditConfig {
    /// Minimum level to log (events below this are filtered)
    pub min_level: AuditLevel,
    /// Whether to include debug information
    pub include_debug: bool,
    /// Maximum size for parameter/result payloads (bytes)
    pub max_payload_size: usize,
    /// Whether to redact sensitive fields
    pub redact_sensitive: bool,
    /// Fields to redact
    pub redact_fields: Vec<String>,
    /// Whether audit logging is enabled
    pub enabled: bool,
    /// Buffer size for async logging
    pub buffer_size: usize,
    /// Flush interval in seconds
    pub flush_interval_secs: u64,
}

impl Default for AuditConfig {
    fn default() -> Self {
        Self {
            min_level: AuditLevel::Info,
            include_debug: false,
            max_payload_size: 10 * 1024, // 10KB
            redact_sensitive: true,
            redact_fields: vec![
                "password".to_string(),
                "secret".to_string(),
                "token".to_string(),
                "api_key".to_string(),
                "apiKey".to_string(),
                "authorization".to_string(),
            ],
            enabled: true,
            buffer_size: 1000,
            flush_interval_secs: 5,
        }
    }
}

impl AuditConfig {
    /// Create a new configuration with defaults.
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a development configuration with debug enabled.
    pub fn development() -> Self {
        Self {
            min_level: AuditLevel::Debug,
            include_debug: true,
            redact_sensitive: false,
            ..Default::default()
        }
    }

    /// Create a production configuration with stricter settings.
    pub fn production() -> Self {
        Self {
            min_level: AuditLevel::Info,
            include_debug: false,
            redact_sensitive: true,
            max_payload_size: 5 * 1024, // 5KB in production
            ..Default::default()
        }
    }

    /// Set the minimum log level.
    pub fn with_min_level(mut self, level: AuditLevel) -> Self {
        self.min_level = level;
        self
    }

    /// Enable or disable debug information.
    pub fn with_debug(mut self, include: bool) -> Self {
        self.include_debug = include;
        self
    }

    /// Set maximum payload size.
    pub fn with_max_payload_size(mut self, size: usize) -> Self {
        self.max_payload_size = size;
        self
    }

    /// Enable or disable sensitive field redaction.
    pub fn with_redaction(mut self, enabled: bool) -> Self {
        self.redact_sensitive = enabled;
        self
    }

    /// Add fields to redact.
    pub fn with_redact_fields(mut self, fields: Vec<String>) -> Self {
        self.redact_fields.extend(fields);
        self
    }

    /// Enable or disable audit logging.
    pub fn enabled(mut self, enabled: bool) -> Self {
        self.enabled = enabled;
        self
    }

    /// Set buffer size.
    pub fn with_buffer_size(mut self, size: usize) -> Self {
        self.buffer_size = size;
        self
    }

    /// Check if an event should be logged based on level.
    pub fn should_log(&self, level: AuditLevel) -> bool {
        self.enabled && level >= self.min_level
    }
}

/// The core audit logger trait.
///
/// All audit backends implement this trait to provide consistent logging behavior.
#[async_trait]
pub trait AuditLogger: Send + Sync {
    /// Log an audit event.
    async fn log(&self, event: AuditEvent) -> Result<(), AuditError>;

    /// Log multiple events in a batch.
    async fn log_batch(&self, events: Vec<AuditEvent>) -> Result<(), AuditError> {
        for event in events {
            self.log(event).await?;
        }
        Ok(())
    }

    /// Flush any buffered events.
    async fn flush(&self) -> Result<(), AuditError>;

    /// Get the logger name for identification.
    fn name(&self) -> &str;

    /// Check if the logger is healthy.
    async fn health_check(&self) -> Result<(), AuditError> {
        Ok(())
    }

    /// Get statistics about logged events.
    async fn stats(&self) -> AuditStats {
        AuditStats::default()
    }
}

/// Statistics about audit logging.
#[derive(Debug, Clone, Default)]
pub struct AuditStats {
    /// Total events logged
    pub total_events: u64,
    /// Events by level
    pub events_by_level: std::collections::HashMap<AuditLevel, u64>,
    /// Failed log attempts
    pub failed_events: u64,
    /// Bytes written
    pub bytes_written: u64,
    /// Last event timestamp
    pub last_event_time: Option<chrono::DateTime<chrono::Utc>>,
}

/// A composite logger that writes to multiple backends.
pub struct CompositeLogger {
    loggers: Vec<Arc<dyn AuditLogger>>,
    config: AuditConfig,
}

impl CompositeLogger {
    /// Create a new composite logger.
    pub fn new(config: AuditConfig) -> Self {
        Self {
            loggers: Vec::new(),
            config,
        }
    }

    /// Add a logger backend.
    pub fn add_logger(mut self, logger: Arc<dyn AuditLogger>) -> Self {
        self.loggers.push(logger);
        self
    }

    /// Add a logger backend by reference.
    pub fn with_logger(&mut self, logger: Arc<dyn AuditLogger>) {
        self.loggers.push(logger);
    }
}

#[async_trait]
impl AuditLogger for CompositeLogger {
    async fn log(&self, event: AuditEvent) -> Result<(), AuditError> {
        if !self.config.should_log(event.level) {
            return Ok(());
        }

        let mut errors = Vec::new();
        for logger in &self.loggers {
            if let Err(e) = logger.log(event.clone()).await {
                errors.push(format!("{}: {}", logger.name(), e));
            }
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(AuditError::Multiple(errors))
        }
    }

    async fn flush(&self) -> Result<(), AuditError> {
        let mut errors = Vec::new();
        for logger in &self.loggers {
            if let Err(e) = logger.flush().await {
                errors.push(format!("{}: {}", logger.name(), e));
            }
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(AuditError::Multiple(errors))
        }
    }

    fn name(&self) -> &str {
        "composite"
    }

    async fn health_check(&self) -> Result<(), AuditError> {
        for logger in &self.loggers {
            logger.health_check().await?;
        }
        Ok(())
    }
}

/// A no-op logger for testing or when audit is disabled.
pub struct NoOpLogger;

#[async_trait]
impl AuditLogger for NoOpLogger {
    async fn log(&self, _event: AuditEvent) -> Result<(), AuditError> {
        Ok(())
    }

    async fn flush(&self) -> Result<(), AuditError> {
        Ok(())
    }

    fn name(&self) -> &str {
        "noop"
    }
}

/// A logger that collects events in memory for testing.
#[derive(Default)]
pub struct MemoryLogger {
    events: tokio::sync::RwLock<Vec<AuditEvent>>,
}

impl MemoryLogger {
    /// Create a new memory logger.
    pub fn new() -> Self {
        Self::default()
    }

    /// Get all logged events.
    pub async fn events(&self) -> Vec<AuditEvent> {
        self.events.read().await.clone()
    }

    /// Get event count.
    pub async fn count(&self) -> usize {
        self.events.read().await.len()
    }

    /// Clear all events.
    pub async fn clear(&self) {
        self.events.write().await.clear();
    }
}

#[async_trait]
impl AuditLogger for MemoryLogger {
    async fn log(&self, event: AuditEvent) -> Result<(), AuditError> {
        self.events.write().await.push(event);
        Ok(())
    }

    async fn flush(&self) -> Result<(), AuditError> {
        Ok(())
    }

    fn name(&self) -> &str {
        "memory"
    }

    async fn stats(&self) -> AuditStats {
        let events = self.events.read().await;
        let mut stats = AuditStats {
            total_events: events.len() as u64,
            ..Default::default()
        };

        for event in events.iter() {
            *stats.events_by_level.entry(event.level).or_insert(0) += 1;
        }

        if let Some(last) = events.last() {
            stats.last_event_time = Some(last.timestamp);
        }

        stats
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::EventKind;

    #[test]
    fn test_audit_config_defaults() {
        let config = AuditConfig::default();
        assert_eq!(config.min_level, AuditLevel::Info);
        assert!(config.enabled);
        assert!(config.redact_sensitive);
    }

    #[test]
    fn test_audit_config_should_log() {
        let config = AuditConfig::new().with_min_level(AuditLevel::Warn);

        assert!(!config.should_log(AuditLevel::Debug));
        assert!(!config.should_log(AuditLevel::Info));
        assert!(config.should_log(AuditLevel::Warn));
        assert!(config.should_log(AuditLevel::Error));
        assert!(config.should_log(AuditLevel::Critical));
    }

    #[test]
    fn test_audit_config_disabled() {
        let config = AuditConfig::new().enabled(false);
        assert!(!config.should_log(AuditLevel::Critical));
    }

    #[tokio::test]
    async fn test_memory_logger() {
        let logger = MemoryLogger::new();

        let event = AuditEvent::info(EventKind::Custom {
            name: "test".to_string(),
            payload: serde_json::json!({}),
        });

        logger.log(event).await.unwrap();
        assert_eq!(logger.count().await, 1);

        let events = logger.events().await;
        assert_eq!(events.len(), 1);
    }

    #[tokio::test]
    async fn test_noop_logger() {
        let logger = NoOpLogger;
        let event = AuditEvent::info(EventKind::Custom {
            name: "test".to_string(),
            payload: serde_json::json!({}),
        });

        assert!(logger.log(event).await.is_ok());
        assert!(logger.flush().await.is_ok());
    }

    #[tokio::test]
    async fn test_composite_logger() {
        let memory1 = Arc::new(MemoryLogger::new());
        let memory2 = Arc::new(MemoryLogger::new());

        let composite = CompositeLogger::new(AuditConfig::default())
            .add_logger(memory1.clone())
            .add_logger(memory2.clone());

        let event = AuditEvent::info(EventKind::Custom {
            name: "test".to_string(),
            payload: serde_json::json!({}),
        });

        composite.log(event).await.unwrap();

        assert_eq!(memory1.count().await, 1);
        assert_eq!(memory2.count().await, 1);
    }
}