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/// Cookie name proving that the visitor unlocked share `share_id`.
107///
108/// One cookie per share: a visitor may hold links to several protected
109/// shares, and one shared name would let each unlock evict the last.
110pub fn share_cookie_name(share_id: i64) -> String {
111 format!("fbng_share_{share_id}")
112}
113
114/// Session cookie for an unlocked share. A session cookie (no `Max-Age`), so
115/// the unlock lasts as long as the browser stays open and is not written to
116/// disk.
117pub fn share_cookie(share_id: i64, token: &str, https: bool) -> String {
118 let mut c = format!(
119 "{}={token}; Path=/; HttpOnly; SameSite=Lax",
120 share_cookie_name(share_id)
121 );
122 if https {
123 c.push_str("; Secure");
124 }
125 c
126}
127
128/// Extract the unlock token for `share_id` from the Cookie header.
129pub fn parse_share_cookie(headers: &axum::http::HeaderMap, share_id: i64) -> Option<String> {
130 cookie_value(headers, &share_cookie_name(share_id))
131}
132
133/// Extract the session token from the Cookie header, if present.
134pub fn parse_session_cookie(headers: &axum::http::HeaderMap) -> Option<String> {
135 cookie_value(headers, COOKIE_NAME)
136}
137
138/// One cookie's value out of the `Cookie` header. Empty values are treated
139/// as absent: that is how a cleared cookie arrives before it expires.
140fn cookie_value(headers: &axum::http::HeaderMap, name: &str) -> Option<String> {
141 let header = headers.get(axum::http::header::COOKIE)?.to_str().ok()?;
142 for part in header.split(';') {
143 let part = part.trim();
144 if let Some((k, v)) = part.split_once('=')
145 && k == name
146 && !v.is_empty()
147 {
148 return Some(v.to_string());
149 }
150 }
151 None
152}
153
154#[cfg(test)]
155mod tests {
156 use super::*;
157 use axum::http::{HeaderMap, header};
158
159 #[test]
160 fn share_cookie_is_per_share_and_session_scoped() {
161 let c = share_cookie(7, "tok", false);
162 assert!(c.starts_with("fbng_share_7=tok;"));
163 assert!(c.contains("HttpOnly"));
164 // No Max-Age: the unlock must not outlive the browser session.
165 assert!(!c.contains("Max-Age"));
166 assert!(!c.contains("Secure"));
167 assert!(share_cookie(7, "tok", true).contains("Secure"));
168
169 let mut h = HeaderMap::new();
170 h.insert(
171 header::COOKIE,
172 "fbng_share_7=abc; fbng_share_8=def".parse().unwrap(),
173 );
174 assert_eq!(parse_share_cookie(&h, 7).as_deref(), Some("abc"));
175 assert_eq!(parse_share_cookie(&h, 8).as_deref(), Some("def"));
176 assert_eq!(parse_share_cookie(&h, 9), None);
177 }
178
179 #[test]
180 fn password_hash_round_trip() {
181 let h = hash_password("hunter22").unwrap();
182 assert!(verify_password("hunter22", &h));
183 assert!(!verify_password("wrong-password", &h));
184 assert!(!verify_password("hunter23", &h));
185 // Fresh salt on every hash.
186 assert_ne!(h, hash_password("hunter22").unwrap());
187 // Argon2id marker is present.
188 assert!(h.starts_with("$argon2id$"));
189 }
190
191 #[test]
192 fn verify_rejects_garbage_hashes() {
193 assert!(!verify_password("x", ""));
194 assert!(!verify_password("x", "not-a-hash"));
195 assert!(!verify_password("x", "$argon2id$"));
196 }
197
198 #[test]
199 fn token_shapes_and_uniqueness() {
200 let t = random_token();
201 assert_eq!(t.len(), 64);
202 assert!(t.chars().all(|c| c.is_ascii_hexdigit()));
203
204 let s = share_token();
205 assert_eq!(s.len(), 32);
206 assert!(s.chars().all(|c| c.is_ascii_hexdigit()));
207
208 let mut seen = std::collections::HashSet::new();
209 for _ in 0..100 {
210 assert!(seen.insert(random_token()), "session token collision");
211 assert!(seen.insert(share_token()), "share token collision");
212 }
213 }
214
215 #[test]
216 fn login_delay_grows_after_free_tries() {
217 assert_eq!(delay_for(0), Duration::ZERO);
218 assert_eq!(delay_for(2), Duration::ZERO);
219 assert_eq!(delay_for(3), Duration::from_millis(500));
220 assert_eq!(delay_for(6), Duration::from_millis(2000));
221 assert_eq!(delay_for(100), Duration::from_millis(5000));
222
223 let name = "throttle-test-user";
224 assert_eq!(login_delay(name), Duration::ZERO);
225 for _ in 0..4 {
226 record_login(name, false);
227 }
228 assert_eq!(login_delay(name), Duration::from_millis(1000));
229 // Case-insensitive like the account names themselves.
230 assert_eq!(
231 login_delay("THROTTLE-test-USER"),
232 Duration::from_millis(1000)
233 );
234 record_login(name, true);
235 assert_eq!(login_delay(name), Duration::ZERO);
236 }
237
238 #[test]
239 fn session_cookie_shape() {
240 let c = session_cookie("tok123", false);
241 assert!(c.starts_with("fbng_session=tok123;"));
242 assert!(c.contains("Path=/"));
243 assert!(c.contains("HttpOnly"));
244 assert!(c.contains("SameSite=Lax"));
245 assert!(c.contains(&format!("Max-Age={SESSION_MAX_AGE}")));
246 assert!(!c.contains("Secure"));
247
248 let c = session_cookie("tok123", true);
249 assert!(c.ends_with("; Secure"));
250
251 let c = clear_session_cookie(true);
252 assert!(c.starts_with("fbng_session=;"));
253 assert!(c.contains("Max-Age=0"));
254 assert!(c.contains("Secure"));
255 assert!(!clear_session_cookie(false).contains("Secure"));
256 }
257
258 #[test]
259 fn parse_session_cookie_variants() {
260 let mut h = HeaderMap::new();
261 h.insert(
262 header::COOKIE,
263 "other=1; fbng_session=abc123; x=y".parse().unwrap(),
264 );
265 assert_eq!(parse_session_cookie(&h).as_deref(), Some("abc123"));
266
267 let mut h = HeaderMap::new();
268 h.insert(header::COOKIE, "other=1".parse().unwrap());
269 assert_eq!(parse_session_cookie(&h), None);
270
271 // Empty value → treated as absent.
272 let mut h = HeaderMap::new();
273 h.insert(header::COOKIE, "fbng_session=".parse().unwrap());
274 assert_eq!(parse_session_cookie(&h), None);
275
276 assert_eq!(parse_session_cookie(&HeaderMap::new()), None);
277
278 // First occurrence wins.
279 let mut h = HeaderMap::new();
280 h.insert(
281 header::COOKIE,
282 "fbng_session=first; fbng_session=second".parse().unwrap(),
283 );
284 assert_eq!(parse_session_cookie(&h).as_deref(), Some("first"));
285
286 // Cookie name must match exactly.
287 let mut h = HeaderMap::new();
288 h.insert(
289 header::COOKIE,
290 "fbng_session2=x; Xfbng_session=y".parse().unwrap(),
291 );
292 assert_eq!(parse_session_cookie(&h), None);
293 }
294}
295