use std::collections::HashMap; 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()) } 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: std::sync::Mutex>> = std::sync::Mutex::new(None); 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 mut g = LOGIN_FAILURES.lock().unwrap_or_else(|e| e.into_inner()); let map = g.get_or_insert_with(HashMap::new); 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 g = LOGIN_FAILURES.lock().unwrap_or_else(|e| e.into_inner()); let map = g.get_or_insert_with(HashMap::new); 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)) } 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); } }