daa-rules 0.2.1

Rules engine for DAA system providing policy enforcement and decision automation
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
//! Audit logging for rule engine operations

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::VecDeque;
use std::sync::{Arc, Mutex};
use tracing::{debug, info};

use crate::engine::RuleEvaluationResult;
use crate::error::{Result, RuleError};
use crate::rules::RuleViolation;

/// Audit log entry
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuditEntry {
    pub timestamp: DateTime<Utc>,
    pub event_type: AuditEventType,
    pub message: String,
    pub metadata: serde_json::Value,
}

/// Types of audit events
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum AuditEventType {
    RuleRegistration,
    RuleRemoval,
    RuleViolation,
    EvaluationStarted,
    EvaluationCompleted,
    SystemError,
}

/// Trait for audit logging implementations
pub trait AuditLogger: Send + Sync {
    /// Log a rule registration event
    fn log_rule_registration(&self, rule_id: &str) -> Result<()>;
    
    /// Log a rule removal event
    fn log_rule_removal(&self, rule_id: &str) -> Result<()>;
    
    /// Log a rule violation
    fn log_rule_violation(&self, violation: &RuleViolation) -> Result<()>;
    
    /// Log evaluation summary
    fn log_evaluation_summary(&self, result: &RuleEvaluationResult) -> Result<()>;
    
    /// Log a system error
    fn log_system_error(&self, error: &str) -> Result<()>;
    
    /// Get recent audit entries
    fn get_recent_entries(&self, limit: usize) -> Result<Vec<AuditEntry>>;
    
    /// Get entries by event type
    fn get_entries_by_type(&self, event_type: AuditEventType, limit: usize) -> Result<Vec<AuditEntry>>;
}

/// In-memory audit logger implementation
pub struct MemoryAuditLogger {
    entries: Arc<Mutex<VecDeque<AuditEntry>>>,
    max_entries: usize,
}

impl MemoryAuditLogger {
    /// Create a new memory audit logger
    pub fn new(max_entries: usize) -> Self {
        Self {
            entries: Arc::new(Mutex::new(VecDeque::new())),
            max_entries,
        }
    }

    /// Create with default capacity
    pub fn default() -> Self {
        Self::new(10000)
    }

    fn add_entry(&self, event_type: AuditEventType, message: String, metadata: serde_json::Value) -> Result<()> {
        let entry = AuditEntry {
            timestamp: Utc::now(),
            event_type,
            message,
            metadata,
        };

        let mut entries = self.entries.lock()
            .map_err(|_| RuleError::Internal("Failed to acquire audit log lock".to_string()))?;

        // Remove old entries if we're at capacity
        while entries.len() >= self.max_entries {
            entries.pop_front();
        }

        entries.push_back(entry);
        debug!("Added audit entry: {:?}", entries.back().unwrap().event_type);
        
        Ok(())
    }

    /// Get the number of entries
    pub fn entry_count(&self) -> Result<usize> {
        let entries = self.entries.lock()
            .map_err(|_| RuleError::Internal("Failed to acquire audit log lock".to_string()))?;
        Ok(entries.len())
    }

    /// Clear all entries
    pub fn clear(&self) -> Result<()> {
        let mut entries = self.entries.lock()
            .map_err(|_| RuleError::Internal("Failed to acquire audit log lock".to_string()))?;
        entries.clear();
        info!("Cleared audit log");
        Ok(())
    }

    /// Export entries to JSON
    pub fn export_to_json(&self) -> Result<String> {
        let entries = self.entries.lock()
            .map_err(|_| RuleError::Internal("Failed to acquire audit log lock".to_string()))?;
        
        let entries_vec: Vec<AuditEntry> = entries.iter().cloned().collect();
        serde_json::to_string_pretty(&entries_vec)
            .map_err(|e| RuleError::SerializationError(e.to_string()))
    }
}

impl AuditLogger for MemoryAuditLogger {
    fn log_rule_registration(&self, rule_id: &str) -> Result<()> {
        self.add_entry(
            AuditEventType::RuleRegistration,
            format!("Rule registered: {}", rule_id),
            serde_json::json!({ "rule_id": rule_id }),
        )
    }

    fn log_rule_removal(&self, rule_id: &str) -> Result<()> {
        self.add_entry(
            AuditEventType::RuleRemoval,
            format!("Rule removed: {}", rule_id),
            serde_json::json!({ "rule_id": rule_id }),
        )
    }

    fn log_rule_violation(&self, violation: &RuleViolation) -> Result<()> {
        self.add_entry(
            AuditEventType::RuleViolation,
            format!("Rule violation: {}", violation.message),
            serde_json::json!({
                "rule_id": violation.rule_id,
                "severity": violation.severity,
                "context": violation.context
            }),
        )
    }

