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