diff options
| -rw-r--r-- | README.md | 5 | ||||
| -rw-r--r-- | docs/DECISIONS.md | 48 | ||||
| -rw-r--r-- | src/pipeline/publish.rs | 147 | ||||
| -rw-r--r-- | src/shims/mod.rs | 41 | ||||
| -rw-r--r-- | tests/shims.rs | 118 |
5 files changed, 323 insertions, 36 deletions
@@ -83,7 +83,10 @@ make that possible (§16a): `.pkg.tar.zst` files with real `.PKGINFO` and `.BUILDINFO` inside them, and the fake `pacman -U` refuses bytes that do not hash to the digest their name claims. The step machine cannot tell it is not in a sandbox, - which is the point. + which is the point. Each shim is as strict as the tool it replaces — the + fake `repo-add` refuses a database filename the real one refuses — because a + shim that accepts more than its tool is how a broken publish path passes 200 + tests and then fails on a real package. * **The fixture corpus.** `testcorpus/` holds ~20 synthetic packages, each with a `PKGBUILD` and a manifest describing what the shims should emit: a split pkgbase, a build that fails, a recipe whose payload drifts under a `SKIP` diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 2861fed..bded52a 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -379,3 +379,51 @@ world mismatch rather than being helpfully fetched, which is correct here but depends on `plan()` computing the closure honestly. The shim `pacman` models all of this for real: `-U` refuses bytes that do not hash to the digest their name claims, and `-Q` reports exactly what landed. + +## repo-add names the database; the render happens in scratch space + +Publishing needs the index rendered *before* the DB transaction commits and +renamed into place *after* it, so a crash between the two leaves the old index +serving (I4). The obvious way to get that was to render to `<db>.tar.gz.tmp` +beside the live file and rename over it. That is also a filename real `repo-add` +refuses: its database argument has to be a name pacman would itself accept, and +a trailing `.tmp` is a usage error to it. Every publish test passed and the first +real package anyone tried to publish died at the last step, with the database +already committed and the served index untouched. + +**Choice.** `render_db` renders into a scratch directory *under* the served +directory — `.render-<pid>-<n>-<tag>/` — under the exact name a consumer will +download. Same filesystem, so the caller's `rename` is still the atomic swap I4 +requires, and the live database is never the file repo-add is writing into. The +scratch directory is removed on every path this code controls, and +`reconcile` sweeps leftovers at startup for the paths it does not. `run_repo_add` +also dropped `-s`: repo-add would sign the database into scratch space that is +about to be deleted, and `publish::sign` signs the renamed file — one key, one +code path, signature always over the bytes that shipped. + +**Cost.** Three call sites (`publish`, `reconcile`, `withdraw_package`) now share +the render helper instead of each doing its own tmp-and-rename, and a publish that +dies between render and rename leaves a directory for the next startup to sweep +rather than a single stray `.tmp` for a human to notice. + +## A shim is as strict as the tool it replaces, or it is not a test of it + +The `repo-add` shim wrote the database wherever it was told to. The real tool +validates the filename first. That asymmetry is the whole reason the previous +entry was possible: 200+ tests drove a real subprocess through a real publish and +reported success, because the fake accepted what the real thing rejects. + +**Choice.** The shim enforces the accepted set — `.db.tar` with or without a +compression suffix, nothing else, `.files.*` included in the refusals because +those belong to `repo-files` — with the real tool's wording and exit status. The +set was measured against `repo-add (pacman) 7.1.0`, not read out of its docs, and +`shims::repo_add_db_names_match_the_real_repo_add` re-derives it against the +installed tool whenever there is one, in the shape of the `vercmp` oracle test. +The same rule already holds elsewhere — the `pacman` shim refuses bytes that do +not hash to the digest their name claims — this is that rule, applied where it was +missing. + +**Cost.** The shim now rejects things the pipeline might one day want to do, and +the rejection has to be updated if pacman's rule changes. That is the correct +failure: a shim drifting from its tool should break a test loudly, not let a +production path go untested. diff --git a/src/pipeline/publish.rs b/src/pipeline/publish.rs index fd2fdd1..f8efeff 100644 --- a/src/pipeline/publish.rs +++ b/src/pipeline/publish.rs @@ -2,9 +2,9 @@ //! //! Publishing is the only externally visible step, and it is atomic and //! serialized per repo (I4). The served database is a materialized view of the -//! DB: we render it to `.tmp`, fsync, commit the DB, then `rename` over the real -//! one. A crash anywhere in there leaves the *old* index intact, and -//! [`reconcile`] re-materializes from the DB on startup. +//! DB: we render it in scratch space beside the live file, fsync, commit the DB, +//! then `rename` over the real one. A crash anywhere in there leaves the *old* +//! index intact, and [`reconcile`] re-materializes from the DB on startup. use std::collections::BTreeSet; use std::path::{Path, PathBuf}; @@ -20,8 +20,8 @@ use crate::time; /// One writer to the served repo at a time. /// /// This is *the* serialization guarantee for the index (§8.2, §9, I4): a publish -/// renders a new pacman database to `.tmp`, commits the DB, then renames over -/// the live one, and a second writer interleaving anywhere in that sequence +/// renders a new pacman database in scratch space, commits the DB, then renames +/// over the live one, and a second writer interleaving anywhere in that sequence /// would produce an index that matches neither DB state. It is held by /// [`publish`] for the whole of it — staging, render, DB commit, rename, sign — /// and by [`withdraw_package`] for the same reason. With @@ -61,7 +61,7 @@ pub fn index_world(db: &Db) -> Result<Vec<WorldMember>> { } /// Package files that belong in the served index right now, plus the extra ones -/// being published (which are not in the DB yet when we render `.tmp`). +/// being published (which are not in the DB yet when the new index is rendered). fn index_artifacts(db: &Db, extra: &[PathBuf]) -> Result<Vec<PathBuf>> { let mut out: Vec<PathBuf> = Vec::new(); for p in db::index_packages(db)? { @@ -91,6 +91,9 @@ pub fn publish(ctx: &Ctx) -> Result<i64> { // Artifacts are copied into the served tree under their real filenames. let mut staged: Vec<(PathBuf, PathBuf)> = Vec::new(); + // Set once the render starts, so the failure path below can sweep the scratch + // directory even when the publish died after repo-add returned. + let mut scratch_dir: Option<PathBuf> = None; // Files this publish created that were not there before. If the publish does // not land, they are orphans: no index names them and no consumer will ever // ask for them (§6 m-16). A file that already existed belongs to the release @@ -119,17 +122,16 @@ pub fn publish(ctx: &Ctx) -> Result<i64> { } let outcome = (|| -> Result<i64> { - // 1. render the new database to .tmp and fsync it. The old one is untouched. + // 1. render the new database and fsync it. The live one is untouched + // until step 3's rename. let db_name = ctx.cfg.repo_db_name(); let final_db = arch_dir.join(format!("{db_name}.tar.gz")); - let tmp_db = arch_dir.join(format!("{db_name}.tar.gz.tmp")); let mut pkgs = index_artifacts(&ctx.db, &staged.iter().map(|(d, _)| d.clone()).collect::<Vec<_>>())?; // Deduplicate: the same package name must appear once, newest wins. pkgs = dedupe_by_name(pkgs); - run_repo_add(&ctx.cfg, &tmp_db, &pkgs)?; - fsync_file(&tmp_db)?; + let rendered = render_db(&ctx.cfg, &arch_dir, "publish", &pkgs, &mut scratch_dir)?; - // Fault injection so I4 can be tested for real: die between the tmp write + // Fault injection so I4 can be tested for real: die between the render // and the rename, and the old index must still be what consumers get. // Compiled out of a production build (§6 M-9). #[cfg(feature = "test-support")] @@ -141,15 +143,9 @@ pub fn publish(ctx: &Ctx) -> Result<i64> { // transaction, with the pointer moved by compare-and-swap. let release_id = commit_release(ctx, &collect)?; - // 3. atomic swap: rename over the real database, then sign and swap the sig. - std::fs::rename(&tmp_db, &final_db)?; - fsync_dir(&arch_dir)?; + // 3. atomic swap: rename over the real database, then sign the new bytes. + rendered.swap_into(&final_db)?; sign(&ctx.cfg, &final_db)?; - let sig = arch_dir.join(format!("{db_name}.tar.gz.sig")); - let tmp_sig = arch_dir.join(format!("{db_name}.tar.gz.sig.tmp")); - if tmp_sig.exists() { - std::fs::rename(&tmp_sig, &sig)?; - } // 4. a publish can unblock builds waiting on a dependency we just added. let unblocked = builds::requeue_blocked(&ctx.db)?; @@ -178,6 +174,9 @@ pub fn publish(ctx: &Ctx) -> Result<i64> { for p in &fresh { let _ = std::fs::remove_file(p); } + if let Some(s) = &scratch_dir { + let _ = std::fs::remove_dir_all(s); + } } outcome } @@ -281,14 +280,93 @@ fn commit_release(ctx: &Ctx, collect: &Collect) -> Result<i64> { }) } -/// `repo-add -s -p <key> -R <db> <pkgs...>` (§9: both packages and the database -/// are signed so consumers can run `SigLevel = Required`). +/// Remove scratch directories a crash left behind. [`render_db`] cleans up after +/// itself on every path it controls; these are the ones it did not get to, and +/// they are unambiguous — the leading dot means nothing a consumer asks for, and +/// only a render creates one. +pub fn sweep_render_dirs(arch_dir: &Path) { + let Ok(entries) = std::fs::read_dir(arch_dir) else { + return; + }; + for entry in entries.flatten() { + if entry.file_name().to_string_lossy().starts_with(".render-") { + let _ = std::fs::remove_dir_all(entry.path()); + } + } +} + +/// A database repo-add has rendered, and the scratch directory it rendered into. +struct Rendered { + db: PathBuf, + dir: PathBuf, + arch_dir: PathBuf, +} + +impl Rendered { + /// The publish point: rename the rendered database over the live one, fsync + /// the directory entry, then drop the scratch directory. Before the rename a + /// consumer still gets the old index; after it, the new one. + fn swap_into(self, final_db: &Path) -> Result<()> { + std::fs::rename(&self.db, final_db)?; + fsync_dir(&self.arch_dir)?; + let _ = std::fs::remove_dir_all(&self.dir); + Ok(()) + } +} + +/// Render a fresh database with repo-add, ready to be renamed into place. +/// +/// repo-add refuses any database argument that is not a name pacman itself would +/// accept (`<repo>.db.tar.gz` and friends) — a `.tmp` suffix is a usage error to +/// it, not a convention. So the render cannot happen at `<db>.tar.gz.tmp` beside +/// the live file, which is what this code used to do: every publish of a real +/// package failed the moment it met a real repo-add, while 200+ tests stayed +/// green because the shim accepted any filename. It renders instead into a +/// scratch directory *under* the served directory, under the exact name a +/// consumer will download. Same filesystem, so the caller's `rename` is still the +/// atomic swap I4 requires, and the live database is never the file repo-add is +/// writing into. +/// +/// `scratch` is filled in as soon as the directory exists, so the caller can +/// sweep it even if this function is never reached again. +fn render_db( + cfg: &Config, + arch_dir: &Path, + tag: &str, + pkgs: &[PathBuf], + scratch: &mut Option<PathBuf>, +) -> Result<Rendered> { + static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let dir = arch_dir.join(format!(".render-{}-{n}-{tag}", std::process::id())); + std::fs::create_dir_all(&dir)?; + *scratch = Some(dir.clone()); + let db = dir.join(format!("{}.tar.gz", cfg.repo_db_name())); + let rendered = Rendered { db, dir, arch_dir: arch_dir.to_path_buf() }; + // Anything that can still fail lives here, so the scratch directory does not + // outlive the attempt on the error path. + let attempt = (|| -> Result<()> { + run_repo_add(cfg, &rendered.db, pkgs)?; + fsync_file(&rendered.db)?; + Ok(()) + })(); + if let Err(e) = attempt { + let _ = std::fs::remove_dir_all(&rendered.dir); + *scratch = None; + return Err(e); + } + Ok(rendered) +} + +/// `repo-add -R <db> <pkgs...>`. +/// +/// Deliberately *not* `-s`: repo-add would sign the database into whatever +/// directory it was rendered in, which is scratch space that gets deleted, and +/// the hub signs the live file itself in [`sign`] — one key, one code path, and +/// the signature is always over the bytes that were renamed into place (§9). fn run_repo_add(cfg: &Config, db_path: &Path, pkgs: &[PathBuf]) -> Result<()> { let mut cmd = Command::new(&cfg.repo_add_bin); cmd.arg("-R"); - if !cfg.signing_key_id.is_empty() { - cmd.args(["-s", "-p", &cfg.signing_key_id]); - } cmd.arg(db_path); for p in pkgs { cmd.arg(p); @@ -338,10 +416,10 @@ pub(crate) fn sign_to(cfg: &Config, path: &Path, sig_out: &Path) -> Result<()> { Ok(()) } -/// fsync, and *say so* when it fails (m-7). The whole point of writing to -/// `.tmp`, fsyncing, and renaming is the promise that a consumer never sees a -/// half-written database; swallowing the error made that a comment rather than -/// a guarantee — on a filesystem that refuses `fsync` (full, read-only, a +/// fsync, and *say so* when it fails (m-7). The whole point of writing to a +/// scratch file, fsyncing, and renaming is the promise that a consumer never +/// sees a half-written database; swallowing the error made that a comment rather +/// than a guarantee — on a filesystem that refuses `fsync` (full, read-only, a /// network mount that dropped), the rename still "succeeded". fn fsync_file(p: &Path) -> Result<()> { let f = std::fs::File::open(p) @@ -419,9 +497,10 @@ pub fn reconcile(cfg: &Config, db: &Db) -> Result<usize> { return Ok(0); } let arch_dir = cfg.repo_arch_dir(); - let tmp = arch_dir.join(format!("{}.tar.gz.tmp", cfg.repo_db_name())); - run_repo_add(cfg, &tmp, &dedupe_by_name(files.clone()))?; - std::fs::rename(&tmp, arch_dir.join(format!("{}.tar.gz", cfg.repo_db_name())))?; + sweep_render_dirs(&arch_dir); + let mut scratch = None; + let rendered = render_db(cfg, &arch_dir, "reconcile", &dedupe_by_name(files.clone()), &mut scratch)?; + rendered.swap_into(&arch_dir.join(format!("{}.tar.gz", cfg.repo_db_name())))?; Ok(files.len()) } @@ -432,10 +511,10 @@ pub fn withdraw_package(cfg: &Config, db: &Db, name: &str) -> Result<()> { let n = name.to_string(); db.writer.tx(move |tx| db::remove_package_by_name_in(tx, rid, &n))?; let arch_dir = cfg.repo_arch_dir(); - let tmp = arch_dir.join(format!("{}.tar.gz.tmp", cfg.repo_db_name())); + let mut scratch = None; let files = index_artifacts(db, &[])?; - run_repo_add(cfg, &tmp, &dedupe_by_name(files))?; - std::fs::rename(&tmp, arch_dir.join(format!("{}.tar.gz", cfg.repo_db_name())))?; + let rendered = render_db(cfg, &arch_dir, "withdraw", &dedupe_by_name(files), &mut scratch)?; + rendered.swap_into(&arch_dir.join(format!("{}.tar.gz", cfg.repo_db_name())))?; db::audit(&db.writer, "human", "cli", "withdraw.publish", "package", name, serde_json::json!({}))?; Ok(()) } diff --git a/src/shims/mod.rs b/src/shims/mod.rs index d0c253d..7118283 100644 --- a/src/shims/mod.rs +++ b/src/shims/mod.rs @@ -562,6 +562,38 @@ fn installed_db() -> Option<std::path::PathBuf> { /// The real tool appends; `-R` replaces an existing entry. We rebuild the whole /// db from the packages given, which is what our publish step does anyway (it /// passes exactly the packages that belong in the index). +/// The database filenames pacman's repo-add accepts — and therefore the ones +/// this shim must accept, and no others. +/// +/// A shim that is more permissive than the tool it stands in for is worse than no +/// shim: the pipeline used to render its database to `<db>.tar.gz.tmp` and rename +/// it into place, real repo-add rejects that filename as a usage error, and every +/// publish test in the suite passed because the shim would write anywhere. That +/// is how the first real package anyone tried to publish died at the last step. +/// This list is the accepted set as measured against `repo-add (pacman) 7.1.0`: +/// the `.db.tar` forms with or without a compression suffix, and nothing else — +/// not `aur.db`, not `aur.db.gz`, and not the `.files.*` forms, which belong to +/// `repo-files`. +pub const DB_SUFFIXES: [&str; 5] = [ + ".db.tar", + ".db.tar.gz", + ".db.tar.zst", + ".db.tar.bz2", + ".db.tar.xz", +]; + +/// Whether repo-add would accept this path as its database argument. +pub fn valid_db_arg(p: &Path) -> bool { + let name = p + .file_name() + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_default(); + !name.is_empty() + && DB_SUFFIXES + .iter() + .any(|sfx| name.ends_with(sfx)) +} + pub fn repo_add(args: &[String], _m: &Manifest) -> Result<i32, String> { // `-p <key>` and friends take a value; a naive filter would treat the key id // as a package path. @@ -584,6 +616,15 @@ pub fn repo_add(args: &[String], _m: &Manifest) -> Result<i32, String> { Some((db, rest)) => (PathBuf::from(db), rest.iter().map(|p| PathBuf::from(p.as_str())).collect::<Vec<_>>()), None => return Err("repo-add: no database given".into()), }; + if !valid_db_arg(&db_path) { + // Same wording and same exit status as the real tool, so a caller that + // learns to branch on one learns to branch on the other. + eprintln!( + "==> ERROR: '{}' does not have a valid database archive extension.", + db_path.display() + ); + return Ok(1); + } let mut ar = tar::Builder::new(Vec::new()); for pkg in &pkgs { let bytes = std::fs::read(pkg).map_err(|e| format!("repo-add: {}: {e}", pkg.display()))?; diff --git a/tests/shims.rs b/tests/shims.rs index b21efab..d512bd7 100644 --- a/tests/shims.rs +++ b/tests/shims.rs @@ -7,7 +7,7 @@ mod common; use std::path::{Path, PathBuf}; use std::process::Command; -use common::{corpus_root, env_with_fixture, shim_dir, Env}; +use common::{corpus_root, env_with_fixture, shim_dir, Env, Web}; use aur_build::shims; @@ -358,3 +358,119 @@ fn shim_environment_reaches_child_processes_through_the_config() { assert!(s.contains("makechrootpkg"), "{s}"); assert!(s.contains("manifest.json"), "{s}"); } + +// --------------------------------------------------------------------------- +// repo-add's database filename. +// +// The shim used to write the database wherever it was told to, and the pipeline +// took that literally: it rendered the index to `<db>.tar.gz.tmp` and renamed it +// into place. Real repo-add rejects that filename as a usage error, so every +// publish test in this suite passed while the first real package anyone tried to +// publish died at the last step. A shim must be as strict as the tool it stands +// in for, or it is not a test of the tool. +// --------------------------------------------------------------------------- + +/// Names pacman's repo-add accepts as its database argument, measured against +/// `repo-add (pacman) 7.1.0` rather than guessed from its docs. +const REAL_ACCEPTED: [&str; 5] = [ + "aur.db.tar", + "aur.db.tar.gz", + "aur.db.tar.zst", + "aur.db.tar.bz2", + "aur.db.tar.xz", +]; + +/// Names it refuses — including the render target the pipeline used to use, and +/// the `.files.*` forms, which are `repo-files`' business and not repo-add's. +const REAL_REJECTED: [&str; 5] = + ["aur.db", "aur.db.gz", "aur.db.tar.gz.tmp", "aur.files.tar.gz", "aur"]; + +#[test] +fn repo_add_shim_refuses_a_database_name_repo_add_refuses() { + let tmp = tempfile::tempdir().unwrap(); + for name in REAL_REJECTED { + let bad = tmp.path().join(name); + let (code, _, err) = shim("repo-add", tmp.path(), &[], &["-R", &bad.display().to_string()]); + assert_eq!(code, 1, "repo-add must fail on {name}, like the real tool"); + assert!( + err.contains("does not have a valid database archive extension"), + "{name}: {err}" + ); + assert!(!bad.exists(), "{name}: nothing may be written for a rejected name"); + } + for name in REAL_ACCEPTED { + let good = tmp.path().join(name); + let (code, _, err) = shim("repo-add", tmp.path(), &[], &["-R", &good.display().to_string()]); + assert_eq!(code, 0, "{name}: {err}"); + assert!(good.exists(), "{name}: a valid database name must be written"); + } +} + +/// The oracle, when the host has one: the shim's verdict must be the real tool's +/// verdict, name for name. Gated and noted rather than skipped silently, in the +/// shape of `versions::vercmp_matches_the_system_oracle`. +#[test] +fn repo_add_db_names_match_the_real_repo_add() { + if Command::new("repo-add").arg("--version").output().is_err() { + eprintln!("note: no real repo-add on PATH; the differential check is not running"); + return; + } + let tmp = tempfile::tempdir().unwrap(); + for name in REAL_ACCEPTED.into_iter().chain(REAL_REJECTED) { + let p = tmp.path().join(name); + let real = Command::new("repo-add") + .args(["-R", &p.display().to_string()]) + .output() + .unwrap(); + assert_eq!( + shims::valid_db_arg(&p), + real.status.success(), + "the shim and the real repo-add disagree about {name}" + ); + } +} + +/// The regression itself, asserted on the pipeline rather than on the shim: what +/// filename does publish actually hand repo-add, and does it clean up after +/// itself while doing it? +#[test] +fn publish_hands_repo_add_a_database_name_the_real_tool_accepts() { + let web = Web::new("plain-make"); + web.publish("plain-make"); + + let shim = web.env.cfg.hooks.shim_dir.clone().unwrap(); + let args = shims::invocations(&shim) + .into_iter() + .find(|e| e["tool"] == "repo-add") + .expect("publish must invoke repo-add") + .get("args") + .and_then(|a| a.as_array().cloned()) + .expect("the invocation log records args") + .iter() + .filter_map(|v| v.as_str().map(|s| s.to_string())) + .collect::<Vec<_>>(); + let db = args + .iter() + .find(|a| !a.starts_with('-')) + .expect("repo-add's first positional is the database"); + assert!( + shims::valid_db_arg(Path::new(db)), + "publish passed {db}, which repo-add would refuse" + ); + + // The render happens in a scratch directory beside the live database, under + // the name a consumer will download, and is gone once the rename lands. A + // leftover would mean a publish that died on a path that never cleaned up. + let arch = web.env.cfg.repo_arch_dir(); + let leftovers: Vec<String> = std::fs::read_dir(&arch) + .unwrap() + .flatten() + .map(|e| e.file_name().to_string_lossy().into_owned()) + .filter(|n| n.starts_with(".render-")) + .collect(); + assert!( + leftovers.is_empty(), + "scratch directories left behind in {}: {leftovers:?}", + arch.display() + ); +} |
