From a6b652985f40cf022d6c522415c36fad13bc663d Mon Sep 17 00:00:00 2001 From: aur-build Date: Wed, 18 Nov 2026 08:06:39 +0000 Subject: =?UTF-8?q?http:=20the=20review=20surface=20=E2=80=94=20server-ren?= =?UTF-8?q?dered,=20no=20JavaScript=20required=20(=C2=A712,=20=C2=A713)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit tiny_http, thread-per-connection, askama templates. Every §13 surface is server-rendered HTML that works with scripts switched off: Inbox, review detail with the full panel set, Builds, Attention, Index, Subscriptions, Ops/audit, Settings. The parts that are easy to get wrong: - Handlers read through thread-local READ-ONLY connections. They cannot take the write lock even by accident, so a slow page render never blocks the build pipeline's writer. tests/http.rs asserts this by trying to write through a read connection and requiring failure. - Every POST requires a CSRF token derived from the session id. Logout drops the session, which invalidates every form still open in a browser. - Approve carries identity_hash AND diff_digest (§7.1a). If either has moved, the approval is refused with 409 and the page re-renders the review AS IT IS NOW — never a silent retarget onto the newer state. - Bulk approve refuses high-risk items unless each one is individually confirmed by id. Bulk is per-item, never 'approve everything forever'. - Reject requires a note; it is re-openable, not a deletion. - Optional password gate; anonymous visitors are redirected to /login. Also: the index page states the pacman conf snippet including 'SigLevel = Required DatabaseOptional', because a repo consumers ignore the signature is a repo that gets MITM'd. --- src/http/auth.rs | 102 ++++++ src/http/forms.rs | 46 +++ src/http/mod.rs | 228 +++++++++++++ src/http/render.rs | 373 ++++++++++++++++++++ src/http/routes.rs | 909 +++++++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 1 + src/main.rs | 36 ++ src/watch/mod.rs | 1 + src/watch/staleness.rs | 125 +++++++ 9 files changed, 1821 insertions(+) create mode 100644 src/http/auth.rs create mode 100644 src/http/forms.rs create mode 100644 src/http/mod.rs create mode 100644 src/http/render.rs create mode 100644 src/http/routes.rs create mode 100644 src/watch/staleness.rs (limited to 'src') diff --git a/src/http/auth.rs b/src/http/auth.rs new file mode 100644 index 0000000..9186f0e --- /dev/null +++ b/src/http/auth.rs @@ -0,0 +1,102 @@ +//! Session and CSRF (§12: "form posts are plain `
` with a +//! CSRF token"). +//! +//! One operator, one shared credential, no user table (§14). A session is an +//! 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. + +use std::collections::HashSet; +use std::sync::Mutex; +use std::sync::OnceLock; + +use crate::hash; + +static SESSIONS: OnceLock>> = OnceLock::new(); + +fn sessions() -> &'static Mutex> { + SESSIONS.get_or_init(|| Mutex::new(HashSet::new())) +} + +/// Random hex token from the system RNG (`/dev/urandom` through our hash). +fn random_hex() -> String { + let mut buf = [0u8; 32]; + if let Ok(mut f) = std::fs::File::open("/dev/urandom") { + use std::io::Read; + let _ = f.read_exact(&mut buf); + } + // Mix in a counter and the clock so two calls in the same instant differ. + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0); + let salt = format!("{:?}", (buf, nanos, std::process::id(), counter())); + hash::hex(salt.as_bytes()) +} + +fn counter() -> u64 { + static C: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + C.fetch_add(1, std::sync::atomic::Ordering::Relaxed) +} + +pub fn new_session() -> String { + let sid = random_hex(); + if let Ok(mut s) = sessions().lock() { + s.insert(sid.clone()); + } + sid +} + +pub fn is_valid_session(sid: &str) -> bool { + sessions().lock().map(|s| s.contains(sid)).unwrap_or(false) +} + +pub fn drop_session(sid: &str) { + if let Ok(mut s) = sessions().lock() { + s.remove(sid); + } +} + +/// The CSRF token for a session. Derived rather than stored: it cannot drift +/// out of sync with the session, and it is cheap to recompute per request. +pub fn csrf_token(sid: &str) -> String { + hash::hex(format!("csrf|{sid}").as_bytes())[..32].to_string() +} + +pub fn csrf_ok(sid: &str, token: &str) -> bool { + !token.is_empty() && is_valid_session(sid) && constant_time_eq(&csrf_token(sid), token) +} + +fn constant_time_eq(a: &str, b: &str) -> bool { + let (a, b) = (a.as_bytes(), b.as_bytes()); + if a.len() != b.len() { + return false; + } + let mut diff = 0u8; + for (x, y) in a.iter().zip(b.iter()) { + diff |= x ^ y; + } + diff == 0 +} + +/// Parse a `Cookie:` header value. +pub fn parse_cookies(header: &str) -> Vec<(String, String)> { + header + .split(';') + .filter_map(|p| { + let p = p.trim(); + let (k, v) = p.split_once('=')?; + Some((k.trim().to_string(), v.trim().to_string())) + }) + .collect() +} + +/// Check the shared password. Empty password means the UI is open, which is the +// default on loopback; the CSRF gate still applies. +pub fn password_ok(cfg: &crate::config::Config, given: &str) -> bool { + cfg.password.is_empty() || constant_time_eq(&cfg.password, given) +} + +pub fn auth_required(cfg: &crate::config::Config) -> bool { + !cfg.password.is_empty() +} diff --git a/src/http/forms.rs b/src/http/forms.rs new file mode 100644 index 0000000..6e36e38 --- /dev/null +++ b/src/http/forms.rs @@ -0,0 +1,46 @@ +//! `application/x-www-form-urlencoded` parsing and HTML escaping. +//! +//! Deliberately tiny: the only forms in this application are ours, so we need +//! decoding for names, versions and hashes — not a general MIME parser. + +/// Percent-decode one token (`+` means space in a form body). +pub fn decode(s: &str) -> String { + let bytes = s.as_bytes(); + let mut out: Vec = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + match bytes[i] { + b'+' => { + out.push(b' '); + i += 1; + } + b'%' if i + 2 < bytes.len() => { + match u8::from_str_radix(&s[i + 1..i + 3], 16) { + Ok(v) => { + out.push(v); + i += 3; + } + Err(_) => { + out.push(bytes[i]); + i += 1; + } + } + } + c => { + out.push(c); + i += 1; + } + } + } + String::from_utf8_lossy(&out).into_owned() +} + +pub fn parse(body: &str) -> Vec<(String, String)> { + body.split('&') + .filter(|p| !p.is_empty()) + .map(|p| match p.split_once('=') { + Some((k, v)) => (decode(k), decode(v)), + None => (decode(p), String::new()), + }) + .collect() +} 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 ``, 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 { + self.form().into_iter().find(|(k, _)| k == key).map(|(_, v)| v) + } + pub fn query_get(&self, key: &str) -> Option { + self.query_pairs.iter().find(|(k, _)| k == key).map(|(_, v)| v.clone()) + } + pub fn cookie(&self, name: &str) -> Option { + 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, + 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 { + 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, 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 = 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() +} diff --git a/src/http/render.rs b/src/http/render.rs new file mode 100644 index 0000000..2fad5c8 --- /dev/null +++ b/src/http/render.rs @@ -0,0 +1,373 @@ +//! Template contexts (§12, §13). +//! +//! Askama compiles every template into Rust at build time, so a missing field +//! is a compile error rather than a blank page at 2am. Contexts are built from +//! live DB state; nothing here writes. + +use askama::Template; + +/// Everything the shared chrome needs. Embedded in each page context because +/// askama inheritance passes the whole struct down. +#[derive(Debug, Clone)] +pub struct Page { + pub title: String, + pub flash: String, + pub has_flash: bool, + pub flash_err: bool, + pub csrf: String, + pub pending: i64, + pub running: i64, + pub attention: i64, + pub nav_reviews: &'static str, + pub nav_builds: &'static str, + pub nav_attention: &'static str, + pub nav_packages: &'static str, + pub nav_subscriptions: &'static str, + pub nav_audit: &'static str, + pub nav_settings: &'static str, + /// True when a password gate is configured, so the chrome offers a logout. + pub gated: bool, +} + +impl Page { + pub fn new(title: &str, csrf: String) -> Self { + Self { + title: title.into(), + flash: String::new(), + has_flash: false, + flash_err: false, + csrf, + pending: 0, + running: 0, + attention: 0, + nav_reviews: "", + nav_builds: "", + nav_attention: "", + nav_packages: "", + nav_subscriptions: "", + nav_audit: "", + nav_settings: "", + gated: false, + } + } + pub fn flash(mut self, msg: String, err: bool) -> Self { + self.flash = msg; + self.has_flash = true; + self.flash_err = err; + self + } +} + +#[derive(Template)] +#[template(path = "login.html")] +pub struct Login { + pub page: Page, + pub error: String, +} + +#[derive(Template)] +#[template(path = "error.html")] +pub struct ErrorPage { + pub page: Page, + pub status: String, + pub message: String, + pub detail: String, +} + +#[derive(Template)] +#[template(path = "dashboard.html")] +pub struct Dashboard { + pub page: Page, + pub subscriptions: i64, + pub index_count: i64, + pub pending_reviews: i64, + pub running_builds: i64, + pub attention: i64, + pub publishes: Vec, +} + +#[derive(Debug, Clone)] +pub struct PublishRow { + pub name: String, + pub version: String, + pub published_at: String, + pub aur_commit: String, + pub aur_commit_short: String, +} + +#[derive(Template)] +#[template(path = "reviews.html")] +pub struct ReviewsPage { + pub page: Page, + pub rows: Vec, +} + +#[derive(Debug, Clone)] +pub struct ReviewRow { + pub id: i64, + pub pkgbase: String, + pub version: String, + pub kind: String, + pub risk: String, + pub signals: Vec, + pub age: String, + pub revision: i64, +} + +#[derive(Template)] +#[template(path = "review.html")] +pub struct ReviewDetail { + pub page: Page, + pub c: ReviewHead, + pub base_version: String, + pub has_base: bool, + pub panels: Vec, + /// First introductions show the whole recipe instead of a diff (§7.1b). + pub recipe: String, + pub srcinfo: String, + pub has_srcinfo: bool, + pub sources_resolved: String, + pub deps_resolved: String, +} + +#[derive(Debug, Clone)] +pub struct ReviewHead { + pub id: i64, + pub pkgbase: String, + pub version: String, + pub kind: String, + pub is_first: bool, + pub risk: String, + pub signals: Vec, + pub missing_deps: Vec, + pub revision: i64, + pub aur_commit: String, + pub aur_commit_short: String, + pub identity_hash: String, + pub diff_digest: String, +} + +#[derive(Debug, Clone)] +pub struct Panel { + pub title: String, + pub body: String, + pub empty: bool, + pub empty_note: String, +} + +impl Panel { + pub fn new(title: &str, body: String) -> Self { + Self { + title: title.into(), + empty: body.trim().is_empty(), + empty_note: "no change".into(), + body, + } + } +} + +#[derive(Template)] +#[template(path = "subscriptions.html")] +pub struct Subscriptions { + pub page: Page, + pub rows: Vec, +} + +#[derive(Debug, Clone)] +pub struct SubRow { + pub name: String, + pub state: String, + pub maintainer: String, + pub last_checked: String, + pub next_check: String, + pub last_error: String, + pub has_error: bool, + pub pending: i64, + pub pause_label: &'static str, +} + +#[derive(Template)] +#[template(path = "attention.html")] +pub struct Attention { + pub page: Page, + pub empty: bool, + pub notices: Vec, + pub outdated: Vec, + pub missing: Vec, + pub downgrades: Vec, + pub blocked: Vec, +} + +#[derive(Debug, Clone)] +pub struct NoticeRow { + pub id: i64, + pub pkgbase: String, + pub kind: String, + pub severity: String, + pub detail: String, + pub created_at: String, +} + +#[derive(Debug, Clone)] +pub struct StaleRow { + pub pkgbase: String, + pub built_with: String, + pub now: String, +} + +#[derive(Debug, Clone)] +pub struct BlockedRow { + pub id: String, + pub id_short: String, + pub pkgbase: String, + pub blocked_on: Vec, +} + +#[derive(Template)] +#[template(path = "packages.html")] +pub struct Packages { + pub page: Page, + pub repo: String, + pub rows: Vec, + pub snippet: String, +} + +#[derive(Debug, Clone)] +pub struct IndexRow { + pub name: String, + pub version: String, + pub arch: String, + pub size: String, + pub published_at: String, +} + +#[derive(Template)] +#[template(path = "package.html")] +pub struct PackageDetail { + pub page: Page, + pub name: String, + pub summary: String, + pub can_withdraw: bool, + pub stale: Vec, + pub deps_in: Vec, + pub deps_out: Vec, + pub timeline: Vec, + pub builds: Vec, +} + +#[derive(Debug, Clone)] +pub struct TimelineRow { + pub version: String, + pub state: String, + pub aur_commit: String, + pub aur_commit_short: String, + pub published_at: String, + pub approver: String, +} + +#[derive(Template)] +#[template(path = "builds.html")] +pub struct Builds { + pub page: Page, + pub rows: Vec, + pub recent: Vec, +} + +#[derive(Debug, Clone)] +pub struct BuildLite { + pub id: String, + pub id_short: String, + pub kind: String, + pub state: String, + pub step: String, +} + +#[derive(Debug, Clone)] +pub struct BuildRow { + pub id: String, + pub id_short: String, + pub pkgbase: String, + pub version: String, + pub kind: String, + pub state: String, + pub step: String, + pub lease: String, + pub cancel: bool, + pub error: String, +} + +#[derive(Template)] +#[template(path = "build.html")] +pub struct BuildDetail { + pub page: Page, + pub id: String, + pub id_short: String, + pub pkgbase: String, + pub version: String, + pub kind: String, + pub state: String, + pub error: String, + pub blocked_on: Vec, + pub steps: Vec, + pub log: String, + pub log_lines: usize, + pub log_truncated: bool, +} + +#[derive(Debug, Clone)] +pub struct StepRow { + pub step: String, + pub status: String, + pub attempt: i64, + pub digest: String, + pub cls: String, + pub error: String, +} + +#[derive(Template)] +#[template(path = "audit.html")] +pub struct Audit { + pub page: Page, + pub rows: Vec, +} + +#[derive(Debug, Clone)] +pub struct AuditRow { + pub at: String, + pub actor_kind: String, + pub actor: String, + pub action: String, + pub entity: String, + pub entity_id: String, + pub detail: String, +} + +#[derive(Template)] +#[template(path = "settings.html")] +pub struct Settings { + pub page: Page, + pub rows: Vec, + pub repo: String, +} + +#[derive(Debug, Clone)] +pub struct SettingRow { + pub key: String, + pub value: String, +} + +/// Vendored static assets. htmx arrives in P3; until then this serves the +/// favicon and refuses everything else rather than walking the filesystem. +pub fn static_asset(name: &str) -> crate::http::Res { + use crate::http::Res; + match name { + "htmx.min.js" => Res::text(404, "htmx is vendored in P3\n".into()), + "app.css" => { + let s = std::include_str!("../../static/app.css"); + let mut r = Res::text(200, s.to_string()); + r.content_type = "text/css".into(); + r + } + _ => Res::text(404, "not found\n".into()), + } +} diff --git a/src/http/routes.rs b/src/http/routes.rs new file mode 100644 index 0000000..784024d --- /dev/null +++ b/src/http/routes.rs @@ -0,0 +1,909 @@ +//! 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::{approve as ap, candidates, diff, risk}; +use crate::{pipeline, time}; + +use super::auth; +use super::render::*; +use super::{Req, Res, State}; + +/// Redirect an unauthenticated visitor to the login page. +pub fn gate(state: &State, req: &Req) -> Option { + if !auth::auth_required(&state.cfg) { + return None; + } + let signed_in = req.cookie("auth").as_deref() == Some("1"); + if signed_in || 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 both cookies. 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", "auth=; Path=/; Max-Age=0"); + 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) { + let mut res = Res::redirect("/"); + res.header("Set-Cookie", "auth=1; Path=/; HttpOnly; SameSite=Strict"); + 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), + ("POST", ["builds", id, "cancel"]) => build_cancel(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}") +} + +// ------------------------------------------------------------- dashboard -- + +fn dashboard(state: &State, req: &Req) -> Res { + let db = &state.db; + let page = chrome(state, req, "Dashboard", ""); + let publishes: Vec = db::all_published_releases(db) + .unwrap_or_default() + .into_iter() + .take(15) + .filter_map(|r| { + let pb = db::get_pkgbase_by_id(db, r.pkgbase_id).ok().flatten()?; + Some(PublishRow { + name: pb.name, + version: r.version(), + published_at: r.published_at.unwrap_or_else(|| r.state.clone()), + aur_commit: r.aur_commit.clone(), + aur_commit_short: short(&r.aur_commit), + }) + }) + .collect(); + page_to_res( + Dashboard { + page, + subscriptions: db::list_subscriptions(db).map(|v| v.len() as i64).unwrap_or(0), + index_count: db::index_packages(db).map(|v| v.len() as i64).unwrap_or(0), + pending_reviews: candidates::pending_candidates(db).map(|v| v.len() as i64).unwrap_or(0), + running_builds: builds::in_flight(db).map(|v| v as i64).unwrap_or(0), + attention: db::list_notices(db, false).map(|v| v.len() as i64).unwrap_or(0), + publishes, + }, + 200, + ) +} + +// ---------------------------------------------------------------- inbox -- + +fn review_rows(state: &State) -> Vec { + let db = &state.db; + let mut rows: Vec = candidates::pending_candidates(db) + .unwrap_or_default() + .into_iter() + .map(|c| ReviewRow { + id: c.id, + pkgbase: c.pkgbase.clone(), + version: full_version(&c), + kind: c.kind.clone(), + risk: c.risk_level.clone(), + signals: c.risk_signals(), + age: age(&c.detected_at), + revision: c.revision, + }) + .collect(); + // Risk first, then oldest — the scarcest resource gets the loudest rows. + let rank = |r: &str| match r { + risk::level::HIGH => 0, + risk::level::MEDIUM => 1, + _ => 2, + }; + rows.sort_by_key(|r| (rank(&r.risk), r.age.clone(), r.id)); + let _ = state; + rows +} + +fn reviews(state: &State, req: &Req) -> Res { + let page = chrome(state, req, "Reviews", "nav_reviews"); + page_to_res(ReviewsPage { page, rows: review_rows(state) }, 200) +} + +fn full_version(c: &CandidateRow) -> String { + crate::pkgver::full_version(&c.epoch, &c.pkgver, &c.pkgrel) +} + +fn review_detail(state: &State, req: &Req, id: &str) -> Res { + let db = &state.db; + let Some(id) = id.parse::().ok() else { + return not_found(state, req); + }; + let Some(c) = candidates::candidate_by_id(db, id).unwrap_or(None) else { + return not_found(state, req); + }; + // Opening a review freezes it: a later detection now opens a fresh review + // instead of silently changing what is on screen (§7.1). + let _ = candidates::mark_viewed(db, id); + let page = chrome(state, req, &format!("Review {}", c.pkgbase), "nav_reviews"); + let (head, panels, recipe, srcinfo, sources_resolved, deps_resolved) = review_body(state, &c); + let base = panels_base(&c); + page_to_res( + ReviewDetail { + page, + c: head, + base_version: base.0, + has_base: base.1, + panels, + recipe, + has_srcinfo: !srcinfo.is_empty(), + srcinfo, + sources_resolved, + deps_resolved, + }, + 200, + ) +} + +fn panels_base(c: &CandidateRow) -> (String, bool) { + match c.base_release_id { + Some(_) => ("previous accepted release".into(), true), + None => ("nothing accepted yet".into(), false), + } +} + +/// Build the review body: the panel set plus the first-introduction material. +fn review_body( + state: &State, + c: &CandidateRow, +) -> (ReviewHead, Vec, String, String, String, String) { + let db = &state.db; + let base = match c.base_release_id { + Some(id) => db::release_by_id(db, id).unwrap_or(None), + None => None, + }; + let panels = diff::panels(&state.cfg, db, c, base.as_ref()).unwrap_or_default(); + let rendered = diff::render_text(&panels); + let _ = rendered; + let snapshot = db::snapshot_by_id(db, c.snapshot_id).unwrap_or(None); + let recipe_json = snapshot.as_ref().map(|s| s.srcinfo_json.clone()).unwrap_or_default(); + let parsed: Option = serde_json::from_str(&recipe_json).ok(); + let is_first = c.kind == candidate_kind::FIRST_INTRODUCTION; + + let head = ReviewHead { + id: c.id, + pkgbase: c.pkgbase.clone(), + version: full_version(c), + kind: c.kind.clone(), + is_first, + risk: c.risk_level.clone(), + signals: c.risk_signals(), + missing_deps: c.missing_deps(), + revision: c.revision, + aur_commit: snapshot.as_ref().map(|s| s.aur_commit.clone()).unwrap_or_default(), + aur_commit_short: snapshot + .as_ref() + .map(|s| short(&s.aur_commit)) + .unwrap_or_default(), + identity_hash: c.identity_hash.clone(), + diff_digest: c.diff_digest.clone(), + }; + let shown: Vec = panels + .iter() + .map(|p| Panel::new(p.title, p.body.clone())) + .collect(); + let (recipe_text, srcinfo) = match &parsed { + Some(r) => (r.pkgbuild.clone(), r.srcinfo.clone().unwrap_or_default()), + None => (String::new(), String::new()), + }; + let sources_resolved = serde_json::to_string_pretty( + &serde_json::from_str::(&c.source_digests_json) + .unwrap_or_else(|_| serde_json::json!([])), + ) + .unwrap_or_default(); + let deps_resolved = parsed + .as_ref() + .map(|r| { + format!( + "depends: {}\nmakedepends: {}\ncheckdepends: {}\noptdepends: {}", + r.depends.join(", "), + r.makedepends.join(", "), + r.checkdepends.join(", "), + r.optdepends.join(", ") + ) + }) + .unwrap_or_default(); + (head, shown, recipe_text, srcinfo, sources_resolved, deps_resolved) +} + +// -------------------------------------------------------------- approve -- + +fn review_approve(state: &State, req: &Req, id: &str) -> Res { + let db = &state.db; + let Some(id) = id.parse::().ok() else { + return not_found(state, req); + }; + let Some(c) = candidates::candidate_by_id(db, id).unwrap_or(None) else { + return not_found(state, req); + }; + 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()) { + Ok(a) => { + let mut page = chrome(state, req, "Reviews", "nav_reviews"); + page.flash = format!("approved {} (approval {}); build queued", c.pkgbase, a.id); + page.has_flash = true; + match pipeline::enqueue_for_candidate(&state.cfg, db, &c) { + Ok(bid) => { + page.flash = format!("approved {}; build {} queued", c.pkgbase, short(&bid)); + page.has_flash = true; + } + Err(e) => { + page.flash = format!("approved, but the build could not be queued: {e}"); + page.has_flash = true; + page.flash_err = true; + } + } + page_to_res(ReviewsPage { page, rows: review_rows(state) }, 200) + } + Err(stale) => { + // §7.1a: refuse, re-render what it is now, and say why. Never + // silently retarget the approval onto the newer state. + let mut page = chrome(state, req, "Review changed", "nav_reviews"); + page.flash = format!("refused: {stale}"); + page.has_flash = true; + page.flash_err = true; + // Show the review as it stands NOW — the frozen one the form came + // from may have collapsed or been superseded while it was open. + let current = candidates::pending_candidates(db) + .unwrap_or_default() + .into_iter() + .find(|p| p.pkgbase_id == c.pkgbase_id) + .unwrap_or_else(|| c.clone()); + let (head, panels, recipe, srcinfo, sources, deps) = review_body(state, ¤t); + let base = panels_base(¤t); + page_to_res( + ReviewDetail { + page, + c: head, + base_version: base.0, + has_base: base.1, + panels, + recipe, + has_srcinfo: !srcinfo.is_empty(), + srcinfo, + sources_resolved: sources, + deps_resolved: deps, + }, + 409, + ) + } + } +} + +fn review_reject(state: &State, req: &Req, id: &str) -> Res { + let db = &state.db; + let Some(id) = id.parse::().ok() else { + return not_found(state, req); + }; + let Some(note) = req.form_get("note").filter(|s| !s.trim().is_empty()) else { + let mut page = chrome(state, req, "Review", "nav_reviews"); + page.flash = "a rejection needs a reason: it is the only record of why".into(); + page.has_flash = true; + page.flash_err = true; + return page_to_res(ReviewsPage { page, rows: review_rows(state) }, 400); + }; + match ap::reject(db, actor(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"); + page.has_flash = true; + page_to_res(ReviewsPage { page, rows: review_rows(state) }, 200) + } + Err(e) => { + let mut page = chrome(state, req, "Reviews", "nav_reviews"); + page.flash = format!("could not reject: {e}"); + page.has_flash = true; + page.flash_err = true; + page_to_res(ReviewsPage { page, rows: review_rows(state) }, 409) + } + } +} + +/// Bulk approve/reject (§7.4): per-item, never "approve everything forever", +/// and high-risk items are refused unless each was confirmed individually. +fn reviews_bulk(state: &State, req: &Req) -> Res { + let db = &state.db; + let form = req.form(); + let ids: Vec = form + .iter() + .filter(|(k, _)| k == "ids") + .filter_map(|(_, v)| v.parse().ok()) + .collect(); + let decision = form + .iter() + .find(|(k, _)| k == "decision") + .map(|(_, v)| v.clone()) + .unwrap_or_default(); + let confirmed: std::collections::BTreeSet = form + .iter() + .filter(|(k, _)| k == "confirm") + .filter_map(|(_, v)| v.parse().ok()) + .collect(); + if ids.is_empty() { + let mut page = chrome(state, req, "Reviews", "nav_reviews"); + page.flash = "nothing selected".into(); + page.has_flash = true; + page.flash_err = true; + return page_to_res(ReviewsPage { page, rows: review_rows(state) }, 400); + } + let mut done = Vec::new(); + let mut refused = Vec::new(); + for id in ids { + let Some(c) = candidates::candidate_by_id(db, id).unwrap_or(None) else { continue }; + if decision == "approve" && c.risk_level == risk::level::HIGH && !confirmed.contains(&id) { + refused.push(format!("{} (high risk: confirm it individually)", c.pkgbase)); + continue; + } + let res = if decision == "approve" { + ap::approve(db, actor(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()) + }; + match res { + Ok(()) => { + if decision == "approve" { + let _ = pipeline::enqueue_for_candidate(&state.cfg, db, &c); + } + done.push(c.pkgbase); + } + Err(e) => refused.push(format!("{}: {e}", c.pkgbase)), + } + } + let mut page = chrome(state, req, "Reviews", "nav_reviews"); + page.flash = format!( + "{}: {}{}", + if decision == "approve" { "approved" } else { "rejected" }, + done.join(", "), + if refused.is_empty() { String::new() } else { format!(" — refused: {}", refused.join("; ")) } + ); + page.has_flash = true; + page.flash_err = !refused.is_empty(); + page_to_res(ReviewsPage { page, rows: review_rows(state) }, 200) +} + +fn actor(req: &Req) -> &str { + if req.cookie("auth").is_some() { + "web" + } else { + "web-anon" + } +} + +// -------------------------------------------------------- subscriptions -- + +fn subscriptions(state: &State, req: &Req) -> Res { + let db = &state.db; + let page = chrome(state, req, "Subscriptions", "nav_subscriptions"); + let pending = candidates::pending_candidates(db).unwrap_or_default(); + let rows = db::list_subscriptions(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.clone(), + 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 == subscription_state::PAUSED { "resume" } else { "pause" }, + }) + .collect(); + page_to_res(Subscriptions { page, rows }, 200) +} + +fn sub_add(state: &State, req: &Req) -> Res { + let db = &state.db; + let Some(name) = req.form_get("pkgbase").map(|s| s.trim().to_string()).filter(|s| !s.is_empty()) else { + return flash_sub(state, req, "give a pkgbase name", true); + }; + let rid = db::repo_id(db).unwrap_or(1); + let url = format!("https://aur.archlinux.org/{name}.git"); + match db::subscribe(&db.writer, rid, &name, &url) { + Ok(_) => { + let _ = crate::watch::detect::check_pkgbase(&state.cfg, db, &name); + flash_sub(state, req, &format!("subscribed {name} and ran a first check"), false) + } + Err(e) => flash_sub(state, req, &format!("could not subscribe: {e}"), true), + } +} + +fn sub_pause(state: &State, req: &Req) -> Res { + let db = &state.db; + let name = req.form_get("pkgbase").unwrap_or_default(); + let cur = db::get_subscription(db, &name).ok().flatten().map(|s| s.state).unwrap_or_default(); + let next = if cur == subscription_state::PAUSED { subscription_state::ACTIVE } else { subscription_state::PAUSED }; + let _ = db::set_subscription_state(&db.writer, &name, next); + flash_sub(state, req, &format!("{name}: {next}"), false) +} + +fn sub_remove(state: &State, req: &Req) -> Res { + let db = &state.db; + let name = req.form_get("pkgbase").unwrap_or_default(); + let _ = db::set_subscription_state(&db.writer, &name, subscription_state::REMOVED); + flash_sub(state, req, &format!("{name}: removed"), false) +} + +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.clone(), + 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 == subscription_state::PAUSED { "resume" } else { "pause" }, + }) + .collect(); + page_to_res(Subscriptions { page, rows }, 200) +} + +// ------------------------------------------------------------ attention -- + +fn attention(state: &State, req: &Req) -> Res { + let db = &state.db; + let page = chrome(state, req, "Attention", "nav_attention"); + let notices = db::list_notices(db, false) + .unwrap_or_default() + .into_iter() + .map(|n| NoticeRow { + id: n.id, + pkgbase: n.pkgbase.clone(), + kind: n.kind.clone(), + severity: n.severity.clone(), + detail: n.detail_json.clone(), + created_at: n.created_at.clone(), + }) + .collect::>(); + let blocked: Vec = builds::blocked_builds(db) + .unwrap_or_default() + .into_iter() + .map(|(id, pkgbase, blocked_on)| BlockedRow { id_short: short(&id), id, pkgbase, blocked_on }) + .collect(); + // Staleness is computed on read (P4 fills the query in). + let stale = crate::watch::staleness::stale_rows(db).unwrap_or_default(); + let outdated: Vec = stale + .iter() + .filter(|s| s.kind == crate::watch::staleness::Kind::Outdated) + .cloned() + .map(|s| StaleRow { pkgbase: s.pkgbase, built_with: s.built_with, now: s.now }) + .collect(); + let missing: Vec = stale + .iter() + .filter(|s| s.kind == crate::watch::staleness::Kind::Missing) + .cloned() + .map(|s| StaleRow { pkgbase: s.pkgbase, built_with: s.built_with, now: s.now }) + .collect(); + let downgrades: Vec = Vec::new(); + let empty = notices.is_empty() && outdated.is_empty() && missing.is_empty() && blocked.is_empty(); + page_to_res( + Attention { page, empty, notices, outdated, missing, downgrades, blocked }, + 200, + ) +} + +fn notice_ack(state: &State, req: &Req) -> Res { + let id: i64 = req.form_get("id").and_then(|s| s.parse().ok()).unwrap_or(0); + let _ = db::acknowledge_notice(&state.db.writer, id); + // POST-redirect-GET: the notice vanishing from the list is its own + // confirmation, and a refresh can no longer re-POST. + let _ = req; + Res::redirect("/attention") +} + +// ------------------------------------------------------------- packages -- + +fn packages(state: &State, req: &Req) -> Res { + let db = &state.db; + let page = chrome(state, req, "Index", "nav_packages"); + let rows: Vec = db::index_packages(db) + .unwrap_or_default() + .into_iter() + .map(|p| IndexRow { + name: p.name.clone(), + version: p.version.clone(), + arch: p.arch.clone(), + size: p.size.map(human_size).unwrap_or_else(|| "—".into()), + published_at: p.published_at.clone().unwrap_or_else(|| "—".into()), + }) + .collect(); + let snippet = format!( + "[{}]\nServer = {}/$repo/os/$arch\nSigLevel = Required DatabaseOptional", + state.cfg.repo_name, state.cfg.base_url + ); + page_to_res(Packages { page, repo: state.cfg.repo_name.clone(), rows, snippet }, 200) +} + +fn package_detail(state: &State, req: &Req, name: &str) -> Res { + let db = &state.db; + let page = chrome(state, req, name, "nav_packages"); + let Some(pb) = db::get_pkgbase(db, name).unwrap_or(None) else { + return not_found(state, req); + }; + let releases = db::releases_for_pkgbase(db, pb.id, 20).unwrap_or_default(); + let accepted = db::accepted_release(db, name).unwrap_or(None); + let timeline: Vec = releases + .into_iter() + .map(|r| TimelineRow { + version: r.version(), + state: r.state.clone(), + aur_commit: r.aur_commit.clone(), + aur_commit_short: short(&r.aur_commit), + published_at: r.published_at.unwrap_or_else(|| "—".into()), + approver: r + .approval_id + .and_then(|aid| { + db.read(|c| { + use rusqlite::OptionalExtension; + c.query_row( + "SELECT COALESCE(note,'') FROM approval WHERE id=?1", + rusqlite::params![aid], + |r| r.get::<_, String>(0), + ) + .optional() + .map_err(Into::into) + }) + .ok() + .flatten() + }) + .filter(|s| !s.is_empty()) + .unwrap_or_else(|| "—".into()), + }) + .collect(); + let builds: Vec = db::builds_for_pkgbase(db, pb.id, 10) + .unwrap_or_default() + .into_iter() + .map(|b| BuildLite { + id_short: short(&b.id), + id: b.id, + kind: b.kind, + state: b.state, + step: b.current_step.unwrap_or_default(), + }) + .collect(); + let stale: Vec = crate::watch::staleness::stale_for(db, name) + .unwrap_or_default() + .into_iter() + .map(|s| format!("{} was built against {} but the index has {}", s.pkgbase, s.built_with, s.now)) + .collect(); + let summary = match &accepted { + Some(r) => format!("serving {} · approved from aur_commit {}", r.version(), short(&r.aur_commit)), + None => "nothing published yet".into(), + }; + page_to_res( + PackageDetail { + page, + name: name.to_string(), + summary, + can_withdraw: accepted.is_some(), + stale, + deps_in: Vec::new(), + deps_out: Vec::new(), + timeline, + builds, + }, + 200, + ) +} + +fn package_rebuild(state: &State, req: &Req, name: &str) -> Res { + match pipeline::enqueue_manual_rebuild(&state.cfg, &state.db, name) { + Ok(id) => { + let _ = id; + let mut page = chrome(state, req, "Builds", "nav_builds"); + page.flash = format!("queued a rebuild of the approved version of {name} (no new approval needed)"); + page.has_flash = true; + builds_with(state, req, page) + } + Err(e) => { + let mut page = chrome(state, req, "Index", "nav_packages"); + page.flash = format!("could not queue a rebuild: {e}"); + page.has_flash = true; + page.flash_err = true; + page_to_res(Packages { page, repo: state.cfg.repo_name.clone(), rows: vec![], snippet: String::new() }, 400) + } + } +} + +fn package_withdraw(state: &State, req: &Req, name: &str) -> Res { + match pipeline::publish::withdraw_package(&state.cfg, &state.db, name) { + Ok(()) => Res::redirect("/packages"), + Err(e) => { + let mut page = chrome(state, req, "Index", "nav_packages"); + page.flash = format!("withdrawal failed: {e}"); + page.has_flash = true; + page.flash_err = true; + page_to_res(Packages { page, repo: state.cfg.repo_name.clone(), rows: vec![], snippet: String::new() }, 500) + } + } +} + +// --------------------------------------------------------------- builds -- + +fn build_rows(state: &State) -> Vec { + builds::list( + &state.db, + &[build_state::QUEUED, build_state::RUNNING, build_state::LEASED, build_state::BLOCKED_MISSING_DEP], + 100, + ) + .unwrap_or_default() + .into_iter() + .map(|b| { + let pkgbase = db::get_pkgbase_by_id(&state.db, b.pkgbase_id) + .ok() + .flatten() + .map(|p| p.name) + .unwrap_or_default(); + BuildRow { + id_short: short(&b.id), + id: b.id, + pkgbase, + version: String::new(), + kind: b.kind, + state: b.state, + step: b.current_step.unwrap_or_default(), + lease: b.lease_expires_at.unwrap_or_else(|| "—".into()), + cancel: b.cancel_requested, + error: b.error.unwrap_or_default(), + } + }) + .collect() +} + +fn builds_page(state: &State, req: &Req) -> Res { + let page = chrome(state, req, "Builds", "nav_builds"); + builds_with(state, req, page) +} + +fn builds_with(state: &State, _req: &Req, page: Page) -> Res { + let recent: Vec = builds::list(&state.db, &[build_state::FAILED, build_state::SUCCEEDED], 10) + .unwrap_or_default() + .into_iter() + .map(|b| BuildRow { + id_short: short(&b.id), + id: b.id, + pkgbase: db::get_pkgbase_by_id(&state.db, b.pkgbase_id).ok().flatten().map(|p| p.name).unwrap_or_default(), + version: String::new(), + kind: b.kind, + state: b.state, + step: b.current_step.unwrap_or_default(), + lease: String::new(), + cancel: b.cancel_requested, + error: b.error.unwrap_or_default(), + }) + .collect(); + page_to_res(Builds { page, rows: build_rows(state), recent }, 200) +} + +fn build_detail(state: &State, req: &Req, id: &str) -> Res { + let db = &state.db; + let Some(b) = builds::get(db, id).unwrap_or(None) else { + return not_found(state, req); + }; + let page = chrome(state, req, "Build", "nav_builds"); + let steps: Vec = builds::steps(db, id) + .unwrap_or_default() + .into_iter() + .map(|s| { + let cls = if s.status == "failed" { "risk-high" } else { "mut" }.to_string(); + StepRow { + step: s.step, + status: s.status, + attempt: s.attempt, + digest: String::new(), + cls, + error: s.error.unwrap_or_default(), + } + }) + .collect(); + let log_path = state.cfg.build_log_path(id); + let all = std::fs::read_to_string(&log_path).unwrap_or_default(); + let lines: Vec<&str> = all.lines().collect(); + let tail = lines[lines.len().saturating_sub(200)..].join("\n"); + let blocked_on: Vec = serde_json::from_str(&b.blocked_on_json).unwrap_or_default(); + let pkgbase = db::get_pkgbase_by_id(db, b.pkgbase_id).ok().flatten().map(|p| p.name).unwrap_or_default(); + page_to_res( + BuildDetail { + page, + id: id.to_string(), + id_short: short(id), + pkgbase, + version: String::new(), + kind: b.kind, + state: b.state, + error: b.error.clone().unwrap_or_default(), + blocked_on, + steps, + log: tail, + log_lines: lines.len().min(200), + log_truncated: lines.len() > 200, + }, + 200, + ) +} + +fn build_log(state: &State, id: &str) -> Res { + let body = std::fs::read_to_string(state.cfg.build_log_path(id)).unwrap_or_default(); + Res::text(200, body) +} + +fn build_cancel(state: &State, req: &Req, id: &str) -> Res { + let _ = builds::request_cancel(&state.db, id); + let mut page = chrome(state, req, "Builds", "nav_builds"); + page.flash = format!("cancellation requested for {}; it stops at the next step boundary", short(id)); + page.has_flash = true; + builds_with(state, req, page) +} + +// ----------------------------------------------------------- ops, config -- + +fn audit(state: &State, req: &Req) -> Res { + let page = chrome(state, req, "Ops", "nav_audit"); + let rows = db::list_audit(&state.db, 200) + .unwrap_or_default() + .into_iter() + .map(|a| AuditRow { + at: a.at, + actor_kind: a.actor_kind, + actor: a.actor, + action: a.action, + entity: a.entity, + entity_id: a.entity_id, + detail: a.detail_json, + }) + .collect(); + page_to_res(Audit { page, rows }, 200) +} + +fn settings(state: &State, req: &Req) -> Res { + let page = chrome(state, req, "Settings", "nav_settings"); + let rows = db::all_settings(&state.db) + .unwrap_or_default() + .into_iter() + .map(|(key, value)| SettingRow { key, value }) + .collect(); + let repo = format!( + "name: {}\narch: {}\npath: {}\nsigning key: {}\nbind: {}", + state.cfg.repo_name, + state.cfg.arch, + state.cfg.repo_arch_dir().display(), + if state.cfg.signing_key_id.is_empty() { "none (unsigned!)" } else { &state.cfg.signing_key_id }, + state.cfg.bind + ); + page_to_res(Settings { page, rows, repo }, 200) +} + +// ------------------------------------------------------------ rendering -- + +fn page_to_res(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}")), + } +} diff --git a/src/lib.rs b/src/lib.rs index 2351385..b697ac6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -11,6 +11,7 @@ pub mod error; pub mod fetch; pub mod git; pub mod hash; +pub mod http; pub mod pipeline; pub mod pkgver; pub mod recipe; diff --git a/src/main.rs b/src/main.rs index 75cb282..b88e757 100644 --- a/src/main.rs +++ b/src/main.rs @@ -84,6 +84,12 @@ enum Cmd { Status { build: String }, /// Show the current index. Packages, + /// Run the web server and the watcher until interrupted. + Serve { + /// Override the bind address, e.g. 127.0.0.1:8484. + #[arg(long)] + bind: Option, + }, /// Show recent audit rows. Audit { #[arg(long, default_value_t = 30)] @@ -100,8 +106,38 @@ fn main() -> anyhow::Result<()> { }), None => Config::load(&Config::default().root)?, }; + if let Cmd::Serve { bind } = &cli.cmd { + let mut cfg = cfg; + if let Some(b) = bind { + cfg.bind = b.clone(); + } + cfg.ensure_dirs()?; + db::migrate(&cfg.db_path())?; + let db = db::Db::open_migrated(&cfg.db_path())?; + db::ensure_repo( + &db.writer, + &cfg.repo_name, + &cfg.repo_arch_dir().display().to_string(), + &cfg.arch, + &cfg.signing_key_id, + )?; + // Re-materialize the served index from the DB: if a crash left the file + // behind the database, close the gap before anyone asks for it. + let _ = pipeline::publish::reconcile(&cfg, &db); + let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + aur_build::watch::scheduler::spawn_scheduler(std::sync::Arc::new(cfg.clone()), db.clone(), stop); + let _server = aur_build::http::spawn(cfg.clone(), db.clone())?; + println!("serving on http://{} — ctrl-c to stop", cfg.bind); + // Single process, thread per connection: the main thread has nothing to + // do but wait to be killed. + loop { + std::thread::sleep(std::time::Duration::from_secs(3600)); + } + } let ctx = Ctx::open(&cfg)?; match cli.cmd { + // Handled above, before the CLI's own database context is opened. + Cmd::Serve { .. } => Ok(()), Cmd::Init { repo, signing_key } => { let mut cfg = cfg; if let Some(r) = repo { diff --git a/src/watch/mod.rs b/src/watch/mod.rs index 2016166..f469f86 100644 --- a/src/watch/mod.rs +++ b/src/watch/mod.rs @@ -5,6 +5,7 @@ pub mod detect; pub mod digests; pub mod mirror; pub mod scheduler; +pub mod staleness; pub mod upstream; pub use detect::{check_pkgbase, CheckReport, Outcome}; diff --git a/src/watch/staleness.rs b/src/watch/staleness.rs new file mode 100644 index 0000000..40bafeb --- /dev/null +++ b/src/watch/staleness.rs @@ -0,0 +1,125 @@ +//! Staleness (§10.2): "would rebuilding this change what a consumer gets?" +//! +//! Computed **on read**, never stored. A stored staleness flag goes wrong the +//! moment anything else is published, and there is always something else being +//! published; deriving it from the world snapshots and the current index means +//! it can never lie. +//! +//! The pair comes from §10.1: each build recorded the versions of *our* +//! packages it was built against. If any of those differ from what the index +//! holds now, the artifact was built against a world that no longer exists. + +use crate::db::{self, Db}; +use crate::error::Result; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Kind { + /// A dependency we publish has moved on. + Outdated, + /// A dependency we publish has disappeared from the index. + Missing, +} + +#[derive(Debug, Clone)] +pub struct Stale { + pub kind: Kind, + /// The pkgbase that would need rebuilding. + pub pkgbase: String, + /// The dependency, or the pkgbase itself for `Missing`. + pub dependency: String, + /// Version it was built against. + pub built_with: String, + /// Version the index serves now (empty when missing). + pub now: String, +} + +/// Every stale package, derived from world snapshots against the live index. +pub fn stale_rows(db: &Db) -> Result> { + let rows: Vec<(String, String, String, String)> = db.read(|c| { + let mut st = c.prepare( + "SELECT p.name, w.members_json + FROM release r + JOIN pkgbase p ON p.id = r.pkgbase_id + JOIN build b ON b.id = r.build_id + JOIN world_snapshot w ON w.id = b.world_snapshot_id + WHERE r.state = 'published'", + )?; + let rows = st.query_map([], |r| { + Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, String::new(), String::new())) + })?; + Ok(rows.filter_map(|r| r.ok()).collect::>()) + })?; + + let mut out = Vec::new(); + for (pkgbase, members_json, _, _) in rows { + let members: Vec = serde_json::from_str(&members_json).unwrap_or_default(); + for m in members { + // A package is not stale relative to itself. + if m.pkgbase == pkgbase { + continue; + } + match db::index_version(db, &m.pkgbase)? { + Some(now) if now != m.version => out.push(Stale { + kind: Kind::Outdated, + pkgbase: pkgbase.clone(), + dependency: m.pkgbase.clone(), + built_with: m.version.clone(), + now, + }), + None => out.push(Stale { + kind: Kind::Missing, + pkgbase: pkgbase.clone(), + dependency: m.pkgbase.clone(), + built_with: m.version.clone(), + now: String::new(), + }), + Some(_) => {} + } + } + } + out.sort_by(|a, b| a.pkgbase.cmp(&b.pkgbase).then(a.dependency.cmp(&b.dependency))); + Ok(out) +} + +/// Staleness for one pkgbase, rendered for the package page. +pub fn stale_for(db: &Db, pkgbase: &str) -> Result> { + Ok(stale_rows(db)?.into_iter().filter(|s| s.pkgbase == pkgbase).collect()) +} + +/// "If I approve this, what goes stale?" — the dependents question (§10.3). +/// A package depends on `name` if `name` appears in its recorded world or in +/// its recipe dependencies. +pub fn dependents_of(db: &Db, name: &str) -> Result> { + let mut out: Vec = Vec::new(); + for p in db::index_packages(db)? { + if p.name == name { + continue; + } + let depends: bool = db.read(|c| { + use rusqlite::OptionalExtension; + let json: Option = c + .query_row( + "SELECT s.srcinfo_json FROM package pk + JOIN release r ON r.id = pk.release_id + JOIN candidate cnd ON cnd.id = r.candidate_id + JOIN snapshot s ON s.id = cnd.snapshot_id + WHERE pk.name = ?1 AND pk.state='in_index'", + rusqlite::params![p.name], + |r| r.get::<_, String>(0), + ) + .optional()?; + Ok(json + .and_then(|j| serde_json::from_str::(&j).ok()) + .map(|r| { + crate::pkgver::dep_names(&r.depends) + .into_iter() + .any(|d| d == name) + }) + .unwrap_or(false)) + })?; + if depends { + out.push(p.name); + } + } + Ok(out) +} -- cgit v1.2.3