diff options
| author | aur-build <aur-build@localhost> | 2026-11-18 08:06:39 +0000 |
|---|---|---|
| committer | aur-build <aur-build@localhost> | 2026-11-18 08:06:39 +0000 |
| commit | a6b652985f40cf022d6c522415c36fad13bc663d (patch) | |
| tree | 2383d83a820803808202084db1aa30b12f0e02c2 | |
| parent | ab8d33d5edc4c88075685206e3046c719e9bc855 (diff) | |
| download | aur-build-a6b652985f40cf022d6c522415c36fad13bc663d.tar.gz aur-build-a6b652985f40cf022d6c522415c36fad13bc663d.zip | |
http: the review surface — server-rendered, no JavaScript required (§12, §13)
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.
| -rw-r--r-- | src/http/auth.rs | 102 | ||||
| -rw-r--r-- | src/http/forms.rs | 46 | ||||
| -rw-r--r-- | src/http/mod.rs | 228 | ||||
| -rw-r--r-- | src/http/render.rs | 373 | ||||
| -rw-r--r-- | src/http/routes.rs | 909 | ||||
| -rw-r--r-- | src/lib.rs | 1 | ||||
| -rw-r--r-- | src/main.rs | 36 | ||||
| -rw-r--r-- | src/watch/mod.rs | 1 | ||||
| -rw-r--r-- | src/watch/staleness.rs | 125 | ||||
| -rw-r--r-- | static/app.css | 1 | ||||
| -rw-r--r-- | templates/attention.html | 35 | ||||
| -rw-r--r-- | templates/audit.html | 8 | ||||
| -rw-r--r-- | templates/base.html | 52 | ||||
| -rw-r--r-- | templates/build.html | 17 | ||||
| -rw-r--r-- | templates/builds.html | 22 | ||||
| -rw-r--r-- | templates/dashboard.html | 21 | ||||
| -rw-r--r-- | templates/error.html | 6 | ||||
| -rw-r--r-- | templates/login.html | 10 | ||||
| -rw-r--r-- | templates/package.html | 29 | ||||
| -rw-r--r-- | templates/packages.html | 11 | ||||
| -rw-r--r-- | templates/review.html | 49 | ||||
| -rw-r--r-- | templates/reviews.html | 28 | ||||
| -rw-r--r-- | templates/settings.html | 7 | ||||
| -rw-r--r-- | templates/subscriptions.html | 32 | ||||
| -rw-r--r-- | tests/http.rs | 369 |
25 files changed, 2518 insertions, 0 deletions
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 `<form method=post>` 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<Mutex<HashSet<String>>> = OnceLock::new(); + +fn sessions() -> &'static Mutex<HashSet<String>> { + 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<u8> = 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 `<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() +} 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<PublishRow>, +} + +#[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<ReviewRow>, +} + +#[derive(Debug, Clone)] +pub struct ReviewRow { + pub id: i64, + pub pkgbase: String, + pub version: String, + pub kind: String, + pub risk: String, + pub signals: Vec<String>, + 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<Panel>, + /// 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<String>, + pub missing_deps: Vec<String>, + 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<SubRow>, +} + +#[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<NoticeRow>, + pub outdated: Vec<StaleRow>, + pub missing: Vec<StaleRow>, + pub downgrades: Vec<StaleRow>, + pub blocked: Vec<BlockedRow>, +} + +#[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<String>, +} + +#[derive(Template)] +#[template(path = "packages.html")] +pub struct Packages { + pub page: Page, + pub repo: String, + pub rows: Vec<IndexRow>, + 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<String>, + pub deps_in: Vec<String>, + pub deps_out: Vec<String>, + pub timeline: Vec<TimelineRow>, + pub builds: Vec<BuildLite>, +} + +#[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<BuildRow>, + pub recent: Vec<BuildRow>, +} + +#[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<String>, + pub steps: Vec<StepRow>, + 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<AuditRow>, +} + +#[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<SettingRow>, + 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<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" { + 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<PublishRow> = 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<ReviewRow> { + let db = &state.db; + let mut rows: Vec<ReviewRow> = 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::<i64>().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<Panel>, 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<Recipe> = 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<Panel> = 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::<serde_json::Value>(&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::<i64>().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::<i64>().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<i64> = 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<i64> = 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::<Vec<NoticeRow>>(); + let blocked: Vec<BlockedRow> = 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<StaleRow> = 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<StaleRow> = 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<StaleRow> = 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<IndexRow> = 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<TimelineRow> = 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<BuildLite> = 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<String> = 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<BuildRow> { + 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<BuildRow> = 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<StepRow> = 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<String> = 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: 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}")), + } +} @@ -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<String>, + }, /// 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<Vec<Stale>> { + 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::<Vec<_>>()) + })?; + + let mut out = Vec::new(); + for (pkgbase, members_json, _, _) in rows { + let members: Vec<db::WorldMember> = 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<Vec<Stale>> { + 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<Vec<String>> { + let mut out: Vec<String> = 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<String> = 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::<crate::db::model::Recipe>(&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) +} diff --git a/static/app.css b/static/app.css new file mode 100644 index 0000000..8a2fbcb --- /dev/null +++ b/static/app.css @@ -0,0 +1 @@ +/* styles live inline in base.html to keep this a no-build-step app */ diff --git a/templates/attention.html b/templates/attention.html new file mode 100644 index 0000000..caa277f --- /dev/null +++ b/templates/attention.html @@ -0,0 +1,35 @@ +{% extends "base.html" %} +{% block content %} +<h1>Attention</h1> +{% if empty %}<p class="mut">Nothing needs you.</p>{% endif %} +{% if !notices.is_empty() %}<h2>Alerts</h2> +<table><tr><th>pkgbase</th><th>kind</th><th>severity</th><th>detail</th><th>since</th><th></th></tr> +{% for n in notices %}<tr> +<td><a href="/packages/{{ n.pkgbase }}">{{ n.pkgbase }}</a></td> +<td>{{ n.kind }}</td><td class="risk-{{ n.severity }}">{{ n.severity }}</td> +<td><pre>{{ n.detail }}</pre></td><td class="mut">{{ n.created_at }}</td> +<td><form class="inline" method="post" action="/attention/ack"> +<input type="hidden" name="csrf" value="{{ page.csrf }}"><input type="hidden" name="id" value="{{ n.id }}"> +<button type="submit">acknowledge</button></form></td></tr>{% endfor %}</table>{% endif %} + +{% if !outdated.is_empty() %}<h2>Outdated: a dependency we publish has a newer version</h2> +<table><tr><th>package</th><th>built against</th><th>now in the index</th><th></th></tr> +{% for o in outdated %}<tr><td><a href="/packages/{{ o.pkgbase }}">{{ o.pkgbase }}</a></td> +<td>{{ o.built_with }}</td><td class="ok">{{ o.now }}</td> +<td><form class="inline" method="post" action="/packages/{{ o.pkgbase }}/rebuild"> +<input type="hidden" name="csrf" value="{{ page.csrf }}"><button type="submit">rebuild</button></form></td></tr> +{% endfor %}</table>{% endif %} + +{% if !missing.is_empty() %}<h2>Missing: a dependency we no longer publish</h2> +<table><tr><th>package</th><th>missing</th></tr> +{% for m in missing %}<tr><td>{{ m.pkgbase }}</td><td class="risk-high">{{ m.now }}</td></tr>{% endfor %}</table>{% endif %} + +{% if !blocked.is_empty() %}<h2>Blocked builds</h2> +<table><tr><th>build</th><th>pkgbase</th><th>waiting on</th></tr> +{% for b in blocked %}<tr><td><a href="/builds/{{ b.id }}">{{ b.id_short }}</a></td> +<td>{{ b.pkgbase }}</td><td>{% for d in b.blocked_on %}<span class="tag">{{ d }}</span> {% endfor %}</td></tr>{% endfor %}</table>{% endif %} + +{% if !downgrades.is_empty() %}<h2>Downgrades in the index</h2> +<table><tr><th>package</th><th>serving</th><th>AUR offers</th></tr> +{% for d in downgrades %}<tr><td>{{ d.pkgbase }}</td><td>{{ d.built_with }}</td><td>{{ d.now }}</td></tr>{% endfor %}</table>{% endif %} +{% endblock %} diff --git a/templates/audit.html b/templates/audit.html new file mode 100644 index 0000000..f47030e --- /dev/null +++ b/templates/audit.html @@ -0,0 +1,8 @@ +{% extends "base.html" %} +{% block content %} +<h1>Ops</h1> +<p class="mut">Append-only: the audit table rejects UPDATE and DELETE at the schema level (I10).</p> +<table><tr><th>when</th><th>actor</th><th>action</th><th>entity</th><th>detail</th></tr> +{% for a in rows %}<tr><td class="mut">{{ a.at }}</td><td>{{ a.actor_kind }}:{{ a.actor }}</td> +<td>{{ a.action }}</td><td>{{ a.entity }} {{ a.entity_id }}</td><td><pre>{{ a.detail }}</pre></td></tr>{% endfor %}</table> +{% endblock %} diff --git a/templates/base.html b/templates/base.html new file mode 100644 index 0000000..d36f9cc --- /dev/null +++ b/templates/base.html @@ -0,0 +1,52 @@ +<!doctype html> +<html lang="en"> +<head> +<meta charset="utf-8"> +<meta name="viewport" content="width=device-width, initial-scale=1"> +<meta name="csrf" content="{{ page.csrf }}"> +<title>{{ page.title }} · aur-build</title> +<style> +:root { --bg:#fbfbfa; --fg:#1b1b1a; --mut:#6b6b66; --line:#e2e1dc; --card:#fff; --hi:#b3261e; --ok:#1f6b3a; --warn:#8a5b00; } +* { box-sizing:border-box } +body { margin:0; font:15px/1.5 ui-sans-serif, system-ui, sans-serif; background:var(--bg); color:var(--fg); } +header { border-bottom:1px solid var(--line); background:var(--card); } +nav { display:flex; gap:1.2rem; padding:.7rem 1.2rem; align-items:center; flex-wrap:wrap; max-width:1100px; margin:0 auto; } +nav a { color:var(--mut); text-decoration:none; } +nav a.on, nav a:hover { color:var(--fg); border-bottom:2px solid var(--fg); } +.brand { font-weight:650; color:var(--fg) !important; } +main { max-width:1100px; margin:0 auto; padding:1.2rem; } +table { border-collapse:collapse; width:100%; background:var(--card); } +th, td { text-align:left; padding:.45rem .6rem; border-bottom:1px solid var(--line); vertical-align:top; } +th { font:inherit; font-weight:600; color:var(--mut); } +.badge { background:var(--hi); color:#fff; border-radius:9px; padding:0 .4rem; font-size:.8em; } +.risk-high { color:var(--hi); font-weight:600 } .risk-medium { color:var(--warn) } .risk-low { color:var(--mut) } +pre { background:#f4f4f1; border:1px solid var(--line); padding:.6rem; overflow-x:auto; font-size:12.5px; } +.card { background:var(--card); border:1px solid var(--line); padding:.9rem; margin-bottom:1rem; } +.card.first { border-left:3px solid var(--hi); } +.flash { background:#fff4e5; border:1px solid #f0d9b5; padding:.6rem .8rem; } +.flash.err { background:#fdecea; border-color:#f5c6c2; } +.mut { color:var(--mut) } .ok { color:var(--ok) } +form.inline { display:inline } +button { font:inherit; padding:.2rem .6rem; } +h1 { font-size:1.3rem } h2 { font-size:1.05rem; margin:1.4rem 0 .4rem } +.tag { border:1px solid var(--line); border-radius:3px; padding:0 .3rem; font-size:.85em; background:#f4f4f1 } +</style> +</head> +<body> +<header><nav> +<a class="brand" href="/">aur-build</a> +<a href="/reviews" class="{{ page.nav_reviews }}">Reviews{% if page.pending > 0 %} <span class="badge">{{ page.pending }}</span>{% endif %}</a> +<a href="/builds" class="{{ page.nav_builds }}">Builds{% if page.running > 0 %} <span class="badge">{{ page.running }}</span>{% endif %}</a> +<a href="/attention" class="{{ page.nav_attention }}">Attention{% if page.attention > 0 %} <span class="badge">{{ page.attention }}</span>{% endif %}</a> +<a href="/packages" class="{{ page.nav_packages }}">Index</a> +<a href="/subscriptions" class="{{ page.nav_subscriptions }}">Subscriptions</a> +<a href="/audit" class="{{ page.nav_audit }}">Ops</a> +<a href="/settings" class="{{ page.nav_settings }}">Settings</a> +{% if page.gated %}<form method="post" action="/logout" class="inline"><input type="hidden" name="csrf" value="{{ page.csrf }}"><button type="submit">Sign out</button></form>{% endif %} +</nav></header> +<main> +{% if page.has_flash %}<div class="flash{% if page.flash_err %} err{% endif %}">{{ page.flash }}</div>{% endif %} +{% block content %}{% endblock %} +</main> +</body> +</html> diff --git a/templates/build.html b/templates/build.html new file mode 100644 index 0000000..f1fc7cf --- /dev/null +++ b/templates/build.html @@ -0,0 +1,17 @@ +{% extends "base.html" %} +{% block content %} +<h1>Build {{ id_short }}</h1> +<p class="mut">{{ pkgbase }} {{ version }} · {{ kind }} · <b>{{ state }}</b> +{% if error != "" %} · <span class="risk-high">{{ error }}</span>{% endif %}</p> +{% if !blocked_on.is_empty() %}<div class="card">Blocked on: +{% for d in blocked_on %}<span class="tag">{{ d }}</span> {% endfor %}</div>{% endif %} +<table> +<tr><th>step</th><th>status</th><th>attempt</th><th>output</th><th>error</th></tr> +{% for s in steps %}<tr><td>{{ s.step }}</td> +<td class="{{ s.cls }}">{{ s.status }}</td> +<td>{{ s.attempt }}</td><td class="mut">{{ s.digest }}</td> +<td class="risk-high">{{ s.error }}</td></tr>{% endfor %}</table> +<h2>Log</h2> +{% if log_truncated %}<p class="mut">(last {{ log_lines }} lines — <a href="/builds/{{ id }}/log.txt">full log</a>)</p>{% endif %} +<pre id="log">{{ log }}</pre> +{% endblock %} diff --git a/templates/builds.html b/templates/builds.html new file mode 100644 index 0000000..7f83239 --- /dev/null +++ b/templates/builds.html @@ -0,0 +1,22 @@ +{% extends "base.html" %} +{% block content %} +<h1>Builds</h1> +<div id="builds"> +{% if rows.is_empty() %}<p class="mut">Nothing queued or running.</p>{% else %} +<table> +<tr><th>id</th><th>pkgbase</th><th>version</th><th>kind</th><th>state</th><th>step</th><th>lease</th><th></th></tr> +{% for b in rows %}<tr> +<td><a href="/builds/{{ b.id }}">{{ b.id_short }}</a></td> +<td><a href="/packages/{{ b.pkgbase }}">{{ b.pkgbase }}</a></td> +<td>{{ b.version }}</td><td>{{ b.kind }}</td> +<td>{{ b.state }}{% if b.cancel %} <span class="tag">cancel requested</span>{% endif %}</td> +<td class="mut">{{ b.step }}</td><td class="mut">{{ b.lease }}</td> +<td><form class="inline" method="post" action="/builds/{{ b.id }}/cancel"> +<input type="hidden" name="csrf" value="{{ page.csrf }}"><button type="submit">cancel</button></form></td> +</tr>{% endfor %}</table>{% endif %} +</div> +{% if !recent.is_empty() %}<h2>Recently finished</h2> +<table><tr><th>id</th><th>pkgbase</th><th>state</th><th>error</th></tr> +{% for b in recent %}<tr><td><a href="/builds/{{ b.id }}">{{ b.id_short }}</a></td> +<td>{{ b.pkgbase }}</td><td>{{ b.state }}</td><td class="risk-high">{{ b.error }}</td></tr>{% endfor %}</table>{% endif %} +{% endblock %} diff --git a/templates/dashboard.html b/templates/dashboard.html new file mode 100644 index 0000000..6cca81e --- /dev/null +++ b/templates/dashboard.html @@ -0,0 +1,21 @@ +{% extends "base.html" %} +{% block content %} +<h1>Dashboard</h1> +<div class="card"> +<table> +<tr><th>Subscriptions</th><td>{{ subscriptions }}</td></tr> +<tr><th>Packages in the index</th><td>{{ index_count }}</td></tr> +<tr><th>Reviews pending</th><td><a href="/reviews">{{ pending_reviews }}</a></td></tr> +<tr><th>Builds queued or running</th><td><a href="/builds">{{ running_builds }}</a></td></tr> +<tr><th>Needs attention</th><td><a href="/attention">{{ attention }}</a></td></tr> +</table> +</div> +<h2>Recent publishes</h2> +{% if publishes.is_empty() %}<p class="mut">Nothing published yet.</p>{% else %} +<table><tr><th>pkgbase</th><th>version</th><th>published</th><th>aur_commit</th></tr> +{% for r in publishes %}<tr> +<td><a href="/packages/{{ r.name }}">{{ r.name }}</a></td> +<td>{{ r.version }}</td><td class="mut">{{ r.published_at }}</td> +<td><a href="https://aur.archlinux.org/cgit/aur.git/tree/?h={{ r.name }}&id={{ r.aur_commit }}">{{ r.aur_commit_short }}</a></td> +</tr>{% endfor %}</table>{% endif %} +{% endblock %} diff --git a/templates/error.html b/templates/error.html new file mode 100644 index 0000000..c9c7561 --- /dev/null +++ b/templates/error.html @@ -0,0 +1,6 @@ +{% extends "base.html" %} +{% block content %} +<h1>{{ status }}</h1> +<p>{{ message }}</p> +{% if detail != "" %}<pre>{{ detail }}</pre>{% endif %} +{% endblock %} diff --git a/templates/login.html b/templates/login.html new file mode 100644 index 0000000..f0eaa6a --- /dev/null +++ b/templates/login.html @@ -0,0 +1,10 @@ +{% extends "base.html" %} +{% block content %} +<h1>Sign in</h1> +{% if error != "" %}<div class="flash err">{{ error }}</div>{% endif %} +<form method="post" action="/login"> +<input type="hidden" name="csrf" value="{{ page.csrf }}"> +<p><label>Password <input type="password" name="password" autofocus></label></p> +<button type="submit">Sign in</button> +</form> +{% endblock %} diff --git a/templates/package.html b/templates/package.html new file mode 100644 index 0000000..ded5e1c --- /dev/null +++ b/templates/package.html @@ -0,0 +1,29 @@ +{% extends "base.html" %} +{% block content %} +<h1>{{ name }}</h1> +<p class="mut">{{ summary }}</p> +<div class="card"> +<form class="inline" method="post" action="/packages/{{ name }}/rebuild"> +<input type="hidden" name="csrf" value="{{ page.csrf }}"> +<button type="submit">Rebuild current version</button></form> +<span class="mut">Rebuilds reuse the approved source identity and need no new approval (I6).</span> +{% if can_withdraw %} +<form class="inline" method="post" action="/packages/{{ name }}/withdraw"> +<input type="hidden" name="csrf" value="{{ page.csrf }}"> +<button type="submit">Withdraw from index</button></form>{% endif %} +</div> +{% if !stale.is_empty() %}<div class="card"><b>Stale</b><ul> +{% for s in stale %}<li>{{ s }}</li>{% endfor %}</ul></div>{% endif %} +{% if !deps_in.is_empty() || !deps_out.is_empty() %}<div class="card"> +<b>Depends on</b>: {% for d in deps_in %}<span class="tag">{{ d }}</span> {% endfor %} +<p><b>Needed by</b>: {% for d in deps_out %}<span class="tag">{{ d }}</span> {% endfor %}</p></div>{% endif %} +<h2>Timeline</h2> +<table><tr><th>version</th><th>state</th><th>aur_commit</th><th>published</th><th>approved by</th></tr> +{% for r in timeline %}<tr><td>{{ r.version }}</td><td>{{ r.state }}</td> +<td><a href="https://aur.archlinux.org/cgit/aur.git/tree/?h={{ name }}&id={{ r.aur_commit }}">{{ r.aur_commit_short }}</a></td> +<td class="mut">{{ r.published_at }}</td><td class="mut">{{ r.approver }}</td></tr>{% endfor %}</table> +{% if !builds.is_empty() %}<h2>Builds</h2> +<table><tr><th>id</th><th>kind</th><th>state</th><th>step</th></tr> +{% for b in builds %}<tr><td><a href="/builds/{{ b.id }}">{{ b.id_short }}</a></td><td>{{ b.kind }}</td> +<td>{{ b.state }}</td><td class="mut">{{ b.step }}</td></tr>{% endfor %}</table>{% endif %} +{% endblock %} diff --git a/templates/packages.html b/templates/packages.html new file mode 100644 index 0000000..79b27cc --- /dev/null +++ b/templates/packages.html @@ -0,0 +1,11 @@ +{% extends "base.html" %} +{% block content %} +<h1>Index <span class="mut">[{{ repo }}]</span></h1> +<p class="mut">Exactly the set of accepted releases — one entry per pkgbase, nothing else (I8).</p> +{% if rows.is_empty() %}<p class="mut">The index is empty.</p>{% else %} +<table><tr><th>package</th><th>version</th><th>arch</th><th>size</th><th>published</th></tr> +{% for p in rows %}<tr> +<td><a href="/packages/{{ p.name }}">{{ p.name }}</a></td><td>{{ p.version }}</td><td>{{ p.arch }}</td> +<td class="mut">{{ p.size }}</td><td class="mut">{{ p.published_at }}</td></tr>{% endfor %}</table>{% endif %} +<div class="card"><b>Consumer config</b><pre>{{ snippet }}</pre></div> +{% endblock %} diff --git a/templates/review.html b/templates/review.html new file mode 100644 index 0000000..32441f9 --- /dev/null +++ b/templates/review.html @@ -0,0 +1,49 @@ +{% extends "base.html" %} +{% block content %} +<h1>{{ c.pkgbase }} → {{ c.version }}</h1> +<p class="mut"> + base: {% if has_base %}{{ base_version }}{% else %}<b>nothing accepted yet</b>{% endif %} + · aur_commit <span class="tag">{{ c.aur_commit_short }}</span> + <a href="https://aur.archlinux.org/cgit/aur.git/tree/?h={{ c.pkgbase }}&id={{ c.aur_commit }}">cgit</a> + · kind {{ c.kind }} + · revision {{ c.revision }} · risk <span class="risk-{{ c.risk }}">{{ c.risk }}</span> +</p> +{% if c.is_first %}<div class="card first"> +<b>First build of this package here.</b> +<p class="mut">There is no accepted version to diff against, so the whole recipe is shown below +and the maintainer and age of the package are the only trust signals available. This is the +most consequential approval this pkgbase will ever get: it establishes the base every later +diff is measured against.</p> +</div>{% endif %} +{% if !c.signals.is_empty() %}<div class="card"><b>Risk signals</b><br> +{% for s in c.signals %}<span class="tag risk-high">{{ s }}</span> {% endfor %}</div>{% endif %} +{% if !c.missing_deps.is_empty() %}<div class="card"><b>Missing dependencies</b> +<p>The build will block until these are published: {% for d in c.missing_deps %}<span class="tag">{{ d }}</span> {% endfor %}</p></div>{% endif %} +{% if c.is_first %} +<h2>Recipe</h2> +<div class="card"><b>PKGBUILD</b><pre>{{ recipe }}</pre></div> +{% if has_srcinfo %}<div class="card"><b>.SRCINFO</b><pre>{{ srcinfo }}</pre></div>{% endif %} +<div class="card"><b>Sources, as resolved</b><pre>{{ sources_resolved }}</pre></div> +<div class="card"><b>Dependencies</b><pre>{{ deps_resolved }}</pre></div> +{% endif %} +{% for panel in panels %} +<h2>{{ panel.title }}</h2> +{% if panel.empty %}<p class="mut">{{ panel.empty_note }}</p>{% else %}<pre>{{ panel.body }}</pre>{% endif %} +{% endfor %} +<div class="card"> +<form method="post" action="/reviews/{{ c.id }}/approve"> +<input type="hidden" name="csrf" value="{{ page.csrf }}"> +<input type="hidden" name="identity_hash" value="{{ c.identity_hash }}"> +<input type="hidden" name="diff_digest" value="{{ c.diff_digest }}"> +<p><label>Note (optional) <input name="note" size="60"></label></p> +<button type="submit">Approve and build</button> +<span class="mut">Approving builds exactly what is displayed above; if it changed while you +were reading, this is refused with a 409 and re-rendered.</span> +</form> +<form method="post" action="/reviews/{{ c.id }}/reject" style="margin-top:.6rem"> +<input type="hidden" name="csrf" value="{{ page.csrf }}"> +<label>Reject with reason <input name="note" size="60" required></label> +<button type="submit">Reject</button> +</form> +</div> +{% endblock %} diff --git a/templates/reviews.html b/templates/reviews.html new file mode 100644 index 0000000..65efe80 --- /dev/null +++ b/templates/reviews.html @@ -0,0 +1,28 @@ +{% extends "base.html" %} +{% block content %} +<h1>Reviews</h1> +<p class="mut">Sorted by risk, then age. Risk is advisory: nothing is auto-approved.</p> +{% if rows.is_empty() %}<p class="mut">Nothing here. That is the good state.</p>{% else %} +<form method="post" action="/reviews/bulk"> +<input type="hidden" name="csrf" value="{{ page.csrf }}"> +<table> +<tr><th></th><th>pkgbase</th><th>version</th><th>kind</th><th>risk</th><th>signals</th><th>age</th><th></th></tr> +{% for r in rows %}<tr> +<td><input type="checkbox" name="ids" value="{{ r.id }}"></td> +<td><a href="/reviews/{{ r.id }}">{{ r.pkgbase }}</a></td> +<td>{{ r.version }}</td> +<td>{{ r.kind }}{% if r.revision > 1 %} <span class="tag">rev{{ r.revision }}</span>{% endif %}</td> +<td class="risk-{{ r.risk }}">{{ r.risk }}</td> +<td class="mut">{% for s in r.signals %}<span class="tag">{{ s }}</span> {% endfor %}</td> +<td class="mut">{{ r.age }}</td> +<td><a href="/reviews/{{ r.id }}">review</a></td> +</tr>{% endfor %} +</table> +<p> +<button type="submit" name="decision" value="approve">Approve selected</button> +<button type="submit" name="decision" value="reject">Reject selected</button> +<span class="mut">High-risk items are refused in bulk unless confirmed individually.</span> +</p> +</form> +{% endif %} +{% endblock %} diff --git a/templates/settings.html b/templates/settings.html new file mode 100644 index 0000000..650a453 --- /dev/null +++ b/templates/settings.html @@ -0,0 +1,7 @@ +{% extends "base.html" %} +{% block content %} +<h1>Settings</h1> +<table><tr><th>key</th><th>value</th></tr> +{% for s in rows %}<tr><td>{{ s.key }}</td><td>{{ s.value }}</td></tr>{% endfor %}</table> +<div class="card"><b>Repo</b><pre>{{ repo }}</pre></div> +{% endblock %} diff --git a/templates/subscriptions.html b/templates/subscriptions.html new file mode 100644 index 0000000..5562dfb --- /dev/null +++ b/templates/subscriptions.html @@ -0,0 +1,32 @@ +{% extends "base.html" %} +{% block content %} +<h1>Subscriptions</h1> +{% if rows.is_empty() %}<p class="mut">Nothing subscribed.</p>{% else %} +<table> +<tr><th>pkgbase</th><th>state</th><th>maintainer</th><th>last checked</th><th>next check</th><th>pending</th><th></th></tr> +{% for s in rows %}<tr> +<td><a href="/packages/{{ s.name }}">{{ s.name }}</a></td> +<td>{{ s.state }}{% if s.has_error %} <span class="tag risk-high">{{ s.last_error }}</span>{% endif %}</td> +<td class="mut">{{ s.maintainer }}</td> +<td class="mut">{{ s.last_checked }}</td> +<td class="mut">{{ s.next_check }}</td> +<td>{{ s.pending }}</td> +<td> +<form class="inline" method="post" action="/subscriptions/pause"> +<input type="hidden" name="csrf" value="{{ page.csrf }}"><input type="hidden" name="pkgbase" value="{{ s.name }}"> +<button type="submit">{{ s.pause_label }}</button></form> +<form class="inline" method="post" action="/subscriptions/remove"> +<input type="hidden" name="csrf" value="{{ page.csrf }}"><input type="hidden" name="pkgbase" value="{{ s.name }}"> +<button type="submit">remove</button></form> +</td></tr>{% endfor %}</table>{% endif %} +<div class="card"> +<h2>Subscribe to a pkgbase</h2> +<form method="post" action="/subscriptions/add"> +<input type="hidden" name="csrf" value="{{ page.csrf }}"> +<label>pkgbase <input name="pkgbase" size="30" required></label> +<button type="submit">Subscribe</button> +</form> +<p class="mut">A new subscription produces a <b>first introduction</b> review, which is the most +careful review you will do for it.</p> +</div> +{% endblock %} diff --git a/tests/http.rs b/tests/http.rs new file mode 100644 index 0000000..20dcbcb --- /dev/null +++ b/tests/http.rs @@ -0,0 +1,369 @@ +//! The web surface (§12, §13): routes render, the CSRF gate holds, and a stale +//! approval comes back as a 409 with the current diff instead of a silent +//! retarget. +//! +//! These drive a real `tiny_http` server on an ephemeral loopback port over a +//! real fixture corpus — no mocked transport, because the transport is part of +//! what we are claiming works. + +mod common; + +use aur_build::db::model::*; +use aur_build::http::{self, Server}; +use aur_build::review::{candidates, diff}; +use common::*; + +struct Web { + env: Env, + fx: Fixture, + #[allow(dead_code)] + server: Server, + cookie: String, + csrf: String, +} + +struct Page { + status: u16, + body: String, +} + +impl Web { + fn new(name: &str) -> Self { + Self::with_password(name, "") + } + + fn with_password(name: &str, password: &str) -> Self { + let (mut env, fx) = env_with_fixture(name); + env.cfg.bind = "127.0.0.1:0".into(); + env.cfg.password = password.into(); + let server = http::spawn(env.cfg.clone(), env.db.clone()).unwrap(); + let mut web = Self { env, fx, server, cookie: String::new(), csrf: String::new() }; + // First contact mints the session cookie and the CSRF token. + let first = web.raw_get("/"); + web.cookie = first + .0 + .iter() + .find(|(k, _)| k == "set-cookie") + .and_then(|(_, v)| v.split(';').next().map(|s| s.to_string())) + .unwrap_or_default(); + let body = web.get("/"); + web.csrf = extract(&body.body, "name=\"csrf\" content=\"", "\"").unwrap_or_default(); + web + } + + fn url(&self, path: &str) -> String { + format!("http://{}{}", self.server.addr, path) + } + + fn raw_get(&self, path: &str) -> (Vec<(String, String)>, String) { + let resp = ureq::get(&self.url(path)).set("Cookie", &self.cookie).call(); + let r = match resp { + Ok(r) => r, + Err(ureq::Error::Status(_, r)) => r, + Err(e) => panic!("GET {path}: {e}"), + }; + let cookie = r.header("set-cookie").map(|s| s.to_string()).unwrap_or_default(); + (vec![("set-cookie".to_string(), cookie)], r.into_string().unwrap_or_default()) + } + + fn get(&self, path: &str) -> Page { + let resp = ureq::get(&self.url(path)).set("Cookie", &self.cookie).call(); + self.finish(resp, path) + } + + fn post(&self, path: &str, form: &[(&str, &str)]) -> Page { + let resp = ureq::post(&self.url(path)).set("Cookie", &self.cookie).send_form(form); + self.finish(resp, path) + } + + 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() }, + Err(ureq::Error::Status(code, r)) => Page { status: code, body: r.into_string().unwrap_or_default() }, + Err(e) => panic!("{path}: {e}"), + } + } + + /// Subscribe, detect and render a review so an approval can be attempted. + fn open_review(&self, name: &str) -> CandidateRow { + aur_build::watch::detect::check_pkgbase(&self.env.cfg, &self.env.db, name).unwrap(); + let c = candidates::pending_candidates(&self.env.db).unwrap().remove(0); + let dd = diff::render_and_store(&self.env.db, &self.env.cfg, &c).unwrap(); + let _ = dd; + candidates::candidate_by_id(&self.env.db, c.id).unwrap().unwrap() + } +} + +fn extract(hay: &str, open: &str, close: &str) -> Option<String> { + let i = hay.find(open)? + open.len(); + let rest = &hay[i..]; + let j = rest.find(close)?; + Some(unescape(&rest[..j])) +} + +/// Templates escape attribute values; a test comparing one back to a Rust +/// string has to undo that. +fn unescape(s: &str) -> String { + s.replace("&", "&") + .replace(""", "\"") + .replace("<", "<") + .replace(">", ">") + .replace("'", "'") +} + +#[test] +fn every_surface_renders() { + let web = Web::new("plain-make"); + web.open_review("plain-make"); + for path in [ + "/", + "/reviews", + "/reviews?state=pending", + "/subscriptions", + "/attention", + "/packages", + "/packages/plain-make", + "/builds", + "/audit", + "/settings", + ] { + let page = web.get(path); + assert_eq!(page.status, 200, "{path} did not render"); + assert!(page.body.contains("<!doctype html>"), "{path} is not a page"); + assert!(page.body.contains("aur-build"), "{path} has no chrome"); + } +} + +#[test] +fn the_review_detail_shows_the_panels_and_the_hashes() { + let web = Web::new("plain-make"); + // Publish a first version so the review has something to diff against; + // every panel compares the accepted release to the candidate (§6). + let first = web.open_review("plain-make"); + let page = web.get(&format!("/reviews/{}", first.id)); + let dd = extract(&page.body, "name=\"diff_digest\" value=\"", "\"").unwrap(); + web.post( + &format!("/reviews/{}/approve", first.id), + &[("csrf", &web.csrf), ("identity_hash", &first.identity_hash), ("diff_digest", &dd)], + ); + let id = aur_build::pipeline::enqueue_for_candidate(&web.env.cfg, &web.env.db, &first).unwrap(); + aur_build::pipeline::run(&web.env.cfg, &web.env.db, &id).unwrap(); + web.fx.bump(&[("pkgver", "2.0")]); + let c = web.open_review("plain-make"); + let page = web.get(&format!("/reviews/{}", c.id)); + assert_eq!(page.status, 200); + // The panel set (§6), all comparing accepted → candidate. + for want in ["Recipe diff", "Version delta", "Source digest delta", "Dependency delta", "Build-env delta"] { + assert!(page.body.contains(want), "missing panel {want}"); + } + assert!(page.body.contains("previous accepted release"), "no base shown"); + // The approve form carries both hashes (§7.1a) and is a plain POST form, + // so it works with JavaScript switched off. + assert!(page.body.contains("name=\"identity_hash\"")); + assert!(page.body.contains("name=\"diff_digest\"")); + assert!(page.body.contains("<form method=\"post\"")); + assert!(!page.body.contains("<script"), "P2 ships no JavaScript at all"); + // The aur_commit is shown and linked into AUR's cgit. + assert!(page.body.contains("aur.archlinux.org/cgit/aur.git"), "no cgit link"); +} + +#[test] +fn a_first_introduction_shows_the_whole_recipe_not_a_diff() { + let web = Web::new("plain-make"); + let c = web.open_review("plain-make"); + let page = web.get(&format!("/reviews/{}", c.id)); + assert!(page.body.contains("First build of this package here"), "no first-introduction card"); + assert!(page.body.contains("pkgbase=plain-make"), "the PKGBUILD was not shown"); + assert!(page.body.contains("Sources, as resolved")); +} + +#[test] +fn risk_signals_are_shown_inline() { + let web = Web::new("skip-checksum"); + let c = web.open_review("skip-checksum"); + let page = web.get(&format!("/reviews/{}", c.id)); + assert!(page.body.contains("Risk signals"), "no risk block"); + assert!(page.body.contains("skip-checksum:source-0"), "the SKIP signal is not shown"); + assert!(page.body.contains("risk-high")); +} + +#[test] +fn every_post_requires_a_csrf_token() { + let web = Web::new("plain-make"); + let c = web.open_review("plain-make"); + // A form post with no token at all is refused outright. + let page = { + let resp = ureq::post(&web.url(&format!("/reviews/{}/approve", c.id))) + .set("Cookie", &web.cookie) + .send_form(&[("identity_hash", "x"), ("diff_digest", "y")]); + web.finish(resp, "approve") + }; + assert_eq!(page.status, 403, "a POST without CSRF must be refused"); + // And so is one with a token from someone else's session. + let page = web.post(&format!("/reviews/{}/approve", c.id), &[ + ("csrf", "not-the-token"), + ("identity_hash", &c.identity_hash), + ("diff_digest", &c.diff_digest), + ]); + assert_eq!(page.status, 403, "a forged CSRF token must be refused"); + assert_eq!( + web.env.query_i64("SELECT count(*) FROM approval", &[]), + Some(0), + "a refused POST must not have written anything" + ); +} + +#[test] +fn approve_carries_both_hashes_and_queues_a_build() { + let web = Web::new("plain-make"); + let c = web.open_review("plain-make"); + let page = web.get(&format!("/reviews/{}", c.id)); + let shown_digest = extract(&page.body, "name=\"diff_digest\" value=\"", "\"").unwrap(); + let shown_identity = extract(&page.body, "name=\"identity_hash\" value=\"", "\"").unwrap(); + assert_eq!(shown_identity, c.identity_hash); + + let res = web.post( + &format!("/reviews/{}/approve", c.id), + &[("csrf", &web.csrf), ("identity_hash", &shown_identity), ("diff_digest", &shown_digest), ("note", "looked")], + ); + assert_eq!(res.status, 200, "approve should succeed: {}", &res.body[..200.min(res.body.len())]); + assert!(res.body.contains("approved"), "no confirmation: {}", &res.body[..200.min(res.body.len())]); + assert_eq!(web.env.query_i64("SELECT count(*) FROM approval", &[]), Some(1)); + assert_eq!(web.env.query_i64("SELECT count(*) FROM build", &[]), Some(1), "approval must queue the build"); +} + +#[test] +fn a_stale_approval_is_a_409_that_renders_the_current_diff() { + let web = Web::new("plain-make"); + let c = web.open_review("plain-make"); + let page = web.get(&format!("/reviews/{}", c.id)); + let shown_digest = extract(&page.body, "name=\"diff_digest\" value=\"", "\"").unwrap(); + + // Upstream moves while the reviewer is reading: the identity changes under + // them (§7.1a). + web.fx.bump(&[("pkgver", "9.9")]); + aur_build::watch::detect::check_pkgbase(&web.env.cfg, &web.env.db, "plain-make").unwrap(); + + let res = web.post( + &format!("/reviews/{}/approve", c.id), + &[("csrf", &web.csrf), ("identity_hash", &c.identity_hash), ("diff_digest", &shown_digest)], + ); + assert_eq!(res.status, 409, "a stale approval must come back as 409"); + assert!(res.body.contains("refused"), "no explanation: {}", &res.body[..200.min(res.body.len())]); + // Either way the reviewer is told the ground moved under them, and shown + // the review as it is NOW rather than the one they asked to approve. + assert!( + res.body.contains("while you were looking") || res.body.contains("no longer pending"), + "not a §7.1a explanation: {}", + &res.body[..400.min(res.body.len())] + ); + assert!(res.body.contains("9.9"), "the re-render does not show the new version"); + assert_eq!( + web.env.query_i64("SELECT count(*) FROM approval", &[]), + Some(0), + "a refused approval must leave nothing behind" + ); +} + +#[test] +fn reject_requires_a_note() { + let web = Web::new("plain-make"); + let c = web.open_review("plain-make"); + let res = web.post( + &format!("/reviews/{}/reject", c.id), + &[("csrf", &web.csrf), ("note", "")], + ); + assert_eq!(res.status, 400, "an empty note must be refused"); + assert_eq!(web.env.query_i64("SELECT count(*) FROM approval", &[]), Some(0)); + let res = web.post( + &format!("/reviews/{}/reject", c.id), + &[("csrf", &web.csrf), ("note", "upstream dropped our license")], + ); + assert_eq!(res.status, 200); + assert_eq!(web.env.query_i64("SELECT count(*) FROM approval WHERE decision='rejected'", &[]), Some(1)); +} + +#[test] +fn bulk_approve_refuses_high_risk_without_individual_confirmation() { + let web = Web::new("skip-checksum"); + let c = web.open_review("skip-checksum"); + assert_eq!(c.risk_level, aur_build::review::risk::level::HIGH, "fixture should be high risk"); + let id = c.id.to_string(); + let res = web.post("/reviews/bulk", &[("csrf", &web.csrf), ("decision", "approve"), ("ids", &id)]); + assert!(res.body.contains("refused"), "bulk approve accepted a high-risk item: {}", &res.body[..300.min(res.body.len())]); + assert_eq!(web.env.query_i64("SELECT count(*) FROM approval", &[]), Some(0)); + + // Confirming it individually lets it through — bulk is per-item, never + // "approve everything forever" (§7.4). + let res = web.post( + "/reviews/bulk", + &[("csrf", &web.csrf), ("decision", "approve"), ("ids", &id), ("confirm", &id)], + ); + assert!(!res.body.contains("refused"), "confirmed item was still refused: {}", &res.body[..300.min(res.body.len())]); + assert_eq!(web.env.query_i64("SELECT count(*) FROM approval", &[]), Some(1)); +} + +#[test] +fn a_password_gate_redirects_anonymous_visitors() { + let 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. + assert!(page.body.contains("Sign in"), "not the login page: {}", &page.body[..200.min(page.body.len())]); + // Wrong password is refused, right password lets us through. + 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"); +} + +#[test] +fn handlers_read_on_a_read_only_connection() { + // The claim under test: a handler can never take the write lock, because + // the connection it reads through is read-only at the SQLite level. + let web = Web::new("plain-make"); + let err = web + .env + .db + .read(|c| { + c.execute("CREATE TABLE should_never_exist (x INTEGER)", [])?; + Ok(()) + }) + .err(); + assert!(err.is_some(), "a read connection was able to write: the split is not real"); + // And the page still renders while that is true. + assert_eq!(web.get("/").status, 200); +} + +#[test] +fn the_index_page_tells_a_consumer_how_to_use_it() { + let web = Web::new("plain-make"); + let page = web.get("/packages"); + assert!(page.body.contains("SigLevel = Required"), "no signing guidance"); + assert!(page.body.contains(&web.env.cfg.repo_name)); +} + +#[test] +fn attention_lists_blocked_builds_with_their_blocking_pkgbase() { + let (env, _fx) = env_with_fixture("missing-dep"); + env.subscribe("dep-partner"); + aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, "missing-dep").unwrap(); + let c = candidates::pending_candidates(&env.db).unwrap().remove(0); + let dd = diff::render_and_store(&env.db, &env.cfg, &c).unwrap(); + aur_build::review::approve::approve(&env.db, "t", c.id, &c.identity_hash, &dd, None).unwrap(); + let c = candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap(); + let id = aur_build::pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap(); + aur_build::pipeline::run(&env.cfg, &env.db, &id).unwrap(); + + let server = aur_build::http::spawn(env.cfg.clone(), env.db.clone()).unwrap(); + let url = format!("http://{}/attention", server.addr); + let body = ureq::get(&url).call().unwrap().into_string().unwrap(); + assert!(body.contains("Blocked builds"), "no blocked section"); + assert!(body.contains("dep-partner"), "the blocking pkgbase is not named"); +} + +#[test] +fn unknown_paths_are_404_not_500() { + let web = Web::new("plain-make"); + assert_eq!(web.get("/nope").status, 404); + assert_eq!(web.get("/reviews/not-a-number").status, 404); +} |
