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
//! Security presets for the Auth Framework
//!
//! This module provides pre-configured security levels that automatically
//! apply appropriate security settings for different environments and use cases.
//!
//! # Security Presets
//!
//! - **Development**: Convenient settings for development environments
//! - **Balanced**: Good security with reasonable performance (default)
//! - **HighSecurity**: Strong security for sensitive applications
//! - **Paranoid**: Maximum security settings for high-risk environments
//!
//! # Usage
//!
//! ```rust,no_run
//! # #[tokio::main]
//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! use auth_framework::prelude::*;
//!
//! // Quick setup with security preset
//! let auth = AuthFramework::quick_start()
//!     .jwt_auth_from_env()
//!     .security_level(SecurityPreset::HighSecurity)
//!     .build().await?;
//!
//! // Or apply to existing configuration
//! let config = AuthConfig::new()
//!     .security(SecurityPreset::Paranoid.to_config());
//! # Ok(())
//! # }
//! ```
//!
//! # Security Validation
//!
//! Each preset includes built-in validation to ensure security requirements
//! are met for the target environment:
//!
//! ```rust,no_run
//! # #[tokio::main]
//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! use auth_framework::prelude::*;
//!
//! // Validate security configuration
//! let issues = SecurityPreset::HighSecurity
//!     .validate_environment()
//!     .await?;
//!
//! for issue in issues {
//!     println!("⚠️  {}: {}", issue.severity, issue.description);
//!     println!("💡 Fix: {}", issue.suggestion);
//! }
//! # Ok(())
//! # }
//! ```

use crate::{
    config::{
        AuditConfig, AuditStorage, CookieSameSite, JwtAlgorithm, PasswordHashAlgorithm,
        RateLimitConfig, SecurityConfig,
    },
    prelude::{AuthFrameworkResult, hours, minutes},
};
use std::time::Duration;

/// Security presets for common configurations
#[derive(Debug, Clone, PartialEq)]
pub enum SecurityPreset {
    /// Development-friendly settings (lower security, more convenient)
    ///
    /// **USE ONLY FOR DEVELOPMENT - NOT PRODUCTION SAFE**
    ///
    /// - Shorter passwords allowed (6+ chars)
    /// - Weaker password requirements
    /// - Less strict cookie settings
    /// - Disabled CSRF protection for easier testing
    /// - Longer session timeouts for convenience
    Development,

    /// Balanced settings for most applications
    ///
    /// Good balance of security and usability suitable for most production
    /// applications that don't handle highly sensitive data.
    ///
    /// - Standard password requirements (8+ chars)
    /// - Secure cookies and CSRF protection
    /// - Reasonable rate limiting
    /// - Basic audit logging
    Balanced,

    /// High security settings for sensitive applications
    ///
    /// Strong security settings suitable for applications handling
    /// sensitive data like financial information, healthcare records,
    /// or personal data subject to compliance requirements.
    ///
    /// - Strict password requirements (12+ chars, complexity)
    /// - Strong JWT algorithms (RSA-256)
    /// - Aggressive rate limiting
    /// - Comprehensive audit logging
    /// - Short session timeouts
    HighSecurity,

    /// Maximum security (paranoid mode)
    ///
    /// Extremely strict security settings for high-risk environments
    /// where security is paramount over convenience.
    ///
    /// - Very strict password requirements (16+ chars)
    /// - Strongest cryptographic algorithms
    /// - Very aggressive rate limiting
    /// - Extensive audit logging and monitoring
    /// - Very short session timeouts
    /// - Constant-time operations
    Paranoid,
}

/// Security validation issue
#[derive(Debug, Clone)]
pub struct SecurityIssue {
    /// Severity level of the issue
    pub severity: SecuritySeverity,
    /// Component that has the issue
    pub component: String,
    /// Description of the security issue
    pub description: String,
    /// Suggested fix for the issue
    pub suggestion: String,
    /// Whether this issue blocks production deployment
    pub blocks_production: bool,
}

/// Security issue severity levels
#[derive(Debug, Clone, PartialEq, PartialOrd)]
pub enum SecuritySeverity {
    /// Information about security configuration
    Info,
    /// Security recommendation that should be addressed
    Warning,
    /// Security issue that should be fixed
    Error,
    /// Critical security issue that must be fixed
    Critical,
}

