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
+48 -21
View File
@@ -1,12 +1,14 @@
"""A cut's pull request steps on the forge origin lives on: gh on GitHub, tea elsewhere, as chunk_preflight tells them apart."""
"""A cut's pull request steps on the forge origin lives on: gh on GitHub, tea elsewhere, as chunk_preflight tells them apart.
Each step is pinned to head, the commit origin's release branch points at: the cut takes only a pull request from origin itself whose head is that commit, and the forge merges it only while its head is still that commit. So a fork's pull request from a branch of the same name, or a push to the branch after its checks passed, is never merged.
"""
import json
import subprocess
import time
import typing
from chunk_preflight.choices import Forge, pulls_command
from chunk_preflight.facts import open_pulls
from failure import Failure
from chunk_preflight.choices import Forge
# How long tea waits between two reads of the pull request's checks.
POLL_SECONDS = 10
@@ -27,13 +29,36 @@ def runner(cwd: str) -> Run:
return run
def open_pull(forge: Forge, branch: str, run: Run) -> str | None | Failure:
"""The number of branch's open pull request; None where it has none."""
listed = run(pulls_command(forge, branch))
if isinstance(listed, Failure):
return listed
found = open_pulls(listed, forge, branch)
return found[0].split()[0].removeprefix("#") if found else None
def gitea(run: Run, endpoint: str, *fields: str) -> typing.Any | Failure:
"""What Gitea's API answered at endpoint, parsed; with fields, `key=value` strings, a POST of them. tea api exits 0 on an HTTP error too, so an answer holding only Gitea's `message` is a Failure."""
answered = run(["tea", "api", *(["--method", "POST"] if fields else []), *[word for field in fields for word in ("--field", field)], endpoint])
if isinstance(answered, Failure) or not answered.strip():
return answered
try:
parsed = json.loads(answered)
except ValueError:
return Failure(f"tea api {endpoint} printed no JSON: {answered.strip()[:200]}")
if isinstance(parsed, dict) and "message" in parsed:
return Failure(f"tea api {endpoint}: {parsed['message']}")
return parsed
def open_pull(forge: Forge, branch: str, head: str, run: Run) -> str | None | Failure:
"""The number of the open pull request from origin's own branch whose head is head; None where there is none."""
if forge == "gh":
listed = run(["gh", "pr", "list", "--head", branch, "--json", "number,headRefOid,isCrossRepository", "--template", "{{range .}}{{.number}}\t{{.headRefOid}}\t{{.isCrossRepository}}\n{{end}}"])
if isinstance(listed, Failure):
return listed
rows = [line.split("\t") for line in listed.splitlines()]
return next((row[0] for row in rows if row[1:] == [head, "false"]), None)
# Gitea lists at most 50 a page; a release's pull request is among the newest.
pulls = gitea(run, "repos/{owner}/{repo}/pulls?state=open&limit=50")
if isinstance(pulls, Failure):
return pulls
try:
return next((str(pull["number"]) for pull in pulls if pull["head"]["ref"] == branch and pull["head"]["sha"] == head and pull["head"]["repo"]["full_name"] == pull["base"]["repo"]["full_name"]), None)
except (KeyError, TypeError):
return Failure(f"tea api listed pull requests in a shape the cut doesn't read: {str(pulls)[:200]}")
def create_pull(forge: Forge, branch: str, base: str, title: str, run: Run) -> Failure | None:
@@ -51,15 +76,14 @@ def checks_passed(forge: Forge, number: str, head: str, run: Run, sleep: typing.
return watched
return None
while True:
read = run(["tea", "api", f"repos/{{owner}}/{{repo}}/commits/{head}/status"])
if isinstance(read, Failure):
return read
# Gitea reads a commit with no status as pending, with total_count 0.
status = gitea(run, f"repos/{{owner}}/{{repo}}/commits/{head}/status")
if isinstance(status, Failure):
return status
try:
status = json.loads(read)
count, state = status["total_count"], status["state"]
except (ValueError, KeyError, TypeError):
return Failure(f"tea api printed no commit status for {head}: {read.strip()[:200]}")
except (KeyError, TypeError):
return Failure(f"tea api printed no commit status for {head}: {str(status)[:200]}")
# Gitea reads a commit with no status as pending, with total_count 0.
if count == 0 or state == "success":
return None
if state != "pending":
@@ -67,8 +91,11 @@ def checks_passed(forge: Forge, number: str, head: str, run: Run, sleep: typing.
sleep(POLL_SECONDS)
def merge(forge: Forge, number: str, run: Run) -> Failure | None:
# GitHub has no fast-forward-only merge. A rebase merge of a branch already on top of main is the nearest, though it may give the commit a new hash, so the cut finds it on main by its title.
command = ["gh", "pr", "merge", number, "--rebase"] if forge == "gh" else ["tea", "pulls", "merge", "--style", "fast-forward-only", number]
merged = run(command)
def merge(forge: Forge, number: str, head: str, run: Run) -> Failure | None:
"""Merge pull request number fast-forward only, refused by the forge where its head is no longer head."""
if forge == "gh":
# GitHub has no fast-forward-only merge. A rebase merge of a branch already on top of main is the nearest, though it may give the commit a new hash, so the cut finds it on main by its title.
merged = run(["gh", "pr", "merge", number, "--rebase", "--match-head-commit", head])
else:
merged = gitea(run, f"repos/{{owner}}/{{repo}}/pulls/{number}/merge", "Do=fast-forward-only", f"head_commit_id={head}")
return merged if isinstance(merged, Failure) else None