diff --git a/.github/ci-policy.yml b/.github/ci-policy.yml new file mode 100644 index 000000000..8103daf23 --- /dev/null +++ b/.github/ci-policy.yml @@ -0,0 +1,4 @@ +merge_queue: false +required_checks: [] +status_contexts: [] +exceptions: [] diff --git a/.github/ci-policy/check.py b/.github/ci-policy/check.py new file mode 100755 index 000000000..b90ea96a9 --- /dev/null +++ b/.github/ci-policy/check.py @@ -0,0 +1,436 @@ +#!/usr/bin/env python3 +"""ci-policy checker: enforces rules R1 to R8 and decisions D-1, D-3, D-7, D-8 of +standards/general/ci.md. Reads only .github/ci-policy.yml and .github/workflows (no token).""" +import argparse +import itertools +import re +import sys +from datetime import date +from pathlib import Path +from typing import NamedTuple + +import yaml + +CLASSES = {"pr-validation", "main-build", "deploy", "gate", "scheduled", "manual"} +POLICY = ".github/ci-policy.yml" +SELECTOR = "changes" # D-5: the job that decides relevance +HEADER = re.compile(r"^#\s*ci-policy:\s*class=([\w-]+)", re.M) + + +class Violation(NamedTuple): + workflow: str + rule: str + reason: str + + +class Workflow(NamedTuple): + file: str + cls: str | None + on: dict + doc: dict + + +def triggers(raw) -> dict: + if isinstance(raw, str): + return {raw: {}} + if isinstance(raw, list): + return {event: {} for event in raw} + return {event: cfg if isinstance(cfg, dict) else {} for event, cfg in (raw or {}).items()} + + +def load_workflows(root: Path) -> tuple[list[Workflow], list[Violation]]: + workflows, problems = [], [] + for path in sorted((root / ".github/workflows").glob("*.y*ml")): + text = path.read_text() + try: + doc = yaml.safe_load(text) or {} + except yaml.YAMLError as err: + problems.append(Violation(path.name, "parse", f"invalid YAML: {err}")) + continue + header = HEADER.search(text) + # PyYAML (YAML 1.1) reads the key `on` as boolean True + workflows.append(Workflow(path.name, header and header[1], triggers(doc.get("on", doc.get(True))), doc)) + return workflows, problems + + +def load_policy(root: Path) -> dict: + return yaml.safe_load((root / POLICY).read_text()) or {} + + +def evaluate(cond, event, known=None): + """Three-valued evaluation of a workflow `if:`/`cancel-in-progress` value for one event. + + Only `github.event_name` and the `known` atoms are known; any other atom is unknown (None), so callers treat + "not provably False" as admitted. Parse trouble also yields unknown.""" + if cond is None or isinstance(cond, bool): + return cond + expr = re.sub(r"^\s*\$\{\{(.*)\}\}\s*$", r"\1", str(cond), flags=re.S) + toks = re.findall(r"'(?:[^']|'')*'|&&|\|\||==|!=|[()!,]|[^\s()!,&|=']+", expr) + pos = 0 + + def peek(): + return toks[pos] if pos < len(toks) else None + + def take(): + nonlocal pos + pos += 1 + return toks[pos - 1] + + def truth(v): + return v if v is None or isinstance(v, bool) else bool(v) + + def or_(): + left = and_() + while peek() == "||": + take() + a, b = truth(left), truth(and_()) + left = True if a or b else (None if a is None or b is None else False) + return left + + def and_(): + left = cmp_() + while peek() == "&&": + take() + a, b = truth(left), truth(cmp_()) + left = False if a is False or b is False else (None if a is None or b is None else True) + return left + + def cmp_(): + left = unary() + if peek() in ("==", "!="): + op, right = take(), unary() + return None if left is None or right is None else (left == right) == (op == "==") + return left + + def unary(): + if peek() == "!": + take() + v = truth(unary()) + return None if v is None else not v + return atom() + + def atom(): + tok = take() + if tok == "(": + v = or_() + take() + return v + if tok.startswith("'"): + return tok[1:-1].replace("''", "'") + if peek() == "(": # function call: skip the balanced argument list + depth = 0 + while True: + t = take() + depth += (t == "(") - (t == ")") + if depth == 0: + return None + return {"github.event_name": event, "true": True, "false": False, **(known or {})}.get(tok) + + try: + return truth(or_()) + except IndexError: + return None + + +def job_names(job_id: str, job: dict, by_file: dict) -> list[tuple[str, dict]]: + """(check name, job that runs it) pairs a job produces (D-3); a reusable call yields the callee's jobs. + A name ending in ' / ' marks a remote callee that cannot be read.""" + name = job.get("name") or job_id + uses = job.get("uses") + if uses: + callee = by_file.get(Path(uses).name) if uses.startswith("./") else None + if callee is None: + return [(f"{name} / ", job)] + return [(f"{name} / {n}", leaf) for cid, cjob in (callee.doc.get("jobs") or {}).items() + for n, leaf in job_names(cid, cjob, {})] + matrix = (job.get("strategy") or {}).get("matrix") + if not isinstance(matrix, dict): + return [(name, job)] + axes = {k: v for k, v in matrix.items() if isinstance(v, list) and k not in ("include", "exclude")} + combos = [dict(zip(axes, vals)) for vals in itertools.product(*axes.values())] if axes else [] + subset = lambda part, whole: all(k in whole and whole[k] == v for k, v in part.items()) + combos = [c for c in combos if not any(subset(x, c) for x in matrix.get("exclude") or [])] + labels = [list(c.values()) for c in combos] # default names use the original axis values only + original = len(combos) # an include only extends original combos, never ones added by an earlier include + for inc in (i for i in matrix.get("include") or [] if isinstance(i, dict)): + # it extends every original combo whose axis values it does not overwrite, else it is a new combo + hits = [n for n in range(original) if all(combos[n][k] == inc[k] for k in axes if k in inc)] + for n in hits: + combos[n] = {**combos[n], **{k: v for k, v in inc.items() if k not in axes}} + if not hits: + combos.append(inc) + labels.append(list(inc.values())) + if not combos: + return [(name, job)] + if job.get("name"): + return [(re.sub(r"\$\{\{\s*matrix\.([\w-]+)\s*\}\}", lambda m, c=c: str(c.get(m[1], m[0])), name), job) for c in combos] + return [(f"{job_id} ({', '.join(map(str, lab))})", job) for lab in labels] + + +def name_matches(required: str, produced: str) -> bool: + return required == produced + + +def concurrency(doc: dict) -> dict: + conc = doc.get("concurrency") + return {"group": conc} if isinstance(conc, str) else conc or {} + + +def only_default_branch(cfg: dict, default_branch: str) -> bool: + branches = cfg.get("branches") + if branches: + return set([branches] if isinstance(branches, str) else branches) <= {default_branch} + return "tags" in cfg and "branches-ignore" not in cfg # a tags-only push never runs for a branch push + + +def deploy_markers(w: Workflow, overrides: dict) -> list[str]: + markers = [f"file name {w.file}"] if re.search(r"deploy|release", w.file) else [] + for jid, job in (w.doc.get("jobs") or {}).items(): + if overrides.get(jid) == "deploy": # D9: the job is declared a deploy job + continue + if "environment" in job: + markers.append(f"job {jid} environment") + if re.search(r"-deploy\b", str(job.get("runs-on"))): + markers.append(f"job {jid} *-deploy runner label") + return markers + + +def workflow_rules(w: Workflow, producing: bool, mq: bool, private: bool, default_branch: str, + overrides: dict) -> list[Violation]: + out = [] + + def bad(rule, reason): + out.append(Violation(w.file, rule, reason)) + + if w.cls not in CLASSES: + bad("D-1", "unclassified workflow: add `# ci-policy: class=<" + "|".join(sorted(CLASSES)) + ">`" + if w.cls is None else f"unknown class {w.cls!r}") + elif w.cls != "deploy" and (markers := deploy_markers(w, overrides)): + bad("D-1", f"class is {w.cls} but it has deploy markers ({'; '.join(markers)}): class must be deploy") + + jobs = w.doc.get("jobs") or {} + conc = concurrency(w.doc) + if "push" in w.on: # R1 + if mq and producing: + bad("R1", "merge-queue repo: workflow produces a required check or status and must not run on push (D-4)") + elif (w.cls == "pr-validation" or producing) and not only_default_branch(w.on["push"], default_branch): + bad("R1", f"push trigger must be limited to branches: [{default_branch}]") + pr_events = [e for e in ("pull_request", "pull_request_target") if e in w.on] + if w.cls == "pr-validation" and pr_events: # R2 + if not conc.get("group"): + bad("R2", "no workflow-level concurrency group") + elif not re.search(r"github\.(event\.pull_request\.number|head_ref|ref)\b", str(conc["group"])): + bad("R2", "concurrency group is not per PR (use github.event.pull_request.number or github.ref)") + for event in pr_events if conc.get("group") else []: # omitted cancel-in-progress defaults to false + cancel = conc.get("cancel-in-progress") + if cancel is None or evaluate(cancel, event) is False: + bad("R2", f"cancel-in-progress must be true for {event} events") + if w.cls == "main-build": # R3 + cancel = conc.get("cancel-in-progress") + if not conc.get("group"): + bad("R3", "no concurrency group: every push starts a parallel run") + elif re.search(r"github\.(sha|run_id|run_number)\b", str(conc["group"])): + bad("R3", "concurrency group is per run, not a stable group per ref") + if cancel is not None and evaluate(cancel, None) is not False: + bad("R3", "cancel-in-progress must be false (one running, one pending)") + deploys = list(jobs) if w.cls == "deploy" else [j for j in jobs if overrides.get(j) == "deploy"] # D9 overrides count + if deploys and w.cls in CLASSES: # R4: the workflow-level group also cancels an overridden deploy job + for where, c in [("workflow", conc)] + [(f"job {j}", concurrency(jobs[j])) for j in deploys]: + if c.get("cancel-in-progress") is not None and evaluate(c["cancel-in-progress"], None) is not False: + bad("R4", f"{where}: deploy must never cancel in progress") + if private: # R6 + for jid, job in jobs.items(): + runs = job.get("runs-on") + if runs is not None and "self-hosted" not in str(runs) and not (isinstance(runs, dict) and "group" in runs): + bad("R6", f"job {jid} runs on {runs!r}, not a self-hosted runner") + return out + + +def required_check_rules(w: Workflow, name: str, job_id: str, job: dict, mq: bool) -> list[Violation]: + out = [] + for gated in ([("pull_request", "pull_request_target")] + ([("merge_group",)] if mq else [])): + event = next((e for e in gated if e in w.on), None) + if event is None: + out.append(Violation(w.file, "R5", f"produces required check {name!r} but has no {gated[0]} trigger")) + continue + if {"paths", "paths-ignore"} & w.on[event].keys(): + out.append(Violation(w.file, "R5", f"required check {name!r}: {event} trigger has a paths filter (check can hang)")) + if evaluate(job.get("if"), event) is False: + out.append(Violation(w.file, "R5", f"required check {name!r}: job {job_id} `if:` excludes {event}")) + return out + + +BAD_RESULTS = ("failure", "cancelled", "skipped") + + +def skip_covered(cond, producer_if, need: str) -> bool: + """True when `cond` fires on `needs..result == skipped` for every value of the selector's outputs that + leaves the producer job relevant (its `if:` not provably False). The outputs are tried over the string literals + of both conditions plus an empty and an unrelated value. Anything still unknown after that counts as not covered.""" + both = f"{cond} {producer_if or ''}" + atoms = sorted(set(re.findall(rf"needs\.{SELECTOR}\.outputs\.[\w\-]+", both))) + if len(atoms) > 4: + return False + values = sorted({m.replace("''", "'") for m in re.findall(r"'((?:[^']|'')*)'", both)} | {"", "\0other"}) + for combo in itertools.product(values, repeat=len(atoms)): + known = dict(zip(atoms, combo)) + if evaluate(producer_if, None, known) is not False and \ + evaluate(cond, None, {**known, f"needs.{need}.result": "skipped"}) is not True: + return False + return True + + +def failing_states(job: dict, need: str, producer_if=None) -> set[str]: + """Results of `need` on which a step fails the job (R8). Only two step shapes are understood: a single + `test`/`[` assertion `= success` with no `if:`, and `run: exit N` under an `if:` that is evaluated per result. + A step with `continue-on-error`, or an assertion with extra shell (`|| true`), proves nothing. `skipped` may + also be guarded by the selector's relevance: `skip_covered` proves the condition fires whenever the producer + job's own `if:` leaves it relevant.""" + ref = rf"\$\{{\{{\s*needs\.{re.escape(need)}\.result\s*\}}\}}" + assertion = re.compile(rf'(?:test\s+"?{ref}"?\s+==?\s+"?success"?|\[\s+"?{ref}"?\s+==?\s+"?success"?\s+\])') + states = set() + for step in job.get("steps") or []: + if step.get("continue-on-error") not in (None, False, "false"): + continue + run, cond = str(step.get("run") or "").strip(), step.get("if") + if cond is None and assertion.fullmatch(run): + states |= set(BAD_RESULTS) + elif cond is not None and re.fullmatch(r"(exit\s+[1-9]|false)", run): + for state in BAD_RESULTS: + fires = evaluate(cond, None, {f"needs.{need}.result": state}) + if fires is True or (state == "skipped" and skip_covered(cond, producer_if, need)): + states.add(state) + return states + + +def aggregate_rules(w: Workflow, name: str, job_id: str, job: dict, jobs: dict) -> list[Violation]: + """R8 (D-5, D13): a required check is an aggregate job that cannot pass when the selector failed or a job was skipped.""" + out = [] + + def bad(reason): + out.append(Violation(w.file, "R8", f"required check {name!r}: job {job_id} {reason}")) + + if not re.search(r"\balways\(\)", re.sub(r"^\s*\$\{\{(.*)\}\}\s*$", r"\1", str(job.get("if") or ""), flags=re.S)): + bad("`if:` must use always(): a skipped or failed selector would otherwise pass the check") + needs = job.get("needs") or [] + needs = [needs] if isinstance(needs, str) else needs + if SELECTOR not in needs: + bad(f"must need the `{SELECTOR}` selector job") + if job.get("continue-on-error") not in (None, False, "false"): + bad("must not set continue-on-error: the check would pass when the job fails") + for need in needs: + if missing := [r for r in BAD_RESULTS if r not in failing_states(job, need, (jobs.get(need) or {}).get("if"))]: + bad(f"does not fail the job when needs.{need}.result is {', '.join(missing)}" + f" (add a step `test \"${{{{ needs.{need}.result }}}}\" = success`)") + return out + + +def job_class_rules(overrides: dict, by_file: dict) -> list[Violation]: + """D9: every `job_classes` entry names an existing job and a known class.""" + out = [] + for file, jobs in overrides.items(): + existing = (by_file[file].doc.get("jobs") or {}) if file in by_file else {} + for jid, cls in (jobs or {}).items(): + if jid not in existing: + out.append(Violation(POLICY, "D-1", f"job_classes: no job {jid!r} in {file}")) + elif cls not in CLASSES: + out.append(Violation(POLICY, "D-1", f"job_classes: {file} {jid} has unknown class {cls!r}")) + return out + + +def status_rules(ctx: dict, by_file: dict, mq: bool) -> list[Violation]: + name, file, targets = ctx.get("name"), ctx.get("workflow"), ctx.get("targets") or {} + w = by_file.get(file) + if w is None: + return [Violation(POLICY, "R7", f"status {name!r}: workflow {file!r} not found")] + out = [] + for events, want in [(("pull_request", "pull_request_target"), "pr-head")] + ([(("merge_group",), "merge-group-head")] if mq else []): + if not any(e in w.on for e in events): + out.append(Violation(w.file, "R7", f"status {name!r}: no {events[0]} trigger")) + if next((targets[e] for e in events if e in targets), None) != want: + out.append(Violation(w.file, "R7", f"status {name!r}: declare target {want} for {events[0]}")) + return out + + +def apply_exceptions(found: list[Violation], exceptions: list, today: date, repo: str) -> tuple[list[Violation], list[Violation]]: + """D-7 and D-8: a valid exception removes matching findings; an invalid or expired one adds its own.""" + warnings, extra = [], [] + for e in exceptions: + rule, file = e.get("rule"), e.get("workflow") or "-" + need = ["repo", "workflow", "rule", "reason", "owner", "expires"] + (["decision"] if rule in ("R4", "R6", "R7") else []) + errors = [] + if missing := [k for k in need if not e.get(k)]: + errors.append(Violation(file, "D-7", f"exception for {rule}: missing {', '.join(missing)}")) + if e.get("repo") and e["repo"] != repo: + errors.append(Violation(file, "D-7", f"exception for {rule} is for repo {e['repo']}, not {repo}")) + try: + expires = e["expires"] if isinstance(e.get("expires"), date) else date.fromisoformat(str(e.get("expires"))) + except ValueError: + expires = None + errors.append(Violation(file, "D-7", f"exception for {rule}: invalid expires {e.get('expires')!r}")) + if expires and (expires - today).days > 60: + errors.append(Violation(file, "D-7", f"exception for {rule}: expires {expires} is more than 60 days out")) + if expires and expires < today: + late = Violation(file, "D-8", f"exception for {rule} expired {expires}") + (errors if (today - expires).days > 7 else warnings).append(late) + if errors: + extra += errors + else: + found = [v for v in found if (v.workflow, v.rule) != (file, rule)] + return found + extra, warnings + + +def check(root: Path, repo: str, private: bool = False, default_branch: str = "main", + today: date | None = None) -> tuple[list[Violation], list[Violation]]: + """Return (violations, warnings).""" + if not (root / POLICY).exists(): + return [Violation(POLICY, "D-2", "policy file missing")], [] + workflows, found = load_workflows(root) + policy = load_policy(root) + mq = bool(policy.get("merge_queue")) + required = policy.get("required_checks") or [] + contexts = policy.get("status_contexts") or [] + by_file = {w.file: w for w in workflows} + overrides = policy.get("job_classes") or {} + found += job_class_rules(overrides, by_file) + producers = [(n, w, jid, job, leaf) for w in workflows for jid, job in (w.doc.get("jobs") or {}).items() + for n, leaf in job_names(jid, job, by_file)] + producing = {w.file for n, w, *_ in producers if any(name_matches(r, n) for r in required)} + producing |= {c.get("workflow") for c in contexts} + for w in workflows: + found += workflow_rules(w, w.file in producing, mq, private, default_branch, overrides.get(w.file) or {}) + for req in required: + hits = [p for p in producers if name_matches(req, p[0])] + if not hits: + remote = any(req.startswith(n) for n, *_ in producers if n.endswith(" / ")) + found.append(Violation(POLICY, "R5", f"required check {req!r} is not produced by any job" + + (" (remote reusable workflow names cannot be verified: add an R5 exception)" if remote else ""))) + for _, w, jid, job, leaf in hits: + found += required_check_rules(w, req, jid, job, mq) + siblings = next((x.doc["jobs"] for x in workflows if any(j is leaf for j in (x.doc.get("jobs") or {}).values())), {}) + found += aggregate_rules(w, req, jid, leaf, siblings) # leaf: the callee job for a reusable call + for ctx in contexts: + found += status_rules(ctx, by_file, mq) + found, warnings = apply_exceptions(list(dict.fromkeys(found)), policy.get("exceptions") or [], today or date.today(), repo) + return found, warnings + + +def main(argv=None) -> int: + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument("--root", type=Path, default=Path(".")) + ap.add_argument("--repo", required=True, help="owner/name; exceptions for other repos are rejected") + ap.add_argument("--private", action="store_true", help="repo is private (R6)") + ap.add_argument("--default-branch", default="main") + ap.add_argument("--today", type=date.fromisoformat, default=None) + ap.add_argument("--report-only", action="store_true", help="print violations, always exit 0") + args = ap.parse_args(argv) + violations, warnings = check(args.root, args.repo, args.private, args.default_branch, args.today) + for v in warnings: + print(f"WARN {args.repo} {v.workflow} {v.rule} {v.reason}") + for v in violations: + print(f"{args.repo} {v.workflow} {v.rule} {v.reason}") + return 1 if violations and not args.report_only else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.github/ci-policy/gate.py b/.github/ci-policy/gate.py new file mode 100644 index 000000000..e12ce6176 --- /dev/null +++ b/.github/ci-policy/gate.py @@ -0,0 +1,153 @@ +#!/usr/bin/env python3 +"""ci-policy caller logic (D-6, eng review D10 and D14). Run from the BASE revision's bytes: the head is only read as +data (`git archive`), nothing from it is executed. Needs `git` and, for the API reads, `gh` with GH_TOKEN. + + pr --repo OWNER/NAME --pr N --base SHA --head SHA [--private] [--default-branch main] [--root DIR] + merge-group --repo OWNER/NAME --group-ref REF + +`pr` runs check.py on the head's workflow files and policy file. A PR that edits `.github/ci-policy*` or the caller +workflow also fails `policy-changed` until a GitHub review APPROVED by a human who is not the author or a bot, with +write access, on the current head SHA. A new push moves the head, so it resets the approval. `merge-group` lists the PRs queued +in the group (the merge commits on the group head's first-parent chain), finds each by its recorded head and copies its latest +`ci-policy` check-run result; a commit whose PR the queue data does not identify fails closed.""" +import argparse +import json +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import check as ci_check # noqa: E402 + +CHECK_NAME = "ci-policy" +WRITERS = {"OWNER", "MEMBER", "COLLABORATOR"} +VERDICTS = {"APPROVED", "CHANGES_REQUESTED", "DISMISSED"} # a COMMENTED review changes nothing +COMPARE_CAP = 250 # the compare API lists at most this many commits +GROUP_REF = re.compile(r"^refs/heads/(gh-readonly-queue/(.+)/pr-(\d+)-[0-9a-f]{40})$") + + +def is_protected(path: str) -> bool: + return path.startswith(".github/ci-policy") or path == ".github/workflows/ci-policy.yml" + + +def gh_api(path: str): + """JSON for one object, or a list for a paginated array (`check_runs` unwrapped).""" + jq = (".check_runs[]" if "/check-runs" in path else ".commits[]" if "/compare/" in path + else ".[]" if path.endswith(("/reviews", "/pulls")) else ".") + out = subprocess.run(["gh", "api", "--paginate", path, "--jq", jq], check=True, capture_output=True, text=True).stdout + items = [json.loads(line) for line in out.splitlines() if line.strip()] + return items if jq != "." else items[0] + + +def approver(reviews: list, head: str, author: str) -> str | None: + latest = {} + for r in reviews: # chronological: the last verdict of each reviewer stands + if r["state"] in VERDICTS: + latest[r["user"]["login"]] = r + return next((login for login, r in latest.items() + if r["state"] == "APPROVED" and r["commit_id"] == head and login != author + and r["user"]["type"] == "User" and r.get("author_association") in WRITERS), None) + + +def changed_paths(root: Path, base: str, head: str) -> list[str]: + out = subprocess.run(["git", "-C", str(root), "-c", "core.quotepath=off", "diff", "--name-only", "--no-renames", f"{base}...{head}"], + check=True, capture_output=True, text=True).stdout + return out.splitlines() + + +def extract_head(root: Path, head: str, dest: Path) -> None: + """The head's `.github` tree as plain files; a repo without one yields an empty dir (the checker then reports D-2).""" + archive = subprocess.run(["git", "-C", str(root), "archive", head, ".github"], capture_output=True) + if archive.returncode == 0: + subprocess.run(["tar", "-x", "-C", str(dest)], input=archive.stdout, check=True) + + +def check_pr(root: Path, repo: str, pr: int, base: str, head: str, private: bool, default_branch: str, api=gh_api) -> list: + live = api(f"repos/{repo}/pulls/{pr}") + if live["head"]["sha"] != head: + return [ci_check.Violation("-", "head-moved", f"PR head is {live['head']['sha'][:12]}, not {head[:12]}: a newer run reports")] + found = [] + touched = [p for p in changed_paths(root, base, head) if is_protected(p)] + if touched and not approver(api(f"repos/{repo}/pulls/{pr}/reviews"), head, live["user"]["login"]): + found.append(ci_check.Violation(touched[0], "policy-changed", + f"PR edits {', '.join(touched)}: needs a non-author human APPROVED review on head {head[:12]}")) + with tempfile.TemporaryDirectory() as tmp: + extract_head(root, head, Path(tmp)) + violations, _ = ci_check.check(Path(tmp), repo, private, default_branch) + return found + violations + + +def check_merge_group(repo: str, group_ref: str, api=gh_api) -> list: + """Every PR queued in the group (the ref names only the last one) must have a successful `ci-policy` result. + + Only queue data GitHub itself records identifies a PR. Walk the first-parent chain from the group head down to the + base branch (the compare response also lists each PR's own commits, which are not queue commits). Each chain commit + must be a merge commit: its second parent is the PR head the queue merged, and `commits/{head}/pulls` names the one open PR that has that head. Titles and tree + contents prove nothing about identity and are not read. A squashed commit records no head, so it fails closed.""" + def bad(reason): + return [ci_check.Violation("-", "merge-group", reason)] + + if not (m := GROUP_REF.match(group_ref)): + return bad(f"cannot read the PR number from {group_ref!r}") + branch, base_branch, last = m[1], m[2], int(m[3]) + group_head = api(f"repos/{repo}/git/ref/heads/{branch}")["object"]["sha"] + commits = api(f"repos/{repo}/compare/{base_branch}...{group_head}?per_page=100") + if len(commits) >= COMPARE_CAP: + return bad(f"binding unavailable: compare lists {len(commits)} commits, so it may be truncated") + by_sha = {c["sha"]: c for c in commits} # compare also lists each PR's own commits; only the first-parent chain is the queue's + queued = {} # PR number -> the head the queue merged + sha = group_head + while sha in by_sha: + c = by_sha[sha] + parents = c["parents"] + if len(parents) != 2: + return bad(f"binding unavailable: group commit {c['sha'][:12]} is not a merge commit, so it records no PR head") + head = parents[1]["sha"] + owners = [p["number"] for p in api(f"repos/{repo}/commits/{head}/pulls") + if p["state"] == "open" and p["head"]["sha"] == head and p["base"]["ref"] == base_branch] + if len(owners) != 1: + return bad(f"binding unavailable: queued head {head[:12]} belongs to {len(owners)} open PRs, not one") + if owners[0] in queued: + return bad(f"PR #{owners[0]} is queued by two group commits") + queued[owners[0]] = head + sha = parents[0]["sha"] + if last not in queued: + return bad(f"binding unavailable: PR #{last} from the ref is not among the group's merged heads") + found = [] + for pr, head in sorted(queued.items()): + runs = api(f"repos/{repo}/commits/{head}/check-runs?check_name={CHECK_NAME}&per_page=100") + latest = max(runs, key=lambda r: r["id"], default=None) + if latest is None or latest["status"] != "completed" or latest["conclusion"] != "success": + state = latest and (latest["conclusion"] or latest["status"]) + found += bad(f"PR #{pr} head {head[:12]}: latest {CHECK_NAME} result is {state or 'missing'}, not success") + return found + + +def main(argv=None) -> int: + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + sub = ap.add_subparsers(dest="cmd", required=True) + pr = sub.add_parser("pr") + pr.add_argument("--root", type=Path, default=Path(".")) + pr.add_argument("--repo", required=True) + pr.add_argument("--pr", type=int, required=True) + pr.add_argument("--base", required=True) + pr.add_argument("--head", required=True) + pr.add_argument("--private", action="store_true") + pr.add_argument("--default-branch", default="main") + mg = sub.add_parser("merge-group") + mg.add_argument("--repo", required=True) + mg.add_argument("--group-ref", required=True) + args = ap.parse_args(argv) + if args.cmd == "pr": + found = check_pr(args.root, args.repo, args.pr, args.base, args.head, args.private, args.default_branch) + else: + found = check_merge_group(args.repo, args.group_ref) + for v in found: + print(f"{args.repo} {v.workflow} {v.rule} {v.reason}") + return 1 if found else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.github/workflows/ci-policy.yml b/.github/workflows/ci-policy.yml new file mode 100644 index 000000000..526e7de5d --- /dev/null +++ b/.github/workflows/ci-policy.yml @@ -0,0 +1,77 @@ +# ci-policy: class=gate +# ci-policy caller (D-6, eng review D10 = A and D14 = A). Same content in every enrolled repo; scripts/ci-policy/sync.py +# keeps the copies current. See standards/general/ci.md. +# +# SECURITY — same boundary as mechanical-tier.yml: `pull_request_target` and `pull_request_review` run PR checks with +# the BASE revision's checker. The job checks out the base SHA and only FETCHES head objects; gate.py reads the head's +# `.github` tree as data. Do not add a head checkout, a head `run:` or a secret to this workflow. +# `merge_group` checks out the default branch and copies every queued PR's `ci-policy` result (gate.py merge-group); gate.py fetches the group and head commits it must compare. +# Not a required check until D-9 promotion; a push trigger is never needed (D-4). + +name: ci-policy + +on: + pull_request_target: + types: [opened, synchronize, reopened, ready_for_review] + pull_request_review: + types: [submitted, dismissed] + merge_group: + +permissions: + contents: read + pull-requests: read + checks: read + +# One group per event type: a review run must not cancel the run for a newer push. +concurrency: + group: ci-policy-${{ github.event_name }}-${{ github.event.pull_request.number || github.event.merge_group.head_sha }} + cancel-in-progress: true + +jobs: + ci-policy: + name: ci-policy + runs-on: ${{ github.repository_owner == 'cheese-work' && fromJSON('["self-hosted","Linux","X64","cheese-x99-gate"]') || fromJSON('["ubuntu-latest"]') }} + timeout-minutes: 10 + env: + GH_TOKEN: ${{ github.token }} + PR_NUMBER: ${{ github.event.pull_request.number }} + BASE_SHA: ${{ github.event.pull_request.base.sha }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + GROUP_REF: ${{ github.event.merge_group.head_ref }} + DEFAULT_BRANCH: ${{ github.event.repository.default_branch }} + PRIVATE: ${{ github.event.repository.private && '--private' || '' }} + steps: + - name: Discard a reused workspace + run: | + find "$GITHUB_WORKSPACE" -mindepth 1 -delete + # A plain git checkout of the BASE sha (or the default branch for a queue run): no `actions/checkout` and no head + # ref, so the pull_request_target checkout rule has nothing to match and the base-only boundary stays visible. + - name: Check out the trusted base + run: | + auth="$(printf 'x-access-token:%s' "$GH_TOKEN" | base64 -w0)" + git init --quiet . + git remote add origin "https://github.com/${GITHUB_REPOSITORY}.git" + git -c "http.https://github.com/.extraheader=AUTHORIZATION: basic $auth" \ + fetch --quiet --no-tags origin "+refs/heads/*:refs/remotes/origin/*" + git checkout --quiet --detach "${BASE_SHA:-refs/remotes/origin/${DEFAULT_BRANCH}}" + - name: Fetch the head objects without checking them out + if: github.event_name != 'merge_group' + run: | + auth="$(printf 'x-access-token:%s' "$GH_TOKEN" | base64 -w0)" + git -c "http.https://github.com/.extraheader=AUTHORIZATION: basic $auth" \ + fetch --no-tags origin "+refs/pull/${PR_NUMBER}/head:refs/remotes/pull/head" + test "$(git rev-parse refs/remotes/pull/head)" = "$HEAD_SHA" + # Some X99 runners ship no PyYAML (CHE-2397); --target avoids PEP 668. + - name: Install PyYAML + run: | + python3 -m pip install --quiet --target "$RUNNER_TEMP/pydeps" pyyaml + echo "PYTHONPATH=$RUNNER_TEMP/pydeps" >> "$GITHUB_ENV" + - name: Check the PR against the base policy + if: github.event_name != 'merge_group' + run: | + python3 .github/ci-policy/gate.py pr --repo "$GITHUB_REPOSITORY" --pr "$PR_NUMBER" \ + --base "$BASE_SHA" --head "$HEAD_SHA" --default-branch "$DEFAULT_BRANCH" $PRIVATE + - name: Copy the queued PR's result + if: github.event_name == 'merge_group' + run: | + python3 .github/ci-policy/gate.py merge-group --repo "$GITHUB_REPOSITORY" --group-ref "$GROUP_REF" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0854dca5b..11e6d5670 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,3 +1,4 @@ +# ci-policy: class=pr-validation name: CI on: diff --git a/.github/workflows/host-agent.yml b/.github/workflows/host-agent.yml index 911828ced..ef5780f28 100644 --- a/.github/workflows/host-agent.yml +++ b/.github/workflows/host-agent.yml @@ -1,8 +1,10 @@ +# ci-policy: class=pr-validation name: Host agent core on: workflow_dispatch: push: + branches: [main] paths: - 'host-agent/**' - 'artemis/runtime/adb_gateway.py' diff --git a/.github/workflows/preview-controller.yml b/.github/workflows/preview-controller.yml index 016f2b043..61b113f27 100644 --- a/.github/workflows/preview-controller.yml +++ b/.github/workflows/preview-controller.yml @@ -1,3 +1,4 @@ +# ci-policy: class=manual name: Preview controller (inactive) on: diff --git a/.github/workflows/whats-new.yml b/.github/workflows/whats-new.yml index f495ab6c5..8b3eb2e8b 100644 --- a/.github/workflows/whats-new.yml +++ b/.github/workflows/whats-new.yml @@ -1,3 +1,4 @@ +# ci-policy: class=pr-validation name: What's New # Separate from CI so adding or removing the no-whats-new label re-runs only @@ -9,6 +10,10 @@ on: permissions: contents: read +concurrency: + group: whats-new-${{ github.ref }} + cancel-in-progress: true + jobs: entry: name: What's New entry diff --git a/pyproject.toml b/pyproject.toml index 48355f6ea..2af1adb05 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -137,6 +137,9 @@ exclude = [ # CHE-564: unmodified upstream directory fails the fork's UP ruleset; # excluded to keep the fork's diff against upstream minimal. "playground", + # CHE-3275: vendored ci-policy checker, kept byte-identical to + # cheese-work/multica-dotfiles (S3a, de75e73); not formatted here. + ".github/ci-policy", ] # Same as Black. diff --git a/tests/unit/test_workflow_runner_policy.py b/tests/unit/test_workflow_runner_policy.py index be6f7f111..ed94502fa 100644 --- a/tests/unit/test_workflow_runner_policy.py +++ b/tests/unit/test_workflow_runner_policy.py @@ -43,7 +43,8 @@ def _x99_labels(runs_on): def test_every_active_job_runs_on_the_x99_pool(): for file, name, _workflow, job in _jobs(): labels = _x99_labels(job["runs-on"]) - assert labels[0] == "self-hosted" and "cheese-x99" in labels, (file, name, labels) + on_pool = "cheese-x99" in labels or "cheese-x99-gate" in labels + assert labels[0] == "self-hosted" and on_pool, (file, name, labels) def test_only_the_frontend_job_requires_the_browser_runner():