    fn log_evaluation_summary(&self, result: &RuleEvaluationResult) -> Result<()> {
        self.add_entry(
            AuditEventType::EvaluationCompleted,
            result.summary(),
            serde_json::json!({
                "rules_evaluated": result.rules_evaluated,
                "rules_passed": result.rules_passed,
                "rules_failed": result.rules_failed,
                "violations_count": result.violations.len(),
                "execution_time_ms": result.execution_time_ms,
                "has_critical_violations": result.has_critical_violations()
            }),
        )
    }

    fn log_system_error(&self, error: &str) -> Result<()> {
        self.add_entry(
            AuditEventType::SystemError,
            format!("System error: {}", error),
            serde_json::json!({ "error": error }),
        )
    }

    fn get_recent_entries(&self, limit: usize) -> Result<Vec<AuditEntry>> {
        let entries = self.entries.lock()
            .map_err(|_| RuleError::Internal("Failed to acquire audit log lock".to_string()))?;
        
        let recent: Vec<AuditEntry> = entries
            .iter()
            .rev() // Most recent first
            .take(limit)
            .cloned()
            .collect();
        
        Ok(recent)
    }

    fn get_entries_by_type(&self, event_type: AuditEventType, limit: usize) -> Result<Vec<AuditEntry>> {
        let entries = self.entries.lock()
            .map_err(|_| RuleError::Internal("Failed to acquire audit log lock".to_string()))?;
        
        let filtered: Vec<AuditEntry> = entries
            .iter()
            .rev()
            .filter(|entry| std::mem::discriminant(&entry.event_type) == std::mem::discriminant(&event_type))
            .take(limit)
            .cloned()
            .collect();
        
        Ok(filtered)
    }
}

/// File-based audit logger implementation
pub struct FileAuditLogger {
    file_path: String,
    memory_logger: MemoryAuditLogger,
}

impl FileAuditLogger {
    /// Create a new file audit logger
    pub fn new(file_path: String) -> Self {
        Self {
            file_path,
            memory_logger: MemoryAuditLogger::new(1000), // Keep recent entries in memory
        }
    }

    fn write_to_file(&self, entry: &AuditEntry) -> Result<()> {
        use std::fs::OpenOptions;
        use std::io::Write;
        
        let json_line = format!("{}\n", serde_json::to_string(entry)?);
        
        let mut file = OpenOptions::new()
            .create(true)
            .append(true)
            .open(&self.file_path)
            .map_err(|e| RuleError::Internal(format!("Failed to open audit file: {}", e)))?;
        
        file.write_all(json_line.as_bytes())
            .map_err(|e| RuleError::Internal(format!("Failed to write to audit file: {}", e)))?;
        
        file.sync_all()
            .map_err(|e| RuleError::Internal(format!("Failed to sync audit file: {}", e)))?;
        
        Ok(())
    }
}

impl AuditLogger for FileAuditLogger {
    fn log_rule_registration(&self, rule_id: &str) -> Result<()> {
        let entry = AuditEntry {
            timestamp: Utc::now(),
            event_type: AuditEventType::RuleRegistration,
            message: format!("Rule registered: {}", rule_id),
            metadata: serde_json::json!({ "rule_id": rule_id }),
        };
        
        self.write_to_file(&entry)?;
        self.memory_logger.log_rule_registration(rule_id)?;
        Ok(())
    }

    fn log_rule_removal(&self, rule_id: &str) -> Result<()> {
        let entry = AuditEntry {
            timestamp: Utc::now(),
            event_type: AuditEventType::RuleRemoval,
            message: format!("Rule removed: {}", rule_id),
            metadata: serde_json::json!({ "rule_id": rule_id }),
        };
        
        self.write_to_file(&entry)?;
        self.memory_logger.log_rule_removal(rule_id)?;
        Ok(())
    }

    fn log_rule_violation(&self, violation: &RuleViolation) -> Result<()> {
        let entry = AuditEntry {
            timestamp: Utc::now(),
            event_type: AuditEventType::RuleViolation,
            message: format!("Rule violation: {}", violation.message),
            metadata: serde_json::json!({
                "rule_id": violation.rule_id,
                "severity": violation.severity,
                "context": violation.context
            }),
        };
        
        self.write_to_file(&entry)?;
        self.memory_logger.log_rule_violation(violation)?;
        Ok(())
    }

    fn log_evaluation_summary(&self, result: &RuleEvaluationResult) -> Result<()> {
        let entry = AuditEntry {
            timestamp: Utc::now(),
            event_type: AuditEventType::EvaluationCompleted,
            message: result.summary(),
            metadata: serde_json::json!({
                "rules_evaluated": result.rules_evaluated,
                "rules_passed": result.rules_passed,
                "rules_failed": result.rules_failed,
                "violations_count": result.violations.len(),
                "execution_time_ms": result.execution_time_ms,
                "has_critical_violations": result.has_critical_violations()
            }),
        };
        
        self.write_to_file(&entry)?;
        self.memory_logger.log_evaluation_summary(result)?;
        Ok(())
    }

