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