1use crate::errors::{AuthError, Result};
3use base64::Engine;
4use ring::rand::{SecureRandom, SystemRandom};
5use subtle::ConstantTimeEq;
6use zeroize::ZeroizeOnDrop;
7
8#[derive(Debug, Clone, ZeroizeOnDrop)]
10pub struct SecureString {
11 data: String,
12}
13
14impl SecureString {
15 pub fn new(data: String) -> Self {
17 Self { data }
18 }
19
20 pub fn as_str(&self) -> &str {
22 &self.data
23 }
24
25 pub fn as_bytes(&self) -> &[u8] {
27 self.data.as_bytes()
28 }
29
30 pub fn len(&self) -> usize {
32 self.data.len()
33 }
34
35 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
53pub struct SecureComparison;
55
56impl SecureComparison {
57 pub fn constant_time_eq(a: &str, b: &str) -> bool {
59 if a.len() != b.len() {
60 return false;
61 }
62 a.as_bytes().ct_eq(b.as_bytes()).into()
63 }
64
65 pub fn constant_time_eq_bytes(a: &[u8], b: &[u8]) -> bool {
67 if a.len() != b.len() {
68 return false;
69 }
70 a.ct_eq(b).into()
71 }
72
73 pub fn secure_string_compare(a: &str, b: &str) -> bool {
76 a.len() == b.len() && bool::from(a.as_bytes().ct_eq(b.as_bytes()))
80 }
81
82 pub fn verify_token(token1: &str, token2: &str) -> bool {
84 Self::secure_string_compare(token1, token2)
85 }
86}
87
88pub struct SecureRandomGen;
90
91impl SecureRandomGen {
92 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 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 pub fn generate_token() -> Result<String> {
109 Self::generate_string(32) }
111
112 pub fn generate_session_id() -> Result<String> {
114 Self::generate_string(24) }
116
117 pub fn generate_challenge_id() -> Result<String> {
119 Self::generate_string(16) }
121}
122
123pub struct SecureValidation;
125
126impl SecureValidation {
127 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 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 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 #[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 }
169
170 Ok(())
171 }
172
173 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 if password.contains('\0') {
187 return Err(AuthError::validation(
188 "Password contains null bytes".to_string(),
189 ));
190 }
191
192 Ok(())
193 }
194
195 pub fn sanitize_input(input: &str) -> String {
197 input
199 .chars()
200 .filter(|&c| !c.is_control() || c == '\n' || c == '\t' || c == ' ')
201 .collect()
202 }
203
204 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 if !sanitized.contains('@') || sanitized.starts_with('@') || sanitized.ends_with('@') {
218 return Err(AuthError::validation("Invalid email format".to_string()));
219 }
220
221 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 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 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 if sanitized.contains(' ') {
247 return Err(AuthError::validation("Invalid email format".to_string()));
248 }
249
250 Ok(sanitized)
251 }
252}
253
254pub fn constant_time_compare(a: &[u8], b: &[u8]) -> bool {
287 SecureComparison::constant_time_eq_bytes(a, b)
288}
289
290pub fn generate_secure_token(byte_length: usize) -> Result<String> {
321 SecureRandomGen::generate_string(byte_length)
322}
323
324pub fn hash_password(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
366pub fn verify_password(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 }
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 assert_eq!(secret.as_str(), "sensitive_data");
484 drop(secret);
485
486 }
489
490 #[test]
491 fn test_constant_time_comparison_edge_cases() {
492 assert!(SecureComparison::constant_time_eq("", ""));
494 assert!(!SecureComparison::constant_time_eq("", "nonempty"));
495 assert!(!SecureComparison::constant_time_eq("nonempty", ""));
496
497 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 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 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 for byte_len in [8, 16, 32, 64] {
530 let token = SecureRandomGen::generate_string(byte_len).unwrap();
531 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 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 assert!(SecureValidation::validate_username("user\x01").is_err());
552 assert!(SecureValidation::validate_username("user\x1f").is_err());
553
554 assert!(SecureValidation::validate_username("user_ñ").is_ok());
556 }
557
558 #[test]
559 fn test_email_validation_comprehensive() {
560 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 let invalid_emails = vec![
580 "",
581 "user",
582 "@example.com",
583 "user@",
584 "user@@example.com",
585 "user@example",
586 "user @example.com", "user@exam ple.com", "user@.example.com", "user@example..com", ".user@example.com", "user.@example.com", ];
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 let test_cases = vec![
607 ("hello\0world", "helloworld"), ("test\x01\x02\x03", "test"), ("normal text", "normal text"), ("\x7f", ""), ("mix\0ed\x01cont\x02rol", "mixedcontrol"), ("", ""), (" spaced ", " spaced "), ];
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 let hash1 = hash_password(password).unwrap();
628 let hash2 = hash_password(password).unwrap();
629
630 assert_ne!(
632 hash1, hash2,
633 "Password hashes should be different due to random salt"
634 );
635
636 assert!(verify_password(password, &hash1).unwrap());
638 assert!(verify_password(password, &hash2).unwrap());
639
640 assert!(!verify_password("wrong_password", &hash1).unwrap());
642 assert!(!verify_password("wrong_password", &hash2).unwrap());
643 }
644
645 #[test]
646 fn test_password_hashing_edge_cases() {
647 let result = hash_password("");
649 assert!(result.is_err(), "Should reject empty password");
650
651 let long_password = "a".repeat(100);
653 let hash = hash_password(&long_password).unwrap();
654 assert!(verify_password(&long_password, &hash).unwrap());
655
656 let special_password = "p@ssw0rd!#$%^&*()";
658 let hash = hash_password(special_password).unwrap();
659 assert!(verify_password(special_password, &hash).unwrap());
660
661 let unicode_password = "пароль123测试";
663 let hash = hash_password(unicode_password).unwrap();
664 assert!(verify_password(unicode_password, &hash).unwrap());
665 }
666
667 #[test]
668 fn test_secure_comparison_timing() {
669 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 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"; let prefix_token = "secure_token_12"; let longer_token = "secure_token_1234"; 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}