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