Skip to main content

isb_server/auth/
secret.rs

1//! Secrets: bearer tokens, their hashes, constant-time comparison, and
2//! argon2id password hashes.
3//!
4//! A token is 32 bytes from the OS (ring's `SystemRandom`, i.e. getrandom),
5//! base64url-encoded behind a prefix that says what it is (`isb_sess_`,
6//! `isb_tok_`, `isb_sa_`, `isb_ws_`, `isb_inv_`, `isb_rst_`, `isb_setup_`). It is shown once; the
7//! store keeps only its SHA-256. Looking a row up by that hash through an
8//! index leaks nothing useful (the input is 256 bits of randomness, so timing
9//! on the hash says nothing about any other token), and the row found is still
10//! compared with [`ct_eq`] before it is trusted.
11
12use std::sync::OnceLock;
13
14use argon2::{Algorithm, Argon2, Params, Version};
15use base64::Engine;
16use base64::engine::general_purpose::{STANDARD_NO_PAD, URL_SAFE_NO_PAD};
17use ring::rand::{SecureRandom, SystemRandom};
18
19use super::AuthError;
20
21/// What a token is for, and the prefix that marks it.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum TokenKind {
24    Session,
25    Api,
26    /// A superadmin token: the unix socket's reach over HTTP.
27    Superadmin,
28    /// An org's workspace token (docs/concepts/workspaces.md).
29    Workspace,
30    Invitation,
31    PasswordReset,
32    Setup,
33}
34
35impl TokenKind {
36    pub fn prefix(self) -> &'static str {
37        match self {
38            TokenKind::Session => "isb_sess_",
39            TokenKind::Api => "isb_tok_",
40            TokenKind::Superadmin => "isb_sa_",
41            TokenKind::Workspace => "isb_ws_",
42            TokenKind::Invitation => "isb_inv_",
43            TokenKind::PasswordReset => "isb_rst_",
44            TokenKind::Setup => "isb_setup_",
45        }
46    }
47}
48
49/// `n` bytes from the OS.
50pub fn random_bytes<const N: usize>() -> Result<[u8; N], AuthError> {
51    let mut b = [0u8; N];
52    SystemRandom::new()
53        .fill(&mut b)
54        .map_err(|_| AuthError::Internal("the OS random source failed".into()))?;
55    Ok(b)
56}
57
58/// A new token of `kind`: the string to hand out once, and the hash to store.
59pub fn new_token(kind: TokenKind) -> Result<(String, Vec<u8>), AuthError> {
60    let raw: [u8; 32] = random_bytes()?;
61    let token = format!("{}{}", kind.prefix(), URL_SAFE_NO_PAD.encode(raw));
62    let h = hash_token(&token);
63    Ok((token, h))
64}
65
66/// The stored form of a token: SHA-256 of the whole string, prefix included.
67pub fn hash_token(token: &str) -> Vec<u8> {
68    ring::digest::digest(&ring::digest::SHA256, token.as_bytes())
69        .as_ref()
70        .to_vec()
71}
72
73/// True when `token` has `kind`'s prefix and a well-formed body (43
74/// base64url characters). Anything else is refused before touching the store.
75pub fn well_formed(token: &str, kind: TokenKind) -> bool {
76    token.strip_prefix(kind.prefix()).is_some_and(|b| {
77        b.len() == 43
78            && b.bytes()
79                .all(|c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_')
80    })
81}
82
83/// Compare two byte strings in time that depends only on their lengths.
84pub fn ct_eq(a: &[u8], b: &[u8]) -> bool {
85    if a.len() != b.len() {
86        return false;
87    }
88    let mut d = 0u8;
89    for (x, y) in a.iter().zip(b) {
90        d |= x ^ y;
91    }
92    // Keep the optimiser from turning the fold into an early exit.
93    std::hint::black_box(d) == 0
94}
95
96/// Shortest password accepted.
97pub const MIN_PASSWORD_LEN: usize = 12;
98/// Longest password accepted: argon2 takes anything, but a megabyte of
99/// "password" is a denial of service, not a secret.
100pub const MAX_PASSWORD_LEN: usize = 1024;
101
102pub fn check_password_policy(pw: &str) -> Result<(), AuthError> {
103    let n = pw.chars().count();
104    if n < MIN_PASSWORD_LEN {
105        return Err(AuthError::Invalid(format!(
106            "password too short: at least {MIN_PASSWORD_LEN} characters"
107        )));
108    }
109    if pw.len() > MAX_PASSWORD_LEN {
110        return Err(AuthError::Invalid(format!(
111            "password too long: at most {MAX_PASSWORD_LEN} bytes"
112        )));
113    }
114    Ok(())
115}
116
117/// argon2id cost. The default is OWASP's recommendation (19 MiB, 2 passes,
118/// 1 lane), about 30 ms on a server core; tests use a cheap one.
119#[derive(Debug, Clone, Copy, PartialEq, Eq)]
120pub struct PasswordCost {
121    pub m_kib: u32,
122    pub t: u32,
123    pub p: u32,
124}
125
126impl Default for PasswordCost {
127    fn default() -> Self {
128        PasswordCost {
129            m_kib: Params::DEFAULT_M_COST,
130            t: Params::DEFAULT_T_COST,
131            p: Params::DEFAULT_P_COST,
132        }
133    }
134}
135
136impl PasswordCost {
137    /// For tests only: fast, and useless against an offline attacker.
138    pub fn insecure_fast() -> Self {
139        PasswordCost {
140            m_kib: 64,
141            t: 1,
142            p: 1,
143        }
144    }
145}
146
147fn argon(cost: PasswordCost) -> Result<Argon2<'static>, AuthError> {
148    let params = Params::new(cost.m_kib, cost.t, cost.p, Some(32))
149        .map_err(|e| AuthError::Internal(format!("argon2 parameters: {e}")))?;
150    Ok(Argon2::new(Algorithm::Argon2id, Version::V0x13, params))
151}
152
153/// Hash a password into a PHC string:
154/// `$argon2id$v=19$m=19456,t=2,p=1$<salt>$<hash>` (standard base64, no
155/// padding), the format every argon2 implementation reads.
156pub fn hash_password(pw: &str, cost: PasswordCost) -> Result<String, AuthError> {
157    let salt: [u8; 16] = random_bytes()?;
158    let mut out = [0u8; 32];
159    argon(cost)?
160        .hash_password_into(pw.as_bytes(), &salt, &mut out)
161        .map_err(|e| AuthError::Internal(format!("argon2: {e}")))?;
162    Ok(format!(
163        "$argon2id$v=19$m={},t={},p={}${}${}",
164        cost.m_kib,
165        cost.t,
166        cost.p,
167        STANDARD_NO_PAD.encode(salt),
168        STANDARD_NO_PAD.encode(out)
169    ))
170}
171
172/// Check a password against a PHC string written by [`hash_password`], with
173/// the cost recorded in it. A malformed hash never verifies.
174pub fn verify_password(pw: &str, phc: &str) -> bool {
175    let Some((cost, salt, want)) = parse_phc(phc) else {
176        return false;
177    };
178    let Ok(a) = argon(cost) else { return false };
179    let mut got = vec![0u8; want.len()];
180    a.hash_password_into(pw.as_bytes(), &salt, &mut got).is_ok() && ct_eq(&got, &want)
181}
182
183fn parse_phc(phc: &str) -> Option<(PasswordCost, Vec<u8>, Vec<u8>)> {
184    let mut parts = phc.split('$');
185    if !parts.next()?.is_empty() || parts.next()? != "argon2id" || parts.next()? != "v=19" {
186        return None;
187    }
188    let mut cost = PasswordCost {
189        m_kib: 0,
190        t: 0,
191        p: 0,
192    };
193    for kv in parts.next()?.split(',') {
194        let (k, v) = kv.split_once('=')?;
195        let v: u32 = v.parse().ok()?;
196        match k {
197            "m" => cost.m_kib = v,
198            "t" => cost.t = v,
199            "p" => cost.p = v,
200            _ => return None,
201        }
202    }
203    let salt = STANDARD_NO_PAD.decode(parts.next()?).ok()?;
204    let hash = STANDARD_NO_PAD.decode(parts.next()?).ok()?;
205    if parts.next().is_some() || hash.len() < 16 {
206        return None;
207    }
208    Some((cost, salt, hash))
209}
210
211/// A hash of a random password at `cost`, verified against when the email is
212/// unknown, so a miss costs as much as a wrong password and timing does not
213/// say which half was wrong. Computed once per `cell`.
214pub fn dummy_hash(cell: &OnceLock<String>, cost: PasswordCost) -> &str {
215    cell.get_or_init(|| {
216        let pw = URL_SAFE_NO_PAD.encode(random_bytes::<18>().unwrap_or([7; 18]));
217        hash_password(&pw, cost).unwrap_or_default()
218    })
219}
220
221#[cfg(test)]
222mod tests {
223    use super::*;
224
225    #[test]
226    fn tokens() {
227        let (t, h) = new_token(TokenKind::Session).unwrap();
228        assert!(t.starts_with("isb_sess_"));
229        assert!(well_formed(&t, TokenKind::Session));
230        assert!(!well_formed(&t, TokenKind::Api));
231        assert_eq!(h, hash_token(&t));
232        assert_eq!(h.len(), 32);
233        let (t2, _) = new_token(TokenKind::Session).unwrap();
234        assert_ne!(t, t2);
235        assert!(!well_formed("isb_sess_short", TokenKind::Session));
236        assert!(!well_formed(
237            &format!("isb_tok_{}", "!".repeat(43)),
238            TokenKind::Api
239        ));
240    }
241
242    #[test]
243    fn constant_time_compare() {
244        assert!(ct_eq(b"abc", b"abc"));
245        assert!(!ct_eq(b"abc", b"abd"));
246        assert!(!ct_eq(b"abc", b"ab"));
247        assert!(ct_eq(b"", b""));
248        let a = hash_token("x");
249        let mut b = a.clone();
250        assert!(ct_eq(&a, &b));
251        b[31] ^= 1;
252        assert!(!ct_eq(&a, &b));
253        b[31] ^= 1;
254        b[0] ^= 0x80;
255        assert!(!ct_eq(&a, &b));
256    }
257
258    #[test]
259    fn passwords() {
260        let c = PasswordCost::insecure_fast();
261        let h = hash_password("correct horse battery", c).unwrap();
262        assert!(h.starts_with("$argon2id$v=19$m=64,t=1,p=1$"));
263        assert!(verify_password("correct horse battery", &h));
264        assert!(!verify_password("correct horse batterz", &h));
265        assert!(!verify_password("correct horse battery", "garbage"));
266        assert!(!verify_password("x", ""));
267        // Salted: the same password hashes differently.
268        assert_ne!(h, hash_password("correct horse battery", c).unwrap());
269        let cell = OnceLock::new();
270        let d = dummy_hash(&cell, c).to_string();
271        assert!(!verify_password("a", &d));
272        assert_eq!(dummy_hash(&cell, c), d);
273    }
274
275    #[test]
276    fn default_cost_is_owasp() {
277        let h = hash_password("correct horse battery", PasswordCost::default()).unwrap();
278        assert!(h.starts_with("$argon2id$v=19$m=19456,t=2,p=1$"));
279        assert!(verify_password("correct horse battery", &h));
280    }
281
282    #[test]
283    fn policy() {
284        assert!(check_password_policy("short").is_err());
285        assert!(check_password_policy("exactly12chr").is_ok());
286        assert!(check_password_policy(&"x".repeat(2000)).is_err());
287    }
288}