diff options
Diffstat (limited to 'src')
| -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 |
6 files changed, 256 insertions, 91 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. /// |
