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    pub fn to_config(&self) -> SecurityConfig {
148        match self {
149            SecurityPreset::Development => SecurityConfig {
150                min_password_length: 6,
151                require_password_complexity: false,
152                password_hash_algorithm: PasswordHashAlgorithm::Bcrypt, // Faster for development
153                jwt_algorithm: JwtAlgorithm::HS256,
154                secret_key: None,      // Must be set externally
155                secure_cookies: false, // Allow HTTP for local development
156                cookie_same_site: CookieSameSite::Lax,
157                csrf_protection: false,     // Easier API testing
158                session_timeout: hours(24), // Long timeout for development convenience
159            },
160            SecurityPreset::Balanced => SecurityConfig {
161                min_password_length: 8,
162                require_password_complexity: true,
163                password_hash_algorithm: PasswordHashAlgorithm::Argon2,
164                jwt_algorithm: JwtAlgorithm::HS256,
165                secret_key: None,
166                secure_cookies: true,
167                cookie_same_site: CookieSameSite::Lax,
168                csrf_protection: true,
169                session_timeout: hours(8),
170            },
171            SecurityPreset::HighSecurity => SecurityConfig {
172                min_password_length: 12,
173                require_password_complexity: true,
174                password_hash_algorithm: PasswordHashAlgorithm::Argon2,
175                jwt_algorithm: JwtAlgorithm::RS256, // RSA for better security
176                secret_key: None,
177                secure_cookies: true,
178                cookie_same_site: CookieSameSite::Strict,
179                csrf_protection: true,
180                session_timeout: hours(2), // Shorter sessions
181            },
182            SecurityPreset::Paranoid => SecurityConfig {
183                min_password_length: 16,
184                require_password_complexity: true,
185                password_hash_algorithm: PasswordHashAlgorithm::Argon2,
186                jwt_algorithm: JwtAlgorithm::RS512, // Strongest RSA
187                secret_key: None,
188                secure_cookies: true,
189                cookie_same_site: CookieSameSite::Strict,
190                csrf_protection: true,
191                session_timeout: minutes(30), // Very short sessions
192            },
193        }
194    }
195
196    /// Get rate limiting configuration for this security preset
197    pub fn to_rate_limit_config(&self) -> RateLimitConfig {
198        match self {
199            SecurityPreset::Development => RateLimitConfig {
200                enabled: false, // Disabled for easier development
201                max_requests: 1000,
202                window: Duration::from_secs(60),
203                burst: 100,
204            },
205            SecurityPreset::Balanced => RateLimitConfig {
206                enabled: true,
207                max_requests: 100,
208                window: Duration::from_secs(60),
209                burst: 20,
210            },
211            SecurityPreset::HighSecurity => RateLimitConfig {
212                enabled: true,
213                max_requests: 60, // 1 per second average
214                window: Duration::from_secs(60),
215                burst: 10,
216            },
217            SecurityPreset::Paranoid => RateLimitConfig {
218                enabled: true,
219                max_requests: 30, // 0.5 per second average
220                window: Duration::from_secs(60),
221                burst: 5,
222            },
223        }
224    }
225
226    /// Get audit configuration for this security preset
227    pub fn to_audit_config(&self) -> AuditConfig {
228        match self {
229            SecurityPreset::Development => AuditConfig {
230                enabled: false, // Disabled for cleaner development logs
231                log_success: false,
232                log_failures: true, // Still log failures for debugging
233                log_permissions: false,
234                log_tokens: false,
235                storage: AuditStorage::Tracing,
236            },
237            SecurityPreset::Balanced => AuditConfig {
238                enabled: true,
239                log_success: false, // Don't log every success to reduce noise
240                log_failures: true,
241                log_permissions: true,
242                log_tokens: false, // Tokens can be sensitive
243                storage: AuditStorage::Tracing,
244            },
245            SecurityPreset::HighSecurity => AuditConfig {
246                enabled: true,
247                log_success: true,
248                log_failures: true,
249                log_permissions: true,
250                log_tokens: false,
251                storage: AuditStorage::Tracing, // Should be database in real deployment
252            },
253            SecurityPreset::Paranoid => AuditConfig {
254                enabled: true,
255                log_success: true,
256                log_failures: true,
257                log_permissions: true,
258                log_tokens: true,               // Log everything in paranoid mode
259                storage: AuditStorage::Tracing, // Should be secure external service
260            },
261        }
262    }
263
264    /// Validate the current environment against this security preset
265    pub async fn validate_environment(&self) -> AuthFrameworkResult<Vec<SecurityIssue>> {
266        let mut issues = Vec::new();
267
268        // Check environment type
269        let is_production = self.is_production_environment();
270        let is_development = self.is_development_environment();
271
272        // Validate preset appropriateness for environment
273        match (self, is_production, is_development) {
274            (SecurityPreset::Development, true, false) => {
275                issues.push(SecurityIssue {
276                    severity: SecuritySeverity::Critical,
277                    component: "Security Preset".to_string(),
278                    description: "Development security preset used in production environment".to_string(),
279                    suggestion: "Use SecurityPreset::HighSecurity or SecurityPreset::Paranoid for production".to_string(),
280                    blocks_production: true,
281                });
282            }
283            (SecurityPreset::Balanced, true, false) => {
284                issues.push(SecurityIssue {
285                    severity: SecuritySeverity::Warning,
286                    component: "Security Preset".to_string(),
287                    description:
288                        "Balanced security preset in production - consider higher security"
289                            .to_string(),
290                    suggestion: "Consider SecurityPreset::HighSecurity for better protection"
291                        .to_string(),
292                    blocks_production: false,
293                });
294            }
295            _ => {} // Other combinations are acceptable
296        }
297
298        // Check JWT secret
299        self.validate_jwt_secret(&mut issues);
300
301        // Check HTTPS in production
302        if is_production && self.requires_secure_cookies() {
303            self.validate_https_requirement(&mut issues);
304        }
305
306        // Check database configuration
307        self.validate_storage_security(&mut issues);
308
309        // Check environment variables
310        self.validate_environment_variables(&mut issues);
311
312        Ok(issues)
313    }
314
315    /// Perform a security audit of the current configuration
316    pub async fn security_audit(&self) -> AuthFrameworkResult<SecurityAuditReport> {
317        let issues = self.validate_environment().await?;
318
319        let critical_count = issues
320            .iter()
321            .filter(|i| i.severity == SecuritySeverity::Critical)
322            .count();
323        let error_count = issues
324            .iter()
325            .filter(|i| i.severity == SecuritySeverity::Error)
326            .count();
327        let warning_count = issues
328            .iter()
329            .filter(|i| i.severity == SecuritySeverity::Warning)
330            .count();
331
332        let overall_status = if critical_count > 0 {
333            SecurityAuditStatus::Critical
334        } else if error_count > 0 {
335            SecurityAuditStatus::Failed
336        } else if warning_count > 0 {
337            SecurityAuditStatus::Warning
338        } else {
339            SecurityAuditStatus::Passed
340        };
341
342        Ok(SecurityAuditReport {
343            preset: self.clone(),
344            status: overall_status,
345            issues,
346            critical_count,
347            error_count,
348            warning_count,
349            recommendations: self.get_security_recommendations(),
350        })
351    }
352
353    /// Get security recommendations for this preset
354    pub fn get_security_recommendations(&self) -> Vec<String> {
355        let mut recommendations = Vec::new();
356
357        match self {
358            SecurityPreset::Development => {
359                recommendations.push(
360                    "âš ī¸  Development preset detected - ensure this is not used in production"
361                        .to_string(),
362                );
363                recommendations
364                    .push("🔐 Set JWT_SECRET environment variable with a secure value".to_string());
365                recommendations
366                    .push("📝 Enable audit logging when moving to production".to_string());
367            }
368            SecurityPreset::Balanced => {
369                recommendations.push(
370                    "🔒 Consider upgrading to HighSecurity for sensitive applications".to_string(),
371                );
372                recommendations
373                    .push("📊 Monitor authentication patterns for suspicious activity".to_string());
374                recommendations.push("🔄 Regularly rotate JWT secrets and API keys".to_string());
375            }
376            SecurityPreset::HighSecurity => {
377                recommendations
378                    .push("✅ Good security configuration for production use".to_string());
379                recommendations
380                    .push("🔐 Ensure RSA keys are properly managed and rotated".to_string());
381                recommendations.push("📈 Monitor failed authentication attempts".to_string());
382                recommendations.push(
383                    "đŸ›Ąī¸  Consider multi-factor authentication for admin accounts".to_string(),
384                );
385            }
386            SecurityPreset::Paranoid => {
387                recommendations
388                    .push("đŸ›Ąī¸  Maximum security enabled - monitor performance impact".to_string());
389                recommendations.push(
390                    "⚡ Consider connection pooling to handle strict rate limits".to_string(),
391                );
392                recommendations.push("🔍 Implement comprehensive security monitoring".to_string());
393                recommendations
394                    .push("🚨 Set up alerting for all authentication failures".to_string());
395            }
396        }
397
398        recommendations
399    }
400
401    // Helper methods for validation
402
403    fn is_production_environment(&self) -> bool {
404        std::env::var("ENVIRONMENT").as_deref() == Ok("production")
405            || std::env::var("ENV").as_deref() == Ok("production")
406            || std::env::var("NODE_ENV").as_deref() == Ok("production")
407            || std::env::var("RUST_ENV").as_deref() == Ok("production")
408            || std::env::var("KUBERNETES_SERVICE_HOST").is_ok()
409    }
410
411    fn is_development_environment(&self) -> bool {
412        std::env::var("ENVIRONMENT").as_deref() == Ok("development")
413            || std::env::var("ENV").as_deref() == Ok("development")
414            || std::env::var("NODE_ENV").as_deref() == Ok("development")
415            || std::env::var("RUST_ENV").as_deref() == Ok("development")
416            || cfg!(debug_assertions)
417    }
418
419    fn requires_secure_cookies(&self) -> bool {
420        matches!(
421            self,
422            SecurityPreset::Balanced | SecurityPreset::HighSecurity | SecurityPreset::Paranoid
423        )
424    }
425
426    fn validate_jwt_secret(&self, issues: &mut Vec<SecurityIssue>) {
427        if let Ok(secret) = std::env::var("JWT_SECRET") {
428            let min_length = match self {
429                SecurityPreset::Development => 16,
430                SecurityPreset::Balanced => 32,
431                SecurityPreset::HighSecurity => 64,
432                SecurityPreset::Paranoid => 128,
433            };
434
435            if secret.len() < min_length {
436                issues.push(SecurityIssue {
437                    severity: if matches!(self, SecurityPreset::Development) {
438                        SecuritySeverity::Warning
439                    } else {
440                        SecuritySeverity::Error
441                    },
442                    component: "JWT Secret".to_string(),
443                    description: format!(
444                        "JWT secret too short ({} chars, need {}+)",
445                        secret.len(),
446                        min_length
447                    ),
448                    suggestion: format!(
449                        "Generate a longer secret: `openssl rand -base64 {}`",
450                        min_length * 3 / 4
451                    ),
452                    blocks_production: !matches!(self, SecurityPreset::Development),
453                });
454            }
455
456            // Check for weak patterns
457            if secret.to_lowercase().contains("secret")
458                || secret.to_lowercase().contains("password")
459                || secret.contains("123")
460            {
461                issues.push(SecurityIssue {
462                    severity: SecuritySeverity::Error,
463                    component: "JWT Secret".to_string(),
464                    description: "JWT secret contains weak patterns or common words".to_string(),
465                    suggestion:
466                        "Use a cryptographically secure random string: `openssl rand -base64 64`"
467                            .to_string(),
468                    blocks_production: true,
469                });
470            }
471        } else {
472            issues.push(SecurityIssue {
473                severity: SecuritySeverity::Critical,
474                component: "JWT Secret".to_string(),
475                description: "JWT_SECRET environment variable not set".to_string(),
476                suggestion: "Set JWT_SECRET environment variable with a secure random value"
477                    .to_string(),
478                blocks_production: true,
479            });
480        }
481    }
482
483    fn validate_https_requirement(&self, issues: &mut Vec<SecurityIssue>) {
484        // In a real implementation, this would check if HTTPS is properly configured
485        // For now, we'll check for common HTTPS indicators
486        let has_tls_cert =
487            std::env::var("TLS_CERT_PATH").is_ok() || std::env::var("SSL_CERT_PATH").is_ok();
488        let behind_proxy = std::env::var("HTTPS").as_deref() == Ok("on")
489            || std::env::var("HTTP_X_FORWARDED_PROTO").as_deref() == Ok("https");
490
491        if !has_tls_cert && !behind_proxy {
492            issues.push(SecurityIssue {
493                severity: SecuritySeverity::Warning,
494                component: "HTTPS".to_string(),
495                description: "HTTPS configuration not detected".to_string(),
496                suggestion: "Ensure HTTPS is properly configured for secure cookie transmission"
497                    .to_string(),
498                blocks_production: false,
499            });
500        }
501    }
502
503    fn validate_storage_security(&self, issues: &mut Vec<SecurityIssue>) {
504        // Check for database connection security
505        if let Ok(db_url) = std::env::var("DATABASE_URL")
506            && db_url.starts_with("postgresql://")
507            && !db_url.contains("sslmode=require")
508        {
509            issues.push(SecurityIssue {
510                severity: SecuritySeverity::Warning,
511                component: "Database".to_string(),
512                description: "Database connection may not be using SSL".to_string(),
513                suggestion: "Add sslmode=require to DATABASE_URL for encrypted connections"
514                    .to_string(),
515                blocks_production: false,
516            });
517        }
518
519        if let Ok(redis_url) = std::env::var("REDIS_URL")
520            && !redis_url.starts_with("rediss://")
521            && !redis_url.contains("tls")
522        {
523            issues.push(SecurityIssue {
524                severity: SecuritySeverity::Info,
525                component: "Redis".to_string(),
526                description: "Redis connection may not be using TLS".to_string(),
527                suggestion: "Consider using rediss:// URL or enabling TLS for Redis connections"
528                    .to_string(),
529                blocks_production: false,
530            });
531        }
532    }
533
534    fn validate_environment_variables(&self, issues: &mut Vec<SecurityIssue>) {
535        let sensitive_vars = [
536            "JWT_SECRET",
537            "DATABASE_URL",
538            "REDIS_URL",
539            "OAUTH_CLIENT_SECRET",
540        ];
541
542        for var in &sensitive_vars {
543            if let Ok(value) = std::env::var(var)
544                && value.len() < 20
545            {
546                issues.push(SecurityIssue {
547                    severity: SecuritySeverity::Warning,
548                    component: "Environment Variables".to_string(),
549                    description: format!("{} appears to be too short", var),
550                    suggestion: format!(
551                        "Ensure {} contains a sufficiently long, secure value",
552                        var
553                    ),
554                    blocks_production: false,
555                });
556            }
557        }
558    }
559}
560
561/// Security audit report
562#[derive(Debug, Clone)]
563pub struct SecurityAuditReport {
564    pub preset: SecurityPreset,
565    pub status: SecurityAuditStatus,
566    pub issues: Vec<SecurityIssue>,
567    pub critical_count: usize,
568    pub error_count: usize,
569    pub warning_count: usize,
570    pub recommendations: Vec<String>,
571}
572
573/// Overall security audit status
574#[derive(Debug, Clone, PartialEq)]
575pub enum SecurityAuditStatus {
576    /// All security checks passed
577    Passed,
578    /// Non-critical warnings found
579    Warning,
580    /// Security errors found that should be addressed
581    Failed,
582    /// Critical security issues that block production deployment
583    Critical,
584}
585
586impl SecurityAuditReport {
587    /// Print a formatted security report to stdout
588    pub fn print_report(&self) {
589        println!("🔒 Security Audit Report");
590        println!("========================");
591        println!("Preset: {:?}", self.preset);
592        println!("Status: {}", self.status_emoji());
593        println!();
594
595        if self.issues.is_empty() {
596            println!("✅ No security issues found!");
597        } else {
598            println!("📊 Issues Summary:");
599            println!("   Critical: {}", self.critical_count);
600            println!("   Errors: {}", self.error_count);
601            println!("   Warnings: {}", self.warning_count);
602            println!();
603
604            for issue in &self.issues {
605                println!(
606                    "{} {}: {}",
607                    issue.severity.emoji(),
608                    issue.component,
609                    issue.description
610                );
611                println!("   💡 {}", issue.suggestion);
612                println!();
613            }
614        }
615
616        if !self.recommendations.is_empty() {
617            println!("📋 Recommendations:");
618            for rec in &self.recommendations {
619                println!("   {}", rec);
620            }
621            println!();
622        }
623
624        println!("{}", self.get_summary_message());
625    }
626
627    fn status_emoji(&self) -> &str {
628        match self.status {
629            SecurityAuditStatus::Passed => "✅ Passed",
630            SecurityAuditStatus::Warning => "âš ī¸  Warning",
631            SecurityAuditStatus::Failed => "❌ Failed",
632            SecurityAuditStatus::Critical => "🚨 Critical",
633        }
634    }
635
636    fn get_summary_message(&self) -> String {
637        match self.status {
638            SecurityAuditStatus::Passed => "🎉 Security audit passed! Your configuration meets security requirements.".to_string(),
639            SecurityAuditStatus::Warning => "âš ī¸  Security audit completed with warnings. Consider addressing the issues above.".to_string(),
640            SecurityAuditStatus::Failed => "❌ Security audit failed. Please address the errors before deploying to production.".to_string(),
641            SecurityAuditStatus::Critical => "🚨 Critical security issues found! Do not deploy to production until these are resolved.".to_string(),
642        }
643    }
644
645    /// Check if the configuration is safe for production deployment
646    pub fn is_production_ready(&self) -> bool {
647        matches!(
648            self.status,
649            SecurityAuditStatus::Passed | SecurityAuditStatus::Warning
650        )
651    }
652
653    /// Get all blocking issues that prevent production deployment
654    pub fn get_blocking_issues(&self) -> Vec<&SecurityIssue> {
655        self.issues
656            .iter()
657            .filter(|issue| issue.blocks_production)
658            .collect()
659    }
660}
661
662impl SecuritySeverity {
663    fn emoji(&self) -> &str {
664        match self {
665            SecuritySeverity::Info => "â„šī¸ ",
666            SecuritySeverity::Warning => "âš ī¸ ",
667            SecuritySeverity::Error => "❌",
668            SecuritySeverity::Critical => "🚨",
669        }
670    }
671}
672
673impl std::fmt::Display for SecuritySeverity {
674    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
675        match self {
676            SecuritySeverity::Info => write!(f, "INFO"),
677            SecuritySeverity::Warning => write!(f, "WARNING"),
678            SecuritySeverity::Error => write!(f, "ERROR"),
679            SecuritySeverity::Critical => write!(f, "CRITICAL"),
680        }
681    }
682}