auth-framework 0.5.0-rc19

A comprehensive, production-ready authentication and authorization framework for Rust applications
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
//! Monitoring and Metrics Collection Module
//!
//! This module provides comprehensive monitoring capabilities for the authentication framework,
//! including metrics collection, performance monitoring, security event tracking, and
//! integration with external monitoring systems.
//!
//! # Features
//!
//! - **Performance Metrics**: Track authentication performance, latency, and throughput
//! - **Security Monitoring**: Monitor security events, failed attempts, and anomalies
//! - **Health Checks**: Provide health status for all authentication components
//! - **Custom Metrics**: Support for application-specific metrics
//! - **Integration**: Export metrics to Prometheus, Grafana, DataDog, etc.
//! - **Alerting**: Configuration-based alerting for critical events

use crate::errors::Result;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tokio::sync::RwLock;
use tracing::warn;

pub mod alerts;
pub mod collectors;
pub mod exporters;
pub mod health;

// Re-export atomic counters so other modules can increment them directly.
pub use collectors::{
    AUTH_FAILED_REQUESTS, AUTH_SUCCESSFUL_REQUESTS, AUTH_TOTAL_REQUESTS, SESSION_ACTIVE_COUNT,
    SESSION_CREATED_TOTAL, SESSION_EXPIRED_COUNT, TOKEN_CREATION_COUNT, TOKEN_EXPIRATION_COUNT,
    TOKEN_VALIDATION_COUNT,
};

/// Monitoring configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MonitoringConfig {
    /// Enable monitoring system
    pub enabled: bool,
    /// Collection interval in seconds
    pub collection_interval: u64,
    /// Maximum metrics history size
    pub max_history_size: usize,
    /// Enable performance monitoring
    pub enable_performance_metrics: bool,
    /// Enable security monitoring
    pub enable_security_metrics: bool,
    /// Enable health checks
    pub enable_health_checks: bool,
    /// External monitoring endpoints
    pub external_endpoints: Vec<String>,
}

impl Default for MonitoringConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            collection_interval: 60, // 1 minute
            max_history_size: 1000,
            enable_performance_metrics: true,
            enable_security_metrics: true,
            enable_health_checks: true,
            external_endpoints: vec![],
        }
    }
}

/// Metric data point
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MetricDataPoint {
    /// Metric name
    pub name: String,
    /// Metric value
    pub value: f64,
    /// Timestamp
    pub timestamp: u64,
    /// Labels/tags
    pub labels: HashMap<String, String>,
    /// Metric type
    pub metric_type: MetricType,
}

/// Types of metrics
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum MetricType {
    /// Counter - monotonically increasing
    Counter,
    /// Gauge - can go up and down
    Gauge,
    /// Histogram - distribution of values
    Histogram,
    /// Summary - like histogram with quantiles
    Summary,
}

/// Security event for monitoring
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityEvent {
    /// Event type
    pub event_type: SecurityEventType,
    /// User ID (if applicable)
    pub user_id: Option<String>,
    /// IP address
    pub ip_address: Option<String>,
    /// Event details
    pub details: HashMap<String, String>,
    /// Severity level
    pub severity: SecurityEventSeverity,
    /// Timestamp
    pub timestamp: u64,
}

impl SecurityEvent {
    /// Start building a new [`SecurityEvent`] of the given type and severity.
    ///
    /// The builder auto-fills `timestamp` at build time, so callers only need
    /// to supply the fields that are relevant to the event.
    ///
    /// # Example
    /// ```rust,ignore
    /// let event = SecurityEvent::builder(SecurityEventType::FailedLogin, SecurityEventSeverity::Medium)
    ///     .user("user-123")
    ///     .ip("192.168.1.1")
    ///     .detail("reason", "bad password")
    ///     .build();
    /// ```
    pub fn builder(
        event_type: SecurityEventType,
        severity: SecurityEventSeverity,
    ) -> SecurityEventBuilder {
        SecurityEventBuilder {
            event_type,
            severity,
            user_id: None,
            ip_address: None,
            details: HashMap::new(),
        }
    }
}

/// Ergonomic builder for [`SecurityEvent`].
///
/// Created via [`SecurityEvent::builder()`].
pub struct SecurityEventBuilder {
    event_type: SecurityEventType,
    severity: SecurityEventSeverity,
    user_id: Option<String>,
    ip_address: Option<String>,
    details: HashMap<String, String>,
}

