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 Self::secure_string_compare(a, b)
60 }
61
62 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 pub fn secure_string_compare(a: &str, b: &str) -> bool {
72 Self::constant_time_eq_bytes(a.as_bytes(), b.as_bytes())
73 }
74 pub fn verify_token(token1: &str, token2: &str) -> bool {
76 Self::secure_string_compare(token1, token2)
77 }
78}
79
80pub struct SecureRandomGen;
82
83impl SecureRandomGen {
84 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 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 pub fn generate_token() -> Result<String> {
101 Self::generate_string(32) }
103
104 pub fn generate_session_id() -> Result<String> {
106 Self::generate_string(24) }
108
109 pub fn generate_challenge_id() -> Result<String> {
111 Self::generate_string(16) }
113}
114
115pub struct SecureValidation;
117
118impl SecureValidation {
119 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 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 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 #[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 }
161
162 Ok(())
163 }
164
165 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 if password.contains('\0') {
179 return Err(AuthError::validation(
180 "Password contains null bytes".to_string(),
181 ));
182 }
183
184 Ok(())
185 }
186
187 pub fn sanitize_input(input: &str) -> String {
189 input
191 .chars()
192 .filter(|&c| !c.is_control() || c == '\n' || c == '\t' || c == ' ')
193 .collect()
194 }
195
196 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 if !sanitized.contains('@') || sanitized.starts_with('@') || sanitized.ends_with('@') {
210 return Err(AuthError::validation("Invalid email format".to_string()));
211 }
212
213 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 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 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 if sanitized.contains(' ') {
239 return Err(AuthError::validation("Invalid email format".to_string()));
240 }
241
242 Ok(sanitized)
243 }
244}
245
246pub fn constant_time_compare(a: &[u8], b: &[u8]) -> bool {
279 SecureComparison::constant_time_eq_bytes(a, b)
280}
281
282pub fn generate_secure_token(byte_length: usize) -> Result<String> {
313 SecureRandomGen::generate_string(byte_length)
314}
315
316pub 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
358pub 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 }
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 assert_eq!(secret.as_str(), "sensitive_data");
476 drop(secret);
477
478 }
481
482 #[test]
483 fn test_constant_time_comparison_edge_cases() {
484 assert!(SecureComparison::constant_time_eq("", ""));
486 assert!(!SecureComparison::constant_time_eq("", "nonempty"));
487 assert!(!SecureComparison::constant_time_eq("nonempty", ""));
488
489 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 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 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 for byte_len in [8, 16, 32, 64] {
522 let token = SecureRandomGen::generate_string(byte_len).unwrap();
523 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 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 assert!(SecureValidation::validate_username("user\x01").is_err());
544 assert!(SecureValidation::validate_username("user\x1f").is_err());
545
546 assert!(SecureValidation::validate_username("user_ñ").is_ok());
548 }
549
550 #[test]
551 fn test_email_validation_comprehensive() {
552 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 let invalid_emails = vec![
572 "",
573 "user",
574 "@example.com",
575 "user@",
576 "user@@example.com",
577 "user@example",
578 "user @example.com", "user@exam ple.com", "user@.example.com", "user@example..com", ".user@example.com", "user.@example.com", ];
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 let test_cases = vec![
599 ("hello\0world", "helloworld"), ("test\x01\x02\x03", "test"), ("normal text", "normal text"), ("\x7f", ""), ("mix\0ed\x01cont\x02rol", "mixedcontrol"), ("", ""), (" spaced ", " spaced "), ];
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 let hash1 = hash_password_bcrypt(password).unwrap();
620 let hash2 = hash_password_bcrypt(password).unwrap();
621
622 assert_ne!(
624 hash1, hash2,
625 "Password hashes should be different due to random salt"
626 );
627
628 assert!(verify_password_bcrypt(password, &hash1).unwrap());
630 assert!(verify_password_bcrypt(password, &hash2).unwrap());
631
632 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 let result = hash_password_bcrypt("");
641 assert!(result.is_err(), "Should reject empty password");
642
643 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 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 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 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 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"; let prefix_token = "secure_token_12"; let longer_token = "secure_token_1234"; 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}