1use 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#[derive(Clone)]
23pub struct Secret(Zeroizing<Vec<u8>>);
24
25impl Secret {
26 pub const MIN_LEN: usize = 32;
27
28 pub const MIN_ENTROPY_BITS: f64 = 120.0;
31
32 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 pub fn from_bytes(bytes: impl Into<Vec<u8>>) -> Self {
95 Secret(Zeroizing::new(bytes.into()))
96 }
97
98 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 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
142pub fn random_token() -> String {
144 B64.encode(random_bytes::<32>())
145}
146
147pub 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#[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
194pub fn ct_eq(a: &[u8], b: &[u8]) -> bool {
196 a.ct_eq(b).into()
197}
198
199pub 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 better_auth: Option<Secret>,
210}
211
212impl fmt::Debug for Keys {
213 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
214 write!(f, "Keys({} secrets)", self.secrets.len())
215 }
216}
217
218#[derive(Clone, Copy, Debug, PartialEq, Eq)]
219pub enum SignPurpose {
220 Cookie,
221 CookieCache,
222}
223
224impl Keys {
225 pub(crate) fn new(secrets: Vec<Secret>) -> Self {
226 Self {
227 cookie: secrets
228 .iter()
229 .map(|s| s.derive("fastauth/v1/cookie"))
230 .collect(),
231 cache: secrets
232 .iter()
233 .map(|s| s.derive("fastauth/v1/cookie-cache"))
234 .collect(),
235 encrypt: secrets
236 .iter()
237 .map(|s| s.derive("fastauth/v1/encrypt"))
238 .collect(),
239 secrets,
240 better_auth: None,
241 }
242 }
243
244 pub(crate) fn with_cookie_signing(mut self, signing: &crate::config::CookieSigning) -> Self {
246 self.better_auth = match signing {
247 crate::config::CookieSigning::Fastauth => None,
248 crate::config::CookieSigning::BetterAuth(secret) => Some(secret.clone()),
249 };
250 self
251 }
252
253 fn sign_keys(&self, purpose: SignPurpose) -> &[Zeroizing<[u8; 32]>] {
254 match purpose {
255 SignPurpose::Cookie => &self.cookie,
256 SignPurpose::CookieCache => &self.cache,
257 }
258 }
259
260 fn mac(key: &[u8; 32], value: &str) -> HmacSha256 {
261 let mut mac =
262 <HmacSha256 as KeyInit>::new_from_slice(key).expect("HMAC takes any key length");
263 mac.update(value.as_bytes());
264 mac
265 }
266
267 pub fn sign(&self, purpose: SignPurpose, value: &str) -> String {
270 if let (SignPurpose::Cookie, Some(secret)) = (purpose, &self.better_auth) {
271 return crate::compat::sign_cookie(&secret.0, value);
272 }
273 let tag = Self::mac(&self.sign_keys(purpose)[0], value)
274 .finalize()
275 .into_bytes();
276 format!("{value}.{}", B64.encode(tag))
277 }
278
279 pub fn verify<'a>(&self, purpose: SignPurpose, signed: &'a str) -> Option<&'a str> {
285 if let (SignPurpose::Cookie, Some(secret)) = (purpose, &self.better_auth) {
286 return crate::compat::verify_cookie(&secret.0, signed);
287 }
288 Self::verify_with(&self.sign_keys(purpose)[..1], signed)
289 }
290
291 pub fn verify_token<'a>(&self, signed: &'a str) -> Option<&'a str> {
299 if let Some(secret) = &self.better_auth {
300 return crate::compat::verify_cookie(&secret.0, signed);
301 }
302 Self::verify_with(&self.cookie, signed)
303 }
304
305 pub fn decode_cookie<'a>(&self, raw: &'a str) -> std::borrow::Cow<'a, str> {
309 match self.better_auth {
310 Some(_) => crate::compat::decode_cookie(raw),
311 None => std::borrow::Cow::Borrowed(raw),
312 }
313 }
314
315 fn verify_with<'a>(keys: &[Zeroizing<[u8; 32]>], signed: &'a str) -> Option<&'a str> {
316 let (value, sig) = signed.rsplit_once('.')?;
317 let sig = B64.decode(sig).ok()?;
318 keys.iter()
319 .any(|key| Self::mac(key, value).verify_slice(&sig).is_ok())
320 .then_some(value)
321 }
322
323 pub fn encrypt(&self, plaintext: &[u8]) -> Vec<u8> {
325 let cipher =
326 XChaCha20Poly1305::new_from_slice(self.encrypt[0].as_ref()).expect("32-byte key");
327 let nonce_bytes = random_bytes::<24>();
328 let nonce = chacha20poly1305::XNonce::from(nonce_bytes);
329 let ciphertext = cipher
330 .encrypt(&nonce, plaintext)
331 .expect("XChaCha20-Poly1305 encryption cannot fail");
332 let mut out = Vec::with_capacity(1 + 24 + ciphertext.len());
333 out.push(0);
334 out.extend_from_slice(&nonce_bytes);
335 out.extend_from_slice(&ciphertext);
336 out
337 }
338
339 pub fn decrypt(&self, data: &[u8]) -> Option<Vec<u8>> {
340 if data.len() < 25 {
341 return None;
342 }
343 let (nonce, ciphertext) = data[1..].split_at(24);
344 let nonce = chacha20poly1305::XNonce::try_from(nonce).ok()?;
345 self.encrypt.iter().find_map(|key| {
346 let cipher = XChaCha20Poly1305::new_from_slice(key.as_ref()).ok()?;
347 cipher.decrypt(&nonce, ciphertext).ok()
348 })
349 }
350
351 pub(crate) fn rate_limit_key(&self) -> Zeroizing<[u8; 32]> {
353 self.secrets[0].derive("fastauth/v1/rate-limit")
354 }
355
356 pub fn derive_key(&self, plugin_id: &str) -> Zeroizing<[u8; 32]> {
358 self.secrets[0].derive(&format!("fastauth/v1/plugin/{plugin_id}"))
359 }
360}
361
362pub trait PasswordHasher: Send + Sync + 'static {
364 fn hash(&self, password: &str) -> Result<String, String>;
365 fn verify(&self, password: &str, hash: &str) -> Result<bool, String>;
366 fn needs_rehash(&self, hash: &str) -> bool {
368 let _ = hash;
369 false
370 }
371}
372
373#[derive(Debug, Clone)]
375pub struct Argon2id {
376 params: argon2::Params,
377}
378
379impl Argon2id {
380 pub fn owasp() -> Self {
381 Self::with_params(19 * 1024, 2, 1)
382 }
383
384 pub fn with_params(m_cost_kib: u32, t_cost: u32, p_cost: u32) -> Self {
385 let params =
386 argon2::Params::new(m_cost_kib, t_cost, p_cost, None).expect("valid argon2 parameters");
387 Self { params }
388 }
389
390 fn engine(&self) -> argon2::Argon2<'static> {
391 argon2::Argon2::new(
392 argon2::Algorithm::Argon2id,
393 argon2::Version::V0x13,
394 self.params.clone(),
395 )
396 }
397}
398
399impl Default for Argon2id {
400 fn default() -> Self {
401 Self::owasp()
402 }
403}
404
405impl PasswordHasher for Argon2id {
406 fn hash(&self, password: &str) -> Result<String, String> {
407 use argon2::password_hash::PasswordHasher as _;
408 self.engine()
409 .hash_password(password.as_bytes())
410 .map(|h| h.to_string())
411 .map_err(|e| e.to_string())
412 }
413
414 fn verify(&self, password: &str, hash: &str) -> Result<bool, String> {
415 use argon2::password_hash::PasswordVerifier as _;
416 let parsed =
417 argon2::password_hash::phc::PasswordHash::new(hash).map_err(|e| e.to_string())?;
418 Ok(self
419 .engine()
420 .verify_password(password.as_bytes(), &parsed)
421 .is_ok())
422 }
423
424 fn needs_rehash(&self, hash: &str) -> bool {
425 let Ok(parsed) = argon2::password_hash::phc::PasswordHash::new(hash) else {
426 return true;
427 };
428 let Ok(params) = argon2::Params::try_from(&parsed) else {
429 return true;
430 };
431 parsed.algorithm.as_str() != "argon2id"
432 || params.m_cost() < self.params.m_cost()
433 || params.t_cost() < self.params.t_cost()
434 }
435}
436
437#[derive(Clone)]
440pub struct Passwords {
441 hasher: Arc<dyn PasswordHasher>,
442 permits: Arc<Semaphore>,
443 dummy_hash: Arc<std::sync::OnceLock<String>>,
444}
445
446impl fmt::Debug for Passwords {
447 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
448 f.write_str("Passwords(..)")
449 }
450}
451
452impl Passwords {
453 pub fn new(hasher: Arc<dyn PasswordHasher>) -> Self {
455 let cpus = std::thread::available_parallelism().map_or(2, |n| n.get());
456 Self::with_concurrency(hasher, cpus)
457 }
458
459 pub fn with_concurrency(hasher: Arc<dyn PasswordHasher>, permits: usize) -> Self {
461 Self {
462 hasher,
463 permits: Arc::new(Semaphore::new(permits.max(1))),
464 dummy_hash: Arc::default(),
465 }
466 }
467
468 async fn run<T: Send + 'static>(
472 &self,
473 f: impl FnOnce(&dyn PasswordHasher) -> T + Send + 'static,
474 ) -> T {
475 let permit = self
476 .permits
477 .clone()
478 .acquire_owned()
479 .await
480 .expect("semaphore is never closed");
481 let hasher = self.hasher.clone();
482 match tokio::runtime::Handle::try_current() {
483 Ok(handle) => handle
484 .spawn_blocking(move || {
485 let _permit = permit;
486 f(hasher.as_ref())
487 })
488 .await
489 .expect("password hashing task panicked"),
490 Err(_) => f(hasher.as_ref()),
491 }
492 }
493
494 pub async fn hash(&self, password: &str) -> Result<String, String> {
495 let password = Zeroizing::new(password.to_owned());
496 self.run(move |h| h.hash(&password)).await
497 }
498
499 pub async fn verify(&self, password: &str, hash: &str) -> Result<bool, String> {
500 let password = Zeroizing::new(password.to_owned());
501 let hash = hash.to_owned();
502 self.run(move |h| h.verify(&password, &hash)).await
503 }
504
505 pub fn needs_rehash(&self, hash: &str) -> bool {
506 self.hasher.needs_rehash(hash)
507 }
508
509 pub async fn verify_dummy(&self, password: &str) {
513 match self.dummy_hash.get() {
514 Some(dummy) => {
515 let _ = self.verify(password, &dummy.clone()).await;
516 }
517 None => {
518 let dummy = self
519 .hash("fastauth-dummy-password")
520 .await
521 .unwrap_or_default();
522 let _ = self.dummy_hash.set(dummy);
523 }
524 }
525 }
526}
527
528#[cfg(test)]
529mod tests {
530 use super::*;
531
532 fn keys() -> Keys {
533 Keys::new(vec![Secret::from_bytes(vec![7u8; 32])])
534 }
535
536 #[test]
537 fn sign_round_trips_and_rejects_tampering() {
538 let keys = keys();
539 let signed = keys.sign(SignPurpose::Cookie, "token");
540 assert_eq!(keys.verify(SignPurpose::Cookie, &signed), Some("token"));
541 assert_eq!(keys.verify(SignPurpose::CookieCache, &signed), None);
542 assert_eq!(
543 keys.verify(SignPurpose::Cookie, &signed.replace("token", "tokem")),
544 None
545 );
546 }
547
548 #[test]
549 fn rotation_keeps_old_tokens_and_ciphertexts_but_not_old_signatures() {
550 let old = keys();
551 let signed = old.sign(SignPurpose::Cookie, "v");
552 let cached = old.sign(SignPurpose::CookieCache, "v");
553 let rotated = Keys::new(vec![
554 Secret::from_bytes(vec![9u8; 32]),
555 Secret::from_bytes(vec![7u8; 32]),
556 ]);
557 assert_eq!(rotated.verify_token(&signed), Some("v"));
558 assert_eq!(rotated.verify(SignPurpose::Cookie, &signed), None);
559 assert_eq!(rotated.verify(SignPurpose::CookieCache, &cached), None);
560 let fresh = rotated.sign(SignPurpose::CookieCache, "v");
561 assert_eq!(rotated.verify(SignPurpose::CookieCache, &fresh), Some("v"));
562 assert_eq!(
563 rotated.decrypt(&old.encrypt(b"hi")).as_deref(),
564 Some(&b"hi"[..])
565 );
566 }
567
568 #[test]
569 fn encryption_round_trips() {
570 let keys = keys();
571 let sealed = keys.encrypt(b"secret");
572 assert_ne!(&sealed[25..], b"secret");
573 assert_eq!(keys.decrypt(&sealed).unwrap(), b"secret");
574 }
575
576 #[test]
577 fn argon2_hashes_and_verifies() {
578 let hasher = Argon2id::with_params(1024, 1, 1);
579 let hash = hasher.hash("correct horse").unwrap();
580 assert!(hash.starts_with("$argon2id$"));
581 assert!(hasher.verify("correct horse", &hash).unwrap());
582 assert!(!hasher.verify("wrong", &hash).unwrap());
583 assert!(Argon2id::owasp().needs_rehash(&hash));
584 }
585
586 #[test]
587 fn entropy_estimate_separates_generated_from_guessable_secrets() {
588 assert!(Secret::from_base64(&Secret::generate()).entropy_bits() > 300.0);
589 assert_eq!(Secret::from_bytes(vec![0u8; 32]).entropy_bits(), 0.0);
590 assert!(
591 Secret::from_base64("password password password pass!").entropy_bits()
592 < Secret::MIN_ENTROPY_BITS
593 );
594 }
595
596 #[test]
597 fn random_string_uses_alphabet() {
598 let s = random_string(40, b"ab");
599 assert_eq!(s.len(), 40);
600 assert!(s.bytes().all(|b| b == b'a' || b == b'b'));
601 }
602}