Skip to main content

auth_framework/auth_modular/mfa/
mod.rs

1//! Multi-Factor Authentication management module.
2
3pub 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 base64::Engine as _;
12use hmac::{Hmac, Mac};
13use sha2::Sha256;
14use std::collections::HashMap;
15use std::sync::Arc;
16use std::time::Duration;
17use tokio::sync::RwLock;
18use tracing::debug;
19
20type EmergencyBypassHmac = Hmac<Sha256>;
21
22#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
23struct EmergencyBypassClaims {
24    admin_user_id: String,
25    target_user_id: String,
26    iat: i64,
27    exp: i64,
28    jti: String,
29}
30
31pub use backup_codes::BackupCodesManager;
32pub use email::EmailManager;
33pub use totp::TotpManager;
34
35// Export SMSKit manager as the primary SMS interface
36pub use sms_kit::{
37    RateLimitConfig as SmsKitRateLimitConfig, SmsKitConfig, SmsKitManager, SmsKitProvider,
38    SmsKitProviderConfig, WebhookConfig,
39};
40
41// Re-export as SmsManager for backward compatibility
42pub use sms_kit::SmsKitManager as SmsManager;
43
44/// Centralized multi-factor authentication (MFA) manager.
45///
46/// `MfaManager` coordinates all MFA operations across different authentication
47/// factors including TOTP, SMS, email, and backup codes. It provides a unified
48/// interface for MFA setup, challenge generation, and verification while
49/// supporting multiple MFA methods simultaneously.
50///
51/// # Supported MFA Methods
52///
53/// - **TOTP (Time-based OTP)**: RFC 6238 compliant authenticator apps
54/// - **SMS**: Text message-based verification codes
55/// - **Email**: Email-based verification codes
56/// - **Backup Codes**: Single-use recovery codes
57///
58/// # Multi-Method Support
59///
60/// Users can enable multiple MFA methods simultaneously, providing flexibility
61/// and redundancy. The manager handles method coordination and fallback scenarios.
62///
63/// # Security Features
64///
65/// - **Challenge Expiration**: Time-limited challenges prevent replay attacks
66/// - **Rate Limiting**: Prevents brute force attacks on MFA codes
67/// - **Secure Code Generation**: Cryptographically secure random code generation
68/// - **Method Validation**: Validates MFA setup before enabling
69/// - **Audit Logging**: Comprehensive logging of all MFA operations
70///
71/// # Cross-Method Operations
72///
73/// The manager supports advanced scenarios like:
74/// - Method fallback when primary method fails
75/// - Cross-method challenge validation
76/// - Method strength assessment
77/// - Risk-based MFA requirements
78///
79/// # Example
80///
81/// ```rust,no_run
82/// use auth_framework::auth_modular::mfa::MfaManager;
83/// use std::sync::Arc;
84///
85/// # #[tokio::main]
86/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
87/// # let storage: Arc<dyn auth_framework::storage::AuthStorage> = unimplemented!();
88/// // Create MFA manager with storage backend
89/// let mfa_manager = MfaManager::new(storage);
90///
91/// // Generate a TOTP secret for a user (store it and show QR code to the user)
92/// let secret = mfa_manager.totp.generate_secret("user123").await?;
93///
94/// // Verify a TOTP code during an authentication attempt
95/// let is_valid = mfa_manager.totp.verify_code("user123", "123456").await?;
96/// # Ok(())
97/// # }
98/// ```
99///
100/// # Thread Safety
101///
102/// The MFA manager is designed for concurrent use and safely coordinates
103/// access to underlying MFA method implementations.
104///
105/// # Storage Integration
106///
107/// Integrates with the framework's storage system to persist:
108/// - User MFA method configurations
109/// - Active challenges
110/// - Usage statistics and audit logs
111/// - Backup codes and secrets
112pub struct MfaManager {
113    /// TOTP manager
114    pub totp: TotpManager,
115
116    /// SMS manager (using SMSKit)
117    pub sms: SmsKitManager,
118
119    /// Email manager
120    pub email: EmailManager,
121
122    /// Backup codes manager
123    pub backup_codes: BackupCodesManager,
124
125    /// Active MFA challenges
126    challenges: Arc<RwLock<HashMap<String, MfaChallenge>>>,
127
128    /// Storage backend for direct manager operations and fallback scenarios
129    storage: Arc<dyn AuthStorage>,
130}
131
132impl MfaManager {
133    /// Create a new MFA manager
134    pub fn new(storage: Arc<dyn AuthStorage>) -> Self {
135        Self {
136            totp: TotpManager::new(storage.clone()),
137            sms: SmsKitManager::new(storage.clone()),
138            email: EmailManager::new(storage.clone()),
139            backup_codes: BackupCodesManager::new(storage.clone()),
140            challenges: Arc::new(RwLock::new(HashMap::new())),
141            storage,
142        }
143    }
144
145    /// Create a new MFA manager with SMSKit configuration
146    pub fn new_with_smskit_config(
147        storage: Arc<dyn AuthStorage>,
148        smskit_config: SmsKitConfig,
149    ) -> Result<Self> {
150        Ok(Self {
151            totp: TotpManager::new(storage.clone()),
152            sms: SmsKitManager::new_with_config(storage.clone(), smskit_config)?,
153            email: EmailManager::new(storage.clone()),
154            backup_codes: BackupCodesManager::new(storage.clone()),
155            challenges: Arc::new(RwLock::new(HashMap::new())),
156            storage,
157        })
158    }
159
160    /// Store an MFA challenge
161    pub async fn store_challenge(&self, challenge: MfaChallenge) -> Result<()> {
162        debug!("Storing MFA challenge '{}'", challenge.id);
163
164        let mut challenges = self.challenges.write().await;
165        challenges.insert(challenge.id.clone(), challenge);
166
167        Ok(())
168    }
169
170    /// Guard the global challenge budget and store the challenge.
171    ///
172    /// Returns an error if more than 10 000 challenges are pending; otherwise
173    /// delegates to [`Self::store_challenge`].
174    pub async fn guard_and_store(&self, challenge: MfaChallenge) -> Result<()> {
175        const MAX_TOTAL_CHALLENGES: usize = 10_000;
176        if self.get_active_challenge_count().await >= MAX_TOTAL_CHALLENGES {
177            tracing::warn!("Maximum MFA challenges ({}) exceeded", MAX_TOTAL_CHALLENGES);
178            return Err(crate::errors::AuthError::rate_limit(
179                "Too many pending MFA challenges. Please try again later.",
180            ));
181        }
182        self.store_challenge(challenge).await
183    }
184
185    /// Get an MFA challenge
186    pub async fn get_challenge(&self, challenge_id: &str) -> Result<Option<MfaChallenge>> {
187        let challenges = self.challenges.read().await;
188        Ok(challenges.get(challenge_id).cloned())
189    }
190
191    /// Remove an MFA challenge
192    pub async fn remove_challenge(&self, challenge_id: &str) -> Result<()> {
193        debug!("Removing MFA challenge '{}'", challenge_id);
194
195        let mut challenges = self.challenges.write().await;
196        challenges.remove(challenge_id);
197
198        Ok(())
199    }
200
201    /// Clean up expired challenges
202    pub async fn cleanup_expired_challenges(&self) -> Result<()> {
203        debug!("Cleaning up expired MFA challenges");
204
205        let mut challenges = self.challenges.write().await;
206        let now = chrono::Utc::now();
207        challenges.retain(|_, challenge| challenge.expires_at > now);
208
209        Ok(())
210    }
211
212    /// Get count of active challenges
213    pub async fn get_active_challenge_count(&self) -> usize {
214        self.challenges.read().await.len()
215    }
216
217    /// Verify a code against the given MFA challenge, dispatching to the appropriate sub-manager.
218    pub async fn verify_challenge_code(
219        &self,
220        challenge: &crate::methods::MfaChallenge,
221        code: &str,
222    ) -> Result<bool> {
223        use crate::security::secure_utils::constant_time_compare;
224
225        if challenge.is_expired() {
226            return Ok(false);
227        }
228
229        match &challenge.mfa_type {
230            crate::methods::MfaType::Totp => {
231                self.totp.verify_login_code(&challenge.user_id, code).await
232            }
233            crate::methods::MfaType::Sms { .. } => {
234                if code.len() != 6 || !code.chars().all(|c| c.is_ascii_digit()) {
235                    return Ok(false);
236                }
237                let sms_key = format!("smskit_challenge:{}:code", challenge.id);
238                match self.storage.get_kv(&sms_key).await? {
239                    Some(stored) => {
240                        let stored_code = std::str::from_utf8(&stored).unwrap_or("");
241                        Ok(constant_time_compare(
242                            stored_code.as_bytes(),
243                            code.as_bytes(),
244                        ))
245                    }
246                    None => Ok(false),
247                }
248            }
249            crate::methods::MfaType::Email { .. } => {
250                if code.len() != 6 || !code.chars().all(|c| c.is_ascii_digit()) {
251                    return Ok(false);
252                }
253                let email_key = format!("email_challenge:{}:code", challenge.id);
254                match self.storage.get_kv(&email_key).await? {
255                    Some(stored) => {
256                        let stored_code = std::str::from_utf8(&stored).unwrap_or("");
257                        Ok(constant_time_compare(
258                            stored_code.as_bytes(),
259                            code.as_bytes(),
260                        ))
261                    }
262                    None => Ok(false),
263                }
264            }
265            crate::methods::MfaType::BackupCode => {
266                self.backup_codes
267                    .verify_login_code(&challenge.user_id, code)
268                    .await
269            }
270            crate::methods::MfaType::MultiMethod => {
271                if self
272                    .totp
273                    .verify_login_code(&challenge.user_id, code)
274                    .await?
275                {
276                    return Ok(true);
277                }
278                self.backup_codes
279                    .verify_login_code(&challenge.user_id, code)
280                    .await
281            }
282            _ => Ok(false),
283        }
284    }
285
286    /// MFA CROSS-METHOD OPERATIONS: Step-up authentication with multiple factors
287    pub async fn initiate_step_up_authentication(
288        &self,
289        user_id: &str,
290        required_methods: &[MfaMethod],
291        risk_level: RiskLevel,
292    ) -> Result<CrossMethodChallenge> {
293        tracing::info!(
294            "Initiating step-up authentication for user: {} with risk level: {:?}",
295            user_id,
296            risk_level
297        );
298
299        // Determine required methods based on risk level
300        let adaptive_methods = self
301            .adapt_required_methods(required_methods, risk_level.clone())
302            .await?;
303
304        // Generate challenge ID
305        let challenge_id = uuid::Uuid::new_v4().to_string();
306
307        // Create individual challenges for each method
308        let mut method_challenges = HashMap::new();
309        let mut completion_status = HashMap::new();
310
311        for method in &adaptive_methods {
312            let method_challenge = match method {
313                MfaMethod::Totp => {
314                    completion_status.insert(method.clone(), false);
315                    self.create_totp_challenge(user_id, &challenge_id).await?
316                }
317                MfaMethod::Sms => {
318                    completion_status.insert(method.clone(), false);
319                    self.create_sms_challenge(user_id, &challenge_id).await?
320                }
321                MfaMethod::Email => {
322                    completion_status.insert(method.clone(), false);
323                    self.create_email_challenge(user_id, &challenge_id).await?
324                }
325                MfaMethod::BackupCode => {
326                    completion_status.insert(method.clone(), false);
327                    MethodChallenge::BackupCode {
328                        challenge_id: format!("{}-backup", challenge_id),
329                        instructions: "Enter one of your backup codes".to_string(),
330                    }
331                }
332            };
333
334            method_challenges.insert(method.clone(), method_challenge);
335        }
336
337        let cross_method_challenge = CrossMethodChallenge {
338            id: challenge_id,
339            user_id: user_id.to_string(),
340            required_methods: adaptive_methods.clone(),
341            method_challenges,
342            completion_status,
343            risk_level,
344            expires_at: chrono::Utc::now() + chrono::Duration::minutes(10),
345            created_at: chrono::Utc::now(),
346        };
347
348        // Store the cross-method challenge
349        {
350            let mut challenges = self.challenges.write().await;
351            challenges.insert(
352                cross_method_challenge.id.clone(),
353                MfaChallenge {
354                    id: cross_method_challenge.id.clone(),
355                    mfa_type: crate::methods::MfaType::MultiMethod,
356                    user_id: user_id.to_string(),
357                    expires_at: cross_method_challenge.expires_at,
358                    created_at: chrono::Utc::now(),
359                    attempts: 0,
360                    max_attempts: 3,
361                    code_hash: None,
362                    message: Some("Complete all required authentication methods".to_string()),
363                    data: {
364                        let mut data = HashMap::new();
365                        data.insert(
366                            "cross_method_data".to_string(),
367                            serde_json::to_value(&cross_method_challenge)?,
368                        );
369                        data
370                    },
371                },
372            );
373        }
374
375        tracing::info!(
376            "Step-up authentication initiated with {} methods",
377            adaptive_methods.len()
378        );
379        Ok(cross_method_challenge)
380    }
381
382    /// Complete a specific method within a cross-method challenge
383    pub async fn complete_cross_method_step(
384        &self,
385        challenge_id: &str,
386        method: MfaMethod,
387        response: &str,
388    ) -> Result<CrossMethodCompletionResult> {
389        tracing::debug!(
390            "Completing cross-method step: {:?} for challenge: {}",
391            method,
392            challenge_id
393        );
394
395        // Retrieve and update the cross-method challenge
396        let mut cross_challenge = self.get_cross_method_challenge(challenge_id).await?;
397
398        if cross_challenge.completion_status.get(&method) == Some(&true) {
399            return Ok(CrossMethodCompletionResult {
400                method,
401                success: true,
402                remaining_methods: self.get_remaining_methods(&cross_challenge),
403                all_completed: false,
404                error: Some("Method already completed".to_string()),
405            });
406        }
407
408        // Verify the specific method response
409        let verification_result = match method {
410            MfaMethod::Totp => {
411                self.totp
412                    .verify_code(&cross_challenge.user_id, response)
413                    .await
414            }
415            MfaMethod::Sms => {
416                self.sms
417                    .verify_code(&cross_challenge.user_id, response)
418                    .await
419            }
420            MfaMethod::Email => {
421                self.email
422                    .verify_code(&cross_challenge.user_id, response)
423                    .await
424            }
425            MfaMethod::BackupCode => {
426                self.backup_codes
427                    .verify_code(&cross_challenge.user_id, response)
428                    .await
429            }
430        };
431
432        // `verify_code` returns Ok(false) for a wrong code, so `is_ok()` is NOT success.
433        let success = matches!(verification_result, Ok(true));
434
435        if success {
436            // Mark method as completed
437            cross_challenge
438                .completion_status
439                .insert(method.clone(), true);
440
441            // Update stored challenge
442            self.update_cross_method_challenge(&cross_challenge).await?;
443
444            tracing::info!("Cross-method step completed successfully: {:?}", method);
445        } else {
446            tracing::warn!(
447                "Cross-method step failed: {:?} - {:?}",
448                method,
449                verification_result
450            );
451        }
452
453        let remaining_methods = self.get_remaining_methods(&cross_challenge);
454        let all_completed = remaining_methods.is_empty();
455
456        if all_completed {
457            tracing::info!(
458                "All cross-method authentication steps completed for challenge: {}",
459                challenge_id
460            );
461            // Clean up the challenge
462            self.remove_challenge(challenge_id).await?;
463        }
464
465        Ok(CrossMethodCompletionResult {
466            method,
467            success,
468            remaining_methods,
469            all_completed,
470            error: if success {
471                None
472            } else {
473                Some(match &verification_result {
474                    Ok(_) => "Verification failed: invalid code".to_string(),
475                    Err(e) => format!("Verification failed: {:?}", e),
476                })
477            },
478        })
479    }
480
481    /// Get available MFA methods for a user
482    pub async fn get_available_methods(&self, user_id: &str) -> Result<Vec<MfaMethod>> {
483        tracing::debug!("Getting available MFA methods for user: {}", user_id);
484
485        let mut available_methods = Vec::new();
486
487        // Check TOTP availability
488        if self.totp.has_totp_secret(user_id).await.unwrap_or(false) {
489            available_methods.push(MfaMethod::Totp);
490        }
491
492        // Check SMS availability
493        if self.sms.has_phone_number(user_id).await.unwrap_or(false) {
494            available_methods.push(MfaMethod::Sms);
495        }
496
497        // Check email availability
498        if self.email.has_email(user_id).await.unwrap_or(false) {
499            available_methods.push(MfaMethod::Email);
500        }
501
502        // Check backup codes availability
503        if self
504            .backup_codes
505            .has_backup_codes(user_id)
506            .await
507            .unwrap_or(false)
508        {
509            available_methods.push(MfaMethod::BackupCode);
510        }
511
512        tracing::debug!(
513            "Available methods for user {}: {:?}",
514            user_id,
515            available_methods
516        );
517        Ok(available_methods)
518    }
519
520    /// Perform method fallback when primary method fails
521    pub async fn perform_method_fallback(
522        &self,
523        user_id: &str,
524        failed_method: MfaMethod,
525        fallback_order: &[MfaMethod],
526    ) -> Result<MethodFallbackResult> {
527        tracing::info!(
528            "Performing method fallback for user: {} after failed method: {:?}",
529            user_id,
530            failed_method
531        );
532
533        let available_methods = self.get_available_methods(user_id).await?;
534
535        // Find the first available fallback method
536        for fallback_method in fallback_order {
537            if available_methods.contains(fallback_method) && fallback_method != &failed_method {
538                // Create challenge for fallback method
539                let fallback_challenge = match fallback_method {
540                    MfaMethod::Totp => self.create_totp_challenge(user_id, "fallback").await?,
541                    MfaMethod::Sms => self.create_sms_challenge(user_id, "fallback").await?,
542                    MfaMethod::Email => self.create_email_challenge(user_id, "fallback").await?,
543                    MfaMethod::BackupCode => MethodChallenge::BackupCode {
544                        challenge_id: "fallback-backup".to_string(),
545                        instructions: "Enter one of your backup codes".to_string(),
546                    },
547                };
548
549                tracing::info!(
550                    "Fallback method activated: {:?} for user: {}",
551                    fallback_method,
552                    user_id
553                );
554
555                return Ok(MethodFallbackResult {
556                    fallback_method: fallback_method.clone(),
557                    challenge: fallback_challenge,
558                    remaining_fallbacks: fallback_order
559                        .iter()
560                        .skip_while(|&m| m != fallback_method)
561                        .skip(1)
562                        .filter(|&m| available_methods.contains(m))
563                        .cloned()
564                        .collect(),
565                });
566            }
567        }
568
569        Err(crate::errors::AuthError::validation(
570            "No fallback methods available",
571        ))
572    }
573
574    /// Adaptive MFA: Adjust required methods based on risk level
575    async fn adapt_required_methods(
576        &self,
577        base_methods: &[MfaMethod],
578        risk_level: RiskLevel,
579    ) -> Result<Vec<MfaMethod>> {
580        let mut adapted_methods = base_methods.to_vec();
581
582        match risk_level {
583            RiskLevel::Low => {
584                // Low risk: single factor is sufficient
585                adapted_methods.truncate(1);
586            }
587            RiskLevel::Medium => {
588                // Medium risk: use base methods as-is
589                // No changes needed
590            }
591            RiskLevel::High => {
592                // High risk: require additional verification
593                if !adapted_methods.contains(&MfaMethod::Email) {
594                    adapted_methods.push(MfaMethod::Email);
595                }
596                if !adapted_methods.contains(&MfaMethod::Sms) {
597                    adapted_methods.push(MfaMethod::Sms);
598                }
599            }
600            RiskLevel::Critical => {
601                // Critical risk: require all available methods
602                adapted_methods = vec![MfaMethod::Totp, MfaMethod::Sms, MfaMethod::Email];
603            }
604        }
605
606        Ok(adapted_methods)
607    }
608
609    /// Helper methods for cross-method operations
610    async fn get_cross_method_challenge(&self, challenge_id: &str) -> Result<CrossMethodChallenge> {
611        let challenges = self.challenges.read().await;
612        let challenge = challenges
613            .get(challenge_id)
614            .ok_or_else(|| crate::errors::AuthError::validation("Challenge not found"))?;
615
616        let cross_challenge: CrossMethodChallenge =
617            if let Some(cross_method_value) = challenge.data.get("cross_method_data") {
618                serde_json::from_value(cross_method_value.clone())?
619            } else {
620                return Err(crate::errors::AuthError::validation(
621                    "Invalid cross-method challenge data",
622                ));
623            };
624        Ok(cross_challenge)
625    }
626
627    async fn update_cross_method_challenge(
628        &self,
629        cross_challenge: &CrossMethodChallenge,
630    ) -> Result<()> {
631        let mut challenges = self.challenges.write().await;
632        if let Some(challenge) = challenges.get_mut(&cross_challenge.id) {
633            challenge.data.insert(
634                "cross_method_data".to_string(),
635                serde_json::to_value(cross_challenge)?,
636            );
637        }
638        Ok(())
639    }
640
641    fn get_remaining_methods(&self, cross_challenge: &CrossMethodChallenge) -> Vec<MfaMethod> {
642        cross_challenge
643            .completion_status
644            .iter()
645            .filter_map(|(method, &completed)| {
646                if !completed {
647                    Some(method.clone())
648                } else {
649                    None
650                }
651            })
652            .collect()
653    }
654
655    /// Create individual method challenges
656    async fn create_totp_challenge(
657        &self,
658        _user_id: &str,
659        challenge_prefix: &str,
660    ) -> Result<MethodChallenge> {
661        Ok(MethodChallenge::Totp {
662            challenge_id: format!("{}-totp", challenge_prefix),
663            instructions: "Enter the 6-digit code from your authenticator app".to_string(),
664        })
665    }
666
667    async fn create_sms_challenge(
668        &self,
669        user_id: &str,
670        challenge_prefix: &str,
671    ) -> Result<MethodChallenge> {
672        let _code = self.sms.send_verification_code(user_id).await?;
673        Ok(MethodChallenge::Sms {
674            challenge_id: format!("{}-sms", challenge_prefix),
675            instructions: "Enter the verification code sent to your phone".to_string(),
676            phone_hint: self
677                .get_phone_hint(user_id)
678                .await
679                .unwrap_or_else(|_| "***-***-****".to_string()),
680        })
681    }
682
683    async fn create_email_challenge(
684        &self,
685        user_id: &str,
686        challenge_prefix: &str,
687    ) -> Result<MethodChallenge> {
688        let _code = self.email.send_email_code(user_id).await?;
689        Ok(MethodChallenge::Email {
690            challenge_id: format!("{}-email", challenge_prefix),
691            instructions: "Enter the verification code sent to your email".to_string(),
692            email_hint: self
693                .get_email_hint(user_id)
694                .await
695                .unwrap_or_else(|_| "****@****.com".to_string()),
696        })
697    }
698
699    async fn get_phone_hint(&self, user_id: &str) -> Result<String> {
700        // Try to look up the user's phone number from storage
701        if let Ok(Some(data)) = self
702            .storage
703            .get_kv(&format!("user_phone:{}", user_id))
704            .await
705            && let Ok(phone) = String::from_utf8(data)
706            && phone.len() >= 4
707        {
708            return Ok(format!("***-***-{}", &phone[phone.len() - 4..]));
709        }
710        // Fallback: no phone data in storage
711        Ok("Phone on file".to_string())
712    }
713
714    async fn get_email_hint(&self, user_id: &str) -> Result<String> {
715        // Try to look up the user's email from storage
716        if let Ok(Some(data)) = self
717            .storage
718            .get_kv(&format!("user_email:{}", user_id))
719            .await
720            && let Ok(email) = String::from_utf8(data)
721            && let Some(at_pos) = email.find('@')
722        {
723            let prefix_len = at_pos.min(2);
724            return Ok(format!(
725                "{}****@****{}",
726                &email[..prefix_len],
727                &email[at_pos..]
728            ));
729        }
730        // Fallback: no email data in storage
731        Ok(format!("{}****@****.com", &user_id[..user_id.len().min(2)]))
732    }
733
734    fn emergency_bypass_secret() -> Result<Vec<u8>> {
735        let secret = std::env::var("AUTHFRAMEWORK_EMERGENCY_BYPASS_SECRET").map_err(|_| {
736            crate::errors::AuthError::config(
737                "Emergency MFA bypass is disabled until AUTHFRAMEWORK_EMERGENCY_BYPASS_SECRET is configured",
738            )
739        })?;
740
741        if secret.len() < 32 {
742            return Err(crate::errors::AuthError::config(
743                "AUTHFRAMEWORK_EMERGENCY_BYPASS_SECRET must be at least 32 bytes long",
744            ));
745        }
746
747        Ok(secret.into_bytes())
748    }
749
750    fn sign_emergency_bypass_payload(secret: &[u8], payload: &str) -> Result<String> {
751        let mut mac = EmergencyBypassHmac::new_from_slice(secret).map_err(|_| {
752            crate::errors::AuthError::config("Invalid emergency bypass signing key")
753        })?;
754        mac.update(payload.as_bytes());
755        Ok(hex::encode(mac.finalize().into_bytes()))
756    }
757
758    fn verify_emergency_bypass_token(secret: &[u8], token: &str) -> Result<EmergencyBypassClaims> {
759        let (payload_b64, signature_hex) = token.split_once('.').ok_or_else(|| {
760            crate::errors::AuthError::validation("Invalid emergency bypass token format")
761        })?;
762
763        let payload_bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
764            .decode(payload_b64)
765            .map_err(|_| {
766                crate::errors::AuthError::validation("Invalid emergency bypass token encoding")
767            })?;
768        let payload = String::from_utf8(payload_bytes).map_err(|_| {
769            crate::errors::AuthError::validation("Invalid emergency bypass token payload")
770        })?;
771
772        let expected_signature = Self::sign_emergency_bypass_payload(secret, &payload)?;
773        if !crate::security::secure_utils::constant_time_compare(
774            expected_signature.as_bytes(),
775            signature_hex.as_bytes(),
776        ) {
777            return Err(crate::errors::AuthError::validation(
778                "Emergency bypass token signature verification failed",
779            ));
780        }
781
782        let claims: EmergencyBypassClaims = serde_json::from_str(&payload).map_err(|_| {
783            crate::errors::AuthError::validation("Invalid emergency bypass token claims")
784        })?;
785
786        let now = chrono::Utc::now().timestamp();
787        if now >= claims.exp {
788            return Err(crate::errors::AuthError::validation(
789                "Emergency bypass token has expired",
790            ));
791        }
792
793        Ok(claims)
794    }
795
796    async fn user_has_admin_role(&self, user_id: &str) -> Result<bool> {
797        let user_key = format!("user:{}", user_id);
798        let Some(user_data) = self.storage.get_kv(&user_key).await? else {
799            return Ok(false);
800        };
801
802        let profile: serde_json::Value = serde_json::from_slice(&user_data).map_err(|e| {
803            crate::errors::AuthError::internal(format!(
804                "Failed to parse stored user profile for emergency bypass validation: {}",
805                e
806            ))
807        })?;
808
809        Ok(profile
810            .get("roles")
811            .and_then(|v| v.as_array())
812            .map(|roles| roles.iter().any(|role| role.as_str() == Some("admin")))
813            .unwrap_or(false))
814    }
815
816    /// Generate a signed emergency MFA bypass token for a specific target user.
817    pub async fn generate_emergency_bypass_token(
818        &self,
819        admin_user_id: &str,
820        target_user_id: &str,
821        lifetime: Duration,
822    ) -> Result<String> {
823        if !self.user_has_admin_role(admin_user_id).await? {
824            return Err(crate::errors::AuthError::Permission(
825                crate::errors::PermissionError::Denied {
826                    action: "generate emergency MFA bypass token".to_string(),
827                    resource: admin_user_id.to_string(),
828                    message:
829                        "Admin privileges are required to generate an emergency MFA bypass token"
830                            .to_string(),
831                },
832            ));
833        }
834
835        let secret = Self::emergency_bypass_secret()?;
836        let now = chrono::Utc::now().timestamp();
837        let exp = now
838            + i64::try_from(lifetime.as_secs()).map_err(|_| {
839                crate::errors::AuthError::validation(
840                    "Emergency bypass token lifetime exceeds supported range",
841                )
842            })?;
843
844        let claims = EmergencyBypassClaims {
845            admin_user_id: admin_user_id.to_string(),
846            target_user_id: target_user_id.to_string(),
847            iat: now,
848            exp,
849            jti: uuid::Uuid::new_v4().to_string(),
850        };
851        let payload = serde_json::to_string(&claims)
852            .map_err(|e| crate::errors::AuthError::internal(e.to_string()))?;
853        let payload_b64 =
854            base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(payload.as_bytes());
855        let signature = Self::sign_emergency_bypass_payload(&secret, &payload)?;
856        Ok(format!("{}.{}", payload_b64, signature))
857    }
858
859    /// Emergency MFA bypass using direct storage access
860    /// This method provides a way to recover when all MFA methods fail
861    pub async fn emergency_mfa_bypass(&self, user_id: &str, admin_token: &str) -> Result<bool> {
862        tracing::warn!("Emergency MFA bypass requested for user: {}", user_id);
863
864        let secret = Self::emergency_bypass_secret()?;
865        let claims = match Self::verify_emergency_bypass_token(&secret, admin_token) {
866            Ok(claims) => claims,
867            Err(e) => {
868                tracing::error!(error = %e, "Invalid emergency MFA bypass token");
869                return Ok(false);
870            }
871        };
872
873        if claims.target_user_id != user_id {
874            tracing::error!(
875                target = %claims.target_user_id,
876                requested = %user_id,
877                "Emergency MFA bypass token target user mismatch"
878            );
879            return Ok(false);
880        }
881
882        if !self.user_has_admin_role(&claims.admin_user_id).await? {
883            tracing::error!(
884                admin_user_id = %claims.admin_user_id,
885                "Emergency MFA bypass denied because issuing admin no longer has admin role"
886            );
887            return Ok(false);
888        }
889
890        tracing::info!(
891            admin_user_id = %claims.admin_user_id,
892            target_user_id = %claims.target_user_id,
893            "Emergency MFA bypass granted"
894        );
895
896        let bypass_key = format!("mfa_bypass:{}:{}", user_id, chrono::Utc::now().timestamp());
897        let bypass_data = serde_json::json!({
898            "admin_user_id": claims.admin_user_id,
899            "target_user_id": claims.target_user_id,
900            "issued_at": claims.iat,
901            "expires_at": claims.exp,
902            "jti": claims.jti,
903            "bypassed_at": chrono::Utc::now().to_rfc3339(),
904        })
905        .to_string();
906        self.storage
907            .store_kv(
908                &bypass_key,
909                bypass_data.as_bytes(),
910                Some(Duration::from_secs(86400)),
911            )
912            .await?;
913
914        Ok(true)
915    }
916}
917
918/// MFA method types
919#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
920pub enum MfaMethod {
921    Totp,
922    Sms,
923    Email,
924    BackupCode,
925}
926
927/// Risk levels for adaptive MFA
928#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
929pub enum RiskLevel {
930    Low,
931    Medium,
932    High,
933    Critical,
934}
935
936/// Cross-method challenge combining multiple MFA factors
937#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
938pub struct CrossMethodChallenge {
939    pub id: String,
940    pub user_id: String,
941    pub required_methods: Vec<MfaMethod>,
942    pub method_challenges: HashMap<MfaMethod, MethodChallenge>,
943    pub completion_status: HashMap<MfaMethod, bool>,
944    pub risk_level: RiskLevel,
945    pub expires_at: chrono::DateTime<chrono::Utc>,
946    pub created_at: chrono::DateTime<chrono::Utc>,
947}
948
949/// Individual method challenge
950#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
951pub enum MethodChallenge {
952    Totp {
953        challenge_id: String,
954        instructions: String,
955    },
956    Sms {
957        challenge_id: String,
958        instructions: String,
959        phone_hint: String,
960    },
961    Email {
962        challenge_id: String,
963        instructions: String,
964        email_hint: String,
965    },
966    BackupCode {
967        challenge_id: String,
968        instructions: String,
969    },
970}
971
972/// Result of cross-method completion attempt
973#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
974pub struct CrossMethodCompletionResult {
975    pub method: MfaMethod,
976    pub success: bool,
977    pub remaining_methods: Vec<MfaMethod>,
978    pub all_completed: bool,
979    pub error: Option<String>,
980}
981
982/// Result of method fallback operation
983#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
984pub struct MethodFallbackResult {
985    pub fallback_method: MfaMethod,
986    pub challenge: MethodChallenge,
987    pub remaining_fallbacks: Vec<MfaMethod>,
988}
989
990#[cfg(test)]
991mod tests {
992    use super::*;
993    use crate::storage::MemoryStorage;
994
995    fn make_mfa() -> MfaManager {
996        MfaManager::new(Arc::new(MemoryStorage::new()))
997    }
998
999    fn make_challenge(user_id: &str) -> MfaChallenge {
1000        use crate::methods::{MfaChallenge, MfaType};
1001        MfaChallenge {
1002            id: format!("chal_{}", uuid::Uuid::new_v4()),
1003            mfa_type: MfaType::Totp,
1004            user_id: user_id.to_string(),
1005            created_at: chrono::Utc::now(),
1006            expires_at: chrono::Utc::now() + chrono::Duration::minutes(5),
1007            attempts: 0,
1008            max_attempts: 3,
1009            code_hash: None,
1010            message: None,
1011            data: HashMap::new(),
1012        }
1013    }
1014
1015    // ── store / get / remove challenge ──────────────────────────────────
1016
1017    #[tokio::test]
1018    async fn test_store_and_get_challenge() {
1019        let mfa = make_mfa();
1020        let chal = make_challenge("u1");
1021        let id = chal.id.clone();
1022        mfa.store_challenge(chal).await.unwrap();
1023        let retrieved = mfa.get_challenge(&id).await.unwrap();
1024        assert!(retrieved.is_some());
1025        assert_eq!(retrieved.unwrap().user_id, "u1");
1026    }
1027
1028    #[tokio::test]
1029    async fn test_remove_challenge() {
1030        let mfa = make_mfa();
1031        let chal = make_challenge("u2");
1032        let id = chal.id.clone();
1033        mfa.store_challenge(chal).await.unwrap();
1034        mfa.remove_challenge(&id).await.unwrap();
1035        assert!(mfa.get_challenge(&id).await.unwrap().is_none());
1036    }
1037
1038    #[tokio::test]
1039    async fn test_get_challenge_nonexistent() {
1040        let mfa = make_mfa();
1041        assert!(mfa.get_challenge("ghost").await.unwrap().is_none());
1042    }
1043
1044    #[tokio::test]
1045    async fn test_get_active_challenge_count() {
1046        let mfa = make_mfa();
1047        assert_eq!(mfa.get_active_challenge_count().await, 0);
1048        mfa.store_challenge(make_challenge("u3")).await.unwrap();
1049        assert_eq!(mfa.get_active_challenge_count().await, 1);
1050    }
1051
1052    #[tokio::test]
1053    async fn test_cleanup_expired_challenges() {
1054        let mfa = make_mfa();
1055        let mut chal = make_challenge("u4");
1056        chal.expires_at = chrono::Utc::now() - chrono::Duration::minutes(1);
1057        mfa.store_challenge(chal).await.unwrap();
1058        mfa.cleanup_expired_challenges().await.unwrap();
1059        assert_eq!(mfa.get_active_challenge_count().await, 0);
1060    }
1061
1062    #[tokio::test]
1063    async fn test_guard_and_store_succeeds() {
1064        let mfa = make_mfa();
1065        let chal = make_challenge("guard_user");
1066        mfa.guard_and_store(chal).await.unwrap();
1067        assert_eq!(mfa.get_active_challenge_count().await, 1);
1068    }
1069
1070    // ── get_available_methods ───────────────────────────────────────────
1071
1072    #[tokio::test]
1073    async fn test_get_available_methods_none() {
1074        let mfa = make_mfa();
1075        let methods = mfa.get_available_methods("nobody").await.unwrap();
1076        // Only backup codes might be default-available or might be empty
1077        // Either way this shouldn't error
1078        assert!(methods.len() <= 4);
1079    }
1080
1081    #[tokio::test]
1082    async fn test_get_available_methods_with_totp() {
1083        let mfa = make_mfa();
1084        let _secret = mfa.totp.generate_secret("totp_user").await.unwrap();
1085        let methods = mfa.get_available_methods("totp_user").await.unwrap();
1086        assert!(methods.contains(&MfaMethod::Totp));
1087    }
1088
1089    #[tokio::test]
1090    async fn test_perform_method_fallback_uses_api_enrolled_totp() {
1091        let storage: Arc<dyn AuthStorage> = Arc::new(MemoryStorage::new());
1092        let mfa = MfaManager::new(storage.clone());
1093        let api_secret = base32::encode(base32::Alphabet::Rfc4648 { padding: true }, &[42; 20]);
1094
1095        storage
1096            .store_kv("mfa_secret:api_totp_user", api_secret.as_bytes(), None)
1097            .await
1098            .unwrap();
1099
1100        let fallback = mfa
1101            .perform_method_fallback("api_totp_user", MfaMethod::Email, &[MfaMethod::Totp])
1102            .await
1103            .unwrap();
1104
1105        assert_eq!(fallback.fallback_method, MfaMethod::Totp);
1106        assert!(matches!(fallback.challenge, MethodChallenge::Totp { .. }));
1107    }
1108
1109    // ── step-up authentication ──────────────────────────────────────────
1110
1111    #[tokio::test]
1112    async fn test_cross_method_step_accepts_valid_code() {
1113        let mfa = make_mfa();
1114        let secret = mfa.totp.generate_secret("ok_user").await.unwrap();
1115        let cross = mfa
1116            .initiate_step_up_authentication("ok_user", &[MfaMethod::Totp], RiskLevel::Medium)
1117            .await
1118            .unwrap();
1119        let code = mfa.totp.generate_code(&secret).await.unwrap();
1120        let res = mfa
1121            .complete_cross_method_step(&cross.id, MfaMethod::Totp, &code)
1122            .await
1123            .unwrap();
1124        assert!(
1125            res.success,
1126            "a valid TOTP code must complete the step (error={:?})",
1127            res.error
1128        );
1129    }
1130
1131    #[tokio::test]
1132    async fn test_cross_method_step_rejects_invalid_code() {
1133        let mfa = make_mfa();
1134        let _secret = mfa.totp.generate_secret("bypass_user").await.unwrap();
1135        let cross = mfa
1136            .initiate_step_up_authentication("bypass_user", &[MfaMethod::Totp], RiskLevel::Medium)
1137            .await
1138            .unwrap();
1139        // Malformed on purpose: TOTP verify_code returns Ok(false) for any non-6-char code,
1140        // so this is deterministic and cannot collide with a real TOTP value.
1141        let res = mfa
1142            .complete_cross_method_step(&cross.id, MfaMethod::Totp, "garbage")
1143            .await
1144            .unwrap();
1145        assert!(
1146            !res.success,
1147            "an invalid TOTP code must NOT complete a step-up MFA step (success={})",
1148            res.success
1149        );
1150    }
1151
1152    #[tokio::test]
1153    async fn test_initiate_step_up_authentication() {
1154        let mfa = make_mfa();
1155        // Setup TOTP for user
1156        let _secret = mfa.totp.generate_secret("step_user").await.unwrap();
1157
1158        let cross = mfa
1159            .initiate_step_up_authentication("step_user", &[MfaMethod::Totp], RiskLevel::Medium)
1160            .await
1161            .unwrap();
1162        assert_eq!(cross.user_id, "step_user");
1163        assert_eq!(cross.risk_level, RiskLevel::Medium);
1164    }
1165
1166    /// Helper to create an admin user profile in storage so `user_has_admin_role` passes.
1167    async fn setup_admin(storage: &Arc<dyn AuthStorage>, user_id: &str) {
1168        let profile = serde_json::json!({
1169            "user_id": user_id,
1170            "username": user_id,
1171            "roles": ["admin"]
1172        });
1173        let key = format!("user:{}", user_id);
1174        storage
1175            .store_kv(&key, profile.to_string().as_bytes(), None)
1176            .await
1177            .unwrap();
1178    }
1179
1180    // ── emergency bypass ────────────────────────────────────────────────
1181
1182    #[tokio::test]
1183    async fn test_generate_and_use_emergency_bypass() {
1184        let _env = crate::testing::test_infrastructure::TestEnvironmentGuard::new()
1185            .with_custom_var(
1186                "AUTHFRAMEWORK_EMERGENCY_BYPASS_SECRET",
1187                "this-is-a-very-long-test-secret-that-is-at-least-32-bytes",
1188            );
1189        let storage: Arc<dyn AuthStorage> = Arc::new(MemoryStorage::new());
1190        let mfa = MfaManager::new(storage.clone());
1191        setup_admin(&storage, "admin1").await;
1192        let token = mfa
1193            .generate_emergency_bypass_token("admin1", "target1", Duration::from_secs(300))
1194            .await
1195            .unwrap();
1196        assert!(!token.is_empty());
1197        let result = mfa.emergency_mfa_bypass("target1", &token).await.unwrap();
1198        assert!(result);
1199    }
1200
1201    #[tokio::test]
1202    async fn test_emergency_bypass_wrong_user() {
1203        let _env = crate::testing::test_infrastructure::TestEnvironmentGuard::new()
1204            .with_custom_var(
1205                "AUTHFRAMEWORK_EMERGENCY_BYPASS_SECRET",
1206                "this-is-a-very-long-test-secret-that-is-at-least-32-bytes",
1207            );
1208        let storage: Arc<dyn AuthStorage> = Arc::new(MemoryStorage::new());
1209        let mfa = MfaManager::new(storage.clone());
1210        setup_admin(&storage, "admin1").await;
1211        let token = mfa
1212            .generate_emergency_bypass_token("admin1", "target1", Duration::from_secs(300))
1213            .await
1214            .unwrap();
1215        let result = mfa
1216            .emergency_mfa_bypass("wrong_user", &token)
1217            .await
1218            .unwrap();
1219        assert!(!result);
1220    }
1221
1222    #[tokio::test]
1223    async fn test_emergency_bypass_invalid_token() {
1224        let mfa = make_mfa();
1225        let result = mfa.emergency_mfa_bypass("user1", "bogus_token").await;
1226        // Should return Ok(false) or Err — either way not Ok(true)
1227        assert!(!result.unwrap_or(false));
1228    }
1229
1230    #[tokio::test]
1231    async fn test_emergency_bypass_non_admin_rejected() {
1232        let _env = crate::testing::test_infrastructure::TestEnvironmentGuard::new()
1233            .with_custom_var(
1234                "AUTHFRAMEWORK_EMERGENCY_BYPASS_SECRET",
1235                "this-is-a-very-long-test-secret-that-is-at-least-32-bytes",
1236            );
1237        let storage: Arc<dyn AuthStorage> = Arc::new(MemoryStorage::new());
1238        let mfa = MfaManager::new(storage.clone());
1239        // Don't set up admin — should fail
1240        let result = mfa
1241            .generate_emergency_bypass_token("notadmin", "target1", Duration::from_secs(300))
1242            .await;
1243        assert!(result.is_err());
1244    }
1245
1246    // ── TOTP sub-module ─────────────────────────────────────────────────
1247
1248    #[tokio::test]
1249    async fn test_totp_generate_secret() {
1250        let mfa = make_mfa();
1251        let secret = mfa.totp.generate_secret("totp1").await.unwrap();
1252        assert!(!secret.is_empty());
1253        assert!(mfa.totp.has_totp_secret("totp1").await.unwrap());
1254    }
1255
1256    #[tokio::test]
1257    async fn test_totp_generate_code() {
1258        let mfa = make_mfa();
1259        let secret = mfa.totp.generate_secret("totp2").await.unwrap();
1260        let code = mfa.totp.generate_code(&secret).await.unwrap();
1261        assert_eq!(code.len(), 6);
1262        assert!(code.chars().all(|c| c.is_ascii_digit()));
1263    }
1264
1265    #[tokio::test]
1266    async fn test_totp_verify_code_success() {
1267        let mfa = make_mfa();
1268        let secret = mfa.totp.generate_secret("totp3").await.unwrap();
1269        let code = mfa.totp.generate_code(&secret).await.unwrap();
1270        assert!(mfa.totp.verify_code("totp3", &code).await.unwrap());
1271    }
1272
1273    #[tokio::test]
1274    async fn test_totp_verify_code_wrong() {
1275        let mfa = make_mfa();
1276        let _secret = mfa.totp.generate_secret("totp4").await.unwrap();
1277        assert!(
1278            !mfa.totp
1279                .verify_code("totp4", "000000")
1280                .await
1281                .unwrap_or(true)
1282        );
1283    }
1284
1285    #[tokio::test]
1286    async fn test_totp_has_no_secret() {
1287        let mfa = make_mfa();
1288        assert!(!mfa.totp.has_totp_secret("nobody").await.unwrap());
1289    }
1290
1291    /// `verify_code` must reject an unenrolled user outright, never silently
1292    /// derive and accept a fallback secret computed purely from the user_id.
1293    /// Proves absence, not just "some code was rejected": computes the
1294    /// specific fallback this method used to derive
1295    /// (`SHA256(user_id || "totp_secret_salt_2024")`, base32-encoded, same
1296    /// as the TOTP secret format `generate_secret` produces), generates the
1297    /// valid code for that derived secret, and submits it -- if the fallback
1298    /// still existed, this specific code would verify as `true`.
1299    #[tokio::test]
1300    async fn test_totp_verify_code_rejects_unenrolled_user_even_with_the_old_derived_code() {
1301        let mfa = make_mfa();
1302        let user_id = "totp_unenrolled_user";
1303
1304        use sha2::{Digest, Sha256};
1305        let mut hasher = Sha256::new();
1306        hasher.update(user_id.as_bytes());
1307        hasher.update(b"totp_secret_salt_2024");
1308        let hash = hasher.finalize();
1309        let would_be_derived_secret =
1310            base32::encode(base32::Alphabet::Rfc4648 { padding: true }, &hash[0..20]);
1311
1312        let code_for_derived_secret = mfa
1313            .totp
1314            .generate_code(&would_be_derived_secret)
1315            .await
1316            .unwrap();
1317
1318        assert!(
1319            !mfa.totp
1320                .verify_code(user_id, &code_for_derived_secret)
1321                .await
1322                .unwrap(),
1323            "an unenrolled user must not be verifiable via the old predictable fallback secret"
1324        );
1325        assert!(!mfa.totp.has_totp_secret(user_id).await.unwrap());
1326    }
1327
1328    /// A user who enrolled via the live `/mfa/setup` API route (which
1329    /// stores under `mfa_secret:{user_id}`) must be verifiable through the
1330    /// same `verify_code` the modular `generate_secret` path uses -- the two
1331    /// routes must agree on where the secret lives, not silently diverge.
1332    #[tokio::test]
1333    async fn test_totp_verify_code_finds_secret_enrolled_via_api_setup_key() {
1334        use crate::storage::MemoryStorage;
1335        let storage: Arc<dyn AuthStorage> = Arc::new(MemoryStorage::new());
1336        let mfa = MfaManager::new(storage.clone());
1337        let user_id = "totp_api_enrolled_user";
1338
1339        // Simulate the live /mfa/setup route's storage key directly, bypassing
1340        // the modular generate_secret path entirely.
1341        let secret = "JBSWY3DPEHPK3PXP".to_string(); // valid base32
1342        storage
1343            .store_kv(&format!("mfa_secret:{}", user_id), secret.as_bytes(), None)
1344            .await
1345            .unwrap();
1346
1347        let code = mfa.totp.generate_code(&secret).await.unwrap();
1348        assert!(
1349            mfa.totp.verify_code(user_id, &code).await.unwrap(),
1350            "verify_code must find a secret enrolled under the API route's key"
1351        );
1352    }
1353
1354    #[tokio::test]
1355    async fn test_totp_generate_qr_code() {
1356        let mfa = make_mfa();
1357        let secret = mfa.totp.generate_secret("totp5").await.unwrap();
1358        let qr = mfa
1359            .totp
1360            .generate_qr_code("totp5", "AuthFramework", &secret)
1361            .await
1362            .unwrap();
1363        assert!(qr.contains("otpauth://"));
1364    }
1365
1366    // ── Backup codes sub-module ─────────────────────────────────────────
1367
1368    #[tokio::test]
1369    async fn test_backup_codes_generate() {
1370        let mfa = make_mfa();
1371        let codes = mfa.backup_codes.generate_codes("bc1", 10).await.unwrap();
1372        assert_eq!(codes.len(), 10);
1373    }
1374
1375    #[tokio::test]
1376    async fn test_backup_codes_verify() {
1377        let mfa = make_mfa();
1378        let codes = mfa.backup_codes.generate_codes("bc2", 5).await.unwrap();
1379        let code = codes[0].clone();
1380        assert!(mfa.backup_codes.verify_code("bc2", &code).await.unwrap());
1381        // Code should be consumed — second verify should fail
1382        assert!(!mfa.backup_codes.verify_code("bc2", &code).await.unwrap());
1383    }
1384
1385    #[tokio::test]
1386    async fn test_backup_codes_remaining_count() {
1387        let mfa = make_mfa();
1388        mfa.backup_codes.generate_codes("bc3", 5).await.unwrap();
1389        assert_eq!(
1390            mfa.backup_codes.get_remaining_count("bc3").await.unwrap(),
1391            5
1392        );
1393    }
1394
1395    #[tokio::test]
1396    async fn test_backup_codes_verify_wrong_code() {
1397        let mfa = make_mfa();
1398        mfa.backup_codes.generate_codes("bc4", 5).await.unwrap();
1399        assert!(
1400            !mfa.backup_codes
1401                .verify_code("bc4", "WRONGCODE")
1402                .await
1403                .unwrap()
1404        );
1405    }
1406
1407    #[tokio::test]
1408    async fn test_backup_codes_regenerate() {
1409        let mfa = make_mfa();
1410        let old = mfa.backup_codes.generate_codes("bc5", 5).await.unwrap();
1411        let new = mfa.backup_codes.regenerate_codes("bc5", 5).await.unwrap();
1412        assert_ne!(old, new);
1413    }
1414
1415    #[tokio::test]
1416    async fn test_backup_codes_has_codes() {
1417        let mfa = make_mfa();
1418        assert!(!mfa.backup_codes.has_backup_codes("nobody").await.unwrap());
1419        mfa.backup_codes.generate_codes("bc6", 3).await.unwrap();
1420        assert!(mfa.backup_codes.has_backup_codes("bc6").await.unwrap());
1421    }
1422
1423    // ── Email MFA sub-module ────────────────────────────────────────────
1424
1425    #[tokio::test]
1426    async fn test_email_register_and_has_email() {
1427        let mfa = make_mfa();
1428        assert!(!mfa.email.has_email("em1").await.unwrap());
1429        mfa.email
1430            .register_email("em1", "test@example.com")
1431            .await
1432            .unwrap();
1433        assert!(mfa.email.has_email("em1").await.unwrap());
1434    }
1435
1436    #[tokio::test]
1437    async fn test_email_get_user_email() {
1438        let mfa = make_mfa();
1439        mfa.email
1440            .register_email("em2", "em2@example.com")
1441            .await
1442            .unwrap();
1443        let email = mfa.email.get_user_email("em2").await.unwrap();
1444        assert_eq!(email.as_deref(), Some("em2@example.com"));
1445    }
1446
1447    #[tokio::test]
1448    async fn test_email_get_user_email_none() {
1449        let mfa = make_mfa();
1450        let email = mfa.email.get_user_email("nobody").await.unwrap();
1451        assert!(email.is_none());
1452    }
1453
1454    #[tokio::test]
1455    async fn test_email_initiate_challenge() {
1456        let mfa = make_mfa();
1457        mfa.email
1458            .register_email("em3", "em3@example.com")
1459            .await
1460            .unwrap();
1461        let challenge_id = mfa.email.initiate_challenge("em3").await.unwrap();
1462        assert!(!challenge_id.is_empty());
1463    }
1464
1465    #[tokio::test]
1466    async fn test_email_generate_and_verify_code() {
1467        let mfa = make_mfa();
1468        mfa.email
1469            .register_email("em4", "em4@example.com")
1470            .await
1471            .unwrap();
1472        let cid = mfa.email.initiate_challenge("em4").await.unwrap();
1473        let code = mfa.email.generate_code(&cid).await.unwrap();
1474        assert!(mfa.email.verify_code(&cid, &code).await.unwrap());
1475    }
1476
1477    #[tokio::test]
1478    async fn test_email_verify_wrong_code() {
1479        let mfa = make_mfa();
1480        mfa.email
1481            .register_email("em5", "em5@example.com")
1482            .await
1483            .unwrap();
1484        let cid = mfa.email.initiate_challenge("em5").await.unwrap();
1485        let _code = mfa.email.generate_code(&cid).await.unwrap();
1486        assert!(!mfa.email.verify_code(&cid, "000000").await.unwrap());
1487    }
1488
1489    // ── SMS MFA sub-module ──────────────────────────────────────────────
1490
1491    #[tokio::test]
1492    async fn test_sms_register_and_has_phone() {
1493        let mfa = make_mfa();
1494        assert!(!mfa.sms.has_phone_number("sms1").await.unwrap());
1495        mfa.sms
1496            .register_phone_number("sms1", "+1234567890")
1497            .await
1498            .unwrap();
1499        assert!(mfa.sms.has_phone_number("sms1").await.unwrap());
1500    }
1501
1502    #[tokio::test]
1503    async fn test_sms_get_user_phone() {
1504        let mfa = make_mfa();
1505        mfa.sms
1506            .register_phone_number("sms2", "+9876543210")
1507            .await
1508            .unwrap();
1509        let phone = mfa.sms.get_user_phone("sms2").await.unwrap();
1510        assert_eq!(phone.as_deref(), Some("+9876543210"));
1511    }
1512
1513    #[tokio::test]
1514    async fn test_sms_get_user_phone_none() {
1515        let mfa = make_mfa();
1516        let phone = mfa.sms.get_user_phone("nobody").await.unwrap();
1517        assert!(phone.is_none());
1518    }
1519
1520    #[tokio::test]
1521    async fn test_sms_initiate_challenge() {
1522        let mfa = make_mfa();
1523        mfa.sms
1524            .register_phone_number("sms3", "+1111111111")
1525            .await
1526            .unwrap();
1527        let cid = mfa.sms.initiate_challenge("sms3").await.unwrap();
1528        assert!(!cid.is_empty());
1529    }
1530
1531    #[tokio::test]
1532    async fn test_sms_generate_and_verify_code() {
1533        let mfa = make_mfa();
1534        mfa.sms
1535            .register_phone_number("sms4", "+2222222222")
1536            .await
1537            .unwrap();
1538        let cid = mfa.sms.initiate_challenge("sms4").await.unwrap();
1539        let code = mfa.sms.generate_code(&cid).await.unwrap();
1540        assert!(mfa.sms.verify_code(&cid, &code).await.unwrap());
1541    }
1542
1543    #[tokio::test]
1544    async fn test_sms_verify_wrong_code() {
1545        let mfa = make_mfa();
1546        mfa.sms
1547            .register_phone_number("sms5", "+3333333333")
1548            .await
1549            .unwrap();
1550        let cid = mfa.sms.initiate_challenge("sms5").await.unwrap();
1551        let _code = mfa.sms.generate_code(&cid).await.unwrap();
1552        assert!(!mfa.sms.verify_code(&cid, "000000").await.unwrap());
1553    }
1554}