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