impl SecurityPreset {
    /// Convert the security preset to a SecurityConfig
    pub fn to_config(&self) -> SecurityConfig {
        match self {
            SecurityPreset::Development => SecurityConfig {
                min_password_length: 6,
                require_password_complexity: false,
                password_hash_algorithm: PasswordHashAlgorithm::Bcrypt, // Faster for development
                jwt_algorithm: JwtAlgorithm::HS256,
                secret_key: None, // Must be set externally
                previous_secret_key: None,
                secure_cookies: false, // Allow HTTP for local development
                cookie_same_site: CookieSameSite::Lax,
                csrf_protection: false,     // Easier API testing
                session_timeout: hours(24), // Long timeout for development convenience
            },
            SecurityPreset::Balanced => SecurityConfig {
                min_password_length: 8,
                require_password_complexity: true,
                password_hash_algorithm: PasswordHashAlgorithm::Argon2,
                jwt_algorithm: JwtAlgorithm::HS256,
                secret_key: None,
                previous_secret_key: None,
                secure_cookies: true,
                cookie_same_site: CookieSameSite::Lax,
                csrf_protection: true,
                session_timeout: hours(8),
            },
            SecurityPreset::HighSecurity => SecurityConfig {
                min_password_length: 12,
                require_password_complexity: true,
                password_hash_algorithm: PasswordHashAlgorithm::Argon2,
                jwt_algorithm: JwtAlgorithm::RS256, // RSA for better security
                secret_key: None,
                previous_secret_key: None,
                secure_cookies: true,
                cookie_same_site: CookieSameSite::Strict,
                csrf_protection: true,
                session_timeout: hours(2), // Shorter sessions
            },
            SecurityPreset::Paranoid => SecurityConfig {
                min_password_length: 16,
                require_password_complexity: true,
                password_hash_algorithm: PasswordHashAlgorithm::Argon2,
                jwt_algorithm: JwtAlgorithm::RS512, // Strongest RSA
                secret_key: None,
                previous_secret_key: None,
                secure_cookies: true,
                cookie_same_site: CookieSameSite::Strict,
                csrf_protection: true,
                session_timeout: minutes(30), // Very short sessions
            },
        }
    }

    /// Get rate limiting configuration for this security preset
    pub fn to_rate_limit_config(&self) -> RateLimitConfig {
        match self {
            SecurityPreset::Development => RateLimitConfig {
                enabled: false, // Disabled for easier development
                max_requests: 1000,
                window: Duration::from_secs(60),
                burst: 100,
            },
            SecurityPreset::Balanced => RateLimitConfig {
                enabled: true,
                max_requests: 100,
                window: Duration::from_secs(60),
                burst: 20,
            },
            SecurityPreset::HighSecurity => RateLimitConfig {
                enabled: true,
                max_requests: 60, // 1 per second average
                window: Duration::from_secs(60),
                burst: 10,
            },
            SecurityPreset::Paranoid => RateLimitConfig {
                enabled: true,
                max_requests: 30, // 0.5 per second average
                window: Duration::from_secs(60),
                burst: 5,
            },
        }
    }

    /// Get audit configuration for this security preset
    pub fn to_audit_config(&self) -> AuditConfig {
        match self {
            SecurityPreset::Development => AuditConfig {
                enabled: false, // Disabled for cleaner development logs
                log_success: false,
                log_failures: true, // Still log failures for debugging
                log_permissions: false,
                log_tokens: false,
                storage: AuditStorage::Tracing,
            },
            SecurityPreset::Balanced => AuditConfig {
                enabled: true,
                log_success: false, // Don't log every success to reduce noise
                log_failures: true,
                log_permissions: true,
                log_tokens: false, // Tokens can be sensitive
                storage: AuditStorage::Tracing,
            },
            SecurityPreset::HighSecurity => AuditConfig {
                enabled: true,
                log_success: true,
                log_failures: true,
                log_permissions: true,
                log_tokens: false,
                storage: AuditStorage::Tracing, // Should be database in real deployment
            },
            SecurityPreset::Paranoid => AuditConfig {
                enabled: true,
                log_success: true,
                log_failures: true,
                log_permissions: true,
                log_tokens: true,               // Log everything in paranoid mode
                storage: AuditStorage::Tracing, // Should be secure external service
            },
        }
    }

