Files
Kamino/scripts/check_bot_pr_diff.py
T
Defame1297andClaude Sonnet 5.5 068bec93a9
Build / build (pull_request) Successful in 11s
Lint / lint (pull_request) Successful in 43s
Molecule / molecule (pull_request) Successful in 6m19s
fix(molecule): install community.docker for the Docker driver
Every scenario failed in its create step (couldn't resolve module community.docker.docker_login): molecule's Docker driver runs community.docker modules in its own create and destroy playbooks, and the collection came from the runner-provisioned /opt/molecule-collections that the previous commit stopped reading. The roles do not call it, so it is not in requirements.yml, which the ci image bakes for Lint and which Renovate would rebuild the image for. It is pinned in extensions/molecule/requirements.yml instead; the Molecule job installs both files, cached by their combined checksum. Renovate tracks the new file and the bot-diff gate allows only its version: lines.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_014uGZTNmHMc85bomfevwUDG
2026-11-14 14:30:11 +00:00

324 lines
11 KiB
Python

# 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 <head-ref> <base-ref>
When <head-ref> starts with `renovate/`, the diff of <base-ref>...HEAD may only touch:
* requirements-dev.txt: pinned `name==version` lines, the same packages before and after;
* requirements.yml and extensions/molecule/requirements.yml: `version:` lines (the collection
names, and every other line, stay);
* .pre-commit-config.yaml: `rev:` lines;
* images/<name>/Dockerfile: the tag and digest of FROM lines (the image name stays), and
the `uv==<version>` token of a line that holds one;
* .gitea/workflows/image.yml: the matrix `version:` lines, and the tag and digest of the
job containers' `job_image: ubuntu:...@sha256:...` lines (the name stays);
* .gitea/workflows/{lint,build,molecule}.yml: the version and digest of a
`git.rkdr.net/mortis/<name>:<version>@sha256:<digest>` 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.
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/"
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*["']?(?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(
rf"^(\s*job_image:\s*ubuntu)(?::{TAG})?@sha256:[0-9a-f]{{64}}\s*$"
)
DOCKERFILE = re.compile(r"images/[^/]+/Dockerfile")
COLLECTION_PINS = {"requirements.yml", "extensions/molecule/requirements.yml"}
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_version(line):
return "version" if VERSION_LINE.match(line) 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 in COLLECTION_PINS:
return same_shape(removed, added, reduce_version, "a `version:` line")
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 a `job_image:` ubuntu 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
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"):
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((old_n, line[1:]))
old_n += 1
elif line.startswith("+"):
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 unused, line in removed], [line for unused, 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, unused in removed] != [n for n, unused in added]:
return "moves or deletes a line (the changed lines must stay where they are)"
for (unused, old), (unused, 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 = []
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
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 unused, line in removed], [line for unused, 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
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 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):
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(
"--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)
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))