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, KeyInit, 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
1030    /// The emergency-bypass signature is HMAC-SHA256 (RFC 4231 test case 2: key "Jefe").
1031    #[test]
1032    fn emergency_bypass_signature_known_answer() {
1033        let sig =
1034            MfaManager::sign_emergency_bypass_payload(b"Jefe", "what do ya want for nothing?")
1035                .unwrap();
1036        assert_eq!(
1037            sig,
1038            "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"
1039        );
1040    }
1041
1042    use crate::storage::MemoryStorage;
1043
1044    fn make_mfa() -> MfaManager {
1045        MfaManager::new(Arc::new(MemoryStorage::new()))
1046    }
1047
1048    fn make_challenge(user_id: &str) -> MfaChallenge {
1049        use crate::methods::{MfaChallenge, MfaType};
1050        MfaChallenge {
1051            id: format!("chal_{}", uuid::Uuid::new_v4()),
1052            mfa_type: MfaType::Totp,
1053            user_id: user_id.to_string(),
1054            created_at: chrono::Utc::now(),
1055            expires_at: chrono::Utc::now() + chrono::Duration::minutes(5),
1056            attempts: 0,
1057            max_attempts: 3,
1058            code_hash: None,
1059            message: None,
1060            data: HashMap::new(),
1061        }
1062    }
1063
1064    // ── store / get / remove challenge ──────────────────────────────────
1065
1066    #[tokio::test]
1067    async fn test_store_and_get_challenge() {
1068        let mfa = make_mfa();
1069        let chal = make_challenge("u1");
1070        let id = chal.id.clone();
1071        mfa.store_challenge(chal).await.unwrap();
1072        let retrieved = mfa.get_challenge(&id).await.unwrap();
1073        assert!(retrieved.is_some());
1074        assert_eq!(retrieved.unwrap().user_id, "u1");
1075    }
1076
1077    #[tokio::test]
1078    async fn test_remove_challenge() {
1079        let mfa = make_mfa();
1080        let chal = make_challenge("u2");
1081        let id = chal.id.clone();
1082        mfa.store_challenge(chal).await.unwrap();
1083        mfa.remove_challenge(&id).await.unwrap();
1084        assert!(mfa.get_challenge(&id).await.unwrap().is_none());
1085    }
1086
1087    #[tokio::test]
1088    async fn test_get_challenge_nonexistent() {
1089        let mfa = make_mfa();
1090        assert!(mfa.get_challenge("ghost").await.unwrap().is_none());
1091    }
1092
1093    #[tokio::test]
1094    async fn test_get_active_challenge_count() {
1095        let mfa = make_mfa();
1096        assert_eq!(mfa.get_active_challenge_count().await, 0);
1097        mfa.store_challenge(make_challenge("u3")).await.unwrap();
1098        assert_eq!(mfa.get_active_challenge_count().await, 1);
1099    }
1100
1101    #[tokio::test]
1102    async fn test_cleanup_expired_challenges() {
1103        let mfa = make_mfa();
1104        let mut chal = make_challenge("u4");
1105        chal.expires_at = chrono::Utc::now() - chrono::Duration::minutes(1);
1106        mfa.store_challenge(chal).await.unwrap();
1107        mfa.cleanup_expired_challenges().await.unwrap();
1108        assert_eq!(mfa.get_active_challenge_count().await, 0);
1109    }
1110
1111    #[tokio::test]
1112    async fn test_guard_and_store_succeeds() {
1113        let mfa = make_mfa();
1114        let chal = make_challenge("guard_user");
1115        mfa.guard_and_store(chal).await.unwrap();
1116        assert_eq!(mfa.get_active_challenge_count().await, 1);
1117    }
1118
1119    // ── get_available_methods ───────────────────────────────────────────
1120
1121    #[tokio::test]
1122    async fn test_get_available_methods_none() {
1123        let mfa = make_mfa();
1124        let methods = mfa.get_available_methods("nobody").await.unwrap();
1125        // Only backup codes might be default-available or might be empty
1126        // Either way this shouldn't error
1127        assert!(methods.len() <= 4);
1128    }
1129
1130    #[tokio::test]
1131    async fn test_get_available_methods_with_totp() {
1132        let mfa = make_mfa();
1133        let _secret = mfa.totp.generate_secret("totp_user").await.unwrap();
1134        let methods = mfa.get_available_methods("totp_user").await.unwrap();
1135        assert!(methods.contains(&MfaMethod::Totp));
1136    }
1137
1138    #[tokio::test]
1139    async fn test_perform_method_fallback_uses_api_enrolled_totp() {
1140        let storage: Arc<dyn AuthStorage> = Arc::new(MemoryStorage::new());
1141        let mfa = MfaManager::new(storage.clone());
1142        let api_secret = base32::encode(base32::Alphabet::Rfc4648 { padding: true }, &[42; 20]);
1143
1144        storage
1145            .store_kv("mfa_secret:api_totp_user", api_secret.as_bytes(), None)
1146            .await
1147            .unwrap();
1148
1149        let fallback = mfa
1150            .perform_method_fallback("api_totp_user", MfaMethod::Email, &[MfaMethod::Totp])
1151            .await
1152            .unwrap();
1153
1154        assert_eq!(fallback.fallback_method, MfaMethod::Totp);
1155        assert!(matches!(fallback.challenge, MethodChallenge::Totp { .. }));
1156    }
1157
1158    // ── step-up authentication ──────────────────────────────────────────
1159
1160    #[tokio::test]
1161    async fn test_cross_method_step_accepts_valid_code() {
1162        let mfa = make_mfa();
1163        let secret = mfa.totp.generate_secret("ok_user").await.unwrap();
1164        let cross = mfa
1165            .initiate_step_up_authentication("ok_user", &[MfaMethod::Totp], RiskLevel::Medium)
1166            .await
1167            .unwrap();
1168        let code = mfa.totp.generate_code(&secret).await.unwrap();
1169        let res = mfa
1170            .complete_cross_method_step(&cross.id, MfaMethod::Totp, &code)
1171            .await
1172            .unwrap();
1173        assert!(
1174            res.success,
1175            "a valid TOTP code must complete the step (error={:?})",
1176            res.error
1177        );
1178    }
1179
1180    #[tokio::test]
1181    async fn test_cross_method_step_rejects_invalid_code() {
1182        let mfa = make_mfa();
1183        let _secret = mfa.totp.generate_secret("bypass_user").await.unwrap();
1184        let cross = mfa
1185            .initiate_step_up_authentication("bypass_user", &[MfaMethod::Totp], RiskLevel::Medium)
1186            .await
1187            .unwrap();
1188        // Malformed on purpose: TOTP verify_code returns Ok(false) for any non-6-char code,
1189        // so this is deterministic and cannot collide with a real TOTP value.
1190        let res = mfa
1191            .complete_cross_method_step(&cross.id, MfaMethod::Totp, "garbage")
1192            .await
1193            .unwrap();
1194        assert!(
1195            !res.success,
1196            "an invalid TOTP code must NOT complete a step-up MFA step (success={})",
1197            res.success
1198        );
1199    }
1200
1201    #[tokio::test]
1202    async fn test_initiate_step_up_authentication() {
1203        let mfa = make_mfa();
1204        // Setup TOTP for user
1205        let _secret = mfa.totp.generate_secret("step_user").await.unwrap();
1206
1207        let cross = mfa
1208            .initiate_step_up_authentication("step_user", &[MfaMethod::Totp], RiskLevel::Medium)
1209            .await
1210            .unwrap();
1211        assert_eq!(cross.user_id, "step_user");
1212        assert_eq!(cross.risk_level, RiskLevel::Medium);
1213    }
1214
1215    /// Helper to create an admin user profile in storage so `user_has_admin_role` passes.
1216    async fn setup_admin(storage: &Arc<dyn AuthStorage>, user_id: &str) {
1217        let profile = serde_json::json!({
1218            "user_id": user_id,
1219            "username": user_id,
1220            "roles": ["admin"]
1221        });
1222        let key = format!("user:{}", user_id);
1223        storage
1224            .store_kv(&key, profile.to_string().as_bytes(), None)
1225            .await
1226            .unwrap();
1227    }
1228
1229    // ── emergency bypass ────────────────────────────────────────────────
1230
1231    #[tokio::test]
1232    async fn test_generate_and_use_emergency_bypass() {
1233        let _env = crate::testing::test_infrastructure::TestEnvironmentGuard::new()
1234            .with_custom_var(
1235                "AUTHFRAMEWORK_EMERGENCY_BYPASS_SECRET",
1236                "this-is-a-very-long-test-secret-that-is-at-least-32-bytes",
1237            );
1238        let storage: Arc<dyn AuthStorage> = Arc::new(MemoryStorage::new());
1239        let mfa = MfaManager::new(storage.clone());
1240        setup_admin(&storage, "admin1").await;
1241        let token = mfa
1242            .generate_emergency_bypass_token("admin1", "target1", Duration::from_secs(300))
1243            .await
1244            .unwrap();
1245        assert!(!token.is_empty());
1246        let result = mfa.emergency_mfa_bypass("target1", &token).await.unwrap();
1247        assert!(result);
1248    }
1249
1250    #[tokio::test]
1251    async fn test_emergency_bypass_wrong_user() {
1252        let _env = crate::testing::test_infrastructure::TestEnvironmentGuard::new()
1253            .with_custom_var(
1254                "AUTHFRAMEWORK_EMERGENCY_BYPASS_SECRET",
1255                "this-is-a-very-long-test-secret-that-is-at-least-32-bytes",
1256            );
1257        let storage: Arc<dyn AuthStorage> = Arc::new(MemoryStorage::new());
1258        let mfa = MfaManager::new(storage.clone());
1259        setup_admin(&storage, "admin1").await;
1260        let token = mfa
1261            .generate_emergency_bypass_token("admin1", "target1", Duration::from_secs(300))
1262            .await
1263            .unwrap();
1264        let result = mfa
1265            .emergency_mfa_bypass("wrong_user", &token)
1266            .await
1267            .unwrap();
1268        assert!(!result);
1269    }
1270
1271    #[tokio::test]
1272    async fn test_emergency_bypass_invalid_token() {
1273        let mfa = make_mfa();
1274        let result = mfa.emergency_mfa_bypass("user1", "bogus_token").await;
1275        // Should return Ok(false) or Err — either way not Ok(true)
1276        assert!(!result.unwrap_or(false));
1277    }
1278
1279    #[tokio::test]
1280    async fn test_emergency_bypass_non_admin_rejected() {
1281        let _env = crate::testing::test_infrastructure::TestEnvironmentGuard::new()
1282            .with_custom_var(
1283                "AUTHFRAMEWORK_EMERGENCY_BYPASS_SECRET",
1284                "this-is-a-very-long-test-secret-that-is-at-least-32-bytes",
1285            );
1286        let storage: Arc<dyn AuthStorage> = Arc::new(MemoryStorage::new());
1287        let mfa = MfaManager::new(storage.clone());
1288        // Don't set up admin — should fail
1289        let result = mfa
1290            .generate_emergency_bypass_token("notadmin", "target1", Duration::from_secs(300))
1291            .await;
1292        assert!(result.is_err());
1293    }
1294
1295    // ── TOTP sub-module ─────────────────────────────────────────────────
1296
1297    #[tokio::test]
1298    async fn test_totp_generate_secret() {
1299        let mfa = make_mfa();
1300        let secret = mfa.totp.generate_secret("totp1").await.unwrap();
1301        assert!(!secret.is_empty());
1302        assert!(mfa.totp.has_totp_secret("totp1").await.unwrap());
1303    }
1304
1305    #[tokio::test]
1306    async fn test_totp_generate_code() {
1307        let mfa = make_mfa();
1308        let secret = mfa.totp.generate_secret("totp2").await.unwrap();
1309        let code = mfa.totp.generate_code(&secret).await.unwrap();
1310        assert_eq!(code.len(), 6);
1311        assert!(code.chars().all(|c| c.is_ascii_digit()));
1312    }
1313
1314    #[tokio::test]
1315    async fn test_totp_verify_code_success() {
1316        let mfa = make_mfa();
1317        let secret = mfa.totp.generate_secret("totp3").await.unwrap();
1318        let code = mfa.totp.generate_code(&secret).await.unwrap();
1319        assert!(mfa.totp.verify_code("totp3", &code).await.unwrap());
1320    }
1321
1322    #[tokio::test]
1323    async fn test_totp_verify_code_wrong() {
1324        let mfa = make_mfa();
1325        let _secret = mfa.totp.generate_secret("totp4").await.unwrap();
1326        assert!(
1327            !mfa.totp
1328                .verify_code("totp4", "000000")
1329                .await
1330                .unwrap_or(true)
1331        );
1332    }
1333
1334    #[tokio::test]
1335    async fn test_totp_has_no_secret() {
1336        let mfa = make_mfa();
1337        assert!(!mfa.totp.has_totp_secret("nobody").await.unwrap());
1338    }
1339
1340    /// `verify_code` must reject an unenrolled user outright, never silently
1341    /// derive and accept a fallback secret computed purely from the user_id.
1342    /// Proves absence, not just "some code was rejected": computes the
1343    /// specific fallback this method used to derive
1344    /// (`SHA256(user_id || "totp_secret_salt_2024")`, base32-encoded, same
1345    /// as the TOTP secret format `generate_secret` produces), generates the
1346    /// valid code for that derived secret, and submits it -- if the fallback
1347    /// still existed, this specific code would verify as `true`.
1348    #[tokio::test]
1349    async fn test_totp_verify_code_rejects_unenrolled_user_even_with_the_old_derived_code() {
1350        let mfa = make_mfa();
1351        let user_id = "totp_unenrolled_user";
1352
1353        use sha2::{Digest, Sha256};
1354        let mut hasher = Sha256::new();
1355        hasher.update(user_id.as_bytes());
1356        hasher.update(b"totp_secret_salt_2024");
1357        let hash = hasher.finalize();
1358        let would_be_derived_secret =
1359            base32::encode(base32::Alphabet::Rfc4648 { padding: true }, &hash[0..20]);
1360
1361        let code_for_derived_secret = mfa
1362            .totp
1363            .generate_code(&would_be_derived_secret)
1364            .await
1365            .unwrap();
1366
1367        assert!(
1368            !mfa.totp
1369                .verify_code(user_id, &code_for_derived_secret)
1370                .await
1371                .unwrap(),
1372            "an unenrolled user must not be verifiable via the old predictable fallback secret"
1373        );
1374        assert!(!mfa.totp.has_totp_secret(user_id).await.unwrap());
1375    }
1376
1377    /// A user who enrolled via the live `/mfa/setup` API route (which
1378    /// stores under `mfa_secret:{user_id}`) must be verifiable through the
1379    /// same `verify_code` the modular `generate_secret` path uses -- the two
1380    /// routes must agree on where the secret lives, not silently diverge.
1381    #[tokio::test]
1382    async fn test_totp_verify_code_finds_secret_enrolled_via_api_setup_key() {
1383        use crate::storage::MemoryStorage;
1384        let storage: Arc<dyn AuthStorage> = Arc::new(MemoryStorage::new());
1385        let mfa = MfaManager::new(storage.clone());
1386        let user_id = "totp_api_enrolled_user";
1387
1388        // Simulate the live /mfa/setup route's storage key directly, bypassing
1389        // the modular generate_secret path entirely.
1390        let secret = "JBSWY3DPEHPK3PXP".to_string(); // valid base32
1391        storage
1392            .store_kv(&format!("mfa_secret:{}", user_id), secret.as_bytes(), None)
1393            .await
1394            .unwrap();
1395
1396        let code = mfa.totp.generate_code(&secret).await.unwrap();
1397        assert!(
1398            mfa.totp.verify_code(user_id, &code).await.unwrap(),
1399            "verify_code must find a secret enrolled under the API route's key"
1400        );
1401    }
1402
1403    #[tokio::test]
1404    async fn test_totp_generate_qr_code() {
1405        let mfa = make_mfa();
1406        let secret = mfa.totp.generate_secret("totp5").await.unwrap();
1407        let qr = mfa
1408            .totp
1409            .generate_qr_code("totp5", "AuthFramework", &secret)
1410            .await
1411            .unwrap();
1412        assert!(qr.contains("otpauth://"));
1413    }
1414
1415    // ── Backup codes sub-module ─────────────────────────────────────────
1416
1417    #[tokio::test]
1418    async fn test_backup_codes_generate() {
1419        let mfa = make_mfa();
1420        let codes = mfa.backup_codes.generate_codes("bc1", 10).await.unwrap();
1421        assert_eq!(codes.len(), 10);
1422    }
1423
1424    #[tokio::test]
1425    async fn test_backup_codes_verify() {
1426        let mfa = make_mfa();
1427        let codes = mfa.backup_codes.generate_codes("bc2", 5).await.unwrap();
1428        let code = codes[0].clone();
1429        assert!(mfa.backup_codes.verify_code("bc2", &code).await.unwrap());
1430        // Code should be consumed — second verify should fail
1431        assert!(!mfa.backup_codes.verify_code("bc2", &code).await.unwrap());
1432    }
1433
1434    #[tokio::test]
1435    async fn test_backup_codes_remaining_count() {
1436        let mfa = make_mfa();
1437        mfa.backup_codes.generate_codes("bc3", 5).await.unwrap();
1438        assert_eq!(
1439            mfa.backup_codes.get_remaining_count("bc3").await.unwrap(),
1440            5
1441        );
1442    }
1443
1444    #[tokio::test]
1445    async fn test_backup_codes_verify_wrong_code() {
1446        let mfa = make_mfa();
1447        mfa.backup_codes.generate_codes("bc4", 5).await.unwrap();
1448        assert!(
1449            !mfa.backup_codes
1450                .verify_code("bc4", "WRONGCODE")
1451                .await
1452                .unwrap()
1453        );
1454    }
1455
1456    #[tokio::test]
1457    async fn test_backup_codes_regenerate() {
1458        let mfa = make_mfa();
1459        let old = mfa.backup_codes.generate_codes("bc5", 5).await.unwrap();
1460        let new = mfa.backup_codes.regenerate_codes("bc5", 5).await.unwrap();
1461        assert_ne!(old, new);
1462    }
1463
1464    #[tokio::test]
1465    async fn test_backup_codes_has_codes() {
1466        let mfa = make_mfa();
1467        assert!(!mfa.backup_codes.has_backup_codes("nobody").await.unwrap());
1468        mfa.backup_codes.generate_codes("bc6", 3).await.unwrap();
1469        assert!(mfa.backup_codes.has_backup_codes("bc6").await.unwrap());
1470    }
1471
1472    // ── Email MFA sub-module ────────────────────────────────────────────
1473
1474    #[tokio::test]
1475    async fn test_email_register_and_has_email() {
1476        let mfa = make_mfa();
1477        assert!(!mfa.email.has_email("em1").await.unwrap());
1478        mfa.email
1479            .register_email("em1", "test@example.com")
1480            .await
1481            .unwrap();
1482        assert!(mfa.email.has_email("em1").await.unwrap());
1483    }
1484
1485    #[tokio::test]
1486    async fn test_email_get_user_email() {
1487        let mfa = make_mfa();
1488        mfa.email
1489            .register_email("em2", "em2@example.com")
1490            .await
1491            .unwrap();
1492        let email = mfa.email.get_user_email("em2").await.unwrap();
1493        assert_eq!(email.as_deref(), Some("em2@example.com"));
1494    }
1495
1496    #[tokio::test]
1497    async fn test_email_get_user_email_none() {
1498        let mfa = make_mfa();
1499        let email = mfa.email.get_user_email("nobody").await.unwrap();
1500        assert!(email.is_none());
1501    }
1502
1503    #[tokio::test]
1504    async fn test_email_initiate_challenge() {
1505        let mfa = make_mfa();
1506        mfa.email
1507            .register_email("em3", "em3@example.com")
1508            .await
1509            .unwrap();
1510        let challenge_id = mfa.email.initiate_challenge("em3").await.unwrap();
1511        assert!(!challenge_id.is_empty());
1512    }
1513
1514    #[tokio::test]
1515    async fn test_email_generate_and_verify_code() {
1516        let mfa = make_mfa();
1517        mfa.email
1518            .register_email("em4", "em4@example.com")
1519            .await
1520            .unwrap();
1521        let cid = mfa.email.initiate_challenge("em4").await.unwrap();
1522        let code = mfa.email.generate_code(&cid).await.unwrap();
1523        assert!(mfa.email.verify_code(&cid, &code).await.unwrap());
1524    }
1525
1526    #[tokio::test]
1527    async fn test_email_verify_wrong_code() {
1528        let mfa = make_mfa();
1529        mfa.email
1530            .register_email("em5", "em5@example.com")
1531            .await
1532            .unwrap();
1533        let cid = mfa.email.initiate_challenge("em5").await.unwrap();
1534        let _code = mfa.email.generate_code(&cid).await.unwrap();
1535        assert!(!mfa.email.verify_code(&cid, "000000").await.unwrap());
1536    }
1537
1538    // ── SMS MFA sub-module ──────────────────────────────────────────────
1539
1540    #[tokio::test]
1541    async fn test_sms_register_and_has_phone() {
1542        let mfa = make_mfa();
1543        assert!(!mfa.sms.has_phone_number("sms1").await.unwrap());
1544        mfa.sms
1545            .register_phone_number("sms1", "+1234567890")
1546            .await
1547            .unwrap();
1548        assert!(mfa.sms.has_phone_number("sms1").await.unwrap());
1549    }
1550
1551    #[tokio::test]
1552    async fn test_sms_get_user_phone() {
1553        let mfa = make_mfa();
1554        mfa.sms
1555            .register_phone_number("sms2", "+9876543210")
1556            .await
1557            .unwrap();
1558        let phone = mfa.sms.get_user_phone("sms2").await.unwrap();
1559        assert_eq!(phone.as_deref(), Some("+9876543210"));
1560    }
1561
1562    #[tokio::test]
1563    async fn test_sms_get_user_phone_none() {
1564        let mfa = make_mfa();
1565        let phone = mfa.sms.get_user_phone("nobody").await.unwrap();
1566        assert!(phone.is_none());
1567    }
1568
1569    #[tokio::test]
1570    async fn test_sms_initiate_challenge() {
1571        let mfa = make_mfa();
1572        mfa.sms
1573            .register_phone_number("sms3", "+1111111111")
1574            .await
1575            .unwrap();
1576        let cid = mfa.sms.initiate_challenge("sms3").await.unwrap();
1577        assert!(!cid.is_empty());
1578    }
1579
1580    #[tokio::test]
1581    async fn test_sms_generate_and_verify_code() {
1582        let mfa = make_mfa();
1583        mfa.sms
1584            .register_phone_number("sms4", "+2222222222")
1585            .await
1586            .unwrap();
1587        let cid = mfa.sms.initiate_challenge("sms4").await.unwrap();
1588        let code = mfa.sms.generate_code(&cid).await.unwrap();
1589        assert!(mfa.sms.verify_code(&cid, &code).await.unwrap());
1590    }
1591
1592    #[tokio::test]
1593    async fn test_sms_verify_wrong_code() {
1594        let mfa = make_mfa();
1595        mfa.sms
1596            .register_phone_number("sms5", "+3333333333")
1597            .await
1598            .unwrap();
1599        let cid = mfa.sms.initiate_challenge("sms5").await.unwrap();
1600        let _code = mfa.sms.generate_code(&cid).await.unwrap();
1601        assert!(!mfa.sms.verify_code(&cid, "000000").await.unwrap());
1602    }
1603
1604    // ── verify_challenge_code: expiry gate ──────────────────────────────
1605    //
1606    // Replaces tests/vulnerability_testing_analysis.rs (issue #11), which
1607    // claimed (in a println!-only, zero-assertion test) that this expiry
1608    // check was absent. It is not: `verify_challenge_code` checks
1609    // `challenge.is_expired()` before dispatching to any sub-manager. These
1610    // tests assert that directly, against the real storage-backed code path
1611    // (Email, which stores a plaintext code under a KV key verified by
1612    // `constant_time_compare`), rather than printing a claim nobody checks.
1613
1614    async fn store_email_code(mfa: &MfaManager, challenge_id: &str, code: &str) {
1615        let key = format!("email_challenge:{}:code", challenge_id);
1616        mfa.storage
1617            .store_kv(&key, code.as_bytes(), None)
1618            .await
1619            .unwrap();
1620    }
1621
1622    fn make_email_challenge(
1623        user_id: &str,
1624        expires_at: chrono::DateTime<chrono::Utc>,
1625    ) -> MfaChallenge {
1626        use crate::methods::MfaType;
1627        MfaChallenge {
1628            id: format!("chal_{}", uuid::Uuid::new_v4()),
1629            mfa_type: MfaType::Email {
1630                email_address: format!("{user_id}@example.com"),
1631            },
1632            user_id: user_id.to_string(),
1633            created_at: chrono::Utc::now(),
1634            expires_at,
1635            attempts: 0,
1636            max_attempts: 3,
1637            code_hash: None,
1638            message: None,
1639            data: HashMap::new(),
1640        }
1641    }
1642
1643    #[tokio::test]
1644    async fn test_verify_challenge_code_accepts_correct_code_before_expiry() {
1645        let mfa = make_mfa();
1646        let challenge =
1647            make_email_challenge("expiry1", chrono::Utc::now() + chrono::Duration::minutes(5));
1648        store_email_code(&mfa, &challenge.id, "123456").await;
1649        assert!(
1650            mfa.verify_challenge_code(&challenge, "123456")
1651                .await
1652                .unwrap()
1653        );
1654    }
1655
1656    #[tokio::test]
1657    async fn test_verify_challenge_code_rejects_correct_code_after_expiry() {
1658        let mfa = make_mfa();
1659        let challenge =
1660            make_email_challenge("expiry2", chrono::Utc::now() - chrono::Duration::seconds(1));
1661        store_email_code(&mfa, &challenge.id, "123456").await;
1662        // The code is objectively correct -- only expiry distinguishes this
1663        // from the accept case above. If this ever returns `true`, a
1664        // reviewer must treat it as a live MFA-bypass vulnerability, not a
1665        // test-quality issue.
1666        assert!(
1667            !mfa.verify_challenge_code(&challenge, "123456")
1668                .await
1669                .unwrap()
1670        );
1671    }
1672
1673    #[tokio::test]
1674    async fn test_verify_challenge_code_expiry_check_runs_before_storage_lookup() {
1675        // Positive control for the test above: an expired challenge is
1676        // rejected even when no code was ever stored for it, proving the
1677        // expiry check short-circuits before the storage-dependent branches
1678        // (so an expired/garbage challenge can't be used to probe storage
1679        // state via timing or error differences).
1680        let mfa = make_mfa();
1681        let challenge =
1682            make_email_challenge("expiry3", chrono::Utc::now() - chrono::Duration::seconds(1));
1683        assert!(
1684            !mfa.verify_challenge_code(&challenge, "123456")
1685                .await
1686                .unwrap()
1687        );
1688    }
1689}