Repository navigation
CNTRLPLANE-3677: address-review-pr: add author authorization check #590
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
openshift-merge-bot
merged 2 commits into
openshift-eng:main
from
enxebre:address-review-pr-author-authorization
Jul 6, 2026
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
248 changes: 248 additions & 0 deletions
248
plugins/openshift-developer/skills/address-review-pr/scripts/check_authorized.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,248 @@ | ||
| #!/usr/bin/env python3 | ||
| """ | ||
| Check if a GitHub user is authorized to trigger review agent responses. | ||
|
|
||
| Authorized authors are: | ||
| 1. Approved bots (coderabbitai) | ||
| 2. Users listed in OWNERS or OWNERS_ALIASES | ||
| 3. Members of the repository's GitHub organization (fallback) | ||
|
|
||
| Usage: | ||
| check_authorized.py <owner> <repo> <login> | ||
|
|
||
| Returns: | ||
| Exit 0: Authorized | ||
| Exit 1: Not authorized | ||
| Exit 2: Error occurred | ||
|
|
||
| Output: | ||
| JSON with authorization result and reason. | ||
| """ | ||
|
|
||
| import json | ||
| import subprocess | ||
| import sys | ||
| from typing import Any | ||
|
|
||
| try: | ||
| import yaml | ||
| HAS_YAML = True | ||
| except ImportError: | ||
| HAS_YAML = False | ||
|
|
||
| GH_TIMEOUT = 30 | ||
|
|
||
| APPROVED_BOTS = [ | ||
| "coderabbitai", | ||
| "coderabbitai[bot]", | ||
| ] | ||
|
|
||
| IGNORED_ACCOUNTS = [ | ||
| "openshift-ci-robot", | ||
| "openshift-ci", | ||
| "openshift-merge-robot", | ||
| "openshift-bot", | ||
| ] | ||
|
|
||
|
|
||
| def run_gh(args: list[str]) -> str: | ||
| result = subprocess.run( | ||
| ["gh"] + args, | ||
| capture_output=True, | ||
| text=True, | ||
| check=True, | ||
| timeout=GH_TIMEOUT, | ||
| ) | ||
| return result.stdout | ||
|
|
||
|
|
||
| def _parse_simple_yaml_list(content: str, key: str) -> list[str]: | ||
| result = [] | ||
| in_key = False | ||
| for line in content.split("\n"): | ||
| stripped = line.strip() | ||
| if stripped.startswith(f"{key}:"): | ||
| in_key = True | ||
| continue | ||
| if in_key: | ||
| if stripped.startswith("- "): | ||
| result.append(stripped[2:].strip()) | ||
| elif stripped and not stripped.startswith("#") and ":" in stripped: | ||
| in_key = False | ||
| return result | ||
|
|
||
|
|
||
| def _parse_simple_yaml_aliases(content: str) -> dict[str, list[str]]: | ||
| aliases: dict[str, list[str]] = {} | ||
| current_alias = None | ||
| in_aliases = False | ||
|
|
||
| for line in content.split("\n"): | ||
| stripped = line.rstrip() | ||
| if stripped.startswith("aliases:"): | ||
| in_aliases = True | ||
| continue | ||
| if not in_aliases: | ||
| continue | ||
| if stripped and not stripped.startswith(" ") and not stripped.startswith("\t"): | ||
| break | ||
|
|
||
| stripped = stripped.strip() | ||
| if not stripped or stripped.startswith("#"): | ||
| continue | ||
|
|
||
| if stripped.endswith(":") and not stripped.startswith("- "): | ||
| current_alias = stripped[:-1].strip() | ||
| aliases[current_alias] = [] | ||
| elif stripped.startswith("- ") and current_alias: | ||
| aliases[current_alias].append(stripped[2:].strip()) | ||
|
|
||
| return aliases | ||
|
|
||
|
|
||
| class OwnersLookupError(Exception): | ||
| pass | ||
|
|
||
|
|
||
| class OrgMembershipLookupError(Exception): | ||
| pass | ||
|
|
||
|
|
||
| def get_authorized_users(owner: str, repo: str) -> set[str]: | ||
| authorized: set[str] = set(APPROVED_BOTS) | ||
| aliases: dict[str, list[str]] = {} | ||
| errors: list[str] = [] | ||
|
|
||
| try: | ||
| content = run_gh([ | ||
| "api", "-H", "Accept: application/vnd.github.raw", | ||
| f"repos/{owner}/{repo}/contents/OWNERS_ALIASES", | ||
| ]) | ||
| if HAS_YAML: | ||
| data = yaml.safe_load(content) | ||
| if data and "aliases" in data: | ||
| aliases = data["aliases"] | ||
| else: | ||
| aliases = _parse_simple_yaml_aliases(content) | ||
|
|
||
| for members in aliases.values(): | ||
| authorized.update(members) | ||
| except subprocess.CalledProcessError as e: | ||
| if "404" in (e.stderr or ""): | ||
| print(f"Info: No OWNERS_ALIASES file in {owner}/{repo}", file=sys.stderr) | ||
| else: | ||
| errors.append(f"OWNERS_ALIASES: {e}") | ||
| except subprocess.TimeoutExpired: | ||
| errors.append("OWNERS_ALIASES: gh timed out") | ||
| except Exception as e: | ||
| errors.append(f"OWNERS_ALIASES: {e}") | ||
|
|
||
| try: | ||
| content = run_gh([ | ||
| "api", "-H", "Accept: application/vnd.github.raw", | ||
| f"repos/{owner}/{repo}/contents/OWNERS", | ||
| ]) | ||
| if HAS_YAML: | ||
| data = yaml.safe_load(content) | ||
| if data: | ||
| def add_entries(entries: list): | ||
| for entry in entries: | ||
| if entry not in aliases: | ||
| authorized.add(entry) | ||
|
|
||
| add_entries(data.get("approvers", [])) | ||
| add_entries(data.get("reviewers", [])) | ||
|
|
||
| if "filters" in data: | ||
| for _, config in data["filters"].items(): | ||
| if isinstance(config, dict): | ||
| add_entries(config.get("approvers", [])) | ||
| add_entries(config.get("reviewers", [])) | ||
| else: | ||
| for entry in _parse_simple_yaml_list(content, "approvers"): | ||
| if entry not in aliases: | ||
| authorized.add(entry) | ||
| for entry in _parse_simple_yaml_list(content, "reviewers"): | ||
| if entry not in aliases: | ||
| authorized.add(entry) | ||
|
enxebre marked this conversation as resolved.
Resolved
|
||
| except subprocess.CalledProcessError as e: | ||
| if "404" in (e.stderr or ""): | ||
| print(f"Info: No OWNERS file in {owner}/{repo}", file=sys.stderr) | ||
| else: | ||
| errors.append(f"OWNERS: {e}") | ||
| except subprocess.TimeoutExpired: | ||
| errors.append("OWNERS: gh timed out") | ||
| except Exception as e: | ||
| errors.append(f"OWNERS: {e}") | ||
|
|
||
| if errors: | ||
| raise OwnersLookupError("; ".join(errors)) | ||
|
|
||
| return authorized | ||
|
|
||
|
|
||
| def is_org_member(owner: str, login: str) -> bool: | ||
| try: | ||
| result = subprocess.run( | ||
| ["gh", "api", f"orgs/{owner}/members/{login}"], | ||
| capture_output=True, | ||
| text=True, | ||
| timeout=GH_TIMEOUT, | ||
| ) | ||
| if result.returncode == 0: | ||
| return True | ||
| if "404" in (result.stderr or "") or "Not Found" in (result.stdout or ""): | ||
| return False | ||
| raise OrgMembershipLookupError( | ||
| f"gh api failed (rc={result.returncode}): {result.stderr.strip()}" | ||
| ) | ||
| except OrgMembershipLookupError: | ||
| raise | ||
| except subprocess.TimeoutExpired: | ||
| raise OrgMembershipLookupError(f"Org membership check timed out for {login}") | ||
| except Exception as e: | ||
| raise OrgMembershipLookupError(f"Failed to check org membership for {login}: {e}") | ||
|
|
||
|
|
||
| def main(): | ||
| if len(sys.argv) < 4: | ||
| print("Usage: check_authorized.py <owner> <repo> <login>", file=sys.stderr) | ||
| sys.exit(2) | ||
|
|
||
| owner = sys.argv[1] | ||
| repo = sys.argv[2] | ||
| login = sys.argv[3] | ||
|
|
||
| if not login: | ||
| print(json.dumps({"authorized": False, "login": login, "reason": "empty_login"})) | ||
| sys.exit(1) | ||
|
|
||
| if login in IGNORED_ACCOUNTS or (login.endswith("[bot]") and login not in APPROVED_BOTS): | ||
| print(json.dumps({"authorized": False, "login": login, "reason": "ignored_bot"})) | ||
| sys.exit(1) | ||
|
|
||
| try: | ||
| authorized_users = get_authorized_users(owner, repo) | ||
| except OwnersLookupError as e: | ||
| print(json.dumps({"authorized": False, "login": login, "reason": f"owners_lookup_error: {e}"})) | ||
| sys.exit(2) | ||
|
|
||
| if login.lower() in {u.lower() for u in authorized_users}: | ||
| reason = "approved_bot" if login in APPROVED_BOTS else "owners" | ||
| print(json.dumps({"authorized": True, "login": login, "reason": reason})) | ||
| sys.exit(0) | ||
|
|
||
| try: | ||
| if is_org_member(owner, login): | ||
| print(json.dumps({"authorized": True, "login": login, "reason": "org_member"})) | ||
| sys.exit(0) | ||
| except OrgMembershipLookupError as e: | ||
| print(json.dumps({"authorized": False, "login": login, "reason": f"org_membership_error: {e}"})) | ||
| sys.exit(2) | ||
|
|
||
| print(json.dumps({"authorized": False, "login": login, "reason": "not_authorized"})) | ||
| sys.exit(1) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.