1pub mod backup_codes;
4pub mod email;
5pub mod sms_kit;
6pub mod totp;
7
8use crate::errors::Result;
9use crate::methods::MfaChallenge;
10use crate::storage::AuthStorage;
11use std::collections::HashMap;
12use std::sync::Arc;
13use tokio::sync::RwLock;
14use tracing::debug;
15
16pub use backup_codes::BackupCodesManager;
17pub use email::EmailManager;
18pub use totp::TotpManager;
19
20pub use sms_kit::{
22 RateLimitConfig as SmsKitRateLimitConfig, SmsKitConfig, SmsKitManager, SmsKitProvider,
23 SmsKitProviderConfig, WebhookConfig,
24};
25
26pub use sms_kit::SmsKitManager as SmsManager;
28
29pub struct MfaManager {
95 pub totp: TotpManager,
97
98 pub sms: SmsKitManager,
100
101 pub email: EmailManager,
103
104 pub backup_codes: BackupCodesManager,
106
107 challenges: Arc<RwLock<HashMap<String, MfaChallenge>>>,
109
110 storage: Arc<dyn AuthStorage>,
113}
114
115impl MfaManager {
116 pub fn new(storage: Arc<dyn AuthStorage>) -> Self {
118 Self {
119 totp: TotpManager::new(storage.clone()),
120 sms: SmsKitManager::new(storage.clone()),
121 email: EmailManager::new(storage.clone()),
122 backup_codes: BackupCodesManager::new(storage.clone()),
123 challenges: Arc::new(RwLock::new(HashMap::new())),
124 storage,
125 }
126 }
127
128 pub fn new_with_smskit_config(
130 storage: Arc<dyn AuthStorage>,
131 smskit_config: SmsKitConfig,
132 ) -> Result<Self> {
133 Ok(Self {
134 totp: TotpManager::new(storage.clone()),
135 sms: SmsKitManager::new_with_config(storage.clone(), smskit_config)?,
136 email: EmailManager::new(storage.clone()),
137 backup_codes: BackupCodesManager::new(storage.clone()),
138 challenges: Arc::new(RwLock::new(HashMap::new())),
139 storage,
140 })
141 }
142
143 pub async fn store_challenge(&self, challenge: MfaChallenge) -> Result<()> {
145 debug!("Storing MFA challenge '{}'", challenge.id);
146
147 let mut challenges = self.challenges.write().await;
148 challenges.insert(challenge.id.clone(), challenge);
149
150 Ok(())
151 }
152
153 pub async fn get_challenge(&self, challenge_id: &str) -> Result<Option<MfaChallenge>> {
155 let challenges = self.challenges.read().await;
156 Ok(challenges.get(challenge_id).cloned())
157 }
158
159 pub async fn remove_challenge(&self, challenge_id: &str) -> Result<()> {
161 debug!("Removing MFA challenge '{}'", challenge_id);
162
163 let mut challenges = self.challenges.write().await;
164 challenges.remove(challenge_id);
165
166 Ok(())
167 }
168
169 pub async fn cleanup_expired_challenges(&self) -> Result<()> {
171 debug!("Cleaning up expired MFA challenges");
172
173 let mut challenges = self.challenges.write().await;
174 let now = chrono::Utc::now();
175 challenges.retain(|_, challenge| challenge.expires_at > now);
176
177 Ok(())
178 }
179
180 pub async fn get_active_challenge_count(&self) -> usize {
182 self.challenges.read().await.len()
183 }
184
185 pub async fn initiate_step_up_authentication(
187 &self,
188 user_id: &str,
189 required_methods: &[MfaMethod],
190 risk_level: RiskLevel,
191 ) -> Result<CrossMethodChallenge> {
192 tracing::info!(
193 "Initiating step-up authentication for user: {} with risk level: {:?}",
194 user_id,
195 risk_level
196 );
197
198 let adaptive_methods = self
200 .adapt_required_methods(required_methods, risk_level.clone())
201 .await?;
202
203 let challenge_id = uuid::Uuid::new_v4().to_string();
205
206 let mut method_challenges = HashMap::new();
208 let mut completion_status = HashMap::new();
209
210 for method in &adaptive_methods {
211 let method_challenge = match method {
212 MfaMethod::Totp => {
213 completion_status.insert(method.clone(), false);
214 self.create_totp_challenge(user_id, &challenge_id).await?
215 }
216 MfaMethod::Sms => {
217 completion_status.insert(method.clone(), false);
218 self.create_sms_challenge(user_id, &challenge_id).await?
219 }
220 MfaMethod::Email => {
221 completion_status.insert(method.clone(), false);
222 self.create_email_challenge(user_id, &challenge_id).await?
223 }
224 MfaMethod::BackupCode => {
225 completion_status.insert(method.clone(), false);
226 MethodChallenge::BackupCode {
227 challenge_id: format!("{}-backup", challenge_id),
228 instructions: "Enter one of your backup codes".to_string(),
229 }
230 }
231 };
232
233 method_challenges.insert(method.clone(), method_challenge);
234 }
235
236 let cross_method_challenge = CrossMethodChallenge {
237 id: challenge_id,
238 user_id: user_id.to_string(),
239 required_methods: adaptive_methods.clone(),
240 method_challenges,
241 completion_status,
242 risk_level,
243 expires_at: chrono::Utc::now() + chrono::Duration::minutes(10),
244 created_at: chrono::Utc::now(),
245 };
246
247 {
249 let mut challenges = self.challenges.write().await;
250 challenges.insert(
251 cross_method_challenge.id.clone(),
252 MfaChallenge {
253 id: cross_method_challenge.id.clone(),
254 mfa_type: crate::methods::MfaType::Totp, user_id: user_id.to_string(),
256 expires_at: cross_method_challenge.expires_at,
257 message: Some("Complete all required authentication methods".to_string()),
258 data: {
259 let mut data = HashMap::new();
260 data.insert(
261 "cross_method_data".to_string(),
262 serde_json::to_value(&cross_method_challenge)?,
263 );
264 data
265 },
266 },
267 );
268 }
269
270 tracing::info!(
271 "Step-up authentication initiated with {} methods",
272 adaptive_methods.len()
273 );
274 Ok(cross_method_challenge)
275 }
276
277 pub async fn complete_cross_method_step(
279 &self,
280 challenge_id: &str,
281 method: MfaMethod,
282 response: &str,
283 ) -> Result<CrossMethodCompletionResult> {
284 tracing::debug!(
285 "Completing cross-method step: {:?} for challenge: {}",
286 method,
287 challenge_id
288 );
289
290 let mut cross_challenge = self.get_cross_method_challenge(challenge_id).await?;
292
293 if cross_challenge.completion_status.get(&method) == Some(&true) {
294 return Ok(CrossMethodCompletionResult {
295 method,
296 success: true,
297 remaining_methods: self.get_remaining_methods(&cross_challenge),
298 all_completed: false,
299 error: Some("Method already completed".to_string()),
300 });
301 }
302
303 let verification_result = match method {
305 MfaMethod::Totp => {
306 self.totp
307 .verify_code(&cross_challenge.user_id, response)
308 .await
309 }
310 MfaMethod::Sms => {
311 self.sms
312 .verify_code(&cross_challenge.user_id, response)
313 .await
314 }
315 MfaMethod::Email => {
316 self.email
317 .verify_code(&cross_challenge.user_id, response)
318 .await
319 }
320 MfaMethod::BackupCode => {
321 self.backup_codes
322 .verify_code(&cross_challenge.user_id, response)
323 .await
324 }
325 };
326
327 let success = matches!(verification_result, Ok(true));
329
330 if success {
331 cross_challenge
333 .completion_status
334 .insert(method.clone(), true);
335
336 self.update_cross_method_challenge(&cross_challenge).await?;
338
339 tracing::info!("Cross-method step completed successfully: {:?}", method);
340 } else {
341 tracing::warn!(
342 "Cross-method step failed: {:?} - {:?}",
343 method,
344 verification_result
345 );
346 }
347
348 let remaining_methods = self.get_remaining_methods(&cross_challenge);
349 let all_completed = remaining_methods.is_empty();
350
351 if all_completed {
352 tracing::info!(
353 "All cross-method authentication steps completed for challenge: {}",
354 challenge_id
355 );
356 self.remove_challenge(challenge_id).await?;
358 }
359
360 Ok(CrossMethodCompletionResult {
361 method,
362 success,
363 remaining_methods,
364 all_completed,
365 error: if success {
366 None
367 } else {
368 Some(match &verification_result {
369 Ok(_) => "Verification failed: invalid code".to_string(),
370 Err(e) => format!("Verification failed: {:?}", e),
371 })
372 },
373 })
374 }
375
376 pub async fn get_available_methods(&self, user_id: &str) -> Result<Vec<MfaMethod>> {
378 tracing::debug!("Getting available MFA methods for user: {}", user_id);
379
380 let mut available_methods = Vec::new();
381
382 if self.totp.has_totp_secret(user_id).await.unwrap_or(false) {
384 available_methods.push(MfaMethod::Totp);
385 }
386
387 if self.sms.has_phone_number(user_id).await.unwrap_or(false) {
389 available_methods.push(MfaMethod::Sms);
390 }
391
392 if self.email.has_email(user_id).await.unwrap_or(false) {
394 available_methods.push(MfaMethod::Email);
395 }
396
397 if self
399 .backup_codes
400 .has_backup_codes(user_id)
401 .await
402 .unwrap_or(false)
403 {
404 available_methods.push(MfaMethod::BackupCode);
405 }
406
407 tracing::debug!(
408 "Available methods for user {}: {:?}",
409 user_id,
410 available_methods
411 );
412 Ok(available_methods)
413 }
414
415 pub async fn perform_method_fallback(
417 &self,
418 user_id: &str,
419 failed_method: MfaMethod,
420 fallback_order: &[MfaMethod],
421 ) -> Result<MethodFallbackResult> {
422 tracing::info!(
423 "Performing method fallback for user: {} after failed method: {:?}",
424 user_id,
425 failed_method
426 );
427
428 let available_methods = self.get_available_methods(user_id).await?;
429
430 for fallback_method in fallback_order {
432 if available_methods.contains(fallback_method) && fallback_method != &failed_method {
433 let fallback_challenge = match fallback_method {
435 MfaMethod::Totp => self.create_totp_challenge(user_id, "fallback").await?,
436 MfaMethod::Sms => self.create_sms_challenge(user_id, "fallback").await?,
437 MfaMethod::Email => self.create_email_challenge(user_id, "fallback").await?,
438 MfaMethod::BackupCode => MethodChallenge::BackupCode {
439 challenge_id: "fallback-backup".to_string(),
440 instructions: "Enter one of your backup codes".to_string(),
441 },
442 };
443
444 tracing::info!(
445 "Fallback method activated: {:?} for user: {}",
446 fallback_method,
447 user_id
448 );
449
450 return Ok(MethodFallbackResult {
451 fallback_method: fallback_method.clone(),
452 challenge: fallback_challenge,
453 remaining_fallbacks: fallback_order
454 .iter()
455 .skip_while(|&m| m != fallback_method)
456 .skip(1)
457 .filter(|&m| available_methods.contains(m))
458 .cloned()
459 .collect(),
460 });
461 }
462 }
463
464 Err(crate::errors::AuthError::validation(
465 "No fallback methods available",
466 ))
467 }
468
469 async fn adapt_required_methods(
471 &self,
472 base_methods: &[MfaMethod],
473 risk_level: RiskLevel,
474 ) -> Result<Vec<MfaMethod>> {
475 let mut adapted_methods = base_methods.to_vec();
476
477 match risk_level {
478 RiskLevel::Low => {
479 adapted_methods.truncate(1);
481 }
482 RiskLevel::Medium => {
483 }
486 RiskLevel::High => {
487 if !adapted_methods.contains(&MfaMethod::Email) {
489 adapted_methods.push(MfaMethod::Email);
490 }
491 if !adapted_methods.contains(&MfaMethod::Sms) {
492 adapted_methods.push(MfaMethod::Sms);
493 }
494 }
495 RiskLevel::Critical => {
496 adapted_methods = vec![MfaMethod::Totp, MfaMethod::Sms, MfaMethod::Email];
498 }
499 }
500
501 Ok(adapted_methods)
502 }
503
504 async fn get_cross_method_challenge(&self, challenge_id: &str) -> Result<CrossMethodChallenge> {
506 let challenges = self.challenges.read().await;
507 let challenge = challenges
508 .get(challenge_id)
509 .ok_or_else(|| crate::errors::AuthError::validation("Challenge not found"))?;
510
511 let cross_challenge: CrossMethodChallenge =
512 if let Some(cross_method_value) = challenge.data.get("cross_method_data") {
513 serde_json::from_value(cross_method_value.clone())?
514 } else {
515 return Err(crate::errors::AuthError::validation(
516 "Invalid cross-method challenge data",
517 ));
518 };
519 Ok(cross_challenge)
520 }
521
522 async fn update_cross_method_challenge(
523 &self,
524 cross_challenge: &CrossMethodChallenge,
525 ) -> Result<()> {
526 let mut challenges = self.challenges.write().await;
527 if let Some(challenge) = challenges.get_mut(&cross_challenge.id) {
528 challenge.data.insert(
529 "cross_method_data".to_string(),
530 serde_json::to_value(cross_challenge)?,
531 );
532 }
533 Ok(())
534 }
535
536 fn get_remaining_methods(&self, cross_challenge: &CrossMethodChallenge) -> Vec<MfaMethod> {
537 cross_challenge
538 .completion_status
539 .iter()
540 .filter_map(|(method, &completed)| {
541 if !completed {
542 Some(method.clone())
543 } else {
544 None
545 }
546 })
547 .collect()
548 }
549
550 async fn create_totp_challenge(
552 &self,
553 _user_id: &str,
554 challenge_prefix: &str,
555 ) -> Result<MethodChallenge> {
556 Ok(MethodChallenge::Totp {
557 challenge_id: format!("{}-totp", challenge_prefix),
558 instructions: "Enter the 6-digit code from your authenticator app".to_string(),
559 })
560 }
561
562 async fn create_sms_challenge(
563 &self,
564 user_id: &str,
565 challenge_prefix: &str,
566 ) -> Result<MethodChallenge> {
567 let _code = self.sms.send_verification_code(user_id).await?;
568 Ok(MethodChallenge::Sms {
569 challenge_id: format!("{}-sms", challenge_prefix),
570 instructions: "Enter the verification code sent to your phone".to_string(),
571 phone_hint: self
572 .get_phone_hint(user_id)
573 .await
574 .unwrap_or_else(|_| "***-***-****".to_string()),
575 })
576 }
577
578 async fn create_email_challenge(
579 &self,
580 user_id: &str,
581 challenge_prefix: &str,
582 ) -> Result<MethodChallenge> {
583 let _code = self.email.send_email_code(user_id).await?;
584 Ok(MethodChallenge::Email {
585 challenge_id: format!("{}-email", challenge_prefix),
586 instructions: "Enter the verification code sent to your email".to_string(),
587 email_hint: self
588 .get_email_hint(user_id)
589 .await
590 .unwrap_or_else(|_| "****@****.com".to_string()),
591 })
592 }
593
594 async fn get_phone_hint(&self, user_id: &str) -> Result<String> {
595 Ok(format!("***-***-{}", &user_id[..4]))
597 }
598
599 async fn get_email_hint(&self, user_id: &str) -> Result<String> {
600 Ok(format!("{}****@****.com", &user_id[..2]))
602 }
603
604 pub async fn emergency_mfa_bypass(&self, user_id: &str, admin_token: &str) -> Result<bool> {
607 tracing::warn!("Emergency MFA bypass requested for user: {}", user_id);
608
609 let admin_key = format!("emergency_admin:{}", admin_token);
611 if let Some(_admin_data) = self.storage.get_kv(&admin_key).await? {
612 tracing::info!("Emergency MFA bypass granted for user: {}", user_id);
613
614 let bypass_key = format!("mfa_bypass:{}:{}", user_id, chrono::Utc::now().timestamp());
616 let bypass_data = format!(
617 "Emergency bypass by admin token at {}",
618 chrono::Utc::now().to_rfc3339()
619 );
620 self.storage
621 .store_kv(
622 &bypass_key,
623 bypass_data.as_bytes(),
624 Some(std::time::Duration::from_secs(86400)),
625 )
626 .await?;
627
628 Ok(true)
629 } else {
630 tracing::error!("Invalid admin token for emergency MFA bypass");
631 Ok(false)
632 }
633 }
634}
635
636#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
638pub enum MfaMethod {
639 Totp,
640 Sms,
641 Email,
642 BackupCode,
643}
644
645#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
647pub enum RiskLevel {
648 Low,
649 Medium,
650 High,
651 Critical,
652}
653
654#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
656pub struct CrossMethodChallenge {
657 pub id: String,
658 pub user_id: String,
659 pub required_methods: Vec<MfaMethod>,
660 pub method_challenges: HashMap<MfaMethod, MethodChallenge>,
661 pub completion_status: HashMap<MfaMethod, bool>,
662 pub risk_level: RiskLevel,
663 pub expires_at: chrono::DateTime<chrono::Utc>,
664 pub created_at: chrono::DateTime<chrono::Utc>,
665}
666
667#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
669pub enum MethodChallenge {
670 Totp {
671 challenge_id: String,
672 instructions: String,
673 },
674 Sms {
675 challenge_id: String,
676 instructions: String,
677 phone_hint: String,
678 },
679 Email {
680 challenge_id: String,
681 instructions: String,
682 email_hint: String,
683 },
684 BackupCode {
685 challenge_id: String,
686 instructions: String,
687 },
688}
689
690#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
692pub struct CrossMethodCompletionResult {
693 pub method: MfaMethod,
694 pub success: bool,
695 pub remaining_methods: Vec<MfaMethod>,
696 pub all_completed: bool,
697 pub error: Option<String>,
698}
699
700#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
702pub struct MethodFallbackResult {
703 pub fallback_method: MfaMethod,
704 pub challenge: MethodChallenge,
705 pub remaining_fallbacks: Vec<MfaMethod>,
706}
707
708#[cfg(test)]
709mod tests {
710 use super::*;
711 use crate::storage::MemoryStorage;
712
713 fn make_mfa() -> MfaManager {
714 let storage: Arc<dyn AuthStorage> = Arc::new(MemoryStorage::new());
715 MfaManager::new(storage)
716 }
717
718 #[tokio::test]
719 async fn test_cross_method_step_rejects_invalid_code() {
720 let mfa = make_mfa();
721 let _secret = mfa.totp.generate_secret("bypass_user").await.unwrap();
722 let cross = mfa
723 .initiate_step_up_authentication("bypass_user", &[MfaMethod::Totp], RiskLevel::Medium)
724 .await
725 .unwrap();
726 let res = mfa
727 .complete_cross_method_step(&cross.id, MfaMethod::Totp, "garbage")
728 .await
729 .unwrap();
730 assert!(
731 !res.success,
732 "an invalid TOTP code must NOT complete a step-up MFA step (success={})",
733 res.success
734 );
735 }
736
737 #[tokio::test]
738 async fn test_cross_method_step_accepts_valid_code() {
739 let storage: Arc<dyn AuthStorage> = Arc::new(MemoryStorage::new());
740 let mfa = MfaManager::new(storage.clone());
741 let secret = "JBSWY3DPEHPK3PXP".to_string();
742 storage
743 .store_kv("user:ok_user:totp_secret", secret.as_bytes(), None)
744 .await
745 .unwrap();
746 let cross = mfa
747 .initiate_step_up_authentication("ok_user", &[MfaMethod::Totp], RiskLevel::Medium)
748 .await
749 .unwrap();
750 let code = mfa.totp.generate_code(&secret).await.unwrap();
751 let res = mfa
752 .complete_cross_method_step(&cross.id, MfaMethod::Totp, &code)
753 .await
754 .unwrap();
755 assert!(res.success, "a valid TOTP code must complete the step (error={:?})", res.error);
756 }
757
758 #[tokio::test]
764 async fn test_generate_secret_output_round_trips_through_generate_and_verify_code() {
765 let mfa = make_mfa();
766 let secret = mfa.totp.generate_secret("roundtrip_user").await.unwrap();
767 let code = mfa
768 .totp
769 .generate_code(&secret)
770 .await
771 .expect("generate_secret's own output must be accepted by generate_code");
772 let verified = mfa.totp.verify_code("roundtrip_user", &code).await.unwrap();
773 assert!(
774 verified,
775 "a code generated from generate_secret's own output must verify successfully"
776 );
777 }
778}