diff --git a/tests/external/update/docker/test_image_reachable.py b/tests/external/update/docker/test_image_reachable.py index 9065c44535..362d1e5ec9 100644 --- a/tests/external/update/docker/test_image_reachable.py +++ b/tests/external/update/docker/test_image_reachable.py @@ -17,6 +17,7 @@ import unittest from utils.annotations.message import warning from utils.docker.image.discovery import iter_role_images, load_yaml +from utils.docker.image.pin import pull_reference from utils.docker.registry import manifest_exists from utils.roles.mapping import ROLE_FILE_META_SERVICES from utils.update.base import resolve_max_fetch_workers @@ -28,6 +29,10 @@ def _pull_image(ref) -> str: return ref.name if ref.registry == "docker.io" else f"{ref.registry}/{ref.name}" +def _display(ref) -> str: + return pull_reference(_pull_image(ref), ref.version) + + class TestDockerImageReachable(unittest.TestCase): """Fail on any pinned Docker image:version tag the registry reports absent.""" @@ -57,7 +62,7 @@ class TestDockerImageReachable(unittest.TestCase): for ref in indeterminate: warning( - f"{ref.role}/{ref.service}: {_pull_image(ref)}:{ref.version} " + f"{ref.role}/{ref.service}: {_display(ref)} " f"could not be verified (network / auth / rate-limit)", title="šŸ” Unverified Docker image", file=f"roles/{ref.role}/{ROLE_FILE_META_SERVICES}", @@ -65,12 +70,12 @@ class TestDockerImageReachable(unittest.TestCase): if missing: lines = "\n".join( - f" {ref.role}/{ref.service}: {_pull_image(ref)}:{ref.version}" + f" {ref.role}/{ref.service}: {_display(ref)}" for ref in sorted(missing, key=lambda r: (r.role, r.service)) ) self.fail( - "These pinned Docker image:version tags do not exist in their " - f"registry (HTTP 404):\n{lines}" + "These pinned Docker images do not exist in their registry " + f"(HTTP 404):\n{lines}" ) def test_incomplete_image_version_pairs_warn(self) -> None: diff --git a/tests/lint/ansible/services/test_semver_pinning.py b/tests/lint/ansible/services/test_semver_pinning.py index 07e1df230e..c09544eda9 100644 --- a/tests/lint/ansible/services/test_semver_pinning.py +++ b/tests/lint/ansible/services/test_semver_pinning.py @@ -59,6 +59,7 @@ from utils.annotations.message import warning as gha_warning from utils.annotations.suppress import is_suppressed_at from utils.cache.files import read_text from utils.cache.yaml import load_yaml_any +from utils.docker.image.pin import is_digest from utils.roles.mapping import ROLE_FILE_META_SERVICES from utils.update.base import is_semver @@ -69,6 +70,7 @@ if TYPE_CHECKING: _DOCKER_RULE = "docker-version" +_DIGEST_RULE = "docker-digest" _REPO_RULE = "repository-version" _DOCKER_TITLE = "Non-semver Docker image version" @@ -176,7 +178,7 @@ class TestSemverPinning(unittest.TestCase): line_no = _locate_value_line( lines, "version", value, used_version_lines ) - rule = _DOCKER_RULE + rule = _DIGEST_RULE if is_digest(value) else _DOCKER_RULE title = _DOCKER_TITLE category: type[Warning] = NonSemverImageVersionWarning key_label = "version" @@ -208,10 +210,10 @@ class TestSemverPinning(unittest.TestCase): if findings_emitted: print( - "\nšŸ’” Non-semver pins: suppress with " - "'# nocheck: docker-version' (above or on the `version:` line) " - "or '# nocheck: repository-version' (above or on the `ref:` " - "line) when the non-semver pin is intentional.", + "\nšŸ’” Non-semver pins: a digest is the preferred fallback and " + "declares itself with '# nocheck: docker-digest'; a general " + "tag uses '# nocheck: docker-version' and a general git ref " + "'# nocheck: repository-version', above or on the pinned line.", flush=True, ) diff --git a/tests/unit/python/utils/docker/test_image_pin.py b/tests/unit/python/utils/docker/test_image_pin.py new file mode 100644 index 0000000000..1b7b7e949f --- /dev/null +++ b/tests/unit/python/utils/docker/test_image_pin.py @@ -0,0 +1,88 @@ +from __future__ import annotations + +import unittest + +from utils.docker.image.discovery import docker_hub_source, image_source +from utils.docker.image.pin import ( + DIGEST, + REF, + RULE_BY_CLASS, + SEMVER, + is_digest, + pin_class, + pull_reference, + reference_separator, +) + +DIGEST_VALUE = "sha256:d5591131b1d898cd02fc7a17adb8ea026352d67809bc9289707778e9e03a76a4" + + +class TestPinClass(unittest.TestCase): + def test_a_semver_tag_is_a_semver_pin(self): + for value in ("3.0.1", "16", "17-3.5", "5.4.5-php8.3-apache", "v1.12.27"): + self.assertEqual(pin_class(value), SEMVER, value) + + def test_a_content_address_is_a_digest_pin(self): + self.assertEqual(pin_class(DIGEST_VALUE), DIGEST) + + def test_a_moving_name_is_neither(self): + for value in ("latest", "main", "stable", "buildx-stable-1"): + self.assertEqual(pin_class(value), REF, value) + + def test_surrounding_whitespace_does_not_change_the_class(self): + self.assertEqual(pin_class(f" {DIGEST_VALUE} "), DIGEST) + self.assertEqual(pin_class(" 3.0.1 "), SEMVER) + + def test_every_class_has_its_own_rule(self): + rules = [RULE_BY_CLASS[SEMVER], RULE_BY_CLASS[DIGEST], RULE_BY_CLASS[REF]] + + self.assertEqual(len(set(rules)), 3, "a shared rule cannot express intent") + self.assertEqual(rules, ["docker-version", "docker-digest", "docker-ref"]) + + +class TestPullReference(unittest.TestCase): + def test_a_digest_is_joined_with_an_at_sign(self): + self.assertEqual(reference_separator(DIGEST_VALUE), "@") + self.assertEqual( + pull_reference("ghcr.io/owner/app", DIGEST_VALUE), + f"ghcr.io/owner/app@{DIGEST_VALUE}", + ) + + def test_a_tag_is_joined_with_a_colon(self): + self.assertEqual(reference_separator("3.0.1"), ":") + self.assertEqual(pull_reference("ghcr.io/owner/app", "3.0.1"), "ghcr.io/owner/app:3.0.1") + + def test_is_digest_rejects_a_tag_that_merely_mentions_sha256(self): + self.assertFalse(is_digest("v2-sha256:abc")) + + +class TestSourceKeepsTheDigest(unittest.TestCase): + """A pull ref that silently drops the digest pins nothing at all.""" + + def test_image_source_keeps_a_digest(self): + self.assertEqual( + image_source("ghcr.io/owner/app", DIGEST_VALUE), + f"ghcr.io/owner/app@{DIGEST_VALUE}", + ) + + def test_image_source_still_tags_a_semver(self): + self.assertEqual(image_source("ghcr.io/owner/app", "3.0.1"), "ghcr.io/owner/app:3.0.1") + + def test_docker_hub_source_keeps_a_digest(self): + self.assertEqual( + docker_hub_source("postgres", DIGEST_VALUE), + f"docker.io/library/postgres@{DIGEST_VALUE}", + ) + + def test_a_digest_never_yields_a_tag_separator(self): + source = image_source("quay.io/owner/app", DIGEST_VALUE) + + self.assertNotIn( + f":{DIGEST_VALUE}", + source, + "a colon here would make the registry read the digest as a tag name", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/utils/docker/image/discovery.py b/utils/docker/image/discovery.py index c569aed7c1..559003e0e7 100644 --- a/utils/docker/image/discovery.py +++ b/utils/docker/image/discovery.py @@ -4,6 +4,7 @@ from dataclasses import dataclass from typing import TYPE_CHECKING from utils.cache.yaml import load_yaml_any as _load_yaml_cached +from utils.docker.image.pin import pull_reference from utils.roles.mapping import ROLE_FILE_META_SERVICES if TYPE_CHECKING: @@ -146,7 +147,7 @@ def docker_hub_source(image: str, version: str) -> str: if "/" not in base: base = f"library/{base}" - return f"docker.io/{base}:{version}" + return pull_reference(f"docker.io/{base}", version) def image_source(image: str, version: str) -> str: @@ -166,7 +167,7 @@ def image_source(image: str, version: str) -> str: if registry == "docker.io" and "/" not in base: base = f"library/{base}" - return f"{registry}/{base}:{version}" + return pull_reference(f"{registry}/{base}", version) def canonical_image_name(image: str) -> str: diff --git a/utils/docker/image/pin.py b/utils/docker/image/pin.py new file mode 100644 index 0000000000..4ddfce88e5 --- /dev/null +++ b/utils/docker/image/pin.py @@ -0,0 +1,59 @@ +from utils.update.base import version_depth + +DIGEST_PREFIX = "sha256:" + +SEMVER = "semver" +DIGEST = "digest" +REF = "ref" + +RULE_BY_CLASS = { + SEMVER: "docker-version", + DIGEST: "docker-digest", + REF: "docker-ref", +} + + +def is_digest(version: str) -> bool: + """Whether ``version`` pins by content rather than by name. + + Args: + version: the ``version:`` value a role declares for an image. + """ + return str(version).strip().startswith(DIGEST_PREFIX) + + +def pin_class(version: str) -> str: + """Classify a pin as ``semver``, ``digest`` or ``ref``. + + Args: + version: the ``version:`` value a role declares for an image. + + Returns: + The class name. ``ref`` is the residue: a tag that names no version + the registry can order, so nothing can tell whether it moved. + """ + stripped = str(version).strip() + if is_digest(stripped): + return DIGEST + if version_depth(stripped) > 0: + return SEMVER + return REF + + +def reference_separator(version: str) -> str: + """The character that joins an image name to ``version`` in a pull ref. + + Args: + version: the ``version:`` value a role declares for an image. + """ + return "@" if is_digest(version) else ":" + + +def pull_reference(name: str, version: str) -> str: + """Join an image name and a pin into the reference a registry accepts. + + Args: + name: image name, with or without a registry prefix. + version: the ``version:`` value a role declares for an image. + """ + return f"{name}{reference_separator(version)}{str(version).strip()}"