diff options
Diffstat (limited to 'tests')
| -rw-r--r-- | tests/common/mod.rs | 151 | ||||
| -rw-r--r-- | tests/shims.rs | 309 |
2 files changed, 460 insertions, 0 deletions
diff --git a/tests/common/mod.rs b/tests/common/mod.rs index b598b80..d5a4f81 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -22,6 +22,10 @@ impl Env { signing_key_id: "TESTKEY".into(), ..Config::default() }; + Self::with_cfg(tmp, cfg) + } + + pub fn with_cfg(tmp: tempfile::TempDir, cfg: Config) -> Self { cfg.ensure_dirs().expect("ensure_dirs"); db::migrate(&cfg.db_path()).expect("migrate"); let db = Db::open_migrated(&cfg.db_path()).expect("open db"); @@ -175,6 +179,153 @@ impl Drop for Env { } } +// ------------------------------------------------------------- fixtures ---- + +/// Root of the checked-in fake-package corpus (§16a). +pub fn corpus_root() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("testcorpus") +} + +/// Directory holding the shim executables cargo just built. Prepending this to +/// PATH is the whole test harness: the pipeline runs unmodified. +pub fn shim_dir() -> PathBuf { + Path::new(&env!("CARGO_BIN_EXE_makechrootpkg")) + .parent() + .unwrap() + .to_path_buf() +} + +/// An environment wired to one corpus fixture: the fixture is committed into a +/// real git repo standing in for AUR, an optional local upstream git repo exists +/// for VCS sources, and the shims are told to obey the fixture manifest. +pub fn env_with_fixture(name: &str) -> (Env, Fixture) { + let tmp = tempfile::tempdir().expect("tempdir"); + let fx = materialize_fixture(tmp.path(), name); + let cfg = Config { + root: tmp.path().to_path_buf(), + signing_key_id: "TESTKEY".into(), + path_prepend: Some(shim_dir()), + shim_manifest: Some(fx.manifest.clone()), + shim_dir: Some(tmp.path().join("shimlog")), + ..Config::default() + }; + std::fs::create_dir_all(cfg.shim_dir.as_ref().unwrap()).unwrap(); + cfg.ensure_dirs().unwrap(); + let env = Env::with_cfg(tmp, cfg); + env.subscribe(name); + (env, fx) +} + +/// Copy a corpus fixture into a server root: recipe files into a git repo that +/// stands in for AUR, payload files beside it so their bytes can be swapped, +/// and a local upstream repo when the recipe references one. +pub fn materialize_fixture(root: &Path, name: &str) -> Fixture { + let src = corpus_root().join(name); + assert!(src.exists(), "no fixture {name} in {}", corpus_root().display()); + let manifest = root.join("manifest.json"); + std::fs::copy(src.join("manifest.json"), &manifest).expect("copy manifest"); + + // Data files that a source URL points at live outside the recipe so a test + // can swap their bytes (the digest-drift case) without touching git. + let data = root.join(format!("fixture/{name}")); + std::fs::create_dir_all(&data).unwrap(); + let aur = root.join(format!("aur/{name}.git")); + std::fs::create_dir_all(&aur).unwrap(); + + let upstream = root.join(format!("upstream/{name}")); + let subs = [ + ("@AUR_DIR@".to_string(), data.display().to_string()), + ("@UPSTREAM_DIR@".to_string(), upstream.display().to_string()), + ]; + + let mut recipe_files: Vec<(String, String)> = Vec::new(); + let mut has_upstream_ref = false; + for entry in std::fs::read_dir(&src).unwrap() { + let path = entry.unwrap().path(); + let fname = path.file_name().unwrap().to_string_lossy().to_string(); + if fname == "manifest.json" { + continue; + } + let body = std::fs::read_to_string(&path).unwrap_or_default(); + let body = subs.iter().fold(body, |b, (from, to)| b.replace(from, to)); + has_upstream_ref |= body.contains(&upstream.display().to_string()); + if matches!(fname.as_str(), "payload.bin" | "data.bin") { + std::fs::write(data.join(&fname), &body).unwrap(); + } else { + recipe_files.push((fname, body)); + } + } + if has_upstream_ref { + make_git_repo(&upstream, &[("README", "upstream\n")], "upstream: initial"); + } + make_git_repo( + &aur, + &recipe_files.iter().map(|(n, b)| (n.as_str(), b.as_str())).collect::<Vec<_>>(), + "initial", + ); + Fixture { + name: name.to_string(), + src, + aur, + data, + manifest, + upstream: has_upstream_ref.then_some(upstream), + } +} + +pub struct Fixture { + pub name: String, + pub src: PathBuf, + pub aur: PathBuf, + pub data: PathBuf, + pub manifest: PathBuf, + pub upstream: Option<PathBuf>, +} + +impl Fixture { + /// Commit a new recipe revision, rewriting `pkgver`/`pkgrel`/`epoch`. + pub fn bump(&self, changes: &[(&str, &str)]) -> String { + let path = self.aur.join("PKGBUILD"); + let text = std::fs::read_to_string(&path).unwrap(); + let mut out = String::new(); + for line in text.lines() { + let key = line.split('=').next().unwrap_or("").to_string(); + match changes.iter().find(|(k, _)| *k == key) { + Some((_, v)) => out.push_str(&format!("{key}={v}\n")), + None => out.push_str(line), + } + out.push('\n'); + } + std::fs::write(&path, out).unwrap(); + git(&self.aur, &["add", "-A"]); + git(&self.aur, &["commit", "-q", "-m", "bump"]); + git(&self.aur, &["rev-parse", "HEAD"]) + } + + /// Swap the bytes behind a `SKIP` source without touching the recipe. + pub fn swap_payload(&self, body: &str) { + for f in ["payload.bin", "data.bin"] { + let p = self.data.join(f); + if p.exists() { + std::fs::write(p, body).unwrap(); + return; + } + } + panic!("fixture {} has no payload file", self.name); + } + + /// Add a commit to the local upstream repo (pin drift, §5.2). + pub fn upstream_commit(&self, body: &str) -> String { + let up = self.upstream.clone().expect("fixture has no upstream repo"); + git_add_commit(&up, &[("README", body)], body); + git(&up, &["rev-parse", "HEAD"]) + } + + pub fn manifest_json(&self) -> serde_json::Value { + serde_json::from_str(&std::fs::read_to_string(&self.manifest).unwrap()).unwrap() + } +} + /// A minimal PKGBUILD for tests that need recipe bytes without a fixture dir. pub fn pkgbuild(pkgbase: &str, pkgver: &str, pkgrel: &str, extra: &str) -> String { format!( diff --git a/tests/shims.rs b/tests/shims.rs new file mode 100644 index 0000000..f5cab7d --- /dev/null +++ b/tests/shims.rs @@ -0,0 +1,309 @@ +//! The §16a test harness itself: toolchain shims and the fake-package corpus. +//! +//! If these tests fail, nothing above the harness can be trusted. + +mod common; + +use std::path::{Path, PathBuf}; +use std::process::Command; + +use common::{corpus_root, env_with_fixture, shim_dir, Env}; + +use aur_build::shims; + +/// Run a shim binary with the harness protocol in the environment. +fn shim(tool: &str, cwd: &Path, envs: &[(&str, &Path)], args: &[&str]) -> (i32, String, String) { + let exe = shim_dir().join(tool); + assert!(exe.exists(), "shim {tool} not built at {}", exe.display()); + let out = Command::new(&exe) + .current_dir(cwd) + .envs( + envs + .iter() + .map(|(k, v)| (*k, v.as_os_str().to_os_string())), + ) + .args(args) + .output() + .expect("run shim"); + ( + out.status.code().unwrap_or(-1), + String::from_utf8_lossy(&out.stdout).into_owned(), + String::from_utf8_lossy(&out.stderr).into_owned(), + ) +} + +fn fixture_manifest(name: &str) -> PathBuf { + corpus_root().join(name).join("manifest.json") +} + +#[test] +fn makechrootpkg_emits_pkginfo_buildinfo_and_sig() { + let tmp = tempfile::tempdir().unwrap(); + let build = tmp.path().join("build"); + std::fs::create_dir_all(&build).unwrap(); + std::fs::write( + build.join("PKGBUILD"), + common::pkgbuild("plain-make", "1.0", "1", ""), + ) + .unwrap(); + let log = tmp.path().join("shimlog"); + std::fs::create_dir_all(&log).unwrap(); + + // Exactly the invocation §8.1 step 5 makes. + let chroot_args = ["-c", "-r", "chroot", "--", "-siTESTKEY", "-f"]; + let (code, out, err) = shim( + "makechrootpkg", + &build, + &[("AUR_SHIM_MANIFEST", &fixture_manifest("plain-make")), ("AUR_SHIM_DIR", &log)], + &chroot_args, + ); + assert_eq!(code, 0, "stdout={out} stderr={err}"); + + let pkg = build.join("plain-make-1.0-1-x86_64.pkg.tar.zst"); + assert!(pkg.exists(), "artifact left in the build dir like the real tool does"); + let bytes = std::fs::read(&pkg).unwrap(); + let pkginfo = shims::read_pkginfo(&bytes).unwrap(); + assert!(pkginfo.contains("pkgname = plain-make")); + assert!(pkginfo.contains("pkgver = 1.0-1")); + assert!(pkginfo.contains("pkgarch = x86_64")); + let buildinfo = shims::read_buildinfo(&bytes).unwrap(); + assert!(buildinfo.contains("format = 2")); + assert!(buildinfo.contains("installed ="), "BUILDINFO carries the chroot world (§10.1)"); + assert!(buildinfo.contains(" glibc 2.39-1 x86_64 -")); + assert!(build.with_extension("pkg.tar.zst.sig").exists() || pkg.with_extension("pkg.tar.zst.sig").exists()); + assert_eq!( + shims::invocations(&log) + .iter() + .filter(|e| e["tool"] == "makechrootpkg") + .count(), + 1, + "invocation recorded for the pipeline to assert on" + ); +} + +#[test] +fn makechrootpkg_refuses_a_missing_pkgbuild() { + // Step 0 materializes from the mirror; if that silently produced nothing, + // the fake tool must notice rather than build an empty package. + let tmp = tempfile::tempdir().unwrap(); + let build = tmp.path().join("build"); + std::fs::create_dir_all(&build).unwrap(); + let (code, _, err) = shim( + "makechrootpkg", + &build, + &[("AUR_SHIM_MANIFEST", &fixture_manifest("plain-make"))], + &["-c", "-r", "chroot"], + ); + assert_eq!(code, 1); + assert!(err.contains("no PKGBUILD"), "{err}"); +} + +#[test] +fn scripted_failures_are_honoured() { + for (fixture, expect) in [("build-fails", 1), ("check-fails", 1), ("plain-make", 0)] { + let tmp = tempfile::tempdir().unwrap(); + let build = tmp.path().join("build"); + std::fs::create_dir_all(&build).unwrap(); + std::fs::write( + build.join("PKGBUILD"), + std::fs::read_to_string(corpus_root().join(fixture).join("PKGBUILD")).unwrap(), + ) + .unwrap(); + let (code, _, err) = shim( + "makechrootpkg", + &build, + &[("AUR_SHIM_MANIFEST", &fixture_manifest(fixture))], + &["-c", "-r", "chroot"], + ); + assert_eq!(code, expect, "{fixture}: {err}"); + } +} + +#[test] +fn repo_add_writes_a_pacman_database() { + let tmp = tempfile::tempdir().unwrap(); + let build = tmp.path().join("build"); + std::fs::create_dir_all(&build).unwrap(); + std::fs::write(build.join("PKGBUILD"), common::pkgbuild("plain-make", "1.0", "1", "")).unwrap(); + shim( + "makechrootpkg", + &build, + &[("AUR_SHIM_MANIFEST", &fixture_manifest("plain-make"))], + &["-c", "-r", "chroot"], + ); + let pkg = build.join("plain-make-1.0-1-x86_64.pkg.tar.zst"); + + let db = tmp.path().join("aur-build.db.tar.gz"); + let out = Command::new(shim_dir().join("repo-add")) + .current_dir(tmp.path()) + .env("AUR_SHIM_MANIFEST", fixture_manifest("plain-make")) + .args(["-R", "-s", "-p", "TESTKEY", &db.display().to_string(), &pkg.display().to_string()]) + .output() + .unwrap(); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + assert!(db.exists(), "database written"); + + // The db is a gzip'd tar with one DESC per package — what pacman downloads. + let dec = flate2::read::GzDecoder::new(std::fs::File::open(&db).unwrap()); + let mut ar = tar::Archive::new(dec); + let names: Vec<String> = ar + .entries() + .unwrap() + .map(|e| e.unwrap().path().unwrap().display().to_string()) + .collect(); + assert!(names.iter().any(|n| n == "plain-make/DESC"), "{names:?}"); + let desc = { + let dec = flate2::read::GzDecoder::new(std::fs::File::open(&db).unwrap()); + let mut ar = tar::Archive::new(dec); + let mut found = String::new(); + for e in ar.entries().unwrap() { + let mut e = e.unwrap(); + if e.path().unwrap().ends_with("plain-make/DESC") { + use std::io::Read; + e.read_to_string(&mut found).unwrap(); + } + } + found + }; + assert!(desc.contains("%FILENAME%")); + assert!(desc.contains("plain-make-1.0-1-x86_64.pkg.tar.zst")); + assert!(desc.contains("%VERSION%\n1.0-1")); + assert!(desc.contains("%SHA256SUM%")); +} + +#[test] +fn gpg_writes_a_detached_signature() { + let tmp = tempfile::tempdir().unwrap(); + let f = tmp.path().join("thing.pkg.tar.zst"); + std::fs::write(&f, b"bytes").unwrap(); + let sig = tmp.path().join("thing.pkg.tar.zst.sig"); + let out = Command::new(shim_dir().join("gpg")) + .current_dir(tmp.path()) + .args(["--batch", "--detach-sign", "--output", &sig.display().to_string(), &f.display().to_string()]) + .output() + .unwrap(); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + let body = std::fs::read_to_string(&sig).unwrap(); + assert!(body.contains("PGP SIGNATURE")); + assert!(body.contains(&aur_build::hash::hex(b"bytes"))); +} + +#[test] +fn mkarchroot_creates_a_warm_root() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path().join("chroot/extra-x86_64"); + let out = Command::new(shim_dir().join("mkarchroot")) + .args(["-C", "/dev/null", &root.display().to_string()]) + .output() + .unwrap(); + assert!(out.status.success()); + assert!(root.join("SHIM-ROOT").exists()); +} + +/// Every fixture in the corpus must be drivable through the shims. This is the +/// executable documentation of the §16 edge cases. +#[test] +fn every_fixture_is_drivable_through_the_shims() { + let mut names = Vec::new(); + for entry in std::fs::read_dir(corpus_root()).unwrap() { + let dir = entry.unwrap().path(); + if !dir.is_dir() || !dir.join("manifest.json").exists() { + continue; + } + let name = dir.file_name().unwrap().to_string_lossy().to_string(); + names.push(name.clone()); + + let tmp = tempfile::tempdir().unwrap(); + let build = tmp.path().join("build"); + std::fs::create_dir_all(&build).unwrap(); + for f in std::fs::read_dir(&dir).unwrap() { + let p = f.unwrap().path(); + if p.file_name().unwrap() == "manifest.json" { + continue; + } + std::fs::copy(&p, build.join(p.file_name().unwrap())).unwrap(); + } + let manifest = dir.join("manifest.json"); + let want_fail = serde_json::from_str::<serde_json::Value>(&std::fs::read_to_string(&manifest).unwrap()) + .unwrap()["build"] + .as_str() + .unwrap_or("succeed") + != "succeed"; + let out = Command::new(shim_dir().join("makechrootpkg")) + .current_dir(&build) + .env("AUR_SHIM_MANIFEST", &manifest) + .args(["-c", "-r", "chroot", "--", "-siTESTKEY", "-f"]) + .output() + .unwrap(); + if want_fail { + assert!(!out.status.success(), "{name} should fail"); + } else { + assert!(out.status.success(), "{name}: {}", String::from_utf8_lossy(&out.stderr)); + let pkgs: Vec<_> = std::fs::read_dir(&build) + .unwrap() + .filter_map(|e| e.ok()) + .map(|e| e.file_name().to_string_lossy().into_owned()) + .filter(|n| n.ends_with(".pkg.tar.zst")) + .collect(); + assert!(!pkgs.is_empty(), "{name} produced no package"); + } + } + for required in [ + "plain-make", + "with-patch", + "install-hooks", + "skip-checksum", + "split-pkgbase", + "build-fails", + "check-fails", + "missing-dep", + "dep-cycle", + "epoch-bump", + "pkgrel-reset", + "downgrade", + "digest-drift", + "pin-drift", + "git-sourced", + "unresolvable", + ] { + assert!(names.iter().any(|n| n == required), "missing fixture {required}"); + } +} + +/// The corpus doubles as detection fixtures: each one must be detectable through +/// the real watcher against its local git repo. +#[test] +fn fixtures_are_detected_through_the_watcher() { + for name in ["plain-make", "with-patch", "install-hooks", "skip-checksum", "split-pkgbase", "epoch-bump"] { + let (env, _fx) = env_with_fixture(name); + let rep = aur_build::watch::check_pkgbase(&env.cfg, &env.db, name).unwrap(); + match &rep.outcome { + aur_build::watch::Outcome::Candidate { kind, .. } => { + assert_eq!(kind, "first_introduction", "{name}"); + } + other => panic!("fixture {name}: expected a first_introduction candidate, got {other:?}"), + } + assert!( + aur_build::db::unapproved_index_entries(&env.db).unwrap().is_empty(), + "detection alone must never touch the index (I1)" + ); + } +} + +#[test] +fn shim_environment_reaches_child_processes_through_the_config() { + let env = Env::new(); + let mut cfg = env.cfg.clone(); + cfg.path_prepend = Some(shim_dir()); + cfg.shim_manifest = Some(fixture_manifest("plain-make")); + cfg.shim_dir = Some(env.path("shimlog")); + std::fs::create_dir_all(env.path("shimlog")).unwrap(); + + // Prove the config is what puts the shims on PATH, not the test process env. + let mut cmd = Command::new("sh"); + cfg.child_env(&mut cmd); + let out = cmd.args(["-c", "command -v makechrootpkg; echo $AUR_SHIM_MANIFEST"]).output().unwrap(); + let s = String::from_utf8_lossy(&out.stdout); + assert!(s.contains("makechrootpkg"), "{s}"); + assert!(s.contains("manifest.json"), "{s}"); +} |
