diff options
| author | aur-build <aur-build@localhost> | 2026-11-19 11:17:27 +0000 |
|---|---|---|
| committer | aur-build <aur-build@localhost> | 2026-11-19 11:17:27 +0000 |
| commit | bc8f069d18c5de3dee04ae303227a255248efc1e (patch) | |
| tree | 35143f64346a2a555672789ae33cbf0905bffc0b | |
| parent | 99ad2034be8fc5b107205199e19da831596a6791 (diff) | |
| download | aur-build-bc8f069d18c5de3dee04ae303227a255248efc1e.tar.gz aur-build-bc8f069d18c5de3dee04ae303227a255248efc1e.zip | |
pipeline: replace the devtools chroot with pinned pacman -U provisioning
The chroot step existed to run mkarchroot/makechrootpkg, whose sudo
requirement was the whole reason a build had to run on the hub under
root-adjacent rules. The sandbox model makes the chroot redundant: the
sandbox boots from a base that already carries the official packages,
and step 2 now provisions it with a lease manifest instead — every
dependency we publish, pinned to the exact version and digest of the
artifact the index serves. The hub re-hashes every blob before staging
it, installs with pacman -U (no -Sy, no live resolution, no mirror at
build time), and the sandbox's own pacman -Q must confirm the pinned
world landed before a build may start. A byte that hashes differently,
or a world that drifted, fails closed.
The build step is now plain makepkg -c -f: no -s (dependencies arrive
installed; resolving at build time is what the pinning model forbids)
and no -si (ingest signs). mkarchroot/makechrootpkg are gone from the
pipeline and the config; their shims stay as stand-ins for the real
devtools so the shim protocol itself remains exercised. The shim pacman
grew a real fake installed-database: -U refuses bytes that do not hash
to the digest their name claims, -Q reports what landed, so the world
check is a test and not a no-op.
| -rw-r--r-- | src/config.rs | 33 | ||||
| -rw-r--r-- | src/db/queries.rs | 18 | ||||
| -rw-r--r-- | src/pipeline/steps.rs | 147 | ||||
| -rw-r--r-- | src/sandbox/loopback.rs | 30 | ||||
| -rw-r--r-- | src/sandbox/mod.rs | 5 | ||||
| -rw-r--r-- | src/shims/mod.rs | 114 | ||||
| -rw-r--r-- | tests/crash.rs | 20 | ||||
| -rw-r--r-- | tests/dispatch.rs | 8 | ||||
| -rw-r--r-- | tests/invariants.rs | 4 | ||||
| -rw-r--r-- | tests/pipeline.rs | 57 | ||||
| -rw-r--r-- | tests/shims.rs | 48 |
11 files changed, 374 insertions, 110 deletions
diff --git a/src/config.rs b/src/config.rs index 8e303d4..e544b2d 100644 --- a/src/config.rs +++ b/src/config.rs @@ -33,17 +33,10 @@ pub struct Config { pub git_bin: String, /// Path to the makepkg executable. pub makepkg_bin: String, - /// Path to makechrootpkg. - pub makechrootpkg_bin: String, - /// Path to mkarchroot. - pub mkarchroot_bin: String, - /// Package list handed to `mkarchroot` after the working directory, i.e. - /// what goes into the warm root. The default is the real devtools usage - /// (`mkarchroot <dir> base`); there is no `-N` flag on the real tool, so - /// hardcoding one would make the first real-chroot run fail on its first - /// step. Kept configurable because a site may want a smaller seed. - #[serde(default = "default_mkarchroot_args")] - pub mkarchroot_args: Vec<String>, + /// Path to pacman. The provisioning step installs the pinned lease set + /// with `pacman -U` inside the sandbox (§8); nothing resolves against a + /// live mirror at build time. + pub pacman_bin: String, /// Path to repo-add. pub repo_add_bin: String, /// Path to gpg. @@ -96,7 +89,7 @@ pub struct TestHooks { /// Abort publish at a named point so I4 (atomic publish) can be exercised /// for real: `before-rename` or `after-rename`. pub publish_fault: Option<String>, - /// The named shim must fail, e.g. `makechrootpkg`. + /// The named shim must fail, e.g. `makepkg`. pub shim_fail: Option<String>, /// The named shim SIGKILLs its parent — the process running the pipeline — /// mid-step. This is how a real crash is reproduced for I5: not a caught @@ -134,9 +127,7 @@ impl Default for Config { build_profile: "extra-x86_64".into(), git_bin: "git".into(), makepkg_bin: "makepkg".into(), - makechrootpkg_bin: "makechrootpkg".into(), - mkarchroot_bin: "mkarchroot".into(), - mkarchroot_args: default_mkarchroot_args(), + pacman_bin: "pacman".into(), repo_add_bin: "repo-add".into(), gpg_bin: "gpg".into(), build_user: String::new(), @@ -228,7 +219,6 @@ impl Config { self.store_dir(), self.log_dir(), self.repo_dir(), - self.chroot_dir(), ] { std::fs::create_dir_all(d)?; } @@ -295,20 +285,9 @@ impl Config { pub fn repo_db_name(&self) -> String { format!("{}.db", self.repo_name) } - /// Warm chroot seeds, one per profile (§8.3). - pub fn chroot_dir(&self) -> PathBuf { - self.root.join("chroot") - } - pub fn chroot_seed(&self, profile: &str) -> PathBuf { - self.chroot_dir().join(profile) - } } /// Filesystem-safe slug for a URL, used in cache filenames. -fn default_mkarchroot_args() -> Vec<String> { - vec!["base".to_string()] -} - pub fn slug(url: &str) -> String { url.chars() .map(|c| { diff --git a/src/db/queries.rs b/src/db/queries.rs index 62c1045..fe0518f 100644 --- a/src/db/queries.rs +++ b/src/db/queries.rs @@ -679,6 +679,24 @@ pub fn index_version(db: &Db, name: &str) -> Result<Option<String>> { }) } +/// The exact artifact we serve for a package name: `(version, digest)` of the +/// in-index row's artifact. This is what a build's lease manifest pins — the +/// dependency arrives as these bytes or the build fails closed (§8, +/// provisioning); nothing about it is re-resolved at build time. +pub fn index_artifact(db: &Db, name: &str) -> Result<Option<(String, String)>> { + db.read(|c| { + c.query_row( + "SELECT p.version, a.digest FROM package p + JOIN artifact a ON a.id = p.artifact_id + WHERE p.name=?1 AND p.state='in_index' ORDER BY p.id DESC LIMIT 1", + params![name], + |r| Ok((r.get(0)?, r.get(1)?)), + ) + .optional() + .map_err(Into::into) + }) +} + /// Is `name` one of the packages we publish? Used to filter world snapshots /// down to our own packages (§10.1). pub fn is_ours(db: &Db, name: &str) -> Result<bool> { diff --git a/src/pipeline/steps.rs b/src/pipeline/steps.rs index 89c01f2..c989476 100644 --- a/src/pipeline/steps.rs +++ b/src/pipeline/steps.rs @@ -16,7 +16,7 @@ pub fn run_step(ctx: &Ctx, step: &str) -> Result<StepResult> { match step { "materialize" => materialize(ctx), "plan" => plan(ctx), - "chroot" => chroot(ctx), + "chroot" => provision(ctx), "sources" => sources(ctx), "pkgver" => pkgver(ctx), "build" => build(ctx), @@ -113,26 +113,115 @@ fn plan(ctx: &Ctx) -> Result<StepResult> { Ok(StepResult::Done(Some(hash))) } -/// Step 2 — warm chroot seed, created once per profile and never mutated; each -/// build gets a copy-on-write snapshot from it (§8.3). -fn chroot(ctx: &Ctx) -> Result<StepResult> { - let seed = ctx.cfg.chroot_seed(&ctx.profile); - if !seed.exists() { - std::fs::create_dir_all(seed.parent().unwrap_or(&ctx.cfg.chroot_dir()))?; - // Real devtools usage: `mkarchroot [options] <working-dir> <packages...>`. - let mut argv = vec![ctx.cfg.mkarchroot_bin.clone(), seed.display().to_string()]; - argv.extend(ctx.cfg.mkarchroot_args.iter().cloned()); - let sbx = ctx.sandbox()?; - let out = sbx.run(&Cmd::new(argv), &mut |_| {})?; - if !out.success() { - return Err(Error::Subprocess { - cmd: ctx.cfg.mkarchroot_bin.clone(), - detail: String::from_utf8_lossy(&out.stderr).into_owned(), - }); +/// Step 2 — provision the sandbox with the pinned lease set. +/// +/// The devtools chroot is gone: the sandbox boots from a base that already +/// carries the official packages, and everything *we* publish that this build +/// needs arrives as content-addressed blobs installed with `pacman -U`. The +/// step id stays `chroot` in the checkpoint table — the DB does not care what +/// the string means, and renaming would strand every existing checkpoint row. +/// +/// Nothing is resolved at build time: the lease manifest is the plan, every +/// blob is re-hashed before it is staged, and the sandbox's own `pacman -Q` +/// must confirm the pinned world actually landed. A byte that hashes to +/// something else, or a world that drifted, fails the build closed. +fn provision(ctx: &Ctx) -> Result<StepResult> { + let lease = lease_manifest(ctx)?; + if lease.is_empty() { + return Ok(StepResult::Skipped("no of-our-packages dependencies to install".into())); + } + let sbx = ctx.sandbox()?; + for e in &lease { + let path = ctx.cfg.store_path(&e.digest); + // The hub hashes what it sends: store corruption is caught here, not + // discovered by a confused package manager inside the sandbox. + let (digest, _) = crate::hash::digest_file(&path)?; + if digest != e.digest { + return Err(Error::fail_closed(format!( + "lease artifact {}-{}: store bytes hash to {digest} but the index says {}", + e.name, e.version, e.digest + ))); } - ctx.log_line(&format!(" created chroot seed {}", seed.display())); + let mut f = std::fs::File::open(&path)?; + sbx.put(&e.digest, &mut f)?; } - Ok(StepResult::Done(Some(seed.display().to_string()))) + let mut argv = vec![ctx.cfg.pacman_bin.clone(), "-U".into(), "--noconfirm".into()]; + argv.extend(lease.iter().map(|e| format!("blob:{}", e.digest))); + let out = sbx.run(&Cmd::new(argv), &mut |_| {})?; + if !out.success() { + return Err(Error::fail_closed(format!( + "{} -U refused the lease set: {}", + ctx.cfg.pacman_bin, + tail(&out.stderr) + ))); + } + // Fail-closed world check: every pinned entry must be present in the + // sandbox at exactly the pinned version. The world we approved is the + // world we build in, or nothing. + let q = sbx.run(&Cmd::new(vec![ctx.cfg.pacman_bin.clone(), "-Q".into()]), &mut |_| {})?; + if !q.success() { + return Err(Error::fail_closed(format!( + "{} -Q failed: {}", + ctx.cfg.pacman_bin, + tail(&q.stderr) + ))); + } + let installed: std::collections::BTreeSet<(String, String)> = String::from_utf8_lossy(&q.stdout) + .lines() + .filter_map(|l| { + let mut it = l.split_whitespace(); + let (name, ver) = (it.next()?, it.next()?); + Some((name.to_string(), ver.to_string())) + }) + .collect(); + for e in &lease { + if !installed.contains(&(e.name.clone(), e.version.clone())) { + return Err(Error::fail_closed(format!( + "sandbox world is missing {}-{} after installing the lease set", + e.name, e.version + ))); + } + } + ctx.log_line(&format!( + " provisioned {} pinned package(s): {}", + lease.len(), + lease.iter().map(|e| format!("{}-{}", e.name, e.version)).collect::<Vec<_>>().join(", ") + )); + let world: Vec<(&str, &str)> = lease.iter().map(|e| (e.name.as_str(), e.version.as_str())).collect(); + Ok(StepResult::Done(Some(crate::hash::canonical_json(&world)?))) +} + +/// One pinned entry of the lease manifest. +#[derive(Debug, Clone)] +struct LeasePkg { + name: String, + version: String, + digest: String, +} + +/// The lease manifest: every dependency this build needs that we publish, +/// pinned to the exact version and digest of the artifact we serve. Official +/// packages are the base image's business — they arrive with the sandbox, and +/// pinning them is the hub's official-repo cache, not this step. Anything +/// unresolvable here would have been `plan()`'s problem (blocked, not built). +fn lease_manifest(ctx: &Ctx) -> Result<Vec<LeasePkg>> { + let recipe = recipe_at(&ctx.srcdir)?; + let mut wanted: Vec<String> = Vec::new(); + for list in [&recipe.depends, &recipe.makedepends, &recipe.checkdepends] { + wanted.extend(crate::pkgver::dep_names(list)); + } + wanted.sort(); + wanted.dedup(); + let mut out = Vec::new(); + for dep in wanted { + if dep == ctx.pb.name || recipe.pkgnames.contains(&dep) { + continue; // this build's own output is not its own dependency + } + if let Some((version, digest)) = db::index_artifact(&ctx.db, &dep)? { + out.push(LeasePkg { name: dep, version, digest }); + } + } + Ok(out) } /// Step 3 — make sure every source we reviewed is on disk and hashes to what the @@ -211,19 +300,13 @@ fn pkgver(ctx: &Ctx) -> Result<StepResult> { Ok(StepResult::Done(Some(text))) } -/// Step 5 — `makechrootpkg -c -r <chroot> -- -f`, with the log going to the -/// file the SSE tail reads. No `-si`: the build environment never holds the -/// signing key — packages are signed hub-side at ingest. +/// Step 5 — `makepkg -c -f` in the provisioned sandbox, with the log going to +/// the file the SSE tail reads. No `-s`: the lease set is already installed, +/// and a build that resolves dependencies at build time is exactly what the +/// pinning model forbids. No `-si`: the sandbox never holds the signing key; +/// ingest signs hub-side. fn build(ctx: &Ctx) -> Result<StepResult> { - let seed = ctx.cfg.chroot_seed(&ctx.profile); - let argv = vec![ - ctx.cfg.makechrootpkg_bin.clone(), - "-c".into(), - "-r".into(), - seed.display().to_string(), - "--".into(), - "-f".into(), - ]; + let argv = vec![ctx.cfg.makepkg_bin.clone(), "-c".into(), "-f".into()]; // Capture the child's output into the build log regardless of outcome — // the sandbox streams it here as it arrives, and the SSE tail reads the // same file. @@ -242,7 +325,7 @@ fn build(ctx: &Ctx) -> Result<StepResult> { drop(on_log); // closes the log file before the outcome is recorded if !out.success() { return Err(Error::Subprocess { - cmd: ctx.cfg.makechrootpkg_bin.clone(), + cmd: ctx.cfg.makepkg_bin.clone(), detail: tail(&out.stderr), }); } diff --git a/src/sandbox/loopback.rs b/src/sandbox/loopback.rs index 1b31b1a..8e9f52d 100644 --- a/src/sandbox/loopback.rs +++ b/src/sandbox/loopback.rs @@ -65,12 +65,30 @@ impl Sandbox for LoopbackSandbox { } fn run(&self, cmd: &Cmd, on_log: &mut dyn FnMut(&[u8])) -> Result<Exit> { - let argv0 = cmd - .argv - .first() - .ok_or_else(|| Error::invalid("sandbox command has no argv[0]"))?; - let mut c = std::process::Command::new(argv0); - c.args(&cmd.argv[1..]); + if cmd.argv.is_empty() { + return Err(Error::invalid("sandbox command has no argv[0]")); + } + // Expand `blob:<digest>` argv elements to the staged blob's path — + // the loopback sandbox's blob dir is "inside the sandbox" as much as + // anything here is. An unstaged blob is a caller bug and fails closed. + let mut argv: Vec<String> = Vec::with_capacity(cmd.argv.len()); + for a in &cmd.argv { + match a.strip_prefix("blob:") { + Some(digest) => { + let path = self.blob_path(digest)?; + if !path.exists() { + return Err(Error::fail_closed(format!( + "blob {digest} was never staged in sandbox {}", + self.id + ))); + } + argv.push(path.display().to_string()); + } + None => argv.push(a.clone()), + } + } + let mut c = std::process::Command::new(&argv[0]); + c.args(&argv[1..]); if let Some(dir) = &cmd.cwd { c.current_dir(dir); } diff --git a/src/sandbox/mod.rs b/src/sandbox/mod.rs index 18c98ad..5be5f4f 100644 --- a/src/sandbox/mod.rs +++ b/src/sandbox/mod.rs @@ -37,6 +37,11 @@ pub mod loopback; /// `Command`-shaped: a remote sandbox must never be handed a shell string, and /// the environment is the backend's business (see `Config::child_env`), not the /// caller's. +/// +/// An argv element of the form `blob:<digest>` names a content-addressed blob +/// staged with [`Sandbox::put`]: the backend expands it to wherever that blob +/// materializes inside the sandbox. Callers never name sandbox-local paths — +/// that is what keeps a loopback step byte-identical to a remote one. #[derive(Debug, Clone)] pub struct Cmd { pub argv: Vec<String>, diff --git a/src/shims/mod.rs b/src/shims/mod.rs index c1b169c..d0c253d 100644 --- a/src/shims/mod.rs +++ b/src/shims/mod.rs @@ -1,10 +1,13 @@ //! Toolchain shims (§16a). //! -//! The pipeline shells out to `mkarchroot`, `makechrootpkg`, `makepkg`, -//! `repo-add`, `gpg` and `pacman`. In test mode the harness prepends a directory -//! of fakes to `PATH`; each fake records its invocation, obeys a scripted -//! outcome from the fixture manifest, and emits plausible -//! `.PKGINFO`/`.BUILDINFO`/`.sig` output. +//! The pipeline shells out to `makepkg`, `pacman`, `repo-add` and `gpg` inside +//! a sandbox, and `git` outside it. In test mode the harness prepends a +//! directory of fakes to `PATH`; each fake records its invocation, obeys a +//! scripted outcome from the fixture manifest, and emits plausible +//! `.PKGINFO`/`.BUILDINFO`/`.sig` output. The `mkarchroot` and `makechrootpkg` +//! fakes remain as stand-ins for the real devtools — the pipeline stopped +//! calling them when builds moved to the provisioning model — so the shim +//! protocol itself stays exercised end to end. //! //! That is what makes the full step machine, checkpointing, lease/reaper //! recovery, publishing and index regeneration runnable in milliseconds on any @@ -208,7 +211,7 @@ pub fn run(tool: &str) -> i32 { "makepkg" => makepkg(&args, &m), "repo-add" => repo_add(&args, &m), "gpg" => gpg(&args), - "pacman" => Ok(0), + "pacman" => pacman(&args), other => Err(format!("no shim named {other}")), }; match r { @@ -247,15 +250,31 @@ pub fn mkarchroot(args: &[String]) -> Result<i32, String> { Ok(0) } -/// `makechrootpkg -c -r <chroot> -- -f`, run with cwd = the build dir. -/// -/// Emits one `.pkg.tar.zst` per package in the manifest into the current -/// directory, exactly where the real tool leaves them. +/// `makechrootpkg -c -r <chroot> -- ...`: the real tool's contract, kept as a +/// stand-in for direct shim tests. The pipeline no longer calls it — the build +/// step runs `makepkg` in the provisioned sandbox — so the package-emitting +/// logic lives in [`emit_packages`], shared with the `makepkg` shim. pub fn makechrootpkg(args: &[String], m: &Manifest) -> Result<i32, String> { + // The real tool reads a chroot root; asserting it keeps the fake honest + // about the real tool's contract. + if !args.iter().any(|a| a == "-r") { + return Err("makechrootpkg: expected -r <chroot>".into()); + } + // Sign only when the caller asked for it, like the real tool: signing is + // `-si<key>`/`-i`, and the pipeline stopped passing it when signing moved + // hub-side to ingest. A shim that signed anyway would hide that move from + // every test in the suite. + let wants_sig = args.iter().any(|a| a.starts_with("-si") || a == "-i" || a == "--sign"); + emit_packages(m, "makechrootpkg", wants_sig) +} + +/// The shared build emulation: emit one `.pkg.tar.zst` per manifest package +/// into the current directory, exactly where the real tools leave them. +pub fn emit_packages(m: &Manifest, tool: &str, wants_sig: bool) -> Result<i32, String> { for l in &m.log_lines { println!("{l}"); } - if forced_fail("makechrootpkg") || m.build == "fail" { + if forced_fail(tool) || m.build == "fail" { eprintln!("==> ERROR: A build function returned error."); return Ok(1); } @@ -263,29 +282,19 @@ pub fn makechrootpkg(args: &[String], m: &Manifest) -> Result<i32, String> { eprintln!("==> ERROR: A failure occurred in check()."); return Ok(1); } - // The pipeline always passes a chroot root; asserting it keeps the fake - // honest about the real tool's contract. - if !args.iter().any(|a| a == "-r") { - return Err("makechrootpkg: expected -r <chroot>".into()); - } let startdir = std::env::current_dir().map_err(|e| e.to_string())?; - // The real tool reads the PKGBUILD it was handed; we assert it is there so a - // broken materialize step cannot pass silently. + // The real tool reads the PKGBUILD it was handed; we assert it is there so + // a broken materialize step cannot pass silently. if !startdir.join("PKGBUILD").exists() { let found = std::fs::read_dir(&startdir) .map(|rd| rd.filter_map(|e| e.ok()).map(|e| e.file_name().to_string_lossy().into_owned()).collect::<Vec<_>>()) .unwrap_or_default(); return Err(format!( - "makechrootpkg: no PKGBUILD in {} (contains {found:?})", + "{tool}: no PKGBUILD in {} (contains {found:?})", startdir.display() )); } let pkgs = packages_to_emit(m, &startdir); - // Sign only when the caller asked for it, like the real tool: signing is - // `-si<key>`/`-i`, and the pipeline stopped passing it when signing moved - // hub-side to ingest. A shim that signed anyway would hide that move from - // every test in the suite. - let wants_sig = args.iter().any(|a| a.starts_with("-si") || a == "-i" || a == "--sign"); for p in &pkgs { let path = write_package(&startdir, p, m)?; println!("==> Creating package '{}'", path.file_name().unwrap().to_string_lossy()); @@ -489,11 +498,64 @@ pub fn makepkg(args: &[String], m: &Manifest) -> Result<i32, String> { } } } else { - // `makepkg -si` style: behave like a local build. - makechrootpkg(args, m) + // `makepkg -c -f` style: the pipeline's build step, running in the + // provisioned sandbox. No `-s` and no `-si` reach this shim, and the + // emulation does not care: dependencies and signatures are the hub's + // business now. + emit_packages(m, "makepkg", false) } } +/// `pacman -U <blobs...>` / `pacman -Q`: a fake installed database living in +/// the shim dir, so the provisioning step's world check runs against something +/// that behaves. +/// +/// `-U` refuses any file that does not hash to the digest its filename claims +/// — the same trust posture as the real signature check — and records each +/// package from its `.PKGINFO`. `-Q` then reports exactly what was installed, +/// which is what makes the pipeline's fail-closed world assertion a real test +/// rather than a no-op. +pub fn pacman(args: &[String]) -> Result<i32, String> { + if args.iter().any(|a| a == "-U") { + for path in args.iter().filter(|a| !a.starts_with('-')) { + let p = std::path::Path::new(path); + let claimed = p + .file_name() + .and_then(|s| s.to_str()) + .ok_or_else(|| format!("pacman: bad blob path {path}"))?; + let bytes = std::fs::read(p).map_err(|e| format!("pacman: {path}: {e}"))?; + if crate::hash::hex(&bytes) != claimed { + return Err(format!( + "pacman: {claimed} does not hash to the digest its name claims" + )); + } + let pkginfo = crate::pkginfo::pkginfo_text(&bytes)?; + let info = crate::pkginfo::parse_pkginfo(&pkginfo); + if let Some(db) = installed_db() { + use std::io::Write; + if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(db) { + let _ = writeln!(f, "{} {}", info.name, info.version); + } + } + println!(":: installing {}-{}", info.name, info.version); + } + return Ok(0); + } + if args.iter().any(|a| a == "-Q") { + if let Some(db) = installed_db() { + if let Ok(text) = std::fs::read_to_string(db) { + print!("{text}"); + } + } + return Ok(0); + } + Ok(0) +} + +fn installed_db() -> Option<std::path::PathBuf> { + std::env::var("AUR_SHIM_DIR").ok().map(|d| std::path::Path::new(&d).join("installed.txt")) +} + /// `repo-add [-s -p key -R] <db.tar.{gz,zst}> <pkg...>`: rebuild the database /// from the packages handed to it. /// diff --git a/tests/crash.rs b/tests/crash.rs index ca58a04..e1f856f 100644 --- a/tests/crash.rs +++ b/tests/crash.rs @@ -45,8 +45,8 @@ fn run_cli(env: &Env, args: &[&str]) -> std::process::Output { fn a_process_killed_mid_step_resumes_from_its_checkpoints_with_no_duplicate_work() { let (mut env, _fx) = env_with_fixture("plain-make"); let id = queued(&env, "plain-make"); - // The child will be murdered the moment it invokes makechrootpkg. - env.cfg.hooks.shim_kill_parent = Some("makechrootpkg".into()); + // The child will be murdered the moment it invokes makepkg. + env.cfg.hooks.shim_kill_parent = Some("makepkg".into()); env.cfg.save().unwrap(); let out = run_cli(&env, &["run", &id]); @@ -71,10 +71,10 @@ fn a_process_killed_mid_step_resumes_from_its_checkpoints_with_no_duplicate_work Some(StepState::Running), "the step that was running should be recorded as running" ); - assert_eq!( - builds::step_status(&env.db, &id, "chroot").unwrap(), - Some(StepState::Succeeded), - "the completed step before the crash must be checkpointed" + let chroot_status = builds::step_status(&env.db, &id, "chroot").unwrap(); + assert!( + chroot_status.is_some_and(|s| s.is_done()), + "the completed step before the crash must be checkpointed: {chroot_status:?}" ); assert!(db::accepted_release(&env.db, "plain-make").unwrap().is_none(), "nothing was published"); @@ -97,11 +97,11 @@ fn a_process_killed_mid_step_resumes_from_its_checkpoints_with_no_duplicate_work let shim = env.cfg.hooks.shim_dir.clone().unwrap(); assert_eq!( aur_build::shims::called_with(&shim, "mkarchroot", ""), - 1, - "the chroot step was checkpointed as done and must not run again" + 0, + "the provisioning model never calls devtools, before or after a crash" ); assert_eq!( - aur_build::shims::called_with(&shim, "makechrootpkg", ""), + aur_build::shims::called_with(&shim, "makepkg", ""), 2, "exactly one rebuild: the crashed attempt and the resumed one" ); @@ -147,7 +147,7 @@ fn a_failed_build_leaves_the_index_serving_the_old_version_and_says_so() { // v2 is approved and its build fails deterministically. fx.bump(&[("pkgver", "2.0")]); - env.set_shim_fail("makechrootpkg"); + env.set_shim_fail("makepkg"); let c2 = approved(&env, "plain-make"); let id2 = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c2).unwrap(); let out = pipeline::run(&env.cfg, &env.db, &id2).unwrap(); diff --git a/tests/dispatch.rs b/tests/dispatch.rs index 8c0e4ff..5f65b6f 100644 --- a/tests/dispatch.rs +++ b/tests/dispatch.rs @@ -178,13 +178,13 @@ fn a_transient_failure_is_retried_up_to_the_cap() { #[test] fn a_missing_toolchain_is_not_retried() { - // m-14: this used to be the transient test. A missing `makechrootpkg` + // m-14: this used to be the transient test. A missing `makepkg` // surfaces as an `Io` error, and `Io` used to mean "retry" — so a // misconfigured host or a full disk burned every attempt and then went // quiet. It is deterministic: the tool is not going to appear. let (mut env, _fx) = env_with_fixture("plain-make"); let id = queued_build(&env, "plain-make"); - env.cfg.makechrootpkg_bin = "/nonexistent/makechrootpkg-for-test".into(); + env.cfg.makepkg_bin = "/nonexistent/makepkg-for-test".into(); env.cfg.max_transient_attempts = 3; env.cfg.dispatch_tick_secs = 0; let pool = dispatch::Pool::spawn(Arc::new(env.cfg.clone()), env.db.clone()); @@ -231,7 +231,7 @@ fn a_reaped_build_resumes_at_the_next_incomplete_step_with_no_duplicate_work() { pipeline::run(&env.cfg, &env.db, &id).unwrap(), pipeline::Outcome::Failed { .. } )); - let builds_before = aur_build::shims::called_with(&env.cfg.hooks.shim_dir.clone().unwrap(), "makechrootpkg", ""); + let builds_before = aur_build::shims::called_with(&env.cfg.hooks.shim_dir.clone().unwrap(), "makepkg", ""); // The worker "died" at publish: the row is leased with a lease nobody will // extend. A fresh dispatcher reaps it and a worker finishes from the @@ -252,7 +252,7 @@ fn a_reaped_build_resumes_at_the_next_incomplete_step_with_no_duplicate_work() { assert_eq!(state, BuildState::Succeeded, "the resumed build did not finish"); assert_eq!( - aur_build::shims::called_with(&env.cfg.hooks.shim_dir.clone().unwrap(), "makechrootpkg", ""), + aur_build::shims::called_with(&env.cfg.hooks.shim_dir.clone().unwrap(), "makepkg", ""), builds_before, "I5: resuming must not rebuild" ); diff --git a/tests/invariants.rs b/tests/invariants.rs index 1f6f7f2..770966f 100644 --- a/tests/invariants.rs +++ b/tests/invariants.rs @@ -159,7 +159,7 @@ fn i5_resume_after_a_crash_repeats_no_completed_step() { pipeline::Outcome::Failed { .. } )); let shim = env.cfg.hooks.shim_dir.clone().unwrap(); - let builds_before = aur_build::shims::called_with(&shim, "makechrootpkg", ""); + let builds_before = aur_build::shims::called_with(&shim, "makepkg", ""); assert_eq!(builds_before, 2, "one build per attempted publish"); // "Restart" the worker on the same build row. @@ -169,7 +169,7 @@ fn i5_resume_after_a_crash_repeats_no_completed_step() { other => panic!("{other:?}"), } assert_eq!( - aur_build::shims::called_with(&shim, "makechrootpkg", ""), + aur_build::shims::called_with(&shim, "makepkg", ""), builds_before, "I5: resuming re-ran the build step" ); diff --git a/tests/pipeline.rs b/tests/pipeline.rs index 878c193..d4ef724 100644 --- a/tests/pipeline.rs +++ b/tests/pipeline.rs @@ -118,6 +118,57 @@ fn the_build_never_signs_ingest_does() { } #[test] +fn a_tampered_store_artifact_fails_the_lease_closed() { + // dep-client depends on plain-make, so its lease pins plain-make's exact + // artifact. Corrupt the store bytes after publication: provisioning + // re-hashes everything it stages and must refuse, not build against bytes + // that are not what the index — and the review behind it — approved. + let (env, _plain, _client) = env_with_two_fixtures("plain-make", "dep-client"); + let c = approve_fixture(&env, "plain-make"); + assert!(matches!(run_for(&env, &c), pipeline::Outcome::Succeeded { .. })); + + let c2 = approve_fixture(&env, "dep-client"); + let id2 = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c2).unwrap(); + + let (digest, path): (String, String) = env + .db + .read(|c| { + Ok(c.query_row("SELECT digest, path FROM artifact LIMIT 1", [], |r| { + Ok((r.get(0)?, r.get(1)?)) + })?) + }) + .unwrap(); + let original = std::fs::read(&path).unwrap(); + let mut tampered = original.clone(); + tampered[16] ^= 0xFF; + std::fs::write(&path, &tampered).unwrap(); + + match pipeline::run(&env.cfg, &env.db, &id2).unwrap() { + pipeline::Outcome::Failed { step, error, transient } => { + assert_eq!(step, "chroot", "provisioning is where the lie gets caught"); + assert!(error.contains("hash") && error.contains(&digest), "{error}"); + assert!(!transient, "a corrupt store is not a network hiccup"); + } + other => panic!("{other:?}"), + } + + // Restore the bytes and resume: the lease verifies, the sandbox's own + // `pacman -Q` confirms the pinned world landed, and the build completes — + // which is the happy provisioning path proven end to end as well. + std::fs::write(&path, &original).unwrap(); + assert!( + matches!(pipeline::run(&env.cfg, &env.db, &id2).unwrap(), pipeline::Outcome::Succeeded { .. }), + "the resumed build failed" + ); + assert!(in_index(&env).iter().any(|(n, _)| n == "dep-client")); + let shimlog = env.cfg.hooks.shim_dir.clone().unwrap(); + assert!( + aur_build::shims::called_with(&shimlog, "pacman", "-U") > 0, + "the dependency arrived as a pinned blob through pacman -U, not a live mirror" + ); +} + +#[test] fn i1_no_index_entry_without_an_approval() { let (env, _fx) = env_with_fixture("plain-make"); let c = approve_fixture(&env, "plain-make"); @@ -256,7 +307,7 @@ fn i5_a_restarted_build_resumes_at_the_next_incomplete_step() { pipeline::Outcome::Failed { .. } )); let builds_after_crash = - aur_build::shims::called_with(&env.cfg.hooks.shim_dir.clone().unwrap(), "makechrootpkg", ""); + aur_build::shims::called_with(&env.cfg.hooks.shim_dir.clone().unwrap(), "makepkg", ""); assert_eq!(builds_after_crash, 2, "one real build before the crash"); // "Restart": same build row, no fault. Steps 0-8 are checkpointed as @@ -267,7 +318,7 @@ fn i5_a_restarted_build_resumes_at_the_next_incomplete_step() { other => panic!("{other:?}"), } assert_eq!( - aur_build::shims::called_with(&env.cfg.hooks.shim_dir.clone().unwrap(), "makechrootpkg", ""), + aur_build::shims::called_with(&env.cfg.hooks.shim_dir.clone().unwrap(), "makepkg", ""), builds_after_crash, "I5: resuming must not rebuild" ); @@ -301,7 +352,7 @@ fn a_failed_build_leaves_the_previous_version_serving() { fx.bump(&[("pkgver", "1.0.1")]); let c2 = approve_pending(&env, "plain-make"); // The build itself fails this time. - env.set_shim_fail("makechrootpkg"); + env.set_shim_fail("makepkg"); let out = run_for(&env, &c2); match out { pipeline::Outcome::Failed { step, .. } => assert_eq!(step, "build"), diff --git a/tests/shims.rs b/tests/shims.rs index 3422500..b21efab 100644 --- a/tests/shims.rs +++ b/tests/shims.rs @@ -175,6 +175,54 @@ fn repo_add_writes_a_pacman_database() { } #[test] +fn pacman_u_verifies_digests_and_q_reports_the_world() { + // The provisioning step's fail-closed world check runs against this fake: + // `-U` must refuse bytes that do not hash to the digest their name claims, + // and `-Q` must report exactly what landed. + let tmp = tempfile::tempdir().unwrap(); + let log = tmp.path().join("shimlog"); + std::fs::create_dir_all(&log).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( + "makepkg", + &build, + &[("AUR_SHIM_MANIFEST", &fixture_manifest("plain-make")), ("AUR_SHIM_DIR", &log)], + &["-c", "-f"], + ); + let pkg = build.join("plain-make-1.0-1-x86_64.pkg.tar.zst"); + let bytes = std::fs::read(&pkg).unwrap(); + let blob = tmp.path().join(aur_build::hash::hex(&bytes)); + std::fs::write(&blob, &bytes).unwrap(); + + let (code, _, err) = shim( + "pacman", + tmp.path(), + &[("AUR_SHIM_DIR", &log)], + &["-U", "--noconfirm", &blob.display().to_string()], + ); + assert_eq!(code, 0, "{err}"); + + let (code, out, _) = shim("pacman", tmp.path(), &[("AUR_SHIM_DIR", &log)], &["-Q"]); + assert_eq!(code, 0); + assert!(out.contains("plain-make 1.0-1"), "the world check reads -Q: {out}"); + + // A blob whose bytes do not match the digest its name claims is refused + // like a bad signature: name it with some other digest's hex. + let bad = tmp.path().join(aur_build::hash::hex(b"some other artifact")); + std::fs::write(&bad, b"tampered").unwrap(); + let (code, _, err) = shim( + "pacman", + tmp.path(), + &[("AUR_SHIM_DIR", &log)], + &["-U", &bad.display().to_string()], + ); + assert_ne!(code, 0, "a digest mismatch must fail closed"); + assert!(err.contains("hash"), "{err}"); +} + +#[test] fn gpg_writes_a_detached_signature() { let tmp = tempfile::tempdir().unwrap(); let f = tmp.path().join("thing.pkg.tar.zst"); |
