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