Skip to main content

auth_framework/
utils.rs

1//! Utility functions for the authentication framework.
2use crate::errors::{AuthError, Result};
3use rand::Rng;
4pub use rate_limit::RateLimiter;
5use ring::digest;
6use std::time::{SystemTime, UNIX_EPOCH};
7
8pub(crate) mod redact {
9    //! Helpers for `Debug` impls that must not print secret values.
10    //!
11    //! A field that holds a secret is shown as `<redacted>`; an optional one keeps its shape
12    //! (`None` stays `None`, `Some(..)` becomes `Some(<redacted>)`), so a log line still says whether
13    //! the secret is configured.
14
15    use std::fmt;
16
17    /// What a secret field prints as.
18    pub(crate) enum Redacted {
19        Absent,
20        Present,
21    }
22
23    impl fmt::Debug for Redacted {
24        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
25            match self {
26                Redacted::Absent => f.write_str("None"),
27                Redacted::Present => f.write_str("<redacted>"),
28            }
29        }
30    }
31
32    /// Anything a secret can be stored in.
33    pub(crate) trait Secret {
34        fn redacted(&self) -> Redacted;
35    }
36
37    impl Secret for String {
38        fn redacted(&self) -> Redacted {
39            Redacted::Present
40        }
41    }
42
43    impl Secret for Vec<String> {
44        fn redacted(&self) -> Redacted {
45            Redacted::Present
46        }
47    }
48
49    impl Secret for Vec<u8> {
50        fn redacted(&self) -> Redacted {
51            Redacted::Present
52        }
53    }
54
55    impl<T> Secret for Option<T> {
56        fn redacted(&self) -> Redacted {
57            if self.is_some() {
58                Redacted::Present
59            } else {
60                Redacted::Absent
61            }
62        }
63    }
64
65    /// Maps, sets, JSON values and shared wrappers: the whole container is hidden, keys included (a map
66    /// keyed by a token or session id would print it).
67    impl Secret for serde_json::Value {
68        fn redacted(&self) -> Redacted {
69            Redacted::Present
70        }
71    }
72
73    impl<K, V, S> Secret for std::collections::HashMap<K, V, S> {
74        fn redacted(&self) -> Redacted {
75            Redacted::Present
76        }
77    }
78
79    impl<K, V> Secret for std::collections::BTreeMap<K, V> {
80        fn redacted(&self) -> Redacted {
81            Redacted::Present
82        }
83    }
84
85    impl<T, S> Secret for std::collections::HashSet<T, S> {
86        fn redacted(&self) -> Redacted {
87            Redacted::Present
88        }
89    }
90
91    impl<K: Eq + std::hash::Hash, V> Secret for dashmap::DashMap<K, V> {
92        fn redacted(&self) -> Redacted {
93            Redacted::Present
94        }
95    }
96
97    impl<T: ?Sized> Secret for std::sync::Arc<T> {
98        fn redacted(&self) -> Redacted {
99            Redacted::Present
100        }
101    }
102
103    impl<T: ?Sized> Secret for tokio::sync::RwLock<T> {
104        fn redacted(&self) -> Redacted {
105            Redacted::Present
106        }
107    }
108
109    impl<T: ?Sized> Secret for tokio::sync::Mutex<T> {
110        fn redacted(&self) -> Redacted {
111            Redacted::Present
112        }
113    }
114
115    impl<T: ?Sized> Secret for std::sync::Mutex<T> {
116        fn redacted(&self) -> Redacted {
117            Redacted::Present
118        }
119    }
120
121    impl<T: ?Sized> Secret for std::sync::RwLock<T> {
122        fn redacted(&self) -> Redacted {
123            Redacted::Present
124        }
125    }
126
127    /// The value to hand to `DebugStruct::field` in place of a secret.
128    pub(crate) fn redacted<T: Secret>(value: &T) -> Redacted {
129        value.redacted()
130    }
131
132    /// A short reference to a high-entropy identifier (a session id, a token) that is safe to put in a log
133    /// line: it lets two lines about the same value be matched, and it cannot be turned back into the
134    /// value. Low-entropy secrets (one-time codes, passwords) must not be fingerprinted -- a 32-bit prefix
135    /// of their hash can be brute-forced -- and are logged as `"<redacted>"` instead.
136    pub(crate) struct Fingerprint(String);
137
138    impl fmt::Display for Fingerprint {
139        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
140            f.write_str(&self.0)
141        }
142    }
143
144    impl fmt::Debug for Fingerprint {
145        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
146            f.write_str(&self.0)
147        }
148    }
149
150    /// `sha256:` and the first four bytes of the SHA-256 of `value`, in hex.
151    pub(crate) fn fingerprint(value: &str) -> Fingerprint {
152        use sha2::{Digest, Sha256};
153        let digest = Sha256::digest(value.as_bytes());
154        let mut out = String::from("sha256:");
155        for byte in &digest[..4] {
156            out.push_str(&format!("{byte:02x}"));
157        }
158        Fingerprint(out)
159    }
160
161    /// `scheme://host[:port]` of a URL, for a log line: user info, path, query and fragment are dropped,
162    /// because a webhook URL carries its secret in the path or the query (`hooks.slack.com/services/..`).
163    /// Text that is not an absolute URL is logged as `<invalid url>`.
164    pub(crate) fn url_origin(url: &str) -> String {
165        let Some((scheme, rest)) = url.split_once("://") else {
166            return "<invalid url>".to_string();
167        };
168        let authority = rest.split(['/', '?', '#']).next().unwrap_or("");
169        let host = authority.rsplit('@').next().unwrap_or("");
170        let scheme_ok = !scheme.is_empty()
171            && scheme
172                .chars()
173                .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'));
174        if !scheme_ok || host.is_empty() {
175            return "<invalid url>".to_string();
176        }
177        format!("{scheme}://{host}")
178    }
179
180    #[cfg(test)]
181    mod tests {
182        use super::*;
183
184        #[test]
185        fn url_origin_keeps_only_scheme_and_host() {
186            assert_eq!(
187                url_origin("https://hooks.slack.com/services/T000/B000/SECRET-MARKER"),
188                "https://hooks.slack.com"
189            );
190            assert_eq!(
191                url_origin(
192                    "https://user:SECRET-MARKER@example.com:8443/p?license_key=SECRET-MARKER#f"
193                ),
194                "https://example.com:8443"
195            );
196            assert_eq!(
197                url_origin("https://example.com?key=SECRET-MARKER"),
198                "https://example.com"
199            );
200        }
201
202        #[test]
203        fn url_origin_does_not_echo_text_that_is_not_a_url() {
204            assert_eq!(url_origin("SECRET-MARKER"), "<invalid url>");
205            assert_eq!(url_origin("https:///SECRET-MARKER"), "<invalid url>");
206            assert_eq!(url_origin("://example.com"), "<invalid url>");
207        }
208
209        /// SHA-256("abc") starts ba7816bf (FIPS 180-2 test vector).
210        #[test]
211        fn fingerprint_is_a_prefix_of_the_sha256_digest() {
212            assert_eq!(fingerprint("abc").to_string(), "sha256:ba7816bf");
213            assert_eq!(format!("{:?}", fingerprint("abc")), "sha256:ba7816bf");
214        }
215
216        #[test]
217        fn fingerprint_does_not_contain_the_value() {
218            let secret = "SECRET-MARKER-7f3a9c";
219            assert!(!fingerprint(secret).to_string().contains(secret));
220            assert_ne!(
221                fingerprint(secret).to_string(),
222                fingerprint("other").to_string()
223            );
224        }
225    }
226}
227
228/// Password hashing utilities.
229pub mod password {
230    use super::*;
231
232    /// Hash a password using bcrypt.
233    pub fn hash_password(password: &str) -> Result<String> {
234        bcrypt::hash(password, bcrypt::DEFAULT_COST)
235            .map_err(|e| AuthError::crypto(format!("Password hashing failed: {e}")))
236    }
237
238    /// Verify a password against a hash.
239    pub fn verify_password(password: &str, hash: &str) -> Result<bool> {
240        bcrypt::verify(password, hash)
241            .map_err(|e| AuthError::crypto(format!("Password verification failed: {e}")))
242    }
243
244    /// Generate a secure random password.
245    pub fn generate_password(length: usize) -> String {
246        const CHARSET: &[u8] =
247            b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";
248        let mut rng = rand::rng();
249        (0..length)
250            .map(|_| CHARSET[rng.random_range(0..CHARSET.len())] as char)
251            .collect()
252    }
253
254    /// Check password strength.
255    pub fn check_password_strength(password: &str) -> PasswordStrength {
256        let mut score = 0;
257        let mut feedback = Vec::new();
258
259        // Length check
260        if password.len() >= 8 {
261            score += 1;
262        } else {
263            feedback.push("Password should be at least 8 characters long".to_string());
264        }
265
266        if password.len() >= 12 {
267            score += 1;
268        }
269
270        if password.len() >= 16 {
271            score += 1; // Extra point for very long passwords
272        }
273
274        // Character variety checks
275        if password.chars().any(|c| c.is_lowercase()) {
276            score += 1;
277        } else {
278            feedback.push("Password should contain lowercase letters".to_string());
279        }
280
281        if password.chars().any(|c| c.is_uppercase()) {
282            score += 1;
283        } else {
284            feedback.push("Password should contain uppercase letters".to_string());
285        }
286
287        if password.chars().any(|c| c.is_ascii_digit()) {
288            score += 1;
289        } else {
290            feedback.push("Password should contain numbers".to_string());
291        }
292
293        if password
294            .chars()
295            .any(|c| "!@#$%^&*()_+-=[]{}|;:,.<>?".contains(c))
296        {
297            score += 1;
298        } else {
299            feedback.push("Password should contain special characters".to_string());
300        }
301
302        // Common password check (basic)
303        let common_passwords = ["password", "123456", "password123", "admin", "letmein"];
304        if common_passwords.contains(&password.to_lowercase().as_str()) {
305            score = 0;
306            feedback.push("Password is too common".to_string());
307        }
308
309        let strength = match score {
310            0..=2 => PasswordStrengthLevel::Weak,
311            3..=4 => PasswordStrengthLevel::Medium,
312            5..=6 => PasswordStrengthLevel::Strong,
313            _ => PasswordStrengthLevel::VeryStrong,
314        };
315
316        PasswordStrength {
317            level: strength,
318            score,
319            feedback,
320        }
321    }
322
323    /// Password strength assessment.
324    #[derive(Debug, Clone)]
325    pub struct PasswordStrength {
326        pub level: PasswordStrengthLevel,
327        pub score: u8,
328        pub feedback: Vec<String>,
329    }
330
331    /// Password strength levels.
332    #[derive(Debug, Clone, PartialEq)]
333    pub enum PasswordStrengthLevel {
334        Weak,
335        Medium,
336        Strong,
337        VeryStrong,
338    }
339}
340
341/// Cryptographic utilities.
342pub mod crypto {
343    use super::*;
344
345    /// Generate a secure random string.
346    pub fn generate_random_string(length: usize) -> String {
347        const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
348
349        let mut rng = rand::rng();
350        (0..length)
351            .map(|_| {
352                let idx = rng.random_range(0..CHARSET.len());
353                CHARSET[idx] as char
354            })
355            .collect()
356    }
357
358    /// Generate a secure random byte array.
359    pub fn generate_random_bytes(length: usize) -> Vec<u8> {
360        use rand::RngCore;
361        let mut bytes = vec![0u8; length];
362        rand::rng().fill_bytes(&mut bytes);
363        bytes
364    }
365
366    /// Compute SHA256 hash.
367    pub fn sha256(data: &[u8]) -> Vec<u8> {
368        let digest = digest::digest(&digest::SHA256, data);
369        digest.as_ref().to_vec()
370    }
371
372    /// Compute SHA256 hash and return as hex string.
373    pub fn sha256_hex(data: &[u8]) -> String {
374        hex::encode(sha256(data))
375    }
376
377    /// Generate a secure token.
378    pub fn generate_token(length: usize) -> String {
379        use base64::Engine;
380        base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(generate_random_bytes(length))
381    }
382
383    /// Constant-time string comparison.
384    pub fn constant_time_eq(a: &str, b: &str) -> bool {
385        if a.len() != b.len() {
386            return false;
387        }
388
389        // Use a simple constant-time comparison
390        let mut result = 0u8;
391        for (byte_a, byte_b) in a.as_bytes().iter().zip(b.as_bytes().iter()) {
392            result |= byte_a ^ byte_b;
393        }
394        result == 0
395    }
396}
397
398/// Time utilities.
399pub mod time {
400    use super::*;
401    use std::time::Duration;
402
403    /// Get current Unix timestamp.
404    pub fn current_timestamp() -> u64 {
405        SystemTime::now()
406            .duration_since(UNIX_EPOCH)
407            .unwrap()
408            .as_secs()
409    }
410
411    /// Get current Unix timestamp in milliseconds.
412    pub fn current_timestamp_millis() -> u64 {
413        SystemTime::now()
414            .duration_since(UNIX_EPOCH)
415            .unwrap()
416            .as_millis() as u64
417    }
418
419    /// Convert duration to seconds.
420    pub fn duration_to_seconds(duration: Duration) -> u64 {
421        duration.as_secs()
422    }
423
424    /// Convert seconds to duration.
425    pub fn seconds_to_duration(seconds: u64) -> Duration {
426        Duration::from_secs(seconds)
427    }
428
429    /// Check if a timestamp is expired.
430    pub fn is_expired(expires_at: u64) -> bool {
431        current_timestamp() > expires_at
432    }
433
434    /// Get time remaining until expiration.
435    pub fn time_until_expiry(expires_at: u64) -> Option<Duration> {
436        let now = current_timestamp();
437        if expires_at > now {
438            Some(Duration::from_secs(expires_at - now))
439        } else {
440            None
441        }
442    }
443}
444
445/// String utilities.
446pub mod string {
447    /// Mask a string for safe logging.
448    pub fn mask_string(input: &str, visible_chars: usize) -> String {
449        if input.is_empty() {
450            return String::new();
451        }
452
453        if visible_chars >= input.len() {
454            return input.to_string();
455        }
456
457        if input.len() <= visible_chars * 2 {
458            "*".repeat(input.len().min(8))
459        } else {
460            format!(
461                "{}{}{}",
462                &input[..visible_chars],
463                "*".repeat(input.len() - visible_chars * 2),
464                &input[input.len() - visible_chars..]
465            )
466        }
467    }
468
469    /// Truncate a string to a maximum length.
470    pub fn truncate(input: &str, max_length: usize) -> String {
471        if input.len() <= max_length {
472            input.to_string()
473        } else {
474            format!("{}...", &input[..max_length.saturating_sub(3)])
475        }
476    }
477
478    /// Check if a string is a valid email address (basic check).
479    pub fn is_valid_email(email: &str) -> bool {
480        if email.len() <= 5 || !email.contains('@') || !email.contains('.') {
481            return false;
482        }
483
484        // Must not start or end with @
485        if email.starts_with('@') || email.ends_with('@') {
486            return false;
487        }
488
489        // Must not contain spaces
490        if email.contains(' ') {
491            return false;
492        }
493
494        // Must have exactly one @
495        if email.matches('@').count() != 1 {
496            return false;
497        }
498
499        let parts: Vec<&str> = email.split('@').collect();
500        let local = parts[0];
501        let domain = parts[1];
502
503        // Local part must not be empty
504        if local.is_empty() {
505            return false;
506        }
507
508        // Domain must contain a dot and not be empty
509        if domain.is_empty() || !domain.contains('.') {
510            return false;
511        }
512
513        // Domain must not start or end with dots
514        if domain.starts_with('.') || domain.ends_with('.') {
515            return false;
516        }
517
518        // Domain must not contain consecutive dots
519        if domain.contains("..") {
520            return false;
521        }
522
523        true
524    }
525    /// Normalize an email address.
526    pub fn normalize_email(email: &str) -> String {
527        email.trim().to_lowercase()
528    }
529
530    /// Generate a random identifier.
531    pub fn generate_id(prefix: Option<&str>) -> String {
532        let id = uuid::Uuid::new_v4().to_string();
533        match prefix {
534            Some(prefix) => format!("{prefix}_{id}"),
535            None => id,
536        }
537    }
538}
539
540/// Validation utilities.
541pub mod validation {
542    use super::*;
543
544    /// Validate username format.
545    pub fn validate_username(username: &str) -> Result<()> {
546        if username.is_empty() {
547            return Err(AuthError::validation("Username cannot be empty"));
548        }
549
550        if username.len() < 3 {
551            return Err(AuthError::validation(
552                "Username must be at least 3 characters long",
553            ));
554        }
555
556        if username.len() > 50 {
557            return Err(AuthError::validation(
558                "Username cannot be longer than 50 characters",
559            ));
560        }
561
562        // Check for valid characters (alphanumeric, underscore, hyphen)
563        if !username
564            .chars()
565            .all(|c| c.is_alphanumeric() || c == '_' || c == '-')
566        {
567            return Err(AuthError::validation(
568                "Username can only contain letters, numbers, underscores, and hyphens",
569            ));
570        }
571
572        // Cannot start or end with special characters
573        if username.starts_with('_')
574            || username.starts_with('-')
575            || username.ends_with('_')
576            || username.ends_with('-')
577        {
578            return Err(AuthError::validation(
579                "Username cannot start or end with underscore or hyphen",
580            ));
581        }
582
583        Ok(())
584    }
585
586    /// Validate email format.
587    pub fn validate_email(email: &str) -> Result<()> {
588        use crate::security::secure_utils::SecureValidation;
589        SecureValidation::validate_email(email).map(|_| ())
590    }
591
592    /// Validate password according to policy.
593    pub fn validate_password(
594        password: &str,
595        min_length: usize,
596        require_complexity: bool,
597    ) -> Result<()> {
598        if password.is_empty() {
599            return Err(AuthError::validation("Password cannot be empty"));
600        }
601
602        if password.len() < min_length {
603            return Err(AuthError::validation(format!(
604                "Password must be at least {min_length} characters long"
605            )));
606        }
607
608        if require_complexity {
609            let strength = password::check_password_strength(password);
610            if matches!(strength.level, password::PasswordStrengthLevel::Weak) {
611                return Err(AuthError::validation(format!(
612                    "Password is too weak: {}",
613                    strength.feedback.join(", ")
614                )));
615            }
616        }
617
618        Ok(())
619    }
620
621    /// Validate API key format.
622    pub fn validate_api_key(api_key: &str, expected_prefix: Option<&str>) -> Result<()> {
623        if api_key.is_empty() {
624            return Err(AuthError::validation("API key cannot be empty"));
625        }
626
627        if let Some(prefix) = expected_prefix
628            && !api_key.starts_with(prefix)
629        {
630            return Err(AuthError::validation(format!(
631                "API key must start with '{prefix}'"
632            )));
633        }
634
635        // Basic length check
636        if api_key.len() < 16 {
637            return Err(AuthError::validation("API key is too short"));
638        }
639
640        if api_key.len() > 128 {
641            return Err(AuthError::validation("API key is too long"));
642        }
643
644        Ok(())
645    }
646}
647
648/// Rate limiting utilities.
649pub mod rate_limit {
650    use dashmap::DashMap;
651
652    use std::sync::Arc;
653    use std::time::{Duration, Instant};
654
655    /// Simple in-memory rate limiter.
656    pub struct RateLimiter {
657        buckets: Arc<DashMap<String, Bucket>>,
658        max_requests: u32,
659        window: Duration,
660    }
661
662    impl std::fmt::Debug for RateLimiter {
663        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
664            let mut d = f.debug_struct("RateLimiter");
665            d.field("buckets", &crate::utils::redact::redacted(&self.buckets));
666            d.field("max_requests", &self.max_requests);
667            d.field("window", &self.window);
668            d.finish()
669        }
670    }
671
672    #[derive(Debug)]
673    struct Bucket {
674        count: u32,
675        window_start: Instant,
676    }
677
678    impl RateLimiter {
679        /// Create a new rate limiter.
680        pub fn new(max_requests: u32, window: Duration) -> Self {
681            Self {
682                buckets: Arc::new(DashMap::new()),
683                max_requests,
684                window,
685            }
686        }
687
688        /// Check if a request is allowed for the given key.
689        pub fn is_allowed(&self, key: &str) -> bool {
690            let now = Instant::now();
691
692            // Get or create bucket with deadlock-safe pattern
693            let mut bucket = self.buckets.entry(key.to_string()).or_insert(Bucket {
694                count: 0,
695                window_start: now,
696            });
697
698            // Reset bucket if window has passed
699            if now.duration_since(bucket.window_start) >= self.window {
700                bucket.count = 0;
701                bucket.window_start = now;
702            }
703
704            // Check if under limit
705            if bucket.count < self.max_requests {
706                bucket.count += 1;
707                true
708            } else {
709                false
710            }
711        }
712
713        /// Get remaining requests for a key.
714        pub fn remaining_requests(&self, key: &str) -> u32 {
715            if let Some(bucket_ref) = self.buckets.get(key) {
716                let bucket = bucket_ref.value();
717                let now = Instant::now();
718                if now.duration_since(bucket.window_start) >= self.window {
719                    self.max_requests
720                } else {
721                    self.max_requests.saturating_sub(bucket.count)
722                }
723            } else {
724                self.max_requests
725            }
726        }
727
728        /// Clean up expired buckets.
729        pub fn cleanup(&self) {
730            let now = Instant::now();
731            self.buckets
732                .retain(|_, bucket| now.duration_since(bucket.window_start) < self.window);
733        }
734    }
735}
736
737#[cfg(test)]
738mod tests {
739    use super::*;
740
741    #[test]
742    fn test_password_hashing() {
743        let password = "test_password_123";
744        let hash = password::hash_password(password).unwrap();
745
746        assert!(password::verify_password(password, &hash).unwrap());
747        assert!(!password::verify_password("wrong_password", &hash).unwrap());
748    }
749
750    #[test]
751    fn test_password_strength() {
752        let weak = password::check_password_strength("123");
753        assert!(matches!(weak.level, password::PasswordStrengthLevel::Weak));
754
755        let strong = password::check_password_strength("MySecureP@ssw0rd!");
756        assert!(matches!(
757            strong.level,
758            password::PasswordStrengthLevel::Strong | password::PasswordStrengthLevel::VeryStrong
759        ));
760    }
761
762    #[test]
763    fn test_crypto_utils() {
764        let random_string = crypto::generate_random_string(16);
765        assert_eq!(random_string.len(), 16);
766
767        let data = b"test data";
768        let hash = crypto::sha256_hex(data);
769        assert_eq!(hash.len(), 64); // SHA256 hex is 64 characters
770    }
771
772    #[test]
773    fn test_string_utils() {
774        let masked = string::mask_string("secret123456", 2);
775        assert!(masked.starts_with("se"));
776        assert!(masked.ends_with("56"));
777        assert!(masked.contains("*"));
778
779        assert!(string::is_valid_email("test@example.com"));
780        assert!(!string::is_valid_email("invalid_email"));
781    }
782
783    #[test]
784    fn test_validation() {
785        // Valid username
786        assert!(validation::validate_username("test_user").is_ok());
787
788        // Invalid usernames
789        assert!(validation::validate_username("").is_err());
790        assert!(validation::validate_username("ab").is_err());
791        assert!(validation::validate_username("_invalid").is_err());
792        assert!(validation::validate_username("invalid@").is_err());
793
794        // Valid email
795        assert!(validation::validate_email("test@example.com").is_ok());
796
797        // Invalid emails
798        assert!(validation::validate_email("").is_err());
799        assert!(validation::validate_email("invalid").is_err());
800    }
801
802    #[test]
803    fn test_rate_limiter() {
804        let limiter = rate_limit::RateLimiter::new(3, std::time::Duration::from_secs(1));
805
806        // First 3 requests should be allowed
807        assert!(limiter.is_allowed("user1"));
808        assert!(limiter.is_allowed("user1"));
809        assert!(limiter.is_allowed("user1"));
810
811        // 4th request should be blocked
812        assert!(!limiter.is_allowed("user1"));
813
814        // Different user should still be allowed
815        assert!(limiter.is_allowed("user2"));
816    }
817
818    #[test]
819    fn test_password_hashing_edge_cases() {
820        // Test very long password
821        let long_password = "a".repeat(1000);
822        let hash = password::hash_password(&long_password).unwrap();
823        assert!(password::verify_password(&long_password, &hash).unwrap());
824
825        // Test password with special characters
826        let special_password = "!@#$%^&*()_+-=[]{}|;:,.<>?";
827        let hash = password::hash_password(special_password).unwrap();
828        assert!(password::verify_password(special_password, &hash).unwrap());
829
830        // Test Unicode password
831        let unicode_password = "пароль测试🔒";
832        let hash = password::hash_password(unicode_password).unwrap();
833        assert!(password::verify_password(unicode_password, &hash).unwrap());
834
835        // Test different passwords produce different hashes
836        let password1 = "password123";
837        let password2 = "password124";
838        let hash1 = password::hash_password(password1).unwrap();
839        let hash2 = password::hash_password(password2).unwrap();
840        assert_ne!(hash1, hash2);
841    }
842
843    #[test]
844    fn test_password_strength_comprehensive() {
845        let test_cases = vec![
846            ("", password::PasswordStrengthLevel::Weak),
847            ("a", password::PasswordStrengthLevel::Weak),
848            ("password", password::PasswordStrengthLevel::Weak),
849            ("password123", password::PasswordStrengthLevel::Weak), // Common password
850            ("mypassword123", password::PasswordStrengthLevel::Medium), // Not in common list
851            ("MyPassword123", password::PasswordStrengthLevel::Medium),
852            ("MyPassword123!", password::PasswordStrengthLevel::Strong),
853            (
854                "VerySecureP@ssw0rd2024!",
855                password::PasswordStrengthLevel::VeryStrong,
856            ),
857        ];
858
859        for (password, expected_min_level) in test_cases {
860            let strength = password::check_password_strength(password);
861            // Check that we meet at least the minimum expected level
862            match expected_min_level {
863                password::PasswordStrengthLevel::Weak => {
864                    // All levels are acceptable
865                }
866                password::PasswordStrengthLevel::Medium => {
867                    assert!(
868                        !matches!(strength.level, password::PasswordStrengthLevel::Weak),
869                        "Password '{}' should be at least Medium strength",
870                        password
871                    );
872                }
873                password::PasswordStrengthLevel::Strong => {
874                    assert!(
875                        matches!(
876                            strength.level,
877                            password::PasswordStrengthLevel::Strong
878                                | password::PasswordStrengthLevel::VeryStrong
879                        ),
880                        "Password '{}' should be at least Strong",
881                        password
882                    );
883                }
884                password::PasswordStrengthLevel::VeryStrong => {
885                    assert!(
886                        matches!(strength.level, password::PasswordStrengthLevel::VeryStrong),
887                        "Password '{}' should be VeryStrong",
888                        password
889                    );
890                }
891            }
892        }
893    }
894
895    #[test]
896    fn test_crypto_utils_edge_cases() {
897        // Test random string generation with different lengths
898        let lengths = vec![0, 1, 8, 16, 32, 64, 128];
899        for length in lengths {
900            let random_string = crypto::generate_random_string(length);
901            assert_eq!(
902                random_string.len(),
903                length,
904                "Generated string should have requested length"
905            );
906
907            if length > 0 {
908                // Generate another string and ensure they're different (extremely high probability)
909                let another_string = crypto::generate_random_string(length);
910                if length > 4 {
911                    // For very short strings, collision is possible but unlikely
912                    assert_ne!(
913                        random_string, another_string,
914                        "Random strings should be different"
915                    );
916                }
917            }
918        }
919
920        // Test SHA256 with various inputs
921        let test_data = vec![
922            b"".as_slice(),
923            b"a",
924            b"hello world",
925            &[0u8; 1000], // Large data
926            "unicode: 测试 🔒".as_bytes(),
927        ];
928
929        for data in test_data {
930            let hash = crypto::sha256_hex(data);
931            assert_eq!(hash.len(), 64, "SHA256 hex should always be 64 characters");
932
933            // Same input should produce same hash
934            let hash2 = crypto::sha256_hex(data);
935            assert_eq!(hash, hash2, "Same input should produce same hash");
936        }
937    }
938
939    #[test]
940    fn test_string_utils_comprehensive() {
941        // Test masking with various inputs
942        let masking_tests = vec![
943            ("", 0),
944            ("a", 1),
945            ("ab", 1),
946            ("secret", 2),
947            ("verylongsecret", 3),
948            ("short", 10), // reveal_chars > length
949        ];
950
951        for (input, reveal_chars) in masking_tests {
952            let masked = string::mask_string(input, reveal_chars);
953            if input.is_empty() {
954                assert_eq!(masked, "");
955            } else if reveal_chars >= input.len() {
956                assert_eq!(masked, input, "Should not mask if reveal_chars >= length");
957            } else if input.len() > reveal_chars * 2 {
958                // Only test character preservation for longer strings
959                assert!(
960                    masked.starts_with(&input[..reveal_chars]),
961                    "Should preserve first {} characters",
962                    reveal_chars
963                );
964                assert!(masked.contains("*"), "Should contain masking characters");
965            } else {
966                // For short strings, just check it contains masking characters
967                assert!(
968                    masked.contains("*"),
969                    "Should contain masking characters for short strings"
970                );
971            }
972        }
973
974        // Test email validation comprehensively
975        let valid_emails = vec![
976            "user@example.com",
977            "user.name@example.com",
978            "user+tag@example.co.uk",
979            "user123@example-domain.com",
980            "a@b.co",
981            "test_email@domain.info",
982        ];
983
984        let invalid_emails = vec![
985            "",
986            "user",
987            "@example.com",
988            "user@",
989            "user@@example.com",
990            "user@example",
991            "user @example.com",
992            "user@exam ple.com",
993            "user@.example.com",
994            "user@example..com",
995        ];
996
997        for email in valid_emails {
998            assert!(
999                string::is_valid_email(email),
1000                "Should accept valid email: {}",
1001                email
1002            );
1003        }
1004
1005        for email in invalid_emails {
1006            assert!(
1007                !string::is_valid_email(email),
1008                "Should reject invalid email: {}",
1009                email
1010            );
1011        }
1012    }
1013
1014    #[test]
1015    fn test_validation_comprehensive() {
1016        // Test username validation edge cases
1017        let valid_usernames = vec!["user", "user123", "user_name", "user-name", "abc"];
1018
1019        let invalid_usernames = vec![
1020            "",
1021            "us",          // too short
1022            "a",           // too short
1023            "user name",   // space
1024            "user@domain", // @
1025            "user\0name",  // null
1026            "_invalid",    // starts with underscore
1027        ];
1028
1029        for username in valid_usernames {
1030            assert!(
1031                validation::validate_username(username).is_ok(),
1032                "Should accept valid username: {}",
1033                username
1034            );
1035        }
1036
1037        for username in invalid_usernames {
1038            assert!(
1039                validation::validate_username(username).is_err(),
1040                "Should reject invalid username: {}",
1041                username
1042            );
1043        }
1044
1045        // Test email validation
1046        let valid_emails = vec![
1047            "test@example.com",
1048            "user.name@domain.co.uk",
1049            "user+tag@example.org",
1050        ];
1051
1052        let invalid_emails = vec!["", "invalid", "@example.com", "user@", "user@@example.com"];
1053
1054        for email in valid_emails {
1055            assert!(
1056                validation::validate_email(email).is_ok(),
1057                "Should accept valid email: {}",
1058                email
1059            );
1060        }
1061
1062        for email in invalid_emails {
1063            assert!(
1064                validation::validate_email(email).is_err(),
1065                "Should reject invalid email: {}",
1066                email
1067            );
1068        }
1069    }
1070
1071    #[test]
1072    fn test_rate_limiter_edge_cases() {
1073        // Test with zero limit
1074        let zero_limiter = rate_limit::RateLimiter::new(0, std::time::Duration::from_secs(60));
1075        assert!(!zero_limiter.is_allowed("user1")); // Should always deny
1076
1077        // Test with very short window
1078        let short_limiter = rate_limit::RateLimiter::new(1, std::time::Duration::from_millis(10));
1079        assert!(short_limiter.is_allowed("user1"));
1080        assert!(!short_limiter.is_allowed("user1")); // Should be blocked
1081
1082        // Wait for window to expire
1083        std::thread::sleep(std::time::Duration::from_millis(20));
1084        assert!(short_limiter.is_allowed("user1")); // Should be allowed again
1085    }
1086
1087    #[test]
1088    fn test_rate_limiter_multiple_users() {
1089        let limiter = rate_limit::RateLimiter::new(2, std::time::Duration::from_secs(60));
1090
1091        // Each user should have independent limits
1092        assert!(limiter.is_allowed("user1"));
1093        assert!(limiter.is_allowed("user1"));
1094        assert!(!limiter.is_allowed("user1")); // user1 exhausted
1095
1096        assert!(limiter.is_allowed("user2"));
1097        assert!(limiter.is_allowed("user2"));
1098        assert!(!limiter.is_allowed("user2")); // user2 exhausted
1099
1100        // user3 should still be allowed
1101        assert!(limiter.is_allowed("user3"));
1102        assert!(limiter.is_allowed("user3"));
1103        assert!(!limiter.is_allowed("user3")); // user3 exhausted
1104    }
1105
1106    #[test]
1107    fn test_crypto_random_uniqueness() {
1108        // Generate multiple random strings and ensure they're all unique
1109        let mut strings = std::collections::HashSet::new();
1110        for _ in 0..1000 {
1111            let random_string = crypto::generate_random_string(16);
1112            assert!(
1113                !strings.contains(&random_string),
1114                "Generated duplicate random string"
1115            );
1116            strings.insert(random_string);
1117        }
1118    }
1119
1120    #[test]
1121    fn test_password_hash_uniqueness() {
1122        // Same password should produce different hashes due to salt
1123        let password = "test_password_123";
1124        let mut hashes = std::collections::HashSet::new();
1125
1126        for _ in 0..10 {
1127            let hash = password::hash_password(password).unwrap();
1128            assert!(
1129                !hashes.contains(&hash),
1130                "Password hashes should be unique due to salt"
1131            );
1132            hashes.insert(hash.clone());
1133
1134            // Each hash should still verify correctly
1135            assert!(password::verify_password(password, &hash).unwrap());
1136        }
1137    }
1138}