From 19b8d61c477879cbd5687fd91225facdfd071c6f Mon Sep 17 00:00:00 2001 From: John Myers Date: Mon, 30 Nov 2026 17:24:16 -0800 Subject: [PATCH 1/4] ci: accept Gator approvals for maintainer-authored PRs Signed-off-by: John Myers --- .github/workflows/maintainer-approval.yml | 24 ++-- CONTRIBUTING.md | 2 +- tasks/scripts/check_maintainer_approval.py | 57 ++++++--- .../scripts/check_maintainer_approval_test.py | 112 ++++++++++++++++++ 4 files changed, 170 insertions(+), 25 deletions(-) diff --git a/.github/workflows/maintainer-approval.yml b/.github/workflows/maintainer-approval.yml index 6cbe2ae91b..78079dabbd 100644 --- a/.github/workflows/maintainer-approval.yml +++ b/.github/workflows/maintainer-approval.yml @@ -6,6 +6,8 @@ name: Maintainer Approval on: merge_group: types: [checks_requested] + pull_request: + types: [opened, reopened, synchronize, ready_for_review] pull_request_review: types: [submitted, dismissed] @@ -14,7 +16,7 @@ permissions: pull-requests: read concurrency: - group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}-${{ github.event.pull_request.head.sha || github.sha }} cancel-in-progress: true jobs: @@ -44,21 +46,27 @@ jobs: sparse-checkout-cone-mode: false persist-credentials: false - - name: Require an approving review from a maintainer + - name: Verify maintainer or Gator approval env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} GH_REPO: ${{ github.repository }} PR_NUMBER: ${{ github.event.pull_request.number }} + EVENT_HEAD_SHA: ${{ github.event.pull_request.head.sha }} shell: bash run: | set -euo pipefail - gh api --paginate "repos/$GH_REPO/pulls/$PR_NUMBER/reviews" --jq '.[]' \ - | jq -s '.' > reviews.json + gh api --paginate --slurp "repos/$GH_REPO/pulls/$PR_NUMBER/reviews" \ + | jq 'add // []' > reviews.json + pr_json=$(gh api "repos/$GH_REPO/pulls/$PR_NUMBER") + pr_author=$(jq -er '.user.login' <<< "$pr_json") + head_sha=$(jq -er '.head.sha' <<< "$pr_json") + if [[ "$head_sha" != "$EVENT_HEAD_SHA" ]]; then + echo "PR head changed while checking approval" + exit 1 + fi - # Exits non-zero when no maintainer's latest decisive review is an - # approval, and when MAINTAINERS.md yields no handles. That exit code - # is the check result; nothing is posted anywhere. - python3 tasks/scripts/check_maintainer_approval.py \ + OPENSHELL_PR_AUTHOR="$pr_author" OPENSHELL_PR_HEAD_SHA="$head_sha" \ + python3 tasks/scripts/check_maintainer_approval.py \ --maintainers MAINTAINERS.md \ --reviews reviews.json diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c33842dd79..b6adfa00bc 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -59,7 +59,7 @@ Do not start substantial issue-backed work until a maintainer has accepted the i Use agents and the repository skills as needed to understand the affected code, evaluate tradeoffs, implement the smallest coherent change, and verify it. The pull request should explain what changed and how it was tested; it should not substitute an agent transcript for the contributor's understanding. -Every pull request must be approved by someone listed in [MAINTAINERS.md](MAINTAINERS.md) before it can merge. This is enforced by the `OpenShell / Maintainer Approval` status check, which turns green once one of those reviewers approves. Reviews from other contributors are welcome and count toward the general approval requirement, but they do not satisfy this check. +The `OpenShell / Maintainer Approval` check accepts an approval from someone listed in [MAINTAINERS.md](MAINTAINERS.md). For a pull request authored by a listed maintainer, it also accepts a Gator App approval on the current head. Reviews from other contributors are welcome and count toward the general approval requirement, but they do not satisfy this check. Pull requests that touch the enforcement machinery or reviewer routing — anything under `.github/workflows/`, `.github/actions/`, `MAINTAINERS.md`, `REVIEWERS.md`, `.github/CODEOWNERS`, or the enforcement and reviewer-routing scripts in `tasks/scripts/` — additionally require a code owner's approval, listed in [.github/CODEOWNERS](.github/CODEOWNERS). The status check reads its inputs from `main`, but a workflow triggered by a review runs the pull request's own copy of the workflow file, so GitHub's native code owner requirement is what keeps a change from disabling the gate that would have blocked it. diff --git a/tasks/scripts/check_maintainer_approval.py b/tasks/scripts/check_maintainer_approval.py index 76d84af8d3..8bc73de7c9 100644 --- a/tasks/scripts/check_maintainer_approval.py +++ b/tasks/scripts/check_maintainer_approval.py @@ -7,7 +7,7 @@ # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""Exit non-zero unless a maintainer listed in MAINTAINERS.md has approved. +"""Require a maintainer approval or current-head Gator approval of a maintainer PR. Runs as bare `python3` on the Actions runner, so it must stay stdlib-only. """ @@ -16,6 +16,7 @@ import argparse import json +import os import re import sys from pathlib import Path @@ -31,6 +32,8 @@ # States that express a standing position. COMMENTED and PENDING leave a # reviewer's earlier approval intact, which is how GitHub itself treats them. DECISIVE_STATES = frozenset({"APPROVED", "CHANGES_REQUESTED", "DISMISSED"}) +# GitHub's numeric ID for gator-review-bot[bot], independent of review text. +GATOR_BOT_ID = 363243726 def parse_maintainers(markdown: str) -> set[str]: @@ -38,21 +41,28 @@ def parse_maintainers(markdown: str) -> set[str]: return {match.group(1).lower() for match in MAINTAINER_RE.finditer(markdown)} +def latest_decisive_reviews(reviews: list[dict]) -> dict[str, dict]: + """Index the latest decisive review for each login by GitHub review ID.""" + positions: dict[str, dict] = {} + for entry in sorted(reviews, key=lambda review: review.get("id") or 0): + state = str(entry.get("state") or "").upper() + login = str((entry.get("user") or {}).get("login") or "").lower() + if state in DECISIVE_STATES and login: + positions[login] = entry + return positions + + def parse_reviews_to_approvers(reviews: list[dict]) -> set[str]: """Return the lowercased logins whose current review state is an approval. A reviewer's latest decisive review supersedes their earlier ones, ordered by review id rather than by the order the caller assembled the pages in. """ - positions: dict[str, str] = {} - for entry in sorted(reviews, key=lambda r: r.get("id") or 0): - state = str(entry.get("state") or "").upper() - if state not in DECISIVE_STATES: - continue - login = str((entry.get("user") or {}).get("login") or "").lower() - if login: - positions[login] = state - return {login for login, state in positions.items() if state == "APPROVED"} + return { + login + for login, entry in latest_decisive_reviews(reviews).items() + if entry["state"].upper() == "APPROVED" + } def main(argv: list[str] | None = None) -> int: @@ -70,6 +80,10 @@ def main(argv: list[str] | None = None) -> int: help="JSON array returned by the list-reviews API", ) args = parser.parse_args(argv) + # PR metadata is passed via env so older workflow revisions can keep using + # the human-only gate when they check out this helper from main. + pr_author = os.environ.get("OPENSHELL_PR_AUTHOR", "").lower() + head_sha = os.environ.get("OPENSHELL_PR_HEAD_SHA", "") maintainers = parse_maintainers(args.maintainers.read_text(encoding="utf-8")) if not maintainers: @@ -79,12 +93,23 @@ def main(argv: list[str] | None = None) -> int: reviews = json.loads(args.reviews.read_text(encoding="utf-8")) approvers = sorted(parse_reviews_to_approvers(reviews) & maintainers) - if not approvers: - print("Needs approval from a maintainer listed in MAINTAINERS.md") - return 1 - - print("Approved by " + ", ".join(f"@{login}" for login in approvers)) - return 0 + if approvers: + print("Approved by " + ", ".join(f"@{login}" for login in approvers)) + return 0 + + gator_review = latest_decisive_reviews(reviews).get("gator-review-bot[bot]", {}) + if ( + pr_author in maintainers + and re.fullmatch(r"[0-9a-f]{40}", head_sha) + and (gator_review.get("user") or {}).get("id") == GATOR_BOT_ID + and gator_review.get("state", "").upper() == "APPROVED" + and gator_review.get("commit_id") == head_sha + ): + print("Approved by Gator on the current head of a maintainer-authored PR") + return 0 + + print("Needs maintainer approval or current-head Gator approval of a maintainer-authored PR") + return 1 if __name__ == "__main__": diff --git a/tasks/scripts/check_maintainer_approval_test.py b/tasks/scripts/check_maintainer_approval_test.py index 2e72f73e9d..32508a4f18 100644 --- a/tasks/scripts/check_maintainer_approval_test.py +++ b/tasks/scripts/check_maintainer_approval_test.py @@ -11,6 +11,12 @@ from __future__ import annotations import json +import os +import subprocess +from pathlib import Path + +import pytest +import yaml import check_maintainer_approval as gate @@ -22,6 +28,7 @@ | Evan Lezar | [@elezar](https://github.com/elezar) | NVIDIA | | Piotr Mlocek | [@pimlock](https://github.com/pimlock) | NVIDIA | """ +HEAD_SHA = "a" * 40 def review(login: str, state: str) -> dict: @@ -92,3 +99,108 @@ def test_exits_nonzero_on_non_maintainer_approval(tmp_path) -> None: def test_fails_closed_on_unparseable_list(tmp_path) -> None: assert run(tmp_path, "# Maintainers\n", [review("pimlock", "APPROVED")]) != 0 + + +def gator_review(state="APPROVED", review_id=1, commit_id=HEAD_SHA, bot_id=gate.GATOR_BOT_ID): + return { + "id": review_id, + "user": {"login": "gator-review-bot[bot]", "id": bot_id}, + "state": state, + "commit_id": commit_id, + } + + +@pytest.fixture +def pr_metadata(monkeypatch): + monkeypatch.setenv("OPENSHELL_PR_HEAD_SHA", HEAD_SHA) + monkeypatch.setenv("OPENSHELL_PR_AUTHOR", "PiMlOcK") + + +def test_current_head_app_approval_counts_for_maintainer_author( + tmp_path, pr_metadata +) -> None: + assert run(tmp_path, TABLE, [gator_review()]) == 0 + + +def test_app_approval_does_not_count_for_contributor( + tmp_path, pr_metadata, monkeypatch +) -> None: + monkeypatch.setenv("OPENSHELL_PR_AUTHOR", "outsider") + assert run(tmp_path, TABLE, [gator_review()]) != 0 + assert run(tmp_path, TABLE, [gator_review(), review("pimlock", "APPROVED")]) == 0 + + +@pytest.mark.parametrize("missing", ["OPENSHELL_PR_AUTHOR", "OPENSHELL_PR_HEAD_SHA"]) +def test_workflow_without_pr_metadata_keeps_human_approval( + tmp_path, pr_metadata, monkeypatch, missing +) -> None: + monkeypatch.delenv(missing) + assert run(tmp_path, TABLE, [gator_review()]) != 0 + assert run(tmp_path, TABLE, [review("pimlock", "APPROVED")]) == 0 + + +@pytest.mark.parametrize( + "commit_id,bot_id", + [("b" * 40, gate.GATOR_BOT_ID), (None, gate.GATOR_BOT_ID), (HEAD_SHA, 123)], +) +def test_app_approval_requires_current_head_and_verified_identity( + tmp_path, pr_metadata, commit_id, bot_id +) -> None: + assert run(tmp_path, TABLE, [gator_review(commit_id=commit_id, bot_id=bot_id)]) != 0 + + +@pytest.mark.parametrize("state", ["DISMISSED", "CHANGES_REQUESTED"]) +def test_later_decisive_app_review_supersedes_approval( + tmp_path, pr_metadata, state +) -> None: + reviews = [gator_review(state, review_id=2), gator_review()] + assert run(tmp_path, TABLE, reviews) != 0 + + +def test_app_comment_does_not_revoke_approval(tmp_path, pr_metadata) -> None: + reviews = [gator_review(), gator_review("COMMENTED", review_id=2)] + assert run(tmp_path, TABLE, reviews) == 0 + + +@pytest.mark.parametrize("event_head", [HEAD_SHA, "b" * 40]) +def test_workflow_checks_the_live_pr_and_event_head(tmp_path, event_head) -> None: + root = Path(__file__).resolve().parents[2] + workflow = yaml.safe_load( + (root / ".github/workflows/maintainer-approval.yml").read_text() + ) + step = workflow["jobs"]["maintainer-approval"]["steps"][-1] + (tmp_path / "MAINTAINERS.md").write_text(TABLE) + (tmp_path / "reviews-api.json").write_text(json.dumps([[gator_review()]])) + (tmp_path / "pr.json").write_text( + json.dumps({"user": {"login": "pimlock"}, "head": {"sha": HEAD_SHA}}) + ) + (tmp_path / "tasks").symlink_to(root / "tasks", target_is_directory=True) + gh = tmp_path / "gh" + gh.write_text( + '#!/bin/sh\n' + 'case "$*" in\n' + ' "api --paginate --slurp repos/ai-openshell/openshell/pulls/42/reviews") cat reviews-api.json ;;\n' + ' "api repos/ai-openshell/openshell/pulls/42") cat pr.json ;;\n' + ' *) exit 1 ;;\n' + 'esac\n' + ) + gh.chmod(0o755) + result = subprocess.run( + ["bash", "-c", step["run"]], + cwd=tmp_path, + env=os.environ + | { + "PATH": f"{tmp_path}:{os.environ['PATH']}", + "GH_REPO": "ai-openshell/openshell", + "PR_NUMBER": "42", + "EVENT_HEAD_SHA": event_head, + }, + capture_output=True, + text=True, + ) + if event_head == HEAD_SHA: + assert result.returncode == 0, result.stderr + assert "Approved by Gator" in result.stdout + else: + assert result.returncode != 0 + assert "PR head changed" in result.stdout From 1fdd98fccdede5182508c692beb0800ae8eba889 Mon Sep 17 00:00:00 2001 From: John Myers Date: Mon, 30 Nov 2026 17:32:59 -0800 Subject: [PATCH 2/4] ci: satisfy Python formatting and lint for approval checks Signed-off-by: John Myers --- tasks/scripts/check_maintainer_approval.py | 4 +- .../scripts/check_maintainer_approval_test.py | 37 ++++++++++--------- 2 files changed, 22 insertions(+), 19 deletions(-) diff --git a/tasks/scripts/check_maintainer_approval.py b/tasks/scripts/check_maintainer_approval.py index 8bc73de7c9..84f2483df2 100644 --- a/tasks/scripts/check_maintainer_approval.py +++ b/tasks/scripts/check_maintainer_approval.py @@ -108,7 +108,9 @@ def main(argv: list[str] | None = None) -> int: print("Approved by Gator on the current head of a maintainer-authored PR") return 0 - print("Needs maintainer approval or current-head Gator approval of a maintainer-authored PR") + print( + "Needs maintainer approval or current-head Gator approval of a maintainer-authored PR" + ) return 1 diff --git a/tasks/scripts/check_maintainer_approval_test.py b/tasks/scripts/check_maintainer_approval_test.py index 32508a4f18..bc7d465c68 100644 --- a/tasks/scripts/check_maintainer_approval_test.py +++ b/tasks/scripts/check_maintainer_approval_test.py @@ -15,11 +15,10 @@ import subprocess from pathlib import Path +import check_maintainer_approval as gate import pytest import yaml -import check_maintainer_approval as gate - TABLE = """# Maintainers | Name | GitHub ID | Company/Organization | @@ -101,7 +100,9 @@ def test_fails_closed_on_unparseable_list(tmp_path) -> None: assert run(tmp_path, "# Maintainers\n", [review("pimlock", "APPROVED")]) != 0 -def gator_review(state="APPROVED", review_id=1, commit_id=HEAD_SHA, bot_id=gate.GATOR_BOT_ID): +def gator_review( + state="APPROVED", review_id=1, commit_id=HEAD_SHA, bot_id=gate.GATOR_BOT_ID +): return { "id": review_id, "user": {"login": "gator-review-bot[bot]", "id": bot_id}, @@ -116,23 +117,22 @@ def pr_metadata(monkeypatch): monkeypatch.setenv("OPENSHELL_PR_AUTHOR", "PiMlOcK") -def test_current_head_app_approval_counts_for_maintainer_author( - tmp_path, pr_metadata -) -> None: +@pytest.mark.usefixtures("pr_metadata") +def test_current_head_app_approval_counts_for_maintainer_author(tmp_path) -> None: assert run(tmp_path, TABLE, [gator_review()]) == 0 -def test_app_approval_does_not_count_for_contributor( - tmp_path, pr_metadata, monkeypatch -) -> None: +@pytest.mark.usefixtures("pr_metadata") +def test_app_approval_does_not_count_for_contributor(tmp_path, monkeypatch) -> None: monkeypatch.setenv("OPENSHELL_PR_AUTHOR", "outsider") assert run(tmp_path, TABLE, [gator_review()]) != 0 assert run(tmp_path, TABLE, [gator_review(), review("pimlock", "APPROVED")]) == 0 @pytest.mark.parametrize("missing", ["OPENSHELL_PR_AUTHOR", "OPENSHELL_PR_HEAD_SHA"]) +@pytest.mark.usefixtures("pr_metadata") def test_workflow_without_pr_metadata_keeps_human_approval( - tmp_path, pr_metadata, monkeypatch, missing + tmp_path, monkeypatch, missing ) -> None: monkeypatch.delenv(missing) assert run(tmp_path, TABLE, [gator_review()]) != 0 @@ -143,21 +143,22 @@ def test_workflow_without_pr_metadata_keeps_human_approval( "commit_id,bot_id", [("b" * 40, gate.GATOR_BOT_ID), (None, gate.GATOR_BOT_ID), (HEAD_SHA, 123)], ) +@pytest.mark.usefixtures("pr_metadata") def test_app_approval_requires_current_head_and_verified_identity( - tmp_path, pr_metadata, commit_id, bot_id + tmp_path, commit_id, bot_id ) -> None: assert run(tmp_path, TABLE, [gator_review(commit_id=commit_id, bot_id=bot_id)]) != 0 @pytest.mark.parametrize("state", ["DISMISSED", "CHANGES_REQUESTED"]) -def test_later_decisive_app_review_supersedes_approval( - tmp_path, pr_metadata, state -) -> None: +@pytest.mark.usefixtures("pr_metadata") +def test_later_decisive_app_review_supersedes_approval(tmp_path, state) -> None: reviews = [gator_review(state, review_id=2), gator_review()] assert run(tmp_path, TABLE, reviews) != 0 -def test_app_comment_does_not_revoke_approval(tmp_path, pr_metadata) -> None: +@pytest.mark.usefixtures("pr_metadata") +def test_app_comment_does_not_revoke_approval(tmp_path) -> None: reviews = [gator_review(), gator_review("COMMENTED", review_id=2)] assert run(tmp_path, TABLE, reviews) == 0 @@ -177,12 +178,12 @@ def test_workflow_checks_the_live_pr_and_event_head(tmp_path, event_head) -> Non (tmp_path / "tasks").symlink_to(root / "tasks", target_is_directory=True) gh = tmp_path / "gh" gh.write_text( - '#!/bin/sh\n' + "#!/bin/sh\n" 'case "$*" in\n' ' "api --paginate --slurp repos/ai-openshell/openshell/pulls/42/reviews") cat reviews-api.json ;;\n' ' "api repos/ai-openshell/openshell/pulls/42") cat pr.json ;;\n' - ' *) exit 1 ;;\n' - 'esac\n' + " *) exit 1 ;;\n" + "esac\n" ) gh.chmod(0o755) result = subprocess.run( From d4427843738128c0e77bbb839f0793c9c59edf21 Mon Sep 17 00:00:00 2001 From: John Myers Date: Tue, 1 Dec 2026 08:07:52 -0800 Subject: [PATCH 3/4] ci: require verified maintainer commits for Gator approvals Signed-off-by: John Myers --- .github/workflows/maintainer-approval.yml | 41 +++++- CONTRIBUTING.md | 2 +- tasks/scripts/check_maintainer_approval.py | 73 ++++++++++- .../scripts/check_maintainer_approval_test.py | 119 ++++++++++++++++-- 4 files changed, 219 insertions(+), 16 deletions(-) diff --git a/.github/workflows/maintainer-approval.yml b/.github/workflows/maintainer-approval.yml index 78079dabbd..d81fd489ba 100644 --- a/.github/workflows/maintainer-approval.yml +++ b/.github/workflows/maintainer-approval.yml @@ -66,7 +66,46 @@ jobs: exit 1 fi + printf '[]\n' > commit-pages.json + if jq -e --arg head "$head_sha" \ + 'any(.[]; .state == "APPROVED" and .commit_id == $head and .user.type == "Bot")' \ + reviews.json >/dev/null; then + # GraphQL exposes the signer and can page through the complete PR history. + if ! gh api graphql --paginate --slurp \ + -f owner="${GH_REPO%/*}" -f repo="${GH_REPO#*/}" \ + -F number="$PR_NUMBER" -f query=' + query($owner: String!, $repo: String!, $number: Int!, $endCursor: String) { + repository(owner: $owner, name: $repo) { + pullRequest(number: $number) { + headRefOid + baseRefOid + commits(first: 100, after: $endCursor) { + totalCount + pageInfo { hasNextPage endCursor } + nodes { + commit { + oid + author { user { login } } + committer { user { login databaseId } } + committedViaWeb + signature { + isValid + signer { databaseId } + wasSignedByGitHub + } + } + } + } + } + } + }' > commit-pages.json; then + echo "Could not verify PR commits for Gator approval" + printf '[]\n' > commit-pages.json + fi + fi + OPENSHELL_PR_AUTHOR="$pr_author" OPENSHELL_PR_HEAD_SHA="$head_sha" \ python3 tasks/scripts/check_maintainer_approval.py \ --maintainers MAINTAINERS.md \ - --reviews reviews.json + --reviews reviews.json \ + --commit-pages commit-pages.json diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b6adfa00bc..bdc3708e0d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -59,7 +59,7 @@ Do not start substantial issue-backed work until a maintainer has accepted the i Use agents and the repository skills as needed to understand the affected code, evaluate tradeoffs, implement the smallest coherent change, and verify it. The pull request should explain what changed and how it was tested; it should not substitute an agent transcript for the contributor's understanding. -The `OpenShell / Maintainer Approval` check accepts an approval from someone listed in [MAINTAINERS.md](MAINTAINERS.md). For a pull request authored by a listed maintainer, it also accepts a Gator App approval on the current head. Reviews from other contributors are welcome and count toward the general approval requirement, but they do not satisfy this check. +The `OpenShell / Maintainer Approval` check accepts an approval from someone listed in [MAINTAINERS.md](MAINTAINERS.md). It also accepts a Gator App approval on the current head of a maintainer-authored pull request if every commit is authored by a listed maintainer and verified as signed by a maintainer or by GitHub when made on the web. The commits can come from different maintainers. Reviews from other contributors are welcome and count toward the general approval requirement, but they do not satisfy this check. Pull requests that touch the enforcement machinery or reviewer routing — anything under `.github/workflows/`, `.github/actions/`, `MAINTAINERS.md`, `REVIEWERS.md`, `.github/CODEOWNERS`, or the enforcement and reviewer-routing scripts in `tasks/scripts/` — additionally require a code owner's approval, listed in [.github/CODEOWNERS](.github/CODEOWNERS). The status check reads its inputs from `main`, but a workflow triggered by a review runs the pull request's own copy of the workflow file, so GitHub's native code owner requirement is what keeps a change from disabling the gate that would have blocked it. diff --git a/tasks/scripts/check_maintainer_approval.py b/tasks/scripts/check_maintainer_approval.py index 84f2483df2..60061e37cb 100644 --- a/tasks/scripts/check_maintainer_approval.py +++ b/tasks/scripts/check_maintainer_approval.py @@ -34,6 +34,7 @@ DECISIVE_STATES = frozenset({"APPROVED", "CHANGES_REQUESTED", "DISMISSED"}) # GitHub's numeric ID for gator-review-bot[bot], independent of review text. GATOR_BOT_ID = 363243726 +WEB_FLOW_ID = 19864447 def parse_maintainers(markdown: str) -> set[str]: @@ -65,6 +66,61 @@ def parse_reviews_to_approvers(reviews: list[dict]) -> set[str]: } +def verify_maintainer_commits( + pages: list[dict], maintainers: set[str], head_sha: str +) -> bool: + """Require a complete current-head commit list and verified maintainers.""" + commits: dict[str, dict] = {} + snapshot = None + for page in pages: + pr = (page.get("data") or {}).get("repository", {}).get("pullRequest") + if page.get("errors") or not pr or pr.get("headRefOid") != head_sha: + print("Could not verify PR commits for the approved head") + return False + connection = pr["commits"] + current = (pr["baseRefOid"], connection["totalCount"]) + if snapshot is not None and snapshot != current: + print("PR commit list changed while verifying Gator approval") + return False + snapshot = current + for node in connection["nodes"]: + commit = node["commit"] + oid = commit["oid"] + if oid in commits: + print("Duplicate commit while verifying Gator approval") + return False + commits[oid] = commit + if snapshot is None or len(commits) != snapshot[1] or head_sha not in commits: + print("Could not verify the complete PR commit list for Gator approval") + return False + + for oid, commit in commits.items(): + author = ((commit.get("author") or {}).get("user") or {}).get("login", "") + committer = (commit.get("committer") or {}).get("user") or {} + signature = commit.get("signature") or {} + signer = (signature.get("signer") or {}).get("databaseId") + # GitHub-signed web commits can have no mapped committer. Verify the + # web-flow signer explicitly instead of trusting a raw committer email. + web_commit = ( + commit.get("committedViaWeb") is True + and signature.get("wasSignedByGitHub") is True + and signer == WEB_FLOW_ID + ) + maintainer_committer = ( + committer.get("login", "").lower() in maintainers + and signer is not None + and signer == committer.get("databaseId") + ) + if ( + author.lower() not in maintainers + or signature.get("isValid") is not True + or not (web_commit or maintainer_committer) + ): + print(f"Commit {oid[:12]} is not a verified maintainer commit") + return False + return True + + def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( @@ -79,6 +135,11 @@ def main(argv: list[str] | None = None) -> int: type=Path, help="JSON array returned by the list-reviews API", ) + parser.add_argument( + "--commit-pages", + type=Path, + help="Paginated GitHub GraphQL response for the PR commits", + ) args = parser.parse_args(argv) # PR metadata is passed via env so older workflow revisions can keep using # the human-only gate when they check out this helper from main. @@ -104,12 +165,20 @@ def main(argv: list[str] | None = None) -> int: and (gator_review.get("user") or {}).get("id") == GATOR_BOT_ID and gator_review.get("state", "").upper() == "APPROVED" and gator_review.get("commit_id") == head_sha + and args.commit_pages is not None + and verify_maintainer_commits( + json.loads(args.commit_pages.read_text(encoding="utf-8")), + maintainers, + head_sha, + ) ): - print("Approved by Gator on the current head of a maintainer-authored PR") + print( + "Approved by Gator on the current head of a PR with verified maintainer commits" + ) return 0 print( - "Needs maintainer approval or current-head Gator approval of a maintainer-authored PR" + "Needs maintainer approval or current-head Gator approval of a maintainer-authored PR with verified maintainer commits" ) return 1 diff --git a/tasks/scripts/check_maintainer_approval_test.py b/tasks/scripts/check_maintainer_approval_test.py index bc7d465c68..72ff63ed9c 100644 --- a/tasks/scripts/check_maintainer_approval_test.py +++ b/tasks/scripts/check_maintainer_approval_test.py @@ -34,14 +34,19 @@ def review(login: str, state: str) -> dict: return {"user": {"login": login}, "state": state} -def run(tmp_path, table: str, reviews: list[dict]) -> int: +def run( + tmp_path, table: str, reviews: list[dict], pages: list[dict] | None = None +) -> int: maintainers = tmp_path / "MAINTAINERS.md" maintainers.write_text(table, encoding="utf-8") reviews_file = tmp_path / "reviews.json" reviews_file.write_text(json.dumps(reviews), encoding="utf-8") - return gate.main( - ["--maintainers", str(maintainers), "--reviews", str(reviews_file)] - ) + args = ["--maintainers", str(maintainers), "--reviews", str(reviews_file)] + if pages is not None: + commit_file = tmp_path / "commit-pages.json" + commit_file.write_text(json.dumps(pages), encoding="utf-8") + args.extend(["--commit-pages", str(commit_file)]) + return gate.main(args) def test_parse_maintainers_extracts_linked_logins() -> None: @@ -105,12 +110,43 @@ def gator_review( ): return { "id": review_id, - "user": {"login": "gator-review-bot[bot]", "id": bot_id}, + "user": {"login": "gator-review-bot[bot]", "id": bot_id, "type": "Bot"}, "state": state, "commit_id": commit_id, } +def signed_commit(oid=HEAD_SHA, author="pimlock", committer="pimlock", signer=1): + return { + "oid": oid, + "author": {"user": {"login": author}}, + "committer": {"user": {"login": committer, "databaseId": 1}}, + "committedViaWeb": False, + "signature": { + "isValid": True, + "signer": {"databaseId": signer}, + "wasSignedByGitHub": False, + }, + } + + +def commit_page(*commits, count=1, head=HEAD_SHA): + return { + "data": { + "repository": { + "pullRequest": { + "headRefOid": head, + "baseRefOid": "b" * 40, + "commits": { + "totalCount": count, + "nodes": [{"commit": commit} for commit in commits], + }, + } + } + } + } + + @pytest.fixture def pr_metadata(monkeypatch): monkeypatch.setenv("OPENSHELL_PR_HEAD_SHA", HEAD_SHA) @@ -119,14 +155,24 @@ def pr_metadata(monkeypatch): @pytest.mark.usefixtures("pr_metadata") def test_current_head_app_approval_counts_for_maintainer_author(tmp_path) -> None: - assert run(tmp_path, TABLE, [gator_review()]) == 0 + # The two commits are on separate pages and come from different maintainers. + web_commit = signed_commit("c" * 40, author="elezar", signer=gate.WEB_FLOW_ID) + web_commit["committer"] = {"user": None} + web_commit["committedViaWeb"] = True + web_commit["signature"]["wasSignedByGitHub"] = True + pages = [commit_page(web_commit, count=2), commit_page(signed_commit(), count=2)] + assert run(tmp_path, TABLE, [gator_review()], pages) == 0 @pytest.mark.usefixtures("pr_metadata") def test_app_approval_does_not_count_for_contributor(tmp_path, monkeypatch) -> None: monkeypatch.setenv("OPENSHELL_PR_AUTHOR", "outsider") - assert run(tmp_path, TABLE, [gator_review()]) != 0 - assert run(tmp_path, TABLE, [gator_review(), review("pimlock", "APPROVED")]) == 0 + pages = [commit_page(signed_commit())] + assert run(tmp_path, TABLE, [gator_review()], pages) != 0 + assert ( + run(tmp_path, TABLE, [gator_review(), review("pimlock", "APPROVED")], pages) + == 0 + ) @pytest.mark.parametrize("missing", ["OPENSHELL_PR_AUTHOR", "OPENSHELL_PR_HEAD_SHA"]) @@ -135,7 +181,7 @@ def test_workflow_without_pr_metadata_keeps_human_approval( tmp_path, monkeypatch, missing ) -> None: monkeypatch.delenv(missing) - assert run(tmp_path, TABLE, [gator_review()]) != 0 + assert run(tmp_path, TABLE, [gator_review()], [commit_page(signed_commit())]) != 0 assert run(tmp_path, TABLE, [review("pimlock", "APPROVED")]) == 0 @@ -147,20 +193,65 @@ def test_workflow_without_pr_metadata_keeps_human_approval( def test_app_approval_requires_current_head_and_verified_identity( tmp_path, commit_id, bot_id ) -> None: - assert run(tmp_path, TABLE, [gator_review(commit_id=commit_id, bot_id=bot_id)]) != 0 + assert ( + run( + tmp_path, + TABLE, + [gator_review(commit_id=commit_id, bot_id=bot_id)], + [commit_page(signed_commit())], + ) + != 0 + ) @pytest.mark.parametrize("state", ["DISMISSED", "CHANGES_REQUESTED"]) @pytest.mark.usefixtures("pr_metadata") def test_later_decisive_app_review_supersedes_approval(tmp_path, state) -> None: reviews = [gator_review(state, review_id=2), gator_review()] - assert run(tmp_path, TABLE, reviews) != 0 + assert run(tmp_path, TABLE, reviews, [commit_page(signed_commit())]) != 0 @pytest.mark.usefixtures("pr_metadata") def test_app_comment_does_not_revoke_approval(tmp_path) -> None: reviews = [gator_review(), gator_review("COMMENTED", review_id=2)] - assert run(tmp_path, TABLE, reviews) == 0 + assert run(tmp_path, TABLE, reviews, [commit_page(signed_commit())]) == 0 + + +@pytest.mark.parametrize( + "commit", + [ + signed_commit(author="outsider"), + signed_commit(committer="outsider"), + signed_commit(signer=2), + signed_commit() | {"author": {"user": None}}, + signed_commit() | {"signature": None}, + signed_commit() + | {"signature": {"isValid": False, "signer": {"databaseId": 1}}}, + signed_commit(committer="web-flow", signer=gate.WEB_FLOW_ID), + ], +) +@pytest.mark.usefixtures("pr_metadata") +def test_app_approval_rejects_unverified_or_nonmaintainer_commits( + tmp_path, commit +) -> None: + assert run(tmp_path, TABLE, [gator_review()], [commit_page(commit)]) != 0 + + +@pytest.mark.parametrize( + "pages", + [ + None, + [], + [commit_page(signed_commit(), count=2)], + [commit_page(signed_commit(), head="c" * 40)], + [commit_page(signed_commit("c" * 40))], + [commit_page(signed_commit(), signed_commit(), count=2)], + ], +) +@pytest.mark.usefixtures("pr_metadata") +def test_app_approval_requires_complete_commit_history(tmp_path, pages) -> None: + assert run(tmp_path, TABLE, [gator_review()], pages) != 0 + assert run(tmp_path, TABLE, [review("elezar", "APPROVED")], pages) == 0 @pytest.mark.parametrize("event_head", [HEAD_SHA, "b" * 40]) @@ -172,6 +263,9 @@ def test_workflow_checks_the_live_pr_and_event_head(tmp_path, event_head) -> Non step = workflow["jobs"]["maintainer-approval"]["steps"][-1] (tmp_path / "MAINTAINERS.md").write_text(TABLE) (tmp_path / "reviews-api.json").write_text(json.dumps([[gator_review()]])) + (tmp_path / "commit-pages-api.json").write_text( + json.dumps([commit_page(signed_commit())]) + ) (tmp_path / "pr.json").write_text( json.dumps({"user": {"login": "pimlock"}, "head": {"sha": HEAD_SHA}}) ) @@ -182,6 +276,7 @@ def test_workflow_checks_the_live_pr_and_event_head(tmp_path, event_head) -> Non 'case "$*" in\n' ' "api --paginate --slurp repos/ai-openshell/openshell/pulls/42/reviews") cat reviews-api.json ;;\n' ' "api repos/ai-openshell/openshell/pulls/42") cat pr.json ;;\n' + ' "api graphql --paginate --slurp "*) cat commit-pages-api.json ;;\n' " *) exit 1 ;;\n" "esac\n" ) From 87dffe99e634cea781d06a9fc5345c187307689e Mon Sep 17 00:00:00 2001 From: John Myers Date: Tue, 1 Dec 2026 09:10:12 -0800 Subject: [PATCH 4/4] ci: keep the approval workflow compatible with main Signed-off-by: John Myers --- .github/workflows/maintainer-approval.yml | 4 ++-- tasks/scripts/check_maintainer_approval.py | 14 +++++--------- tasks/scripts/check_maintainer_approval_test.py | 10 +++++++--- 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/.github/workflows/maintainer-approval.yml b/.github/workflows/maintainer-approval.yml index d81fd489ba..7d8f2a6b57 100644 --- a/.github/workflows/maintainer-approval.yml +++ b/.github/workflows/maintainer-approval.yml @@ -105,7 +105,7 @@ jobs: fi OPENSHELL_PR_AUTHOR="$pr_author" OPENSHELL_PR_HEAD_SHA="$head_sha" \ + OPENSHELL_PR_COMMIT_PAGES=commit-pages.json \ python3 tasks/scripts/check_maintainer_approval.py \ --maintainers MAINTAINERS.md \ - --reviews reviews.json \ - --commit-pages commit-pages.json + --reviews reviews.json diff --git a/tasks/scripts/check_maintainer_approval.py b/tasks/scripts/check_maintainer_approval.py index 60061e37cb..440ef27cf7 100644 --- a/tasks/scripts/check_maintainer_approval.py +++ b/tasks/scripts/check_maintainer_approval.py @@ -135,16 +135,12 @@ def main(argv: list[str] | None = None) -> int: type=Path, help="JSON array returned by the list-reviews API", ) - parser.add_argument( - "--commit-pages", - type=Path, - help="Paginated GitHub GraphQL response for the PR commits", - ) args = parser.parse_args(argv) - # PR metadata is passed via env so older workflow revisions can keep using - # the human-only gate when they check out this helper from main. + # Keep the CLI compatible with the workflow and helper on different + # revisions. Older helpers on main can ignore the App-only metadata. pr_author = os.environ.get("OPENSHELL_PR_AUTHOR", "").lower() head_sha = os.environ.get("OPENSHELL_PR_HEAD_SHA", "") + commit_pages_path = os.environ.get("OPENSHELL_PR_COMMIT_PAGES", "") maintainers = parse_maintainers(args.maintainers.read_text(encoding="utf-8")) if not maintainers: @@ -165,9 +161,9 @@ def main(argv: list[str] | None = None) -> int: and (gator_review.get("user") or {}).get("id") == GATOR_BOT_ID and gator_review.get("state", "").upper() == "APPROVED" and gator_review.get("commit_id") == head_sha - and args.commit_pages is not None + and commit_pages_path and verify_maintainer_commits( - json.loads(args.commit_pages.read_text(encoding="utf-8")), + json.loads(Path(commit_pages_path).read_text(encoding="utf-8")), maintainers, head_sha, ) diff --git a/tasks/scripts/check_maintainer_approval_test.py b/tasks/scripts/check_maintainer_approval_test.py index 72ff63ed9c..ffd948b6b1 100644 --- a/tasks/scripts/check_maintainer_approval_test.py +++ b/tasks/scripts/check_maintainer_approval_test.py @@ -14,6 +14,7 @@ import os import subprocess from pathlib import Path +from unittest.mock import patch import check_maintainer_approval as gate import pytest @@ -41,12 +42,15 @@ def run( maintainers.write_text(table, encoding="utf-8") reviews_file = tmp_path / "reviews.json" reviews_file.write_text(json.dumps(reviews), encoding="utf-8") - args = ["--maintainers", str(maintainers), "--reviews", str(reviews_file)] + commit_pages_path = "" if pages is not None: commit_file = tmp_path / "commit-pages.json" commit_file.write_text(json.dumps(pages), encoding="utf-8") - args.extend(["--commit-pages", str(commit_file)]) - return gate.main(args) + commit_pages_path = str(commit_file) + with patch.dict(os.environ, {"OPENSHELL_PR_COMMIT_PAGES": commit_pages_path}): + return gate.main( + ["--maintainers", str(maintainers), "--reviews", str(reviews_file)] + ) def test_parse_maintainers_extracts_linked_logins() -> None: