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