//! 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, /// The subscription is paused: we look at nothing and change nothing. Paused, /// 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}")))?; // A paused subscription is not observed at all. Pausing because a package is // broken must not keep opening reviews nobody is going to act on, and it // must not keep polling AUR either. The pause lives on the subscription, so // that is what we consult. let paused = db::get_subscription(db, name)? .map(|s| s.state == subscription_state::PAUSED) .unwrap_or(false); if paused { return Ok(CheckReport { pkgbase: name.into(), head: String::new(), outcome: Outcome::Paused }); } 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(); // §5.2, the two-stage funnel. Stage A is one `ls-remote` per VCS source and // costs no clone; if the tip set is what the accepted release was built // from, nothing can have changed and Stage B never runs. let has_vcs = recipe.source_entries.iter().any(|e| e.is_vcs()); let accepted_pins: Vec = accepted.as_ref().map(|a| a.pins()).unwrap_or_default(); // A recipe with no VCS sources states its own version; there is nothing to // probe and nothing to resolve. let stage_a = if has_vcs { Some(crate::watch::upstream::probe(&recipe, &accepted_pins)?) } else { None }; let resolved = if !has_vcs { None } else if stage_a.as_ref().unwrap().needs_stage_b() { crate::watch::upstream::resolve(cfg, db, pb, &recipe, &recipe_hash, stage_a.as_ref().unwrap())? } else { // Upstream has not moved. The version we serve is still the answer, and // reusing its pins is what makes the next pass cheap too. accepted.as_ref().map(|a| crate::watch::upstream::StageB { epoch: a.epoch.clone(), pkgver: a.pkgver.clone(), pkgrel: a.pkgrel.clone(), pins: accepted_pins.clone(), cached: true, }) }; // For a VCS package the literal `pkgver=` is frozen; the resolved one is the // only version a consumer could actually install. let (epoch, pkgver, pkgrel, pins) = match &resolved { Some(r) => (r.epoch.clone(), r.pkgver.clone(), r.pkgrel.clone(), r.pins.clone()), None => (recipe.epoch.clone(), recipe.pkgver.clone(), recipe.pkgrel.clone(), Vec::new()), }; let digests = resolve_sources(cfg, db, &mirror, head, &tree, &recipe, &pins)?; let identity = Identity { aur_commit: head.to_string(), epoch: epoch.clone(), pkgver: pkgver.clone(), pkgrel: 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: epoch.clone(), pkgver: pkgver.clone(), pkgrel: 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. let up = upsert_candidate(db, pb, None, &nc)?; score(db, cfg, pb, &recipe, &digests, None, candidate_id_of(&up)); return Ok(report(outcome_of(up))); }; // 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)?; score(db, cfg, pb, &recipe, &digests, Some(&base), candidate_id_of(&up)); Ok(report(outcome_of(up))) } fn candidate_id_of(up: &Upsert) -> Option { match up { Upsert::Created { id, .. } | Upsert::Collapsed { id, .. } | Upsert::Superseded { new: id, .. } => Some(*id), Upsert::PreviouslyRejected | Upsert::Unchanged => None, } } /// Advisory risk scoring (§6). Best-effort: a scoring failure must never lose a /// candidate, so this logs rather than propagates. fn score( db: &Db, cfg: &Config, pb: &Pkgbase, recipe: &Recipe, digests: &[SourceDigest], accepted: Option<&ReleaseRow>, candidate_id: Option, ) { let Some(id) = candidate_id else { return }; if let Ok(a) = crate::review::risk::assess(db, cfg, pb, recipe, digests, accepted) { let _ = crate::review::candidates::set_risk(db, id, &a.level, &a.signals); } } 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). // A VCS source's digest *is* its pin, so upstream moving shows up there too // — but that is ordinary drift, handled by the pin check below, not an // integrity event. Integrity means "the bytes we built are gone and the // version says nothing moved", which only applies to fixed downloads. let vcs_indices: std::collections::BTreeSet = recipe .source_entries .iter() .filter(|e| e.is_vcs()) .map(|e| e.index) .collect(); let changed_remote: Vec<&SourceDigest> = new_digests .iter() .filter(|n| n.kind != "local" && !vcs_indices.contains(&n.index)) .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. 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!({}) }) }