Skip to main content

auth_framework/security/
secure_utils.rs

1// Secure utility functions with constant-time operations
2use crate::errors::{AuthError, Result};
3use base64::Engine;
4use ring::rand::{SecureRandom, SystemRandom};
5use subtle::ConstantTimeEq;
6use zeroize::ZeroizeOnDrop;
7
8/// A secure string that is automatically zeroized when dropped
9#[derive(Clone, ZeroizeOnDrop)]
10pub struct SecureString {
11    data: String,
12}
13
14impl std::fmt::Debug for SecureString {
15    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
16        let mut d = f.debug_struct("SecureString");
17        d.field("data", &crate::utils::redact::redacted(&self.data));
18        d.finish()
19    }
20}
21
22impl SecureString {
23    /// Create a new secure string
24    pub fn new(data: String) -> Self {
25        Self { data }
26    }
27
28    /// Get the string data (use carefully)
29    pub fn as_str(&self) -> &str {
30        &self.data
31    }
32
33    /// Get the string data as bytes
34    pub fn as_bytes(&self) -> &[u8] {
35        self.data.as_bytes()
36    }
37
38    /// Get the length
39    pub fn len(&self) -> usize {
40        self.data.len()
41    }
42
43    /// Check if empty
44    pub fn is_empty(&self) -> bool {
45        self.data.is_empty()
46    }
47}
48
49impl From<String> for SecureString {
50    fn from(data: String) -> Self {
51        Self::new(data)
52    }
53}
54
55impl From<&str> for SecureString {
56    fn from(data: &str) -> Self {
57        Self::new(data.to_string())
58    }
59}
60
61/// Secure comparison utilities
62pub struct SecureComparison;
63
64impl SecureComparison {
65    /// Constant-time string comparison over the full length of both inputs.
66    pub fn constant_time_eq(a: &str, b: &str) -> bool {
67        Self::secure_string_compare(a, b)
68    }
69
70    /// Constant-time byte comparison over the full length of both slices.
71    ///
72    /// Every byte is compared, however long the inputs are. The length itself is not secret, and
73    /// `ct_eq` examines all bytes of equal-length slices without an early exit.
74    pub fn constant_time_eq_bytes(a: &[u8], b: &[u8]) -> bool {
75        a.len() == b.len() && bool::from(a.ct_eq(b))
76    }
77
78    /// Compare strings with timing attack protection, over the full length of both inputs.
79    pub fn secure_string_compare(a: &str, b: &str) -> bool {
80        Self::constant_time_eq_bytes(a.as_bytes(), b.as_bytes())
81    }
82    /// Verify that two tokens match using constant-time comparison
83    pub fn verify_token(token1: &str, token2: &str) -> bool {
84        Self::secure_string_compare(token1, token2)
85    }
86}
87
88/// Generate secure random values
89pub struct SecureRandomGen;
90
91impl SecureRandomGen {
92    /// Generate secure random bytes
93    pub fn generate_bytes(len: usize) -> Result<Vec<u8>> {
94        let rng = SystemRandom::new();
95        let mut bytes = vec![0u8; len];
96        rng.fill(&mut bytes)
97            .map_err(|_| AuthError::crypto("Failed to generate random bytes".to_string()))?;
98        Ok(bytes)
99    }
100
101    /// Generate secure random string (base64url encoded)
102    pub fn generate_string(byte_len: usize) -> Result<String> {
103        let bytes = Self::generate_bytes(byte_len)?;
104        Ok(base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(&bytes))
105    }
106
107    /// Generate secure random token for sessions/API keys
108    pub fn generate_token() -> Result<String> {
109        Self::generate_string(32) // 256 bits of entropy
110    }
111
112    /// Generate secure session ID
113    pub fn generate_session_id() -> Result<String> {
114        Self::generate_string(24) // 192 bits of entropy
115    }
116
117    /// Generate secure challenge ID
118    pub fn generate_challenge_id() -> Result<String> {
119        Self::generate_string(16) // 128 bits of entropy
120    }
121}
122
123/// Input validation with security considerations
124pub struct SecureValidation;
125
126impl SecureValidation {
127    /// Validate username with security checks
128    pub fn validate_username(username: &str) -> Result<()> {
129        if username.is_empty() {
130            return Err(AuthError::validation(
131                "Username cannot be empty".to_string(),
132            ));
133        }
134
135        if username.len() > 320 {
136            return Err(AuthError::validation("Username too long".to_string()));
137        }
138
139        // Check for potentially dangerous characters
140        if username.contains('\0') || username.contains('\r') || username.contains('\n') {
141            return Err(AuthError::validation(
142                "Username contains invalid characters".to_string(),
143            ));
144        }
145
146        // Control characters must always be rejected, regardless of unicode-support feature
147        if username.chars().any(|c| c.is_control()) {
148            return Err(AuthError::validation(
149                "Username contains invalid control characters".to_string(),
150            ));
151        }
152
153        // Unicode normalization to prevent bypass attacks
154        #[cfg(feature = "unicode-support")]
155        {
156            let normalized = unicode_normalization::UnicodeNormalization::nfc(username.chars())
157                .collect::<String>();
158            if normalized != username {
159                return Err(AuthError::validation(
160                    "Username must be in NFC form".to_string(),
161                ));
162            }
163        }
164
165        #[cfg(not(feature = "unicode-support"))]
166        {
167            // No additional checks needed; the control-character check above covers this path.
168        }
169
170        Ok(())
171    }
172
173    /// Validate password with security considerations
174    pub fn validate_password(password: &str) -> Result<()> {
175        if password.is_empty() {
176            return Err(AuthError::validation(
177                "Password cannot be empty".to_string(),
178            ));
179        }
180
181        if password.len() > 1000 {
182            return Err(AuthError::validation("Password too long".to_string()));
183        }
184
185        // Check for null bytes
186        if password.contains('\0') {
187            return Err(AuthError::validation(
188                "Password contains null bytes".to_string(),
189            ));
190        }
191
192        Ok(())
193    }
194
195    /// Sanitize user input to prevent injection attacks
196    pub fn sanitize_input(input: &str) -> String {
197        // Remove null bytes and control characters except newlines/tabs and spaces
198        input
199            .chars()
200            .filter(|&c| !c.is_control() || c == '\n' || c == '\t' || c == ' ')
201            .collect()
202    }
203
204    /// Validate and sanitize email address
205    pub fn validate_email(email: &str) -> Result<String> {
206        let sanitized = Self::sanitize_input(email);
207
208        if sanitized.is_empty() {
209            return Err(AuthError::validation("Email cannot be empty".to_string()));
210        }
211
212        if sanitized.len() > 320 {
213            return Err(AuthError::validation("Email too long".to_string()));
214        }
215
216        // Basic email validation
217        if !sanitized.contains('@') || sanitized.starts_with('@') || sanitized.ends_with('@') {
218            return Err(AuthError::validation("Invalid email format".to_string()));
219        }
220
221        // Check for multiple @ symbols
222        if sanitized.matches('@').count() != 1 {
223            return Err(AuthError::validation("Invalid email format".to_string()));
224        }
225
226        let parts: Vec<&str> = sanitized.split('@').collect();
227        let local_part = parts[0];
228        let domain_part = parts[1];
229
230        // Check local part
231        if local_part.is_empty() || local_part.starts_with('.') || local_part.ends_with('.') {
232            return Err(AuthError::validation("Invalid email format".to_string()));
233        }
234
235        // Check domain part
236        if domain_part.is_empty()
237            || domain_part.starts_with('.')
238            || domain_part.ends_with('.')
239            || domain_part.contains("..")
240            || !domain_part.contains('.')
241        {
242            return Err(AuthError::validation("Invalid email format".to_string()));
243        }
244
245        // Check for spaces in email
246        if sanitized.contains(' ') {
247            return Err(AuthError::validation("Invalid email format".to_string()));
248        }
249
250        Ok(sanitized)
251    }
252}
253
254/// Performs constant-time comparison of two byte slices to prevent timing attacks.
255///
256/// This function compares two byte slices in constant time, meaning the execution
257/// time does not depend on where the first difference occurs. This is crucial for
258/// security-sensitive comparisons like tokens, passwords, or MAC verification.
259///
260/// # Arguments
261///
262/// * `a` - First byte slice to compare
263/// * `b` - Second byte slice to compare
264///
265/// # Returns
266///
267/// * `true` if the byte slices are equal, `false` otherwise
268///
269/// # Security Notes
270///
271/// This function is designed to prevent timing attacks by ensuring that the
272/// comparison time remains constant regardless of input values.
273///
274/// # Example
275///
276/// ```rust
277/// use auth_framework::security::secure_utils::constant_time_compare;
278///
279/// let token1 = b"secure_token_value";
280/// let token2 = b"secure_token_value";
281/// let token3 = b"different_token";
282///
283/// assert!(constant_time_compare(token1, token2));
284/// assert!(!constant_time_compare(token1, token3));
285/// ```
286pub fn constant_time_compare(a: &[u8], b: &[u8]) -> bool {
287    SecureComparison::constant_time_eq_bytes(a, b)
288}
289
290/// Generates a cryptographically secure random token as a base64-encoded string.
291///
292/// This function creates a secure random token suitable for use as session tokens,
293/// API keys, or other security-sensitive identifiers. The token is base64url-encoded
294/// for safe use in URLs and HTTP headers.
295///
296/// # Arguments
297///
298/// * `byte_length` - The number of random bytes to generate before encoding
299///
300/// # Returns
301///
302/// * `Ok(String)` - A base64url-encoded random token
303/// * `Err(AuthError)` - If random number generation fails
304///
305/// # Security Notes
306///
307/// - Uses cryptographically secure random number generation
308/// - The output length will be approximately 4/3 times the input byte length due to base64 encoding
309/// - Tokens are suitable for cryptographic purposes
310///
311/// # Example
312///
313/// ```rust
314/// use auth_framework::security::secure_utils::generate_secure_token;
315///
316/// // Generate a 256-bit (32-byte) token
317/// let token = generate_secure_token(32).unwrap();
318/// println!("Generated token: {}", token);
319/// ```
320pub fn generate_secure_token(byte_length: usize) -> Result<String> {
321    SecureRandomGen::generate_string(byte_length)
322}
323
324/// Hashes a password using bcrypt with a secure cost factor.
325///
326/// This function uses the bcrypt algorithm to hash passwords with a predefined
327/// cost factor. Bcrypt is designed to be computationally expensive to prevent
328/// brute-force attacks and includes automatic salt generation.
329///
330/// # Arguments
331///
332/// * `password` - The plaintext password to hash
333///
334/// # Returns
335///
336/// * `Ok(String)` - The bcrypt hash including salt and cost parameters
337/// * `Err(AuthError)` - If hashing fails or password is invalid
338///
339/// # Security Notes
340///
341/// - Uses bcrypt's default cost factor (currently 12)
342/// - Each hash includes a unique random salt
343/// - The same password will produce different hashes due to random salting
344/// - Empty passwords are rejected for security
345///
346/// # Example
347///
348/// ```rust
349/// use auth_framework::security::secure_utils::hash_password_bcrypt;
350///
351/// let password = "user_password_123";
352/// let hash = hash_password_bcrypt(password).unwrap();
353/// println!("Password hash: {}", hash);
354/// ```
355pub fn hash_password_bcrypt(password: &str) -> Result<String> {
356    if password.is_empty() {
357        return Err(AuthError::validation(
358            "Password cannot be empty".to_string(),
359        ));
360    }
361
362    bcrypt::hash(password, bcrypt::DEFAULT_COST)
363        .map_err(|e| AuthError::crypto(format!("Password hashing failed: {}", e)))
364}
365
366/// Verifies a plaintext password against a bcrypt hash.
367///
368/// This function uses bcrypt to verify that a plaintext password matches
369/// a previously generated hash. The verification is performed in constant
370/// time to prevent timing attacks.
371///
372/// # Arguments
373///
374/// * `password` - The plaintext password to verify
375/// * `hash` - The bcrypt hash to verify against
376///
377/// # Returns
378///
379/// * `Ok(true)` if the password matches the hash
380/// * `Ok(false)` if the password does not match the hash
381/// * `Err(AuthError)` if verification fails due to an invalid hash format
382///
383/// # Security Notes
384///
385/// - Verification is performed in constant time
386/// - The hash must be a valid bcrypt hash including salt and cost parameters
387/// - Invalid hash formats will result in an error rather than false
388///
389/// # Example
390///
391/// ```rust
392/// use auth_framework::security::secure_utils::{hash_password_bcrypt, verify_password_bcrypt};
393///
394/// let password = "user_password_123";
395/// let hash = hash_password_bcrypt(password).unwrap();
396///
397/// assert!(verify_password_bcrypt(password, &hash).unwrap());
398/// assert!(!verify_password_bcrypt("wrong_password", &hash).unwrap());
399/// ```
400pub fn verify_password_bcrypt(password: &str, hash: &str) -> Result<bool> {
401    bcrypt::verify(password, hash)
402        .map_err(|e| AuthError::crypto(format!("Password verification failed: {}", e)))
403}
404
405#[cfg(test)]
406mod tests {
407    use super::*;
408
409    #[test]
410    fn test_secure_string() {
411        let secret = SecureString::new("password123".to_string());
412        assert_eq!(secret.as_str(), "password123");
413        assert_eq!(secret.len(), 11);
414        // SecureString will be zeroized when dropped
415    }
416
417    #[test]
418    fn test_constant_time_comparison() {
419        assert!(SecureComparison::constant_time_eq("hello", "hello"));
420        assert!(!SecureComparison::constant_time_eq("hello", "world"));
421        assert!(!SecureComparison::constant_time_eq("hello", "hello world"));
422    }
423
424    #[test]
425    fn test_secure_string_compare() {
426        assert!(SecureComparison::secure_string_compare("test", "test"));
427        assert!(!SecureComparison::secure_string_compare(
428            "test",
429            "different"
430        ));
431        assert!(!SecureComparison::secure_string_compare("short", "longer"));
432    }
433
434    #[test]
435    fn test_token_verification() {
436        let token = "abc123def456";
437        assert!(SecureComparison::verify_token(token, token));
438        assert!(!SecureComparison::verify_token(token, "different"));
439    }
440
441    #[test]
442    fn test_secure_random_generation() {
443        let token1 = SecureRandomGen::generate_token().unwrap();
444        let token2 = SecureRandomGen::generate_token().unwrap();
445
446        assert_ne!(token1, token2);
447        assert!(!token1.is_empty());
448        assert!(!token2.is_empty());
449    }
450
451    #[test]
452    fn test_input_validation() {
453        assert!(SecureValidation::validate_username("user123").is_ok());
454        assert!(SecureValidation::validate_username("").is_err());
455        assert!(SecureValidation::validate_username("user\0name").is_err());
456    }
457
458    #[test]
459    fn test_email_validation() {
460        assert!(SecureValidation::validate_email("test@example.com").is_ok());
461        assert!(SecureValidation::validate_email("").is_err());
462        assert!(SecureValidation::validate_email("@example.com").is_err());
463        assert!(SecureValidation::validate_email("user@").is_err());
464    }
465
466    #[test]
467    fn test_input_sanitization() {
468        let dirty = "hello\0world\x01test";
469        let clean = SecureValidation::sanitize_input(dirty);
470        assert_eq!(clean, "helloworldtest");
471
472        let with_newlines = "line1\nline2\tline3";
473        let cleaned = SecureValidation::sanitize_input(with_newlines);
474        assert_eq!(cleaned, "line1\nline2\tline3");
475    }
476
477    #[test]
478    fn test_secure_string_zeroization() {
479        let secret = SecureString::new("sensitive_data".to_string());
480        let _ptr = secret.as_str().as_ptr();
481
482        // Verify content before drop
483        assert_eq!(secret.as_str(), "sensitive_data");
484        drop(secret);
485
486        // After drop, we can't verify zeroization directly due to Rust safety,
487        // but this test ensures the SecureString type is working correctly
488    }
489
490    #[test]
491    fn test_constant_time_comparison_edge_cases() {
492        // Test empty strings
493        assert!(SecureComparison::constant_time_eq("", ""));
494        assert!(!SecureComparison::constant_time_eq("", "nonempty"));
495        assert!(!SecureComparison::constant_time_eq("nonempty", ""));
496
497        // Test very long strings
498        let long1 = "a".repeat(1000);
499        let long2 = "a".repeat(1000);
500        let long3 = "b".repeat(1000);
501
502        assert!(SecureComparison::constant_time_eq(&long1, &long2));
503        assert!(!SecureComparison::constant_time_eq(&long1, &long3));
504
505        // Test strings that differ only in the last character
506        let almost_same1 = "verylongstringtestX";
507        let almost_same2 = "verylongstringtestY";
508        assert!(!SecureComparison::constant_time_eq(
509            almost_same1,
510            almost_same2
511        ));
512    }
513
514    #[test]
515    fn test_secure_random_generation_uniqueness() {
516        let mut tokens = std::collections::HashSet::new();
517
518        // Generate multiple tokens and ensure they're unique
519        for _ in 0..100 {
520            let token = SecureRandomGen::generate_token().unwrap();
521            assert!(!tokens.contains(&token), "Generated duplicate token");
522            tokens.insert(token);
523        }
524    }
525
526    #[test]
527    fn test_secure_random_generation_length() {
528        // Test different lengths
529        for byte_len in [8, 16, 32, 64] {
530            let token = SecureRandomGen::generate_string(byte_len).unwrap();
531            // Base64url encoding: 4 chars per 3 bytes, no padding
532            let expected_len = (byte_len * 4).div_ceil(3);
533            assert!(
534                token.len() >= expected_len - 2 && token.len() <= expected_len + 2,
535                "Token length {} not in expected range for {} bytes",
536                token.len(),
537                byte_len
538            );
539        }
540    }
541
542    #[test]
543    fn test_input_validation_edge_cases() {
544        // Test various edge cases for username validation
545        let long_username = "a".repeat(320);
546        assert!(SecureValidation::validate_username(&long_username).is_ok());
547        let too_long_username = "a".repeat(321);
548        assert!(SecureValidation::validate_username(&too_long_username).is_err());
549
550        // Control characters
551        assert!(SecureValidation::validate_username("user\x01").is_err());
552        assert!(SecureValidation::validate_username("user\x1f").is_err());
553
554        // Unicode considerations (basic test)
555        assert!(SecureValidation::validate_username("user_ñ").is_ok());
556    }
557
558    #[test]
559    fn test_email_validation_comprehensive() {
560        // Valid emails
561        let valid_emails = vec![
562            "user@example.com",
563            "user.name@example.com",
564            "user+tag@example.com",
565            "user123@example-domain.com",
566            "a@b.co",
567            "very.long.email.address@very.long.domain.name.com",
568        ];
569
570        for email in valid_emails {
571            assert!(
572                SecureValidation::validate_email(email).is_ok(),
573                "Should accept valid email: {}",
574                email
575            );
576        }
577
578        // Invalid emails
579        let invalid_emails = vec![
580            "",
581            "user",
582            "@example.com",
583            "user@",
584            "user@@example.com",
585            "user@example",
586            "user @example.com", // Space
587            "user@exam ple.com", // Space in domain
588            "user@.example.com", // Leading dot
589            "user@example..com", // Double dot
590            ".user@example.com", // Leading dot in local part
591            "user.@example.com", // Trailing dot in local part
592        ];
593
594        for email in invalid_emails {
595            assert!(
596                SecureValidation::validate_email(email).is_err(),
597                "Should reject invalid email: {}",
598                email
599            );
600        }
601    }
602
603    #[test]
604    fn test_input_sanitization_comprehensive() {
605        // Test various control characters
606        let test_cases = vec![
607            ("hello\0world", "helloworld"),             // Null byte
608            ("test\x01\x02\x03", "test"),               // Control chars
609            ("normal text", "normal text"),             // No change
610            ("\x7f", ""),                               // DEL character
611            ("mix\0ed\x01cont\x02rol", "mixedcontrol"), // Mixed
612            ("", ""),                                   // Empty
613            ("   spaced   ", "   spaced   "),           // Preserve normal spaces
614        ];
615
616        for (input, expected) in test_cases {
617            let result = SecureValidation::sanitize_input(input);
618            assert_eq!(result, expected, "Sanitization failed for: {:?}", input);
619        }
620    }
621
622    #[test]
623    fn test_password_hashing_security() {
624        let password = "test_password_123";
625
626        // Hash the same password multiple times
627        let hash1 = hash_password_bcrypt(password).unwrap();
628        let hash2 = hash_password_bcrypt(password).unwrap();
629
630        // Hashes should be different (due to salt)
631        assert_ne!(
632            hash1, hash2,
633            "Password hashes should be different due to random salt"
634        );
635
636        // Both hashes should verify correctly
637        assert!(verify_password_bcrypt(password, &hash1).unwrap());
638        assert!(verify_password_bcrypt(password, &hash2).unwrap());
639
640        // Wrong password should not verify
641        assert!(!verify_password_bcrypt("wrong_password", &hash1).unwrap());
642        assert!(!verify_password_bcrypt("wrong_password", &hash2).unwrap());
643    }
644
645    #[test]
646    fn test_password_hashing_edge_cases() {
647        // Test empty password
648        let result = hash_password_bcrypt("");
649        assert!(result.is_err(), "Should reject empty password");
650
651        // Test very long password
652        let long_password = "a".repeat(100);
653        let hash = hash_password_bcrypt(&long_password).unwrap();
654        assert!(verify_password_bcrypt(&long_password, &hash).unwrap());
655
656        // Test password with special characters
657        let special_password = "p@ssw0rd!#$%^&*()";
658        let hash = hash_password_bcrypt(special_password).unwrap();
659        assert!(verify_password_bcrypt(special_password, &hash).unwrap());
660
661        // Test password with Unicode
662        let unicode_password = "пароль123测试";
663        let hash = hash_password_bcrypt(unicode_password).unwrap();
664        assert!(verify_password_bcrypt(unicode_password, &hash).unwrap());
665    }
666
667    #[test]
668    fn test_secure_comparison_timing() {
669        // This test can't verify timing directly, but ensures the function works correctly
670        // with various input sizes to ensure it's implemented properly
671
672        let short_a = "a";
673        let short_b = "a";
674        let long_a = "a".repeat(1000);
675        let long_b = "a".repeat(1000);
676
677        assert!(SecureComparison::constant_time_eq(short_a, short_b));
678        assert!(SecureComparison::secure_string_compare(short_a, short_b));
679        assert!(SecureComparison::verify_token(short_a, short_b));
680
681        assert!(SecureComparison::constant_time_eq(&long_a, &long_b));
682        assert!(SecureComparison::secure_string_compare(&long_a, &long_b));
683        assert!(SecureComparison::verify_token(&long_a, &long_b));
684
685        let different_short_a = "a";
686        let different_short_b = "b";
687        let different_long_a = "a".repeat(1000);
688        let different_long_b = "b".repeat(1000);
689
690        assert!(!SecureComparison::constant_time_eq(
691            different_short_a,
692            different_short_b
693        ));
694        assert!(!SecureComparison::secure_string_compare(
695            different_short_a,
696            different_short_b
697        ));
698        assert!(!SecureComparison::verify_token(
699            different_short_a,
700            different_short_b
701        ));
702
703        assert!(!SecureComparison::constant_time_eq(
704            &different_long_a,
705            &different_long_b
706        ));
707        assert!(!SecureComparison::secure_string_compare(
708            &different_long_a,
709            &different_long_b
710        ));
711        assert!(!SecureComparison::verify_token(
712            &different_long_a,
713            &different_long_b
714        ));
715    }
716
717    #[test]
718    fn test_secure_string_multiple_operations() {
719        let secret1 = SecureString::new("password1".to_string());
720        let secret2 = SecureString::new("password2".to_string());
721
722        assert_ne!(secret1.as_str(), secret2.as_str());
723        assert!(SecureComparison::verify_token(
724            secret1.as_str(),
725            secret1.as_str()
726        ));
727        assert!(!SecureComparison::verify_token(
728            secret1.as_str(),
729            secret2.as_str()
730        ));
731
732        // Test operations
733        assert_eq!(secret1.len(), 9);
734        assert_eq!(secret2.len(), 9);
735        assert!(!secret1.is_empty());
736        assert!(!secret2.is_empty());
737    }
738
739    #[test]
740    fn test_token_verification_false_positives() {
741        let token = "secure_token_123";
742        let similar_token = "secure_token_124"; // Only last char different
743        let prefix_token = "secure_token_12"; // Shorter
744        let longer_token = "secure_token_1234"; // Longer
745
746        assert!(SecureComparison::verify_token(token, token));
747        assert!(!SecureComparison::verify_token(token, similar_token));
748        assert!(!SecureComparison::verify_token(token, prefix_token));
749        assert!(!SecureComparison::verify_token(token, longer_token));
750    }
751}