forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

auth.rs482 lines, 16.8 KiBHistoryRawDownload
1//! Session cookie, current user, CSRF checks and login redirect helpers.
2//!
3//! The browser holds the raw session token in `__Host-forge_session`. The database
4//! stores only `hash_token(token)`, so a leaked DB row cannot be replayed as a cookie.
5
6use std::sync::{Arc, OnceLock};
7use std::time::Duration;
8
9use forge_core::password::{hash_password, verify_password};
10use forge_core::session::{new_csrf_token, new_session_token};
11use forge_core::time::stamp_after;
12use forge_core::token::{constant_time_eq, hash_token};
13use forge_core::{Session, Store, User, secret, totp};
14use tokio::sync::Semaphore;
15use topcoat::Result;
16use topcoat::context::{Cx, context};
17use topcoat::cookie::{Cookie, Cookies, SameSite, cookies, time};
18use topcoat::router::error::{forbidden, see_other};
19use topcoat::router::request::{headers, uri};
20
21use crate::client_ip::client_addr;
22use crate::state::AppState;
23
24/// Logical cookie name. `override_prefix_host()` stores it as `__Host-forge_session`.
25pub const SESSION_COOKIE: &str = "forge_session";
26/// Lifetime of a web session, both in the database and on the cookie.
27pub const SESSION_TTL: Duration = Duration::from_secs(30 * 24 * 60 * 60);
28
29/// Logical name of the pre-session CSRF cookie, used by `/login` and `/setup` before any
30/// session exists. Stored as `__Host-forge_precsrf`.
31pub const PRE_CSRF_COOKIE: &str = "forge_precsrf";
32/// Lifetime of the pre-session CSRF cookie.
33const PRE_CSRF_TTL: Duration = Duration::from_secs(60 * 60);
34
35/// Logical name of the pending-login cookie set between the password and the second factor.
36/// Stored as `__Host-forge_2fa`. Its value is sealed with the instance key.
37pub const PENDING_2FA_COOKIE: &str = "forge_2fa";
38/// How long a password-verified login may wait for its second factor.
39pub const PENDING_2FA_TTL: Duration = Duration::from_secs(5 * 60);
40
41/// Maximum accepted length of a `next` redirect target.
42const MAX_NEXT_LEN: usize = 2048;
43
44/// Cookie jar that forces the `__Host-` prefix (Secure, Path=/, no Domain).
45fn session_jar(cx: &Cx) -> impl Cookies + '_ {
46 cookies(cx).override_prefix_host()
47}
48
49/// Resolves the signed-in user from the session cookie.
50///
51/// Returns `None` when there is no cookie, the session is unknown or expired, or its
52/// user no longer exists. Every successful lookup refreshes `last_seen`.
53pub async fn current_user(cx: &Cx) -> forge_core::Result<Option<(User, Session)>> {
54 let Some(cookie) = session_jar(cx).get(SESSION_COOKIE) else {
55 return Ok(None);
56 };
57 let store = &context::<AppState>(cx).store;
58 let Some(session) = store
59 .session_by_token_hash(&hash_token(cookie.value()))
60 .await?
61 else {
62 return Ok(None);
63 };
64 // An organization never signs in, even if a session row names one.
65 let Some(user) = store
66 .user_by_id(&session.user_id)
67 .await?
68 .filter(|user| !user.is_org())
69 else {
70 return Ok(None);
71 };
72 let addr = client_addr(cx).to_string();
73 store.touch_session(&session.id, Some(&addr)).await?;
74 Ok(Some((user, session)))
75}
76
77/// Creates a session for `user` and sets the session cookie on the response.
78pub async fn login(cx: &Cx, user: &User) -> forge_core::Result<Session> {
79 let store = &context::<AppState>(cx).store;
80 let token = new_session_token();
81 let addr = client_addr(cx).to_string();
82 let session = store
83 .create_session(
84 &user.id,
85 &hash_token(&token),
86 &new_csrf_token(),
87 &stamp_after(SESSION_TTL),
88 user_agent(cx).as_deref(),
89 Some(&addr),
90 )
91 .await?;
92 // A new sign-in shows up in the user's session list in their other open tabs.
93 context::<AppState>(cx)
94 .live
95 .bump(&crate::live::Topic::Account(user.id.clone()));
96 let max_age = time::Duration::seconds(i64::try_from(SESSION_TTL.as_secs()).unwrap_or(i64::MAX));
97 session_jar(cx).add(
98 Cookie::build((SESSION_COOKIE, token))
99 .path("/")
100 .secure(true)
101 .http_only(true)
102 .same_site(SameSite::Lax)
103 .max_age(max_age)
104 .build(),
105 );
106 Ok(session)
107}
108
109/// Deletes the session row and clears the cookie.
110pub async fn logout(cx: &Cx, session: &Session) -> forge_core::Result<()> {
111 let state = context::<AppState>(cx);
112 state.store.delete_session(&session.id).await?;
113 // The user's other tabs may show this session (a page that now leaves for the login page).
114 crate::live::bump_account(state, &session.user_id);
115 session_jar(cx).remove(Cookie::build((SESSION_COOKIE, "")).path("/"));
116 Ok(())
117}
118
119/// Constant-time comparison of the submitted CSRF token with the session's token.
120pub fn check_csrf(session: &Session, submitted: &str) -> bool {
121 // An empty stored token must never match, even an empty submission.
122 !session.csrf_token.is_empty()
123 && constant_time_eq(session.csrf_token.as_bytes(), submitted.as_bytes())
124}
125
126/// Returns the pre-session CSRF token for a form, issuing one when the browser has none.
127///
128/// The existing cookie is reused so that two open login tabs keep working. The same value
129/// goes into a hidden `precsrf` field; the POST must echo it back.
130pub fn pre_csrf_token(cx: &Cx) -> String {
131 if let Some(cookie) = session_jar(cx).get(PRE_CSRF_COOKIE) {
132 let value = cookie.value();
133 if !value.is_empty() {
134 return value.to_owned();
135 }
136 }
137 let token = new_csrf_token();
138 session_jar(cx).add(pre_csrf_cookie(token.clone()));
139 token
140}
141
142/// True only when the submitted `precsrf` equals the cookie, compared in constant time.
143pub fn check_pre_csrf(cx: &Cx, submitted: &str) -> bool {
144 let Some(cookie) = session_jar(cx).get(PRE_CSRF_COOKIE) else {
145 return false;
146 };
147 !cookie.value().is_empty() && constant_time_eq(cookie.value().as_bytes(), submitted.as_bytes())
148}
149
150/// Removes the pre-session CSRF cookie. Called after a successful login or setup.
151pub fn clear_pre_csrf(cx: &Cx) {
152 session_jar(cx).remove(Cookie::build((PRE_CSRF_COOKIE, "")).path("/"));
153}
154
155fn pre_csrf_cookie(token: String) -> Cookie<'static> {
156 Cookie::build((PRE_CSRF_COOKIE, token))
157 .path("/")
158 .secure(true)
159 .http_only(true)
160 .same_site(SameSite::Strict)
161 .max_age(time::Duration::seconds(
162 i64::try_from(PRE_CSRF_TTL.as_secs()).unwrap_or(i64::MAX),
163 ))
164 .build()
165}
166
167/// Argon2 runs at once, server-wide. Each hash or verify allocates about 19 MiB, so a burst of
168/// logins would otherwise pile that memory up on the blocking pool.
169const MAX_CONCURRENT_PASSWORD_HASHES: usize = 4;
170
171/// Permits for argon2 work. A permit is held until the hash or verify finishes.
172fn password_slots() -> &'static Arc<Semaphore> {
173 static SLOTS: OnceLock<Arc<Semaphore>> = OnceLock::new();
174 SLOTS.get_or_init(|| Arc::new(Semaphore::new(MAX_CONCURRENT_PASSWORD_HASHES)))
175}
176
177/// Hashes a password with argon2 on the blocking pool, keeping the async runtime free.
178pub async fn hash_password_async(password: String) -> forge_core::Result<String> {
179 let _permit = password_slots()
180 .acquire()
181 .await
182 .map_err(|_| forge_core::Error::Crypto("password hashing is shut down".into()))?;
183 tokio::task::spawn_blocking(move || hash_password(&password))
184 .await
185 .map_err(|_| forge_core::Error::Crypto("password hashing task failed".into()))?
186}
187
188/// Verifies a password with argon2 on the blocking pool.
189pub async fn verify_password_async(password: String, hash: String) -> forge_core::Result<bool> {
190 let _permit = password_slots()
191 .acquire()
192 .await
193 .map_err(|_| forge_core::Error::Crypto("password verification is shut down".into()))?;
194 tokio::task::spawn_blocking(move || verify_password(&password, &hash))
195 .await
196 .map_err(|_| forge_core::Error::Crypto("password verification task failed".into()))
197}
198
199/// Returns the signed-in user, or a 303 redirect to `/login?next=<current path>`.
200pub async fn require_user(cx: &Cx) -> Result<(User, Session)> {
201 match current_user(cx).await? {
202 Some(viewer) => Ok(viewer),
203 None => {
204 let path = uri(cx).path_and_query().map_or("/", |p| p.as_str());
205 let target = format!("/login?next={}", percent_encode(path));
206 Err(see_other(target).into())
207 }
208 }
209}
210
211/// Requires a signed-in user and a valid `csrf` form field. Returns 403 on a bad token.
212pub async fn require_csrf(cx: &Cx, submitted: &str) -> Result<(User, Session)> {
213 let (user, session) = require_user(cx).await?;
214 if check_csrf(&session, submitted) {
215 Ok((user, session))
216 } else {
217 Err(forbidden().into())
218 }
219}
220
221/// A login that has passed its password and waits for the second factor.
222pub struct PendingLogin {
223 pub user_id: String,
224 pub next: String,
225}
226
227/// Seconds since the Unix epoch, or 0 if the clock is before it.
228pub fn unix_now() -> u64 {
229 std::time::SystemTime::now()
230 .duration_since(std::time::UNIX_EPOCH)
231 .map_or(0, |d| d.as_secs())
232}
233
234/// Sets the pending-login cookie. Its payload is `expires|user_id|next`, sealed so the browser
235/// cannot change the user or the expiry.
236pub fn set_pending_login(
237 cx: &Cx,
238 key: &[u8; 32],
239 user_id: &str,
240 next: &str,
241) -> forge_core::Result<()> {
242 let expires = unix_now() + PENDING_2FA_TTL.as_secs();
243 let sealed = secret::seal(key, format!("{expires}|{user_id}|{next}").as_bytes())?;
244 let max_age = time::Duration::seconds(i64::try_from(PENDING_2FA_TTL.as_secs()).unwrap_or(0));
245 session_jar(cx).add(
246 Cookie::build((PENDING_2FA_COOKIE, sealed))
247 .path("/")
248 .secure(true)
249 .http_only(true)
250 .same_site(SameSite::Strict)
251 .max_age(max_age)
252 .build(),
253 );
254 Ok(())
255}
256
257/// The pending login from the cookie, or `None` when the cookie is missing, tampered with,
258/// malformed or past its expiry.
259pub fn pending_login(cx: &Cx, key: &[u8; 32]) -> Option<PendingLogin> {
260 let cookie = session_jar(cx).get(PENDING_2FA_COOKIE)?;
261 let plain = secret::open(key, cookie.value()).ok()?;
262 let text = String::from_utf8(plain).ok()?;
263 let mut parts = text.splitn(3, '|');
264 let expires: u64 = parts.next()?.parse().ok()?;
265 let user_id = parts.next()?;
266 let next = parts.next()?;
267 if unix_now() >= expires {
268 return None;
269 }
270 Some(PendingLogin {
271 user_id: user_id.to_owned(),
272 next: next.to_owned(),
273 })
274}
275
276/// Removes the pending-login cookie.
277pub fn clear_pending_login(cx: &Cx) {
278 session_jar(cx).remove(Cookie::build((PENDING_2FA_COOKIE, "")).path("/"));
279}
280
281/// True when the user has confirmed two-factor authentication.
282pub async fn two_factor_enabled(store: &Store, user_id: &str) -> forge_core::Result<bool> {
283 Ok(store
284 .totp_state(user_id)
285 .await?
286 .is_some_and(|state| state.enabled))
287}
288
289/// Checks a second-factor input for a user with two-factor on. A six-digit input is a TOTP
290/// code, checked with replay protection. Anything else is a recovery code, which is used up
291/// on success. Returns false for any wrong or spent input.
292pub async fn verify_second_factor(
293 store: &Store,
294 key: &[u8; 32],
295 user_id: &str,
296 input: &str,
297) -> forge_core::Result<bool> {
298 let input = input.trim();
299 // An organization has no second factor and never passes one.
300 if store
301 .user_by_id(user_id)
302 .await?
303 .is_none_or(|user| user.is_org())
304 {
305 return Ok(false);
306 }
307 let Some(state) = store.totp_state(user_id).await? else {
308 return Ok(false);
309 };
310 let Some(sealed) = state.sealed_secret.as_deref() else {
311 return Ok(false);
312 };
313 if !state.enabled {
314 return Ok(false);
315 }
316 let shared = secret::open(key, sealed)?;
317 let is_totp = input.len() == totp::DIGITS && input.bytes().all(|b| b.is_ascii_digit());
318 if is_totp {
319 return match totp::verify(&shared, input, totp::step_for(unix_now()), state.last_step) {
320 Some(step) => store.accept_totp_step(user_id, step).await,
321 None => Ok(false),
322 };
323 }
324 store
325 .consume_recovery_code(user_id, &totp::recovery_code_hash(input))
326 .await
327}
328
329/// Returns `next` only when it is a same-site relative path; otherwise `/`.
330///
331/// Accepts a single leading `/`, rejects `//` and `/\` (protocol-relative or browser
332/// backslash tricks), rejects control characters and caps the length.
333pub fn safe_next(next: Option<&str>) -> &str {
334 match next {
335 Some(n) if is_local_path(n) => n,
336 _ => "/",
337 }
338}
339
340fn is_local_path(path: &str) -> bool {
341 path.len() <= MAX_NEXT_LEN
342 && path.starts_with('/')
343 && !path.starts_with("//")
344 && !path.starts_with("/\\")
345 && path.chars().all(|c| !c.is_control())
346}
347
348/// Percent-encodes everything except unreserved characters and `/`.
349pub fn percent_encode(input: &str) -> String {
350 let mut out = String::with_capacity(input.len());
351 for b in input.bytes() {
352 match b {
353 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => {
354 out.push(char::from(b));
355 }
356 _ => out.push_str(&format!("%{b:02X}")),
357 }
358 }
359 out
360}
361
362/// The request's `User-Agent`, truncated to 512 characters.
363pub fn user_agent(cx: &Cx) -> Option<String> {
364 headers(cx)
365 .get(http::header::USER_AGENT)
366 .and_then(|v| v.to_str().ok())
367 .map(|s| s.chars().take(512).collect())
368}
369
370#[cfg(test)]
371mod tests {
372 use super::*;
373
374 fn session_with_csrf(csrf: &str) -> Session {
375 Session {
376 id: "s1".into(),
377 user_id: "u1".into(),
378 csrf_token: csrf.into(),
379 created_at: String::new(),
380 expires_at: String::new(),
381 last_seen: String::new(),
382 user_agent: None,
383 ip: None,
384 last_ip: None,
385 }
386 }
387
388 #[test]
389 fn csrf_accepts_only_the_exact_token() {
390 let s = session_with_csrf("abc123");
391 assert!(check_csrf(&s, "abc123"));
392 assert!(!check_csrf(&s, "abc124"));
393 assert!(!check_csrf(&s, "abc12"));
394 assert!(!check_csrf(&s, ""));
395 }
396
397 #[test]
398 fn csrf_rejects_empty_session_token() {
399 let s = session_with_csrf("");
400 assert!(!check_csrf(&s, ""));
401 assert!(!check_csrf(&s, "x"));
402 }
403
404 #[test]
405 fn next_allows_local_paths() {
406 assert_eq!(safe_next(Some("/")), "/");
407 assert_eq!(safe_next(Some("/tahinli/repo")), "/tahinli/repo");
408 assert_eq!(safe_next(Some("/settings/keys?x=1")), "/settings/keys?x=1");
409 }
410
411 #[test]
412 fn next_rejects_open_redirects() {
413 for bad in [
414 "",
415 "https://evil.example/",
416 "//evil.example/",
417 "/\\evil.example/",
418 "evil.example",
419 "\\\\evil",
420 "/\n/evil",
421 "/\t",
422 ] {
423 assert_eq!(safe_next(Some(bad)), "/", "input {bad:?}");
424 }
425 assert_eq!(safe_next(None), "/");
426 }
427
428 #[test]
429 fn next_rejects_overlong_paths() {
430 let long = format!("/{}", "a".repeat(MAX_NEXT_LEN));
431 assert_eq!(safe_next(Some(&long)), "/");
432 }
433
434 #[test]
435 fn percent_encode_keeps_slashes_and_encodes_the_rest() {
436 assert_eq!(percent_encode("/a/b-c_d.e~f"), "/a/b-c_d.e~f");
437 assert_eq!(percent_encode("/s?x=1&y=2"), "/s%3Fx%3D1%26y%3D2");
438 assert_eq!(percent_encode("/a b"), "/a%20b");
439 }
440
441 /// An organization has no second factor and never passes one, even with a valid TOTP code or
442 /// a recovery code on its row. A person with the same setup does pass.
443 #[tokio::test]
444 async fn an_org_never_passes_a_second_factor() {
445 let dir = tempfile::tempdir().unwrap();
446 let store = Store::open(&dir.path().join("forge.db")).await.unwrap();
447 let key = [7u8; 32];
448 let tahinli = store
449 .create_user("tahinli", None, "h", false)
450 .await
451 .unwrap();
452 let org = store.create_org("acme", &tahinli.id).await.unwrap();
453 let shared = forge_core::totp::new_secret();
454 let sealed = forge_core::secret::seal(&key, &shared).unwrap();
455 let code = forge_core::totp::code_at(&shared, forge_core::totp::step_for(unix_now()));
456 let recovery = forge_core::totp::recovery_code_hash("aaaa-bbbb");
457 for id in [&org.id, &tahinli.id] {
458 store.set_totp_secret(id, &sealed).await.unwrap();
459 store
460 .enable_totp(id, 0, std::slice::from_ref(&recovery))
461 .await
462 .unwrap();
463 }
464
465 assert!(
466 !verify_second_factor(&store, &key, &org.id, &code)
467 .await
468 .unwrap()
469 );
470 assert!(
471 !verify_second_factor(&store, &key, &org.id, "aaaa-bbbb")
472 .await
473 .unwrap()
474 );
475 // The same setup on a person works, so the refusal is the org rule.
476 assert!(
477 verify_second_factor(&store, &key, &tahinli.id, "aaaa-bbbb")
478 .await
479 .unwrap()
480 );
481 }
482}