    /// Validate the current environment against this security preset
    pub async fn validate_environment(&self) -> AuthFrameworkResult<Vec<SecurityIssue>> {
        let mut issues = Vec::new();

        // Check environment type
        let is_production = self.is_production_environment();
        let is_development = self.is_development_environment();

        // Validate preset appropriateness for environment
        match (self, is_production, is_development) {
            (SecurityPreset::Development, true, false) => {
                issues.push(SecurityIssue {
                    severity: SecuritySeverity::Critical,
                    component: "Security Preset".to_string(),
                    description: "Development security preset used in production environment".to_string(),
                    suggestion: "Use SecurityPreset::HighSecurity or SecurityPreset::Paranoid for production".to_string(),
                    blocks_production: true,
                });
            }
            (SecurityPreset::Balanced, true, false) => {
                issues.push(SecurityIssue {
                    severity: SecuritySeverity::Warning,
                    component: "Security Preset".to_string(),
                    description:
                        "Balanced security preset in production - consider higher security"
                            .to_string(),
                    suggestion: "Consider SecurityPreset::HighSecurity for better protection"
                        .to_string(),
                    blocks_production: false,
                });
            }
            _ => {} // Other combinations are acceptable
        }

        // Check JWT secret
        self.validate_jwt_secret(&mut issues);

        // Check HTTPS in production
        if is_production && self.requires_secure_cookies() {
            self.validate_https_requirement(&mut issues);
        }

        // Check database configuration
        self.validate_storage_security(&mut issues);

        // Check environment variables
        self.validate_environment_variables(&mut issues);

        Ok(issues)
    }

    /// Perform a security audit of the current configuration
    pub async fn security_audit(&self) -> AuthFrameworkResult<SecurityAuditReport> {
        let issues = self.validate_environment().await?;

        let critical_count = issues
            .iter()
            .filter(|i| i.severity == SecuritySeverity::Critical)
            .count();
        let error_count = issues
            .iter()
            .filter(|i| i.severity == SecuritySeverity::Error)
            .count();
        let warning_count = issues
            .iter()
            .filter(|i| i.severity == SecuritySeverity::Warning)
            .count();

        let overall_status = if critical_count > 0 {
            SecurityAuditStatus::Critical
        } else if error_count > 0 {
            SecurityAuditStatus::Failed
        } else if warning_count > 0 {
            SecurityAuditStatus::Warning
        } else {
            SecurityAuditStatus::Passed
        };

        Ok(SecurityAuditReport {
            preset: self.clone(),
            status: overall_status,
            issues,
            critical_count,
            error_count,
            warning_count,
            recommendations: self.get_security_recommendations(),
        })
    }

    /// Get security recommendations for this preset
    pub fn get_security_recommendations(&self) -> Vec<String> {
        let mut recommendations = Vec::new();

        match self {
            SecurityPreset::Development => {
                recommendations.push(
                    "⚠️  Development preset detected - ensure this is not used in production"
                        .to_string(),
                );
                recommendations
                    .push("🔐 Set JWT_SECRET environment variable with a secure value".to_string());
                recommendations
                    .push("📝 Enable audit logging when moving to production".to_string());
            }
            SecurityPreset::Balanced => {
                recommendations.push(
                    "🔒 Consider upgrading to HighSecurity for sensitive applications".to_string(),
                );
                recommendations
                    .push("📊 Monitor authentication patterns for suspicious activity".to_string());
                recommendations.push("🔄 Regularly rotate JWT secrets and API keys".to_string());
            }
            SecurityPreset::HighSecurity => {
                recommendations
                    .push("✅ Good security configuration for production use".to_string());
                recommendations
                    .push("🔐 Ensure RSA keys are properly managed and rotated".to_string());
                recommendations.push("📈 Monitor failed authentication attempts".to_string());
                recommendations.push(
                    "🛡️  Consider multi-factor authentication for admin accounts".to_string(),
                );
            }
            SecurityPreset::Paranoid => {
                recommendations
                    .push("🛡️  Maximum security enabled - monitor performance impact".to_string());
                recommendations.push(
                    "⚡ Consider connection pooling to handle strict rate limits".to_string(),
                );
                recommendations.push("🔍 Implement comprehensive security monitoring".to_string());
                recommendations
                    .push("🚨 Set up alerting for all authentication failures".to_string());
            }
        }

        recommendations
    }

    // Helper methods for validation

    fn is_production_environment(&self) -> bool {
        std::env::var("ENVIRONMENT").as_deref() == Ok("production")
            || std::env::var("ENV").as_deref() == Ok("production")
            || std::env::var("NODE_ENV").as_deref() == Ok("production")
            || std::env::var("RUST_ENV").as_deref() == Ok("production")
            || std::env::var("KUBERNETES_SERVICE_HOST").is_ok()
    }

