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