1use serde::{Deserialize, Serialize};
18use zeroize::Zeroizing;
19
20pub mod timing_protection;
22
23pub mod secure_jwt;
25pub mod secure_mfa;
26pub mod secure_session;
27pub mod secure_session_config;
28pub mod secure_utils;
29
30pub mod presets;
32
33#[cfg(feature = "enhanced-crypto")]
35pub mod enhanced_crypto;
36
37pub use presets::{
39 SecurityAuditReport, SecurityAuditStatus, SecurityIssue, SecurityPreset, SecuritySeverity,
40};
41
42#[derive(Debug, Clone, Serialize, Deserialize)]
44pub struct MfaConfig {
45 pub totp_config: TotpConfig,
47 pub sms_config: Option<SmsConfig>,
49 pub email_config: Option<EmailConfig>,
51 pub backup_codes_config: BackupCodesConfig,
53 pub challenge_timeout_seconds: u64,
55 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, max_verification_attempts: 3,
68 }
69 }
70}
71
72#[derive(Debug, Clone, Serialize, Deserialize)]
74pub struct TotpConfig {
75 pub issuer: String,
77 pub digits: u8,
79 pub period: u64,
81 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#[derive(Debug, Clone, Serialize, Deserialize)]
98pub struct BackupCodesConfig {
99 pub count: usize,
101 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#[derive(Debug, Clone, PartialEq)]
116pub enum PasswordStrength {
117 VeryWeak,
118 Weak,
119 Fair,
120 Good,
121 Strong,
122 VeryStrong,
123}
124
125#[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#[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#[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#[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#[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#[derive(Debug, 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
215pub struct PasswordValidator {
217 pub min_length: usize,
218 pub require_uppercase: bool,
219 pub require_lowercase: bool,
220 pub require_digits: bool,
221 pub require_special_chars: bool,
222 pub min_special_chars: usize,
223 pub forbidden_patterns: Vec<String>,
224}
225
226impl Default for PasswordValidator {
227 fn default() -> Self {
228 Self {
229 min_length: 8,
230 require_uppercase: true,
231 require_lowercase: true,
232 require_digits: true,
233 require_special_chars: true,
234 min_special_chars: 1,
235 forbidden_patterns: vec![
236 "password".to_string(),
237 "123456".to_string(),
238 "qwerty".to_string(),
239 "admin".to_string(),
240 ],
241 }
242 }
243}
244
245impl PasswordValidator {
246 pub fn validate(&self, password: &str) -> PasswordValidation {
248 let mut is_valid = true;
249 let mut issues = Vec::new();
250 let mut suggestions = Vec::new();
251
252 if password.len() < self.min_length {
254 is_valid = false;
255 issues.push(format!(
256 "Password must be at least {} characters long",
257 self.min_length
258 ));
259 suggestions.push("Use a longer password".to_string());
260 }
261
262 if self.require_uppercase && !password.chars().any(|c| c.is_uppercase()) {
264 is_valid = false;
265 issues.push("Password must contain at least one uppercase letter".to_string());
266 suggestions.push("Add uppercase letters".to_string());
267 }
268
269 if self.require_lowercase && !password.chars().any(|c| c.is_lowercase()) {
270 is_valid = false;
271 issues.push("Password must contain at least one lowercase letter".to_string());
272 suggestions.push("Add lowercase letters".to_string());
273 }
274
275 if self.require_digits && !password.chars().any(|c| c.is_numeric()) {
276 is_valid = false;
277 issues.push("Password must contain at least one digit".to_string());
278 suggestions.push("Add numbers".to_string());
279 }
280
281 if self.require_special_chars {
282 let special_count = password.chars().filter(|&c| !c.is_alphanumeric()).count();
283 if special_count < self.min_special_chars {
284 is_valid = false;
285 issues.push(format!(
286 "Password must contain at least {} special characters",
287 self.min_special_chars
288 ));
289 suggestions.push("Add special characters like !@#$%^&*".to_string());
290 }
291 }
292
293 for pattern in &self.forbidden_patterns {
295 if password.to_lowercase().contains(&pattern.to_lowercase()) {
296 is_valid = false;
297 issues.push(format!("Password contains forbidden pattern: {}", pattern));
298 suggestions.push("Avoid common passwords and patterns".to_string());
299 }
300 }
301
302 let strength = self.assess_strength(password);
304
305 PasswordValidation {
306 is_valid,
307 strength,
308 issues,
309 suggestions,
310 }
311 }
312
313 fn assess_strength(&self, password: &str) -> PasswordStrength {
315 let mut score = 0;
316
317 if password.len() >= 8 {
319 score += 1;
320 }
321 if password.len() >= 12 {
322 score += 1;
323 }
324 if password.len() >= 16 {
325 score += 1;
326 }
327
328 if password.chars().any(|c| c.is_lowercase()) {
330 score += 1;
331 }
332 if password.chars().any(|c| c.is_uppercase()) {
333 score += 1;
334 }
335 if password.chars().any(|c| c.is_numeric()) {
336 score += 1;
337 }
338 if password.chars().any(|c| !c.is_alphanumeric()) {
339 score += 1;
340 }
341
342 if password.len() >= 20 {
344 score += 1;
345 }
346
347 match score {
348 0..=2 => PasswordStrength::VeryWeak,
349 3..=4 => PasswordStrength::Weak,
350 5 => PasswordStrength::Fair,
351 6 => PasswordStrength::Good,
352 7 => PasswordStrength::Strong,
353 _ => PasswordStrength::VeryStrong,
354 }
355 }
356}
357
358#[cfg(test)]
359mod tests {
360 use super::*;
361
362 #[test]
363 fn test_password_validation() {
364 let validator = PasswordValidator::default();
365
366 let result = validator.validate("weak");
368 assert!(!result.is_valid);
369 assert_eq!(result.strength, PasswordStrength::VeryWeak);
370 assert!(!result.issues.is_empty());
371
372 let result = validator.validate("Strong@Secure123!");
374 assert!(result.is_valid);
375 assert!(matches!(
376 result.strength,
377 PasswordStrength::Strong | PasswordStrength::VeryStrong
378 ));
379 assert!(result.issues.is_empty());
380 }
381
382 #[test]
383 fn test_forbidden_patterns() {
384 let validator = PasswordValidator::default();
385 let result = validator.validate("Password123!");
386 assert!(!result.is_valid);
387 assert!(
388 result
389 .issues
390 .iter()
391 .any(|issue| issue.contains("forbidden pattern"))
392 );
393 }
394}