diff --git a/.github/VOUCHED.td b/.github/VOUCHED.td new file mode 100644 index 00000000000000..c7a6b8f0d9f836 --- /dev/null +++ b/.github/VOUCHED.td @@ -0,0 +1,35 @@ +# Authors whose pull requests get a full kernel build on every push. +# +# The kernel team. A pull request from anyone listed here builds the package +# and runs KUnit and the boot test on every push once it is out of draft, +# from a fork too, with no ci:build label needed, as long as whoever pushed +# is listed too. Everyone else, omacom +# organization members and repository collaborators included, gets the +# checks only until a maintainer applies ci:build to that pull request. CI +# never builds a denounced author's pull requests, label or not. +# +# CI reads this file from the target branch, so a pull request cannot vouch +# for its own author. GitHub holds pull request runs from outside +# collaborators; kernel-ci-approve.yml releases them for those listed here. +# +# Syntax (the mitchellh/vouch format omacom/omarchy-pkgs uses): +# github:username +# -github:username reason for denouncement +# +# Keep entries sorted alphabetically, ignoring case. +github:Acelogic +github:chriskearney +github:dhh +github:DjDeveloperr +github:emirb +github:erykwieliczko +github:joshuaswarren +github:kwilczynski +github:LiamRay11 +github:malik-na +github:maralcbr +github:outfoxxed +github:ryanrhughes +github:RyanTheTide +github:scottjones +github:themartiano diff --git a/.github/workflows/kernel-ci-approve.yml b/.github/workflows/kernel-ci-approve.yml new file mode 100644 index 00000000000000..2a80dd4a52af0f --- /dev/null +++ b/.github/workflows/kernel-ci-approve.yml @@ -0,0 +1,48 @@ +# GitHub holds every pull request run from outside collaborators until a +# maintainer approves it. This releases the kernel CI run of a pull request +# whose author is vouched for in .github/VOUCHED.td, so the team's outside +# collaborators build like everyone else on the team. Anyone else's run stays +# held for a maintainer. tools/aurora-ci/README.rst, "Who can start a build". + +name: Kernel CI (approve vouched authors) + +on: + # pull_request_target runs the target branch's workflow, and this job only + # fetches the target branch's files: no pull request code ever runs here, + # with or without the write token. + pull_request_target: # zizmor: ignore[dangerous-triggers] no checkout; target-branch code only + branches: [integration/aurora] + types: [opened, synchronize, reopened, ready_for_review] + +permissions: {} + +concurrency: + group: kernel-ci-approve-${{ github.event.pull_request.number }} + cancel-in-progress: true + +jobs: + approve: + name: approve + # Organization members' and collaborators' runs are never held. + if: ${{ !contains(fromJSON('["OWNER", "MEMBER", "COLLABORATOR"]'), github.event.pull_request.author_association) }} + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + actions: write # approve the held kernel CI run + contents: read # read the target branch's tools and vouch list + pull-requests: read # recheck the pull request's head before approving + steps: + # github.sha is the target branch's tip on pull_request_target. + - name: Fetch the target branch's tools and vouch list + env: + GH_TOKEN: ${{ github.token }} + run: | + mkdir -p "$RUNNER_TEMP/tools" + for file in tools/aurora-ci/plan.py tools/aurora-ci/approve-runs.py .github/VOUCHED.td; do + gh api -H "Accept: application/vnd.github.raw+json" \ + "repos/$GITHUB_REPOSITORY/contents/$file?ref=$GITHUB_SHA" > "$RUNNER_TEMP/tools/${file##*/}" + done + - name: Approve the run of a vouched author + env: + GITHUB_TOKEN: ${{ github.token }} + run: python3 -I "$RUNNER_TEMP/tools/approve-runs.py" --vouched "$RUNNER_TEMP/tools/VOUCHED.td" diff --git a/.github/workflows/kernel-ci-jobs.yml b/.github/workflows/kernel-ci-jobs.yml index 9b4a1c6ac4ce33..e9a854a57fd0c9 100644 --- a/.github/workflows/kernel-ci-jobs.yml +++ b/.github/workflows/kernel-ci-jobs.yml @@ -61,9 +61,27 @@ jobs: persist-credentials: false filter: blob:none sparse-checkout: tools/aurora-ci + # From the target branch, never the pull request: a pull request must + # not vouch for its own author. Without the list (the branch does not + # have one yet, or the API fails) no author is trusted. + - name: Read the vouch list from the target branch + if: github.event_name == 'pull_request' + env: + GH_TOKEN: ${{ github.token }} + BASE_SHA: ${{ github.event.pull_request.base.sha }} + run: | + if ! gh api -H "Accept: application/vnd.github.raw+json" \ + "repos/$GITHUB_REPOSITORY/contents/.github/VOUCHED.td?ref=$BASE_SHA" \ + > "$RUNNER_TEMP/VOUCHED.td"; then + : > "$RUNNER_TEMP/VOUCHED.td" + echo "::warning title=Vouch list::no .github/VOUCHED.td at $BASE_SHA; no author is trusted" + fi - name: Plan the run id: plan - run: python3 -I tools/aurora-ci/plan.py --label "$BUILD_LABEL" + run: | + vouched=() + [[ -f $RUNNER_TEMP/VOUCHED.td ]] && vouched=(--vouched "$RUNNER_TEMP/VOUCHED.td") + python3 -I tools/aurora-ci/plan.py --label "$BUILD_LABEL" "${vouched[@]}" # Only trees are needed: the build key is made of tree hashes. - name: Fetch the packaging inputs if: steps.plan.outputs.tier == 'full' diff --git a/.github/workflows/kernel-ci.yml b/.github/workflows/kernel-ci.yml index e02c9ee7481a57..64855775d8474f 100644 --- a/.github/workflows/kernel-ci.yml +++ b/.github/workflows/kernel-ci.yml @@ -2,8 +2,9 @@ # locally: tools/aurora-ci/README.rst. # # pull request checks only (commit hygiene, host test suites, the CI's -# own tests), on every push; add the ci:build label for a -# build now (kernel-ci-label.yml) +# own tests), on every push; everything for the team +# (.github/VOUCHED.td) once out of draft; add the ci:build +# label for a build now (kernel-ci-label.yml) # merge queue everything: the kernel package built with omarchy-pkgs' # own recipe, KUnit, a QEMU boot that loads every module, # and a comparison with the target branch's package diff --git a/tools/aurora-ci/README.rst b/tools/aurora-ci/README.rst index 687be0ca91e7a3..54bc1f1752a14b 100644 --- a/tools/aurora-ci/README.rst +++ b/tools/aurora-ci/README.rst @@ -12,14 +12,17 @@ What runs when ============== Builds take time and, on some runners, money. Pull requests get the checks -that run on free GitHub-hosted runners on every push; the kernel is built -once, in the merge queue, from exactly the tree that will land. +that run on free GitHub-hosted runners on every push; the team's pull +requests are also built on every push, and everyone's kernel is built again +in the merge queue, from exactly the tree that will land. ==================== ================================================= Event Jobs ==================== ================================================= pull request push plan, commits, compile, device trees, host tests, CI self-test +trusted author push all of the above, then package, KUnit and boot + (not on drafts) ``ci:build`` label all of the above, then package, KUnit and boot merge queue everything push to the branch package (reused from the queue), attestation @@ -124,12 +127,32 @@ Who can start a build ===================== Light runs execute a pull request's code on GitHub-hosted runners with a -read-only token, as every public repository's CI does. Full runs start only -from a maintainer action: queueing a pull request, pushing to the branch, a -manual run, or applying ``ci:build`` (which needs triage access). On a branch -of this repository the label applies to every later push; on a fork it -applies to the head it was applied to, and has to be applied again after a -new push. +read-only token, as every public repository's CI does. Full runs start from +a trusted author or a maintainer action: + +- a push to a pull request, from a fork too, once it is out of draft, by + anyone vouched for in ``.github/VOUCHED.td`` (the kernel team), when the + pusher is vouched for too. Access to the repository or the omacom + organization alone does not count; +- queueing a pull request, pushing to the branch, or a manual run; +- applying ``ci:build`` (which needs triage access). On a branch of this + repository the label applies to every later push; on a fork it applies to + the head it was applied to, and has to be applied again after a new push. + +``VOUCHED.td`` lists the team: one ``github:`` per line, sorted. +``-github: `` denounces an author, which the label does not +override. The plan job reads the list from the target +branch through the API, so a pull request that edits it changes nothing until +it merges. To add someone, open a pull request adding their line. + +GitHub holds every run of a pull request from an outside collaborator until +a maintainer approves it. ``kernel-ci-approve.yml`` (``approve-runs.py``) +releases the held ``kernel-ci.yml`` run of the current head when the author +is vouched for, so they need no clicks either. It runs on +``pull_request_target`` and fetches only the target branch's files; no pull +request code runs with its write token. Anyone else's runs stay held, and +once approved they run the checks only unless a maintainer applies +``ci:build``. On a ``pull_request`` event GitHub runs the workflow files from the pull request itself, so these rules decide cost, not security: a fork could edit @@ -160,10 +183,12 @@ Repository setup These need an administrator: - a ``ci:build`` label; +- ``.github/VOUCHED.td`` kept to the team (a pull request, like any other); - branch protection for ``integration/aurora`` requiring ``ci / result``; - the merge queue (merge method: merge commit), so the tree that merges is the tree that was tested; -- workflow approval for outside collaborators (Settings, Actions, General); +- workflow approval for all outside collaborators (Settings, Actions, + General), which ``kernel-ci-approve.yml`` relies on; - optionally ``KERNEL_CI_RUNNER`` for faster builds. Running the tools locally diff --git a/tools/aurora-ci/approve-runs.py b/tools/aurora-ci/approve-runs.py new file mode 100755 index 00000000000000..2bca56a5566293 --- /dev/null +++ b/tools/aurora-ci/approve-runs.py @@ -0,0 +1,118 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0 +"""Release the held kernel CI run of a pull request by a vouched-for author. + +GitHub holds every pull_request run from outside collaborators until a +maintainer approves it. kernel-ci-approve.yml runs this on +pull_request_target, from the target branch's code, never the pull +request's: when the author and the pusher are vouched for in +.github/VOUCHED.td it approves the held kernel-ci.yml run of the pull request's current head, and plan.py then +decides what that run does. Organization members' and collaborators' runs +are never held; anyone else's stay held for a maintainer. +""" + +import argparse +import importlib.util +import json +import os +import sys +import time +import urllib.parse +import urllib.request +from pathlib import Path + +WORKFLOW = ".github/workflows/kernel-ci.yml" +HELD = "action_required" + + +def load_plan(): + path = Path(__file__).resolve().parent / "plan.py" + spec = importlib.util.spec_from_file_location("plan", path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +class Api: + def __init__(self, url, repository, token): + self.url, self.repository, self.token = url.rstrip("/"), repository, token + + def request(self, method, path, **query): + address = f"{self.url}/repos/{self.repository}/{path}" + if query: + address += "?" + urllib.parse.urlencode(query) + request = urllib.request.Request(address, method=method, headers={ + "Accept": "application/vnd.github+json", + "Authorization": f"Bearer {self.token}", + "X-GitHub-Api-Version": "2022-11-28", + }) + with urllib.request.urlopen(request, timeout=60) as response: + body = response.read() + return json.loads(body) if body else {} + + def get(self, path, **query): + return self.request("GET", path, **query) + + def post(self, path): + return self.request("POST", path) + + +def held(run): + return HELD in (run.get("status"), run.get("conclusion")) + + +def approve(api, event, vouched, plan, attempts=36, sleep=time.sleep): + """Approve the newest held kernel-ci.yml run of the pull request's head. + Returns a sentence saying what happened.""" + pr = event["pull_request"] + status, author = plan.trust(event, vouched) + if status != "vouched": + return f"{author} is {status}: nothing to approve" + number, head_sha = pr["number"], pr["head"]["sha"] + head_repo = (pr["head"].get("repo") or {}).get("id") + + for attempt in range(attempts): + if attempt: + sleep(5) + current = api.get(f"pulls/{number}") + if current.get("state") != "open" or current["head"]["sha"] != head_sha: + return f"#{number} closed or moved past {head_sha[:12]}: nothing to approve" + data = api.get("actions/runs", event="pull_request", head_sha=head_sha, per_page=100) + runs = sorted((run for run in data.get("workflow_runs", []) + if run.get("path") == WORKFLOW and run.get("head_sha") == head_sha + and (run.get("head_repository") or {}).get("id") == head_repo), + key=lambda run: run["id"]) + if not runs: + continue # GitHub creates the pull_request run alongside this one + newest = runs[-1] + if not held(newest): + return f"run {newest['id']} for {head_sha[:12]} is not held" + api.post(f"actions/runs/{newest['id']}/approve") + return f"approved run {newest['id']} for {author} ({status}) at {head_sha[:12]}" + raise TimeoutError(f"no {WORKFLOW} run for {head_sha[:12]} appeared") + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--event-path", type=Path, default=os.environ.get("GITHUB_EVENT_PATH")) + parser.add_argument("--vouched", type=Path, required=True, help="the target branch's VOUCHED.td") + args = parser.parse_args(argv) + + plan = load_plan() + api = Api(os.environ.get("GITHUB_API_URL", "https://api.github.com"), + os.environ["GITHUB_REPOSITORY"], os.environ["GITHUB_TOKEN"]) + try: + result = approve(api, json.loads(args.event_path.read_text()), + plan.read_vouched(args.vouched.read_text()), plan) + except (OSError, KeyError, TypeError, ValueError) as error: + print(f"::error title=Approve kernel CI::{error!r}", file=sys.stderr) + return 1 + print(result) + if os.environ.get("GITHUB_STEP_SUMMARY"): + with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as out: + out.write(f"{result}.\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/aurora-ci/plan.py b/tools/aurora-ci/plan.py index be5b4c6de625e9..310d4de0fabe76 100755 --- a/tools/aurora-ci/plan.py +++ b/tools/aurora-ci/plan.py @@ -17,10 +17,18 @@ pull_request, labeled full when the label is the build label. Applying a label needs triage access, so this is a maintainer asking for this exact head commit. - pull_request, other full when the build label is already on a branch - of this repository (only writers can push there); - light for forks, where a new push needs the label + pull_request, other full when the author is trusted and the pull + request is not a draft, from a fork too; full when + the build label is already on a branch of this + repository (only writers can push there); light + for forks, where a new push needs the label re-applied, and light otherwise. + +Trusted authors are the team, those vouched for in .github/VOUCHED.td, +which the workflow reads from the target branch so that a pull request cannot +vouch for itself. Repository or organization access alone does not count: +the organization is wider than the kernel team. An author denounced there +gets light runs only, whatever their labels. """ import argparse @@ -34,7 +42,43 @@ PR_REFRESH_ACTIONS = {"opened", "synchronize", "reopened", "ready_for_review"} -def plan(event_name, event, label=DEFAULT_LABEL): +def read_vouched(text): + """Lower-cased GitHub login -> "vouched" or "denounced", from VOUCHED.td. + A denouncement wins over any vouch for the same login.""" + entries = {} + for line in text.splitlines(): + line = line.strip() + if not line or line.startswith("#"): + continue + denounced = line.startswith("-") + platform, _, login = line.lstrip("-").split(None, 1)[0].partition(":") + if platform != "github" or not login: + continue + login = login.lower() + if denounced: + entries[login] = "denounced" + else: + entries.setdefault(login, "vouched") + return entries + + +def trust(event, vouched): + """(status, login) for a pull request event: "vouched" only when both the + pull request's author and whoever triggered the event (the pusher, on a + push) are vouched for, so no one outside the team can push to a team + member's pull request and have it built. Otherwise the login that is + denounced, or failing that unknown.""" + logins = [(event["pull_request"].get("user") or {}).get("login", ""), + (event.get("sender") or {}).get("login", "")] + statuses = [(vouched.get(login.lower(), "unknown"), login or "?") for login in logins] + for wanted in ("denounced", "unknown"): + for status, login in statuses: + if status == wanted: + return status, login + return "vouched", statuses[0][1] + + +def plan(event_name, event, label=DEFAULT_LABEL, vouched=None): """Return the plan as a dict of strings, ready for $GITHUB_OUTPUT.""" out = {"tier": "light", "reason": "", "base_sha": "", "head_sha": "", "pr_number": "", "fork": "false", "force": "false"} @@ -44,18 +88,26 @@ def plan(event_name, event, label=DEFAULT_LABEL): action = event.get("action", "") labels = {item["name"] for item in pr.get("labels", [])} fork = pr["head"]["repo"] is None or pr["head"]["repo"]["full_name"] != pr["base"]["repo"]["full_name"] + status, author = trust(event, vouched or {}) out.update(base_sha=pr["base"]["sha"], head_sha=pr["head"]["sha"], pr_number=str(pr["number"]), fork=str(fork).lower()) - if action == "labeled" and event.get("label", {}).get("name") == label: + if status == "denounced": + out["reason"] = f"checks only: {author} is denounced in .github/VOUCHED.td" + elif action == "labeled" and event.get("label", {}).get("name") == label: out.update(tier="full", reason=f"`{label}` applied to {pr['head']['sha'][:12]}") + elif action in PR_REFRESH_ACTIONS and status == "vouched" and not pr.get("draft"): + out.update(tier="full", reason=f"{author} is vouched for") elif action in PR_REFRESH_ACTIONS and label in labels and not fork: out.update(tier="full", reason=f"`{label}` is on this pull request") elif action in PR_REFRESH_ACTIONS and label in labels: out["reason"] = (f"fork pull request: re-apply `{label}` to build " f"{pr['head']['sha'][:12]}") + elif status == "vouched": + out["reason"] = (f"draft: {author}'s builds start when it is ready for review, " + f"or add `{label}` for a build now") else: - out["reason"] = (f"checks only; the merge queue builds the kernel, or add `{label}` " - "for a build now") + out["reason"] = (f"checks only ({author} is not in .github/VOUCHED.td); the merge " + f"queue builds the kernel, or add `{label}` for a build now") elif event_name == "merge_group": group = event["merge_group"] out.update(tier="full", reason="merge queue", base_sha=group["base_sha"], @@ -81,13 +133,16 @@ def main(argv=None): parser.add_argument("--event-name", default=os.environ.get("GITHUB_EVENT_NAME")) parser.add_argument("--event-path", type=Path, default=os.environ.get("GITHUB_EVENT_PATH")) parser.add_argument("--label", default=DEFAULT_LABEL) + parser.add_argument("--vouched", type=Path, + help="the target branch's VOUCHED.td; without it no author is trusted") args = parser.parse_args(argv) if not args.event_name or not args.event_path: parser.error("--event-name and --event-path (or the GitHub environment) are required") try: - result = plan(args.event_name, json.loads(args.event_path.read_text()), args.label) - except (KeyError, TypeError, ValueError) as error: + vouched = read_vouched(args.vouched.read_text()) if args.vouched else {} + result = plan(args.event_name, json.loads(args.event_path.read_text()), args.label, vouched) + except (KeyError, TypeError, ValueError, OSError) as error: print(f"::error title=CI plan::cannot plan this {args.event_name} event: {error!r}", file=sys.stderr) return 1 diff --git a/tools/aurora-ci/tests/test_approve_runs.py b/tools/aurora-ci/tests/test_approve_runs.py new file mode 100644 index 00000000000000..78941755e97cb3 --- /dev/null +++ b/tools/aurora-ci/tests/test_approve_runs.py @@ -0,0 +1,98 @@ +# SPDX-License-Identifier: GPL-2.0 +import os +import unittest.mock + +from support import TempDirTestCase, load + +approve_runs = load("approve-runs") +plan = load("plan") + +HEAD = "b" * 40 +FORK = 7 +WORKFLOW = ".github/workflows/kernel-ci.yml" +VOUCHED = plan.read_vouched("github:Teammate\n-github:banned spam\n") + + +def event(author="teammate", association="CONTRIBUTOR", sender=None): + return {"sender": {"login": sender or author}, "pull_request": {"number": 42, "user": {"login": author}, + "author_association": association, + "head": {"sha": HEAD, "repo": {"id": FORK}}}} + + +def run(run_id, conclusion="action_required", status="completed", path=WORKFLOW, sha=HEAD, repo=FORK): + return {"id": run_id, "path": path, "head_sha": sha, "status": status, "conclusion": conclusion, + "head_repository": {"id": repo}} + + +class FakeApi: + def __init__(self, runs=(), pulls=None): + self.runs = list(runs) # one list per poll; the last one repeats + self.pulls = pulls or [{"state": "open", "head": {"sha": HEAD}}] + self.polls = 0 + self.approved = [] + + def get(self, path, **query): + if path == "pulls/42": + return self.pulls[min(self.polls, len(self.pulls) - 1)] + if path == "actions/runs": + assert query["event"] == "pull_request" and query["head_sha"] == HEAD + runs = self.runs[min(self.polls, len(self.runs) - 1)] if self.runs else [] + self.polls += 1 + return {"workflow_runs": runs} + raise AssertionError(path) + + def post(self, path): + self.approved.append(path) + + +class ApproveTest(TempDirTestCase): + def approve(self, api, pr_event=None, attempts=3): + return approve_runs.approve(api, pr_event or event(), VOUCHED, plan, attempts=attempts, + sleep=lambda seconds: None) + + def test_approves_the_newest_held_run_of_a_vouched_author(self): + api = FakeApi([[run(5), run(9), run(7)]]) + self.assertIn("approved run 9", self.approve(api)) + self.assertEqual(api.approved, ["actions/runs/9/approve"]) + + def test_waits_for_the_run_to_appear(self): + api = FakeApi([[], [], [run(3)]]) + self.approve(api) + self.assertEqual(api.approved, ["actions/runs/3/approve"]) + + def test_never_approves_anyone_else(self): + for pr_event in (event("stranger"), event("banned"), event("BANNED"), + event("member", association="MEMBER"), event(sender="stranger"), + event(sender="banned")): + with self.subTest(event=pr_event): + api = FakeApi([[run(3)]]) + self.assertIn("nothing to approve", self.approve(api, pr_event)) + self.assertEqual((api.approved, api.polls), ([], 0)) + + def test_ignores_other_workflows_heads_and_repositories(self): + api = FakeApi([[run(3, path=".github/workflows/kernel-ci-label.yml"), run(4, sha="c" * 40), + run(5, repo=99)]]) + with self.assertRaises(TimeoutError): + self.approve(api) + self.assertEqual(api.approved, []) + + def test_leaves_a_run_that_is_not_held(self): + api = FakeApi([[run(3), run(4, conclusion=None, status="in_progress")]]) + self.assertIn("not held", self.approve(api)) + self.assertEqual(api.approved, []) + + def test_stops_when_the_head_moves_or_the_pull_request_closes(self): + for pull in ({"state": "open", "head": {"sha": "c" * 40}}, {"state": "closed", "head": {"sha": HEAD}}): + with self.subTest(pull=pull): + api = FakeApi([[run(3)]], pulls=[pull]) + self.assertIn("nothing to approve", self.approve(api)) + self.assertEqual(api.approved, []) + + def test_main_fails_without_a_vouch_list(self): + self.github_env() + path = self.tmp / "event.json" + path.write_text("{}") + environment = {"GITHUB_REPOSITORY": "omacom/linux-aurora", "GITHUB_TOKEN": "unused"} + with unittest.mock.patch.dict(os.environ, environment): + self.assertEqual(approve_runs.main(["--event-path", str(path), + "--vouched", str(self.tmp / "missing")]), 1) diff --git a/tools/aurora-ci/tests/test_plan.py b/tools/aurora-ci/tests/test_plan.py index a3c61e44e684a0..93c82a30509256 100644 --- a/tools/aurora-ci/tests/test_plan.py +++ b/tools/aurora-ci/tests/test_plan.py @@ -1,7 +1,7 @@ # SPDX-License-Identifier: GPL-2.0 import json -from support import TempDirTestCase, load, read_outputs +from support import TREE, TempDirTestCase, load, read_outputs plan_module = load("plan") plan = plan_module.plan @@ -10,11 +10,16 @@ HEAD = "b" * 40 -def pull_request(action, labels=(), fork=False, label=None): +def pull_request(action, labels=(), fork=False, label=None, author="someone", + association="CONTRIBUTOR", draft=False, sender=None): event = { "action": action, + "sender": {"login": sender or author}, "pull_request": { "number": 42, + "user": {"login": author}, + "author_association": association, + "draft": draft, "labels": [{"name": name} for name in labels], "base": {"sha": BASE, "repo": {"full_name": "omacom/linux-aurora"}}, "head": {"sha": HEAD, "repo": {"full_name": "someone/linux-aurora" if fork @@ -65,6 +70,93 @@ def test_custom_label(self): self.assertEqual(plan("pull_request", event, label="build-approved")["tier"], "full") +VOUCHED = """\ +# comment +github:Acelogic +github:Teammate +-github:Banned spam +github:banned +-github:Revoked +gitlab:other +""" + + +class TrustedAuthorTest(TempDirTestCase): + def setUp(self): + super().setUp() + self.vouched = plan_module.read_vouched(VOUCHED) + + def test_read_vouched(self): + self.assertEqual(self.vouched, {"acelogic": "vouched", "teammate": "vouched", + "banned": "denounced", "revoked": "denounced"}) + + def test_vouched_author_builds_every_push_from_a_fork(self): + for action in ("opened", "synchronize", "reopened", "ready_for_review"): + with self.subTest(action=action): + result = plan("pull_request", pull_request(action, fork=True, author="acelogic"), + vouched=self.vouched) + self.assertEqual(result["tier"], "full") + self.assertIn("acelogic is vouched for", result["reason"]) + + def test_unlisted_author_runs_checks_only_whatever_their_access(self): + for association in ("OWNER", "MEMBER", "COLLABORATOR", "CONTRIBUTOR", + "FIRST_TIME_CONTRIBUTOR", "NONE"): + with self.subTest(association=association): + event = pull_request("synchronize", fork=True, association=association) + self.assertEqual(plan("pull_request", event, vouched=self.vouched)["tier"], "light") + + def test_push_by_someone_outside_the_team_runs_checks_only(self): + for sender in ("stranger", "banned"): + with self.subTest(sender=sender): + event = pull_request("synchronize", fork=True, author="Teammate", sender=sender) + result = plan("pull_request", event, vouched=self.vouched) + self.assertEqual(result["tier"], "light") + self.assertIn(sender, result["reason"]) + + def test_missing_sender_is_not_trusted(self): + event = pull_request("synchronize", author="Teammate") + del event["sender"] + self.assertEqual(plan("pull_request", event, vouched=self.vouched)["tier"], "light") + + def test_maintainer_label_still_builds_an_unknown_author(self): + event = pull_request("labeled", label="ci:build", author="stranger", sender="Teammate") + self.assertEqual(plan("pull_request", event, vouched=self.vouched)["tier"], "full") + + def test_draft_waits_until_ready_for_review(self): + draft = plan("pull_request", pull_request("synchronize", author="Teammate", draft=True), + vouched=self.vouched) + self.assertEqual(draft["tier"], "light") + self.assertIn("ready for review", draft["reason"]) + labeled = plan("pull_request", pull_request("labeled", author="Teammate", draft=True, + label="ci:build"), vouched=self.vouched) + self.assertEqual(labeled["tier"], "full") + + def test_denouncement_overrides_access_and_label(self): + for event in (pull_request("synchronize", author="banned", association="COLLABORATOR"), + pull_request("labeled", labels=["ci:build"], label="ci:build", author="Revoked"), + pull_request("synchronize", labels=["ci:build"], author="BANNED")): + with self.subTest(event=event): + result = plan("pull_request", event, vouched=self.vouched) + self.assertEqual(result["tier"], "light") + self.assertIn("denounced", result["reason"]) + + def test_without_a_list_no_author_is_trusted(self): + for event in (pull_request("opened", author="Acelogic"), pull_request("opened", association="MEMBER")): + with self.subTest(event=event): + self.assertEqual(plan("pull_request", event)["tier"], "light") + + def test_the_repository_list_is_well_formed(self): + path = TREE / ".github" / "VOUCHED.td" + entries = [line for line in path.read_text().splitlines() if line and not line.startswith("#")] + logins = [entry.lstrip("-").split()[0].partition(":")[2] for entry in entries] + self.assertTrue(all(entry.lstrip("-").startswith("github:") for entry in entries)) + self.assertTrue(all(len(entry.split()) > 1 for entry in entries if entry.startswith("-")), + "a denouncement needs a reason") + self.assertIn("vouched", plan_module.read_vouched(path.read_text()).values()) + self.assertEqual(logins, sorted(logins, key=str.lower)) + self.assertEqual(len(logins), len({login.lower() for login in logins})) + + class OtherEventsTest(TempDirTestCase): def test_merge_group_builds_the_queue_commit(self): result = plan("merge_group", {"merge_group": {"base_sha": BASE, "head_sha": HEAD}}) @@ -105,6 +197,16 @@ def test_writes_github_outputs(self): self.assertEqual(values["head_sha"], HEAD) self.assertIn("full run", summary.read_text()) + def test_reads_the_vouch_list(self): + output, _ = self.github_env() + event = self.tmp / "event.json" + event.write_text(json.dumps(pull_request("synchronize", fork=True, author="Teammate"))) + vouched = self.tmp / "VOUCHED.td" + vouched.write_text(VOUCHED) + self.assertEqual(plan_module.main(["--event-name", "pull_request", "--event-path", str(event), + "--vouched", str(vouched)]), 0) + self.assertEqual(read_outputs(output)["tier"], "full") + def test_malformed_event_fails_cleanly(self): self.github_env() event = self.tmp / "event.json"