impl SecurityEventBuilder {
    /// Attach a user ID to this event.
    pub fn user(mut self, user_id: impl Into<String>) -> Self {
        self.user_id = Some(user_id.into());
        self
    }

    /// Attach an IP address to this event.
    pub fn ip(mut self, ip_address: impl Into<String>) -> Self {
        self.ip_address = Some(ip_address.into());
        self
    }

    /// Add a single key-value detail to the event.
    pub fn detail(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.details.insert(key.into(), value.into());
        self
    }

    /// Add multiple details at once from an iterator.
    pub fn details(
        mut self,
        iter: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
    ) -> Self {
        for (k, v) in iter {
            self.details.insert(k.into(), v.into());
        }
        self
    }

    /// Build the [`SecurityEvent`], setting the timestamp to the current time.
    pub fn build(self) -> SecurityEvent {
        SecurityEvent {
            event_type: self.event_type,
            user_id: self.user_id,
            ip_address: self.ip_address,
            details: self.details,
            severity: self.severity,
            timestamp: SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs(),
        }
    }
}

/// Security event types
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum SecurityEventType {
    /// Failed login attempt
    FailedLogin,
    /// Account lockout
    AccountLockout,
    /// Privilege escalation
    PrivilegeEscalation,
    /// Unusual activity pattern
    UnusualActivity,
    /// Token manipulation
    TokenManipulation,
    /// Configuration change
    ConfigurationChange,
    /// System error
    SystemError,
}

/// Security event severity levels
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, PartialOrd)]
pub enum SecurityEventSeverity {
    /// Low severity
    Low = 1,
    /// Medium severity
    Medium = 2,
    /// High severity
    High = 3,
    /// Critical severity
    Critical = 4,
}

/// Performance metrics
#[derive(Debug, Clone)]
pub struct PerformanceMetrics {
    /// Authentication request count
    pub auth_requests: Arc<AtomicU64>,
    /// Successful authentications
    pub auth_successes: Arc<AtomicU64>,
    /// Failed authentications
    pub auth_failures: Arc<AtomicU64>,
    /// Token creation count
    pub token_creations: Arc<AtomicU64>,
    /// Token validation count
    pub token_validations: Arc<AtomicU64>,
    /// Session count
    pub active_sessions: Arc<AtomicU64>,
    /// MFA challenges
    pub mfa_challenges: Arc<AtomicU64>,
    /// Average response time (microseconds)
    pub avg_response_time: Arc<AtomicU64>,
}

impl Default for PerformanceMetrics {
    fn default() -> Self {
        Self {
            auth_requests: Arc::new(AtomicU64::new(0)),
            auth_successes: Arc::new(AtomicU64::new(0)),
            auth_failures: Arc::new(AtomicU64::new(0)),
            token_creations: Arc::new(AtomicU64::new(0)),
            token_validations: Arc::new(AtomicU64::new(0)),
            active_sessions: Arc::new(AtomicU64::new(0)),
            mfa_challenges: Arc::new(AtomicU64::new(0)),
            avg_response_time: Arc::new(AtomicU64::new(0)),
        }
    }
}

/// Health check status
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum HealthStatus {
    /// All systems operational
    Healthy,
    /// Minor issues, still functional
    Degraded,
    /// Major issues, limited functionality
    Unhealthy,
    /// System down
    Critical,
}

/// Health check result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HealthCheckResult {
    /// Component name
    pub component: String,
    /// Health status
    pub status: HealthStatus,
    /// Status message
    pub message: String,
    /// Last check timestamp
    pub timestamp: u64,
    /// Response time in milliseconds
    pub response_time: u64,
}

/// Main monitoring manager
pub struct MonitoringManager {
    /// Configuration
    config: MonitoringConfig,
    /// Performance metrics
    performance: PerformanceMetrics,
    /// Metric history
    metrics_history: Arc<RwLock<Vec<MetricDataPoint>>>,
    /// Security events
    security_events: Arc<RwLock<Vec<SecurityEvent>>>,
    /// Health check results
    health_results: Arc<RwLock<HashMap<String, HealthCheckResult>>>,
}

