Skip to main content

auth_framework/security/
mod.rs

1//! Security primitives and hardened implementations.
2//!
3//! This module contains:
4//!
5//! - **[`secure_jwt`]** — Production-grade JWT creation and validation with
6//!   key-rotation and revocation support.
7//! - **[`secure_mfa`]** — Hardened TOTP, backup-code, and recovery-flow logic.
8//! - **[`secure_session`]** — Session management with abuse-detection guards.
9//! - **[`timing_protection`]** — Constant-time comparison utilities to prevent
10//!   timing side-channel attacks.
11//! - **[`presets`]** — One-call security presets (`HighSecurity`, `Standard`,
12//!   `Development`) and an automated security-audit report generator.
13//!
14//! Most users interact with these through [`AuthFramework`](crate::auth::AuthFramework)
15//! rather than importing security types directly.
16
17use serde::{Deserialize, Serialize};
18
19// Timing protection utilities
20pub mod timing_protection;
21
22// Secure implementations
23pub mod secure_jwt;
24pub mod secure_mfa;
25pub mod secure_session;
26pub mod secure_session_config;
27pub mod secure_utils;
28
29// Security presets for easy configuration
30pub mod presets;
31
32// Enhanced cryptography (ChaCha20-Poly1305, Ed25519, X25519)
33#[cfg(feature = "enhanced-crypto")]
34pub mod enhanced_crypto;
35
36// Re-export presets for convenience
37pub use presets::{
38    SecurityAuditReport, SecurityAuditStatus, SecurityIssue, SecurityPreset, SecuritySeverity,
39};
40
41/// Multi-Factor Authentication configuration
42#[derive(Debug, Clone, Serialize, Deserialize)]
43pub struct MfaConfig {
44    /// TOTP configuration
45    pub totp_config: TotpConfig,
46    /// SMS configuration (optional)
47    pub sms_config: Option<SmsConfig>,
48    /// Email configuration (optional)
49    pub email_config: Option<EmailConfig>,
50    /// Backup codes configuration
51    pub backup_codes_config: BackupCodesConfig,
52    /// Challenge timeout in seconds
53    pub challenge_timeout_seconds: u64,
54    /// Maximum verification attempts
55    pub max_verification_attempts: u32,
56}
57
58impl Default for MfaConfig {
59    fn default() -> Self {
60        Self {
61            totp_config: TotpConfig::default(),
62            sms_config: None,
63            email_config: None,
64            backup_codes_config: BackupCodesConfig::default(),
65            challenge_timeout_seconds: 300, // 5 minutes
66            max_verification_attempts: 3,
67        }
68    }
69}
70
71/// TOTP (Time-based One-Time Password) configuration
72#[derive(Debug, Clone, Serialize, Deserialize)]
73pub struct TotpConfig {
74    /// Issuer name for TOTP apps
75    pub issuer: String,
76    /// Number of digits in the TOTP code
77    pub digits: u8,
78    /// Time period in seconds
79    pub period: u64,
80    /// Number of time windows to allow (for clock skew)
81    pub skew: u8,
82}
83
84impl Default for TotpConfig {
85    fn default() -> Self {
86        Self {
87            issuer: "Auth Framework".to_string(),
88            digits: 6,
89            period: 30,
90            skew: 1,
91        }
92    }
93}
94
95/// Backup codes configuration
96#[derive(Debug, Clone, Serialize, Deserialize)]
97pub struct BackupCodesConfig {
98    /// Number of backup codes to generate
99    pub count: usize,
100    /// Length of each backup code
101    pub length: usize,
102}
103
104impl Default for BackupCodesConfig {
105    fn default() -> Self {
106        Self {
107            count: 8,
108            length: 8,
109        }
110    }
111}
112
113/// Password strength assessment result
114#[derive(Debug, Clone, PartialEq)]
115pub enum PasswordStrength {
116    VeryWeak,
117    Weak,
118    Fair,
119    Good,
120    Strong,
121    VeryStrong,
122}
123
124/// Password validation result
125#[derive(Debug, Clone)]
126pub struct PasswordValidation {
127    pub is_valid: bool,
128    pub strength: PasswordStrength,
129    pub issues: Vec<String>,
130    pub suggestions: Vec<String>,
131}
132
133/// Audit logging configuration
134#[derive(Debug, Clone, Serialize, Deserialize, Default)]
135pub struct AuditConfig {
136    pub enabled: bool,
137    pub log_success: bool,
138    pub log_failures: bool,
139    pub log_permission_changes: bool,
140    pub log_admin_actions: bool,
141    pub retention_days: u32,
142    pub include_metadata: bool,
143}
144
145/// Account lockout configuration
146#[derive(Debug, Clone, Serialize, Deserialize, Default)]
147pub struct LockoutConfig {
148    pub enabled: bool,
149    pub max_failed_attempts: u32,
150    pub lockout_duration_seconds: u64,
151    pub progressive_lockout: bool,
152    pub max_lockout_duration_seconds: u64,
153}
154
155/// SMS configuration
156///
157/// **Security note:** `api_key` is never serialized to prevent accidental
158/// secret leakage in logs or config dumps.
159#[derive(Clone, Serialize, Deserialize)]
160pub struct SmsConfig {
161    pub provider: String,
162    #[serde(skip_serializing, default)]
163    pub api_key: String,
164    pub from_number: String,
165}
166
167impl std::fmt::Debug for SmsConfig {
168    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
169        let mut d = f.debug_struct("SmsConfig");
170        d.field("provider", &self.provider);
171        d.field("api_key", &crate::utils::redact::redacted(&self.api_key));
172        d.field("from_number", &self.from_number);
173        d.finish()
174    }
175}
176
177impl Default for SmsConfig {
178    fn default() -> Self {
179        Self {
180            provider: "twilio".to_string(),
181            api_key: String::new(),
182            from_number: String::new(),
183        }
184    }
185}
186
187/// Email configuration
188///
189/// **Security note:** `password` is never serialized to prevent accidental
190/// secret leakage in logs or config dumps.
191#[derive(Clone, Serialize, Deserialize)]
192pub struct EmailConfig {
193    pub smtp_server: String,
194    pub smtp_port: u16,
195    pub username: String,
196    #[serde(skip_serializing, default)]
197    pub password: String,
198    pub from_email: String,
199    pub use_tls: bool,
200}
201
202impl std::fmt::Debug for EmailConfig {
203    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
204        let mut d = f.debug_struct("EmailConfig");
205        d.field("smtp_server", &self.smtp_server);
206        d.field("smtp_port", &self.smtp_port);
207        d.field("username", &self.username);
208        d.field("password", &crate::utils::redact::redacted(&self.password));
209        d.field("from_email", &self.from_email);
210        d.field("use_tls", &self.use_tls);
211        d.finish()
212    }
213}
214
215impl Default for EmailConfig {
216    fn default() -> Self {
217        Self {
218            smtp_server: "smtp.gmail.com".to_string(),
219            smtp_port: 587,
220            username: String::new(),
221            password: String::new(),
222            from_email: String::new(),
223            use_tls: true,
224        }
225    }
226}
227
228/// Security context for authentication operations
229#[derive(Clone, Default)]
230pub struct SecurityContext {
231    pub ip_address: Option<String>,
232    pub user_agent: Option<String>,
233    pub session_id: Option<String>,
234    pub request_id: Option<String>,
235}
236
237impl std::fmt::Debug for SecurityContext {
238    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
239        let mut d = f.debug_struct("SecurityContext");
240        d.field("ip_address", &self.ip_address);
241        d.field("user_agent", &self.user_agent);
242        d.field(
243            "session_id",
244            &crate::utils::redact::redacted(&self.session_id),
245        );
246        d.field("request_id", &self.request_id);
247        d.finish()
248    }
249}
250
251/// Password validator
252pub struct PasswordValidator {
253    pub min_length: usize,
254    pub require_uppercase: bool,
255    pub require_lowercase: bool,
256    pub require_digits: bool,
257    pub require_special_chars: bool,
258    pub min_special_chars: usize,
259    pub forbidden_patterns: Vec<String>,
260}
261
262impl Default for PasswordValidator {
263    fn default() -> Self {
264        Self {
265            min_length: 8,
266            require_uppercase: true,
267            require_lowercase: true,
268            require_digits: true,
269            require_special_chars: true,
270            min_special_chars: 1,
271            forbidden_patterns: vec![
272                "password".to_string(),
273                "123456".to_string(),
274                "qwerty".to_string(),
275                "admin".to_string(),
276            ],
277        }
278    }
279}
280
281impl PasswordValidator {
282    /// Validate password strength and return detailed results
283    pub fn validate(&self, password: &str) -> PasswordValidation {
284        let mut is_valid = true;
285        let mut issues = Vec::new();
286        let mut suggestions = Vec::new();
287
288        // Check minimum length
289        if password.len() < self.min_length {
290            is_valid = false;
291            issues.push(format!(
292                "Password must be at least {} characters long",
293                self.min_length
294            ));
295            suggestions.push("Use a longer password".to_string());
296        }
297
298        // Check character requirements
299        if self.require_uppercase && !password.chars().any(|c| c.is_uppercase()) {
300            is_valid = false;
301            issues.push("Password must contain at least one uppercase letter".to_string());
302            suggestions.push("Add uppercase letters".to_string());
303        }
304
305        if self.require_lowercase && !password.chars().any(|c| c.is_lowercase()) {
306            is_valid = false;
307            issues.push("Password must contain at least one lowercase letter".to_string());
308            suggestions.push("Add lowercase letters".to_string());
309        }
310
311        if self.require_digits && !password.chars().any(|c| c.is_numeric()) {
312            is_valid = false;
313            issues.push("Password must contain at least one digit".to_string());
314            suggestions.push("Add numbers".to_string());
315        }
316
317        if self.require_special_chars {
318            let special_count = password.chars().filter(|&c| !c.is_alphanumeric()).count();
319            if special_count < self.min_special_chars {
320                is_valid = false;
321                issues.push(format!(
322                    "Password must contain at least {} special characters",
323                    self.min_special_chars
324                ));
325                suggestions.push("Add special characters like !@#$%^&*".to_string());
326            }
327        }
328
329        // Check forbidden patterns
330        for pattern in &self.forbidden_patterns {
331            if password.to_lowercase().contains(&pattern.to_lowercase()) {
332                is_valid = false;
333                issues.push(format!("Password contains forbidden pattern: {}", pattern));
334                suggestions.push("Avoid common passwords and patterns".to_string());
335            }
336        }
337
338        // Assess strength
339        let strength = self.assess_strength(password);
340
341        PasswordValidation {
342            is_valid,
343            strength,
344            issues,
345            suggestions,
346        }
347    }
348
349    /// Assess password strength
350    fn assess_strength(&self, password: &str) -> PasswordStrength {
351        let mut score = 0;
352
353        // Length scoring
354        if password.len() >= 8 {
355            score += 1;
356        }
357        if password.len() >= 12 {
358            score += 1;
359        }
360        if password.len() >= 16 {
361            score += 1;
362        }
363
364        // Character variety scoring
365        if password.chars().any(|c| c.is_lowercase()) {
366            score += 1;
367        }
368        if password.chars().any(|c| c.is_uppercase()) {
369            score += 1;
370        }
371        if password.chars().any(|c| c.is_numeric()) {
372            score += 1;
373        }
374        if password.chars().any(|c| !c.is_alphanumeric()) {
375            score += 1;
376        }
377
378        // Complexity bonus
379        if password.len() >= 20 {
380            score += 1;
381        }
382
383        match score {
384            0..=2 => PasswordStrength::VeryWeak,
385            3..=4 => PasswordStrength::Weak,
386            5 => PasswordStrength::Fair,
387            6 => PasswordStrength::Good,
388            7 => PasswordStrength::Strong,
389            _ => PasswordStrength::VeryStrong,
390        }
391    }
392}
393
394#[cfg(test)]
395mod tests {
396    use super::*;
397
398    #[test]
399    fn test_password_validation() {
400        let validator = PasswordValidator::default();
401
402        // Test weak password
403        let result = validator.validate("weak");
404        assert!(!result.is_valid);
405        assert_eq!(result.strength, PasswordStrength::VeryWeak);
406        assert!(!result.issues.is_empty());
407
408        // Test strong password
409        let result = validator.validate("Strong@Secure123!");
410        assert!(result.is_valid);
411        assert!(matches!(
412            result.strength,
413            PasswordStrength::Strong | PasswordStrength::VeryStrong
414        ));
415        assert!(result.issues.is_empty());
416    }
417
418    #[test]
419    fn test_forbidden_patterns() {
420        let validator = PasswordValidator::default();
421        let result = validator.validate("Password123!");
422        assert!(!result.is_valid);
423        assert!(
424            result
425                .issues
426                .iter()
427                .any(|issue| issue.contains("forbidden pattern"))
428        );
429    }
430}