diff --git a/.github/workflows/maintainer-approval.yml b/.github/workflows/maintainer-approval.yml index 6cbe2ae91b..7d8f2a6b57 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,66 @@ 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 \ + 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" \ + OPENSHELL_PR_COMMIT_PAGES=commit-pages.json \ + python3 tasks/scripts/check_maintainer_approval.py \ --maintainers MAINTAINERS.md \ --reviews reviews.json diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c33842dd79..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. -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). 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 76d84af8d3..440ef27cf7 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,9 @@ # 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 +WEB_FLOW_ID = 19864447 def parse_maintainers(markdown: str) -> set[str]: @@ -38,21 +42,83 @@ 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 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: @@ -70,6 +136,11 @@ def main(argv: list[str] | None = None) -> int: help="JSON array returned by the list-reviews API", ) args = parser.parse_args(argv) + # 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: @@ -79,12 +150,33 @@ 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 + and commit_pages_path + and verify_maintainer_commits( + json.loads(Path(commit_pages_path).read_text(encoding="utf-8")), + maintainers, + head_sha, + ) + ): + 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 with verified maintainer commits" + ) + 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..ffd948b6b1 100644 --- a/tasks/scripts/check_maintainer_approval_test.py +++ b/tasks/scripts/check_maintainer_approval_test.py @@ -11,8 +11,14 @@ from __future__ import annotations import json +import os +import subprocess +from pathlib import Path +from unittest.mock import patch import check_maintainer_approval as gate +import pytest +import yaml TABLE = """# Maintainers @@ -22,20 +28,29 @@ | 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: 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)] - ) + 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") + 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: @@ -92,3 +107,200 @@ 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, "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) + monkeypatch.setenv("OPENSHELL_PR_AUTHOR", "PiMlOcK") + + +@pytest.mark.usefixtures("pr_metadata") +def test_current_head_app_approval_counts_for_maintainer_author(tmp_path) -> None: + # 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") + 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"]) +@pytest.mark.usefixtures("pr_metadata") +def test_workflow_without_pr_metadata_keeps_human_approval( + tmp_path, monkeypatch, missing +) -> None: + monkeypatch.delenv(missing) + assert run(tmp_path, TABLE, [gator_review()], [commit_page(signed_commit())]) != 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)], +) +@pytest.mark.usefixtures("pr_metadata") +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)], + [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, [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, [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]) +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 / "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}}) + ) + (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' + ' "api graphql --paginate --slurp "*) cat commit-pages-api.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