From 4fabe1358ef4825dbdda628a955fa370b06251da Mon Sep 17 00:00:00 2001 From: Defame1297 Date: Sun, 25 Oct 2026 19:16:30 +0000 Subject: [PATCH] fix(ci): make check_image_versions pass ansible-test sanity and harden its input handling Sanity (pylint, shebang) failed the Build check: drop the shebang and the executable bit, simplify a comprehension, define functions instead of assigning lambdas and pass check= to every subprocess.run. Read the changed files with git diff -z so non-ASCII paths are compared unquoted. Validate the matrix shape (non-empty list of mappings, string name/version/dockerfile/subpath, no duplicate names) with one-line errors. Match semver with fullmatch and reject leading zeros. Let a pin end at , ) ] } or a quote. Document the known limits. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01MmzvM9skAvYcph2c9EiPcm --- scripts/check_image_versions.py | 64 ++++++++++++++++------ tests/scripts/test_check_image_versions.py | 58 +++++++++++++++++++- 2 files changed, 102 insertions(+), 20 deletions(-) mode change 100755 => 100644 scripts/check_image_versions.py diff --git a/scripts/check_image_versions.py b/scripts/check_image_versions.py old mode 100755 new mode 100644 index cb16a01..56fd7a9 --- a/scripts/check_image_versions.py +++ b/scripts/check_image_versions.py @@ -1,10 +1,9 @@ -#!/usr/bin/env python3 # SPDX-FileCopyrightText: Defame1297 and contributors # SPDX-License-Identifier: GPL-3.0-or-later """Keep image versions and image pins honest (ADR 0004, Image distribution). - scripts/check_image_versions.py pins - scripts/check_image_versions.py bump + python3 scripts/check_image_versions.py pins + python3 scripts/check_image_versions.py bump The matrix of .gitea/workflows/image.yml is the registry of images: name, version, build context (subpath) and Dockerfile. A published version tag is never moved (Gitea @@ -22,6 +21,13 @@ bump Fails when the diff ...HEAD touches an input of an image without higher version for it in the matrix. Inputs of an image: its build context directory (the Dockerfile's directory, or the subpath), plus, for a repository- root context, every file the Dockerfile COPYs from the context. + +Known limits: + * is compared through the merge-base, so a bump that collides with a newer + bump already on the base branch (two branches bumping to the same version) is not + detected here; the second one to merge has to rebase and bump again. + * Whether a version tag points at the digest of a pin is a registry fact and is not + verified offline; only the shape of the pin and the version order are checked. """ import fnmatch import json @@ -35,8 +41,12 @@ import yaml MATRIX_FILE = ".gitea/workflows/image.yml" CONSUMERS = [".gitea/workflows/lint.yml", ".gitea/workflows/build.yml", ".gitea/workflows/molecule.yml"] PIN_RE = re.compile(r"git\.rkdr\.net/mortis/(?P[a-z0-9._-]+):(?P[^@\s]+)@(?Psha256:[0-9a-f]{64})") -ANY_PIN_RE = re.compile(r"git\.rkdr\.net/mortis/[a-z0-9._-]+[:@]\S*") -SEMVER_RE = re.compile(r"^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$") +# A mention ends at whitespace, quotes or closing punctuation, so a pin followed by `,` `)` `]` `}` parses. +ANY_PIN_RE = re.compile(r"""git\.rkdr\.net/mortis/[a-z0-9._-]+[:@][^\s,)\]}'"]*""") +# Semver 2.0.0: no leading zeros in numeric identifiers (core or prerelease). +_NUM = r"(?:0|[1-9][0-9]*)" +_PRE_ID = r"(?:0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*)" +SEMVER_RE = re.compile(rf"({_NUM})\.({_NUM})\.({_NUM})(?:-({_PRE_ID}(?:\.{_PRE_ID})*))?") # A base ref is a plain ref name or SHA: no leading '-', so it can never be read as an option. REF_RE = re.compile(r"^[A-Za-z0-9._/][A-Za-z0-9._/-]*$") @@ -46,7 +56,7 @@ class CheckError(Exception): def parse_version(text): - m = SEMVER_RE.match(str(text)) + m = SEMVER_RE.fullmatch(str(text)) if not m: raise ValueError(f"'{text}' is not MAJOR.MINOR.PATCH[-prerelease]") # Semver precedence: a prerelease sorts below its release; prerelease identifiers are @@ -61,20 +71,38 @@ def matrix_of(text): try: doc = yaml.safe_load(text) except yaml.YAMLError as exc: - raise CheckError(f"{MATRIX_FILE} is not valid YAML: {exc}") from exc + raise CheckError(f"{MATRIX_FILE} is not valid YAML: {' '.join(str(exc).split())}") from exc try: entries = doc["jobs"]["image"]["strategy"]["matrix"]["include"] except (KeyError, TypeError) as exc: raise CheckError(f"{MATRIX_FILE} has no jobs.image.strategy.matrix.include list " f"(missing key {exc})") from exc + if not isinstance(entries, list) or not entries: + raise CheckError(f"{MATRIX_FILE}: matrix.include must be a non-empty list of mappings") matrix = {} - for e in entries: - try: - matrix[e["name"]] = {"version": str(e["version"]), "subpath": e.get("subpath") or "", - "dockerfile": e["dockerfile"]} - except (KeyError, TypeError, AttributeError) as exc: - raise CheckError(f"a matrix entry of {MATRIX_FILE} lacks the key {exc} " - "(name, version and dockerfile are required)") from exc + for n, e in enumerate(entries, 1): + if not isinstance(e, dict): + raise CheckError(f"{MATRIX_FILE}: matrix.include entry {n} is not a mapping") + for key in ("name", "version", "dockerfile"): + if key not in e: + raise CheckError(f"a matrix entry of {MATRIX_FILE} lacks the key '{key}' " + "(name, version and dockerfile are required)") + name = e["name"] + if not isinstance(name, str) or not name: + raise CheckError(f"{MATRIX_FILE}: matrix.include entry {n}: name must be a non-empty string") + if name in matrix: + raise CheckError(f"{MATRIX_FILE}: duplicate image name '{name}' in matrix.include") + # A YAML number (0.1) would silently become a string; versions must be written as strings. + for key in ("version", "dockerfile"): + if not isinstance(e[key], str): + raise CheckError(f"{MATRIX_FILE}: image '{name}': {key} must be a string " + f"(quote it in the YAML), got {e[key]!r}") + subpath = e.get("subpath") + if subpath is None: + subpath = "" + elif not isinstance(subpath, str): + raise CheckError(f"{MATRIX_FILE}: image '{name}': subpath must be a string, got {subpath!r}") + matrix[name] = {"version": e["version"], "subpath": subpath, "dockerfile": e["dockerfile"]} return matrix @@ -103,7 +131,7 @@ def inputs_of(entry, dockerfile_text): if entry["subpath"]: return [entry["subpath"].rstrip("/")], [] dirs = [str(pathlib.PurePosixPath(entry["dockerfile"]).parent)] - files = [s for s in copy_sources(dockerfile_text)] + files = list(copy_sources(dockerfile_text)) return dirs, files @@ -190,8 +218,10 @@ def run(argv): 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. - changed = [p for p in git("diff", "--name-only", "--no-renames", "--end-of-options", base, "HEAD") - .splitlines() if p] + # -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 = [p for p in git("-c", "core.quotePath=false", "diff", "--name-only", "-z", "--no-renames", + "--end-of-options", base, "HEAD").split("\0") if p] try: base_text = git("show", f"{base}:{MATRIX_FILE}") except CheckError: diff --git a/tests/scripts/test_check_image_versions.py b/tests/scripts/test_check_image_versions.py index 5083f15..c7eea34 100644 --- a/tests/scripts/test_check_image_versions.py +++ b/tests/scripts/test_check_image_versions.py @@ -84,8 +84,52 @@ class PureTest(unittest.TestCase): self.assertEqual(len(civ.check_pins(m, {"f": "git.rkdr.net/mortis/ci:0.2.0"})), 1) self.assertEqual(len(civ.check_pins(m, {"f": "git.rkdr.net/mortis/ci@sha256:abc"})), 1) + def test_semver_is_strict(self): + for bad in ("0.1.0\n", "01.0.0", "1.02.0", "1.0.00", "1.0.0-01", "1.0.0-rc.01", "1.0.0 ", "v1.0.0"): + with self.assertRaises(ValueError, msg=repr(bad)): + civ.parse_version(bad) + for good in ("0.0.0", "1.0.0-0", "1.0.0-0a", "1.0.0-rc.0", "10.20.30"): + civ.parse_version(good) + + def test_pin_followed_by_punctuation_is_parsed(self): + m = self.matrix() + for tail in (",", ")", "]", "}", "'", '"', ";"): + text = f"x: [git.rkdr.net/mortis/ci:0.1.0@{DIGEST}{tail if tail != ';' else ''} y]\n" + self.assertEqual(civ.check_pins(m, {"f": text}), [], tail) + ahead = f"x: (git.rkdr.net/mortis/ci:0.3.0@{DIGEST}), z\n" + self.assertEqual(len(civ.check_pins(m, {"f": ahead})), 1) + self.assertEqual(len(civ.check_pins(m, {"f": "x: [git.rkdr.net/mortis/ci:0.1.0@sha256:abc, y]"})), 1) + + def test_matrix_shape_errors(self): + def doc(include): + return "jobs:\n image:\n strategy:\n matrix:\n include: " + include + "\n" + + entry = "{name: a, version: '0.1.0', dockerfile: D" + cases = { + "[]": "non-empty list", + "{}": "non-empty list", + "[1]": "not a mapping", + "[{name: 1, version: '0.1.0', dockerfile: D}]": "name must be a non-empty string", + "[" + entry + ", subpath: 5}]": "subpath must be a string", + "[" + entry + ", subpath: [x]}]": "subpath must be a string", + "[{name: a, version: 0.1, dockerfile: D}]": "version must be a string", + "[" + entry + "}, " + entry + "}]": "duplicate image name 'a'", + } + for include, text in cases.items(): + with self.assertRaises(civ.CheckError, msg=include) as ctx: + civ.matrix_of(doc(include)) + self.assertIn(text, str(ctx.exception)) + self.assertNotIn("\n", str(ctx.exception)) + self.assertEqual(civ.matrix_of(doc("[" + entry + ", subpath: }]"))["a"]["subpath"], "") + with self.assertRaises(civ.CheckError) as ctx: + civ.matrix_of("jobs: [unclosed\n") + self.assertNotIn("\n", str(ctx.exception)) + def test_bump_logic(self): - base, read = self.matrix(), lambda p: CI_DOCKERFILE + def read(_path): + return CI_DOCKERFILE + + base = self.matrix() same = self.matrix() for path in ("images/mol/Dockerfile", "images/ci/Dockerfile", "requirements-dev.txt", ".pre-commit-config.yaml"): self.assertTrue(civ.check_bump(base, same, [path], read), path) @@ -123,12 +167,12 @@ class GitTest(unittest.TestCase): def bump(self): proc = subprocess.run([sys.executable, str(SCRIPTS / "check_image_versions.py"), "bump", "main"], - cwd=self.repo, capture_output=True, text=True) + cwd=self.repo, capture_output=True, text=True, check=False) return proc.returncode, proc.stderr def bump_args(self, *args, cwd=None): proc = subprocess.run([sys.executable, str(SCRIPTS / "check_image_versions.py"), *args], - cwd=cwd or self.repo, capture_output=True, text=True) + cwd=cwd or self.repo, capture_output=True, text=True, check=False) return proc.returncode, proc.stderr def assert_clean_failure(self, result, text): @@ -177,6 +221,14 @@ class GitTest(unittest.TestCase): run(self.repo, "git", "rm", "-q", ".gitea/workflows/image.yml") self.assert_clean_failure(self.bump_args("pins"), "cannot read a file") + def test_non_ascii_input_path_counts(self): + self.write("images/mol/caf\u00e9", "x\n") + self.commit("non-ascii input") + code, err = self.bump() + self.assertEqual(code, 1, err) + self.assertIn("image 'mol'", err) + self.assertIn("caf\u00e9", err) + def test_unrelated_change_passes(self): self.write("README.md", "x\n") self.commit("docs")