Skip to main content

auth_framework/security/
presets.rs

1//! Security presets for the Auth Framework
2//!
3//! This module provides pre-configured security levels that automatically
4//! apply appropriate security settings for different environments and use cases.
5//!
6//! # Security Presets
7//!
8//! - **Development**: Convenient settings for development environments
9//! - **Balanced**: Good security with reasonable performance (default)
10//! - **HighSecurity**: Strong security for sensitive applications
11//! - **Paranoid**: Maximum security settings for high-risk environments
12//!
13//! # Usage
14//!
15//! ```rust,no_run
16//! # #[tokio::main]
17//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
18//! use auth_framework::prelude::*;
19//!
20//! // Quick setup with security preset
21//! let auth = AuthFramework::quick_start()
22//!     .jwt_auth_from_env()
23//!     .security_level(SecurityPreset::HighSecurity)
24//!     .build().await?;
25//!
26//! // Or apply to existing configuration
27//! let config = AuthConfig::new()
28//!     .security(SecurityPreset::Paranoid.to_config());
29//! # Ok(())
30//! # }
31//! ```
32//!
33//! # Security Validation
34//!
35//! Each preset includes built-in validation to ensure security requirements
36//! are met for the target environment:
37//!
38//! ```rust,no_run
39//! # #[tokio::main]
40//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
41//! use auth_framework::prelude::*;
42//!
43//! // Validate security configuration
44//! let issues = SecurityPreset::HighSecurity
45//!     .validate_environment()
46//!     .await?;
47//!
48//! for issue in issues {
49//!     println!("âš ī¸  {}: {}", issue.severity, issue.description);
50//!     println!("💡 Fix: {}", issue.suggestion);
51//! }
52//! # Ok(())
53//! # }
54//! ```
55
56use crate::{
57    config::{
58        AuditConfig, AuditStorage, CookieSameSite, JwtAlgorithm, PasswordHashAlgorithm,
59        RateLimitConfig, SecurityConfig,
60    },
61    prelude::{AuthFrameworkResult, hours, minutes},
62};
63use std::time::Duration;
64
65/// Security presets for common configurations
66#[derive(Debug, Clone, PartialEq)]
67pub enum SecurityPreset {
68    /// Development-friendly settings (lower security, more convenient)
69    ///
70    /// **USE ONLY FOR DEVELOPMENT - NOT PRODUCTION SAFE**
71    ///
72    /// - Shorter passwords allowed (6+ chars)
73    /// - Weaker password requirements
74    /// - Less strict cookie settings
75    /// - Disabled CSRF protection for easier testing
76    /// - Longer session timeouts for convenience
77    Development,
78
79    /// Balanced settings for most applications
80    ///
81    /// Good balance of security and usability suitable for most production
82    /// applications that don't handle highly sensitive data.
83    ///
84    /// - Standard password requirements (8+ chars)
85    /// - Secure cookies and CSRF protection
86    /// - Reasonable rate limiting
87    /// - Basic audit logging
88    Balanced,
89
90    /// High security settings for sensitive applications
91    ///
92    /// Strong security settings suitable for applications handling
93    /// sensitive data like financial information, healthcare records,
94    /// or personal data subject to compliance requirements.
95    ///
96    /// - Strict password requirements (12+ chars, complexity)
97    /// - Strong JWT algorithms (RSA-256)
98    /// - Aggressive rate limiting
99    /// - Comprehensive audit logging
100    /// - Short session timeouts
101    HighSecurity,
102
103    /// Maximum security (paranoid mode)
104    ///
105    /// Extremely strict security settings for high-risk environments
106    /// where security is paramount over convenience.
107    ///
108    /// - Very strict password requirements (16+ chars)
109    /// - Strongest cryptographic algorithms
110    /// - Very aggressive rate limiting
111    /// - Extensive audit logging and monitoring
112    /// - Very short session timeouts
113    /// - Constant-time operations
114    Paranoid,
115}
116
117/// Security validation issue
118#[derive(Debug, Clone)]
119pub struct SecurityIssue {
120    /// Severity level of the issue
121    pub severity: SecuritySeverity,
122    /// Component that has the issue
123    pub component: String,
124    /// Description of the security issue
125    pub description: String,
126    /// Suggested fix for the issue
127    pub suggestion: String,
128    /// Whether this issue blocks production deployment
129    pub blocks_production: bool,
130}
131
132/// Security issue severity levels
133#[derive(Debug, Clone, PartialEq, PartialOrd)]
134pub enum SecuritySeverity {
135    /// Information about security configuration
136    Info,
137    /// Security recommendation that should be addressed
138    Warning,
139    /// Security issue that should be fixed
140    Error,
141    /// Critical security issue that must be fixed
142    Critical,
143}
144
145impl SecurityPreset {
146    /// Convert the security preset to a SecurityConfig
147    ///
148    /// # Why HighSecurity/Paranoid default to ES256/ES384, not RS256/RS512
149    ///
150    /// `rsa` (the crate RS*/PS* JWT signing/verification and JARM's RSA-OAEP
151    /// JWE used to depend on) has an open, unpatched timing-sidechannel
152    /// advisory (RUSTSEC-2023-0071, "Marvin Attack") with no fix available.
153    /// Both of those paths have since been rewritten against `aws-lc-rs`
154    /// (not subject to this advisory) -- see deny.toml's RUSTSEC-2023-0071
155    /// entry for current status. These presets still default to ES256/ES384
156    /// rather than RS256/RS512: ECDSA sidesteps the RSA key-size and
157    /// padding-scheme questions entirely, which is a simpler recommendation
158    /// to stand behind, not a statement that RS*/PS* are currently unsafe.
159    /// RS*/PS* remain fully selectable via `SecurityConfig::jwt_algorithm`
160    /// for integrators who need RSA-based JWTs for interop with an existing
161    /// keypair or third party -- this only changes what we recommend, not
162    /// what we permit. CireSnave's ruling, 2026-09-24, escalated to full
163    /// `rsa` removal in a later pass; see deny.toml for what's left.
164    pub fn to_config(&self) -> SecurityConfig {
165        match self {
166            SecurityPreset::Development => SecurityConfig {
167                min_password_length: 6,
168                require_password_complexity: false,
169                password_hash_algorithm: PasswordHashAlgorithm::Bcrypt, // Faster for development
170                jwt_algorithm: JwtAlgorithm::HS256,
171                secret_key: None, // Must be set externally
172                previous_secret_key: None,
173                secure_cookies: false, // Allow HTTP for local development
174                cookie_same_site: CookieSameSite::Lax,
175                csrf_protection: false,     // Easier API testing
176                session_timeout: hours(24), // Long timeout for development convenience
177            },
178            SecurityPreset::Balanced => SecurityConfig {
179                min_password_length: 8,
180                require_password_complexity: true,
181                password_hash_algorithm: PasswordHashAlgorithm::Argon2,
182                jwt_algorithm: JwtAlgorithm::HS256,
183                secret_key: None,
184                previous_secret_key: None,
185                secure_cookies: true,
186                cookie_same_site: CookieSameSite::Lax,
187                csrf_protection: true,
188                session_timeout: hours(8),
189            },
190            SecurityPreset::HighSecurity => SecurityConfig {
191                min_password_length: 12,
192                require_password_complexity: true,
193                password_hash_algorithm: PasswordHashAlgorithm::Argon2,
194                jwt_algorithm: JwtAlgorithm::ES256, // ECDSA -- see note below on why not RS*
195                secret_key: None,
196                previous_secret_key: None,
197                secure_cookies: true,
198                cookie_same_site: CookieSameSite::Strict,
199                csrf_protection: true,
200                session_timeout: hours(2), // Shorter sessions
201            },
202            SecurityPreset::Paranoid => SecurityConfig {
203                min_password_length: 16,
204                require_password_complexity: true,
205                password_hash_algorithm: PasswordHashAlgorithm::Argon2,
206                jwt_algorithm: JwtAlgorithm::ES384, // ECDSA -- see note below on why not RS*
207                secret_key: None,
208                previous_secret_key: None,
209                secure_cookies: true,
210                cookie_same_site: CookieSameSite::Strict,
211                csrf_protection: true,
212                session_timeout: minutes(30), // Very short sessions
213            },
214        }
215    }
216
217    /// Get rate limiting configuration for this security preset
218    pub fn to_rate_limit_config(&self) -> RateLimitConfig {
219        match self {
220            SecurityPreset::Development => RateLimitConfig {
221                enabled: false, // Disabled for easier development
222                max_requests: 1000,
223                window: Duration::from_secs(60),
224                burst: 100,
225            },
226            SecurityPreset::Balanced => RateLimitConfig {
227                enabled: true,
228                max_requests: 100,
229                window: Duration::from_secs(60),
230                burst: 20,
231            },
232            SecurityPreset::HighSecurity => RateLimitConfig {
233                enabled: true,
234                max_requests: 60, // 1 per second average
235                window: Duration::from_secs(60),
236                burst: 10,
237            },
238            SecurityPreset::Paranoid => RateLimitConfig {
239                enabled: true,
240                max_requests: 30, // 0.5 per second average
241                window: Duration::from_secs(60),
242                burst: 5,
243            },
244        }
245    }
246
247    /// Get audit configuration for this security preset
248    pub fn to_audit_config(&self) -> AuditConfig {
249        match self {
250            SecurityPreset::Development => AuditConfig {
251                enabled: false, // Disabled for cleaner development logs
252                log_success: false,
253                log_failures: true, // Still log failures for debugging
254                log_permissions: false,
255                log_tokens: false,
256                storage: AuditStorage::Tracing,
257            },
258            SecurityPreset::Balanced => AuditConfig {
259                enabled: true,
260                log_success: false, // Don't log every success to reduce noise
261                log_failures: true,
262                log_permissions: true,
263                log_tokens: false, // Tokens can be sensitive
264                storage: AuditStorage::Tracing,
265            },
266            SecurityPreset::HighSecurity => AuditConfig {
267                enabled: true,
268                log_success: true,
269                log_failures: true,
270                log_permissions: true,
271                log_tokens: false,
272                storage: AuditStorage::Tracing, // Should be database in real deployment
273            },
274            SecurityPreset::Paranoid => AuditConfig {
275                enabled: true,
276                log_success: true,
277                log_failures: true,
278                log_permissions: true,
279                log_tokens: true,               // Log everything in paranoid mode
280                storage: AuditStorage::Tracing, // Should be secure external service
281            },
282        }
283    }
284
285    /// Validate the current environment against this security preset
286    pub async fn validate_environment(&self) -> AuthFrameworkResult<Vec<SecurityIssue>> {
287        let mut issues = Vec::new();
288
289        // Check environment type
290        let is_production = self.is_production_environment();
291        let is_development = self.is_development_environment();
292
293        // Validate preset appropriateness for environment
294        match (self, is_production, is_development) {
295            (SecurityPreset::Development, true, false) => {
296                issues.push(SecurityIssue {
297                    severity: SecuritySeverity::Critical,
298                    component: "Security Preset".to_string(),
299                    description: "Development security preset used in production environment".to_string(),
300                    suggestion: "Use SecurityPreset::HighSecurity or SecurityPreset::Paranoid for production".to_string(),
301                    blocks_production: true,
302                });
303            }
304            (SecurityPreset::Balanced, true, false) => {
305                issues.push(SecurityIssue {
306                    severity: SecuritySeverity::Warning,
307                    component: "Security Preset".to_string(),
308                    description:
309                        "Balanced security preset in production - consider higher security"
310                            .to_string(),
311                    suggestion: "Consider SecurityPreset::HighSecurity for better protection"
312                        .to_string(),
313                    blocks_production: false,
314                });
315            }
316            _ => {} // Other combinations are acceptable
317        }
318
319        // Check JWT secret
320        self.validate_jwt_secret(&mut issues);
321
322        // Check HTTPS in production
323        if is_production && self.requires_secure_cookies() {
324            self.validate_https_requirement(&mut issues);
325        }
326
327        // Check database configuration
328        self.validate_storage_security(&mut issues);
329
330        // Check environment variables
331        self.validate_environment_variables(&mut issues);
332
333        Ok(issues)
334    }
335
336    /// Perform a security audit of the current configuration
337    pub async fn security_audit(&self) -> AuthFrameworkResult<SecurityAuditReport> {
338        let issues = self.validate_environment().await?;
339
340        let critical_count = issues
341            .iter()
342            .filter(|i| i.severity == SecuritySeverity::Critical)
343            .count();
344        let error_count = issues
345            .iter()
346            .filter(|i| i.severity == SecuritySeverity::Error)
347            .count();
348        let warning_count = issues
349            .iter()
350            .filter(|i| i.severity == SecuritySeverity::Warning)
351            .count();
352
353        let overall_status = if critical_count > 0 {
354            SecurityAuditStatus::Critical
355        } else if error_count > 0 {
356            SecurityAuditStatus::Failed
357        } else if warning_count > 0 {
358            SecurityAuditStatus::Warning
359        } else {
360            SecurityAuditStatus::Passed
361        };
362
363        Ok(SecurityAuditReport {
364            preset: self.clone(),
365            status: overall_status,
366            issues,
367            critical_count,
368            error_count,
369            warning_count,
370            recommendations: self.get_security_recommendations(),
371        })
372    }
373
374    /// Get security recommendations for this preset
375    pub fn get_security_recommendations(&self) -> Vec<String> {
376        let mut recommendations = Vec::new();
377
378        match self {
379            SecurityPreset::Development => {
380                recommendations.push(
381                    "âš ī¸  Development preset detected - ensure this is not used in production"
382                        .to_string(),
383                );
384                recommendations
385                    .push("🔐 Set JWT_SECRET environment variable with a secure value".to_string());
386                recommendations
387                    .push("📝 Enable audit logging when moving to production".to_string());
388            }
389            SecurityPreset::Balanced => {
390                recommendations.push(
391                    "🔒 Consider upgrading to HighSecurity for sensitive applications".to_string(),
392                );
393                recommendations
394                    .push("📊 Monitor authentication patterns for suspicious activity".to_string());
395                recommendations.push("🔄 Regularly rotate JWT secrets and API keys".to_string());
396            }
397            SecurityPreset::HighSecurity => {
398                recommendations
399                    .push("✅ Good security configuration for production use".to_string());
400                recommendations
401                    .push("🔐 Ensure RSA keys are properly managed and rotated".to_string());
402                recommendations.push("📈 Monitor failed authentication attempts".to_string());
403                recommendations.push(
404                    "đŸ›Ąī¸  Consider multi-factor authentication for admin accounts".to_string(),
405                );
406            }
407            SecurityPreset::Paranoid => {
408                recommendations
409                    .push("đŸ›Ąī¸  Maximum security enabled - monitor performance impact".to_string());
410                recommendations.push(
411                    "⚡ Consider connection pooling to handle strict rate limits".to_string(),
412                );
413                recommendations.push("🔍 Implement comprehensive security monitoring".to_string());
414                recommendations
415                    .push("🚨 Set up alerting for all authentication failures".to_string());
416            }
417        }
418
419        recommendations
420    }
421
422    // Helper methods for validation
423
424    fn is_production_environment(&self) -> bool {
425        std::env::var("ENVIRONMENT").as_deref() == Ok("production")
426            || std::env::var("ENV").as_deref() == Ok("production")
427            || std::env::var("NODE_ENV").as_deref() == Ok("production")
428            || std::env::var("RUST_ENV").as_deref() == Ok("production")
429            || std::env::var("KUBERNETES_SERVICE_HOST").is_ok()
430    }
431
432    fn is_development_environment(&self) -> bool {
433        std::env::var("ENVIRONMENT").as_deref() == Ok("development")
434            || std::env::var("ENV").as_deref() == Ok("development")
435            || std::env::var("NODE_ENV").as_deref() == Ok("development")
436            || std::env::var("RUST_ENV").as_deref() == Ok("development")
437            || cfg!(debug_assertions)
438    }
439
440    fn requires_secure_cookies(&self) -> bool {
441        matches!(
442            self,
443            SecurityPreset::Balanced | SecurityPreset::HighSecurity | SecurityPreset::Paranoid
444        )
445    }
446
447    fn validate_jwt_secret(&self, issues: &mut Vec<SecurityIssue>) {
448        if let Ok(secret) = std::env::var("JWT_SECRET") {
449            let min_length = match self {
450                SecurityPreset::Development => 16,
451                SecurityPreset::Balanced => 32,
452                SecurityPreset::HighSecurity => 64,
453                SecurityPreset::Paranoid => 128,
454            };
455
456            if secret.len() < min_length {
457                issues.push(SecurityIssue {
458                    severity: if matches!(self, SecurityPreset::Development) {
459                        SecuritySeverity::Warning
460                    } else {
461                        SecuritySeverity::Error
462                    },
463                    component: "JWT Secret".to_string(),
464                    description: format!(
465                        "JWT secret too short ({} chars, need {}+)",
466                        secret.len(),
467                        min_length
468                    ),
469                    suggestion: format!(
470                        "Generate a longer secret: `openssl rand -base64 {}`",
471                        min_length * 3 / 4
472                    ),
473                    blocks_production: !matches!(self, SecurityPreset::Development),
474                });
475            }
476
477            // Check for weak patterns
478            if secret.to_lowercase().contains("secret")
479                || secret.to_lowercase().contains("password")
480                || secret.contains("123")
481            {
482                issues.push(SecurityIssue {
483                    severity: SecuritySeverity::Error,
484                    component: "JWT Secret".to_string(),
485                    description: "JWT secret contains weak patterns or common words".to_string(),
486                    suggestion:
487                        "Use a cryptographically secure random string: `openssl rand -base64 64`"
488                            .to_string(),
489                    blocks_production: true,
490                });
491            }
492        } else {
493            issues.push(SecurityIssue {
494                severity: SecuritySeverity::Critical,
495                component: "JWT Secret".to_string(),
496                description: "JWT_SECRET environment variable not set".to_string(),
497                suggestion: "Set JWT_SECRET environment variable with a secure random value"
498                    .to_string(),
499                blocks_production: true,
500            });
501        }
502    }
503
504    fn validate_https_requirement(&self, issues: &mut Vec<SecurityIssue>) {
505        // In a real implementation, this would check if HTTPS is properly configured
506        // For now, we'll check for common HTTPS indicators
507        let has_tls_cert =
508            std::env::var("TLS_CERT_PATH").is_ok() || std::env::var("SSL_CERT_PATH").is_ok();
509        let behind_proxy = std::env::var("HTTPS").as_deref() == Ok("on")
510            || std::env::var("HTTP_X_FORWARDED_PROTO").as_deref() == Ok("https");
511
512        if !has_tls_cert && !behind_proxy {
513            issues.push(SecurityIssue {
514                severity: SecuritySeverity::Warning,
515                component: "HTTPS".to_string(),
516                description: "HTTPS configuration not detected".to_string(),
517                suggestion: "Ensure HTTPS is properly configured for secure cookie transmission"
518                    .to_string(),
519                blocks_production: false,
520            });
521        }
522    }
523
524    fn validate_storage_security(&self, issues: &mut Vec<SecurityIssue>) {
525        // Check for database connection security
526        if let Ok(db_url) = std::env::var("DATABASE_URL")
527            && db_url.starts_with("postgresql://")
528            && !db_url.contains("sslmode=require")
529        {
530            issues.push(SecurityIssue {
531                severity: SecuritySeverity::Warning,
532                component: "Database".to_string(),
533                description: "Database connection may not be using SSL".to_string(),
534                suggestion: "Add sslmode=require to DATABASE_URL for encrypted connections"
535                    .to_string(),
536                blocks_production: false,
537            });
538        }
539
540        if let Ok(redis_url) = std::env::var("REDIS_URL")
541            && !redis_url.starts_with("rediss://")
542            && !redis_url.contains("tls")
543        {
544            issues.push(SecurityIssue {
545                severity: SecuritySeverity::Info,
546                component: "Redis".to_string(),
547                description: "Redis connection may not be using TLS".to_string(),
548                suggestion: "Consider using rediss:// URL or enabling TLS for Redis connections"
549                    .to_string(),
550                blocks_production: false,
551            });
552        }
553    }
554
555    fn validate_environment_variables(&self, issues: &mut Vec<SecurityIssue>) {
556        let sensitive_vars = [
557            "JWT_SECRET",
558            "DATABASE_URL",
559            "REDIS_URL",
560            "OAUTH_CLIENT_SECRET",
561        ];
562
563        for var in &sensitive_vars {
564            if let Ok(value) = std::env::var(var)
565                && value.len() < 20
566            {
567                issues.push(SecurityIssue {
568                    severity: SecuritySeverity::Warning,
569                    component: "Environment Variables".to_string(),
570                    description: format!("{} appears to be too short", var),
571                    suggestion: format!(
572                        "Ensure {} contains a sufficiently long, secure value",
573                        var
574                    ),
575                    blocks_production: false,
576                });
577            }
578        }
579    }
580}
581
582/// Security audit report
583#[derive(Debug, Clone)]
584pub struct SecurityAuditReport {
585    pub preset: SecurityPreset,
586    pub status: SecurityAuditStatus,
587    pub issues: Vec<SecurityIssue>,
588    pub critical_count: usize,
589    pub error_count: usize,
590    pub warning_count: usize,
591    pub recommendations: Vec<String>,
592}
593
594/// Overall security audit status
595#[derive(Debug, Clone, PartialEq)]
596pub enum SecurityAuditStatus {
597    /// All security checks passed
598    Passed,
599    /// Non-critical warnings found
600    Warning,
601    /// Security errors found that should be addressed
602    Failed,
603    /// Critical security issues that block production deployment
604    Critical,
605}
606
607impl SecurityAuditReport {
608    /// Print a formatted security report to stdout
609    pub fn print_report(&self) {
610        println!("🔒 Security Audit Report");
611        println!("========================");
612        println!("Preset: {:?}", self.preset);
613        println!("Status: {}", self.status_emoji());
614        println!();
615
616        if self.issues.is_empty() {
617            println!("✅ No security issues found!");
618        } else {
619            println!("📊 Issues Summary:");
620            println!("   Critical: {}", self.critical_count);
621            println!("   Errors: {}", self.error_count);
622            println!("   Warnings: {}", self.warning_count);
623            println!();
624
625            for issue in &self.issues {
626                println!(
627                    "{} {}: {}",
628                    issue.severity.emoji(),
629                    issue.component,
630                    issue.description
631                );
632                println!("   💡 {}", issue.suggestion);
633                println!();
634            }
635        }
636
637        if !self.recommendations.is_empty() {
638            println!("📋 Recommendations:");
639            for rec in &self.recommendations {
640                println!("   {}", rec);
641            }
642            println!();
643        }
644
645        println!("{}", self.get_summary_message());
646    }
647
648    fn status_emoji(&self) -> &str {
649        match self.status {
650            SecurityAuditStatus::Passed => "✅ Passed",
651            SecurityAuditStatus::Warning => "âš ī¸  Warning",
652            SecurityAuditStatus::Failed => "❌ Failed",
653            SecurityAuditStatus::Critical => "🚨 Critical",
654        }
655    }
656
657    fn get_summary_message(&self) -> String {
658        match self.status {
659            SecurityAuditStatus::Passed => "🎉 Security audit passed! Your configuration meets security requirements.".to_string(),
660            SecurityAuditStatus::Warning => "âš ī¸  Security audit completed with warnings. Consider addressing the issues above.".to_string(),
661            SecurityAuditStatus::Failed => "❌ Security audit failed. Please address the errors before deploying to production.".to_string(),
662            SecurityAuditStatus::Critical => "🚨 Critical security issues found! Do not deploy to production until these are resolved.".to_string(),
663        }
664    }
665
666    /// Check if the configuration is safe for production deployment
667    pub fn is_production_ready(&self) -> bool {
668        matches!(
669            self.status,
670            SecurityAuditStatus::Passed | SecurityAuditStatus::Warning
671        )
672    }
673
674    /// Get all blocking issues that prevent production deployment
675    pub fn get_blocking_issues(&self) -> Vec<&SecurityIssue> {
676        self.issues
677            .iter()
678            .filter(|issue| issue.blocks_production)
679            .collect()
680    }
681}
682
683impl SecuritySeverity {
684    fn emoji(&self) -> &str {
685        match self {
686            SecuritySeverity::Info => "â„šī¸ ",
687            SecuritySeverity::Warning => "âš ī¸ ",
688            SecuritySeverity::Error => "❌",
689            SecuritySeverity::Critical => "🚨",
690        }
691    }
692}
693
694impl std::fmt::Display for SecuritySeverity {
695    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
696        match self {
697            SecuritySeverity::Info => write!(f, "INFO"),
698            SecuritySeverity::Warning => write!(f, "WARNING"),
699            SecuritySeverity::Error => write!(f, "ERROR"),
700            SecuritySeverity::Critical => write!(f, "CRITICAL"),
701        }
702    }
703}
704
705#[cfg(test)]
706mod tests {
707    use super::*;
708
709    #[test]
710    fn test_development_preset_config() {
711        let config = SecurityPreset::Development.to_config();
712        assert_eq!(config.min_password_length, 6);
713        assert!(!config.require_password_complexity);
714        assert!(!config.secure_cookies);
715        assert!(!config.csrf_protection);
716    }
717
718    #[test]
719    fn test_balanced_preset_config() {
720        let config = SecurityPreset::Balanced.to_config();
721        assert_eq!(config.min_password_length, 8);
722        assert!(config.require_password_complexity);
723        assert!(config.secure_cookies);
724        assert!(config.csrf_protection);
725    }
726
727    #[test]
728    fn test_high_security_preset_config() {
729        let config = SecurityPreset::HighSecurity.to_config();
730        assert_eq!(config.min_password_length, 12);
731        assert!(config.secure_cookies);
732        assert!(config.csrf_protection);
733        assert!(matches!(config.cookie_same_site, CookieSameSite::Strict));
734    }
735
736    #[test]
737    fn test_paranoid_preset_config() {
738        let config = SecurityPreset::Paranoid.to_config();
739        assert_eq!(config.min_password_length, 16);
740        assert!(config.csrf_protection);
741        assert_eq!(config.session_timeout, minutes(30));
742    }
743
744    #[test]
745    fn test_presets_have_increasing_password_length() {
746        let dev = SecurityPreset::Development.to_config().min_password_length;
747        let bal = SecurityPreset::Balanced.to_config().min_password_length;
748        let high = SecurityPreset::HighSecurity.to_config().min_password_length;
749        let paranoid = SecurityPreset::Paranoid.to_config().min_password_length;
750        assert!(dev < bal);
751        assert!(bal < high);
752        assert!(high < paranoid);
753    }
754
755    #[test]
756    fn test_presets_have_decreasing_session_timeout() {
757        let dev = SecurityPreset::Development.to_config().session_timeout;
758        let bal = SecurityPreset::Balanced.to_config().session_timeout;
759        let high = SecurityPreset::HighSecurity.to_config().session_timeout;
760        let paranoid = SecurityPreset::Paranoid.to_config().session_timeout;
761        assert!(dev > bal);
762        assert!(bal > high);
763        assert!(high > paranoid);
764    }
765
766    #[test]
767    fn test_rate_limit_configs_are_valid() {
768        for preset in [
769            SecurityPreset::Development,
770            SecurityPreset::Balanced,
771            SecurityPreset::HighSecurity,
772            SecurityPreset::Paranoid,
773        ] {
774            let rl = preset.to_rate_limit_config();
775            assert!(rl.max_requests > 0);
776            assert!(!rl.window.is_zero());
777        }
778    }
779
780    #[test]
781    fn test_audit_configs_are_valid() {
782        for preset in [
783            SecurityPreset::Development,
784            SecurityPreset::Balanced,
785            SecurityPreset::HighSecurity,
786            SecurityPreset::Paranoid,
787        ] {
788            let ac = preset.to_audit_config();
789            // All presets produce a valid config; HighSecurity+ enable logging
790            if matches!(
791                preset,
792                SecurityPreset::HighSecurity | SecurityPreset::Paranoid
793            ) {
794                assert!(ac.enabled);
795            }
796        }
797    }
798
799    #[test]
800    fn test_security_recommendations_non_empty() {
801        for preset in [
802            SecurityPreset::Development,
803            SecurityPreset::Balanced,
804            SecurityPreset::HighSecurity,
805            SecurityPreset::Paranoid,
806        ] {
807            let recs = preset.get_security_recommendations();
808            assert!(!recs.is_empty());
809        }
810    }
811
812    #[test]
813    fn test_audit_report_production_ready() {
814        let report = SecurityAuditReport {
815            preset: SecurityPreset::Balanced,
816            status: SecurityAuditStatus::Passed,
817            issues: vec![],
818            critical_count: 0,
819            error_count: 0,
820            warning_count: 0,
821            recommendations: vec![],
822        };
823        assert!(report.is_production_ready());
824    }
825
826    #[test]
827    fn test_audit_report_not_production_ready_on_critical() {
828        let report = SecurityAuditReport {
829            preset: SecurityPreset::HighSecurity,
830            status: SecurityAuditStatus::Critical,
831            issues: vec![SecurityIssue {
832                severity: SecuritySeverity::Critical,
833                component: "test".into(),
834                description: "fail".into(),
835                suggestion: "fix".into(),
836                blocks_production: true,
837            }],
838            critical_count: 1,
839            error_count: 0,
840            warning_count: 0,
841            recommendations: vec![],
842        };
843        assert!(!report.is_production_ready());
844        assert_eq!(report.get_blocking_issues().len(), 1);
845    }
846
847    #[test]
848    fn test_severity_display() {
849        assert_eq!(format!("{}", SecuritySeverity::Critical), "CRITICAL");
850        assert_eq!(format!("{}", SecuritySeverity::Warning), "WARNING");
851    }
852}