Revert "Fix merge queue merging non-approved commits (#10552)" (#10691)

This commit is contained in:
Andy Leiserson authored and GitHub committed 2026-10-22 05:01:14 +00:00
1 parent 0f0262acdd
commit ade0590d81
4 files changed
-324

No files matched your search

-203
View File
@@ -1,203 +0,0 @@
"""Posts a passing `head-approved` check when a pull request head is approved.
`.github/workflows/head-approved.yml` runs this script and gives the inputs
through environment variables. Read the security rules in that file before you
change this script.
"""
import json
import os
import time
import urllib.error
import urllib.parse
import urllib.request
CHECK_NAME = "head-approved"
WORKFLOW_FILE = "head-approved.yml"
REPO = os.environ["REPO"]
DEFAULT_BRANCH = os.environ["DEFAULT_BRANCH"]
APP_TOKEN = os.environ["APP_TOKEN"]
APP_SLUG = os.environ["APP_SLUG"]
READ_TOKEN = os.environ["READ_TOKEN"]
def api(token, path, params=None, body=None):
"""Sends a request to the GitHub REST API and returns the JSON response.
Sends a POST request if `body` is given, otherwise a GET request.
"""
url = f"https://api.github.com/{path}"
if params:
url += "?" + urllib.parse.urlencode(params)
request = urllib.request.Request(
url,
data=None if body is None else json.dumps(body).encode(),
headers={
"Accept": "application/vnd.github+json",
"Authorization": f"Bearer {token}",
"X-GitHub-Api-Version": "2022-11-28",
},
)
with urllib.request.urlopen(request, timeout=30) as response:
return json.load(response)
def quote(value):
"""Encodes `value` for use as one segment of an API path."""
return urllib.parse.quote(value, safe="")
def has_write(login):
"""Returns true if the user has write access or higher."""
try:
permission = api(
APP_TOKEN, f"repos/{REPO}/collaborators/{quote(login)}/permission"
)
except urllib.error.HTTPError as error:
if error.code == 404:
return False
raise
return permission["permission"] in ("admin", "write")
def is_trusted(login):
"""Returns true if the user is a trusted actor."""
if login == "mergify[bot]":
return True
if login.endswith("[bot]"):
return False
return has_write(login)
def approved_at(pr, sha):
"""Returns true if a user with write access approved commit `sha` of pull request `pr`."""
approvers = set()
page = 1
while True:
reviews = api(
READ_TOKEN,
f"repos/{REPO}/pulls/{pr}/reviews",
{"per_page": 100, "page": page},
)
for review in reviews:
if (
review["state"] == "APPROVED"
and review["commit_id"] == sha
and review["user"]
):
approvers.add(review["user"]["login"])
if len(reviews) < 100:
break
page += 1
return any(has_write(login) for login in sorted(approvers))
def passed(sha):
"""Returns true if this app posted a passing check on the commit."""
runs = api(
READ_TOKEN,
f"repos/{REPO}/commits/{quote(sha)}/check-runs",
{"check_name": CHECK_NAME, "filter": "all", "per_page": 100},
)
return any(
(run.get("app") or {}).get("slug") == APP_SLUG
and run["conclusion"] == "success"
for run in runs["check_runs"]
)
def will_pass(sha):
"""Returns true if this app posts a passing check on the commit.
Waits while a run of this workflow for the commit is not complete, because
that run decides the result.
"""
while True:
if passed(sha):
return True
runs = api(
READ_TOKEN,
f"repos/{REPO}/actions/workflows/{WORKFLOW_FILE}/runs",
{"event": "pull_request_target", "head_sha": sha},
)
if all(run["status"] == "completed" for run in runs["workflow_runs"]):
return passed(sha)
time.sleep(10)
def in_default_branch(sha):
"""Returns true if the commit is in the default branch."""
comparison = api(
READ_TOKEN, f"repos/{REPO}/compare/{quote(DEFAULT_BRANCH)}...{quote(sha)}"
)
return comparison["status"] in ("behind", "identical")
def parents_ok(sha):
"""Returns true if each parent of the commit passes or is in the default branch."""
commit = api(READ_TOKEN, f"repos/{REPO}/commits/{quote(sha)}")
return all(
in_default_branch(parent["sha"]) or will_pass(parent["sha"])
for parent in commit["parents"]
)
def post(sha, title, summary):
"""Posts a passing check on the commit."""
print(f"{sha}: {title}")
api(
APP_TOKEN,
f"repos/{REPO}/check-runs",
body={
"name": CHECK_NAME,
"head_sha": sha,
"conclusion": "success",
"output": {"title": title, "summary": summary},
},
)
def on_pull_request_target():
"""Evaluates the head commit after a pull request is opened or pushed to."""
action = os.environ["ACTION"]
pr = os.environ["PR"]
head_sha = os.environ["HEAD_SHA"]
before = os.environ["BEFORE"]
sender = os.environ["SENDER"]
if os.environ["PR_AUTHOR"] == "mergify[bot]" and os.environ["HEAD_REPO"] == REPO:
# A merge queue head merges queued pull request heads into the default branch.
if parents_ok(head_sha):
post(
head_sha,
"Merge queue",
f"Each parent of this merge queue commit passed or is in {DEFAULT_BRANCH}.",
)
elif approved_at(pr, head_sha):
post(head_sha, "Approved", "A user with write access approved this commit.")
elif (
action == "synchronize"
and is_trusted(sender)
and (approved_at(pr, before) or will_pass(before))
):
post(
head_sha,
"Pushed by a trusted actor",
f"{sender} pushed this commit, and the previous head commit passed.",
)
def on_workflow_run():
"""Evaluates the head commits of the pull request that got a review."""
head = f"{os.environ['RUN_HEAD_OWNER']}:{os.environ['RUN_HEAD_BRANCH']}"
for pull in api(READ_TOKEN, f"repos/{REPO}/pulls", {"state": "open", "head": head}):
sha = pull["head"]["sha"]
if approved_at(pull["number"], sha):
post(sha, "Approved", "A user with write access approved this commit.")
if os.environ["EVENT"] == "pull_request_target":
on_pull_request_target()
else:
on_workflow_run()
@@ -1,22 +0,0 @@
# Starts the `Head approved` workflow when a user approves a pull request.
#
# On pull requests from forks, this workflow gets no secrets, so it cannot post
# the check. The `Head approved` workflow runs from `trunk` on `workflow_run`
# and posts it.
name: Head approved review
on:
pull_request_review:
types: [submitted]
permissions: {}
jobs:
trigger:
name: Trigger head-approved check
if: github.event.review.state == 'approved'
runs-on: ubuntu-latest
timeout-minutes: 1
permissions: {}
steps:
- run: echo "The Head approved workflow posts the check."
-96
View File
@@ -1,96 +0,0 @@
# Posts a passing `head-approved` check on approved pull request heads.
#
# The check passes on a commit when one of these is true:
#
# - A user with write access approved this exact commit.
# - A trusted actor pushed this commit, and the previous head commit passed or
# a user with write access approved it. Trusted actors are users with write
# access and Mergify.
# - The commit is the head of a Mergify merge queue pull request, and each of
# its parents passed or is in the default branch.
#
# Branch protection on `trunk` requires this check. Check results belong to a
# commit, so a new push has no result. Thus GitHub blocks the merge of commits
# that a user without write access pushed after the last approval.
#
# Security rules. Read these before you change this file:
#
# - This workflow runs with secrets on events that untrusted users can cause.
# Do not check out, build, or run code from a pull request. The checkout
# step gets `.github/scripts/head-approved.py` from the default branch. Do
# not set its `ref`.
# - Do not put text that a pull request controls (titles, branch names, commit
# messages) in a `run:` script. Give values to scripts only through `env:`.
# - The `workflow_run` trigger can come from a fork, because a fork controls
# the workflow file that sends it. Use its payload only to find the pull
# request. Read all other data from the API.
# - Only post passing checks. A check result applies to all pull requests with
# the same head commit. If this workflow posts failures, an outsider can push
# the head commit of another pull request and block it.
# - Branch protection must require this check from the `head-approved` app and
# not from "any source". If not, a fork can post a check with this name.
# - The required check must stay in classic branch protection, or in a ruleset
# that Mergify cannot bypass. If Mergify can bypass it, GitHub does not
# enforce it when Mergify merges.
# - The app private key is in the `head-approved` environment, which only
# `trunk` can use. Give the app only the "Checks: write" permission.
name: Head approved
on: # zizmor: ignore[dangerous-triggers] This workflow does not run pull request code.
pull_request_target:
types: [opened, synchronize]
workflow_run:
workflows: ["Head approved review"]
types: [completed]
permissions: {}
jobs:
head-approved:
name: Post head-approved check
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
# Finds runs of this workflow that are not complete.
actions: read
# Reads the check result on the previous head commit.
checks: read
# Reads pull requests and their reviews.
pull-requests: read
environment:
name: head-approved
deployment: false
steps:
- name: Create app token
id: app
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0
with:
client-id: ${{ vars.HEAD_APPROVED_CLIENT_ID }}
private-key: ${{ secrets.HEAD_APPROVED_PRIVATE_KEY }}
permission-checks: write
- name: Check out script
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
sparse-checkout: .github/scripts/head-approved.py
sparse-checkout-cone-mode: false
- name: Evaluate and post check
env:
APP_TOKEN: ${{ steps.app.outputs.token }}
APP_SLUG: ${{ steps.app.outputs.app-slug }}
READ_TOKEN: ${{ github.token }}
REPO: ${{ github.repository }}
EVENT: ${{ github.event_name }}
ACTION: ${{ github.event.action }}
PR: ${{ github.event.pull_request.number }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
HEAD_REPO: ${{ github.event.pull_request.head.repo.full_name }}
PR_AUTHOR: ${{ github.event.pull_request.user.login }}
DEFAULT_BRANCH: ${{ github.event.repository.default_branch }}
BEFORE: ${{ github.event.before }}
SENDER: ${{ github.event.sender.login }}
RUN_HEAD_OWNER: ${{ github.event.workflow_run.head_repository.owner.login }}
RUN_HEAD_BRANCH: ${{ github.event.workflow_run.head_branch }}
run: python3 .github/scripts/head-approved.py
-3
View File
@@ -52,6 +52,3 @@ wgpu/src/backend/webgpu/webgpu_sys/wasm_bindgen_clone_tmp
# Wasm test generated files
/tests/wasm/dist
/tests/wasm/runner/node_modules
# Pycache files
**/__pycache__/