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 serde::{Deserialize, Serialize};
13use std::collections::HashMap;
14use std::time::SystemTime;
15
16/// Audit event types
17#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
18pub enum AuditEventType {
19    // Authentication events
20    LoginSuccess,
21    LoginFailure,
22    Logout,
23    TokenRefresh,
24    TokenExpired,
25    TokenRevoked,
26
27    // MFA events
28    MfaSetup,
29    MfaChallengeCreated,
30    MfaVerificationSuccess,
31    MfaVerificationFailure,
32    MfaMethodEnabled,
33    MfaMethodDisabled,
34
35    // Authorization events
36    PermissionGranted,
37    PermissionDenied,
38    RoleAssigned,
39    RoleRevoked,
40    RoleCreated,
41    RoleUpdated,
42    RoleDeleted,
43
44    // User management events
45    UserCreated,
46    UserUpdated,
47    UserDeleted,
48    UserActivated,
49    UserDeactivated,
50    UserPasswordChanged,
51    UserPasswordReset,
52
53    // Security events
54    AccountLocked,
55    AccountUnlocked,
56    SuspiciousActivity,
57    BruteForceDetected,
58    RateLimitExceeded,
59    SecurityPolicyViolation,
60    SecurityViolation,
61
62    // Administrative events
63    AdminAction,
64    ConfigurationChanged,
65    SystemStartup,
66    SystemShutdown,
67    BackupCreated,
68    DataExported,
69    DataImported,
70}
71
72/// Security risk level
73#[derive(Debug, Clone, PartialEq, PartialOrd, Ord, Eq, Serialize, Deserialize)]
74pub enum RiskLevel {
75    Low,
76    Medium,
77    High,
78    Critical,
79}
80
81/// Audit event outcome
82#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
83pub enum EventOutcome {
84    Success,
85    Failure,
86    Partial,
87    Unknown,
88}
89
90/// Comprehensive audit event
91#[derive(Clone, Serialize, Deserialize)]
92pub struct AuditEvent {
93    /// Unique event ID
94    pub id: String,
95    /// Type of event
96    pub event_type: AuditEventType,
97    /// When the event occurred
98    pub timestamp: SystemTime,
99    /// User who initiated the event (if applicable)
100    pub user_id: Option<String>,
101    /// Session ID (if applicable)
102    pub session_id: Option<String>,
103    /// Event outcome
104    pub outcome: EventOutcome,
105    /// Risk level assessment
106    pub risk_level: RiskLevel,
107    /// Human-readable event description
108    pub description: String,
109    /// Additional event details
110    pub details: HashMap<String, String>,
111    /// Request metadata
112    pub request_metadata: RequestMetadata,
113    /// Resource affected (if applicable)
114    pub resource: Option<ResourceInfo>,
115    /// Actor information
116    pub actor: ActorInfo,
117    /// Correlation ID for tracking related events
118    pub correlation_id: Option<String>,
119}
120
121impl std::fmt::Debug for AuditEvent {
122    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
123        let mut d = f.debug_struct("AuditEvent");
124        d.field("id", &self.id);
125        d.field("event_type", &self.event_type);
126        d.field("timestamp", &self.timestamp);
127        d.field("user_id", &self.user_id);
128        d.field(
129            "session_id",
130            &crate::utils::redact::redacted(&self.session_id),
131        );
132        d.field("outcome", &self.outcome);
133        d.field("risk_level", &self.risk_level);
134        d.field("description", &self.description);
135        d.field("details", &self.details);
136        d.field("request_metadata", &self.request_metadata);
137        d.field("resource", &self.resource);
138        d.field("actor", &self.actor);
139        d.field("correlation_id", &self.correlation_id);
140        d.finish()
141    }
142}
143
144/// Request metadata for audit context
145#[derive(Debug, Clone, Serialize, Deserialize)]
146pub struct RequestMetadata {
147    /// Source IP address
148    pub ip_address: Option<String>,
149    /// User agent string
150    pub user_agent: Option<String>,
151    /// Request ID
152    pub request_id: Option<String>,
153    /// API endpoint or action
154    pub endpoint: Option<String>,
155    /// HTTP method (if applicable)
156    pub http_method: Option<String>,
157    /// Geographic location (if available)
158    pub geolocation: Option<GeolocationInfo>,
159    /// Device information
160    pub device_info: Option<DeviceInfo>,
161}
162
163/// Geographic location information
164#[derive(Debug, Clone, Serialize, Deserialize)]
165pub struct GeolocationInfo {
166    pub country: Option<String>,
167    pub region: Option<String>,
168    pub city: Option<String>,
169    pub latitude: Option<f64>,
170    pub longitude: Option<f64>,
171}
172
173/// Device information
174#[derive(Debug, Clone, Serialize, Deserialize)]
175pub struct DeviceInfo {
176    pub device_type: Option<String>,
177    pub operating_system: Option<String>,
178    pub browser: Option<String>,
179    pub is_mobile: bool,
180    pub screen_resolution: Option<String>,
181}
182
183/// Resource information
184#[derive(Debug, Clone, Serialize, Deserialize)]
185pub struct ResourceInfo {
186    /// Resource type (user, document, api, etc.)
187    pub resource_type: String,
188    /// Resource ID
189    pub resource_id: String,
190    /// Resource name or title
191    pub resource_name: Option<String>,
192    /// Additional resource attributes
193    pub attributes: HashMap<String, String>,
194}
195
196/// Actor information (who performed the action)
197#[derive(Debug, Clone, Serialize, Deserialize)]
198pub struct ActorInfo {
199    /// Actor type (user, system, api_client, etc.)
200    pub actor_type: String,
201    /// Actor ID
202    pub actor_id: String,
203    /// Actor name or identifier
204    pub actor_name: Option<String>,
205    /// Roles or permissions of the actor
206    pub roles: Vec<String>,
207}
208
209/// Audit log storage trait
210#[async_trait]
211pub trait AuditStorage: Send + Sync {
212    /// Store an audit event
213    async fn store_event(&self, event: &AuditEvent) -> Result<()>;
214
215    /// Query audit events with filters
216    async fn query_events(&self, query: &AuditQuery) -> Result<Vec<AuditEvent>>;
217
218    /// Get event by ID
219    async fn get_event(&self, event_id: &str) -> Result<Option<AuditEvent>>;
220
221    /// Count events matching criteria
222    async fn count_events(&self, query: &AuditQuery) -> Result<u64>;
223
224    /// Delete old events (for retention management)
225    async fn delete_old_events(&self, before: SystemTime) -> Result<u64>;
226
227    /// Get audit statistics
228    async fn get_statistics(&self, query: &StatsQuery) -> Result<AuditStatistics>;
229}
230
231/// Query parameters for audit events
232#[derive(Debug, Clone)]
233pub struct AuditQuery {
234    /// Filter by event types
235    pub event_types: Option<Vec<AuditEventType>>,
236    /// Filter by user ID
237    pub user_id: Option<String>,
238    /// Filter by risk level
239    pub risk_level: Option<RiskLevel>,
240    /// Filter by outcome
241    pub outcome: Option<EventOutcome>,
242    /// Time range filter
243    pub time_range: Option<TimeRange>,
244    /// IP address filter
245    pub ip_address: Option<String>,
246    /// Resource filter
247    pub resource_type: Option<String>,
248    /// Actor filter
249    pub actor_id: Option<String>,
250    /// Correlation ID filter
251    pub correlation_id: Option<String>,
252    /// Limit number of results
253    pub limit: Option<u64>,
254    /// Offset for pagination
255    pub offset: Option<u64>,
256    /// Sort order
257    pub sort_order: SortOrder,
258}
259
260/// Time range for queries
261#[derive(Debug, Clone)]
262pub struct TimeRange {
263    pub start: SystemTime,
264    pub end: SystemTime,
265}
266
267/// Sort order for queries
268#[derive(Debug, Clone)]
269pub enum SortOrder {
270    TimestampAsc,
271    TimestampDesc,
272    RiskLevelDesc,
273}
274
275/// Statistics query parameters
276#[derive(Debug, Clone)]
277pub struct StatsQuery {
278    pub time_range: TimeRange,
279    pub group_by: Vec<StatsGroupBy>,
280}
281
282/// Grouping options for statistics
283#[derive(Debug, Clone)]
284pub enum StatsGroupBy {
285    EventType,
286    RiskLevel,
287    Outcome,
288    Hour,
289    Day,
290    Week,
291    UserId,
292    IpAddress,
293}
294
295/// Audit statistics result
296#[derive(Debug, Clone, Serialize, Deserialize)]
297pub struct AuditStatistics {
298    pub total_events: u64,
299    pub event_type_counts: HashMap<String, u64>,
300    pub risk_level_counts: HashMap<String, u64>,
301    pub outcome_counts: HashMap<String, u64>,
302    pub time_series: Vec<TimeSeriesPoint>,
303    pub top_users: Vec<UserEventCount>,
304    pub top_ips: Vec<IpEventCount>,
305}
306
307/// Time series data point
308#[derive(Debug, Clone, Serialize, Deserialize)]
309pub struct TimeSeriesPoint {
310    pub timestamp: SystemTime,
311    pub count: u64,
312}
313
314/// User event count
315#[derive(Debug, Clone, Serialize, Deserialize)]
316pub struct UserEventCount {
317    pub user_id: String,
318    pub event_count: u64,
319}
320
321/// IP address event count
322#[derive(Debug, Clone, Serialize, Deserialize)]
323pub struct IpEventCount {
324    pub ip_address: String,
325    pub event_count: u64,
326}
327
328/// Main audit logger
329pub struct AuditLogger<S: AuditStorage> {
330    storage: S,
331    correlation_generator: CorrelationIdGenerator,
332}
333
334impl<S: AuditStorage> AuditLogger<S> {
335    /// Create a new audit logger
336    pub fn new(storage: S) -> Self {
337        Self {
338            storage,
339            correlation_generator: CorrelationIdGenerator::new(),
340        }
341    }
342
343    /// Log an audit event
344    pub async fn log_event(&self, mut event: AuditEvent) -> Result<()> {
345        // Generate ID if not provided
346        if event.id.is_empty() {
347            event.id = uuid::Uuid::new_v4().to_string();
348        }
349
350        // Set timestamp if not provided
351        if event.timestamp == SystemTime::UNIX_EPOCH {
352            event.timestamp = SystemTime::now();
353        }
354
355        // Store the event
356        self.storage.store_event(&event).await?;
357
358        // Check for security alerts
359        self.check_security_alerts(&event).await?;
360
361        Ok(())
362    }
363
364    /// Log authentication success
365    pub async fn log_login_success(
366        &self,
367        user_id: &str,
368        session_id: &str,
369        metadata: RequestMetadata,
370    ) -> Result<()> {
371        let event = AuditEvent {
372            id: String::new(),
373            event_type: AuditEventType::LoginSuccess,
374            timestamp: SystemTime::UNIX_EPOCH,
375            user_id: Some(user_id.to_string()),
376            session_id: Some(session_id.to_string()),
377            outcome: EventOutcome::Success,
378            risk_level: RiskLevel::Low,
379            description: "User successfully authenticated".to_string(),
380            details: HashMap::new(),
381            request_metadata: metadata,
382            resource: None,
383            actor: ActorInfo {
384                actor_type: "user".to_string(),
385                actor_id: user_id.to_string(),
386                actor_name: None,
387                roles: vec![],
388            },
389            correlation_id: Some(self.correlation_generator.generate()),
390        };
391
392        self.log_event(event).await
393    }
394
395    /// Log authentication failure
396    pub async fn log_login_failure(
397        &self,
398        attempted_user: &str,
399        reason: &str,
400        metadata: RequestMetadata,
401    ) -> Result<()> {
402        let mut details = HashMap::new();
403        details.insert("failure_reason".to_string(), reason.to_string());
404        details.insert("attempted_user".to_string(), attempted_user.to_string());
405
406        let event = AuditEvent {
407            id: String::new(),
408            event_type: AuditEventType::LoginFailure,
409            timestamp: SystemTime::UNIX_EPOCH,
410            user_id: None,
411            session_id: None,
412            outcome: EventOutcome::Failure,
413            risk_level: RiskLevel::Medium,
414            description: format!("Authentication failed for user: {}", attempted_user),
415            details,
416            request_metadata: metadata,
417            resource: None,
418            actor: ActorInfo {
419                actor_type: "user".to_string(),
420                actor_id: attempted_user.to_string(),
421                actor_name: None,
422                roles: vec![],
423            },
424            correlation_id: Some(self.correlation_generator.generate()),
425        };
426
427        self.log_event(event).await
428    }
429
430    /// Log permission denied event
431    pub async fn log_permission_denied(
432        &self,
433        user_id: &str,
434        resource: ResourceInfo,
435        permission: &str,
436        metadata: RequestMetadata,
437    ) -> Result<()> {
438        let mut details = HashMap::new();
439        details.insert("requested_permission".to_string(), permission.to_string());
440
441        let event = AuditEvent {
442            id: String::new(),
443            event_type: AuditEventType::PermissionDenied,
444            timestamp: SystemTime::UNIX_EPOCH,
445            user_id: Some(user_id.to_string()),
446            session_id: None,
447            outcome: EventOutcome::Failure,
448            risk_level: RiskLevel::Medium,
449            description: format!(
450                "Permission denied: {} on {}",
451                permission, resource.resource_type
452            ),
453            details,
454            request_metadata: metadata,
455            resource: Some(resource),
456            actor: ActorInfo {
457                actor_type: "user".to_string(),
458                actor_id: user_id.to_string(),
459                actor_name: None,
460                roles: vec![],
461            },
462            correlation_id: Some(self.correlation_generator.generate()),
463        };
464
465        self.log_event(event).await
466    }
467
468    /// Log suspicious activity
469    pub async fn log_suspicious_activity(
470        &self,
471        user_id: Option<&str>,
472        activity_type: &str,
473        description: &str,
474        metadata: RequestMetadata,
475    ) -> Result<()> {
476        let mut details = HashMap::new();
477        details.insert("activity_type".to_string(), activity_type.to_string());
478
479        let event = AuditEvent {
480            id: String::new(),
481            event_type: AuditEventType::SuspiciousActivity,
482            timestamp: SystemTime::UNIX_EPOCH,
483            user_id: user_id.map(|s| s.to_string()),
484            session_id: None,
485            outcome: EventOutcome::Unknown,
486            risk_level: RiskLevel::High,
487            description: description.to_string(),
488            details,
489            request_metadata: metadata,
490            resource: None,
491            actor: ActorInfo {
492                actor_type: user_id.map(|_| "user").unwrap_or("system").to_string(),
493                actor_id: user_id.unwrap_or("system").to_string(),
494                actor_name: None,
495                roles: vec![],
496            },
497            correlation_id: Some(self.correlation_generator.generate()),
498        };
499
500        self.log_event(event).await
501    }
502
503    /// Check for security alerts based on event patterns
504    async fn check_security_alerts(&self, event: &AuditEvent) -> Result<()> {
505        match event.event_type {
506            AuditEventType::LoginFailure => {
507                self.check_brute_force_pattern(event).await?;
508            }
509            AuditEventType::SuspiciousActivity => {
510                // Could trigger immediate alerts
511                self.trigger_security_alert(event).await?;
512            }
513            _ => {}
514        }
515        Ok(())
516    }
517
518    /// Check for brute force attack patterns
519    async fn check_brute_force_pattern(&self, event: &AuditEvent) -> Result<()> {
520        let query = AuditQuery {
521            event_types: Some(vec![AuditEventType::LoginFailure]),
522            ip_address: event.request_metadata.ip_address.clone(),
523            time_range: Some(TimeRange {
524                start: SystemTime::now() - std::time::Duration::from_secs(300), // Last 5 minutes
525                end: SystemTime::now(),
526            }),
527            limit: Some(10),
528            offset: None,
529            user_id: None,
530            risk_level: None,
531            outcome: None,
532            resource_type: None,
533            actor_id: None,
534            correlation_id: None,
535            sort_order: SortOrder::TimestampDesc,
536        };
537
538        let recent_failures = self.storage.query_events(&query).await?;
539
540        if recent_failures.len() >= 5 {
541            // Log brute force detection
542            let mut details = HashMap::new();
543            details.insert(
544                "failure_count".to_string(),
545                recent_failures.len().to_string(),
546            );
547            details.insert("time_window".to_string(), "300".to_string());
548
549            let brute_force_event = AuditEvent {
550                id: String::new(),
551                event_type: AuditEventType::BruteForceDetected,
552                timestamp: SystemTime::now(),
553                user_id: None,
554                session_id: None,
555                outcome: EventOutcome::Success,
556                risk_level: RiskLevel::Critical,
557                description: "Brute force attack detected".to_string(),
558                details,
559                request_metadata: event.request_metadata.clone(),
560                resource: None,
561                actor: ActorInfo {
562                    actor_type: "system".to_string(),
563                    actor_id: "security_monitor".to_string(),
564                    actor_name: Some("Security Monitor".to_string()),
565                    roles: vec!["system".to_string()],
566                },
567                correlation_id: Some(self.correlation_generator.generate()),
568            };
569
570            self.storage.store_event(&brute_force_event).await?;
571        }
572
573        Ok(())
574    }
575
576    /// Trigger security alert
577    async fn trigger_security_alert(&self, _event: &AuditEvent) -> Result<()> {
578        // In a real implementation, this would:
579        // - Send notifications to security team
580        // - Update security dashboards
581        // - Trigger automated responses
582        Ok(())
583    }
584
585    /// Query audit events
586    pub async fn query_events(&self, query: &AuditQuery) -> Result<Vec<AuditEvent>> {
587        self.storage.query_events(query).await
588    }
589
590    /// Get audit statistics
591    pub async fn get_statistics(&self, query: &StatsQuery) -> Result<AuditStatistics> {
592        self.storage.get_statistics(query).await
593    }
594
595    /// Get failed login count in the last 24 hours
596    pub async fn get_failed_login_count_24h(&self) -> Result<u64> {
597        let query = AuditQuery {
598            event_types: Some(vec![AuditEventType::LoginFailure]),
599            time_range: Some(TimeRange {
600                start: SystemTime::now() - std::time::Duration::from_secs(24 * 60 * 60),
601                end: SystemTime::now(),
602            }),
603            limit: None,
604            offset: None,
605            user_id: None,
606            risk_level: None,
607            outcome: None,
608            resource_type: None,
609            actor_id: None,
610            correlation_id: None,
611            ip_address: None,
612            sort_order: SortOrder::TimestampDesc,
613        };
614        self.storage.count_events(&query).await
615    }
616
617    /// Get successful login count in the last 24 hours
618    pub async fn get_successful_login_count_24h(&self) -> Result<u64> {
619        let query = AuditQuery {
620            event_types: Some(vec![AuditEventType::LoginSuccess]),
621            time_range: Some(TimeRange {
622                start: SystemTime::now() - std::time::Duration::from_secs(24 * 60 * 60),
623                end: SystemTime::now(),
624            }),
625            limit: None,
626            offset: None,
627            user_id: None,
628            risk_level: None,
629            outcome: None,
630            resource_type: None,
631            actor_id: None,
632            correlation_id: None,
633            ip_address: None,
634            sort_order: SortOrder::TimestampDesc,
635        };
636        self.storage.count_events(&query).await
637    }
638
639    /// Get token issued count in the last 24 hours
640    pub async fn get_token_issued_count_24h(&self) -> Result<u64> {
641        let query = AuditQuery {
642            event_types: Some(vec![
643                AuditEventType::TokenRefresh,
644                AuditEventType::LoginSuccess,
645            ]),
646            time_range: Some(TimeRange {
647                start: SystemTime::now() - std::time::Duration::from_secs(24 * 60 * 60),
648                end: SystemTime::now(),
649            }),
650            limit: None,
651            offset: None,
652            user_id: None,
653            risk_level: None,
654            outcome: None,
655            resource_type: None,
656            actor_id: None,
657            correlation_id: None,
658            ip_address: None,
659            sort_order: SortOrder::TimestampDesc,
660        };
661        self.storage.count_events(&query).await
662    }
663
664    /// Get unique users count in the last 24 hours
665    pub async fn get_unique_users_24h(&self) -> Result<u64> {
666        let query = AuditQuery {
667            event_types: Some(vec![AuditEventType::LoginSuccess]),
668            time_range: Some(TimeRange {
669                start: SystemTime::now() - std::time::Duration::from_secs(24 * 60 * 60),
670                end: SystemTime::now(),
671            }),
672            limit: None,
673            offset: None,
674            user_id: None,
675            risk_level: None,
676            outcome: None,
677            resource_type: None,
678            actor_id: None,
679            correlation_id: None,
680            ip_address: None,
681            sort_order: SortOrder::TimestampDesc,
682        };
683
684        let events = self.storage.query_events(&query).await?;
685        let unique_users: std::collections::HashSet<_> =
686            events.iter().filter_map(|e| e.user_id.as_ref()).collect();
687        Ok(unique_users.len() as u64)
688    }
689
690    /// Get password reset count in the last 24 hours
691    pub async fn get_password_reset_count_24h(&self) -> Result<u64> {
692        let query = AuditQuery {
693            event_types: Some(vec![AuditEventType::UserPasswordReset]),
694            time_range: Some(TimeRange {
695                start: SystemTime::now() - std::time::Duration::from_secs(24 * 60 * 60),
696                end: SystemTime::now(),
697            }),
698            limit: None,
699            offset: None,
700            user_id: None,
701            risk_level: None,
702            outcome: None,
703            resource_type: None,
704            actor_id: None,
705            correlation_id: None,
706            ip_address: None,
707            sort_order: SortOrder::TimestampDesc,
708        };
709        self.storage.count_events(&query).await
710    }
711
712    /// Get admin action count in the last 24 hours
713    pub async fn get_admin_action_count_24h(&self) -> Result<u64> {
714        let query = AuditQuery {
715            event_types: Some(vec![
716                AuditEventType::AdminAction,
717                AuditEventType::UserCreated,
718                AuditEventType::UserUpdated,
719                AuditEventType::UserDeleted,
720                AuditEventType::RoleCreated,
721                AuditEventType::RoleUpdated,
722                AuditEventType::RoleDeleted,
723            ]),
724            time_range: Some(TimeRange {
725                start: SystemTime::now() - std::time::Duration::from_secs(24 * 60 * 60),
726                end: SystemTime::now(),
727            }),
728            limit: None,
729            offset: None,
730            user_id: None,
731            risk_level: None,
732            outcome: None,
733            resource_type: None,
734            actor_id: None,
735            correlation_id: None,
736            ip_address: None,
737            sort_order: SortOrder::TimestampDesc,
738        };
739        self.storage.count_events(&query).await
740    }
741
742    /// Get security alert count in the last 24 hours
743    pub async fn get_security_alert_count_24h(&self) -> Result<u64> {
744        let query = AuditQuery {
745            event_types: Some(vec![
746                AuditEventType::SuspiciousActivity,
747                AuditEventType::BruteForceDetected,
748                AuditEventType::SecurityViolation,
749            ]),
750            time_range: Some(TimeRange {
751                start: SystemTime::now() - std::time::Duration::from_secs(24 * 60 * 60),
752                end: SystemTime::now(),
753            }),
754            limit: None,
755            offset: None,
756            user_id: None,
757            risk_level: Some(RiskLevel::High),
758            outcome: None,
759            resource_type: None,
760            actor_id: None,
761            correlation_id: None,
762            ip_address: None,
763            sort_order: SortOrder::TimestampDesc,
764        };
765        self.storage.count_events(&query).await
766    }
767
768    /// Clean up old audit events
769    pub async fn cleanup_old_events(&self, retention_days: u32) -> Result<u64> {
770        let cutoff_time =
771            SystemTime::now() - std::time::Duration::from_secs(retention_days as u64 * 86400);
772        self.storage.delete_old_events(cutoff_time).await
773    }
774}
775
776/// Correlation ID generator for tracking related events
777pub struct CorrelationIdGenerator {
778    counter: std::sync::atomic::AtomicU64,
779}
780
781impl CorrelationIdGenerator {
782    pub fn new() -> Self {
783        Self {
784            counter: std::sync::atomic::AtomicU64::new(0),
785        }
786    }
787
788    pub fn generate(&self) -> String {
789        let count = self
790            .counter
791            .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
792        format!(
793            "corr_{:016x}_{}",
794            SystemTime::now()
795                .duration_since(SystemTime::UNIX_EPOCH)
796                .unwrap_or_default()
797                .as_secs(),
798            count
799        )
800    }
801}
802
803/// Helper for creating request metadata
804impl RequestMetadata {
805    pub fn new() -> Self {
806        Self {
807            ip_address: None,
808            user_agent: None,
809            request_id: None,
810            endpoint: None,
811            http_method: None,
812            geolocation: None,
813            device_info: None,
814        }
815    }
816
817    pub fn with_ip(mut self, ip: impl Into<String>) -> Self {
818        self.ip_address = Some(ip.into());
819        self
820    }
821
822    pub fn with_user_agent(mut self, user_agent: impl Into<String>) -> Self {
823        self.user_agent = Some(user_agent.into());
824        self
825    }
826
827    pub fn with_endpoint(mut self, endpoint: impl Into<String>) -> Self {
828        self.endpoint = Some(endpoint.into());
829        self
830    }
831}
832
833impl Default for RequestMetadata {
834    fn default() -> Self {
835        Self::new()
836    }
837}
838
839#[cfg(test)]
840mod tests {
841    use super::*;
842
843    #[test]
844    fn test_correlation_id_generation() {
845        let generator = CorrelationIdGenerator::new();
846        let id1 = generator.generate();
847        let id2 = generator.generate();
848
849        assert_ne!(id1, id2);
850        assert!(id1.starts_with("corr_"));
851        assert!(id2.starts_with("corr_"));
852    }
853
854    #[test]
855    fn test_request_metadata_builder() {
856        let metadata = RequestMetadata::new()
857            .with_ip("192.168.1.1")
858            .with_user_agent("Mozilla/5.0")
859            .with_endpoint("/api/auth/login");
860
861        assert_eq!(metadata.ip_address, Some("192.168.1.1".to_string()));
862        assert_eq!(metadata.user_agent, Some("Mozilla/5.0".to_string()));
863        assert_eq!(metadata.endpoint, Some("/api/auth/login".to_string()));
864    }
865}