spawn_access_control/
security_analyzer.rs1use crate::audit::AuditLogEntry;
2use crate::audit::ActionResult;
3use chrono::{DateTime, Utc, Duration};
4use std::collections::HashMap;
5use serde::{Serialize, Deserialize};
6
7#[derive(Debug, Clone, Serialize, Deserialize)]
8pub struct SuspiciousPattern {
9 pub pattern_type: String,
10 pub confidence: f64,
11 pub first_seen: DateTime<Utc>,
12 pub last_seen: DateTime<Utc>,
13 pub occurrences: u32,
14}
15
16#[derive(Debug, Clone, Serialize, Deserialize)]
17pub struct SecurityReport {
18 pub timestamp: DateTime<Utc>,
19 pub suspicious_patterns: HashMap<String, Vec<SuspiciousPattern>>,
20 pub recent_failures: usize,
21 pub risk_level: RiskLevel,
22}
23
24#[derive(Debug, Clone, Serialize, Deserialize)]
25pub enum RiskLevel {
26 Low,
27 Medium,
28 High,
29 Critical,
30}
31
32#[derive(Debug, Clone)]
33pub struct SecurityAnalyzer {
34 #[allow(dead_code)]
35 access_history: Vec<AuditLogEntry>,
36 suspicious_patterns: HashMap<String, Vec<SuspiciousPattern>>,
37 config: SecurityConfig,
38}
39
40impl SecurityAnalyzer {
41 pub fn new(config: SecurityConfig) -> Self {
42 Self {
43 access_history: Vec::new(),
44 suspicious_patterns: HashMap::new(),
45 config,
46 }
47 }
48
49 pub fn analyze_recent_activity(&self, accesses: &[AuditLogEntry]) -> SecurityReport {
50 let now = Utc::now();
51 let recent_window = self.config.recent_window;
52
53 let recent_failures = accesses.iter()
55 .filter(|entry| (now - entry.timestamp).num_minutes() < recent_window.num_minutes())
56 .filter(|entry| matches!(entry.result, ActionResult::Failure { .. }))
57 .count();
58
59 SecurityReport {
60 timestamp: now,
61 suspicious_patterns: self.suspicious_patterns.clone(),
62 recent_failures,
63 risk_level: self.calculate_risk_level(recent_failures),
64 }
65 }
66
67 fn calculate_risk_level(&self, recent_failures: usize) -> RiskLevel {
68 if recent_failures > 5 {
69 RiskLevel::Critical
70 } else if recent_failures > 2 {
71 RiskLevel::High
72 } else if recent_failures > 0 {
73 RiskLevel::Medium
74 } else {
75 RiskLevel::Low
76 }
77 }
78}
79
80#[derive(Debug, Clone)]
81pub struct SecurityConfig {
82 pub recent_window: Duration,
83 pub max_failures: u32,
84 pub min_suspicious_score: f64,
85}
86
87impl Default for SecurityConfig {
88 fn default() -> Self {
89 Self {
90 recent_window: Duration::minutes(30),
91 max_failures: 5,
92 min_suspicious_score: 0.7,
93 }
94 }
95}