summaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authoraur-build <aur-build@localhost>2026-11-18 07:29:07 +0000
committeraur-build <aur-build@localhost>2026-11-18 07:29:07 +0000
commit04b40812f3366c71bf1c99779f880cc74b7f9efa (patch)
tree79586843b34b5a1cf703e18f2b5a35dd6814e9d6 /src
parent0b3cb443e70b46ec61455255c3ddfc2a26997613 (diff)
downloadaur-build-04b40812f3366c71bf1c99779f880cc74b7f9efa.tar.gz
aur-build-04b40812f3366c71bf1c99779f880cc74b7f9efa.zip
review: advisory risk scoring and non-publishable change handling (§6, §5.3, I11)
Every candidate is scored against the recipe the accepted release was actually built from (release -> candidate -> snapshot), never against 'last seen'. Signals: SKIP on a non-VCS source, a sum changed to SKIP, new source host, --skippgpcheck, removed validpgpkeys, new makedepends and fetching build tools (cargo/npm/go/pip), .install scripts, weakened options, removed checkdepends, pkgrel reset, epoch bump, downgrade, a diff touching build()/package() bodies rather than metadata, upstream ranges that touch a build-system file, and first introduction. Advisory only — there is no auto-approval, so a wrong score costs attention and never safety (§7.3). Fixes a fixture bug the new tests exposed: digest-drift and skip-checksum declared bare paths as sources, which parse as local recipe files rather than remote downloads, so the drift path never fired. They now use file:// URLs like a real remote would. tests/notices.rs: integrity_alert is high severity and leaves no candidate, pin_drift is informational, recipe drift under a static version is a warning, SKIP-on-non-VCS is a high risk signal, repeated polling of one drift is one notice, and an I11 sweep over twelve fixtures proving a change is never silently dropped.
Diffstat (limited to 'src')
-rw-r--r--src/db/queries.rs22
-rw-r--r--src/review/mod.rs1
-rw-r--r--src/review/risk.rs277
-rw-r--r--src/watch/detect.rs32
4 files changed, 328 insertions, 4 deletions
diff --git a/src/db/queries.rs b/src/db/queries.rs
index fe3109a..2bbd4c1 100644
--- a/src/db/queries.rs
+++ b/src/db/queries.rs
@@ -575,6 +575,28 @@ pub fn our_package_names(db: &Db) -> Result<std::collections::BTreeSet<String>>
})
}
+/// The recipe the accepted release was actually built from, by walking
+/// release -> candidate -> snapshot. Risk scoring compares against this, which
+/// is why "last seen" can never leak into a review (§6, I2).
+pub fn accepted_recipe(db: &Db, release: &ReleaseRow) -> Result<Option<Recipe>> {
+ let cid = match release.candidate_id {
+ Some(c) => c,
+ None => return Ok(None),
+ };
+ db.read(move |c| {
+ use rusqlite::OptionalExtension;
+ Ok(c.query_row(
+ "SELECT s.srcinfo_json FROM snapshot s
+ JOIN candidate cnd ON cnd.snapshot_id = s.id
+ WHERE cnd.id = ?1",
+ params![cid],
+ |r| r.get::<_, String>(0),
+ )
+ .optional()?
+ .and_then(|j| serde_json::from_str::<Recipe>(&j).ok()))
+ })
+}
+
// --------------------------------------------------------- stage B cache --
/// Exact cache hit: same recipe, same upstream tips (§5.2).
diff --git a/src/review/mod.rs b/src/review/mod.rs
index 25abca8..c8b2f50 100644
--- a/src/review/mod.rs
+++ b/src/review/mod.rs
@@ -4,5 +4,6 @@
pub mod approve;
pub mod candidates;
pub mod diff;
+pub mod risk;
pub use candidates::{upsert_candidate, NewCandidate, Upsert};
diff --git a/src/review/risk.rs b/src/review/risk.rs
new file mode 100644
index 0000000..b05604d
--- /dev/null
+++ b/src/review/risk.rs
@@ -0,0 +1,277 @@
+//! Advisory risk scoring (§6).
+//!
+//! The reviewer's attention is the scarcest resource in this system, so every
+//! candidate gets a computed level that orders and colours the inbox. It is
+//! **advisory only**: there is no auto-approval in v1 (§7.3), so nothing is
+//! gated on a score and no heuristic can let something through. A wrong score
+//! costs attention, never safety.
+//!
+//! Every signal is computed from what the accepted release recorded against
+//! what the candidate records now — the same "never last seen" rule that makes
+//! I2 true for the diff panels.
+
+use crate::db::{self, model::*, Db, Pkgbase};
+use crate::error::Result;
+use crate::pkgver;
+
+pub mod level {
+ pub const LOW: &str = "low";
+ pub const MEDIUM: &str = "medium";
+ pub const HIGH: &str = "high";
+}
+
+/// A build tool in `makedepends` means the build can fetch and compile anything
+/// (§16: we do not sandbox the network in v0, so the reviewer should see it).
+const FETCHING_BUILD_TOOLS: &[&str] = &["cargo", "npm", "go", "pip", "python", "ruby", "deno", "rust", "nodejs"];
+
+/// Files whose presence in an upstream commit range means the build itself
+/// changed, not just the code.
+const BUILD_SYSTEM_FILES: &[&str] = &[
+ "Cargo.toml", "Cargo.lock", "package.json", "setup.py", "pyproject.toml", "Makefile", "CMakeLists.txt",
+ "meson.build", "go.mod", "Gemfile", "build.gradle",
+];
+
+#[derive(Debug, Clone, Default)]
+pub struct Assessment {
+ pub level: String,
+ pub signals: Vec<String>,
+}
+
+impl Assessment {
+ pub fn is_high(&self) -> bool {
+ self.level == level::HIGH
+ }
+}
+
+/// Score a candidate against the release it would replace. `None` accepted
+/// means a first introduction, which is its own kind of review (§7.1b).
+pub fn assess(
+ db: &Db,
+ cfg: &crate::config::Config,
+ pb: &Pkgbase,
+ new: &Recipe,
+ new_digests: &[SourceDigest],
+ accepted: Option<&ReleaseRow>,
+) -> Result<Assessment> {
+ let mut s = SignalSet::default();
+ let old: Option<Recipe> = match accepted {
+ Some(r) => db::accepted_recipe(db, r)?,
+ None => None,
+ };
+
+ match &old {
+ None => s.add("first-introduction", level::MEDIUM),
+ Some(old) => {
+ compare_recipes(old, new, &mut s);
+ compare_digests(old, new, accepted.unwrap(), new_digests, &mut s);
+ }
+ }
+
+ // Things only visible from the recipe itself.
+ if new.skipgpcheck {
+ s.add("skippgpcheck", level::HIGH);
+ }
+ for idx in crate::watch::digests::skip_on_non_vcs(new) {
+ s.add(&format!("skip-checksum:source-{idx}"), level::HIGH);
+ }
+ for md in pkgver::dep_names(&new.makedepends) {
+ if FETCHING_BUILD_TOOLS.iter().any(|t| md.starts_with(t)) {
+ s.add(&format!("build-tool:{md}"), level::MEDIUM);
+ }
+ }
+ if new.install.is_some() {
+ // An `.install` script is arbitrary code that runs on every consumer
+ // machine at install time.
+ s.add("install-script", level::HIGH);
+ }
+ for opt in &new.options {
+ if matches!(opt.as_str(), "!debug" | "!strip" | "!buildflags" | "!security" | "!emptydirs") {
+ s.add(&format!("option:{opt}"), level::MEDIUM);
+ }
+ }
+
+ // Upstream movement that touches the build system (§6): the diff is in a
+ // language ecosystem we cannot inspect, so say so.
+ if let Some(a) = accepted {
+ for pin in accepted_pins(db, accepted) {
+ if let Some(old_pin) = a.pins().into_iter().find(|p| p.index == pin.index) {
+ if !old_pin.commit.is_empty()
+ && !pin.commit.is_empty()
+ && old_pin.commit != pin.commit
+ && upstream_touches_build_system(cfg, pb, &old_pin.commit, &pin.commit)
+ {
+ s.add("upstream-build-system", level::MEDIUM);
+ }
+ }
+ }
+ }
+
+ Ok(Assessment { level: s.level(), signals: s.signals })
+}
+
+fn accepted_pins(db: &Db, accepted: Option<&ReleaseRow>) -> Vec<UpstreamPin> {
+ let _ = db;
+ accepted.map(|a| a.pins()).unwrap_or_default()
+}
+
+fn compare_recipes(old: &Recipe, new: &Recipe, s: &mut SignalSet) {
+ // Version deltas.
+ if new.epoch != old.epoch && pkgver::vercmp(&new.epoch, &old.epoch) == std::cmp::Ordering::Greater {
+ s.add("epoch-bump", level::MEDIUM);
+ }
+ if new.pkgver == old.pkgver && pkgver::vercmp(&new.pkgrel, &old.pkgrel) == std::cmp::Ordering::Less {
+ s.add("pkgrel-reset", level::LOW);
+ }
+ if pkgver::is_downgrade(&old.pkgver, &new.pkgver) {
+ s.add("downgrade", level::MEDIUM);
+ }
+ // Sources: added/removed entries and host changes.
+ let old_hosts = hosts(&old.source);
+ let new_hosts = hosts(&new.source);
+ for h in &new_hosts {
+ if !old_hosts.contains(h) {
+ s.add(&format!("new-source-host:{h}"), level::HIGH);
+ }
+ }
+ if new.source.len() != old.source.len() {
+ s.add("source-set-changed", level::MEDIUM);
+ }
+ // Checksums weakening: a sum that existed and is now SKIP.
+ for (i, sum) in new.sha256sums.iter().enumerate() {
+ if sum.eq_ignore_ascii_case("SKIP") {
+ match old.sha256sums.get(i) {
+ Some(prev) if prev != "SKIP" && !prev.is_empty() => {
+ s.add(&format!("sums-to-skip:{i}"), level::HIGH)
+ }
+ _ => {}
+ }
+ }
+ }
+ if !old.validpgpkeys.is_empty() && new.validpgpkeys.is_empty() {
+ s.add("validpgpkeys-removed", level::HIGH);
+ }
+ // Dependencies.
+ let old_md: std::collections::BTreeSet<String> = pkgver::dep_names(&old.makedepends).into_iter().collect();
+ for md in pkgver::dep_names(&new.makedepends) {
+ if !old_md.contains(&md) {
+ s.add(&format!("new-makedepends:{md}"), level::MEDIUM);
+ }
+ }
+ let old_cd: std::collections::BTreeSet<String> = pkgver::dep_names(&old.checkdepends).into_iter().collect();
+ let new_cd: std::collections::BTreeSet<String> = pkgver::dep_names(&new.checkdepends).into_iter().collect();
+ if !old_cd.is_empty() && new_cd.is_empty() {
+ // Tests silently stopped running.
+ s.add("checkdepends-removed", level::MEDIUM);
+ }
+ // Did the executable part of the recipe change, or only metadata?
+ if body_changed(&old.pkgbuild, &new.pkgbuild) {
+ s.add("recipe-code-changed", level::HIGH);
+ }
+ if old.install != new.install {
+ s.add("install-script-changed", level::HIGH);
+ }
+}
+
+/// Digest comparison. Drift with no version change is an `integrity_alert`
+/// (§5.3) and never reaches here as a review, so anything that *does* show up
+/// alongside a version change is still worth saying.
+fn compare_digests(
+ _old: &Recipe,
+ _new: &Recipe,
+ accepted: &ReleaseRow,
+ new_digests: &[SourceDigest],
+ s: &mut SignalSet,
+) {
+ let old_digests = accepted.digests();
+ for n in new_digests {
+ if let Some(o) = old_digests.iter().find(|d| d.index == n.index) {
+ if o.digest != n.digest && !n.digest.is_empty() && o.kind != "local" {
+ s.add(&format!("digest-changed:source-{}", n.index), level::MEDIUM);
+ }
+ }
+ }
+}
+
+/// True when the diff touches a `build()`/`package()`/`prepare()`/`check()`
+/// body rather than only the variable assignments above them.
+fn body_changed(old_src: &str, new_src: &str) -> bool {
+ fn bodies(text: &str) -> String {
+ let mut out = String::new();
+ let mut inside = false;
+ for line in text.lines() {
+ let t = line.trim_start();
+ if t.starts_with("build()")
+ || t.starts_with("package")
+ || t.starts_with("prepare()")
+ || t.starts_with("check()")
+ {
+ inside = true;
+ }
+ if inside {
+ out.push_str(t);
+ out.push('\n');
+ }
+ }
+ out
+ }
+ bodies(old_src) != bodies(new_src)
+}
+
+fn hosts(sources: &[String]) -> std::collections::BTreeSet<String> {
+ sources
+ .iter()
+ .filter_map(|s| {
+ let s = s.rsplit("::").next().unwrap_or(s);
+ let s = s.rsplit('+').next().unwrap_or(s);
+ let rest = s.split("://").nth(1)?;
+ rest.split('/').next().map(|h| h.to_string())
+ })
+ .collect()
+}
+
+fn upstream_touches_build_system(cfg: &crate::config::Config, pb: &Pkgbase, from: &str, to: &str) -> bool {
+ // Best-effort: if we have the upstream clone cached we can ask it directly.
+ let cache = cfg.vcs_cache_dir();
+ if !cache.exists() {
+ return false;
+ }
+ let range = format!("{from}..{to}");
+ for dir in std::fs::read_dir(&cache).into_iter().flatten().filter_map(|d| d.ok()) {
+ let path = dir.path();
+ if let Ok(files) = crate::git::git(Some(&path), &["diff", "--name-only", &range]) {
+ if files.lines().any(|f| BUILD_SYSTEM_FILES.iter().any(|b| f.ends_with(b))) {
+ let _ = pb;
+ return true;
+ }
+ }
+ }
+ false
+}
+
+/// Accumulator that keeps the highest level seen and de-duplicates signals.
+#[derive(Debug, Default)]
+struct SignalSet {
+ level: String,
+ signals: Vec<String>,
+}
+
+impl SignalSet {
+ fn add(&mut self, signal: &str, lvl: &str) {
+ if !self.signals.contains(&signal.to_string()) {
+ self.signals.push(signal.to_string());
+ }
+ self.level = match (self.level.as_str(), lvl) {
+ (_, level::HIGH) | (level::HIGH, _) => level::HIGH,
+ (_, level::MEDIUM) | (level::MEDIUM, _) => level::MEDIUM,
+ _ => level::LOW,
+ }
+ .to_string();
+ }
+ fn level(&self) -> String {
+ if self.level.is_empty() {
+ level::LOW.to_string()
+ } else {
+ self.level.clone()
+ }
+ }
+}
diff --git a/src/watch/detect.rs b/src/watch/detect.rs
index d5f5c46..084052f 100644
--- a/src/watch/detect.rs
+++ b/src/watch/detect.rs
@@ -184,10 +184,9 @@ fn analyse(cfg: &Config, db: &Db, pb: &Pkgbase, head: &str) -> Result<CheckRepor
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))),
- };
+ 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.
@@ -221,9 +220,34 @@ fn analyse(cfg: &Config, db: &Db, pb: &Pkgbase, head: &str) -> Result<CheckRepor
}
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<i64> {
+ 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<i64>,
+) {
+ 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 },