1impl 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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
19pub enum AuditEventType {
20 LoginSuccess,
22 LoginFailure,
23 Logout,
24 TokenRefresh,
25 TokenExpired,
26 TokenRevoked,
27
28 MfaSetup,
30 MfaChallengeCreated,
31 MfaVerificationSuccess,
32 MfaVerificationFailure,
33 MfaMethodEnabled,
34 MfaMethodDisabled,
35
36 PermissionGranted,
38 PermissionDenied,
39 RoleAssigned,
40 RoleRevoked,
41 RoleCreated,
42 RoleUpdated,
43 RoleDeleted,
44
45 UserCreated,
47 UserUpdated,
48 UserDeleted,
49 UserActivated,
50 UserDeactivated,
51 UserPasswordChanged,
52 UserPasswordReset,
53
54 AccountLocked,
56 AccountUnlocked,
57 SuspiciousActivity,
58 BruteForceDetected,
59 RateLimitExceeded,
60 SecurityPolicyViolation,
61 SecurityViolation,
62
63 AdminAction,
65 ConfigurationChanged,
66 SystemStartup,
67 SystemShutdown,
68 BackupCreated,
69 DataExported,
70 DataImported,
71}
72
73impl std::fmt::Display for AuditEventType {
74 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
75 match self {
76 Self::LoginSuccess => write!(f, "login_success"),
77 Self::LoginFailure => write!(f, "login_failure"),
78 Self::Logout => write!(f, "logout"),
79 Self::TokenRefresh => write!(f, "token_refresh"),
80 Self::TokenExpired => write!(f, "token_expired"),
81 Self::TokenRevoked => write!(f, "token_revoked"),
82 Self::MfaSetup => write!(f, "mfa_setup"),
83 Self::MfaChallengeCreated => write!(f, "mfa_challenge_created"),
84 Self::MfaVerificationSuccess => write!(f, "mfa_verification_success"),
85 Self::MfaVerificationFailure => write!(f, "mfa_verification_failure"),
86 Self::MfaMethodEnabled => write!(f, "mfa_method_enabled"),
87 Self::MfaMethodDisabled => write!(f, "mfa_method_disabled"),
88 Self::PermissionGranted => write!(f, "permission_granted"),
89 Self::PermissionDenied => write!(f, "permission_denied"),
90 Self::RoleAssigned => write!(f, "role_assigned"),
91 Self::RoleRevoked => write!(f, "role_revoked"),
92 Self::RoleCreated => write!(f, "role_created"),
93 Self::RoleUpdated => write!(f, "role_updated"),
94 Self::RoleDeleted => write!(f, "role_deleted"),
95 Self::UserCreated => write!(f, "user_created"),
96 Self::UserUpdated => write!(f, "user_updated"),
97 Self::UserDeleted => write!(f, "user_deleted"),
98 Self::UserActivated => write!(f, "user_activated"),
99 Self::UserDeactivated => write!(f, "user_deactivated"),
100 Self::UserPasswordChanged => write!(f, "user_password_changed"),
101 Self::UserPasswordReset => write!(f, "user_password_reset"),
102 Self::AccountLocked => write!(f, "account_locked"),
103 Self::AccountUnlocked => write!(f, "account_unlocked"),
104 Self::SuspiciousActivity => write!(f, "suspicious_activity"),
105 Self::BruteForceDetected => write!(f, "brute_force_detected"),
106 Self::RateLimitExceeded => write!(f, "rate_limit_exceeded"),
107 Self::SecurityPolicyViolation => write!(f, "security_policy_violation"),
108 Self::SecurityViolation => write!(f, "security_violation"),
109 Self::AdminAction => write!(f, "admin_action"),
110 Self::ConfigurationChanged => write!(f, "configuration_changed"),
111 Self::SystemStartup => write!(f, "system_startup"),
112 Self::SystemShutdown => write!(f, "system_shutdown"),
113 Self::BackupCreated => write!(f, "backup_created"),
114 Self::DataExported => write!(f, "data_exported"),
115 Self::DataImported => write!(f, "data_imported"),
116 }
117 }
118}
119
120#[derive(Debug, Clone, PartialEq, PartialOrd, Ord, Eq, Serialize, Deserialize)]
122pub enum RiskLevel {
123 Low,
124 Medium,
125 High,
126 Critical,
127}
128
129impl std::fmt::Display for RiskLevel {
130 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
131 match self {
132 Self::Low => write!(f, "low"),
133 Self::Medium => write!(f, "medium"),
134 Self::High => write!(f, "high"),
135 Self::Critical => write!(f, "critical"),
136 }
137 }
138}
139
140#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
142pub enum EventOutcome {
143 Success,
144 Failure,
145 Partial,
146 Unknown,
147}
148
149impl std::fmt::Display for EventOutcome {
150 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
151 match self {
152 Self::Success => write!(f, "success"),
153 Self::Failure => write!(f, "failure"),
154 Self::Partial => write!(f, "partial"),
155 Self::Unknown => write!(f, "unknown"),
156 }
157 }
158}
159
160#[derive(Clone, Serialize, Deserialize)]
162pub struct AuditEvent {
163 pub id: String,
165 pub event_type: AuditEventType,
167 pub timestamp: SystemTime,
169 pub user_id: Option<String>,
171 pub session_id: Option<String>,
173 pub outcome: EventOutcome,
175 pub risk_level: RiskLevel,
177 pub description: String,
179 pub details: HashMap<String, String>,
181 pub request_metadata: RequestMetadata,
183 pub resource: Option<ResourceInfo>,
185 pub actor: ActorInfo,
187 pub correlation_id: Option<String>,
189}
190
191impl std::fmt::Debug for AuditEvent {
192 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
193 let mut d = f.debug_struct("AuditEvent");
194 d.field("id", &self.id);
195 d.field("event_type", &self.event_type);
196 d.field("timestamp", &self.timestamp);
197 d.field("user_id", &self.user_id);
198 d.field(
199 "session_id",
200 &crate::utils::redact::redacted(&self.session_id),
201 );
202 d.field("outcome", &self.outcome);
203 d.field("risk_level", &self.risk_level);
204 d.field("description", &self.description);
205 d.field("details", &self.details);
206 d.field("request_metadata", &self.request_metadata);
207 d.field("resource", &self.resource);
208 d.field("actor", &self.actor);
209 d.field("correlation_id", &self.correlation_id);
210 d.finish()
211 }
212}
213
214#[derive(Debug, Clone, Serialize, Deserialize)]
216pub struct RequestMetadata {
217 pub ip_address: Option<String>,
219 pub user_agent: Option<String>,
221 pub request_id: Option<String>,
223 pub endpoint: Option<String>,
225 pub http_method: Option<String>,
227 pub geolocation: Option<GeolocationInfo>,
229 pub device_info: Option<DeviceInfo>,
231}
232
233#[derive(Debug, Clone, Serialize, Deserialize)]
235pub struct GeolocationInfo {
236 pub country: Option<String>,
237 pub region: Option<String>,
238 pub city: Option<String>,
239 pub latitude: Option<f64>,
240 pub longitude: Option<f64>,
241}
242
243#[derive(Debug, Clone, Serialize, Deserialize)]
245pub struct DeviceInfo {
246 pub device_type: Option<String>,
247 pub operating_system: Option<String>,
248 pub browser: Option<String>,
249 pub is_mobile: bool,
250 pub screen_resolution: Option<String>,
251}
252
253#[derive(Debug, Clone, Serialize, Deserialize)]
255pub struct ResourceInfo {
256 pub resource_type: String,
258 pub resource_id: String,
260 pub resource_name: Option<String>,
262 pub attributes: HashMap<String, String>,
264}
265
266#[derive(Debug, Clone, Serialize, Deserialize)]
268pub struct ActorInfo {
269 pub actor_type: String,
271 pub actor_id: String,
273 pub actor_name: Option<String>,
275 pub roles: Vec<String>,
277}
278
279#[async_trait]
281pub trait AuditStorage: Send + Sync {
282 async fn store_event(&self, event: &AuditEvent) -> Result<()>;
284
285 async fn query_events(&self, query: &AuditQuery) -> Result<Vec<AuditEvent>>;
287
288 async fn get_event(&self, event_id: &str) -> Result<Option<AuditEvent>>;
290
291 async fn count_events(&self, query: &AuditQuery) -> Result<u64>;
293
294 async fn delete_old_events(&self, before: SystemTime) -> Result<u64>;
296
297 async fn get_statistics(&self, query: &StatsQuery) -> Result<AuditStatistics>;
299}
300
301#[derive(Debug, Clone)]
303pub struct AuditQuery {
304 pub event_types: Option<Vec<AuditEventType>>,
306 pub user_id: Option<String>,
308 pub risk_level: Option<RiskLevel>,
310 pub outcome: Option<EventOutcome>,
312 pub time_range: Option<TimeRange>,
314 pub ip_address: Option<String>,
316 pub resource_type: Option<String>,
318 pub actor_id: Option<String>,
320 pub correlation_id: Option<String>,
322 pub limit: Option<u64>,
324 pub offset: Option<u64>,
326 pub sort_order: SortOrder,
328}
329
330#[derive(Debug, Clone)]
332pub struct TimeRange {
333 pub start: SystemTime,
334 pub end: SystemTime,
335}
336
337#[derive(Debug, Clone, Default)]
339pub enum SortOrder {
340 TimestampAsc,
341 #[default]
342 TimestampDesc,
343 RiskLevelDesc,
344}
345
346#[derive(Debug, Clone)]
348pub struct StatsQuery {
349 pub time_range: TimeRange,
350 pub group_by: Vec<StatsGroupBy>,
351}
352
353#[derive(Debug, Clone)]
355pub enum StatsGroupBy {
356 EventType,
357 RiskLevel,
358 Outcome,
359 Hour,
360 Day,
361 Week,
362 UserId,
363 IpAddress,
364}
365
366#[derive(Debug, Clone, Serialize, Deserialize)]
368pub struct AuditStatistics {
369 pub total_events: u64,
370 pub event_type_counts: HashMap<String, u64>,
371 pub risk_level_counts: HashMap<String, u64>,
372 pub outcome_counts: HashMap<String, u64>,
373 pub time_series: Vec<TimeSeriesPoint>,
374 pub top_users: Vec<UserEventCount>,
375 pub top_ips: Vec<IpEventCount>,
376}
377
378#[derive(Debug, Clone, Serialize, Deserialize)]
380pub struct TimeSeriesPoint {
381 pub timestamp: SystemTime,
382 pub count: u64,
383}
384
385#[derive(Debug, Clone, Serialize, Deserialize)]
387pub struct UserEventCount {
388 pub user_id: String,
389 pub event_count: u64,
390}
391
392#[derive(Debug, Clone, Serialize, Deserialize)]
394pub struct IpEventCount {
395 pub ip_address: String,
396 pub event_count: u64,
397}
398
399pub struct AuditLogger<S: AuditStorage> {
401 storage: S,
402 correlation_generator: CorrelationIdGenerator,
403}
404
405impl<S: AuditStorage> AuditLogger<S> {
406 pub fn new(storage: S) -> Self {
408 Self {
409 storage,
410 correlation_generator: CorrelationIdGenerator::new(),
411 }
412 }
413
414 pub async fn log_event(&self, mut event: AuditEvent) -> Result<()> {
416 if event.id.is_empty() {
418 event.id = uuid::Uuid::new_v4().to_string();
419 }
420
421 if event.timestamp == SystemTime::UNIX_EPOCH {
423 event.timestamp = SystemTime::now();
424 }
425
426 self.storage.store_event(&event).await?;
428
429 self.check_security_alerts(&event).await?;
431
432 Ok(())
433 }
434
435 pub async fn log_login_success(
437 &self,
438 user_id: &str,
439 session_id: &str,
440 metadata: RequestMetadata,
441 ) -> Result<()> {
442 let event = AuditEvent::builder(
443 AuditEventType::LoginSuccess,
444 "User successfully authenticated",
445 )
446 .user_id(user_id)
447 .session_id(session_id)
448 .outcome(EventOutcome::Success)
449 .request_metadata(metadata)
450 .with_actor("user", user_id)
451 .correlation_id(self.correlation_generator.generate())
452 .build();
453
454 self.log_event(event).await
455 }
456
457 pub async fn log_login_failure(
459 &self,
460 attempted_user: &str,
461 reason: &str,
462 metadata: RequestMetadata,
463 ) -> Result<()> {
464 let mut details = HashMap::new();
465 details.insert("failure_reason".to_string(), reason.to_string());
466 details.insert("attempted_user".to_string(), attempted_user.to_string());
467
468 let event = AuditEvent::builder(
469 AuditEventType::LoginFailure,
470 format!("Authentication failed for user: {}", attempted_user),
471 )
472 .outcome(EventOutcome::Failure)
473 .risk_level(RiskLevel::Medium)
474 .details(details)
475 .request_metadata(metadata)
476 .with_actor("user", attempted_user)
477 .correlation_id(self.correlation_generator.generate())
478 .build();
479
480 self.log_event(event).await
481 }
482
483 pub async fn log_permission_denied(
485 &self,
486 user_id: &str,
487 resource: ResourceInfo,
488 permission: &str,
489 metadata: RequestMetadata,
490 ) -> Result<()> {
491 let mut details = HashMap::new();
492 details.insert("requested_permission".to_string(), permission.to_string());
493
494 let event = AuditEvent::builder(
495 AuditEventType::PermissionDenied,
496 format!(
497 "Permission denied: {} on {}",
498 permission, resource.resource_type
499 ),
500 )
501 .user_id(user_id)
502 .outcome(EventOutcome::Failure)
503 .risk_level(RiskLevel::Medium)
504 .details(details)
505 .request_metadata(metadata)
506 .resource(resource)
507 .with_actor("user", user_id)
508 .correlation_id(self.correlation_generator.generate())
509 .build();
510
511 self.log_event(event).await
512 }
513
514 pub async fn log_suspicious_activity(
516 &self,
517 user_id: Option<&str>,
518 activity_type: &str,
519 description: &str,
520 metadata: RequestMetadata,
521 ) -> Result<()> {
522 let mut details = HashMap::new();
523 details.insert("activity_type".to_string(), activity_type.to_string());
524
525 let mut builder = AuditEvent::builder(AuditEventType::SuspiciousActivity, description)
526 .outcome(EventOutcome::Unknown)
527 .risk_level(RiskLevel::High)
528 .details(details)
529 .request_metadata(metadata)
530 .with_actor(
531 user_id.map(|_| "user").unwrap_or("system"),
532 user_id.unwrap_or("system"),
533 )
534 .correlation_id(self.correlation_generator.generate());
535 if let Some(uid) = user_id {
536 builder = builder.user_id(uid);
537 }
538 let event = builder.build();
539
540 self.log_event(event).await
541 }
542
543 async fn check_security_alerts(&self, event: &AuditEvent) -> Result<()> {
545 match event.event_type {
546 AuditEventType::LoginFailure => {
547 self.check_brute_force_pattern(event).await?;
548 }
549 AuditEventType::SuspiciousActivity
550 | AuditEventType::BruteForceDetected
551 | AuditEventType::SecurityPolicyViolation
552 | AuditEventType::SecurityViolation => {
553 self.trigger_security_alert(event).await?;
554 }
555 AuditEventType::AccountLocked | AuditEventType::RateLimitExceeded => {
556 tracing::warn!(
558 event_type = ?event.event_type,
559 user_id = ?event.user_id,
560 "Security-relevant audit event recorded"
561 );
562 }
563 _ => {}
565 }
566 Ok(())
567 }
568
569 async fn check_brute_force_pattern(&self, event: &AuditEvent) -> Result<()> {
571 let mut query = AuditQuery::builder()
572 .event_types(vec![AuditEventType::LoginFailure])
573 .last_seconds(300)
574 .limit(10)
575 .build();
576 query.ip_address = event.request_metadata.ip_address.clone();
577
578 let recent_failures = self.storage.query_events(&query).await?;
579
580 if recent_failures.len() >= 5 {
581 let mut details = HashMap::new();
583 details.insert(
584 "failure_count".to_string(),
585 recent_failures.len().to_string(),
586 );
587 details.insert("time_window".to_string(), "300".to_string());
588
589 let brute_force_event = AuditEvent::builder(
590 AuditEventType::BruteForceDetected,
591 "Brute force attack detected",
592 )
593 .outcome(EventOutcome::Success)
594 .risk_level(RiskLevel::Critical)
595 .details(details)
596 .request_metadata(event.request_metadata.clone())
597 .actor(ActorInfo {
598 actor_type: "system".to_string(),
599 actor_id: "security_monitor".to_string(),
600 actor_name: Some("Security Monitor".to_string()),
601 roles: vec!["system".to_string()],
602 })
603 .correlation_id(self.correlation_generator.generate())
604 .build();
605
606 self.storage.store_event(&brute_force_event).await?;
607 }
608
609 Ok(())
610 }
611
612 async fn trigger_security_alert(&self, event: &AuditEvent) -> Result<()> {
614 tracing::warn!(
615 event_type = ?event.event_type,
616 user_id = ?event.user_id,
617 risk_level = ?event.risk_level,
618 description = %event.description,
619 ip_address = ?event.request_metadata.ip_address,
620 "SECURITY ALERT: {}", event.description
621 );
622 Ok(())
623 }
624
625 pub async fn query_events(&self, query: &AuditQuery) -> Result<Vec<AuditEvent>> {
627 self.storage.query_events(query).await
628 }
629
630 pub async fn get_statistics(&self, query: &StatsQuery) -> Result<AuditStatistics> {
632 self.storage.get_statistics(query).await
633 }
634
635 pub async fn get_failed_login_count_24h(&self) -> Result<u64> {
637 let query = AuditQuery::builder()
638 .event_types(vec![AuditEventType::LoginFailure])
639 .last_24h()
640 .build();
641 self.storage.count_events(&query).await
642 }
643
644 pub async fn get_successful_login_count_24h(&self) -> Result<u64> {
646 let query = AuditQuery::builder()
647 .event_types(vec![AuditEventType::LoginSuccess])
648 .last_24h()
649 .build();
650 self.storage.count_events(&query).await
651 }
652
653 pub async fn get_token_issued_count_24h(&self) -> Result<u64> {
655 let query = AuditQuery::builder()
656 .event_types(vec![
657 AuditEventType::TokenRefresh,
658 AuditEventType::LoginSuccess,
659 ])
660 .last_24h()
661 .build();
662 self.storage.count_events(&query).await
663 }
664
665 pub async fn get_unique_users_24h(&self) -> Result<u64> {
667 let query = AuditQuery::builder()
668 .event_types(vec![AuditEventType::LoginSuccess])
669 .last_24h()
670 .build();
671
672 let events = self.storage.query_events(&query).await?;
673 let unique_users: std::collections::HashSet<_> =
674 events.iter().filter_map(|e| e.user_id.as_ref()).collect();
675 Ok(unique_users.len() as u64)
676 }
677
678 pub async fn get_password_reset_count_24h(&self) -> Result<u64> {
680 let query = AuditQuery::builder()
681 .event_types(vec![AuditEventType::UserPasswordReset])
682 .last_24h()
683 .build();
684 self.storage.count_events(&query).await
685 }
686
687 pub async fn get_admin_action_count_24h(&self) -> Result<u64> {
689 let query = AuditQuery::builder()
690 .event_types(vec![
691 AuditEventType::AdminAction,
692 AuditEventType::UserCreated,
693 AuditEventType::UserUpdated,
694 AuditEventType::UserDeleted,
695 AuditEventType::RoleCreated,
696 AuditEventType::RoleUpdated,
697 AuditEventType::RoleDeleted,
698 ])
699 .last_24h()
700 .build();
701 self.storage.count_events(&query).await
702 }
703
704 pub async fn get_security_alert_count_24h(&self) -> Result<u64> {
706 let query = AuditQuery::builder()
707 .event_types(vec![
708 AuditEventType::SuspiciousActivity,
709 AuditEventType::BruteForceDetected,
710 AuditEventType::SecurityViolation,
711 ])
712 .last_24h()
713 .risk_level(RiskLevel::High)
714 .build();
715 self.storage.count_events(&query).await
716 }
717
718 pub async fn get_permission_checks_last_hour(&self) -> Result<u64> {
720 let query = AuditQuery::builder()
721 .event_types(vec![
722 AuditEventType::PermissionGranted,
723 AuditEventType::PermissionDenied,
724 ])
725 .last_seconds(3600)
726 .build();
727 self.storage.count_events(&query).await
728 }
729
730 pub async fn get_permission_audit_logs(
732 &self,
733 user_id: Option<&str>,
734 action: Option<&str>,
735 resource: Option<&str>,
736 limit: Option<usize>,
737 ) -> Result<Vec<String>> {
738 let mut builder = AuditQuery::builder().event_types(vec![
739 AuditEventType::PermissionGranted,
740 AuditEventType::PermissionDenied,
741 AuditEventType::RoleAssigned,
742 AuditEventType::RoleRevoked,
743 AuditEventType::RoleCreated,
744 AuditEventType::RoleUpdated,
745 AuditEventType::RoleDeleted,
746 ]);
747 if let Some(uid) = user_id {
748 builder = builder.user_id(uid);
749 }
750 if let Some(rt) = resource {
751 builder = builder.resource_type(rt);
752 }
753 if let Some(l) = limit {
754 builder = builder.limit(l as u64);
755 }
756 let query = builder.build();
757
758 let events = self.storage.query_events(&query).await?;
759
760 let logs = events
761 .into_iter()
762 .filter(|e| {
763 action.is_none_or(|a| {
764 e.description.to_lowercase().contains(&a.to_lowercase())
765 || e.details
766 .values()
767 .any(|v| v.to_lowercase().contains(&a.to_lowercase()))
768 })
769 })
770 .map(|e| {
771 let ts = e
772 .timestamp
773 .duration_since(std::time::UNIX_EPOCH)
774 .map(|d| {
775 chrono::Utc
776 .timestamp_opt(d.as_secs() as i64, 0)
777 .single()
778 .map(|dt| dt.format("%Y-%m-%dT%H:%M:%SZ").to_string())
779 .unwrap_or_else(|| "unknown-time".to_string())
780 })
781 .unwrap_or_else(|_| "unknown-time".to_string());
782 let uid = e.user_id.as_deref().unwrap_or("system");
783 format!(
784 "[{}] {} user={} outcome={} - {}",
785 ts, e.event_type, uid, e.outcome, e.description
786 )
787 })
788 .collect();
789
790 Ok(logs)
791 }
792
793 pub async fn get_security_audit_stats(
798 &self,
799 active_sessions: u64,
800 ) -> Result<SecurityAuditStats> {
801 let failed_logins_24h = self.get_failed_login_count_24h().await.unwrap_or(0);
802 let successful_logins_24h = self
803 .get_successful_login_count_24h()
804 .await
805 .unwrap_or(active_sessions * 2);
806 let token_issued_24h = self
807 .get_token_issued_count_24h()
808 .await
809 .unwrap_or(active_sessions * 3);
810 let unique_users_24h = self
811 .get_unique_users_24h()
812 .await
813 .unwrap_or((successful_logins_24h as f64 * 0.7) as u64);
814 let password_resets_24h = self.get_password_reset_count_24h().await.unwrap_or(0);
815 let admin_actions_24h = self.get_admin_action_count_24h().await.unwrap_or(0);
816 let security_alerts_24h = self.get_security_alert_count_24h().await.unwrap_or(0);
817
818 Ok(SecurityAuditStats {
819 active_sessions,
820 failed_logins_24h,
821 successful_logins_24h,
822 unique_users_24h,
823 token_issued_24h,
824 password_resets_24h,
825 admin_actions_24h,
826 security_alerts_24h,
827 collection_timestamp: chrono::Utc::now(),
828 })
829 }
830
831 pub async fn log_auth_trace_event(
835 &self,
836 event_type: &str,
837 user_id: &str,
838 method: &str,
839 client_ip: &str,
840 user_agent: &str,
841 ) {
842 tracing::info!(
843 target: "auth_audit",
844 event_type = event_type,
845 user_id = user_id,
846 method = method,
847 client_ip = client_ip,
848 user_agent = user_agent,
849 timestamp = %chrono::Utc::now().to_rfc3339(),
850 "Authentication event"
851 );
852 }
853
854 pub async fn cleanup_old_events(&self, retention_days: u32) -> Result<u64> {
856 let cutoff_time =
857 SystemTime::now() - std::time::Duration::from_secs(retention_days as u64 * 86400);
858 self.storage.delete_old_events(cutoff_time).await
859 }
860}
861
862#[derive(Debug, Clone, Serialize, Deserialize)]
866pub struct SecurityAuditStats {
867 pub active_sessions: u64,
868 pub failed_logins_24h: u64,
869 pub successful_logins_24h: u64,
870 pub unique_users_24h: u64,
871 pub token_issued_24h: u64,
872 pub password_resets_24h: u64,
873 pub admin_actions_24h: u64,
874 pub security_alerts_24h: u64,
875 pub collection_timestamp: chrono::DateTime<chrono::Utc>,
876}
877
878impl SecurityAuditStats {
879 pub fn security_score(&self) -> f64 {
882 let mut score = 1.0_f64;
883
884 if self.successful_logins_24h > 0 {
885 let failure_rate = self.failed_logins_24h as f64
886 / (self.successful_logins_24h + self.failed_logins_24h) as f64;
887 if failure_rate > 0.1 {
888 score -= failure_rate * 0.3;
889 }
890 }
891
892 if self.security_alerts_24h > 0 {
893 score -= (self.security_alerts_24h as f64 * 0.1).min(0.4);
894 }
895
896 if self.successful_logins_24h > 0 && self.failed_logins_24h < 10 {
897 score += 0.05;
898 }
899
900 score.clamp(0.0, 1.0)
901 }
902
903 pub fn requires_immediate_attention(&self) -> bool {
917 self.failed_logins_24h > 100 || self.security_alerts_24h > 5 || self.security_score() < 0.3
918 }
919
920 pub fn security_alert_message(&self) -> Option<String> {
935 if !self.requires_immediate_attention() {
936 return None;
937 }
938
939 let mut alerts = Vec::new();
940
941 if self.failed_logins_24h > 100 {
942 alerts.push(format!(
943 "High failed login attempts: {}",
944 self.failed_logins_24h
945 ));
946 }
947 if self.security_alerts_24h > 5 {
948 alerts.push(format!(
949 "Multiple security alerts: {}",
950 self.security_alerts_24h
951 ));
952 }
953 if self.security_score() < 0.3 {
954 alerts.push(format!(
955 "Critical security score: {:.2}",
956 self.security_score()
957 ));
958 }
959
960 Some(format!(
961 "🚨 SECURITY ATTENTION REQUIRED: {}",
962 alerts.join(", ")
963 ))
964 }
965}
966
967pub struct CorrelationIdGenerator {
969 counter: std::sync::atomic::AtomicU64,
970}
971
972impl CorrelationIdGenerator {
973 pub fn new() -> Self {
974 Self {
975 counter: std::sync::atomic::AtomicU64::new(0),
976 }
977 }
978
979 pub fn generate(&self) -> String {
980 let count = self
981 .counter
982 .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
983 format!(
984 "corr_{:016x}_{}",
985 SystemTime::now()
986 .duration_since(SystemTime::UNIX_EPOCH)
987 .unwrap_or_default()
988 .as_secs(),
989 count
990 )
991 }
992}
993
994pub struct AuditEventBuilder {
1018 event: AuditEvent,
1019}
1020
1021impl AuditEvent {
1022 pub fn builder(
1024 event_type: AuditEventType,
1025 description: impl Into<String>,
1026 ) -> AuditEventBuilder {
1027 AuditEventBuilder::new(event_type, description)
1028 }
1029}
1030
1031impl AuditEventBuilder {
1032 pub fn new(event_type: AuditEventType, description: impl Into<String>) -> Self {
1034 Self {
1035 event: AuditEvent {
1036 id: String::new(),
1037 event_type,
1038 timestamp: SystemTime::UNIX_EPOCH,
1039 user_id: None,
1040 session_id: None,
1041 outcome: EventOutcome::Unknown,
1042 risk_level: RiskLevel::Low,
1043 description: description.into(),
1044 details: HashMap::new(),
1045 request_metadata: RequestMetadata::new(),
1046 resource: None,
1047 actor: ActorInfo {
1048 actor_type: "unknown".to_string(),
1049 actor_id: String::new(),
1050 actor_name: None,
1051 roles: Vec::new(),
1052 },
1053 correlation_id: None,
1054 },
1055 }
1056 }
1057
1058 pub fn user_id(mut self, id: impl Into<String>) -> Self {
1060 self.event.user_id = Some(id.into());
1061 self
1062 }
1063
1064 pub fn session_id(mut self, id: impl Into<String>) -> Self {
1066 self.event.session_id = Some(id.into());
1067 self
1068 }
1069
1070 pub fn outcome(mut self, outcome: EventOutcome) -> Self {
1072 self.event.outcome = outcome;
1073 self
1074 }
1075
1076 pub fn risk_level(mut self, level: RiskLevel) -> Self {
1078 self.event.risk_level = level;
1079 self
1080 }
1081
1082 pub fn with_actor(
1084 mut self,
1085 actor_type: impl Into<String>,
1086 actor_id: impl Into<String>,
1087 ) -> Self {
1088 self.event.actor = ActorInfo {
1089 actor_type: actor_type.into(),
1090 actor_id: actor_id.into(),
1091 actor_name: None,
1092 roles: Vec::new(),
1093 };
1094 self
1095 }
1096
1097 pub fn actor(mut self, actor: ActorInfo) -> Self {
1099 self.event.actor = actor;
1100 self
1101 }
1102
1103 pub fn request_metadata(mut self, metadata: RequestMetadata) -> Self {
1105 self.event.request_metadata = metadata;
1106 self
1107 }
1108
1109 pub fn resource(mut self, resource: ResourceInfo) -> Self {
1111 self.event.resource = Some(resource);
1112 self
1113 }
1114
1115 pub fn correlation_id(mut self, id: impl Into<String>) -> Self {
1117 self.event.correlation_id = Some(id.into());
1118 self
1119 }
1120
1121 pub fn detail(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
1123 self.event.details.insert(key.into(), value.into());
1124 self
1125 }
1126
1127 pub fn details(mut self, details: HashMap<String, String>) -> Self {
1129 self.event.details = details;
1130 self
1131 }
1132
1133 pub fn build(mut self) -> AuditEvent {
1138 if self.event.id.is_empty() {
1139 self.event.id = uuid::Uuid::new_v4().to_string();
1140 }
1141 if self.event.timestamp == SystemTime::UNIX_EPOCH {
1142 self.event.timestamp = SystemTime::now();
1143 }
1144 self.event
1145 }
1146}
1147
1148impl Default for AuditQuery {
1151 fn default() -> Self {
1152 Self {
1153 event_types: None,
1154 user_id: None,
1155 risk_level: None,
1156 outcome: None,
1157 time_range: None,
1158 ip_address: None,
1159 resource_type: None,
1160 actor_id: None,
1161 correlation_id: None,
1162 limit: None,
1163 offset: None,
1164 sort_order: SortOrder::TimestampDesc,
1165 }
1166 }
1167}
1168
1169pub struct AuditQueryBuilder {
1187 query: AuditQuery,
1188}
1189
1190impl AuditQuery {
1191 pub fn builder() -> AuditQueryBuilder {
1193 AuditQueryBuilder {
1194 query: AuditQuery::default(),
1195 }
1196 }
1197}
1198
1199impl AuditQueryBuilder {
1200 pub fn event_types(mut self, types: Vec<AuditEventType>) -> Self {
1202 self.query.event_types = Some(types);
1203 self
1204 }
1205
1206 pub fn user_id(mut self, id: impl Into<String>) -> Self {
1208 self.query.user_id = Some(id.into());
1209 self
1210 }
1211
1212 pub fn risk_level(mut self, level: RiskLevel) -> Self {
1214 self.query.risk_level = Some(level);
1215 self
1216 }
1217
1218 pub fn outcome(mut self, outcome: EventOutcome) -> Self {
1220 self.query.outcome = Some(outcome);
1221 self
1222 }
1223
1224 pub fn time_range(mut self, start: SystemTime, end: SystemTime) -> Self {
1226 self.query.time_range = Some(TimeRange { start, end });
1227 self
1228 }
1229
1230 pub fn last_seconds(mut self, seconds: u64) -> Self {
1232 self.query.time_range = Some(TimeRange {
1233 start: SystemTime::now() - std::time::Duration::from_secs(seconds),
1234 end: SystemTime::now(),
1235 });
1236 self
1237 }
1238
1239 pub fn last_24h(self) -> Self {
1241 self.last_seconds(24 * 60 * 60)
1242 }
1243
1244 pub fn ip_address(mut self, ip: impl Into<String>) -> Self {
1246 self.query.ip_address = Some(ip.into());
1247 self
1248 }
1249
1250 pub fn resource_type(mut self, rt: impl Into<String>) -> Self {
1252 self.query.resource_type = Some(rt.into());
1253 self
1254 }
1255
1256 pub fn actor_id(mut self, id: impl Into<String>) -> Self {
1258 self.query.actor_id = Some(id.into());
1259 self
1260 }
1261
1262 pub fn correlation_id(mut self, id: impl Into<String>) -> Self {
1264 self.query.correlation_id = Some(id.into());
1265 self
1266 }
1267
1268 pub fn limit(mut self, limit: u64) -> Self {
1270 self.query.limit = Some(limit);
1271 self
1272 }
1273
1274 pub fn offset(mut self, offset: u64) -> Self {
1276 self.query.offset = Some(offset);
1277 self
1278 }
1279
1280 pub fn sort_order(mut self, order: SortOrder) -> Self {
1282 self.query.sort_order = order;
1283 self
1284 }
1285
1286 pub fn build(self) -> AuditQuery {
1288 self.query
1289 }
1290}
1291
1292impl RequestMetadata {
1294 pub fn new() -> Self {
1295 Self {
1296 ip_address: None,
1297 user_agent: None,
1298 request_id: None,
1299 endpoint: None,
1300 http_method: None,
1301 geolocation: None,
1302 device_info: None,
1303 }
1304 }
1305
1306 pub fn with_ip(mut self, ip: impl Into<String>) -> Self {
1307 self.ip_address = Some(ip.into());
1308 self
1309 }
1310
1311 pub fn with_user_agent(mut self, user_agent: impl Into<String>) -> Self {
1312 self.user_agent = Some(user_agent.into());
1313 self
1314 }
1315
1316 pub fn with_endpoint(mut self, endpoint: impl Into<String>) -> Self {
1317 self.endpoint = Some(endpoint.into());
1318 self
1319 }
1320}
1321
1322impl Default for RequestMetadata {
1323 fn default() -> Self {
1324 Self::new()
1325 }
1326}
1327
1328#[cfg(test)]
1329mod tests {
1330 use super::*;
1331
1332 #[test]
1333 fn test_correlation_id_generation() {
1334 let generator = CorrelationIdGenerator::new();
1335 let id1 = generator.generate();
1336 let id2 = generator.generate();
1337
1338 assert_ne!(id1, id2);
1339 assert!(id1.starts_with("corr_"));
1340 assert!(id2.starts_with("corr_"));
1341 }
1342
1343 #[test]
1344 fn test_request_metadata_builder() {
1345 let metadata = RequestMetadata::new()
1346 .with_ip("192.168.1.1")
1347 .with_user_agent("Mozilla/5.0")
1348 .with_endpoint("/api/auth/login");
1349
1350 assert_eq!(metadata.ip_address, Some("192.168.1.1".to_string()));
1351 assert_eq!(metadata.user_agent, Some("Mozilla/5.0".to_string()));
1352 assert_eq!(metadata.endpoint, Some("/api/auth/login".to_string()));
1353 }
1354
1355 #[test]
1356 fn test_audit_event_builder_minimal() {
1357 let event = AuditEvent::builder(AuditEventType::LoginSuccess, "User logged in").build();
1358 assert_eq!(event.event_type, AuditEventType::LoginSuccess);
1359 assert_eq!(event.description, "User logged in");
1360 assert!(!event.id.is_empty(), "id should be auto-generated");
1361 assert_ne!(
1362 event.timestamp,
1363 SystemTime::UNIX_EPOCH,
1364 "timestamp should be auto-set"
1365 );
1366 assert_eq!(event.outcome, EventOutcome::Unknown);
1367 assert_eq!(event.risk_level, RiskLevel::Low);
1368 }
1369
1370 #[test]
1371 fn test_audit_event_builder_full() {
1372 let event = AuditEvent::builder(AuditEventType::PermissionDenied, "Access denied")
1373 .user_id("u123")
1374 .session_id("s456")
1375 .outcome(EventOutcome::Failure)
1376 .risk_level(RiskLevel::High)
1377 .with_actor("user", "u123")
1378 .detail("resource", "admin_panel")
1379 .correlation_id("corr_xyz")
1380 .build();
1381
1382 assert_eq!(event.user_id, Some("u123".to_string()));
1383 assert_eq!(event.session_id, Some("s456".to_string()));
1384 assert_eq!(event.outcome, EventOutcome::Failure);
1385 assert_eq!(event.risk_level, RiskLevel::High);
1386 assert_eq!(event.actor.actor_type, "user");
1387 assert_eq!(event.actor.actor_id, "u123");
1388 assert_eq!(
1389 event.details.get("resource"),
1390 Some(&"admin_panel".to_string())
1391 );
1392 assert_eq!(event.correlation_id, Some("corr_xyz".to_string()));
1393 }
1394
1395 #[test]
1396 fn test_audit_query_builder() {
1397 let query = AuditQuery::builder()
1398 .event_types(vec![AuditEventType::LoginFailure])
1399 .limit(50)
1400 .offset(10)
1401 .build();
1402
1403 assert_eq!(query.event_types, Some(vec![AuditEventType::LoginFailure]));
1404 assert_eq!(query.limit, Some(50));
1405 assert_eq!(query.offset, Some(10));
1406 assert!(query.user_id.is_none());
1407 }
1408
1409 #[test]
1410 fn test_audit_query_default() {
1411 let query = AuditQuery::default();
1412 assert!(query.event_types.is_none());
1413 assert!(query.user_id.is_none());
1414 assert!(query.limit.is_none());
1415 assert!(matches!(query.sort_order, SortOrder::TimestampDesc));
1416 }
1417
1418 #[test]
1419 fn test_audit_query_last_24h() {
1420 let query = AuditQuery::builder().last_24h().build();
1421 assert!(query.time_range.is_some());
1422 let range = query.time_range.unwrap();
1423 let elapsed = range.end.duration_since(range.start).unwrap();
1424 assert!(elapsed.as_secs() >= 86399 && elapsed.as_secs() <= 86401);
1426 }
1427
1428 #[test]
1429 fn test_audit_query_last_seconds() {
1430 let query = AuditQuery::builder().last_seconds(3600).build();
1431 assert!(query.time_range.is_some());
1432 let range = query.time_range.unwrap();
1433 let elapsed = range.end.duration_since(range.start).unwrap();
1434 assert!(elapsed.as_secs() >= 3599 && elapsed.as_secs() <= 3601);
1435 }
1436
1437 #[test]
1438 fn test_audit_event_type_display() {
1439 assert_eq!(AuditEventType::LoginSuccess.to_string(), "login_success");
1440 assert_eq!(AuditEventType::LoginFailure.to_string(), "login_failure");
1441 assert_eq!(AuditEventType::Logout.to_string(), "logout");
1442 assert_eq!(AuditEventType::TokenRefresh.to_string(), "token_refresh");
1443 assert_eq!(
1444 AuditEventType::MfaVerificationSuccess.to_string(),
1445 "mfa_verification_success"
1446 );
1447 assert_eq!(
1448 AuditEventType::PermissionGranted.to_string(),
1449 "permission_granted"
1450 );
1451 assert_eq!(
1452 AuditEventType::PermissionDenied.to_string(),
1453 "permission_denied"
1454 );
1455 assert_eq!(AuditEventType::RoleAssigned.to_string(), "role_assigned");
1456 assert_eq!(AuditEventType::UserCreated.to_string(), "user_created");
1457 assert_eq!(AuditEventType::AccountLocked.to_string(), "account_locked");
1458 assert_eq!(
1459 AuditEventType::BruteForceDetected.to_string(),
1460 "brute_force_detected"
1461 );
1462 assert_eq!(AuditEventType::AdminAction.to_string(), "admin_action");
1463 assert_eq!(AuditEventType::SystemStartup.to_string(), "system_startup");
1464 assert_eq!(AuditEventType::DataExported.to_string(), "data_exported");
1465 }
1466
1467 #[test]
1468 fn test_risk_level_display() {
1469 assert_eq!(RiskLevel::Low.to_string(), "low");
1470 assert_eq!(RiskLevel::Medium.to_string(), "medium");
1471 assert_eq!(RiskLevel::High.to_string(), "high");
1472 assert_eq!(RiskLevel::Critical.to_string(), "critical");
1473 }
1474
1475 #[test]
1476 fn test_event_outcome_display() {
1477 assert_eq!(EventOutcome::Success.to_string(), "success");
1478 assert_eq!(EventOutcome::Failure.to_string(), "failure");
1479 assert_eq!(EventOutcome::Partial.to_string(), "partial");
1480 assert_eq!(EventOutcome::Unknown.to_string(), "unknown");
1481 }
1482}