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