The renovate-config job clones in its own step and validates in a second step, so the job token is not in the environment that reads the pull request's renovate.json. check_bot_pr_diff.py now refuses a moved image line in every workflow whose pins a bot may move, lint.yml included, not only in image.yml and renovate.yml. Tests cover a moved lint.yml line, an added second Renovate line and a changed indentation. Refs: #188 Assisted-by: Claude Code
434 lines
16 KiB
Python
434 lines
16 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 and requirements-molecule.txt: pinned `name==version` lines, the same
|
|
packages before and after;
|
|
* requirements-dev.lock and requirements-molecule.lock (pip-compile --generate-hashes output):
|
|
`name==version` entries, `--hash=sha256:<64 hex>` lines and plain `# via` or prose comments,
|
|
nothing else; packages may be added or removed (a transitive dependency), but the
|
|
`# pip-compile ...` command in the header, which Renovate runs again, must stay as it is;
|
|
* pyproject.toml: the version of a quoted `"name==version"` pin (the names, spelled as they
|
|
are, and every other line, stay), only together with uv.lock;
|
|
* uv.lock: the apm-cli bump to the pin of the new pyproject.toml, and nothing else
|
|
(check_uv_lock.py), only together with pyproject.toml;
|
|
* requirements.yml and extensions/molecule/requirements.yml: `version:` lines (the collection
|
|
names, and every other line, stay);
|
|
* .pre-commit-config.yaml: `rev:` lines (a tag, or a commit SHA with its `# frozen: <tag>` comment);
|
|
* 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 tag and digest of the job containers'
|
|
`job_image: ubuntu:...@sha256:...` lines (the name stays); CI assigns the image versions
|
|
and a human sets the matrix `base:`, so neither is the bot's to change;
|
|
* .gitea/workflows/{lint,build,molecule,gitea-release-key}.yml: the version and digest of a
|
|
`git.rkdr.net/mortis/<name>:<version>@sha256:<digest>` pin, in place (the name stays),
|
|
including the MOLECULE_IMAGE value;
|
|
* .gitea/workflows/renovate.yml, and lint.yml's copy of it: the version and digest of the
|
|
`image: renovate/renovate:<version>-full@sha256:<digest>` line, in place; the name and the
|
|
`-full` flavour stay (the job's report check needs the python3 that only -full ships).
|
|
|
|
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
|
|
import check_uv_lock
|
|
|
|
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.+!_-]*$")
|
|
# A hook `rev:` is a tag or a commit SHA; a SHA carries its release in a `# frozen: <tag>` comment.
|
|
# Nothing else may trail it, so the comment cannot hide a second instruction.
|
|
REV_LINE = re.compile(r"^\s*rev:\s*\S+(?:\s+#\s*frozen:\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*$"
|
|
)
|
|
RENOVATE_LINE = re.compile(
|
|
r"^(\s*image:\s*renovate/renovate:)[0-9]+(?:\.[0-9]+)*(-full)@sha256:[0-9a-f]{64}\s*$"
|
|
)
|
|
RENOVATE_WORKFLOW = ".gitea/workflows/renovate.yml"
|
|
LINT_WORKFLOW = ".gitea/workflows/lint.yml"
|
|
DOCKERFILE = re.compile(r"images/[^/]+/Dockerfile")
|
|
COLLECTION_PINS = {"requirements.yml", "extensions/molecule/requirements.yml"}
|
|
# Lint's and the molecule-controller image's requirements, each with its pip-compile lock.
|
|
REQUIREMENTS = {"requirements-dev.txt", "requirements-molecule.txt"}
|
|
LOCKS = {"requirements-dev.lock", "requirements-molecule.lock"}
|
|
UV_LOCK = "uv.lock"
|
|
CONSUMERS = {
|
|
".gitea/workflows/build.yml",
|
|
".gitea/workflows/molecule.yml",
|
|
".gitea/workflows/gitea-release-key.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
|
|
|
|
|
|
# A lock: an entry (with an optional environment marker), a hash, or a comment.
|
|
# The marker and the prose comment use a small character set: no backslash, quote of a shell, `$` or `--`.
|
|
LOCK_ENTRY = re.compile(
|
|
r"^[A-Za-z0-9][A-Za-z0-9._-]*==[0-9][0-9A-Za-z.+!_-]*"
|
|
r"(?:\s*;\s*[A-Za-z0-9_.\"' =<>!()~,-]+?)?\s*\\?$"
|
|
)
|
|
LOCK_HASH = re.compile(r"^\s+--hash=sha256:[0-9a-f]{64}(?:\s*\\)?$")
|
|
LOCK_COMMAND = re.compile(r"^#\s+pip-compile\s.*$")
|
|
LOCK_COMMENT = re.compile(
|
|
r"^\s*(?:#(?:\s[A-Za-z0-9 ._,:()/'-]*)?)?$"
|
|
) # a blank line is allowed too
|
|
|
|
|
|
def lock_problem(removed, added):
|
|
"""None when every changed line of a lock is an entry, a hash or a plain comment and
|
|
the `# pip-compile ...` command line is the same on both sides."""
|
|
for line in removed + added:
|
|
if LOCK_COMMAND.match(line):
|
|
continue
|
|
if not (
|
|
LOCK_ENTRY.match(line) or LOCK_HASH.match(line) or LOCK_COMMENT.match(line)
|
|
):
|
|
return (
|
|
"changes a line that is not an entry, a sha256 hash or a plain comment"
|
|
)
|
|
old = sorted(line for line in removed if LOCK_COMMAND.match(line))
|
|
new = sorted(line for line in added if LOCK_COMMAND.match(line))
|
|
if old != new:
|
|
return "changes the pip-compile command of the header"
|
|
return None
|
|
|
|
|
|
# A quoted `name==version` pin in a pyproject.toml dependency array.
|
|
PYPROJECT_PIN = re.compile(r'"([A-Za-z0-9][A-Za-z0-9._-]*)==[0-9][0-9A-Za-z.+!_-]*"')
|
|
|
|
|
|
def reduce_pyproject(line):
|
|
if not PYPROJECT_PIN.search(line):
|
|
return None
|
|
return PYPROJECT_PIN.sub(lambda m: f'"{m[1]}==X"', line)
|
|
|
|
|
|
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):
|
|
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 reduce_renovate_image(line):
|
|
m = RENOVATE_LINE.match(line)
|
|
return m[1] + "X" + m[2] if m else None
|
|
|
|
|
|
def reduce_lint_yml(line):
|
|
# Lint also validates renovate.json in a copy of renovate.yml's image.
|
|
return reduce_pin(line) or reduce_renovate_image(line)
|
|
|
|
|
|
MORTIS_PIN = (reduce_pin, "an image pin of the mortis registry")
|
|
# The workflows whose image lines a bot moves: (reduce_line, what may change).
|
|
WORKFLOW_PINS = {
|
|
**dict.fromkeys(CONSUMERS, MORTIS_PIN),
|
|
LINT_WORKFLOW: (
|
|
reduce_lint_yml,
|
|
"an image pin of the mortis registry or the Renovate image line",
|
|
),
|
|
RENOVATE_WORKFLOW: (reduce_renovate_image, "the Renovate image line"),
|
|
}
|
|
|
|
|
|
def file_problem(path, removed, added):
|
|
"""One-line reason why the change to `path` is not allowed for a bot, or None."""
|
|
if path in REQUIREMENTS:
|
|
return same_shape(
|
|
removed,
|
|
added,
|
|
reduce_requirement,
|
|
"a pinned `name==version` line of the same package",
|
|
)
|
|
if path in LOCKS:
|
|
return lock_problem(removed, added)
|
|
if path == "pyproject.toml":
|
|
return same_shape(
|
|
removed, added, reduce_pyproject, "a quoted `name==version` pin"
|
|
)
|
|
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 `job_image:` ubuntu pin",
|
|
)
|
|
if path in WORKFLOW_PINS:
|
|
return same_shape(removed, added, *WORKFLOW_PINS[path])
|
|
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 moved_problem(removed, added):
|
|
"""A reason when a changed line changes position, else None; both lists are (line number, line).
|
|
A `job_image:` pin moved to another matrix entry, or a workflow's image line moved to another
|
|
job, would change which job runs on it."""
|
|
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)"
|
|
return None
|
|
|
|
|
|
def check(entries, patch_of, show=None):
|
|
"""One message per offending file; patch_of(path) returns that file's -U0 patch text and
|
|
show(side, path) its text on the "base" or "head" side (needed for uv.lock)."""
|
|
problems = []
|
|
# The pin and its lock move together, so neither can change what the other one locks.
|
|
partners = {"pyproject.toml": UV_LOCK, UV_LOCK: "pyproject.toml"}
|
|
paths = {path for unused, unused, unused, path in entries}
|
|
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
|
|
if path in partners and partners[path] not in paths:
|
|
problems.append(f"{path}: changes without {partners[path]}")
|
|
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
|
|
if path == UV_LOCK:
|
|
reason = (
|
|
check_uv_lock.lock_problem(
|
|
show("base", path),
|
|
show("head", path),
|
|
show("head", "pyproject.toml"),
|
|
)
|
|
if show
|
|
else "is not a file a bot pull request may change"
|
|
)
|
|
else:
|
|
reason = file_problem(
|
|
path,
|
|
[line for unused, line in removed],
|
|
[line for unused, line in added],
|
|
)
|
|
if not reason and (path == civ.MATRIX_FILE or path in WORKFLOW_PINS):
|
|
reason = moved_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,
|
|
)
|
|
|
|
def show(side, path):
|
|
rev = base if side == "base" else "HEAD"
|
|
return civ.git("cat-file", "blob", f"{rev}:{path}")
|
|
|
|
entries = parse_raw(raw)
|
|
return check(
|
|
entries, patch_of, show
|
|
), 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))
|