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