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(Debug, 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
78#[derive(Debug, Clone, Serialize, Deserialize)]
80pub struct UserMfaMethod {
81 pub id: String,
83 pub user_id: String,
85 pub method_type: MfaMethodType,
87 pub method_data: MfaMethodData,
89 pub display_name: String,
91 pub is_primary: bool,
93 pub is_enabled: bool,
95 pub created_at: SystemTime,
97 pub last_used_at: Option<SystemTime>,
99}
100
101#[derive(Clone, Serialize, Deserialize)]
103pub enum MfaMethodData {
104 Totp {
105 secret_key: Zeroizing<String>,
107 qr_code_url: String,
109 },
110 Sms {
111 phone_number: String,
113 is_verified: bool,
115 },
116 Email {
117 email: String,
119 is_verified: bool,
121 },
122 WebAuthn {
123 credential_id: String,
125 public_key: Vec<u8>,
127 counter: u32,
129 },
130 BackupCodes {
131 codes: Vec<String>,
133 used_count: u32,
135 },
136}
137
138impl std::fmt::Debug for MfaMethodData {
139 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
140 use crate::utils::redact::redacted;
141 match self {
142 Self::Totp {
143 secret_key,
144 qr_code_url,
145 } => f
146 .debug_struct("Totp")
147 .field("secret_key", secret_key)
148 .field("qr_code_url", &redacted(qr_code_url))
149 .finish(),
150 Self::Sms {
151 phone_number,
152 is_verified,
153 } => f
154 .debug_struct("Sms")
155 .field("phone_number", phone_number)
156 .field("is_verified", is_verified)
157 .finish(),
158 Self::Email { email, is_verified } => f
159 .debug_struct("Email")
160 .field("email", email)
161 .field("is_verified", is_verified)
162 .finish(),
163 Self::WebAuthn {
164 credential_id,
165 public_key,
166 counter,
167 } => f
168 .debug_struct("WebAuthn")
169 .field("credential_id", credential_id)
170 .field("public_key", public_key)
171 .field("counter", counter)
172 .finish(),
173 Self::BackupCodes { codes, used_count } => f
174 .debug_struct("BackupCodes")
175 .field("codes", &redacted(codes))
176 .field("used_count", used_count)
177 .finish(),
178 }
179 }
180}
181
182#[derive(Debug, Clone)]
184pub struct MfaVerificationResult {
185 pub success: bool,
187 pub method_type: MfaMethodType,
189 pub remaining_attempts: Option<u32>,
191 pub error_message: Option<String>,
193}
194
195pub struct TotpProvider {
197 config: crate::security::TotpConfig,
198}
199
200impl TotpProvider {
201 pub fn new(config: crate::security::TotpConfig) -> Self {
202 Self { config }
203 }
204
205 pub fn generate_secret(&self) -> crate::Result<String> {
207 use ring::rand::{SecureRandom, SystemRandom};
208 let rng = SystemRandom::new();
209 let mut secret = [0u8; 20];
210 rng.fill(&mut secret).map_err(|_| {
211 crate::errors::AuthError::crypto("Failed to generate secure TOTP secret".to_string())
212 })?;
213 Ok(base32::encode(
214 base32::Alphabet::Rfc4648 { padding: true },
215 &secret,
216 ))
217 }
218
219 pub fn generate_qr_code_url(&self, secret: &str, user_identifier: &str) -> String {
221 format!(
222 "otpauth://totp/{}:{}?secret={}&issuer={}&digits={}&period={}",
223 urlencoding::encode(&self.config.issuer),
224 urlencoding::encode(user_identifier),
225 secret,
226 urlencoding::encode(&self.config.issuer),
227 self.config.digits,
228 self.config.period
229 )
230 }
231
232 pub fn generate_code(&self, secret: &str, time_step: Option<u64>) -> Result<String> {
234 if secret.trim().is_empty() {
235 return Err(AuthError::validation("TOTP secret cannot be empty"));
236 }
237
238 let secret_bytes = base32::decode(base32::Alphabet::Rfc4648 { padding: true }, secret)
239 .ok_or_else(|| AuthError::validation("Invalid TOTP secret"))?;
240
241 let time_step = time_step.unwrap_or_else(|| {
242 SystemTime::now()
243 .duration_since(UNIX_EPOCH)
244 .unwrap_or_default()
245 .as_secs()
246 / self.config.period
247 });
248
249 let unix_timestamp = time_step.checked_mul(self.config.period).ok_or_else(|| {
252 AuthError::InvalidInput("Time step too large for conversion".to_string())
253 })?;
254
255 let totp_value = totp::<Sha1>(&secret_bytes, unix_timestamp);
257
258 let parsed_value: u32 = totp_value
260 .parse()
261 .map_err(|_| AuthError::validation("TOTP generation error"))?;
262
263 Ok(format!(
265 "{:0width$}",
266 parsed_value % 10_u32.pow(self.config.digits.into()),
267 width = self.config.digits as usize
268 ))
269 }
270
271 pub fn verify_code(&self, secret: &str, code: &str, time_window: Option<u64>) -> Result<bool> {
273 let _secret_bytes = base32::decode(base32::Alphabet::Rfc4648 { padding: true }, secret)
275 .ok_or_else(|| AuthError::validation("Invalid TOTP secret"))?;
276
277 let current_time_step = if let Some(time) = time_window {
278 time / self.config.period
279 } else {
280 SystemTime::now()
281 .duration_since(UNIX_EPOCH)
282 .unwrap_or_default()
283 .as_secs()
284 / self.config.period
285 };
286
287 let mut matched = false;
290 for step_offset in [-1i64, 0, 1] {
291 let time_step_i64 = current_time_step as i64 + step_offset;
292 if time_step_i64 < 0 {
294 continue;
295 }
296 let time_step = time_step_i64 as u64;
297 let expected_code = self.generate_code(secret, Some(time_step))?;
298 let eq: bool = expected_code.as_bytes().ct_eq(code.as_bytes()).into();
299 matched |= eq;
300 }
301
302 Ok(matched)
303 }
304
305 pub fn verify_totp(&self, secret: &str, token: &str, window: u8) -> Result<bool> {
307 let now = SystemTime::now()
308 .duration_since(UNIX_EPOCH)
309 .map_err(|_| AuthError::validation("System time error"))?
310 .as_secs()
311 / self.config.period;
312
313 for i in 0..=window {
316 if i == 0 {
318 if let Ok(expected_code) = self.generate_code(secret, Some(now))
319 && expected_code.as_bytes().ct_eq(token.as_bytes()).into()
320 {
321 return Ok(true);
322 }
323 } else {
324 for offset in [i as i64, -(i as i64)] {
326 let time_step_i64 = now as i64 + offset;
327 if time_step_i64 < 0 {
329 continue;
330 }
331 let time_step = time_step_i64 as u64;
332 if let Ok(expected_code) = self.generate_code(secret, Some(time_step))
333 && expected_code.as_bytes().ct_eq(token.as_bytes()).into()
334 {
335 return Ok(true);
336 }
337 }
338 }
339 }
340 Ok(false)
341 }
342}
343
344#[async_trait]
346pub trait SmsProvider: Send + Sync {
347 async fn send_code(&self, phone_number: &str, code: &str) -> Result<()>;
348}
349
350#[async_trait]
352pub trait EmailProvider: Send + Sync {
353 async fn send_code(&self, email: &str, code: &str) -> Result<()>;
354}
355
356pub struct BackupCodesProvider;
358
359impl BackupCodesProvider {
360 pub fn generate_codes(count: u8) -> Vec<String> {
362 let rng = ring::rand::SystemRandom::new();
363 (0..count)
364 .map(|_| {
365 let mut buf = [0u8; 4];
366 rng.fill(&mut buf).expect("system RNG failure");
367 let val1 = u16::from_le_bytes([buf[0], buf[1]]) % 8999 + 1000;
368 let val2 = u16::from_le_bytes([buf[2], buf[3]]) % 8999 + 1000;
369 format!("{:04}-{:04}", val1, val2)
370 })
371 .collect()
372 }
373
374 pub fn hash_codes(codes: &[String]) -> Result<Vec<String>> {
376 use sha2::{Digest, Sha256};
377 codes
378 .iter()
379 .map(|code| {
380 let hash = Sha256::digest(code.as_bytes());
381 Ok(hex::encode(hash))
382 })
383 .collect()
384 }
385
386 pub fn verify_code(hashed_codes: &[String], provided_code: &str) -> bool {
388 use sha2::{Digest, Sha256};
389 let provided_hash = hex::encode(Sha256::digest(provided_code.as_bytes()));
390 let provided_bytes = provided_hash.as_bytes();
391 hashed_codes
392 .iter()
393 .any(|h| h.as_bytes().ct_eq(provided_bytes).into())
394 }
395}
396
397#[async_trait]
399pub trait MfaStorage: Send + Sync {
400 async fn store_mfa_method(&self, method: &UserMfaMethod) -> Result<()>;
402
403 async fn get_user_mfa_methods(&self, user_id: &str) -> Result<Vec<UserMfaMethod>>;
405
406 async fn update_mfa_method(&self, method: &UserMfaMethod) -> Result<()>;
408
409 async fn delete_mfa_method(&self, method_id: &str) -> Result<()>;
411
412 async fn store_mfa_challenge(&self, challenge: &MfaChallenge) -> Result<()>;
414
415 async fn get_mfa_challenge(&self, challenge_id: &str) -> Result<Option<MfaChallenge>>;
417
418 async fn update_mfa_challenge(&self, challenge: &MfaChallenge) -> Result<()>;
420
421 async fn delete_mfa_challenge(&self, challenge_id: &str) -> Result<()>;
423
424 async fn cleanup_expired_challenges(&self) -> Result<()>;
426}
427
428pub struct MfaManager<S: MfaStorage> {
430 storage: S,
431 config: MfaConfig,
432 totp_provider: TotpProvider,
433 sms_provider: Option<Box<dyn SmsProvider>>,
434 email_provider: Option<Box<dyn EmailProvider>>,
435}
436
437impl<S: MfaStorage> MfaManager<S> {
438 pub fn new(storage: S, config: MfaConfig) -> Self {
440 let totp_provider = TotpProvider::new(config.totp_config.clone());
441
442 Self {
443 storage,
444 config,
445 totp_provider,
446 sms_provider: None,
447 email_provider: None,
448 }
449 }
450
451 pub fn with_sms_provider(mut self, provider: Box<dyn SmsProvider>) -> Self {
453 self.sms_provider = Some(provider);
454 self
455 }
456
457 pub fn with_email_provider(mut self, provider: Box<dyn EmailProvider>) -> Self {
459 self.email_provider = Some(provider);
460 self
461 }
462
463 pub async fn setup_totp(&self, user_id: &str, user_identifier: &str) -> Result<UserMfaMethod> {
465 let secret = self.totp_provider.generate_secret()?;
466 let qr_code_url = self
467 .totp_provider
468 .generate_qr_code_url(&secret, user_identifier);
469
470 let method = UserMfaMethod {
471 id: uuid::Uuid::new_v4().to_string(),
472 user_id: user_id.to_string(),
473 method_type: MfaMethodType::Totp,
474 method_data: MfaMethodData::Totp {
475 secret_key: secret.into(),
476 qr_code_url,
477 },
478 display_name: "Authenticator App".to_string(),
479 is_primary: false,
480 is_enabled: false, created_at: SystemTime::now(),
482 last_used_at: None,
483 };
484
485 self.storage.store_mfa_method(&method).await?;
486 Ok(method)
487 }
488
489 pub async fn setup_sms(&self, user_id: &str, phone_number: &str) -> Result<UserMfaMethod> {
491 let method = UserMfaMethod {
492 id: uuid::Uuid::new_v4().to_string(),
493 user_id: user_id.to_string(),
494 method_type: MfaMethodType::Sms,
495 method_data: MfaMethodData::Sms {
496 phone_number: phone_number.to_string(),
497 is_verified: false,
498 },
499 display_name: format!("SMS to {}", mask_phone_number(phone_number)),
500 is_primary: false,
501 is_enabled: false,
502 created_at: SystemTime::now(),
503 last_used_at: None,
504 };
505
506 self.storage.store_mfa_method(&method).await?;
507 Ok(method)
508 }
509
510 pub async fn generate_backup_codes(
512 &self,
513 user_id: &str,
514 ) -> Result<(UserMfaMethod, Vec<String>)> {
515 let codes = BackupCodesProvider::generate_codes(10);
516 let hashed_codes = BackupCodesProvider::hash_codes(&codes)?;
517
518 let method = UserMfaMethod {
519 id: uuid::Uuid::new_v4().to_string(),
520 user_id: user_id.to_string(),
521 method_type: MfaMethodType::BackupCodes,
522 method_data: MfaMethodData::BackupCodes {
523 codes: hashed_codes,
524 used_count: 0,
525 },
526 display_name: "Backup Codes".to_string(),
527 is_primary: false,
528 is_enabled: true,
529 created_at: SystemTime::now(),
530 last_used_at: None,
531 };
532
533 self.storage.store_mfa_method(&method).await?;
534 Ok((method, codes))
535 }
536
537 pub async fn create_challenge(
539 &self,
540 user_id: &str,
541 method_type: MfaMethodType,
542 ) -> Result<MfaChallenge> {
543 let user_methods = self.storage.get_user_mfa_methods(user_id).await?;
544 let method = user_methods
545 .iter()
546 .find(|m| m.method_type == method_type && m.is_enabled)
547 .ok_or_else(|| AuthError::validation("MFA method not found or not enabled"))?;
548
549 let challenge_data = match &method.method_data {
550 MfaMethodData::Totp { .. } => MfaChallengeData::Totp {
551 time_window: SystemTime::now()
552 .duration_since(UNIX_EPOCH)
553 .unwrap_or_default()
554 .as_secs()
555 / self.config.totp_config.period,
556 },
557 MfaMethodData::Sms { phone_number, .. } => {
558 let code = generate_numeric_code(6);
559 if let Some(sms_provider) = &self.sms_provider {
560 sms_provider.send_code(phone_number, &code).await?;
561 }
562 MfaChallengeData::Sms {
563 phone_number: mask_phone_number(phone_number),
564 code,
565 }
566 }
567 MfaMethodData::Email { email, .. } => {
568 let code = generate_numeric_code(6);
569 if let Some(email_provider) = &self.email_provider {
570 email_provider.send_code(email, &code).await?;
571 }
572 MfaChallengeData::Email {
573 email: mask_email(email),
574 code,
575 }
576 }
577 MfaMethodData::BackupCodes { .. } => {
578 MfaChallengeData::BackupCodes { remaining_codes: 8 } }
580 _ => return Err(AuthError::validation("Unsupported MFA method type")),
581 };
582
583 let challenge = MfaChallenge {
584 id: uuid::Uuid::new_v4().to_string(),
585 user_id: user_id.to_string(),
586 method_type,
587 challenge_data,
588 created_at: SystemTime::now(),
589 expires_at: SystemTime::now() + std::time::Duration::from_secs(300), attempts: 0,
591 max_attempts: 3,
592 };
593
594 self.storage.store_mfa_challenge(&challenge).await?;
595 Ok(challenge)
596 }
597
598 pub async fn verify_challenge(
600 &self,
601 challenge_id: &str,
602 response: &str,
603 ) -> Result<MfaVerificationResult> {
604 let mut challenge = self
605 .storage
606 .get_mfa_challenge(challenge_id)
607 .await?
608 .ok_or_else(|| AuthError::validation("MFA challenge not found"))?;
609
610 if SystemTime::now() > challenge.expires_at {
612 self.storage.delete_mfa_challenge(challenge_id).await?;
613 return Ok(MfaVerificationResult {
614 success: false,
615 method_type: challenge.method_type,
616 remaining_attempts: None,
617 error_message: Some("Challenge has expired".to_string()),
618 });
619 }
620
621 if challenge.attempts >= challenge.max_attempts {
623 self.storage.delete_mfa_challenge(challenge_id).await?;
624 return Ok(MfaVerificationResult {
625 success: false,
626 method_type: challenge.method_type,
627 remaining_attempts: Some(0),
628 error_message: Some("Maximum attempts exceeded".to_string()),
629 });
630 }
631
632 challenge.attempts += 1;
633
634 let success = match &challenge.challenge_data {
635 MfaChallengeData::Totp { time_window } => {
636 let user_methods = self
637 .storage
638 .get_user_mfa_methods(&challenge.user_id)
639 .await?;
640 if let Some(method) = user_methods
641 .iter()
642 .find(|m| m.method_type == MfaMethodType::Totp)
643 {
644 if let MfaMethodData::Totp { secret_key, .. } = &method.method_data {
645 self.totp_provider
646 .verify_code(secret_key, response, Some(*time_window))?
647 } else {
648 false
649 }
650 } else {
651 false
652 }
653 }
654 MfaChallengeData::Sms { code, .. } => code.as_bytes().ct_eq(response.as_bytes()).into(),
655 MfaChallengeData::Email { code, .. } => {
656 code.as_bytes().ct_eq(response.as_bytes()).into()
657 }
658 MfaChallengeData::BackupCodes { .. } => {
659 let user_methods = self
660 .storage
661 .get_user_mfa_methods(&challenge.user_id)
662 .await?;
663 if let Some(method) = user_methods
664 .iter()
665 .find(|m| m.method_type == MfaMethodType::BackupCodes)
666 {
667 if let MfaMethodData::BackupCodes { codes, .. } = &method.method_data {
668 BackupCodesProvider::verify_code(codes, response)
669 } else {
670 false
671 }
672 } else {
673 false
674 }
675 }
676 _ => false,
677 };
678
679 if success {
680 self.storage.delete_mfa_challenge(challenge_id).await?;
681 Ok(MfaVerificationResult {
682 success: true,
683 method_type: challenge.method_type,
684 remaining_attempts: None,
685 error_message: None,
686 })
687 } else {
688 let remaining = challenge.max_attempts.saturating_sub(challenge.attempts);
689 self.storage.update_mfa_challenge(&challenge).await?;
690
691 Ok(MfaVerificationResult {
692 success: false,
693 method_type: challenge.method_type,
694 remaining_attempts: Some(remaining),
695 error_message: Some("Invalid code".to_string()),
696 })
697 }
698 }
699
700 pub async fn has_mfa_enabled(&self, user_id: &str) -> Result<bool> {
702 let methods = self.storage.get_user_mfa_methods(user_id).await?;
703 Ok(methods.iter().any(|m| m.is_enabled))
704 }
705
706 pub async fn get_enabled_methods(&self, user_id: &str) -> Result<Vec<MfaMethodType>> {
708 let methods = self.storage.get_user_mfa_methods(user_id).await?;
709 Ok(methods
710 .iter()
711 .filter(|m| m.is_enabled)
712 .map(|m| m.method_type.clone())
713 .collect())
714 }
715}
716
717fn generate_numeric_code(length: u8) -> String {
719 let rng = ring::rand::SystemRandom::new();
720 (0..length)
721 .map(|_| {
722 let mut buf = [0u8; 1];
723 rng.fill(&mut buf).expect("system RNG failure");
724 (buf[0] % 10).to_string()
725 })
726 .collect()
727}
728
729fn mask_phone_number(phone: &str) -> String {
731 if phone.len() > 4 {
732 format!("***-***-{}", &phone[phone.len() - 4..])
733 } else {
734 "***-***-****".to_string()
735 }
736}
737
738fn mask_email(email: &str) -> String {
740 if let Some(at_pos) = email.find('@') {
741 let (local, domain) = email.split_at(at_pos);
742 if local.len() > 2 {
743 format!("{}***{}", &local[0..1], domain)
744 } else {
745 format!("***{}", domain)
746 }
747 } else {
748 "***@***.***".to_string()
749 }
750}
751
752#[cfg(test)]
753mod tests {
754 use super::*;
755
756 #[test]
757 fn test_totp_generation() {
758 let config = crate::security::TotpConfig::default();
759 let provider = TotpProvider::new(config);
760
761 let secret = provider.generate_secret().unwrap();
762 assert!(!secret.is_empty());
763
764 let code = provider.generate_code(&secret, Some(1)).unwrap();
765 assert_eq!(code.len(), 6);
766
767 assert!(provider.verify_code(&secret, &code, Some(1)).unwrap());
769
770 assert!(!provider.verify_code(&secret, "000000", Some(1)).unwrap());
772 }
773
774 #[test]
775 fn test_backup_codes() {
776 let codes = BackupCodesProvider::generate_codes(5);
777 assert_eq!(codes.len(), 5);
778
779 let hashed = BackupCodesProvider::hash_codes(&codes).unwrap();
780 assert_eq!(hashed.len(), 5);
781
782 assert!(BackupCodesProvider::verify_code(&hashed, &codes[0]));
784
785 assert!(!BackupCodesProvider::verify_code(&hashed, "1234-5678"));
787 }
788
789 #[test]
790 fn test_masking() {
791 assert_eq!(mask_phone_number("+1234567890"), "***-***-7890");
792 assert_eq!(mask_email("user@example.com"), "u***@example.com");
793 }
794}