    fn log_system_error(&self, error: &str) -> Result<()> {
        let entry = AuditEntry {
            timestamp: Utc::now(),
            event_type: AuditEventType::SystemError,
            message: format!("System error: {}", error),
            metadata: serde_json::json!({ "error": error }),
        };
        
        self.write_to_file(&entry)?;
        self.memory_logger.log_system_error(error)?;
        Ok(())
    }

    fn get_recent_entries(&self, limit: usize) -> Result<Vec<AuditEntry>> {
        // Return from memory cache for recent entries
        self.memory_logger.get_recent_entries(limit)
    }

    fn get_entries_by_type(&self, event_type: AuditEventType, limit: usize) -> Result<Vec<AuditEntry>> {
        // Return from memory cache for recent entries
        self.memory_logger.get_entries_by_type(event_type, limit)
    }
}

/// Audit log aggregator
pub struct AuditLog {
    logger: Arc<dyn AuditLogger>,
}

impl AuditLog {
    /// Create new audit log with given logger
    pub fn new(logger: Arc<dyn AuditLogger>) -> Self {
        Self { logger }
    }

    /// Create with memory logger
    pub fn with_memory_logger(max_entries: usize) -> Self {
        Self::new(Arc::new(MemoryAuditLogger::new(max_entries)))
    }

    /// Create with file logger
    pub fn with_file_logger(file_path: String) -> Self {
        Self::new(Arc::new(FileAuditLogger::new(file_path)))
    }

    /// Get the underlying logger
    pub fn logger(&self) -> Arc<dyn AuditLogger> {
        self.logger.clone()
    }

    /// Get violation statistics
    pub fn get_violation_stats(&self) -> Result<ViolationStats> {
        let violations = self.logger.get_entries_by_type(AuditEventType::RuleViolation, 1000)?;
        
        let mut stats = ViolationStats::default();
        stats.total_violations = violations.len();
        
        for entry in violations {
            if let Some(severity) = entry.metadata.get("severity") {
                if let Some(severity_str) = severity.as_str() {
                    match severity_str {
                        "Info" => stats.info_violations += 1,
                        "Warning" => stats.warning_violations += 1,
                        "Error" => stats.error_violations += 1,
                        "Critical" => stats.critical_violations += 1,
                        _ => {}
                    }
                }
            }
        }
        
        Ok(stats)
    }
}

/// Statistics about rule violations
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct ViolationStats {
    pub total_violations: usize,
    pub info_violations: usize,
    pub warning_violations: usize,
    pub error_violations: usize,
    pub critical_violations: usize,
}

impl ViolationStats {
    pub fn summary(&self) -> String {
        format!(
            "Total: {}, Critical: {}, Error: {}, Warning: {}, Info: {}",
            self.total_violations,
            self.critical_violations,
            self.error_violations,
            self.warning_violations,
            self.info_violations
        )
    }
}

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

    #[test]
    fn test_memory_audit_logger() {
        let logger = MemoryAuditLogger::new(10);
        
        logger.log_rule_registration("test_rule").unwrap();
        assert_eq!(logger.entry_count().unwrap(), 1);
        
        let entries = logger.get_recent_entries(5).unwrap();
        assert_eq!(entries.len(), 1);
        assert!(matches!(entries[0].event_type, AuditEventType::RuleRegistration));
    }

    #[test]
    fn test_memory_logger_capacity() {
        let logger = MemoryAuditLogger::new(2);
        
        logger.log_rule_registration("rule1").unwrap();
        logger.log_rule_registration("rule2").unwrap();
        logger.log_rule_registration("rule3").unwrap();
        
        // Should only keep 2 entries (most recent)
        assert_eq!(logger.entry_count().unwrap(), 2);
    }

    #[test]
    fn test_violation_logging() {
        let logger = MemoryAuditLogger::new(10);
        
        let violation = RuleViolation {
            rule_id: "test_rule".to_string(),
            message: "Test violation".to_string(),
            severity: ViolationSeverity::Error,
            timestamp: Utc::now(),
            context: serde_json::json!({}),
        };
        
        logger.log_rule_violation(&violation).unwrap();
        
        let entries = logger.get_entries_by_type(AuditEventType::RuleViolation, 5).unwrap();
        assert_eq!(entries.len(), 1);
    }

    #[test]
    fn test_audit_log_stats() {
        let audit_log = AuditLog::with_memory_logger(100);
        
        let violation = RuleViolation {
            rule_id: "test_rule".to_string(),
            message: "Test violation".to_string(),
            severity: ViolationSeverity::Critical,
            timestamp: Utc::now(),
            context: serde_json::json!({}),
        };
        
        audit_log.logger.log_rule_violation(&violation).unwrap();
        
        let stats = audit_log.get_violation_stats().unwrap();
        assert_eq!(stats.total_violations, 1);
        assert_eq!(stats.critical_violations, 1);
    }
}