Skip to main content

fastauth_core/
crypto.rs

1//! Secrets, derived keys, signing, encryption, hashing and password hashing.
2//! See `docs/concepts/03-security.md`.
3
4use std::fmt;
5use std::sync::Arc;
6
7use base64::Engine as _;
8use base64::engine::general_purpose::URL_SAFE_NO_PAD as B64;
9use chacha20poly1305::XChaCha20Poly1305;
10use chacha20poly1305::aead::{Aead, KeyInit};
11use hmac::{Hmac, Mac};
12use sha2::{Digest, Sha256};
13use subtle::ConstantTimeEq;
14use tokio::sync::Semaphore;
15use zeroize::Zeroizing;
16
17use crate::error::BuildError;
18
19type HmacSha256 = Hmac<Sha256>;
20
21/// A master secret. Zeroized on drop; never printed.
22#[derive(Clone)]
23pub struct Secret(Zeroizing<Vec<u8>>);
24
25impl Secret {
26    pub const MIN_LEN: usize = 32;
27
28    /// The least estimated entropy `.build()` accepts for a production `base_url`, as in
29    /// Better Auth. See [`Secret::entropy_bits`].
30    pub const MIN_ENTROPY_BITS: f64 = 120.0;
31
32    /// A rough entropy estimate: the bytes a guesser can't predict, times log2 of the
33    /// alphabet. A run of four or more bytes that repeats earlier bytes (`changeme` again,
34    /// `aaaa`) or counts up or down by one (`abcd`, `6543`) counts as two bytes, where it
35    /// starts and what it follows. The alphabet is the smallest of hex digits, letters and
36    /// digits, base64, printable ASCII or any byte that holds every byte of the secret, but at
37    /// most twice the distinct bytes seen, so a secret drawn from a handful of characters
38    /// scores low. A generated secret scores about
39    /// 440 bits, `openssl rand -hex 16` about 128; one repeated byte scores 0.
40    pub fn entropy_bits(&self) -> f64 {
41        let bytes: &[u8] = &self.0;
42        let mut seen = [false; 256];
43        for byte in bytes {
44            seen[usize::from(*byte)] = true;
45        }
46        let distinct = seen.iter().filter(|s| **s).count();
47        if distinct < 2 {
48            return 0.0;
49        }
50        let all = |class: fn(&u8) -> bool| bytes.iter().all(class);
51        let class = if all(u8::is_ascii_hexdigit)
52            && (all(|b| !b.is_ascii_uppercase()) || all(|b| !b.is_ascii_lowercase()))
53        {
54            16
55        } else if all(u8::is_ascii_alphanumeric) {
56            62
57        } else if all(|b| b.is_ascii_alphanumeric() || b"-_+/=".contains(b)) {
58            64
59        } else if all(|b| (0x20..0x7f).contains(b)) {
60            95
61        } else {
62            256
63        };
64        let alphabet = class.min(2 * distinct) as f64;
65        let mut unpredictable = 0;
66        let mut i = 0;
67        while i < bytes.len() {
68            let repeat = (0..i)
69                .map(|j| {
70                    (0..bytes.len() - i)
71                        .take_while(|&k| bytes[j + k] == bytes[i + k])
72                        .count()
73                })
74                .max()
75                .unwrap_or(0);
76            let step = |delta: i16| {
77                1 + (i + 1..bytes.len())
78                    .take_while(|&k| i16::from(bytes[k]) - i16::from(bytes[k - 1]) == delta)
79                    .count()
80            };
81            let run = repeat.max(step(1)).max(step(-1));
82            if run >= 4 {
83                unpredictable += 2;
84                i += run;
85            } else {
86                unpredictable += 1;
87                i += 1;
88            }
89        }
90        unpredictable as f64 * alphabet.log2()
91    }
92
93    /// Raw bytes. Prefer `from_env` or `from_base64` so the secret never sits in source.
94    pub fn from_bytes(bytes: impl Into<Vec<u8>>) -> Self {
95        Secret(Zeroizing::new(bytes.into()))
96    }
97
98    /// Accepts base64url (what `fastauth secret` prints) or, failing that, the raw string.
99    pub fn from_base64(value: &str) -> Self {
100        match B64.decode(value.trim()) {
101            Ok(bytes) if bytes.len() >= Self::MIN_LEN => Secret::from_bytes(bytes),
102            _ => Secret::from_bytes(value.as_bytes().to_vec()),
103        }
104    }
105
106    pub fn from_env(var: &str) -> Result<Self, BuildError> {
107        let value = std::env::var(var)
108            .map_err(|_| BuildError::new(format!("environment variable `{var}` is not set")))?;
109        Ok(Secret::from_base64(&value))
110    }
111
112    /// 64 random bytes as base64url: a fresh secret.
113    pub fn generate() -> String {
114        B64.encode(random_bytes::<64>())
115    }
116
117    pub(crate) fn len(&self) -> usize {
118        self.0.len()
119    }
120
121    fn derive(&self, info: &str) -> Zeroizing<[u8; 32]> {
122        let hk = hkdf::Hkdf::<Sha256>::new(Some(b"fastauth"), &self.0);
123        let mut out = Zeroizing::new([0u8; 32]);
124        hk.expand(info.as_bytes(), out.as_mut())
125            .expect("32 bytes is a valid HKDF output length");
126        out
127    }
128}
129
130impl fmt::Debug for Secret {
131    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
132        f.write_str("Secret(..)")
133    }
134}
135
136pub fn random_bytes<const N: usize>() -> [u8; N] {
137    let mut buf = [0u8; N];
138    getrandom::fill(&mut buf).expect("the OS random number generator is available");
139    buf
140}
141
142/// 32 random bytes as base64url (43 chars): session tokens, verification values, state.
143pub fn random_token() -> String {
144    B64.encode(random_bytes::<32>())
145}
146
147/// A random string from `alphabet`, without modulo bias.
148pub fn random_string(len: usize, alphabet: &[u8]) -> String {
149    assert!(!alphabet.is_empty() && alphabet.len() <= 256);
150    let limit = 256 - (256 % alphabet.len());
151    let mut out = String::with_capacity(len);
152    while out.len() < len {
153        for byte in random_bytes::<64>() {
154            if (byte as usize) < limit && out.len() < len {
155                out.push(alphabet[byte as usize % alphabet.len()] as char);
156            }
157        }
158    }
159    out
160}
161
162pub fn base64url(bytes: &[u8]) -> String {
163    B64.encode(bytes)
164}
165
166pub fn base64url_decode(s: &str) -> Option<Vec<u8>> {
167    B64.decode(s).ok()
168}
169
170/// SHA-256 digest. Stored instead of tokens.
171#[derive(Clone, Copy, PartialEq, Eq, Hash)]
172pub struct Hash([u8; 32]);
173
174impl Hash {
175    pub fn sha256(data: impl AsRef<[u8]>) -> Self {
176        Hash(Sha256::digest(data.as_ref()).into())
177    }
178
179    pub fn as_bytes(&self) -> &[u8; 32] {
180        &self.0
181    }
182
183    pub fn from_slice(bytes: &[u8]) -> Option<Self> {
184        bytes.try_into().ok().map(Hash)
185    }
186}
187
188impl fmt::Debug for Hash {
189    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
190        write!(f, "Hash({}..)", &base64url(&self.0)[..8])
191    }
192}
193
194/// Constant-time string equality.
195pub fn ct_eq(a: &[u8], b: &[u8]) -> bool {
196    a.ct_eq(b).into()
197}
198
199/// Keys derived from the configured secrets. The first secret signs, verifies and encrypts.
200/// Every secret decrypts, so encrypted columns stay readable after a rotation, and every
201/// secret verifies a signed session token ([`Keys::verify_token`]), which is only a
202/// pointer to a session row, so rotating signs nobody out. A retired secret can't sign
203/// anything self-contained (the cookie cache, plugin cookies) that is accepted.
204pub struct Keys {
205    cookie: Vec<Zeroizing<[u8; 32]>>,
206    cache: Vec<Zeroizing<[u8; 32]>>,
207    encrypt: Vec<Zeroizing<[u8; 32]>>,
208    secrets: Vec<Secret>,
209}
210
211impl fmt::Debug for Keys {
212    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
213        write!(f, "Keys({} secrets)", self.secrets.len())
214    }
215}
216
217#[derive(Clone, Copy, Debug, PartialEq, Eq)]
218pub enum SignPurpose {
219    Cookie,
220    CookieCache,
221}
222
223impl Keys {
224    pub(crate) fn new(secrets: Vec<Secret>) -> Self {
225        Self {
226            cookie: secrets
227                .iter()
228                .map(|s| s.derive("fastauth/v1/cookie"))
229                .collect(),
230            cache: secrets
231                .iter()
232                .map(|s| s.derive("fastauth/v1/cookie-cache"))
233                .collect(),
234            encrypt: secrets
235                .iter()
236                .map(|s| s.derive("fastauth/v1/encrypt"))
237                .collect(),
238            secrets,
239        }
240    }
241
242    fn sign_keys(&self, purpose: SignPurpose) -> &[Zeroizing<[u8; 32]>] {
243        match purpose {
244            SignPurpose::Cookie => &self.cookie,
245            SignPurpose::CookieCache => &self.cache,
246        }
247    }
248
249    fn mac(key: &[u8; 32], value: &str) -> HmacSha256 {
250        let mut mac =
251            <HmacSha256 as KeyInit>::new_from_slice(key).expect("HMAC takes any key length");
252        mac.update(value.as_bytes());
253        mac
254    }
255
256    /// `value.signature`, signature base64url.
257    pub fn sign(&self, purpose: SignPurpose, value: &str) -> String {
258        let tag = Self::mac(&self.sign_keys(purpose)[0], value)
259            .finalize()
260            .into_bytes();
261        format!("{value}.{}", B64.encode(tag))
262    }
263
264    /// The value, when the current (first) secret signed it. For values that carry their
265    /// own meaning, like the cookie cache or a plugin's signed cookie.
266    pub fn verify<'a>(&self, purpose: SignPurpose, signed: &'a str) -> Option<&'a str> {
267        Self::verify_with(&self.sign_keys(purpose)[..1], signed)
268    }
269
270    /// A session token signed with [`SignPurpose::Cookie`] by any configured secret. Only
271    /// for raw session tokens, and for markers that only restrict the session they come
272    /// with (the `rememberMe: false` flag): a token means nothing until its session row is
273    /// found, and a forged marker only shortens a session, so a retired secret can't gain
274    /// anything, and values signed before a rotation keep working.
275    pub fn verify_token<'a>(&self, signed: &'a str) -> Option<&'a str> {
276        Self::verify_with(&self.cookie, signed)
277    }
278
279    fn verify_with<'a>(keys: &[Zeroizing<[u8; 32]>], signed: &'a str) -> Option<&'a str> {
280        let (value, sig) = signed.rsplit_once('.')?;
281        let sig = B64.decode(sig).ok()?;
282        keys.iter()
283            .any(|key| Self::mac(key, value).verify_slice(&sig).is_ok())
284            .then_some(value)
285    }
286
287    /// `[key id][24-byte nonce][ciphertext]`.
288    pub fn encrypt(&self, plaintext: &[u8]) -> Vec<u8> {
289        let cipher =
290            XChaCha20Poly1305::new_from_slice(self.encrypt[0].as_ref()).expect("32-byte key");
291        let nonce_bytes = random_bytes::<24>();
292        let nonce = chacha20poly1305::XNonce::from(nonce_bytes);
293        let ciphertext = cipher
294            .encrypt(&nonce, plaintext)
295            .expect("XChaCha20-Poly1305 encryption cannot fail");
296        let mut out = Vec::with_capacity(1 + 24 + ciphertext.len());
297        out.push(0);
298        out.extend_from_slice(&nonce_bytes);
299        out.extend_from_slice(&ciphertext);
300        out
301    }
302
303    pub fn decrypt(&self, data: &[u8]) -> Option<Vec<u8>> {
304        if data.len() < 25 {
305            return None;
306        }
307        let (nonce, ciphertext) = data[1..].split_at(24);
308        let nonce = chacha20poly1305::XNonce::try_from(nonce).ok()?;
309        self.encrypt.iter().find_map(|key| {
310            let cipher = XChaCha20Poly1305::new_from_slice(key.as_ref()).ok()?;
311            cipher.decrypt(&nonce, ciphertext).ok()
312        })
313    }
314
315    /// The key of the rate limiter's account buckets, the same on every instance.
316    pub(crate) fn rate_limit_key(&self) -> Zeroizing<[u8; 32]> {
317        self.secrets[0].derive("fastauth/v1/rate-limit")
318    }
319
320    /// A per-plugin key, so plugins can't reach core's keys.
321    pub fn derive_key(&self, plugin_id: &str) -> Zeroizing<[u8; 32]> {
322        self.secrets[0].derive(&format!("fastauth/v1/plugin/{plugin_id}"))
323    }
324}
325
326/// Password hashing. Runs on a blocking thread; see `Passwords`.
327pub trait PasswordHasher: Send + Sync + 'static {
328    fn hash(&self, password: &str) -> Result<String, String>;
329    fn verify(&self, password: &str, hash: &str) -> Result<bool, String>;
330    /// Whether a stored hash should be replaced on the next successful sign-in.
331    fn needs_rehash(&self, hash: &str) -> bool {
332        let _ = hash;
333        false
334    }
335}
336
337/// argon2id with OWASP parameters: 19 MiB, t=2, p=1.
338#[derive(Debug, Clone)]
339pub struct Argon2id {
340    params: argon2::Params,
341}
342
343impl Argon2id {
344    pub fn owasp() -> Self {
345        Self::with_params(19 * 1024, 2, 1)
346    }
347
348    pub fn with_params(m_cost_kib: u32, t_cost: u32, p_cost: u32) -> Self {
349        let params =
350            argon2::Params::new(m_cost_kib, t_cost, p_cost, None).expect("valid argon2 parameters");
351        Self { params }
352    }
353
354    fn engine(&self) -> argon2::Argon2<'static> {
355        argon2::Argon2::new(
356            argon2::Algorithm::Argon2id,
357            argon2::Version::V0x13,
358            self.params.clone(),
359        )
360    }
361}
362
363impl Default for Argon2id {
364    fn default() -> Self {
365        Self::owasp()
366    }
367}
368
369impl PasswordHasher for Argon2id {
370    fn hash(&self, password: &str) -> Result<String, String> {
371        use argon2::password_hash::PasswordHasher as _;
372        self.engine()
373            .hash_password(password.as_bytes())
374            .map(|h| h.to_string())
375            .map_err(|e| e.to_string())
376    }
377
378    fn verify(&self, password: &str, hash: &str) -> Result<bool, String> {
379        use argon2::password_hash::PasswordVerifier as _;
380        let parsed =
381            argon2::password_hash::phc::PasswordHash::new(hash).map_err(|e| e.to_string())?;
382        Ok(self
383            .engine()
384            .verify_password(password.as_bytes(), &parsed)
385            .is_ok())
386    }
387
388    fn needs_rehash(&self, hash: &str) -> bool {
389        let Ok(parsed) = argon2::password_hash::phc::PasswordHash::new(hash) else {
390            return true;
391        };
392        let Ok(params) = argon2::Params::try_from(&parsed) else {
393            return true;
394        };
395        parsed.algorithm.as_str() != "argon2id"
396            || params.m_cost() < self.params.m_cost()
397            || params.t_cost() < self.params.t_cost()
398    }
399}
400
401/// Runs a `PasswordHasher` on the blocking pool behind a semaphore, so a burst of sign-ins
402/// can't allocate unbounded argon2 memory.
403#[derive(Clone)]
404pub struct Passwords {
405    hasher: Arc<dyn PasswordHasher>,
406    permits: Arc<Semaphore>,
407    dummy_hash: Arc<std::sync::OnceLock<String>>,
408}
409
410impl fmt::Debug for Passwords {
411    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
412        f.write_str("Passwords(..)")
413    }
414}
415
416impl Passwords {
417    pub fn new(hasher: Arc<dyn PasswordHasher>) -> Self {
418        let cpus = std::thread::available_parallelism().map_or(2, |n| n.get());
419        Self {
420            hasher,
421            permits: Arc::new(Semaphore::new(cpus)),
422            dummy_hash: Arc::default(),
423        }
424    }
425
426    /// The permit moves into the blocking task and is released when the hash finishes, not
427    /// when the request's future does: a request dropped mid-hash (a client that disconnects,
428    /// a timeout layer) leaves argon2 running, and its permit with it.
429    async fn run<T: Send + 'static>(
430        &self,
431        f: impl FnOnce(&dyn PasswordHasher) -> T + Send + 'static,
432    ) -> T {
433        let permit = self
434            .permits
435            .clone()
436            .acquire_owned()
437            .await
438            .expect("semaphore is never closed");
439        let hasher = self.hasher.clone();
440        match tokio::runtime::Handle::try_current() {
441            Ok(handle) => handle
442                .spawn_blocking(move || {
443                    let _permit = permit;
444                    f(hasher.as_ref())
445                })
446                .await
447                .expect("password hashing task panicked"),
448            Err(_) => f(hasher.as_ref()),
449        }
450    }
451
452    pub async fn hash(&self, password: &str) -> Result<String, String> {
453        let password = Zeroizing::new(password.to_owned());
454        self.run(move |h| h.hash(&password)).await
455    }
456
457    pub async fn verify(&self, password: &str, hash: &str) -> Result<bool, String> {
458        let password = Zeroizing::new(password.to_owned());
459        let hash = hash.to_owned();
460        self.run(move |h| h.verify(&password, &hash)).await
461    }
462
463    pub fn needs_rehash(&self, hash: &str) -> bool {
464        self.hasher.needs_rehash(hash)
465    }
466
467    /// Spends the same time as a real verification, for unknown emails: one run of the
468    /// hasher. The first call hashes the dummy password, which costs what a verification
469    /// does, and later calls verify against it.
470    pub async fn verify_dummy(&self, password: &str) {
471        match self.dummy_hash.get() {
472            Some(dummy) => {
473                let _ = self.verify(password, &dummy.clone()).await;
474            }
475            None => {
476                let dummy = self
477                    .hash("fastauth-dummy-password")
478                    .await
479                    .unwrap_or_default();
480                let _ = self.dummy_hash.set(dummy);
481            }
482        }
483    }
484}
485
486#[cfg(test)]
487mod tests {
488    use super::*;
489
490    fn keys() -> Keys {
491        Keys::new(vec![Secret::from_bytes(vec![7u8; 32])])
492    }
493
494    #[test]
495    fn sign_round_trips_and_rejects_tampering() {
496        let keys = keys();
497        let signed = keys.sign(SignPurpose::Cookie, "token");
498        assert_eq!(keys.verify(SignPurpose::Cookie, &signed), Some("token"));
499        assert_eq!(keys.verify(SignPurpose::CookieCache, &signed), None);
500        assert_eq!(
501            keys.verify(SignPurpose::Cookie, &signed.replace("token", "tokem")),
502            None
503        );
504    }
505
506    #[test]
507    fn rotation_keeps_old_tokens_and_ciphertexts_but_not_old_signatures() {
508        let old = keys();
509        let signed = old.sign(SignPurpose::Cookie, "v");
510        let cached = old.sign(SignPurpose::CookieCache, "v");
511        let rotated = Keys::new(vec![
512            Secret::from_bytes(vec![9u8; 32]),
513            Secret::from_bytes(vec![7u8; 32]),
514        ]);
515        assert_eq!(rotated.verify_token(&signed), Some("v"));
516        assert_eq!(rotated.verify(SignPurpose::Cookie, &signed), None);
517        assert_eq!(rotated.verify(SignPurpose::CookieCache, &cached), None);
518        let fresh = rotated.sign(SignPurpose::CookieCache, "v");
519        assert_eq!(rotated.verify(SignPurpose::CookieCache, &fresh), Some("v"));
520        assert_eq!(
521            rotated.decrypt(&old.encrypt(b"hi")).as_deref(),
522            Some(&b"hi"[..])
523        );
524    }
525
526    #[test]
527    fn encryption_round_trips() {
528        let keys = keys();
529        let sealed = keys.encrypt(b"secret");
530        assert_ne!(&sealed[25..], b"secret");
531        assert_eq!(keys.decrypt(&sealed).unwrap(), b"secret");
532    }
533
534    #[test]
535    fn argon2_hashes_and_verifies() {
536        let hasher = Argon2id::with_params(1024, 1, 1);
537        let hash = hasher.hash("correct horse").unwrap();
538        assert!(hash.starts_with("$argon2id$"));
539        assert!(hasher.verify("correct horse", &hash).unwrap());
540        assert!(!hasher.verify("wrong", &hash).unwrap());
541        assert!(Argon2id::owasp().needs_rehash(&hash));
542    }
543
544    #[test]
545    fn entropy_estimate_separates_generated_from_guessable_secrets() {
546        assert!(Secret::from_base64(&Secret::generate()).entropy_bits() > 300.0);
547        assert_eq!(Secret::from_bytes(vec![0u8; 32]).entropy_bits(), 0.0);
548        assert!(
549            Secret::from_base64("password password password pass!").entropy_bits()
550                < Secret::MIN_ENTROPY_BITS
551        );
552    }
553
554    #[test]
555    fn random_string_uses_alphabet() {
556        let s = random_string(40, b"ab");
557        assert_eq!(s.len(), 40);
558        assert!(s.bytes().all(|b| b == b'a' || b == b'b'));
559    }
560}