Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 55 additions & 8 deletions .github/workflows/maintainer-approval.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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]

Expand All @@ -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:
Expand Down Expand Up @@ -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
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
124 changes: 108 additions & 16 deletions tasks/scripts/check_maintainer_approval.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
"""
Expand All @@ -16,6 +16,7 @@

import argparse
import json
import os
import re
import sys
from pathlib import Path
Expand All @@ -31,28 +32,93 @@
# 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]:
"""Return the lowercased GitHub logins listed in a MAINTAINERS.md table."""
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:
Expand All @@ -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:
Expand All @@ -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
Comment thread
purp marked this conversation as resolved.
Resolved
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__":
Expand Down
Loading
Loading