auth.rs
| 1 | use std::collections::HashMap; |
| 2 | use std::time::{Duration, Instant}; |
| 3 | |
| 4 | use argon2::Argon2; |
| 5 | use argon2::password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString}; |
| 6 | |
| 7 | pub const COOKIE_NAME: &str = "fbng_session"; |
| 8 | /// 30 days. |
| 9 | pub const SESSION_MAX_AGE: u64 = 60 * 60 * 24 * 30; |
| 10 | |
| 11 | pub fn hash_password(password: &str) -> anyhow::Result<String> { |
| 12 | let salt = SaltString::generate(&mut rand::thread_rng()); |
| 13 | let hash = Argon2::default() |
| 14 | .hash_password(password.as_bytes(), &salt) |
| 15 | .map_err(|e| anyhow::anyhow!("password hashing failed: {e}"))?; |
| 16 | Ok(hash.to_string()) |
| 17 | } |
| 18 | |
| 19 | pub fn verify_password(password: &str, hash: &str) -> bool { |
| 20 | let Ok(parsed) = PasswordHash::new(hash) else { |
| 21 | return false; |
| 22 | }; |
| 23 | Argon2::default() |
| 24 | .verify_password(password.as_bytes(), &parsed) |
| 25 | .is_ok() |
| 26 | } |
| 27 | |
| 28 | /// 32 random bytes, hex-encoded (64 chars). |
| 29 | pub fn random_token() -> String { |
| 30 | hex_token(32) |
| 31 | } |
| 32 | |
| 33 | /// 16 random bytes, hex-encoded (32 chars). Used for public share links. |
| 34 | pub fn share_token() -> String { |
| 35 | hex_token(16) |
| 36 | } |
| 37 | |
| 38 | fn hex_token(bytes: usize) -> String { |
| 39 | use rand::RngCore; |
| 40 | use std::fmt::Write as _; |
| 41 | let mut b = vec![0u8; bytes]; |
| 42 | rand::thread_rng().fill_bytes(&mut b); |
| 43 | b.iter().fold(String::with_capacity(bytes * 2), |mut s, x| { |
| 44 | let _ = write!(s, "{x:02x}"); |
| 45 | s |
| 46 | }) |
| 47 | } |
| 48 | |
| 49 | /// Failed logins per name within the last [`FAILURE_WINDOW`]. |
| 50 | /// ponytail: process-wide map, keyed by name. Enough to blunt online guessing |
| 51 | /// on a single-node deployment; move to the DB if the server is ever scaled out. |
| 52 | static LOGIN_FAILURES: std::sync::Mutex<Option<HashMap<String, (u32, Instant)>>> = |
| 53 | std::sync::Mutex::new(None); |
| 54 | const FAILURE_WINDOW: Duration = Duration::from_secs(15 * 60); |
| 55 | |
| 56 | /// How long a login attempt for `name` must wait before it is checked: 0 for |
| 57 | /// the first few tries, then growing per failure, capped at a few seconds. A |
| 58 | /// delay rather than a lockout, so an attacker cannot lock a real user out. |
| 59 | pub fn login_delay(name: &str) -> Duration { |
| 60 | let mut g = LOGIN_FAILURES.lock().unwrap_or_else(|e| e.into_inner()); |
| 61 | let map = g.get_or_insert_with(HashMap::new); |
| 62 | match map.get(&name.to_lowercase()) { |
| 63 | Some((n, at)) if at.elapsed() < FAILURE_WINDOW => delay_for(*n), |
| 64 | _ => Duration::ZERO, |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | pub fn record_login(name: &str, ok: bool) { |
| 69 | let mut g = LOGIN_FAILURES.lock().unwrap_or_else(|e| e.into_inner()); |
| 70 | let map = g.get_or_insert_with(HashMap::new); |
| 71 | map.retain(|_, (_, at)| at.elapsed() < FAILURE_WINDOW); |
| 72 | let key = name.to_lowercase(); |
| 73 | if ok { |
| 74 | map.remove(&key); |
| 75 | } else { |
| 76 | let n = map.get(&key).map_or(0, |(n, _)| *n); |
| 77 | map.insert(key, (n + 1, Instant::now())); |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | fn delay_for(failures: u32) -> Duration { |
| 82 | Duration::from_millis(500 * u64::from(failures.saturating_sub(2)).min(10)) |
| 83 | } |
| 84 | |
| 85 | pub fn session_cookie(token: &str, https: bool) -> String { |
| 86 | let mut c = |
| 87 | format!("{COOKIE_NAME}={token}; Path=/; HttpOnly; SameSite=Lax; Max-Age={SESSION_MAX_AGE}"); |
| 88 | if https { |
| 89 | c.push_str("; Secure"); |
| 90 | } |
| 91 | c |
| 92 | } |
| 93 | |
| 94 | pub fn clear_session_cookie(https: bool) -> String { |
| 95 | let mut c = format!("{COOKIE_NAME}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0"); |
| 96 | if https { |
| 97 | c.push_str("; Secure"); |
| 98 | } |
| 99 | c |
| 100 | } |
| 101 | |
| 102 | /// Extract the session token from the Cookie header, if present. |
| 103 | pub fn parse_session_cookie(headers: &axum::http::HeaderMap) -> Option<String> { |
| 104 | let header = headers.get(axum::http::header::COOKIE)?.to_str().ok()?; |
| 105 | for part in header.split(';') { |
| 106 | let part = part.trim(); |
| 107 | if let Some((k, v)) = part.split_once('=') |
| 108 | && k == COOKIE_NAME |
| 109 | && !v.is_empty() |
| 110 | { |
| 111 | return Some(v.to_string()); |
| 112 | } |
| 113 | } |
| 114 | None |
| 115 | } |
| 116 | |
| 117 | #[cfg(test)] |
| 118 | mod tests { |
| 119 | use super::*; |
| 120 | use axum::http::{HeaderMap, header}; |
| 121 | |
| 122 | #[test] |
| 123 | fn password_hash_round_trip() { |
| 124 | let h = hash_password("hunter22").unwrap(); |
| 125 | assert!(verify_password("hunter22", &h)); |
| 126 | assert!(!verify_password("wrong-password", &h)); |
| 127 | assert!(!verify_password("hunter23", &h)); |
| 128 | // Fresh salt on every hash. |
| 129 | assert_ne!(h, hash_password("hunter22").unwrap()); |
| 130 | // Argon2id marker is present. |
| 131 | assert!(h.starts_with("$argon2id$")); |
| 132 | } |
| 133 | |
| 134 | #[test] |
| 135 | fn verify_rejects_garbage_hashes() { |
| 136 | assert!(!verify_password("x", "")); |
| 137 | assert!(!verify_password("x", "not-a-hash")); |
| 138 | assert!(!verify_password("x", "$argon2id$")); |
| 139 | } |
| 140 | |
| 141 | #[test] |
| 142 | fn token_shapes_and_uniqueness() { |
| 143 | let t = random_token(); |
| 144 | assert_eq!(t.len(), 64); |
| 145 | assert!(t.chars().all(|c| c.is_ascii_hexdigit())); |
| 146 | |
| 147 | let s = share_token(); |
| 148 | assert_eq!(s.len(), 32); |
| 149 | assert!(s.chars().all(|c| c.is_ascii_hexdigit())); |
| 150 | |
| 151 | let mut seen = std::collections::HashSet::new(); |
| 152 | for _ in 0..100 { |
| 153 | assert!(seen.insert(random_token()), "session token collision"); |
| 154 | assert!(seen.insert(share_token()), "share token collision"); |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | #[test] |
| 159 | fn login_delay_grows_after_free_tries() { |
| 160 | assert_eq!(delay_for(0), Duration::ZERO); |
| 161 | assert_eq!(delay_for(2), Duration::ZERO); |
| 162 | assert_eq!(delay_for(3), Duration::from_millis(500)); |
| 163 | assert_eq!(delay_for(6), Duration::from_millis(2000)); |
| 164 | assert_eq!(delay_for(100), Duration::from_millis(5000)); |
| 165 | |
| 166 | let name = "throttle-test-user"; |
| 167 | assert_eq!(login_delay(name), Duration::ZERO); |
| 168 | for _ in 0..4 { |
| 169 | record_login(name, false); |
| 170 | } |
| 171 | assert_eq!(login_delay(name), Duration::from_millis(1000)); |
| 172 | // Case-insensitive like the account names themselves. |
| 173 | assert_eq!( |
| 174 | login_delay("THROTTLE-test-USER"), |
| 175 | Duration::from_millis(1000) |
| 176 | ); |
| 177 | record_login(name, true); |
| 178 | assert_eq!(login_delay(name), Duration::ZERO); |
| 179 | } |
| 180 | |
| 181 | #[test] |
| 182 | fn session_cookie_shape() { |
| 183 | let c = session_cookie("tok123", false); |
| 184 | assert!(c.starts_with("fbng_session=tok123;")); |
| 185 | assert!(c.contains("Path=/")); |
| 186 | assert!(c.contains("HttpOnly")); |
| 187 | assert!(c.contains("SameSite=Lax")); |
| 188 | assert!(c.contains(&format!("Max-Age={SESSION_MAX_AGE}"))); |
| 189 | assert!(!c.contains("Secure")); |
| 190 | |
| 191 | let c = session_cookie("tok123", true); |
| 192 | assert!(c.ends_with("; Secure")); |
| 193 | |
| 194 | let c = clear_session_cookie(true); |
| 195 | assert!(c.starts_with("fbng_session=;")); |
| 196 | assert!(c.contains("Max-Age=0")); |
| 197 | assert!(c.contains("Secure")); |
| 198 | assert!(!clear_session_cookie(false).contains("Secure")); |
| 199 | } |
| 200 | |
| 201 | #[test] |
| 202 | fn parse_session_cookie_variants() { |
| 203 | let mut h = HeaderMap::new(); |
| 204 | h.insert( |
| 205 | header::COOKIE, |
| 206 | "other=1; fbng_session=abc123; x=y".parse().unwrap(), |
| 207 | ); |
| 208 | assert_eq!(parse_session_cookie(&h).as_deref(), Some("abc123")); |
| 209 | |
| 210 | let mut h = HeaderMap::new(); |
| 211 | h.insert(header::COOKIE, "other=1".parse().unwrap()); |
| 212 | assert_eq!(parse_session_cookie(&h), None); |
| 213 | |
| 214 | // Empty value → treated as absent. |
| 215 | let mut h = HeaderMap::new(); |
| 216 | h.insert(header::COOKIE, "fbng_session=".parse().unwrap()); |
| 217 | assert_eq!(parse_session_cookie(&h), None); |
| 218 | |
| 219 | assert_eq!(parse_session_cookie(&HeaderMap::new()), None); |
| 220 | |
| 221 | // First occurrence wins. |
| 222 | let mut h = HeaderMap::new(); |
| 223 | h.insert( |
| 224 | header::COOKIE, |
| 225 | "fbng_session=first; fbng_session=second".parse().unwrap(), |
| 226 | ); |
| 227 | assert_eq!(parse_session_cookie(&h).as_deref(), Some("first")); |
| 228 | |
| 229 | // Cookie name must match exactly. |
| 230 | let mut h = HeaderMap::new(); |
| 231 | h.insert( |
| 232 | header::COOKIE, |
| 233 | "fbng_session2=x; Xfbng_session=y".parse().unwrap(), |
| 234 | ); |
| 235 | assert_eq!(parse_session_cookie(&h), None); |
| 236 | } |
| 237 | } |
| 238 |