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 std::collections::HashMap;
12use std::sync::Arc;
13use tokio::sync::RwLock;
14use tracing::debug;
15
16pub use backup_codes::BackupCodesManager;
17pub use email::EmailManager;
18pub use totp::TotpManager;
19
20// Export SMSKit manager as the primary SMS interface
21pub use sms_kit::{
22    RateLimitConfig as SmsKitRateLimitConfig, SmsKitConfig, SmsKitManager, SmsKitProvider,
23    SmsKitProviderConfig, WebhookConfig,
24};
25
26// Re-export as SmsManager for backward compatibility
27pub use sms_kit::SmsKitManager as SmsManager;
28
29/// Centralized multi-factor authentication (MFA) manager.
30///
31/// `MfaManager` coordinates all MFA operations across different authentication
32/// factors including TOTP, SMS, email, and backup codes. It provides a unified
33/// interface for MFA setup, challenge generation, and verification while
34/// supporting multiple MFA methods simultaneously.
35///
36/// # Supported MFA Methods
37///
38/// - **TOTP (Time-based OTP)**: RFC 6238 compliant authenticator apps
39/// - **SMS**: Text message-based verification codes
40/// - **Email**: Email-based verification codes
41/// - **Backup Codes**: Single-use recovery codes
42///
43/// # Multi-Method Support
44///
45/// Users can enable multiple MFA methods simultaneously, providing flexibility
46/// and redundancy. The manager handles method coordination and fallback scenarios.
47///
48/// # Security Features
49///
50/// - **Challenge Expiration**: Time-limited challenges prevent replay attacks
51/// - **Rate Limiting**: Prevents brute force attacks on MFA codes
52/// - **Secure Code Generation**: Cryptographically secure random code generation
53/// - **Method Validation**: Validates MFA setup before enabling
54/// - **Audit Logging**: Comprehensive logging of all MFA operations
55///
56/// # Cross-Method Operations
57///
58/// The manager supports advanced scenarios like:
59/// - Method fallback when primary method fails
60/// - Cross-method challenge validation
61/// - Method strength assessment
62/// - Risk-based MFA requirements
63///
64/// # Example
65///
66/// ```rust,no_run
67/// use auth_framework::auth_modular::mfa::MfaManager;
68/// use std::sync::Arc;
69///
70/// # async fn example(storage: Arc<dyn auth_framework::storage::AuthStorage>) -> Result<(), Box<dyn std::error::Error>> {
71/// // Create MFA manager with storage backend
72/// let mfa_manager = MfaManager::new(storage);
73///
74/// // Generate a TOTP secret for a user (store it and show QR code to the user)
75/// let secret = mfa_manager.totp.generate_secret("user123").await?;
76///
77/// // Verify a TOTP code during an authentication attempt
78/// let is_valid = mfa_manager.totp.verify_code("user123", "123456").await?;
79/// # Ok(())
80/// # }
81/// ```
82///
83/// # Thread Safety
84///
85/// The MFA manager is designed for concurrent use and safely coordinates
86/// access to underlying MFA method implementations.
87///
88/// # Storage Integration
89///
90/// Integrates with the framework's storage system to persist:
91/// - User MFA method configurations
92/// - Active challenges
93/// - Usage statistics and audit logs
94/// - Backup codes and secrets
95pub struct MfaManager {
96    /// TOTP manager
97    pub totp: TotpManager,
98
99    /// SMS manager (using SMSKit)
100    pub sms: SmsKitManager,
101
102    /// Email manager
103    pub email: EmailManager,
104
105    /// Backup codes manager
106    pub backup_codes: BackupCodesManager,
107
108    /// Active MFA challenges
109    challenges: Arc<RwLock<HashMap<String, MfaChallenge>>>,
110
111    /// Storage backend
112    /// PRODUCTION FIX: Available for direct manager operations and fallback scenarios
113    storage: Arc<dyn AuthStorage>,
114}
115
116impl MfaManager {
117    /// Create a new MFA manager
118    pub fn new(storage: Arc<dyn AuthStorage>) -> Self {
119        Self {
120            totp: TotpManager::new(storage.clone()),
121            sms: SmsKitManager::new(storage.clone()),
122            email: EmailManager::new(storage.clone()),
123            backup_codes: BackupCodesManager::new(storage.clone()),
124            challenges: Arc::new(RwLock::new(HashMap::new())),
125            storage,
126        }
127    }
128
129    /// Create a new MFA manager with SMSKit configuration
130    pub fn new_with_smskit_config(
131        storage: Arc<dyn AuthStorage>,
132        smskit_config: SmsKitConfig,
133    ) -> Result<Self> {
134        Ok(Self {
135            totp: TotpManager::new(storage.clone()),
136            sms: SmsKitManager::new_with_config(storage.clone(), smskit_config)?,
137            email: EmailManager::new(storage.clone()),
138            backup_codes: BackupCodesManager::new(storage.clone()),
139            challenges: Arc::new(RwLock::new(HashMap::new())),
140            storage,
141        })
142    }
143
144    /// Store an MFA challenge
145    pub async fn store_challenge(&self, challenge: MfaChallenge) -> Result<()> {
146        debug!("Storing MFA challenge '{}'", challenge.id);
147
148        let mut challenges = self.challenges.write().await;
149        challenges.insert(challenge.id.clone(), challenge);
150
151        Ok(())
152    }
153
154    /// Get an MFA challenge
155    pub async fn get_challenge(&self, challenge_id: &str) -> Result<Option<MfaChallenge>> {
156        let challenges = self.challenges.read().await;
157        Ok(challenges.get(challenge_id).cloned())
158    }
159
160    /// Remove an MFA challenge
161    pub async fn remove_challenge(&self, challenge_id: &str) -> Result<()> {
162        debug!("Removing MFA challenge '{}'", challenge_id);
163
164        let mut challenges = self.challenges.write().await;
165        challenges.remove(challenge_id);
166
167        Ok(())
168    }
169
170    /// Clean up expired challenges
171    pub async fn cleanup_expired_challenges(&self) -> Result<()> {
172        debug!("Cleaning up expired MFA challenges");
173
174        let mut challenges = self.challenges.write().await;
175        let now = chrono::Utc::now();
176        challenges.retain(|_, challenge| challenge.expires_at > now);
177
178        Ok(())
179    }
180
181    /// Get count of active challenges
182    pub async fn get_active_challenge_count(&self) -> usize {
183        self.challenges.read().await.len()
184    }
185
186    /// MFA CROSS-METHOD OPERATIONS: Step-up authentication with multiple factors
187    pub async fn initiate_step_up_authentication(
188        &self,
189        user_id: &str,
190        required_methods: &[MfaMethod],
191        risk_level: RiskLevel,
192    ) -> Result<CrossMethodChallenge> {
193        tracing::info!(
194            "Initiating step-up authentication for user: {} with risk level: {:?}",
195            user_id,
196            risk_level
197        );
198
199        // Determine required methods based on risk level
200        let adaptive_methods = self
201            .adapt_required_methods(required_methods, risk_level.clone())
202            .await?;
203
204        // Generate challenge ID
205        let challenge_id = uuid::Uuid::new_v4().to_string();
206
207        // Create individual challenges for each method
208        let mut method_challenges = HashMap::new();
209        let mut completion_status = HashMap::new();
210
211        for method in &adaptive_methods {
212            let method_challenge = match method {
213                MfaMethod::Totp => {
214                    completion_status.insert(method.clone(), false);
215                    self.create_totp_challenge(user_id, &challenge_id).await?
216                }
217                MfaMethod::Sms => {
218                    completion_status.insert(method.clone(), false);
219                    self.create_sms_challenge(user_id, &challenge_id).await?
220                }
221                MfaMethod::Email => {
222                    completion_status.insert(method.clone(), false);
223                    self.create_email_challenge(user_id, &challenge_id).await?
224                }
225                MfaMethod::BackupCode => {
226                    completion_status.insert(method.clone(), false);
227                    MethodChallenge::BackupCode {
228                        challenge_id: format!("{}-backup", challenge_id),
229                        instructions: "Enter one of your backup codes".to_string(),
230                    }
231                }
232            };
233
234            method_challenges.insert(method.clone(), method_challenge);
235        }
236
237        let cross_method_challenge = CrossMethodChallenge {
238            id: challenge_id,
239            user_id: user_id.to_string(),
240            required_methods: adaptive_methods.clone(),
241            method_challenges,
242            completion_status,
243            risk_level,
244            expires_at: chrono::Utc::now() + chrono::Duration::minutes(10),
245            created_at: chrono::Utc::now(),
246        };
247
248        // Store the cross-method challenge
249        {
250            let mut challenges = self.challenges.write().await;
251            challenges.insert(
252                cross_method_challenge.id.clone(),
253                MfaChallenge {
254                    id: cross_method_challenge.id.clone(),
255                    mfa_type: crate::methods::MfaType::Totp, // Placeholder for cross-method challenge
256                    user_id: user_id.to_string(),
257                    expires_at: cross_method_challenge.expires_at,
258                    message: Some("Complete all required authentication methods".to_string()),
259                    data: {
260                        let mut data = HashMap::new();
261                        data.insert(
262                            "cross_method_data".to_string(),
263                            serde_json::to_value(&cross_method_challenge)?,
264                        );
265                        data
266                    },
267                },
268            );
269        }
270
271        tracing::info!(
272            "Step-up authentication initiated with {} methods",
273            adaptive_methods.len()
274        );
275        Ok(cross_method_challenge)
276    }
277
278    /// Complete a specific method within a cross-method challenge
279    pub async fn complete_cross_method_step(
280        &self,
281        challenge_id: &str,
282        method: MfaMethod,
283        response: &str,
284    ) -> Result<CrossMethodCompletionResult> {
285        tracing::debug!(
286            "Completing cross-method step: {:?} for challenge: {}",
287            method,
288            challenge_id
289        );
290
291        // Retrieve and update the cross-method challenge
292        let mut cross_challenge = self.get_cross_method_challenge(challenge_id).await?;
293
294        if cross_challenge.completion_status.get(&method) == Some(&true) {
295            return Ok(CrossMethodCompletionResult {
296                method,
297                success: true,
298                remaining_methods: self.get_remaining_methods(&cross_challenge),
299                all_completed: false,
300                error: Some("Method already completed".to_string()),
301            });
302        }
303
304        // Verify the specific method response
305        let verification_result = match method {
306            MfaMethod::Totp => {
307                self.totp
308                    .verify_code(&cross_challenge.user_id, response)
309                    .await
310            }
311            MfaMethod::Sms => {
312                self.sms
313                    .verify_code(&cross_challenge.user_id, response)
314                    .await
315            }
316            MfaMethod::Email => {
317                self.email
318                    .verify_code(&cross_challenge.user_id, response)
319                    .await
320            }
321            MfaMethod::BackupCode => {
322                self.backup_codes
323                    .verify_code(&cross_challenge.user_id, response)
324                    .await
325            }
326        };
327
328        // `verify_code` returns Ok(false) for a wrong code, so `is_ok()` is NOT success.
329        let success = matches!(verification_result, Ok(true));
330
331        if success {
332            // Mark method as completed
333            cross_challenge
334                .completion_status
335                .insert(method.clone(), true);
336
337            // Update stored challenge
338            self.update_cross_method_challenge(&cross_challenge).await?;
339
340            tracing::info!("Cross-method step completed successfully: {:?}", method);
341        } else {
342            tracing::warn!(
343                "Cross-method step failed: {:?} - {:?}",
344                method,
345                verification_result
346            );
347        }
348
349        let remaining_methods = self.get_remaining_methods(&cross_challenge);
350        let all_completed = remaining_methods.is_empty();
351
352        if all_completed {
353            tracing::info!(
354                "All cross-method authentication steps completed for challenge: {}",
355                challenge_id
356            );
357            // Clean up the challenge
358            self.remove_challenge(challenge_id).await?;
359        }
360
361        Ok(CrossMethodCompletionResult {
362            method,
363            success,
364            remaining_methods,
365            all_completed,
366            error: if success {
367                None
368            } else {
369                Some(match &verification_result {
370                    Ok(_) => "Verification failed: invalid code".to_string(),
371                    Err(e) => format!("Verification failed: {:?}", e),
372                })
373            },
374        })
375    }
376
377    /// Get available MFA methods for a user
378    pub async fn get_available_methods(&self, user_id: &str) -> Result<Vec<MfaMethod>> {
379        tracing::debug!("Getting available MFA methods for user: {}", user_id);
380
381        let mut available_methods = Vec::new();
382
383        // Check TOTP availability
384        if self.totp.has_totp_secret(user_id).await.unwrap_or(false) {
385            available_methods.push(MfaMethod::Totp);
386        }
387
388        // Check SMS availability
389        if self.sms.has_phone_number(user_id).await.unwrap_or(false) {
390            available_methods.push(MfaMethod::Sms);
391        }
392
393        // Check email availability
394        if self.email.has_email(user_id).await.unwrap_or(false) {
395            available_methods.push(MfaMethod::Email);
396        }
397
398        // Check backup codes availability
399        if self
400            .backup_codes
401            .has_backup_codes(user_id)
402            .await
403            .unwrap_or(false)
404        {
405            available_methods.push(MfaMethod::BackupCode);
406        }
407
408        tracing::debug!(
409            "Available methods for user {}: {:?}",
410            user_id,
411            available_methods
412        );
413        Ok(available_methods)
414    }
415
416    /// Perform method fallback when primary method fails
417    pub async fn perform_method_fallback(
418        &self,
419        user_id: &str,
420        failed_method: MfaMethod,
421        fallback_order: &[MfaMethod],
422    ) -> Result<MethodFallbackResult> {
423        tracing::info!(
424            "Performing method fallback for user: {} after failed method: {:?}",
425            user_id,
426            failed_method
427        );
428
429        let available_methods = self.get_available_methods(user_id).await?;
430
431        // Find the first available fallback method
432        for fallback_method in fallback_order {
433            if available_methods.contains(fallback_method) && fallback_method != &failed_method {
434                // Create challenge for fallback method
435                let fallback_challenge = match fallback_method {
436                    MfaMethod::Totp => self.create_totp_challenge(user_id, "fallback").await?,
437                    MfaMethod::Sms => self.create_sms_challenge(user_id, "fallback").await?,
438                    MfaMethod::Email => self.create_email_challenge(user_id, "fallback").await?,
439                    MfaMethod::BackupCode => MethodChallenge::BackupCode {
440                        challenge_id: "fallback-backup".to_string(),
441                        instructions: "Enter one of your backup codes".to_string(),
442                    },
443                };
444
445                tracing::info!(
446                    "Fallback method activated: {:?} for user: {}",
447                    fallback_method,
448                    user_id
449                );
450
451                return Ok(MethodFallbackResult {
452                    fallback_method: fallback_method.clone(),
453                    challenge: fallback_challenge,
454                    remaining_fallbacks: fallback_order
455                        .iter()
456                        .skip_while(|&m| m != fallback_method)
457                        .skip(1)
458                        .filter(|&m| available_methods.contains(m))
459                        .cloned()
460                        .collect(),
461                });
462            }
463        }
464
465        Err(crate::errors::AuthError::validation(
466            "No fallback methods available",
467        ))
468    }
469
470    /// Adaptive MFA: Adjust required methods based on risk level
471    async fn adapt_required_methods(
472        &self,
473        base_methods: &[MfaMethod],
474        risk_level: RiskLevel,
475    ) -> Result<Vec<MfaMethod>> {
476        let mut adapted_methods = base_methods.to_vec();
477
478        match risk_level {
479            RiskLevel::Low => {
480                // Low risk: single factor is sufficient
481                adapted_methods.truncate(1);
482            }
483            RiskLevel::Medium => {
484                // Medium risk: use base methods as-is
485                // No changes needed
486            }
487            RiskLevel::High => {
488                // High risk: require additional verification
489                if !adapted_methods.contains(&MfaMethod::Email) {
490                    adapted_methods.push(MfaMethod::Email);
491                }
492                if !adapted_methods.contains(&MfaMethod::Sms) {
493                    adapted_methods.push(MfaMethod::Sms);
494                }
495            }
496            RiskLevel::Critical => {
497                // Critical risk: require all available methods
498                adapted_methods = vec![MfaMethod::Totp, MfaMethod::Sms, MfaMethod::Email];
499            }
500        }
501
502        Ok(adapted_methods)
503    }
504
505    /// Helper methods for cross-method operations
506    async fn get_cross_method_challenge(&self, challenge_id: &str) -> Result<CrossMethodChallenge> {
507        let challenges = self.challenges.read().await;
508        let challenge = challenges
509            .get(challenge_id)
510            .ok_or_else(|| crate::errors::AuthError::validation("Challenge not found"))?;
511
512        let cross_challenge: CrossMethodChallenge =
513            if let Some(cross_method_value) = challenge.data.get("cross_method_data") {
514                serde_json::from_value(cross_method_value.clone())?
515            } else {
516                return Err(crate::errors::AuthError::validation(
517                    "Invalid cross-method challenge data",
518                ));
519            };
520        Ok(cross_challenge)
521    }
522
523    async fn update_cross_method_challenge(
524        &self,
525        cross_challenge: &CrossMethodChallenge,
526    ) -> Result<()> {
527        let mut challenges = self.challenges.write().await;
528        if let Some(challenge) = challenges.get_mut(&cross_challenge.id) {
529            challenge.data.insert(
530                "cross_method_data".to_string(),
531                serde_json::to_value(cross_challenge)?,
532            );
533        }
534        Ok(())
535    }
536
537    fn get_remaining_methods(&self, cross_challenge: &CrossMethodChallenge) -> Vec<MfaMethod> {
538        cross_challenge
539            .completion_status
540            .iter()
541            .filter_map(|(method, &completed)| {
542                if !completed {
543                    Some(method.clone())
544                } else {
545                    None
546                }
547            })
548            .collect()
549    }
550
551    /// Create individual method challenges
552    async fn create_totp_challenge(
553        &self,
554        _user_id: &str,
555        challenge_prefix: &str,
556    ) -> Result<MethodChallenge> {
557        Ok(MethodChallenge::Totp {
558            challenge_id: format!("{}-totp", challenge_prefix),
559            instructions: "Enter the 6-digit code from your authenticator app".to_string(),
560        })
561    }
562
563    async fn create_sms_challenge(
564        &self,
565        user_id: &str,
566        challenge_prefix: &str,
567    ) -> Result<MethodChallenge> {
568        let _code = self.sms.send_verification_code(user_id).await?;
569        Ok(MethodChallenge::Sms {
570            challenge_id: format!("{}-sms", challenge_prefix),
571            instructions: "Enter the verification code sent to your phone".to_string(),
572            phone_hint: self
573                .get_phone_hint(user_id)
574                .await
575                .unwrap_or_else(|_| "***-***-****".to_string()),
576        })
577    }
578
579    async fn create_email_challenge(
580        &self,
581        user_id: &str,
582        challenge_prefix: &str,
583    ) -> Result<MethodChallenge> {
584        let _code = self.email.send_email_code(user_id).await?;
585        Ok(MethodChallenge::Email {
586            challenge_id: format!("{}-email", challenge_prefix),
587            instructions: "Enter the verification code sent to your email".to_string(),
588            email_hint: self
589                .get_email_hint(user_id)
590                .await
591                .unwrap_or_else(|_| "****@****.com".to_string()),
592        })
593    }
594
595    async fn get_phone_hint(&self, user_id: &str) -> Result<String> {
596        // Mock implementation - in production, get from storage
597        Ok(format!("***-***-{}", &user_id[..4]))
598    }
599
600    async fn get_email_hint(&self, user_id: &str) -> Result<String> {
601        // Mock implementation - in production, get from storage
602        Ok(format!("{}****@****.com", &user_id[..2]))
603    }
604
605    /// Emergency MFA bypass using direct storage access
606    /// This method provides a way to recover when all MFA methods fail
607    pub async fn emergency_mfa_bypass(&self, user_id: &str, admin_token: &str) -> Result<bool> {
608        tracing::warn!("Emergency MFA bypass requested for user: {}", user_id);
609
610        // Verify admin token through direct storage access
611        let admin_key = format!("emergency_admin:{}", admin_token);
612        if let Some(_admin_data) = self.storage.get_kv(&admin_key).await? {
613            tracing::info!("Emergency MFA bypass granted for user: {}", user_id);
614
615            // Store bypass record for audit purposes
616            let bypass_key = format!("mfa_bypass:{}:{}", user_id, chrono::Utc::now().timestamp());
617            let bypass_data = format!(
618                "Emergency bypass by admin token at {}",
619                chrono::Utc::now().to_rfc3339()
620            );
621            self.storage
622                .store_kv(
623                    &bypass_key,
624                    bypass_data.as_bytes(),
625                    Some(std::time::Duration::from_secs(86400)),
626                )
627                .await?;
628
629            Ok(true)
630        } else {
631            tracing::error!("Invalid admin token for emergency MFA bypass");
632            Ok(false)
633        }
634    }
635}
636
637/// MFA method types
638#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
639pub enum MfaMethod {
640    Totp,
641    Sms,
642    Email,
643    BackupCode,
644}
645
646/// Risk levels for adaptive MFA
647#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
648pub enum RiskLevel {
649    Low,
650    Medium,
651    High,
652    Critical,
653}
654
655/// Cross-method challenge combining multiple MFA factors
656#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
657pub struct CrossMethodChallenge {
658    pub id: String,
659    pub user_id: String,
660    pub required_methods: Vec<MfaMethod>,
661    pub method_challenges: HashMap<MfaMethod, MethodChallenge>,
662    pub completion_status: HashMap<MfaMethod, bool>,
663    pub risk_level: RiskLevel,
664    pub expires_at: chrono::DateTime<chrono::Utc>,
665    pub created_at: chrono::DateTime<chrono::Utc>,
666}
667
668/// Individual method challenge
669#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
670pub enum MethodChallenge {
671    Totp {
672        challenge_id: String,
673        instructions: String,
674    },
675    Sms {
676        challenge_id: String,
677        instructions: String,
678        phone_hint: String,
679    },
680    Email {
681        challenge_id: String,
682        instructions: String,
683        email_hint: String,
684    },
685    BackupCode {
686        challenge_id: String,
687        instructions: String,
688    },
689}
690
691/// Result of cross-method completion attempt
692#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
693pub struct CrossMethodCompletionResult {
694    pub method: MfaMethod,
695    pub success: bool,
696    pub remaining_methods: Vec<MfaMethod>,
697    pub all_completed: bool,
698    pub error: Option<String>,
699}
700
701/// Result of method fallback operation
702#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
703pub struct MethodFallbackResult {
704    pub fallback_method: MfaMethod,
705    pub challenge: MethodChallenge,
706    pub remaining_fallbacks: Vec<MfaMethod>,
707}
708
709#[cfg(test)]
710mod tests {
711    use super::*;
712    use crate::storage::MemoryStorage;
713
714    fn make_mfa() -> MfaManager {
715        let storage: Arc<dyn AuthStorage> = Arc::new(MemoryStorage::new());
716        MfaManager::new(storage)
717    }
718
719    /// `verify_code` must reject an unenrolled user outright, never silently
720    /// derive and accept a fallback secret computed purely from the user_id.
721    /// Proves absence, not just "some code was rejected": computes the
722    /// specific fallback this method used to derive
723    /// (`SHA256(user_id || "totp_secret_salt_2024")`, base32-encoded, same
724    /// as the TOTP secret format `generate_secret` produces), generates the
725    /// valid code for that derived secret, and submits it -- if the fallback
726    /// still existed, this specific code would verify as `true`.
727    #[tokio::test]
728    async fn test_totp_verify_code_rejects_unenrolled_user_even_with_the_old_derived_code() {
729        let mfa = make_mfa();
730        let user_id = "totp_unenrolled_user";
731
732        use sha2::{Digest, Sha256};
733        let mut hasher = Sha256::new();
734        hasher.update(user_id.as_bytes());
735        hasher.update(b"totp_secret_salt_2024");
736        let hash = hasher.finalize();
737        let would_be_derived_secret =
738            base32::encode(base32::Alphabet::Rfc4648 { padding: true }, &hash[0..20]);
739
740        let code_for_derived_secret = mfa
741            .totp
742            .generate_code(&would_be_derived_secret)
743            .await
744            .unwrap();
745
746        assert!(
747            !mfa.totp
748                .verify_code(user_id, &code_for_derived_secret)
749                .await
750                .unwrap(),
751            "an unenrolled user must not be verifiable via the old predictable fallback secret"
752        );
753    }
754
755    #[tokio::test]
756    async fn test_cross_method_step_rejects_invalid_code() {
757        let mfa = make_mfa();
758        let _secret = mfa.totp.generate_secret("bypass_user").await.unwrap();
759        let cross = mfa
760            .initiate_step_up_authentication("bypass_user", &[MfaMethod::Totp], RiskLevel::Medium)
761            .await
762            .unwrap();
763        let res = mfa
764            .complete_cross_method_step(&cross.id, MfaMethod::Totp, "garbage")
765            .await
766            .unwrap();
767        assert!(
768            !res.success,
769            "an invalid TOTP code must NOT complete a step-up MFA step (success={})",
770            res.success
771        );
772    }
773
774    #[tokio::test]
775    async fn test_cross_method_step_accepts_valid_code() {
776        let storage: Arc<dyn AuthStorage> = Arc::new(MemoryStorage::new());
777        let mfa = MfaManager::new(storage.clone());
778        let secret = "JBSWY3DPEHPK3PXP".to_string();
779        storage
780            .store_kv("user:ok_user:totp_secret", secret.as_bytes(), None)
781            .await
782            .unwrap();
783        let cross = mfa
784            .initiate_step_up_authentication("ok_user", &[MfaMethod::Totp], RiskLevel::Medium)
785            .await
786            .unwrap();
787        let code = mfa.totp.generate_code(&secret).await.unwrap();
788        let res = mfa
789            .complete_cross_method_step(&cross.id, MfaMethod::Totp, &code)
790            .await
791            .unwrap();
792        assert!(
793            res.success,
794            "a valid TOTP code must complete the step (error={:?})",
795            res.error
796        );
797    }
798
799    /// Regression test for issue #24: `generate_secret` used to emit a raw,
800    /// non-base32 token (`crate::utils::crypto::generate_token`) that
801    /// `generate_code`/`verify_code` can't decode, so an enrolled user's
802    /// correct codes were always rejected. `generate_secret`'s own output
803    /// must round-trip through `generate_code` and `verify_code`.
804    #[tokio::test]
805    async fn test_generate_secret_output_round_trips_through_generate_and_verify_code() {
806        let mfa = make_mfa();
807        let secret = mfa.totp.generate_secret("roundtrip_user").await.unwrap();
808        let code = mfa
809            .totp
810            .generate_code(&secret)
811            .await
812            .expect("generate_secret's own output must be accepted by generate_code");
813        let verified = mfa.totp.verify_code("roundtrip_user", &code).await.unwrap();
814        assert!(
815            verified,
816            "a code generated from generate_secret's own output must verify successfully"
817        );
818    }
819}