Answer security round 1: 0 🔴, 1 🟡 (0 misread); take only origin's own pull request at the branch's head and merge it pinned to that head

This commit is contained in:
2026-11-08 10:47:36 +01:00
parent 29b986ca42
commit f6e96da675
7 changed files with 122 additions and 58 deletions
+56 -15
View File
@@ -156,24 +156,30 @@ def git(*words):
return subprocess.run(["git", "--git-dir", state["origin"], *words], capture_output=True, text=True)
def pull(number):
return next(found for found in state["pulls"] if str(found["number"]) == number)
def merge(number):
head = git("rev-parse", "refs/heads/" + pull(number)["head"]).stdout.strip()
def merge(number, guard):
head = pull(number)["sha"]
if head != guard:
save()
sys.exit("head commit changed")
if git("merge-base", "--is-ancestor", "refs/heads/main", head).returncode:
save()
sys.exit("Not possible to fast-forward")
git("update-ref", "refs/heads/main", head)
pull(number)["state"] = "merged"
opened = [found for found in state["pulls"] if found["state"] == "open"]
if forge == "tea" and args == ["pulls", "list", "--fields", "index,head,url", "--output", "tsv"]:
print("index\thead\turl")
for found in opened:
print(f"{found['number']}\t{found['head']}\thttps://forge/pulls/{found['number']}")
elif forge == "gh" and args[:3] == ["pr", "list", "--head"]:
if forge == "tea" and args == ["api", "repos/{owner}/{repo}/pulls?state=open&limit=50"]:
repo = lambda found: {"full_name": "fork/r" if found["fork"] else "o/r"}
print(json.dumps([{"number": found["number"], "head": {"ref": found["head"], "sha": found["sha"], "repo": repo(found)}, "base": {"repo": {"full_name": "o/r"}}} for found in opened]))
elif forge == "gh" and args[:3] == ["pr", "list", "--head"] and args[4:6] == ["--json", "number,headRefOid,isCrossRepository"]:
for found in opened:
if found["head"] == args[3]:
print(f"{found['number']}\thttps://forge/pull/{found['number']}")
print(f"{found['number']}\t{found['sha']}\t{str(found['fork']).lower()}")
elif args[:2] in (["pulls", "create"], ["pr", "create"]):
state["pulls"].append({"number": len(state["pulls"]) + 1, "head": args[args.index("--head") + 1], "state": "open"})
head = args[args.index("--head") + 1]
if any(found["head"] == head and not found["fork"] for found in opened):
save()
sys.exit("pull request already exists for these targets")
state["pulls"].append({"number": len(state["pulls"]) + 1, "head": head, "sha": git("rev-parse", "refs/heads/" + head).stdout.strip(), "fork": False, "state": "open"})
elif forge == "tea" and args[0] == "api" and args[1].endswith("/status"):
checks = state["checks"]
print(json.dumps({"state": "pending" if checks == "none" else checks, "total_count": 0 if checks == "none" else 1}))
@@ -184,10 +190,14 @@ elif forge == "gh" and args[:2] == ["pr", "checks"]:
if state["checks"] == "failure":
save()
sys.exit("lint\tfail")
elif args[:3] == ["pulls", "merge", "--style"] and args[3] == "fast-forward-only":
merge(args[4])
elif args[:2] == ["pr", "merge"] and args[3] == "--rebase":
merge(args[2])
elif forge == "tea" and args[:5] == ["api", "--method", "POST", "--field", "Do=fast-forward-only"] and args[5] == "--field" and args[7].endswith("/merge"):
try:
merge(args[7].split("/")[-2], args[6].removeprefix("head_commit_id="))
except SystemExit as refused:
# Gitea answers an error with a message, and tea api exits 0 all the same.
print(json.dumps({"message": str(refused)}))
elif args[:2] == ["pr", "merge"] and args[3:5] == ["--rebase", "--match-head-commit"]:
merge(args[2], args[5])
else:
save()
sys.exit("unexpected call")
@@ -264,7 +274,7 @@ class Cut(unittest.TestCase):
self.assertIn("v0.2.0", ran.stdout)
calls = self.forge_state()["calls"]
self.assertIn(["tea", "pulls", "create", "--head", "release-0.2.0", "--base", "main"], [call[:7] for call in calls])
self.assertIn(["tea", "pulls", "merge", "--style", "fast-forward-only", "1"], calls)
self.assertIn("Do=fast-forward-only", [word for call in calls if call[-1].endswith("/pulls/1/merge") for word in call])
self.assertEqual(self.git(self.clone, "rev-parse", "HEAD"), head, "the clone's own checkout stays where it was")
self.assertEqual(self.git(self.clone, "status", "--porcelain"), "")
@@ -275,7 +285,7 @@ class Cut(unittest.TestCase):
self.assert_cut(ran)
calls = self.forge_state()["calls"]
self.assertIn(["gh", "pr", "create", "--head", "release-0.2.0", "--base", "main"], [call[:7] for call in calls])
self.assertIn(["gh", "pr", "merge", "1", "--rebase"], calls)
self.assertIn(["gh", "pr", "merge", "1", "--rebase"], [call[:5] for call in calls])
def test_refuses_changing_nothing_while_the_next_release_holds_an_item(self):
self.commit({"todo.md": TODO + ROW.format(id=1, release="0.2.0") + ROW.format(id=2, release="0.3.0")}, "Plan item 1 again")
@@ -332,6 +342,37 @@ class Cut(unittest.TestCase):
self.assert_cut(self.cut())
self.assertEqual(len(self.forge_state()["pulls"]), 1, "the rerun finds the merged commit, so it opens no second pull request")
def test_merges_only_origins_own_pull_request_where_a_fork_opened_one_from_a_branch_of_the_same_name(self):
for forge_name in ("tea", "gh"):
with self.subTest(forge_name):
self.setUp()
if forge_name == "gh":
self.git(self.clone, "remote", "set-url", "origin", "https://github.com/o/r.git")
self.git(self.clone, "config", f"url.{self.origin}.insteadOf", "https://github.com/o/r.git")
self.set_checks("failure")
self.cut()
self.git(self.clone, "switch", "-q", "-c", "fork", "origin/release-0.2.0")
self.commit({"settings.json": "{\"hooks\": \"evil\"}\n"}, "Cut release 0.2.0")
self.git(self.clone, "push", "-q", "origin", "fork:refs/forks/release-0.2.0")
self.git(self.clone, "switch", "-q", "main")
state = self.forge_state()
fork = {"number": 9, "head": "release-0.2.0", "sha": self.git(self.clone, "rev-parse", "fork").strip(), "fork": True, "state": "open"}
self.forge_state({**state, "pulls": [fork, *state["pulls"]], "checks": "success"})
self.assert_cut(self.cut())
self.assertEqual([found["state"] for found in self.forge_state()["pulls"]], ["open", "merged"])
self.assertNotIn("evil", self.origin_git("show", "main:settings.json") if "settings.json" in self.origin_git("ls-tree", "--name-only", "main") else "")
def test_stops_where_origins_open_pull_request_has_another_head_than_the_branch(self):
self.set_checks("failure")
self.cut()
state = self.forge_state()
state["pulls"][0]["sha"] = "0" * 40
self.forge_state({**state, "checks": "success"})
ran = self.cut()
self.assertEqual(ran.returncode, 1)
self.assertIn("already exists", ran.stderr)
self.assertEqual(self.origin_git("log", "-1", "--format=%s", "main").strip(), "Release review of 0.2.0")
class ChecksPassed(unittest.TestCase):
def test_waits_on_tea_while_a_check_is_pending_and_takes_none_as_passed(self):