    fn is_development_environment(&self) -> bool {
        std::env::var("ENVIRONMENT").as_deref() == Ok("development")
            || std::env::var("ENV").as_deref() == Ok("development")
            || std::env::var("NODE_ENV").as_deref() == Ok("development")
            || std::env::var("RUST_ENV").as_deref() == Ok("development")
            || cfg!(debug_assertions)
    }

    fn requires_secure_cookies(&self) -> bool {
        matches!(
            self,
            SecurityPreset::Balanced | SecurityPreset::HighSecurity | SecurityPreset::Paranoid
        )
    }

    fn validate_jwt_secret(&self, issues: &mut Vec<SecurityIssue>) {
        if let Ok(secret) = std::env::var("JWT_SECRET") {
            let min_length = match self {
                SecurityPreset::Development => 16,
                SecurityPreset::Balanced => 32,
                SecurityPreset::HighSecurity => 64,
                SecurityPreset::Paranoid => 128,
            };

            if secret.len() < min_length {
                issues.push(SecurityIssue {
                    severity: if matches!(self, SecurityPreset::Development) {
                        SecuritySeverity::Warning
                    } else {
                        SecuritySeverity::Error
                    },
                    component: "JWT Secret".to_string(),
                    description: format!(
                        "JWT secret too short ({} chars, need {}+)",
                        secret.len(),
                        min_length
                    ),
                    suggestion: format!(
                        "Generate a longer secret: `openssl rand -base64 {}`",
                        min_length * 3 / 4
                    ),
                    blocks_production: !matches!(self, SecurityPreset::Development),
                });
            }

            // Check for weak patterns
            if secret.to_lowercase().contains("secret")
                || secret.to_lowercase().contains("password")
                || secret.contains("123")
            {
                issues.push(SecurityIssue {
                    severity: SecuritySeverity::Error,
                    component: "JWT Secret".to_string(),
                    description: "JWT secret contains weak patterns or common words".to_string(),
                    suggestion:
                        "Use a cryptographically secure random string: `openssl rand -base64 64`"
                            .to_string(),
                    blocks_production: true,
                });
            }
        } else {
            issues.push(SecurityIssue {
                severity: SecuritySeverity::Critical,
                component: "JWT Secret".to_string(),
                description: "JWT_SECRET environment variable not set".to_string(),
                suggestion: "Set JWT_SECRET environment variable with a secure random value"
                    .to_string(),
                blocks_production: true,
            });
        }
    }

    fn validate_https_requirement(&self, issues: &mut Vec<SecurityIssue>) {
        // In a real implementation, this would check if HTTPS is properly configured
        // For now, we'll check for common HTTPS indicators
        let has_tls_cert =
            std::env::var("TLS_CERT_PATH").is_ok() || std::env::var("SSL_CERT_PATH").is_ok();
        let behind_proxy = std::env::var("HTTPS").as_deref() == Ok("on")
            || std::env::var("HTTP_X_FORWARDED_PROTO").as_deref() == Ok("https");

        if !has_tls_cert && !behind_proxy {
            issues.push(SecurityIssue {
                severity: SecuritySeverity::Warning,
                component: "HTTPS".to_string(),
                description: "HTTPS configuration not detected".to_string(),
                suggestion: "Ensure HTTPS is properly configured for secure cookie transmission"
                    .to_string(),
                blocks_production: false,
            });
        }
    }

    fn validate_storage_security(&self, issues: &mut Vec<SecurityIssue>) {
        // Check for database connection security
        if let Ok(db_url) = std::env::var("DATABASE_URL")
            && db_url.starts_with("postgresql://")
            && !db_url.contains("sslmode=require")
        {
            issues.push(SecurityIssue {
                severity: SecuritySeverity::Warning,
                component: "Database".to_string(),
                description: "Database connection may not be using SSL".to_string(),
                suggestion: "Add sslmode=require to DATABASE_URL for encrypted connections"
                    .to_string(),
                blocks_production: false,
            });
        }

        if let Ok(redis_url) = std::env::var("REDIS_URL")
            && !redis_url.starts_with("rediss://")
            && !redis_url.contains("tls")
        {
            issues.push(SecurityIssue {
                severity: SecuritySeverity::Info,
                component: "Redis".to_string(),
                description: "Redis connection may not be using TLS".to_string(),
                suggestion: "Consider using rediss:// URL or enabling TLS for Redis connections"
                    .to_string(),
                blocks_production: false,
            });
        }
    }

