Files
Kamino/scripts/check_bot_pr_diff.py
T
Defame1297andClaude Sonnet 5.5 f2e1139562 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 <[email protected]>
Claude-Session: https://claude.ai/code/session_01MmzvM9skAvYcph2c9EiPcm
2026-10-25 21:08:21 +00:00

196 lines
7.6 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;
* .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 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/<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.
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))