Skip to main content

auth_framework/monitoring/
alerts.rs

1//! Alerting system for security and performance monitoring
2
3use super::{SecurityEvent, SecurityEventSeverity, SecurityEventType};
4use crate::errors::Result;
5use serde::{Deserialize, Serialize};
6use std::collections::HashMap;
7
8/// Alert configuration
9#[derive(Debug, Clone, Serialize, Deserialize)]
10pub struct AlertConfig {
11    /// Enable alerting
12    pub enabled: bool,
13    /// Alert thresholds
14    pub thresholds: AlertThresholds,
15    /// Notification channels
16    pub channels: Vec<NotificationChannel>,
17}
18
19/// Alert threshold configuration
20#[derive(Debug, Clone, Serialize, Deserialize)]
21pub struct AlertThresholds {
22    /// Failed login attempts per minute
23    pub failed_logins_per_minute: u64,
24    /// Maximum response time in milliseconds
25    pub max_response_time_ms: u64,
26    /// Error rate threshold (0.0 - 1.0)
27    pub error_rate_threshold: f64,
28    /// Minimum time between duplicate alerts in seconds
29    pub alert_cooldown_seconds: u64,
30}
31
32impl Default for AlertThresholds {
33    fn default() -> Self {
34        Self {
35            failed_logins_per_minute: 10,
36            max_response_time_ms: 5000,
37            error_rate_threshold: 0.1,   // 10%
38            alert_cooldown_seconds: 300, // 5 minutes
39        }
40    }
41}
42
43/// Notification channel types
44#[derive(Clone, Serialize, Deserialize)]
45pub enum NotificationChannel {
46    /// Email notifications
47    Email { recipients: Vec<String> },
48    /// Slack webhook
49    Slack { webhook_url: String },
50    /// Microsoft Teams webhook
51    Teams { webhook_url: String },
52    /// Generic webhook
53    Webhook {
54        url: String,
55        headers: HashMap<String, String>,
56    },
57    /// Log-based alerts
58    Log { level: String },
59}
60
61impl std::fmt::Debug for NotificationChannel {
62    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63        use crate::utils::redact::redacted;
64        match self {
65            Self::Email { recipients } => f
66                .debug_struct("Email")
67                .field("recipients", recipients)
68                .finish(),
69            Self::Slack { webhook_url } => f
70                .debug_struct("Slack")
71                .field("webhook_url", &redacted(webhook_url))
72                .finish(),
73            Self::Teams { webhook_url } => f
74                .debug_struct("Teams")
75                .field("webhook_url", &redacted(webhook_url))
76                .finish(),
77            // Webhook URLs embed their access token and the headers may carry an Authorization value.
78            Self::Webhook { url, headers } => f
79                .debug_struct("Webhook")
80                .field("url", &redacted(url))
81                .field("headers", &headers.keys().collect::<Vec<_>>())
82                .finish(),
83            Self::Log { level } => f.debug_struct("Log").field("level", level).finish(),
84        }
85    }
86}
87
88/// Alert severity levels
89#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, PartialOrd)]
90pub enum AlertSeverity {
91    Info,
92    Warning,
93    Critical,
94}
95
96/// Alert message
97#[derive(Debug, Clone, Serialize, Deserialize)]
98pub struct Alert {
99    /// Alert ID
100    pub id: String,
101    /// Alert title
102    pub title: String,
103    /// Alert message
104    pub message: String,
105    /// Severity level
106    pub severity: AlertSeverity,
107    /// Source component
108    pub source: String,
109    /// Related metrics
110    pub metrics: HashMap<String, f64>,
111    /// Timestamp
112    pub timestamp: u64,
113}
114
115/// Alert manager
116pub struct AlertManager {
117    /// Configuration
118    config: AlertConfig,
119    /// Recent alerts for cooldown tracking
120    recent_alerts: HashMap<String, u64>,
121}
122
123impl AlertManager {
124    /// Create new alert manager
125    pub fn new(config: AlertConfig) -> Self {
126        Self {
127            config,
128            recent_alerts: HashMap::new(),
129        }
130    }
131
132    /// Process security event and generate alerts if needed
133    pub async fn process_security_event(&mut self, event: &SecurityEvent) -> Result<()> {
134        if !self.config.enabled {
135            return Ok(());
136        }
137
138        let alert = match event.event_type {
139            SecurityEventType::FailedLogin => {
140                if event.severity >= SecurityEventSeverity::High {
141                    Some(Alert {
142                        id: format!("failed_login_{}", event.timestamp),
143                        title: "High volume of failed login attempts detected".to_string(),
144                        message: format!(
145                            "Multiple failed login attempts detected for user {:?} from IP {:?}",
146                            event.user_id, event.ip_address
147                        ),
148                        severity: AlertSeverity::Warning,
149                        source: "authentication".to_string(),
150                        metrics: HashMap::new(),
151                        timestamp: event.timestamp,
152                    })
153                } else {
154                    None
155                }
156            }
157            SecurityEventType::AccountLockout => Some(Alert {
158                id: format!("account_lockout_{}", event.timestamp),
159                title: "Account lockout triggered".to_string(),
160                message: format!(
161                    "Account {:?} has been locked due to security policy",
162                    event.user_id
163                ),
164                severity: AlertSeverity::Warning,
165                source: "security".to_string(),
166                metrics: HashMap::new(),
167                timestamp: event.timestamp,
168            }),
169            SecurityEventType::PrivilegeEscalation => Some(Alert {
170                id: format!("privilege_escalation_{}", event.timestamp),
171                title: "Privilege escalation attempt detected".to_string(),
172                message: format!("Privilege escalation attempt by user {:?}", event.user_id),
173                severity: AlertSeverity::Critical,
174                source: "authorization".to_string(),
175                metrics: HashMap::new(),
176                timestamp: event.timestamp,
177            }),
178            _ => None,
179        };
180
181        if let Some(alert) = alert {
182            self.send_alert(alert).await?;
183        }
184
185        Ok(())
186    }
187
188    /// Process performance metrics and generate alerts
189    pub async fn process_performance_metrics(
190        &mut self,
191        metrics: &HashMap<String, u64>,
192    ) -> Result<()> {
193        if !self.config.enabled {
194            return Ok(());
195        }
196
197        // Check response time threshold
198        if let Some(&response_time) = metrics.get("avg_response_time_us") {
199            let response_time_ms = response_time / 1000; // Convert to milliseconds
200
201            if response_time_ms > self.config.thresholds.max_response_time_ms {
202                let alert = Alert {
203                    id: format!(
204                        "high_response_time_{}",
205                        crate::monitoring::current_timestamp()
206                    ),
207                    title: "High response time detected".to_string(),
208                    message: format!(
209                        "Average response time is {}ms, which exceeds the threshold of {}ms",
210                        response_time_ms, self.config.thresholds.max_response_time_ms
211                    ),
212                    severity: AlertSeverity::Warning,
213                    source: "performance".to_string(),
214                    metrics: {
215                        let mut m = HashMap::new();
216                        m.insert("response_time_ms".to_string(), response_time_ms as f64);
217                        m.insert(
218                            "threshold_ms".to_string(),
219                            self.config.thresholds.max_response_time_ms as f64,
220                        );
221                        m
222                    },
223                    timestamp: crate::monitoring::current_timestamp(),
224                };
225
226                self.send_alert(alert).await?;
227            }
228        }
229
230        // Check error rate
231        if let (Some(&auth_requests), Some(&auth_failures)) =
232            (metrics.get("auth_requests"), metrics.get("auth_failures"))
233            && auth_requests > 0
234        {
235            let error_rate = auth_failures as f64 / auth_requests as f64;
236
237            if error_rate > self.config.thresholds.error_rate_threshold {
238                let alert = Alert {
239                    id: format!("high_error_rate_{}", crate::monitoring::current_timestamp()),
240                    title: "High authentication error rate".to_string(),
241                    message: format!(
242                        "Authentication error rate is {:.1}%, which exceeds the threshold of {:.1}%",
243                        error_rate * 100.0,
244                        self.config.thresholds.error_rate_threshold * 100.0
245                    ),
246                    severity: AlertSeverity::Critical,
247                    source: "authentication".to_string(),
248                    metrics: {
249                        let mut m = HashMap::new();
250                        m.insert("error_rate".to_string(), error_rate);
251                        m.insert(
252                            "threshold".to_string(),
253                            self.config.thresholds.error_rate_threshold,
254                        );
255                        m.insert("total_requests".to_string(), auth_requests as f64);
256                        m.insert("failed_requests".to_string(), auth_failures as f64);
257                        m
258                    },
259                    timestamp: crate::monitoring::current_timestamp(),
260                };
261
262                self.send_alert(alert).await?;
263            }
264        }
265
266        Ok(())
267    }
268
269    /// Send alert through configured channels
270    async fn send_alert(&mut self, alert: Alert) -> Result<()> {
271        // Check cooldown
272        if let Some(&last_alert_time) = self.recent_alerts.get(&alert.id) {
273            let current_time = crate::monitoring::current_timestamp();
274            if current_time - last_alert_time < self.config.thresholds.alert_cooldown_seconds {
275                tracing::debug!("Alert {} is in cooldown period, skipping", alert.id);
276                return Ok(());
277            }
278        }
279
280        // Update recent alerts tracking
281        self.recent_alerts.insert(alert.id.clone(), alert.timestamp);
282
283        // Send to all configured channels
284        for channel in &self.config.channels {
285            self.send_to_channel(&alert, channel).await?;
286        }
287
288        tracing::info!(
289            "Alert sent: {} - {} (Severity: {:?})",
290            alert.title,
291            alert.message,
292            alert.severity
293        );
294
295        Ok(())
296    }
297
298    /// Send alert to specific channel
299    async fn send_to_channel(&self, alert: &Alert, channel: &NotificationChannel) -> Result<()> {
300        match channel {
301            NotificationChannel::Email { recipients } => {
302                // In production: Send email using SMTP or email service API
303                tracing::info!(
304                    "EMAIL ALERT to {:?}: {} - {}",
305                    recipients,
306                    alert.title,
307                    alert.message
308                );
309            }
310            NotificationChannel::Slack { webhook_url } => {
311                // In production: Send POST request to Slack webhook
312                tracing::info!(
313                    "SLACK ALERT to {}: {} - {}",
314                    crate::utils::redact::url_origin(webhook_url),
315                    alert.title,
316                    alert.message
317                );
318            }
319            NotificationChannel::Teams { webhook_url } => {
320                // In production: Send POST request to Teams webhook
321                tracing::info!(
322                    "TEAMS ALERT to {}: {} - {}",
323                    crate::utils::redact::url_origin(webhook_url),
324                    alert.title,
325                    alert.message
326                );
327            }
328            NotificationChannel::Webhook { url, headers: _ } => {
329                // In production: Send POST request to generic webhook
330                tracing::info!(
331                    "WEBHOOK ALERT to {}: {} - {}",
332                    crate::utils::redact::url_origin(url),
333                    alert.title,
334                    alert.message
335                );
336            }
337            NotificationChannel::Log { level } => match level.as_str() {
338                "error" => tracing::error!("ALERT: {} - {}", alert.title, alert.message),
339                "warn" => tracing::warn!("ALERT: {} - {}", alert.title, alert.message),
340                _ => tracing::info!("ALERT: {} - {}", alert.title, alert.message),
341            },
342        }
343
344        Ok(())
345    }
346
347    /// Clean up old alert tracking data
348    pub fn cleanup_alert_history(&mut self, max_age_seconds: u64) {
349        let current_time = crate::monitoring::current_timestamp();
350        self.recent_alerts
351            .retain(|_, &mut timestamp| current_time - timestamp < max_age_seconds);
352    }
353}
354
355impl Default for AlertConfig {
356    fn default() -> Self {
357        Self {
358            enabled: true,
359            thresholds: AlertThresholds::default(),
360            channels: vec![NotificationChannel::Log {
361                level: "warn".to_string(),
362            }],
363        }
364    }
365}