Skip to main content

auth_framework/
audit.rs

1//! Comprehensive audit logging and security event tracking.
2//!
3//! This module provides detailed audit logging for all authentication,
4//! authorization, and security-related events in the system.
5impl Default for CorrelationIdGenerator {
6    fn default() -> Self {
7        Self::new()
8    }
9}
10use crate::errors::Result;
11use async_trait::async_trait;
12use chrono::TimeZone as _;
13use serde::{Deserialize, Serialize};
14use std::collections::HashMap;
15use std::time::SystemTime;
16
17/// Audit event types
18#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
19pub enum AuditEventType {
20    // Authentication events
21    LoginSuccess,
22    LoginFailure,
23    Logout,
24    TokenRefresh,
25    TokenExpired,
26    TokenRevoked,
27
28    // MFA events
29    MfaSetup,
30    MfaChallengeCreated,
31    MfaVerificationSuccess,
32    MfaVerificationFailure,
33    MfaMethodEnabled,
34    MfaMethodDisabled,
35
36    // Authorization events
37    PermissionGranted,
38    PermissionDenied,
39    RoleAssigned,
40    RoleRevoked,
41    RoleCreated,
42    RoleUpdated,
43    RoleDeleted,
44
45    // User management events
46    UserCreated,
47    UserUpdated,
48    UserDeleted,
49    UserActivated,
50    UserDeactivated,
51    UserPasswordChanged,
52    UserPasswordReset,
53
54    // Security events
55    AccountLocked,
56    AccountUnlocked,
57    SuspiciousActivity,
58    BruteForceDetected,
59    RateLimitExceeded,
60    SecurityPolicyViolation,
61    SecurityViolation,
62
63    // Administrative events
64    AdminAction,
65    ConfigurationChanged,
66    SystemStartup,
67    SystemShutdown,
68    BackupCreated,
69    DataExported,
70    DataImported,
71}
72
73impl std::fmt::Display for AuditEventType {
74    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
75        match self {
76            Self::LoginSuccess => write!(f, "login_success"),
77            Self::LoginFailure => write!(f, "login_failure"),
78            Self::Logout => write!(f, "logout"),
79            Self::TokenRefresh => write!(f, "token_refresh"),
80            Self::TokenExpired => write!(f, "token_expired"),
81            Self::TokenRevoked => write!(f, "token_revoked"),
82            Self::MfaSetup => write!(f, "mfa_setup"),
83            Self::MfaChallengeCreated => write!(f, "mfa_challenge_created"),
84            Self::MfaVerificationSuccess => write!(f, "mfa_verification_success"),
85            Self::MfaVerificationFailure => write!(f, "mfa_verification_failure"),
86            Self::MfaMethodEnabled => write!(f, "mfa_method_enabled"),
87            Self::MfaMethodDisabled => write!(f, "mfa_method_disabled"),
88            Self::PermissionGranted => write!(f, "permission_granted"),
89            Self::PermissionDenied => write!(f, "permission_denied"),
90            Self::RoleAssigned => write!(f, "role_assigned"),
91            Self::RoleRevoked => write!(f, "role_revoked"),
92            Self::RoleCreated => write!(f, "role_created"),
93            Self::RoleUpdated => write!(f, "role_updated"),
94            Self::RoleDeleted => write!(f, "role_deleted"),
95            Self::UserCreated => write!(f, "user_created"),
96            Self::UserUpdated => write!(f, "user_updated"),
97            Self::UserDeleted => write!(f, "user_deleted"),
98            Self::UserActivated => write!(f, "user_activated"),
99            Self::UserDeactivated => write!(f, "user_deactivated"),
100            Self::UserPasswordChanged => write!(f, "user_password_changed"),
101            Self::UserPasswordReset => write!(f, "user_password_reset"),
102            Self::AccountLocked => write!(f, "account_locked"),
103            Self::AccountUnlocked => write!(f, "account_unlocked"),
104            Self::SuspiciousActivity => write!(f, "suspicious_activity"),
105            Self::BruteForceDetected => write!(f, "brute_force_detected"),
106            Self::RateLimitExceeded => write!(f, "rate_limit_exceeded"),
107            Self::SecurityPolicyViolation => write!(f, "security_policy_violation"),
108            Self::SecurityViolation => write!(f, "security_violation"),
109            Self::AdminAction => write!(f, "admin_action"),
110            Self::ConfigurationChanged => write!(f, "configuration_changed"),
111            Self::SystemStartup => write!(f, "system_startup"),
112            Self::SystemShutdown => write!(f, "system_shutdown"),
113            Self::BackupCreated => write!(f, "backup_created"),
114            Self::DataExported => write!(f, "data_exported"),
115            Self::DataImported => write!(f, "data_imported"),
116        }
117    }
118}
119
120/// Security risk level
121#[derive(Debug, Clone, PartialEq, PartialOrd, Ord, Eq, Serialize, Deserialize)]
122pub enum RiskLevel {
123    Low,
124    Medium,
125    High,
126    Critical,
127}
128
129impl std::fmt::Display for RiskLevel {
130    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
131        match self {
132            Self::Low => write!(f, "low"),
133            Self::Medium => write!(f, "medium"),
134            Self::High => write!(f, "high"),
135            Self::Critical => write!(f, "critical"),
136        }
137    }
138}
139
140/// Audit event outcome
141#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
142pub enum EventOutcome {
143    Success,
144    Failure,
145    Partial,
146    Unknown,
147}
148
149impl std::fmt::Display for EventOutcome {
150    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
151        match self {
152            Self::Success => write!(f, "success"),
153            Self::Failure => write!(f, "failure"),
154            Self::Partial => write!(f, "partial"),
155            Self::Unknown => write!(f, "unknown"),
156        }
157    }
158}
159
160/// Comprehensive audit event
161#[derive(Clone, Serialize, Deserialize)]
162pub struct AuditEvent {
163    /// Unique event ID
164    pub id: String,
165    /// Type of event
166    pub event_type: AuditEventType,
167    /// When the event occurred
168    pub timestamp: SystemTime,
169    /// User who initiated the event (if applicable)
170    pub user_id: Option<String>,
171    /// Session ID (if applicable)
172    pub session_id: Option<String>,
173    /// Event outcome
174    pub outcome: EventOutcome,
175    /// Risk level assessment
176    pub risk_level: RiskLevel,
177    /// Human-readable event description
178    pub description: String,
179    /// Additional event details
180    pub details: HashMap<String, String>,
181    /// Request metadata
182    pub request_metadata: RequestMetadata,
183    /// Resource affected (if applicable)
184    pub resource: Option<ResourceInfo>,
185    /// Actor information
186    pub actor: ActorInfo,
187    /// Correlation ID for tracking related events
188    pub correlation_id: Option<String>,
189}
190
191impl std::fmt::Debug for AuditEvent {
192    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
193        let mut d = f.debug_struct("AuditEvent");
194        d.field("id", &self.id);
195        d.field("event_type", &self.event_type);
196        d.field("timestamp", &self.timestamp);
197        d.field("user_id", &self.user_id);
198        d.field(
199            "session_id",
200            &crate::utils::redact::redacted(&self.session_id),
201        );
202        d.field("outcome", &self.outcome);
203        d.field("risk_level", &self.risk_level);
204        d.field("description", &self.description);
205        d.field("details", &self.details);
206        d.field("request_metadata", &self.request_metadata);
207        d.field("resource", &self.resource);
208        d.field("actor", &self.actor);
209        d.field("correlation_id", &self.correlation_id);
210        d.finish()
211    }
212}
213
214/// Request metadata for audit context
215#[derive(Debug, Clone, Serialize, Deserialize)]
216pub struct RequestMetadata {
217    /// Source IP address
218    pub ip_address: Option<String>,
219    /// User agent string
220    pub user_agent: Option<String>,
221    /// Request ID
222    pub request_id: Option<String>,
223    /// API endpoint or action
224    pub endpoint: Option<String>,
225    /// HTTP method (if applicable)
226    pub http_method: Option<String>,
227    /// Geographic location (if available)
228    pub geolocation: Option<GeolocationInfo>,
229    /// Device information
230    pub device_info: Option<DeviceInfo>,
231}
232
233/// Geographic location information
234#[derive(Debug, Clone, Serialize, Deserialize)]
235pub struct GeolocationInfo {
236    pub country: Option<String>,
237    pub region: Option<String>,
238    pub city: Option<String>,
239    pub latitude: Option<f64>,
240    pub longitude: Option<f64>,
241}
242
243/// Device information
244#[derive(Debug, Clone, Serialize, Deserialize)]
245pub struct DeviceInfo {
246    pub device_type: Option<String>,
247    pub operating_system: Option<String>,
248    pub browser: Option<String>,
249    pub is_mobile: bool,
250    pub screen_resolution: Option<String>,
251}
252
253/// Resource information
254#[derive(Debug, Clone, Serialize, Deserialize)]
255pub struct ResourceInfo {
256    /// Resource type (user, document, api, etc.)
257    pub resource_type: String,
258    /// Resource ID
259    pub resource_id: String,
260    /// Resource name or title
261    pub resource_name: Option<String>,
262    /// Additional resource attributes
263    pub attributes: HashMap<String, String>,
264}
265
266/// Actor information (who performed the action)
267#[derive(Debug, Clone, Serialize, Deserialize)]
268pub struct ActorInfo {
269    /// Actor type (user, system, api_client, etc.)
270    pub actor_type: String,
271    /// Actor ID
272    pub actor_id: String,
273    /// Actor name or identifier
274    pub actor_name: Option<String>,
275    /// Roles or permissions of the actor
276    pub roles: Vec<String>,
277}
278
279/// Audit log storage trait
280#[async_trait]
281pub trait AuditStorage: Send + Sync {
282    /// Store an audit event
283    async fn store_event(&self, event: &AuditEvent) -> Result<()>;
284
285    /// Query audit events with filters
286    async fn query_events(&self, query: &AuditQuery) -> Result<Vec<AuditEvent>>;
287
288    /// Get event by ID
289    async fn get_event(&self, event_id: &str) -> Result<Option<AuditEvent>>;
290
291    /// Count events matching criteria
292    async fn count_events(&self, query: &AuditQuery) -> Result<u64>;
293
294    /// Delete old events (for retention management)
295    async fn delete_old_events(&self, before: SystemTime) -> Result<u64>;
296
297    /// Get audit statistics
298    async fn get_statistics(&self, query: &StatsQuery) -> Result<AuditStatistics>;
299}
300
301/// Query parameters for audit events
302#[derive(Debug, Clone)]
303pub struct AuditQuery {
304    /// Filter by event types
305    pub event_types: Option<Vec<AuditEventType>>,
306    /// Filter by user ID
307    pub user_id: Option<String>,
308    /// Filter by risk level
309    pub risk_level: Option<RiskLevel>,
310    /// Filter by outcome
311    pub outcome: Option<EventOutcome>,
312    /// Time range filter
313    pub time_range: Option<TimeRange>,
314    /// IP address filter
315    pub ip_address: Option<String>,
316    /// Resource filter
317    pub resource_type: Option<String>,
318    /// Actor filter
319    pub actor_id: Option<String>,
320    /// Correlation ID filter
321    pub correlation_id: Option<String>,
322    /// Limit number of results
323    pub limit: Option<u64>,
324    /// Offset for pagination
325    pub offset: Option<u64>,
326    /// Sort order
327    pub sort_order: SortOrder,
328}
329
330/// Time range for queries
331#[derive(Debug, Clone)]
332pub struct TimeRange {
333    pub start: SystemTime,
334    pub end: SystemTime,
335}
336
337/// Sort order for queries
338#[derive(Debug, Clone, Default)]
339pub enum SortOrder {
340    TimestampAsc,
341    #[default]
342    TimestampDesc,
343    RiskLevelDesc,
344}
345
346/// Statistics query parameters
347#[derive(Debug, Clone)]
348pub struct StatsQuery {
349    pub time_range: TimeRange,
350    pub group_by: Vec<StatsGroupBy>,
351}
352
353/// Grouping options for statistics
354#[derive(Debug, Clone)]
355pub enum StatsGroupBy {
356    EventType,
357    RiskLevel,
358    Outcome,
359    Hour,
360    Day,
361    Week,
362    UserId,
363    IpAddress,
364}
365
366/// Audit statistics result
367#[derive(Debug, Clone, Serialize, Deserialize)]
368pub struct AuditStatistics {
369    pub total_events: u64,
370    pub event_type_counts: HashMap<String, u64>,
371    pub risk_level_counts: HashMap<String, u64>,
372    pub outcome_counts: HashMap<String, u64>,
373    pub time_series: Vec<TimeSeriesPoint>,
374    pub top_users: Vec<UserEventCount>,
375    pub top_ips: Vec<IpEventCount>,
376}
377
378/// Time series data point
379#[derive(Debug, Clone, Serialize, Deserialize)]
380pub struct TimeSeriesPoint {
381    pub timestamp: SystemTime,
382    pub count: u64,
383}
384
385/// User event count
386#[derive(Debug, Clone, Serialize, Deserialize)]
387pub struct UserEventCount {
388    pub user_id: String,
389    pub event_count: u64,
390}
391
392/// IP address event count
393#[derive(Debug, Clone, Serialize, Deserialize)]
394pub struct IpEventCount {
395    pub ip_address: String,
396    pub event_count: u64,
397}
398
399/// Main audit logger
400pub struct AuditLogger<S: AuditStorage> {
401    storage: S,
402    correlation_generator: CorrelationIdGenerator,
403}
404
405impl<S: AuditStorage> AuditLogger<S> {
406    /// Create a new audit logger
407    pub fn new(storage: S) -> Self {
408        Self {
409            storage,
410            correlation_generator: CorrelationIdGenerator::new(),
411        }
412    }
413
414    /// Log an audit event
415    pub async fn log_event(&self, mut event: AuditEvent) -> Result<()> {
416        // Generate ID if not provided
417        if event.id.is_empty() {
418            event.id = uuid::Uuid::new_v4().to_string();
419        }
420
421        // Set timestamp if not provided
422        if event.timestamp == SystemTime::UNIX_EPOCH {
423            event.timestamp = SystemTime::now();
424        }
425
426        // Store the event
427        self.storage.store_event(&event).await?;
428
429        // Check for security alerts
430        self.check_security_alerts(&event).await?;
431
432        Ok(())
433    }
434
435    /// Log authentication success
436    pub async fn log_login_success(
437        &self,
438        user_id: &str,
439        session_id: &str,
440        metadata: RequestMetadata,
441    ) -> Result<()> {
442        let event = AuditEvent::builder(
443            AuditEventType::LoginSuccess,
444            "User successfully authenticated",
445        )
446        .user_id(user_id)
447        .session_id(session_id)
448        .outcome(EventOutcome::Success)
449        .request_metadata(metadata)
450        .with_actor("user", user_id)
451        .correlation_id(self.correlation_generator.generate())
452        .build();
453
454        self.log_event(event).await
455    }
456
457    /// Log authentication failure
458    pub async fn log_login_failure(
459        &self,
460        attempted_user: &str,
461        reason: &str,
462        metadata: RequestMetadata,
463    ) -> Result<()> {
464        let mut details = HashMap::new();
465        details.insert("failure_reason".to_string(), reason.to_string());
466        details.insert("attempted_user".to_string(), attempted_user.to_string());
467
468        let event = AuditEvent::builder(
469            AuditEventType::LoginFailure,
470            format!("Authentication failed for user: {}", attempted_user),
471        )
472        .outcome(EventOutcome::Failure)
473        .risk_level(RiskLevel::Medium)
474        .details(details)
475        .request_metadata(metadata)
476        .with_actor("user", attempted_user)
477        .correlation_id(self.correlation_generator.generate())
478        .build();
479
480        self.log_event(event).await
481    }
482
483    /// Log permission denied event
484    pub async fn log_permission_denied(
485        &self,
486        user_id: &str,
487        resource: ResourceInfo,
488        permission: &str,
489        metadata: RequestMetadata,
490    ) -> Result<()> {
491        let mut details = HashMap::new();
492        details.insert("requested_permission".to_string(), permission.to_string());
493
494        let event = AuditEvent::builder(
495            AuditEventType::PermissionDenied,
496            format!(
497                "Permission denied: {} on {}",
498                permission, resource.resource_type
499            ),
500        )
501        .user_id(user_id)
502        .outcome(EventOutcome::Failure)
503        .risk_level(RiskLevel::Medium)
504        .details(details)
505        .request_metadata(metadata)
506        .resource(resource)
507        .with_actor("user", user_id)
508        .correlation_id(self.correlation_generator.generate())
509        .build();
510
511        self.log_event(event).await
512    }
513
514    /// Log suspicious activity
515    pub async fn log_suspicious_activity(
516        &self,
517        user_id: Option<&str>,
518        activity_type: &str,
519        description: &str,
520        metadata: RequestMetadata,
521    ) -> Result<()> {
522        let mut details = HashMap::new();
523        details.insert("activity_type".to_string(), activity_type.to_string());
524
525        let mut builder = AuditEvent::builder(AuditEventType::SuspiciousActivity, description)
526            .outcome(EventOutcome::Unknown)
527            .risk_level(RiskLevel::High)
528            .details(details)
529            .request_metadata(metadata)
530            .with_actor(
531                user_id.map(|_| "user").unwrap_or("system"),
532                user_id.unwrap_or("system"),
533            )
534            .correlation_id(self.correlation_generator.generate());
535        if let Some(uid) = user_id {
536            builder = builder.user_id(uid);
537        }
538        let event = builder.build();
539
540        self.log_event(event).await
541    }
542
543    /// Check for security alerts based on event patterns
544    async fn check_security_alerts(&self, event: &AuditEvent) -> Result<()> {
545        match event.event_type {
546            AuditEventType::LoginFailure => {
547                self.check_brute_force_pattern(event).await?;
548            }
549            AuditEventType::SuspiciousActivity
550            | AuditEventType::BruteForceDetected
551            | AuditEventType::SecurityPolicyViolation
552            | AuditEventType::SecurityViolation => {
553                self.trigger_security_alert(event).await?;
554            }
555            AuditEventType::AccountLocked | AuditEventType::RateLimitExceeded => {
556                // Elevated events — worth logging as alerts but not as urgent
557                tracing::warn!(
558                    event_type = ?event.event_type,
559                    user_id = ?event.user_id,
560                    "Security-relevant audit event recorded"
561                );
562            }
563            // Non-security events — no alert action needed
564            _ => {}
565        }
566        Ok(())
567    }
568
569    /// Check for brute force attack patterns
570    async fn check_brute_force_pattern(&self, event: &AuditEvent) -> Result<()> {
571        let mut query = AuditQuery::builder()
572            .event_types(vec![AuditEventType::LoginFailure])
573            .last_seconds(300)
574            .limit(10)
575            .build();
576        query.ip_address = event.request_metadata.ip_address.clone();
577
578        let recent_failures = self.storage.query_events(&query).await?;
579
580        if recent_failures.len() >= 5 {
581            // Log brute force detection
582            let mut details = HashMap::new();
583            details.insert(
584                "failure_count".to_string(),
585                recent_failures.len().to_string(),
586            );
587            details.insert("time_window".to_string(), "300".to_string());
588
589            let brute_force_event = AuditEvent::builder(
590                AuditEventType::BruteForceDetected,
591                "Brute force attack detected",
592            )
593            .outcome(EventOutcome::Success)
594            .risk_level(RiskLevel::Critical)
595            .details(details)
596            .request_metadata(event.request_metadata.clone())
597            .actor(ActorInfo {
598                actor_type: "system".to_string(),
599                actor_id: "security_monitor".to_string(),
600                actor_name: Some("Security Monitor".to_string()),
601                roles: vec!["system".to_string()],
602            })
603            .correlation_id(self.correlation_generator.generate())
604            .build();
605
606            self.storage.store_event(&brute_force_event).await?;
607        }
608
609        Ok(())
610    }
611
612    /// Trigger security alert
613    async fn trigger_security_alert(&self, event: &AuditEvent) -> Result<()> {
614        tracing::warn!(
615            event_type = ?event.event_type,
616            user_id = ?event.user_id,
617            risk_level = ?event.risk_level,
618            description = %event.description,
619            ip_address = ?event.request_metadata.ip_address,
620            "SECURITY ALERT: {}", event.description
621        );
622        Ok(())
623    }
624
625    /// Query audit events
626    pub async fn query_events(&self, query: &AuditQuery) -> Result<Vec<AuditEvent>> {
627        self.storage.query_events(query).await
628    }
629
630    /// Get audit statistics
631    pub async fn get_statistics(&self, query: &StatsQuery) -> Result<AuditStatistics> {
632        self.storage.get_statistics(query).await
633    }
634
635    /// Get failed login count in the last 24 hours
636    pub async fn get_failed_login_count_24h(&self) -> Result<u64> {
637        let query = AuditQuery::builder()
638            .event_types(vec![AuditEventType::LoginFailure])
639            .last_24h()
640            .build();
641        self.storage.count_events(&query).await
642    }
643
644    /// Get successful login count in the last 24 hours
645    pub async fn get_successful_login_count_24h(&self) -> Result<u64> {
646        let query = AuditQuery::builder()
647            .event_types(vec![AuditEventType::LoginSuccess])
648            .last_24h()
649            .build();
650        self.storage.count_events(&query).await
651    }
652
653    /// Get token issued count in the last 24 hours
654    pub async fn get_token_issued_count_24h(&self) -> Result<u64> {
655        let query = AuditQuery::builder()
656            .event_types(vec![
657                AuditEventType::TokenRefresh,
658                AuditEventType::LoginSuccess,
659            ])
660            .last_24h()
661            .build();
662        self.storage.count_events(&query).await
663    }
664
665    /// Get unique users count in the last 24 hours
666    pub async fn get_unique_users_24h(&self) -> Result<u64> {
667        let query = AuditQuery::builder()
668            .event_types(vec![AuditEventType::LoginSuccess])
669            .last_24h()
670            .build();
671
672        let events = self.storage.query_events(&query).await?;
673        let unique_users: std::collections::HashSet<_> =
674            events.iter().filter_map(|e| e.user_id.as_ref()).collect();
675        Ok(unique_users.len() as u64)
676    }
677
678    /// Get password reset count in the last 24 hours
679    pub async fn get_password_reset_count_24h(&self) -> Result<u64> {
680        let query = AuditQuery::builder()
681            .event_types(vec![AuditEventType::UserPasswordReset])
682            .last_24h()
683            .build();
684        self.storage.count_events(&query).await
685    }
686
687    /// Get admin action count in the last 24 hours
688    pub async fn get_admin_action_count_24h(&self) -> Result<u64> {
689        let query = AuditQuery::builder()
690            .event_types(vec![
691                AuditEventType::AdminAction,
692                AuditEventType::UserCreated,
693                AuditEventType::UserUpdated,
694                AuditEventType::UserDeleted,
695                AuditEventType::RoleCreated,
696                AuditEventType::RoleUpdated,
697                AuditEventType::RoleDeleted,
698            ])
699            .last_24h()
700            .build();
701        self.storage.count_events(&query).await
702    }
703
704    /// Get security alert count in the last 24 hours
705    pub async fn get_security_alert_count_24h(&self) -> Result<u64> {
706        let query = AuditQuery::builder()
707            .event_types(vec![
708                AuditEventType::SuspiciousActivity,
709                AuditEventType::BruteForceDetected,
710                AuditEventType::SecurityViolation,
711            ])
712            .last_24h()
713            .risk_level(RiskLevel::High)
714            .build();
715        self.storage.count_events(&query).await
716    }
717
718    /// Get permission check event count in the last hour.
719    pub async fn get_permission_checks_last_hour(&self) -> Result<u64> {
720        let query = AuditQuery::builder()
721            .event_types(vec![
722                AuditEventType::PermissionGranted,
723                AuditEventType::PermissionDenied,
724            ])
725            .last_seconds(3600)
726            .build();
727        self.storage.count_events(&query).await
728    }
729
730    /// Get permission-related audit log entries with optional filters.
731    pub async fn get_permission_audit_logs(
732        &self,
733        user_id: Option<&str>,
734        action: Option<&str>,
735        resource: Option<&str>,
736        limit: Option<usize>,
737    ) -> Result<Vec<String>> {
738        let mut builder = AuditQuery::builder().event_types(vec![
739            AuditEventType::PermissionGranted,
740            AuditEventType::PermissionDenied,
741            AuditEventType::RoleAssigned,
742            AuditEventType::RoleRevoked,
743            AuditEventType::RoleCreated,
744            AuditEventType::RoleUpdated,
745            AuditEventType::RoleDeleted,
746        ]);
747        if let Some(uid) = user_id {
748            builder = builder.user_id(uid);
749        }
750        if let Some(rt) = resource {
751            builder = builder.resource_type(rt);
752        }
753        if let Some(l) = limit {
754            builder = builder.limit(l as u64);
755        }
756        let query = builder.build();
757
758        let events = self.storage.query_events(&query).await?;
759
760        let logs = events
761            .into_iter()
762            .filter(|e| {
763                action.is_none_or(|a| {
764                    e.description.to_lowercase().contains(&a.to_lowercase())
765                        || e.details
766                            .values()
767                            .any(|v| v.to_lowercase().contains(&a.to_lowercase()))
768                })
769            })
770            .map(|e| {
771                let ts = e
772                    .timestamp
773                    .duration_since(std::time::UNIX_EPOCH)
774                    .map(|d| {
775                        chrono::Utc
776                            .timestamp_opt(d.as_secs() as i64, 0)
777                            .single()
778                            .map(|dt| dt.format("%Y-%m-%dT%H:%M:%SZ").to_string())
779                            .unwrap_or_else(|| "unknown-time".to_string())
780                    })
781                    .unwrap_or_else(|_| "unknown-time".to_string());
782                let uid = e.user_id.as_deref().unwrap_or("system");
783                format!(
784                    "[{}] {} user={} outcome={} - {}",
785                    ts, e.event_type, uid, e.outcome, e.description
786                )
787            })
788            .collect();
789
790        Ok(logs)
791    }
792
793    /// Assemble comprehensive security audit statistics.
794    ///
795    /// `active_sessions` should be obtained from the session manager
796    /// and passed in by the caller.
797    pub async fn get_security_audit_stats(
798        &self,
799        active_sessions: u64,
800    ) -> Result<SecurityAuditStats> {
801        let failed_logins_24h = self.get_failed_login_count_24h().await.unwrap_or(0);
802        let successful_logins_24h = self
803            .get_successful_login_count_24h()
804            .await
805            .unwrap_or(active_sessions * 2);
806        let token_issued_24h = self
807            .get_token_issued_count_24h()
808            .await
809            .unwrap_or(active_sessions * 3);
810        let unique_users_24h = self
811            .get_unique_users_24h()
812            .await
813            .unwrap_or((successful_logins_24h as f64 * 0.7) as u64);
814        let password_resets_24h = self.get_password_reset_count_24h().await.unwrap_or(0);
815        let admin_actions_24h = self.get_admin_action_count_24h().await.unwrap_or(0);
816        let security_alerts_24h = self.get_security_alert_count_24h().await.unwrap_or(0);
817
818        Ok(SecurityAuditStats {
819            active_sessions,
820            failed_logins_24h,
821            successful_logins_24h,
822            unique_users_24h,
823            token_issued_24h,
824            password_resets_24h,
825            admin_actions_24h,
826            security_alerts_24h,
827            collection_timestamp: chrono::Utc::now(),
828        })
829    }
830
831    /// Emit a structured tracing event for an authentication event (success, failure, or MFA required).
832    ///
833    /// Callers are responsible for applying their own config guards before invoking this.
834    pub async fn log_auth_trace_event(
835        &self,
836        event_type: &str,
837        user_id: &str,
838        method: &str,
839        client_ip: &str,
840        user_agent: &str,
841    ) {
842        tracing::info!(
843            target: "auth_audit",
844            event_type = event_type,
845            user_id = user_id,
846            method = method,
847            client_ip = client_ip,
848            user_agent = user_agent,
849            timestamp = %chrono::Utc::now().to_rfc3339(),
850            "Authentication event"
851        );
852    }
853
854    /// Clean up old audit events
855    pub async fn cleanup_old_events(&self, retention_days: u32) -> Result<u64> {
856        let cutoff_time =
857            SystemTime::now() - std::time::Duration::from_secs(retention_days as u64 * 86400);
858        self.storage.delete_old_events(cutoff_time).await
859    }
860}
861
862/// Security audit statistics aggregated from audit logs.
863///
864/// Provides comprehensive security metrics for monitoring and incident response.
865#[derive(Debug, Clone, Serialize, Deserialize)]
866pub struct SecurityAuditStats {
867    pub active_sessions: u64,
868    pub failed_logins_24h: u64,
869    pub successful_logins_24h: u64,
870    pub unique_users_24h: u64,
871    pub token_issued_24h: u64,
872    pub password_resets_24h: u64,
873    pub admin_actions_24h: u64,
874    pub security_alerts_24h: u64,
875    pub collection_timestamp: chrono::DateTime<chrono::Utc>,
876}
877
878impl SecurityAuditStats {
879    /// Calculate security score based on current metrics.
880    /// Returns a value between 0.0 (critical) and 1.0 (excellent).
881    pub fn security_score(&self) -> f64 {
882        let mut score = 1.0_f64;
883
884        if self.successful_logins_24h > 0 {
885            let failure_rate = self.failed_logins_24h as f64
886                / (self.successful_logins_24h + self.failed_logins_24h) as f64;
887            if failure_rate > 0.1 {
888                score -= failure_rate * 0.3;
889            }
890        }
891
892        if self.security_alerts_24h > 0 {
893            score -= (self.security_alerts_24h as f64 * 0.1).min(0.4);
894        }
895
896        if self.successful_logins_24h > 0 && self.failed_logins_24h < 10 {
897            score += 0.05;
898        }
899
900        score.clamp(0.0, 1.0)
901    }
902
903    /// Returns `true` if security metrics require immediate administrative attention.
904    ///
905    /// Criteria: > 100 failed logins, > 5 security alerts, or security score < 0.3.
906    ///
907    /// ```rust,no_run
908    /// use auth_framework::audit::SecurityAuditStats;
909    ///
910    /// # fn alert_security_team(_: &SecurityAuditStats) {}
911    /// # let security_stats: SecurityAuditStats = unimplemented!();
912    /// if security_stats.requires_immediate_attention() {
913    ///     alert_security_team(&security_stats);
914    /// }
915    /// ```
916    pub fn requires_immediate_attention(&self) -> bool {
917        self.failed_logins_24h > 100 || self.security_alerts_24h > 5 || self.security_score() < 0.3
918    }
919
920    /// Generates a human-readable alert message when immediate attention is required.
921    ///
922    /// Returns `None` if no immediate security concerns are detected.
923    ///
924    /// ```rust,no_run
925    /// use auth_framework::audit::SecurityAuditStats;
926    ///
927    /// # fn notify_administrators(_: &str) {}
928    /// # let security_stats: SecurityAuditStats = unimplemented!();
929    /// if let Some(alert) = security_stats.security_alert_message() {
930    ///     log::error!("Security Alert: {}", alert);
931    ///     notify_administrators(&alert);
932    /// }
933    /// ```
934    pub fn security_alert_message(&self) -> Option<String> {
935        if !self.requires_immediate_attention() {
936            return None;
937        }
938
939        let mut alerts = Vec::new();
940
941        if self.failed_logins_24h > 100 {
942            alerts.push(format!(
943                "High failed login attempts: {}",
944                self.failed_logins_24h
945            ));
946        }
947        if self.security_alerts_24h > 5 {
948            alerts.push(format!(
949                "Multiple security alerts: {}",
950                self.security_alerts_24h
951            ));
952        }
953        if self.security_score() < 0.3 {
954            alerts.push(format!(
955                "Critical security score: {:.2}",
956                self.security_score()
957            ));
958        }
959
960        Some(format!(
961            "🚨 SECURITY ATTENTION REQUIRED: {}",
962            alerts.join(", ")
963        ))
964    }
965}
966
967/// Correlation ID generator for tracking related events
968pub struct CorrelationIdGenerator {
969    counter: std::sync::atomic::AtomicU64,
970}
971
972impl CorrelationIdGenerator {
973    pub fn new() -> Self {
974        Self {
975            counter: std::sync::atomic::AtomicU64::new(0),
976        }
977    }
978
979    pub fn generate(&self) -> String {
980        let count = self
981            .counter
982            .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
983        format!(
984            "corr_{:016x}_{}",
985            SystemTime::now()
986                .duration_since(SystemTime::UNIX_EPOCH)
987                .unwrap_or_default()
988                .as_secs(),
989            count
990        )
991    }
992}
993
994// ── AuditEvent builder ────────────────────────────────────────────────
995
996/// A fluent builder for [`AuditEvent`].
997///
998/// Only `event_type` and `description` are required; every other field
999/// receives a sensible default (auto-generated `id`, `SystemTime::now()`
1000/// timestamp, `RiskLevel::Low`, `EventOutcome::Unknown`, etc.).
1001///
1002/// # Example
1003///
1004/// ```rust
1005/// use auth_framework::audit::*;
1006///
1007/// let event = AuditEvent::builder(AuditEventType::LoginSuccess, "User logged in")
1008///     .user_id("user_123")
1009///     .session_id("sess_abc")
1010///     .outcome(EventOutcome::Success)
1011///     .with_actor("user", "user_123")
1012///     .build();
1013///
1014/// assert_eq!(event.event_type, AuditEventType::LoginSuccess);
1015/// assert_eq!(event.user_id, Some("user_123".to_string()));
1016/// ```
1017pub struct AuditEventBuilder {
1018    event: AuditEvent,
1019}
1020
1021impl AuditEvent {
1022    /// Create a builder pre-populated with `event_type` and `description`.
1023    pub fn builder(
1024        event_type: AuditEventType,
1025        description: impl Into<String>,
1026    ) -> AuditEventBuilder {
1027        AuditEventBuilder::new(event_type, description)
1028    }
1029}
1030
1031impl AuditEventBuilder {
1032    /// Create a new builder with required fields.
1033    pub fn new(event_type: AuditEventType, description: impl Into<String>) -> Self {
1034        Self {
1035            event: AuditEvent {
1036                id: String::new(),
1037                event_type,
1038                timestamp: SystemTime::UNIX_EPOCH,
1039                user_id: None,
1040                session_id: None,
1041                outcome: EventOutcome::Unknown,
1042                risk_level: RiskLevel::Low,
1043                description: description.into(),
1044                details: HashMap::new(),
1045                request_metadata: RequestMetadata::new(),
1046                resource: None,
1047                actor: ActorInfo {
1048                    actor_type: "unknown".to_string(),
1049                    actor_id: String::new(),
1050                    actor_name: None,
1051                    roles: Vec::new(),
1052                },
1053                correlation_id: None,
1054            },
1055        }
1056    }
1057
1058    /// Set the user ID.
1059    pub fn user_id(mut self, id: impl Into<String>) -> Self {
1060        self.event.user_id = Some(id.into());
1061        self
1062    }
1063
1064    /// Set the session ID.
1065    pub fn session_id(mut self, id: impl Into<String>) -> Self {
1066        self.event.session_id = Some(id.into());
1067        self
1068    }
1069
1070    /// Set the event outcome.
1071    pub fn outcome(mut self, outcome: EventOutcome) -> Self {
1072        self.event.outcome = outcome;
1073        self
1074    }
1075
1076    /// Set the risk level.
1077    pub fn risk_level(mut self, level: RiskLevel) -> Self {
1078        self.event.risk_level = level;
1079        self
1080    }
1081
1082    /// Set actor information.
1083    pub fn with_actor(
1084        mut self,
1085        actor_type: impl Into<String>,
1086        actor_id: impl Into<String>,
1087    ) -> Self {
1088        self.event.actor = ActorInfo {
1089            actor_type: actor_type.into(),
1090            actor_id: actor_id.into(),
1091            actor_name: None,
1092            roles: Vec::new(),
1093        };
1094        self
1095    }
1096
1097    /// Set full actor information.
1098    pub fn actor(mut self, actor: ActorInfo) -> Self {
1099        self.event.actor = actor;
1100        self
1101    }
1102
1103    /// Set request metadata.
1104    pub fn request_metadata(mut self, metadata: RequestMetadata) -> Self {
1105        self.event.request_metadata = metadata;
1106        self
1107    }
1108
1109    /// Set the affected resource.
1110    pub fn resource(mut self, resource: ResourceInfo) -> Self {
1111        self.event.resource = Some(resource);
1112        self
1113    }
1114
1115    /// Set the correlation ID.
1116    pub fn correlation_id(mut self, id: impl Into<String>) -> Self {
1117        self.event.correlation_id = Some(id.into());
1118        self
1119    }
1120
1121    /// Insert a key-value pair into the event details.
1122    pub fn detail(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
1123        self.event.details.insert(key.into(), value.into());
1124        self
1125    }
1126
1127    /// Set the full details map.
1128    pub fn details(mut self, details: HashMap<String, String>) -> Self {
1129        self.event.details = details;
1130        self
1131    }
1132
1133    /// Consume the builder and produce the [`AuditEvent`].
1134    ///
1135    /// Auto-generates a UUID `id` if one was not set, and sets the
1136    /// timestamp to `SystemTime::now()` if it was left at the default.
1137    pub fn build(mut self) -> AuditEvent {
1138        if self.event.id.is_empty() {
1139            self.event.id = uuid::Uuid::new_v4().to_string();
1140        }
1141        if self.event.timestamp == SystemTime::UNIX_EPOCH {
1142            self.event.timestamp = SystemTime::now();
1143        }
1144        self.event
1145    }
1146}
1147
1148// ── AuditQuery builder ───────────────────────────────────────────────
1149
1150impl Default for AuditQuery {
1151    fn default() -> Self {
1152        Self {
1153            event_types: None,
1154            user_id: None,
1155            risk_level: None,
1156            outcome: None,
1157            time_range: None,
1158            ip_address: None,
1159            resource_type: None,
1160            actor_id: None,
1161            correlation_id: None,
1162            limit: None,
1163            offset: None,
1164            sort_order: SortOrder::TimestampDesc,
1165        }
1166    }
1167}
1168
1169/// A fluent builder for [`AuditQuery`].
1170///
1171/// Starts from the [`Default`] query (no filters, descending timestamp).
1172///
1173/// # Example
1174///
1175/// ```rust
1176/// use auth_framework::audit::*;
1177/// use std::time::{Duration, SystemTime};
1178///
1179/// let query = AuditQuery::builder()
1180///     .event_types(vec![AuditEventType::LoginFailure])
1181///     .limit(50)
1182///     .build();
1183///
1184/// assert_eq!(query.limit, Some(50));
1185/// ```
1186pub struct AuditQueryBuilder {
1187    query: AuditQuery,
1188}
1189
1190impl AuditQuery {
1191    /// Create a new builder for constructing queries.
1192    pub fn builder() -> AuditQueryBuilder {
1193        AuditQueryBuilder {
1194            query: AuditQuery::default(),
1195        }
1196    }
1197}
1198
1199impl AuditQueryBuilder {
1200    /// Filter by event types.
1201    pub fn event_types(mut self, types: Vec<AuditEventType>) -> Self {
1202        self.query.event_types = Some(types);
1203        self
1204    }
1205
1206    /// Filter by user ID.
1207    pub fn user_id(mut self, id: impl Into<String>) -> Self {
1208        self.query.user_id = Some(id.into());
1209        self
1210    }
1211
1212    /// Filter by minimum risk level.
1213    pub fn risk_level(mut self, level: RiskLevel) -> Self {
1214        self.query.risk_level = Some(level);
1215        self
1216    }
1217
1218    /// Filter by outcome.
1219    pub fn outcome(mut self, outcome: EventOutcome) -> Self {
1220        self.query.outcome = Some(outcome);
1221        self
1222    }
1223
1224    /// Filter by time range.
1225    pub fn time_range(mut self, start: SystemTime, end: SystemTime) -> Self {
1226        self.query.time_range = Some(TimeRange { start, end });
1227        self
1228    }
1229
1230    /// Convenience: filter to the last N seconds.
1231    pub fn last_seconds(mut self, seconds: u64) -> Self {
1232        self.query.time_range = Some(TimeRange {
1233            start: SystemTime::now() - std::time::Duration::from_secs(seconds),
1234            end: SystemTime::now(),
1235        });
1236        self
1237    }
1238
1239    /// Convenience: filter to the last 24 hours.
1240    pub fn last_24h(self) -> Self {
1241        self.last_seconds(24 * 60 * 60)
1242    }
1243
1244    /// Filter by IP address.
1245    pub fn ip_address(mut self, ip: impl Into<String>) -> Self {
1246        self.query.ip_address = Some(ip.into());
1247        self
1248    }
1249
1250    /// Filter by resource type.
1251    pub fn resource_type(mut self, rt: impl Into<String>) -> Self {
1252        self.query.resource_type = Some(rt.into());
1253        self
1254    }
1255
1256    /// Filter by actor ID.
1257    pub fn actor_id(mut self, id: impl Into<String>) -> Self {
1258        self.query.actor_id = Some(id.into());
1259        self
1260    }
1261
1262    /// Filter by correlation ID.
1263    pub fn correlation_id(mut self, id: impl Into<String>) -> Self {
1264        self.query.correlation_id = Some(id.into());
1265        self
1266    }
1267
1268    /// Limit the number of results.
1269    pub fn limit(mut self, limit: u64) -> Self {
1270        self.query.limit = Some(limit);
1271        self
1272    }
1273
1274    /// Set pagination offset.
1275    pub fn offset(mut self, offset: u64) -> Self {
1276        self.query.offset = Some(offset);
1277        self
1278    }
1279
1280    /// Set the sort order.
1281    pub fn sort_order(mut self, order: SortOrder) -> Self {
1282        self.query.sort_order = order;
1283        self
1284    }
1285
1286    /// Consume the builder and produce the [`AuditQuery`].
1287    pub fn build(self) -> AuditQuery {
1288        self.query
1289    }
1290}
1291
1292/// Helper for creating request metadata
1293impl RequestMetadata {
1294    pub fn new() -> Self {
1295        Self {
1296            ip_address: None,
1297            user_agent: None,
1298            request_id: None,
1299            endpoint: None,
1300            http_method: None,
1301            geolocation: None,
1302            device_info: None,
1303        }
1304    }
1305
1306    pub fn with_ip(mut self, ip: impl Into<String>) -> Self {
1307        self.ip_address = Some(ip.into());
1308        self
1309    }
1310
1311    pub fn with_user_agent(mut self, user_agent: impl Into<String>) -> Self {
1312        self.user_agent = Some(user_agent.into());
1313        self
1314    }
1315
1316    pub fn with_endpoint(mut self, endpoint: impl Into<String>) -> Self {
1317        self.endpoint = Some(endpoint.into());
1318        self
1319    }
1320}
1321
1322impl Default for RequestMetadata {
1323    fn default() -> Self {
1324        Self::new()
1325    }
1326}
1327
1328#[cfg(test)]
1329mod tests {
1330    use super::*;
1331
1332    #[test]
1333    fn test_correlation_id_generation() {
1334        let generator = CorrelationIdGenerator::new();
1335        let id1 = generator.generate();
1336        let id2 = generator.generate();
1337
1338        assert_ne!(id1, id2);
1339        assert!(id1.starts_with("corr_"));
1340        assert!(id2.starts_with("corr_"));
1341    }
1342
1343    #[test]
1344    fn test_request_metadata_builder() {
1345        let metadata = RequestMetadata::new()
1346            .with_ip("192.168.1.1")
1347            .with_user_agent("Mozilla/5.0")
1348            .with_endpoint("/api/auth/login");
1349
1350        assert_eq!(metadata.ip_address, Some("192.168.1.1".to_string()));
1351        assert_eq!(metadata.user_agent, Some("Mozilla/5.0".to_string()));
1352        assert_eq!(metadata.endpoint, Some("/api/auth/login".to_string()));
1353    }
1354
1355    #[test]
1356    fn test_audit_event_builder_minimal() {
1357        let event = AuditEvent::builder(AuditEventType::LoginSuccess, "User logged in").build();
1358        assert_eq!(event.event_type, AuditEventType::LoginSuccess);
1359        assert_eq!(event.description, "User logged in");
1360        assert!(!event.id.is_empty(), "id should be auto-generated");
1361        assert_ne!(
1362            event.timestamp,
1363            SystemTime::UNIX_EPOCH,
1364            "timestamp should be auto-set"
1365        );
1366        assert_eq!(event.outcome, EventOutcome::Unknown);
1367        assert_eq!(event.risk_level, RiskLevel::Low);
1368    }
1369
1370    #[test]
1371    fn test_audit_event_builder_full() {
1372        let event = AuditEvent::builder(AuditEventType::PermissionDenied, "Access denied")
1373            .user_id("u123")
1374            .session_id("s456")
1375            .outcome(EventOutcome::Failure)
1376            .risk_level(RiskLevel::High)
1377            .with_actor("user", "u123")
1378            .detail("resource", "admin_panel")
1379            .correlation_id("corr_xyz")
1380            .build();
1381
1382        assert_eq!(event.user_id, Some("u123".to_string()));
1383        assert_eq!(event.session_id, Some("s456".to_string()));
1384        assert_eq!(event.outcome, EventOutcome::Failure);
1385        assert_eq!(event.risk_level, RiskLevel::High);
1386        assert_eq!(event.actor.actor_type, "user");
1387        assert_eq!(event.actor.actor_id, "u123");
1388        assert_eq!(
1389            event.details.get("resource"),
1390            Some(&"admin_panel".to_string())
1391        );
1392        assert_eq!(event.correlation_id, Some("corr_xyz".to_string()));
1393    }
1394
1395    #[test]
1396    fn test_audit_query_builder() {
1397        let query = AuditQuery::builder()
1398            .event_types(vec![AuditEventType::LoginFailure])
1399            .limit(50)
1400            .offset(10)
1401            .build();
1402
1403        assert_eq!(query.event_types, Some(vec![AuditEventType::LoginFailure]));
1404        assert_eq!(query.limit, Some(50));
1405        assert_eq!(query.offset, Some(10));
1406        assert!(query.user_id.is_none());
1407    }
1408
1409    #[test]
1410    fn test_audit_query_default() {
1411        let query = AuditQuery::default();
1412        assert!(query.event_types.is_none());
1413        assert!(query.user_id.is_none());
1414        assert!(query.limit.is_none());
1415        assert!(matches!(query.sort_order, SortOrder::TimestampDesc));
1416    }
1417
1418    #[test]
1419    fn test_audit_query_last_24h() {
1420        let query = AuditQuery::builder().last_24h().build();
1421        assert!(query.time_range.is_some());
1422        let range = query.time_range.unwrap();
1423        let elapsed = range.end.duration_since(range.start).unwrap();
1424        // Should be approximately 24 hours (allow small timing variance)
1425        assert!(elapsed.as_secs() >= 86399 && elapsed.as_secs() <= 86401);
1426    }
1427
1428    #[test]
1429    fn test_audit_query_last_seconds() {
1430        let query = AuditQuery::builder().last_seconds(3600).build();
1431        assert!(query.time_range.is_some());
1432        let range = query.time_range.unwrap();
1433        let elapsed = range.end.duration_since(range.start).unwrap();
1434        assert!(elapsed.as_secs() >= 3599 && elapsed.as_secs() <= 3601);
1435    }
1436
1437    #[test]
1438    fn test_audit_event_type_display() {
1439        assert_eq!(AuditEventType::LoginSuccess.to_string(), "login_success");
1440        assert_eq!(AuditEventType::LoginFailure.to_string(), "login_failure");
1441        assert_eq!(AuditEventType::Logout.to_string(), "logout");
1442        assert_eq!(AuditEventType::TokenRefresh.to_string(), "token_refresh");
1443        assert_eq!(
1444            AuditEventType::MfaVerificationSuccess.to_string(),
1445            "mfa_verification_success"
1446        );
1447        assert_eq!(
1448            AuditEventType::PermissionGranted.to_string(),
1449            "permission_granted"
1450        );
1451        assert_eq!(
1452            AuditEventType::PermissionDenied.to_string(),
1453            "permission_denied"
1454        );
1455        assert_eq!(AuditEventType::RoleAssigned.to_string(), "role_assigned");
1456        assert_eq!(AuditEventType::UserCreated.to_string(), "user_created");
1457        assert_eq!(AuditEventType::AccountLocked.to_string(), "account_locked");
1458        assert_eq!(
1459            AuditEventType::BruteForceDetected.to_string(),
1460            "brute_force_detected"
1461        );
1462        assert_eq!(AuditEventType::AdminAction.to_string(), "admin_action");
1463        assert_eq!(AuditEventType::SystemStartup.to_string(), "system_startup");
1464        assert_eq!(AuditEventType::DataExported.to_string(), "data_exported");
1465    }
1466
1467    #[test]
1468    fn test_risk_level_display() {
1469        assert_eq!(RiskLevel::Low.to_string(), "low");
1470        assert_eq!(RiskLevel::Medium.to_string(), "medium");
1471        assert_eq!(RiskLevel::High.to_string(), "high");
1472        assert_eq!(RiskLevel::Critical.to_string(), "critical");
1473    }
1474
1475    #[test]
1476    fn test_event_outcome_display() {
1477        assert_eq!(EventOutcome::Success.to_string(), "success");
1478        assert_eq!(EventOutcome::Failure.to_string(), "failure");
1479        assert_eq!(EventOutcome::Partial.to_string(), "partial");
1480        assert_eq!(EventOutcome::Unknown.to_string(), "unknown");
1481    }
1482}