Skip to main content

config_lib/
audit.rs

1//! Comprehensive Audit Logging System
2//!
3//! Enterprise-grade audit logging with:
4//! - Structured logging for all configuration operations
5//! - Access tracking with user context and timestamps
6//! - Modification logging with before/after values
7//! - Validation failure tracking
8//! - Configurable log levels and outputs
9//! - Performance-optimized with minimal overhead
10
11use crate::value::Value;
12use std::collections::HashMap;
13use std::fmt;
14use std::sync::{Arc, Mutex};
15use std::time::{SystemTime, UNIX_EPOCH};
16
17/// Audit event types for configuration operations.
18///
19/// **Stability:** `AuditEventType` is `#[non_exhaustive]` so the
20/// v1.x SemVer contract can add new event categories in MINOR releases
21/// without breaking user code. Callers must use a wildcard arm when
22/// pattern-matching.
23#[derive(Debug, Clone, PartialEq)]
24#[non_exhaustive]
25pub enum AuditEventType {
26    /// Configuration key was accessed/read
27    Access,
28    /// Configuration key was modified
29    Modification,
30    /// Configuration validation failed
31    ValidationFailure,
32    /// Configuration was reloaded from file
33    Reload,
34    /// Configuration file was loaded initially
35    Load,
36    /// Configuration was serialized/saved
37    Save,
38}
39
40/// Severity levels for audit events.
41///
42/// **Stability:** `AuditSeverity` is `#[non_exhaustive]` so the v1.x
43/// SemVer contract can add new severity tiers in MINOR releases
44/// without breaking user code. Callers must use a wildcard arm when
45/// pattern-matching.
46#[derive(Debug, Clone, PartialEq, PartialOrd)]
47#[non_exhaustive]
48pub enum AuditSeverity {
49    /// Informational events (normal operations)
50    Info = 1,
51    /// Warning events (potential issues)
52    Warning = 2,
53    /// Error events (failures)
54    Error = 3,
55    /// Critical events (security concerns)
56    Critical = 4,
57}
58
59/// Comprehensive audit event record
60#[derive(Debug, Clone)]
61pub struct AuditEvent {
62    /// Unique event ID
63    pub id: String,
64    /// Timestamp when the event occurred
65    pub timestamp: SystemTime,
66    /// Type of operation that triggered this event
67    pub event_type: AuditEventType,
68    /// Severity level of the event
69    pub severity: AuditSeverity,
70    /// Configuration key that was accessed/modified
71    pub key: Option<String>,
72    /// Previous value (for modifications)
73    pub old_value: Option<Value>,
74    /// New value (for modifications)
75    pub new_value: Option<Value>,
76    /// User or system context that triggered the event
77    pub user_context: Option<String>,
78    /// Additional contextual information
79    pub metadata: HashMap<String, String>,
80    /// Error message (for failures)
81    pub error_message: Option<String>,
82    /// Source location (file path, line number, etc.)
83    pub source: Option<String>,
84}
85
86impl AuditEvent {
87    /// Create a new audit event with minimal required fields
88    pub fn new(event_type: AuditEventType, severity: AuditSeverity) -> Self {
89        Self {
90            id: generate_event_id(),
91            timestamp: SystemTime::now(),
92            event_type,
93            severity,
94            key: None,
95            old_value: None,
96            new_value: None,
97            user_context: None,
98            metadata: HashMap::new(),
99            error_message: None,
100            source: None,
101        }
102    }
103
104    /// Set the configuration key for this event
105    pub fn with_key(mut self, key: impl Into<String>) -> Self {
106        self.key = Some(key.into());
107        self
108    }
109
110    /// Set the old value (for modifications)
111    pub fn with_old_value(mut self, value: Value) -> Self {
112        self.old_value = Some(value);
113        self
114    }
115
116    /// Set the new value (for modifications)
117    pub fn with_new_value(mut self, value: Value) -> Self {
118        self.new_value = Some(value);
119        self
120    }
121
122    /// Set the user context
123    pub fn with_user_context(mut self, context: impl Into<String>) -> Self {
124        self.user_context = Some(context.into());
125        self
126    }
127
128    /// Add metadata key-value pair
129    pub fn with_metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
130        self.metadata.insert(key.into(), value.into());
131        self
132    }
133
134    /// Set error message
135    pub fn with_error(mut self, message: impl Into<String>) -> Self {
136        self.error_message = Some(message.into());
137        self
138    }
139
140    /// Set source location
141    pub fn with_source(mut self, source: impl Into<String>) -> Self {
142        self.source = Some(source.into());
143        self
144    }
145}
146
147/// A field written with control characters, quotes and backslashes escaped,
148/// so a newline in a key or a user name cannot forge another audit line
149struct Escaped<'a>(&'a str);
150
151impl fmt::Display for Escaped<'_> {
152    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153        for c in self.0.chars() {
154            match c {
155                '"' => f.write_str("\\\"")?,
156                '\\' => f.write_str("\\\\")?,
157                '\n' => f.write_str("\\n")?,
158                '\r' => f.write_str("\\r")?,
159                '\t' => f.write_str("\\t")?,
160                c if c.is_control() => write!(f, "\\u{{{:x}}}", c as u32)?,
161                c => fmt::Write::write_char(f, c)?,
162            }
163        }
164        Ok(())
165    }
166}
167
168/// A value's type and size, never its contents: configuration values can be
169/// secrets
170struct Redacted<'a>(&'a Value);
171
172impl fmt::Display for Redacted<'_> {
173    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
174        match self.0 {
175            Value::String(s) => write!(f, "<string, {} bytes>", s.len()),
176            Value::Array(items) => write!(f, "<array, {} items>", items.len()),
177            Value::Table(table) => write!(f, "<table, {} keys>", table.len()),
178            other => write!(f, "<{}>", other.type_name()),
179        }
180    }
181}
182
183impl fmt::Display for AuditEvent {
184    /// One line per event. Since v1.4.0 every text field is escaped, and
185    /// old and new values are shown as their type and size only; the
186    /// values themselves stay available on the event for sinks that need
187    /// them.
188    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
189        let timestamp_millis = self
190            .timestamp
191            .duration_since(UNIX_EPOCH)
192            .unwrap_or_default()
193            .as_millis();
194
195        write!(
196            f,
197            "[{}] {:?}:{:?} id={} key=\"{}\" user=\"{}\"",
198            timestamp_millis,
199            self.event_type,
200            self.severity,
201            Escaped(&self.id),
202            Escaped(self.key.as_deref().unwrap_or("none")),
203            Escaped(self.user_context.as_deref().unwrap_or("system"))
204        )?;
205
206        if let Some(error) = &self.error_message {
207            write!(f, " error=\"{}\"", Escaped(error))?;
208        }
209
210        match (&self.old_value, &self.new_value) {
211            (Some(old), Some(new)) => write!(f, " change={} -> {}", Redacted(old), Redacted(new))?,
212            (None, Some(new)) => write!(f, " value={}", Redacted(new))?,
213            _ => {}
214        }
215
216        for (key, value) in &self.metadata {
217            write!(f, " {}=\"{}\"", Escaped(key), Escaped(value))?;
218        }
219
220        Ok(())
221    }
222}
223
224/// Trait for audit log outputs/sinks
225pub trait AuditSink: Send + Sync {
226    /// Write an audit event to this sink
227    fn write_event(&self, event: &AuditEvent) -> Result<(), String>;
228
229    /// Flush any buffered events
230    fn flush(&self) -> Result<(), String>;
231}
232
233/// Console/stdout audit sink for development
234pub struct ConsoleSink {
235    level_filter: AuditSeverity,
236}
237
238impl ConsoleSink {
239    /// Create a new console sink with minimum severity level
240    pub fn new(min_level: AuditSeverity) -> Self {
241        Self {
242            level_filter: min_level,
243        }
244    }
245}
246
247impl AuditSink for ConsoleSink {
248    fn write_event(&self, event: &AuditEvent) -> Result<(), String> {
249        if event.severity >= self.level_filter {
250            // REPS-AUDIT: `ConsoleSink` writes audit events to stdout by
251            // contract — that is the sink's stated purpose. Allowed at the
252            // call site only; the crate-level `clippy::print_stdout` deny
253            // remains in force everywhere else.
254            #[allow(clippy::print_stdout)]
255            {
256                println!("AUDIT: {event}");
257            }
258        }
259        Ok(())
260    }
261
262    fn flush(&self) -> Result<(), String> {
263        Ok(()) // stdout auto-flushes
264    }
265}
266
267/// File-based audit sink for production
268pub struct FileSink {
269    file_path: String,
270    level_filter: AuditSeverity,
271}
272
273impl FileSink {
274    /// Create a new file sink
275    pub fn new(file_path: impl Into<String>, min_level: AuditSeverity) -> Self {
276        Self {
277            file_path: file_path.into(),
278            level_filter: min_level,
279        }
280    }
281}
282
283impl AuditSink for FileSink {
284    fn write_event(&self, event: &AuditEvent) -> Result<(), String> {
285        if event.severity >= self.level_filter {
286            use std::fs::OpenOptions;
287            use std::io::Write;
288
289            let mut file = OpenOptions::new()
290                .create(true)
291                .append(true)
292                .open(&self.file_path)
293                .map_err(|e| format!("Failed to open audit log file: {e}"))?;
294
295            writeln!(file, "{event}").map_err(|e| format!("Failed to write to audit log: {e}"))?;
296        }
297        Ok(())
298    }
299
300    fn flush(&self) -> Result<(), String> {
301        // For append-only files, OS handles flushing
302        Ok(())
303    }
304}
305
306/// Main audit logger with multiple sinks
307pub struct AuditLogger {
308    sinks: Vec<Box<dyn AuditSink>>,
309    enabled: bool,
310}
311
312impl AuditLogger {
313    /// Create a new audit logger
314    pub fn new() -> Self {
315        Self {
316            sinks: Vec::new(),
317            enabled: true,
318        }
319    }
320
321    /// Add a sink to the logger
322    pub fn add_sink(mut self, sink: Box<dyn AuditSink>) -> Self {
323        self.sinks.push(sink);
324        self
325    }
326
327    /// Enable or disable audit logging
328    pub fn set_enabled(mut self, enabled: bool) -> Self {
329        self.enabled = enabled;
330        self
331    }
332
333    /// Log an audit event to all configured sinks
334    pub fn log_event(&self, event: AuditEvent) {
335        if !self.enabled {
336            return;
337        }
338
339        for sink in &self.sinks {
340            if let Err(e) = sink.write_event(&event) {
341                // REPS-AUDIT: last-resort report when an audit sink itself
342                // fails. `log_event` is fire-and-forget (returns `()`); we
343                // cannot bubble the error up. Stderr is the conventional
344                // out-of-band channel for daemon diagnostics. Allowed at
345                // the call site only.
346                #[allow(clippy::print_stderr)]
347                {
348                    eprintln!("Audit sink error: {e}");
349                }
350            }
351        }
352    }
353
354    /// Log a configuration access event
355    pub fn log_access(&self, key: &str, user_context: Option<&str>) {
356        let event = AuditEvent::new(AuditEventType::Access, AuditSeverity::Info)
357            .with_key(key)
358            .with_metadata("operation", "get");
359
360        let event = if let Some(user) = user_context {
361            event.with_user_context(user)
362        } else {
363            event
364        };
365
366        self.log_event(event);
367    }
368
369    /// Log a configuration modification event
370    pub fn log_modification(
371        &self,
372        key: &str,
373        old_value: Option<&Value>,
374        new_value: &Value,
375        user_context: Option<&str>,
376    ) {
377        let mut event = AuditEvent::new(AuditEventType::Modification, AuditSeverity::Warning)
378            .with_key(key)
379            .with_new_value(new_value.clone())
380            .with_metadata("operation", "set");
381
382        if let Some(old) = old_value {
383            event = event.with_old_value(old.clone());
384        }
385
386        if let Some(user) = user_context {
387            event = event.with_user_context(user);
388        }
389
390        self.log_event(event);
391    }
392
393    /// Log a validation failure event
394    pub fn log_validation_failure(
395        &self,
396        key: &str,
397        error: &str,
398        value: &Value,
399        user_context: Option<&str>,
400    ) {
401        let event = AuditEvent::new(AuditEventType::ValidationFailure, AuditSeverity::Error)
402            .with_key(key)
403            .with_new_value(value.clone())
404            .with_error(error)
405            .with_metadata("operation", "validate");
406
407        let event = if let Some(user) = user_context {
408            event.with_user_context(user)
409        } else {
410            event
411        };
412
413        self.log_event(event);
414    }
415
416    /// Log a configuration reload event
417    pub fn log_reload(&self, source: &str, success: bool, error: Option<&str>) {
418        let severity = if success {
419            AuditSeverity::Info
420        } else {
421            AuditSeverity::Error
422        };
423        let mut event = AuditEvent::new(AuditEventType::Reload, severity)
424            .with_source(source)
425            .with_metadata("operation", "reload");
426
427        if let Some(err) = error {
428            event = event.with_error(err);
429        }
430
431        self.log_event(event);
432    }
433
434    /// Flush all sinks
435    pub fn flush(&self) {
436        for sink in &self.sinks {
437            if let Err(e) = sink.flush() {
438                // REPS-AUDIT: same rationale as `log_event` above —
439                // `flush` cannot return an error, so the only way to
440                // surface a sink-side failure is the daemon stderr
441                // channel. Allowed at the call site only.
442                #[allow(clippy::print_stderr)]
443                {
444                    eprintln!("Audit sink flush error: {e}");
445                }
446            }
447        }
448    }
449}
450
451impl Default for AuditLogger {
452    fn default() -> Self {
453        Self::new()
454    }
455}
456
457/// Thread-safe global audit logger
458static GLOBAL_AUDIT_LOGGER: Mutex<Option<Arc<AuditLogger>>> = Mutex::new(None);
459
460/// Initialize the global audit logger
461pub fn init_audit_logger(logger: AuditLogger) {
462    if let Ok(mut global) = GLOBAL_AUDIT_LOGGER.lock() {
463        *global = Some(Arc::new(logger));
464    }
465    // If mutex is poisoned, we can't initialize the logger but we don't panic
466}
467
468/// Get the global audit logger
469pub fn get_audit_logger() -> Option<Arc<AuditLogger>> {
470    GLOBAL_AUDIT_LOGGER
471        .lock()
472        .ok()
473        .and_then(|guard| guard.clone())
474}
475
476/// Log an event using the global audit logger
477pub fn audit_log(event: AuditEvent) {
478    if let Some(logger) = get_audit_logger() {
479        logger.log_event(event);
480    }
481}
482
483/// Generate a unique event ID
484fn generate_event_id() -> String {
485    use std::sync::atomic::{AtomicU64, Ordering};
486    static COUNTER: AtomicU64 = AtomicU64::new(1);
487
488    let timestamp = SystemTime::now()
489        .duration_since(UNIX_EPOCH)
490        .unwrap_or_default()
491        .as_secs();
492    let counter = COUNTER.fetch_add(1, Ordering::Relaxed);
493
494    format!("{timestamp:x}-{counter:x}")
495}
496
497#[cfg(test)]
498mod tests {
499    use super::*;
500    use std::sync::{Arc, Mutex};
501
502    struct TestSink {
503        events: Arc<Mutex<Vec<AuditEvent>>>,
504    }
505
506    impl TestSink {
507        fn new() -> (Self, Arc<Mutex<Vec<AuditEvent>>>) {
508            let events = Arc::new(Mutex::new(Vec::new()));
509            (
510                Self {
511                    events: Arc::clone(&events),
512                },
513                events,
514            )
515        }
516    }
517
518    impl AuditSink for TestSink {
519        fn write_event(&self, event: &AuditEvent) -> Result<(), String> {
520            self.events.lock().unwrap().push(event.clone());
521            Ok(())
522        }
523
524        fn flush(&self) -> Result<(), String> {
525            Ok(())
526        }
527    }
528
529    #[test]
530    fn test_audit_event_creation() {
531        let event = AuditEvent::new(AuditEventType::Access, AuditSeverity::Info)
532            .with_key("test.key")
533            .with_user_context("test_user")
534            .with_metadata("operation", "get");
535
536        assert_eq!(event.event_type, AuditEventType::Access);
537        assert_eq!(event.severity, AuditSeverity::Info);
538        assert_eq!(event.key, Some("test.key".to_string()));
539        assert_eq!(event.user_context, Some("test_user".to_string()));
540        assert_eq!(event.metadata.get("operation"), Some(&"get".to_string()));
541    }
542
543    #[test]
544    fn test_audit_logger_basic() {
545        let (sink, events) = TestSink::new();
546        let logger = AuditLogger::new().add_sink(Box::new(sink));
547
548        logger.log_access("test.key", Some("test_user"));
549        logger.log_modification(
550            "test.key",
551            None,
552            &Value::String("new_value".to_string()),
553            Some("test_user"),
554        );
555
556        let events = events.lock().unwrap();
557        assert_eq!(events.len(), 2);
558
559        assert_eq!(events[0].event_type, AuditEventType::Access);
560        assert_eq!(events[0].key, Some("test.key".to_string()));
561
562        assert_eq!(events[1].event_type, AuditEventType::Modification);
563        assert_eq!(events[1].key, Some("test.key".to_string()));
564    }
565
566    #[test]
567    fn test_console_sink() {
568        let sink = ConsoleSink::new(AuditSeverity::Info);
569        let event =
570            AuditEvent::new(AuditEventType::Access, AuditSeverity::Info).with_key("test.key");
571
572        // This should not panic
573        assert!(sink.write_event(&event).is_ok());
574    }
575
576    #[test]
577    fn test_event_display() {
578        let event = AuditEvent::new(AuditEventType::Modification, AuditSeverity::Warning)
579            .with_key("test.key")
580            .with_user_context("test_user")
581            .with_old_value(Value::String("old".to_string()))
582            .with_new_value(Value::String("new".to_string()))
583            .with_metadata("operation", "set");
584
585        let display = format!("{event}");
586        assert!(display.contains("Modification"));
587        assert!(display.contains("Warning"));
588        assert!(display.contains("test.key"));
589        assert!(display.contains("test_user"));
590    }
591
592    #[test]
593    fn test_severity_filtering() {
594        let (sink, events) = TestSink::new();
595        let logger = AuditLogger::new().add_sink(Box::new(sink));
596
597        // Log events of different severities
598        logger.log_event(AuditEvent::new(AuditEventType::Access, AuditSeverity::Info));
599        logger.log_event(AuditEvent::new(
600            AuditEventType::ValidationFailure,
601            AuditSeverity::Error,
602        ));
603
604        let events = events.lock().unwrap();
605        assert_eq!(events.len(), 2);
606        assert_eq!(events[0].severity, AuditSeverity::Info);
607        assert_eq!(events[1].severity, AuditSeverity::Error);
608    }
609}