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