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 <[email protected]>
Claude-Session: https://claude.ai/code/session_01MmzvM9skAvYcph2c9EiPcm
This commit is contained in:
Defame1297andClaude Sonnet 5.5 committed 2026-10-26 06:41:20 +00:00
1 parent a57714342b
commit 8e9a8c5df0
3 files changed
+189 -13

No files matched your search

+62 -11
View File
@@ -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 <head-ref> 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<v>[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)