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(Debug, 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
191#[derive(Debug, Clone, Serialize, Deserialize)]
193pub struct RequestMetadata {
194 pub ip_address: Option<String>,
196 pub user_agent: Option<String>,
198 pub request_id: Option<String>,
200 pub endpoint: Option<String>,
202 pub http_method: Option<String>,
204 pub geolocation: Option<GeolocationInfo>,
206 pub device_info: Option<DeviceInfo>,
208}
209
210#[derive(Debug, Clone, Serialize, Deserialize)]
212pub struct GeolocationInfo {
213 pub country: Option<String>,
214 pub region: Option<String>,
215 pub city: Option<String>,
216 pub latitude: Option<f64>,
217 pub longitude: Option<f64>,
218}
219
220#[derive(Debug, Clone, Serialize, Deserialize)]
222pub struct DeviceInfo {
223 pub device_type: Option<String>,
224 pub operating_system: Option<String>,
225 pub browser: Option<String>,
226 pub is_mobile: bool,
227 pub screen_resolution: Option<String>,
228}
229
230#[derive(Debug, Clone, Serialize, Deserialize)]
232pub struct ResourceInfo {
233 pub resource_type: String,
235 pub resource_id: String,
237 pub resource_name: Option<String>,
239 pub attributes: HashMap<String, String>,
241}
242
243#[derive(Debug, Clone, Serialize, Deserialize)]
245pub struct ActorInfo {
246 pub actor_type: String,
248 pub actor_id: String,
250 pub actor_name: Option<String>,
252 pub roles: Vec<String>,
254}
255
256#[async_trait]
258pub trait AuditStorage: Send + Sync {
259 async fn store_event(&self, event: &AuditEvent) -> Result<()>;
261
262 async fn query_events(&self, query: &AuditQuery) -> Result<Vec<AuditEvent>>;
264
265 async fn get_event(&self, event_id: &str) -> Result<Option<AuditEvent>>;
267
268 async fn count_events(&self, query: &AuditQuery) -> Result<u64>;
270
271 async fn delete_old_events(&self, before: SystemTime) -> Result<u64>;
273
274 async fn get_statistics(&self, query: &StatsQuery) -> Result<AuditStatistics>;
276}
277
278#[derive(Debug, Clone)]
280pub struct AuditQuery {
281 pub event_types: Option<Vec<AuditEventType>>,
283 pub user_id: Option<String>,
285 pub risk_level: Option<RiskLevel>,
287 pub outcome: Option<EventOutcome>,
289 pub time_range: Option<TimeRange>,
291 pub ip_address: Option<String>,
293 pub resource_type: Option<String>,
295 pub actor_id: Option<String>,
297 pub correlation_id: Option<String>,
299 pub limit: Option<u64>,
301 pub offset: Option<u64>,
303 pub sort_order: SortOrder,
305}
306
307#[derive(Debug, Clone)]
309pub struct TimeRange {
310 pub start: SystemTime,
311 pub end: SystemTime,
312}
313
314#[derive(Debug, Clone, Default)]
316pub enum SortOrder {
317 TimestampAsc,
318 #[default]
319 TimestampDesc,
320 RiskLevelDesc,
321}
322
323#[derive(Debug, Clone)]
325pub struct StatsQuery {
326 pub time_range: TimeRange,
327 pub group_by: Vec<StatsGroupBy>,
328}
329
330#[derive(Debug, Clone)]
332pub enum StatsGroupBy {
333 EventType,
334 RiskLevel,
335 Outcome,
336 Hour,
337 Day,
338 Week,
339 UserId,
340 IpAddress,
341}
342
343#[derive(Debug, Clone, Serialize, Deserialize)]
345pub struct AuditStatistics {
346 pub total_events: u64,
347 pub event_type_counts: HashMap<String, u64>,
348 pub risk_level_counts: HashMap<String, u64>,
349 pub outcome_counts: HashMap<String, u64>,
350 pub time_series: Vec<TimeSeriesPoint>,
351 pub top_users: Vec<UserEventCount>,
352 pub top_ips: Vec<IpEventCount>,
353}
354
355#[derive(Debug, Clone, Serialize, Deserialize)]
357pub struct TimeSeriesPoint {
358 pub timestamp: SystemTime,
359 pub count: u64,
360}
361
362#[derive(Debug, Clone, Serialize, Deserialize)]
364pub struct UserEventCount {
365 pub user_id: String,
366 pub event_count: u64,
367}
368
369#[derive(Debug, Clone, Serialize, Deserialize)]
371pub struct IpEventCount {
372 pub ip_address: String,
373 pub event_count: u64,
374}
375
376pub struct AuditLogger<S: AuditStorage> {
378 storage: S,
379 correlation_generator: CorrelationIdGenerator,
380}
381
382impl<S: AuditStorage> AuditLogger<S> {
383 pub fn new(storage: S) -> Self {
385 Self {
386 storage,
387 correlation_generator: CorrelationIdGenerator::new(),
388 }
389 }
390
391 pub async fn log_event(&self, mut event: AuditEvent) -> Result<()> {
393 if event.id.is_empty() {
395 event.id = uuid::Uuid::new_v4().to_string();
396 }
397
398 if event.timestamp == SystemTime::UNIX_EPOCH {
400 event.timestamp = SystemTime::now();
401 }
402
403 self.storage.store_event(&event).await?;
405
406 self.check_security_alerts(&event).await?;
408
409 Ok(())
410 }
411
412 pub async fn log_login_success(
414 &self,
415 user_id: &str,
416 session_id: &str,
417 metadata: RequestMetadata,
418 ) -> Result<()> {
419 let event = AuditEvent::builder(
420 AuditEventType::LoginSuccess,
421 "User successfully authenticated",
422 )
423 .user_id(user_id)
424 .session_id(session_id)
425 .outcome(EventOutcome::Success)
426 .request_metadata(metadata)
427 .with_actor("user", user_id)
428 .correlation_id(self.correlation_generator.generate())
429 .build();
430
431 self.log_event(event).await
432 }
433
434 pub async fn log_login_failure(
436 &self,
437 attempted_user: &str,
438 reason: &str,
439 metadata: RequestMetadata,
440 ) -> Result<()> {
441 let mut details = HashMap::new();
442 details.insert("failure_reason".to_string(), reason.to_string());
443 details.insert("attempted_user".to_string(), attempted_user.to_string());
444
445 let event = AuditEvent::builder(
446 AuditEventType::LoginFailure,
447 format!("Authentication failed for user: {}", attempted_user),
448 )
449 .outcome(EventOutcome::Failure)
450 .risk_level(RiskLevel::Medium)
451 .details(details)
452 .request_metadata(metadata)
453 .with_actor("user", attempted_user)
454 .correlation_id(self.correlation_generator.generate())
455 .build();
456
457 self.log_event(event).await
458 }
459
460 pub async fn log_permission_denied(
462 &self,
463 user_id: &str,
464 resource: ResourceInfo,
465 permission: &str,
466 metadata: RequestMetadata,
467 ) -> Result<()> {
468 let mut details = HashMap::new();
469 details.insert("requested_permission".to_string(), permission.to_string());
470
471 let event = AuditEvent::builder(
472 AuditEventType::PermissionDenied,
473 format!(
474 "Permission denied: {} on {}",
475 permission, resource.resource_type
476 ),
477 )
478 .user_id(user_id)
479 .outcome(EventOutcome::Failure)
480 .risk_level(RiskLevel::Medium)
481 .details(details)
482 .request_metadata(metadata)
483 .resource(resource)
484 .with_actor("user", user_id)
485 .correlation_id(self.correlation_generator.generate())
486 .build();
487
488 self.log_event(event).await
489 }
490
491 pub async fn log_suspicious_activity(
493 &self,
494 user_id: Option<&str>,
495 activity_type: &str,
496 description: &str,
497 metadata: RequestMetadata,
498 ) -> Result<()> {
499 let mut details = HashMap::new();
500 details.insert("activity_type".to_string(), activity_type.to_string());
501
502 let mut builder = AuditEvent::builder(AuditEventType::SuspiciousActivity, description)
503 .outcome(EventOutcome::Unknown)
504 .risk_level(RiskLevel::High)
505 .details(details)
506 .request_metadata(metadata)
507 .with_actor(
508 user_id.map(|_| "user").unwrap_or("system"),
509 user_id.unwrap_or("system"),
510 )
511 .correlation_id(self.correlation_generator.generate());
512 if let Some(uid) = user_id {
513 builder = builder.user_id(uid);
514 }
515 let event = builder.build();
516
517 self.log_event(event).await
518 }
519
520 async fn check_security_alerts(&self, event: &AuditEvent) -> Result<()> {
522 match event.event_type {
523 AuditEventType::LoginFailure => {
524 self.check_brute_force_pattern(event).await?;
525 }
526 AuditEventType::SuspiciousActivity
527 | AuditEventType::BruteForceDetected
528 | AuditEventType::SecurityPolicyViolation
529 | AuditEventType::SecurityViolation => {
530 self.trigger_security_alert(event).await?;
531 }
532 AuditEventType::AccountLocked | AuditEventType::RateLimitExceeded => {
533 tracing::warn!(
535 event_type = ?event.event_type,
536 user_id = ?event.user_id,
537 "Security-relevant audit event recorded"
538 );
539 }
540 _ => {}
542 }
543 Ok(())
544 }
545
546 async fn check_brute_force_pattern(&self, event: &AuditEvent) -> Result<()> {
548 let mut query = AuditQuery::builder()
549 .event_types(vec![AuditEventType::LoginFailure])
550 .last_seconds(300)
551 .limit(10)
552 .build();
553 query.ip_address = event.request_metadata.ip_address.clone();
554
555 let recent_failures = self.storage.query_events(&query).await?;
556
557 if recent_failures.len() >= 5 {
558 let mut details = HashMap::new();
560 details.insert(
561 "failure_count".to_string(),
562 recent_failures.len().to_string(),
563 );
564 details.insert("time_window".to_string(), "300".to_string());
565
566 let brute_force_event = AuditEvent::builder(
567 AuditEventType::BruteForceDetected,
568 "Brute force attack detected",
569 )
570 .outcome(EventOutcome::Success)
571 .risk_level(RiskLevel::Critical)
572 .details(details)
573 .request_metadata(event.request_metadata.clone())
574 .actor(ActorInfo {
575 actor_type: "system".to_string(),
576 actor_id: "security_monitor".to_string(),
577 actor_name: Some("Security Monitor".to_string()),
578 roles: vec!["system".to_string()],
579 })
580 .correlation_id(self.correlation_generator.generate())
581 .build();
582
583 self.storage.store_event(&brute_force_event).await?;
584 }
585
586 Ok(())
587 }
588
589 async fn trigger_security_alert(&self, event: &AuditEvent) -> Result<()> {
591 tracing::warn!(
592 event_type = ?event.event_type,
593 user_id = ?event.user_id,
594 risk_level = ?event.risk_level,
595 description = %event.description,
596 ip_address = ?event.request_metadata.ip_address,
597 "SECURITY ALERT: {}", event.description
598 );
599 Ok(())
600 }
601
602 pub async fn query_events(&self, query: &AuditQuery) -> Result<Vec<AuditEvent>> {
604 self.storage.query_events(query).await
605 }
606
607 pub async fn get_statistics(&self, query: &StatsQuery) -> Result<AuditStatistics> {
609 self.storage.get_statistics(query).await
610 }
611
612 pub async fn get_failed_login_count_24h(&self) -> Result<u64> {
614 let query = AuditQuery::builder()
615 .event_types(vec![AuditEventType::LoginFailure])
616 .last_24h()
617 .build();
618 self.storage.count_events(&query).await
619 }
620
621 pub async fn get_successful_login_count_24h(&self) -> Result<u64> {
623 let query = AuditQuery::builder()
624 .event_types(vec![AuditEventType::LoginSuccess])
625 .last_24h()
626 .build();
627 self.storage.count_events(&query).await
628 }
629
630 pub async fn get_token_issued_count_24h(&self) -> Result<u64> {
632 let query = AuditQuery::builder()
633 .event_types(vec![
634 AuditEventType::TokenRefresh,
635 AuditEventType::LoginSuccess,
636 ])
637 .last_24h()
638 .build();
639 self.storage.count_events(&query).await
640 }
641
642 pub async fn get_unique_users_24h(&self) -> Result<u64> {
644 let query = AuditQuery::builder()
645 .event_types(vec![AuditEventType::LoginSuccess])
646 .last_24h()
647 .build();
648
649 let events = self.storage.query_events(&query).await?;
650 let unique_users: std::collections::HashSet<_> =
651 events.iter().filter_map(|e| e.user_id.as_ref()).collect();
652 Ok(unique_users.len() as u64)
653 }
654
655 pub async fn get_password_reset_count_24h(&self) -> Result<u64> {
657 let query = AuditQuery::builder()
658 .event_types(vec![AuditEventType::UserPasswordReset])
659 .last_24h()
660 .build();
661 self.storage.count_events(&query).await
662 }
663
664 pub async fn get_admin_action_count_24h(&self) -> Result<u64> {
666 let query = AuditQuery::builder()
667 .event_types(vec![
668 AuditEventType::AdminAction,
669 AuditEventType::UserCreated,
670 AuditEventType::UserUpdated,
671 AuditEventType::UserDeleted,
672 AuditEventType::RoleCreated,
673 AuditEventType::RoleUpdated,
674 AuditEventType::RoleDeleted,
675 ])
676 .last_24h()
677 .build();
678 self.storage.count_events(&query).await
679 }
680
681 pub async fn get_security_alert_count_24h(&self) -> Result<u64> {
683 let query = AuditQuery::builder()
684 .event_types(vec![
685 AuditEventType::SuspiciousActivity,
686 AuditEventType::BruteForceDetected,
687 AuditEventType::SecurityViolation,
688 ])
689 .last_24h()
690 .risk_level(RiskLevel::High)
691 .build();
692 self.storage.count_events(&query).await
693 }
694
695 pub async fn get_permission_checks_last_hour(&self) -> Result<u64> {
697 let query = AuditQuery::builder()
698 .event_types(vec![
699 AuditEventType::PermissionGranted,
700 AuditEventType::PermissionDenied,
701 ])
702 .last_seconds(3600)
703 .build();
704 self.storage.count_events(&query).await
705 }
706
707 pub async fn get_permission_audit_logs(
709 &self,
710 user_id: Option<&str>,
711 action: Option<&str>,
712 resource: Option<&str>,
713 limit: Option<usize>,
714 ) -> Result<Vec<String>> {
715 let mut builder = AuditQuery::builder().event_types(vec![
716 AuditEventType::PermissionGranted,
717 AuditEventType::PermissionDenied,
718 AuditEventType::RoleAssigned,
719 AuditEventType::RoleRevoked,
720 AuditEventType::RoleCreated,
721 AuditEventType::RoleUpdated,
722 AuditEventType::RoleDeleted,
723 ]);
724 if let Some(uid) = user_id {
725 builder = builder.user_id(uid);
726 }
727 if let Some(rt) = resource {
728 builder = builder.resource_type(rt);
729 }
730 if let Some(l) = limit {
731 builder = builder.limit(l as u64);
732 }
733 let query = builder.build();
734
735 let events = self.storage.query_events(&query).await?;
736
737 let logs = events
738 .into_iter()
739 .filter(|e| {
740 action.is_none_or(|a| {
741 e.description.to_lowercase().contains(&a.to_lowercase())
742 || e.details
743 .values()
744 .any(|v| v.to_lowercase().contains(&a.to_lowercase()))
745 })
746 })
747 .map(|e| {
748 let ts = e
749 .timestamp
750 .duration_since(std::time::UNIX_EPOCH)
751 .map(|d| {
752 chrono::Utc
753 .timestamp_opt(d.as_secs() as i64, 0)
754 .single()
755 .map(|dt| dt.format("%Y-%m-%dT%H:%M:%SZ").to_string())
756 .unwrap_or_else(|| "unknown-time".to_string())
757 })
758 .unwrap_or_else(|_| "unknown-time".to_string());
759 let uid = e.user_id.as_deref().unwrap_or("system");
760 format!(
761 "[{}] {} user={} outcome={} - {}",
762 ts, e.event_type, uid, e.outcome, e.description
763 )
764 })
765 .collect();
766
767 Ok(logs)
768 }
769
770 pub async fn get_security_audit_stats(
775 &self,
776 active_sessions: u64,
777 ) -> Result<SecurityAuditStats> {
778 let failed_logins_24h = self.get_failed_login_count_24h().await.unwrap_or(0);
779 let successful_logins_24h = self
780 .get_successful_login_count_24h()
781 .await
782 .unwrap_or(active_sessions * 2);
783 let token_issued_24h = self
784 .get_token_issued_count_24h()
785 .await
786 .unwrap_or(active_sessions * 3);
787 let unique_users_24h = self
788 .get_unique_users_24h()
789 .await
790 .unwrap_or((successful_logins_24h as f64 * 0.7) as u64);
791 let password_resets_24h = self.get_password_reset_count_24h().await.unwrap_or(0);
792 let admin_actions_24h = self.get_admin_action_count_24h().await.unwrap_or(0);
793 let security_alerts_24h = self.get_security_alert_count_24h().await.unwrap_or(0);
794
795 Ok(SecurityAuditStats {
796 active_sessions,
797 failed_logins_24h,
798 successful_logins_24h,
799 unique_users_24h,
800 token_issued_24h,
801 password_resets_24h,
802 admin_actions_24h,
803 security_alerts_24h,
804 collection_timestamp: chrono::Utc::now(),
805 })
806 }
807
808 pub async fn log_auth_trace_event(
812 &self,
813 event_type: &str,
814 user_id: &str,
815 method: &str,
816 client_ip: &str,
817 user_agent: &str,
818 ) {
819 tracing::info!(
820 target: "auth_audit",
821 event_type = event_type,
822 user_id = user_id,
823 method = method,
824 client_ip = client_ip,
825 user_agent = user_agent,
826 timestamp = %chrono::Utc::now().to_rfc3339(),
827 "Authentication event"
828 );
829 }
830
831 pub async fn cleanup_old_events(&self, retention_days: u32) -> Result<u64> {
833 let cutoff_time =
834 SystemTime::now() - std::time::Duration::from_secs(retention_days as u64 * 86400);
835 self.storage.delete_old_events(cutoff_time).await
836 }
837}
838
839#[derive(Debug, Clone, Serialize, Deserialize)]
843pub struct SecurityAuditStats {
844 pub active_sessions: u64,
845 pub failed_logins_24h: u64,
846 pub successful_logins_24h: u64,
847 pub unique_users_24h: u64,
848 pub token_issued_24h: u64,
849 pub password_resets_24h: u64,
850 pub admin_actions_24h: u64,
851 pub security_alerts_24h: u64,
852 pub collection_timestamp: chrono::DateTime<chrono::Utc>,
853}
854
855impl SecurityAuditStats {
856 pub fn security_score(&self) -> f64 {
859 let mut score = 1.0_f64;
860
861 if self.successful_logins_24h > 0 {
862 let failure_rate = self.failed_logins_24h as f64
863 / (self.successful_logins_24h + self.failed_logins_24h) as f64;
864 if failure_rate > 0.1 {
865 score -= failure_rate * 0.3;
866 }
867 }
868
869 if self.security_alerts_24h > 0 {
870 score -= (self.security_alerts_24h as f64 * 0.1).min(0.4);
871 }
872
873 if self.successful_logins_24h > 0 && self.failed_logins_24h < 10 {
874 score += 0.05;
875 }
876
877 score.clamp(0.0, 1.0)
878 }
879
880 pub fn requires_immediate_attention(&self) -> bool {
894 self.failed_logins_24h > 100 || self.security_alerts_24h > 5 || self.security_score() < 0.3
895 }
896
897 pub fn security_alert_message(&self) -> Option<String> {
912 if !self.requires_immediate_attention() {
913 return None;
914 }
915
916 let mut alerts = Vec::new();
917
918 if self.failed_logins_24h > 100 {
919 alerts.push(format!(
920 "High failed login attempts: {}",
921 self.failed_logins_24h
922 ));
923 }
924 if self.security_alerts_24h > 5 {
925 alerts.push(format!(
926 "Multiple security alerts: {}",
927 self.security_alerts_24h
928 ));
929 }
930 if self.security_score() < 0.3 {
931 alerts.push(format!(
932 "Critical security score: {:.2}",
933 self.security_score()
934 ));
935 }
936
937 Some(format!(
938 "🚨 SECURITY ATTENTION REQUIRED: {}",
939 alerts.join(", ")
940 ))
941 }
942}
943
944pub struct CorrelationIdGenerator {
946 counter: std::sync::atomic::AtomicU64,
947}
948
949impl CorrelationIdGenerator {
950 pub fn new() -> Self {
951 Self {
952 counter: std::sync::atomic::AtomicU64::new(0),
953 }
954 }
955
956 pub fn generate(&self) -> String {
957 let count = self
958 .counter
959 .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
960 format!(
961 "corr_{:016x}_{}",
962 SystemTime::now()
963 .duration_since(SystemTime::UNIX_EPOCH)
964 .unwrap_or_default()
965 .as_secs(),
966 count
967 )
968 }
969}
970
971pub struct AuditEventBuilder {
995 event: AuditEvent,
996}
997
998impl AuditEvent {
999 pub fn builder(
1001 event_type: AuditEventType,
1002 description: impl Into<String>,
1003 ) -> AuditEventBuilder {
1004 AuditEventBuilder::new(event_type, description)
1005 }
1006}
1007
1008impl AuditEventBuilder {
1009 pub fn new(event_type: AuditEventType, description: impl Into<String>) -> Self {
1011 Self {
1012 event: AuditEvent {
1013 id: String::new(),
1014 event_type,
1015 timestamp: SystemTime::UNIX_EPOCH,
1016 user_id: None,
1017 session_id: None,
1018 outcome: EventOutcome::Unknown,
1019 risk_level: RiskLevel::Low,
1020 description: description.into(),
1021 details: HashMap::new(),
1022 request_metadata: RequestMetadata::new(),
1023 resource: None,
1024 actor: ActorInfo {
1025 actor_type: "unknown".to_string(),
1026 actor_id: String::new(),
1027 actor_name: None,
1028 roles: Vec::new(),
1029 },
1030 correlation_id: None,
1031 },
1032 }
1033 }
1034
1035 pub fn user_id(mut self, id: impl Into<String>) -> Self {
1037 self.event.user_id = Some(id.into());
1038 self
1039 }
1040
1041 pub fn session_id(mut self, id: impl Into<String>) -> Self {
1043 self.event.session_id = Some(id.into());
1044 self
1045 }
1046
1047 pub fn outcome(mut self, outcome: EventOutcome) -> Self {
1049 self.event.outcome = outcome;
1050 self
1051 }
1052
1053 pub fn risk_level(mut self, level: RiskLevel) -> Self {
1055 self.event.risk_level = level;
1056 self
1057 }
1058
1059 pub fn with_actor(
1061 mut self,
1062 actor_type: impl Into<String>,
1063 actor_id: impl Into<String>,
1064 ) -> Self {
1065 self.event.actor = ActorInfo {
1066 actor_type: actor_type.into(),
1067 actor_id: actor_id.into(),
1068 actor_name: None,
1069 roles: Vec::new(),
1070 };
1071 self
1072 }
1073
1074 pub fn actor(mut self, actor: ActorInfo) -> Self {
1076 self.event.actor = actor;
1077 self
1078 }
1079
1080 pub fn request_metadata(mut self, metadata: RequestMetadata) -> Self {
1082 self.event.request_metadata = metadata;
1083 self
1084 }
1085
1086 pub fn resource(mut self, resource: ResourceInfo) -> Self {
1088 self.event.resource = Some(resource);
1089 self
1090 }
1091
1092 pub fn correlation_id(mut self, id: impl Into<String>) -> Self {
1094 self.event.correlation_id = Some(id.into());
1095 self
1096 }
1097
1098 pub fn detail(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
1100 self.event.details.insert(key.into(), value.into());
1101 self
1102 }
1103
1104 pub fn details(mut self, details: HashMap<String, String>) -> Self {
1106 self.event.details = details;
1107 self
1108 }
1109
1110 pub fn build(mut self) -> AuditEvent {
1115 if self.event.id.is_empty() {
1116 self.event.id = uuid::Uuid::new_v4().to_string();
1117 }
1118 if self.event.timestamp == SystemTime::UNIX_EPOCH {
1119 self.event.timestamp = SystemTime::now();
1120 }
1121 self.event
1122 }
1123}
1124
1125impl Default for AuditQuery {
1128 fn default() -> Self {
1129 Self {
1130 event_types: None,
1131 user_id: None,
1132 risk_level: None,
1133 outcome: None,
1134 time_range: None,
1135 ip_address: None,
1136 resource_type: None,
1137 actor_id: None,
1138 correlation_id: None,
1139 limit: None,
1140 offset: None,
1141 sort_order: SortOrder::TimestampDesc,
1142 }
1143 }
1144}
1145
1146pub struct AuditQueryBuilder {
1164 query: AuditQuery,
1165}
1166
1167impl AuditQuery {
1168 pub fn builder() -> AuditQueryBuilder {
1170 AuditQueryBuilder {
1171 query: AuditQuery::default(),
1172 }
1173 }
1174}
1175
1176impl AuditQueryBuilder {
1177 pub fn event_types(mut self, types: Vec<AuditEventType>) -> Self {
1179 self.query.event_types = Some(types);
1180 self
1181 }
1182
1183 pub fn user_id(mut self, id: impl Into<String>) -> Self {
1185 self.query.user_id = Some(id.into());
1186 self
1187 }
1188
1189 pub fn risk_level(mut self, level: RiskLevel) -> Self {
1191 self.query.risk_level = Some(level);
1192 self
1193 }
1194
1195 pub fn outcome(mut self, outcome: EventOutcome) -> Self {
1197 self.query.outcome = Some(outcome);
1198 self
1199 }
1200
1201 pub fn time_range(mut self, start: SystemTime, end: SystemTime) -> Self {
1203 self.query.time_range = Some(TimeRange { start, end });
1204 self
1205 }
1206
1207 pub fn last_seconds(mut self, seconds: u64) -> Self {
1209 self.query.time_range = Some(TimeRange {
1210 start: SystemTime::now() - std::time::Duration::from_secs(seconds),
1211 end: SystemTime::now(),
1212 });
1213 self
1214 }
1215
1216 pub fn last_24h(self) -> Self {
1218 self.last_seconds(24 * 60 * 60)
1219 }
1220
1221 pub fn ip_address(mut self, ip: impl Into<String>) -> Self {
1223 self.query.ip_address = Some(ip.into());
1224 self
1225 }
1226
1227 pub fn resource_type(mut self, rt: impl Into<String>) -> Self {
1229 self.query.resource_type = Some(rt.into());
1230 self
1231 }
1232
1233 pub fn actor_id(mut self, id: impl Into<String>) -> Self {
1235 self.query.actor_id = Some(id.into());
1236 self
1237 }
1238
1239 pub fn correlation_id(mut self, id: impl Into<String>) -> Self {
1241 self.query.correlation_id = Some(id.into());
1242 self
1243 }
1244
1245 pub fn limit(mut self, limit: u64) -> Self {
1247 self.query.limit = Some(limit);
1248 self
1249 }
1250
1251 pub fn offset(mut self, offset: u64) -> Self {
1253 self.query.offset = Some(offset);
1254 self
1255 }
1256
1257 pub fn sort_order(mut self, order: SortOrder) -> Self {
1259 self.query.sort_order = order;
1260 self
1261 }
1262
1263 pub fn build(self) -> AuditQuery {
1265 self.query
1266 }
1267}
1268
1269impl RequestMetadata {
1271 pub fn new() -> Self {
1272 Self {
1273 ip_address: None,
1274 user_agent: None,
1275 request_id: None,
1276 endpoint: None,
1277 http_method: None,
1278 geolocation: None,
1279 device_info: None,
1280 }
1281 }
1282
1283 pub fn with_ip(mut self, ip: impl Into<String>) -> Self {
1284 self.ip_address = Some(ip.into());
1285 self
1286 }
1287
1288 pub fn with_user_agent(mut self, user_agent: impl Into<String>) -> Self {
1289 self.user_agent = Some(user_agent.into());
1290 self
1291 }
1292
1293 pub fn with_endpoint(mut self, endpoint: impl Into<String>) -> Self {
1294 self.endpoint = Some(endpoint.into());
1295 self
1296 }
1297}
1298
1299impl Default for RequestMetadata {
1300 fn default() -> Self {
1301 Self::new()
1302 }
1303}
1304
1305#[cfg(test)]
1306mod tests {
1307 use super::*;
1308
1309 #[test]
1310 fn test_correlation_id_generation() {
1311 let generator = CorrelationIdGenerator::new();
1312 let id1 = generator.generate();
1313 let id2 = generator.generate();
1314
1315 assert_ne!(id1, id2);
1316 assert!(id1.starts_with("corr_"));
1317 assert!(id2.starts_with("corr_"));
1318 }
1319
1320 #[test]
1321 fn test_request_metadata_builder() {
1322 let metadata = RequestMetadata::new()
1323 .with_ip("192.168.1.1")
1324 .with_user_agent("Mozilla/5.0")
1325 .with_endpoint("/api/auth/login");
1326
1327 assert_eq!(metadata.ip_address, Some("192.168.1.1".to_string()));
1328 assert_eq!(metadata.user_agent, Some("Mozilla/5.0".to_string()));
1329 assert_eq!(metadata.endpoint, Some("/api/auth/login".to_string()));
1330 }
1331
1332 #[test]
1333 fn test_audit_event_builder_minimal() {
1334 let event = AuditEvent::builder(AuditEventType::LoginSuccess, "User logged in").build();
1335 assert_eq!(event.event_type, AuditEventType::LoginSuccess);
1336 assert_eq!(event.description, "User logged in");
1337 assert!(!event.id.is_empty(), "id should be auto-generated");
1338 assert_ne!(
1339 event.timestamp,
1340 SystemTime::UNIX_EPOCH,
1341 "timestamp should be auto-set"
1342 );
1343 assert_eq!(event.outcome, EventOutcome::Unknown);
1344 assert_eq!(event.risk_level, RiskLevel::Low);
1345 }
1346
1347 #[test]
1348 fn test_audit_event_builder_full() {
1349 let event = AuditEvent::builder(AuditEventType::PermissionDenied, "Access denied")
1350 .user_id("u123")
1351 .session_id("s456")
1352 .outcome(EventOutcome::Failure)
1353 .risk_level(RiskLevel::High)
1354 .with_actor("user", "u123")
1355 .detail("resource", "admin_panel")
1356 .correlation_id("corr_xyz")
1357 .build();
1358
1359 assert_eq!(event.user_id, Some("u123".to_string()));
1360 assert_eq!(event.session_id, Some("s456".to_string()));
1361 assert_eq!(event.outcome, EventOutcome::Failure);
1362 assert_eq!(event.risk_level, RiskLevel::High);
1363 assert_eq!(event.actor.actor_type, "user");
1364 assert_eq!(event.actor.actor_id, "u123");
1365 assert_eq!(
1366 event.details.get("resource"),
1367 Some(&"admin_panel".to_string())
1368 );
1369 assert_eq!(event.correlation_id, Some("corr_xyz".to_string()));
1370 }
1371
1372 #[test]
1373 fn test_audit_query_builder() {
1374 let query = AuditQuery::builder()
1375 .event_types(vec![AuditEventType::LoginFailure])
1376 .limit(50)
1377 .offset(10)
1378 .build();
1379
1380 assert_eq!(query.event_types, Some(vec![AuditEventType::LoginFailure]));
1381 assert_eq!(query.limit, Some(50));
1382 assert_eq!(query.offset, Some(10));
1383 assert!(query.user_id.is_none());
1384 }
1385
1386 #[test]
1387 fn test_audit_query_default() {
1388 let query = AuditQuery::default();
1389 assert!(query.event_types.is_none());
1390 assert!(query.user_id.is_none());
1391 assert!(query.limit.is_none());
1392 assert!(matches!(query.sort_order, SortOrder::TimestampDesc));
1393 }
1394
1395 #[test]
1396 fn test_audit_query_last_24h() {
1397 let query = AuditQuery::builder().last_24h().build();
1398 assert!(query.time_range.is_some());
1399 let range = query.time_range.unwrap();
1400 let elapsed = range.end.duration_since(range.start).unwrap();
1401 assert!(elapsed.as_secs() >= 86399 && elapsed.as_secs() <= 86401);
1403 }
1404
1405 #[test]
1406 fn test_audit_query_last_seconds() {
1407 let query = AuditQuery::builder().last_seconds(3600).build();
1408 assert!(query.time_range.is_some());
1409 let range = query.time_range.unwrap();
1410 let elapsed = range.end.duration_since(range.start).unwrap();
1411 assert!(elapsed.as_secs() >= 3599 && elapsed.as_secs() <= 3601);
1412 }
1413
1414 #[test]
1415 fn test_audit_event_type_display() {
1416 assert_eq!(AuditEventType::LoginSuccess.to_string(), "login_success");
1417 assert_eq!(AuditEventType::LoginFailure.to_string(), "login_failure");
1418 assert_eq!(AuditEventType::Logout.to_string(), "logout");
1419 assert_eq!(AuditEventType::TokenRefresh.to_string(), "token_refresh");
1420 assert_eq!(
1421 AuditEventType::MfaVerificationSuccess.to_string(),
1422 "mfa_verification_success"
1423 );
1424 assert_eq!(
1425 AuditEventType::PermissionGranted.to_string(),
1426 "permission_granted"
1427 );
1428 assert_eq!(
1429 AuditEventType::PermissionDenied.to_string(),
1430 "permission_denied"
1431 );
1432 assert_eq!(AuditEventType::RoleAssigned.to_string(), "role_assigned");
1433 assert_eq!(AuditEventType::UserCreated.to_string(), "user_created");
1434 assert_eq!(AuditEventType::AccountLocked.to_string(), "account_locked");
1435 assert_eq!(
1436 AuditEventType::BruteForceDetected.to_string(),
1437 "brute_force_detected"
1438 );
1439 assert_eq!(AuditEventType::AdminAction.to_string(), "admin_action");
1440 assert_eq!(AuditEventType::SystemStartup.to_string(), "system_startup");
1441 assert_eq!(AuditEventType::DataExported.to_string(), "data_exported");
1442 }
1443
1444 #[test]
1445 fn test_risk_level_display() {
1446 assert_eq!(RiskLevel::Low.to_string(), "low");
1447 assert_eq!(RiskLevel::Medium.to_string(), "medium");
1448 assert_eq!(RiskLevel::High.to_string(), "high");
1449 assert_eq!(RiskLevel::Critical.to_string(), "critical");
1450 }
1451
1452 #[test]
1453 fn test_event_outcome_display() {
1454 assert_eq!(EventOutcome::Success.to_string(), "success");
1455 assert_eq!(EventOutcome::Failure.to_string(), "failure");
1456 assert_eq!(EventOutcome::Partial.to_string(), "partial");
1457 assert_eq!(EventOutcome::Unknown.to_string(), "unknown");
1458 }
1459}