impl MonitoringManager {
    /// Create new monitoring manager
    pub fn new(config: MonitoringConfig) -> Self {
        Self {
            config,
            performance: PerformanceMetrics::default(),
            metrics_history: Arc::new(RwLock::new(Vec::new())),
            security_events: Arc::new(RwLock::new(Vec::new())),
            health_results: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    /// Record authentication request
    pub async fn record_auth_request(&self) {
        self.performance
            .auth_requests
            .fetch_add(1, Ordering::Relaxed);

        if self.config.enable_performance_metrics {
            self.record_metric(MetricDataPoint {
                name: "auth_requests_total".to_string(),
                value: self.performance.auth_requests.load(Ordering::Relaxed) as f64,
                timestamp: current_timestamp(),
                labels: HashMap::new(),
                metric_type: MetricType::Counter,
            })
            .await;
        }
    }

    /// Record successful authentication
    pub async fn record_auth_success(&self, user_id: &str, duration: Duration) {
        self.performance
            .auth_successes
            .fetch_add(1, Ordering::Relaxed);
        self.update_avg_response_time(duration).await;

        if self.config.enable_performance_metrics {
            let mut labels = HashMap::new();
            labels.insert("result".to_string(), "success".to_string());
            labels.insert("user_id".to_string(), user_id.to_string());

            self.record_metric(MetricDataPoint {
                name: "auth_attempts_total".to_string(),
                value: 1.0,
                timestamp: current_timestamp(),
                labels,
                metric_type: MetricType::Counter,
            })
            .await;
        }
    }

    /// Record failed authentication
    pub async fn record_auth_failure(&self, user_id: Option<&str>, reason: &str) {
        self.performance
            .auth_failures
            .fetch_add(1, Ordering::Relaxed);

        if self.config.enable_security_metrics {
            let mut details = HashMap::new();
            details.insert("reason".to_string(), reason.to_string());
            if let Some(user) = user_id {
                details.insert("user_id".to_string(), user.to_string());
            }

            let security_event = SecurityEvent {
                event_type: SecurityEventType::FailedLogin,
                user_id: user_id.map(|s| s.to_string()),
                ip_address: None, // Would be populated from request context
                details,
                severity: SecurityEventSeverity::Medium,
                timestamp: current_timestamp(),
            };

            self.record_security_event(security_event).await;
        }

        if self.config.enable_performance_metrics {
            let mut labels = HashMap::new();
            labels.insert("result".to_string(), "failure".to_string());
            labels.insert("reason".to_string(), reason.to_string());

            self.record_metric(MetricDataPoint {
                name: "auth_attempts_total".to_string(),
                value: 1.0,
                timestamp: current_timestamp(),
                labels,
                metric_type: MetricType::Counter,
            })
            .await;
        }
    }

    /// Record token creation
    pub async fn record_token_creation(&self, token_type: &str) {
        self.performance
            .token_creations
            .fetch_add(1, Ordering::Relaxed);

        if self.config.enable_performance_metrics {
            let mut labels = HashMap::new();
            labels.insert("token_type".to_string(), token_type.to_string());

            self.record_metric(MetricDataPoint {
                name: "tokens_created_total".to_string(),
                value: 1.0,
                timestamp: current_timestamp(),
                labels,
                metric_type: MetricType::Counter,
            })
            .await;
        }
    }

    /// Record token validation
    pub async fn record_token_validation(&self, valid: bool) {
        self.performance
            .token_validations
            .fetch_add(1, Ordering::Relaxed);

        if self.config.enable_performance_metrics {
            let mut labels = HashMap::new();
            labels.insert(
                "result".to_string(),
                if valid { "valid" } else { "invalid" }.to_string(),
            );

            self.record_metric(MetricDataPoint {
                name: "tokens_validated_total".to_string(),
                value: 1.0,
                timestamp: current_timestamp(),
                labels,
                metric_type: MetricType::Counter,
            })
            .await;
        }
    }

    /// Update session count
    pub async fn update_session_count(&self, count: u64) {
        self.performance
            .active_sessions
            .store(count, Ordering::Relaxed);

        if self.config.enable_performance_metrics {
            self.record_metric(MetricDataPoint {
                name: "active_sessions".to_string(),
                value: count as f64,
                timestamp: current_timestamp(),
                labels: HashMap::new(),
                metric_type: MetricType::Gauge,
            })
            .await;
        }
    }

    /// Record MFA challenge
    pub async fn record_mfa_challenge(&self, method: &str) {
        self.performance
            .mfa_challenges
            .fetch_add(1, Ordering::Relaxed);

        if self.config.enable_performance_metrics {
            let mut labels = HashMap::new();
            labels.insert("method".to_string(), method.to_string());

            self.record_metric(MetricDataPoint {
                name: "mfa_challenges_total".to_string(),
                value: 1.0,
                timestamp: current_timestamp(),
                labels,
                metric_type: MetricType::Counter,
            })
            .await;
        }
    }

    /// Record security event
    pub async fn record_security_event(&self, event: SecurityEvent) {
        if !self.config.enable_security_metrics {
            return;
        }

        let mut events = self.security_events.write().await;
        events.push(event.clone());

        // Keep only recent events
        if events.len() > self.config.max_history_size {
            events.remove(0);
        }

        tracing::warn!(
            "Security event: {:?} - User: {:?}, Severity: {:?}",
            event.event_type,
            event.user_id,
            event.severity
        );

        // Alert on critical events
        if event.severity == SecurityEventSeverity::Critical {
            // Would trigger external alerting system
            tracing::error!("CRITICAL security event: {:?}", event);
        }
    }

    /// Record generic metric
    async fn record_metric(&self, metric: MetricDataPoint) {
        if !self.config.enabled {
            return;
        }

        let mut metrics = self.metrics_history.write().await;
        metrics.push(metric);

        // Keep history size manageable
        if metrics.len() > self.config.max_history_size {
            metrics.remove(0);
        }
    }

    /// Update average response time
    async fn update_avg_response_time(&self, duration: Duration) {
        let current_avg = self.performance.avg_response_time.load(Ordering::Relaxed);
        let new_time = duration.as_micros() as u64;

        // Simple moving average
        let updated_avg = if current_avg == 0 {
            new_time
        } else {
            (current_avg + new_time) / 2
        };

        self.performance
            .avg_response_time
            .store(updated_avg, Ordering::Relaxed);
    }

    /// Get current performance metrics
    pub fn get_performance_metrics(&self) -> HashMap<String, u64> {
        let mut metrics = HashMap::new();
        metrics.insert(
            "auth_requests".to_string(),
            self.performance.auth_requests.load(Ordering::Relaxed),
        );
        metrics.insert(
            "auth_successes".to_string(),
            self.performance.auth_successes.load(Ordering::Relaxed),
        );
        metrics.insert(
            "auth_failures".to_string(),
            self.performance.auth_failures.load(Ordering::Relaxed),
        );
        metrics.insert(
            "token_creations".to_string(),
            self.performance.token_creations.load(Ordering::Relaxed),
        );
        metrics.insert(
            "token_validations".to_string(),
            self.performance.token_validations.load(Ordering::Relaxed),
        );
        metrics.insert(
            "active_sessions".to_string(),
            self.performance.active_sessions.load(Ordering::Relaxed),
        );
        metrics.insert(
            "mfa_challenges".to_string(),
            self.performance.mfa_challenges.load(Ordering::Relaxed),
        );
        metrics.insert(
            "avg_response_time_us".to_string(),
            self.performance.avg_response_time.load(Ordering::Relaxed),
        );
        metrics
    }

    /// Get security events
    pub async fn get_security_events(&self, limit: Option<usize>) -> Vec<SecurityEvent> {
        let events = self.security_events.read().await;
        let limit = limit.unwrap_or(100);

        if events.len() <= limit {
            events.clone()
        } else {
            events.iter().rev().take(limit).cloned().collect()
        }
    }

    /// Get metrics history
    pub async fn get_metrics_history(&self, metric_name: Option<&str>) -> Vec<MetricDataPoint> {
        let metrics = self.metrics_history.read().await;

        if let Some(name) = metric_name {
            metrics.iter().filter(|m| m.name == name).cloned().collect()
        } else {
            metrics.clone()
        }
    }

    /// Perform health check
    pub async fn health_check(&self) -> Result<HashMap<String, HealthCheckResult>> {
        if !self.config.enable_health_checks {
            let mut results = HashMap::new();
            let timestamp = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs();
            results.insert(
                "monitoring".to_string(),
                HealthCheckResult {
                    component: "monitoring".to_string(),
                    status: HealthStatus::Healthy,
                    message: "Health checks disabled; monitoring subsystem not active"
                        .to_string(),
                    timestamp,
                    response_time: 0,
                },
            );
            return Ok(results);
        }

        let mut results = HashMap::new();
        let start_time = SystemTime::now();

        // Check authentication system health
        let auth_health = self.check_auth_health().await;
        results.insert("authentication".to_string(), auth_health);

        // Check storage health
        let storage_health = self.check_storage_health().await;
        results.insert("storage".to_string(), storage_health);

        // Check token system health
        let token_health = self.check_token_health().await;
        results.insert("tokens".to_string(), token_health);

        // Update health results cache
        let mut health_cache = self.health_results.write().await;
        for (component, result) in &results {
            health_cache.insert(component.clone(), result.clone());
        }

        let elapsed = start_time.elapsed().unwrap_or_default();
        tracing::debug!("Health check completed in {:?}", elapsed);

        Ok(results)
    }

    /// Check authentication system health
    async fn check_auth_health(&self) -> HealthCheckResult {
        let start_time = SystemTime::now();

        // Check basic metrics
        let auth_requests = self.performance.auth_requests.load(Ordering::Relaxed);
        let auth_failures = self.performance.auth_failures.load(Ordering::Relaxed);

        let status = if auth_requests > 0 {
            let failure_rate = (auth_failures as f64) / (auth_requests as f64);
            if failure_rate > 0.5 {
                HealthStatus::Unhealthy
            } else if failure_rate > 0.2 {
                HealthStatus::Degraded
            } else {
                HealthStatus::Healthy
            }
        } else {
            HealthStatus::Healthy
        };

        let message = match status {
            HealthStatus::Healthy => "Authentication system operating normally".to_string(),
            HealthStatus::Degraded => format!(
                "High failure rate: {:.1}%",
                (auth_failures as f64 / auth_requests as f64) * 100.0
            ),
            HealthStatus::Unhealthy => format!(
                "Critical failure rate: {:.1}%",
                (auth_failures as f64 / auth_requests as f64) * 100.0
            ),
            HealthStatus::Critical => "Authentication system down".to_string(),
        };

        HealthCheckResult {
            component: "authentication".to_string(),
            status,
            message,
            timestamp: current_timestamp(),
            response_time: start_time.elapsed().unwrap_or_default().as_millis() as u64,
        }
    }

    /// Check storage system health
    async fn check_storage_health(&self) -> HealthCheckResult {
        let start_time = SystemTime::now();

        // Test storage connectivity with a simple operation
        let status = match self.test_storage_connectivity().await {
            Ok(response_time_ms) => {
                if response_time_ms > 5000 {
                    HealthStatus::Degraded
                } else {
                    HealthStatus::Healthy
                }
            }
            Err(e) => {
                warn!("Storage health check failed: {}", e);
                HealthStatus::Critical
            }
        };

        let message = match status {
            HealthStatus::Healthy => "Storage system operational".to_string(),
            HealthStatus::Degraded => "Storage system slow but operational".to_string(),
            HealthStatus::Critical => "Storage system connectivity failed".to_string(),
            HealthStatus::Unhealthy => "Storage system unhealthy".to_string(),
        };

        HealthCheckResult {
            component: "storage".to_string(),
            status,
            message,
            timestamp: current_timestamp(),
            response_time: start_time.elapsed().unwrap_or_default().as_millis() as u64,
        }
    }

    /// Test storage connectivity with a lightweight operation
    async fn test_storage_connectivity(
        &self,
    ) -> Result<u64, Box<dyn std::error::Error + Send + Sync>> {
        let start_time = SystemTime::now();

        // Attempt a simple storage operation to test connectivity
        // This is a lightweight test that doesn't affect application data
        match tokio::time::timeout(
            std::time::Duration::from_secs(5),
            self.attempt_storage_ping(),
        )
        .await
        {
            Ok(result) => {
                result?;
                let response_time = start_time.elapsed()?.as_millis() as u64;
                Ok(response_time)
            }
            Err(_) => Err("Storage connectivity test timed out".into()),
        }
    }

    /// Attempt to ping the storage system
    async fn attempt_storage_ping(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        // Verify internal data structures are accessible and locks aren't deadlocked.
        // This is a meaningful liveness check without requiring an external storage dependency.
        let _history = self.metrics_history.read().await;
        let _health = self.health_results.read().await;
        Ok(())
    }

    /// Check token system health
    async fn check_token_health(&self) -> HealthCheckResult {
        let start_time = SystemTime::now();

        let token_validations = self.performance.token_validations.load(Ordering::Relaxed);

        HealthCheckResult {
            component: "tokens".to_string(),
            status: HealthStatus::Healthy,
            message: format!(
                "Token system operational - {} validations",
                token_validations
            ),
            timestamp: current_timestamp(),
            response_time: start_time.elapsed().unwrap_or_default().as_millis() as u64,
        }
    }

    /// Export metrics in Prometheus format
    pub async fn export_prometheus_metrics(&self) -> String {
        let mut output = String::new();

        let metrics = self.get_performance_metrics();

        for (name, value) in metrics {
            output.push_str(&format!(
                "# HELP auth_{} Authentication framework metric\n",
                name
            ));
            output.push_str(&format!("# TYPE auth_{} counter\n", name));
            output.push_str(&format!("auth_{} {}\n", name, value));
        }

        output
    }
}

/// Get current Unix timestamp
fn current_timestamp() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs()
}

#[cfg(test)]
mod tests {
    use super::*;
    use tokio;

