From a51090192e396c528d9fa1620232ee9c24a7ec1d Mon Sep 17 00:00:00 2001 From: Defame1297 Date: Sun, 25 Oct 2026 18:22:03 +0000 Subject: [PATCH 1/4] ci: check image pins and image version bumps in Lint Add scripts/check_image_versions.py (pins mode, and bump mode on pull requests) with unit tests, and run both plus the scripts' tests in lint.yml. tests/scripts is added to galaxy.yml build_ignore. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01MmzvM9skAvYcph2c9EiPcm --- .gitea/workflows/lint.yml | 20 ++ .../fragments/image-version-and-pin-check.yml | 5 + galaxy.yml | 1 + scripts/check_image_versions.py | 174 ++++++++++++++++++ tests/scripts/test_check_image_versions.py | 149 +++++++++++++++ 5 files changed, 349 insertions(+) create mode 100644 changelogs/fragments/image-version-and-pin-check.yml create mode 100755 scripts/check_image_versions.py create mode 100644 tests/scripts/test_check_image_versions.py diff --git a/.gitea/workflows/lint.yml b/.gitea/workflows/lint.yml index c2f3e27..0f69c3d 100644 --- a/.gitea/workflows/lint.yml +++ b/.gitea/workflows/lint.yml @@ -67,6 +67,26 @@ jobs: export PATH="/opt/venv/bin:$PATH" pre-commit run --all-files --show-diff-on-failure + # Image versions and pins (scripts/check_image_versions.py): a change to an image's + # inputs needs a higher version in image.yml, and a pin in a workflow must name an + # image of the matrix. Not a pre-commit hook: a change to .pre-commit-config.yaml + # is itself an input of the ci image and would force an image rebuild. + - name: Check image pins + run: | + export PATH="/opt/venv/bin:$PATH" + python3 scripts/check_image_versions.py pins + + - name: Check image versions were bumped + if: github.event_name == 'pull_request' + run: | + export PATH="/opt/venv/bin:$PATH" + python3 scripts/check_image_versions.py bump origin/main + + - name: Test the repository scripts + run: | + export PATH="/opt/venv/bin:$PATH" + python3 -m unittest discover -s tests/scripts + # The gitleaks hook scans --staged only, which is empty in a clean checkout, # so scan the PR's commits explicitly with the binary pre-commit built. - name: Scan PR commits for secrets diff --git a/changelogs/fragments/image-version-and-pin-check.yml b/changelogs/fragments/image-version-and-pin-check.yml new file mode 100644 index 0000000..10bc10d --- /dev/null +++ b/changelogs/fragments/image-version-and-pin-check.yml @@ -0,0 +1,5 @@ +trivial: + - >- + Add scripts/check_image_versions.py and its tests, and run them in the Lint workflow: + image pins must name an image of the build matrix, and a pull request that changes an + image's inputs must bump its version. diff --git a/galaxy.yml b/galaxy.yml index 7bb9fd3..c164924 100644 --- a/galaxy.yml +++ b/galaxy.yml @@ -27,5 +27,6 @@ build_ignore: - CONTRIBUTING.md - images - scripts + - tests/scripts - requirements-dev.txt - '*.tar.gz' diff --git a/scripts/check_image_versions.py b/scripts/check_image_versions.py new file mode 100755 index 0000000..f5de31b --- /dev/null +++ b/scripts/check_image_versions.py @@ -0,0 +1,174 @@ +#!/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 + +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 +cannot make a tag immutable), so an image whose content changes under an unchanged +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 + 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). + Offline: whether the tag points at the digest is a registry fact, see the + "unverified" note in the PR description. +bump Fails when the diff ...HEAD touches an input of an image without a + 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. +""" +import fnmatch +import json +import pathlib +import re +import subprocess +import sys + +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.-]+)?$") + + +def parse_version(text): + m = SEMVER_RE.match(str(text)) + if not m: + raise ValueError(f"'{text}' is not MAJOR.MINOR.PATCH[-prerelease]") + # A prerelease sorts below its release. + return (int(m[1]), int(m[2]), int(m[3]), 0 if m[4] else 1, m[4] or "") + + +def matrix_of(text): + """Return {name: {version, subpath, dockerfile}} from the text of image.yml.""" + doc = yaml.safe_load(text) + entries = doc["jobs"]["image"]["strategy"]["matrix"]["include"] + return {e["name"]: {"version": str(e["version"]), "subpath": e.get("subpath") or "", + "dockerfile": e["dockerfile"]} for e in entries} + + +def copy_sources(dockerfile_text): + """Context paths a Dockerfile COPY/ADD reads (not --from=, not URLs).""" + sources = [] + for line in dockerfile_text.replace("\\\n", " ").splitlines(): + parts = line.split() + if not parts or parts[0].upper() not in ("COPY", "ADD"): + continue + rest = [p for p in parts[1:] if not p.startswith("--")] + if rest and rest[0].startswith("["): # JSON form: COPY ["a", "b"] + try: + rest = [str(a) for a in json.loads(" ".join(rest))] + except ValueError: + rest = [] + args = rest + if any(p.startswith("--from") for p in parts[1:]) or len(args) < 2: + continue + sources += [a for a in args[:-1] if "://" not in a] + return sources + + +def inputs_of(entry, dockerfile_text): + """(directories, files) whose change alters the image.""" + if entry["subpath"]: + return [entry["subpath"].rstrip("/")], [] + dirs = [str(pathlib.PurePosixPath(entry["dockerfile"]).parent)] + files = [s for s in copy_sources(dockerfile_text)] + return dirs, files + + +def _under(path, entry): + """True when path is the entry, below it (a directory), matches it (a glob) or entry is the root.""" + entry = entry.strip() + if entry in ("", ".", "./", "/"): + return True + entry = entry[2:] if entry.startswith("./") else entry + return (path == entry.rstrip("/") or path.startswith(entry.rstrip("/") + "/") + or fnmatch.fnmatchcase(path, entry)) + + +def touched(changed, dirs, files): + return [path for path in changed if any(_under(path, e) for e in [*dirs, *files])] + + +def check_pins(matrix, consumer_texts): + errors = [] + for fname, text in consumer_texts.items(): + for mention in ANY_PIN_RE.finditer(text): + if not PIN_RE.fullmatch(mention.group(0).rstrip("\"'")): + errors.append(f"{fname}: '{mention.group(0)}' is not a :@sha256:<64 hex> pin") + for m in PIN_RE.finditer(text): + name, version = m["name"], m["version"] + if name not in matrix: + errors.append(f"{fname}: image '{name}' is not in the matrix of {MATRIX_FILE}") + continue + try: + if parse_version(version) > parse_version(matrix[name]["version"]): + errors.append(f"{fname}: pin {name}:{version} is newer than the matrix version " + f"{matrix[name]['version']}") + except ValueError as exc: + errors.append(f"{fname}: {name}: {exc}") + return errors + + +def check_bump(base_matrix, head_matrix, changed, read_head_file): + errors = [] + 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 + 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 " + 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(): + old = base_matrix.get(name) + if old and parse_version(entry["version"]) < parse_version(old["version"]): + errors.append(f"image '{name}' version went backwards: {old['version']} -> {entry['version']}") + return errors + + +def git(*args): + return subprocess.run(["git", *args], capture_output=True, text=True, check=True).stdout + + +def main(argv): + if len(argv) >= 2 and argv[1] == "pins" and len(argv) == 2: + matrix = matrix_of(pathlib.Path(MATRIX_FILE).read_text()) + texts = {f: pathlib.Path(f).read_text() for f in CONSUMERS if pathlib.Path(f).exists()} + errors = check_pins(matrix, texts) + elif len(argv) == 3 and argv[1] == "bump": + base = git("merge-base", argv[2], "HEAD").strip() + changed = [p for p in git("diff", "--name-only", f"{base}", "HEAD").splitlines() if p] + try: + base_matrix = matrix_of(git("show", f"{base}:{MATRIX_FILE}")) + except subprocess.CalledProcessError: + base_matrix = {} + head_matrix = matrix_of(pathlib.Path(MATRIX_FILE).read_text()) + errors = check_bump(base_matrix, head_matrix, changed, lambda p: pathlib.Path(p).read_text()) + else: + sys.stderr.write(__doc__) + return 2 + for e in errors: + sys.stderr.write(f"::error::{e}\n") + if not errors: + print("image versions and pins: ok") + return 1 if errors else 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/tests/scripts/test_check_image_versions.py b/tests/scripts/test_check_image_versions.py new file mode 100644 index 0000000..b35c4b1 --- /dev/null +++ b/tests/scripts/test_check_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 check_image_versions as civ # noqa: E402 + +DIGEST = "sha256:" + "a" * 64 +IMAGE_YML = """\ +jobs: + image: + strategy: + matrix: + include: + - name: mol + version: {mol} + 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 ./\nCOPY --from=b /a /b\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_copy_sources_skip_from_stage(self): + self.assertEqual(civ.copy_sources(CI_DOCKERFILE), ["requirements-dev.txt", ".pre-commit-config.yaml"]) + + def test_copy_sources_json_form_and_directories(self): + self.assertEqual(civ.copy_sources('COPY ["a.txt", "b/", "/dst/"]\n'), ["a.txt", "b/"]) + self.assertEqual(civ.touched(["conf/x.cfg", "other"], [], ["conf/"]), ["conf/x.cfg"]) + self.assertEqual(civ.touched(["a.txt", "b.txt", "c.md"], [], ["*.txt"]), ["a.txt", "b.txt"]) + self.assertEqual(civ.touched(["anything"], [], ["."]), ["anything"]) + + def test_version_order(self): + self.assertGreater(civ.parse_version("0.10.0"), civ.parse_version("0.9.0")) + self.assertGreater(civ.parse_version("1.0.0"), civ.parse_version("1.0.0-rc.1")) + with self.assertRaises(ValueError): + civ.parse_version("1.0.0+build") + + def matrix(self, mol="0.1.0", ci="0.2.0"): + return civ.matrix_of(IMAGE_YML.format(mol=mol, ci=ci)) + + def test_pins_ok_and_lagging(self): + pin = f"image: git.rkdr.net/mortis/ci:0.1.0@{DIGEST}\n" + self.assertEqual(civ.check_pins(self.matrix(), {"lint.yml": pin}), []) + + def test_pin_ahead_of_matrix_unknown_image_and_malformed(self): + m = self.matrix() + self.assertEqual(len(civ.check_pins(m, {"f": f"git.rkdr.net/mortis/ci:0.3.0@{DIGEST}"})), 1) + self.assertEqual(len(civ.check_pins(m, {"f": f"git.rkdr.net/mortis/zzz:0.1.0@{DIGEST}"})), 1) + 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_bump_logic(self): + base, read = self.matrix(), lambda p: CI_DOCKERFILE + 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) + self.assertEqual(civ.check_bump(base, same, ["README.md", "images/other/x", ".gitea/workflows/lint.yml"], read), []) + self.assertEqual(civ.check_bump(base, self.matrix(ci="0.2.1"), ["requirements-dev.txt"], read), []) + self.assertTrue(civ.check_bump(base, self.matrix(ci="0.1.9"), [], read)) # backwards + + +class GitTest(unittest.TestCase): + """Run the script as CI does, in a throwaway repository.""" + + 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 bump(self): + proc = subprocess.run([sys.executable, str(SCRIPTS / "check_image_versions.py"), "bump", "main"], + cwd=self.repo, capture_output=True, text=True) + return proc.returncode, proc.stderr + + def test_unrelated_change_passes(self): + self.write("README.md", "x\n") + self.commit("docs") + self.assertEqual(self.bump()[0], 0) + + def test_pinned_input_without_bump_fails(self): + self.write("requirements-dev.txt", "a==2\n") + self.commit("deps") + code, err = self.bump() + self.assertEqual(code, 1) + self.assertIn("image 'ci'", err) + self.assertNotIn("image 'mol'", err) + + def test_pinned_input_with_bump_passes(self): + self.write("requirements-dev.txt", "a==2\n") + self.write(".gitea/workflows/image.yml", IMAGE_YML.format(mol="0.1.0", ci="0.2.1")) + self.commit("deps and bump") + self.assertEqual(self.bump()[0], 0) + + def test_dockerfile_change_of_molecule_image_fails(self): + self.write("images/mol/Dockerfile", "FROM y\n") + self.commit("mol") + code, err = self.bump() + self.assertEqual(code, 1) + self.assertIn("image 'mol'", err) + + def test_bump_survives_main_moving_on(self): + run(self.repo, "git", "checkout", "-q", "main") + self.write("README.md", "newer main\n") + self.commit("main moves") + run(self.repo, "git", "checkout", "-q", "feature") + self.write("images/mol/Dockerfile", "FROM y\n") + self.write(".gitea/workflows/image.yml", IMAGE_YML.format(mol="0.2.0", ci="0.2.0")) + self.commit("mol with bump") + self.assertEqual(self.bump()[0], 0) + + +if __name__ == "__main__": + unittest.main() From 8a0c5bf3dd4ee07308137934cb00d7a5dbdb9f08 Mon Sep 17 00:00:00 2001 From: Defame1297 Date: Sun, 25 Oct 2026 18:50:51 +0000 Subject: [PATCH 2/4] fix(ci): harden check_image_versions against renames, odd refs and parse errors Renamed or moved input files now count as touched (git diff --no-renames), so a rename can no longer hide a changed image input. The base ref must be a plain ref name and is passed after --end-of-options. Parse and git failures exit 1 with a one-line message instead of a traceback. Prerelease versions compare per semver (numeric identifiers numerically, numeric below alphanumeric). Whole-line YAML comments are ignored when looking for pins. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01MmzvM9skAvYcph2c9EiPcm --- scripts/check_image_versions.py | 81 ++++++++++++++++++---- tests/scripts/test_check_image_versions.py | 69 ++++++++++++++++++ 2 files changed, 136 insertions(+), 14 deletions(-) diff --git a/scripts/check_image_versions.py b/scripts/check_image_versions.py index f5de31b..cb16a01 100755 --- a/scripts/check_image_versions.py +++ b/scripts/check_image_versions.py @@ -36,23 +36,46 @@ 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.-]+)?$") +SEMVER_RE = re.compile(r"^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$") +# 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._/-]*$") + + +class CheckError(Exception): + """A failure to run the check (bad input, git failure); reported as one line, no traceback.""" def parse_version(text): m = SEMVER_RE.match(str(text)) if not m: raise ValueError(f"'{text}' is not MAJOR.MINOR.PATCH[-prerelease]") - # A prerelease sorts below its release. - return (int(m[1]), int(m[2]), int(m[3]), 0 if m[4] else 1, m[4] or "") + # Semver precedence: a prerelease sorts below its release; prerelease identifiers are + # compared left to right, numeric ones numerically, numeric below alphanumeric, and a + # shorter list below a longer one that starts the same. + ids = tuple((0, int(i), "") if i.isdigit() else (1, 0, i) for i in m[4].split(".")) if m[4] else () + return (int(m[1]), int(m[2]), int(m[3]), 0 if m[4] else 1, ids) def matrix_of(text): """Return {name: {version, subpath, dockerfile}} from the text of image.yml.""" - doc = yaml.safe_load(text) - entries = doc["jobs"]["image"]["strategy"]["matrix"]["include"] - return {e["name"]: {"version": str(e["version"]), "subpath": e.get("subpath") or "", - "dockerfile": e["dockerfile"]} for e in entries} + try: + doc = yaml.safe_load(text) + except yaml.YAMLError as exc: + raise CheckError(f"{MATRIX_FILE} is not valid YAML: {exc}") 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 + 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 + return matrix def copy_sources(dockerfile_text): @@ -98,9 +121,15 @@ def touched(changed, dirs, files): return [path for path in changed if any(_under(path, e) for e in [*dirs, *files])] +def without_comment_lines(text): + """Whole-line YAML comments may mention an image freely; trailing comments are kept.""" + return "\n".join(line for line in text.splitlines() if not line.lstrip().startswith("#")) + + def check_pins(matrix, consumer_texts): errors = [] for fname, text in consumer_texts.items(): + text = without_comment_lines(text) for mention in ANY_PIN_RE.finditer(text): if not PIN_RE.fullmatch(mention.group(0).rstrip("\"'")): errors.append(f"{fname}: '{mention.group(0)}' is not a :@sha256:<64 hex> pin") @@ -143,25 +172,49 @@ def check_bump(base_matrix, head_matrix, changed, read_head_file): def git(*args): - return subprocess.run(["git", *args], capture_output=True, text=True, check=True).stdout + try: + return subprocess.run(["git", *args], capture_output=True, text=True, check=True).stdout + 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 -def main(argv): +def run(argv): if len(argv) >= 2 and argv[1] == "pins" and len(argv) == 2: matrix = matrix_of(pathlib.Path(MATRIX_FILE).read_text()) texts = {f: pathlib.Path(f).read_text() for f in CONSUMERS if pathlib.Path(f).exists()} errors = check_pins(matrix, texts) elif len(argv) == 3 and argv[1] == "bump": - base = git("merge-base", argv[2], "HEAD").strip() - changed = [p for p in git("diff", "--name-only", f"{base}", "HEAD").splitlines() if p] + 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. + changed = [p for p in git("diff", "--name-only", "--no-renames", "--end-of-options", base, "HEAD") + .splitlines() if p] try: - base_matrix = matrix_of(git("show", f"{base}:{MATRIX_FILE}")) - except subprocess.CalledProcessError: - base_matrix = {} + base_text = git("show", f"{base}:{MATRIX_FILE}") + except CheckError: + base_text = None # no matrix at the base: every image is new + base_matrix = matrix_of(base_text) if base_text is not None else {} head_matrix = matrix_of(pathlib.Path(MATRIX_FILE).read_text()) errors = check_bump(base_matrix, head_matrix, changed, lambda p: pathlib.Path(p).read_text()) else: sys.stderr.write(__doc__) + return None + return errors + + +def main(argv): + try: + errors = run(argv) + except CheckError as exc: + errors = [str(exc)] + except ValueError as exc: # parse_version + errors = [f"cannot parse a version: {exc}"] + except OSError as exc: + errors = [f"cannot read a file: {exc}"] + if errors is None: return 2 for e in errors: sys.stderr.write(f"::error::{e}\n") diff --git a/tests/scripts/test_check_image_versions.py b/tests/scripts/test_check_image_versions.py index b35c4b1..5083f15 100644 --- a/tests/scripts/test_check_image_versions.py +++ b/tests/scripts/test_check_image_versions.py @@ -52,6 +52,24 @@ class PureTest(unittest.TestCase): with self.assertRaises(ValueError): civ.parse_version("1.0.0+build") + def test_prerelease_precedence_per_semver(self): + order = ["1.0.0-alpha", "1.0.0-alpha.1", "1.0.0-alpha.beta", "1.0.0-beta", "1.0.0-beta.2", + "1.0.0-beta.11", "1.0.0-rc.1", "1.0.0"] + keys = [civ.parse_version(v) for v in order] + self.assertEqual(keys, sorted(keys)) + self.assertEqual(len(set(keys)), len(keys)) + self.assertLess(civ.parse_version("1.0.0-2"), civ.parse_version("1.0.0-10")) + self.assertLess(civ.parse_version("1.0.0-9"), civ.parse_version("1.0.0-a")) + with self.assertRaises(ValueError): + civ.parse_version("1.0.0-a..b") + + def test_whole_line_comments_are_not_pins(self): + m = self.matrix() + text = f"# was git.rkdr.net/mortis/zzz:0.1.0@{DIGEST}\n # see git.rkdr.net/mortis/ci:9.9.9\n" + self.assertEqual(civ.check_pins(m, {"f": text}), []) + both = text + f"image: git.rkdr.net/mortis/zzz:0.1.0@{DIGEST} # trailing\n" + self.assertEqual(len(civ.check_pins(m, {"f": both})), 1) + def matrix(self, mol="0.1.0", ci="0.2.0"): return civ.matrix_of(IMAGE_YML.format(mol=mol, ci=ci)) @@ -108,6 +126,57 @@ class GitTest(unittest.TestCase): cwd=self.repo, capture_output=True, text=True) 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) + return proc.returncode, proc.stderr + + def assert_clean_failure(self, result, text): + code, err = result + self.assertEqual(code, 1, err) + self.assertNotIn("Traceback", err) + self.assertIn(text, err) + self.assertEqual(len(err.strip().splitlines()), 1, err) + + def test_moved_input_out_of_the_set_fails(self): + run(self.repo, "git", "mv", "images/mol/Dockerfile", "elsewhere.dockerfile") + self.commit("move out") + code, err = self.bump() + self.assertEqual(code, 1) + self.assertIn("image 'mol'", err) + + def test_renamed_pinned_input_fails(self): + run(self.repo, "git", "mv", "requirements-dev.txt", "req2.txt") + self.commit("rename") + code, err = self.bump() + self.assertEqual(code, 1) + self.assertIn("image 'ci'", err) + + def test_option_like_base_ref_is_rejected(self): + for ref in ("--output=/tmp/x", "-h", "a b", "main\n"): + self.assert_clean_failure(self.bump_args("bump", ref), "not a plain ref name") + + def test_unknown_base_ref_is_one_line(self): + self.assert_clean_failure(self.bump_args("bump", "nope"), "git merge-base failed") + + 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") + self.assert_clean_failure(self.bump(), "'latest' is not MAJOR.MINOR.PATCH") + + def test_missing_matrix_keys_is_one_line(self): + self.write(".gitea/workflows/image.yml", IMAGE_YML.replace(" version: {mol}\n", "") + .format(mol="", ci="0.2.0")) + self.commit("no version") + self.assert_clean_failure(self.bump(), "lacks the key") + self.write(".gitea/workflows/image.yml", "jobs: {}\n") + self.commit("no matrix") + self.assert_clean_failure(self.bump(), "no jobs.image.strategy.matrix.include") + + def test_pins_mode_missing_matrix_file_is_one_line(self): + run(self.repo, "git", "rm", "-q", ".gitea/workflows/image.yml") + self.assert_clean_failure(self.bump_args("pins"), "cannot read a file") + def test_unrelated_change_passes(self): self.write("README.md", "x\n") self.commit("docs") From 4fabe1358ef4825dbdda628a955fa370b06251da Mon Sep 17 00:00:00 2001 From: Defame1297 Date: Sun, 25 Oct 2026 19:16:30 +0000 Subject: [PATCH 3/4] 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") From c3cd04e0131b77b03729c29d3d073489c3f1af02 Mon Sep 17 00:00:00 2001 From: Defame1297 Date: Sun, 25 Oct 2026 19:54:28 +0000 Subject: [PATCH 4/4] fix(ci): make the image pin check fail closed on odd spellings and Dockerfile sources Pin mentions are matched case-insensitively with an optional port, a nested path and no tag, so a mis-spelled or untagged pin is reported instead of ignored. The Dockerfile COPY/ADD reader raises an error naming file and line on a source with a variable, quote or comment character and on a RUN --mount of the build context, and joins continuation lines with trailing blanks. A non-UTF-8 diff path and an empty image.yml get their own messages, lint.yml is a required consumer, the success line lists the consumers checked, and the docstring states the known limits. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01MmzvM9skAvYcph2c9EiPcm --- .../fragments/image-version-and-pin-check.yml | 4 + scripts/check_image_versions.py | 127 +++++++++++++++--- tests/scripts/test_check_image_versions.py | 93 +++++++++++++ 3 files changed, 204 insertions(+), 20 deletions(-) diff --git a/changelogs/fragments/image-version-and-pin-check.yml b/changelogs/fragments/image-version-and-pin-check.yml index 10bc10d..a462d1e 100644 --- a/changelogs/fragments/image-version-and-pin-check.yml +++ b/changelogs/fragments/image-version-and-pin-check.yml @@ -3,3 +3,7 @@ trivial: Add scripts/check_image_versions.py and its tests, and run them in the Lint workflow: image pins must name an image of the build matrix, and a pull request that changes an image's inputs must bump its version. + - >- + scripts/check_image_versions.py reports a pin written in any case, with a port, in a nested path or without a tag; fails closed (naming + file and line) on a Dockerfile COPY source with a variable, quote or comment character and on a RUN --mount of the build context; says so + for a non-UTF-8 diff path and an empty image.yml; requires lint.yml and lists the consumer files it checked. diff --git a/scripts/check_image_versions.py b/scripts/check_image_versions.py index 56fd7a9..d514485 100644 --- a/scripts/check_image_versions.py +++ b/scripts/check_image_versions.py @@ -28,6 +28,16 @@ Known limits: 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. + * Renaming an image in the matrix in the same PR skips the bump check for it (the new + name has no base entry); the pins check still catches a consumer pin left on the old + name, because that name is no longer in the matrix. + * Of the consumer files, only lint.yml is required (it runs this check); build.yml and + molecule.yml are skipped when absent, and the success line lists the files that were + actually checked, so a consumer that vanished is visible. + * Duplicate YAML keys inside a matrix entry are accepted (PyYAML keeps the last one). + * The Dockerfile COPY/ADD reader is not a Dockerfile parser: it fails closed (an error + naming the file and line) on a source with `$`, a quote or `#`, and on a RUN + --mount bind of the build context, instead of guessing which files are inputs. """ import fnmatch import json @@ -39,10 +49,16 @@ import sys import yaml MATRIX_FILE = ".gitea/workflows/image.yml" -CONSUMERS = [".gitea/workflows/lint.yml", ".gitea/workflows/build.yml", ".gitea/workflows/molecule.yml"] +REQUIRED_CONSUMER = ".gitea/workflows/lint.yml" # runs this check; its absence is an error +CONSUMERS = [REQUIRED_CONSUMER, ".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})") -# 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,)\]}'"]*""") +# A mention of the registry's mortis namespace in any spelling: host in any case, optional +# :port, any case or nested path, tagged or not. It ends at whitespace, quotes or closing +# punctuation, so a pin followed by `,` `)` `]` `}` parses. Not a mention: a URL +# (https://git.rkdr.net/mortis/kamino) or an SSH remote (git@git.rkdr.net). +ANY_PIN_RE = re.compile( + r"""(?= 2 and argv[1] == "pins" and len(argv) == 2: matrix = matrix_of(pathlib.Path(MATRIX_FILE).read_text()) + if not pathlib.Path(REQUIRED_CONSUMER).exists(): + raise CheckError(f"{REQUIRED_CONSUMER} is missing: it runs this check and is a required consumer") texts = {f: pathlib.Path(f).read_text() for f in CONSUMERS if pathlib.Path(f).exists()} errors = check_pins(matrix, texts) + note = " (checked: " + ", ".join(texts) + ")" 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 '-')") @@ -220,8 +296,15 @@ def run(argv): # 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 = [p for p in git("-c", "core.quotePath=false", "diff", "--name-only", "-z", "--no-renames", - "--end-of-options", base, "HEAD").split("\0") if p] + 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 try: base_text = git("show", f"{base}:{MATRIX_FILE}") except CheckError: @@ -229,17 +312,21 @@ def run(argv): base_matrix = matrix_of(base_text) if base_text is not None else {} head_matrix = matrix_of(pathlib.Path(MATRIX_FILE).read_text()) errors = check_bump(base_matrix, head_matrix, changed, lambda p: pathlib.Path(p).read_text()) + note = "" else: sys.stderr.write(__doc__) - return None - return errors + return None, "" + return errors, note def main(argv): + note = "" try: - errors = run(argv) + errors, note = run(argv) except CheckError as exc: errors = [str(exc)] + except UnicodeDecodeError as exc: # before ValueError, which it subclasses + errors = [f"a file is not valid UTF-8: {exc}"] except ValueError as exc: # parse_version errors = [f"cannot parse a version: {exc}"] except OSError as exc: @@ -249,7 +336,7 @@ def main(argv): for e in errors: sys.stderr.write(f"::error::{e}\n") if not errors: - print("image versions and pins: ok") + print(f"image versions and pins: ok{note}") return 1 if errors else 0 diff --git a/tests/scripts/test_check_image_versions.py b/tests/scripts/test_check_image_versions.py index c7eea34..877eac5 100644 --- a/tests/scripts/test_check_image_versions.py +++ b/tests/scripts/test_check_image_versions.py @@ -84,6 +84,67 @@ 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_pin_spellings_are_reported(self): + m = self.matrix() + spellings = [ + f"Git.rkdr.net/mortis/ci:0.1.0@{DIGEST}", + f"git.rkdr.net/Mortis/ci:0.1.0@{DIGEST}", + f"git.rkdr.net:443/mortis/ci:0.1.0@{DIGEST}", + f"git.rkdr.net/mortis/ci/sub:0.1.0@{DIGEST}", + f"GIT.RKDR.NET/mortis/CI:0.1.0@{DIGEST}", + "git.rkdr.net/mortis/ci", + "git.rkdr.net/mortis/ci:0.1.0", + ] + for spelling in spellings: + errors = civ.check_pins(m, {"f": f"image: {spelling}\n"}) + self.assertEqual(len(errors), 1, f"{spelling}: {errors}") + self.assertIn("not a :@sha256", errors[0]) + valid = f"image: git.rkdr.net/mortis/ci:0.1.0@{DIGEST}\n" + self.assertEqual(civ.check_pins(m, {"f": valid}), []) + + def test_urls_and_ssh_remotes_are_not_pin_mentions(self): + m = self.matrix() + text = ("url: https://git.rkdr.net/mortis/kamino\nurl2: http://git.rkdr.net/mortis/kamino.git\n" + "ssh: git@git.rkdr.net:mortis/kamino.git\n") + self.assertEqual(civ.check_pins(m, {"f": text}), []) + + def test_copy_source_fails_closed(self): + cases = { + "COPY $FILE /dst/\n": "'$'", + 'COPY "a b" /dst/\n': "'\"'", + "COPY 'a' /dst/\n": "\"'\"", + "COPY a#b /dst/\n": "'#'", + 'COPY ["$X", "/dst/"]\n': "'$'", + "COPY [\"a\", unquoted]\n": "JSON form", + "RUN --mount=type=bind,source=src,target=/s make\n": "RUN --mount binds the build context", + "RUN --mount=source=src,target=/s make\n": "RUN --mount binds the build context", + "FROM x\nRUN --mount=type=bind,target=/s \\\n make\n": "Dockerfile:2:", + } + for text, expected in cases.items(): + with self.assertRaises(civ.CheckError, msg=text) as ctx: + civ.copy_sources(text, "images/ci/Dockerfile") + message = str(ctx.exception) + self.assertIn(expected, message, text) + self.assertIn("images/ci/Dockerfile:", message) + self.assertNotIn("\n", message) + + def test_copy_source_ok_cases_still_pass(self): + ok = ("RUN --mount=type=cache,target=/c make\nRUN --mount=type=bind,from=b,source=/x,target=/y make\n" + "# COPY $IGNORED /x\nCOPY --chown=1:1 a b/ /dst/\nCOPY https://example.org/x /dst/\n") + self.assertEqual(civ.copy_sources(ok), ["a", "b/"]) + + def test_continuation_with_trailing_blanks_is_joined(self): + text = "COPY a.txt \\ \n b.txt /dst/\n" + self.assertEqual(civ.copy_sources(text), ["a.txt", "b.txt"]) + text = "COPY a.txt \\\n# a comment\n b.txt /dst/\n" + self.assertEqual(civ.copy_sources(text), ["a.txt", "b.txt"]) + + def test_empty_or_non_mapping_matrix_file(self): + for text in ("", "# only a comment\n", "- a\n- b\n", "just a string\n"): + with self.assertRaises(civ.CheckError, msg=repr(text)) as ctx: + civ.matrix_of(text) + self.assertIn("image.yml is empty or not a mapping", str(ctx.exception)) + 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)): @@ -229,6 +290,38 @@ class GitTest(unittest.TestCase): self.assertIn("image 'mol'", err) self.assertIn("caf\u00e9", err) + def test_non_utf8_path_in_the_diff_is_named(self): + path = os.fsencode(str(self.repo)) + b"/images/mol/caf\xe9" + try: + with open(path, "wb") as handle: + handle.write(b"x\n") + except OSError: + self.skipTest("the file system does not accept a non-UTF-8 name") + self.commit("non-utf8 input") + self.assert_clean_failure(self.bump(), "path is not valid UTF-8") + + def test_empty_image_yml_says_so(self): + self.write(".gitea/workflows/image.yml", "") + self.commit("empty matrix") + self.assert_clean_failure(self.bump(), "image.yml is empty or not a mapping") + + def test_unsupported_dockerfile_source_fails_with_file_and_line(self): + self.write("images/ci/Dockerfile", "FROM x\nCOPY $SRC ./\n") + self.commit("variable source") + self.assert_clean_failure(self.bump(), "images/ci/Dockerfile:2:") + + def test_pins_mode_requires_lint_yml_and_lists_checked_consumers(self): + proc = subprocess.run([sys.executable, str(SCRIPTS / "check_image_versions.py"), "pins"], + cwd=self.repo, capture_output=True, text=True, check=False) + self.assertEqual(proc.returncode, 1, proc.stdout) + self.assertIn("lint.yml is missing", proc.stderr) + self.write(".gitea/workflows/lint.yml", f"image: git.rkdr.net/mortis/ci:0.1.0@{DIGEST}\n") + proc = subprocess.run([sys.executable, str(SCRIPTS / "check_image_versions.py"), "pins"], + cwd=self.repo, capture_output=True, text=True, check=False) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertIn("(checked: .gitea/workflows/lint.yml)", proc.stdout) + self.assertNotIn("build.yml", proc.stdout) + def test_unrelated_change_passes(self): self.write("README.md", "x\n") self.commit("docs")