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