auth.rs
⎇
Raw
1use std::collections::HashMap;
2use std::sync::LazyLock;
3use std::time::{Duration, Instant};
4
5use argon2::Argon2;
6use argon2::password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString};
7
8pub const COOKIE_NAME: &str = "fbng_session";
9/// 30 days.
10pub const SESSION_MAX_AGE: u64 = 60 * 60 * 24 * 30;
11
12/// Concurrent Argon2 runs. Each one burns a blocking thread and ~19 MiB, so
13/// a burst of logins must not take the whole pool. Waiters queue here.
14pub(crate) static ARGON2_SLOTS: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(4);
15
16pub fn hash_password(password: &str) -> anyhow::Result<String> {
17 let salt = SaltString::generate(&mut rand::thread_rng());
18 let hash = Argon2::default()
19 .hash_password(password.as_bytes(), &salt)
20 .map_err(|e| anyhow::anyhow!("password hashing failed: {e}"))?;
21 Ok(hash.to_string())
22}
23
24/// [`verify_password`] off the async executor, behind [`ARGON2_SLOTS`].
25///
26/// Argon2 is slow and memory-hungry by design, so it must not run on a tokio
27/// worker. A join failure means the task panicked or the runtime is shutting
28/// down; either way nothing was verified, so the answer is `false`.
29pub async fn verify_password_async(password: &str, hash: &str) -> bool {
30 let (password, hash) = (password.to_string(), hash.to_string());
31 let _slot = ARGON2_SLOTS.acquire().await;
32 tokio::task::spawn_blocking(move || verify_password(&password, &hash))
33 .await
34 .unwrap_or(false)
35}
36
37pub fn verify_password(password: &str, hash: &str) -> bool {
38 let Ok(parsed) = PasswordHash::new(hash) else {
39 return false;
40 };
41 Argon2::default()
42 .verify_password(password.as_bytes(), &parsed)
43 .is_ok()
44}
45
46/// 32 random bytes, hex-encoded (64 chars).
47pub fn random_token() -> String {
48 hex_token(32)
49}
50
51/// 16 random bytes, hex-encoded (32 chars). Used for public share links.
52pub fn share_token() -> String {
53 hex_token(16)
54}
55
56/// The secret of an app password: 16 random bytes, hex-encoded.
57pub fn app_password() -> String {
58 hex_token(16)
59}
60
61/// The stored form of an app password secret.
62///
63/// SHA-256, not Argon2: the secret is 128 random bits, so no dictionary
64/// applies. A lookup by hash then replaces a per-request verification.
65pub fn app_password_hash(secret: &str) -> String {
66 use sha2::{Digest, Sha256};
67 hex(&Sha256::digest(secret.as_bytes()))
68}
69
70fn hex_token(bytes: usize) -> String {
71 use rand::RngCore;
72 let mut b = vec![0u8; bytes];
73 rand::thread_rng().fill_bytes(&mut b);
74 hex(&b)
75}
76
77fn hex(bytes: &[u8]) -> String {
78 use std::fmt::Write as _;
79 bytes
80 .iter()
81 .fold(String::with_capacity(bytes.len() * 2), |mut s, b| {
82 let _ = write!(s, "{b:02x}");
83 s
84 })
85}
86
87/// Failed logins per name within the last [`FAILURE_WINDOW`].
88/// ponytail: process-wide map, keyed by name. Enough to blunt online guessing
89/// on a single-node deployment; move to the DB if the server is ever scaled out.
90static LOGIN_FAILURES: LazyLock<std::sync::Mutex<HashMap<String, (u32, Instant)>>> =
91 LazyLock::new(Default::default);
92const FAILURE_WINDOW: Duration = Duration::from_secs(15 * 60);
93
94/// How long a login attempt for `name` must wait before it is checked: 0 for
95/// the first few tries, then growing per failure, capped at a few seconds. A
96/// delay rather than a lockout, so an attacker cannot lock a real user out.
97pub fn login_delay(name: &str) -> Duration {
98 let map = LOGIN_FAILURES.lock().unwrap_or_else(|e| e.into_inner());
99 match map.get(&name.to_lowercase()) {
100 Some((n, at)) if at.elapsed() < FAILURE_WINDOW => delay_for(*n),
101 _ => Duration::ZERO,
102 }
103}
104
105pub fn record_login(name: &str, ok: bool) {
106 let mut map = LOGIN_FAILURES.lock().unwrap_or_else(|e| e.into_inner());
107 map.retain(|_, (_, at)| at.elapsed() < FAILURE_WINDOW);
108 let key = name.to_lowercase();
109 if ok {
110 map.remove(&key);
111 } else {
112 let n = map.get(&key).map_or(0, |(n, _)| *n);
113 map.insert(key, (n + 1, Instant::now()));
114 }
115}
116
117fn delay_for(failures: u32) -> Duration {
118 Duration::from_millis(500 * u64::from(failures.saturating_sub(2)).min(10))
119}
120
121// ---------------------------------------------------------------------------
122// Verified HTTP Basic credentials
123// ---------------------------------------------------------------------------
124
125/// How long a verified Basic credential is trusted without re-running Argon2.
126///
127/// Only the WebDAV mount uses Basic, and a mount client re-sends the header on
128/// every request. Each verify costs ~100 ms and one of the four
129/// [`ARGON2_SLOTS`], which real logins queue for too.
130const VERIFIED_TTL: Duration = Duration::from_secs(300);
131
132type CredCache = HashMap<[u8; 32], (i64, Instant)>;
133
134/// Verified credentials: keyed hash of the credential → (subject id, when it
135/// was verified).
136///
137/// ponytail: process-wide map like [`LOGIN_FAILURES`]; move it to the DB if
138/// the server is ever scaled out.
139static VERIFIED: LazyLock<std::sync::Mutex<CredCache>> = LazyLock::new(Default::default);
140
141/// Look a credential up in the cache, falling back to `verify`, which returns
142/// the subject id on success.
143///
144/// `realm` separates the key spaces: `0` for accounts, a share id for that
145/// share's password, so a share password can never satisfy an account lookup.
146pub async fn verify_cached<F, Fut>(realm: i64, name: &str, password: &str, verify: F) -> Option<i64>
147where
148 F: FnOnce() -> Fut,
149 Fut: std::future::Future<Output = Option<i64>>,
150{
151 let key = cache_key(realm, name, password);
152 {
153 let mut map = VERIFIED.lock().unwrap_or_else(|e| e.into_inner());
154 map.retain(|_, (_, at)| at.elapsed() < VERIFIED_TTL);
155 if let Some((id, _)) = map.get(&key) {
156 return Some(*id);
157 }
158 }
159 let id = verify().await?;
160 VERIFIED
161 .lock()
162 .unwrap_or_else(|e| e.into_inner())
163 .insert(key, (id, Instant::now()));
164 Some(id)
165}
166
167/// Drop every cached credential.
168///
169/// Called whenever an account's password, active flag or roots change. Without
170/// it a changed password would keep working on an open mount until the entry
171/// aged out.
172pub fn forget_verified() {
173 VERIFIED.lock().unwrap_or_else(|e| e.into_inner()).clear();
174}
175
176/// Drop one subject's cached credentials.
177///
178/// The self-service credential routes use this rather than [`forget_verified`].
179/// Any user can reach them, and clearing the whole map would make every open
180/// mount on the server pay for Argon2 again.
181///
182/// A share whose id happens to equal `subject` is dropped too, because the
183/// realms share one value space. That costs one extra verification, nothing
184/// more.
185pub fn forget_verified_for(subject: i64) {
186 VERIFIED
187 .lock()
188 .unwrap_or_else(|e| e.into_inner())
189 .retain(|_, (id, _)| *id != subject);
190}
191
192/// A keyed hash of the credential, never the credential itself. The pepper is
193/// fresh per process, so a dump of the map alone yields no passwords.
194fn cache_key(realm: i64, name: &str, password: &str) -> [u8; 32] {
195 use sha2::{Digest, Sha256};
196 static PEPPER: LazyLock<[u8; 32]> = LazyLock::new(|| {
197 use rand::RngCore;
198 let mut b = [0u8; 32];
199 rand::thread_rng().fill_bytes(&mut b);
200 b
201 });
202 let mut h = Sha256::new();
203 h.update(*PEPPER);
204 h.update(realm.to_le_bytes());
205 // Length-prefixed, so ("ab", "c") and ("a", "bc") cannot collide.
206 h.update((name.len() as u64).to_le_bytes());
207 h.update(name.as_bytes());
208 h.update(password.as_bytes());
209 h.finalize().into()
210}
211
212/// Parse `Authorization: Basic <base64(name:password)>`.
213pub fn basic_credentials(headers: &axum::http::HeaderMap) -> Option<(String, String)> {
214 use headers::HeaderMapExt as _;
215 use headers::authorization::{Authorization, Basic};
216 let auth = headers.typed_get::<Authorization<Basic>>()?;
217 Some((auth.username().to_string(), auth.password().to_string()))
218}
219
220pub fn session_cookie(token: &str, https: bool) -> String {
221 let mut c =
222 format!("{COOKIE_NAME}={token}; Path=/; HttpOnly; SameSite=Lax; Max-Age={SESSION_MAX_AGE}");
223 if https {
224 c.push_str("; Secure");
225 }
226 c
227}
228
229pub fn clear_session_cookie(https: bool) -> String {
230 let mut c = format!("{COOKIE_NAME}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0");
231 if https {
232 c.push_str("; Secure");
233 }
234 c
235}
236
237/// Cookie name proving that the visitor unlocked share `share_id`.
238///
239/// One cookie per share: a visitor may hold links to several protected
240/// shares, and one shared name would let each unlock evict the last.
241pub fn share_cookie_name(share_id: i64) -> String {
242 format!("fbng_share_{share_id}")
243}
244
245/// Session cookie for an unlocked share. A session cookie (no `Max-Age`), so
246/// the unlock lasts as long as the browser stays open and is not written to
247/// disk.
248pub fn share_cookie(share_id: i64, token: &str, https: bool) -> String {
249 let mut c = format!(
250 "{}={token}; Path=/; HttpOnly; SameSite=Lax",
251 share_cookie_name(share_id)
252 );
253 if https {
254 c.push_str("; Secure");
255 }
256 c
257}
258
259/// Extract the unlock token for `share_id` from the Cookie header.
260pub fn parse_share_cookie(headers: &axum::http::HeaderMap, share_id: i64) -> Option<String> {
261 cookie_value(headers, &share_cookie_name(share_id))
262}
263
264/// Extract the session token from the Cookie header, if present.
265pub fn parse_session_cookie(headers: &axum::http::HeaderMap) -> Option<String> {
266 cookie_value(headers, COOKIE_NAME)
267}
268
269/// One cookie's value out of the `Cookie` header. Empty values are treated
270/// as absent: that is how a cleared cookie arrives before it expires.
271fn cookie_value(headers: &axum::http::HeaderMap, name: &str) -> Option<String> {
272 let header = headers.get(axum::http::header::COOKIE)?.to_str().ok()?;
273 for part in header.split(';') {
274 let part = part.trim();
275 if let Some((k, v)) = part.split_once('=')
276 && k == name
277 && !v.is_empty()
278 {
279 return Some(v.to_string());
280 }
281 }
282 None
283}
284
285#[cfg(test)]
286mod tests {
287 use super::*;
288 use axum::http::{HeaderMap, header};
289
290 #[test]
291 fn share_cookie_is_per_share_and_session_scoped() {
292 let c = share_cookie(7, "tok", false);
293 assert!(c.starts_with("fbng_share_7=tok;"));
294 assert!(c.contains("HttpOnly"));
295 // No Max-Age: the unlock must not outlive the browser session.
296 assert!(!c.contains("Max-Age"));
297 assert!(!c.contains("Secure"));
298 assert!(share_cookie(7, "tok", true).contains("Secure"));
299
300 let mut h = HeaderMap::new();
301 h.insert(
302 header::COOKIE,
303 "fbng_share_7=abc; fbng_share_8=def".parse().unwrap(),
304 );
305 assert_eq!(parse_share_cookie(&h, 7).as_deref(), Some("abc"));
306 assert_eq!(parse_share_cookie(&h, 8).as_deref(), Some("def"));
307 assert_eq!(parse_share_cookie(&h, 9), None);
308 }
309
310 #[test]
311 fn password_hash_round_trip() {
312 let h = hash_password("hunter22").unwrap();
313 assert!(verify_password("hunter22", &h));
314 assert!(!verify_password("wrong-password", &h));
315 assert!(!verify_password("hunter23", &h));
316 // Fresh salt on every hash.
317 assert_ne!(h, hash_password("hunter22").unwrap());
318 // Argon2id marker is present.
319 assert!(h.starts_with("$argon2id$"));
320 }
321
322 #[test]
323 fn verify_rejects_garbage_hashes() {
324 assert!(!verify_password("x", ""));
325 assert!(!verify_password("x", "not-a-hash"));
326 assert!(!verify_password("x", "$argon2id$"));
327 }
328
329 #[test]
330 fn token_shapes_and_uniqueness() {
331 let t = random_token();
332 assert_eq!(t.len(), 64);
333 assert!(t.chars().all(|c| c.is_ascii_hexdigit()));
334
335 let s = share_token();
336 assert_eq!(s.len(), 32);
337 assert!(s.chars().all(|c| c.is_ascii_hexdigit()));
338
339 let mut seen = std::collections::HashSet::new();
340 for _ in 0..100 {
341 assert!(seen.insert(random_token()), "session token collision");
342 assert!(seen.insert(share_token()), "share token collision");
343 }
344 }
345
346 #[test]
347 fn login_delay_grows_after_free_tries() {
348 assert_eq!(delay_for(0), Duration::ZERO);
349 assert_eq!(delay_for(2), Duration::ZERO);
350 assert_eq!(delay_for(3), Duration::from_millis(500));
351 assert_eq!(delay_for(6), Duration::from_millis(2000));
352 assert_eq!(delay_for(100), Duration::from_millis(5000));
353
354 let name = "throttle-test-user";
355 assert_eq!(login_delay(name), Duration::ZERO);
356 for _ in 0..4 {
357 record_login(name, false);
358 }
359 assert_eq!(login_delay(name), Duration::from_millis(1000));
360 // Case-insensitive like the account names themselves.
361 assert_eq!(
362 login_delay("THROTTLE-test-USER"),
363 Duration::from_millis(1000)
364 );
365 record_login(name, true);
366 assert_eq!(login_delay(name), Duration::ZERO);
367 }
368
369 #[test]
370 fn session_cookie_shape() {
371 let c = session_cookie("tok123", false);
372 assert!(c.starts_with("fbng_session=tok123;"));
373 assert!(c.contains("Path=/"));
374 assert!(c.contains("HttpOnly"));
375 assert!(c.contains("SameSite=Lax"));
376 assert!(c.contains(&format!("Max-Age={SESSION_MAX_AGE}")));
377 assert!(!c.contains("Secure"));
378
379 let c = session_cookie("tok123", true);
380 assert!(c.ends_with("; Secure"));
381
382 let c = clear_session_cookie(true);
383 assert!(c.starts_with("fbng_session=;"));
384 assert!(c.contains("Max-Age=0"));
385 assert!(c.contains("Secure"));
386 assert!(!clear_session_cookie(false).contains("Secure"));
387 }
388
389 #[test]
390 fn parse_session_cookie_variants() {
391 let mut h = HeaderMap::new();
392 h.insert(
393 header::COOKIE,
394 "other=1; fbng_session=abc123; x=y".parse().unwrap(),
395 );
396 assert_eq!(parse_session_cookie(&h).as_deref(), Some("abc123"));
397
398 let mut h = HeaderMap::new();
399 h.insert(header::COOKIE, "other=1".parse().unwrap());
400 assert_eq!(parse_session_cookie(&h), None);
401
402 // Empty value → treated as absent.
403 let mut h = HeaderMap::new();
404 h.insert(header::COOKIE, "fbng_session=".parse().unwrap());
405 assert_eq!(parse_session_cookie(&h), None);
406
407 assert_eq!(parse_session_cookie(&HeaderMap::new()), None);
408
409 // First occurrence wins.
410 let mut h = HeaderMap::new();
411 h.insert(
412 header::COOKIE,
413 "fbng_session=first; fbng_session=second".parse().unwrap(),
414 );
415 assert_eq!(parse_session_cookie(&h).as_deref(), Some("first"));
416
417 // Cookie name must match exactly.
418 let mut h = HeaderMap::new();
419 h.insert(
420 header::COOKIE,
421 "fbng_session2=x; Xfbng_session=y".parse().unwrap(),
422 );
423 assert_eq!(parse_session_cookie(&h), None);
424 }
425}
426