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