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