diff options
| author | aur-build <aur-build@localhost> | 2026-11-18 18:41:27 +0000 |
|---|---|---|
| committer | aur-build <aur-build@localhost> | 2026-11-18 18:41:27 +0000 |
| commit | 76a214ed4d82d8937a3ec38c27d4d59304b8fac3 (patch) | |
| tree | 4a81e60b8f40fb3e9838c8e7f5ab7c361049dbeb /src/http/routes/mod.rs | |
| parent | 1abce8ba992353bca3d7b64b2633a15136e9303b (diff) | |
| download | aur-build-76a214ed4d82d8937a3ec38c27d4d59304b8fac3.tar.gz aur-build-76a214ed4d82d8937a3ec38c27d4d59304b8fac3.zip | |
http: routes split by direction of travel
n-4. `routes.rs` was 1,065 lines with the routing table, twenty-odd page
renderers, every mutating POST, and the size/date formatting helpers in one
file, so finding where a form landed meant scrolling past everything that did
not touch it.
It is a module now: `routes/mod.rs` keeps the gate, the login handlers, the
routing table and the helpers two files share (207 lines); `routes/pages.rs`
holds the read side, which only ever goes through `db.read`; `routes/mutations.rs`
holds the write side, which is where the audit writes and the flash messages
live. The split is by *read versus write*, which is the distinction the crate
actually cares about — the read path uses the thread-local read-only connection
and must never reach the writer — so the file boundary now matches the invariant
rather than being an arbitrary line count.
Behaviour is unchanged: the handlers are the same functions, re-exported into
`routes` so the routing table still reads as one flat list of endpoints.
Diffstat (limited to 'src/http/routes/mod.rs')
| -rw-r--r-- | src/http/routes/mod.rs | 207 |
1 files changed, 207 insertions, 0 deletions
diff --git a/src/http/routes/mod.rs b/src/http/routes/mod.rs new file mode 100644 index 0000000..e78cc74 --- /dev/null +++ b/src/http/routes/mod.rs @@ -0,0 +1,207 @@ +//! Route handlers (§12). +//! +//! Every handler reads through `db.read` — the thread-local read-only +//! connection — and hands mutations to the writer actor. A slow client can +//! therefore never hold the write lock, which is the whole point of the split. + +use crate::db::{self, builds, model::*}; +use crate::review::candidates; +use crate::time; +use super::auth; +use super::render::*; +use super::{Req, Res, State}; + +mod mutations; +mod pages; + +// The handlers live in two files by direction of travel — reads in `pages`, +// writes in `mutations` — and are pulled back into scope here so the routing +// table below still reads as one flat list of endpoints (n-4). +pub(crate) use mutations::*; +pub(crate) use pages::*; + +pub fn gate(state: &State, req: &Req, sid: &str) -> Option<Res> { + if !auth::auth_required(&state.cfg) { + return None; + } + if auth::is_authenticated(sid) || req.path == "/login" { + return None; + } + Some(Res::redirect("/login")) +} + +pub fn login_form(state: &State, req: &Req) -> Res { + let page = Page::new("Sign in", csrf(state, req)); + page_to_res(Login { page, error: String::new() }, 200) +} + +/// 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 { + if let Some(sid) = req.cookie("sid") { + auth::drop_session(&sid); + } + let mut res = Res::redirect("/login"); + res.header("Set-Cookie", "sid=; Path=/; Max-Age=0"); + res +} + +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 = match auth::new_session() { + Some(sid) => sid, + None => return page_to_res(Login { page, error: "server: no entropy for a session".into() }, 500), + }; + auth::authenticate(&sid); + let mut res = Res::redirect("/"); + // `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) + } +} + +pub fn route(state: &State, req: &Req, seg: &[&str]) -> Res { + match (req.method.as_str(), seg) { + ("GET", []) => dashboard(state, req), + ("GET", ["reviews"]) => reviews(state, req), + ("GET", ["reviews", id]) => review_detail(state, req, id), + ("POST", ["reviews", id, "approve"]) => review_approve(state, req, id), + ("POST", ["reviews", id, "reject"]) => review_reject(state, req, id), + ("POST", ["reviews", "bulk"]) => reviews_bulk(state, req), + ("POST", ["logout"]) => logout(req), + ("GET", ["subscriptions"]) => subscriptions(state, req), + ("POST", ["subscriptions", "add"]) => sub_add(state, req), + ("POST", ["subscriptions", "pause"]) => sub_pause(state, req), + ("POST", ["subscriptions", "remove"]) => sub_remove(state, req), + ("GET", ["attention"]) => attention(state, req), + ("POST", ["attention", "ack"]) => notice_ack(state, req), + ("GET", ["packages"]) => packages(state, req), + ("GET", ["packages", name]) => package_detail(state, req, name), + ("POST", ["packages", name, "rebuild"]) => package_rebuild(state, req, name), + ("POST", ["packages", name, "withdraw"]) => package_withdraw(state, req, name), + ("GET", ["builds"]) => builds_page(state, req), + ("GET", ["builds", id]) => build_detail(state, req, id), + ("GET", ["builds", id, "log.txt"]) => build_log(state, id), + ("GET", ["builds", id, "log.stream"]) => build_log_stream(state, req, id), + ("POST", ["builds", id, "cancel"]) => build_cancel(state, req, id), + ("POST", ["builds", id, "requeue"]) => build_retry(state, req, id), + ("GET", ["audit"]) => audit(state, req), + ("GET", ["settings"]) => settings(state, req), + _ => not_found(state, req), + } +} + +fn not_found(state: &State, req: &Req) -> Res { + let page = chrome(state, req, "Not found", "nav_packages"); + page_to_res( + ErrorPage { + page, + status: "404".into(), + message: "no such page".into(), + detail: String::new(), + }, + 404, + ) +} + +/// The shared chrome: counts for the nav badges and the active-tab marker. +fn chrome(state: &State, req: &Req, title: &str, active: &str) -> Page { + let db = &state.db; + let mut page = Page::new(title, csrf(state, req)); + page.pending = candidates::pending_candidates(db).map(|v| v.len() as i64).unwrap_or(0); + page.running = builds::in_flight(db).map(|v| v as i64).unwrap_or(0) + + builds::queue_depth(db).map(|v| v as i64).unwrap_or(0); + page.attention = db::list_notices(db, false).map(|v| v.len() as i64).unwrap_or(0) + + builds::blocked_builds(db).map(|v| v.len() as i64).unwrap_or(0); + page.nav_reviews = if active == "nav_reviews" { "on" } else { "" }; + page.nav_builds = if active == "nav_builds" { "on" } else { "" }; + page.nav_attention = if active == "nav_attention" { "on" } else { "" }; + page.nav_packages = if active == "nav_packages" { "on" } else { "" }; + page.nav_subscriptions = if active == "nav_subscriptions" { "on" } else { "" }; + page.nav_audit = if active == "nav_audit" { "on" } else { "" }; + page.nav_settings = if active == "nav_settings" { "on" } else { "" }; + page.gated = auth::auth_required(&state.cfg); + page +} + +fn csrf(_state: &State, req: &Req) -> String { + req.cookie("sid").map(|s| auth::csrf_token(&s)).unwrap_or_default() +} + +/// A byte count a human can read at a glance. +fn human_size(bytes: i64) -> String { + const UNITS: [&str; 4] = ["B", "KiB", "MiB", "GiB"]; + let mut v = bytes as f64; + let mut i = 0; + while v >= 1024.0 && i < UNITS.len() - 1 { + v /= 1024.0; + i += 1; + } + if i == 0 { + format!("{bytes} {}", UNITS[0]) + } else { + format!("{v:.1} {}", UNITS[i]) + } +} + +fn short(id: &str) -> String { + id.chars().take(10).collect() +} + +fn age(detected_at: &str) -> String { + let now = time::now(); + format!("{detected_at} → {now}") +} + +/// 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" + } +} + +fn flash_sub(state: &State, req: &Req, msg: &str, err: bool) -> Res { + let page = chrome(state, req, "Subscriptions", "nav_subscriptions").flash(msg.into(), err); + let pending = candidates::pending_candidates(&state.db).unwrap_or_default(); + let rows = db::list_subscriptions(&state.db) + .unwrap_or_default() + .into_iter() + .map(|s| SubRow { + pending: pending.iter().filter(|c| c.pkgbase == s.pkgbase).count() as i64, + name: s.pkgbase.clone(), + state: s.state.to_string(), + maintainer: s.maintainer.unwrap_or_else(|| "unknown".into()), + last_checked: s.last_checked_at.unwrap_or_else(|| "never".into()), + next_check: s.next_check_at.unwrap_or_else(|| "soon".into()), + last_error: s.last_error.clone().unwrap_or_default(), + has_error: s.last_error.is_some(), + pause_label: if s.state == SubscriptionState::Paused { "resume" } else { "pause" }, + }) + .collect(); + page_to_res(Subscriptions { page, rows }, 200) +} + +// ------------------------------------------------------------ rendering -- + +fn page_to_res<T: askama::Template>(t: T, status: u16) -> Res { + match askama::Template::render(&t) { + Ok(body) => Res::html(status, body), + Err(e) => Res::text(500, format!("template error: {e}")), + } +} |
