//! Shared test scaffolding: an isolated server root in a tempdir with a migrated //! database and a running writer actor. #![allow(dead_code)] use std::path::{Path, PathBuf}; use aur_build::config::Config; use aur_build::db::{self, Db}; pub struct Env { pub tmp: tempfile::TempDir, pub cfg: Config, pub db: Db, } impl Env { pub fn new() -> Self { let tmp = tempfile::tempdir().expect("tempdir"); let cfg = Config { root: tmp.path().to_path_buf(), 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"); let rid = db::ensure_repo( &db.writer, &cfg.repo_name, &cfg.repo_arch_dir().display().to_string(), &cfg.arch, &cfg.signing_key_id, ) .expect("repo row"); assert!(rid > 0); Self { tmp, cfg, db } } pub fn root(&self) -> &Path { self.tmp.path() } pub fn path(&self, p: &str) -> PathBuf { self.tmp.path().join(p) } /// Insert a pkgbase + active subscription and return the pkgbase id. pub fn subscribe(&self, name: &str) -> i64 { let rid = db::repo_id(&self.db).unwrap(); let url = format!("file://{}/aur/{}.git", self.root().display(), name); db::subscribe(&self.db.writer, rid, name, &url).unwrap(); db::get_pkgbase(&self.db, name).unwrap().unwrap().id } /// Drop a row back in via raw SQL (tests need to construct states the API /// only reaches through several steps). pub fn exec(&self, sql: &str, params: &[P]) -> usize { let sql = sql.to_string(); let params: Vec

= params.to_vec(); self.db .writer .tx(move |tx| { let refs: Vec<&dyn rusqlite::ToSql> = params .iter() .map(|p| match p { P::I(i) => i as &dyn rusqlite::ToSql, P::S(s) => s as &dyn rusqlite::ToSql, }) .collect(); Ok(tx.execute(&sql, rusqlite::params_from_iter(refs.iter()))?) }) .unwrap() } /// Stand in for the build+publish path: turn an approved candidate into a /// published release and move the accepted pointer. The real path lives in /// `pipeline`; detection tests need an accepted base without a build. pub fn accept_as_release(&self, candidate_id: i64) -> i64 { let at = "2026-01-01T00:00:00Z"; self.db .writer .tx(move |tx| { tx.execute( "INSERT INTO approval (candidate_id, base_release_id, decided_at, decision, risk_level, diff_digest, identity_hash) SELECT id, base_release_id, ?2, 'approved', risk_level, diff_digest, identity_hash FROM candidate WHERE id=?1", rusqlite::params![candidate_id, at], )?; let approval_id = tx.last_insert_rowid(); tx.execute( "INSERT INTO release (pkgbase_id, candidate_id, approval_id, aur_commit, recipe_hash, upstream_pins_json, source_digests_json, epoch, pkgver, pkgrel, state, published_at, created_at) SELECT c.pkgbase_id, c.id, ?2, s.aur_commit, s.recipe_hash, c.upstream_pins_json, c.source_digests_json, c.epoch, c.pkgver, c.pkgrel, 'published', ?3, ?3 FROM candidate c JOIN snapshot s ON s.id = c.snapshot_id WHERE c.id=?1", rusqlite::params![candidate_id, approval_id, at], )?; let release_id = tx.last_insert_rowid(); tx.execute( "UPDATE candidate SET state='approved', resolved_at=?1 WHERE id=?2", rusqlite::params![at, candidate_id], )?; tx.execute( "INSERT INTO package (repo_id, release_id, name, arch, version, state) SELECT (SELECT id FROM repo ORDER BY id LIMIT 1), ?1, b.name, 'x86_64', c.pkgver || '-' || c.pkgrel, 'in_index' FROM candidate c JOIN pkgbase b ON b.id = c.pkgbase_id WHERE c.id=?2", rusqlite::params![release_id, candidate_id], )?; tx.execute( "UPDATE pkgbase SET current_accepted_release_id=?1 WHERE id=(SELECT pkgbase_id FROM candidate WHERE id=?2)", rusqlite::params![release_id, candidate_id], )?; Ok(release_id) }) .unwrap() } /// Make the next publish abort at a named point (I4 / I5 tests). pub fn set_publish_fault(&mut self, at: &str) { self.cfg.publish_fault = Some(at.to_string()); } pub fn clear_publish_fault(&mut self) { self.cfg.publish_fault = None; } /// Make the named shim fail (the "build failed" path, §8.4). pub fn set_shim_fail(&mut self, tool: &str) { self.cfg.shim_fail = Some(tool.to_string()); } pub fn query_i64(&self, sql: &str, params: &[P]) -> Option { let sql = sql.to_string(); let params: Vec

