allsource-core 0.19.1

High-performance event store core built in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
/// ML-Based Anomaly Detection System
///
/// Detects suspicious patterns in audit logs using statistical analysis
/// and machine learning techniques to identify:
/// - Unusual access patterns
/// - Brute force attacks
/// - Privilege escalation attempts
/// - Data exfiltration patterns
/// - Account compromise indicators
use crate::domain::entities::{AuditAction, AuditEvent, AuditOutcome};
use crate::error::Result;
use chrono::{DateTime, Duration, Timelike, Utc};
use dashmap::DashMap;
use parking_lot::RwLock;
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, sync::Arc};

/// Anomaly detection configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnomalyDetectionConfig {
    /// Enable anomaly detection
    pub enabled: bool,

    /// Sensitivity level (0.0 = very lenient, 1.0 = very strict)
    pub sensitivity: f64,

    /// Minimum events required for baseline
    pub min_baseline_events: usize,

    /// Time window for analysis (hours)
    pub analysis_window_hours: i64,

    /// Enable specific detectors
    pub enable_brute_force_detection: bool,
    pub enable_unusual_access_detection: bool,
    pub enable_privilege_escalation_detection: bool,
    pub enable_data_exfiltration_detection: bool,
    pub enable_velocity_detection: bool,
}

impl Default for AnomalyDetectionConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            sensitivity: 0.7,
            min_baseline_events: 100,
            analysis_window_hours: 24,
            enable_brute_force_detection: true,
            enable_unusual_access_detection: true,
            enable_privilege_escalation_detection: true,
            enable_data_exfiltration_detection: true,
            enable_velocity_detection: true,
        }
    }
}

