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