    #[tokio::test]
    async fn test_monitoring_manager_creation() {
        let config = MonitoringConfig::default();
        let manager = MonitoringManager::new(config);

        let metrics = manager.get_performance_metrics();
        assert_eq!(metrics["auth_requests"], 0);
    }

    #[tokio::test]
    async fn test_auth_request_recording() {
        let config = MonitoringConfig::default();
        let manager = MonitoringManager::new(config);

        manager.record_auth_request().await;
        manager.record_auth_request().await;

        let metrics = manager.get_performance_metrics();
        assert_eq!(metrics["auth_requests"], 2);
    }

    #[tokio::test]
    async fn test_security_event_recording() {
        let config = MonitoringConfig::default();
        let manager = MonitoringManager::new(config);

        let event = SecurityEvent {
            event_type: SecurityEventType::FailedLogin,
            user_id: Some("test_user".to_string()),
            ip_address: Some("127.0.0.1".to_string()),
            details: HashMap::new(),
            severity: SecurityEventSeverity::Medium,
            timestamp: current_timestamp(),
        };

        manager.record_security_event(event).await;

        let events = manager.get_security_events(None).await;
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].event_type, SecurityEventType::FailedLogin);
    }

    #[tokio::test]
    async fn test_security_event_builder() {
        let event = SecurityEvent::builder(
            SecurityEventType::AccountLockout,
            SecurityEventSeverity::High,
        )
        .user("user-42")
        .ip("10.0.0.1")
        .detail("reason", "too many failures")
        .detail("attempts", "5")
        .build();

        assert_eq!(event.event_type, SecurityEventType::AccountLockout);
        assert_eq!(event.severity, SecurityEventSeverity::High);
        assert_eq!(event.user_id.as_deref(), Some("user-42"));
        assert_eq!(event.ip_address.as_deref(), Some("10.0.0.1"));
        assert_eq!(event.details.len(), 2);
        assert_eq!(event.details["reason"], "too many failures");
        assert!(event.timestamp > 0);
    }

    #[tokio::test]
    async fn test_security_event_builder_minimal() {
        let event = SecurityEvent::builder(
            SecurityEventType::SystemError,
            SecurityEventSeverity::Low,
        )
        .build();

        assert_eq!(event.event_type, SecurityEventType::SystemError);
        assert!(event.user_id.is_none());
        assert!(event.ip_address.is_none());
        assert!(event.details.is_empty());
    }

    #[tokio::test]
    async fn test_health_check() {
        let config = MonitoringConfig::default();
        let manager = MonitoringManager::new(config);

        let health_results = manager.health_check().await.unwrap();

        assert!(health_results.contains_key("authentication"));
        assert!(health_results.contains_key("storage"));
        assert!(health_results.contains_key("tokens"));
    }

    #[tokio::test]
    async fn test_prometheus_export() {
        let config = MonitoringConfig::default();
        let manager = MonitoringManager::new(config);

        manager.record_auth_request().await;

        let prometheus_output = manager.export_prometheus_metrics().await;

        assert!(prometheus_output.contains("auth_auth_requests"));
        assert!(prometheus_output.contains("# HELP"));
        assert!(prometheus_output.contains("# TYPE"));
    }
}