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