= params.to_vec(); self.db .read(move |c| { let refs: Vec<&dyn rusqlite::ToSql> = params .iter() .map(|p| match p { P::I(i) => i as &dyn rusqlite::ToSql, P::S(s) => s as &dyn rusqlite::ToSql, }) .collect(); use rusqlite::OptionalExtension; Ok(c.query_row(&sql, rusqlite::params_from_iter(refs.iter()), |r| r.get::<_, i64>(0)) .optional()?) }) .unwrap() } } /// A test parameter. Owned so it can cross the writer-actor channel. #[derive(Debug, Clone)] pub enum P { I(i64), S(String), } impl From for P { fn from(i: i64) -> Self { P::I(i) } } impl From<&str> for P { fn from(s: &str) -> Self { P::S(s.to_string()) } } impl From for P { fn from(s: String) -> Self { P::S(s) } } /// Shorthand for building a parameter slice. pub fn params(v: Vec>) -> Vec

{ v.into_iter().map(Into::into).collect() } impl Drop for Env { fn drop(&mut self) { self.db.writer.shutdown(); } } // ------------------------------------------------------------- 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) } /// Two fixtures sharing one server root, so a test can talk about packages that /// depend on each other. The second fixture's manifest wins for the shim, which /// is what you want when the second one is the dependent. pub fn env_with_two_fixtures(a: &str, b: &str) -> (Env, Fixture, Fixture) { let tmp = tempfile::tempdir().expect("tempdir"); let fa = materialize_fixture(tmp.path(), a); let fb = materialize_fixture(tmp.path(), b); let cfg = Config { root: tmp.path().to_path_buf(), signing_key_id: "TESTKEY".into(), path_prepend: Some(shim_dir()), shim_manifest: Some(fb.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(a); env.subscribe(b); (env, fa, fb) } /// 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 upstream2 = root.join(format!("upstream/{name}-2")); let subs = [ ("@AUR_DIR@".to_string(), data.display().to_string()), ("@UPSTREAM_DIR@".to_string(), upstream.display().to_string()), ("@UPSTREAM2_DIR@".to_string(), upstream2.display().to_string()), ]; let mut has_upstream2 = false; 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()); has_upstream2 |= body.contains(&upstream2.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"); } if has_upstream2 { make_git_repo(&upstream2, &[("README", "second upstream\n")], "upstream: initial"); } // A `#tag=v1` source needs the tag to exist. if std::fs::read_to_string(src.join("PKGBUILD")) .unwrap_or_default() .contains("#tag=") { git(&upstream, &["tag", "v1"]); } make_git_repo( &aur, &recipe_files.iter().map(|(n, b)| (n.as_str(), b.as_str())).collect::>(), "initial", ); Fixture { name: name.to_string(), src, aur, data, manifest, upstream: has_upstream_ref.then_some(upstream), upstream2: has_upstream2.then_some(upstream2), } } pub struct Fixture { pub name: String, pub src: PathBuf, pub aur: PathBuf, pub data: PathBuf, pub manifest: PathBuf, pub upstream: Option, /// A second upstream repo, for pkgbases that build from two of them. pub upstream2: Option, } 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"]) } /// Add a commit to the second upstream repo. pub fn upstream2_commit(&self, body: &str) -> String { let up = self.upstream2.clone().expect("fixture has no second upstream repo"); git_add_commit(&up, &[(("README"), body)], body); git(&up, &["rev-parse", "HEAD"]) } /// HEAD of the (first) upstream repo. pub fn upstream_head(&self) -> String { let up = self.upstream.clone().expect("fixture has no upstream repo"); git(&up, &["rev-parse", "HEAD"]) } pub fn upstream2_head(&self) -> String { let up = self.upstream2.clone().expect("fixture has no second upstream repo"); 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!( "pkgbase={pkgbase}\npkgver={pkgver}\npkgrel={pkgrel}\npkgdesc=test\narch=(x86_64)\nurl=https://example.invalid\nlicense=(MIT)\n{extra}\nbuild() {{ :\n}}\npackage_{pkgbase}() {{ :\n}}\n" ) } /// Build a throwaway git repo with the given files and return its path. pub fn make_git_repo(dir: &Path, files: &[(&str, &str)], msg: &str) -> String { std::fs::create_dir_all(dir).unwrap(); git(dir, &["init", "-q", "-b", "master"]); git(dir, &["config", "user.email", "t@example.invalid"]); git(dir, &["config", "user.name", "t"]); for (name, body) in files { let p = dir.join(name); if let Some(parent) = p.parent() { std::fs::create_dir_all(parent).unwrap(); } std::fs::write(p, body).unwrap(); } git(dir, &["add", "-A"]); git(dir, &["commit", "-q", "-m", msg]); git(dir, &["rev-parse", "HEAD"]) } pub fn git_add_commit(dir: &Path, files: &[(&str, &str)], msg: &str) -> String { for (name, body) in files { std::fs::write(dir.join(name), body).unwrap(); } git(dir, &["add", "-A"]); git(dir, &["commit", "-q", "-m", msg]); git(dir, &["rev-parse", "HEAD"]) } pub fn git(dir: &Path, args: &[&str]) -> String { let out = std::process::Command::new("git") .arg("-C") .arg(dir) .args(args) .output() .expect("git"); assert!( out.status.success(), "git {args:?} failed: {}", String::from_utf8_lossy(&out.stderr) ); String::from_utf8_lossy(&out.stdout).trim().to_string() } // ------------------------------------------------------------- web driver -- /// A tiny HTTP client for the surface tests: keeps the session cookie and the /// CSRF token, and hands back status + body. pub struct Web { pub env: Env, pub fx: Fixture, #[allow(dead_code)] pub server: aur_build::http::Server, pub cookie: String, pub csrf: String, } pub struct Page { pub status: u16, pub body: String, } impl Web { pub fn new(name: &str) -> Self { Self::with_password(name, "") } pub fn with_password(name: &str, password: &str) -> Self { let (mut env, fx) = env_with_fixture(name); env.cfg.password = password.into(); Self::attach(env, fx) } /// Start a server on an env the test already built (two fixtures, odd /// configs) and pick up the session it hands out. pub fn attach(mut env: Env, fx: Fixture) -> Self { env.cfg.bind = "127.0.0.1:0".into(); let server = aur_build::http::spawn(env.cfg.clone(), env.db.clone()).unwrap(); let mut web = Self { env, fx, server, cookie: String::new(), csrf: String::new() }; let first = web.raw_get("/"); web.cookie = first .0 .iter() .find(|(k, _)| k == "set-cookie") .and_then(|(_, v)| v.split(';').next().map(|s| s.to_string())) .unwrap_or_default(); let body = web.get("/"); web.csrf = extract(&body.body, "name=\"csrf\" content=\"", "\"").unwrap_or_default(); web } /// Subscribe, detect and render a review so an approval can be attempted. pub fn open_review(&self, name: &str) -> aur_build::db::model::CandidateRow { aur_build::watch::detect::check_pkgbase(&self.env.cfg, &self.env.db, name).unwrap(); let c = aur_build::review::candidates::pending_candidates(&self.env.db).unwrap().remove(0); aur_build::review::diff::render_and_store(&self.env.db, &self.env.cfg, &c).unwrap(); aur_build::review::candidates::candidate_by_id(&self.env.db, c.id).unwrap().unwrap() } /// Approve through the library and run the build to publication, so a test /// can talk about "what the index serves" without re-implementing P0. pub fn publish(&self, name: &str) { let c = self.open_review(name); aur_build::review::approve::approve(&self.env.db, "test", c.id, &c.identity_hash, &c.diff_digest, None) .unwrap(); let c = aur_build::review::candidates::candidate_by_id(&self.env.db, c.id).unwrap().unwrap(); let id = aur_build::pipeline::enqueue_for_candidate(&self.env.cfg, &self.env.db, &c).unwrap(); aur_build::pipeline::run(&self.env.cfg, &self.env.db, &id).unwrap(); } pub fn url(&self, path: &str) -> String { format!("http://{}{}", self.server.addr, path) } pub fn raw_get(&self, path: &str) -> (Vec<(String, String)>, String) { let resp = ureq::get(&self.url(path)).set("Cookie", &self.cookie).call(); let r = match resp { Ok(r) => r, Err(ureq::Error::Status(_, r)) => r, Err(e) => panic!("GET {path}: {e}"), }; let cookie = r.header("set-cookie").map(|s| s.to_string()).unwrap_or_default(); let mut headers = vec![("set-cookie".to_string(), cookie)]; // ureq 2 will not hand out the whole header map, but it will answer for a // named one, which is all the assertions below need. for name in ["content-type", "content-encoding", "location"] { if let Some(v) = r.header(name) { headers.push((name.to_string(), v.to_string())); } } (headers, r.into_string().unwrap_or_default()) } pub fn get(&self, path: &str) -> Page { let resp = ureq::get(&self.url(path)).set("Cookie", &self.cookie).call(); self.finish(resp, path) } pub fn post(&self, path: &str, form: &[(&str, &str)]) -> Page { let resp = ureq::post(&self.url(path)).set("Cookie", &self.cookie).send_form(form); self.finish(resp, path) } /// POST with exactly the fields given and nothing added — used to prove the /// CSRF gate refuses a form that omitted the token. pub fn post_bare(&self, path: &str, form: &[(&str, &str)]) -> Page { let resp = ureq::post(&self.url(path)).set("Cookie", &self.cookie).send_form(form); self.finish(resp, path) } fn finish(&self, resp: Result, path: &str) -> Page { match resp { Ok(r) => Page { status: r.status(), body: r.into_string().unwrap_or_default() }, Err(ureq::Error::Status(code, r)) => Page { status: code, body: r.into_string().unwrap_or_default() }, Err(e) => panic!("{path}: {e}"), } } } /// Pull an attribute or meta value out of rendered HTML and undo the escaping /// the templates applied — a page is the contract here, so we read it as one. pub fn extract(hay: &str, open: &str, close: &str) -> Option { let i = hay.find(open)? + open.len(); let rest = &hay[i..]; let j = rest.find(close)?; Some(unescape(&rest[..j])) } fn unescape(s: &str) -> String { s.replace("&", "&") .replace(""", "\"") .replace("<", "<") .replace(">", ">") .replace("'", "'") }