summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--src/http/auth.rs40
-rw-r--r--src/http/mod.rs13
-rw-r--r--src/http/routes.rs39
-rw-r--r--tests/common/mod.rs87
-rw-r--r--tests/http.rs52
5 files changed, 206 insertions, 25 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, &note) {
+ match ap::reject(db, actor(state, req), id, &note) {
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, &note).map_err(|e| e.to_string())
+ ap::reject(db, actor(state, req), id, &note).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"
diff --git a/tests/common/mod.rs b/tests/common/mod.rs
index 661e248..67c5592 100644
--- a/tests/common/mod.rs
+++ b/tests/common/mod.rs
@@ -551,6 +551,46 @@ impl Web {
self.finish(resp, path)
}
+ /// Send a request over a bare socket: no cookie jar, no redirect following,
+ /// so the test sees the 303 a browser would have swallowed. The session
+ /// gate is only meaningful at this level — a client that follows redirects
+ /// turns "you are not signed in" into the login page's 200.
+ pub fn raw_request(&self, method: &str, path: &str, headers: &[(&str, String)], body: Option<&str>) -> Raw {
+ use std::io::{Read, Write};
+ let addr = self.server.addr.clone();
+ let mut sock = std::net::TcpStream::connect(&addr).unwrap();
+ let mut req = format!("{method} {path} HTTP/1.1\r\nHost: {addr}\r\nConnection: close\r\n");
+ for (k, v) in headers {
+ req.push_str(&format!("{k}: {v}\r\n"));
+ }
+ match body {
+ Some(b) => {
+ req.push_str("Content-Type: application/x-www-form-urlencoded\r\n");
+ req.push_str(&format!("Content-Length: {}\r\n", b.len()));
+ req.push_str("\r\n");
+ req.push_str(b);
+ }
+ None => req.push_str("\r\n"),
+ }
+ sock.write_all(req.as_bytes()).unwrap();
+ let mut raw = Vec::new();
+ sock.read_to_end(&mut raw).unwrap();
+ Raw::parse(&raw)
+ }
+
+ /// Log in and adopt the session cookie the server issued, refreshing the
+ /// CSRF token with it — the token is derived from the sid, so a login that
+ /// rotates the session invalidates the one captured before it.
+ pub fn login(&mut self, password: &str) -> Raw {
+ let raw = self.raw_request("POST", "/login", &[], Some(&format!("password={}", url_encode(password))));
+ if let Some(cookie) = raw.cookie() {
+ self.cookie = cookie;
+ }
+ let page = self.get("/");
+ self.csrf = extract(&page.body, "name=\"csrf\" content=\"", "\"").unwrap_or_default();
+ raw
+ }
+
fn finish(&self, resp: Result<ureq::Response, ureq::Error>, path: &str) -> Page {
match resp {
Ok(r) => Page { status: r.status(), body: r.into_string().unwrap_or_default() },
@@ -560,6 +600,53 @@ impl Web {
}
}
+/// A response read straight off the wire, before any client undoes it.
+pub struct Raw {
+ pub status: u16,
+ pub headers: Vec<(String, String)>,
+ pub body: String,
+}
+
+impl Raw {
+ fn parse(raw: &[u8]) -> Self {
+ let split = raw
+ .windows(4)
+ .position(|w| w == b"\r\n\r\n")
+ .unwrap_or(raw.len());
+ let head = String::from_utf8_lossy(&raw[..split]).to_string();
+ let mut lines = head.lines();
+ let status = lines.next().and_then(|l| l.split_whitespace().nth(1)).and_then(|s| s.parse().ok()).unwrap_or(0);
+ let headers = lines
+ .filter_map(|l| l.split_once(':'))
+ .map(|(k, v)| (k.trim().to_lowercase(), v.trim().to_string()))
+ .collect();
+ Self { status, headers, body: String::from_utf8_lossy(&raw[split.min(raw.len())..]).to_string() }
+ }
+
+ pub fn header(&self, name: &str) -> Option<&str> {
+ self.headers.iter().find(|(k, _)| k == name).map(|(_, v)| v.as_str())
+ }
+
+ /// The `name=value` a browser would keep from this response, i.e. the first
+ /// Set-Cookie with its attributes stripped.
+ pub fn cookie(&self) -> Option<String> {
+ self.header("set-cookie")
+ .map(|v| v.split(';').next().unwrap_or("").to_string())
+ .filter(|v| !v.is_empty() && v.contains('='))
+ }
+}
+
+/// Percent-encode enough for a form body built by hand.
+fn url_encode(s: &str) -> String {
+ s.bytes()
+ .map(|b| match b {
+ b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => (b as char).to_string(),
+ b' ' => "+".into(),
+ _ => format!("%{b:02X}"),
+ })
+ .collect()
+}
+
/// Pull an attribute or meta value out of rendered HTML and undo the escaping
/// the templates applied — a page is the contract here, so we read it as one.
pub fn extract(hay: &str, open: &str, close: &str) -> Option<String> {
diff --git a/tests/http.rs b/tests/http.rs
index d5387dc..0ca8a6b 100644
--- a/tests/http.rs
+++ b/tests/http.rs
@@ -203,7 +203,7 @@ fn bulk_approve_refuses_high_risk_without_individual_confirmation() {
#[test]
fn a_password_gate_redirects_anonymous_visitors() {
- let web = Web::with_password("plain-make", "s3cret");
+ let mut web = Web::with_password("plain-make", "s3cret");
let page = web.get("/reviews");
assert_eq!(page.status, 200);
// The gate redirects; ureq follows, so we land on the login page.
@@ -212,6 +212,56 @@ fn a_password_gate_redirects_anonymous_visitors() {
let bad = web.post("/login", &[("csrf", &web.csrf), ("password", "nope")]);
assert_eq!(bad.status, 401);
assert!(web.get("/packages").body.contains("Sign in"), "still not gated");
+ let ok = web.login("s3cret");
+ assert_eq!(ok.status, 303, "a correct password did not redirect");
+ let page = web.get("/packages");
+ assert_eq!(page.status, 200);
+ assert!(!page.body.contains("Sign in"), "still gated after the right password");
+}
+
+#[test]
+fn a_forged_auth_cookie_is_not_a_session() {
+ // What this pins: the gate used to read `Cookie: auth=1`, a value login
+ // merely echoed, so any client that typed the cookie itself could read the
+ // reviews, the audit log and the build output without ever supplying the
+ // password. The session id is the credential now, and only this process
+ // can mint one.
+ let web = Web::with_password("plain-make", "s3cret");
+ for path in ["/", "/reviews", "/audit", "/settings", "/builds", "/packages"] {
+ let res = web.raw_request("GET", path, &[("Cookie", "auth=1".into())], None);
+ assert_eq!(res.status, 303, "{path} let a forged cookie through ({}): {}", res.status, &res.body[..120.min(res.body.len())]);
+ assert_eq!(res.header("location"), Some("/login"), "{path} did not redirect to the login page");
+ }
+ // A POST with the forged cookie is turned away at the gate too, before the
+ // CSRF step ever gets a chance to mint the attacker a session of their own.
+ let res = web.raw_request("POST", "/logout", &[("Cookie", "auth=1".into())], Some(""));
+ assert_eq!(res.status, 303, "a forged cookie reached a mutating route");
+ // And the word "auth" is not a cookie the server recognises anywhere.
+ let res = web.raw_request("GET", "/reviews", &[("Cookie", "auth=yes".into())], None);
+ assert_eq!(res.status, 303);
+}
+
+#[test]
+fn login_rotates_the_session_and_logout_ends_it() {
+ let mut web = Web::with_password("plain-make", "s3cret");
+ // Arrive with an anonymous session (the CSRF token needs one), then log in.
+ let anon = web.raw_request("GET", "/", &[], None).cookie().unwrap_or_default();
+ let res = web.login("s3cret");
+ assert_eq!(res.status, 303);
+ assert_eq!(res.header("location"), Some("/"));
+ let session = res.cookie().unwrap_or_default();
+ assert!(!session.is_empty(), "a successful login issued no session cookie");
+ assert_ne!(session, anon, "login promoted the anonymous session instead of rotating it");
+ // The new session sees the surface; the sid it replaced is dead.
+ assert_eq!(web.raw_request("GET", "/reviews", &[("Cookie", session.clone())], None).status, 200);
+ if !anon.is_empty() {
+ assert_eq!(web.raw_request("GET", "/reviews", &[("Cookie", anon)], None).status, 303, "the pre-login sid still worked");
+ }
+ // Logout drops the sid server-side, which invalidates its CSRF token with
+ // it, so the same cookie is an anonymous visitor again.
+ let out = web.raw_request("POST", "/logout", &[("Cookie", session.clone()), ("Content-Type", "application/x-www-form-urlencoded".into())], Some(&format!("csrf={}", web.csrf)));
+ assert_eq!(out.status, 303, "logout did not redirect: {}", out.status);
+ assert_eq!(web.raw_request("GET", "/reviews", &[("Cookie", session)], None).status, 303, "the logged-out sid still worked");
}
#[test]