diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/http/auth.rs | 40 | ||||
| -rw-r--r-- | src/http/mod.rs | 13 | ||||
| -rw-r--r-- | src/http/routes.rs | 39 |
3 files changed, 68 insertions, 24 deletions
diff --git a/src/http/auth.rs b/src/http/auth.rs index 9186f0e..3d05cab 100644 --- a/src/http/auth.rs +++ b/src/http/auth.rs @@ -5,17 +5,26 @@ //! opaque random id held in memory; the CSRF token is derived from it, so a //! cross-site form cannot produce one it has not seen, and there is no token //! table to keep in step with the sessions. +//! +//! **The sid is the credential.** A sid is minted for anonymous visitors too, +//! because the CSRF token has to be derivable before anyone has typed a +//! password; what the password buys is the `authenticated` flag on one sid. +//! Nothing else in the request proves who you are, which is why there is no +//! separate "logged in" cookie to forge. -use std::collections::HashSet; +use std::collections::HashMap; use std::sync::Mutex; use std::sync::OnceLock; use crate::hash; -static SESSIONS: OnceLock<Mutex<HashSet<String>>> = OnceLock::new(); +/// Live sids and whether each has passed the password gate. One map, so the +/// two facts cannot drift apart: dropping a session removes its authentication +/// with it. +static SESSIONS: OnceLock<Mutex<HashMap<String, bool>>> = OnceLock::new(); -fn sessions() -> &'static Mutex<HashSet<String>> { - SESSIONS.get_or_init(|| Mutex::new(HashSet::new())) +fn sessions() -> &'static Mutex<HashMap<String, bool>> { + SESSIONS.get_or_init(|| Mutex::new(HashMap::new())) } /// Random hex token from the system RNG (`/dev/urandom` through our hash). @@ -39,16 +48,35 @@ fn counter() -> u64 { C.fetch_add(1, std::sync::atomic::Ordering::Relaxed) } +/// Mint an anonymous session: enough for a CSRF token, not enough to see a +/// single page when a password is set. pub fn new_session() -> String { let sid = random_hex(); if let Ok(mut s) = sessions().lock() { - s.insert(sid.clone()); + s.insert(sid.clone(), false); } sid } pub fn is_valid_session(sid: &str) -> bool { - sessions().lock().map(|s| s.contains(sid)).unwrap_or(false) + sessions().lock().map(|s| s.contains_key(sid)).unwrap_or(false) +} + +/// Mark a session as having passed the password gate. Only ever called with a +/// sid this process minted, and it cannot mint one: an unknown sid stays +/// unknown rather than being inserted as a side effect of a login attempt. +pub fn authenticate(sid: &str) { + if let Ok(mut s) = sessions().lock() { + if let Some(authenticated) = s.get_mut(sid) { + *authenticated = true; + } + } +} + +/// The gate's whole question: is this sid one we issued *and* did someone type +/// the password into a form on this session? +pub fn is_authenticated(sid: &str) -> bool { + sessions().lock().map(|s| s.get(sid).copied().unwrap_or(false)).unwrap_or(false) } pub fn drop_session(sid: &str) { diff --git a/src/http/mod.rs b/src/http/mod.rs index 16ff6b1..07024d8 100644 --- a/src/http/mod.rs +++ b/src/http/mod.rs @@ -5,9 +5,11 @@ //! mutations are handed to the writer actor as a transaction request. That is //! what keeps a slow browser from ever holding the database lock. //! -//! Two guards on every POST: a session cookie, and a CSRF token that must match -//! it. Forms are plain `<form method=post>`, so the whole approval flow works -//! with JavaScript switched off (§12). +//! Two guards on every POST: a session id, and a CSRF token that must match +//! it. The session id is the only credential the browser holds, and it counts +//! as authentication only if someone typed the password into a form on that +//! exact session (§12). Forms are plain `<form method=post>`, so the whole +//! approval flow works with JavaScript switched off. mod auth; mod forms; @@ -232,12 +234,13 @@ fn dispatch(state: &State, req: &Req) -> Res { } // Session gate: mint a session for anonymous visitors so the CSRF token - // exists even before anyone logs in. + // exists even before anyone logs in. It is not a login — `gate` only lets + // through a sid that a successful login marked authenticated. let (sid, new_session) = match req.cookie("sid") { Some(s) if auth::is_valid_session(&s) => (s, false), _ => (auth::new_session(), true), }; - let gated = routes::gate(state, req); + let gated = routes::gate(state, req, &sid); if let Some(mut res) = gated { if new_session { res.header("X-New-Session", &sid); diff --git a/src/http/routes.rs b/src/http/routes.rs index 9efb90b..abd7345 100644 --- a/src/http/routes.rs +++ b/src/http/routes.rs @@ -12,13 +12,14 @@ use super::auth; use super::render::*; use super::{sse, Req, Res, State}; -/// Redirect an unauthenticated visitor to the login page. -pub fn gate(state: &State, req: &Req) -> Option<Res> { +/// Redirect an unauthenticated visitor to the login page. The session id is +/// the credential: a cookie a client typed by hand proves nothing, only a sid +/// this process minted and marked authenticated at a successful login does. +pub fn gate(state: &State, req: &Req, sid: &str) -> Option<Res> { if !auth::auth_required(&state.cfg) { return None; } - let signed_in = req.cookie("auth").as_deref() == Some("1"); - if signed_in || req.path == "/login" { + if auth::is_authenticated(sid) || req.path == "/login" { return None; } Some(Res::redirect("/login")) @@ -29,7 +30,7 @@ pub fn login_form(state: &State, req: &Req) -> Res { page_to_res(Login { page, error: String::new() }, 200) } -/// Forget the session server-side and clear both cookies. The CSRF token is +/// Forget the session server-side and clear the cookie. The CSRF token is /// derived from the sid, so dropping the sid invalidates every form a browser /// still has open — which is exactly what logout should do. pub fn logout(req: &Req) -> Res { @@ -37,7 +38,6 @@ pub fn logout(req: &Req) -> Res { auth::drop_session(&sid); } let mut res = Res::redirect("/login"); - res.header("Set-Cookie", "auth=; Path=/; Max-Age=0"); res.header("Set-Cookie", "sid=; Path=/; Max-Age=0"); res } @@ -46,8 +46,17 @@ pub fn login(state: &State, req: &Req) -> Res { let given = req.form_get("password").unwrap_or_default(); let page = Page::new("Sign in", csrf(state, req)); if auth::password_ok(&state.cfg, &given) { + // Rotate rather than promote: the sid the visitor arrived with (if any) + // is dropped, so the session that existed before the password was typed + // is never the one that carries the privilege afterwards. + if let Some(old) = req.cookie("sid") { + auth::drop_session(&old); + } + let sid = auth::new_session(); + auth::authenticate(&sid); let mut res = Res::redirect("/"); - res.header("Set-Cookie", "auth=1; Path=/; HttpOnly; SameSite=Strict"); + // `serve` turns this into the `Set-Cookie: sid=…` header. + res.header("X-New-Session", &sid); res } else { page_to_res(Login { page, error: "wrong password".into() }, 401) @@ -335,7 +344,7 @@ fn review_approve(state: &State, req: &Req, id: &str) -> Res { let identity = req.form_get("identity_hash").unwrap_or_default(); let digest = req.form_get("diff_digest").unwrap_or_default(); let note = req.form_get("note").filter(|s| !s.trim().is_empty()); - match ap::approve(db, actor(req), id, &identity, &digest, note.as_deref()) { + match ap::approve(db, actor(state, req), id, &identity, &digest, note.as_deref()) { Ok(a) => { let mut page = chrome(state, req, "Reviews", "nav_reviews"); page.flash = format!("approved {} (approval {}); build queued", c.pkgbase, a.id); @@ -400,7 +409,7 @@ fn review_reject(state: &State, req: &Req, id: &str) -> Res { page.flash_err = true; return page_to_res(ReviewsPage { page, rows: review_rows(state) }, 400); }; - match ap::reject(db, actor(req), id, ¬e) { + match ap::reject(db, actor(state, req), id, ¬e) { Ok(()) => { let mut page = chrome(state, req, "Reviews", "nav_reviews"); page.flash = format!("rejected #{id}; it can be re-opened from the package page"); @@ -453,12 +462,12 @@ fn reviews_bulk(state: &State, req: &Req) -> Res { continue; } let res = if decision == "approve" { - ap::approve(db, actor(req), id, &c.identity_hash, &c.diff_digest, Some("bulk")) + ap::approve(db, actor(state, req), id, &c.identity_hash, &c.diff_digest, Some("bulk")) .map(|_| ()) .map_err(|e| e.to_string()) } else { let note = req.form_get("note").unwrap_or_else(|| "bulk reject".into()); - ap::reject(db, actor(req), id, ¬e).map_err(|e| e.to_string()) + ap::reject(db, actor(state, req), id, ¬e).map_err(|e| e.to_string()) }; match res { Ok(()) => { @@ -482,8 +491,12 @@ fn reviews_bulk(state: &State, req: &Req) -> Res { page_to_res(ReviewsPage { page, rows: review_rows(state) }, 200) } -fn actor(req: &Req) -> &str { - if req.cookie("auth").is_some() { +/// Who the audit trail says made a decision. With no password configured the +/// UI is open on loopback and every session is the operator's; with one, only +/// a session that passed the gate gets a name. +fn actor(state: &State, req: &Req) -> &'static str { + let sid = req.cookie("sid").unwrap_or_default(); + if !auth::auth_required(&state.cfg) || auth::is_authenticated(&sid) { "web" } else { "web-anon" |
