Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Harden the workflow-trigger lint: scan .yaml, and host it outside the workflow it audits (#8545)
Daniel Han90a6a236b5ae
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERSindex a9694036cf2..1f7007d4ade 100644--- a/.github/CODEOWNERS+++ b/.github/CODEOWNERS@@ -54,6 +54,12 @@/tests/ @danielhanchen/scripts/ @danielhanchen+# CI definitions. A workflow change can hand a fork PR the base repo's+# secrets, or skip the very lint that would have caught it, and no CI gate+# can stop a PR that disables its own gate. Owner review is the control.+/.github/workflows/ @danielhanchen+/.github/CODEOWNERS @danielhanchen+# Snapshot data for the notebook linter / Colab oracle. Drift in these# files changes the pin floor for every Unsloth notebook, so refreshes# must be reviewed by the notebook owners directly. CODEOWNERS laterdiff --git a/.github/workflows/security-audit.yml b/.github/workflows/security-audit.ymlindex 3b1ca9d408d..d24095114ad 100644--- a/.github/workflows/security-audit.yml+++ b/.github/workflows/security-audit.yml@@ -26,8 +26,6 @@# does not block the supply-chain pattern scan# (or vice versa).# - npm-scan-packages: npm tarball content scan, no npm install.-# - workflow-trigger-lint:-# bans pull_request_target + shared cache keys.# - tests-security: pytest tests/security regression suite.# - npm-provenance-and-install-scripts:# npm audit signatures + new-postinstall gate.@@ -1045,52 +1043,6 @@ jobs:path: logs-scan-npm.txtretention-days: 30- # ─────────────────────────────────────────────────────────────────────- # Workflow-trigger lint. Refuses two patterns that together powered the- # TanStack GHSA-g7cv-rxg3-hmpx supply-chain compromise:- #- # 1. `pull_request_target` -- runs a fork's workflow YAML against- # the base repository's secrets. There is no safe use of this- # trigger for a public open-source project.- #- # 2. Shared cache keys between PR-triggered workflows and the- # publish workflow. A fork PR can poison the cache; the publish- # workflow then restores the poisoned cache on next run.- #- # Cheap pure-Python lint, runs in seconds. Fail-closed.- # ─────────────────────────────────────────────────────────────────────- workflow-trigger-lint:- name: workflow-trigger lint (pull_request_target / cache-poisoning)- runs-on: ubuntu-latest- timeout-minutes: 5- steps:- - name: Harden runner (egress block)- uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0- with:- egress-policy: block- disable-sudo: true- allowed-endpoints: >- api.github.com:443- github.com:443- codeload.github.com:443- objects.githubusercontent.com:443- pypi.org:443- files.pythonhosted.org:443-- - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1- with:- persist-credentials: false-- - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0- with:- python-version: '3.12'-- - name: Install PyYAML- run: pip install pyyaml-- - name: Lint workflow triggers + cache keys- run: python3 scripts/lint_workflow_triggers.py-# ─────────────────────────────────────────────────────────────────────# Regression tests: pin scanner IOC tables and pre-install fixtures.# Hard gate (no continue-on-error) so future drift in the IOC tablesdiff --git a/.github/workflows/workflow-trigger-lint.yml b/.github/workflows/workflow-trigger-lint.ymlnew file mode 100644index 00000000000..674fab23f10--- /dev/null+++ b/.github/workflows/workflow-trigger-lint.yml@@ -0,0 +1,70 @@+# Workflow-trigger lint. Refuses two patterns that together powered the+# TanStack GHSA-g7cv-rxg3-hmpx supply-chain compromise:+#+# 1. `pull_request_target` -- runs a fork's workflow YAML against the+# base repository's secrets. There is no safe use of this trigger+# for a public open-source project.+#+# 2. Shared cache keys between PR-triggered workflows and the publish+# workflow. A fork PR can poison the cache; the publish workflow+# then restores the poisoned cache on next run.+#+# This lives in its own workflow, not inside security-audit.yml, for one+# reason: `on.pull_request` here carries NO `paths` / `paths-ignore`+# filter, and must never gain one. A gate that only runs for some PRs+# does not gate workflow changes, which is exactly what it exists to+# review. security-audit.yml is a heavy nightly audit whose filters are+# tuned for cost; coupling this lint to them once already opened that+# hole. scripts/lint_workflow_triggers.py enforces the invariant on+# whichever workflow runs it, so this file cannot quietly re-acquire a+# filter.+#+# Cheap pure-Python lint, runs in seconds. Fail-closed.++name: Workflow trigger lint++on:+ pull_request:+ push:+ branches: [main]+ workflow_dispatch:++concurrency:+ group: ${{ github.workflow }}-${{ github.ref }}-${{ github.event_name }}+ cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}++permissions:+ contents: read++jobs:+ workflow-trigger-lint:+ name: workflow-trigger lint (pull_request_target / cache-poisoning)+ runs-on: ubuntu-latest+ timeout-minutes: 5+ steps:+ - name: Harden runner (egress block)+ uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0+ with:+ egress-policy: block+ disable-sudo: true+ allowed-endpoints: >+ api.github.com:443+ github.com:443+ codeload.github.com:443+ objects.githubusercontent.com:443+ pypi.org:443+ files.pythonhosted.org:443++ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false++ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0+ with:+ python-version: '3.12'++ - name: Install PyYAML+ run: pip install pyyaml++ - name: Lint workflow triggers + cache keys+ run: python3 scripts/lint_workflow_triggers.pydiff --git a/scripts/lint_workflow_triggers.py b/scripts/lint_workflow_triggers.pyindex 8f22fcaf455..4875671c259 100644--- a/scripts/lint_workflow_triggers.py+++ b/scripts/lint_workflow_triggers.py@@ -23,8 +23,9 @@ from __future__ import annotationsimport argparseimport re+import shleximport sys-from pathlib import Path+from pathlib import Path, PurePosixPathtry:import yaml@@ -37,7 +38,15 @@ DEFAULT_WORKFLOWS_DIR = REPO_ROOT / ".github" / "workflows"BANNED_TRIGGERS: tuple[str, ...] = ("pull_request_target",)RESTRICTED_TRIGGERS: tuple[str, ...] = ("workflow_run",)-PUBLISH_WORKFLOW_NAMES: tuple[str, ...] = ("release-desktop.yml",)+# Stem, not filename: `.yaml` is scanned too, and a renamed publisher must+# still be classified as one.+PUBLISH_WORKFLOW_STEMS: tuple[str, ...] = ("release-desktop",)++# A workflow running this script is a "host". `pull_request` resolves the+# workflow file from the PR merge ref, so any narrowing a PR adds to its host+# applies to that same PR, and the gate misses the change it exists to review.+# Hence: a bare `pull_request:`, and a step that can fail.+LINT_SCRIPT_NAME = "lint_workflow_triggers.py"def _normalise_on(on_field):@@ -66,28 +75,273 @@ def _extract_cache_keys(path: Path) -> list[str]:return keys-def _trigger_set(yaml_doc) -> set[str]:- on = yaml_doc.get(True)- if on is None:+def _on_field(yaml_doc):+ # PyYAML resolves a bare `on:` key to the boolean True.+ on = yaml_doc.get(True) if isinstance(yaml_doc, dict) else None+ if on is None and isinstance(yaml_doc, dict):on = yaml_doc.get("on")- return _normalise_on(on)+ return on+++def _trigger_set(yaml_doc) -> set[str]:+ return _normalise_on(_on_field(yaml_doc))+++# A host runs this repo's script as a plain command with no arguments. Each+# clause below is a way that looked satisfied while nothing was enforced: a+# decoy path, a fake interpreter, a `|| true` (the default `run:` shell is+# `bash -e`, no pipefail), or an argument that makes it exit early.+_PYTHON_BASENAME = re.compile(r"python(3(\.\d+)?)?")+# Allowlist, not denylist: too many flags skip the file or mask its status+# (-c, -m, --version, and -i, which exits 0 from the REPL even after+# sys.exit(1)). Anything unrecognised fails closed.+_SAFE_OPTS = ("-u", "-E", "-s", "-S", "-B", "-O", "-OO", "-q")+LINT_SCRIPT_PATH = f"scripts/{LINT_SCRIPT_NAME}"+# Safe, but they consume the next token, so the script path is not mistaken+# for their value.+_OPTS_WITH_VALUE = ("-X", "-W", "--check-hash-based-pycs")+_SHELL_OPERATORS = ("|", "&", ";", ">", "<", "`", "$(")+++def _is_trusted_python(token: str) -> bool:+ """A bare `python3`, or an absolute system path to one.++ A relative `./python3` would resolve inside the checkout, where a PR can+ add an executable of that name.+ """+ if any(op in token for op in _SHELL_OPERATORS):+ return False # a substitution runs before the path is used+ path = PurePosixPath(token)+ if not _PYTHON_BASENAME.fullmatch(path.name):+ return False+ return token == path.name or token.startswith(("/usr/", "/bin/", "/opt/"))+++def _classify_lint_line(line: str) -> tuple[bool, str | None]:+ """(is an enforcing invocation, problem) for one line naming the script."""+ try:+ tokens = shlex.split(line.strip())+ except ValueError:+ return False, None+ if not tokens or not _is_trusted_python(tokens[0]):+ return False, None # `echo <script>`, a decoy interpreter, or not python++ args, i = tokens[1:], 0+ while i < len(args) and args[i].startswith("-"):+ if args[i] in _OPTS_WITH_VALUE:+ value = args[i + 1] if i + 1 < len(args) else ""+ if any(op in value for op in _SHELL_OPERATORS):+ return False, None # a substitution runs before python+ i += 2+ elif args[i] in _SAFE_OPTS:+ i += 1+ else:+ return False, None++ rest = args[i:]+ # Exactly the repo-relative path. A suffix match would accept a decoy at+ # /tmp/scripts/lint_workflow_triggers.py.+ if not rest or rest[0] not in (LINT_SCRIPT_PATH, f"./{LINT_SCRIPT_PATH}"):+ return False, None+ if len(rest) == 1:+ return True, None++ trailing = " ".join(rest[1:])+ if any(op in tok for tok in rest[1:] for op in _SHELL_OPERATORS):+ return False, (+ f"its lint command is chained, piped or backgrounded ({trailing}), "+ "so the step's exit status need not be the lint's"+ )+ return False, (+ f"its lint command passes {trailing}, so it does not gate the live "+ "workflows with its own checks on"+ )+++def _lint_step_report(run: str) -> tuple[bool, list[str]]:+ """(an enforcing invocation is present, problems with lint-ish commands).++ The step body must be the lint command and nothing else. Judging lines in+ isolation cannot tell a call from a definition, so an invocation parked in+ an uncalled function or a here-document would read as enforcing while+ executing nothing. Requiring a single command sidesteps shell parsing.+ """+ lines = [line for line in run.splitlines() if line.strip() and not line.strip().startswith("#")]+ mentions = [line for line in lines if LINT_SCRIPT_NAME in line]+ if not mentions:+ return False, []++ problems = [p for _, p in map(_classify_lint_line, mentions) if p]+ enforcing = any(ok for ok, _ in map(_classify_lint_line, mentions))+ if enforcing and len(lines) > 1:+ return False, problems + [+ "its lint step runs other shell besides the lint command, so the "+ "lint need not execute (a function body or here-document is not a "+ "call)"+ ]+ return enforcing, problems+++# A `shell:` template can wrap the command, e.g. `bash -c '"{0}" || true'`.+SAFE_SHELLS: tuple[str, ...] = ("bash", "sh")++# Redirect execution without changing the command: bash sources BASH_ENV+# before the step script, and PATH picks the interpreter.+UNSAFE_ENV_KEYS: tuple[str, ...] = (+ "BASH_ENV",+ "ENV",+ "PATH",+ # `sitecustomize.py` on PYTHONPATH is imported before the script runs.+ "PYTHONPATH",+ "PYTHONHOME",+ "PYTHONSTARTUP",+)+++def _effective_run_setting(yaml_doc, job: dict, step: dict, key: str) -> str | None:+ """A step's `run` setting, falling back to job then workflow defaults."""+ if step.get(key):+ return str(step[key])+ for scope in (job, yaml_doc):+ defaults = scope.get("defaults") if isinstance(scope, dict) else None+ run = defaults.get("run") if isinstance(defaults, dict) else None+ if isinstance(run, dict) and run.get(key):+ return str(run[key])+ return None+++def _effective_env(yaml_doc, job: dict, step: dict) -> dict:+ """Workflow, job and step `env`, merged in precedence order."""+ merged = {}+ for scope in (yaml_doc, job, step):+ env = scope.get("env") if isinstance(scope, dict) else None+ if isinstance(env, dict):+ merged.update(env)+ return merged+++def _pull_request_config_problem(yaml_doc) -> str | None:+ """`pull_request:` must be bare or a mapping; GitHub rejects anything else."""+ on = _on_field(yaml_doc)+ if not isinstance(on, dict) or "pull_request" not in on:+ return None+ pr = on["pull_request"]+ if pr is None or isinstance(pr, dict):+ return None+ return (+ f"its 'pull_request' value is {pr!r}, which is not a valid event "+ "configuration, so GitHub will not load the workflow at all"+ )+++def _lint_steps(yaml_doc) -> list[tuple[dict, dict, bool, list[str]]]:+ """(job, step, enforcing, problems) for every step that runs the lint.++ Reads the parsed steps rather than the raw text: a commented-out+ `# - run: python3 scripts/lint_workflow_triggers.py` executes nothing, and+ counting it as a host would let a deleted gate look wired.+ """+ jobs = yaml_doc.get("jobs") if isinstance(yaml_doc, dict) else None+ if not isinstance(jobs, dict):+ return []+ found = []+ for job in jobs.values():+ steps = job.get("steps") if isinstance(job, dict) else None+ if not isinstance(steps, list):+ continue+ for step in steps:+ if not isinstance(step, dict):+ continue+ enforcing, problems = _lint_step_report(str(step.get("run") or ""))+ if not (enforcing or problems):+ continue+ if job.get("container") is not None:+ enforcing = False+ problems.append(+ "its lint job runs in a 'container:', a PR-selected image "+ "that controls the shell and environment"+ )+ shell = _effective_run_setting(yaml_doc, job, step, "shell")+ if shell is not None and shell not in SAFE_SHELLS:+ enforcing = False+ problems.append(+ f"its lint step runs under shell {shell!r}, which can wrap "+ "the command and drop its exit status"+ )+ unsafe_env = sorted(+ k for k in _effective_env(yaml_doc, job, step) if k in UNSAFE_ENV_KEYS+ )+ if unsafe_env:+ enforcing = False+ problems.append(+ f"its lint step sets {' + '.join(unsafe_env)}, which can "+ "redirect the step before the lint runs"+ )+ workdir = _effective_run_setting(yaml_doc, job, step, "working-directory")+ if workdir is not None:+ enforcing = False+ problems.append(+ f"its lint step runs in working-directory {workdir!r}, so "+ "the command resolves to a different file than this "+ "repository's script"+ )+ found.append((job, step, enforcing, problems))+ return found+++def _pull_request_restrictions(yaml_doc) -> list[str]:+ """Keys narrowing the `pull_request` trigger. A gate wants none of them."""+ on = _on_field(yaml_doc)+ pr = on.get("pull_request") if isinstance(on, dict) else None+ return sorted(pr) if isinstance(pr, dict) else []+++def _is_truthy(value) -> bool:+ """YAML truthiness, treating any `${{ ... }}` expression as possibly true."""+ if isinstance(value, bool):+ return value+ return isinstance(value, str) and value.strip().lower() not in ("", "false")def main() -> int:- parser = argparse.ArgumentParser(description = __doc__)+ # No abbreviations: `--workflows-d` must not silently mean+ # `--workflows-dir`, or a host could smuggle it past review.+ parser = argparse.ArgumentParser(description = __doc__, allow_abbrev = False)parser.add_argument("--workflows-dir",type = Path,default = DEFAULT_WORKFLOWS_DIR,help = "Override the workflows directory (used by tests).",)+ parser.add_argument(+ "--require-host",+ action = "store_true",+ default = None,+ help = "Require a workflow that runs this script on unfiltered "+ "`pull_request`. Defaults on for the live tree, off for a "+ "fixture directory.",+ )+ parser.add_argument(+ "--no-require-host",+ dest = "require_host",+ action = "store_false",+ help = "Skip the host-wiring check.",+ )args = parser.parse_args()workflows_dir = args.workflows_dir+ require_host = args.require_host+ if require_host is None:+ require_host = workflows_dir.resolve() == DEFAULT_WORKFLOWS_DIR.resolve()+findings: list[str] = []- workflows = sorted(workflows_dir.glob("*.yml"))+ # GitHub Actions loads BOTH `.yml` and `.yaml` from .github/workflows/, so+ # scanning only `*.yml` leaves a rename-away bypass: `evil.yaml` with+ # `pull_request_target` would run for real and lint clean.+ workflows = sorted(list(workflows_dir.glob("*.yml")) + list(workflows_dir.glob("*.yaml")))pr_triggered: list[tuple[Path, list[str]]] = []publish_triggered: list[tuple[Path, list[str]]] = []+ unfiltered_hosts: list[Path] = []for path in workflows:doc = _load_workflow(path)@@ -112,14 +366,66 @@ def main() -> int:"comment somewhere in the file, with a justification.")+ lint_steps = _lint_steps(doc)+ if lint_steps:+ problems = []+ restrictions = _pull_request_restrictions(doc)+ if restrictions:+ problems.append(+ f"its 'pull_request' trigger is narrowed by "+ f"{' + '.join(restrictions)}, so a PR adding that skips "+ "this workflow for its own PR"+ )+ config_problem = _pull_request_config_problem(doc)+ if config_problem:+ problems.append(config_problem)+ if any(+ _is_truthy(job.get("continue-on-error"))+ or _is_truthy(step.get("continue-on-error"))+ for job, step, _, _ in lint_steps+ ):+ problems.append(+ "its lint step is continue-on-error, so findings cannot fail the run"+ )+ if any(+ job.get("if") is not None or step.get("if") is not None+ for job, step, _, _ in lint_steps+ ):+ problems.append(+ "its lint step is gated by an 'if:' condition, so the gate "+ "can be skipped while the run still succeeds"+ )+ if any(job.get("needs") is not None for job, _, _, _ in lint_steps):+ problems.append(+ "its lint job declares 'needs:', so a skipped prerequisite "+ "skips the gate without failing the run"+ )+ for _, _, _, step_problems in lint_steps:+ problems.extend(step_problems)+ if problems:+ findings.append(+ f"{path.name}: runs {LINT_SCRIPT_NAME} but "+ + ", and ".join(problems)+ + ". The gate must run, and be able to fail, on every PR."+ )+ elif "pull_request" in triggers and any(enforcing for _, _, enforcing, _ in lint_steps):+ unfiltered_hosts.append(path)+if "pull_request" in triggers:pr_triggered.append((path, _extract_cache_keys(path)))is_dispatch_only = "workflow_dispatch" in triggers and not ("push" in triggers or "pull_request" in triggers)- if path.name in PUBLISH_WORKFLOW_NAMES or is_dispatch_only:+ if path.stem in PUBLISH_WORKFLOW_STEMS or is_dispatch_only:publish_triggered.append((path, _extract_cache_keys(path)))+ if require_host and not unfiltered_hosts:+ findings.append(+ f"no workflow runs {LINT_SCRIPT_NAME} on an unfiltered "+ "'pull_request' trigger, so this gate does not cover every PR. "+ "Restore the workflow-trigger-lint workflow."+ )+pr_keys = {key for _, keys in pr_triggered for key in keys}for pub_path, pub_keys in publish_triggered:for k in pub_keys:diff --git a/tests/security/test_lint_workflow_triggers.py b/tests/security/test_lint_workflow_triggers.pyindex e4ee3fd28f5..d1c8257c2b1 100644--- a/tests/security/test_lint_workflow_triggers.py+++ b/tests/security/test_lint_workflow_triggers.py@@ -2,6 +2,7 @@from __future__ import annotations+import reimport shutilimport subprocessimport sys@@ -13,12 +14,11 @@ REPO_ROOT = Path(__file__).resolve().parents[2]SCRIPT = REPO_ROOT / "scripts" / "lint_workflow_triggers.py"-def _run(workflows_dir: Path) -> subprocess.CompletedProcess:- return subprocess.run(- [sys.executable, str(SCRIPT), "--workflows-dir", str(workflows_dir)],- capture_output = True,- text = True,- )+def _run(workflows_dir: Path, require_host: bool = False) -> subprocess.CompletedProcess:+ cmd = [sys.executable, str(SCRIPT), "--workflows-dir", str(workflows_dir)]+ if require_host:+ cmd.append("--require-host")+ return subprocess.run(cmd, capture_output = True, text = True)def test_lint_passes_on_current_workflows():@@ -51,6 +51,819 @@ def test_lint_rejects_pull_request_target(tmp_path):assert "GHSA-g7cv-rxg3-hmpx" in proc.stderr+def test_lint_rejects_pull_request_target_in_yaml_extension(tmp_path):+ """GitHub Actions also loads `.yaml`; the lint must not stop at `.yml`."""+ wf = tmp_path / "wf"+ wf.mkdir()+ (wf / "bad.yaml").write_text(+ "name: bad\n"+ "on:\n"+ " pull_request_target:\n"+ " branches: [main]\n"+ "jobs:\n"+ " build:\n"+ " runs-on: ubuntu-latest\n"+ " steps:\n"+ " - run: echo evil\n"+ )+ proc = _run(wf)+ assert proc.returncode == 1+ assert "bad.yaml" in proc.stderr+ assert "BANNED trigger 'pull_request_target'" in proc.stderr+++def _host_workflow(restriction: str = "", step_extra: str = "") -> str:+ """A workflow that runs the lint, optionally narrowed or non-blocking."""+ return (+ "name: host\n"+ "on:\n"+ " pull_request:\n" + restriction + "jobs:\n"+ " lint:\n"+ " runs-on: ubuntu-latest\n"+ " steps:\n"+ " - run: python3 scripts/lint_workflow_triggers.py\n" + step_extra+ )+++ "key, value",+ [+ ("paths", " - 'studio/**'\n"),+ ("paths-ignore", " - 'studio/**'\n"),+ ("branches", " - some-other-branch\n"),+ ("branches-ignore", " - main\n"),+ ("types", " - closed\n"),+ ],+)+def test_lint_rejects_a_narrowed_host(tmp_path, key, value):+ """A host narrowed any way is skipped by the PR that narrows it.++ The merge ref carries the restriction, so it applies to that PR. A branch+ or event-type filter skips ordinary PRs as well as `paths` does.+ """+ wf = tmp_path / "wf"+ wf.mkdir()+ (wf / "host.yml").write_text(_host_workflow(f" {key}:\n{value}"))+ proc = _run(wf, require_host = True)+ assert proc.returncode == 1+ assert key in proc.stderr+ assert "host.yml" in proc.stderr++[email protected]("where", ["step", "job"])+ "key, value, expected",+ [+ ("continue-on-error", "true", "continue-on-error"),+ ("if", "${{ false }}", "'if:' condition"),+ ],+)+def test_lint_rejects_a_host_that_cannot_fail(tmp_path, where, key, value, expected):+ """A host that cannot fail, or is skipped, is not a gate.++ `continue-on-error` makes findings advisory; a false `if:` skips the step.+ """+ wf = tmp_path / "wf"+ wf.mkdir()+ if where == "step":+ body = _host_workflow(step_extra = f" {key}: {value}\n")+ else:+ body = _host_workflow().replace(+ " runs-on: ubuntu-latest\n",+ f" runs-on: ubuntu-latest\n {key}: {value}\n",+ )+ (wf / "host.yml").write_text(body)+ proc = _run(wf, require_host = True)+ assert proc.returncode == 1+ assert expected in proc.stderr+++ "command, expected",+ [+ ("python3 scripts/lint_workflow_triggers.py || true", "chained"),+ ("python3 scripts/lint_workflow_triggers.py ; true", "chained"),+ ("python3 scripts/lint_workflow_triggers.py | tee lint.log", "chained"),+ ("python3 scripts/lint_workflow_triggers.py &", "chained"),+ (+ "set +e\n python3 scripts/lint_workflow_triggers.py",+ "other shell besides the lint command",+ ),+ (+ "python3 scripts/lint_workflow_triggers.py --workflows-dir /tmp/empty",+ "--workflows-dir",+ ),+ ("python3 scripts/lint_workflow_triggers.py --no-require-host", "--no-require-host"),+ ("python3 scripts/lint_workflow_triggers.py --workflows-d /tmp/empty", "--workflows-d"),+ ("python3 scripts/lint_workflow_triggers.py --help", "--help"),+ ],+ ids = [+ "or-true",+ "semi-true",+ "pipe-tee",+ "background",+ "extra-shell",+ "elsewhere-dir",+ "self-check-off",+ "abbreviated-flag",+ "help",+ ],+)+def test_lint_rejects_a_defanged_invocation(tmp_path, command, expected):+ """Running the script is not enough; it has to be able to gate.++ A pipeline or `|| true` detaches the step's status from the lint's, and an+ argument can redirect it, disable its wiring check, or exit early.+ """+ wf = tmp_path / "wf"+ wf.mkdir()+ (wf / "host.yml").write_text(+ _host_workflow().replace(+ "run: python3 scripts/lint_workflow_triggers.py",+ f"run: |\n {command}",+ )+ )+ proc = _run(wf, require_host = True)+ assert proc.returncode == 1+ assert expected in proc.stderr+++ "command",+ [+ "python3 -c 'pass' scripts/lint_workflow_triggers.py",+ "python3 -m json.tool scripts/lint_workflow_triggers.py",+ "echo scripts/lint_workflow_triggers.py",+ # A decoy with the right basename but not this repository's script.+ "python3 /tmp/lint_workflow_triggers.py",+ ],+ ids = ["dash-c", "dash-m", "echo", "decoy-path"],+)+def test_lint_does_not_count_a_non_running_command_as_a_host(tmp_path, command):+ """None of these execute the repository's lint, so none is a host."""+ wf = tmp_path / "wf"+ wf.mkdir()+ (wf / "host.yml").write_text(+ _host_workflow().replace(+ "run: python3 scripts/lint_workflow_triggers.py", f"run: {command}"+ )+ )+ proc = _run(wf, require_host = True)+ assert proc.returncode == 1+ assert "does not cover every PR" in proc.stderr+++ "body",+ [+ # A decoy under any prefix, not just a bare /tmp path.+ "python3 /tmp/scripts/lint_workflow_triggers.py",+ # Defining a function is not calling it.+ "never_called() {\n python3 scripts/lint_workflow_triggers.py\n }",+ # A here-document is data, not a command.+ "cat <<'EOF'\n python3 scripts/lint_workflow_triggers.py\n EOF",+ ],+ ids = ["prefixed-decoy", "uncalled-function", "heredoc"],+)+def test_lint_rejects_an_unexecuted_lint_command(tmp_path, body):+ """Text that looks like the invocation but never runs it is not a host."""+ wf = tmp_path / "wf"+ wf.mkdir()+ (wf / "host.yml").write_text(+ _host_workflow().replace(+ "run: python3 scripts/lint_workflow_triggers.py",+ f"run: |\n {body}",+ )+ )+ proc = _run(wf, require_host = True)+ assert proc.returncode == 1+ assert "does not cover every PR" in proc.stderr+++ "where",+ ["step", "job-defaults", "workflow-defaults"],+)+def test_lint_rejects_a_custom_shell(tmp_path, where):+ """A shell template can wrap the command and drop its exit status."""+ evil = "bash -c '\"{0}\" || true'"+ body = _host_workflow()+ if where == "step":+ body = body.replace(+ " - run: python3 scripts/lint_workflow_triggers.py\n",+ f" - run: python3 scripts/lint_workflow_triggers.py\n shell: {evil}\n",+ )+ elif where == "job-defaults":+ body = body.replace(+ " runs-on: ubuntu-latest\n",+ f" runs-on: ubuntu-latest\n defaults:\n run:\n shell: {evil}\n",+ )+ else:+ body = body.replace("jobs:\n", f"defaults:\n run:\n shell: {evil}\njobs:\n")+ (wf := tmp_path / "wf").mkdir()+ (wf / "host.yml").write_text(body)+ proc = _run(wf, require_host = True)+ assert proc.returncode == 1+ assert "shell" in proc.stderr+++def test_lint_accepts_an_explicit_plain_shell(tmp_path):+ """`shell: bash` is ordinary and must keep working."""+ (wf := tmp_path / "wf").mkdir()+ (wf / "host.yml").write_text(+ _host_workflow().replace(+ " - run: python3 scripts/lint_workflow_triggers.py\n",+ " - run: python3 scripts/lint_workflow_triggers.py\n shell: bash\n",+ )+ )+ proc = _run(wf, require_host = True)+ assert proc.returncode == 0, proc.stderr+++ "command",+ [+ # A fake interpreter that merely contains "python" in its name.+ "/tmp/fakepython scripts/lint_workflow_triggers.py",+ # Flags that make python print and exit before running the file.+ "python3 --version scripts/lint_workflow_triggers.py",+ "python3 -V scripts/lint_workflow_triggers.py",+ "python3 --help scripts/lint_workflow_triggers.py",+ ],+ ids = ["fake-interpreter", "version-long", "version-short", "help-before-path"],+)+def test_lint_rejects_a_non_running_interpreter(tmp_path, command):+ """The interpreter must be a python that actually executes the file."""+ (wf := tmp_path / "wf").mkdir()+ (wf / "host.yml").write_text(+ _host_workflow().replace(+ "run: python3 scripts/lint_workflow_triggers.py", f"run: {command}"+ )+ )+ proc = _run(wf, require_host = True)+ assert proc.returncode == 1+ assert "does not cover every PR" in proc.stderr++[email protected]("where", ["step", "job-defaults", "workflow-defaults"])+def test_lint_rejects_a_changed_working_directory(tmp_path, where):+ """`working-directory` resolves the command to a different file."""+ body = _host_workflow()+ if where == "step":+ body = body.replace(+ " - run: python3 scripts/lint_workflow_triggers.py\n",+ " - run: python3 scripts/lint_workflow_triggers.py\n"+ " working-directory: /tmp\n",+ )+ elif where == "job-defaults":+ body = body.replace(+ " runs-on: ubuntu-latest\n",+ " runs-on: ubuntu-latest\n"+ " defaults:\n run:\n working-directory: /tmp\n",+ )+ else:+ body = body.replace("jobs:\n", "defaults:\n run:\n working-directory: /tmp\njobs:\n")+ (wf := tmp_path / "wf").mkdir()+ (wf / "host.yml").write_text(body)+ proc = _run(wf, require_host = True)+ assert proc.returncode == 1+ assert "working-directory" in proc.stderr++[email protected]("suffix", [".yml", ".yaml"])+def test_publish_cache_key_collision_found_under_both_suffixes(tmp_path, suffix):+ """Scanning `.yaml` is pointless if publisher classification misses it."""+ (wf := tmp_path / "wf").mkdir()+ (wf / f"release-desktop{suffix}").write_text(+ "name: release\n"+ "on:\n"+ " push:\n"+ " branches: [main]\n"+ " workflow_dispatch:\n"+ "jobs:\n"+ " build:\n"+ " runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: actions/cache@v4\n"+ " with:\n"+ " key: shared-cache-key\n"+ )+ (wf / "pr.yml").write_text(+ "name: pr\n"+ "on:\n"+ " pull_request:\n"+ "jobs:\n"+ " build:\n"+ " runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: actions/cache@v4\n"+ " with:\n"+ " key: shared-cache-key\n"+ )+ proc = _run(wf)+ assert proc.returncode == 1+ assert "cache key" in proc.stderr+++ "command",+ [+ # -i drops into the REPL after the script; on EOF the interpreter+ # exits 0 even though the lint called sys.exit(1).+ "python3 -i scripts/lint_workflow_triggers.py",+ # Anything outside the allowlist fails closed.+ "python3 -d scripts/lint_workflow_triggers.py",+ "python3 -uB scripts/lint_workflow_triggers.py",+ ],+ ids = ["interactive", "unknown-flag", "combined-flag"],+)+def test_lint_rejects_flags_outside_the_allowlist(tmp_path, command):+ """Only flags that leave run-this-file-and-return-its-status intact count."""+ (wf := tmp_path / "wf").mkdir()+ (wf / "host.yml").write_text(+ _host_workflow().replace(+ "run: python3 scripts/lint_workflow_triggers.py", f"run: {command}"+ )+ )+ proc = _run(wf, require_host = True)+ assert proc.returncode == 1+ assert "does not cover every PR" in proc.stderr++[email protected]("flag", ["-u", "-E", "-s", "-B", "-q", "-O"])+def test_lint_accepts_allowlisted_flags(tmp_path, flag):+ """The allowlist must not reject ordinary interpreter flags."""+ (wf := tmp_path / "wf").mkdir()+ (wf / "host.yml").write_text(+ _host_workflow().replace(+ "run: python3 scripts/lint_workflow_triggers.py",+ f"run: python3 {flag} scripts/lint_workflow_triggers.py",+ )+ )+ proc = _run(wf, require_host = True)+ assert proc.returncode == 0, proc.stderr++[email protected]("scope", ["step", "job", "workflow"])[email protected]("key", ["BASH_ENV", "PATH"])+def test_lint_rejects_execution_redirecting_env(tmp_path, scope, key):+ """`BASH_ENV` runs before the step script; `PATH` picks the interpreter."""+ body = _host_workflow()+ entry = f"env:\n {key}: /tmp/x\n"+ if scope == "step":+ body = body.replace(+ " - run: python3 scripts/lint_workflow_triggers.py\n",+ " - run: python3 scripts/lint_workflow_triggers.py\n"+ f" env:\n {key}: /tmp/x\n",+ )+ elif scope == "job":+ body = body.replace(+ " runs-on: ubuntu-latest\n",+ f" runs-on: ubuntu-latest\n env:\n {key}: /tmp/x\n",+ )+ else:+ body = body.replace("jobs:\n", entry + "jobs:\n")+ (wf := tmp_path / "wf").mkdir()+ (wf / "host.yml").write_text(body)+ proc = _run(wf, require_host = True)+ assert proc.returncode == 1+ assert key in proc.stderr++[email protected]("value", ["false", "true", "[opened]", "'yes'"])+def test_lint_rejects_a_non_mapping_pull_request_value(tmp_path, value):+ """GitHub will not load such a workflow, so it cannot be the gate."""+ (wf := tmp_path / "wf").mkdir()+ (wf / "host.yml").write_text(+ _host_workflow().replace(" pull_request:\n", f" pull_request: {value}\n")+ )+ proc = _run(wf, require_host = True)+ assert proc.returncode == 1+ assert "not a valid event configuration" in proc.stderr+++ "command",+ [+ # A repo-root `./python3` can be added by the PR itself.+ "./python3 scripts/lint_workflow_triggers.py",+ "bin/python3 scripts/lint_workflow_triggers.py",+ # A substitution in an option value runs before python does.+ 'python3 -W "$(touch pwned)" scripts/lint_workflow_triggers.py',+ ],+ ids = ["relative-interpreter", "repo-path-interpreter", "expansion-in-value"],+)+def test_lint_rejects_pr_controlled_interpreters(tmp_path, command):+ """The interpreter and its option values must not come from the checkout."""+ (wf := tmp_path / "wf").mkdir()+ (wf / "host.yml").write_text(+ _host_workflow().replace(+ "run: python3 scripts/lint_workflow_triggers.py", f"run: {command}"+ )+ )+ proc = _run(wf, require_host = True)+ assert proc.returncode == 1+ assert "does not cover every PR" in proc.stderr++[email protected]("interpreter", ["python3", "python", "/usr/bin/python3"])+def test_lint_accepts_trusted_interpreters(tmp_path, interpreter):+ """A bare command or a system path stays acceptable."""+ (wf := tmp_path / "wf").mkdir()+ (wf / "host.yml").write_text(+ _host_workflow().replace(+ "run: python3 scripts/lint_workflow_triggers.py",+ f"run: {interpreter} scripts/lint_workflow_triggers.py",+ )+ )+ proc = _run(wf, require_host = True)+ assert proc.returncode == 0, proc.stderr++[email protected]("key", ["PYTHONPATH", "PYTHONHOME", "PYTHONSTARTUP"])+def test_lint_rejects_python_startup_env(tmp_path, key):+ """`sitecustomize.py` on PYTHONPATH runs before the lint and can exit 0."""+ (wf := tmp_path / "wf").mkdir()+ (wf / "host.yml").write_text(+ _host_workflow().replace(+ " - run: python3 scripts/lint_workflow_triggers.py\n",+ " - run: python3 scripts/lint_workflow_triggers.py\n"+ f" env:\n {key}: ./pr-controlled\n",+ )+ )+ proc = _run(wf, require_host = True)+ assert proc.returncode == 1+ assert key in proc.stderr+++def test_lint_rejects_expansion_in_the_interpreter_token(tmp_path):+ """Bash substitutes before the trusted-path test can mean anything."""+ (wf := tmp_path / "wf").mkdir()+ (wf / "host.yml").write_text(+ _host_workflow().replace(+ "run: python3 scripts/lint_workflow_triggers.py",+ 'run: |\n "/usr/$(printf bin)/python3" ' "scripts/lint_workflow_triggers.py",+ )+ )+ proc = _run(wf, require_host = True)+ assert proc.returncode == 1+ assert "does not cover every PR" in proc.stderr+++def test_lint_rejects_a_containerized_host(tmp_path):+ """A PR-selected image controls the shell and environment."""+ (wf := tmp_path / "wf").mkdir()+ (wf / "host.yml").write_text(+ _host_workflow().replace(+ " runs-on: ubuntu-latest\n",+ " runs-on: ubuntu-latest\n container: alpine:latest\n",+ )+ )+ proc = _run(wf, require_host = True)+ assert proc.returncode == 1+ assert "container" in proc.stderr+++def test_lint_rejects_a_host_job_with_needs(tmp_path):+ """A skipped prerequisite skips the lint job without failing the run."""+ wf = tmp_path / "wf"+ wf.mkdir()+ (wf / "host.yml").write_text(+ _host_workflow().replace(+ " lint:\n runs-on: ubuntu-latest\n",+ " setup:\n"+ " runs-on: ubuntu-latest\n"+ " if: ${{ false }}\n"+ " steps:\n"+ " - run: echo hi\n"+ " lint:\n"+ " runs-on: ubuntu-latest\n"+ " needs: setup\n",+ )+ )+ proc = _run(wf, require_host = True)+ assert proc.returncode == 1+ assert "needs:" in proc.stderr+++ "command",+ [+ "python3 scripts/lint_workflow_triggers.py",+ "python3 -u scripts/lint_workflow_triggers.py",+ "python scripts/lint_workflow_triggers.py",+ "python3 -X utf8 scripts/lint_workflow_triggers.py",+ ],+ ids = ["plain", "dash-u", "python", "dash-X-with-value"],+)+def test_lint_accepts_ordinary_invocations(tmp_path, command):+ """Tightening host detection must not reject normal ways to run it."""+ wf = tmp_path / "wf"+ wf.mkdir()+ (wf / "host.yml").write_text(+ _host_workflow().replace(+ "run: python3 scripts/lint_workflow_triggers.py", f"run: {command}"+ )+ )+ proc = _run(wf, require_host = True)+ assert proc.returncode == 0, proc.stderr+++def test_lint_accepts_unfiltered_host(tmp_path):+ """A bare `pull_request:` host that can fail satisfies the requirement."""+ wf = tmp_path / "wf"+ wf.mkdir()+ (wf / "host.yml").write_text(_host_workflow())+ proc = _run(wf, require_host = True)+ assert proc.returncode == 0, proc.stderr+++def test_lint_rejects_missing_host(tmp_path):+ """Deleting the gate's workflow must fail the gate, not silently pass."""+ wf = tmp_path / "wf"+ wf.mkdir()+ (wf / "unrelated.yml").write_text(+ "name: unrelated\n"+ "on:\n"+ " pull_request:\n"+ "jobs:\n"+ " build:\n"+ " runs-on: ubuntu-latest\n"+ " steps:\n"+ " - run: echo hi\n"+ )+ proc = _run(wf, require_host = True)+ assert proc.returncode == 1+ assert "does not cover every PR" in proc.stderr+++ "mention",+ [+ " # scripts/lint_workflow_triggers.py needs PyYAML\n",+ " # - run: python3 scripts/lint_workflow_triggers.py\n",+ ],+ ids = ["prose", "commented-run-step"],+)+def test_commented_mention_is_not_a_host(tmp_path, mention):+ """A mention that executes nothing must not register as a host.++ The commented-out `run:` is the dangerous one: it would satisfy+ `--require-host` with the real workflow deleted.+ """+ wf = tmp_path / "wf"+ wf.mkdir()+ (wf / "mentions.yml").write_text(+ "name: mentions\n"+ "on:\n"+ " pull_request:\n"+ "jobs:\n"+ " build:\n"+ " runs-on: ubuntu-latest\n"+ " steps:\n" + mention + " - run: echo hi\n"+ )+ proc = _run(wf, require_host = True)+ assert proc.returncode == 1+ assert "does not cover every PR" in proc.stderr+++def test_workflow_trigger_lint_host_exists_and_is_unfiltered():+ """End to end on the live tree, with the host requirement forced on."""+ proc = _run(REPO_ROOT / ".github" / "workflows", require_host = True)+ assert (+ proc.returncode == 0+ ), f"live tree failed lint:\nstdout:\n{proc.stdout}\nstderr:\n{proc.stderr}"+++def _codeowners_rules(text: str) -> list[tuple[str, list[str]]]:+ """Rules in file order, INCLUDING ownerless ones.++ A pattern with no owners is valid CODEOWNERS and clears ownership for what+ it matches, so skipping those lines would miss a silent carve-out.+ """+ rules = []+ for line in text.splitlines():+ fields = line.split("#", 1)[0].split()+ if fields:+ rules.append((fields[0], fields[1:]))+ return rules+++def _pattern_regex(pattern: str) -> re.Pattern:+ """CODEOWNERS globbing: `*` stops at `/`, `**` crosses directories.++ `fnmatch` gets both halves wrong here. Its `*` consumes `/`, so+ `/.github/*` would wrongly claim nested workflow files and fail a valid+ CODEOWNERS change; and it cannot express `**/` matching zero directories,+ so `/.github/**/workflows/` would wrongly miss one.+ """+ out, i = [], 0+ while i < len(pattern):+ if pattern.startswith("**/", i):+ out.append("(?:[^/]+/)*")+ i += 3+ elif pattern.startswith("**", i):+ out.append(".*")+ i += 2+ elif pattern[i] == "*":+ out.append("[^/]*")+ i += 1+ elif pattern[i] == "?":+ out.append("[^/]")+ i += 1+ else:+ out.append(re.escape(pattern[i]))+ i += 1+ return re.compile("".join(out) + r"\Z")+++def _is_valid_owner(token: str) -> bool:+ """GitHub only requests review from an @user, an @org/team, or an email."""+ if token.startswith("@"):+ return len(token) > 1+ local, _, domain = token.partition("@")+ return bool(local and "." in domain)+++def _pattern_matches(pattern: str, path: str) -> bool:+ """Approximate GitHub's CODEOWNERS matching.++ A pattern that NAMES a directory owns everything beneath it, so directory+ prefixes of the path are candidates. A pattern with a wildcard in it does+ not: GitHub documents `docs/*` as matching `docs/getting-started.md` but+ not `docs/build-app/troubleshooting.md`.++ Only a pattern with no internal separator floats to any depth, gitignore+ style. A leading slash anchors, and so does an internal one, so+ `workflows/lint.yml` is root-relative and does NOT match+ `.github/workflows/lint.yml`; a bare `workflows/` still matches at any+ depth.+ """+ if pattern == "*":+ return True+ is_dir = pattern.endswith("/")+ body = pattern.strip("/")+ anchored = pattern.startswith("/") or "/" in body+ rx = _pattern_regex(body)+ segments = path.split("/")++ def matches(candidate: str) -> bool:+ parts = candidate.split("/")+ starts = [0] if anchored else range(len(parts))+ return any(rx.match("/".join(parts[j:])) for j in starts)++ prefixes = ["/".join(segments[:i]) for i in range(1, len(segments))]+ if is_dir:+ return any(matches(p) for p in prefixes)+ if matches(path):+ return True+ # A plain path may name a directory, and then owns everything under it.+ return not any(ch in body for ch in "*?") and any(matches(p) for p in prefixes)+++def _effective_owners(text: str, path: str) -> list[str]:+ """Owners GitHub would require, i.e. the LAST matching rule wins."""+ owners: list[str] = []+ for pattern, people in _codeowners_rules(text):+ if _pattern_matches(pattern, path):+ owners = people+ return owners+++CODEOWNERS_PROBES = (+ ".github/workflows/workflow-trigger-lint.yml",+ ".github/CODEOWNERS",+)+++def test_workflow_changes_require_code_owner_review():+ """Every workflow must keep an EFFECTIVE code owner.++ The lint cannot stop a PR that disables the lint's own host workflow, so+ owner review is the merge-time control. GitHub applies only the last+ matching pattern, so checking that a rule exists somewhere is not enough:+ a later rule, broad or narrow, silently takes over. Any workflow can hand+ a fork PR the base repo's secrets, so every one of them is checked, not+ just the lint host. Delegating a workflow to another maintainer is fine;+ leaving one unowned is not.+ """+ text = (REPO_ROOT / ".github" / "CODEOWNERS").read_text(encoding = "utf-8")+ workflows = sorted(+ p.relative_to(REPO_ROOT).as_posix()+ for p in (REPO_ROOT / ".github" / "workflows").iterdir()+ if p.suffix in (".yml", ".yaml")+ )+ assert workflows, "no workflow files found"+ for probe in workflows:+ owners = [o for o in _effective_owners(text, probe) if _is_valid_owner(o)]+ assert owners, (+ f"CODEOWNERS leaves {probe} with no effective owner GitHub could "+ "request review from; a later pattern overrode the "+ ".github/workflows/ rule."+ )+ for probe in CODEOWNERS_PROBES:+ owners = _effective_owners(text, probe)+ assert "@danielhanchen" in owners, (+ f"CODEOWNERS gives {probe} effective owners {owners or '(none)'}; "+ "a later pattern overrode the workflow rule."+ )+++ "pattern, path, matches",+ [+ # `*` stops at a directory boundary, like GitHub's `docs/*` example.+ ("/.github/*", ".github/workflows/lint.yml", False),+ ("/.github/*", ".github/CODEOWNERS", True),+ # `**` crosses them, and `**/` may match zero.+ ("/.github/**", ".github/workflows/lint.yml", True),+ ("/.github/**/workflows/", ".github/workflows/lint.yml", True),+ ("/.github/**/workflows/", ".github/a/b/workflows/lint.yml", True),+ # A plain path naming a directory owns everything beneath it.+ ("/.github/workflows/", ".github/workflows/lint.yml", True),+ ("/scripts", "scripts/data/x.txt", True),+ # Unanchored patterns may start at any depth.+ ("workflows/", ".github/workflows/lint.yml", True),+ ("**/workflows/", ".github/workflows/lint.yml", True),+ # An internal slash anchors at the root, gitignore style, so this+ # names a top-level workflows/ and not the one under .github/.+ ("workflows/lint.yml", ".github/workflows/lint.yml", False),+ ("workflows/lint.yml", "workflows/lint.yml", True),+ # Non-matches.+ ("/unsloth/", ".github/workflows/lint.yml", False),+ ("/unsloth", "unsloth_zoo/x.py", False),+ ],+)+def test_codeowners_pattern_semantics(pattern, path, matches):+ """The matcher must model GitHub, in both directions.++ Under-matching hides a rule that steals ownership; over-matching fails a+ valid CODEOWNERS change that never touched the workflows.+ """+ assert _pattern_matches(pattern, path) is matches+++ "token, valid",+ [+ ("@danielhanchen", True),+ ("@unslothai/maintainers", True),+ ("[email protected]", True),+ ("not-an-owner", False),+ ("@", False),+ ],+)+def test_owner_token_validity(token, valid):+ """An unusable owner token leaves a path effectively unowned.++ GitHub cannot request review from a bare word, so counting it as an owner+ would let a trailing rule quietly disown a workflow.+ """+ assert _is_valid_owner(token) is valid+++def test_invalid_owner_does_not_count_as_ownership():+ """The realistic mistake: a later rule naming a non-owner."""+ text = (REPO_ROOT / ".github" / "CODEOWNERS").read_text(encoding = "utf-8")+ probe = CODEOWNERS_PROBES[0]+ owners = _effective_owners(f"{text}\n/{probe} not-an-owner\n", probe)+ assert owners == ["not-an-owner"]+ assert not [o for o in owners if _is_valid_owner(o)]+++ "override, expected",+ [+ ("* @someone-else", ["@someone-else"]),+ ("/.github/ @someone-else", ["@someone-else"]),+ (f"/{CODEOWNERS_PROBES[0]} @someone-else", ["@someone-else"]),+ # A pattern with no owners is valid, and clears ownership.+ (f"/{CODEOWNERS_PROBES[0]}", []),+ # Globbed and unanchored directory patterns are valid rules too.+ ("**/workflows/ @someone-else", ["@someone-else"]),+ ("workflows/ @someone-else", ["@someone-else"]),+ (".github/*/ @someone-else", ["@someone-else"]),+ # `**/` may match zero directories.+ ("/.github/**/workflows/ @someone-else", ["@someone-else"]),+ ],+ ids = [+ "catch-all",+ "parent-dir",+ "narrower-file",+ "ownerless",+ "globbed-dir",+ "unanchored-dir",+ "wildcard-segment",+ "double-star-zero-dirs",+ ],+)+def test_codeowners_guard_catches_a_later_rule(override, expected):+ """The guard must fail whichever way a trailing rule takes precedence."""+ text = (REPO_ROOT / ".github" / "CODEOWNERS").read_text(encoding = "utf-8")+ owners = _effective_owners(f"{text}\n{override}\n", CODEOWNERS_PROBES[0])+ assert owners == expected, f"{override!r} should win, got {owners}"++def test_lint_rejects_unjustified_workflow_run(tmp_path):"""`workflow_run` requires an explicit allow-comment in the YAML."""wf = tmp_path / "wf"