# 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 DIGEST = "sha256:" + "a" * 64 JOB = f"ubuntu:24.04@{DIGEST}" IMAGE_YML = ( """\ jobs: image: strategy: matrix: include: - name: mol version: {mol} subpath: images/mol dockerfile: Dockerfile job_image: """ + JOB + """ - name: ci version: {ci} subpath: "" dockerfile: images/ci/Dockerfile job_image: """ + JOB + """ container: image: ${{{{ matrix.job_image }}}} """ ) CI_DOCKERFILE = f"FROM {JOB} AS b\nCOPY requirements-dev.txt .pre-commit-config.yaml ./\nCOPY --from=b /a /b\n" def labelled(name, body=""): """A Dockerfile text with the labels check_image_metadata requires.""" values = {key: "x" for key in civ.REQUIRED_LABELS} values["org.opencontainers.image.title"] = name values["org.opencontainers.image.source"] = "https://example.org" values["org.opencontainers.image.documentation"] = ( f"https://example.org/src/branch/main/docs/images/{name}.md" ) values["org.opencontainers.image.base.name"] = "ubuntu:24.04" return ( f"FROM {JOB}\nLABEL " + " \\\n ".join(f'{k}="{v}"' for k, v in values.items()) + "\n" + body ) 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 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)) def test_foreign_production_images_are_denied(self): for text in ( "image: git.rkdr.net/defame1297/gitea-ansible-runner:1@sha256:" + "a" * 64, "# GIT.RKDR.NET:443/Defame1297/x", "image: git.rkdr.net/defame1297/y", ): self.assertEqual(len(civ.check_foreign_images({"w.yml": text})), 1, text) for text in ( "image: git.rkdr.net/mortis/ci:0.2.0", "https://git.rkdr.net/defame1297x", "see Defame1297/ansible-homelab-mono", ): self.assertEqual(civ.check_foreign_images({"w.yml": text}), [], text) 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_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( "no jobs.image.strategy.matrix.include list", 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)): 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(body): return ( "jobs:\n image:\n strategy:\n matrix:\n include:\n" + body ) entry = " - name: a\n version: '0.1.0'\n dockerfile: D\n" cases = { "": "non-empty list", " []\n": "non-empty block list", " - 1\n": "not a mapping", " - name: 1\n version: '0.1.0'\n dockerfile: D\n": "name must be a non-empty string", entry + " subpath: [x]\n": "cannot read the value", entry.replace("'0.1.0'", "0.1") + "": "version must be a string", entry + entry: "duplicate image name 'a'", entry + " version: '0.2.0'\n": "duplicate key 'version'", entry.replace( "version: '0.1.0'", "version: *anchor" ): "cannot read the value", entry.replace( "version: '0.1.0'", 'version: "0\\x2e1.0"' ): "cannot read the quoted value", entry.replace( " - name: a\n", " - name: ''\n" ): "name must be a non-empty string", " - name: a\n dockerfile: D\n": "lacks the key 'version'", } for body, text in cases.items(): with self.assertRaises(civ.CheckError, msg=body) as ctx: civ.matrix_of(doc(body)) self.assertIn(text, str(ctx.exception), body) self.assertNotIn("\n", str(ctx.exception)) self.assertEqual( civ.matrix_of(doc(entry + " subpath:\n"))["a"]["subpath"], "" ) with self.assertRaises(civ.CheckError) as ctx: civ.matrix_of("jobs: [unclosed\n") self.assertNotIn("\n", str(ctx.exception)) def test_matrix_reader_accepts_comments_quotes_and_key_order(self): text = IMAGE_YML.format(mol="0.1.0", ci="0.2.0") text = text.replace( " - name: ci\n version: 0.2.0\n", ' # the ci image\n - version: "0.2.0" # bumped by the bot\n' " name: ci\n", ) self.assertEqual(civ.matrix_of(text)["ci"]["version"], "0.2.0") self.assertEqual(civ.matrix_of(text)["mol"]["subpath"], "images/mol") def test_matrix_reader_agrees_with_pyyaml_on_the_real_file(self): # The reader replaces PyYAML in the Renovate image (which has none); here PyYAML is the oracle. import yaml real = ( pathlib.Path(__file__).resolve().parents[2] / civ.MATRIX_FILE ).read_text() want = { e["name"]: { "version": e["version"], "subpath": e.get("subpath") or "", "dockerfile": e["dockerfile"], "job_image": e["job_image"], } for e in yaml.safe_load(real)["jobs"]["image"]["strategy"]["matrix"][ "include" ] } self.assertEqual(civ.matrix_of(real), want) self.assertEqual( civ.matrix_of(IMAGE_YML.format(mol="0.1.0", ci="0.2.0")), { e["name"]: { "version": e["version"], "subpath": e.get("subpath") or "", "dockerfile": e["dockerfile"], "job_image": e["job_image"], } for e in yaml.safe_load(IMAGE_YML.format(mol="0.1.0", ci="0.2.0"))[ "jobs" ]["image"]["strategy"]["matrix"]["include"] }, ) def test_job_image_must_match_the_dockerfile_release(self): text = IMAGE_YML.format(mol="0.1.0", ci="0.2.0") matrix = civ.matrix_of(text) files = { "images/mol/Dockerfile": f"FROM {JOB}\n", "images/ci/Dockerfile": f"FROM {JOB} AS os\nFROM os AS build\nFROM os AS final\n", } def read(path): return files[path] self.assertEqual(civ.check_job_images(matrix, read, text), []) files["images/ci/Dockerfile"] = ( f"FROM ubuntu:26.04@{DIGEST} AS os\nFROM os AS final\n" ) errors = civ.check_job_images(matrix, read, text) self.assertEqual(len(errors), 1) self.assertIn( "builds on ubuntu:26.04 but its job_image is ubuntu:24.04", errors[0] ) files["images/ci/Dockerfile"] = "FROM debian:12\n" self.assertIn( "FROM debian:12 is not an Ubuntu base", civ.check_job_images(matrix, read, text)[0], ) files["images/ci/Dockerfile"] = f"FROM {JOB} AS os\n" self.assertEqual( civ.check_job_images( matrix, read, text.replace("matrix.job_image", "matrix.other") ), [ ( ".gitea/workflows/image.yml: the job container must be " "`image: ${{ matrix.job_image }}`" ) ], ) def test_job_image_shape_and_missing_key(self): text = IMAGE_YML.format(mol="0.1.0", ci="0.2.0") for bad in ( text.replace(f"job_image: {JOB}", "job_image: ubuntu:latest", 1), text.replace(f" job_image: {JOB}\n", "", 1), ): errors = civ.check_job_images( civ.matrix_of(bad), lambda path: f"FROM {JOB}\n", bad ) self.assertEqual(len(errors), 1, errors) self.assertIn( "job_image in .gitea/workflows/image.yml must be ubuntu:@sha256:", errors[0], ) def test_dockerfile_releases_fail_closed(self): digest = DIGEST cases = { f"FROM --platform=linux/amd64 ubuntu:26.04@{digest} AS a\nFROM a AS b\n": ( ["26.04"], 0, ), f"FROM docker.io/library/ubuntu:24.04@{digest}\n": (["24.04"], 0), "FROM ubuntu:24.04 AS ubuntu\nFROM ubuntu AS x\n": (["24.04"], 0), "FROM golang:1.22 AS b\nFROM ubuntu:24.04\n": (["24.04"], 1), "ARG B=ubuntu:26.04\nFROM ubuntu:24.04 AS a\nFROM ${B} AS b\n": ( ["24.04"], 1, ), "FROM ubuntu:${REL}\n": ([], 1), "FROM ubuntu:24.04\nRUN <