diff options
| author | aur-build <aur-build@localhost> | 2026-11-18 14:41:45 +0000 |
|---|---|---|
| committer | aur-build <aur-build@localhost> | 2026-11-18 14:41:45 +0000 |
| commit | 3370a487d6e1100623ebfd982967f1223d251607 (patch) | |
| tree | 124db2f1fe41c3835b4aa4f39a980200804202ea /tests | |
| parent | 157c078e52fee6c37ff20093189ae7ad7cd223cb (diff) | |
| download | aur-build-3370a487d6e1100623ebfd982967f1223d251607.tar.gz aur-build-3370a487d6e1100623ebfd982967f1223d251607.zip | |
http: the session id is the credential, not a cookie a client can type
The gate asked whether the request carried `Cookie: auth=1`, and login did
nothing but set that literal value, so the password protected the login form
and nothing else: anyone could read the reviews, the audit log, the settings
and the build logs by typing the cookie themselves, and the CSRF step then
happily minted them a session to POST with. The random sid machinery was
already there and already unguessable; it was just never bound to the flag
that said "someone authenticated".
A session now carries that flag. `auth.rs` holds a map of live sids to
whether they passed the password gate; `authenticate` can only flip a sid this
process minted, so a login attempt cannot mint a session as a side effect.
`gate` asks `is_authenticated(sid)` and nothing else, and the `auth` cookie is
gone from both the login response and the logout one. Login rotates the sid
rather than promoting the anonymous one, so the session that existed before
the password was typed is never the one that carries the privilege after it;
logout drops the sid, which invalidates its derived CSRF token with it.
Two tests, both over a bare socket because a client that follows redirects
turns "you are not signed in" into the login page's 200 and hides the whole
point: `a_forged_auth_cookie_is_not_a_session` (the exact forgery, on every
sensitive surface, GET and POST) and `login_rotates_the_session_and_logout_ends_it`
(rotation, dead pre-login sid, dead logged-out sid). The audit actor is
honest now too: with a password set, only an authenticated session is "web".
Diffstat (limited to 'tests')
| -rw-r--r-- | tests/common/mod.rs | 87 | ||||
| -rw-r--r-- | tests/http.rs | 52 |
2 files changed, 138 insertions, 1 deletions
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] |
