auth-framework 0.5.0-rc79

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
//! Security primitives and hardened implementations.
//!
//! This module contains:
//!
//! - **[`secure_jwt`]** — Production-grade JWT creation and validation with
//!   key-rotation and revocation support.
//! - **[`secure_mfa`]** — Hardened TOTP, backup-code, and recovery-flow logic.
//! - **[`secure_session`]** — Session management with abuse-detection guards.
//! - **[`timing_protection`]** — Constant-time comparison utilities to prevent
//!   timing side-channel attacks.
//! - **[`presets`]** — One-call security presets (`HighSecurity`, `Standard`,
//!   `Development`) and an automated security-audit report generator.
//!
//! Most users interact with these through [`AuthFramework`](crate::auth::AuthFramework)
//! rather than importing security types directly.

use serde::{Deserialize, Serialize};

// Timing protection utilities
pub mod timing_protection;

// Secure implementations
pub mod secure_jwt;
pub mod secure_mfa;
pub mod secure_session;
pub mod secure_session_config;
pub mod secure_utils;

// Security presets for easy configuration
pub mod presets;

// Enhanced cryptography (ChaCha20-Poly1305, Ed25519, X25519)
#[cfg(feature = "enhanced-crypto")]
pub mod enhanced_crypto;

// Re-export presets for convenience
pub use presets::{
    SecurityAuditReport, SecurityAuditStatus, SecurityIssue, SecurityPreset, SecuritySeverity,
};

/// Multi-Factor Authentication configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MfaConfig {
    /// TOTP configuration
    pub totp_config: TotpConfig,
    /// SMS configuration (optional)
    pub sms_config: Option<SmsConfig>,
    /// Email configuration (optional)
    pub email_config: Option<EmailConfig>,
    /// Backup codes configuration
    pub backup_codes_config: BackupCodesConfig,
    /// Challenge timeout in seconds
    pub challenge_timeout_seconds: u64,
    /// Maximum verification attempts
    pub max_verification_attempts: u32,
}

impl Default for MfaConfig {
    fn default() -> Self {
        Self {
            totp_config: TotpConfig::default(),
            sms_config: None,
            email_config: None,
            backup_codes_config: BackupCodesConfig::default(),
            challenge_timeout_seconds: 300, // 5 minutes
            max_verification_attempts: 3,
        }
    }
}

/// TOTP (Time-based One-Time Password) configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TotpConfig {
    /// Issuer name for TOTP apps
    pub issuer: String,
    /// Number of digits in the TOTP code
    pub digits: u8,
    /// Time period in seconds
    pub period: u64,
    /// Number of time windows to allow (for clock skew)
    pub skew: u8,
}

impl Default for TotpConfig {
    fn default() -> Self {
        Self {
            issuer: "Auth Framework".to_string(),
            digits: 6,
            period: 30,
            skew: 1,
        }
    }
}

/// Backup codes configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BackupCodesConfig {
    /// Number of backup codes to generate
    pub count: usize,
    /// Length of each backup code
    pub length: usize,
}

impl Default for BackupCodesConfig {
    fn default() -> Self {
        Self {
            count: 8,
            length: 8,
        }
    }
}

/// Password strength assessment result
#[derive(Debug, Clone, PartialEq)]
pub enum PasswordStrength {
    VeryWeak,
    Weak,
    Fair,
    Good,
    Strong,
    VeryStrong,
}

/// Password validation result
#[derive(Debug, Clone)]
pub struct PasswordValidation {
    pub is_valid: bool,
    pub strength: PasswordStrength,
    pub issues: Vec<String>,
    pub suggestions: Vec<String>,
}

/// Audit logging configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct AuditConfig {
    pub enabled: bool,
    pub log_success: bool,
    pub log_failures: bool,
    pub log_permission_changes: bool,
    pub log_admin_actions: bool,
    pub retention_days: u32,
    pub include_metadata: bool,
}

/// Account lockout configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct LockoutConfig {
    pub enabled: bool,
    pub max_failed_attempts: u32,
    pub lockout_duration_seconds: u64,
    pub progressive_lockout: bool,
    pub max_lockout_duration_seconds: u64,
}

/// SMS configuration
///
/// **Security note:** `api_key` is never serialized to prevent accidental
/// secret leakage in logs or config dumps.
#[derive(Clone, Serialize, Deserialize)]
pub struct SmsConfig {
    pub provider: String,
    #[serde(skip_serializing, default)]
    pub api_key: String,
    pub from_number: String,
}

impl std::fmt::Debug for SmsConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut d = f.debug_struct("SmsConfig");
        d.field("provider", &self.provider);
        d.field("api_key", &crate::utils::redact::redacted(&self.api_key));
        d.field("from_number", &self.from_number);
        d.finish()
    }
}

impl Default for SmsConfig {
    fn default() -> Self {
        Self {
            provider: "twilio".to_string(),
            api_key: String::new(),
            from_number: String::new(),
        }
    }
}

/// Email configuration
///
/// **Security note:** `password` is never serialized to prevent accidental
/// secret leakage in logs or config dumps.
#[derive(Clone, Serialize, Deserialize)]
pub struct EmailConfig {
    pub smtp_server: String,
    pub smtp_port: u16,
    pub username: String,
    #[serde(skip_serializing, default)]
    pub password: String,
    pub from_email: String,
    pub use_tls: bool,
}

impl std::fmt::Debug for EmailConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut d = f.debug_struct("EmailConfig");
        d.field("smtp_server", &self.smtp_server);
        d.field("smtp_port", &self.smtp_port);
        d.field("username", &self.username);
        d.field("password", &crate::utils::redact::redacted(&self.password));
        d.field("from_email", &self.from_email);
        d.field("use_tls", &self.use_tls);
        d.finish()
    }
}

