forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.5 MiBb00f3f4Tahinli1 month ago147 commits

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