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