//! Approval semantics (§7.1, §7.1a, §7.2) and the CLI approval path (P0). //! //! The rule these tests exist to protect: **we build exactly what was displayed, //! or nothing.** An approval that does not match the hashes of what the reviewer //! was shown is refused, never retargeted. mod common; use aur_build::db::model::*; use aur_build::review::{approve::Stale, approve::*, candidates, diff}; use common::*; /// Detect, open the review, and render it the way a reviewer opening the page /// would — returning the candidate plus the two hashes an approval must echo. fn open_review(env: &Env, name: &str) -> (CandidateRow, String) { aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, name).unwrap(); let c = candidates::pending_candidates(&env.db).unwrap().remove(0); let dd = diff::render_and_store(&env.db, &env.cfg, &c).unwrap(); (c, dd) } #[test] fn approve_writes_an_immutable_row_carrying_both_hashes() { let (env, _fx) = env_with_fixture("plain-make"); let (c, dd) = open_review(&env, "plain-make"); let a = approve(&env.db, "tester", c.id, &c.identity_hash, &dd, None).unwrap(); assert_eq!(a.decision, "approved"); assert_eq!(a.identity_hash, c.identity_hash); assert_eq!(a.diff_digest, dd); // The row itself records them, so "the human approved *this* diff" is // provable later (§7.2). let stored: (String, String, Option) = env .db .read(|c| { Ok(c.query_row( "SELECT identity_hash, diff_digest, note FROM approval WHERE id=?1", rusqlite::params![a.id], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)), )?) }) .unwrap(); assert_eq!(stored.0, c.identity_hash); assert_eq!(stored.1, dd); // Approvals are append-only: the audit trigger rejects any edit (§10 I10). let err = env .db .writer .tx_for_tests(move |tx| { tx.execute("UPDATE approval SET note='rewritten' WHERE id=1", [])?; Ok(()) }) .err(); assert!(err.is_some(), "approval rows must be immutable"); // And the human action is in the audit log. let actions: Vec = env .db .read(|c| { let mut st = c.prepare("SELECT action FROM audit ORDER BY id")?; let rows = st.query_map([], |r| r.get::<_, String>(0))?; Ok(rows.filter_map(|r| r.ok()).collect()) }) .unwrap(); assert!(actions.iter().any(|a| a == "approve"), "{actions:?}"); } #[test] fn a_stale_identity_hash_is_refused() { let (env, fx) = env_with_fixture("plain-make"); let (c, dd) = open_review(&env, "plain-make"); // AUR moves while the reviewer is reading: the candidate collapses in place // and its identity changes under them. fx.bump(&[("pkgver", "2.0")]); aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, "plain-make").unwrap(); let now = candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap(); assert_ne!(now.identity_hash, c.identity_hash, "identity should have moved"); let err = approve(&env.db, "tester", c.id, &c.identity_hash, &dd, None).unwrap_err(); assert!(matches!(err, Stale::Identity { .. }), "{err:?}"); assert_eq!( env.query_i64("SELECT count(*) FROM approval", &[]), Some(0), "a refused approval must leave nothing behind" ); // Approving with the *current* identity succeeds: the reviewer just has to // look at what is on screen now. let dd2 = diff::render_and_store(&env.db, &env.cfg, &now).unwrap(); approve(&env.db, "tester", c.id, &now.identity_hash, &dd2, None).unwrap(); } #[test] fn a_stale_diff_digest_is_refused() { let (env, _fx) = env_with_fixture("plain-make"); let (c, dd) = open_review(&env, "plain-make"); let err = approve(&env.db, "tester", c.id, &c.identity_hash, "sha256:whatever", None).unwrap_err(); assert!(matches!(err, Stale::Diff { .. }), "{err:?}"); assert_eq!(env.query_i64("SELECT count(*) FROM approval", &[]), Some(0)); let _ = dd; } #[test] fn approving_twice_is_refused_not_duplicated() { let (env, _fx) = env_with_fixture("plain-make"); let (c, dd) = open_review(&env, "plain-make"); approve(&env.db, "tester", c.id, &c.identity_hash, &dd, None).unwrap(); let err = approve(&env.db, "tester", c.id, &c.identity_hash, &dd, None).unwrap_err(); assert!(matches!(err, Stale::NotPending { .. }), "{err:?}"); assert_eq!(env.query_i64("SELECT count(*) FROM approval", &[]), Some(1)); } #[test] fn collapse_in_place_bumps_revision_without_a_new_row() { let (env, fx) = env_with_fixture("plain-make"); let (c, _dd) = open_review(&env, "plain-make"); let first = c.revision; assert!(c.viewed_at.is_none(), "render_and_store must not mark it viewed"); // Nobody has looked at it: the new upstream state collapses *into* the open // review instead of queueing beside it (§7.1). fx.bump(&[("pkgver", "2.0")]); aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, "plain-make").unwrap(); let after = candidates::pending_candidates(&env.db).unwrap(); assert_eq!(after.len(), 1, "still exactly one open review (I7)"); assert_eq!(after[0].id, c.id, "same row, not a new one"); assert!(after[0].revision > first, "revision bumped: {}", after[0].revision); assert_eq!(after[0].pkgver, "2.0"); assert_eq!( env.query_i64("SELECT count(*) FROM candidate WHERE pkgbase_id=?1", ¶ms(vec![after[0].pkgbase_id])), Some(1) ); } #[test] fn once_viewed_a_new_state_freezes_the_old_one_as_superseded() { let (env, fx) = env_with_fixture("plain-make"); let (c, _dd) = open_review(&env, "plain-make"); candidates::mark_viewed(&env.db, c.id).unwrap(); fx.bump(&[("pkgver", "3.0")]); aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, "plain-make").unwrap(); let open = candidates::pending_candidates(&env.db).unwrap(); assert_eq!(open.len(), 1); assert_ne!(open[0].id, c.id, "a fresh review was opened"); let frozen = candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap(); assert_eq!(frozen.state, candidate_state::SUPERSEDED); // The frozen one can no longer be approved: approving it would build a // version nobody is looking at. let err = approve(&env.db, "tester", c.id, &frozen.identity_hash, &frozen.diff_digest, None).unwrap_err(); assert!(matches!(err, Stale::NotPending { .. }), "{err:?}"); } #[test] fn a_rejected_identity_is_not_re_raised() { let (env, _fx) = env_with_fixture("plain-make"); let (c, _dd) = open_review(&env, "plain-make"); reject(&env.db, "tester", c.id, "not this").unwrap(); // Same upstream state, polled again: nothing new to review. aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, "plain-make").unwrap(); assert!(candidates::pending_candidates(&env.db).unwrap().is_empty()); // A different identity is a different question, and gets its own review. let err = approve(&env.db, "tester", c.id, &c.identity_hash, &c.diff_digest, None).unwrap_err(); assert!(matches!(err, Stale::NotPending { .. })); } #[test] fn reject_requires_a_reason_and_records_it() { let (env, _fx) = env_with_fixture("plain-make"); let (c, _dd) = open_review(&env, "plain-make"); reject(&env.db, "tester", c.id, "upstream dropped the license we rely on").unwrap(); let cid = c.id; let note: String = env .db .read(|c| { Ok(c.query_row( "SELECT note FROM approval WHERE candidate_id=?1", rusqlite::params![cid], |r| r.get(0), )?) }) .unwrap(); assert!(note.contains("license"), "{note}"); } // ------------------------------------------------------------- the CLI path -- /// Drive the real binary the way an operator would. This is the P0 approval /// path: `init`, `subscribe`, `detect`, `show`, `approve --yes`. #[test] fn cli_end_to_end_approves_and_queues_a_build() { let tmp = tempfile::tempdir().unwrap(); let root = tmp.path().join("root"); let (aur, _fx) = cli_fixture(tmp.path(), "plain-make"); let bin = env!("CARGO_BIN_EXE_aur-build"); let out = cli(bin, &root, &["init", "--repo", "aurbuild"]); assert!(out.status.success(), "init: {}", out.stderr); assert!(root.join("config.json").exists()); let url = format!("file://{}", aur.display()); let out = cli(bin, &root, &["subscribe", "plain-make", "--url", &url]); assert!(out.status.success(), "subscribe: {}", out.stderr); let out = cli(bin, &root, &["detect", "plain-make"]); assert!(out.status.success(), "detect: {}", out.stderr); let out = cli(bin, &root, &["reviews"]); assert!(out.stdout.contains("#1"), "reviews: {}", out.stdout); // `show` renders the panels and the hashes; `approve` without --yes refuses // to act, which is the CLI's version of "look before you approve". let out = cli(bin, &root, &["show", "1"]); assert!(out.stdout.contains("identity_hash"), "show: {}", out.stdout); let shown = out.stdout.clone(); let out = cli(bin, &root, &["approve", "1"]); assert!(out.stdout.contains("not approved"), "approve w/o --yes: {}", out.stdout); assert_eq!(cli_count(&root, "approval"), 0); let out = cli(bin, &root, &["approve", "1", "--yes", "--note", "looked at it"]); assert!(out.status.success(), "approve: {}", out.stderr); assert!(out.stdout.contains("approved #1"), "approve: {}", out.stdout); assert!(out.stdout.contains("queued build"), "approve should queue: {}", out.stdout); assert_eq!(cli_count(&root, "approval"), 1); assert_eq!(cli_count(&root, "build"), 1); assert!(shown.contains("PKGBUILD") || shown.contains("pkgver"), "diff pane: {shown}"); // Approving the same review again is refused with a non-zero status. let out = cli(bin, &root, &["approve", "1", "--yes"]); assert_eq!(out.code, Some(2), "stale approval should exit 2: {:?}", out); } #[test] fn cli_approve_refuses_a_hash_that_was_never_shown() { let tmp = tempfile::tempdir().unwrap(); let root = tmp.path().join("root"); let (aur, _fx) = cli_fixture(tmp.path(), "plain-make"); let bin = env!("CARGO_BIN_EXE_aur-build"); cli(bin, &root, &["init"]); let url = format!("file://{}", aur.display()); cli(bin, &root, &["subscribe", "plain-make", "--url", &url]); cli(bin, &root, &["detect", "plain-make"]); let out = cli(bin, &root, &["approve", "1", "--yes", "--identity", "sha256:invented", "--diff", "sha256:invented"]); assert_eq!(out.code, Some(2), "must refuse: {:?}", out); assert!(out.stderr.contains("refused"), "stderr: {}", out.stderr); assert_eq!(cli_count(&root, "approval"), 0); } #[derive(Debug)] struct Out { status: std::process::ExitStatus, stdout: String, stderr: String, code: Option, } fn cli(bin: &str, root: &std::path::Path, args: &[&str]) -> Out { let out = std::process::Command::new(bin) .arg("--root") .arg(root) .args(args) .output() .expect("run aur-build"); Out { code: out.status.code(), status: out.status, stdout: String::from_utf8_lossy(&out.stdout).into_owned(), stderr: String::from_utf8_lossy(&out.stderr).into_owned(), } } /// A local git repo standing in for AUR, so the CLI test needs no network. fn cli_fixture(root: &std::path::Path, name: &str) -> (std::path::PathBuf, Fixture) { let fx = materialize_fixture(root, name); (fx.aur.clone(), fx) } /// Query the CLI's own database through a throwaway read connection. fn cli_count(root: &std::path::Path, table: &str) -> i64 { let conn = rusqlite::Connection::open_with_flags( root.join("aur-build.db"), rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY, ) .expect("open cli db"); conn.query_row(&format!("SELECT count(*) FROM {table}"), [], |r| r.get::<_, i64>(0)) .unwrap() }