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