1use crate::errors::{AuthError, Result};
3use base64::Engine;
4use ring::rand::{SecureRandom, SystemRandom};
5use subtle::ConstantTimeEq;
6use zeroize::ZeroizeOnDrop;
7
8#[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 pub fn new(data: String) -> Self {
25 Self { data }
26 }
27
28 pub fn as_str(&self) -> &str {
30 &self.data
31 }
32
33 pub fn as_bytes(&self) -> &[u8] {
35 self.data.as_bytes()
36 }
37
38 pub fn len(&self) -> usize {
40 self.data.len()
41 }
42
43 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
61pub struct SecureComparison;
63
64impl SecureComparison {
65 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 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 pub fn secure_string_compare(a: &str, b: &str) -> bool {
84 a.len() == b.len() && bool::from(a.as_bytes().ct_eq(b.as_bytes()))
88 }
89
90 pub fn verify_token(token1: &str, token2: &str) -> bool {
92 Self::secure_string_compare(token1, token2)
93 }
94}
95
96pub struct SecureRandomGen;
98
99impl SecureRandomGen {
100 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 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 pub fn generate_token() -> Result<String> {
117 Self::generate_string(32) }
119
120 pub fn generate_session_id() -> Result<String> {
122 Self::generate_string(24) }
124
125 pub fn generate_challenge_id() -> Result<String> {
127 Self::generate_string(16) }
129}
130
131pub struct SecureValidation;
133
134impl SecureValidation {
135 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 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 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 #[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 }
177
178 Ok(())
179 }
180
181 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 if password.contains('\0') {
195 return Err(AuthError::validation(
196 "Password contains null bytes".to_string(),
197 ));
198 }
199
200 Ok(())
201 }
202
203 pub fn sanitize_input(input: &str) -> String {
205 input
207 .chars()
208 .filter(|&c| !c.is_control() || c == '\n' || c == '\t' || c == ' ')
209 .collect()
210 }
211
212 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 if !sanitized.contains('@') || sanitized.starts_with('@') || sanitized.ends_with('@') {
226 return Err(AuthError::validation("Invalid email format".to_string()));
227 }
228
229 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 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 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 if sanitized.contains(' ') {
255 return Err(AuthError::validation("Invalid email format".to_string()));
256 }
257
258 Ok(sanitized)
259 }
260}
261
262pub fn constant_time_compare(a: &[u8], b: &[u8]) -> bool {
295 SecureComparison::constant_time_eq_bytes(a, b)
296}
297
298pub fn generate_secure_token(byte_length: usize) -> Result<String> {
329 SecureRandomGen::generate_string(byte_length)
330}
331
332pub 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
374pub 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 }
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 assert_eq!(secret.as_str(), "sensitive_data");
492 drop(secret);
493
494 }
497
498 #[test]
499 fn test_constant_time_comparison_edge_cases() {
500 assert!(SecureComparison::constant_time_eq("", ""));
502 assert!(!SecureComparison::constant_time_eq("", "nonempty"));
503 assert!(!SecureComparison::constant_time_eq("nonempty", ""));
504
505 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 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 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 for byte_len in [8, 16, 32, 64] {
538 let token = SecureRandomGen::generate_string(byte_len).unwrap();
539 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 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 assert!(SecureValidation::validate_username("user\x01").is_err());
560 assert!(SecureValidation::validate_username("user\x1f").is_err());
561
562 assert!(SecureValidation::validate_username("user_ñ").is_ok());
564 }
565
566 #[test]
567 fn test_email_validation_comprehensive() {
568 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 let invalid_emails = vec![
588 "",
589 "user",
590 "@example.com",
591 "user@",
592 "user@@example.com",
593 "user@example",
594 "user @example.com", "user@exam ple.com", "user@.example.com", "user@example..com", ".user@example.com", "user.@example.com", ];
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 let test_cases = vec![
615 ("hello\0world", "helloworld"), ("test\x01\x02\x03", "test"), ("normal text", "normal text"), ("\x7f", ""), ("mix\0ed\x01cont\x02rol", "mixedcontrol"), ("", ""), (" spaced ", " spaced "), ];
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 let hash1 = hash_password(password).unwrap();
636 let hash2 = hash_password(password).unwrap();
637
638 assert_ne!(
640 hash1, hash2,
641 "Password hashes should be different due to random salt"
642 );
643
644 assert!(verify_password(password, &hash1).unwrap());
646 assert!(verify_password(password, &hash2).unwrap());
647
648 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 let result = hash_password("");
657 assert!(result.is_err(), "Should reject empty password");
658
659 let long_password = "a".repeat(100);
661 let hash = hash_password(&long_password).unwrap();
662 assert!(verify_password(&long_password, &hash).unwrap());
663
664 let special_password = "p@ssw0rd!#$%^&*()";
666 let hash = hash_password(special_password).unwrap();
667 assert!(verify_password(special_password, &hash).unwrap());
668
669 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 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 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"; let prefix_token = "secure_token_12"; let longer_token = "secure_token_1234"; 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}