diff options
Diffstat (limited to 'src/review/risk.rs')
| -rw-r--r-- | src/review/risk.rs | 277 |
1 files changed, 277 insertions, 0 deletions
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() + } + } +} |
