diff options
Diffstat (limited to 'src/http/mod.rs')
| -rw-r--r-- | src/http/mod.rs | 228 |
1 files changed, 228 insertions, 0 deletions
diff --git a/src/http/mod.rs b/src/http/mod.rs new file mode 100644 index 0000000..65bf2c4 --- /dev/null +++ b/src/http/mod.rs @@ -0,0 +1,228 @@ +//! The web surface (§12). +//! +//! `tiny_http`, thread-per-connection, blocking. Handlers **read** through the +//! thread-local read-only connections and never touch the write connection; +//! 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). + +mod auth; +mod forms; +mod render; +mod routes; + +use std::sync::Arc; + +use crate::config::Config; +use crate::db::Db; + +/// Shared state every handler needs. +pub struct State { + pub cfg: Config, + pub db: Db, +} + +/// A request that has been decoded enough to route on. +pub struct Req { + pub method: String, + pub path: String, + pub query: String, + pub body: String, + pub cookies: Vec<(String, String)>, + pub query_pairs: Vec<(String, String)>, +} + +impl Req { + pub fn form(&self) -> Vec<(String, String)> { + forms::parse(&self.body) + } + pub fn form_get(&self, key: &str) -> Option<String> { + self.form().into_iter().find(|(k, _)| k == key).map(|(_, v)| v) + } + pub fn query_get(&self, key: &str) -> Option<String> { + self.query_pairs.iter().find(|(k, _)| k == key).map(|(_, v)| v.clone()) + } + pub fn cookie(&self, name: &str) -> Option<String> { + self.cookies.iter().find(|(k, _)| k == name).map(|(_, v)| v.clone()) + } +} + +/// What a handler produced. +pub struct Res { + pub status: u16, + pub content_type: String, + pub body: Vec<u8>, + pub headers: Vec<(String, String)>, +} + +impl Res { + pub fn html(status: u16, body: String) -> Self { + Self { status, content_type: "text/html; charset=utf-8".into(), body: body.into_bytes(), headers: Vec::new() } + } + pub fn text(status: u16, body: String) -> Self { + Self { status, content_type: "text/plain; charset=utf-8".into(), body: body.into_bytes(), headers: Vec::new() } + } + pub fn redirect(location: &str) -> Self { + Self { + status: 303, + content_type: "text/plain".into(), + body: b"redirecting".to_vec(), + headers: vec![("Location".into(), location.into())], + } + } + pub fn found(&self) -> bool { + self.status < 400 + } + fn header(&mut self, name: &str, value: &str) { + self.headers.push((name.into(), value.into())); + } +} + +/// Start the HTTP server. Returns the accept-loop handle and the address it +/// actually bound, which matters for `:0` in tests. +pub struct Server { + pub handle: std::thread::JoinHandle<()>, + pub addr: String, +} + +pub fn spawn(cfg: Config, db: Db) -> std::io::Result<Server> { + let server = tiny_http::Server::http(&cfg.bind) + .map_err(|e| std::io::Error::other(e.to_string()))?; + let addr = server.server_addr().to_ip().map(|a| a.to_string()).unwrap_or_else(|| cfg.bind.clone()); + let state = Arc::new(State { cfg, db }); + eprintln!("aur-build listening on http://{addr}"); + let handle = std::thread::Builder::new() + .name("http-accept".into()) + .spawn(move || { + // `tiny_http` hands each connection to its own worker internally; + // the accept loop just blocks on `recv` and hands off. + for request in server.incoming_requests() { + let state = state.clone(); + std::thread::Builder::new() + .name("http-conn".into()) + .spawn(move || { + if let Err(e) = serve(state, request) { + eprintln!("http: {e}"); + } + }) + .ok(); + } + })?; + Ok(Server { handle, addr }) +} + +fn serve(state: Arc<State>, mut request: tiny_http::Request) -> std::io::Result<()> { + let url = request.url().to_string(); + let (path, query) = match url.split_once('?') { + Some((p, q)) => (p.to_string(), q.to_string()), + None => (url.clone(), String::new()), + }; + let mut body = String::new(); + let _ = request.as_reader().read_to_string(&mut body); + let cookies = request + .headers() + .iter() + .find(|h| h.field.equiv("Cookie")) + .map(|h| auth::parse_cookies(h.value.as_str())) + .unwrap_or_default(); + let req = Req { + method: request.method().as_str().to_string(), + path: percent_decode(&path), + query: query.clone(), + body, + cookies, + query_pairs: forms::parse(&query), + }; + + let mut res = dispatch(&state, &req); + // Attach the session cookie if the handler minted one. + if let Some(sid) = res.headers.iter().find(|(k, _)| k == "X-New-Session").map(|(_, v)| v.clone()) { + res.headers.retain(|(k, _)| k != "X-New-Session"); + res.header("Set-Cookie", &format!("sid={sid}; Path=/; HttpOnly; SameSite=Strict")); + } + let mut builder = tiny_http::Response::from_data(std::mem::take(&mut res.body)) + .with_status_code(tiny_http::StatusCode(res.status)); + if let Ok(h) = tiny_http::Header::from_bytes(b"Content-Type", res.content_type.as_bytes()) { + builder = builder.with_header(h); + } + for (k, v) in &res.headers { + if let Ok(h) = tiny_http::Header::from_bytes(k.as_bytes(), v.as_bytes()) { + builder = builder.with_header(h); + } + } + request.respond(builder) +} + +/// Route table (§12). Everything is one flat match: there is no middleware +/// stack, just the session gate and then a path. +fn dispatch(state: &State, req: &Req) -> Res { + let seg: Vec<&str> = req.path.trim_matches('/').split('/').filter(|s| !s.is_empty()).collect(); + let is_get = req.method == "GET"; + + // Static assets and the login page are reachable without a session. + match (req.method.as_str(), seg.as_slice()) { + ("GET", ["static", name]) => return render::static_asset(name), + ("GET", ["login"]) => return routes::login_form(state, req), + ("POST", ["login"]) => return routes::login(state, req), + ("GET", ["healthz"]) => return Res::text(200, "ok\n".into()), + _ => {} + } + + // Session gate: mint a session for anonymous visitors so the CSRF token + // exists even before anyone logs in. + 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); + if let Some(mut res) = gated { + if new_session { + res.header("X-New-Session", &sid); + } + return finish(state, req, res, &sid, new_session); + } + + // CSRF: every state-changing request must carry the token for its session. + if !is_get { + let token = req.form_get("csrf").or_else(|| req.query_get("csrf")).unwrap_or_default(); + if !auth::csrf_ok(&sid, &token) { + return Res::text(403, "403 forbidden: CSRF token missing or wrong\n".into()); + } + } + + let mut res = routes::route(state, req, &seg); + if new_session { + res.header("X-New-Session", &sid); + } + finish(state, req, res, &sid, new_session) +} + +fn finish(_state: &State, _req: &Req, mut res: Res, _sid: &str, _new: bool) -> Res { + // A tiny security posture for a tool that serves a package index. + res.header("X-Content-Type-Options", "nosniff"); + res.header("Referrer-Policy", "same-origin"); + res +} + +/// Percent-decode a path segment. Enough for package names and ids, which is +/// all that ever needs it here. +fn percent_decode(s: &str) -> String { + let bytes = s.as_bytes(); + let mut out: Vec<u8> = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'%' && i + 2 < bytes.len() { + if let Ok(v) = u8::from_str_radix(&s[i + 1..i + 3], 16) { + out.push(v); + i += 3; + continue; + } + } + out.push(bytes[i]); + i += 1; + } + String::from_utf8_lossy(&out).into_owned() +} |
