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 fn from_bytes(bytes: impl Into<Vec<u8>>) -> Self {
30 Secret(Zeroizing::new(bytes.into()))
31 }
32
33 pub fn from_base64(value: &str) -> Self {
35 match B64.decode(value.trim()) {
36 Ok(bytes) if bytes.len() >= Self::MIN_LEN => Secret::from_bytes(bytes),
37 _ => Secret::from_bytes(value.as_bytes().to_vec()),
38 }
39 }
40
41 pub fn from_env(var: &str) -> Result<Self, BuildError> {
42 let value = std::env::var(var)
43 .map_err(|_| BuildError::new(format!("environment variable `{var}` is not set")))?;
44 Ok(Secret::from_base64(&value))
45 }
46
47 pub fn generate() -> String {
49 B64.encode(random_bytes::<64>())
50 }
51
52 pub(crate) fn len(&self) -> usize {
53 self.0.len()
54 }
55
56 fn derive(&self, info: &str) -> Zeroizing<[u8; 32]> {
57 let hk = hkdf::Hkdf::<Sha256>::new(Some(b"fastauth"), &self.0);
58 let mut out = Zeroizing::new([0u8; 32]);
59 hk.expand(info.as_bytes(), out.as_mut())
60 .expect("32 bytes is a valid HKDF output length");
61 out
62 }
63}
64
65impl fmt::Debug for Secret {
66 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67 f.write_str("Secret(..)")
68 }
69}
70
71pub fn random_bytes<const N: usize>() -> [u8; N] {
72 let mut buf = [0u8; N];
73 getrandom::fill(&mut buf).expect("the OS random number generator is available");
74 buf
75}
76
77pub fn random_token() -> String {
79 B64.encode(random_bytes::<32>())
80}
81
82pub fn random_string(len: usize, alphabet: &[u8]) -> String {
84 assert!(!alphabet.is_empty() && alphabet.len() <= 256);
85 let limit = 256 - (256 % alphabet.len());
86 let mut out = String::with_capacity(len);
87 while out.len() < len {
88 for byte in random_bytes::<64>() {
89 if (byte as usize) < limit && out.len() < len {
90 out.push(alphabet[byte as usize % alphabet.len()] as char);
91 }
92 }
93 }
94 out
95}
96
97pub fn base64url(bytes: &[u8]) -> String {
98 B64.encode(bytes)
99}
100
101pub fn base64url_decode(s: &str) -> Option<Vec<u8>> {
102 B64.decode(s).ok()
103}
104
105#[derive(Clone, Copy, PartialEq, Eq, Hash)]
107pub struct Hash([u8; 32]);
108
109impl Hash {
110 pub fn sha256(data: impl AsRef<[u8]>) -> Self {
111 Hash(Sha256::digest(data.as_ref()).into())
112 }
113
114 pub fn as_bytes(&self) -> &[u8; 32] {
115 &self.0
116 }
117
118 pub fn from_slice(bytes: &[u8]) -> Option<Self> {
119 bytes.try_into().ok().map(Hash)
120 }
121}
122
123impl fmt::Debug for Hash {
124 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
125 write!(f, "Hash({}..)", &base64url(&self.0)[..8])
126 }
127}
128
129pub fn ct_eq(a: &[u8], b: &[u8]) -> bool {
131 a.ct_eq(b).into()
132}
133
134pub struct Keys {
137 cookie: Vec<Zeroizing<[u8; 32]>>,
138 cache: Vec<Zeroizing<[u8; 32]>>,
139 encrypt: Vec<Zeroizing<[u8; 32]>>,
140 secrets: Vec<Secret>,
141}
142
143impl fmt::Debug for Keys {
144 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
145 write!(f, "Keys({} secrets)", self.secrets.len())
146 }
147}
148
149#[derive(Clone, Copy, Debug, PartialEq, Eq)]
150pub enum SignPurpose {
151 Cookie,
152 CookieCache,
153}
154
155impl Keys {
156 pub(crate) fn new(secrets: Vec<Secret>) -> Self {
157 Self {
158 cookie: secrets
159 .iter()
160 .map(|s| s.derive("fastauth/v1/cookie"))
161 .collect(),
162 cache: secrets
163 .iter()
164 .map(|s| s.derive("fastauth/v1/cookie-cache"))
165 .collect(),
166 encrypt: secrets
167 .iter()
168 .map(|s| s.derive("fastauth/v1/encrypt"))
169 .collect(),
170 secrets,
171 }
172 }
173
174 fn sign_keys(&self, purpose: SignPurpose) -> &[Zeroizing<[u8; 32]>] {
175 match purpose {
176 SignPurpose::Cookie => &self.cookie,
177 SignPurpose::CookieCache => &self.cache,
178 }
179 }
180
181 fn mac(key: &[u8; 32], value: &str) -> HmacSha256 {
182 let mut mac =
183 <HmacSha256 as KeyInit>::new_from_slice(key).expect("HMAC takes any key length");
184 mac.update(value.as_bytes());
185 mac
186 }
187
188 pub fn sign(&self, purpose: SignPurpose, value: &str) -> String {
190 let tag = Self::mac(&self.sign_keys(purpose)[0], value)
191 .finalize()
192 .into_bytes();
193 format!("{value}.{}", B64.encode(tag))
194 }
195
196 pub fn verify<'a>(&self, purpose: SignPurpose, signed: &'a str) -> Option<&'a str> {
198 let (value, sig) = signed.rsplit_once('.')?;
199 let sig = B64.decode(sig).ok()?;
200 self.sign_keys(purpose)
201 .iter()
202 .any(|key| Self::mac(key, value).verify_slice(&sig).is_ok())
203 .then_some(value)
204 }
205
206 pub fn encrypt(&self, plaintext: &[u8]) -> Vec<u8> {
208 let cipher =
209 XChaCha20Poly1305::new_from_slice(self.encrypt[0].as_ref()).expect("32-byte key");
210 let nonce_bytes = random_bytes::<24>();
211 let nonce = chacha20poly1305::XNonce::from(nonce_bytes);
212 let ciphertext = cipher
213 .encrypt(&nonce, plaintext)
214 .expect("XChaCha20-Poly1305 encryption cannot fail");
215 let mut out = Vec::with_capacity(1 + 24 + ciphertext.len());
216 out.push(0);
217 out.extend_from_slice(&nonce_bytes);
218 out.extend_from_slice(&ciphertext);
219 out
220 }
221
222 pub fn decrypt(&self, data: &[u8]) -> Option<Vec<u8>> {
223 if data.len() < 25 {
224 return None;
225 }
226 let (nonce, ciphertext) = data[1..].split_at(24);
227 let nonce = chacha20poly1305::XNonce::try_from(nonce).ok()?;
228 self.encrypt.iter().find_map(|key| {
229 let cipher = XChaCha20Poly1305::new_from_slice(key.as_ref()).ok()?;
230 cipher.decrypt(&nonce, ciphertext).ok()
231 })
232 }
233
234 pub fn derive_key(&self, plugin_id: &str) -> Zeroizing<[u8; 32]> {
236 self.secrets[0].derive(&format!("fastauth/v1/plugin/{plugin_id}"))
237 }
238}
239
240pub trait PasswordHasher: Send + Sync + 'static {
242 fn hash(&self, password: &str) -> Result<String, String>;
243 fn verify(&self, password: &str, hash: &str) -> Result<bool, String>;
244 fn needs_rehash(&self, hash: &str) -> bool {
246 let _ = hash;
247 false
248 }
249}
250
251#[derive(Debug, Clone)]
253pub struct Argon2id {
254 params: argon2::Params,
255}
256
257impl Argon2id {
258 pub fn owasp() -> Self {
259 Self::with_params(19 * 1024, 2, 1)
260 }
261
262 pub fn with_params(m_cost_kib: u32, t_cost: u32, p_cost: u32) -> Self {
263 let params =
264 argon2::Params::new(m_cost_kib, t_cost, p_cost, None).expect("valid argon2 parameters");
265 Self { params }
266 }
267
268 fn engine(&self) -> argon2::Argon2<'static> {
269 argon2::Argon2::new(
270 argon2::Algorithm::Argon2id,
271 argon2::Version::V0x13,
272 self.params.clone(),
273 )
274 }
275}
276
277impl Default for Argon2id {
278 fn default() -> Self {
279 Self::owasp()
280 }
281}
282
283impl PasswordHasher for Argon2id {
284 fn hash(&self, password: &str) -> Result<String, String> {
285 use argon2::password_hash::PasswordHasher as _;
286 self.engine()
287 .hash_password(password.as_bytes())
288 .map(|h| h.to_string())
289 .map_err(|e| e.to_string())
290 }
291
292 fn verify(&self, password: &str, hash: &str) -> Result<bool, String> {
293 use argon2::password_hash::PasswordVerifier as _;
294 let parsed =
295 argon2::password_hash::phc::PasswordHash::new(hash).map_err(|e| e.to_string())?;
296 Ok(self
297 .engine()
298 .verify_password(password.as_bytes(), &parsed)
299 .is_ok())
300 }
301
302 fn needs_rehash(&self, hash: &str) -> bool {
303 let Ok(parsed) = argon2::password_hash::phc::PasswordHash::new(hash) else {
304 return true;
305 };
306 let Ok(params) = argon2::Params::try_from(&parsed) else {
307 return true;
308 };
309 parsed.algorithm.as_str() != "argon2id"
310 || params.m_cost() < self.params.m_cost()
311 || params.t_cost() < self.params.t_cost()
312 }
313}
314
315#[derive(Clone)]
318pub struct Passwords {
319 hasher: Arc<dyn PasswordHasher>,
320 permits: Arc<Semaphore>,
321 dummy_hash: Arc<std::sync::OnceLock<String>>,
322}
323
324impl fmt::Debug for Passwords {
325 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
326 f.write_str("Passwords(..)")
327 }
328}
329
330impl Passwords {
331 pub fn new(hasher: Arc<dyn PasswordHasher>) -> Self {
332 let cpus = std::thread::available_parallelism().map_or(2, |n| n.get());
333 Self {
334 hasher,
335 permits: Arc::new(Semaphore::new(cpus)),
336 dummy_hash: Arc::default(),
337 }
338 }
339
340 async fn run<T: Send + 'static>(
341 &self,
342 f: impl FnOnce(&dyn PasswordHasher) -> T + Send + 'static,
343 ) -> T {
344 let _permit = self
345 .permits
346 .acquire()
347 .await
348 .expect("semaphore is never closed");
349 let hasher = self.hasher.clone();
350 match tokio::runtime::Handle::try_current() {
351 Ok(handle) => handle
352 .spawn_blocking(move || f(hasher.as_ref()))
353 .await
354 .expect("password hashing task panicked"),
355 Err(_) => f(hasher.as_ref()),
356 }
357 }
358
359 pub async fn hash(&self, password: &str) -> Result<String, String> {
360 let password = Zeroizing::new(password.to_owned());
361 self.run(move |h| h.hash(&password)).await
362 }
363
364 pub async fn verify(&self, password: &str, hash: &str) -> Result<bool, String> {
365 let password = Zeroizing::new(password.to_owned());
366 let hash = hash.to_owned();
367 self.run(move |h| h.verify(&password, &hash)).await
368 }
369
370 pub fn needs_rehash(&self, hash: &str) -> bool {
371 self.hasher.needs_rehash(hash)
372 }
373
374 pub async fn verify_dummy(&self, password: &str) {
376 let dummy = match self.dummy_hash.get() {
377 Some(h) => h.clone(),
378 None => {
379 let h = self
380 .hash("fastauth-dummy-password")
381 .await
382 .unwrap_or_default();
383 self.dummy_hash.get_or_init(|| h).clone()
384 }
385 };
386 let _ = self.verify(password, &dummy).await;
387 }
388}
389
390#[cfg(test)]
391mod tests {
392 use super::*;
393
394 fn keys() -> Keys {
395 Keys::new(vec![Secret::from_bytes(vec![7u8; 32])])
396 }
397
398 #[test]
399 fn sign_round_trips_and_rejects_tampering() {
400 let keys = keys();
401 let signed = keys.sign(SignPurpose::Cookie, "token");
402 assert_eq!(keys.verify(SignPurpose::Cookie, &signed), Some("token"));
403 assert_eq!(keys.verify(SignPurpose::CookieCache, &signed), None);
404 assert_eq!(
405 keys.verify(SignPurpose::Cookie, &signed.replace("token", "tokem")),
406 None
407 );
408 }
409
410 #[test]
411 fn rotation_verifies_old_signatures() {
412 let old = keys();
413 let signed = old.sign(SignPurpose::Cookie, "v");
414 let rotated = Keys::new(vec![
415 Secret::from_bytes(vec![9u8; 32]),
416 Secret::from_bytes(vec![7u8; 32]),
417 ]);
418 assert_eq!(rotated.verify(SignPurpose::Cookie, &signed), Some("v"));
419 assert_eq!(
420 rotated.decrypt(&old.encrypt(b"hi")).as_deref(),
421 Some(&b"hi"[..])
422 );
423 }
424
425 #[test]
426 fn encryption_round_trips() {
427 let keys = keys();
428 let sealed = keys.encrypt(b"secret");
429 assert_ne!(&sealed[25..], b"secret");
430 assert_eq!(keys.decrypt(&sealed).unwrap(), b"secret");
431 }
432
433 #[test]
434 fn argon2_hashes_and_verifies() {
435 let hasher = Argon2id::with_params(1024, 1, 1);
436 let hash = hasher.hash("correct horse").unwrap();
437 assert!(hash.starts_with("$argon2id$"));
438 assert!(hasher.verify("correct horse", &hash).unwrap());
439 assert!(!hasher.verify("wrong", &hash).unwrap());
440 assert!(Argon2id::owasp().needs_rehash(&hash));
441 }
442
443 #[test]
444 fn random_string_uses_alphabet() {
445 let s = random_string(40, b"ab");
446 assert_eq!(s.len(), 40);
447 assert!(s.bytes().all(|b| b == b'a' || b == b'b'));
448 }
449}