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/// Alert configuration
8#[derive(Debug, Clone, Serialize, Deserialize)]
9pub struct AlertConfig {
10    /// Enable alerting
11    pub enabled: bool,
12    /// Alert thresholds
13    pub thresholds: AlertThresholds,
14    /// Notification channels
15    pub channels: Vec<NotificationChannel>,
16}
17
18/// Alert threshold configuration
19#[derive(Debug, Clone, Serialize, Deserialize)]
20pub struct AlertThresholds {
21    /// Failed login attempts per minute
22    pub failed_logins_per_minute: u64,
23    /// Maximum response time in milliseconds
24    pub max_response_time_ms: u64,
25    /// Error rate threshold (0.0 - 1.0)
26    pub error_rate_threshold: f64,
27    /// Minimum time between duplicate alerts in seconds
28    pub alert_cooldown_seconds: u64,
29}
30
31impl Default for AlertThresholds {
32    fn default() -> Self {
33        Self {
34            failed_logins_per_minute: 10,
35            max_response_time_ms: 5000,
36            error_rate_threshold: 0.1,   // 10%
37            alert_cooldown_seconds: 300, // 5 minutes
38        }
39    }
40}
41
42/// Notification channel types
43#[derive(Clone, Serialize, Deserialize)]
44pub enum NotificationChannel {
45    /// Email notifications
46    Email { recipients: Vec<String> },
47    /// Slack webhook
48    Slack { webhook_url: String },
49    /// Microsoft Teams webhook
50    Teams { webhook_url: String },
51    /// Generic webhook
52    Webhook {
53        url: String,
54        headers: HashMap<String, String>,
55    },
56    /// Log-based alerts
57    Log { level: String },
58}
59
60impl std::fmt::Debug for NotificationChannel {
61    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
62        use crate::utils::redact::redacted;
63        match self {
64            Self::Email { recipients } => f
65                .debug_struct("Email")
66                .field("recipients", recipients)
67                .finish(),
68            Self::Slack { webhook_url } => f
69                .debug_struct("Slack")
70                .field("webhook_url", &redacted(webhook_url))
71                .finish(),
72            Self::Teams { webhook_url } => f
73                .debug_struct("Teams")
74                .field("webhook_url", &redacted(webhook_url))
75                .finish(),
76            // Webhook URLs embed their access token and the headers may carry an Authorization value.
77            Self::Webhook { url, headers } => f
78                .debug_struct("Webhook")
79                .field("url", &redacted(url))
80                .field("headers", &headers.keys().collect::<Vec<_>>())
81                .finish(),
82            Self::Log { level } => f.debug_struct("Log").field("level", level).finish(),
83        }
84    }
85}
86
87/// Alert severity levels
88#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, PartialOrd)]
89pub enum AlertSeverity {
90    Info,
91    Warning,
92    Critical,
93}
94
95/// Alert message
96#[derive(Debug, Clone, Serialize, Deserialize)]
97pub struct Alert {
98    /// Alert ID
99    pub id: String,
100    /// Alert title
101    pub title: String,
102    /// Alert message
103    pub message: String,
104    /// Severity level
105    pub severity: AlertSeverity,
106    /// Source component
107    pub source: String,
108    /// Related metrics
109    pub metrics: HashMap<String, f64>,
110    /// Timestamp
111    pub timestamp: u64,
112}
113
114/// Alert manager
115pub struct AlertManager {
116    /// Configuration
117    config: AlertConfig,
118    /// Recent alerts for cooldown tracking
119    recent_alerts: HashMap<String, u64>,
120}
121
122impl AlertManager {
123    /// Create new alert manager
124    pub fn new(config: AlertConfig) -> Self {
125        Self {
126            config,
127            recent_alerts: HashMap::new(),
128        }
129    }
130
131    /// Process security event and generate alerts if needed
132    pub async fn process_security_event(&mut self, event: &SecurityEvent) -> Result<()> {
133        if !self.config.enabled {
134            return Ok(());
135        }
136
137        let alert = match event.event_type {
138            SecurityEventType::FailedLogin => {
139                if event.severity >= SecurityEventSeverity::High {
140                    Some(Alert {
141                        id: format!("failed_login_{}", event.timestamp),
142                        title: "High volume of failed login attempts detected".to_string(),
143                        message: format!(
144                            "Multiple failed login attempts detected for user {:?} from IP {:?}",
145                            event.user_id, event.ip_address
146                        ),
147                        severity: AlertSeverity::Warning,
148                        source: "authentication".to_string(),
149                        metrics: HashMap::new(),
150                        timestamp: event.timestamp,
151                    })
152                } else {
153                    None
154                }
155            }
156            SecurityEventType::AccountLockout => Some(Alert {
157                id: format!("account_lockout_{}", event.timestamp),
158                title: "Account lockout triggered".to_string(),
159                message: format!(
160                    "Account {:?} has been locked due to security policy",
161                    event.user_id
162                ),
163                severity: AlertSeverity::Warning,
164                source: "security".to_string(),
165                metrics: HashMap::new(),
166                timestamp: event.timestamp,
167            }),
168            SecurityEventType::PrivilegeEscalation => Some(Alert {
169                id: format!("privilege_escalation_{}", event.timestamp),
170                title: "Privilege escalation attempt detected".to_string(),
171                message: format!("Privilege escalation attempt by user {:?}", event.user_id),
172                severity: AlertSeverity::Critical,
173                source: "authorization".to_string(),
174                metrics: HashMap::new(),
175                timestamp: event.timestamp,
176            }),
177            SecurityEventType::UnusualActivity => Some(Alert {
178                id: format!("unusual_activity_{}", event.timestamp),
179                title: "Unusual activity detected".to_string(),
180                message: format!(
181                    "Unusual activity pattern for user {:?}: {:?}",
182                    event.user_id, event.details
183                ),
184                severity: AlertSeverity::Warning,
185                source: "security".to_string(),
186                metrics: HashMap::new(),
187                timestamp: event.timestamp,
188            }),
189            SecurityEventType::TokenManipulation => Some(Alert {
190                id: format!("token_manipulation_{}", event.timestamp),
191                title: "Token manipulation attempt".to_string(),
192                message: format!(
193                    "Token manipulation detected for user {:?}: {:?}",
194                    event.user_id, event.details
195                ),
196                severity: AlertSeverity::Critical,
197                source: "security".to_string(),
198                metrics: HashMap::new(),
199                timestamp: event.timestamp,
200            }),
201            SecurityEventType::ConfigurationChange => Some(Alert {
202                id: format!("config_change_{}", event.timestamp),
203                title: "Security configuration changed".to_string(),
204                message: format!(
205                    "Configuration change by user {:?}: {:?}",
206                    event.user_id, event.details
207                ),
208                severity: AlertSeverity::Info,
209                source: "configuration".to_string(),
210                metrics: HashMap::new(),
211                timestamp: event.timestamp,
212            }),
213            SecurityEventType::SystemError => Some(Alert {
214                id: format!("system_error_{}", event.timestamp),
215                title: "System error in security subsystem".to_string(),
216                message: format!("System error: {:?}", event.details),
217                severity: AlertSeverity::Warning,
218                source: "system".to_string(),
219                metrics: HashMap::new(),
220                timestamp: event.timestamp,
221            }),
222        };
223
224        if let Some(alert) = alert {
225            self.send_alert(alert).await?;
226        }
227
228        Ok(())
229    }
230
231    /// Process performance metrics and generate alerts
232    pub async fn process_performance_metrics(
233        &mut self,
234        metrics: &HashMap<String, u64>,
235    ) -> Result<()> {
236        if !self.config.enabled {
237            return Ok(());
238        }
239
240        // Check response time threshold
241        if let Some(&response_time) = metrics.get("avg_response_time_us") {
242            let response_time_ms = response_time / 1000; // Convert to milliseconds
243
244            if response_time_ms > self.config.thresholds.max_response_time_ms {
245                let alert = Alert {
246                    id: format!(
247                        "high_response_time_{}",
248                        crate::monitoring::current_timestamp()
249                    ),
250                    title: "High response time detected".to_string(),
251                    message: format!(
252                        "Average response time is {}ms, which exceeds the threshold of {}ms",
253                        response_time_ms, self.config.thresholds.max_response_time_ms
254                    ),
255                    severity: AlertSeverity::Warning,
256                    source: "performance".to_string(),
257                    metrics: {
258                        let mut m = HashMap::new();
259                        m.insert("response_time_ms".to_string(), response_time_ms as f64);
260                        m.insert(
261                            "threshold_ms".to_string(),
262                            self.config.thresholds.max_response_time_ms as f64,
263                        );
264                        m
265                    },
266                    timestamp: crate::monitoring::current_timestamp(),
267                };
268
269                self.send_alert(alert).await?;
270            }
271        }
272
273        // Check error rate
274        if let (Some(&auth_requests), Some(&auth_failures)) =
275            (metrics.get("auth_requests"), metrics.get("auth_failures"))
276            && auth_requests > 0
277        {
278            let error_rate = auth_failures as f64 / auth_requests as f64;
279
280            if error_rate > self.config.thresholds.error_rate_threshold {
281                let alert = Alert {
282                    id: format!("high_error_rate_{}", crate::monitoring::current_timestamp()),
283                    title: "High authentication error rate".to_string(),
284                    message: format!(
285                        "Authentication error rate is {:.1}%, which exceeds the threshold of {:.1}%",
286                        error_rate * 100.0,
287                        self.config.thresholds.error_rate_threshold * 100.0
288                    ),
289                    severity: AlertSeverity::Critical,
290                    source: "authentication".to_string(),
291                    metrics: {
292                        let mut m = HashMap::new();
293                        m.insert("error_rate".to_string(), error_rate);
294                        m.insert(
295                            "threshold".to_string(),
296                            self.config.thresholds.error_rate_threshold,
297                        );
298                        m.insert("total_requests".to_string(), auth_requests as f64);
299                        m.insert("failed_requests".to_string(), auth_failures as f64);
300                        m
301                    },
302                    timestamp: crate::monitoring::current_timestamp(),
303                };
304
305                self.send_alert(alert).await?;
306            }
307        }
308
309        Ok(())
310    }
311
312    /// Send alert through configured channels
313    async fn send_alert(&mut self, alert: Alert) -> Result<()> {
314        // Check cooldown
315        if let Some(&last_alert_time) = self.recent_alerts.get(&alert.id) {
316            let current_time = crate::monitoring::current_timestamp();
317            if current_time - last_alert_time < self.config.thresholds.alert_cooldown_seconds {
318                tracing::debug!("Alert {} is in cooldown period, skipping", alert.id);
319                return Ok(());
320            }
321        }
322
323        // Update recent alerts tracking
324        self.recent_alerts.insert(alert.id.clone(), alert.timestamp);
325
326        // Send to all configured channels
327        for channel in &self.config.channels {
328            self.send_to_channel(&alert, channel).await?;
329        }
330
331        tracing::info!(
332            "Alert sent: {} - {} (Severity: {:?})",
333            alert.title,
334            alert.message,
335            alert.severity
336        );
337
338        Ok(())
339    }
340
341    /// Send alert to specific channel
342    async fn send_to_channel(&self, alert: &Alert, channel: &NotificationChannel) -> Result<()> {
343        match channel {
344            NotificationChannel::Email { recipients } => {
345                use lettre::{
346                    AsyncSmtpTransport, AsyncTransport, Message, Tokio1Executor, message::Mailbox,
347                    transport::smtp::authentication::Credentials,
348                };
349
350                // SMTP is configured via environment variables so no credentials are
351                // embedded in the AlertConfig serialisation:
352                //   AUTH_SMTP_HOST     — required; disables email channel if unset
353                //   AUTH_SMTP_PORT     — optional (default 587, STARTTLS)
354                //   AUTH_SMTP_FROM     — optional (default "alerts@<host>")
355                //   AUTH_SMTP_USERNAME — optional
356                //   AUTH_SMTP_PASSWORD — optional
357                let smtp_host = match std::env::var("AUTH_SMTP_HOST") {
358                    Ok(h) => h,
359                    Err(_) => {
360                        tracing::warn!(
361                            recipients = ?recipients,
362                            title = %alert.title,
363                            severity = ?alert.severity,
364                            "EMAIL ALERT: set AUTH_SMTP_HOST to enable SMTP delivery"
365                        );
366                        return Ok(());
367                    }
368                };
369                let smtp_port: u16 = std::env::var("AUTH_SMTP_PORT")
370                    .ok()
371                    .and_then(|p| p.parse().ok())
372                    .unwrap_or(587);
373                let from_addr = std::env::var("AUTH_SMTP_FROM")
374                    .unwrap_or_else(|_| format!("alerts@{}", smtp_host));
375
376                let from_mailbox: Mailbox = match from_addr.parse() {
377                    Ok(m) => m,
378                    Err(e) => {
379                        tracing::error!(from = %from_addr, error = %e, "Invalid AUTH_SMTP_FROM address");
380                        return Ok(());
381                    }
382                };
383
384                let mut builder = match AsyncSmtpTransport::<Tokio1Executor>::starttls_relay(
385                    &smtp_host,
386                ) {
387                    Ok(b) => b.port(smtp_port),
388                    Err(e) => {
389                        tracing::error!(host = %smtp_host, error = %e, "Failed to create SMTP transport");
390                        return Ok(());
391                    }
392                };
393                if let (Ok(user), Ok(pass)) = (
394                    std::env::var("AUTH_SMTP_USERNAME"),
395                    std::env::var("AUTH_SMTP_PASSWORD"),
396                ) {
397                    builder = builder.credentials(Credentials::new(user, pass));
398                }
399                let mailer = builder.build();
400
401                let subject = format!("[{:?}] {}", alert.severity, alert.title);
402                let body = format!(
403                    "Alert: {}\nSeverity: {:?}\nSource: {}\nMessage: {}\nTimestamp: {}",
404                    alert.title, alert.severity, alert.source, alert.message, alert.timestamp
405                );
406
407                for recipient in recipients {
408                    let to_mailbox: Mailbox = match recipient.parse() {
409                        Ok(m) => m,
410                        Err(e) => {
411                            tracing::error!(
412                                recipient = %recipient, error = %e,
413                                "Invalid recipient address — skipping"
414                            );
415                            continue;
416                        }
417                    };
418                    match Message::builder()
419                        .from(from_mailbox.clone())
420                        .to(to_mailbox)
421                        .subject(&subject)
422                        .body(body.clone())
423                    {
424                        Ok(email) => {
425                            if let Err(e) = mailer.send(email).await {
426                                tracing::error!(
427                                    recipient = %recipient, error = %e,
428                                    "Failed to send email alert"
429                                );
430                            } else {
431                                tracing::info!(
432                                    recipient = %recipient,
433                                    "Email alert sent: {}", alert.title
434                                );
435                            }
436                        }
437                        Err(e) => {
438                            tracing::error!(
439                                recipient = %recipient, error = %e,
440                                "Failed to build email message"
441                            );
442                        }
443                    }
444                }
445            }
446            NotificationChannel::Slack { webhook_url } => {
447                let payload = serde_json::json!({
448                    "text": format!(
449                        "*[{:?}]* {} — {}",
450                        alert.severity, alert.title, alert.message
451                    )
452                });
453                let client = reqwest::Client::new();
454                if let Err(e) = client.post(webhook_url).json(&payload).send().await {
455                    tracing::error!(
456                        webhook_url = %crate::utils::redact::url_origin(webhook_url),
457                        error = %e.without_url(),
458                        "Failed to send Slack alert"
459                    );
460                } else {
461                    tracing::info!(webhook_url = %crate::utils::redact::url_origin(webhook_url), "Slack alert sent: {}", alert.title);
462                }
463            }
464            NotificationChannel::Teams { webhook_url } => {
465                // Microsoft Teams Incoming Webhook message card format.
466                let payload = serde_json::json!({
467                    "@type": "MessageCard",
468                    "@context": "http://schema.org/extensions",
469                    "themeColor": match alert.severity {
470                        AlertSeverity::Critical => "FF0000",
471                        AlertSeverity::Warning  => "FFA500",
472                        AlertSeverity::Info     => "0078D7",
473                    },
474                    "summary": &alert.title,
475                    "sections": [{
476                        "activityTitle": &alert.title,
477                        "activityText": &alert.message,
478                        "facts": [
479                            { "name": "Severity", "value": format!("{:?}", alert.severity) },
480                            { "name": "Source",   "value": &alert.source },
481                        ]
482                    }]
483                });
484                let client = reqwest::Client::new();
485                if let Err(e) = client.post(webhook_url).json(&payload).send().await {
486                    tracing::error!(
487                        webhook_url = %crate::utils::redact::url_origin(webhook_url),
488                        error = %e.without_url(),
489                        "Failed to send Teams alert"
490                    );
491                } else {
492                    tracing::info!(webhook_url = %crate::utils::redact::url_origin(webhook_url), "Teams alert sent: {}", alert.title);
493                }
494            }
495            NotificationChannel::Webhook { url, headers } => {
496                let payload = serde_json::json!({
497                    "id":       &alert.id,
498                    "title":    &alert.title,
499                    "message":  &alert.message,
500                    "severity": format!("{:?}", alert.severity),
501                    "source":   &alert.source,
502                    "metrics":  &alert.metrics,
503                    "timestamp": alert.timestamp,
504                });
505                let client = reqwest::Client::new();
506                let mut req = client.post(url).json(&payload);
507                for (k, v) in headers {
508                    req = req.header(k, v);
509                }
510                if let Err(e) = req.send().await {
511                    tracing::error!(url = %crate::utils::redact::url_origin(url), error = %e.without_url(), "Failed to send webhook alert");
512                } else {
513                    tracing::info!(url = %crate::utils::redact::url_origin(url), "Webhook alert sent: {}", alert.title);
514                }
515            }
516            NotificationChannel::Log { level } => match level.as_str() {
517                "error" => tracing::error!("ALERT: {} - {}", alert.title, alert.message),
518                "warn" => tracing::warn!("ALERT: {} - {}", alert.title, alert.message),
519                _ => tracing::info!("ALERT: {} - {}", alert.title, alert.message),
520            },
521        }
522
523        Ok(())
524    }
525
526    /// Clean up old alert tracking data
527    pub fn cleanup_alert_history(&mut self, max_age_seconds: u64) {
528        let current_time = crate::monitoring::current_timestamp();
529        self.recent_alerts
530            .retain(|_, &mut timestamp| current_time - timestamp < max_age_seconds);
531    }
532}
533
534impl Default for AlertConfig {
535    fn default() -> Self {
536        Self {
537            enabled: true,
538            thresholds: AlertThresholds::default(),
539            channels: vec![NotificationChannel::Log {
540                level: "warn".to_string(),
541            }],
542        }
543    }
544}