/// Anomaly detection result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnomalyResult {
    /// Is this event anomalous?
    pub is_anomalous: bool,

    /// Anomaly score (0.0 = normal, 1.0 = highly anomalous)
    pub score: f64,

    /// Type of anomaly detected
    pub anomaly_type: Option<AnomalyType>,

    /// Detailed reason
    pub reason: String,

    /// Recommended action
    pub recommended_action: RecommendedAction,

    /// Contributing factors
    pub factors: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum AnomalyType {
    BruteForceAttack,
    UnusualAccessPattern,
    PrivilegeEscalation,
    DataExfiltration,
    VelocityAnomaly,
    AccountCompromise,
    SuspiciousActivity,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum RecommendedAction {
    Monitor,      // Continue monitoring
    Alert,        // Send alert to security team
    Block,        // Block the action
    RequireMFA,   // Require additional authentication
    RevokeAccess, // Immediately revoke access
}

/// User behavior profile for baseline comparison
#[derive(Debug, Clone, Serialize, Deserialize)]
struct UserProfile {
    user_id: String,
    tenant_id: String,

    // Activity patterns
    typical_hours: Vec<u32>, // Hours of day when user is typically active
    typical_actions: HashMap<AuditAction, usize>, // Action frequency
    typical_locations: Vec<String>, // IP addresses or locations

    // Statistical baselines
    avg_actions_per_hour: f64,
    avg_actions_per_day: f64,
    max_actions_per_hour: usize,

    // Failure rates
    avg_failure_rate: f64,

    // Last updated
    last_updated: DateTime<Utc>,
    event_count: usize,
}

impl UserProfile {
    fn new(user_id: String, tenant_id: String) -> Self {
        Self {
            user_id,
            tenant_id,
            typical_hours: Vec::new(),
            typical_actions: HashMap::new(),
            typical_locations: Vec::new(),
            avg_actions_per_hour: 0.0,
            avg_actions_per_day: 0.0,
            max_actions_per_hour: 0,
            avg_failure_rate: 0.0,
            last_updated: Utc::now(),
            event_count: 0,
        }
    }
}

/// Tenant behavior profile for organizational patterns
#[derive(Debug, Clone, Serialize, Deserialize)]
struct TenantProfile {
    tenant_id: String,

    // Access patterns
    typical_daily_events: f64,
    typical_hourly_events: f64,
    peak_hours: Vec<u32>,

    // User activity
    active_users_per_day: f64,

    // Security metrics
    avg_failure_rate: f64,
    suspicious_event_rate: f64,

    last_updated: DateTime<Utc>,
    event_count: usize,
}

/// ML-based anomaly detector
pub struct AnomalyDetector {
    config: Arc<RwLock<AnomalyDetectionConfig>>,

    // Behavior profiles - using DashMap for lock-free concurrent access
    user_profiles: Arc<DashMap<String, UserProfile>>,
    tenant_profiles: Arc<DashMap<String, TenantProfile>>,

    // Recent events for pattern analysis
    recent_events: Arc<RwLock<Vec<AuditEvent>>>,
}

impl AnomalyDetector {
    /// Create new anomaly detector
    pub fn new(config: AnomalyDetectionConfig) -> Self {
        Self {
            config: Arc::new(RwLock::new(config)),
            user_profiles: Arc::new(DashMap::new()),
            tenant_profiles: Arc::new(DashMap::new()),
            recent_events: Arc::new(RwLock::new(Vec::new())),
        }
    }

    /// Analyze an audit event for anomalies
    pub fn analyze_event(&self, event: &AuditEvent) -> Result<AnomalyResult> {
        let config = self.config.read();

        if !config.enabled {
            return Ok(AnomalyResult {
                is_anomalous: false,
                score: 0.0,
                anomaly_type: None,
                reason: "Anomaly detection disabled".to_string(),
                recommended_action: RecommendedAction::Monitor,
                factors: vec![],
            });
        }

        let mut anomaly_scores: Vec<(AnomalyType, f64, Vec<String>)> = Vec::new();

        // Get user ID from actor
        let user_id = match event.actor() {
            crate::domain::entities::Actor::User { user_id, .. } => user_id.clone(),
            crate::domain::entities::Actor::System { .. } => {
                // System actions are typically not anomalous
                return Ok(AnomalyResult {
                    is_anomalous: false,
                    score: 0.0,
                    anomaly_type: None,
                    reason: "System actor".to_string(),
                    recommended_action: RecommendedAction::Monitor,
                    factors: vec![],
                });
            }
            crate::domain::entities::Actor::ApiKey {
                key_id,
                key_name: _,
            } => key_id.clone(),
        };

        // Check for brute force attacks
        if config.enable_brute_force_detection
            && let Some((score, factors)) = self.detect_brute_force(&user_id, event)?
        {
            anomaly_scores.push((AnomalyType::BruteForceAttack, score, factors));
        }

        // Check for unusual access patterns
        if config.enable_unusual_access_detection
            && let Some((score, factors)) = self.detect_unusual_access(&user_id, event)?
        {
            anomaly_scores.push((AnomalyType::UnusualAccessPattern, score, factors));
        }

        // Check for privilege escalation
        if config.enable_privilege_escalation_detection
            && let Some((score, factors)) = self.detect_privilege_escalation(&user_id, event)?
        {
            anomaly_scores.push((AnomalyType::PrivilegeEscalation, score, factors));
        }

        // Check for data exfiltration
        if config.enable_data_exfiltration_detection
            && let Some((score, factors)) = self.detect_data_exfiltration(&user_id, event)?
        {
            anomaly_scores.push((AnomalyType::DataExfiltration, score, factors));
        }

        // Check for velocity anomalies
        if config.enable_velocity_detection
            && let Some((score, factors)) = self.detect_velocity_anomaly(&user_id, event)?
        {
            anomaly_scores.push((AnomalyType::VelocityAnomaly, score, factors));
        }

        // Store event for future analysis
        self.add_recent_event(event.clone());

        // Calculate overall anomaly score (max of all detectors)
        let (max_anomaly_type, max_score, all_factors) = if anomaly_scores.is_empty() {
            (None, 0.0, vec![])
        } else {
            let max_entry = anomaly_scores
                .iter()
                .max_by(|a, b| a.1.partial_cmp(&b.1).unwrap())
                .unwrap();
            let all_factors: Vec<String> = anomaly_scores
                .iter()
                .flat_map(|(_, _, f)| f.clone())
                .collect();
            (Some(max_entry.0.clone()), max_entry.1, all_factors)
        };

        let is_anomalous = max_score >= config.sensitivity;

        let recommended_action = if max_score >= 0.9 {
            RecommendedAction::RevokeAccess
        } else if max_score >= 0.8 {
            RecommendedAction::Block
        } else if max_score >= 0.7 {
            RecommendedAction::RequireMFA
        } else if max_score >= 0.5 {
            RecommendedAction::Alert
        } else {
            RecommendedAction::Monitor
        };

        let reason = if is_anomalous {
            format!(
                "Anomalous {:?} detected with score {:.2}",
                max_anomaly_type.as_ref().unwrap(),
                max_score
            )
        } else {
            "Normal behavior".to_string()
        };

        Ok(AnomalyResult {
            is_anomalous,
            score: max_score,
            anomaly_type: max_anomaly_type,
            reason,
            recommended_action,
            factors: all_factors,
        })
    }

    /// Update user profile with new event
    pub fn update_profile(&self, event: &AuditEvent) -> Result<()> {
        let user_id = match event.actor() {
            crate::domain::entities::Actor::User { user_id, .. } => user_id.clone(),
            crate::domain::entities::Actor::ApiKey {
                key_id,
                key_name: _,
            } => key_id.clone(),
            crate::domain::entities::Actor::System { .. } => return Ok(()),
        };

        let profile_key = format!("{}-{user_id}", event.tenant_id().as_str());
        let mut profile = self.user_profiles.entry(profile_key).or_insert_with(|| {
            UserProfile::new(user_id.clone(), event.tenant_id().as_str().to_string())
        });

        // Update activity patterns
        let hour = event.timestamp().hour();
        if !profile.typical_hours.contains(&hour) {
            profile.typical_hours.push(hour);
        }

        // Update action frequency
        *profile
            .typical_actions
            .entry(event.action().clone())
            .or_insert(0) += 1;

        // Update statistics
        profile.event_count += 1;
        profile.last_updated = Utc::now();

        // Recalculate averages (simple moving average)
        let events_in_window = profile.event_count.min(1000);
        profile.avg_actions_per_hour = events_in_window as f64 / 24.0;

        Ok(())
    }

    // === Detection Methods ===

    fn detect_brute_force(
        &self,
        user_id: &str,
        event: &AuditEvent,
    ) -> Result<Option<(f64, Vec<String>)>> {
        // Detect multiple failed login attempts
        if event.action() != &AuditAction::Login {
            return Ok(None);
        }

        let recent = self.recent_events.read();
        let mut recent_failures = recent
            .iter()
            .filter(|e| {
                if let crate::domain::entities::Actor::User { user_id: uid, .. } = e.actor() {
                    uid == user_id
                        && e.action() == &AuditAction::Login
                        && e.outcome() == &AuditOutcome::Failure
                        && (Utc::now() - e.timestamp()) < Duration::minutes(15)
                } else {
                    false
                }
            })
            .count();

        // Include current event if it's also a failure
        if event.outcome() == &AuditOutcome::Failure {
            recent_failures += 1;
        }

        if recent_failures >= 5 {
            let score = (recent_failures as f64 / 10.0).min(1.0);
            let factors = vec![format!(
                "{} failed login attempts in 15 minutes",
                recent_failures
            )];
            return Ok(Some((score, factors)));
        }

        Ok(None)
    }

    fn detect_unusual_access(
        &self,
        user_id: &str,
        event: &AuditEvent,
    ) -> Result<Option<(f64, Vec<String>)>> {
        let profile_key = format!("{}-{user_id}", event.tenant_id().as_str());

        if let Some(profile_ref) = self.user_profiles.get(&profile_key) {
            let profile = profile_ref.value();
            if profile.event_count < self.config.read().min_baseline_events {
                return Ok(None); // Not enough data for baseline
            }

            let mut factors = Vec::new();
            let mut anomaly_indicators = 0;

            // Check if access is outside typical hours
            let hour = event.timestamp().hour();
            if !profile.typical_hours.is_empty() && !profile.typical_hours.contains(&hour) {
                factors.push(format!("Access at unusual hour: {hour}:00"));
                anomaly_indicators += 1;
            }

            // Check if action is unusual for this user
            let action_count = profile
                .typical_actions
                .get(event.action())
                .copied()
                .unwrap_or(0);
            if action_count == 0 && profile.event_count > 50 {
                factors.push(format!("First time performing {:?}", event.action()));
                anomaly_indicators += 1;
            }

            if anomaly_indicators > 0 {
                let score = (f64::from(anomaly_indicators) / 2.0).min(1.0);
                return Ok(Some((score, factors)));
            }
        }

        Ok(None)
    }

    fn detect_privilege_escalation(
        &self,
        user_id: &str,
        event: &AuditEvent,
    ) -> Result<Option<(f64, Vec<String>)>> {
        // Detect attempts to gain unauthorized privileges
        let sensitive_actions = [AuditAction::TenantUpdated, AuditAction::RoleChanged];

        if sensitive_actions.contains(event.action()) && event.outcome() == &AuditOutcome::Failure {
            let recent = self.recent_events.read();
            let recent_privilege_attempts = recent
                .iter()
                .filter(|e| {
                    if let crate::domain::entities::Actor::User { user_id: uid, .. } = e.actor() {
                        uid == user_id
                            && sensitive_actions.contains(e.action())
                            && (Utc::now() - e.timestamp()) < Duration::hours(1)
                    } else {
                        false
                    }
                })
                .count();

            if recent_privilege_attempts >= 3 {
                let score = 0.8;
                let factors = vec![
                    format!(
                        "{} privilege escalation attempts in 1 hour",
                        recent_privilege_attempts
                    ),
                    format!("Latest action: {:?}", event.action()),
                ];
                return Ok(Some((score, factors)));
            }
        }

        Ok(None)
    }

    fn detect_data_exfiltration(
        &self,
        user_id: &str,
        event: &AuditEvent,
    ) -> Result<Option<(f64, Vec<String>)>> {
        // Detect unusual data access patterns that might indicate exfiltration
        if event.action() != &AuditAction::EventQueried {
            return Ok(None);
        }

        let recent = self.recent_events.read();
        let recent_queries = recent
            .iter()
            .filter(|e| {
                if let crate::domain::entities::Actor::User { user_id: uid, .. } = e.actor() {
                    uid == user_id
                        && e.action() == &AuditAction::EventQueried
                        && (Utc::now() - e.timestamp()) < Duration::hours(1)
                } else {
                    false
                }
            })
            .count();

        // Check user profile for baseline
        let profile_key = format!("{}-{user_id}", event.tenant_id().as_str());

        if let Some(profile_ref) = self.user_profiles.get(&profile_key) {
            let profile = profile_ref.value();
            if profile.event_count >= self.config.read().min_baseline_events {
                // If current query rate is 5x normal, flag as anomalous
                if recent_queries as f64 > profile.avg_actions_per_hour * 5.0 {
                    let score = 0.75;
                    let factors = vec![
                        format!(
                            "{} queries in 1 hour (baseline: {:.0})",
                            recent_queries, profile.avg_actions_per_hour
                        ),
                        "Potential data exfiltration pattern".to_string(),
                    ];
                    return Ok(Some((score, factors)));
                }
            }
        }

        Ok(None)
    }

    fn detect_velocity_anomaly(
        &self,
        user_id: &str,
        event: &AuditEvent,
    ) -> Result<Option<(f64, Vec<String>)>> {
        // Detect impossibly fast actions (e.g., actions from different locations in short time)
        let recent = self.recent_events.read();
        let very_recent = recent
            .iter()
            .filter(|e| {
                if let crate::domain::entities::Actor::User { user_id: uid, .. } = e.actor() {
                    uid == user_id && (Utc::now() - e.timestamp()) < Duration::seconds(10)
                } else {
                    false
                }
            })
            .count();

        // More than 20 actions in 10 seconds is suspicious
        if very_recent >= 20 {
            let score = 0.7;
            let factors = vec![
                format!("{very_recent} actions in 10 seconds"),
                "Potential automated attack or compromised credentials".to_string(),
            ];
            return Ok(Some((score, factors)));
        }

        Ok(None)
    }

    pub fn add_recent_event(&self, event: AuditEvent) {
        let mut events = self.recent_events.write();
        events.push(event);

        // Keep only recent events (last 24 hours)
        let cutoff = Utc::now() - Duration::hours(24);
        events.retain(|e| e.timestamp() > &cutoff);

        // Limit size to prevent memory issues
        if events.len() > 10000 {
            events.drain(0..1000);
        }
    }

    /// Get statistics about detection
    pub fn get_stats(&self) -> DetectionStats {
        let recent = self.recent_events.read();

        DetectionStats {
            user_profiles_count: self.user_profiles.len(),
            recent_events_count: recent.len(),
            config: self.config.read().clone(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DetectionStats {
    pub user_profiles_count: usize,
    pub recent_events_count: usize,
    pub config: AnomalyDetectionConfig,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::domain::{entities::Actor, value_objects::TenantId};

    fn create_test_event(action: AuditAction, outcome: AuditOutcome, user_id: &str) -> AuditEvent {
        let tenant_id = TenantId::new("test-tenant".to_string()).unwrap();
        let actor = Actor::User {
            user_id: user_id.to_string(),
            username: "testuser".to_string(),
        };
        AuditEvent::new(tenant_id, action, actor, outcome)
    }

    fn create_system_event(action: AuditAction, outcome: AuditOutcome) -> AuditEvent {
        let tenant_id = TenantId::new("test-tenant".to_string()).unwrap();
        let actor = Actor::System {
            component: "test-service".to_string(),
        };
        AuditEvent::new(tenant_id, action, actor, outcome)
    }

    fn create_api_key_event(action: AuditAction, outcome: AuditOutcome) -> AuditEvent {
        let tenant_id = TenantId::new("test-tenant".to_string()).unwrap();
        let actor = Actor::ApiKey {
            key_id: "key-123".to_string(),
            key_name: "test-key".to_string(),
        };
        AuditEvent::new(tenant_id, action, actor, outcome)
    }

    #[test]
    fn test_anomaly_detector_creation() {
        let detector = AnomalyDetector::new(AnomalyDetectionConfig::default());
        let stats = detector.get_stats();
        assert_eq!(stats.user_profiles_count, 0);
        assert_eq!(stats.recent_events_count, 0);
    }

    #[test]
    fn test_normal_behavior_not_flagged() {
        let detector = AnomalyDetector::new(AnomalyDetectionConfig::default());
        let event = create_test_event(AuditAction::EventQueried, AuditOutcome::Success, "user1");

        let result = detector.analyze_event(&event).unwrap();
        assert!(!result.is_anomalous);
        assert_eq!(result.recommended_action, RecommendedAction::Monitor);
    }

    #[test]
    fn test_brute_force_detection() {
        let detector = AnomalyDetector::new(AnomalyDetectionConfig::default());

        // Simulate 6 failed login attempts
        for _ in 0..6 {
            let event = create_test_event(AuditAction::Login, AuditOutcome::Failure, "user1");
            detector.add_recent_event(event.clone());
        }

        // Next login attempt should be flagged
        let event = create_test_event(AuditAction::Login, AuditOutcome::Failure, "user1");
        let result = detector.analyze_event(&event).unwrap();

        assert!(result.is_anomalous);
        assert_eq!(result.anomaly_type, Some(AnomalyType::BruteForceAttack));
        assert!(result.score >= 0.5);
    }

    #[test]
    fn test_profile_building() {
        let detector = AnomalyDetector::new(AnomalyDetectionConfig::default());
        let event = create_test_event(AuditAction::EventQueried, AuditOutcome::Success, "user1");

        detector.update_profile(&event).unwrap();

        let stats = detector.get_stats();
        assert_eq!(stats.user_profiles_count, 1);
    }

    #[test]
    fn test_velocity_anomaly() {
        let detector = AnomalyDetector::new(AnomalyDetectionConfig::default());

        // Simulate 25 actions in rapid succession
        for _ in 0..25 {
            let event =
                create_test_event(AuditAction::EventQueried, AuditOutcome::Success, "user1");
            detector.add_recent_event(event.clone());
        }

        let event = create_test_event(AuditAction::EventQueried, AuditOutcome::Success, "user1");
        let result = detector.analyze_event(&event).unwrap();

        assert!(result.is_anomalous);
        assert_eq!(result.anomaly_type, Some(AnomalyType::VelocityAnomaly));
    }

    #[test]
    fn test_disabled_detection() {
        let config = AnomalyDetectionConfig {
            enabled: false,
            ..Default::default()
        };

        let detector = AnomalyDetector::new(config);
        let event = create_test_event(AuditAction::Login, AuditOutcome::Failure, "user1");

        let result = detector.analyze_event(&event).unwrap();
        assert!(!result.is_anomalous);
    }

    #[test]
    fn test_default_config() {
        let config = AnomalyDetectionConfig::default();
        assert!(config.enabled);
        assert_eq!(config.sensitivity, 0.7);
        assert_eq!(config.min_baseline_events, 100);
        assert_eq!(config.analysis_window_hours, 24);
        assert!(config.enable_brute_force_detection);
        assert!(config.enable_unusual_access_detection);
        assert!(config.enable_privilege_escalation_detection);
        assert!(config.enable_data_exfiltration_detection);
        assert!(config.enable_velocity_detection);
    }

    #[test]
    fn test_config_serde() {
        let config = AnomalyDetectionConfig::default();
        let json = serde_json::to_string(&config).unwrap();
        let parsed: AnomalyDetectionConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.enabled, config.enabled);
        assert_eq!(parsed.sensitivity, config.sensitivity);
    }

    #[test]
    fn test_anomaly_type_equality() {
        assert_eq!(AnomalyType::BruteForceAttack, AnomalyType::BruteForceAttack);
        assert_ne!(AnomalyType::BruteForceAttack, AnomalyType::DataExfiltration);
    }

    #[test]
    fn test_recommended_action_equality() {
        assert_eq!(RecommendedAction::Monitor, RecommendedAction::Monitor);
        assert_ne!(RecommendedAction::Monitor, RecommendedAction::Block);
    }

    #[test]
    fn test_system_actor_not_flagged() {
        let detector = AnomalyDetector::new(AnomalyDetectionConfig::default());
        let event = create_system_event(AuditAction::EventIngested, AuditOutcome::Success);

        let result = detector.analyze_event(&event).unwrap();
        assert!(!result.is_anomalous);
        assert_eq!(result.reason, "System actor");
    }

    #[test]
    fn test_api_key_actor_analyzed() {
        let detector = AnomalyDetector::new(AnomalyDetectionConfig::default());
        let event = create_api_key_event(AuditAction::EventQueried, AuditOutcome::Success);

        let result = detector.analyze_event(&event).unwrap();
        assert!(!result.is_anomalous);
    }

    #[test]
    fn test_update_profile_api_key() {
        let detector = AnomalyDetector::new(AnomalyDetectionConfig::default());
        let event = create_api_key_event(AuditAction::EventQueried, AuditOutcome::Success);

        detector.update_profile(&event).unwrap();

        let stats = detector.get_stats();
        assert_eq!(stats.user_profiles_count, 1);
    }

    #[test]
    fn test_update_profile_system() {
        let detector = AnomalyDetector::new(AnomalyDetectionConfig::default());
        let event = create_system_event(AuditAction::EventIngested, AuditOutcome::Success);

        detector.update_profile(&event).unwrap();

        let stats = detector.get_stats();
        // System events don't create user profiles
        assert_eq!(stats.user_profiles_count, 0);
    }

    #[test]
    fn test_recent_events_pruning() {
        let detector = AnomalyDetector::new(AnomalyDetectionConfig::default());

        // Add more than 10000 events
        for i in 0..10050 {
            let event = create_test_event(
                AuditAction::EventQueried,
                AuditOutcome::Success,
                &format!("user{}", i % 100),
            );
            detector.add_recent_event(event);
        }

        let stats = detector.get_stats();
        // Should be pruned to around 10000
        assert!(stats.recent_events_count <= 10050);
    }

    #[test]
    fn test_detection_stats_serde() {
        let stats = DetectionStats {
            user_profiles_count: 10,
            recent_events_count: 100,
            config: AnomalyDetectionConfig::default(),
        };

        let json = serde_json::to_string(&stats).unwrap();
        assert!(json.contains("\"user_profiles_count\":10"));
        assert!(json.contains("\"recent_events_count\":100"));
    }

    #[test]
    fn test_anomaly_result_serde() {
        let result = AnomalyResult {
            is_anomalous: true,
            score: 0.85,
            anomaly_type: Some(AnomalyType::BruteForceAttack),
            reason: "Test reason".to_string(),
            recommended_action: RecommendedAction::Block,
            factors: vec!["factor1".to_string(), "factor2".to_string()],
        };

        let json = serde_json::to_string(&result).unwrap();
        let parsed: AnomalyResult = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.is_anomalous, result.is_anomalous);
        assert_eq!(parsed.score, result.score);
        assert_eq!(parsed.anomaly_type, result.anomaly_type);
    }

    #[test]
    fn test_recommended_action_for_high_score() {
        let detector = AnomalyDetector::new(AnomalyDetectionConfig::default());

        // Simulate many failed login attempts to get high score
        for _ in 0..15 {
            let event = create_test_event(AuditAction::Login, AuditOutcome::Failure, "user1");
            detector.add_recent_event(event.clone());
        }

        let event = create_test_event(AuditAction::Login, AuditOutcome::Failure, "user1");
        let result = detector.analyze_event(&event).unwrap();

        assert!(result.is_anomalous);
        // With score >= 0.9, should recommend RevokeAccess
        if result.score >= 0.9 {
            assert_eq!(result.recommended_action, RecommendedAction::RevokeAccess);
        } else if result.score >= 0.8 {
            assert_eq!(result.recommended_action, RecommendedAction::Block);
        }
    }

    #[test]
    fn test_successful_login_after_failures() {
        let detector = AnomalyDetector::new(AnomalyDetectionConfig::default());

        // Add some failed logins
        for _ in 0..3 {
            let event = create_test_event(AuditAction::Login, AuditOutcome::Failure, "user1");
            detector.add_recent_event(event);
        }

        // Successful login should not trigger brute force (under threshold)
        let event = create_test_event(AuditAction::Login, AuditOutcome::Success, "user1");
        let result = detector.analyze_event(&event).unwrap();

        // With only 3 failures, should not be flagged (threshold is 5)
        assert!(!result.is_anomalous || result.anomaly_type != Some(AnomalyType::BruteForceAttack));
    }

    #[test]
    fn test_privilege_escalation_detection() {
        let detector = AnomalyDetector::new(AnomalyDetectionConfig::default());

        // Simulate multiple failed privilege escalation attempts
        for _ in 0..4 {
            let event =
                create_test_event(AuditAction::TenantUpdated, AuditOutcome::Failure, "user1");
            detector.add_recent_event(event);
        }

        let event = create_test_event(AuditAction::TenantUpdated, AuditOutcome::Failure, "user1");
        let result = detector.analyze_event(&event).unwrap();

        assert!(result.is_anomalous);
        assert_eq!(result.anomaly_type, Some(AnomalyType::PrivilegeEscalation));
    }

    #[test]
    fn test_non_login_action_not_brute_force() {
        let detector = AnomalyDetector::new(AnomalyDetectionConfig::default());

        // Simulate many failed query attempts (not login)
        for _ in 0..10 {
            let event =
                create_test_event(AuditAction::EventQueried, AuditOutcome::Failure, "user1");
            detector.add_recent_event(event);
        }

        let event = create_test_event(AuditAction::EventQueried, AuditOutcome::Failure, "user1");
        let result = detector.analyze_event(&event).unwrap();

        // Should not be flagged as brute force (only login events trigger this)
        assert!(result.anomaly_type != Some(AnomalyType::BruteForceAttack));
    }

    #[test]
    fn test_multiple_users_independent() {
        let detector = AnomalyDetector::new(AnomalyDetectionConfig::default());

        // Simulate failed logins from user1
        for _ in 0..6 {
            let event = create_test_event(AuditAction::Login, AuditOutcome::Failure, "user1");
            detector.add_recent_event(event);
        }

        // Check user2's login - should not be flagged
        let event = create_test_event(AuditAction::Login, AuditOutcome::Failure, "user2");
        let result = detector.analyze_event(&event).unwrap();

        // User2's single failure should not trigger brute force
        assert!(!result.is_anomalous || result.anomaly_type != Some(AnomalyType::BruteForceAttack));
    }

    #[test]
    fn test_anomaly_types_serde() {
        let types = vec![
            AnomalyType::BruteForceAttack,
            AnomalyType::UnusualAccessPattern,
            AnomalyType::PrivilegeEscalation,
            AnomalyType::DataExfiltration,
            AnomalyType::VelocityAnomaly,
            AnomalyType::AccountCompromise,
            AnomalyType::SuspiciousActivity,
        ];

        for anomaly_type in types {
            let json = serde_json::to_string(&anomaly_type).unwrap();
            let parsed: AnomalyType = serde_json::from_str(&json).unwrap();
            assert_eq!(parsed, anomaly_type);
        }
    }

    #[test]
    fn test_recommended_actions_serde() {
        let actions = vec![
            RecommendedAction::Monitor,
            RecommendedAction::Alert,
            RecommendedAction::Block,
            RecommendedAction::RequireMFA,
            RecommendedAction::RevokeAccess,
        ];

        for action in actions {
            let json = serde_json::to_string(&action).unwrap();
            let parsed: RecommendedAction = serde_json::from_str(&json).unwrap();
            assert_eq!(parsed, action);
        }
    }

    #[test]
    fn test_disabled_individual_detectors() {
        let config = AnomalyDetectionConfig {
            enabled: true,
            enable_brute_force_detection: false,
            enable_velocity_detection: false,
            ..Default::default()
        };

        let detector = AnomalyDetector::new(config);

        // Simulate conditions that would trigger brute force
        for _ in 0..10 {
            let event = create_test_event(AuditAction::Login, AuditOutcome::Failure, "user1");
            detector.add_recent_event(event);
        }

        let event = create_test_event(AuditAction::Login, AuditOutcome::Failure, "user1");
        let result = detector.analyze_event(&event).unwrap();

        // Brute force detection is disabled, so should not be flagged as brute force
        assert!(result.anomaly_type != Some(AnomalyType::BruteForceAttack));
    }
}