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