From ee63d399abfb76f7a0f5ab7a5e4126d05ae2c3b0 Mon Sep 17 00:00:00 2001 From: Gaizka Menendez Date: Tue, 20 Oct 2026 00:21:44 +0100 Subject: [PATCH 1/3] CARRY: feat(odh): pin runtime images by digest and add Renovate coverage MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Pins every runtime image of the ODH OpenShift E2E deployment by digest — gateway, supervisor, sandbox runtime, and an optional default workload — and extends the runtime provenance scenario to verify the deployed digests end to end, writing evidence to results/e2e-odh-runtime-images.json. The deploy script rejects conflicting digests (explicit override vs. inline repo@sha256), malformed digests, and Helm map separators in image references, repositories, and tags before Helm runs. A cluster-free test covers all validation paths and is wired as `mise run test:odh-deploy-digests`. Adds Renovate regex managers for the e2e image bases and tool versions with a sync-generic-fetcher.py helper that keeps Dockerfile versions, Hermeto fetcher URLs, filenames, and checksums in one update, and demonstrates the flow with a uv 0.11.29 → 0.13.1 update. Completes the non-Python follow-ups from PR #61's deferred review feedback and RHAIENG-7753 acceptance criteria 1 and 3. Signed-off-by: Gaizka Menendez --- .github/workflows/odh-deploy-contract.yml | 44 ++ deploy/docker/Dockerfile.konflux.e2e-odh | 24 +- deploy/konflux/e2e-odh/README.md | 8 + deploy/konflux/e2e-odh/generic-fetcher.yaml | 13 +- deploy/konflux/e2e-odh/rpms.in.yaml | 1 + .../konflux/e2e-odh/sync-generic-fetcher.py | 414 +++++++++++++ e2e/rust/tests/odh/README.md | 73 ++- e2e/rust/tests/odh/smoke/image_provenance.rs | 579 +++++++++++++++++- odh/scripts/openshell-deploy-from-quay.sh | 116 +++- .../tests/test-openshell-deploy-from-quay.sh | 414 +++++++++++++ renovate.json | 75 +++ tasks/test-odh.toml | 6 + 12 files changed, 1715 insertions(+), 52 deletions(-) create mode 100644 .github/workflows/odh-deploy-contract.yml create mode 100755 deploy/konflux/e2e-odh/sync-generic-fetcher.py create mode 100755 odh/scripts/tests/test-openshell-deploy-from-quay.sh diff --git a/.github/workflows/odh-deploy-contract.yml b/.github/workflows/odh-deploy-contract.yml new file mode 100644 index 0000000000..8b85ed3382 --- /dev/null +++ b/.github/workflows/odh-deploy-contract.yml @@ -0,0 +1,44 @@ +# Midstream cluster-free deploy contract checks. Runs the digest/Helm +# regression suite for the Quay deploy script without a cluster, so PRs +# touching the deploy path get automated validation. Kept separate from +# branch-checks.yml so ODH does not depend on NVIDIA self-hosted runners. + +name: ODH Deploy Contract + +on: + pull_request: + paths: + - odh/scripts/** + - e2e/support/gateway-common.sh + - e2e/rust/tests/odh/tier_plan.py + - e2e/rust/tests/odh/tiers.toml + - deploy/helm/openshell/ci/values-openshift-e2e.yaml + - odh/values-openshift-e2e.yaml + - .github/workflows/odh-deploy-contract.yml + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: odh-deploy-contract-${{ github.ref }} + cancel-in-progress: true + +jobs: + deploy-contract: + name: Cluster-free deploy script contract + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + # The deploy plan resolver imports tomllib (Python 3.11+); pin the + # interpreter so the check does not depend on the runner default. + - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: "3.12" + + - name: Run the deploy digest contract suite + run: bash odh/scripts/tests/test-openshell-deploy-from-quay.sh diff --git a/deploy/docker/Dockerfile.konflux.e2e-odh b/deploy/docker/Dockerfile.konflux.e2e-odh index cf9122f4b4..bfe6a319c1 100644 --- a/deploy/docker/Dockerfile.konflux.e2e-odh +++ b/deploy/docker/Dockerfile.konflux.e2e-odh @@ -13,23 +13,33 @@ # environment with awk. Every RUN must start at column 0 with `RUN ` and # use `&& \` continuations. +# Tool versions are the source of truth for generic-fetcher.yaml. Renovate +# updates annotated versions in both files; then run +# `deploy/konflux/e2e-odh/sync-generic-fetcher.py --update all` to refresh the +# amd64 and arm64 checksums. +# renovate: datasource=docker depName=quay.io/openshift-release-dev/ocp-release extractVersion=^(?4\.\d+\.\d+)-x86_64$ ARG OC_VERSION=4.20.0 +# renovate: datasource=github-releases depName=helm/helm extractVersion=^v(?.+)$ ARG HELM_VERSION=4.2.0 +# renovate: datasource=github-releases depName=nextest-rs/nextest extractVersion=^cargo-nextest-(?.+)$ ARG NEXTEST_VERSION=0.9.143 +# renovate: datasource=github-releases depName=astral-sh/uv +ARG UV_VERSION=0.13.1 FROM registry.redhat.io/rust-builder-image/rust-rhel9:1.99.0@sha256:b00aaa63f7d6f5b857c170e4aed9d77f013f507ba97e72ebfcac48a7d3760310 AS builder # The builder image runs as 1001 and already ships gcc, gcc-c++, make, -# cmake, openssl-devel, git and tar, so no dnf step. Root writes /usr/local/bin. +# cmake, openssl-devel, git and tar. Install Python for the locked E2E test +# environment; root writes /usr/local/bin. USER 0 ARG NEXTEST_VERSION +ARG UV_VERSION ARG TARGETARCH ARG OPENSHELL_VERSION="" -RUN dnf install -y --nodocs --setopt=install_weak_deps=0 python3.11 && \ - dnf clean all - +RUN dnf install -y --nodocs --setopt=install_weak_deps=0 python3.11 \ + && dnf clean all RUN RUST_ARCH=$(case "${TARGETARCH}" in amd64) echo x86_64;; arm64) echo aarch64;; *) exit 1;; esac) && \ RUST_TRIPLE="${RUST_ARCH}-unknown-linux-gnu" && \ tar xzf "/cachi2/output/deps/generic/cargo-nextest-${NEXTEST_VERSION}-${RUST_TRIPLE}.tar.gz" \ @@ -64,7 +74,7 @@ RUN VER="${OPENSHELL_VERSION#v}" && \ --archive-file /opt/openshell/e2e-odh.tar.zst RUN UV_ARCH=$(case "${TARGETARCH}" in amd64) echo x86_64;; arm64) echo aarch64;; *) exit 1;; esac) && \ - tar xzf "/cachi2/output/deps/generic/uv-${UV_ARCH}-unknown-linux-gnu.tar.gz" \ + tar xzf "/cachi2/output/deps/generic/uv-${UV_VERSION}-${UV_ARCH}-unknown-linux-gnu.tar.gz" \ -C /tmp && \ install -m 0555 "/tmp/uv-${UV_ARCH}-unknown-linux-gnu/uv" /usr/local/bin/uv COPY odh/requirements.txt /tmp/requirements.txt @@ -77,6 +87,7 @@ FROM registry.access.redhat.com/ubi9/ubi:9.8@sha256:25a147defd01e19674714f55d175 ARG OC_VERSION ARG HELM_VERSION +ARG UV_VERSION ARG TARGETARCH RUN dnf install -y --nodocs --setopt=install_weak_deps=0 \ @@ -101,7 +112,7 @@ RUN OC_ARCH=$(case "${TARGETARCH}" in amd64) echo amd64;; arm64) echo arm64;; *) tar xzf "/cachi2/output/deps/generic/helm-v${HELM_VERSION}-linux-${OC_ARCH}.tar.gz" \ -C /tmp/helm && \ install -m 0555 "/tmp/helm/linux-${OC_ARCH}/helm" /usr/local/bin/helm && \ - tar xzf "/cachi2/output/deps/generic/uv-${UV_ARCH}-unknown-linux-gnu.tar.gz" \ + tar xzf "/cachi2/output/deps/generic/uv-${UV_VERSION}-${UV_ARCH}-unknown-linux-gnu.tar.gz" \ -C /tmp && \ install -m 0555 "/tmp/uv-${UV_ARCH}-unknown-linux-gnu/uv" /usr/local/bin/uv @@ -115,6 +126,7 @@ COPY --chown=1001:1001 .config/ .config/ COPY --chown=1001:1001 crates/ crates/ COPY --chown=1001:1001 proto/ proto/ COPY --from=builder --chown=1001:1001 /home/odh/openshell-e2e-odh/python/ python/ +COPY --chown=1001:1001 sdk/conformance/ sdk/conformance/ COPY --chown=1001:1001 providers/ providers/ COPY --chown=1001:1001 examples/ examples/ COPY --chown=1001:1001 e2e/ e2e/ diff --git a/deploy/konflux/e2e-odh/README.md b/deploy/konflux/e2e-odh/README.md index fd5cf31068..b3b0f7ffd9 100644 --- a/deploy/konflux/e2e-odh/README.md +++ b/deploy/konflux/e2e-odh/README.md @@ -63,3 +63,11 @@ The image name is `odh-openshell-e2e`; Konflux automation generates the Tekton YAML files. Before merging, validate the local hermetic build on both `linux/amd64` and `linux/arm64` using `PLATFORM` with `deploy/konflux/build-local.sh e2e-odh`. + +`sync-generic-fetcher.py` keeps the Dockerfile tool versions and the Hermeto +generic artifacts consistent. `--check` (offline) verifies URLs, filenames, +and checksums match the Dockerfile; `--update ` recomputes checksums by +downloading both architectures concurrently, retrying transient failures and +verifying each hash against the checksum sidecar its publisher signs — run it +after a Renovate bump, as the PR note instructs. Nothing is written unless +every download succeeds and matches its sidecar. diff --git a/deploy/konflux/e2e-odh/generic-fetcher.yaml b/deploy/konflux/e2e-odh/generic-fetcher.yaml index 154b2b63c7..9fc36c5efc 100644 --- a/deploy/konflux/e2e-odh/generic-fetcher.yaml +++ b/deploy/konflux/e2e-odh/generic-fetcher.yaml @@ -5,12 +5,13 @@ metadata: version: "1.0" artifacts: - - download_url: https://github.com/astral-sh/uv/releases/download/0.11.29/uv-x86_64-unknown-linux-gnu.tar.gz - checksum: "sha256:04f8b82f5d47f0512dcd32c67a4a6f16a0ea27c81537c338fd0ad6b23cebe829" - filename: uv-x86_64-unknown-linux-gnu.tar.gz - - download_url: https://github.com/astral-sh/uv/releases/download/0.11.29/uv-aarch64-unknown-linux-gnu.tar.gz - checksum: "sha256:94500fb064ae3c971a873cba64d94694c50677e0a4dbf78735c80509e7429919" - filename: uv-aarch64-unknown-linux-gnu.tar.gz + - download_url: https://github.com/astral-sh/uv/releases/download/0.13.1/uv-x86_64-unknown-linux-gnu.tar.gz + checksum: "sha256:eadd9d27c134ab5ac1ffd4473b97a741407f3ea238288f03121fc4deddf90220" + filename: uv-0.13.1-x86_64-unknown-linux-gnu.tar.gz + - download_url: https://github.com/astral-sh/uv/releases/download/0.13.1/uv-aarch64-unknown-linux-gnu.tar.gz + checksum: "sha256:9041c73c99fdc5892cf128140beb354eca9231d502068cc36e6cb53a8e59ad14" + filename: uv-0.13.1-aarch64-unknown-linux-gnu.tar.gz + - download_url: https://mirror.openshift.com/pub/openshift-v4/clients/ocp/4.20.0/openshift-client-linux-amd64-rhel9-4.20.0.tar.gz checksum: "sha256:dbc11aa32c8fa967c47c46900c524798b782b355615c9ca8ec2bbba647850420" filename: openshift-client-linux-amd64-rhel9-4.20.0.tar.gz diff --git a/deploy/konflux/e2e-odh/rpms.in.yaml b/deploy/konflux/e2e-odh/rpms.in.yaml index b6eed7f82e..24549c554b 100644 --- a/deploy/konflux/e2e-odh/rpms.in.yaml +++ b/deploy/konflux/e2e-odh/rpms.in.yaml @@ -23,6 +23,7 @@ packages: - libxslt - util-linux - openssh-clients + - openssl arches: - x86_64 - aarch64 diff --git a/deploy/konflux/e2e-odh/sync-generic-fetcher.py b/deploy/konflux/e2e-odh/sync-generic-fetcher.py new file mode 100755 index 0000000000..e74d07e5da --- /dev/null +++ b/deploy/konflux/e2e-odh/sync-generic-fetcher.py @@ -0,0 +1,414 @@ +#!/usr/bin/env python3 +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Keep the e2e image tool versions and Hermeto generic artifacts consistent. + +The `ARG _VERSION=` lines in Dockerfile.konflux.e2e-odh are the source +of truth. `--check` (the default, offline) verifies that generic-fetcher.yaml +has exactly one amd64 and one arm64 artifact per tool, with the URL and +filename for the Dockerfile version and a well-formed SHA-256 checksum. +`--update TOOL...` rewrites the artifact list from the Dockerfile versions and +recomputes the checksums of the named tools by downloading both +architectures — concurrently, with retries on transient failures, each hash +verified against the checksum sidecar its publisher signs — use it after +Renovate bumps a version. Other tools keep their recorded checksums. Nothing +is written unless every download succeeds and matches its sidecar. +""" + +from __future__ import annotations + +import argparse +import hashlib +import os +import re +import sys +import tempfile +import time +import urllib.error +import urllib.request +from concurrent.futures import ThreadPoolExecutor, as_completed +from urllib.parse import urlparse +from dataclasses import dataclass +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[3] +DOCKERFILE = ROOT / "deploy/docker/Dockerfile.konflux.e2e-odh" +FETCHER = ROOT / "deploy/konflux/e2e-odh/generic-fetcher.yaml" +ARCHES = ("amd64", "arm64") +_RUST_ARCH = {"amd64": "x86_64", "arm64": "aarch64"} +_GO_ARCH = {"amd64": "amd64", "arm64": "arm64"} + + +@dataclass(frozen=True) +class Tool: + arg: str + url: str + filename: str + # URL of the checksum sidecar the publisher signs the artifact with; + # fetched on --update so a substituted download is never blessed. + sidecar: str + arch: dict[str, str] + + +# Order matches generic-fetcher.yaml. `{v}` is the version, `{a}` the arch. +TOOLS = { + "uv": Tool( + "UV_VERSION", + "https://github.com/astral-sh/uv/releases/download/{v}/uv-{a}-unknown-linux-gnu.tar.gz", + "uv-{v}-{a}-unknown-linux-gnu.tar.gz", + "https://github.com/astral-sh/uv/releases/download/{v}/uv-{a}-unknown-linux-gnu.tar.gz.sha256", + _RUST_ARCH, + ), + "oc": Tool( + "OC_VERSION", + "https://mirror.openshift.com/pub/openshift-v4/clients/ocp/{v}/openshift-client-linux-{a}-rhel9-{v}.tar.gz", + "openshift-client-linux-{a}-rhel9-{v}.tar.gz", + "https://mirror.openshift.com/pub/openshift-v4/clients/ocp/{v}/sha256sum.txt", + _GO_ARCH, + ), + "helm": Tool( + "HELM_VERSION", + "https://get.helm.sh/helm-v{v}-linux-{a}.tar.gz", + "helm-v{v}-linux-{a}.tar.gz", + "https://get.helm.sh/helm-v{v}-linux-{a}.tar.gz.sha256sum", + _GO_ARCH, + ), + "nextest": Tool( + "NEXTEST_VERSION", + "https://github.com/nextest-rs/nextest/releases/download/cargo-nextest-{v}/cargo-nextest-{v}-{a}-unknown-linux-gnu.tar.gz", + "cargo-nextest-{v}-{a}-unknown-linux-gnu.tar.gz", + "https://github.com/nextest-rs/nextest/releases/download/cargo-nextest-{v}/cargo-nextest-{v}-{a}-unknown-linux-gnu.sha256", + _RUST_ARCH, + ), +} + +_ARG = re.compile(r"^ARG (?P[A-Z_]+)=(?P\S+)$", re.MULTILINE) +_ARTIFACT = re.compile( + r'^ - download_url: (?P\S+)\n checksum: "(?P[^"]+)"\n filename: (?P\S+)$', + re.MULTILINE, +) +_CHECKSUM = re.compile(r"sha256:[0-9a-f]{64}\Z") +_VERSION = re.compile(r"[0-9A-Za-z.+-]+\Z") + + +def require_https(url: str) -> None: + parsed = urlparse(url) + if parsed.scheme.lower() != "https" or not parsed.netloc: + raise ValueError(f"refusing non-HTTPS URL: {url}") + + +class HTTPSRedirectHandler(urllib.request.HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + require_https(newurl) + return super().redirect_request(req, fp, code, msg, headers, newurl) + + +@dataclass(frozen=True) +class Artifact: + url: str + checksum: str + filename: str + + +def read_versions(dockerfile: Path = DOCKERFILE) -> dict[str, str]: + args = {m["name"]: m["value"] for m in _ARG.finditer(dockerfile.read_text())} + versions = {} + for name, tool in TOOLS.items(): + version = args.get(tool.arg) + if version is None or not _VERSION.fullmatch(version): + raise SystemExit(f"{dockerfile}: missing or invalid ARG {tool.arg}") + versions[name] = version + return versions + + +def read_fetcher(fetcher: Path = FETCHER) -> tuple[str, list[Artifact]]: + text = fetcher.read_text() + header, sep, body = text.partition("artifacts:\n") + if not sep: + raise SystemExit(f"{fetcher}: missing 'artifacts:' list") + artifacts = [ + Artifact(m["url"], m["checksum"], m["filename"]) + for m in _ARTIFACT.finditer(body) + ] + entries = body.count("- download_url:") + if entries != len(artifacts): + raise SystemExit( + f"{fetcher}: {entries - len(artifacts)} artifact(s) do not use the url/checksum/filename layout" + ) + return header + sep, artifacts + + +def expected(name: str, version: str, arch: str) -> tuple[str, str, str]: + tool = TOOLS[name] + values = {"v": version, "a": tool.arch[arch]} + return ( + tool.url.format(**values), + tool.filename.format(**values), + tool.sidecar.format(**values), + ) + + +def filename_pattern(name: str, arch: str) -> re.Pattern[str]: + """Match the tool's artifact filename for an arch at any version.""" + tool = TOOLS[name] + escaped = re.escape(tool.filename).replace( + re.escape("{a}"), re.escape(tool.arch[arch]) + ) + return re.compile(escaped.replace(re.escape("{v}"), r"[0-9A-Za-z.+-]+")) + + +def check(versions: dict[str, str], artifacts: list[Artifact]) -> list[str]: + errors = [] + claimed: set[int] = set() + for name in TOOLS: + for arch in ARCHES: + url, filename, _ = expected(name, versions[name], arch) + matches = [ + i + for i, a in enumerate(artifacts) + if a.url == url and a.filename == filename + ] + claimed.update(matches) + if len(matches) != 1: + stale = [ + a.filename + for a in artifacts + if a.filename != filename + and filename_pattern(name, arch).fullmatch(a.filename) + ] + hint = f"; found {', '.join(stale)}" if stale else "" + errors.append( + f"{name} {arch}: expected exactly one artifact for {versions[name]} ({filename}), found {len(matches)}{hint}" + ) + continue + checksum = artifacts[matches[0]].checksum + if not _CHECKSUM.fullmatch(checksum): + errors.append(f"{name} {arch}: malformed checksum {checksum!r}") + errors.extend( + f"unexpected artifact not derived from the Dockerfile: {a.filename}" + for i, a in enumerate(artifacts) + if i not in claimed + ) + return errors + + +RETRY_ATTEMPTS = 3 + + +def _with_retry(url: str, consume, what: str): + """Run `consume` on `url`'s response, retrying transient failures. + + HTTP 4xx is permanent and raises immediately; connection errors, + timeouts, and HTTP 5xx are retried with exponential backoff. + """ + require_https(url) + for attempt in range(1, RETRY_ATTEMPTS + 1): + try: + opener = urllib.request.build_opener(HTTPSRedirectHandler()) + with opener.open(url, timeout=120) as response: + return consume(response) + except urllib.error.HTTPError as err: + # Client errors are permanent; the mirror hiccuping is not. + if 400 <= err.code < 500 or attempt == RETRY_ATTEMPTS: + raise + last_error: Exception = err + except (urllib.error.URLError, TimeoutError, OSError) as err: + if attempt == RETRY_ATTEMPTS: + raise + last_error = err + delay = 2 ** (attempt - 1) + print( + f"{url}: {last_error}; attempt {attempt}/{RETRY_ATTEMPTS} failed " + f"while {what}, retrying in {delay}s", + file=sys.stderr, + ) + time.sleep(delay) + raise AssertionError("unreachable") + + +def sha256_of(url: str) -> str: + """Download `url` and return its `sha256:` checksum.""" + digest = hashlib.sha256() + + def consume(response): + for chunk in iter(lambda: response.read(1 << 20), b""): + digest.update(chunk) + return f"sha256:{digest.hexdigest()}" + + return _with_retry(url, consume, "hashing the download") + + +def fetch_text(url: str) -> str: + """Download `url` and return its body as text.""" + return _with_retry(url, lambda response: response.read().decode(), "fetching the sidecar") + + +def published_checksum(sidecar_url: str, filename: str) -> str: + """Return the checksum a publisher sidecar records for `filename`. + + Prefers the line naming the artifact exactly; falls back to a + single-checksum sidecar (uv names the file without its version). + """ + text = fetch_text(sidecar_url) + lines = [line for line in text.splitlines() if line.strip()] + for line in lines: + parts = line.split() + if len(parts) >= 2 and parts[1].lstrip("*") == filename: + return f"sha256:{parts[0]}" + if len(lines) == 1: + return f"sha256:{lines[0].split()[0]}" + raise SystemExit(f"{sidecar_url}: no checksum recorded for {filename}") + + +def download_verified(url: str, sidecar_url: str, filename: str) -> str: + """Download `url`, hash it, and verify the hash against the sidecar. + + Without this check the download itself would be the trust root for the + checksums Hermeto later enforces: a substituted tarball would be blessed + with its own digest. + """ + checksum = sha256_of(url) + published = published_checksum(sidecar_url, filename) + if checksum != published: + raise SystemExit( + f"{url}: downloaded checksum {checksum} does not match the " + f"published {published} — refusing to bless a substituted artifact" + ) + return checksum + + +def render(header: str, artifacts: list[list[Artifact]]) -> str: + groups = [ + "".join( + f' - download_url: {a.url}\n checksum: "{a.checksum}"\n filename: {a.filename}\n' + for a in group + ) + for group in artifacts + ] + return header + "\n".join(groups) + + +def known_artifact(artifact: Artifact) -> bool: + """True if the artifact belongs to a tool in TOOLS at some version. + + Old-version artifacts of a tool being updated match their tool's + filename pattern and are legitimately replaced; an artifact no tool + declares would be silently dropped by the rewrite. + """ + return any( + filename_pattern(name, arch).fullmatch(artifact.filename) + for name in TOOLS + for arch in ARCHES + ) + + +def update( + versions: dict[str, str], header: str, artifacts: list[Artifact], tools: list[str] +) -> str: + # Refuse to rewrite while the file holds artifacts no tool declares: + # the rewrite regenerates the list from TOOLS and would delete them + # without any signal to the maintainer running the Renovate note. + unknown = [a for a in artifacts if not known_artifact(a)] + if unknown: + listing = "\n".join(f" {a.filename} ({a.url})" for a in unknown) + raise SystemExit( + "generic-fetcher.yaml holds artifacts no tool in TOOLS declares:\n" + f"{listing}\n" + "Refusing to rewrite. Extend TOOLS or remove the artifacts first." + ) + recorded = {a.url: a.checksum for a in artifacts} + # Resolve which URLs need downloading before touching the network, so a + # missing recorded checksum for an untouched tool fails before any + # transfer starts. + jobs: dict[str, tuple[str, str]] = {} # url -> (sidecar_url, filename) + for name in TOOLS: + for arch in ARCHES: + url, filename, sidecar = expected(name, versions[name], arch) + if name in tools: + jobs[url] = (sidecar, filename) + elif url not in recorded: + raise SystemExit( + f"{name} {arch}: no recorded checksum for {url}; run --update {name}" + ) + checksums: dict[str, str] = {} + if jobs: + for url in jobs: + print(f"Downloading {url}", file=sys.stderr) + # The downloads share no state and nothing is written until every + # checksum exists, so they run concurrently: wall time is the + # slowest artifact, not the sum of all transfers. A failure in any + # future re-raised below aborts before write_atomically runs. + with ThreadPoolExecutor(max_workers=len(jobs)) as pool: + futures = { + pool.submit(download_verified, url, sidecar, filename): url + for url, (sidecar, filename) in jobs.items() + } + for future in as_completed(futures): + checksums[futures[future]] = future.result() + groups = [] + for name in TOOLS: + group = [] + for arch in ARCHES: + url, filename, _ = expected(name, versions[name], arch) + checksum = checksums[url] if url in checksums else recorded[url] + group.append(Artifact(url, checksum, filename)) + groups.append(group) + return render(header, groups) + + +def write_atomically(path: Path, text: str) -> None: + fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.") + try: + with os.fdopen(fd, "w") as stream: + stream.write(text) + Path(tmp).chmod(path.stat().st_mode & 0o777) + Path(tmp).replace(path) + except BaseException: + Path(tmp).unlink(missing_ok=True) + raise + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + mode = parser.add_mutually_exclusive_group() + mode.add_argument( + "--check", action="store_true", help="verify consistency offline (default)" + ) + mode.add_argument( + "--update", + nargs="+", + metavar="TOOL", + choices=[*TOOLS, "all"], + help="rewrite artifacts and re-hash TOOL", + ) + parser.add_argument( + "--dockerfile", type=Path, default=DOCKERFILE, help=argparse.SUPPRESS + ) + parser.add_argument("--fetcher", type=Path, default=FETCHER, help=argparse.SUPPRESS) + args = parser.parse_args(argv) + + versions = read_versions(args.dockerfile) + header, artifacts = read_fetcher(args.fetcher) + if args.update: + tools = list(TOOLS) if "all" in args.update else args.update + write_atomically(args.fetcher, update(versions, header, artifacts, tools)) + header, artifacts = read_fetcher(args.fetcher) + + errors = check(versions, artifacts) + for error in errors: + print(f"ERROR: {error}", file=sys.stderr) + if errors: + print( + f"Fix {args.fetcher.name} or run {Path(__file__).name} --update ", + file=sys.stderr, + ) + return 1 + print( + f"{args.fetcher.name} matches {args.dockerfile.name} for {', '.join(TOOLS)} (amd64, arm64)" + ) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/e2e/rust/tests/odh/README.md b/e2e/rust/tests/odh/README.md index d5c89210a3..76c1c00935 100644 --- a/e2e/rust/tests/odh/README.md +++ b/e2e/rust/tests/odh/README.md @@ -22,7 +22,7 @@ e2e/rust/tests/odh/ ├── smoke/ # Smoke tier: component-level critical tests │ ├── mod.rs │ ├── gateway.rs # gateway reachability -│ ├── image_provenance.rs # sandbox/gateway/supervisor image registry + pull-policy check +│ ├── image_provenance.rs # deployed-image provenance: requested digests vs running pods, registry allowlist, pull-policy check, JSON evidence │ └── sandbox.rs # sandbox create/exec/delete + supervisor presence check ├── tier1/ # Tier 1: high-priority tests, excluding Smoke │ ├── mod.rs @@ -269,11 +269,28 @@ with an empty report. ## Image provenance verification `smoke::image_provenance::test_sandbox_gateway_supervisor_images` creates a -sandbox, then verifies that its image, the gateway's image, and the -supervisor image (read from the rendered gateway config, since the -supervisor never runs as its own pod) all came from an authorized -registry, and that no container — including ephemeral containers — has -regressed away from `imagePullPolicy: IfNotPresent`. +sandbox, then verifies the images actually running on the cluster: + +- **The gateway pod** and the **supervisor companion pod** (the supervisor + runs as its own pod created by the Kubernetes driver; the rendered gateway + config is recorded as secondary evidence). +- **The sandbox pod**, including its bootstrap container and ephemeral + containers. +- When the deployment pins components by digest, each observed pod must run + **exactly the requested immutable reference**: the pod spec's image matches + the requested `repo@sha256:…`, and the resolved `imageID` contains an + immutable digest. For a multi-arch manifest list, the `imageID` may + identify the node's architecture-specific sub-manifest rather than the + requested index digest. +- Workload and remaining images are checked against the + `ALLOWED_IMAGE_REGISTRY_PREFIXES` allowlist, and no container may regress + away from `imagePullPolicy: IfNotPresent`. + +The verified references are written to `results/e2e-odh-runtime-images.json` +(next to the JUnit reports, honoring `OPENSHELL_E2E_RESULTS_DIR`), recording +for each source the requested image, the resolved runtime `imageID`, and the +gateway-configured images. Runtime image digests are required E2E evidence: +failure to persist the evidence fails the test. ```bash ALLOWED_IMAGE_REGISTRY_PREFIXES="quay.io/opendatahub/,nvcr.io/nvidia/base/" \ @@ -281,6 +298,27 @@ ALLOWED_IMAGE_REGISTRY_PREFIXES="quay.io/opendatahub/,nvcr.io/nvidia/base/" \ -- smoke::image_provenance:: ``` +### Digest-pinning inputs + +The deploy script accepts a digest for every component; the provenance test +verifies whichever are requested: + +- `GATEWAY_IMAGE_DIGEST`, `SUPERVISOR_IMAGE_DIGEST`, and + `SANDBOX_IMAGE_DIGEST` — pin the gateway, supervisor, and sandbox runtime + images. Each may also be embedded inline in `GATEWAY_IMAGE`, + `SUPERVISOR_IMAGE`, or `SANDBOX_IMAGE` as `repo@sha256:…`; an explicit + `*_IMAGE_DIGEST` that conflicts with an inline digest fails the deployment + before Helm runs. +- `WORKLOAD_IMAGE`, `WORKLOAD_IMAGE_TAG`, and `WORKLOAD_IMAGE_DIGEST` — + optionally pin the default sandbox workload image. When unset, the + deployment leaves the chart's default untouched (no `sandbox.image.*` + values are set) and the workload is checked only against the registry + allowlist. +- With no digest requested for a component, that component is checked only + against the registry allowlist. + +### Registry allowlist and pull policy + - `ALLOWED_IMAGE_REGISTRY_PREFIXES` (required, comma-separated, each prefix must end in `/`) — no default, since an empty list would silently approve any image. This should include every registry prefix your deployment @@ -291,7 +329,8 @@ ALLOWED_IMAGE_REGISTRY_PREFIXES="quay.io/opendatahub/,nvcr.io/nvidia/base/" \ - `registry.redhat.io/` — RHOAI component images. - `nvcr.io/nvidia/base/` — the Helm chart's current default workload image (`server.sandboxImage`). Include the registry prefix for any - other workload image selected by the deployment. + other workload image selected by the deployment, e.g. + `ghcr.io/astral-sh/` when the Python E2E workload fixture is used. A prefix without a trailing `/` is rejected outright, since it could otherwise match a lookalike host (e.g. `registry.redhat.io` would also @@ -301,8 +340,6 @@ ALLOWED_IMAGE_REGISTRY_PREFIXES="quay.io/opendatahub/,nvcr.io/nvidia/base/" \ `GATEWAY_NAME` and `ROUTE_HOST` are run-scoped. Explicit values are used exactly as supplied; do not run concurrent invocations against the same cluster while using the default namespace and release. -- The check is a registry-prefix allowlist, not an exact image/digest match. - It checks each observed image against the configured allowed prefixes. - The `imagePullPolicy: IfNotPresent` check applies to every container, including the sandbox pod's. The shared Quay deployment script sets the gateway, supervisor, and sandbox pull policies to `IfNotPresent`; manually @@ -386,12 +423,26 @@ multi-phase tiers reject this option before cluster access. The environment file must set `IMAGE_TAG` for the gateway, supervisor, and sandbox images, plus `ALLOWED_IMAGE_REGISTRY_PREFIXES` for the -provenance test. By default, the deployment uses the +provenance test. `IMAGE_TAG` is required in the image because its source +tree carries no Git branch metadata; when running the deployment from a +source checkout, an unset `IMAGE_TAG` is derived from the current Git +branch instead (sanitized and truncated to 128 characters). The tag is a +preflight requirement even when every component uses a complete tagged or +digest reference, and bare repositories inherit it. By default, the +deployment uses the `quay.io/opendatahub/odh-openshell-*` midstream repositories. Override `QUAY_NAMESPACE`, `GATEWAY_IMAGE`, `SUPERVISOR_IMAGE`, or `SANDBOX_IMAGE` when testing another repository. Image variables accept a bare repository (which inherits `IMAGE_TAG`) or a complete tagged/digest reference. -`GATEWAY_IMAGE_DIGEST` remains available to override the gateway digest. +Each component can be pinned by digest with `GATEWAY_IMAGE_DIGEST`, +`SUPERVISOR_IMAGE_DIGEST`, or `SANDBOX_IMAGE_DIGEST` (an inline +`repo@sha256:…` reference works too and must agree with any explicit digest); +the workload image can optionally be pinned with `WORKLOAD_IMAGE`, +`WORKLOAD_IMAGE_TAG`, and `WORKLOAD_IMAGE_DIGEST` — these pins are forwarded +to the deployment but are not yet verified at runtime: the provenance test +checks the workload only against the registry-prefix allowlist. Requested +gateway, supervisor, and sandbox-runtime digests are verified against the pods +that actually run. `NAMESPACE`, `RELEASE`, `ROUTE_HOST`, and `GATEWAY_NAME` control the deployment and are exact when set; use distinct values across parallel invocations. The entrypoint exports diff --git a/e2e/rust/tests/odh/smoke/image_provenance.rs b/e2e/rust/tests/odh/smoke/image_provenance.rs index 8ec46b1d5f..ce7c0d2d01 100644 --- a/e2e/rust/tests/odh/smoke/image_provenance.rs +++ b/e2e/rust/tests/odh/smoke/image_provenance.rs @@ -3,18 +3,32 @@ //! Image provenance verification for downstream `OpenShift` CI. //! -//! Creates a sandbox, then verifies that its image, the gateway's image, and -//! the supervisor image (read from the rendered gateway config — it never -//! runs as its own pod) all came from an authorized downstream registry, and -//! that no container has regressed away from imagePullPolicy=IfNotPresent. +//! Creates a sandbox, then verifies the images actually running on the +//! cluster: the gateway pod, the supervisor companion pod (the supervisor +//! runs as its own pod created by the Kubernetes driver), and the sandbox +//! pod — all from an authorized downstream registry, and no container has +//! regressed away from imagePullPolicy=IfNotPresent. //! //! Requires the `oc` CLI in PATH with a kubeconfig targeting the cluster, and //! `ALLOWED_IMAGE_REGISTRY_PREFIXES` set to a comma-separated list of allowed //! registry prefixes (each ending in "/", e.g. "quay.io/opendatahub/") — //! required with no default, since an empty list would silently approve any //! image, defeating the check. +//! +//! When the deployment pinned images by digest (`GATEWAY_IMAGE_DIGEST`, +//! `SUPERVISOR_IMAGE_DIGEST`, or `SANDBOX_IMAGE_DIGEST`, or `GATEWAY_IMAGE`, +//! `SUPERVISOR_IMAGE`, or `SANDBOX_IMAGE` set to a +//! `repo@sha256:...` reference, see +//! `odh/scripts/openshell-deploy-from-quay.sh`), the test also verifies that +//! the gateway pod, supervisor companion pod, and sandbox bootstrap container +//! use exactly those digests, so nodes cannot run stale mutable-tag caches. Each +//! running container must retain the requested immutable reference and report +//! a resolved immutable `imageID`. The latter may be a platform-specific +//! manifest selected from the requested multi-architecture image index. Every +//! verified reference and resolved ID is written to +//! `results/e2e-odh-runtime-images.json` as test evidence. -use serde_json::Value; +use serde_json::{Value, json}; use openshell_e2e::harness::sandbox::SandboxGuard; @@ -34,12 +48,14 @@ fn allowed_prefixes() -> Vec { /// Collects (source, image) pairs from a pod list and appends imagePullPolicy /// violations directly to `errors`. Checks `containers`, `initContainers`, -/// and `ephemeralContainers` alike. +/// and `ephemeralContainers` alike. Container statuses also add their +/// resolved `imageID` to `evidence`. fn collect_pod_images( pods_json: &Value, selector: &str, errors: &mut Vec, images: &mut Vec<(String, String)>, + evidence: &mut Vec, ) { let items = pods_json .get("items") @@ -79,18 +95,38 @@ fn collect_pod_images( ] { for c in status[key].as_array().into_iter().flatten() { let cname = c["name"].as_str().unwrap_or(""); + let source = format!("{name}/{cname}"); + // Match the status entry with the pod-spec image of the same + // container. Kubernetes does not guarantee that + // ContainerStatus.image keeps the requested reference form, + // so the digest assertion uses the spec image while imageID + // proves the runtime resolved an immutable digest. + let Some(spec_image) = images + .iter() + .find(|(recorded, _)| recorded == &source) + .map(|(_, image)| image.clone()) + else { + errors.push(format!("{source}: no pod-spec image for running container")); + continue; + }; if let Some(image) = c["image"].as_str() { - images.push((format!("{name}/{cname}"), image.to_string())); + images.push((source.clone(), image.to_string())); } + evidence.push(json!({ + "source": source, + "image": spec_image, + "imageID": c["imageID"].as_str().unwrap_or_default(), + })); } } } } -/// Extracts `supervisor_image = "..."` from a rendered `gateway.toml`. -fn parse_supervisor_image(gateway_toml: &str) -> Option { +/// Extracts ` = "..."` (e.g. `supervisor_image`) from a rendered +/// `gateway.toml`. +fn parse_config_image(gateway_toml: &str, key: &str) -> Option { for line in gateway_toml.lines() { - let Some(rest) = line.trim().strip_prefix("supervisor_image") else { + let Some(rest) = line.trim().strip_prefix(key) else { continue; }; let Some(rest) = rest.trim_start().strip_prefix('=') else { @@ -106,7 +142,171 @@ fn parse_supervisor_image(gateway_toml: &str) -> Option { None } +/// The `sha256:` digest of an image reference such as `repo@sha256:...`. +fn reference_digest(reference: &str) -> Option<&str> { + reference + .rsplit_once('@') + .map(|(_, digest)| digest) + .filter(|digest| digest.starts_with("sha256:")) +} + +/// Digests the deployment pinned, read from the deploy script's image inputs: +/// the component-specific digest input, or a digest reference in its image +/// repository override. Components without a digest keep tag-based provenance +/// checks only. +fn requested_digests() -> Vec<(&'static str, String)> { + let var = |name: &str| std::env::var(name).ok().filter(|value| !value.is_empty()); + [ + ("gateway", "GATEWAY_IMAGE", Some("GATEWAY_IMAGE_DIGEST")), + ( + "supervisor", + "SUPERVISOR_IMAGE", + Some("SUPERVISOR_IMAGE_DIGEST"), + ), + ( + "sandbox runtime", + "SANDBOX_IMAGE", + Some("SANDBOX_IMAGE_DIGEST"), + ), + ] + .into_iter() + .filter_map(|(component, image_var, digest_var)| { + digest_var + .and_then(var) + .or_else(|| { + var(image_var).and_then(|image| reference_digest(&image).map(str::to_string)) + }) + .map(|digest| (component, digest)) + }) + .collect() +} + +/// Whether an image reference or resolved image ID carries `digest`. +fn has_digest(reference: &str, digest: &str) -> bool { + reference.ends_with(&format!("@{digest}")) +} + +/// Returns the observed references for a named runtime container. A status +/// entry is required: a pod spec alone does not establish that the kubelet +/// actually ran the container. The returned reference is the pod-spec image +/// for that container; the resolved image ID comes from the status entry. +fn runtime_container_refs<'a>( + evidence: &'a [Value], + container_name: &str, +) -> Vec<(&'a str, Option<&'a str>)> { + evidence + .iter() + .filter(|entry| { + entry["source"] + .as_str() + .and_then(|source| source.rsplit('/').next()) + == Some(container_name) + }) + .filter_map(|entry| { + entry["image"] + .as_str() + .map(|image| (image, entry["imageID"].as_str().filter(|id| !id.is_empty()))) + }) + .collect() +} + +/// Returns true only when every expected running container was requested +/// with the immutable reference and reports a resolved immutable image ID. +/// +/// The requested reference comes from the pod spec, which the deployment +/// controls; Kubernetes does not guarantee that ContainerStatus.image keeps +/// that form, so it is not used for the digest assertion. The resolved ID +/// deliberately need not equal `digest`: Kubernetes resolves a +/// multi-architecture OCI index to its platform-specific child manifest +/// before starting the container. Requiring the spec to request the +/// immutable image and a non-empty resolved digest proves the workload was +/// scheduled from the requested image and that the kubelet actually pulled +/// immutable content. +fn runtime_refs_match_digest(refs: &[(&str, Option<&str>)], digest: &str) -> bool { + !refs.is_empty() + && refs.iter().all(|(image, image_id)| { + has_digest(image, digest) + && image_id.is_some_and(|resolved| reference_digest(resolved).is_some()) + }) +} + +/// Fails each component whose requested digest is not used by its actual +/// runtime container. The gateway runs in the Helm pod, the sandbox runtime +/// runs as the `openshell-sandbox-bootstrap` init container, and the +/// supervisor runs in its controller-managed companion pod. +fn check_requested_digests( + gateway_refs: &[(&str, Option<&str>)], + supervisor_refs: &[(&str, Option<&str>)], + sandbox_runtime_refs: &[(&str, Option<&str>)], + errors: &mut Vec, +) { + for (component, digest) in requested_digests() { + let matched = match component { + "gateway" => runtime_refs_match_digest(gateway_refs, &digest), + "supervisor" => runtime_refs_match_digest(supervisor_refs, &digest), + _ => runtime_refs_match_digest(sandbox_runtime_refs, &digest), + }; + if matched { + println!("{component} image pinned to requested digest {digest}"); + } else { + errors.push(format!( + "{component}: requested digest {digest} is not used by the deployed workload" + )); + } + } +} + +/// Writes the verified references to an explicit results directory. +fn write_evidence_at( + results: &std::path::Path, + evidence: &[Value], +) -> std::io::Result { + let path = results.join("e2e-odh-runtime-images.json"); + let body = serde_json::to_string_pretty(evidence).expect("evidence serializes"); + std::fs::create_dir_all(results)?; + std::fs::write(&path, body)?; + Ok(path) +} + +/// Resolves the results directory for runtime image evidence. A non-empty +/// `OPENSHELL_E2E_RESULTS_DIR` override places the evidence next to the +/// JUnit reports the entrypoint writes; otherwise fall back to the +/// manifest-relative results directory for direct cargo invocations. +/// Parameters are passed in (rather than read here) so the precedence rules +/// stay testable without mutating the process environment. +fn evidence_results_dir( + results_override: Option<&str>, + manifest_dir: Option<&str>, +) -> Result { + if let Some(dir) = results_override.filter(|dir| !dir.is_empty()) { + return Ok(std::path::PathBuf::from(dir)); + } + let manifest_dir = manifest_dir.ok_or_else(|| { + "CARGO_MANIFEST_DIR is unset; cannot write runtime image evidence".to_string() + })?; + Ok(std::path::Path::new(manifest_dir).join("../../results")) +} + +/// Writes the verified references next to the `JUnit` reports. Runtime image +/// digests are required E2E evidence, so inability to persist them fails the +/// test after sandbox cleanup. +fn write_evidence(evidence: &[Value]) -> Result<(), String> { + let results = evidence_results_dir( + std::env::var("OPENSHELL_E2E_RESULTS_DIR").ok().as_deref(), + std::env::var("CARGO_MANIFEST_DIR").ok().as_deref(), + )?; + let path = write_evidence_at(&results, evidence).map_err(|err| { + format!( + "failed to write runtime image evidence to {}: {err}", + results.display() + ) + })?; + println!("runtime image evidence: {}", path.display()); + Ok(()) +} + #[tokio::test] +#[allow(clippy::too_many_lines)] async fn test_sandbox_gateway_supervisor_images() { let namespace = std::env::var("NAMESPACE").unwrap_or_else(|_| "openshell".to_string()); let release = std::env::var("RELEASE").unwrap_or_else(|_| "openshell".to_string()); @@ -114,6 +314,7 @@ async fn test_sandbox_gateway_supervisor_images() { let mut errors = Vec::new(); let mut images: Vec<(String, String)> = Vec::new(); + let mut evidence: Vec = Vec::new(); // A prefix without a trailing "/" would also match a lookalike host, e.g. // "registry.redhat.io" matches "registry.redhat.io.attacker.example/image". @@ -154,22 +355,70 @@ async fn test_sandbox_gateway_supervisor_images() { "json", ]) .await; - let pod_selector = sandbox_crs + let sandbox_cr = sandbox_crs .get("items") .and_then(Value::as_array) - .and_then(|items| items.first()) + .and_then(|items| items.first()); + let pod_selector = sandbox_cr .and_then(|cr| cr["status"]["selector"].as_str()) .map(str::to_string); + let sandbox_id = sandbox_cr + .and_then(|cr| cr["metadata"]["labels"]["openshell.ai/sandbox-id"].as_str()) + .map(str::to_string); + let sandbox_evidence_start = evidence.len(); match pod_selector { Some(pod_selector) => { let sandbox_pods = oc_json(&["get", "pods", "-n", &namespace, "-l", &pod_selector, "-o", "json"]).await; - collect_pod_images(&sandbox_pods, &pod_selector, &mut errors, &mut images); + collect_pod_images( + &sandbox_pods, + &pod_selector, + &mut errors, + &mut images, + &mut evidence, + ); } None => errors.push(format!( "no Sandbox resource with pod selector found for '{sandbox_selector}' — cannot verify image provenance" )), } + let sandbox_evidence_end = evidence.len(); + + // The Kubernetes driver creates a separate, directly-managed supervisor + // pod for every sandbox. It is not selected by the external Sandbox CR's + // controller selector, so query it by the driver's stable labels. Reading + // its container status is what proves the supervisor image was actually + // pulled and run, rather than merely rendered into gateway.toml. + let supervisor_evidence_start = evidence.len(); + match sandbox_id { + Some(sandbox_id) => { + let supervisor_selector = format!( + "openshell.ai/sandbox-id={sandbox_id},openshell.ai/component=supervisor" + ); + let supervisor_pods = oc_json(&[ + "get", + "pods", + "-n", + &namespace, + "-l", + &supervisor_selector, + "-o", + "json", + ]) + .await; + collect_pod_images( + &supervisor_pods, + &supervisor_selector, + &mut errors, + &mut images, + &mut evidence, + ); + } + None => errors.push(format!( + "Sandbox resource for '{sandbox_selector}' has no openshell.ai/sandbox-id label — cannot verify supervisor image provenance" + )), + } + let supervisor_evidence_end = evidence.len(); // Gateway pod. let gateway_selector = format!("app.kubernetes.io/instance={release}"); @@ -184,11 +433,18 @@ async fn test_sandbox_gateway_supervisor_images() { "json", ]) .await; - collect_pod_images(&gateway_pods, &gateway_selector, &mut errors, &mut images); + let gateway_evidence_start = evidence.len(); + collect_pod_images( + &gateway_pods, + &gateway_selector, + &mut errors, + &mut images, + &mut evidence, + ); + let gateway_evidence_end = evidence.len(); - // Supervisor image — never its own pod, so read it from the rendered - // gateway config instead. Held to the same registry-prefix bar (which - // already excludes upstream ghcr.io/nvidia/openshell/* refs). + // The rendered config remains useful deployment evidence, while the + // supervisor pod above provides the authoritative runtime image ID. let cm_name = format!("{release}-config"); let cm_output = oc_command() .args([ @@ -203,18 +459,70 @@ async fn test_sandbox_gateway_supervisor_images() { .output() .await .expect("failed to run oc get configmap"); - let supervisor_image = cm_output + let gateway_toml = if cm_output.status.success() { + String::from_utf8_lossy(&cm_output.stdout).into_owned() + } else { + let stderr = String::from_utf8_lossy(&cm_output.stderr); + errors.push(format!( + "failed to get gateway config configmap {cm_name}: status {}; stderr: {}", + cm_output.status, + stderr.trim() + )); + String::new() + }; + let supervisor_image = if cm_output.status.success() { + parse_config_image(&gateway_toml, "supervisor_image") + } else { + None + }; + if let Some(image) = &supervisor_image { + images.push(( + "supervisor_image (gateway config)".to_string(), + image.clone(), + )); + } else if cm_output.status.success() { + errors.push( + "supervisor_image not found in gateway config configmap — cannot verify provenance" + .to_string(), + ); + } + // Rendered only when the deployment overrides the sandbox runtime image. + let sandbox_runtime_image = cm_output .status .success() - .then(|| parse_supervisor_image(&String::from_utf8_lossy(&cm_output.stdout))) + .then(|| parse_config_image(&gateway_toml, "sandbox_runtime_image")) .flatten(); - match supervisor_image { - Some(image) => images.push(("supervisor_image (gateway config)".to_string(), image)), - None => errors.push( - "supervisor_image not found in gateway config configmap — cannot verify provenance" - .to_string(), - ), + if let Some(image) = &sandbox_runtime_image { + images.push(( + "sandbox_runtime_image (gateway config)".to_string(), + image.clone(), + )); } + for (source, image) in images + .iter() + .filter(|(source, _)| source.contains("gateway config")) + { + evidence.push(json!({ "source": source, "image": image, "imageID": "" })); + } + + let gateway_refs = runtime_container_refs( + &evidence[gateway_evidence_start..gateway_evidence_end], + "openshell-gateway", + ); + let supervisor_refs = runtime_container_refs( + &evidence[supervisor_evidence_start..supervisor_evidence_end], + "supervisor", + ); + let sandbox_runtime_refs = runtime_container_refs( + &evidence[sandbox_evidence_start..sandbox_evidence_end], + "openshell-sandbox-bootstrap", + ); + check_requested_digests( + &gateway_refs, + &supervisor_refs, + &sandbox_runtime_refs, + &mut errors, + ); for (source, image) in &images { if !allowed @@ -231,6 +539,9 @@ async fn test_sandbox_gateway_supervisor_images() { errors.push("no images found — nothing to verify".to_string()); } + if let Err(err) = write_evidence(&evidence) { + errors.push(err); + } sb.cleanup().await; assert!( @@ -239,3 +550,221 @@ async fn test_sandbox_gateway_supervisor_images() { errors.join("\n") ); } + +#[cfg(test)] +mod tests { + use std::sync::atomic::{AtomicUsize, Ordering}; + + use super::{ + evidence_results_dir, has_digest, parse_config_image, reference_digest, + runtime_container_refs, runtime_refs_match_digest, write_evidence_at, + }; + + const DIGEST: &str = "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + static EVIDENCE_PATH_SEQUENCE: AtomicUsize = AtomicUsize::new(0); + + fn temporary_evidence_path(name: &str) -> std::path::PathBuf { + let sequence = EVIDENCE_PATH_SEQUENCE.fetch_add(1, Ordering::Relaxed); + std::env::temp_dir().join(format!( + "openshell-e2e-evidence-{name}-{}-{sequence}", + std::process::id() + )) + } + + #[test] + fn parses_config_images_without_matching_longer_keys() { + let toml = "supervisor_image_pull_policy = \"IfNotPresent\"\n\ + supervisor_image = \"quay.io/opendatahub/odh-openshell-supervisor@sha256:aa\"\n\ + sandbox_runtime_image = \"quay.io/opendatahub/odh-openshell-sandbox:v1\"\n"; + assert_eq!( + parse_config_image(toml, "supervisor_image").as_deref(), + Some("quay.io/opendatahub/odh-openshell-supervisor@sha256:aa") + ); + assert_eq!( + parse_config_image(toml, "sandbox_runtime_image").as_deref(), + Some("quay.io/opendatahub/odh-openshell-sandbox:v1") + ); + assert_eq!(parse_config_image(toml, "gateway_image"), None); + } + + #[test] + fn reads_requested_digests_from_image_references() { + assert_eq!( + reference_digest(&format!( + "quay.io/opendatahub/odh-openshell-supervisor@{DIGEST}" + )), + Some(DIGEST) + ); + assert_eq!( + reference_digest(&format!("registry.example:5000/ns/sandbox:v1@{DIGEST}")), + Some(DIGEST) + ); + assert_eq!( + reference_digest("quay.io/opendatahub/odh-openshell-sandbox:v1"), + None + ); + assert_eq!( + reference_digest("quay.io/opendatahub/odh-openshell-sandbox"), + None + ); + assert_eq!( + reference_digest("quay.io/opendatahub/odh-openshell-sandbox@md5:abc"), + None + ); + } + + #[test] + fn matches_only_the_exact_requested_digest() { + assert!(has_digest( + &format!("quay.io/opendatahub/odh-openshell-gateway@{DIGEST}"), + DIGEST + )); + assert!(!has_digest( + "quay.io/opendatahub/odh-openshell-gateway:v1", + DIGEST + )); + assert!(!has_digest( + &format!("quay.io/opendatahub/odh-openshell-gateway@{DIGEST}0"), + DIGEST + )); + assert!(!has_digest( + &format!( + "quay.io/opendatahub/odh-openshell-gateway@{}", + &DIGEST[..20] + ), + DIGEST + )); + } + + #[test] + fn requires_requested_reference_and_resolved_runtime_ids() { + // The first tuple element is the pod-spec image the deployment + // requested; the second is the runtime-resolved image ID. A + // multi-architecture index is resolved by Kubernetes to this + // platform-specific child manifest. It is intentionally different + // from the requested index digest. + let requested = format!("quay.io/opendatahub/odh-openshell-gateway@{DIGEST}"); + let resolved_child = "quay.io/opendatahub/odh-openshell-gateway@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + let refs = [ + (requested.as_str(), Some(resolved_child)), + (requested.as_str(), Some(resolved_child)), + ]; + assert!(runtime_refs_match_digest(&refs, DIGEST)); + + let tag_only = [( + "quay.io/opendatahub/odh-openshell-gateway:pr-98", + Some(resolved_child), + )]; + assert!(!runtime_refs_match_digest(&tag_only, DIGEST)); + + let missing_resolved_digest = [(requested.as_str(), Some("not-a-digest"))]; + assert!(!runtime_refs_match_digest(&missing_resolved_digest, DIGEST)); + assert!(!runtime_refs_match_digest(&[], DIGEST)); + + let missing_id = [(requested.as_str(), None)]; + assert!(!runtime_refs_match_digest(&missing_id, DIGEST)); + } + + #[test] + fn identifies_and_requires_running_sandbox_and_supervisor_containers() { + let supervisor_id = format!("quay.io/opendatahub/odh-openshell-supervisor@{DIGEST}"); + let sandbox_id = format!("quay.io/opendatahub/odh-openshell-sandbox@{DIGEST}"); + let evidence = vec![ + serde_json::json!({ + "source": "os-supervisor-example/supervisor", + "image": format!("quay.io/opendatahub/odh-openshell-supervisor@{DIGEST}"), + "imageID": supervisor_id, + }), + serde_json::json!({ + "source": "example/openshell-sandbox-bootstrap", + "image": format!("quay.io/opendatahub/odh-openshell-sandbox@{DIGEST}"), + "imageID": sandbox_id, + }), + // A sandbox workload may independently name a container + // "supervisor". The production check passes only the companion + // supervisor pod's evidence slice to the helper, so this entry + // must not influence its requested digest assertion. + serde_json::json!({ + "source": "example-workload/supervisor", + "image": "example.invalid/workload:latest", + "imageID": "example.invalid/workload@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + }), + serde_json::json!({ + "source": "example/agent", + "image": "ghcr.io/astral-sh/uv:latest", + "imageID": "ghcr.io/astral-sh/uv@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + }), + ]; + + let supervisor = runtime_container_refs(&evidence[..1], "supervisor"); + let sandbox = runtime_container_refs(&evidence[1..], "openshell-sandbox-bootstrap"); + assert!(runtime_refs_match_digest(&supervisor, DIGEST)); + assert!(runtime_refs_match_digest(&sandbox, DIGEST)); + assert!(!runtime_refs_match_digest( + &runtime_container_refs(&evidence, "supervisor"), + DIGEST + )); + assert!(runtime_container_refs(&evidence, "missing").is_empty()); + } + + #[test] + fn persists_runtime_image_evidence() { + let results = temporary_evidence_path("writes"); + let path = write_evidence_at(&results, &[serde_json::json!({ "image": "example" })]) + .expect("evidence should be written"); + + assert_eq!( + std::fs::read_to_string(&path).expect("evidence should be readable"), + "[\n {\n \"image\": \"example\"\n }\n]" + ); + std::fs::remove_dir_all(results).expect("temporary evidence directory should be removed"); + } + + #[test] + fn reports_failure_when_evidence_cannot_be_persisted() { + let blocked_path = temporary_evidence_path("blocked"); + std::fs::write(&blocked_path, "not a directory").expect("test fixture should be created"); + + let error = write_evidence_at(&blocked_path, &[]) + .expect_err("a file cannot be used as the evidence directory"); + assert!( + matches!( + error.kind(), + std::io::ErrorKind::AlreadyExists | std::io::ErrorKind::NotADirectory + ), + "unexpected evidence write error: {error}" + ); + std::fs::remove_file(blocked_path).expect("temporary blocker should be removed"); + } + + #[test] + fn evidence_dir_env_override_takes_precedence() { + // A non-empty override wins. + let dir = evidence_results_dir(Some("/tmp/override"), Some("/repo/e2e/rust")) + .expect("override should win"); + assert_eq!(dir, std::path::PathBuf::from("/tmp/override")); + + // An empty override falls back to the manifest-relative results dir. + let dir = evidence_results_dir(Some(""), Some("/repo/e2e/rust")) + .expect("empty override should fall back"); + assert_eq!( + dir, + std::path::Path::new("/repo/e2e/rust").join("../../results") + ); + + // No override at all: the same fallback. + let dir = evidence_results_dir(None, Some("/repo/e2e/rust")) + .expect("no override should fall back"); + assert_eq!( + dir, + std::path::Path::new("/repo/e2e/rust").join("../../results") + ); + + // Neither override nor manifest dir: a clear error. + let error = evidence_results_dir(None, None).expect_err("manifest dir is required"); + assert!( + error.contains("CARGO_MANIFEST_DIR"), + "unexpected error: {error}" + ); + } +} diff --git a/odh/scripts/openshell-deploy-from-quay.sh b/odh/scripts/openshell-deploy-from-quay.sh index e0fef032ab..6e3bae34b1 100755 --- a/odh/scripts/openshell-deploy-from-quay.sh +++ b/odh/scripts/openshell-deploy-from-quay.sh @@ -25,7 +25,12 @@ # GATEWAY_IMAGE gateway image reference (bare repository uses IMAGE_TAG) # GATEWAY_IMAGE_DIGEST optional gateway digest override # SUPERVISOR_IMAGE supervisor image reference (bare repository uses IMAGE_TAG) +# SUPERVISOR_IMAGE_DIGEST optional supervisor digest override # SANDBOX_IMAGE sandbox image reference (bare repository uses IMAGE_TAG) +# SANDBOX_IMAGE_DIGEST optional sandbox runtime digest override +# WORKLOAD_IMAGE optional default sandbox workload image reference (bare repository uses WORKLOAD_IMAGE_TAG) +# WORKLOAD_IMAGE_TAG optional workload image tag (default: latest) +# WORKLOAD_IMAGE_DIGEST optional workload image digest override # NAMESPACE target k8s namespace (default: openshell) # RELEASE Helm release name (default: openshell) # ROUTE_HOST gateway Route hostname (default: openshell.) @@ -187,14 +192,96 @@ fi GATEWAY_IMAGE="${GATEWAY_IMAGE:-${QNS}/odh-openshell-gateway}" SUPERVISOR_IMAGE="${SUPERVISOR_IMAGE:-${QNS}/odh-openshell-supervisor}" SANDBOX_IMAGE="${SANDBOX_IMAGE:-${QNS}/odh-openshell-sandbox}" + +# Helm receives image components through --set-string, so references must not +# carry Helm map separators (',' or '=') that could inject additional values. +validate_image_reference() { + local name="$1" image="$2" repository tag digest + repository="$(e2e_image_reference_repository "${image}")" + [[ "${repository}" =~ ^[a-z0-9][a-z0-9.-]*(:[0-9]+)?(/[a-z0-9][a-z0-9._-]*)+$ ]] || + fail "${name} must be a lowercase registry/repository reference without Helm separators" + # An absent tag is valid (digest-pinned or registry default), but a tag + # delimiter must carry a tag: an empty one would silently fall back to + # the cluster's default tag instead of failing the typo. + local last_component="${image%%@*}" + last_component="${last_component##*/}" + if [[ "${last_component}" == *:* ]]; then + # Extract the tag from the last path component before any digest, + # not from e2e_image_reference_tag: that helper intentionally + # returns an empty string for references that carry a digest, + # which would reject the valid repo:tag@sha256:… form. + tag="${last_component##*:}" + [[ "${tag}" =~ ^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$ ]] || + fail "${name} must carry a valid image tag without Helm separators" + fi + # Likewise, a digest delimiter must carry a valid sha256 digest: an + # empty digest would silently drop the pin and deploy an unpinned, + # mutable reference. + if [[ "${image}" == *@* ]]; then + digest="$(e2e_image_reference_digest "${image}")" + [[ "${digest}" =~ ^sha256:[a-f0-9]{64}$ ]] || + fail "${name} must carry a valid sha256 digest without Helm separators" + fi +} + GATEWAY_IMAGE_REF="$(e2e_resolve_image_reference "${GATEWAY_IMAGE}" "${IMAGE_TAG}")" SUPERVISOR_IMAGE_REF="$(e2e_resolve_image_reference "${SUPERVISOR_IMAGE}" "${IMAGE_TAG}")" SANDBOX_IMAGE_REF="$(e2e_resolve_image_reference "${SANDBOX_IMAGE}" "${IMAGE_TAG}")" -if [[ -n "${GATEWAY_IMAGE_DIGEST:-}" ]]; then - [[ "${GATEWAY_IMAGE_DIGEST}" == sha256:* ]] || fail "GATEWAY_IMAGE_DIGEST must start with sha256:" - GATEWAY_IMAGE_REF="$(e2e_image_reference_repository "${GATEWAY_IMAGE_REF}")@${GATEWAY_IMAGE_DIGEST}" + +# Validate the resolved references: an operator-supplied IMAGE_TAG joins the +# reference during resolution, and every component reaches Helm through +# --set-string. +validate_image_reference GATEWAY_IMAGE "${GATEWAY_IMAGE_REF}" +validate_image_reference SUPERVISOR_IMAGE "${SUPERVISOR_IMAGE_REF}" +validate_image_reference SANDBOX_IMAGE "${SANDBOX_IMAGE_REF}" + +# Apply an explicit _IMAGE_DIGEST override to a resolved image +# reference. A digest already embedded in the reference must agree with the +# override; silently picking one could deploy a different image than intended. +apply_image_digest() { + local digest_var="$1" ref_var="$2" digest ref + digest="${!digest_var:-}" + ref="${!ref_var}" + if [[ -z "${digest}" ]]; then + return 0 + fi + [[ "${digest}" =~ ^sha256:[a-f0-9]{64}$ ]] || + fail "${digest_var} must be a lowercase sha256 digest (sha256:<64 hex digits>)" + if e2e_image_reference_has_digest "${ref}"; then + [[ "${ref}" == *"@${digest}" ]] || + fail "${digest_var} conflicts with the digest already present in ${ref_var}: ${ref}" + return 0 + fi + printf -v "${ref_var}" '%s@%s' "$(e2e_image_reference_repository "${ref}")" "${digest}" +} + +apply_image_digest GATEWAY_IMAGE_DIGEST GATEWAY_IMAGE_REF +apply_image_digest SUPERVISOR_IMAGE_DIGEST SUPERVISOR_IMAGE_REF +apply_image_digest SANDBOX_IMAGE_DIGEST SANDBOX_IMAGE_REF + +# Optional default sandbox workload image. The chart applies it via +# sandbox.image.*, separate from the sandboxRuntime runtime image. +WORKLOAD_IMAGE_REF="" +if [[ -n "${WORKLOAD_IMAGE:-}" ]]; then + validate_image_reference WORKLOAD_IMAGE "${WORKLOAD_IMAGE}" + # An explicit WORKLOAD_IMAGE_TAG must not be silently dropped when the + # reference is already complete: the same input with a conflicting + # digest fails loudly in apply_image_digest below. + if [[ -n "${WORKLOAD_IMAGE_TAG:-}" ]] && + { [[ -n "$(e2e_image_reference_tag "${WORKLOAD_IMAGE}")" ]] || + e2e_image_reference_has_digest "${WORKLOAD_IMAGE}"; }; then + fail "WORKLOAD_IMAGE_TAG conflicts with the complete reference ${WORKLOAD_IMAGE}" + fi + WORKLOAD_IMAGE_TAG="${WORKLOAD_IMAGE_TAG:-latest}" + [[ "${WORKLOAD_IMAGE_TAG}" =~ ^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$ ]] || + fail "WORKLOAD_IMAGE_TAG must be a valid image tag without Helm separators" + WORKLOAD_IMAGE_REF="$(e2e_resolve_image_reference "${WORKLOAD_IMAGE}" "${WORKLOAD_IMAGE_TAG}")" + apply_image_digest WORKLOAD_IMAGE_DIGEST WORKLOAD_IMAGE_REF +elif [[ -n "${WORKLOAD_IMAGE_TAG:-}" || -n "${WORKLOAD_IMAGE_DIGEST:-}" ]]; then + fail "WORKLOAD_IMAGE is required when setting WORKLOAD_IMAGE_TAG or WORKLOAD_IMAGE_DIGEST" fi -for image_ref in "${GATEWAY_IMAGE_REF}" "${SUPERVISOR_IMAGE_REF}" "${SANDBOX_IMAGE_REF}"; do + +for image_ref in "${GATEWAY_IMAGE_REF}" "${SUPERVISOR_IMAGE_REF}" "${SANDBOX_IMAGE_REF}" ${WORKLOAD_IMAGE_REF:+"${WORKLOAD_IMAGE_REF}"}; do [[ -n "$(e2e_image_reference_registry "${image_ref}")" ]] || fail "image reference must include a registry: ${image_ref}" done @@ -222,6 +309,9 @@ echo " Images:" echo " - ${GATEWAY_IMAGE_REF}" echo " - ${SUPERVISOR_IMAGE_REF}" echo " - ${SANDBOX_IMAGE_REF}" +if [[ -n "${WORKLOAD_IMAGE_REF}" ]]; then + echo " - ${WORKLOAD_IMAGE_REF} (default sandbox workload)" +fi echo " Actions:" echo " 1. Replace namespace '${NAMESPACE}' if it exists" echo " 2. Create namespace" @@ -296,9 +386,27 @@ append_image_helm_args() { image_helm_args+=(--set-string "${component}.image.${value}") done } +# The chart's sandbox.image has no registry key: its repository value is the +# full registry-qualified path (the chart default, nvcr.io/nvidia/base/ubuntu, +# shows the convention). Pass the complete reference as the repository so the +# rendered default sandbox image stays pullable, unlike the gateway, +# supervisor, and sandboxRuntime components whose chart helpers render +# registry and repository separately. +append_workload_helm_args() { + local image_ref="$1" value + for value in \ + "repository=$(e2e_image_reference_repository "${image_ref}")" \ + "tag=$(e2e_image_reference_tag "${image_ref}")" \ + "digest=$(e2e_image_reference_digest "${image_ref}")"; do + image_helm_args+=(--set-string "sandbox.image.${value}") + done +} append_image_helm_args gateway "${GATEWAY_IMAGE_REF}" append_image_helm_args supervisor "${SUPERVISOR_IMAGE_REF}" append_image_helm_args sandboxRuntime "${SANDBOX_IMAGE_REF}" +if [[ -n "${WORKLOAD_IMAGE_REF}" ]]; then + append_workload_helm_args "${WORKLOAD_IMAGE_REF}" +fi helm upgrade --install "${RELEASE}" "${CHART}" \ --namespace "${NAMESPACE}" --create-namespace \ "${helm_value_args[@]}" \ diff --git a/odh/scripts/tests/test-openshell-deploy-from-quay.sh b/odh/scripts/tests/test-openshell-deploy-from-quay.sh new file mode 100755 index 0000000000..7e23f505e1 --- /dev/null +++ b/odh/scripts/tests/test-openshell-deploy-from-quay.sh @@ -0,0 +1,414 @@ +#!/usr/bin/env bash +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Exercise image-digest plumbing without a cluster. The deploy script must +# forward each component digest to Helm, retain the corresponding immutable +# reference in its evidence, reject malformed or conflicting input before +# Helm runs, and keep Helm map separators out of --set-string values. + +set -euo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)" +DEPLOY="${ROOT}/odh/scripts/openshell-deploy-from-quay.sh" +WORKDIR="$(mktemp -d)" +MOCK_BIN="${WORKDIR}/bin" +HELM_LOG="${WORKDIR}/helm.log" + +# Tests below set their own image overrides. Do not let caller state change +# which validation path a negative fixture exercises. +unset GATEWAY_IMAGE GATEWAY_IMAGE_DIGEST SUPERVISOR_IMAGE SUPERVISOR_IMAGE_DIGEST +unset SANDBOX_IMAGE SANDBOX_IMAGE_DIGEST WORKLOAD_IMAGE WORKLOAD_IMAGE_TAG WORKLOAD_IMAGE_DIGEST +unset IMAGE_TAG QUAY_NAMESPACE + +cleanup() { + rm -rf "${WORKDIR}" +} +trap cleanup EXIT + +mkdir -p "${MOCK_BIN}" "${WORKDIR}/home" "${WORKDIR}/config" +: > "${HELM_LOG}" + +cat > "${MOCK_BIN}/oc" <<'OC' +#!/usr/bin/env bash +set -euo pipefail +args=("$@") +joined=" ${args[*]} " +if [[ "${joined}" == *" whoami "* ]]; then + if [[ "${joined}" == *" --show-server "* ]]; then echo https://api.example.test; else echo test-user; fi + exit 0 +fi +if [[ "${joined}" == *" api-resources "* ]]; then echo routes; exit 0; fi +if [[ "${joined}" == *" get ingresses.config/cluster "* ]]; then echo apps.example.test; exit 0; fi +if [[ "${joined}" == *" get namespace "* ]]; then exit 0; fi +if [[ "${joined}" == *" get secret openshell-client-tls "* ]]; then printf 'Y2VydA==\n'; exit 0; fi +if [[ "${joined}" == *" create namespace "* ]]; then printf 'apiVersion: v1\nkind: Namespace\n'; exit 0; fi +if [[ "${joined}" == *" label --local "* || "${joined}" == *" create -f - "* ]]; then cat; exit 0; fi +if [[ "${joined}" == *" rollout status "* || "${joined}" == *" wait "* ]]; then exit 0; fi +exit 0 +OC +chmod +x "${MOCK_BIN}/oc" + +cat > "${MOCK_BIN}/helm" <<'HELM' +#!/usr/bin/env bash +set -euo pipefail +printf '%s\n' "$*" >> "${ODH_TEST_HELM_LOG}" +if [[ "${1:-}" == get ]]; then + printf '{"gatewayConfig":{"openshell.gateway.auth":{"allow_unauthenticated_users":false},"openshell.drivers.kubernetes":{"workspace_mode":"shared","image_pull_policy":"IfNotPresent","sandbox_runtime_image_pull_policy":"IfNotPresent","supervisor_image_pull_policy":"IfNotPresent"}}}\n' +fi +HELM +chmod +x "${MOCK_BIN}/helm" + +cat > "${MOCK_BIN}/openshell" <<'OPENSH' +#!/usr/bin/env bash +exit 0 +OPENSH +chmod +x "${MOCK_BIN}/openshell" + +cat > "${MOCK_BIN}/base64" <<'BASE64' +#!/usr/bin/env bash +cat +BASE64 +chmod +x "${MOCK_BIN}/base64" + +# The deploy script probes that the Route rejects unauthenticated gRPC calls +# before registering the gateway. Answer as an mTLS-enforcing endpoint would: +# HTTP 200 with grpc-status 16 (UNAUTHENTICATED). +cat > "${MOCK_BIN}/curl" <<'CURL' +#!/usr/bin/env bash +set -euo pipefail +dump_header="" +while [[ $# -gt 0 ]]; do + case "$1" in + --dump-header) dump_header="$2"; shift 2 ;; + *) shift ;; + esac +done +if [[ -n "${dump_header}" ]]; then + printf 'HTTP/2 200\r\ngrpc-status: 16\r\n\r\n' > "${dump_header}" +fi +printf '200\n' +CURL +chmod +x "${MOCK_BIN}/curl" + +run_deploy() { + # Hermetic against caller state: XDG_CONFIG_HOME (the variable the deploy + # script actually reads — its internal XDG_CONFIG_DIR defaults from the + # caller's XDG_CONFIG_HOME) points at the temporary config, OPENSHELL_BIN + # pins the CLI to the mock instead of an inherited real binary, and a + # leftover OPENSHELL_E2E_DEPLOY_STATE_DIR from a live e2e session cannot + # redirect the deploy's state handling. + env -u ROUTE_HOST -u OPENSHELL_E2E_DEPLOY_STATE_DIR \ + PATH="${MOCK_BIN}:${PATH}" HOME="${WORKDIR}/home" \ + XDG_CONFIG_HOME="${WORKDIR}/config" ODH_TEST_HELM_LOG="${HELM_LOG}" \ + OPENSHELL_BIN="${MOCK_BIN}/openshell" \ + PYTHON_BIN="${PYTHON_BIN_REAL}" \ + IMAGE_TAG="${IMAGE_TAG:-test-tag}" NAMESPACE=openshell-digest-test RELEASE=openshell-digest-test \ + GATEWAY_NAME=openshell-digest-test \ + "${DEPLOY}" deploy --yes +} + +# Resolve a real interpreter path before the mocked environment replaces +# PATH and HOME: resolver shims (mise, venvs) need the original context. +# An explicitly configured PYTHON_BIN may be a bare command name ([[ -x ]] +# checks file paths, not PATH), so invoke it and dereference any shim via +# sys.executable — the underlying binary keeps working under the mocked +# environment, matching the unset-PYTHON_BIN fallback below. +if [[ -n "${PYTHON_BIN:-}" ]]; then + PYTHON_BIN_REAL="$("${PYTHON_BIN}" -c 'import sys; print(sys.executable)' 2>/dev/null || true)" +else + PYTHON_BIN_REAL="$(python3 -c 'import sys; print(sys.executable)' 2>/dev/null || true)" +fi +[[ -n "${PYTHON_BIN_REAL}" && -x "${PYTHON_BIN_REAL}" ]] || + { echo "FAIL: no usable python3 interpreter found for the test (PYTHON_BIN=${PYTHON_BIN:-})" >&2; exit 1; } + +digest="sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +supervisor_digest="sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" +sandbox_digest="sha256:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc" +workload_digest="sha256:dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" + +echo ">> explicit digests for every component plus a pinned workload" +GATEWAY_IMAGE_DIGEST="${digest}" SUPERVISOR_IMAGE_DIGEST="${supervisor_digest}" \ + SANDBOX_IMAGE_DIGEST="${sandbox_digest}" \ + WORKLOAD_IMAGE="registry.redhat.io/ubi9/python-312" \ + WORKLOAD_IMAGE_DIGEST="${workload_digest}" run_deploy > "${WORKDIR}/output.log" +for expected in \ + "gateway.image.digest=${digest}" \ + "supervisor.image.digest=${supervisor_digest}" \ + "sandboxRuntime.image.digest=${sandbox_digest}" \ + "sandbox.image.repository=registry.redhat.io/ubi9/python-312" \ + "sandbox.image.digest=${workload_digest}" \ + "openshiftRoute.host=openshell.apps.example.test" \ + "pkiInitJob.serverDnsNames[0]=openshell.apps.example.test" \ + "values-openshift-e2e.yaml"; do + grep -Fq -- "${expected}" "${HELM_LOG}" || { + echo "FAIL: Helm did not receive ${expected}" >&2 + exit 1 + } +done +if grep -Fq -- 'server.auth.allowUnauthenticatedUsers=true' "${HELM_LOG}"; then + echo "FAIL: ODH Route deployment must not promote unauthenticated callers" >&2 + exit 1 +fi +if grep -Fq -- 'sandbox.image.registry=' "${HELM_LOG}"; then + echo "FAIL: Helm received sandbox.image.registry, a value the chart ignores (repository must be registry-qualified)" >&2 + exit 1 +fi +for expected in \ + "odh-openshell-gateway@${digest}" \ + "odh-openshell-supervisor@${supervisor_digest}" \ + "odh-openshell-sandbox@${sandbox_digest}" \ + "registry.redhat.io/ubi9/python-312@${workload_digest}"; do + grep -Fq -- "${expected}" "${WORKDIR}/output.log" || { + echo "FAIL: deployment evidence did not contain ${expected}" >&2 + exit 1 + } +done + +: > "${HELM_LOG}" +echo ">> inline digests embedded in the image references" +GATEWAY_IMAGE="quay.io/opendatahub/odh-openshell-gateway@${digest}" \ + SUPERVISOR_IMAGE="quay.io/opendatahub/odh-openshell-supervisor@${supervisor_digest}" \ + SANDBOX_IMAGE="quay.io/opendatahub/odh-openshell-sandbox@${sandbox_digest}" \ + WORKLOAD_IMAGE="registry.redhat.io/ubi9/python-312@${workload_digest}" \ + run_deploy > "${WORKDIR}/inline.log" + +for expected in \ + "gateway.image.repository=opendatahub/odh-openshell-gateway" \ + "gateway.image.digest=${digest}" \ + "supervisor.image.repository=opendatahub/odh-openshell-supervisor" \ + "supervisor.image.digest=${supervisor_digest}" \ + "sandboxRuntime.image.repository=opendatahub/odh-openshell-sandbox" \ + "sandboxRuntime.image.digest=${sandbox_digest}" \ + "sandbox.image.repository=registry.redhat.io/ubi9/python-312" \ + "sandbox.image.digest=${workload_digest}"; do + grep -Fq -- "${expected}" "${HELM_LOG}" || { + echo "FAIL: inline digest did not produce ${expected}" >&2 + exit 1 + } +done +if grep -Fq '@sha256:' "${HELM_LOG}"; then + echo "FAIL: inline digest leaked into a Helm image repository" >&2 + exit 1 +fi + +: > "${HELM_LOG}" +echo ">> default deployment without a workload image reaches Helm" +GATEWAY_IMAGE_DIGEST="${digest}" SUPERVISOR_IMAGE_DIGEST="${supervisor_digest}" \ + SANDBOX_IMAGE_DIGEST="${sandbox_digest}" \ + run_deploy > "${WORKDIR}/no-workload.log" + +# The default path (no WORKLOAD_IMAGE) must deploy successfully and leave the +# chart's default sandbox workload image untouched: Helm receives the three +# component references and no sandbox.image.* override at all. +for expected in \ + "gateway.image.digest=${digest}" \ + "supervisor.image.digest=${supervisor_digest}" \ + "sandboxRuntime.image.digest=${sandbox_digest}"; do + grep -Fq -- "${expected}" "${HELM_LOG}" || { + echo "FAIL: default deployment did not reach Helm with ${expected}" >&2 + exit 1 + } +done +if grep -Fq -- 'sandbox.image.' "${HELM_LOG}"; then + echo "FAIL: default deployment set sandbox.image.* values without a workload image" >&2 + exit 1 +fi + +: > "${HELM_LOG}" +echo ">> conflicting inline and explicit digests are rejected" +set +e +GATEWAY_IMAGE="quay.io/opendatahub/odh-openshell-gateway@${digest}" \ + GATEWAY_IMAGE_DIGEST="${supervisor_digest}" run_deploy > "${WORKDIR}/conflict.log" 2>&1 +status=$? +set -e +[[ "${status}" != 0 ]] || { echo "FAIL: conflicting digest inputs were accepted" >&2; exit 1; } +grep -Fq 'GATEWAY_IMAGE_DIGEST conflicts with the digest already present' "${WORKDIR}/conflict.log" \ + || { echo "FAIL: conflicting digest error was not clear" >&2; exit 1; } +[[ ! -s "${HELM_LOG}" ]] || { echo "FAIL: Helm ran with conflicting digest inputs" >&2; exit 1; } + +: > "${HELM_LOG}" +echo ">> malformed digests are rejected" +set +e +SUPERVISOR_IMAGE_DIGEST='sha256:not-a-digest' run_deploy > "${WORKDIR}/invalid.log" 2>&1 +status=$? +set -e +[[ "${status}" != 0 ]] || { echo "FAIL: malformed digest was accepted" >&2; exit 1; } +grep -Fq 'SUPERVISOR_IMAGE_DIGEST must be a lowercase sha256 digest' "${WORKDIR}/invalid.log" \ + || { echo "FAIL: malformed digest error was not clear" >&2; exit 1; } +[[ ! -s "${HELM_LOG}" ]] || { echo "FAIL: Helm ran with malformed digest" >&2; exit 1; } + +: > "${HELM_LOG}" +echo ">> image references with an empty digest are rejected" +set +e +GATEWAY_IMAGE="quay.io/opendatahub/odh-openshell-gateway@" \ + run_deploy > "${WORKDIR}/empty-digest.log" 2>&1 +status=$? +set -e +[[ "${status}" != 0 ]] || { echo "FAIL: empty digest delimiter was accepted" >&2; exit 1; } +grep -Fq 'GATEWAY_IMAGE must carry a valid sha256 digest' "${WORKDIR}/empty-digest.log" \ + || { echo "FAIL: empty digest error was not clear" >&2; exit 1; } +[[ ! -s "${HELM_LOG}" ]] || { echo "FAIL: Helm ran with an empty digest delimiter" >&2; exit 1; } + +: > "${HELM_LOG}" +echo ">> image references with an empty tag are rejected" +set +e +GATEWAY_IMAGE="quay.io/opendatahub/odh-openshell-gateway:" \ + run_deploy > "${WORKDIR}/empty-tag.log" 2>&1 +status=$? +set -e +[[ "${status}" != 0 ]] || { echo "FAIL: empty tag delimiter was accepted" >&2; exit 1; } +grep -Fq 'GATEWAY_IMAGE must carry a valid image tag' "${WORKDIR}/empty-tag.log" \ + || { echo "FAIL: empty tag error was not clear" >&2; exit 1; } +[[ ! -s "${HELM_LOG}" ]] || { echo "FAIL: Helm ran with an empty tag delimiter" >&2; exit 1; } + +: > "${HELM_LOG}" +echo ">> workload inputs without a workload image are rejected" +set +e +WORKLOAD_IMAGE_DIGEST="${workload_digest}" run_deploy > "${WORKDIR}/workload-missing.log" 2>&1 +status=$? +set -e +[[ "${status}" != 0 ]] || { echo "FAIL: workload digest without image was accepted" >&2; exit 1; } +grep -Fq 'WORKLOAD_IMAGE is required when setting WORKLOAD_IMAGE_TAG or WORKLOAD_IMAGE_DIGEST' "${WORKDIR}/workload-missing.log" \ + || { echo "FAIL: workload image requirement error was not clear" >&2; exit 1; } +[[ ! -s "${HELM_LOG}" ]] || { echo "FAIL: Helm ran without a workload image" >&2; exit 1; } + +: > "${HELM_LOG}" +echo ">> workload tags conflicting with a complete workload reference are rejected" +set +e +WORKLOAD_IMAGE="quay.io/opendatahub/odh-openshell-workload:v1" \ + WORKLOAD_IMAGE_TAG="v2" \ + run_deploy > "${WORKDIR}/workload-tag-conflict.log" 2>&1 +status=$? +set -e +[[ "${status}" != 0 ]] || { echo "FAIL: workload tag conflicting with a tagged reference was accepted" >&2; exit 1; } +grep -Fq 'WORKLOAD_IMAGE_TAG conflicts with the complete reference' "${WORKDIR}/workload-tag-conflict.log" \ + || { echo "FAIL: workload tag conflict error was not clear" >&2; exit 1; } +[[ ! -s "${HELM_LOG}" ]] || { echo "FAIL: Helm ran with a conflicting workload tag" >&2; exit 1; } + +: > "${HELM_LOG}" +set +e +WORKLOAD_IMAGE="quay.io/opendatahub/odh-openshell-workload@${digest}" \ + WORKLOAD_IMAGE_TAG="v2" \ + run_deploy > "${WORKDIR}/workload-tag-digest-conflict.log" 2>&1 +status=$? +set -e +[[ "${status}" != 0 ]] || { echo "FAIL: workload tag conflicting with a digest reference was accepted" >&2; exit 1; } +grep -Fq 'WORKLOAD_IMAGE_TAG conflicts with the complete reference' "${WORKDIR}/workload-tag-digest-conflict.log" \ + || { echo "FAIL: workload tag over digest conflict error was not clear" >&2; exit 1; } +[[ ! -s "${HELM_LOG}" ]] || { echo "FAIL: Helm ran with a workload tag over a digest reference" >&2; exit 1; } + +: > "${HELM_LOG}" +echo ">> an explicit workload tag on a bare workload repository is honored" +WORKLOAD_IMAGE="quay.io/opendatahub/odh-openshell-workload" \ + WORKLOAD_IMAGE_TAG="v2" \ + run_deploy > "${WORKDIR}/workload-tag-bare.log" 2>&1 +grep -Fq 'sandbox.image.tag=v2' "${HELM_LOG}" \ + || { echo "FAIL: explicit workload tag did not reach Helm" >&2; exit 1; } +grep -Fq 'sandbox.image.repository=quay.io/opendatahub/odh-openshell-workload' "${HELM_LOG}" \ + || { echo "FAIL: bare workload run did not reach Helm with the repository" >&2; exit 1; } + +: > "${HELM_LOG}" +echo ">> Helm separators in image references are rejected" +set +e +WORKLOAD_IMAGE='registry.redhat.io/ubi9/python-312,server.auth.allowUnauthenticatedUsers=false' \ + run_deploy > "${WORKDIR}/workload-repository-invalid.log" 2>&1 +status=$? +set -e +[[ "${status}" != 0 ]] || { echo "FAIL: workload repository with Helm separator was accepted" >&2; exit 1; } +grep -Fq 'WORKLOAD_IMAGE must be a lowercase registry/repository reference without Helm separators' \ + "${WORKDIR}/workload-repository-invalid.log" \ + || { echo "FAIL: workload repository validation error was not clear" >&2; exit 1; } +[[ ! -s "${HELM_LOG}" ]] || { echo "FAIL: Helm ran with an invalid workload repository" >&2; exit 1; } + +: > "${HELM_LOG}" +set +e +WORKLOAD_IMAGE='registry.redhat.io/ubi9/python-312' \ + WORKLOAD_IMAGE_TAG='latest,sandbox.image.pullPolicy=Always' \ + run_deploy > "${WORKDIR}/workload-tag-invalid.log" 2>&1 +status=$? +set -e +[[ "${status}" != 0 ]] || { echo "FAIL: workload tag with Helm separator was accepted" >&2; exit 1; } +grep -Fq 'WORKLOAD_IMAGE_TAG must be a valid image tag without Helm separators' \ + "${WORKDIR}/workload-tag-invalid.log" \ + || { echo "FAIL: workload tag validation error was not clear" >&2; exit 1; } +[[ ! -s "${HELM_LOG}" ]] || { echo "FAIL: Helm ran with an invalid workload tag" >&2; exit 1; } + +: > "${HELM_LOG}" +set +e +GATEWAY_IMAGE='quay.io/opendatahub/odh-openshell-gateway,server.auth.allowUnauthenticatedUsers=false' \ + run_deploy > "${WORKDIR}/gateway-repository-invalid.log" 2>&1 +status=$? +set -e +[[ "${status}" != 0 ]] || { echo "FAIL: gateway repository with Helm separator was accepted" >&2; exit 1; } +grep -Fq 'GATEWAY_IMAGE must be a lowercase registry/repository reference without Helm separators' \ + "${WORKDIR}/gateway-repository-invalid.log" \ + || { echo "FAIL: gateway repository validation error was not clear" >&2; exit 1; } +[[ ! -s "${HELM_LOG}" ]] || { echo "FAIL: Helm ran with an invalid gateway repository" >&2; exit 1; } + +: > "${HELM_LOG}" +set +e +IMAGE_TAG='test-tag,server.auth.allowUnauthenticatedUsers=true' \ + run_deploy > "${WORKDIR}/image-tag-invalid.log" 2>&1 +status=$? +set -e +[[ "${status}" != 0 ]] || { echo "FAIL: image tag with Helm separator was accepted" >&2; exit 1; } +grep -Fq 'GATEWAY_IMAGE must carry a valid image tag without Helm separators' \ + "${WORKDIR}/image-tag-invalid.log" \ + || { echo "FAIL: image tag validation error was not clear" >&2; exit 1; } +[[ ! -s "${HELM_LOG}" ]] || { echo "FAIL: Helm ran with an invalid image tag" >&2; exit 1; } + +: > "${HELM_LOG}" +echo ">> uppercase image repositories are rejected" +set +e +GATEWAY_IMAGE='quay.io/opendatahub/ODH-Openshell-Gateway' \ + run_deploy > "${WORKDIR}/gateway-uppercase.log" 2>&1 +status=$? +set -e +[[ "${status}" != 0 ]] || { echo "FAIL: gateway repository with uppercase letters was accepted" >&2; exit 1; } +grep -Fq 'GATEWAY_IMAGE must be a lowercase registry/repository reference without Helm separators' \ + "${WORKDIR}/gateway-uppercase.log" \ + || { echo "FAIL: gateway uppercase validation error was not clear" >&2; exit 1; } +[[ ! -s "${HELM_LOG}" ]] || { echo "FAIL: Helm ran with an uppercase gateway repository" >&2; exit 1; } + +: > "${HELM_LOG}" +echo ">> inline tag plus digest references are preserved" +GATEWAY_IMAGE="quay.io/opendatahub/odh-openshell-gateway:odh-stable@${digest}" \ + SUPERVISOR_IMAGE="quay.io/opendatahub/odh-openshell-supervisor@${supervisor_digest}" \ + SANDBOX_IMAGE="quay.io/opendatahub/odh-openshell-sandbox@${sandbox_digest}" \ + run_deploy > "${WORKDIR}/tag-plus-digest.log" 2>&1 + +# A reference carrying both a tag and a digest is valid: the tag is +# extracted from the pre-digest component, and the digest takes +# precedence when forwarded to Helm. +for expected in \ + "gateway.image.repository=opendatahub/odh-openshell-gateway" \ + "gateway.image.digest=${digest}" \ + "supervisor.image.repository=opendatahub/odh-openshell-supervisor" \ + "supervisor.image.digest=${supervisor_digest}" \ + "sandboxRuntime.image.repository=opendatahub/odh-openshell-sandbox" \ + "sandboxRuntime.image.digest=${sandbox_digest}"; do + grep -Fq -- "${expected}" "${HELM_LOG}" || { + echo "FAIL: tag-plus-digest reference did not produce ${expected}" >&2 + exit 1 + } +done +if grep -Fq '@sha256:' "${HELM_LOG}"; then + echo "FAIL: inline digest leaked into a Helm image repository" >&2 + exit 1 +fi + +: > "${HELM_LOG}" +echo ">> inline digests with Helm separators are rejected" +set +e +GATEWAY_IMAGE="quay.io/opendatahub/odh-openshell-gateway@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,server.auth.allowUnauthenticatedUsers=true" \ + run_deploy > "${WORKDIR}/digest-separator.log" 2>&1 +status=$? +set -e +[[ "${status}" != 0 ]] || { echo "FAIL: inline digest with Helm separator was accepted" >&2; exit 1; } +grep -Fq 'GATEWAY_IMAGE must carry a valid sha256 digest without Helm separators' \ + "${WORKDIR}/digest-separator.log" \ + || { echo "FAIL: inline digest validation error was not clear" >&2; exit 1; } +[[ ! -s "${HELM_LOG}" ]] || { echo "FAIL: Helm ran with an invalid inline digest" >&2; exit 1; } + +echo "ODH deploy image-digest checks passed" diff --git a/renovate.json b/renovate.json index 527dc680a3..6be543c0ec 100644 --- a/renovate.json +++ b/renovate.json @@ -8,6 +8,68 @@ "managerFilePatterns": ["/^deploy/docker/Dockerfile\\.konflux\\.openclaw$/"], "matchStrings": ["ARG NODEJS_IMAGE=(?[^:\\s]+):(?[^@\\s]+)@(?sha256:[a-f0-9]{64})"], "datasourceTemplate": "docker" + }, + { + "customType": "regex", + "description": "Track the digest-pinned Rust builder base of the ODH e2e image", + "managerFilePatterns": ["/^deploy/docker/Dockerfile\\.konflux\\.e2e-odh$/"], + "matchStrings": ["FROM (?registry\\.redhat\\.io/rust-builder-image/rust-rhel9):(?[^@\\s]+)@(?sha256:[a-f0-9]{64})"], + "datasourceTemplate": "docker" + }, + { + "customType": "regex", + "description": "Track the digest-pinned UBI base of the ODH e2e image", + "managerFilePatterns": ["/^deploy/docker/Dockerfile\\.konflux\\.e2e-odh$/"], + "matchStrings": ["FROM (?registry\\.access\\.redhat\\.com/ubi9/ubi):(?[^@\\s]+)@(?sha256:[a-f0-9]{64})"], + "datasourceTemplate": "docker" + }, + { + "customType": "regex", + "description": "Track renovate-annotated tool versions of the ODH e2e image", + "managerFilePatterns": ["/^deploy/docker/Dockerfile\\.konflux\\.e2e-odh$/"], + "matchStrings": ["# renovate: datasource=(?\\S+) depName=(?\\S+)(?: extractVersion=(?\\S+))?\\nARG [A-Z_]+_VERSION=(?\\S+)"], + "extractVersionTemplate": "{{#if extractVersion}}{{{extractVersion}}}{{else}}^(?.+)${{/if}}" + }, + { + "customType": "regex", + "description": "Keep ODH e2e generic-fetcher URLs and filenames in the same update as the Dockerfile versions", + "managerFilePatterns": ["/^deploy/konflux/e2e-odh/generic-fetcher\\.yaml$/"], + "matchStrings": [ + "/download/(?\\d+\\.\\d+\\.\\d+)/uv-", + "filename: uv-(?\\d+\\.\\d+\\.\\d+)-" + ], + "depNameTemplate": "astral-sh/uv", + "datasourceTemplate": "github-releases" + }, + { + "customType": "regex", + "description": "Keep ODH e2e generic-fetcher Helm artifacts in the same update as the Dockerfile version", + "managerFilePatterns": ["/^deploy/konflux/e2e-odh/generic-fetcher\\.yaml$/"], + "matchStrings": ["helm-v(?\\d+\\.\\d+\\.\\d+)-linux-"], + "depNameTemplate": "helm/helm", + "datasourceTemplate": "github-releases", + "extractVersionTemplate": "^v(?.+)$" + }, + { + "customType": "regex", + "description": "Keep ODH e2e generic-fetcher cargo-nextest artifacts in the same update as the Dockerfile version", + "managerFilePatterns": ["/^deploy/konflux/e2e-odh/generic-fetcher\\.yaml$/"], + "matchStrings": ["cargo-nextest-(?\\d+\\.\\d+\\.\\d+)"], + "depNameTemplate": "nextest-rs/nextest", + "datasourceTemplate": "github-releases", + "extractVersionTemplate": "^cargo-nextest-(?.+)$" + }, + { + "customType": "regex", + "description": "Keep ODH e2e generic-fetcher OpenShift client artifacts in the same update as the Dockerfile version", + "managerFilePatterns": ["/^deploy/konflux/e2e-odh/generic-fetcher\\.yaml$/"], + "matchStrings": [ + "/ocp/(?4\\.\\d+\\.\\d+)/", + "-rhel9-(?4\\.\\d+\\.\\d+)\\.tar" + ], + "depNameTemplate": "quay.io/openshift-release-dev/ocp-release", + "datasourceTemplate": "docker", + "extractVersionTemplate": "^(?4\\.\\d+\\.\\d+)-x86_64$" } ], "packageRules": [ @@ -15,6 +77,19 @@ "description": "Automerge non-major dependency updates", "matchUpdateTypes": ["minor", "patch", "digest", "pin", "pinDigest", "lockFileMaintenance"], "automerge": true + }, + { + "description": "ODH e2e tool updates need recomputed generic-fetcher checksums, so never automerge them", + "matchFileNames": ["deploy/docker/Dockerfile.konflux.e2e-odh", "deploy/konflux/e2e-odh/generic-fetcher.yaml"], + "matchDepNames": ["astral-sh/uv", "helm/helm", "nextest-rs/nextest", "quay.io/openshift-release-dev/ocp-release"], + "automerge": false, + "prBodyNotes": ["Before merging, refresh the amd64/arm64 checksums with `deploy/konflux/e2e-odh/sync-generic-fetcher.py --update ` and commit the result; the hermetic build fails until they match."] + }, + { + "description": "ODH e2e base-image updates require review and a two-architecture hermetic build", + "matchFileNames": ["deploy/docker/Dockerfile.konflux.e2e-odh"], + "matchDepNames": ["registry.access.redhat.com/ubi9/ubi", "registry.redhat.io/rust-builder-image/rust-rhel9"], + "automerge": false } ] } diff --git a/tasks/test-odh.toml b/tasks/test-odh.toml index 26a735209a..47fbfccd6c 100644 --- a/tasks/test-odh.toml +++ b/tasks/test-odh.toml @@ -43,3 +43,9 @@ run = "odh/scripts/e2e-odh-entrypoint.sh tier2" description = "Run Tier 3: upstream + ODH, negative and destructive tests" depends = ["build:openshell-cli"] run = "odh/scripts/e2e-odh-entrypoint.sh tier3" + +["test:odh-deploy-digests"] +description = "Test ODH deploy script image-digest plumbing without a cluster" +run = "odh/scripts/tests/test-openshell-deploy-from-quay.sh" +run_windows = "echo Skipping test:odh-deploy-digests: the Unix Quay deploy script does not apply on Windows." +hide = true From 15c8dcf5308fe6116ecaea0908b14fa45f560dc1 Mon Sep 17 00:00:00 2001 From: Gaizka Menendez Date: Wed, 28 Oct 2026 17:04:59 +0000 Subject: [PATCH 2/3] fix(odh): cover generic fetcher retries Signed-off-by: Gaizka Menendez --- .github/workflows/odh-deploy-contract.yml | 9 ++ deploy/konflux/e2e-odh/README.md | 15 +- .../konflux/e2e-odh/sync-generic-fetcher.py | 68 +++++---- .../e2e-odh/sync-generic-fetcher_test.py | 137 ++++++++++++++++++ mise.toml | 2 +- .../tests/test-openshell-deploy-from-quay.sh | 2 +- tasks/test-odh.toml | 5 + tasks/test.toml | 2 + 8 files changed, 205 insertions(+), 35 deletions(-) create mode 100644 deploy/konflux/e2e-odh/sync-generic-fetcher_test.py diff --git a/.github/workflows/odh-deploy-contract.yml b/.github/workflows/odh-deploy-contract.yml index 8b85ed3382..896cc9421a 100644 --- a/.github/workflows/odh-deploy-contract.yml +++ b/.github/workflows/odh-deploy-contract.yml @@ -14,6 +14,10 @@ on: - e2e/rust/tests/odh/tiers.toml - deploy/helm/openshell/ci/values-openshift-e2e.yaml - odh/values-openshift-e2e.yaml + - deploy/docker/Dockerfile.konflux.e2e-odh + - deploy/konflux/e2e-odh/** + - renovate.json + - tasks/test-odh.toml - .github/workflows/odh-deploy-contract.yml workflow_dispatch: @@ -42,3 +46,8 @@ jobs: - name: Run the deploy digest contract suite run: bash odh/scripts/tests/test-openshell-deploy-from-quay.sh + + - name: Verify generic-fetcher synchronization + run: | + python3 deploy/konflux/e2e-odh/sync-generic-fetcher.py --check + python3 deploy/konflux/e2e-odh/sync-generic-fetcher_test.py diff --git a/deploy/konflux/e2e-odh/README.md b/deploy/konflux/e2e-odh/README.md index b3b0f7ffd9..6960680eac 100644 --- a/deploy/konflux/e2e-odh/README.md +++ b/deploy/konflux/e2e-odh/README.md @@ -65,9 +65,12 @@ Before merging, validate the local hermetic build on both `linux/amd64` and `linux/arm64` using `PLATFORM` with `deploy/konflux/build-local.sh e2e-odh`. `sync-generic-fetcher.py` keeps the Dockerfile tool versions and the Hermeto -generic artifacts consistent. `--check` (offline) verifies URLs, filenames, -and checksums match the Dockerfile; `--update ` recomputes checksums by -downloading both architectures concurrently, retrying transient failures and -verifying each hash against the checksum sidecar its publisher signs — run it -after a Renovate bump, as the PR note instructs. Nothing is written unless -every download succeeds and matches its sidecar. +generic artifacts consistent. `--check` (offline) verifies that the URLs and +filenames derive from the Dockerfile versions and that checksums are +well-formed. `--update ` recomputes checksums by downloading both +architectures concurrently, retrying transient failures and comparing each +hash with the publisher-provided checksum sidecar. This catches corruption or +inconsistent responses, but the sidecar is not an independent trust root +because it comes from the same origin as the artifact. Run it after a Renovate +bump, as the PR note instructs. Nothing is written unless every download +succeeds and matches its sidecar. diff --git a/deploy/konflux/e2e-odh/sync-generic-fetcher.py b/deploy/konflux/e2e-odh/sync-generic-fetcher.py index e74d07e5da..e63705382b 100755 --- a/deploy/konflux/e2e-odh/sync-generic-fetcher.py +++ b/deploy/konflux/e2e-odh/sync-generic-fetcher.py @@ -11,9 +11,9 @@ `--update TOOL...` rewrites the artifact list from the Dockerfile versions and recomputes the checksums of the named tools by downloading both architectures — concurrently, with retries on transient failures, each hash -verified against the checksum sidecar its publisher signs — use it after -Renovate bumps a version. Other tools keep their recorded checksums. Nothing -is written unless every download succeeds and matches its sidecar. +checked against a publisher-provided checksum sidecar — use it after Renovate +bumps a version. Other tools keep their recorded checksums. Nothing is written +unless every download succeeds and matches its sidecar. """ from __future__ import annotations @@ -28,9 +28,9 @@ import urllib.error import urllib.request from concurrent.futures import ThreadPoolExecutor, as_completed -from urllib.parse import urlparse from dataclasses import dataclass from pathlib import Path +from urllib.parse import urlparse ROOT = Path(__file__).resolve().parents[3] DOCKERFILE = ROOT / "deploy/docker/Dockerfile.konflux.e2e-odh" @@ -45,9 +45,10 @@ class Tool: arg: str url: str filename: str - # URL of the checksum sidecar the publisher signs the artifact with; - # fetched on --update so a substituted download is never blessed. + # URL and asset name recorded in the checksum sidecar. The sidecar is + # fetched on --update to catch corrupted or inconsistent downloads. sidecar: str + sidecar_filename: str arch: dict[str, str] @@ -58,6 +59,7 @@ class Tool: "https://github.com/astral-sh/uv/releases/download/{v}/uv-{a}-unknown-linux-gnu.tar.gz", "uv-{v}-{a}-unknown-linux-gnu.tar.gz", "https://github.com/astral-sh/uv/releases/download/{v}/uv-{a}-unknown-linux-gnu.tar.gz.sha256", + "uv-{a}-unknown-linux-gnu.tar.gz", _RUST_ARCH, ), "oc": Tool( @@ -65,6 +67,7 @@ class Tool: "https://mirror.openshift.com/pub/openshift-v4/clients/ocp/{v}/openshift-client-linux-{a}-rhel9-{v}.tar.gz", "openshift-client-linux-{a}-rhel9-{v}.tar.gz", "https://mirror.openshift.com/pub/openshift-v4/clients/ocp/{v}/sha256sum.txt", + "openshift-client-linux-{a}-rhel9-{v}.tar.gz", _GO_ARCH, ), "helm": Tool( @@ -72,6 +75,7 @@ class Tool: "https://get.helm.sh/helm-v{v}-linux-{a}.tar.gz", "helm-v{v}-linux-{a}.tar.gz", "https://get.helm.sh/helm-v{v}-linux-{a}.tar.gz.sha256sum", + "helm-v{v}-linux-{a}.tar.gz", _GO_ARCH, ), "nextest": Tool( @@ -79,6 +83,7 @@ class Tool: "https://github.com/nextest-rs/nextest/releases/download/cargo-nextest-{v}/cargo-nextest-{v}-{a}-unknown-linux-gnu.tar.gz", "cargo-nextest-{v}-{a}-unknown-linux-gnu.tar.gz", "https://github.com/nextest-rs/nextest/releases/download/cargo-nextest-{v}/cargo-nextest-{v}-{a}-unknown-linux-gnu.sha256", + "cargo-nextest-{v}-{a}-unknown-linux-gnu.tar.gz", _RUST_ARCH, ), } @@ -139,13 +144,14 @@ def read_fetcher(fetcher: Path = FETCHER) -> tuple[str, list[Artifact]]: return header + sep, artifacts -def expected(name: str, version: str, arch: str) -> tuple[str, str, str]: +def expected(name: str, version: str, arch: str) -> tuple[str, str, str, str]: tool = TOOLS[name] values = {"v": version, "a": tool.arch[arch]} return ( tool.url.format(**values), tool.filename.format(**values), tool.sidecar.format(**values), + tool.sidecar_filename.format(**values), ) @@ -163,7 +169,7 @@ def check(versions: dict[str, str], artifacts: list[Artifact]) -> list[str]: claimed: set[int] = set() for name in TOOLS: for arch in ARCHES: - url, filename, _ = expected(name, versions[name], arch) + url, filename, _, _ = expected(name, versions[name], arch) matches = [ i for i, a in enumerate(artifacts) @@ -199,8 +205,8 @@ def check(versions: dict[str, str], artifacts: list[Artifact]) -> list[str]: def _with_retry(url: str, consume, what: str): """Run `consume` on `url`'s response, retrying transient failures. - HTTP 4xx is permanent and raises immediately; connection errors, - timeouts, and HTTP 5xx are retried with exponential backoff. + HTTP 4xx (other than rate limiting) is permanent and raises immediately; + connection errors, timeouts, HTTP 429, and HTTP 5xx are retried. """ require_https(url) for attempt in range(1, RETRY_ATTEMPTS + 1): @@ -210,14 +216,23 @@ def _with_retry(url: str, consume, what: str): return consume(response) except urllib.error.HTTPError as err: # Client errors are permanent; the mirror hiccuping is not. - if 400 <= err.code < 500 or attempt == RETRY_ATTEMPTS: + if (400 <= err.code < 500 and err.code != 429) or attempt == RETRY_ATTEMPTS: raise last_error: Exception = err except (urllib.error.URLError, TimeoutError, OSError) as err: if attempt == RETRY_ATTEMPTS: raise last_error = err - delay = 2 ** (attempt - 1) + retry_after = ( + last_error.headers.get("Retry-After") + if isinstance(last_error, urllib.error.HTTPError) + else None + ) + delay = ( + int(retry_after) + if retry_after and retry_after.isdigit() + else 2 ** (attempt - 1) + ) print( f"{url}: {last_error}; attempt {attempt}/{RETRY_ATTEMPTS} failed " f"while {what}, retrying in {delay}s", @@ -229,9 +244,12 @@ def _with_retry(url: str, consume, what: str): def sha256_of(url: str) -> str: """Download `url` and return its `sha256:` checksum.""" - digest = hashlib.sha256() def consume(response): + # _with_retry invokes this once per response. The digest must be + # per-attempt too: a partial failed download cannot contaminate the + # checksum of a complete retry. + digest = hashlib.sha256() for chunk in iter(lambda: response.read(1 << 20), b""): digest.update(chunk) return f"sha256:{digest.hexdigest()}" @@ -241,32 +259,28 @@ def consume(response): def fetch_text(url: str) -> str: """Download `url` and return its body as text.""" - return _with_retry(url, lambda response: response.read().decode(), "fetching the sidecar") + return _with_retry( + url, lambda response: response.read().decode(), "fetching the sidecar" + ) def published_checksum(sidecar_url: str, filename: str) -> str: - """Return the checksum a publisher sidecar records for `filename`. - - Prefers the line naming the artifact exactly; falls back to a - single-checksum sidecar (uv names the file without its version). - """ + """Return the checksum a publisher sidecar records for `filename`.""" text = fetch_text(sidecar_url) lines = [line for line in text.splitlines() if line.strip()] for line in lines: parts = line.split() if len(parts) >= 2 and parts[1].lstrip("*") == filename: return f"sha256:{parts[0]}" - if len(lines) == 1: - return f"sha256:{lines[0].split()[0]}" raise SystemExit(f"{sidecar_url}: no checksum recorded for {filename}") def download_verified(url: str, sidecar_url: str, filename: str) -> str: """Download `url`, hash it, and verify the hash against the sidecar. - Without this check the download itself would be the trust root for the - checksums Hermeto later enforces: a substituted tarball would be blessed - with its own digest. + The check catches corruption or an inconsistent artifact/sidecar response; + it does not make the sidecar, which comes from the same publisher origin, + an independent trust root. """ checksum = sha256_of(url) published = published_checksum(sidecar_url, filename) @@ -324,9 +338,9 @@ def update( jobs: dict[str, tuple[str, str]] = {} # url -> (sidecar_url, filename) for name in TOOLS: for arch in ARCHES: - url, filename, sidecar = expected(name, versions[name], arch) + url, _, sidecar, sidecar_filename = expected(name, versions[name], arch) if name in tools: - jobs[url] = (sidecar, filename) + jobs[url] = (sidecar, sidecar_filename) elif url not in recorded: raise SystemExit( f"{name} {arch}: no recorded checksum for {url}; run --update {name}" @@ -350,7 +364,7 @@ def update( for name in TOOLS: group = [] for arch in ARCHES: - url, filename, _ = expected(name, versions[name], arch) + url, filename, _, _ = expected(name, versions[name], arch) checksum = checksums[url] if url in checksums else recorded[url] group.append(Artifact(url, checksum, filename)) groups.append(group) diff --git a/deploy/konflux/e2e-odh/sync-generic-fetcher_test.py b/deploy/konflux/e2e-odh/sync-generic-fetcher_test.py new file mode 100644 index 0000000000..b4f1f77c4d --- /dev/null +++ b/deploy/konflux/e2e-odh/sync-generic-fetcher_test.py @@ -0,0 +1,137 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Regression tests for the generic-fetcher checksum synchronizer.""" + +from __future__ import annotations + +import hashlib +import importlib.util +import sys +import unittest +from email.message import Message +from pathlib import Path +from unittest.mock import patch +from urllib.error import HTTPError + + +def _load_module(): + path = Path(__file__).with_name("sync-generic-fetcher.py") + spec = importlib.util.spec_from_file_location("sync_generic_fetcher", path) + assert spec is not None + assert spec.loader is not None + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +sync_generic_fetcher = _load_module() + + +class _Response: + def __init__(self, chunks: list[bytes | Exception]): + self._chunks = iter(chunks) + + def __enter__(self): + return self + + def __exit__(self, *_): + return False + + def read(self, _size: int) -> bytes: + chunk = next(self._chunks) + if isinstance(chunk, Exception): + raise chunk + return chunk + + +class _Opener: + def __init__(self, responses: list[_Response | Exception]): + self._responses = iter(responses) + + def open(self, _url: str, timeout: int): + assert timeout == 120 + response = next(self._responses) + if isinstance(response, Exception): + raise response + return response + + +class SyncGenericFetcherTests(unittest.TestCase): + def test_sha256_of_retries_with_a_fresh_hash(self) -> None: + complete = b"the complete retry response" + opener = _Opener( + [ + _Response([b"partial first response", OSError("interrupted")]), + _Response([complete, b""]), + ] + ) + with ( + patch.object( + sync_generic_fetcher.urllib.request, + "build_opener", + return_value=opener, + ), + patch.object(sync_generic_fetcher.time, "sleep"), + ): + checksum = sync_generic_fetcher.sha256_of("https://example.test/artifact") + + self.assertEqual(checksum, f"sha256:{hashlib.sha256(complete).hexdigest()}") + + def test_retry_after_is_honored_for_rate_limiting(self) -> None: + headers = Message() + headers["Retry-After"] = "7" + rate_limited = HTTPError( + "https://example.test/artifact", 429, "rate limited", headers, None + ) + complete = b"complete retry response" + opener = _Opener([rate_limited, _Response([complete, b""])]) + with ( + patch.object( + sync_generic_fetcher.urllib.request, + "build_opener", + return_value=opener, + ), + patch.object(sync_generic_fetcher.time, "sleep") as sleep, + ): + checksum = sync_generic_fetcher.sha256_of("https://example.test/artifact") + + self.assertEqual(checksum, f"sha256:{hashlib.sha256(complete).hexdigest()}") + sleep.assert_called_once_with(7) + + def test_published_checksum_requires_the_sidecar_asset_name(self) -> None: + with ( + patch.object( + sync_generic_fetcher, + "fetch_text", + return_value="a" * 64 + " unexpected-asset.tar.gz\n", + ), + self.assertRaisesRegex( + SystemExit, "no checksum recorded for expected-asset.tar.gz" + ), + ): + sync_generic_fetcher.published_checksum( + "https://example.test/artifact.sha256", "expected-asset.tar.gz" + ) + + def test_uv_sidecar_accepts_its_unversioned_asset_name(self) -> None: + _, versioned_filename, sidecar_url, sidecar_filename = ( + sync_generic_fetcher.expected("uv", "0.13.1", "amd64") + ) + self.assertNotEqual(versioned_filename, sidecar_filename) + expected_checksum = "sha256:" + "a" * 64 + with patch.object( + sync_generic_fetcher, + "fetch_text", + return_value=f"{'a' * 64} {sidecar_filename}\n", + ): + checksum = sync_generic_fetcher.published_checksum( + sidecar_url, sidecar_filename + ) + + self.assertEqual(checksum, expected_checksum) + + +if __name__ == "__main__": + unittest.main() diff --git a/mise.toml b/mise.toml index 9504f82781..c439847388 100644 --- a/mise.toml +++ b/mise.toml @@ -74,7 +74,7 @@ DOCKER_BUILDKIT = "1" [vars] # Python paths to include in formatting/linting -python_paths = "python/ tasks/scripts/*.py e2e/mcp-conformance/*.py deploy/sbom/*.py" +python_paths = "python/ tasks/scripts/*.py e2e/mcp-conformance/*.py deploy/sbom/*.py deploy/konflux/e2e-odh/*.py" [task_config] includes = ["tasks/*.toml"] diff --git a/odh/scripts/tests/test-openshell-deploy-from-quay.sh b/odh/scripts/tests/test-openshell-deploy-from-quay.sh index 7e23f505e1..edd026f297 100755 --- a/odh/scripts/tests/test-openshell-deploy-from-quay.sh +++ b/odh/scripts/tests/test-openshell-deploy-from-quay.sh @@ -98,7 +98,7 @@ run_deploy() { # pins the CLI to the mock instead of an inherited real binary, and a # leftover OPENSHELL_E2E_DEPLOY_STATE_DIR from a live e2e session cannot # redirect the deploy's state handling. - env -u ROUTE_HOST -u OPENSHELL_E2E_DEPLOY_STATE_DIR \ + env -u ROUTE_HOST -u OPENSHELL_E2E_RUN_ID -u OPENSHELL_E2E_DEPLOY_STATE_DIR \ PATH="${MOCK_BIN}:${PATH}" HOME="${WORKDIR}/home" \ XDG_CONFIG_HOME="${WORKDIR}/config" ODH_TEST_HELM_LOG="${HELM_LOG}" \ OPENSHELL_BIN="${MOCK_BIN}/openshell" \ diff --git a/tasks/test-odh.toml b/tasks/test-odh.toml index 47fbfccd6c..99e2a37fc2 100644 --- a/tasks/test-odh.toml +++ b/tasks/test-odh.toml @@ -49,3 +49,8 @@ description = "Test ODH deploy script image-digest plumbing without a cluster" run = "odh/scripts/tests/test-openshell-deploy-from-quay.sh" run_windows = "echo Skipping test:odh-deploy-digests: the Unix Quay deploy script does not apply on Windows." hide = true + +["test:odh-generic-fetcher"] +description = "Test ODH generic-fetcher checksum synchronization" +run = "python3 deploy/konflux/e2e-odh/sync-generic-fetcher_test.py" +hide = true diff --git a/tasks/test.toml b/tasks/test.toml index 95e049d9ab..bb664350a3 100644 --- a/tasks/test.toml +++ b/tasks/test.toml @@ -23,6 +23,8 @@ depends = [ "test:docs-website", "test:docs-nav", "test:maintainer-approval", + "test:odh-deploy-digests", + "test:odh-generic-fetcher", ] ["test:docs-website"] From 8f469b1074adf3ed0a797e087ba0b5c1734b814e Mon Sep 17 00:00:00 2001 From: Gaizka Menendez Date: Wed, 28 Oct 2026 17:11:38 +0000 Subject: [PATCH 3/3] fix(odh): avoid redundant aggregate task wiring --- tasks/test.toml | 2 -- 1 file changed, 2 deletions(-) diff --git a/tasks/test.toml b/tasks/test.toml index bb664350a3..95e049d9ab 100644 --- a/tasks/test.toml +++ b/tasks/test.toml @@ -23,8 +23,6 @@ depends = [ "test:docs-website", "test:docs-nav", "test:maintainer-approval", - "test:odh-deploy-digests", - "test:odh-generic-fetcher", ] ["test:docs-website"]