    fn validate_environment_variables(&self, issues: &mut Vec<SecurityIssue>) {
        let sensitive_vars = [
            "JWT_SECRET",
            "DATABASE_URL",
            "REDIS_URL",
            "OAUTH_CLIENT_SECRET",
        ];

        for var in &sensitive_vars {
            if let Ok(value) = std::env::var(var)
                && value.len() < 20
            {
                issues.push(SecurityIssue {
                    severity: SecuritySeverity::Warning,
                    component: "Environment Variables".to_string(),
                    description: format!("{} appears to be too short", var),
                    suggestion: format!(
                        "Ensure {} contains a sufficiently long, secure value",
                        var
                    ),
                    blocks_production: false,
                });
            }
        }
    }
}

/// Security audit report
#[derive(Debug, Clone)]
pub struct SecurityAuditReport {
    pub preset: SecurityPreset,
    pub status: SecurityAuditStatus,
    pub issues: Vec<SecurityIssue>,
    pub critical_count: usize,
    pub error_count: usize,
    pub warning_count: usize,
    pub recommendations: Vec<String>,
}

/// Overall security audit status
#[derive(Debug, Clone, PartialEq)]
pub enum SecurityAuditStatus {
    /// All security checks passed
    Passed,
    /// Non-critical warnings found
    Warning,
    /// Security errors found that should be addressed
    Failed,
    /// Critical security issues that block production deployment
    Critical,
}

impl SecurityAuditReport {
    /// Print a formatted security report to stdout
    pub fn print_report(&self) {
        println!("🔒 Security Audit Report");
        println!("========================");
        println!("Preset: {:?}", self.preset);
        println!("Status: {}", self.status_emoji());
        println!();

        if self.issues.is_empty() {
            println!("✅ No security issues found!");
        } else {
            println!("📊 Issues Summary:");
            println!("   Critical: {}", self.critical_count);
            println!("   Errors: {}", self.error_count);
            println!("   Warnings: {}", self.warning_count);
            println!();

            for issue in &self.issues {
                println!(
                    "{} {}: {}",
                    issue.severity.emoji(),
                    issue.component,
                    issue.description
                );
                println!("   💡 {}", issue.suggestion);
                println!();
            }
        }

        if !self.recommendations.is_empty() {
            println!("📋 Recommendations:");
            for rec in &self.recommendations {
                println!("   {}", rec);
            }
            println!();
        }

        println!("{}", self.get_summary_message());
    }

    fn status_emoji(&self) -> &str {
        match self.status {
            SecurityAuditStatus::Passed => "✅ Passed",
            SecurityAuditStatus::Warning => "⚠️  Warning",
            SecurityAuditStatus::Failed => "❌ Failed",
            SecurityAuditStatus::Critical => "🚨 Critical",
        }
    }

    fn get_summary_message(&self) -> String {
        match self.status {
            SecurityAuditStatus::Passed => "🎉 Security audit passed! Your configuration meets security requirements.".to_string(),
            SecurityAuditStatus::Warning => "⚠️  Security audit completed with warnings. Consider addressing the issues above.".to_string(),
            SecurityAuditStatus::Failed => "❌ Security audit failed. Please address the errors before deploying to production.".to_string(),
            SecurityAuditStatus::Critical => "🚨 Critical security issues found! Do not deploy to production until these are resolved.".to_string(),
        }
    }

    /// Check if the configuration is safe for production deployment
    pub fn is_production_ready(&self) -> bool {
        matches!(
            self.status,
            SecurityAuditStatus::Passed | SecurityAuditStatus::Warning
        )
    }

    /// Get all blocking issues that prevent production deployment
    pub fn get_blocking_issues(&self) -> Vec<&SecurityIssue> {
        self.issues
            .iter()
            .filter(|issue| issue.blocks_production)
            .collect()
    }
}

impl SecuritySeverity {
    fn emoji(&self) -> &str {
        match self {
            SecuritySeverity::Info => "ℹ️ ",
            SecuritySeverity::Warning => "⚠️ ",
            SecuritySeverity::Error => "",
            SecuritySeverity::Critical => "🚨",
        }
    }
}

