# SPDX-FileCopyrightText: Defame1297 and contributors # SPDX-License-Identifier: GPL-3.0-or-later """Choose the version an image build publishes, or none. python3 scripts/next_image_version.py Prints " " when the image's inputs differ from the newest published .N (its input-checksum label), and nothing when they match. """ import hashlib import json import os import pathlib import re import sys import urllib.error import urllib.parse import urllib.request import check_image_versions as civ def input_checksum(root, entry): """sha256 over the path, executable bit and content of every input file of the image.""" root = pathlib.Path(root) context = root / entry["subpath"] if entry["subpath"] else root dockerfile = (context / entry["dockerfile"]).read_text(encoding="utf-8") dirs, files = civ.inputs_of(entry, dockerfile) paths = sorted( p.relative_to(root).as_posix() for p in root.rglob("*") if (p.is_file() or p.is_symlink()) and ".git" not in p.relative_to(root).parts ) digest = hashlib.sha256() for path in civ.touched(paths, dirs, files): full = root / path if full.is_symlink(): kind, body = "l", os.readlink(full).encode() else: kind, body = ("x" if os.access(full, os.X_OK) else "f"), full.read_bytes() digest.update(f"{path}\0{kind}\0{hashlib.sha256(body).hexdigest()}\n".encode()) return digest.hexdigest() def next_version(base, tags, checksum, label_of): """The next .N, or None when the newest one was built from these inputs.""" patches = [ int(m[1]) for t in tags if (m := re.fullmatch(re.escape(base) + r"\.(0|[1-9][0-9]*)", t)) ] if not patches: return f"{base}.0" newest = max(patches) if label_of(f"{base}.{newest}") == checksum: return None return f"{base}.{newest + 1}" LABEL = "net.rkdr.mortis.inputs-sha256" MANIFEST_TYPES = ( "application/vnd.oci.image.manifest.v1+json", "application/vnd.docker.distribution.manifest.v2+json", ) # Bot filters in front of a registry commonly refuse Python's default User-Agent. USER_AGENT = "kamino-next-image-version" class RegistryError(Exception): def __init__(self, url, status, text, challenge=""): super().__init__(f"GET {url}: HTTP {status}: {text}") self.status, self.challenge = status, challenge def _readable(raw): """The visible text of an error page on one line, so the job log shows a block page.""" text = re.sub( r"<(script|style)\b.*?|<[^>]+>", " ", raw, flags=re.DOTALL | re.IGNORECASE ) return " ".join(text.split())[:300] def _fetch(url, headers): """(JSON body, headers) of a GET; any HTTP error is a RegistryError naming status and text.""" request = urllib.request.Request(url, headers={**headers, "User-Agent": USER_AGENT}) try: with urllib.request.urlopen(request, timeout=30) as resp: return json.load(resp), resp.headers except urllib.error.HTTPError as exc: raw = exc.read(20000).decode("utf-8", errors="replace") challenge = exc.headers.get("WWW-Authenticate", "") raise RegistryError(url, exc.code, _readable(raw), challenge) from exc class Registry: """Anonymous reads of one image in an OCI registry: the images are public.""" def __init__(self, base_url, image): self.base_url, self.image, self.token = base_url, image, None def _get(self, path, accept="application/json"): url = f"{self.base_url}/v2/{self.image}/{path}" headers = {"Accept": accept} if self.token: headers["Authorization"] = f"Bearer {self.token}" try: return _fetch(url, headers) except RegistryError as exc: # One login at most: a 401 after it is final, whatever token it gave. if ( exc.status != 401 or self.token is not None or not self._login(exc.challenge) ): raise return self._get(path, accept) def _login(self, challenge_header): """Fetch an anonymous pull token from the 401 challenge's realm; False when it names none.""" challenge = dict(re.findall(r'(\w+)="([^"]*)"', challenge_header)) if "realm" not in challenge: return False query = urllib.parse.urlencode( { "service": challenge.get("service", ""), "scope": f"repository:{self.image}:pull", } ) self.token = _fetch(f"{challenge['realm']}?{query}", {})[0]["token"] return True def tags(self): tags, path = [], "tags/list" while path: body, headers = self._get(path) tags += body.get("tags") or [] link = re.search(r"<[^>]*/tags/list(\?[^>]*)>", headers.get("Link", "")) path = f"tags/list{link[1]}" if link else None return tags def label(self, tag): manifest = self._get(f"manifests/{tag}", ", ".join(MANIFEST_TYPES))[0] if manifest.get("mediaType") not in MANIFEST_TYPES: raise ValueError( f"{self.image}:{tag} is not a single-platform image manifest" ) config = self._get(f"blobs/{manifest['config']['digest']}")[0] return (config.get("config", {}).get("Labels") or {}).get(LABEL) def main(argv): if len(argv) != 4: sys.stderr.write(__doc__) return 2 root, name, url = pathlib.Path(argv[1]), argv[2], argv[3] entry = civ.matrix_of((root / civ.MATRIX_FILE).read_text(encoding="utf-8"))[name] checksum = input_checksum(root, entry) registry = Registry(url, f"mortis/{name}") try: version = next_version(entry["base"], registry.tags(), checksum, registry.label) except RegistryError as exc: sys.stderr.write(f"::error::{exc}\n") return 1 if version: print(version, checksum) return 0 if __name__ == "__main__": sys.exit(main(sys.argv))