1use actix_plus_error::{ResponseError, ResponseResult};
7use actix_web::http::StatusCode;
8use rand::{thread_rng, Rng};
9use std::time::{SystemTime, UNIX_EPOCH};
10use unic_ucd_category::GeneralCategory;
11
12pub fn current_unix_time_secs() -> u64 {
14 SystemTime::now()
15 .duration_since(UNIX_EPOCH)
16 .expect("Time went backwards")
17 .as_secs()
18}
19
20#[test]
21fn test_unix_time_increasing_at_proper_rate() {
22 use std::thread::sleep;
23 use std::time::Duration;
24
25 let first_time = current_unix_time_secs();
26 sleep(Duration::from_millis(1000));
27 let second_time = current_unix_time_secs();
28 assert_eq!(first_time, second_time - 1);
29}
30
31pub fn secure_random_string(len: usize) -> String {
33 let chars = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
34 let mut random_string = Vec::new();
35 let mut rng = thread_rng();
36 random_string.reserve(len);
37 for _i in 0..len {
38 random_string.push(chars[rng.gen_range(0, chars.len())]);
39 }
40 String::from_utf8(random_string).expect("Random string contains non-UTF data.")
41}
42
43#[test]
44fn test_secure_random_strings() {
45 let length = 1024;
46 let string_1 = secure_random_string(length);
47 let string_2 = secure_random_string(length);
48 assert_ne!(string_1, string_2);
49 assert_eq!(string_1.len(), length);
50 assert_eq!(string_2.len(), length);
51}
52
53pub fn validate_and_sanitize_string(string: &str, allow_new_line: bool) -> ResponseResult<String> {
57 let mut output = String::new();
58 output.reserve(string.len());
59 for ch in string.chars() {
60 if ch == ' ' || (allow_new_line && ch == '\n') {
61 output.push(ch);
62 } else if allow_new_line && ch == '\r' {
63 } else {
65 let ctg = GeneralCategory::of(ch);
66 if ctg.is_other() || ctg.is_separator() {
67 return Err(ResponseError::StatusCodeError {
68 message: String::from("Input strings for user-supplied content must not contain non-printable characters, excepting newlines in some cases."),
69 code: StatusCode::BAD_REQUEST
70 });
71 } else {
72 output.push(ch);
73 }
74 }
75 }
76
77 Ok(output)
78}
79
80#[test]
81fn test_string_validation() {
82 assert_eq!(
83 validate_and_sanitize_string("Test String", false).is_ok(),
84 true
85 );
86 assert_eq!(
87 validate_and_sanitize_string("Test String", true).is_ok(),
88 true
89 );
90 assert_eq!(
91 validate_and_sanitize_string("Test String\n\r", true).is_ok(),
92 true
93 );
94 assert_eq!(
95 validate_and_sanitize_string("Test String\n\r", false).is_ok(),
96 false
97 );
98 assert_eq!(
99 validate_and_sanitize_string("Test String\n", true).is_ok(),
100 true
101 );
102 assert_eq!(
103 validate_and_sanitize_string("Test String\n", false).is_ok(),
104 false
105 );
106 assert_eq!(
107 validate_and_sanitize_string("Test String\t", false).is_ok(),
108 false
109 );
110 assert_eq!(
111 validate_and_sanitize_string("Test String\t", true).is_ok(),
112 false
113 );
114 assert_eq!(
115 validate_and_sanitize_string("Test\n\rString", true).unwrap(),
116 "Test\nString"
117 );
118}