coqui_access_kit/
secret.rs1use data_encoding::{BASE64URL_NOPAD, HEXLOWER};
4use sha2::{Digest, Sha256};
5use subtle::ConstantTimeEq;
6
7pub const SECRET_CHARS: usize = 43;
9
10pub fn generate(prefix: &str) -> Result<String, String> {
18 let mut random = [0u8; 32];
19 getrandom::fill(&mut random).map_err(|_| "system random source is unavailable".to_owned())?;
20 Ok(format!("{prefix}{}", BASE64URL_NOPAD.encode(&random)))
21}
22
23pub fn identifier() -> Result<String, String> {
29 let mut random = [0u8; 16];
30 getrandom::fill(&mut random).map_err(|_| "system random source is unavailable".to_owned())?;
31 Ok(HEXLOWER.encode(&random))
32}
33
34pub fn hash(secret: &str, domain: Option<&str>) -> String {
39 let mut digest = Sha256::new();
40 if let Some(domain) = domain {
41 digest.update(domain.as_bytes());
42 digest.update([0]);
43 }
44 digest.update(secret.as_bytes());
45 HEXLOWER.encode(&digest.finalize())
46}
47
48pub fn hash_bytes(bytes: &[u8]) -> String {
50 HEXLOWER.encode(&Sha256::digest(bytes))
51}
52
53pub fn same(a: &str, b: &str) -> bool {
55 bool::from(a.as_bytes().ct_eq(b.as_bytes()))
56}
57
58pub fn is_hash(value: &str) -> bool {
60 value.len() == 64
61 && value
62 .bytes()
63 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
64}
65
66#[cfg(test)]
67mod tests {
68 use super::*;
69
70 #[test]
71 fn a_secret_is_prefixed_long_random_and_url_safe() {
72 let (one, other) = (generate("ck_").unwrap(), generate("ck_").unwrap());
73 assert_ne!(one, other);
74 for secret in [&one, &other] {
75 assert_eq!(secret.len(), 3 + SECRET_CHARS);
76 let letters = secret.strip_prefix("ck_").unwrap();
77 assert!(
78 letters
79 .chars()
80 .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
81 );
82 }
83 }
84
85 #[test]
86 fn hashes_are_sha256_hex_and_domain_separated() {
87 assert_eq!(
88 hash("abc", None),
89 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
90 );
91 assert_ne!(hash("abc", Some("login")), hash("abc", Some("ticket")));
92 assert_ne!(hash("abc", Some("login")), hash("abc", None));
93 assert!(is_hash(&hash("x", None)));
94 assert!(!is_hash("ABC"));
95 }
96
97 #[test]
98 fn a_secret_decodes_back_to_32_bytes() {
99 let secret = generate("").unwrap();
100 assert_eq!(BASE64URL_NOPAD.decode(secret.as_bytes()).unwrap().len(), 32);
101 assert_eq!(BASE64URL_NOPAD.encode(&[0xfb, 0xff]), "-_8");
102 }
103
104 #[test]
105 fn comparison_and_identifiers() {
106 assert!(same("abc", "abc"));
107 assert!(!same("abc", "abd") && !same("abc", "ab"));
108 let id = identifier().unwrap();
109 assert_eq!(id.len(), 32);
110 assert_ne!(id, identifier().unwrap());
111 }
112}