1use crate::errors::{AuthError, Result};
7use crate::security::MfaConfig;
8use async_trait::async_trait;
9use rand::Rng;
10use serde::{Deserialize, Serialize};
11use std::time::{SystemTime, UNIX_EPOCH};
12use totp_lite::{Sha1, totp};
13
14#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
16pub enum MfaMethodType {
17 Totp,
18 Sms,
19 Email,
20 WebAuthn,
21 BackupCodes,
22}
23
24#[derive(Debug, Clone, Serialize, Deserialize)]
26pub struct MfaChallenge {
27 pub id: String,
29 pub user_id: String,
31 pub method_type: MfaMethodType,
33 pub challenge_data: MfaChallengeData,
35 pub created_at: SystemTime,
37 pub expires_at: SystemTime,
39 pub attempts: u32,
41 pub max_attempts: u32,
43}
44
45#[derive(Clone, Serialize, Deserialize)]
47pub enum MfaChallengeData {
48 Totp {
49 time_window: u64,
51 },
52 Sms {
53 phone_number: String,
55 code: String,
57 },
58 Email {
59 email: String,
61 code: String,
63 },
64 WebAuthn {
65 challenge: Vec<u8>,
67 allowed_credentials: Vec<String>,
69 },
70 BackupCodes {
71 remaining_codes: u32,
73 },
74}
75
76impl std::fmt::Debug for MfaChallengeData {
77 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
78 use crate::utils::redact::redacted;
79 match self {
80 Self::Totp { time_window } => f
81 .debug_struct("Totp")
82 .field("time_window", time_window)
83 .finish(),
84 Self::Sms { phone_number, code } => f
85 .debug_struct("Sms")
86 .field("phone_number", phone_number)
87 .field("code", &redacted(code))
88 .finish(),
89 Self::Email { email, code } => f
90 .debug_struct("Email")
91 .field("email", email)
92 .field("code", &redacted(code))
93 .finish(),
94 Self::WebAuthn {
95 challenge,
96 allowed_credentials,
97 } => f
98 .debug_struct("WebAuthn")
99 .field("challenge", &redacted(challenge))
100 .field("allowed_credentials", allowed_credentials)
101 .finish(),
102 Self::BackupCodes { remaining_codes } => f
103 .debug_struct("BackupCodes")
104 .field("remaining_codes", remaining_codes)
105 .finish(),
106 }
107 }
108}
109
110#[derive(Debug, Clone, Serialize, Deserialize)]
112pub struct UserMfaMethod {
113 pub id: String,
115 pub user_id: String,
117 pub method_type: MfaMethodType,
119 pub method_data: MfaMethodData,
121 pub display_name: String,
123 pub is_primary: bool,
125 pub is_enabled: bool,
127 pub created_at: SystemTime,
129 pub last_used_at: Option<SystemTime>,
131}
132
133#[derive(Clone, Serialize, Deserialize)]
135pub enum MfaMethodData {
136 Totp {
137 secret_key: String,
139 qr_code_url: String,
141 },
142 Sms {
143 phone_number: String,
145 is_verified: bool,
147 },
148 Email {
149 email: String,
151 is_verified: bool,
153 },
154 WebAuthn {
155 credential_id: String,
157 public_key: Vec<u8>,
159 counter: u32,
161 },
162 BackupCodes {
163 codes: Vec<String>,
165 used_count: u32,
167 },
168}
169
170impl std::fmt::Debug for MfaMethodData {
171 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
172 use crate::utils::redact::redacted;
173 match self {
174 Self::Totp {
175 secret_key,
176 qr_code_url,
177 } => f
178 .debug_struct("Totp")
179 .field("secret_key", &crate::utils::redact::redacted(secret_key))
180 .field("qr_code_url", &redacted(qr_code_url))
181 .finish(),
182 Self::Sms {
183 phone_number,
184 is_verified,
185 } => f
186 .debug_struct("Sms")
187 .field("phone_number", phone_number)
188 .field("is_verified", is_verified)
189 .finish(),
190 Self::Email { email, is_verified } => f
191 .debug_struct("Email")
192 .field("email", email)
193 .field("is_verified", is_verified)
194 .finish(),
195 Self::WebAuthn {
196 credential_id,
197 public_key,
198 counter,
199 } => f
200 .debug_struct("WebAuthn")
201 .field("credential_id", credential_id)
202 .field("public_key", public_key)
203 .field("counter", counter)
204 .finish(),
205 Self::BackupCodes { codes, used_count } => f
206 .debug_struct("BackupCodes")
207 .field("codes", &redacted(codes))
208 .field("used_count", used_count)
209 .finish(),
210 }
211 }
212}
213
214#[derive(Debug, Clone)]
216pub struct MfaVerificationResult {
217 pub success: bool,
219 pub method_type: MfaMethodType,
221 pub remaining_attempts: Option<u32>,
223 pub error_message: Option<String>,
225}
226
227pub struct TotpProvider {
229 config: crate::security::TotpConfig,
230}
231
232impl TotpProvider {
233 pub fn new(config: crate::security::TotpConfig) -> Self {
234 Self { config }
235 }
236
237 pub fn generate_secret(&self) -> crate::Result<String> {
239 use ring::rand::{SecureRandom, SystemRandom};
240 let rng = SystemRandom::new();
241 let mut secret = [0u8; 20];
242 rng.fill(&mut secret).map_err(|_| {
243 crate::errors::AuthError::crypto("Failed to generate secure TOTP secret".to_string())
244 })?;
245 Ok(base32::encode(
246 base32::Alphabet::Rfc4648 { padding: true },
247 &secret,
248 ))
249 }
250
251 pub fn generate_qr_code_url(&self, secret: &str, user_identifier: &str) -> String {
253 format!(
254 "otpauth://totp/{}:{}?secret={}&issuer={}&digits={}&period={}",
255 urlencoding::encode(&self.config.issuer),
256 urlencoding::encode(user_identifier),
257 secret,
258 urlencoding::encode(&self.config.issuer),
259 self.config.digits,
260 self.config.period
261 )
262 }
263
264 pub fn generate_code(&self, secret: &str, time_step: Option<u64>) -> Result<String> {
266 if secret.trim().is_empty() {
267 return Err(AuthError::validation("TOTP secret cannot be empty"));
268 }
269
270 let secret_bytes = base32::decode(base32::Alphabet::Rfc4648 { padding: true }, secret)
271 .ok_or_else(|| AuthError::validation("Invalid TOTP secret"))?;
272
273 let time_step = time_step.unwrap_or_else(|| {
274 SystemTime::now()
275 .duration_since(UNIX_EPOCH)
276 .unwrap()
277 .as_secs()
278 / self.config.period
279 });
280
281 let unix_timestamp = time_step.checked_mul(self.config.period).ok_or_else(|| {
284 AuthError::InvalidInput("Time step too large for conversion".to_string())
285 })?;
286
287 let totp_value = totp::<Sha1>(&secret_bytes, unix_timestamp);
289
290 let parsed_value: u32 = totp_value
292 .parse()
293 .map_err(|_| AuthError::validation("TOTP generation error"))?;
294
295 Ok(format!(
297 "{:0width$}",
298 parsed_value % 10_u32.pow(self.config.digits.into()),
299 width = self.config.digits as usize
300 ))
301 }
302
303 pub fn verify_code(&self, secret: &str, code: &str, time_window: Option<u64>) -> Result<bool> {
305 let _secret_bytes = base32::decode(base32::Alphabet::Rfc4648 { padding: true }, secret)
307 .ok_or_else(|| AuthError::validation("Invalid TOTP secret"))?;
308
309 let current_time_step = if let Some(time) = time_window {
310 time / self.config.period
311 } else {
312 SystemTime::now()
313 .duration_since(UNIX_EPOCH)
314 .unwrap()
315 .as_secs()
316 / self.config.period
317 };
318
319 for step_offset in [-1i64, 0, 1] {
321 let time_step_i64 = current_time_step as i64 + step_offset;
322 if time_step_i64 < 0 {
324 continue;
325 }
326 let time_step = time_step_i64 as u64;
327 let expected_code = self.generate_code(secret, Some(time_step))?;
328 if expected_code == code {
329 return Ok(true);
330 }
331 }
332
333 Ok(false)
334 }
335
336 pub fn verify_totp(&self, secret: &str, token: &str, window: u8) -> Result<bool> {
338 let now = SystemTime::now()
339 .duration_since(UNIX_EPOCH)
340 .map_err(|_| AuthError::validation("System time error"))?
341 .as_secs()
342 / self.config.period;
343
344 use subtle::ConstantTimeEq;
346
347 for i in 0..=window {
348 if i == 0 {
350 if let Ok(expected_code) = self.generate_code(secret, Some(now))
351 && expected_code.as_bytes().ct_eq(token.as_bytes()).into()
352 {
353 return Ok(true);
354 }
355 } else {
356 for offset in [i as i64, -(i as i64)] {
358 let time_step_i64 = now as i64 + offset;
359 if time_step_i64 < 0 {
361 continue;
362 }
363 let time_step = time_step_i64 as u64;
364 if let Ok(expected_code) = self.generate_code(secret, Some(time_step))
365 && expected_code.as_bytes().ct_eq(token.as_bytes()).into()
366 {
367 return Ok(true);
368 }
369 }
370 }
371 }
372 Ok(false)
373 }
374}
375
376#[async_trait]
378pub trait SmsProvider: Send + Sync {
379 async fn send_code(&self, phone_number: &str, code: &str) -> Result<()>;
380}
381
382#[async_trait]
384pub trait EmailProvider: Send + Sync {
385 async fn send_code(&self, email: &str, code: &str) -> Result<()>;
386}
387
388pub struct BackupCodesProvider;
390
391impl BackupCodesProvider {
392 pub fn generate_codes(count: u8) -> Vec<String> {
394 let mut rng = rand::rng();
395 (0..count)
396 .map(|_| {
397 format!(
398 "{:04}-{:04}",
399 rng.random_range(1000..9999),
400 rng.random_range(1000..9999)
401 )
402 })
403 .collect()
404 }
405
406 pub fn hash_codes(codes: &[String]) -> Result<Vec<String>> {
408 codes
409 .iter()
410 .map(|code| {
411 Ok(format!("hashed_{}", code))
413 })
414 .collect()
415 }
416
417 pub fn verify_code(hashed_codes: &[String], provided_code: &str) -> bool {
419 let expected_hash = format!("hashed_{}", provided_code);
420 hashed_codes.contains(&expected_hash)
421 }
422}
423
424#[async_trait]
426pub trait MfaStorage: Send + Sync {
427 async fn store_mfa_method(&self, method: &UserMfaMethod) -> Result<()>;
429
430 async fn get_user_mfa_methods(&self, user_id: &str) -> Result<Vec<UserMfaMethod>>;
432
433 async fn update_mfa_method(&self, method: &UserMfaMethod) -> Result<()>;
435
436 async fn delete_mfa_method(&self, method_id: &str) -> Result<()>;
438
439 async fn store_mfa_challenge(&self, challenge: &MfaChallenge) -> Result<()>;
441
442 async fn get_mfa_challenge(&self, challenge_id: &str) -> Result<Option<MfaChallenge>>;
444
445 async fn update_mfa_challenge(&self, challenge: &MfaChallenge) -> Result<()>;
447
448 async fn delete_mfa_challenge(&self, challenge_id: &str) -> Result<()>;
450
451 async fn cleanup_expired_challenges(&self) -> Result<()>;
453}
454
455pub struct MfaManager<S: MfaStorage> {
457 storage: S,
458 config: MfaConfig,
459 totp_provider: TotpProvider,
460 sms_provider: Option<Box<dyn SmsProvider>>,
461 email_provider: Option<Box<dyn EmailProvider>>,
462}
463
464impl<S: MfaStorage> MfaManager<S> {
465 pub fn new(storage: S, config: MfaConfig) -> Self {
467 let totp_provider = TotpProvider::new(config.totp_config.clone());
468
469 Self {
470 storage,
471 config,
472 totp_provider,
473 sms_provider: None,
474 email_provider: None,
475 }
476 }
477
478 pub fn with_sms_provider(mut self, provider: Box<dyn SmsProvider>) -> Self {
480 self.sms_provider = Some(provider);
481 self
482 }
483
484 pub fn with_email_provider(mut self, provider: Box<dyn EmailProvider>) -> Self {
486 self.email_provider = Some(provider);
487 self
488 }
489
490 pub async fn setup_totp(&self, user_id: &str, user_identifier: &str) -> Result<UserMfaMethod> {
492 let secret = self.totp_provider.generate_secret()?;
493 let qr_code_url = self
494 .totp_provider
495 .generate_qr_code_url(&secret, user_identifier);
496
497 let method = UserMfaMethod {
498 id: uuid::Uuid::new_v4().to_string(),
499 user_id: user_id.to_string(),
500 method_type: MfaMethodType::Totp,
501 method_data: MfaMethodData::Totp {
502 secret_key: secret,
503 qr_code_url,
504 },
505 display_name: "Authenticator App".to_string(),
506 is_primary: false,
507 is_enabled: false, created_at: SystemTime::now(),
509 last_used_at: None,
510 };
511
512 self.storage.store_mfa_method(&method).await?;
513 Ok(method)
514 }
515
516 pub async fn setup_sms(&self, user_id: &str, phone_number: &str) -> Result<UserMfaMethod> {
518 let method = UserMfaMethod {
519 id: uuid::Uuid::new_v4().to_string(),
520 user_id: user_id.to_string(),
521 method_type: MfaMethodType::Sms,
522 method_data: MfaMethodData::Sms {
523 phone_number: phone_number.to_string(),
524 is_verified: false,
525 },
526 display_name: format!("SMS to {}", mask_phone_number(phone_number)),
527 is_primary: false,
528 is_enabled: false,
529 created_at: SystemTime::now(),
530 last_used_at: None,
531 };
532
533 self.storage.store_mfa_method(&method).await?;
534 Ok(method)
535 }
536
537 pub async fn generate_backup_codes(
539 &self,
540 user_id: &str,
541 ) -> Result<(UserMfaMethod, Vec<String>)> {
542 let codes = BackupCodesProvider::generate_codes(10);
543 let hashed_codes = BackupCodesProvider::hash_codes(&codes)?;
544
545 let method = UserMfaMethod {
546 id: uuid::Uuid::new_v4().to_string(),
547 user_id: user_id.to_string(),
548 method_type: MfaMethodType::BackupCodes,
549 method_data: MfaMethodData::BackupCodes {
550 codes: hashed_codes,
551 used_count: 0,
552 },
553 display_name: "Backup Codes".to_string(),
554 is_primary: false,
555 is_enabled: true,
556 created_at: SystemTime::now(),
557 last_used_at: None,
558 };
559
560 self.storage.store_mfa_method(&method).await?;
561 Ok((method, codes))
562 }
563
564 pub async fn create_challenge(
566 &self,
567 user_id: &str,
568 method_type: MfaMethodType,
569 ) -> Result<MfaChallenge> {
570 let user_methods = self.storage.get_user_mfa_methods(user_id).await?;
571 let method = user_methods
572 .iter()
573 .find(|m| m.method_type == method_type && m.is_enabled)
574 .ok_or_else(|| AuthError::validation("MFA method not found or not enabled"))?;
575
576 let challenge_data = match &method.method_data {
577 MfaMethodData::Totp { .. } => MfaChallengeData::Totp {
578 time_window: SystemTime::now()
579 .duration_since(UNIX_EPOCH)
580 .unwrap()
581 .as_secs()
582 / self.config.totp_config.period,
583 },
584 MfaMethodData::Sms { phone_number, .. } => {
585 let code = generate_numeric_code(6);
586 if let Some(sms_provider) = &self.sms_provider {
587 sms_provider.send_code(phone_number, &code).await?;
588 }
589 MfaChallengeData::Sms {
590 phone_number: mask_phone_number(phone_number),
591 code,
592 }
593 }
594 MfaMethodData::Email { email, .. } => {
595 let code = generate_numeric_code(6);
596 if let Some(email_provider) = &self.email_provider {
597 email_provider.send_code(email, &code).await?;
598 }
599 MfaChallengeData::Email {
600 email: mask_email(email),
601 code,
602 }
603 }
604 MfaMethodData::BackupCodes { .. } => {
605 MfaChallengeData::BackupCodes { remaining_codes: 8 } }
607 _ => return Err(AuthError::validation("Unsupported MFA method type")),
608 };
609
610 let challenge = MfaChallenge {
611 id: uuid::Uuid::new_v4().to_string(),
612 user_id: user_id.to_string(),
613 method_type,
614 challenge_data,
615 created_at: SystemTime::now(),
616 expires_at: SystemTime::now() + std::time::Duration::from_secs(300), attempts: 0,
618 max_attempts: 3,
619 };
620
621 self.storage.store_mfa_challenge(&challenge).await?;
622 Ok(challenge)
623 }
624
625 pub async fn verify_challenge(
627 &self,
628 challenge_id: &str,
629 response: &str,
630 ) -> Result<MfaVerificationResult> {
631 let mut challenge = self
632 .storage
633 .get_mfa_challenge(challenge_id)
634 .await?
635 .ok_or_else(|| AuthError::validation("MFA challenge not found"))?;
636
637 if SystemTime::now() > challenge.expires_at {
639 self.storage.delete_mfa_challenge(challenge_id).await?;
640 return Ok(MfaVerificationResult {
641 success: false,
642 method_type: challenge.method_type,
643 remaining_attempts: None,
644 error_message: Some("Challenge has expired".to_string()),
645 });
646 }
647
648 if challenge.attempts >= challenge.max_attempts {
650 self.storage.delete_mfa_challenge(challenge_id).await?;
651 return Ok(MfaVerificationResult {
652 success: false,
653 method_type: challenge.method_type,
654 remaining_attempts: Some(0),
655 error_message: Some("Maximum attempts exceeded".to_string()),
656 });
657 }
658
659 challenge.attempts += 1;
660
661 let success = match &challenge.challenge_data {
662 MfaChallengeData::Totp { time_window } => {
663 let user_methods = self
664 .storage
665 .get_user_mfa_methods(&challenge.user_id)
666 .await?;
667 if let Some(method) = user_methods
668 .iter()
669 .find(|m| m.method_type == MfaMethodType::Totp)
670 {
671 if let MfaMethodData::Totp { secret_key, .. } = &method.method_data {
672 self.totp_provider
673 .verify_code(secret_key, response, Some(*time_window))?
674 } else {
675 false
676 }
677 } else {
678 false
679 }
680 }
681 MfaChallengeData::Sms { code, .. } => code == response,
682 MfaChallengeData::Email { code, .. } => code == response,
683 MfaChallengeData::BackupCodes { .. } => {
684 let user_methods = self
685 .storage
686 .get_user_mfa_methods(&challenge.user_id)
687 .await?;
688 if let Some(method) = user_methods
689 .iter()
690 .find(|m| m.method_type == MfaMethodType::BackupCodes)
691 {
692 if let MfaMethodData::BackupCodes { codes, .. } = &method.method_data {
693 BackupCodesProvider::verify_code(codes, response)
694 } else {
695 false
696 }
697 } else {
698 false
699 }
700 }
701 _ => false,
702 };
703
704 if success {
705 self.storage.delete_mfa_challenge(challenge_id).await?;
706 Ok(MfaVerificationResult {
707 success: true,
708 method_type: challenge.method_type,
709 remaining_attempts: None,
710 error_message: None,
711 })
712 } else {
713 let remaining = challenge.max_attempts.saturating_sub(challenge.attempts);
714 self.storage.update_mfa_challenge(&challenge).await?;
715
716 Ok(MfaVerificationResult {
717 success: false,
718 method_type: challenge.method_type,
719 remaining_attempts: Some(remaining),
720 error_message: Some("Invalid code".to_string()),
721 })
722 }
723 }
724
725 pub async fn has_mfa_enabled(&self, user_id: &str) -> Result<bool> {
727 let methods = self.storage.get_user_mfa_methods(user_id).await?;
728 Ok(methods.iter().any(|m| m.is_enabled))
729 }
730
731 pub async fn get_enabled_methods(&self, user_id: &str) -> Result<Vec<MfaMethodType>> {
733 let methods = self.storage.get_user_mfa_methods(user_id).await?;
734 Ok(methods
735 .iter()
736 .filter(|m| m.is_enabled)
737 .map(|m| m.method_type.clone())
738 .collect())
739 }
740}
741
742fn generate_numeric_code(length: u8) -> String {
744 let mut rng = rand::rng();
745 (0..length)
746 .map(|_| rng.random_range(0..10).to_string())
747 .collect()
748}
749
750fn mask_phone_number(phone: &str) -> String {
752 if phone.len() > 4 {
753 format!("***-***-{}", &phone[phone.len() - 4..])
754 } else {
755 "***-***-****".to_string()
756 }
757}
758
759fn mask_email(email: &str) -> String {
761 if let Some(at_pos) = email.find('@') {
762 let (local, domain) = email.split_at(at_pos);
763 if local.len() > 2 {
764 format!("{}***{}", &local[0..1], domain)
765 } else {
766 format!("***{}", domain)
767 }
768 } else {
769 "***@***.***".to_string()
770 }
771}
772
773#[cfg(test)]
774mod tests {
775 use super::*;
776
777 #[test]
778 fn test_totp_generation() {
779 let config = crate::security::TotpConfig::default();
780 let provider = TotpProvider::new(config);
781
782 let secret = provider.generate_secret().unwrap();
783 assert!(!secret.is_empty());
784
785 let code = provider.generate_code(&secret, Some(1)).unwrap();
786 assert_eq!(code.len(), 6);
787
788 assert!(provider.verify_code(&secret, &code, Some(1)).unwrap());
790
791 assert!(!provider.verify_code(&secret, "000000", Some(1)).unwrap());
793 }
794
795 #[test]
796 fn test_backup_codes() {
797 let codes = BackupCodesProvider::generate_codes(5);
798 assert_eq!(codes.len(), 5);
799
800 let hashed = BackupCodesProvider::hash_codes(&codes).unwrap();
801 assert_eq!(hashed.len(), 5);
802
803 assert!(BackupCodesProvider::verify_code(&hashed, &codes[0]));
805
806 assert!(!BackupCodesProvider::verify_code(&hashed, "1234-5678"));
808 }
809
810 #[test]
811 fn test_masking() {
812 assert_eq!(mask_phone_number("+1234567890"), "***-***-7890");
813 assert_eq!(mask_email("user@example.com"), "u***@example.com");
814 }
815}