use std::collections::HashMap; use std::sync::LazyLock; use std::time::{Duration, Instant}; use argon2::Argon2; use argon2::password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString}; pub const COOKIE_NAME: &str = "fbng_session"; /// 30 days. pub const SESSION_MAX_AGE: u64 = 60 * 60 * 24 * 30; /// Concurrent Argon2 runs. Each one burns a blocking thread and ~19 MiB, so /// a burst of logins must not take the whole pool. Waiters queue here. pub(crate) static ARGON2_SLOTS: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(4); pub fn hash_password(password: &str) -> anyhow::Result { let salt = SaltString::generate(&mut rand::thread_rng()); let hash = Argon2::default() .hash_password(password.as_bytes(), &salt) .map_err(|e| anyhow::anyhow!("password hashing failed: {e}"))?; Ok(hash.to_string()) } /// [`verify_password`] off the async executor, behind [`ARGON2_SLOTS`]. /// /// Argon2 is slow and memory-hungry by design, so it must not run on a tokio /// worker. A join failure means the task panicked or the runtime is shutting /// down; either way nothing was verified, so the answer is `false`. pub async fn verify_password_async(password: &str, hash: &str) -> bool { let (password, hash) = (password.to_string(), hash.to_string()); let _slot = ARGON2_SLOTS.acquire().await; tokio::task::spawn_blocking(move || verify_password(&password, &hash)) .await .unwrap_or(false) } pub fn verify_password(password: &str, hash: &str) -> bool { let Ok(parsed) = PasswordHash::new(hash) else { return false; }; Argon2::default() .verify_password(password.as_bytes(), &parsed) .is_ok() } /// 32 random bytes, hex-encoded (64 chars). pub fn random_token() -> String { hex_token(32) } /// 16 random bytes, hex-encoded (32 chars). Used for public share links. pub fn share_token() -> String { hex_token(16) } fn hex_token(bytes: usize) -> String { use rand::RngCore; use std::fmt::Write as _; let mut b = vec![0u8; bytes]; rand::thread_rng().fill_bytes(&mut b); b.iter().fold(String::with_capacity(bytes * 2), |mut s, x| { let _ = write!(s, "{x:02x}"); s }) } /// Failed logins per name within the last [`FAILURE_WINDOW`]. /// ponytail: process-wide map, keyed by name. Enough to blunt online guessing /// on a single-node deployment; move to the DB if the server is ever scaled out. static LOGIN_FAILURES: LazyLock>> = LazyLock::new(Default::default); const FAILURE_WINDOW: Duration = Duration::from_secs(15 * 60); /// How long a login attempt for `name` must wait before it is checked: 0 for /// the first few tries, then growing per failure, capped at a few seconds. A /// delay rather than a lockout, so an attacker cannot lock a real user out. pub fn login_delay(name: &str) -> Duration { let map = LOGIN_FAILURES.lock().unwrap_or_else(|e| e.into_inner()); match map.get(&name.to_lowercase()) { Some((n, at)) if at.elapsed() < FAILURE_WINDOW => delay_for(*n), _ => Duration::ZERO, } } pub fn record_login(name: &str, ok: bool) { let mut map = LOGIN_FAILURES.lock().unwrap_or_else(|e| e.into_inner()); map.retain(|_, (_, at)| at.elapsed() < FAILURE_WINDOW); let key = name.to_lowercase(); if ok { map.remove(&key); } else { let n = map.get(&key).map_or(0, |(n, _)| *n); map.insert(key, (n + 1, Instant::now())); } } fn delay_for(failures: u32) -> Duration { Duration::from_millis(500 * u64::from(failures.saturating_sub(2)).min(10)) } // --------------------------------------------------------------------------- // Verified HTTP Basic credentials // --------------------------------------------------------------------------- /// How long a verified Basic credential is trusted without re-running Argon2. /// /// Only the WebDAV mount uses Basic, and a mount client re-sends the header on /// every request. Each verify costs ~100 ms and one of the four /// [`ARGON2_SLOTS`], which real logins queue for too. const VERIFIED_TTL: Duration = Duration::from_secs(300); type CredCache = HashMap<[u8; 32], (i64, Instant)>; /// Verified credentials: keyed hash of the credential → (subject id, when it /// was verified). /// /// ponytail: process-wide map like [`LOGIN_FAILURES`]; move it to the DB if /// the server is ever scaled out. static VERIFIED: LazyLock> = LazyLock::new(Default::default); /// Look a credential up in the cache, falling back to `verify`, which returns /// the subject id on success. /// /// `realm` separates the key spaces: `0` for accounts, a share id for that /// share's password, so a share password can never satisfy an account lookup. pub async fn verify_cached(realm: i64, name: &str, password: &str, verify: F) -> Option where F: FnOnce() -> Fut, Fut: std::future::Future>, { let key = cache_key(realm, name, password); { let mut map = VERIFIED.lock().unwrap_or_else(|e| e.into_inner()); map.retain(|_, (_, at)| at.elapsed() < VERIFIED_TTL); if let Some((id, _)) = map.get(&key) { return Some(*id); } } let id = verify().await?; VERIFIED .lock() .unwrap_or_else(|e| e.into_inner()) .insert(key, (id, Instant::now())); Some(id) } /// Drop every cached credential. /// /// Called whenever an account's password, active flag or roots change. Without /// it a changed password would keep working on an open mount until the entry /// aged out. pub fn forget_verified() { VERIFIED.lock().unwrap_or_else(|e| e.into_inner()).clear(); } /// A keyed hash of the credential, never the credential itself. The pepper is /// fresh per process, so a dump of the map alone yields no passwords. fn cache_key(realm: i64, name: &str, password: &str) -> [u8; 32] { use sha2::{Digest, Sha256}; static PEPPER: LazyLock<[u8; 32]> = LazyLock::new(|| { use rand::RngCore; let mut b = [0u8; 32]; rand::thread_rng().fill_bytes(&mut b); b }); let mut h = Sha256::new(); h.update(*PEPPER); h.update(realm.to_le_bytes()); // Length-prefixed, so ("ab", "c") and ("a", "bc") cannot collide. h.update((name.len() as u64).to_le_bytes()); h.update(name.as_bytes()); h.update(password.as_bytes()); h.finalize().into() } /// Parse `Authorization: Basic `. pub fn basic_credentials(headers: &axum::http::HeaderMap) -> Option<(String, String)> { use headers::HeaderMapExt as _; use headers::authorization::{Authorization, Basic}; let auth = headers.typed_get::>()?; Some((auth.username().to_string(), auth.password().to_string())) } pub fn session_cookie(token: &str, https: bool) -> String { let mut c = format!("{COOKIE_NAME}={token}; Path=/; HttpOnly; SameSite=Lax; Max-Age={SESSION_MAX_AGE}"); if https { c.push_str("; Secure"); } c } pub fn clear_session_cookie(https: bool) -> String { let mut c = format!("{COOKIE_NAME}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0"); if https { c.push_str("; Secure"); } c } /// Cookie name proving that the visitor unlocked share `share_id`. /// /// One cookie per share: a visitor may hold links to several protected /// shares, and one shared name would let each unlock evict the last. pub fn share_cookie_name(share_id: i64) -> String { format!("fbng_share_{share_id}") } /// Session cookie for an unlocked share. A session cookie (no `Max-Age`), so /// the unlock lasts as long as the browser stays open and is not written to /// disk. pub fn share_cookie(share_id: i64, token: &str, https: bool) -> String { let mut c = format!( "{}={token}; Path=/; HttpOnly; SameSite=Lax", share_cookie_name(share_id) ); if https { c.push_str("; Secure"); } c } /// Extract the unlock token for `share_id` from the Cookie header. pub fn parse_share_cookie(headers: &axum::http::HeaderMap, share_id: i64) -> Option { cookie_value(headers, &share_cookie_name(share_id)) } /// Extract the session token from the Cookie header, if present. pub fn parse_session_cookie(headers: &axum::http::HeaderMap) -> Option { cookie_value(headers, COOKIE_NAME) } /// One cookie's value out of the `Cookie` header. Empty values are treated /// as absent: that is how a cleared cookie arrives before it expires. fn cookie_value(headers: &axum::http::HeaderMap, name: &str) -> Option { let header = headers.get(axum::http::header::COOKIE)?.to_str().ok()?; for part in header.split(';') { let part = part.trim(); if let Some((k, v)) = part.split_once('=') && k == name && !v.is_empty() { return Some(v.to_string()); } } None } #[cfg(test)] mod tests { use super::*; use axum::http::{HeaderMap, header}; #[test] fn share_cookie_is_per_share_and_session_scoped() { let c = share_cookie(7, "tok", false); assert!(c.starts_with("fbng_share_7=tok;")); assert!(c.contains("HttpOnly")); // No Max-Age: the unlock must not outlive the browser session. assert!(!c.contains("Max-Age")); assert!(!c.contains("Secure")); assert!(share_cookie(7, "tok", true).contains("Secure")); let mut h = HeaderMap::new(); h.insert( header::COOKIE, "fbng_share_7=abc; fbng_share_8=def".parse().unwrap(), ); assert_eq!(parse_share_cookie(&h, 7).as_deref(), Some("abc")); assert_eq!(parse_share_cookie(&h, 8).as_deref(), Some("def")); assert_eq!(parse_share_cookie(&h, 9), None); } #[test] fn password_hash_round_trip() { let h = hash_password("hunter22").unwrap(); assert!(verify_password("hunter22", &h)); assert!(!verify_password("wrong-password", &h)); assert!(!verify_password("hunter23", &h)); // Fresh salt on every hash. assert_ne!(h, hash_password("hunter22").unwrap()); // Argon2id marker is present. assert!(h.starts_with("$argon2id$")); } #[test] fn verify_rejects_garbage_hashes() { assert!(!verify_password("x", "")); assert!(!verify_password("x", "not-a-hash")); assert!(!verify_password("x", "$argon2id$")); } #[test] fn token_shapes_and_uniqueness() { let t = random_token(); assert_eq!(t.len(), 64); assert!(t.chars().all(|c| c.is_ascii_hexdigit())); let s = share_token(); assert_eq!(s.len(), 32); assert!(s.chars().all(|c| c.is_ascii_hexdigit())); let mut seen = std::collections::HashSet::new(); for _ in 0..100 { assert!(seen.insert(random_token()), "session token collision"); assert!(seen.insert(share_token()), "share token collision"); } } #[test] fn login_delay_grows_after_free_tries() { assert_eq!(delay_for(0), Duration::ZERO); assert_eq!(delay_for(2), Duration::ZERO); assert_eq!(delay_for(3), Duration::from_millis(500)); assert_eq!(delay_for(6), Duration::from_millis(2000)); assert_eq!(delay_for(100), Duration::from_millis(5000)); let name = "throttle-test-user"; assert_eq!(login_delay(name), Duration::ZERO); for _ in 0..4 { record_login(name, false); } assert_eq!(login_delay(name), Duration::from_millis(1000)); // Case-insensitive like the account names themselves. assert_eq!( login_delay("THROTTLE-test-USER"), Duration::from_millis(1000) ); record_login(name, true); assert_eq!(login_delay(name), Duration::ZERO); } #[test] fn session_cookie_shape() { let c = session_cookie("tok123", false); assert!(c.starts_with("fbng_session=tok123;")); assert!(c.contains("Path=/")); assert!(c.contains("HttpOnly")); assert!(c.contains("SameSite=Lax")); assert!(c.contains(&format!("Max-Age={SESSION_MAX_AGE}"))); assert!(!c.contains("Secure")); let c = session_cookie("tok123", true); assert!(c.ends_with("; Secure")); let c = clear_session_cookie(true); assert!(c.starts_with("fbng_session=;")); assert!(c.contains("Max-Age=0")); assert!(c.contains("Secure")); assert!(!clear_session_cookie(false).contains("Secure")); } #[test] fn parse_session_cookie_variants() { let mut h = HeaderMap::new(); h.insert( header::COOKIE, "other=1; fbng_session=abc123; x=y".parse().unwrap(), ); assert_eq!(parse_session_cookie(&h).as_deref(), Some("abc123")); let mut h = HeaderMap::new(); h.insert(header::COOKIE, "other=1".parse().unwrap()); assert_eq!(parse_session_cookie(&h), None); // Empty value → treated as absent. let mut h = HeaderMap::new(); h.insert(header::COOKIE, "fbng_session=".parse().unwrap()); assert_eq!(parse_session_cookie(&h), None); assert_eq!(parse_session_cookie(&HeaderMap::new()), None); // First occurrence wins. let mut h = HeaderMap::new(); h.insert( header::COOKIE, "fbng_session=first; fbng_session=second".parse().unwrap(), ); assert_eq!(parse_session_cookie(&h).as_deref(), Some("first")); // Cookie name must match exactly. let mut h = HeaderMap::new(); h.insert( header::COOKIE, "fbng_session2=x; Xfbng_session=y".parse().unwrap(), ); assert_eq!(parse_session_cookie(&h), None); } }