impl Default for EmailConfig {
    fn default() -> Self {
        Self {
            smtp_server: "smtp.gmail.com".to_string(),
            smtp_port: 587,
            username: String::new(),
            password: String::new(),
            from_email: String::new(),
            use_tls: true,
        }
    }
}

/// Security context for authentication operations
#[derive(Clone, Default)]
pub struct SecurityContext {
    pub ip_address: Option<String>,
    pub user_agent: Option<String>,
    pub session_id: Option<String>,
    pub request_id: Option<String>,
}

impl std::fmt::Debug for SecurityContext {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut d = f.debug_struct("SecurityContext");
        d.field("ip_address", &self.ip_address);
        d.field("user_agent", &self.user_agent);
        d.field(
            "session_id",
            &crate::utils::redact::redacted(&self.session_id),
        );
        d.field("request_id", &self.request_id);
        d.finish()
    }
}

/// Password validator
pub struct PasswordValidator {
    pub min_length: usize,
    pub require_uppercase: bool,
    pub require_lowercase: bool,
    pub require_digits: bool,
    pub require_special_chars: bool,
    pub min_special_chars: usize,
    pub forbidden_patterns: Vec<String>,
}

impl Default for PasswordValidator {
    fn default() -> Self {
        Self {
            min_length: 8,
            require_uppercase: true,
            require_lowercase: true,
            require_digits: true,
            require_special_chars: true,
            min_special_chars: 1,
            forbidden_patterns: vec![
                "password".to_string(),
                "123456".to_string(),
                "qwerty".to_string(),
                "admin".to_string(),
            ],
        }
    }
}

impl PasswordValidator {
    /// Validate password strength and return detailed results
    pub fn validate(&self, password: &str) -> PasswordValidation {
        let mut is_valid = true;
        let mut issues = Vec::new();
        let mut suggestions = Vec::new();

        // Check minimum length
        if password.len() < self.min_length {
            is_valid = false;
            issues.push(format!(
                "Password must be at least {} characters long",
                self.min_length
            ));
            suggestions.push("Use a longer password".to_string());
        }

        // Check character requirements
        if self.require_uppercase && !password.chars().any(|c| c.is_uppercase()) {
            is_valid = false;
            issues.push("Password must contain at least one uppercase letter".to_string());
            suggestions.push("Add uppercase letters".to_string());
        }

        if self.require_lowercase && !password.chars().any(|c| c.is_lowercase()) {
            is_valid = false;
            issues.push("Password must contain at least one lowercase letter".to_string());
            suggestions.push("Add lowercase letters".to_string());
        }

        if self.require_digits && !password.chars().any(|c| c.is_numeric()) {
            is_valid = false;
            issues.push("Password must contain at least one digit".to_string());
            suggestions.push("Add numbers".to_string());
        }

        if self.require_special_chars {
            let special_count = password.chars().filter(|&c| !c.is_alphanumeric()).count();
            if special_count < self.min_special_chars {
                is_valid = false;
                issues.push(format!(
                    "Password must contain at least {} special characters",
                    self.min_special_chars
                ));
                suggestions.push("Add special characters like !@#$%^&*".to_string());
            }
        }

        // Check forbidden patterns
        for pattern in &self.forbidden_patterns {
            if password.to_lowercase().contains(&pattern.to_lowercase()) {
                is_valid = false;
                issues.push(format!("Password contains forbidden pattern: {}", pattern));
                suggestions.push("Avoid common passwords and patterns".to_string());
            }
        }

        // Assess strength
        let strength = self.assess_strength(password);

        PasswordValidation {
            is_valid,
            strength,
            issues,
            suggestions,
        }
    }

    /// Assess password strength
    fn assess_strength(&self, password: &str) -> PasswordStrength {
        let mut score = 0;

        // Length scoring
        if password.len() >= 8 {
            score += 1;
        }
        if password.len() >= 12 {
            score += 1;
        }
        if password.len() >= 16 {
            score += 1;
        }

        // Character variety scoring
        if password.chars().any(|c| c.is_lowercase()) {
            score += 1;
        }
        if password.chars().any(|c| c.is_uppercase()) {
            score += 1;
        }
        if password.chars().any(|c| c.is_numeric()) {
            score += 1;
        }
        if password.chars().any(|c| !c.is_alphanumeric()) {
            score += 1;
        }

        // Complexity bonus
        if password.len() >= 20 {
            score += 1;
        }

        match score {
            0..=2 => PasswordStrength::VeryWeak,
            3..=4 => PasswordStrength::Weak,
            5 => PasswordStrength::Fair,
            6 => PasswordStrength::Good,
            7 => PasswordStrength::Strong,
            _ => PasswordStrength::VeryStrong,
        }
    }
}

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

    #[test]
    fn test_password_validation() {
        let validator = PasswordValidator::default();

        // Test weak password
        let result = validator.validate("weak");
        assert!(!result.is_valid);
        assert_eq!(result.strength, PasswordStrength::VeryWeak);
        assert!(!result.issues.is_empty());

        // Test strong password
        let result = validator.validate("Strong@Secure123!");
        assert!(result.is_valid);
        assert!(matches!(
            result.strength,
            PasswordStrength::Strong | PasswordStrength::VeryStrong
        ));
        assert!(result.issues.is_empty());
    }

    #[test]
    fn test_forbidden_patterns() {
        let validator = PasswordValidator::default();
        let result = validator.validate("Password123!");
        assert!(!result.is_valid);
        assert!(
            result
                .issues
                .iter()
                .any(|issue| issue.contains("forbidden pattern"))
        );
    }
}