forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.09.4 MiB3d53dfdTahinli1 month ago208 commits

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