ci(block): pin merge evidence and refuse control changes

This commit is contained in:
pingqiu committed 2026-12-05 00:16:07 -08:00
1 parent 9bdd7f25e0
commit 12b9f2f037
2 files changed
+91 -7

No files matched your search

+68 -1
View File
@@ -6,6 +6,7 @@ import os
import subprocess
import tempfile
import unittest
from unittest.mock import patch
HERE = Path(__file__).resolve().parent
ROOT = HERE.parents[2]
@@ -115,7 +116,7 @@ class PortTests(unittest.TestCase):
spec = importlib.util.spec_from_file_location("safe_merge", HERE / "safe-merge-check.py")
check = importlib.util.module_from_spec(spec); spec.loader.exec_module(check)
pr = {"number": 1, "state": "open", "draft": False, "mergeable": True, "base": {"ref": "master"}, "head": {"sha": "head"}}
run = {"name": "Block Test", "head_sha": "head", "status": "completed", "conclusion": "success", "pull_requests": [{"number": 1, "base": {"sha": "base"}}]}
run = {"path": ".github/workflows/block-test.yml", "name": "Block Test", "head_sha": "head", "status": "completed", "conclusion": "success", "pull_requests": [{"number": 1, "base": {"sha": "base"}}]}
jobs = [{"name": n, "conclusion": "success"} for n in check.JOBS]
check.validate(pr, run, jobs, "base")
for key, value in (("head_sha", "other"), ("conclusion", "cancelled"), ("name", "Other Test")):
@@ -126,6 +127,62 @@ class PortTests(unittest.TestCase):
failed = copy.deepcopy(jobs); failed[0]["conclusion"] = "failure"
with self.assertRaises(ValueError): check.validate(pr, run, failed, "base")
def test_same_named_workflow_cannot_satisfy_the_gate(self):
spec = importlib.util.spec_from_file_location("safe_merge", HERE / "safe-merge-check.py")
check = importlib.util.module_from_spec(spec); spec.loader.exec_module(check)
pr = {"number": 1, "state": "open", "draft": False, "mergeable": True, "base": {"ref": "master"}, "head": {"sha": "head"}}
run = {"id": 1, "created_at": "1", "path": ".github/workflows/block-test.yml", "name": "Block Test", "head_sha": "head", "status": "completed", "conclusion": "success", "pull_requests": [{"number": 1, "base": {"sha": "base"}}]}
jobs = [{"name": n, "conclusion": "success"} for n in check.JOBS]
duplicate = dict(run, id=2, created_at="2", path=".github/workflows/pretend.yml")
with self.assertRaises(ValueError): check.validate(pr, duplicate, jobs, "base")
missing = dict(run); del missing["path"]
with self.assertRaises(ValueError): check.validate(pr, missing, jobs, "base")
import json
with patch.object(check, "api", return_value={"workflow_runs": [run, duplicate]}), patch.object(check.subprocess, "check_output", return_value=json.dumps([{"jobs": jobs}]).encode()):
self.assertEqual(check.successful_run(pr, "base")["id"], 1)
with patch.object(check, "api", return_value={"workflow_runs": [duplicate]}):
with self.assertRaises(ValueError): check.successful_run(pr, "base")
def test_control_path_changes_need_independent_workflow_review(self):
spec = importlib.util.spec_from_file_location("safe_merge", HERE / "safe-merge-check.py")
check = importlib.util.module_from_spec(spec); spec.loader.exec_module(check)
real_output = subprocess.check_output
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
def git(*args): return real_output(["git", *args], cwd=root, timeout=15)
git("init", "-b", "master"); git("config", "user.name", "Example"); git("config", "user.email", "example@example.invalid"); git("config", "commit.gpgsign", "false")
(root / "code.go").write_text("package example")
git("add", "."); git("commit", "-m", "base")
base = git("rev-parse", "HEAD").decode().strip()
for name in (".github/workflows/pretend.yml", ".github/block/scripts/check.py", ".github/dockerfiles/block-image.Dockerfile", "seaweed-block/.github/scripts/record-go-test.sh"):
path = root / name; path.parent.mkdir(parents=True, exist_ok=True); path.write_text("control")
git("add", "."); git("commit", "-m", "control")
added = git("rev-parse", "HEAD").decode().strip()
with patch.object(check.subprocess, "check_output", side_effect=lambda args, **kw: real_output(args, cwd=root, **kw)):
with self.assertRaisesRegex(ValueError, "workflow_review_required"):
check.check_control_paths(base, added)
git("rm", name); git("commit", "-m", "remove")
removed = git("rev-parse", "HEAD").decode().strip()
with patch.object(check.subprocess, "check_output", side_effect=lambda args, **kw: real_output(args, cwd=root, **kw)):
with self.assertRaisesRegex(ValueError, "workflow_review_required"):
check.check_control_paths(added, removed)
(root / "code.go").write_text("package example\nconst N=2")
git("add", "."); git("commit", "-m", "code")
head = git("rev-parse", "HEAD").decode().strip()
with patch.object(check.subprocess, "check_output", side_effect=lambda args, **kw: real_output(args, cwd=root, **kw)):
check.check_control_paths(base, head)
with patch.object(check, "check_control_paths", side_effect=ValueError("workflow_review_required")), patch.object(check.subprocess, "check_output", side_effect=["base", "head"]), patch.object(check.subprocess, "run") as run:
with self.assertRaisesRegex(ValueError, "workflow_review_required"):
check.local_checks({"number": 1, "body": "body", "title": "title", "head": {"sha": "head"}}, "base")
self.assertEqual(run.call_count, 1) # fetch only; no checker certification
def test_fork_runner_guard_is_required_not_only_the_fallback(self):
expected = "${{ (github.event_name == 'push' || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' || github.event.pull_request.head.repo.full_name == github.repository) && vars.BLOCK_RUNNER_LABEL || 'ubuntu-latest' }}"
for name in ("test", "spec-trace", "known-bugs"):
text = (ROOT / (".github/workflows/block-" + name + ".yml")).read_text()
lines = [line.strip() for line in text.splitlines() if line.strip().startswith("runs-on:")]
self.assertEqual(lines, ["runs-on: " + expected])
def test_batch_preserves_pinned_base_heads_order_and_evidence(self):
spec = importlib.util.spec_from_file_location("safe_merge", HERE / "safe-merge-check.py")
check = importlib.util.module_from_spec(spec); spec.loader.exec_module(check)
@@ -138,6 +195,16 @@ class PortTests(unittest.TestCase):
with self.assertRaises(ValueError): check.validate_batch(manifest, list(reversed(prs)), "base")
wrong = copy.deepcopy(prs); wrong[0]["head"]["sha"] = "new"
with self.assertRaises(ValueError): check.validate_batch(manifest, wrong, "base")
batch_manifest = dict(manifest, batch_pr=3)
manifest_path = Path(tmp) / "batch.json"
import json
manifest_path.write_text(json.dumps(batch_manifest))
replies = {"git/ref/heads/master": {"object": {"sha": "base"}}, "pulls/1": prs[0], "pulls/2": prs[1], "pulls/3": {"number": 3, "head": {"sha": "batch"}}}
with patch.object(check, "api", side_effect=lambda path: replies[path]), patch.object(check, "fetch_review_head", side_effect=ValueError("workflow_review_required")) as fetch, patch.object(check, "successful_run") as run:
with self.assertRaisesRegex(ValueError, "workflow_review_required"):
check.main(["--batch", str(manifest_path)])
fetch.assert_called_once_with(replies["pulls/3"], "base")
run.assert_not_called()
evidence.write_text("")
with self.assertRaises(ValueError): check.validate_batch(manifest, prs, "base")
+23 -6
View File
@@ -10,6 +10,7 @@ import tempfile
from pathlib import Path
REPO = "seaweedfs/seaweedfs"
WORKFLOW_PATH = ".github/workflows/block-test.yml"
JOBS = {"go test (linux)", "process-level tests (real binaries)"}
@@ -17,7 +18,7 @@ def validate(pr, run, jobs, current):
if pr["state"] != "open" or pr["draft"] or pr["mergeable"] is not True:
raise ValueError("PR must be open, ready and mergeable")
if pr["base"]["ref"] != "master": raise ValueError("expected master base")
if run["name"] != "Block Test" or run["head_sha"] != pr["head"]["sha"]:
if run.get("path") != WORKFLOW_PATH or run["name"] != "Block Test" or run["head_sha"] != pr["head"]["sha"]:
raise ValueError("wrong workflow or head")
if run["status"] != "completed" or run["conclusion"] != "success":
raise ValueError("Block Test is not successful")
@@ -34,7 +35,7 @@ def api(path):
def successful_run(pr, current):
runs = api("actions/runs?head_sha=" + pr["head"]["sha"] + "&event=pull_request&per_page=100")["workflow_runs"]
runs = [r for r in runs if r["name"] == "Block Test"]
runs = [r for r in runs if r.get("path") == WORKFLOW_PATH and r["name"] == "Block Test"]
if not runs: raise ValueError("no Block Test run")
run = max(runs, key=lambda r: (r["created_at"], r["id"]))
pages = json.loads(subprocess.check_output(["gh", "api", "--paginate", "--slurp", "repos/" + REPO + "/actions/runs/" + str(run["id"]) + "/jobs?per_page=100"]))
@@ -42,16 +43,31 @@ def successful_run(pr, current):
return run
def local_checks(pr, current):
def check_control_paths(base, head):
# Inspect both sides of renames and fail on enumeration errors. These PRs
# need independent workflow review; their own Actions results cannot waive it.
paths = subprocess.check_output(["git", "diff", "--no-renames", "--name-only", "-z", base, head]).split(b"\0")
controls = [p.decode("utf-8", errors="replace") for p in paths if p.startswith((b".github/workflows/", b".github/block/", b".github/dockerfiles/block-", b"seaweed-block/.github/"))]
if controls:
raise ValueError("workflow_review_required: CI controls changed: " + ", ".join(controls))
def fetch_review_head(pr, current):
if subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip() != current:
raise ValueError("run from trusted current master checkout")
subprocess.run(["git", "-c", "fetch.fsckObjects=true", "fetch", "--no-tags", "origin", "+refs/pull/" + str(pr["number"]) + "/head:refs/remotes/block-review/head"], check=True)
actual = subprocess.check_output(["git", "rev-parse", "refs/remotes/block-review/head"], text=True).strip()
if actual != pr["head"]["sha"]: raise ValueError("PR head moved; recheck")
check_control_paths(current, actual)
return actual
def local_checks(pr, current):
actual = fetch_review_head(pr, current)
with tempfile.TemporaryDirectory() as tmp:
body, title = Path(tmp) / "body", Path(tmp) / "title"
body.write_text(pr["body"] or "", encoding="utf-8")
title.write_text(pr["title"], encoding="utf-8")
subprocess.run(["git", "-c", "fetch.fsckObjects=true", "fetch", "--no-tags", "origin", "+refs/pull/" + str(pr["number"]) + "/head:refs/remotes/block-review/head"], check=True)
actual = subprocess.check_output(["git", "rev-parse", "refs/remotes/block-review/head"], text=True).strip()
if actual != pr["head"]["sha"]: raise ValueError("PR head moved; recheck")
subprocess.run(["bash", str(Path(__file__).resolve().with_name("check-pr-base.sh")), current, actual, str(body), str(title)], check=True)
@@ -81,6 +97,7 @@ def main(args):
validate_batch(manifest, prs, current)
batch = api("pulls/" + str(manifest["batch_pr"]))
if batch["head"]["sha"] != manifest["head"]: raise ValueError("batch head changed")
fetch_review_head(batch, current)
run = successful_run(batch, current)
for pr in prs: local_checks(pr, current)
if api("git/ref/heads/master")["object"]["sha"] != current: raise ValueError("master moved; recheck")