|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Validate the repository's fork-safe pull request runner policy.""" |
| 3 | + |
| 4 | +from __future__ import annotations |
| 5 | + |
| 6 | +import re |
| 7 | +import sys |
| 8 | +from pathlib import Path |
| 9 | +from typing import Any, Iterable |
| 10 | + |
| 11 | +import yaml |
| 12 | + |
| 13 | +GITHUB_HOSTED_LABEL = re.compile(r"^(ubuntu|windows|macos)-") |
| 14 | +HEAD_REPOSITORY = "github.event.pull_request.head.repo.full_name" |
| 15 | +CURRENT_REPOSITORY = "github.repository" |
| 16 | +MERGED_PULL_REQUEST = "github.event.pull_request.merged == true" |
| 17 | + |
| 18 | + |
| 19 | +def load_workflow(path: Path) -> dict[str, Any]: |
| 20 | + with path.open(encoding="utf-8") as file: |
| 21 | + workflow = yaml.load(file, Loader=yaml.BaseLoader) |
| 22 | + if not isinstance(workflow, dict): |
| 23 | + raise ValueError("workflow root must be a mapping") |
| 24 | + return workflow |
| 25 | + |
| 26 | + |
| 27 | +def event_enabled(workflow: dict[str, Any], event: str) -> bool: |
| 28 | + triggers = workflow.get("on") |
| 29 | + if isinstance(triggers, str): |
| 30 | + return triggers == event |
| 31 | + if isinstance(triggers, list): |
| 32 | + return event in triggers |
| 33 | + if isinstance(triggers, dict): |
| 34 | + return event in triggers |
| 35 | + return False |
| 36 | + |
| 37 | + |
| 38 | +def runner_labels(runs_on: Any) -> list[str]: |
| 39 | + if isinstance(runs_on, str): |
| 40 | + return [runs_on] |
| 41 | + if isinstance(runs_on, list): |
| 42 | + return [str(label) for label in runs_on] |
| 43 | + return [] |
| 44 | + |
| 45 | + |
| 46 | +def is_github_hosted(runs_on: Any) -> bool: |
| 47 | + labels = runner_labels(runs_on) |
| 48 | + return len(labels) == 1 and GITHUB_HOSTED_LABEL.match(labels[0]) is not None |
| 49 | + |
| 50 | + |
| 51 | +def workflow_paths(workflows_dir: Path) -> Iterable[Path]: |
| 52 | + return sorted((*workflows_dir.glob("*.yml"), *workflows_dir.glob("*.yaml"))) |
| 53 | + |
| 54 | + |
| 55 | +def validate_private_pr_runners(workflows_dir: Path) -> list[str]: |
| 56 | + errors: list[str] = [] |
| 57 | + for path in workflow_paths(workflows_dir): |
| 58 | + try: |
| 59 | + workflow = load_workflow(path) |
| 60 | + except (OSError, ValueError, yaml.YAMLError) as error: |
| 61 | + errors.append(f"{path.name}: cannot parse workflow: {error}") |
| 62 | + continue |
| 63 | + if not event_enabled(workflow, "pull_request"): |
| 64 | + continue |
| 65 | + jobs = workflow.get("jobs", {}) |
| 66 | + if not isinstance(jobs, dict): |
| 67 | + errors.append(f"{path.name}: jobs must be a mapping") |
| 68 | + continue |
| 69 | + for job_id, job in jobs.items(): |
| 70 | + if not isinstance(job, dict) or is_github_hosted(job.get("runs-on")): |
| 71 | + continue |
| 72 | + condition = str(job.get("if", "")) |
| 73 | + guarded_head = HEAD_REPOSITORY in condition and CURRENT_REPOSITORY in condition |
| 74 | + trusted_after_merge = MERGED_PULL_REQUEST in condition |
| 75 | + if not guarded_head and not trusted_after_merge: |
| 76 | + errors.append( |
| 77 | + f"{path.name}:{job_id}: a private pull_request runner must be limited " |
| 78 | + "to a head repository matching github.repository or an already merged PR" |
| 79 | + ) |
| 80 | + return errors |
| 81 | + |
| 82 | + |
| 83 | +def validate_fork_workflow(path: Path) -> list[str]: |
| 84 | + errors: list[str] = [] |
| 85 | + try: |
| 86 | + workflow = load_workflow(path) |
| 87 | + except (OSError, ValueError, yaml.YAMLError) as error: |
| 88 | + return [f"{path.name}: cannot parse workflow: {error}"] |
| 89 | + |
| 90 | + if not event_enabled(workflow, "pull_request"): |
| 91 | + errors.append(f"{path.name}: must use the pull_request event") |
| 92 | + if event_enabled(workflow, "pull_request_target"): |
| 93 | + errors.append(f"{path.name}: must not use pull_request_target") |
| 94 | + |
| 95 | + permissions = workflow.get("permissions") |
| 96 | + if not isinstance(permissions, dict) or permissions.get("contents") != "read": |
| 97 | + errors.append(f"{path.name}: top-level permissions must include contents: read") |
| 98 | + elif any(value not in {"read", "none"} for value in permissions.values()): |
| 99 | + errors.append(f"{path.name}: fork-safe permissions must be read-only") |
| 100 | + |
| 101 | + raw_workflow = path.read_text(encoding="utf-8") |
| 102 | + if re.search(r"\bsecrets\.", raw_workflow): |
| 103 | + errors.append(f"{path.name}: fork-safe workflow must not reference secrets") |
| 104 | + |
| 105 | + jobs = workflow.get("jobs", {}) |
| 106 | + required_jobs = {"lint", "cpu-unit"} |
| 107 | + if not isinstance(jobs, dict): |
| 108 | + return [*errors, f"{path.name}: jobs must be a mapping"] |
| 109 | + if not required_jobs.issubset(jobs): |
| 110 | + errors.append(f"{path.name}: must define lint and cpu-unit jobs") |
| 111 | + for job_id, job in jobs.items(): |
| 112 | + if not isinstance(job, dict): |
| 113 | + errors.append(f"{path.name}:{job_id}: job must be a mapping") |
| 114 | + continue |
| 115 | + if not is_github_hosted(job.get("runs-on")): |
| 116 | + errors.append(f"{path.name}:{job_id}: fork-safe jobs must use a GitHub-hosted runner") |
| 117 | + steps = job.get("steps", []) |
| 118 | + if not isinstance(steps, list): |
| 119 | + errors.append(f"{path.name}:{job_id}: steps must be a list") |
| 120 | + continue |
| 121 | + for step in steps: |
| 122 | + if not isinstance(step, dict) or not str(step.get("uses", "")).startswith("actions/checkout@"): |
| 123 | + continue |
| 124 | + inputs = step.get("with", {}) |
| 125 | + if not isinstance(inputs, dict) or inputs.get("persist-credentials") != "false": |
| 126 | + errors.append(f"{path.name}:{job_id}: checkout must set persist-credentials: false") |
| 127 | + return errors |
| 128 | + |
| 129 | + |
| 130 | +def validate_repository(repository: Path) -> list[str]: |
| 131 | + workflows_dir = repository / ".github" / "workflows" |
| 132 | + fork_workflow = workflows_dir / "fork_pr_checks.yml" |
| 133 | + return [ |
| 134 | + *validate_private_pr_runners(workflows_dir), |
| 135 | + *validate_fork_workflow(fork_workflow), |
| 136 | + ] |
| 137 | + |
| 138 | + |
| 139 | +def main() -> int: |
| 140 | + repository = Path(__file__).resolve().parents[3] |
| 141 | + errors = validate_repository(repository) |
| 142 | + if errors: |
| 143 | + print("Pull request runner policy violations:", file=sys.stderr) |
| 144 | + for error in errors: |
| 145 | + print(f"- {error}", file=sys.stderr) |
| 146 | + return 1 |
| 147 | + print("Pull request runner policy is valid.") |
| 148 | + return 0 |
| 149 | + |
| 150 | + |
| 151 | +if __name__ == "__main__": |
| 152 | + raise SystemExit(main()) |
0 commit comments