Skip to main content

coqui_access_kit/
secret.rs

1//! Secrets that are made, not chosen, and what is kept of them.
2
3use data_encoding::{BASE64URL_NOPAD, HEXLOWER};
4use sha2::{Digest, Sha256};
5use subtle::ConstantTimeEq;
6
7/// Characters of base64url text that 32 random bytes take.
8pub const SECRET_CHARS: usize = 43;
9
10/// Makes a secret: `prefix` followed by 256 random bits as 43 URL-safe base64 characters.
11///
12/// Random and that long, it needs no slow hash to be kept: keep [`hash`] of it.
13///
14/// # Errors
15///
16/// Returns an error when the operating system random source is unavailable.
17pub 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
23/// Makes a random 128-bit identifier as 32 lowercase hexadecimal characters.
24///
25/// # Errors
26///
27/// Returns an error when the operating system random source is unavailable.
28pub 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
34/// What a secret is kept as: its SHA-256 as 64 lowercase hexadecimal characters.
35///
36/// With a `domain`, the digest is over `domain`, a zero byte, then the secret, so a digest
37/// kept for one purpose cannot be presented for another.
38pub 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
48/// The SHA-256 of `bytes` as 64 lowercase hexadecimal characters.
49pub fn hash_bytes(bytes: &[u8]) -> String {
50    HEXLOWER.encode(&Sha256::digest(bytes))
51}
52
53/// Compares two strings in time that does not depend on where they differ.
54pub fn same(a: &str, b: &str) -> bool {
55    bool::from(a.as_bytes().ct_eq(b.as_bytes()))
56}
57
58/// Whether `value` is a SHA-256 digest as [`hash`] writes it.
59pub 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}