impl std::fmt::Display for SecuritySeverity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SecuritySeverity::Info => write!(f, "INFO"),
            SecuritySeverity::Warning => write!(f, "WARNING"),
            SecuritySeverity::Error => write!(f, "ERROR"),
            SecuritySeverity::Critical => write!(f, "CRITICAL"),
        }
    }
}

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

    #[test]
    fn test_development_preset_config() {
        let config = SecurityPreset::Development.to_config();
        assert_eq!(config.min_password_length, 6);
        assert!(!config.require_password_complexity);
        assert!(!config.secure_cookies);
        assert!(!config.csrf_protection);
    }

    #[test]
    fn test_balanced_preset_config() {
        let config = SecurityPreset::Balanced.to_config();
        assert_eq!(config.min_password_length, 8);
        assert!(config.require_password_complexity);
        assert!(config.secure_cookies);
        assert!(config.csrf_protection);
    }

    #[test]
    fn test_high_security_preset_config() {
        let config = SecurityPreset::HighSecurity.to_config();
        assert_eq!(config.min_password_length, 12);
        assert!(config.secure_cookies);
        assert!(config.csrf_protection);
        assert!(matches!(config.cookie_same_site, CookieSameSite::Strict));
    }

    #[test]
    fn test_paranoid_preset_config() {
        let config = SecurityPreset::Paranoid.to_config();
        assert_eq!(config.min_password_length, 16);
        assert!(config.csrf_protection);
        assert_eq!(config.session_timeout, minutes(30));
    }

    #[test]
    fn test_presets_have_increasing_password_length() {
        let dev = SecurityPreset::Development.to_config().min_password_length;
        let bal = SecurityPreset::Balanced.to_config().min_password_length;
        let high = SecurityPreset::HighSecurity.to_config().min_password_length;
        let paranoid = SecurityPreset::Paranoid.to_config().min_password_length;
        assert!(dev < bal);
        assert!(bal < high);
        assert!(high < paranoid);
    }

    #[test]
    fn test_presets_have_decreasing_session_timeout() {
        let dev = SecurityPreset::Development.to_config().session_timeout;
        let bal = SecurityPreset::Balanced.to_config().session_timeout;
        let high = SecurityPreset::HighSecurity.to_config().session_timeout;
        let paranoid = SecurityPreset::Paranoid.to_config().session_timeout;
        assert!(dev > bal);
        assert!(bal > high);
        assert!(high > paranoid);
    }

    #[test]
    fn test_rate_limit_configs_are_valid() {
        for preset in [
            SecurityPreset::Development,
            SecurityPreset::Balanced,
            SecurityPreset::HighSecurity,
            SecurityPreset::Paranoid,
        ] {
            let rl = preset.to_rate_limit_config();
            assert!(rl.max_requests > 0);
            assert!(!rl.window.is_zero());
        }
    }

    #[test]
    fn test_audit_configs_are_valid() {
        for preset in [
            SecurityPreset::Development,
            SecurityPreset::Balanced,
            SecurityPreset::HighSecurity,
            SecurityPreset::Paranoid,
        ] {
            let ac = preset.to_audit_config();
            // All presets produce a valid config; HighSecurity+ enable logging
            if matches!(preset, SecurityPreset::HighSecurity | SecurityPreset::Paranoid) {
                assert!(ac.enabled);
            }
        }
    }

    #[test]
    fn test_security_recommendations_non_empty() {
        for preset in [
            SecurityPreset::Development,
            SecurityPreset::Balanced,
            SecurityPreset::HighSecurity,
            SecurityPreset::Paranoid,
        ] {
            let recs = preset.get_security_recommendations();
            assert!(!recs.is_empty());
        }
    }

    #[test]
    fn test_audit_report_production_ready() {
        let report = SecurityAuditReport {
            preset: SecurityPreset::Balanced,
            status: SecurityAuditStatus::Passed,
            issues: vec![],
            critical_count: 0,
            error_count: 0,
            warning_count: 0,
            recommendations: vec![],
        };
        assert!(report.is_production_ready());
    }

    #[test]
    fn test_audit_report_not_production_ready_on_critical() {
        let report = SecurityAuditReport {
            preset: SecurityPreset::HighSecurity,
            status: SecurityAuditStatus::Critical,
            issues: vec![SecurityIssue {
                severity: SecuritySeverity::Critical,
                component: "test".into(),
                description: "fail".into(),
                suggestion: "fix".into(),
                blocks_production: true,
            }],
            critical_count: 1,
            error_count: 0,
            warning_count: 0,
            recommendations: vec![],
        };
        assert!(!report.is_production_ready());
        assert_eq!(report.get_blocking_issues().len(), 1);
    }

    #[test]
    fn test_severity_display() {
        assert_eq!(format!("{}", SecuritySeverity::Critical), "CRITICAL");
        assert_eq!(format!("{}", SecuritySeverity::Warning), "WARNING");
    }
}