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        {
706            if let Ok(phone) = String::from_utf8(data) {
707                if phone.len() >= 4 {
708                    return Ok(format!("***-***-{}", &phone[phone.len() - 4..]));
709                }
710            }
711        }
712        // Fallback: no phone data in storage
713        Ok("Phone on file".to_string())
714    }
715
716    async fn get_email_hint(&self, user_id: &str) -> Result<String> {
717        // Try to look up the user's email from storage
718        if let Ok(Some(data)) = self
719            .storage
720            .get_kv(&format!("user_email:{}", user_id))
721            .await
722        {
723            if let Ok(email) = String::from_utf8(data) {
724                if let Some(at_pos) = email.find('@') {
725                    let prefix_len = at_pos.min(2);
726                    return Ok(format!(
727                        "{}****@****{}",
728                        &email[..prefix_len],
729                        &email[at_pos..]
730                    ));
731                }
732            }
733        }
734        // Fallback: no email data in storage
735        Ok(format!("{}****@****.com", &user_id[..user_id.len().min(2)]))
736    }
737
738    fn emergency_bypass_secret() -> Result<Vec<u8>> {
739        let secret = std::env::var("AUTHFRAMEWORK_EMERGENCY_BYPASS_SECRET").map_err(|_| {
740            crate::errors::AuthError::config(
741                "Emergency MFA bypass is disabled until AUTHFRAMEWORK_EMERGENCY_BYPASS_SECRET is configured",
742            )
743        })?;
744
745        if secret.len() < 32 {
746            return Err(crate::errors::AuthError::config(
747                "AUTHFRAMEWORK_EMERGENCY_BYPASS_SECRET must be at least 32 bytes long",
748            ));
749        }
750
751        Ok(secret.into_bytes())
752    }
753
754    fn sign_emergency_bypass_payload(secret: &[u8], payload: &str) -> Result<String> {
755        let mut mac = EmergencyBypassHmac::new_from_slice(secret).map_err(|_| {
756            crate::errors::AuthError::config("Invalid emergency bypass signing key")
757        })?;
758        mac.update(payload.as_bytes());
759        Ok(hex::encode(mac.finalize().into_bytes()))
760    }
761
762    fn verify_emergency_bypass_token(secret: &[u8], token: &str) -> Result<EmergencyBypassClaims> {
763        let (payload_b64, signature_hex) = token.split_once('.').ok_or_else(|| {
764            crate::errors::AuthError::validation("Invalid emergency bypass token format")
765        })?;
766
767        let payload_bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
768            .decode(payload_b64)
769            .map_err(|_| {
770                crate::errors::AuthError::validation("Invalid emergency bypass token encoding")
771            })?;
772        let payload = String::from_utf8(payload_bytes).map_err(|_| {
773            crate::errors::AuthError::validation("Invalid emergency bypass token payload")
774        })?;
775
776        let expected_signature = Self::sign_emergency_bypass_payload(secret, &payload)?;
777        if !crate::security::secure_utils::constant_time_compare(
778            expected_signature.as_bytes(),
779            signature_hex.as_bytes(),
780        ) {
781            return Err(crate::errors::AuthError::validation(
782                "Emergency bypass token signature verification failed",
783            ));
784        }
785
786        let claims: EmergencyBypassClaims = serde_json::from_str(&payload).map_err(|_| {
787            crate::errors::AuthError::validation("Invalid emergency bypass token claims")
788        })?;
789
790        let now = chrono::Utc::now().timestamp();
791        if now >= claims.exp {
792            return Err(crate::errors::AuthError::validation(
793                "Emergency bypass token has expired",
794            ));
795        }
796
797        Ok(claims)
798    }
799
800    async fn user_has_admin_role(&self, user_id: &str) -> Result<bool> {
801        let user_key = format!("user:{}", user_id);
802        let Some(user_data) = self.storage.get_kv(&user_key).await? else {
803            return Ok(false);
804        };
805
806        let profile: serde_json::Value = serde_json::from_slice(&user_data).map_err(|e| {
807            crate::errors::AuthError::internal(format!(
808                "Failed to parse stored user profile for emergency bypass validation: {}",
809                e
810            ))
811        })?;
812
813        Ok(profile
814            .get("roles")
815            .and_then(|v| v.as_array())
816            .map(|roles| roles.iter().any(|role| role.as_str() == Some("admin")))
817            .unwrap_or(false))
818    }
819
820    /// Generate a signed emergency MFA bypass token for a specific target user.
821    pub async fn generate_emergency_bypass_token(
822        &self,
823        admin_user_id: &str,
824        target_user_id: &str,
825        lifetime: Duration,
826    ) -> Result<String> {
827        if !self.user_has_admin_role(admin_user_id).await? {
828            return Err(crate::errors::AuthError::Permission(
829                crate::errors::PermissionError::Denied {
830                    action: "generate emergency MFA bypass token".to_string(),
831                    resource: admin_user_id.to_string(),
832                    message:
833                        "Admin privileges are required to generate an emergency MFA bypass token"
834                            .to_string(),
835                },
836            ));
837        }
838
839        let secret = Self::emergency_bypass_secret()?;
840        let now = chrono::Utc::now().timestamp();
841        let exp = now
842            + i64::try_from(lifetime.as_secs()).map_err(|_| {
843                crate::errors::AuthError::validation(
844                    "Emergency bypass token lifetime exceeds supported range",
845                )
846            })?;
847
848        let claims = EmergencyBypassClaims {
849            admin_user_id: admin_user_id.to_string(),
850            target_user_id: target_user_id.to_string(),
851            iat: now,
852            exp,
853            jti: uuid::Uuid::new_v4().to_string(),
854        };
855        let payload = serde_json::to_string(&claims)
856            .map_err(|e| crate::errors::AuthError::internal(e.to_string()))?;
857        let payload_b64 =
858            base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(payload.as_bytes());
859        let signature = Self::sign_emergency_bypass_payload(&secret, &payload)?;
860        Ok(format!("{}.{}", payload_b64, signature))
861    }
862
863    /// Emergency MFA bypass using direct storage access
864    /// This method provides a way to recover when all MFA methods fail
865    pub async fn emergency_mfa_bypass(&self, user_id: &str, admin_token: &str) -> Result<bool> {
866        tracing::warn!("Emergency MFA bypass requested for user: {}", user_id);
867
868        let secret = Self::emergency_bypass_secret()?;
869        let claims = match Self::verify_emergency_bypass_token(&secret, admin_token) {
870            Ok(claims) => claims,
871            Err(e) => {
872                tracing::error!(error = %e, "Invalid emergency MFA bypass token");
873                return Ok(false);
874            }
875        };
876
877        if claims.target_user_id != user_id {
878            tracing::error!(
879                target = %claims.target_user_id,
880                requested = %user_id,
881                "Emergency MFA bypass token target user mismatch"
882            );
883            return Ok(false);
884        }
885
886        if !self.user_has_admin_role(&claims.admin_user_id).await? {
887            tracing::error!(
888                admin_user_id = %claims.admin_user_id,
889                "Emergency MFA bypass denied because issuing admin no longer has admin role"
890            );
891            return Ok(false);
892        }
893
894        tracing::info!(
895            admin_user_id = %claims.admin_user_id,
896            target_user_id = %claims.target_user_id,
897            "Emergency MFA bypass granted"
898        );
899
900        let bypass_key = format!("mfa_bypass:{}:{}", user_id, chrono::Utc::now().timestamp());
901        let bypass_data = serde_json::json!({
902            "admin_user_id": claims.admin_user_id,
903            "target_user_id": claims.target_user_id,
904            "issued_at": claims.iat,
905            "expires_at": claims.exp,
906            "jti": claims.jti,
907            "bypassed_at": chrono::Utc::now().to_rfc3339(),
908        })
909        .to_string();
910        self.storage
911            .store_kv(
912                &bypass_key,
913                bypass_data.as_bytes(),
914                Some(Duration::from_secs(86400)),
915            )
916            .await?;
917
918        Ok(true)
919    }
920}
921
922/// MFA method types
923#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
924pub enum MfaMethod {
925    Totp,
926    Sms,
927    Email,
928    BackupCode,
929}
930
931/// Risk levels for adaptive MFA
932#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
933pub enum RiskLevel {
934    Low,
935    Medium,
936    High,
937    Critical,
938}
939
940/// Cross-method challenge combining multiple MFA factors
941#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
942pub struct CrossMethodChallenge {
943    pub id: String,
944    pub user_id: String,
945    pub required_methods: Vec<MfaMethod>,
946    pub method_challenges: HashMap<MfaMethod, MethodChallenge>,
947    pub completion_status: HashMap<MfaMethod, bool>,
948    pub risk_level: RiskLevel,
949    pub expires_at: chrono::DateTime<chrono::Utc>,
950    pub created_at: chrono::DateTime<chrono::Utc>,
951}
952
953/// Individual method challenge
954#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
955pub enum MethodChallenge {
956    Totp {
957        challenge_id: String,
958        instructions: String,
959    },
960    Sms {
961        challenge_id: String,
962        instructions: String,
963        phone_hint: String,
964    },
965    Email {
966        challenge_id: String,
967        instructions: String,
968        email_hint: String,
969    },
970    BackupCode {
971        challenge_id: String,
972        instructions: String,
973    },
974}
975
976/// Result of cross-method completion attempt
977#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
978pub struct CrossMethodCompletionResult {
979    pub method: MfaMethod,
980    pub success: bool,
981    pub remaining_methods: Vec<MfaMethod>,
982    pub all_completed: bool,
983    pub error: Option<String>,
984}
985
986/// Result of method fallback operation
987#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
988pub struct MethodFallbackResult {
989    pub fallback_method: MfaMethod,
990    pub challenge: MethodChallenge,
991    pub remaining_fallbacks: Vec<MfaMethod>,
992}
993
994#[cfg(test)]
995mod tests {
996    use super::*;
997    use crate::storage::MemoryStorage;
998
999    fn make_mfa() -> MfaManager {
1000        MfaManager::new(Arc::new(MemoryStorage::new()))
1001    }
1002
1003    fn make_challenge(user_id: &str) -> MfaChallenge {
1004        use crate::methods::{MfaChallenge, MfaType};
1005        MfaChallenge {
1006            id: format!("chal_{}", uuid::Uuid::new_v4()),
1007            mfa_type: MfaType::Totp,
1008            user_id: user_id.to_string(),
1009            created_at: chrono::Utc::now(),
1010            expires_at: chrono::Utc::now() + chrono::Duration::minutes(5),
1011            attempts: 0,
1012            max_attempts: 3,
1013            code_hash: None,
1014            message: None,
1015            data: HashMap::new(),
1016        }
1017    }
1018
1019    // ── store / get / remove challenge ──────────────────────────────────
1020
1021    #[tokio::test]
1022    async fn test_store_and_get_challenge() {
1023        let mfa = make_mfa();
1024        let chal = make_challenge("u1");
1025        let id = chal.id.clone();
1026        mfa.store_challenge(chal).await.unwrap();
1027        let retrieved = mfa.get_challenge(&id).await.unwrap();
1028        assert!(retrieved.is_some());
1029        assert_eq!(retrieved.unwrap().user_id, "u1");
1030    }
1031
1032    #[tokio::test]
1033    async fn test_remove_challenge() {
1034        let mfa = make_mfa();
1035        let chal = make_challenge("u2");
1036        let id = chal.id.clone();
1037        mfa.store_challenge(chal).await.unwrap();
1038        mfa.remove_challenge(&id).await.unwrap();
1039        assert!(mfa.get_challenge(&id).await.unwrap().is_none());
1040    }
1041
1042    #[tokio::test]
1043    async fn test_get_challenge_nonexistent() {
1044        let mfa = make_mfa();
1045        assert!(mfa.get_challenge("ghost").await.unwrap().is_none());
1046    }
1047
1048    #[tokio::test]
1049    async fn test_get_active_challenge_count() {
1050        let mfa = make_mfa();
1051        assert_eq!(mfa.get_active_challenge_count().await, 0);
1052        mfa.store_challenge(make_challenge("u3")).await.unwrap();
1053        assert_eq!(mfa.get_active_challenge_count().await, 1);
1054    }
1055
1056    #[tokio::test]
1057    async fn test_cleanup_expired_challenges() {
1058        let mfa = make_mfa();
1059        let mut chal = make_challenge("u4");
1060        chal.expires_at = chrono::Utc::now() - chrono::Duration::minutes(1);
1061        mfa.store_challenge(chal).await.unwrap();
1062        mfa.cleanup_expired_challenges().await.unwrap();
1063        assert_eq!(mfa.get_active_challenge_count().await, 0);
1064    }
1065
1066    #[tokio::test]
1067    async fn test_guard_and_store_succeeds() {
1068        let mfa = make_mfa();
1069        let chal = make_challenge("guard_user");
1070        mfa.guard_and_store(chal).await.unwrap();
1071        assert_eq!(mfa.get_active_challenge_count().await, 1);
1072    }
1073
1074    // ── get_available_methods ───────────────────────────────────────────
1075
1076    #[tokio::test]
1077    async fn test_get_available_methods_none() {
1078        let mfa = make_mfa();
1079        let methods = mfa.get_available_methods("nobody").await.unwrap();
1080        // Only backup codes might be default-available or might be empty
1081        // Either way this shouldn't error
1082        assert!(methods.len() <= 4);
1083    }
1084
1085    #[tokio::test]
1086    async fn test_get_available_methods_with_totp() {
1087        let mfa = make_mfa();
1088        let _secret = mfa.totp.generate_secret("totp_user").await.unwrap();
1089        let methods = mfa.get_available_methods("totp_user").await.unwrap();
1090        assert!(methods.contains(&MfaMethod::Totp));
1091    }
1092
1093    #[tokio::test]
1094    async fn test_perform_method_fallback_uses_api_enrolled_totp() {
1095        let storage: Arc<dyn AuthStorage> = Arc::new(MemoryStorage::new());
1096        let mfa = MfaManager::new(storage.clone());
1097        let api_secret = base32::encode(base32::Alphabet::Rfc4648 { padding: true }, &[42; 20]);
1098
1099        storage
1100            .store_kv("mfa_secret:api_totp_user", api_secret.as_bytes(), None)
1101            .await
1102            .unwrap();
1103
1104        let fallback = mfa
1105            .perform_method_fallback("api_totp_user", MfaMethod::Email, &[MfaMethod::Totp])
1106            .await
1107            .unwrap();
1108
1109        assert_eq!(fallback.fallback_method, MfaMethod::Totp);
1110        assert!(matches!(fallback.challenge, MethodChallenge::Totp { .. }));
1111    }
1112
1113    // ── step-up authentication ──────────────────────────────────────────
1114
1115    #[tokio::test]
1116    async fn test_cross_method_step_accepts_valid_code() {
1117        let mfa = make_mfa();
1118        let secret = mfa.totp.generate_secret("ok_user").await.unwrap();
1119        let cross = mfa
1120            .initiate_step_up_authentication("ok_user", &[MfaMethod::Totp], RiskLevel::Medium)
1121            .await
1122            .unwrap();
1123        let code = mfa.totp.generate_code(&secret).await.unwrap();
1124        let res = mfa
1125            .complete_cross_method_step(&cross.id, MfaMethod::Totp, &code)
1126            .await
1127            .unwrap();
1128        assert!(res.success, "a valid TOTP code must complete the step (error={:?})", res.error);
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    #[tokio::test]
1292    async fn test_totp_generate_qr_code() {
1293        let mfa = make_mfa();
1294        let secret = mfa.totp.generate_secret("totp5").await.unwrap();
1295        let qr = mfa
1296            .totp
1297            .generate_qr_code("totp5", "AuthFramework", &secret)
1298            .await
1299            .unwrap();
1300        assert!(qr.contains("otpauth://"));
1301    }
1302
1303    // ── Backup codes sub-module ─────────────────────────────────────────
1304
1305    #[tokio::test]
1306    async fn test_backup_codes_generate() {
1307        let mfa = make_mfa();
1308        let codes = mfa.backup_codes.generate_codes("bc1", 10).await.unwrap();
1309        assert_eq!(codes.len(), 10);
1310    }
1311
1312    #[tokio::test]
1313    async fn test_backup_codes_verify() {
1314        let mfa = make_mfa();
1315        let codes = mfa.backup_codes.generate_codes("bc2", 5).await.unwrap();
1316        let code = codes[0].clone();
1317        assert!(mfa.backup_codes.verify_code("bc2", &code).await.unwrap());
1318        // Code should be consumed — second verify should fail
1319        assert!(!mfa.backup_codes.verify_code("bc2", &code).await.unwrap());
1320    }
1321
1322    #[tokio::test]
1323    async fn test_backup_codes_remaining_count() {
1324        let mfa = make_mfa();
1325        mfa.backup_codes.generate_codes("bc3", 5).await.unwrap();
1326        assert_eq!(
1327            mfa.backup_codes.get_remaining_count("bc3").await.unwrap(),
1328            5
1329        );
1330    }
1331
1332    #[tokio::test]
1333    async fn test_backup_codes_verify_wrong_code() {
1334        let mfa = make_mfa();
1335        mfa.backup_codes.generate_codes("bc4", 5).await.unwrap();
1336        assert!(
1337            !mfa.backup_codes
1338                .verify_code("bc4", "WRONGCODE")
1339                .await
1340                .unwrap()
1341        );
1342    }
1343
1344    #[tokio::test]
1345    async fn test_backup_codes_regenerate() {
1346        let mfa = make_mfa();
1347        let old = mfa.backup_codes.generate_codes("bc5", 5).await.unwrap();
1348        let new = mfa.backup_codes.regenerate_codes("bc5", 5).await.unwrap();
1349        assert_ne!(old, new);
1350    }
1351
1352    #[tokio::test]
1353    async fn test_backup_codes_has_codes() {
1354        let mfa = make_mfa();
1355        assert!(!mfa.backup_codes.has_backup_codes("nobody").await.unwrap());
1356        mfa.backup_codes.generate_codes("bc6", 3).await.unwrap();
1357        assert!(mfa.backup_codes.has_backup_codes("bc6").await.unwrap());
1358    }
1359
1360    // ── Email MFA sub-module ────────────────────────────────────────────
1361
1362    #[tokio::test]
1363    async fn test_email_register_and_has_email() {
1364        let mfa = make_mfa();
1365        assert!(!mfa.email.has_email("em1").await.unwrap());
1366        mfa.email
1367            .register_email("em1", "test@example.com")
1368            .await
1369            .unwrap();
1370        assert!(mfa.email.has_email("em1").await.unwrap());
1371    }
1372
1373    #[tokio::test]
1374    async fn test_email_get_user_email() {
1375        let mfa = make_mfa();
1376        mfa.email
1377            .register_email("em2", "em2@example.com")
1378            .await
1379            .unwrap();
1380        let email = mfa.email.get_user_email("em2").await.unwrap();
1381        assert_eq!(email.as_deref(), Some("em2@example.com"));
1382    }
1383
1384    #[tokio::test]
1385    async fn test_email_get_user_email_none() {
1386        let mfa = make_mfa();
1387        let email = mfa.email.get_user_email("nobody").await.unwrap();
1388        assert!(email.is_none());
1389    }
1390
1391    #[tokio::test]
1392    async fn test_email_initiate_challenge() {
1393        let mfa = make_mfa();
1394        mfa.email
1395            .register_email("em3", "em3@example.com")
1396            .await
1397            .unwrap();
1398        let challenge_id = mfa.email.initiate_challenge("em3").await.unwrap();
1399        assert!(!challenge_id.is_empty());
1400    }
1401
1402    #[tokio::test]
1403    async fn test_email_generate_and_verify_code() {
1404        let mfa = make_mfa();
1405        mfa.email
1406            .register_email("em4", "em4@example.com")
1407            .await
1408            .unwrap();
1409        let cid = mfa.email.initiate_challenge("em4").await.unwrap();
1410        let code = mfa.email.generate_code(&cid).await.unwrap();
1411        assert!(mfa.email.verify_code(&cid, &code).await.unwrap());
1412    }
1413
1414    #[tokio::test]
1415    async fn test_email_verify_wrong_code() {
1416        let mfa = make_mfa();
1417        mfa.email
1418            .register_email("em5", "em5@example.com")
1419            .await
1420            .unwrap();
1421        let cid = mfa.email.initiate_challenge("em5").await.unwrap();
1422        let _code = mfa.email.generate_code(&cid).await.unwrap();
1423        assert!(!mfa.email.verify_code(&cid, "000000").await.unwrap());
1424    }
1425
1426    // ── SMS MFA sub-module ──────────────────────────────────────────────
1427
1428    #[tokio::test]
1429    async fn test_sms_register_and_has_phone() {
1430        let mfa = make_mfa();
1431        assert!(!mfa.sms.has_phone_number("sms1").await.unwrap());
1432        mfa.sms
1433            .register_phone_number("sms1", "+1234567890")
1434            .await
1435            .unwrap();
1436        assert!(mfa.sms.has_phone_number("sms1").await.unwrap());
1437    }
1438
1439    #[tokio::test]
1440    async fn test_sms_get_user_phone() {
1441        let mfa = make_mfa();
1442        mfa.sms
1443            .register_phone_number("sms2", "+9876543210")
1444            .await
1445            .unwrap();
1446        let phone = mfa.sms.get_user_phone("sms2").await.unwrap();
1447        assert_eq!(phone.as_deref(), Some("+9876543210"));
1448    }
1449
1450    #[tokio::test]
1451    async fn test_sms_get_user_phone_none() {
1452        let mfa = make_mfa();
1453        let phone = mfa.sms.get_user_phone("nobody").await.unwrap();
1454        assert!(phone.is_none());
1455    }
1456
1457    #[tokio::test]
1458    async fn test_sms_initiate_challenge() {
1459        let mfa = make_mfa();
1460        mfa.sms
1461            .register_phone_number("sms3", "+1111111111")
1462            .await
1463            .unwrap();
1464        let cid = mfa.sms.initiate_challenge("sms3").await.unwrap();
1465        assert!(!cid.is_empty());
1466    }
1467
1468    #[tokio::test]
1469    async fn test_sms_generate_and_verify_code() {
1470        let mfa = make_mfa();
1471        mfa.sms
1472            .register_phone_number("sms4", "+2222222222")
1473            .await
1474            .unwrap();
1475        let cid = mfa.sms.initiate_challenge("sms4").await.unwrap();
1476        let code = mfa.sms.generate_code(&cid).await.unwrap();
1477        assert!(mfa.sms.verify_code(&cid, &code).await.unwrap());
1478    }
1479
1480    #[tokio::test]
1481    async fn test_sms_verify_wrong_code() {
1482        let mfa = make_mfa();
1483        mfa.sms
1484            .register_phone_number("sms5", "+3333333333")
1485            .await
1486            .unwrap();
1487        let cid = mfa.sms.initiate_challenge("sms5").await.unwrap();
1488        let _code = mfa.sms.generate_code(&cid).await.unwrap();
1489        assert!(!mfa.sms.verify_code(&cid, "000000").await.unwrap());
1490    }
1491}