Skip to main content

auth_framework/authentication/
mfa.rs

1//! Multi-Factor Authentication (MFA) implementation.
2//!
3//! This module provides comprehensive MFA support including TOTP, SMS, email,
4//! backup codes, and WebAuthn for enhanced security.
5
6use crate::errors::{AuthError, Result};
7use crate::security::MfaConfig;
8use async_trait::async_trait;
9use ring::rand::SecureRandom;
10use serde::{Deserialize, Serialize};
11use std::time::{SystemTime, UNIX_EPOCH};
12use subtle::ConstantTimeEq;
13use totp_lite::{Sha1, totp};
14use zeroize::Zeroizing;
15
16/// MFA method types
17#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
18pub enum MfaMethodType {
19    Totp,
20    Sms,
21    Email,
22    WebAuthn,
23    BackupCodes,
24}
25
26/// MFA challenge that must be completed
27#[derive(Debug, Clone, Serialize, Deserialize)]
28pub struct MfaChallenge {
29    /// Unique challenge ID
30    pub id: String,
31    /// User ID this challenge belongs to
32    pub user_id: String,
33    /// Type of MFA method
34    pub method_type: MfaMethodType,
35    /// Challenge data (varies by method type)
36    pub challenge_data: MfaChallengeData,
37    /// When the challenge was created
38    pub created_at: SystemTime,
39    /// When the challenge expires
40    pub expires_at: SystemTime,
41    /// Number of attempts made
42    pub attempts: u32,
43    /// Maximum allowed attempts
44    pub max_attempts: u32,
45}
46
47/// Challenge data specific to each MFA method
48#[derive(Debug, Clone, Serialize, Deserialize)]
49pub enum MfaChallengeData {
50    Totp {
51        /// Current time window
52        time_window: u64,
53    },
54    Sms {
55        /// Phone number (masked)
56        phone_number: String,
57        /// Generated code
58        code: String,
59    },
60    Email {
61        /// Email address (masked)
62        email: String,
63        /// Generated code
64        code: String,
65    },
66    WebAuthn {
67        /// Challenge bytes
68        challenge: Vec<u8>,
69        /// Allowed credential IDs
70        allowed_credentials: Vec<String>,
71    },
72    BackupCodes {
73        /// Remaining backup codes count
74        remaining_codes: u32,
75    },
76}
77
78/// MFA method configuration for a user
79#[derive(Debug, Clone, Serialize, Deserialize)]
80pub struct UserMfaMethod {
81    /// Unique method ID
82    pub id: String,
83    /// User ID
84    pub user_id: String,
85    /// Method type
86    pub method_type: MfaMethodType,
87    /// Method-specific data
88    pub method_data: MfaMethodData,
89    /// Display name for the method
90    pub display_name: String,
91    /// Whether this is the primary method
92    pub is_primary: bool,
93    /// Whether this method is enabled
94    pub is_enabled: bool,
95    /// When the method was created
96    pub created_at: SystemTime,
97    /// When the method was last used
98    pub last_used_at: Option<SystemTime>,
99}
100
101/// Method-specific configuration data
102#[derive(Clone, Serialize, Deserialize)]
103pub enum MfaMethodData {
104    Totp {
105        /// Base32-encoded secret key
106        secret_key: Zeroizing<String>,
107        /// QR code URL for setup
108        qr_code_url: String,
109    },
110    Sms {
111        /// Phone number
112        phone_number: String,
113        /// Whether phone number is verified
114        is_verified: bool,
115    },
116    Email {
117        /// Email address
118        email: String,
119        /// Whether email is verified
120        is_verified: bool,
121    },
122    WebAuthn {
123        /// Credential ID
124        credential_id: String,
125        /// Public key
126        public_key: Vec<u8>,
127        /// Counter for replay protection
128        counter: u32,
129    },
130    BackupCodes {
131        /// List of backup codes (hashed)
132        codes: Vec<String>,
133        /// Number of codes used
134        used_count: u32,
135    },
136}
137
138impl std::fmt::Debug for MfaMethodData {
139    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
140        use crate::utils::redact::redacted;
141        match self {
142            Self::Totp {
143                secret_key,
144                qr_code_url,
145            } => f
146                .debug_struct("Totp")
147                .field("secret_key", secret_key)
148                .field("qr_code_url", &redacted(qr_code_url))
149                .finish(),
150            Self::Sms {
151                phone_number,
152                is_verified,
153            } => f
154                .debug_struct("Sms")
155                .field("phone_number", phone_number)
156                .field("is_verified", is_verified)
157                .finish(),
158            Self::Email { email, is_verified } => f
159                .debug_struct("Email")
160                .field("email", email)
161                .field("is_verified", is_verified)
162                .finish(),
163            Self::WebAuthn {
164                credential_id,
165                public_key,
166                counter,
167            } => f
168                .debug_struct("WebAuthn")
169                .field("credential_id", credential_id)
170                .field("public_key", public_key)
171                .field("counter", counter)
172                .finish(),
173            Self::BackupCodes { codes, used_count } => f
174                .debug_struct("BackupCodes")
175                .field("codes", &redacted(codes))
176                .field("used_count", used_count)
177                .finish(),
178        }
179    }
180}
181
182/// MFA verification result
183#[derive(Debug, Clone)]
184pub struct MfaVerificationResult {
185    /// Whether verification succeeded
186    pub success: bool,
187    /// Method that was used
188    pub method_type: MfaMethodType,
189    /// Remaining attempts (if failed)
190    pub remaining_attempts: Option<u32>,
191    /// Error message (if failed)
192    pub error_message: Option<String>,
193}
194
195/// TOTP (Time-based One-Time Password) implementation
196pub struct TotpProvider {
197    config: crate::security::TotpConfig,
198}
199
200impl TotpProvider {
201    pub fn new(config: crate::security::TotpConfig) -> Self {
202        Self { config }
203    }
204
205    /// Generate a new TOTP secret using cryptographically secure random
206    pub fn generate_secret(&self) -> crate::Result<String> {
207        use ring::rand::{SecureRandom, SystemRandom};
208        let rng = SystemRandom::new();
209        let mut secret = [0u8; 20];
210        rng.fill(&mut secret).map_err(|_| {
211            crate::errors::AuthError::crypto("Failed to generate secure TOTP secret".to_string())
212        })?;
213        Ok(base32::encode(
214            base32::Alphabet::Rfc4648 { padding: true },
215            &secret,
216        ))
217    }
218
219    /// Generate QR code URL for TOTP setup
220    pub fn generate_qr_code_url(&self, secret: &str, user_identifier: &str) -> String {
221        format!(
222            "otpauth://totp/{}:{}?secret={}&issuer={}&digits={}&period={}",
223            urlencoding::encode(&self.config.issuer),
224            urlencoding::encode(user_identifier),
225            secret,
226            urlencoding::encode(&self.config.issuer),
227            self.config.digits,
228            self.config.period
229        )
230    }
231
232    /// Generate TOTP code for the current time window
233    pub fn generate_code(&self, secret: &str, time_step: Option<u64>) -> Result<String> {
234        if secret.trim().is_empty() {
235            return Err(AuthError::validation("TOTP secret cannot be empty"));
236        }
237
238        let secret_bytes = base32::decode(base32::Alphabet::Rfc4648 { padding: true }, secret)
239            .ok_or_else(|| AuthError::validation("Invalid TOTP secret"))?;
240
241        let time_step = time_step.unwrap_or_else(|| {
242            SystemTime::now()
243                .duration_since(UNIX_EPOCH)
244                .unwrap_or_default()
245                .as_secs()
246                / self.config.period
247        });
248
249        // Convert time step to Unix timestamp for totp-lite
250        // totp-lite expects Unix timestamp, not time step
251        let unix_timestamp = time_step.checked_mul(self.config.period).ok_or_else(|| {
252            AuthError::InvalidInput("Time step too large for conversion".to_string())
253        })?;
254
255        // Use totp-lite for proper TOTP generation
256        let totp_value = totp::<Sha1>(&secret_bytes, unix_timestamp);
257
258        // totp-lite returns variable length string, parse and format according to config
259        let parsed_value: u32 = totp_value
260            .parse()
261            .map_err(|_| AuthError::validation("TOTP generation error"))?;
262
263        // Format to the specified number of digits
264        Ok(format!(
265            "{:0width$}",
266            parsed_value % 10_u32.pow(self.config.digits.into()),
267            width = self.config.digits as usize
268        ))
269    }
270
271    /// Verify TOTP code with time window tolerance
272    pub fn verify_code(&self, secret: &str, code: &str, time_window: Option<u64>) -> Result<bool> {
273        // First validate the secret by trying to decode it
274        let _secret_bytes = base32::decode(base32::Alphabet::Rfc4648 { padding: true }, secret)
275            .ok_or_else(|| AuthError::validation("Invalid TOTP secret"))?;
276
277        let current_time_step = if let Some(time) = time_window {
278            time / self.config.period
279        } else {
280            SystemTime::now()
281                .duration_since(UNIX_EPOCH)
282                .unwrap_or_default()
283                .as_secs()
284                / self.config.period
285        };
286
287        // Check current time step and ±1 time step for clock skew tolerance
288        // Use constant-time comparison to prevent timing attacks
289        let mut matched = false;
290        for step_offset in [-1i64, 0, 1] {
291            let time_step_i64 = current_time_step as i64 + step_offset;
292            // Skip negative time steps to avoid u64 overflow
293            if time_step_i64 < 0 {
294                continue;
295            }
296            let time_step = time_step_i64 as u64;
297            let expected_code = self.generate_code(secret, Some(time_step))?;
298            let eq: bool = expected_code.as_bytes().ct_eq(code.as_bytes()).into();
299            matched |= eq;
300        }
301
302        Ok(matched)
303    }
304
305    /// Verify TOTP code with configurable time window
306    pub fn verify_totp(&self, secret: &str, token: &str, window: u8) -> Result<bool> {
307        let now = SystemTime::now()
308            .duration_since(UNIX_EPOCH)
309            .map_err(|_| AuthError::validation("System time error"))?
310            .as_secs()
311            / self.config.period;
312
313        // Check within the specified time window using constant-time comparison
314
315        for i in 0..=window {
316            // Check current and positive offset
317            if i == 0 {
318                if let Ok(expected_code) = self.generate_code(secret, Some(now))
319                    && expected_code.as_bytes().ct_eq(token.as_bytes()).into()
320                {
321                    return Ok(true);
322                }
323            } else {
324                // Check both positive and negative offsets
325                for offset in [i as i64, -(i as i64)] {
326                    let time_step_i64 = now as i64 + offset;
327                    // Skip negative time steps to avoid u64 overflow
328                    if time_step_i64 < 0 {
329                        continue;
330                    }
331                    let time_step = time_step_i64 as u64;
332                    if let Ok(expected_code) = self.generate_code(secret, Some(time_step))
333                        && expected_code.as_bytes().ct_eq(token.as_bytes()).into()
334                    {
335                        return Ok(true);
336                    }
337                }
338            }
339        }
340        Ok(false)
341    }
342}
343
344/// SMS provider for sending verification codes
345#[async_trait]
346pub trait SmsProvider: Send + Sync {
347    async fn send_code(&self, phone_number: &str, code: &str) -> Result<()>;
348}
349
350/// Email provider for sending verification codes
351#[async_trait]
352pub trait EmailProvider: Send + Sync {
353    async fn send_code(&self, email: &str, code: &str) -> Result<()>;
354}
355
356/// Backup codes provider
357pub struct BackupCodesProvider;
358
359impl BackupCodesProvider {
360    /// Generate backup codes
361    pub fn generate_codes(count: u8) -> Vec<String> {
362        let rng = ring::rand::SystemRandom::new();
363        (0..count)
364            .map(|_| {
365                let mut buf = [0u8; 4];
366                rng.fill(&mut buf).expect("system RNG failure");
367                let val1 = u16::from_le_bytes([buf[0], buf[1]]) % 8999 + 1000;
368                let val2 = u16::from_le_bytes([buf[2], buf[3]]) % 8999 + 1000;
369                format!("{:04}-{:04}", val1, val2)
370            })
371            .collect()
372    }
373
374    /// Hash backup codes for storage
375    pub fn hash_codes(codes: &[String]) -> Result<Vec<String>> {
376        use sha2::{Digest, Sha256};
377        codes
378            .iter()
379            .map(|code| {
380                let hash = Sha256::digest(code.as_bytes());
381                Ok(hex::encode(hash))
382            })
383            .collect()
384    }
385
386    /// Verify backup code
387    pub fn verify_code(hashed_codes: &[String], provided_code: &str) -> bool {
388        use sha2::{Digest, Sha256};
389        let provided_hash = hex::encode(Sha256::digest(provided_code.as_bytes()));
390        let provided_bytes = provided_hash.as_bytes();
391        hashed_codes
392            .iter()
393            .any(|h| h.as_bytes().ct_eq(provided_bytes).into())
394    }
395}
396
397/// MFA storage trait
398#[async_trait]
399pub trait MfaStorage: Send + Sync {
400    /// Store user MFA method
401    async fn store_mfa_method(&self, method: &UserMfaMethod) -> Result<()>;
402
403    /// Get user's MFA methods
404    async fn get_user_mfa_methods(&self, user_id: &str) -> Result<Vec<UserMfaMethod>>;
405
406    /// Update MFA method
407    async fn update_mfa_method(&self, method: &UserMfaMethod) -> Result<()>;
408
409    /// Delete MFA method
410    async fn delete_mfa_method(&self, method_id: &str) -> Result<()>;
411
412    /// Store MFA challenge
413    async fn store_mfa_challenge(&self, challenge: &MfaChallenge) -> Result<()>;
414
415    /// Get MFA challenge
416    async fn get_mfa_challenge(&self, challenge_id: &str) -> Result<Option<MfaChallenge>>;
417
418    /// Update MFA challenge (for attempt counting)
419    async fn update_mfa_challenge(&self, challenge: &MfaChallenge) -> Result<()>;
420
421    /// Delete MFA challenge
422    async fn delete_mfa_challenge(&self, challenge_id: &str) -> Result<()>;
423
424    /// Clean up expired challenges
425    async fn cleanup_expired_challenges(&self) -> Result<()>;
426}
427
428/// MFA manager for handling multi-factor authentication
429pub struct MfaManager<S: MfaStorage> {
430    storage: S,
431    config: MfaConfig,
432    totp_provider: TotpProvider,
433    sms_provider: Option<Box<dyn SmsProvider>>,
434    email_provider: Option<Box<dyn EmailProvider>>,
435}
436
437impl<S: MfaStorage> MfaManager<S> {
438    /// Create a new MFA manager
439    pub fn new(storage: S, config: MfaConfig) -> Self {
440        let totp_provider = TotpProvider::new(config.totp_config.clone());
441
442        Self {
443            storage,
444            config,
445            totp_provider,
446            sms_provider: None,
447            email_provider: None,
448        }
449    }
450
451    /// Set SMS provider
452    pub fn with_sms_provider(mut self, provider: Box<dyn SmsProvider>) -> Self {
453        self.sms_provider = Some(provider);
454        self
455    }
456
457    /// Set email provider
458    pub fn with_email_provider(mut self, provider: Box<dyn EmailProvider>) -> Self {
459        self.email_provider = Some(provider);
460        self
461    }
462
463    /// Setup TOTP for a user
464    pub async fn setup_totp(&self, user_id: &str, user_identifier: &str) -> Result<UserMfaMethod> {
465        let secret = self.totp_provider.generate_secret()?;
466        let qr_code_url = self
467            .totp_provider
468            .generate_qr_code_url(&secret, user_identifier);
469
470        let method = UserMfaMethod {
471            id: uuid::Uuid::new_v4().to_string(),
472            user_id: user_id.to_string(),
473            method_type: MfaMethodType::Totp,
474            method_data: MfaMethodData::Totp {
475                secret_key: secret.into(),
476                qr_code_url,
477            },
478            display_name: "Authenticator App".to_string(),
479            is_primary: false,
480            is_enabled: false, // Will be enabled after verification
481            created_at: SystemTime::now(),
482            last_used_at: None,
483        };
484
485        self.storage.store_mfa_method(&method).await?;
486        Ok(method)
487    }
488
489    /// Setup SMS MFA for a user
490    pub async fn setup_sms(&self, user_id: &str, phone_number: &str) -> Result<UserMfaMethod> {
491        let method = UserMfaMethod {
492            id: uuid::Uuid::new_v4().to_string(),
493            user_id: user_id.to_string(),
494            method_type: MfaMethodType::Sms,
495            method_data: MfaMethodData::Sms {
496                phone_number: phone_number.to_string(),
497                is_verified: false,
498            },
499            display_name: format!("SMS to {}", mask_phone_number(phone_number)),
500            is_primary: false,
501            is_enabled: false,
502            created_at: SystemTime::now(),
503            last_used_at: None,
504        };
505
506        self.storage.store_mfa_method(&method).await?;
507        Ok(method)
508    }
509
510    /// Generate backup codes for a user
511    pub async fn generate_backup_codes(
512        &self,
513        user_id: &str,
514    ) -> Result<(UserMfaMethod, Vec<String>)> {
515        let codes = BackupCodesProvider::generate_codes(10);
516        let hashed_codes = BackupCodesProvider::hash_codes(&codes)?;
517
518        let method = UserMfaMethod {
519            id: uuid::Uuid::new_v4().to_string(),
520            user_id: user_id.to_string(),
521            method_type: MfaMethodType::BackupCodes,
522            method_data: MfaMethodData::BackupCodes {
523                codes: hashed_codes,
524                used_count: 0,
525            },
526            display_name: "Backup Codes".to_string(),
527            is_primary: false,
528            is_enabled: true,
529            created_at: SystemTime::now(),
530            last_used_at: None,
531        };
532
533        self.storage.store_mfa_method(&method).await?;
534        Ok((method, codes))
535    }
536
537    /// Create MFA challenge for user
538    pub async fn create_challenge(
539        &self,
540        user_id: &str,
541        method_type: MfaMethodType,
542    ) -> Result<MfaChallenge> {
543        let user_methods = self.storage.get_user_mfa_methods(user_id).await?;
544        let method = user_methods
545            .iter()
546            .find(|m| m.method_type == method_type && m.is_enabled)
547            .ok_or_else(|| AuthError::validation("MFA method not found or not enabled"))?;
548
549        let challenge_data = match &method.method_data {
550            MfaMethodData::Totp { .. } => MfaChallengeData::Totp {
551                time_window: SystemTime::now()
552                    .duration_since(UNIX_EPOCH)
553                    .unwrap_or_default()
554                    .as_secs()
555                    / self.config.totp_config.period,
556            },
557            MfaMethodData::Sms { phone_number, .. } => {
558                let code = generate_numeric_code(6);
559                if let Some(sms_provider) = &self.sms_provider {
560                    sms_provider.send_code(phone_number, &code).await?;
561                }
562                MfaChallengeData::Sms {
563                    phone_number: mask_phone_number(phone_number),
564                    code,
565                }
566            }
567            MfaMethodData::Email { email, .. } => {
568                let code = generate_numeric_code(6);
569                if let Some(email_provider) = &self.email_provider {
570                    email_provider.send_code(email, &code).await?;
571                }
572                MfaChallengeData::Email {
573                    email: mask_email(email),
574                    code,
575                }
576            }
577            MfaMethodData::BackupCodes { .. } => {
578                MfaChallengeData::BackupCodes { remaining_codes: 8 } // Default backup codes count
579            }
580            _ => return Err(AuthError::validation("Unsupported MFA method type")),
581        };
582
583        let challenge = MfaChallenge {
584            id: uuid::Uuid::new_v4().to_string(),
585            user_id: user_id.to_string(),
586            method_type,
587            challenge_data,
588            created_at: SystemTime::now(),
589            expires_at: SystemTime::now() + std::time::Duration::from_secs(300), // 5 minutes
590            attempts: 0,
591            max_attempts: 3,
592        };
593
594        self.storage.store_mfa_challenge(&challenge).await?;
595        Ok(challenge)
596    }
597
598    /// Verify MFA challenge
599    pub async fn verify_challenge(
600        &self,
601        challenge_id: &str,
602        response: &str,
603    ) -> Result<MfaVerificationResult> {
604        let mut challenge = self
605            .storage
606            .get_mfa_challenge(challenge_id)
607            .await?
608            .ok_or_else(|| AuthError::validation("MFA challenge not found"))?;
609
610        // Check if challenge has expired
611        if SystemTime::now() > challenge.expires_at {
612            self.storage.delete_mfa_challenge(challenge_id).await?;
613            return Ok(MfaVerificationResult {
614                success: false,
615                method_type: challenge.method_type,
616                remaining_attempts: None,
617                error_message: Some("Challenge has expired".to_string()),
618            });
619        }
620
621        // Check if max attempts exceeded
622        if challenge.attempts >= challenge.max_attempts {
623            self.storage.delete_mfa_challenge(challenge_id).await?;
624            return Ok(MfaVerificationResult {
625                success: false,
626                method_type: challenge.method_type,
627                remaining_attempts: Some(0),
628                error_message: Some("Maximum attempts exceeded".to_string()),
629            });
630        }
631
632        challenge.attempts += 1;
633
634        let success = match &challenge.challenge_data {
635            MfaChallengeData::Totp { time_window } => {
636                let user_methods = self
637                    .storage
638                    .get_user_mfa_methods(&challenge.user_id)
639                    .await?;
640                if let Some(method) = user_methods
641                    .iter()
642                    .find(|m| m.method_type == MfaMethodType::Totp)
643                {
644                    if let MfaMethodData::Totp { secret_key, .. } = &method.method_data {
645                        self.totp_provider
646                            .verify_code(secret_key, response, Some(*time_window))?
647                    } else {
648                        false
649                    }
650                } else {
651                    false
652                }
653            }
654            MfaChallengeData::Sms { code, .. } => code.as_bytes().ct_eq(response.as_bytes()).into(),
655            MfaChallengeData::Email { code, .. } => {
656                code.as_bytes().ct_eq(response.as_bytes()).into()
657            }
658            MfaChallengeData::BackupCodes { .. } => {
659                let user_methods = self
660                    .storage
661                    .get_user_mfa_methods(&challenge.user_id)
662                    .await?;
663                if let Some(method) = user_methods
664                    .iter()
665                    .find(|m| m.method_type == MfaMethodType::BackupCodes)
666                {
667                    if let MfaMethodData::BackupCodes { codes, .. } = &method.method_data {
668                        BackupCodesProvider::verify_code(codes, response)
669                    } else {
670                        false
671                    }
672                } else {
673                    false
674                }
675            }
676            _ => false,
677        };
678
679        if success {
680            self.storage.delete_mfa_challenge(challenge_id).await?;
681            Ok(MfaVerificationResult {
682                success: true,
683                method_type: challenge.method_type,
684                remaining_attempts: None,
685                error_message: None,
686            })
687        } else {
688            let remaining = challenge.max_attempts.saturating_sub(challenge.attempts);
689            self.storage.update_mfa_challenge(&challenge).await?;
690
691            Ok(MfaVerificationResult {
692                success: false,
693                method_type: challenge.method_type,
694                remaining_attempts: Some(remaining),
695                error_message: Some("Invalid code".to_string()),
696            })
697        }
698    }
699
700    /// Check if user has MFA enabled
701    pub async fn has_mfa_enabled(&self, user_id: &str) -> Result<bool> {
702        let methods = self.storage.get_user_mfa_methods(user_id).await?;
703        Ok(methods.iter().any(|m| m.is_enabled))
704    }
705
706    /// Get user's enabled MFA methods
707    pub async fn get_enabled_methods(&self, user_id: &str) -> Result<Vec<MfaMethodType>> {
708        let methods = self.storage.get_user_mfa_methods(user_id).await?;
709        Ok(methods
710            .iter()
711            .filter(|m| m.is_enabled)
712            .map(|m| m.method_type.clone())
713            .collect())
714    }
715}
716
717/// Generate a numeric code of specified length
718fn generate_numeric_code(length: u8) -> String {
719    let rng = ring::rand::SystemRandom::new();
720    (0..length)
721        .map(|_| {
722            let mut buf = [0u8; 1];
723            rng.fill(&mut buf).expect("system RNG failure");
724            (buf[0] % 10).to_string()
725        })
726        .collect()
727}
728
729/// Mask phone number for display
730fn mask_phone_number(phone: &str) -> String {
731    if phone.len() > 4 {
732        format!("***-***-{}", &phone[phone.len() - 4..])
733    } else {
734        "***-***-****".to_string()
735    }
736}
737
738/// Mask email address for display
739fn mask_email(email: &str) -> String {
740    if let Some(at_pos) = email.find('@') {
741        let (local, domain) = email.split_at(at_pos);
742        if local.len() > 2 {
743            format!("{}***{}", &local[0..1], domain)
744        } else {
745            format!("***{}", domain)
746        }
747    } else {
748        "***@***.***".to_string()
749    }
750}
751
752#[cfg(test)]
753mod tests {
754    use super::*;
755
756    #[test]
757    fn test_totp_generation() {
758        let config = crate::security::TotpConfig::default();
759        let provider = TotpProvider::new(config);
760
761        let secret = provider.generate_secret().unwrap();
762        assert!(!secret.is_empty());
763
764        let code = provider.generate_code(&secret, Some(1)).unwrap();
765        assert_eq!(code.len(), 6);
766
767        // Verify the same code
768        assert!(provider.verify_code(&secret, &code, Some(1)).unwrap());
769
770        // Verify wrong code
771        assert!(!provider.verify_code(&secret, "000000", Some(1)).unwrap());
772    }
773
774    #[test]
775    fn test_backup_codes() {
776        let codes = BackupCodesProvider::generate_codes(5);
777        assert_eq!(codes.len(), 5);
778
779        let hashed = BackupCodesProvider::hash_codes(&codes).unwrap();
780        assert_eq!(hashed.len(), 5);
781
782        // Should verify correctly
783        assert!(BackupCodesProvider::verify_code(&hashed, &codes[0]));
784
785        // Should not verify wrong code
786        assert!(!BackupCodesProvider::verify_code(&hashed, "1234-5678"));
787    }
788
789    #[test]
790    fn test_masking() {
791        assert_eq!(mask_phone_number("+1234567890"), "***-***-7890");
792        assert_eq!(mask_email("user@example.com"), "u***@example.com");
793    }
794}