Skip to main content

auth_framework/
audit.rs

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