From f586d11f6a1711145ba4804787217a1bab58751d Mon Sep 17 00:00:00 2001 From: aur-build Date: Tue, 17 Nov 2026 21:19:35 +0000 Subject: feat: AUR mirror watcher, recipe parsing, candidate creation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The detection path (§5.1, §5.1a, §5.3, §7.1): * git helpers, all subprocess git in one auditable place. Mirrors are cloned with --mirror and polled with git ls-remote, fetching only when the tip actually moved; --no-prune keeps history we may need forever. * .SRCINFO parsing (authoritative) with a PKGBUILD fallback, and source=() parsing that keeps VCS kind, #commit/#tag/#branch refs and the filename:: form. * recipe_hash over the whole snapshot tree, so a shipped patch is part of the recipe and cannot change silently. * source digest resolution: declared checksums are trusted-as-declared (makepkg enforces them, no bandwidth), local files are hashed from the mirror, and SKIP sources are downloaded and stream-hashed into the content-addressed source cache. Detection always re-fetches SKIP sources — answering from our own cache would defeat drift detection. * candidate creation with base = current_accepted_release, collapse in place while unviewed, supersede only once a human has looked, and a previously rejected identity is not re-raised. * non-publishable change handling (I11): unchanged version string means no review, but never silence — recipe drift and pin drift become notices, and a changed digest on a remote source with an unchanged version becomes a high-severity integrity_alert. Also vercmp + dep-string parsing with the ALPM test vectors, and the approval record with optimistic concurrency (§7.1a) that the CLI and web layers will both call. 16 detection tests against real file:// git fixtures, incl. I2 across three unattended detections and I11 for all three drift kinds. Part of P0 (DESIGN.md §17). --- src/watch/detect.rs | 288 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 288 insertions(+) create mode 100644 src/watch/detect.rs (limited to 'src/watch/detect.rs') diff --git a/src/watch/detect.rs b/src/watch/detect.rs new file mode 100644 index 0000000..e00a2f9 --- /dev/null +++ b/src/watch/detect.rs @@ -0,0 +1,288 @@ +//! Detection: the recipe watcher pass for one pkgbase (§5.1, §5.2, §5.3). +//! +//! The decision that matters is *what counts as a change*. A candidate exists +//! only if something **publishable** changed — if the version string is +//! unchanged, `pacman` cannot offer an upgrade, so there is nothing to approve. +//! Those events become `notice` rows instead, and are never silently dropped +//! (I11). + +use crate::config::Config; +use crate::db::{self, *}; +use crate::error::Result; +use crate::pkgver; +use crate::recipe::recipe_from_tree; +use crate::review::candidates::{upsert_candidate, NewCandidate, Upsert}; +use crate::time; +use crate::watch::digests::resolve_sources; +use crate::watch::mirror::{read_tree, sync_mirror, Sync}; + +#[derive(Debug, Clone)] +pub enum Outcome { + /// Nothing moved at all. + NoChange, + /// A new review was opened. + Candidate { id: i64, kind: String }, + /// The open review was updated in place (I7). + Collapsed { id: i64, revision: i64 }, + /// The seen-but-unresolved review was frozen and a new one opened. + Superseded { old: i64, new: i64 }, + /// Identical to something a human already rejected. + PreviouslyRejected, + /// Something changed but nothing is publishable (I11). + Notice { kind: String, detail: serde_json::Value }, + /// The package vanished from AUR. + Gone, + /// Detection could not complete; the watcher will back off. + Blocked(String), +} + +#[derive(Debug, Clone)] +pub struct CheckReport { + pub pkgbase: String, + pub head: String, + pub outcome: Outcome, +} + +/// One full detection pass for a subscribed pkgbase. +pub fn check_pkgbase(cfg: &Config, db: &Db, name: &str) -> Result { + let pb = get_pkgbase(db, name)? + .ok_or_else(|| crate::error::Error::not_found(format!("pkgbase {name}")))?; + let sync = sync_mirror(cfg, db, name, &pb.aur_url)?; + let head = match &sync { + Sync::Gone => { + db::put_notice_once( + &db.writer, + pb.id, + notice_kind::DELETED, + "high", + serde_json::json!({"aur_url": pb.aur_url, "note": "repository no longer exists"}), + )?; + db::set_subscription_state(&db.writer, name, subscription_state::ORPHANED)?; + return Ok(CheckReport { pkgbase: name.into(), head: String::new(), outcome: Outcome::Gone }); + } + // The cheap poll saved us a fetch, but we still have to look: a source + // can change its bytes without the recipe moving at all, and that is the + // digest-drift case §5.3 calls the single most valuable detection. + Sync::Unchanged { head } => head.clone(), + Sync::Fetched { head, .. } | Sync::Cloned { head } => head.clone(), + }; + let r = analyse(cfg, db, &pb, &head); + schedule_next(db, name, &pb); + r +} + +fn schedule_next(db: &Db, name: &str, pb: &Pkgbase) { + let interval = db + .read(|c| { + use rusqlite::OptionalExtension; + Ok(c.query_row( + "SELECT poll_interval_secs FROM subscription WHERE pkgbase=?1", + rusqlite::params![name], + |r| r.get::<_, Option>(0), + ) + .optional()?) + }) + .ok() + .flatten() + .flatten() + .unwrap_or(crate::db::setting_i64(db, "poll_interval", 86400)); + let next = time::secs_ahead(interval); + let _ = db::note_check(&db.writer, name, &next, None); + let _ = pb; +} + +/// Everything after the mirror is up to date. +fn analyse(cfg: &Config, db: &Db, pb: &Pkgbase, head: &str) -> Result { + let mirror = cfg.mirror_path(&pb.name); + let report = |outcome: Outcome| CheckReport { pkgbase: pb.name.clone(), head: head.to_string(), outcome }; + + // §16 mirror divergence: if the accepted pin has vanished from our own + // mirror, hard-fail this pkgbase rather than silently re-pinning. + let accepted = crate::review::candidates::accepted_for(db, pb)?; + if let Some(a) = &accepted { + if !crate::git::has_commit(&mirror, &a.aur_commit) { + db::put_notice_once( + &db.writer, + pb.id, + notice_kind::DELETED, + "high", + serde_json::json!({"mirror_divergence": a.aur_commit}), + )?; + return Ok(report(Outcome::Blocked(format!( + "accepted pin {} missing from local mirror", + a.aur_commit + )))); + } + } + + let tree = read_tree(&mirror, head)?; + let recipe = recipe_from_tree(&tree.files)?; + let recipe_hash = tree.recipe_hash(); + let digests = resolve_sources(cfg, db, &mirror, head, &tree, &recipe, &[])?; + let pins: Vec = Vec::new(); // P1 fills this in for VCS sources + + let identity = Identity { + aur_commit: head.to_string(), + epoch: recipe.epoch.clone(), + pkgver: recipe.pkgver.clone(), + pkgrel: recipe.pkgrel.clone(), + upstream_pins: pins.clone(), + source_digests: digests.clone(), + }; + let identity_hash = identity.hash(); + let snap_id = db::put_snapshot( + &db.writer, + pb.id, + head, + &recipe_hash, + &serde_json::to_string(&recipe)?, + &tree.json_list(), + )?; + + let nc = NewCandidate { + snapshot_id: snap_id, + epoch: recipe.epoch.clone(), + pkgver: recipe.pkgver.clone(), + pkgrel: recipe.pkgrel.clone(), + upstream_pins_json: serde_json::to_string(&pins)?, + source_digests_json: serde_json::to_string(&digests)?, + identity_hash: identity_hash.clone(), + }; + + let Some(base) = accepted else { + // §7.1b: nothing to diff against — this is a first introduction. + return match upsert_candidate(db, pb, None, &nc)? { + Upsert::Created { id, kind } => Ok(report(Outcome::Candidate { id, kind })), + other => Ok(report(outcome_of(other))), + }; + }; + + // Same identity as what we already serve: nothing happened. + if base.aur_commit == head + && base.epoch == nc.epoch + && base.pkgver == nc.pkgver + && base.pkgrel == nc.pkgrel + && base.upstream_pins_json == nc.upstream_pins_json + && base.source_digests_json == nc.source_digests_json + { + return Ok(report(Outcome::NoChange)); + } + + let new_version = nc.version(); + let publishable = pkgver::vercmp(&base.version(), &new_version) != std::cmp::Ordering::Equal; + + if !publishable { + // §5.2 / §5.3: nothing pacman could offer as an upgrade. Record it + // loudly instead of inventing a pkgrel bump. + return Ok(report(non_publishable(db, pb, &base, &nc, &recipe)?)); + } + + if pkgver::is_downgrade(&base.version(), &new_version) { + db::put_notice_once( + &db.writer, + pb.id, + notice_kind::DOWNGRADE, + "warning", + serde_json::json!({"served": base.version(), "aur": new_version}), + )?; + } + + let up = upsert_candidate(db, pb, Some(&base), &nc)?; + Ok(report(outcome_of(up))) +} + +fn outcome_of(up: Upsert) -> Outcome { + match up { + Upsert::Created { id, kind } => Outcome::Candidate { id, kind }, + Upsert::Collapsed { id, revision } => Outcome::Collapsed { id, revision }, + Upsert::Superseded { old, new } => Outcome::Superseded { old, new }, + Upsert::PreviouslyRejected => Outcome::PreviouslyRejected, + Upsert::Unchanged => Outcome::NoChange, + } +} + +/// The version string did not move, so there is no review to open — but the +/// change is recorded, because a silently drifting tarball is exactly the kind +/// of thing that must not be invisible (§5.3). +fn non_publishable( + db: &Db, + pb: &Pkgbase, + base: &ReleaseRow, + nc: &NewCandidate, + recipe: &Recipe, +) -> Result { + let old_digests: Vec = base.digests(); + let new_digests: Vec = serde_json::from_str(&nc.source_digests_json).unwrap_or_default(); + // A local source is part of the recipe: when its bytes move, that *is* the + // recipe drift, not an integrity event. The integrity alert is specifically + // "the bytes upstream serves no longer match what we built" (§5.3). + let changed_remote: Vec<&SourceDigest> = new_digests + .iter() + .filter(|n| n.kind != "local") + .filter(|n| match old_digests.iter().find(|o| o.index == n.index) { + Some(o) => o.digest != n.digest, + None => true, + }) + .collect(); + let digest_changed = !changed_remote.is_empty(); + let old_pins: Vec = base.pins(); + let new_pins: Vec = serde_json::from_str(&nc.upstream_pins_json).unwrap_or_default(); + let pins_changed = old_pins != new_pins; + + if digest_changed { + // The single most valuable detection in the system: the artifact in the + // index was built from bytes upstream no longer serves, and the version + // string is unchanged. An approval would be useless (approving it would + // not let us publish anything), so this is an alert, not a review. + let changed: Vec = changed_remote + .iter() + .map(|n| { + serde_json::json!({"index": n.index, "url": n.url, + "old": old_digests.iter().find(|o| o.index == n.index) + .map(|o| o.digest.clone()).unwrap_or_default(), + "new": n.digest}) + }) + .collect(); + db::put_notice_once( + &db.writer, + pb.id, + notice_kind::INTEGRITY_ALERT, + "high", + serde_json::json!({ + "version": nc.version(), + "changed": changed, + "message": "the artifact in your index was built from bytes upstream no longer serves; the version string is unchanged", + }), + )?; + return Ok(Outcome::Notice { kind: notice_kind::INTEGRITY_ALERT.into(), detail: serde_json::json!({"changed": changed}) }); + } + if pins_changed { + db::put_notice_once( + &db.writer, + pb.id, + notice_kind::PIN_DRIFT, + "info", + serde_json::json!({ + "version": nc.version(), + "message": "upstream moved; pkgver unchanged, nothing publishable", + }), + )?; + return Ok(Outcome::Notice { kind: notice_kind::PIN_DRIFT.into(), detail: serde_json::json!({}) }); + } + // The recipe drifted under a static version: the maintainer probably forgot + // to bump pkgrel, and the user should know. + let _ = recipe; + db::put_notice_once( + &db.writer, + pb.id, + notice_kind::RECIPE_DRIFT, + "warning", + serde_json::json!({ + "version": nc.version(), + "accepted_aur_commit": base.aur_commit, + "aur_commit": "moved", + "message": "recipe changed but the version did not; the maintainer may have forgotten to bump pkgrel", + }), + )?; + Ok(Outcome::Notice { kind: notice_kind::RECIPE_DRIFT.into(), detail: serde_json::json!({}) }) +} -- cgit v1.2.3