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