//! Process-level, mutation-sensitive regression for the deterministic //! agent-git-identity enforcement wrapper. Unlike the unit tests in //! `buzz-git-identity`, this exercises the REAL multicall binary: `buzz-acp` //! symlinked as `git`, invoked exactly as an agent's shell would invoke it, //! with a `.git-identity` manifest beside the symlink (the harness-owned //! authority) and the real `git` reachable later on PATH. //! //! Each test targets one enforcement layer and is designed to go RED if that //! layer is deleted: //! * `enforce` — flag-based identity/signing override is rejected. //! * `verify_push` — a human-authored outgoing commit cannot be pushed. //! * `apply_authority_env`— the agent identity is re-applied over caller/repo //! config (the env-var override vector), so commits land agent-authored //! even when repo-local config names a human. //! //! The whole suite is unix-only: enforcement installs the wrapper as a PATH //! symlink and every test wires a real `git-sign-nostr` signer via //! [`signed_shim_env`], both of which need unix symlinks. buzz-acp's tests do //! not run on Windows CI; this gate keeps `cargo check --all-targets` there //! from compiling helpers it can never exercise. #![cfg(unix)] use nostr::ToBech32; use std::ffi::OsStr; use std::path::{Path, PathBuf}; use std::process::Command; const ALIAS_HOP_LIMIT: usize = 10; /// A named manifest mutation: a label and a fn that rewrites the manifest body. /// Aliased to keep the tampered-manifest table under `clippy::type_complexity`. type ManifestMutation = (&'static str, fn(&str) -> String); /// Directory of the first real `git` on PATH; the wrapper is installed ahead /// of it so `find_real_git` skips our shim symlink and reaches this one. fn real_git_dir() -> PathBuf { for dir in std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default()) { let cand = dir.join("git"); if cand.is_file() { return dir; } } panic!("no real git on PATH"); } /// Repository-local env git exports into hook processes. Under a pre-push hook /// in a linked worktree `GIT_DIR` is absolute, so an inherited value escapes /// `current_dir`/`-C` and fixture commands would rewrite the real repository. const INHERITED_GIT_ENV: &[&str] = &[ "GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_COMMON_DIR", "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES", "GIT_PREFIX", "GIT_NAMESPACE", "GIT_CONFIG_PARAMETERS", "GIT_CONFIG_COUNT", ]; /// `Command::new(program)` with [`INHERITED_GIT_ENV`] removed. Every test spawn /// that runs git (directly, via the wrapper, or via a child that runs git) goes /// through this so the fixture only ever touches its own tempdir repos. fn hermetic_command(program: impl AsRef) -> Command { let mut cmd = Command::new(program); for var in INHERITED_GIT_ENV { cmd.env_remove(var); } cmd } /// Verdict returned by the isolated capability probe helpers. /// /// Mirrors the production `SubsectionSupport` discrimination: /// - `Supported`: exit 0 + "git version" stdout /// - `Unsupported`: exit 1 + empty stdout + stderr starting with /// `git: '' is not a git command` /// - `Failure`: setup error, spawn failure, timeout, output overflow, or /// unclassifiable output — callers `panic!` (fail the test) #[derive(Debug, PartialEq, Eq)] enum ProbeVerdict { Supported, Unsupported, Failure, } /// Probe timeout — same order of magnitude as the production `PROBE_TIMEOUT`. const PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); /// Classify a raw probe `Output` for alias `sentinel` using the same rules as /// the production `git_supports_subsection_alias` classifier. fn classify_probe_output(out: &std::process::Output, sentinel: &str) -> ProbeVerdict { let unknown_cmd_diag = format!("git: '{sentinel}' is not a git command"); if out.status.success() && out.stdout.starts_with(b"git version") { ProbeVerdict::Supported } else if out.status.code() == Some(1) && out.stdout.is_empty() && out.stderr.starts_with(unknown_cmd_diag.as_bytes()) { ProbeVerdict::Unsupported } else { ProbeVerdict::Failure } } /// Isolated capability probe for `alias..command` form aliases. /// /// Matches the production `git_supports_subsection_alias` isolation model: /// - Probe-only private tempdir with a controlled `git` symlink to the real /// binary (prevents sibling helpers from intercepting the probe) /// - Both PATH and GIT_EXEC_PATH set to the private dir only /// - GIT_CONFIG_NOSYSTEM, scratch HOME, XDG_CONFIG_HOME/GIT_DIR removed /// - LC_ALL=C so the unknown-command diagnostic is ASCII-stable /// - Bounded execution via production `run_bounded`: timeout + output cap /// over the whole process group, including pipe draining and teardown /// /// Callers `panic!` on `Failure` — setup, spawn, timeout, and unclassifiable /// output indicate a broken test environment, not a capability answer. fn isolated_subsection_probe() -> ProbeVerdict { run_isolated_probe_for( &real_git_dir().join("git"), "alias._probe_.command=version", "_probe_", ) } /// Isolated empty-subsection dispatch probe for `alias..` form aliases. /// /// Same isolation model as `isolated_subsection_probe`; same tri-state return. fn isolated_empty_subsection_probe() -> ProbeVerdict { run_isolated_probe_for(&real_git_dir().join("git"), "alias..pub=version", "pub") } /// Shared implementation for the isolated probes: runs /// `git -c ` against `git_binary`. fn run_isolated_probe_for(git_binary: &Path, config: &str, sentinel: &str) -> ProbeVerdict { let git_binary = git_binary .canonicalize() .unwrap_or_else(|_| git_binary.to_path_buf()); // Private probe dir: only the controlled git symlink — no adjacent helpers. let probe_dir = match tempfile::tempdir() { Ok(d) => d, Err(_) => return ProbeVerdict::Failure, }; let git_link = probe_dir.path().join("git"); if std::os::unix::fs::symlink(&git_binary, &git_link).is_err() { return ProbeVerdict::Failure; } let scratch = match tempfile::tempdir() { Ok(d) => d, Err(_) => return ProbeVerdict::Failure, }; let probe_path = probe_dir.path().as_os_str().to_owned(); let out = match buzz_git_identity::git_wrapper::run_bounded( Command::new(&git_link) .args(["-c", config, sentinel]) .env("GIT_CONFIG_NOSYSTEM", "1") .env("HOME", scratch.path()) .env_remove("XDG_CONFIG_HOME") .env_remove("GIT_CONFIG_GLOBAL") .env_remove("GIT_CONFIG_SYSTEM") .env_remove("GIT_DIR") .env_remove("GIT_WORK_TREE") .env_remove("GIT_NAMESPACE") .env_remove("GIT_CONFIG_COUNT") .env_remove("GIT_CONFIG_PARAMETERS") .env("PATH", &probe_path) .env("GIT_EXEC_PATH", probe_dir.path()) .env("LC_ALL", "C") .current_dir(scratch.path()), PROBE_TIMEOUT, ) { Some(o) => o, None => return ProbeVerdict::Failure, }; classify_probe_output(&out, sentinel) } /// The test probe helpers must report setup/process/classification failure as /// `Failure` — never as `Unsupported`, which callers treat as a legitimate skip. #[test] fn probe_helpers_report_timeout_and_unrecognized_exit1_as_failure() { let mut sleeper = Command::new("sh"); sleeper.args(["-c", "sleep 30"]); assert!( buzz_git_identity::git_wrapper::run_bounded( &mut sleeper, std::time::Duration::from_millis(200) ) .is_none(), "a probe exceeding its deadline must yield no output" ); let unrelated = Command::new("sh") .args(["-c", "echo 'fatal: something else' >&2; exit 1"]) .output() .unwrap(); assert_eq!( classify_probe_output(&unrelated, "_probe_"), ProbeVerdict::Failure ); let recognized = Command::new("sh") .args([ "-c", "echo \"git: '_probe_' is not a git command. See 'git --help'.\" >&2; exit 1", ]) .output() .unwrap(); assert_eq!( classify_probe_output(&recognized, "_probe_"), ProbeVerdict::Unsupported ); let missing = Path::new("/nonexistent/buzz-probe-test/git"); assert_eq!( run_isolated_probe_for(missing, "alias._probe_.command=version", "_probe_"), ProbeVerdict::Failure ); } /// A git repo with one human-authored commit and human-named local config. fn human_repo() -> tempfile::TempDir { let d = tempfile::tempdir().unwrap(); let p = d.path(); let g = |args: &[&str]| { let ok = hermetic_command("git") .args(args) .current_dir(p) .env("GIT_CONFIG_GLOBAL", "/dev/null") .env("GIT_CONFIG_SYSTEM", "/dev/null") .status() .unwrap() .success(); assert!(ok, "git {args:?} failed"); }; g(&["init", "-q", "-b", "main"]); g(&["config", "user.name", "Human Dev"]); g(&["config", "user.email", "human@example.com"]); g(&["config", "commit.gpgSign", "false"]); std::fs::write(p.join("f"), "one").unwrap(); g(&["add", "f"]); g(&["commit", "-qm", "human commit"]); d } /// A fresh repo with a staged file but no commit object. fn unborn_repo() -> tempfile::TempDir { let d = tempfile::tempdir().unwrap(); let p = d.path(); let g = |args: &[&str]| { let ok = hermetic_command("git") .args(args) .current_dir(p) .env("GIT_CONFIG_GLOBAL", "/dev/null") .env("GIT_CONFIG_SYSTEM", "/dev/null") .status() .unwrap() .success(); assert!(ok, "git {args:?} failed"); }; g(&["init", "-q", "-b", "main"]); g(&["config", "user.name", "Human Dev"]); g(&["config", "user.email", "human@example.com"]); g(&["config", "commit.gpgSign", "false"]); std::fs::write(p.join("f"), "staged").unwrap(); g(&["add", "f"]); d } /// Number of commit objects in `repo`, including unreachable objects. fn commit_object_count(repo: &Path) -> usize { let out = hermetic_command("git") .args([ "-C", repo.to_str().unwrap(), "cat-file", "--batch-all-objects", "--batch-check", ]) .output() .unwrap(); assert!(out.status.success(), "enumerating git objects failed"); String::from_utf8_lossy(&out.stdout) .lines() .filter(|line| line.split_whitespace().nth(1) == Some("commit")) .count() } /// Invoke the wrapper (`git` on the shim PATH) with `args`, in `cwd`. /// /// `NOSTR_PRIVATE_KEY`/`BUZZ_PRIVATE_KEY` are scrubbed so `git-sign-nostr` signs /// from the manifest's `nostr.keyfile` — the real agent-runtime child has the /// private key env removed, and leaving the runner's ambient key set would make /// the signer load the wrong identity (a non-hermetic test). `BUZZ_AUTH_TAG` is /// scrubbed so the signer skips NIP-OA owner attestation (no relay to verify /// against offline); signing itself needs no network. fn wrapper(path: &str, cwd: &Path, args: &[&str]) -> std::process::Output { hermetic_command("git") .args(args) .current_dir(cwd) .env("PATH", path) .env("GIT_CONFIG_GLOBAL", "/dev/null") .env("GIT_CONFIG_SYSTEM", "/dev/null") .env_remove("NOSTR_PRIVATE_KEY") .env_remove("BUZZ_PRIVATE_KEY") .env_remove("BUZZ_AUTH_TAG") .output() .expect("run wrapper git") } /// Like `wrapper`, but bounded: the whole process tree is killed after /// `timeout` and the test panics. Used for nested-agent tests where a recursion /// regression would otherwise hang CI indefinitely. #[cfg(unix)] fn wrapper_bounded( path: &str, cwd: &Path, args: &[&str], timeout: std::time::Duration, ) -> std::process::Output { let mut cmd = hermetic_command("git"); cmd.args(args) .current_dir(cwd) .env("PATH", path) .env("GIT_CONFIG_GLOBAL", "/dev/null") .env("GIT_CONFIG_SYSTEM", "/dev/null") .env_remove("NOSTR_PRIVATE_KEY") .env_remove("BUZZ_PRIVATE_KEY") .env_remove("BUZZ_AUTH_TAG"); run_tree_bounded(&mut cmd, timeout) } /// Run `cmd` via `run_bounded`, which drains pipes and tears down the full /// process group, so a descendant holding stdout cannot outlive the deadline. #[cfg(unix)] fn run_tree_bounded(cmd: &mut Command, timeout: std::time::Duration) -> std::process::Output { buzz_git_identity::git_wrapper::run_bounded(cmd, timeout).unwrap_or_else(|| { panic!( "bounded run of {cmd:?} timed out after {timeout:?} or failed to spawn \ — likely a recursion or hang regression" ) }) } /// The bounded helper must not wait on, or leave alive, a backgrounded /// descendant that keeps the child's stdout open after the child exits. #[cfg(unix)] #[test] fn bounded_helper_kills_descendant_holding_stdout() { let timeout = std::time::Duration::from_secs(2); let start = std::time::Instant::now(); let out = run_tree_bounded( Command::new("sh").args(["-c", "sleep 30 & echo $!"]), timeout, ); assert!( start.elapsed() < timeout, "helper waited {:?} for a pipe-holding descendant", start.elapsed() ); assert!(out.status.success()); let pid = String::from_utf8_lossy(&out.stdout).trim().to_string(); assert!(!pid.is_empty(), "descendant pid missing from stdout"); // The orphaned sleeper is reaped asynchronously by init; allow a moment. let alive = || { Command::new("kill") .args(["-0", &pid]) .status() .unwrap() .success() }; let reap_deadline = std::time::Instant::now() + std::time::Duration::from_secs(1); while alive() && std::time::Instant::now() < reap_deadline { std::thread::sleep(std::time::Duration::from_millis(20)); } assert!( !alive(), "descendant sleeper {pid} survived the bounded run" ); } /// Assert `remote` enumerates refs successfully and holds none. fn assert_remote_empty(remote: &Path) { let refs = hermetic_command("git") .args(["-C", remote.to_str().unwrap(), "for-each-ref"]) .output() .unwrap(); assert!( refs.status.success(), "for-each-ref failed: {:?}", refs.status ); assert!( refs.stdout.is_empty(), "remote must be empty; refs={}", String::from_utf8_lossy(&refs.stdout) ); } /// The current `HEAD` commit SHA of `repo`, via real git (empty if unborn). fn head_sha(repo: &Path) -> String { let out = hermetic_command("git") .args(["-C", repo.to_str().unwrap(), "rev-parse", "HEAD"]) .output() .unwrap(); if !out.status.success() { return String::new(); } String::from_utf8_lossy(&out.stdout).trim().to_string() } #[test] fn wrapper_rejects_flag_based_identity_override() { let (_shim, path, _email, _keydir) = signed_shim_env(); let repo = human_repo(); std::fs::write(repo.path().join("f"), "two").unwrap(); wrapper(&path, repo.path(), &["add", "f"]); let out = wrapper( &path, repo.path(), &["-c", "user.email=evil@example.com", "commit", "-m", "x"], ); assert!( !out.status.success(), "override commit should be rejected; stdout={} stderr={}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr), ); assert!( String::from_utf8_lossy(&out.stderr).contains("machine-managed"), "expected the loud enforce message; stderr={}", String::from_utf8_lossy(&out.stderr), ); } #[test] fn wrapper_refuses_to_push_human_authored_commit() { let (_shim, path, _email, _keydir) = signed_shim_env(); let repo = human_repo(); // A reachable bare remote so the dry-run plan resolves and HEAD (human // authored) is examined as an offender. let remote = tempfile::tempdir().unwrap(); assert!(hermetic_command("git") .args(["init", "-q", "--bare", remote.path().to_str().unwrap()]) .status() .unwrap() .success()); wrapper( &path, repo.path(), &["remote", "add", "origin", remote.path().to_str().unwrap()], ); let out = wrapper(&path, repo.path(), &["push", "origin", "main"]); assert!( !out.status.success(), "pushing a human-authored commit must be refused; stderr={}", String::from_utf8_lossy(&out.stderr), ); assert!( String::from_utf8_lossy(&out.stderr).contains("not authored by your agent identity"), "expected the push-gate rejection; stderr={}", String::from_utf8_lossy(&out.stderr), ); // The bare remote must have received nothing. let refs = hermetic_command("git") .args(["-C", remote.path().to_str().unwrap(), "for-each-ref"]) .output() .unwrap(); assert!( refs.stdout.is_empty(), "no ref should have reached the remote: {}", String::from_utf8_lossy(&refs.stdout), ); } /// R4 real-wrapper regression for the allowlist alias guard. Two Thufir p3 /// bypass probes must be refused through the actual `buzz-acp`-as-`git` /// multicall, and neither may create a commit: /// /// (a) a *quoted* config alias — git's quote-aware parser dequotes `'-c'` /// `'user.email=…'` into real `-c` config that the whitespace-naive /// round-3 scan missed; /// (b) a *shell* (`!`) commit alias — git runs it with real git ahead of the /// wrapper on PATH, so its inner `-c` re-authors the commit. /// /// A plain-subcommand alias must still resolve and commit as the agent /// identity, proving the allowlist did not over-reject Gurney's working shapes. #[test] fn wrapper_rejects_quoted_and_shell_aliases_and_allows_plain_alias() { let (_shim, path, email, _keydir) = signed_shim_env(); let repo = human_repo(); // (a) quoted config alias — the parser-parity bypass. wrapper( &path, repo.path(), &[ "config", "alias.quoted", "'-c' 'user.name=QuotedHuman' '-c' 'user.email=quoted@human.test' '-c' 'commit.gpgSign=false' commit", ], ); // (b) shell commit alias — git prepends real git to PATH for `!` bodies. wrapper( &path, repo.path(), &[ "config", "alias.sc", "!f(){ git -c user.name=ShellHuman -c user.email=shell@human.test -c commit.gpgSign=false commit \"$@\"; }; f", ], ); // A plain-subcommand alias that must keep working. wrapper(&path, repo.path(), &["config", "alias.ci", "commit"]); let head_before = head_sha(repo.path()); std::fs::write(repo.path().join("f"), "two").unwrap(); wrapper(&path, repo.path(), &["add", "f"]); // (a) refused, no commit created. let out = wrapper(&path, repo.path(), &["quoted", "-m", "via quoted alias"]); assert!( !out.status.success(), "quoted config alias must be refused; stdout={} stderr={}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr), ); assert_eq!( head_sha(repo.path()), head_before, "the refused quoted alias must not create a commit" ); // (b) refused, no commit created. let out = wrapper(&path, repo.path(), &["sc", "-m", "via shell alias"]); assert!( !out.status.success(), "shell commit alias must be refused; stdout={} stderr={}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr), ); assert!( String::from_utf8_lossy(&out.stderr).contains("shell (`!`) git alias"), "expected the shell-alias rejection; stderr={}", String::from_utf8_lossy(&out.stderr), ); assert_eq!( head_sha(repo.path()), head_before, "the refused shell alias must not create a commit" ); // The plain alias must still resolve and commit as the agent identity. let out = wrapper(&path, repo.path(), &["ci", "-m", "via plain alias"]); assert!( out.status.success(), "plain-subcommand alias must still commit; stderr={}", String::from_utf8_lossy(&out.stderr), ); let author = hermetic_command("git") .args([ "-C", repo.path().to_str().unwrap(), "show", "-s", "--format=%ae", "HEAD", ]) .output() .unwrap(); assert_eq!( String::from_utf8_lossy(&author.stdout).trim(), email, "plain-alias commit must be authored as the agent identity" ); } /// R5 real-wrapper regression for the alias-unification fix (Thufir's rd-4 /// IMPORTANT). A bare-word alias whose body carries identity/signing *flags* /// passes the allowlist (every token is a plain bare word), but after the alias /// is expanded the wrapper holds the expansion to the SAME `enforce`/author /// policy as a directly-typed command — so the alias can do no more than its /// expansion could. Three shapes, each of which is refused when typed directly, /// must therefore be refused through the alias too, with `HEAD` unchanged: /// /// (a) Thufir's exact probe — `--author` (split form) plus `--no-gpg-sign`; /// (b) `--no-gpg-sign` alone, pinning that the fix is not one hard-coded string; /// (c) an alias *chain* that resolves to `commit --no-gpg-sign` through two /// hops, pinning that unification applies to the final accumulated command. #[test] fn wrapper_rejects_bare_word_alias_carried_identity_and_signing_flags() { let (_shim, path, _email, _keydir) = signed_shim_env(); let repo = human_repo(); // (a) Thufir's exact bypass probe — bare-word `--author`/`--no-gpg-sign`. wrapper( &path, repo.path(), &[ "config", "alias.human", "commit --author Human --no-gpg-sign", ], ); // (b) `--no-gpg-sign` alone. wrapper( &path, repo.path(), &["config", "alias.unsign", "commit --no-gpg-sign"], ); // (c) an alias chain: `chain` → `co --no-gpg-sign` → `commit --no-gpg-sign`. wrapper(&path, repo.path(), &["config", "alias.co", "commit"]); wrapper( &path, repo.path(), &["config", "alias.chain", "co --no-gpg-sign"], ); let head_before = head_sha(repo.path()); std::fs::write(repo.path().join("f"), "two").unwrap(); wrapper(&path, repo.path(), &["add", "f"]); for (alias, label) in [ ("human", "author+no-gpg-sign alias"), ("unsign", "no-gpg-sign-only alias"), ("chain", "chained no-gpg-sign alias"), ] { let out = wrapper(&path, repo.path(), &[alias, "-m", "leak"]); assert!( !out.status.success(), "{label} must be refused; stdout={} stderr={}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr), ); assert!( String::from_utf8_lossy(&out.stderr).contains("machine-managed"), "{label} must give the identity/signing rejection; stderr={}", String::from_utf8_lossy(&out.stderr), ); assert_eq!( head_sha(repo.path()), head_before, "{label} must not create a commit" ); } } #[test] fn wrapper_refuses_alias_chain_beyond_limit_and_allows_exact_limit() { let (_shim, path, email, _keydir) = signed_shim_env(); let repo = unborn_repo(); // Exactly ALIAS_HOP_LIMIT substitutions end at real `commit`, so the wrapper // must preserve the boundary's useful side: it resolves and commits under // the managed agent identity. for index in 0..ALIAS_HOP_LIMIT { let name = format!("at{index}"); let next = if index + 1 == ALIAS_HOP_LIMIT { "commit".to_string() } else { format!("at{}", index + 1) }; wrapper( &path, repo.path(), &["config", &format!("alias.{name}"), &next], ); } let out = wrapper(&path, repo.path(), &["at0", "-m", "at the alias limit"]); assert!( out.status.success(), "chain at the limit must reach the real command; stderr={}", String::from_utf8_lossy(&out.stderr), ); let author = hermetic_command("git") .args([ "-C", repo.path().to_str().unwrap(), "show", "-s", "--format=%ae", "HEAD", ]) .output() .unwrap(); assert_eq!(String::from_utf8_lossy(&author.stdout).trim(), email); // Thufir's limit+1 counterexample: the wrapper must not hand a partial // expansion to git. A human-author `commit` beyond the bound is refused // before git runs, leaving the fresh repo unborn with no commit objects. let beyond = unborn_repo(); for index in 0..=ALIAS_HOP_LIMIT { let name = format!("a{index}"); let next = if index == ALIAS_HOP_LIMIT { "commit --author Human".to_string() } else { format!("a{}", index + 1) }; wrapper( &path, beyond.path(), &["config", &format!("alias.{name}"), &next], ); } let out = wrapper(&path, beyond.path(), &["a0", "-m", "leak"]); assert!( !out.status.success(), "chain past the limit must be refused; stdout={} stderr={}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr), ); assert!( String::from_utf8_lossy(&out.stderr) .contains(&format!("after {ALIAS_HOP_LIMIT} expansions")), "expected the alias-limit refusal; stderr={}", String::from_utf8_lossy(&out.stderr), ); let beyond_head = head_sha(beyond.path()); assert!( beyond_head.is_empty(), "HEAD must remain unborn; HEAD={beyond_head:?}; stderr={}", String::from_utf8_lossy(&out.stderr), ); assert_eq!( commit_object_count(beyond.path()), 0, "the refused chain must not create an unreachable commit object" ); } #[test] fn wrapper_reapplies_agent_identity_over_repo_config() { // The env-var / repo-config override vector: repo-local config names a // human, yet the wrapper re-appends the agent identity at the highest // GIT_CONFIG_* index, so the resulting commit is agent-authored. Deleting // `apply_authority_env` makes this commit land as `human@example.com`. let (_shim, path, email, _keydir) = signed_shim_env(); let repo = human_repo(); std::fs::write(repo.path().join("f"), "two").unwrap(); wrapper(&path, repo.path(), &["add", "f"]); let out = wrapper(&path, repo.path(), &["commit", "-m", "agent authored"]); assert!( out.status.success(), "ordinary commit should succeed; stderr={}", String::from_utf8_lossy(&out.stderr), ); let author = hermetic_command("git") .args([ "-C", repo.path().to_str().unwrap(), "show", "-s", "--format=%ae", "HEAD", ]) .output() .unwrap(); assert_eq!( String::from_utf8_lossy(&author.stdout).trim(), email, "commit must be authored as the agent identity, not the repo-local human" ); } /// A fixture agent key persisted the way the harness persists it. struct AgentKey { keyfile_path: String, pubkey_hex: String, npub: String, } /// Write `nsec` to an owner-only keyfile in `dir` and derive its identity. fn write_agent_key(dir: &Path, nsec: &str) -> Option { use std::os::unix::fs::OpenOptionsExt; let keys = nostr::Keys::parse(nsec).ok()?; let keyfile = dir.join(".nostr-key"); std::fs::OpenOptions::new() .write(true) .create_new(true) .mode(0o600) .open(&keyfile) .and_then(|mut f| std::io::Write::write_all(&mut f, nsec.as_bytes())) .ok()?; Some(AgentKey { keyfile_path: keyfile.to_str()?.to_owned(), pubkey_hex: keys.public_key().to_hex(), npub: keys.public_key().to_bech32().ok()?, }) } /// The complete manifest a managed install writes for `id` on `relay.test`. fn manifest_entries(id: &AgentKey) -> Vec<(String, String)> { let mut entries = vec![ ("user.name".to_owned(), id.npub.clone()), ( "user.email".to_owned(), format!("{}@relay.test", id.pubkey_hex), ), ]; entries.extend( buzz_git_identity::FIXED_SIGNING_ENTRIES .iter() .map(|&(k, v)| (k.to_owned(), v.to_owned())), ); entries.push(("user.signingkey".to_owned(), id.pubkey_hex.clone())); entries.push(("nostr.keyfile".to_owned(), id.keyfile_path.clone())); entries } /// Build a shim dir wired for REAL signing: `git` and `git-sign-nostr` both /// symlink to the buzz-acp multicall, and the `.git-identity` manifest carries /// the full identity + signing config (`commit.gpgSign=true`, the signer /// program, `user.signingkey`, and the keyfile) for a freshly generated key. /// Returns (shim TempDir, PATH string, expected author email, keyfile-holding /// TempDir). Signing itself needs no network — `BUZZ_AUTH_TAG` is left unset so /// the signer works offline. fn signed_shim_env() -> (tempfile::TempDir, String, String, tempfile::TempDir) { let keys = nostr::Keys::generate(); let nsec = keys.secret_key().to_bech32().unwrap(); // Keyfile + derived identity live in their own 0700 dir (the manifest's // `nostr.keyfile` points here). Kept separate from the shim so the shim // holds only the git symlinks + manifest, as the harness installs them. let keydir = tempfile::tempdir().unwrap(); let id = write_agent_key(keydir.path(), &nsec).expect("write keyfile"); let expected_email = format!("{}@relay.test", id.pubkey_hex); let shim = tempfile::tempdir().unwrap(); for name in ["git", "git-sign-nostr"] { std::os::unix::fs::symlink(env!("CARGO_BIN_EXE_buzz-acp"), shim.path().join(name)).unwrap(); } buzz_git_identity::write_identity_manifest(shim.path(), &manifest_entries(&id)).unwrap(); let real = real_git_dir(); let path = std::env::join_paths([shim.path().to_path_buf(), real]) .unwrap() .into_string() .unwrap(); (shim, path, expected_email, keydir) } /// A repo whose local config names the AGENT identity (author is correct) and a /// reachable bare remote, ready for one commit. Returns (work TempDir, repo /// path, remote path). `commit.gpgSign` is left to the wrapper's injected config /// so the commit shape is set per-test. fn agent_repo_with_remote(agent_email: &str) -> (tempfile::TempDir, PathBuf, PathBuf) { let work = tempfile::tempdir().unwrap(); let repo = work.path().join("repo"); std::fs::create_dir_all(&repo).unwrap(); let remote = work.path().join("remote.git"); let g = |cwd: &Path, args: &[&str]| { assert!(hermetic_command("git") .args(args) .current_dir(cwd) .env("GIT_CONFIG_GLOBAL", "/dev/null") .env("GIT_CONFIG_SYSTEM", "/dev/null") .status() .unwrap() .success()); }; g( work.path(), &["init", "-q", "--bare", remote.to_str().unwrap()], ); g(&repo, &["init", "-q", "-b", "main"]); g(&repo, &["config", "user.name", "Agent"]); g(&repo, &["config", "user.email", agent_email]); g( &repo, &["remote", "add", "origin", remote.to_str().unwrap()], ); (work, repo, remote) } /// L3b (real signer): a genuinely signed agent commit pushes cleanly. This /// proves the push-gate signature check accepts a valid NIP-GS signature by the /// agent key — the happy path that the reject tests below are measured against. #[test] fn wrapper_allows_push_of_signed_agent_commit() { let (_shim, path, email, _keydir) = signed_shim_env(); let (_work, repo, _remote) = agent_repo_with_remote(&email); std::fs::write(repo.join("f"), "x").unwrap(); wrapper(&path, &repo, &["add", "f"]); // The wrapper injects commit.gpgSign=true + the signer, so this commit is // signed by the agent key. let out = wrapper(&path, &repo, &["commit", "-m", "agent signed"]); assert!( out.status.success(), "signed agent commit should succeed; stderr={}", String::from_utf8_lossy(&out.stderr), ); let out = wrapper(&path, &repo, &["push", "origin", "main"]); assert!( out.status.success(), "pushing a signed agent commit must be allowed; stderr={}", String::from_utf8_lossy(&out.stderr), ); } /// L3b (real signer): an agent-authored but UNSIGNED commit created via /// `git merge --no-gpg-sign` — Carl's live repro of the P1 gap — must be refused /// at push. The merge commit is correctly agent-authored, so only the signature /// check catches it; `enforce` cannot, because `merge` is not in its signing /// blocklist. #[test] fn wrapper_refuses_push_of_unsigned_merge_commit() { let (_shim, path, email, _keydir) = signed_shim_env(); let (_work, repo, _remote) = agent_repo_with_remote(&email); // Base signed commit on main. std::fs::write(repo.join("base"), "b").unwrap(); wrapper(&path, &repo, &["add", "base"]); assert!(wrapper(&path, &repo, &["commit", "-m", "base"]) .status .success()); // A signed commit on a side branch. wrapper(&path, &repo, &["checkout", "-q", "-b", "side"]); std::fs::write(repo.join("side"), "s").unwrap(); wrapper(&path, &repo, &["add", "side"]); assert!(wrapper(&path, &repo, &["commit", "-m", "side work"]) .status .success()); // Back on main, merge the side branch WITHOUT signing — an agent-authored // but unsigned merge commit. `--no-ff` forces a merge commit object. wrapper(&path, &repo, &["checkout", "-q", "main"]); let m = wrapper( &path, &repo, &[ "merge", "--no-ff", "--no-gpg-sign", "-m", "merge side", "side", ], ); assert!( m.status.success(), "the unsigned merge itself should succeed; stderr={}", String::from_utf8_lossy(&m.stderr), ); let out = wrapper(&path, &repo, &["push", "origin", "main"]); assert!( !out.status.success(), "pushing an unsigned merge commit must be refused; stderr={}", String::from_utf8_lossy(&out.stderr), ); assert!( String::from_utf8_lossy(&out.stderr).contains("no valid signature by your agent key"), "expected the unsigned-commit rejection; stderr={}", String::from_utf8_lossy(&out.stderr), ); } /// L3b (real signer): an agent-authored but UNSIGNED commit created via the /// `commit-tree` plumbing — which bypasses `commit` entirely and so is never /// touched by `enforce` — must be refused at push. Pins that the push-gate /// check covers the plumbing path, not just porcelain. #[test] fn wrapper_refuses_push_of_unsigned_commit_tree() { let (_shim, path, email, _keydir) = signed_shim_env(); let (_work, repo, _remote) = agent_repo_with_remote(&email); // Seed a signed base so HEAD and the tree exist. std::fs::write(repo.join("f"), "x").unwrap(); wrapper(&path, &repo, &["add", "f"]); assert!(wrapper(&path, &repo, &["commit", "-m", "base"]) .status .success()); // Build an unsigned commit object directly with `commit-tree` (no signing, // agent identity via env), then move the branch to it. let tree = wrapper(&path, &repo, &["write-tree"]); let tree_sha = String::from_utf8_lossy(&tree.stdout).trim().to_string(); let parent = head_sha(&repo); let out = hermetic_command("git") .args(["commit-tree", &tree_sha, "-p", &parent, "-m", "plumbed"]) .current_dir(&repo) .env("PATH", &path) .env("GIT_CONFIG_GLOBAL", "/dev/null") .env("GIT_CONFIG_SYSTEM", "/dev/null") .env("GIT_AUTHOR_NAME", "Agent") .env("GIT_AUTHOR_EMAIL", &email) .env("GIT_COMMITTER_NAME", "Agent") .env("GIT_COMMITTER_EMAIL", &email) .output() .expect("run commit-tree"); assert!( out.status.success(), "commit-tree should succeed; stderr={}", String::from_utf8_lossy(&out.stderr), ); let new_sha = String::from_utf8_lossy(&out.stdout).trim().to_string(); wrapper(&path, &repo, &["update-ref", "refs/heads/main", &new_sha]); let out = wrapper(&path, &repo, &["push", "origin", "main"]); assert!( !out.status.success(), "pushing an unsigned commit-tree commit must be refused; stderr={}", String::from_utf8_lossy(&out.stderr), ); assert!( String::from_utf8_lossy(&out.stderr).contains("no valid signature by your agent key"), "expected the unsigned-commit rejection; stderr={}", String::from_utf8_lossy(&out.stderr), ); } /// Contract regression (Thufir rd-2 IMPORTANT): a `.git-identity` manifest that /// names the agent but drops, falsifies, or misdirects the signing contract is /// tampered — not a legitimate unsigned mode — and must fail closed for EVERY /// command, not silently disable or redirect the push-gate signature check. /// Six mutations, each a distinct silent-disable/misdirect the contract check /// rejects at classification time (`run()` refuses before any dispatch), so /// even a read-only `status` is refused. The duplicate-key and `include.path` /// cases cover the last-value-wins redirect that a first-value-only validator /// would miss. #[test] fn wrapper_refuses_every_command_when_manifest_signing_contract_is_tampered() { let variants: [ManifestMutation; 6] = [ // `commit.gpgSign` removed → the signature gate would never fire. ("commit.gpgSign removed", |m| { m.lines() .filter(|l| !l.starts_with("commit.gpgSign=")) .collect::>() .join("\n") }), // `commit.gpgSign=false` → the same silent-disable, spelled out. ("commit.gpgSign=false", |m| { m.replace("commit.gpgSign=true", "commit.gpgSign=false") }), // `user.signingkey` swapped to a key the author email does not encode → // the probe would trust the wrong key. ("user.signingkey swapped", |m| { m.lines() .map(|l| { if l.starts_with("user.signingkey=") { format!("user.signingkey={}", "b".repeat(64)) } else { l.to_string() } }) .collect::>() .join("\n") }), // A DUPLICATE later `user.signingkey=B` appended after the canonical // first value → git config is last-value-wins, so the probe would // resolve B. classify() rejects any duplicate canonical key. ("duplicate user.signingkey", |m| { format!("{m}\nuser.signingkey={}", "b".repeat(64)) }), // An appended `include.path` → an unknown key that could pull in another // key file whose later `user.signingkey` wins. classify() rejects any // unknown key. ("appended include.path", |m| { format!("{m}\ninclude.path=/tmp/evil.inc") }), // `gpg.x509.program` differing ONLY in case. On a case-sensitive host // `GIT-SIGN-NOSTR` resolves past the managed install to an agent- // controlled fake verifier later on PATH; the probe would then accept // an unsigned commit. classify() compares fixed values byte for byte. ("gpg.x509.program cased", |m| { m.replace( "gpg.x509.program=git-sign-nostr", "gpg.x509.program=GIT-SIGN-NOSTR", ) }), ]; for (label, mutate) in variants { let (shim, path, _email, _keydir) = signed_shim_env(); let manifest_path = shim.path().join(".git-identity"); let original = std::fs::read_to_string(&manifest_path).unwrap(); std::fs::write(&manifest_path, mutate(&original)).unwrap(); let repo = human_repo(); let out = wrapper(&path, repo.path(), &["status"]); assert!( !out.status.success(), "[{label}] a tampered manifest must refuse every command; stderr={}", String::from_utf8_lossy(&out.stderr), ); assert!( String::from_utf8_lossy(&out.stderr).contains("complete signing contract"), "[{label}] expected the tampered-manifest refusal; stderr={}", String::from_utf8_lossy(&out.stderr), ); } } /// L3b (real signer): the wrong-key case Thufir called out — a commit correctly /// authored as the agent (key A) but VALIDLY signed by a DIFFERENT key B must be /// refused at push. `git-sign-nostr` verifies B's signature as cryptographically /// good, but the push probe injects the authority's `user.signingkey=A`, so the /// verified key ≠ the expected key → not `TRUST_FULLY` → `%G?` ≠ `G`. A valid /// signature by the wrong key is not a valid agent signature. #[test] fn wrapper_refuses_push_of_commit_validly_signed_by_wrong_key() { let (_shim, path, email_a, _keydir_a) = signed_shim_env(); let (_work, repo, _remote) = agent_repo_with_remote(&email_a); // A second, unrelated signing identity (key B) with its own keyfile. let keys_b = nostr::Keys::generate(); let nsec_b = keys_b.secret_key().to_bech32().unwrap(); let keydir_b = tempfile::tempdir().unwrap(); let id_b = write_agent_key(keydir_b.path(), &nsec_b).expect("write B keyfile"); // Create a commit authored as agent A but signed with key B, bypassing the // wrapper's `enforce` by invoking the real git binary directly with B's // signing config. `git-sign-nostr` resolves from the shim on PATH. let real_git = real_git_dir().join("git"); let out = hermetic_command(&real_git) .args([ "-C", repo.to_str().unwrap(), "-c", "gpg.format=x509", "-c", "gpg.x509.program=git-sign-nostr", "-c", "commit.gpgSign=true", "-c", &format!("user.signingkey={}", id_b.pubkey_hex), "-c", &format!("nostr.keyfile={}", id_b.keyfile_path), "commit", "--allow-empty", "-m", "authored by A, signed by B", ]) .current_dir(&repo) .env("PATH", &path) .env("GIT_CONFIG_GLOBAL", "/dev/null") .env("GIT_CONFIG_SYSTEM", "/dev/null") .env("GIT_AUTHOR_NAME", "Agent") .env("GIT_AUTHOR_EMAIL", &email_a) .env("GIT_COMMITTER_NAME", "Agent") .env("GIT_COMMITTER_EMAIL", &email_a) .env_remove("NOSTR_PRIVATE_KEY") .env_remove("BUZZ_PRIVATE_KEY") .env_remove("BUZZ_AUTH_TAG") .output() .expect("create B-signed commit"); assert!( out.status.success(), "the B-signed commit itself should be created; stderr={}", String::from_utf8_lossy(&out.stderr), ); // Sanity: it is agent-authored, so the push gate demands a valid agent // signature on it (rather than skipping it as someone else's commit). let author = hermetic_command(&real_git) .args([ "-C", repo.to_str().unwrap(), "show", "-s", "--format=%ae", "HEAD", ]) .output() .unwrap(); assert_eq!(String::from_utf8_lossy(&author.stdout).trim(), email_a); let out = wrapper(&path, &repo, &["push", "origin", "main"]); assert!( !out.status.success(), "a commit signed by the wrong key must be refused at push; stderr={}", String::from_utf8_lossy(&out.stderr), ); assert!( String::from_utf8_lossy(&out.stderr).contains("no valid signature by your agent key"), "expected the wrong-key rejection; stderr={}", String::from_utf8_lossy(&out.stderr), ); } /// Run the real `buzz-acp` harness with a script adapter and `BUZZ_GIT_IDENTITY` /// set to `mode` (unset for `None`). The adapter runs `probe` in `work`, writes /// `done`, and idles until the harness is terminated. Returns the harness exit /// status and its log. Isolated from operator global/system Git config, so any /// identity the probe sees came from the harness or the fixture's repo config. fn run_harness( work: &Path, mode: Option<&str>, probe: &str, tmpdir: Option<&Path>, inherited: &[(&str, &str)], path_prefix: Option<&Path>, ) -> (std::process::ExitStatus, String) { use std::os::unix::fs::PermissionsExt; use std::time::{Duration, Instant}; let adapter = work.join("adapter.sh"); std::fs::write( &adapter, format!( "#!/bin/sh\nset -eu\ncd \"$PROBE_DIR\"\n{probe}\nprintf done > done\nexec sleep 60\n" ), ) .unwrap(); std::fs::set_permissions(&adapter, std::fs::Permissions::from_mode(0o700)).unwrap(); let log = std::fs::File::create(work.join("harness.log")).unwrap(); let mut cmd = hermetic_command(env!("CARGO_BIN_EXE_buzz-acp")); let path = std::env::join_paths(path_prefix.map(Path::to_path_buf).into_iter().chain( std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default()), )) .unwrap(); cmd.env_clear() .env("PATH", path) .env("PROBE_DIR", work) .env("GIT_CONFIG_GLOBAL", "/dev/null") .env("GIT_CONFIG_NOSYSTEM", "1") .args([ "--private-key", &nostr::Keys::generate().secret_key().to_secret_hex(), "--relay-url", "wss://relay.test", "--agent-command", adapter.to_str().unwrap(), "--agent-args", "", ]) .stdin(std::process::Stdio::null()) .stdout(log.try_clone().unwrap()) .stderr(log); if let Some(mode) = mode { cmd.env("BUZZ_GIT_IDENTITY", mode); } if let Some(tmpdir) = tmpdir { cmd.env("TMPDIR", tmpdir); } if !inherited.is_empty() { cmd.env("GIT_CONFIG_COUNT", inherited.len().to_string()); for (i, (key, value)) in inherited.iter().enumerate() { cmd.env(format!("GIT_CONFIG_KEY_{i}"), key) .env(format!("GIT_CONFIG_VALUE_{i}"), value); } } let mut child = cmd.spawn().unwrap(); let pid = nix::unistd::Pid::from_raw(child.id() as i32); let deadline = Instant::now() + Duration::from_secs(20); while !work.join("done").exists() && Instant::now() < deadline { if child.try_wait().unwrap().is_some() { break; } std::thread::sleep(Duration::from_millis(50)); } // Always terminate the exact child so a failure leaves no harness behind. nix::sys::signal::kill(pid, nix::sys::signal::Signal::SIGTERM).ok(); let exit_deadline = Instant::now() + Duration::from_secs(5); while child.try_wait().unwrap().is_none() && Instant::now() < exit_deadline { std::thread::sleep(Duration::from_millis(20)); } if child.try_wait().unwrap().is_none() { child.kill().unwrap(); } let status = child.wait().unwrap(); ( status, std::fs::read_to_string(work.join("harness.log")).unwrap(), ) } /// I4: the harness's `GitEnvironment` must put the enforcement wrapper ahead of /// real git in the adapter's native shell. The script configures a human /// identity in the repo; a bare commit must still land as the agent, and a /// `-c user.email=` override must be refused. Removing the wrapper symlink from /// the install turns this RED on the refusal only: the `GIT_CONFIG_*` block /// still attributes the bare commit to the agent, but the override succeeds. #[test] fn harness_native_shell_commits_as_agent_and_refuses_identity_override() { let work = tempfile::tempdir().unwrap(); let (status, logs) = run_harness( work.path(), None, r#"git init -q -b main repo cd repo git config user.name 'Human Dev' git config user.email human@example.com git commit -q --allow-empty -m 'agent authored' git show -s --format=%ae HEAD > ../author git verify-commit HEAD if git -c user.email=human@example.com commit -q --allow-empty -m override 2> ../override-stderr; then echo accepted > ../override else echo refused > ../override fi cd .."#, None, &[], None, ); assert!(work.path().join("done").exists(), "probe failed: {logs}"); assert!(status.success(), "harness shutdown failed: {logs}"); let author = std::fs::read_to_string(work.path().join("author")).unwrap(); assert!( author.trim().ends_with("@relay.test") && author.trim().len() == 64 + "@relay.test".len(), "bare commit must be authored by the agent key, got {author:?}" ); assert_eq!( std::fs::read_to_string(work.path().join("override")) .unwrap() .trim(), "refused", "stderr: {}", std::fs::read_to_string(work.path().join("override-stderr")).unwrap_or_default() ); } /// `user` mode installs only relay credentials: the nostr helper answers for /// the relay, but there is no wrapper, no signer, no manifest and no injected /// identity, so git resolves the operator's own configuration. #[test] fn harness_user_mode_installs_only_relay_credentials() { let work = tempfile::tempdir().unwrap(); let (status, logs) = run_harness( work.path(), Some("user"), r#"absent() { if git config "$1"; then echo "$1 is set" >&2; exit 1; fi; } helper=$(command -v git-credential-nostr) dir=$(dirname "$helper") test "$(git config --get-urlmatch credential.helper https://relay.test/git/o/r)" = nostr test -n "$(git config nostr.keyfile)" test ! -e "$dir/git" test ! -e "$dir/git-sign-nostr" test ! -e "$dir/.git-identity" test "$(dirname "$(command -v git)")" != "$dir" absent user.name absent user.email absent user.signingkey absent commit.gpgSign"#, None, &[], None, ); assert!(work.path().join("done").exists(), "probe failed: {logs}"); assert!(status.success(), "harness shutdown failed: {logs}"); } /// `user` mode drops inherited `GIT_CONFIG_*` identity, `author.*` / /// `committer.*` and signing keys and config includes (which could carry /// identity), in any case spelling, so the operator's own configuration /// applies; unrelated inherited entries still reach the adapter. #[test] fn harness_user_mode_drops_inherited_identity_and_signing() { let work = tempfile::tempdir().unwrap(); for args in [ &["init", "-q"][..], &["config", "user.name", "Operator"], &["config", "user.email", "operator@example.invalid"], ] { let status = hermetic_command("git") .arg("-C") .arg(work.path()) .args(args) .env("GIT_CONFIG_GLOBAL", "/dev/null") .env("GIT_CONFIG_NOSYSTEM", "1") .status() .unwrap(); assert!(status.success(), "git {args:?}"); } let include_file = work.path().join("identity.inc"); std::fs::write( &include_file, "[user]\n\temail = included@example.invalid\n", ) .unwrap(); let include = include_file.to_str().unwrap().to_owned(); // A parent harness's install dir ahead of real git on the inherited PATH. let parent = work.path().join("parent-install"); std::fs::create_dir(&parent).unwrap(); std::fs::write(parent.join(".git-identity"), "").unwrap(); std::fs::write(parent.join("git"), "#!/bin/sh\necho parent-wrapper\n").unwrap(); std::fs::set_permissions( parent.join("git"), std::os::unix::fs::PermissionsExt::from_mode(0o755), ) .unwrap(); let (status, logs) = run_harness( work.path(), Some("user"), r#"case "$(command -v git)" in */parent-install/*) echo "git resolves to the parent wrapper" >&2; exit 1;; esac absent() { if git config "$1"; then echo "$1 is set" >&2; exit 1; fi; } operator() { case "$(git var "$1")" in "Operator "*) ;; *) echo "$1 is not the operator" >&2; exit 1;; esac; } operator GIT_AUTHOR_IDENT operator GIT_COMMITTER_IDENT absent user.signingkey absent gpg.format absent gpg.x509.program absent commit.gpgSign absent tag.gpgSign test "$(git config core.abbrev)" = 12 test "$(git config gpg.X509.program)" = distinct-subsection"#, None, &[ ("user.name", "Inherited Agent"), ("USER.EMAIL", "inherited@example.invalid"), ("user.signingKey", "inherited-key"), ("GPG.Format", "openpgp"), ("GPG.x509.PROGRAM", "inherited-signer"), ("gpg.X509.program", "distinct-subsection"), ("commit.gpgsign", "true"), ("TAG.GPGSIGN", "true"), ("Author.Name", "Inherited Author"), ("Author.Email", "author@example.invalid"), ("COMMITTER.name", "Inherited Committer"), ("committer.EMAIL", "committer@example.invalid"), ("Include.Path", &include), ("INCLUDEIF.gitdir:/.PATH", &include), ("core.abbrev", "12"), ], Some(&parent), ); assert!(work.path().join("done").exists(), "probe failed: {logs}"); assert!(status.success(), "harness shutdown failed: {logs}"); } /// An unrecognized mode stops the harness before any adapter runs. #[test] fn harness_invalid_mode_fails_startup() { let work = tempfile::tempdir().unwrap(); let (status, logs) = run_harness(work.path(), Some("usr"), "true", None, &[], None); assert!(!status.success(), "invalid mode must fail startup: {logs}"); assert!(!work.path().join("done").exists(), "adapter ran: {logs}"); assert!( logs.contains("BUZZ_GIT_IDENTITY"), "error must name the var: {logs}" ); } /// A configured key whose Git install fails stops the harness; the adapter /// never runs with the ambient identity. #[test] fn harness_git_install_failure_fails_startup() { let work = tempfile::tempdir().unwrap(); let missing = work.path().join("missing-tmp"); let (status, logs) = run_harness(work.path(), None, "true", Some(&missing), &[], None); assert!( !status.success(), "install failure must fail startup: {logs}" ); assert!(!work.path().join("done").exists(), "adapter ran: {logs}"); } /// Wes (5055999359) P1 — real-wrapper regression: `--receive-pack` (custom /// receivepack program) is refused through the ACTUAL `buzz-acp`-as-`git` /// multicall. Also covers `remote.origin.receivepack` config spelling. /// /// Bypass shape (what happens WITHOUT the guard): /// /// `origin` URL → `decoy` (bare repo seeded with the offending human HEAD). /// receivepack script → ignores its `` argument; exec's /// `git-receive-pack ` instead. /// /// 1. `resolve_push_sources` runs `git push --dry-run --porcelain`. /// Git invokes the script as the receive-pack process; negotiation /// happens against `actual` (empty). The porcelain `To` header shows /// the `origin` URL (`decoy`). /// 2. `remote_object_ids` calls `git ls-remote decoy` → returns HEAD's IDs /// → those IDs are used as the exclusion set → HEAD is treated as /// already-remote → `partition_outgoing` finds zero offenders. /// 3. The real push runs; git calls the script again → data flows to /// `actual` → HEAD populates `actual`. /// /// With guard: `reject_receive_pack_override` fires before any dry-run → /// `actual` stays empty. /// Without guard: decoy supplies exemption; push lands in `actual`. /// /// Mutation-sensitive: removing `reject_receive_pack_override` from /// `verify_push` makes the bypass succeed; `actual/refs/heads/main` appears /// and the `show-ref` assertion fires. #[test] fn wrapper_refuses_receive_pack_flag_and_leaves_target_empty() { use std::os::unix::fs::PermissionsExt; let (_shim, path, _email, _keydir) = signed_shim_env(); let repo = human_repo(); // `decoy` already holds the offending HEAD — ls-remote here supplies the // exclusion set that exempts HEAD from outgoing verification. let decoy = tempfile::tempdir().unwrap(); // `actual` starts empty — this is where data lands under the bypass. let actual = tempfile::tempdir().unwrap(); // Init both bare repos. assert!(hermetic_command("git") .args(["init", "-q", "--bare", decoy.path().to_str().unwrap()]) .status() .unwrap() .success()); assert!(hermetic_command("git") .args(["init", "-q", "--bare", actual.path().to_str().unwrap()]) .status() .unwrap() .success()); // Seed decoy with the human HEAD commit. // ls-remote on decoy returns HEAD's IDs; without the guard those IDs // exempt HEAD and the push succeeds to actual. assert!(hermetic_command("git") .args([ "-C", repo.path().to_str().unwrap(), "push", "-q", decoy.path().to_str().unwrap(), "HEAD:refs/heads/main", ]) .status() .unwrap() .success()); // Wire origin → decoy. The porcelain To header will show the decoy URL; // ls-remote on that URL returns HEAD's IDs (the bypass exclusion source). wrapper( &path, repo.path(), &["remote", "add", "origin", decoy.path().to_str().unwrap()], ); // The receivepack script ignores its argument and routes all // receive-pack traffic to `actual` instead. Without the guard, git's // dry-run + real push both talk to actual via this script while ls-remote // exempts HEAD by reading decoy. let actual_path = actual.path().to_str().unwrap().to_owned(); let script = repo.path().join("rp.sh"); std::fs::write( &script, format!("#!/bin/sh\nexec git-receive-pack {actual_path}\n"), ) .unwrap(); std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap(); // ── Test 1a: --receive-pack=