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                self.send_email_alert(alert, recipients).await;
346            }
347            NotificationChannel::Slack { webhook_url } => {
348                let payload = serde_json::json!({
349                    "text": format!(
350                        "*[{:?}]* {} — {}",
351                        alert.severity, alert.title, alert.message
352                    )
353                });
354                let client = reqwest::Client::new();
355                if let Err(e) = client.post(webhook_url).json(&payload).send().await {
356                    tracing::error!(
357                        webhook_url = %crate::utils::redact::url_origin(webhook_url),
358                        error = %e.without_url(),
359                        "Failed to send Slack alert"
360                    );
361                } else {
362                    tracing::info!(webhook_url = %crate::utils::redact::url_origin(webhook_url), "Slack alert sent: {}", alert.title);
363                }
364            }
365            NotificationChannel::Teams { webhook_url } => {
366                // Microsoft Teams Incoming Webhook message card format.
367                let payload = serde_json::json!({
368                    "@type": "MessageCard",
369                    "@context": "http://schema.org/extensions",
370                    "themeColor": match alert.severity {
371                        AlertSeverity::Critical => "FF0000",
372                        AlertSeverity::Warning  => "FFA500",
373                        AlertSeverity::Info     => "0078D7",
374                    },
375                    "summary": &alert.title,
376                    "sections": [{
377                        "activityTitle": &alert.title,
378                        "activityText": &alert.message,
379                        "facts": [
380                            { "name": "Severity", "value": format!("{:?}", alert.severity) },
381                            { "name": "Source",   "value": &alert.source },
382                        ]
383                    }]
384                });
385                let client = reqwest::Client::new();
386                if let Err(e) = client.post(webhook_url).json(&payload).send().await {
387                    tracing::error!(
388                        webhook_url = %crate::utils::redact::url_origin(webhook_url),
389                        error = %e.without_url(),
390                        "Failed to send Teams alert"
391                    );
392                } else {
393                    tracing::info!(webhook_url = %crate::utils::redact::url_origin(webhook_url), "Teams alert sent: {}", alert.title);
394                }
395            }
396            NotificationChannel::Webhook { url, headers } => {
397                let payload = serde_json::json!({
398                    "id":       &alert.id,
399                    "title":    &alert.title,
400                    "message":  &alert.message,
401                    "severity": format!("{:?}", alert.severity),
402                    "source":   &alert.source,
403                    "metrics":  &alert.metrics,
404                    "timestamp": alert.timestamp,
405                });
406                let client = reqwest::Client::new();
407                let mut req = client.post(url).json(&payload);
408                for (k, v) in headers {
409                    req = req.header(k, v);
410                }
411                if let Err(e) = req.send().await {
412                    tracing::error!(url = %crate::utils::redact::url_origin(url), error = %e.without_url(), "Failed to send webhook alert");
413                } else {
414                    tracing::info!(url = %crate::utils::redact::url_origin(url), "Webhook alert sent: {}", alert.title);
415                }
416            }
417            NotificationChannel::Log { level } => match level.as_str() {
418                "error" => tracing::error!("ALERT: {} - {}", alert.title, alert.message),
419                "warn" => tracing::warn!("ALERT: {} - {}", alert.title, alert.message),
420                _ => tracing::info!("ALERT: {} - {}", alert.title, alert.message),
421            },
422        }
423
424        Ok(())
425    }
426
427    /// Deliver an alert by SMTP (configured through `AUTH_SMTP_*` environment variables).
428    #[cfg(feature = "smtp")]
429    async fn send_email_alert(&self, alert: &Alert, recipients: &[String]) {
430        use lettre::{
431            AsyncSmtpTransport, AsyncTransport, Message, Tokio1Executor, message::Mailbox,
432            transport::smtp::authentication::Credentials,
433        };
434
435        // SMTP is configured via environment variables so no credentials are
436        // embedded in the AlertConfig serialisation:
437        //   AUTH_SMTP_HOST     — required; disables email channel if unset
438        //   AUTH_SMTP_PORT     — optional (default 587, STARTTLS)
439        //   AUTH_SMTP_FROM     — optional (default "alerts@<host>")
440        //   AUTH_SMTP_USERNAME — optional
441        //   AUTH_SMTP_PASSWORD — optional
442        let smtp_host = match std::env::var("AUTH_SMTP_HOST") {
443            Ok(h) => h,
444            Err(_) => {
445                tracing::warn!(
446                    recipients = ?recipients,
447                    title = %alert.title,
448                    severity = ?alert.severity,
449                    "EMAIL ALERT: set AUTH_SMTP_HOST to enable SMTP delivery"
450                );
451                return;
452            }
453        };
454        let smtp_port: u16 = std::env::var("AUTH_SMTP_PORT")
455            .ok()
456            .and_then(|p| p.parse().ok())
457            .unwrap_or(587);
458        let from_addr =
459            std::env::var("AUTH_SMTP_FROM").unwrap_or_else(|_| format!("alerts@{}", smtp_host));
460
461        let from_mailbox: Mailbox = match from_addr.parse() {
462            Ok(m) => m,
463            Err(e) => {
464                tracing::error!(from = %from_addr, error = %e, "Invalid AUTH_SMTP_FROM address");
465                return;
466            }
467        };
468
469        let mut builder = match AsyncSmtpTransport::<Tokio1Executor>::starttls_relay(&smtp_host) {
470            Ok(b) => b.port(smtp_port),
471            Err(e) => {
472                tracing::error!(host = %smtp_host, error = %e, "Failed to create SMTP transport");
473                return;
474            }
475        };
476        if let (Ok(user), Ok(pass)) = (
477            std::env::var("AUTH_SMTP_USERNAME"),
478            std::env::var("AUTH_SMTP_PASSWORD"),
479        ) {
480            builder = builder.credentials(Credentials::new(user, pass));
481        }
482        let mailer = builder.build();
483
484        let subject = format!("[{:?}] {}", alert.severity, alert.title);
485        let body = format!(
486            "Alert: {}\nSeverity: {:?}\nSource: {}\nMessage: {}\nTimestamp: {}",
487            alert.title, alert.severity, alert.source, alert.message, alert.timestamp
488        );
489
490        for recipient in recipients {
491            let to_mailbox: Mailbox = match recipient.parse() {
492                Ok(m) => m,
493                Err(e) => {
494                    tracing::error!(
495                        recipient = %recipient, error = %e,
496                        "Invalid recipient address — skipping"
497                    );
498                    continue;
499                }
500            };
501            match Message::builder()
502                .from(from_mailbox.clone())
503                .to(to_mailbox)
504                .subject(&subject)
505                .body(body.clone())
506            {
507                Ok(email) => {
508                    if let Err(e) = mailer.send(email).await {
509                        tracing::error!(
510                            recipient = %recipient, error = %e,
511                            "Failed to send email alert"
512                        );
513                    } else {
514                        tracing::info!(
515                            recipient = %recipient,
516                            "Email alert sent: {}", alert.title
517                        );
518                    }
519                }
520                Err(e) => {
521                    tracing::error!(
522                        recipient = %recipient, error = %e,
523                        "Failed to build email message"
524                    );
525                }
526            }
527        }
528    }
529
530    /// Without the `smtp` feature there is no SMTP stack: say so loudly instead of dropping the alert.
531    #[cfg(not(feature = "smtp"))]
532    async fn send_email_alert(&self, alert: &Alert, recipients: &[String]) {
533        tracing::error!(
534            recipients = ?recipients,
535            title = %alert.title,
536            severity = ?alert.severity,
537            "EMAIL ALERT NOT SENT: this build has no SMTP support; enable the `smtp` feature"
538        );
539    }
540
541    /// Clean up old alert tracking data
542    pub fn cleanup_alert_history(&mut self, max_age_seconds: u64) {
543        let current_time = crate::monitoring::current_timestamp();
544        self.recent_alerts
545            .retain(|_, &mut timestamp| current_time - timestamp < max_age_seconds);
546    }
547}
548
549impl Default for AlertConfig {
550    fn default() -> Self {
551        Self {
552            enabled: true,
553            thresholds: AlertThresholds::default(),
554            channels: vec![NotificationChannel::Log {
555                level: "warn".to_string(),
556            }],
557        }
558    }
559}