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