From 2cd3285f9698449a0fb209c678ebe2509661f20e Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 30 Oct 2026 13:12:51 +0000 Subject: [PATCH 1/2] ci(admission): bind the queued merge commit to the live PR head by tree (#4836) Resolve queued PR accepted a base-suffixed queue ref when the live PR head's commit date preceded the queued commit. The ref names the base and dates are not content, so a different head H2 older than G was admitted (executed counterexample, #4836 comment 6370396130). The step now requires the queued tree to equal `git merge-tree --write-tree `, with the head fetched from refs/pull//head and required to equal the head read from the API; history is completed first because the queue checkout is depth 1. A different head, extra content, a merge conflict, a moved PR ref or a failed fetch refuses. The premise (GitHub's squash tree equals that merge) held for 60/60 recent squash merges to main. xtask/tests/routed_queue_resolution.rs extracts the production step and runs it over real Git objects behind a stubbed gh, including a guard-removal control for the counterexample. The two source pins that required the timestamp snippet now pin the PR-ref and tree comparisons in repo-policy and xtask. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013kSch2opYors8Yb2NR1ZMd --- .github/workflows/routed-rust.yml | 20 +- .../4836-queued-commit-tree-binding.md | 2 + docs/CI.md | 16 +- policy/process_allowlist.txt | 2 + tools/repo-policy/src/lib.rs | 8 +- tools/repo-policy/src/workflow_tests.rs | 8 +- xtask/src/tests.rs | 8 +- xtask/tests/routed_queue_resolution.rs | 520 ++++++++++++++++++ 8 files changed, 557 insertions(+), 27 deletions(-) create mode 100644 changelog.d/4836-queued-commit-tree-binding.md create mode 100644 xtask/tests/routed_queue_resolution.rs diff --git a/.github/workflows/routed-rust.yml b/.github/workflows/routed-rust.yml index bebf99f56dd..dca887081cd 100644 --- a/.github/workflows/routed-rust.yml +++ b/.github/workflows/routed-rust.yml @@ -265,28 +265,28 @@ jobs: # and may equal the group's base otherwise. Admission is per PR: the # queued commit must be one squash commit of that PR directly on the # group's base, so the workflow itself refuses a batch (fail closed) - # even if the ruleset group size is misconfigured. + # even if the ruleset group size is misconfigured. Its tree must be + # that head merged onto the base (checked below). [[ "$GROUP_HEAD_REF" =~ /pr-([0-9]+)-([0-9a-f]{40})$ ]] || { echo "::error::merge group ref names no queued PR: $GROUP_HEAD_REF"; exit 1; } pr="${BASH_REMATCH[1]}" ref_sha="${BASH_REMATCH[2]}" current="$(gh api "repos/${REPOSITORY}/pulls/${pr}")" head="$(jq -r '.head.sha' <<<"$current")" { [ "$ref_sha" = "$head" ] || [ "$ref_sha" = "$GROUP_BASE_SHA" ]; } || { echo "::error::queue ref sha $ref_sha is neither the live head $head of PR #${pr} (pushed after enqueue) nor the group base $GROUP_BASE_SHA"; exit 1; } commit="$(gh api "repos/${REPOSITORY}/commits/${GROUP_HEAD_SHA}")" - if [ "$ref_sha" != "$head" ]; then - # The ref names the base, so it cannot prove the queued squash is of - # the live head. GitHub itself dequeues a PR whose head changes; this - # is defense in depth: a head committed no earlier than the queued - # squash is refused (a backdated push is not detected). - queued_at="$(jq -r '.commit.committer.date' <<<"$commit")" - pushed_at="$(gh api "repos/${REPOSITORY}/commits/${head}" --jq '.commit.committer.date')" - [[ "$pushed_at" < "$queued_at" ]] || { echo "::error::PR #${pr} head $head (committed $pushed_at) is newer than the queued commit (committed $queued_at)"; exit 1; } - fi parents="$(jq -r '.parents | length' <<<"$commit")" subject="$(jq -r '.commit.message | split("\n")[0]' <<<"$commit")" parent="$(jq -r '.parents[0].sha // empty' <<<"$commit")" # A group's base is the parent of its first commit, so a one-entry # group has base == the queued commit's parent; a batch does not. { [ "$parents" = "1" ] && [ "$parent" = "$GROUP_BASE_SHA" ] && [[ "$subject" == *"(#${pr})" ]]; } || { echo "::error::queued commit is not a single squash commit of PR #${pr} ($parents parents, parent $parent, base $GROUP_BASE_SHA: $subject); candidate admission requires exactly one queued PR per group"; exit 1; } + # The ref sha and commit dates do not bind the live head to the queued + # commit, so bind by content: the queued tree must be exactly the live + # head merged onto the group base. The head comes from the PR's own + # ref and must still be the head read above; no match, merge conflict + # or missing history refuses (fail closed). + { [ "$(git rev-parse --is-shallow-repository)" = false ] || git fetch --no-tags --unshallow origin; } || { echo "::error::cannot complete history to bind the queued commit to PR #${pr}"; exit 1; } + fetched="$(git fetch --no-tags origin "refs/pull/${pr}/head" && git rev-parse FETCH_HEAD)" && [ "$fetched" = "$head" ] || { echo "::error::refs/pull/${pr}/head (${fetched:-unfetched}) is not the live head $head of PR #${pr}"; exit 1; } + merged="$(git merge-tree --write-tree "$GROUP_BASE_SHA" "$head")" && [ "${merged%%$'\n'*}" = "$(git rev-parse "${GROUP_HEAD_SHA}^{tree}")" ] || { echo "::error::queued commit ${GROUP_HEAD_SHA} is not PR #${pr} head $head merged onto base $GROUP_BASE_SHA"; exit 1; } queue=$(gh api graphql -f query='query($number:Int!){repository(owner:"EffortlessMetrics",name:"ripr-swarm"){pullRequest(number:$number){headRefOid mergeQueueEntry{id}}}}' -F number="$pr") queue_entry=$(jq -er --arg head "$head" 'select(.errors == null) | .data.repository.pullRequest | select(.headRefOid == $head) | .mergeQueueEntry.id | select(type == "string" and length > 0)' <<<"$queue") labels="$(jq -r '[.labels[].name] | join(",")' <<<"$current")" diff --git a/changelog.d/4836-queued-commit-tree-binding.md b/changelog.d/4836-queued-commit-tree-binding.md new file mode 100644 index 00000000000..28251d3dc10 --- /dev/null +++ b/changelog.d/4836-queued-commit-tree-binding.md @@ -0,0 +1,2 @@ + +- Routed admission binds a merge-queue commit to the live PR head by tree (head merged onto the group base) instead of a commit-date comparison, refusing a different head, extra content, a merge conflict or a moved PR ref (#4836). diff --git a/docs/CI.md b/docs/CI.md index 7031b088ba0..cbd6c228d38 100644 --- a/docs/CI.md +++ b/docs/CI.md @@ -57,8 +57,12 @@ number comes from the merge-group branch name (`gh-readonly-queue//pr--`) and the PR's labels are forwarded to the gate (`full-ci` still selects the advisory reports, `ripr-waive` still reaches the PR-evidence step). The resolver accepts a head-suffixed ref or a -base-suffixed fallback; the latter does not authoritatively identify the queued -H. Admission is per PR, so the queue must use a group size of 1; the queued commit must be a single +base-suffixed fallback; neither ref spelling identifies the queued H, so the +queued commit's tree must also equal the live head merged onto the group base +(`git merge-tree --write-tree `, with the head fetched from the +PR's own `refs/pull//head` and required to match the head read from the API). +A different head, extra content, a merge conflict, a moved PR ref or missing +history refuses. Admission is per PR, so the queue must use a group size of 1; the queued commit must be a single squash commit of the queued PR sitting directly on the group's `base_sha`, or admission refuses it, so a batch fails closed even if the ruleset is misconfigured. Batching needs per-PR admission (#8082) and is a follow-up. The `merge-ready` label request below still works until the label request is @@ -72,9 +76,11 @@ review decision, and every page of review threads. Missing or malformed evidence refuses the result; a Result-only retry cannot reuse admission from an older attempt. Main/manual authorities and child-result checks remain. -This is a late eligibility check, not queue-cutover acceptance. The current -base-suffixed queue-ref fallback still uses a timestamp and does not establish -the reviewed/admitted H or its composed G tree. Candidate-local admission code +This is a late eligibility check, not queue-cutover acceptance. The tree match +binds the queued commit to the head GitHub reports live at admission; it does not +establish that this is the head a reviewer judged ready, and its premise (GitHub's +squash tree equals `merge-tree(base, head)`) is checked here only on past +squash merges and by local fixtures, not on a native queue entry. Candidate-local admission code also remains a trusted-source prerequisite. Neither these API freshness reads nor a tree match authenticates an arbitrary caller workflow or makes the final read and protected merge atomic. Preserve the installed gates until the diff --git a/policy/process_allowlist.txt b/policy/process_allowlist.txt index a98e1be342e..b2f3029ede2 100644 --- a/policy/process_allowlist.txt +++ b/policy/process_allowlist.txt @@ -216,6 +216,8 @@ xtask/tests/hard_cut_admission_selftest.rs|Command::new|5|hard-cut-admission-sel xtask/tests/hard_cut_admission_selftest.rs|use std::process::Command|1|hard-cut-admission-selftest|#5391: imports Command only for the bounded self-test invocation described above. xtask/tests/routed_dispatch_result.rs|Command::new|2|routed-dispatch-result|#5394: executes the checked-in Result and admission shells locally with fixture environments; no GitHub dispatch, credential or network operation. xtask/tests/routed_dispatch_result.rs|use std::process::Command|1|routed-dispatch-result|#5394: imports Command only for the bounded workflow shell controls described above. +xtask/tests/routed_queue_resolution.rs|Command::new|2|routed-queue-resolution|#4836: builds throwaway local Git repositories (hermetic config, file:// remote) and executes the checked-in Resolve queued PR shell against a stubbed read-only gh in a temp dir; no GitHub dispatch, credential or network operation. +xtask/tests/routed_queue_resolution.rs|use std::process::Command|1|routed-queue-resolution|#4836: imports Command only for the bounded Git and workflow shell controls described above. xtask/tests/windows_shard_summary.rs|Command::new|1|windows-shard-summary|#9272: runs the checked-in Summarize failures step through bash against a colored fixture log; no network, credential or GitHub operation. xtask/tests/windows_shard_summary.rs|use std::process::Command|1|windows-shard-summary|#9272: imports Command only for the bounded summary-step control above. crates/ripr/tests/call_budget_repo_exposure.rs|Command::new|1|call-budget-repo-exposure|#8600: runs the built ripr binary over a temp workspace with a distinct-callee test line to read the repo-exposure seam record; no network or credential operation. diff --git a/tools/repo-policy/src/lib.rs b/tools/repo-policy/src/lib.rs index 13e7332f5e2..5bd24ebcdac 100644 --- a/tools/repo-policy/src/lib.rs +++ b/tools/repo-policy/src/lib.rs @@ -1331,12 +1331,12 @@ pub fn routed_rust_ready_event_contract_violations(workflow: &str) -> Vec PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("..") +} + +struct Scratch(PathBuf); + +impl Scratch { + fn new() -> Result { + let path = std::env::temp_dir().join(format!( + "ripr-queue-resolution-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir_all(&path).map_err(|e| e.to_string())?; + Ok(Self(path)) + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +/// The `run:` body of the production `Resolve queued PR` step, de-indented. +fn resolve_shell(source: &str) -> Result { + let (_, rest) = source + .split_once(" - name: Resolve queued PR\n") + .ok_or("missing actual Resolve queued PR step")?; + let (step, _) = rest + .split_once(" - name: Admit exact candidate\n") + .ok_or("missing step after Resolve queued PR")?; + let (_, body) = step + .split_once(" run: |\n") + .ok_or("missing Resolve queued PR shell")?; + body.lines() + .map(|line| { + if line.is_empty() { + Ok("") + } else { + line.strip_prefix(" ") + .ok_or("unexpected Resolve queued PR shell nesting") + } + }) + .collect::, _>>() + .map(|lines| lines.join("\n")) + .map_err(str::to_string) +} + +fn workflow() -> Result { + fs::read_to_string(root().join(".github/workflows/routed-rust.yml")).map_err(|e| e.to_string()) +} + +/// Hermetic Git: no user, system or global configuration, fixed identity. +fn git_command(dir: &Path) -> Command { + let mut command = Command::new("git"); + command + .current_dir(dir) + .env("GIT_CONFIG_NOSYSTEM", "1") + .env("GIT_CONFIG_GLOBAL", "/dev/null") + .env("GIT_AUTHOR_NAME", "fixture") + .env("GIT_AUTHOR_EMAIL", "fixture@example.invalid") + .env("GIT_COMMITTER_NAME", "fixture") + .env("GIT_COMMITTER_EMAIL", "fixture@example.invalid"); + command +} + +fn git(dir: &Path, args: &[&str]) -> Result { + let output = git_command(dir) + .args(args) + .output() + .map_err(|e| e.to_string())?; + if !output.status.success() { + return Err(format!( + "git {args:?} failed: {}", + String::from_utf8_lossy(&output.stderr) + )); + } + Ok(String::from_utf8_lossy(&output.stdout).trim().to_string()) +} + +fn commit_file(dir: &Path, file: &str, content: &str, message: &str) -> Result { + fs::write(dir.join(file), content).map_err(|e| e.to_string())?; + git(dir, &["add", file])?; + git(dir, &["commit", "-q", "-m", message])?; + git(dir, &["rev-parse", "HEAD"]) +} + +/// Real commits behind a bare `origin`, published as the refs a queue run sees. +struct World { + scratch: Scratch, + work: PathBuf, + origin: PathBuf, + /// Group base B: main after it moved past the PR's merge base. + base: String, + /// A PR head branched from the old base, changing `a.txt`. + head: String, + /// A different PR head (changes `c.txt`) branched from the same old base. + other_head: String, + /// A PR head whose `b.txt` edit conflicts with B. + conflicting_head: String, +} + +impl World { + fn new() -> Result { + let scratch = Scratch::new()?; + let work = scratch.0.join("work"); + let origin = scratch.0.join("origin.git"); + fs::create_dir(&work).map_err(|e| e.to_string())?; + fs::create_dir(&origin).map_err(|e| e.to_string())?; + git(&origin, &["init", "-q", "--bare"])?; + git(&work, &["init", "-q", "-b", "main"])?; + commit_file(&work, "a.txt", "one\n", "root")?; + commit_file(&work, "b.txt", "base\n", "base files")?; + let old_base = git(&work, &["rev-parse", "HEAD"])?; + git(&work, &["checkout", "-q", "-b", "feature", &old_base])?; + let head = commit_file(&work, "a.txt", "one\nfeature\n", "feature")?; + git(&work, &["checkout", "-q", "-b", "other", &old_base])?; + let other_head = commit_file(&work, "c.txt", "other\n", "other")?; + git(&work, &["checkout", "-q", "-b", "conflict", &old_base])?; + let conflicting_head = commit_file(&work, "b.txt", "theirs\n", "conflicting")?; + git(&work, &["checkout", "-q", "main"])?; + // The base moved after the PR was branched, so the merge is not a + // fast-forward and the merge base is not B. + let base = commit_file(&work, "b.txt", "ours\n", "main moved")?; + let url = format!("file://{}", origin.display()); + git(&work, &["remote", "add", "origin", &url])?; + git(&work, &["push", "-q", "origin", "main"])?; + Ok(Self { + scratch, + work, + origin, + base, + head, + other_head, + conflicting_head, + }) + } + + /// What GitHub builds for a one-entry squash group: `merge-tree(B, H)` as a + /// single child of B whose subject ends with the PR number. + fn squash(&self, head: &str, subject: &str) -> Result { + let tree = git( + &self.work, + &["merge-tree", "--write-tree", &self.base, head], + )?; + self.commit_tree(&tree, &self.base, subject) + } + + fn commit_tree(&self, tree: &str, parent: &str, subject: &str) -> Result { + git( + &self.work, + &["commit-tree", tree, "-p", parent, "-m", subject], + ) + } + + fn publish(&self, reference: &str, sha: &str) -> Result<(), String> { + git( + &self.work, + &["push", "-q", "-f", "origin", &format!("{sha}:{reference}")], + ) + .map(|_| ()) + } + + /// Mirror `actions/checkout` for a merge_group run: depth 1 at G. + fn shallow_checkout_of(&self, queued: &str) -> Result { + self.publish("refs/heads/queue", queued)?; + let clone = self.scratch.0.join("clone"); + if clone.exists() { + fs::remove_dir_all(&clone).map_err(|e| e.to_string())?; + } + fs::create_dir(&clone).map_err(|e| e.to_string())?; + let url = format!("file://{}", self.origin.display()); + git(&clone, &["init", "-q"])?; + git(&clone, &["remote", "add", "origin", &url])?; + git( + &clone, + &[ + "fetch", + "-q", + "--no-tags", + "--depth", + "1", + "origin", + "refs/heads/queue", + ], + )?; + git(&clone, &["checkout", "-q", "--detach", "FETCH_HEAD"])?; + assert_eq!( + git(&clone, &["rev-parse", "--is-shallow-repository"])?, + "true", + "the fixture must start from a depth-1 checkout like the workflow" + ); + Ok(clone) + } +} + +/// What the stubbed GitHub API reports and what the queue event carries. +struct Run { + queued: String, + /// Live head the pulls API reports for the PR. + api_head: String, + /// The sha embedded in the queue ref name. + ref_sha: String, + /// `refs/pull//head` on the remote. + pull_ref: String, + /// The group base B the queue event reports. + group_base: String, +} + +struct Outcome { + accepted: bool, + log: String, + outputs: BTreeMap, +} + +fn run_resolve(world: &World, shell: &str, run: &Run) -> Result { + world.publish(&format!("refs/pull/{PR}/head"), &run.pull_ref)?; + let clone = world.shallow_checkout_of(&run.queued)?; + let scratch = &world.scratch.0; + + let parents = git(&world.work, &["log", "-1", "--format=%P", &run.queued])?; + let subject = git(&world.work, &["log", "-1", "--format=%s", &run.queued])?; + let commit = json!({ + "parents": parents.split_whitespace().map(|p| json!({"sha": p})).collect::>(), + "commit": {"message": format!("{subject}\n\nbody")}, + }); + let pr = json!({"head": {"sha": run.api_head}, "labels": [{"name": "merge-ready"}]}); + let graphql = json!({"data": {"repository": {"pullRequest": { + "headRefOid": run.api_head, + "mergeQueueEntry": {"id": "entry-42"}, + }}}}); + + let bin = scratch.join("bin"); + fs::create_dir_all(&bin).map_err(|e| e.to_string())?; + let gh = bin.join("gh"); + fs::write( + &gh, + r#"#!/bin/sh +case "$2" in + graphql) printf '%s\n' "$MOCK_GRAPHQL" ;; + repos/*/pulls/42) printf '%s\n' "$MOCK_PR" ;; + repos/*/commits/*) printf '%s\n' "$MOCK_COMMIT" ;; + *) exit 97 ;; +esac +"#, + ) + .map_err(|e| e.to_string())?; + fs::set_permissions(&gh, fs::Permissions::from_mode(0o700)).map_err(|e| e.to_string())?; + let script = scratch.join("resolve.sh"); + fs::write(&script, shell).map_err(|e| e.to_string())?; + let github_output = scratch.join("github-output"); + let _ = fs::remove_file(&github_output); + + let paths = std::iter::once(bin) + .chain(std::env::split_paths( + &std::env::var_os("PATH").ok_or("PATH unavailable")?, + )) + .collect::>(); + let head_ref = format!("refs/heads/gh-readonly-queue/main/pr-{PR}-{}", run.ref_sha); + let output = Command::new("bash") + .arg("-e") + .arg(&script) + .current_dir(&clone) + .env_clear() + .env( + "PATH", + std::env::join_paths(&paths).map_err(|e| e.to_string())?, + ) + .env("HOME", scratch) + .env("GIT_CONFIG_NOSYSTEM", "1") + .env("GIT_CONFIG_GLOBAL", "/dev/null") + .env("GIT_TERMINAL_PROMPT", "0") + .env("GH_TOKEN", "fixture") + .env("EVENT_NAME", "merge_group") + .env("REPOSITORY", REPOSITORY) + .env("PR_NUMBER", "") + .env("PR_HEAD_SHA", "") + .env("PR_LABELS", "") + .env("GROUP_HEAD_REF", head_ref) + .env("GROUP_BASE_SHA", &run.group_base) + .env("GROUP_HEAD_SHA", &run.queued) + .env("GITHUB_RUN_ID", "100") + .env("GITHUB_RUN_ATTEMPT", "1") + .env("GITHUB_OUTPUT", &github_output) + .env("MOCK_PR", pr.to_string()) + .env("MOCK_COMMIT", commit.to_string()) + .env("MOCK_GRAPHQL", graphql.to_string()) + .output() + .map_err(|e| e.to_string())?; + let outputs = fs::read_to_string(&github_output) + .unwrap_or_default() + .lines() + .filter_map(|line| line.split_once('=')) + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect(); + Ok(Outcome { + accepted: output.status.success(), + log: format!( + "{}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ), + outputs, + }) +} + +/// A run for the unchanged live head `head`, queued as its real squash. +fn honest(world: &World, head: &str, ref_sha: &str) -> Result { + Ok(Run { + queued: world.squash(head, &format!("feature (#{PR})"))?, + api_head: head.to_string(), + ref_sha: ref_sha.to_string(), + pull_ref: head.to_string(), + group_base: world.base.clone(), + }) +} + +fn assert_refused(outcome: &Outcome, needle: &str) { + assert!(!outcome.accepted, "must refuse: {}", outcome.log); + assert!( + outcome.log.contains(needle), + "refusal must name `{needle}`: {}", + outcome.log + ); + assert!( + !outcome.outputs.contains_key("queue_entry"), + "a refusal must publish no admission outputs: {:?}", + outcome.outputs + ); +} + +#[test] +fn queued_squash_of_the_live_head_is_accepted_whether_the_ref_names_head_or_base() +-> Result<(), String> { + let world = World::new()?; + let shell = resolve_shell(&workflow()?)?; + for ref_sha in [world.head.clone(), world.base.clone()] { + let run = honest(&world, &world.head, &ref_sha)?; + let outcome = run_resolve(&world, &shell, &run)?; + assert!( + outcome.accepted, + "honest queue entry refused: {}", + outcome.log + ); + assert_eq!(outcome.outputs.get("pr").map(String::as_str), Some(PR)); + assert_eq!( + outcome.outputs.get("head"), + Some(&world.head), + "the admitted head is the live head" + ); + assert_eq!( + outcome.outputs.get("queue_entry").map(String::as_str), + Some("entry-42") + ); + } + Ok(()) +} + +/// #4836 October 23: the queue ref names B, the live head H2 differs from the +/// head H1 that G squashed, and H2's commit predates G. Dates and the ref +/// suffix cannot tell; the tree can. +#[test] +fn queued_squash_of_a_different_head_is_refused_even_when_it_predates_the_queue_commit() +-> Result<(), String> { + let world = World::new()?; + let shell = resolve_shell(&workflow()?)?; + let mut run = honest(&world, &world.head, &world.base)?; + run.api_head = world.other_head.clone(); + run.pull_ref = world.other_head.clone(); + let outcome = run_resolve(&world, &shell, &run)?; + assert_refused(&outcome, "is not PR #42 head"); + + // Control: the same inputs are admitted when the one binding is removed, + // so the refusal above is caused by the tree comparison alone. + let weakened = shell.replace( + "[ \"${merged%%$'\\n'*}\" = \"$(git rev-parse \"${GROUP_HEAD_SHA}^{tree}\")\" ]", + "true", + ); + assert_ne!( + weakened, shell, + "the tree comparison must exist to be removed" + ); + let outcome = run_resolve(&world, &weakened, &run)?; + assert!( + outcome.accepted, + "without the tree comparison the counterexample is admitted: {}", + outcome.log + ); + assert_eq!(outcome.outputs.get("head"), Some(&world.other_head)); + Ok(()) +} + +#[test] +fn queued_commit_with_extra_content_is_refused() -> Result<(), String> { + let world = World::new()?; + let shell = resolve_shell(&workflow()?)?; + let tree = git( + &world.work, + &["merge-tree", "--write-tree", &world.base, &world.head], + )?; + // Same parent and subject as an honest squash, but one extra file. + git( + &world.work, + &["checkout", "-q", "-b", "tamper", &world.base], + )?; + git(&world.work, &["read-tree", &tree])?; + fs::write(world.work.join("extra.txt"), "smuggled\n").map_err(|e| e.to_string())?; + git(&world.work, &["add", "extra.txt"])?; + let tampered_tree = git(&world.work, &["write-tree"])?; + let queued = world.commit_tree(&tampered_tree, &world.base, "feature (#42)")?; + let run = Run { + queued, + api_head: world.head.clone(), + ref_sha: world.head.clone(), + pull_ref: world.head.clone(), + group_base: world.base.clone(), + }; + assert_refused(&run_resolve(&world, &shell, &run)?, "is not PR #42 head"); + Ok(()) +} + +#[test] +fn moved_or_unavailable_pull_ref_is_refused() -> Result<(), String> { + let world = World::new()?; + let shell = resolve_shell(&workflow()?)?; + // The PR's own ref no longer names the head the API reported. + let mut run = honest(&world, &world.head, &world.head)?; + run.pull_ref = world.other_head.clone(); + assert_refused(&run_resolve(&world, &shell, &run)?, "is not the live head"); + + // The reported head cannot be fetched at all: nothing is invented. + let mut run = honest(&world, &world.head, &world.base)?; + run.api_head = "f".repeat(40); + run.ref_sha = world.base.clone(); + assert_refused(&run_resolve(&world, &shell, &run)?, "is not the live head"); + Ok(()) +} + +#[test] +fn head_that_conflicts_with_the_base_cannot_bind_any_queued_tree() -> Result<(), String> { + let world = World::new()?; + let shell = resolve_shell(&workflow()?)?; + // A queued commit claiming the conflicting head; its tree is arbitrary + // because no clean merge exists to compare with. + let queued = world.commit_tree( + &git( + &world.work, + &["rev-parse", &format!("{}^{{tree}}", world.base)], + )?, + &world.base, + "conflicting (#42)", + )?; + let run = Run { + queued, + api_head: world.conflicting_head.clone(), + ref_sha: world.base.clone(), + pull_ref: world.conflicting_head.clone(), + group_base: world.base.clone(), + }; + assert_refused(&run_resolve(&world, &shell, &run)?, "is not PR #42 head"); + Ok(()) +} + +#[test] +fn batch_wrong_parent_and_wrong_subject_still_refuse_before_the_tree_is_read() -> Result<(), String> +{ + let world = World::new()?; + let shell = resolve_shell(&workflow()?)?; + + // Subject does not name the PR. + let mut run = honest(&world, &world.head, &world.base)?; + run.queued = world.squash(&world.head, "feature (#43)")?; + assert_refused( + &run_resolve(&world, &shell, &run)?, + "not a single squash commit", + ); + + // Parent is not the group base (a batch built on an earlier entry). + let mut run = honest(&world, &world.head, &world.base)?; + run.group_base = world.head.clone(); + run.ref_sha = world.head.clone(); + assert_refused( + &run_resolve(&world, &shell, &run)?, + "not a single squash commit", + ); + + // The ref sha is neither the live head nor the base. + let mut run = honest(&world, &world.head, &world.base)?; + run.ref_sha = world.other_head.clone(); + assert_refused( + &run_resolve(&world, &shell, &run)?, + "is neither the live head", + ); + Ok(()) +} From c9396f753be1b005671428a9e66430980363b077 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 30 Oct 2026 14:33:38 +0000 Subject: [PATCH 2/2] test(admission): generic next-step split and discriminating conflict-tree case (#8082) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013kSch2opYors8Yb2NR1ZMd --- xtask/tests/routed_queue_resolution.rs | 36 ++++++++++++++++++-------- 1 file changed, 25 insertions(+), 11 deletions(-) diff --git a/xtask/tests/routed_queue_resolution.rs b/xtask/tests/routed_queue_resolution.rs index 12aeb8ab098..344e3351476 100644 --- a/xtask/tests/routed_queue_resolution.rs +++ b/xtask/tests/routed_queue_resolution.rs @@ -52,7 +52,7 @@ fn resolve_shell(source: &str) -> Result { .split_once(" - name: Resolve queued PR\n") .ok_or("missing actual Resolve queued PR step")?; let (step, _) = rest - .split_once(" - name: Admit exact candidate\n") + .split_once("\n - name:") .ok_or("missing step after Resolve queued PR")?; let (_, body) = step .split_once(" run: |\n") @@ -465,16 +465,30 @@ fn moved_or_unavailable_pull_ref_is_refused() -> Result<(), String> { fn head_that_conflicts_with_the_base_cannot_bind_any_queued_tree() -> Result<(), String> { let world = World::new()?; let shell = resolve_shell(&workflow()?)?; - // A queued commit claiming the conflicting head; its tree is arbitrary - // because no clean merge exists to compare with. - let queued = world.commit_tree( - &git( - &world.work, - &["rev-parse", &format!("{}^{{tree}}", world.base)], - )?, - &world.base, - "conflicting (#42)", - )?; + // A conflicting `merge-tree --write-tree` exits 1 but still prints a tree OID + // (with conflict markers) on its first stdout line. Queue exactly that tree, + // so only the step honouring merge-tree's exit status can refuse it. + let output = git_command(&world.work) + .args([ + "merge-tree", + "--write-tree", + &world.base, + &world.conflicting_head, + ]) + .output() + .map_err(|e| e.to_string())?; + if output.status.code() != Some(1) { + return Err(format!( + "expected a conflicting merge, got {:?}", + output.status + )); + } + let stdout = String::from_utf8_lossy(&output.stdout).into_owned(); + let tree = stdout + .lines() + .next() + .ok_or("conflicting merge-tree printed no tree")?; + let queued = world.commit_tree(tree, &world.base, "conflicting (#42)")?; let run = Run { queued, api_head: world.conflicting_head.clone(),