From c0a807fe5de0f0080f06f6aa97b3545224aae92e Mon Sep 17 00:00:00 2001 From: Anand Topu Date: Sat, 28 Nov 2026 11:43:30 -0600 Subject: [PATCH 1/2] Pin release deployment images to verified digests Daybreak revision 5 (arp_aa6aa19372262ed76c81159319d61ef8). Signed-off-by: Anand Topu --- .github/workflows/ci.yml | 36 ++- .github/workflows/offline-bundle.yml | 23 +- Makefile | 4 +- ...test_installer_checks_release_checksums.py | 75 ++++- .../tests/test_verified_release_promotion.py | 9 + deploy/images.manifest.txt | 6 +- docs/operations/deploy-compose.md | 6 +- docs/operations/deploy-openshift.md | 23 +- e2e-runner/merge_upgrade.py | 8 +- e2e-runner/run.py | 4 +- e2e-runner/test_merge_upgrade.py | 1 + e2e-runner/upgrade.py | 5 +- e2e-runner/upgrade_baseline.py | 4 +- install.sh | 58 +++- k8s/overlays/openshift-artifactory/route.yaml | 2 +- openshiftsetup/artifactory.env.example | 16 +- .../deploy-openshift-artifactory.sh | 250 +++++++++++++--- openshiftsetup/mirror-images.sh | 119 ++++++-- scripts/deploy-k8s.sh | 26 +- scripts/release/check_image_drift.py | 32 ++- scripts/release/image-manifest.sh | 30 ++ .../release/pull-offline-telemetry-images.sh | 36 +++ scripts/release/release_manifest.py | 149 ++++++++-- scripts/release/scan_release_images.py | 2 +- scripts/release/test_image_drift.py | 53 +++- .../release/tests/test_release_manifest.py | 92 +++++- .../release/tests/test_release_transport.py | 270 ++++++++++++++++++ .../release/tests/test_scan_release_images.py | 8 +- scripts/release/verify_kubernetes_rollout.py | 7 +- user-guide/air-gapped-install.md | 18 +- 30 files changed, 1175 insertions(+), 197 deletions(-) create mode 100755 scripts/release/pull-offline-telemetry-images.sh create mode 100644 scripts/release/tests/test_release_transport.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8751bc8e5..0c77359c4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -138,6 +138,11 @@ jobs: # `pip install pytest` takes whatever PyPI serves that minute. run: pip install --require-hashes -r scripts/requirements-ci.txt + - name: Set up Kustomize for release transport tests + uses: imranismail/setup-kustomize@53f941b41dca13ed61874bbc6b4b6e1562877530 # v3.0.0 + with: + kustomize-version: "5.7.1" + - name: Self-test the drift guard # Pins that the guard actually FAILS on drift — a guard that can only # pass is a guard that silently rots. @@ -2243,11 +2248,26 @@ jobs: - name: Create and validate verified image manifest run: | set -euo pipefail + # deploy/images.manifest.txt remains the reviewed version catalogue; + # this signed release identity records what every catalogue tag + # resolved to in this CI run. Downstream release paths consume only + # these immutable refs, so a later upstream tag move is irrelevant. + source scripts/release/image-manifest.sh + image_args=( + --image "backend=${{ env.REGISTRY }}/${{ env.IMAGE_PREFIX }}/backend@${{ steps.build-backend.outputs.digest }}" + --image "frontend=${{ env.REGISTRY }}/${{ env.IMAGE_PREFIX }}/frontend@${{ steps.build-frontend.outputs.digest }}" + --image "mcp=${{ env.REGISTRY }}/${{ env.IMAGE_PREFIX }}/mcp@${{ steps.build-mcp.outputs.digest }}" + ) + while IFS= read -r ref; do + component="$(manifest_ref_component "$ref")" + digest="$(docker buildx imagetools inspect "$ref" --format '{{json .Manifest}}' | jq -r '.digest')" + [[ "$digest" =~ ^sha256:[0-9a-f]{64}$ ]] \ + || { echo "::error::$ref did not resolve to an immutable sha256 digest"; exit 1; } + image_args+=(--image "$component=$ref@$digest") + done < <(manifest_refs any infra core,llm,external) python3 scripts/release/release_manifest.py create \ --source-sha "${GITHUB_SHA}" --version "${{ steps.manifest-version.outputs.version }}" \ - --image "backend=${{ env.REGISTRY }}/${{ env.IMAGE_PREFIX }}/backend@${{ steps.build-backend.outputs.digest }}" \ - --image "frontend=${{ env.REGISTRY }}/${{ env.IMAGE_PREFIX }}/frontend@${{ steps.build-frontend.outputs.digest }}" \ - --image "mcp=${{ env.REGISTRY }}/${{ env.IMAGE_PREFIX }}/mcp@${{ steps.build-mcp.outputs.digest }}" \ + "${image_args[@]}" \ --output verified-images/release-manifest.json python3 scripts/release/release_manifest.py validate --manifest verified-images/release-manifest.json --expected-source-sha "${GITHUB_SHA}" - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 @@ -2382,11 +2402,19 @@ jobs: if manifest["images"][component]["source_ref"] != expected: raise SystemExit("Build output and verified image manifest disagree") PY + infra_images=() + while IFS=$'\t' read -r _ ref; do + tagged_ref="${ref%@sha256:*}" + image_name="${tagged_ref%:*}" + infra_images+=("$image_name=$ref") + done < <(python3 scripts/release/release_manifest.py refs \ + --manifest verified-images/release-manifest.json --kind infrastructure) cd k8s/overlays/dev kustomize edit set image \ "ghcr.io/test-intelligence/testlookup/backend=$REGISTRY/$IMAGE_PREFIX/backend@$BACKEND_DIGEST" \ "ghcr.io/test-intelligence/testlookup/frontend=$REGISTRY/$IMAGE_PREFIX/frontend@$FRONTEND_DIGEST" \ - "ghcr.io/test-intelligence/testlookup/mcp=$REGISTRY/$IMAGE_PREFIX/mcp@$MCP_DIGEST" + "ghcr.io/test-intelligence/testlookup/mcp=$REGISTRY/$IMAGE_PREFIX/mcp@$MCP_DIGEST" \ + "${infra_images[@]}" - name: Authenticate read-only registry inspection if: steps.check-secret.outputs.skip != 'true' diff --git a/.github/workflows/offline-bundle.yml b/.github/workflows/offline-bundle.yml index 122d89dca..1d865447d 100644 --- a/.github/workflows/offline-bundle.yml +++ b/.github/workflows/offline-bundle.yml @@ -159,6 +159,27 @@ jobs: docker tag "$manifest_ref" "testlookup/$component:$BUNDLE_VERSION" printf '%s\t%s\n' "$component" "$manifest_ref" >> release-images.txt done + source scripts/release/image-manifest.sh + infra_filter=core + if [ "$WITH_LLM" = true ]; then infra_filter=core,llm; fi + while IFS= read -r tagged_ref; do + component="$(manifest_ref_component "$tagged_ref")" + manifest_ref="$(jq -r ".images.$component.source_ref" verified-images/release-manifest.json)" + [ "${manifest_ref%@sha256:*}" = "$tagged_ref" ] \ + || { echo "::error::signed $component ref '$manifest_ref' does not lock catalogue ref '$tagged_ref'"; exit 1; } + [[ "${manifest_ref##*@sha256:}" =~ ^[0-9a-f]{64}$ ]] \ + || { echo "::error::signed $component ref is not digest-addressed"; exit 1; } + docker pull "$manifest_ref" + docker tag "$manifest_ref" "$tagged_ref" + done < <(manifest_refs any infra "$infra_filter") + if [ "$WITH_TELEMETRY" = true ]; then + # These optional rows are already immutable in the catalogue and + # are not part of the production release manifest. A tagged bundle + # uses --skip-pull below, so preload them on a fresh runner now. + # The helper selects only `telemetry`, never the AGPL + # `telemetry-external` prerequisites. + bash scripts/release/pull-offline-telemetry-images.sh + fi cat release-images.txt - name: Set up kustomize @@ -198,7 +219,7 @@ jobs: args=(--version "$BUNDLE_VERSION" --created-at "${{ steps.meta.outputs.created_at }}") if [ "$WITH_LLM" = true ]; then args+=(--with-llm); fi if [ "$WITH_TELEMETRY" = true ]; then args+=(--with-telemetry); fi - if [ -n "$RELEASE_TAG" ]; then args+=(--skip-build); fi + if [ -n "$RELEASE_TAG" ]; then args+=(--skip-build --skip-pull); fi bash scripts/release/offline-bundle.sh "${args[@]}" # The bundle must carry the pulled digests, not a local build: diff --git a/Makefile b/Makefile index fed259d55..6cf79f80d 100644 --- a/Makefile +++ b/Makefile @@ -367,10 +367,10 @@ k8s-deploy-k3s-update: ## Rebuild images and redeploy to the K3s cluster (skip r k8s-deploy-openshift-artifactory: ## Air-gapped OpenShift deploy over HTTPS, all images from one Artifactory (config: openshiftsetup/artifactory.env; flags via ARGS) $(BASH_CMD) openshiftsetup/deploy-openshift-artifactory.sh $(ARGS) -k8s-deploy-openshift-artifactory-update: ## Rebuild app images + redeploy to OpenShift, reuse already-mirrored infra images +k8s-deploy-openshift-artifactory-update: ## Redeploy with --skip-mirror; verified releases still authenticate and check every destination digest $(BASH_CMD) openshiftsetup/deploy-openshift-artifactory.sh --skip-mirror $(ARGS) -k8s-mirror-images-openshift: ## Pre-seed the configured Artifactory with all third-party infra images (run on an internet-connected host) +k8s-mirror-images-openshift: ## Pre-seed signed third-party digests (ARGS="--manifest ... --provenance ...") $(BASH_CMD) openshiftsetup/mirror-images.sh $(ARGS) k8s-status: ## Show Kubernetes deployment status diff --git a/backend/tests/regression/test_installer_checks_release_checksums.py b/backend/tests/regression/test_installer_checks_release_checksums.py index 6be053a9e..d1083ebb7 100644 --- a/backend/tests/regression/test_installer_checks_release_checksums.py +++ b/backend/tests/regression/test_installer_checks_release_checksums.py @@ -8,8 +8,8 @@ The rule: when the ref being installed is a release tag (``vX.Y.Z`` in ``TL_REF`` or ``TESTLOOKUP_VERSION``), the installer authenticates that release's ``SHA256SUMS`` and immutable image manifest, compares every file it -fetched, verifies each application-image digest, and generates a Compose -override BEFORE it writes into the install directory or runs anything it +fetched, verifies the complete application-and-infrastructure digest set, and +generates a Compose override BEFORE it writes into the install directory or runs anything it downloaded. A mismatch or missing release asset stops the install. For an untagged ref (``TL_REF=main``, the unreleased tip, only when asked for) there is nothing to compare with, and it says so. With no ref and no version given, the installer @@ -40,7 +40,29 @@ TAG = "v9.9.9" FILES = ("docker-compose.release.yml", ".env.example", "scripts/gen-dev-env.sh", "scripts/init-db.sql") SOURCE_SHA = "a" * 40 -DIGESTS = {"backend": "1" * 64, "frontend": "2" * 64, "mcp": "3" * 64} +APP_COMPONENTS = ("backend", "frontend", "mcp") +INFRA_NAMES = { + "postgres": "postgres:16-alpine", + "valkey": "valkey/valkey:8.1-alpine", + "mongo": "mongo:7", + "versitygw": "ghcr.io/versity/versitygw:v1.8.0", + "busybox": "busybox:1.36", + "ollama": "ollama/ollama:0.40.10", + "chroma": "chromadb/chroma:1.5.9", +} +COMPONENTS = APP_COMPONENTS + tuple(INFRA_NAMES) +DIGESTS = {component: format(index, "x") * 64 for index, component in enumerate(COMPONENTS, start=1)} + + +def _image(component: str) -> str: + name = ( + f"ghcr.io/test-intelligence/testlookup/{component}" + if component in APP_COMPONENTS + else INFRA_NAMES[component] + ) + return f"{name}@sha256:{DIGESTS[component]}" + + #: Stands in for the real generator: proves whether a downloaded script ran. FAKE_GENERATOR = '#!/usr/bin/env bash\ncd "$(dirname "$0")/.."\necho "MARKER=the-downloaded-script-ran" > .env\n' _TIMEOUT_S = 300 # a hang guard, not a speed bound: process start-up is slow on Windows @@ -82,14 +104,12 @@ def _release(tmp_path: Path, ref: str, *, sums: bool = True, tamper: str | None published.mkdir(parents=True) (published / "SHA256SUMS").write_bytes("".join(lines).encode()) manifest = { - "schema_version": 1, + "schema_version": 2, "source_sha": SOURCE_SHA, "version": ref, "images": { - component: { - "source_ref": f"ghcr.io/test-intelligence/testlookup/{component}@sha256:{DIGESTS[component]}" - } - for component in ("backend", "frontend", "mcp") + component: {"source_ref": _image(component)} + for component in COMPONENTS }, } (published / "release-manifest.json").write_text( @@ -150,7 +170,7 @@ def test_a_release_install_checks_every_file_then_runs(tmp_path): assert "docker compose -f docker-compose.release.yml -f docker-compose.images.yml" in result.stdout -def test_a_release_uses_only_authenticated_digest_refs_for_every_application_service(tmp_path): +def test_a_release_uses_only_authenticated_digest_refs_for_every_release_service(tmp_path): env = _release(tmp_path, TAG) env["TL_REF"] = TAG result = _install(tmp_path, env) @@ -161,22 +181,28 @@ def test_a_release_uses_only_authenticated_digest_refs_for_every_application_ser expected_components = {} for service, definition in release["services"].items(): image_ref = definition.get("image", "") - for component in ("backend", "frontend", "mcp"): + for component in APP_COMPONENTS: if f"/{component}:${{TESTLOOKUP_VERSION:-latest}}" in image_ref: expected_components[service] = component + expected_components.update({ + "postgres": "postgres", + "mongo": "mongo", + "redis": "valkey", + "minio": "versitygw", + "ollama": "ollama", + "chromadb": "chroma", + }) assert set(override["services"]) == set(expected_components), ( - "every tag-addressed application service in the release Compose file needs a digest override" + "every tag-addressed release service in the Compose file needs a digest override" ) for service, component in expected_components.items(): - assert override["services"][service]["image"] == ( - f"ghcr.io/test-intelligence/testlookup/{component}@sha256:{DIGESTS[component]}" - ) + assert override["services"][service]["image"] == _image(component) assert all("@sha256:" in service["image"] for service in override["services"].values()) checks = (tmp_path / "gh.log").read_text(encoding="utf-8") assert "attestation verify" in checks assert "SHA256SUMS" in checks and "release-manifest.json" in checks - for component in ("backend", "frontend", "mcp"): + for component in APP_COMPONENTS: assert f"oci://ghcr.io/test-intelligence/testlookup/{component}@sha256:{DIGESTS[component]}" in checks assert f"--source-digest {SOURCE_SHA}" in checks @@ -193,6 +219,22 @@ def test_a_manifest_without_trusted_provenance_stops_before_installing_or_runnin assert not (tmp_path / "install" / "docker-compose.images.yml").exists() +def test_an_incomplete_signed_image_set_stops_before_installing_or_running(tmp_path): + env = _release(tmp_path, TAG) + env["TL_REF"] = TAG + manifest_path = tmp_path / "served" / "releases" / TAG / "release-manifest.json" + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + manifest["images"].pop("postgres") + manifest_path.write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8") + + result = _install(tmp_path, env) + + assert result.returncode != 0 + assert "exactly ten application and infrastructure image references" in result.stderr + assert not (tmp_path / "install" / ".env").exists() + assert not (tmp_path / "install" / "docker-compose.images.yml").exists() + + def test_a_custom_registry_keeps_the_authenticated_digests(tmp_path): env = _release(tmp_path, TAG) env["TL_REF"] = TAG @@ -208,6 +250,9 @@ def test_a_custom_registry_keeps_the_authenticated_digests(tmp_path): ) assert services["frontend"]["image"].endswith(f"/frontend@sha256:{DIGESTS['frontend']}") assert services["mcp"]["image"].endswith(f"/mcp@sha256:{DIGESTS['mcp']}") + for service, component in (("postgres", "postgres"), ("mongo", "mongo"), ("redis", "valkey"), + ("minio", "versitygw"), ("ollama", "ollama"), ("chromadb", "chroma")): + assert services[service]["image"] == _image(component) def test_release_files_and_requested_image_release_must_match(tmp_path): diff --git a/backend/tests/test_verified_release_promotion.py b/backend/tests/test_verified_release_promotion.py index 1e4527bc7..d6219c989 100644 --- a/backend/tests/test_verified_release_promotion.py +++ b/backend/tests/test_verified_release_promotion.py @@ -200,6 +200,8 @@ def test_manifest_tool_is_present_for_workflow_validation_and_materialization(): assert command in text, f"release manifest tool must expose {command!r}" for component in COMPONENTS: assert component in text, f"release manifest tool must require the {component} digest" + for component in ("postgres", "valkey", "mongo", "versitygw", "busybox", "ollama", "chroma"): + assert component in text, f"release manifest tool must require the {component} digest" assert "@sha256:" in text, "release manifest tool must reject mutable tag-only references" @@ -230,6 +232,9 @@ def test_main_image_manifest_resolves_version_file_before_publishing_images(): create_run = str(step_by_name["Create and validate verified image manifest"].get("run", "")) assert "steps.manifest-version.outputs.version" in create_run assert "GITHUB_REF_NAME" not in create_run + assert "manifest_refs any infra core,llm,external" in create_run + assert "docker buildx imagetools inspect" in create_run + assert 'image_args+=(--image "$component=$ref@$digest")' in create_run def test_dev_migration_and_backend_rollout_use_the_same_immutable_digest(): @@ -251,6 +256,8 @@ def test_dev_migration_and_backend_rollout_use_the_same_immutable_digest(): assert 'release_manifest.py validate --manifest verified-images/release-manifest.json --expected-source-sha "$GITHUB_SHA"' in pin["run"] assert 'expected = f"{root}/{component}@{os.environ[component.upper() + \'_DIGEST\']}"' in pin["run"] assert 'manifest["images"][component]["source_ref"] != expected' in pin["run"] + assert "--kind infrastructure" in pin["run"] + assert 'infra_images+=("$image_name=$ref")' in pin["run"] assert backend_ref in migrate assert "run-k8s-migrations.sh testlookup-dev" in migrate assert "verify_kubernetes_rollout.py" in verify @@ -264,6 +271,8 @@ def test_deploy_helper_preserves_the_complete_kustomize_resource_tree(): assert 'cp -r k8s "$TMP_ROOT/k8s"' in script assert 'TMP_OVERLAY="$TMP_ROOT/$OVERLAY"' in script assert 'cp -r "$OVERLAY" "$TMP_OVERLAY"' not in script + assert "for img in backend frontend mcp postgres valkey mongo versitygw busybox ollama chroma" in script + assert 'kubectl kustomize edit set image "$source_name=$ref"' in script def test_airgap_override_routes_the_migration_service_to_the_private_registry(): diff --git a/deploy/images.manifest.txt b/deploy/images.manifest.txt index b4fcdeb95..d914f2fc0 100644 --- a/deploy/images.manifest.txt +++ b/deploy/images.manifest.txt @@ -15,7 +15,11 @@ # read), Python (stdlib only) and the CI drift guard can all parse it without # PyYAML — the drift guard has to run in a job that installs nothing. # -# 1. ref full image reference incl. tag. App images use the literal +# 1. ref reviewed version-catalogue reference incl. tag. Release CI +# resolves every production infra row to @sha256 and records +# the complete set in signed release-manifest.json; installers +# and mirror scripts reject infra refs outside that digest set. +# App images use the literal # tag `@APP_TAG`, resolved at build time (bundle version / # build-YYYYMMDD-HHMMSS / BUILD_TAG_PLACEHOLDER depending on # the deploy path) — only their NAMES are drift-checked. diff --git a/docs/operations/deploy-compose.md b/docs/operations/deploy-compose.md index edfb3943e..6963f3077 100644 --- a/docs/operations/deploy-compose.md +++ b/docs/operations/deploy-compose.md @@ -86,7 +86,7 @@ The lite stack omits Ollama, ChromaDB, Flower, the MCP server and the beat sched curl -fsSL https://raw.githubusercontent.com/test-intelligence/testlookup/main/install.sh | bash ``` -It checks for Docker and Compose v2, downloads `docker-compose.release.yml`, `.env.example`, `scripts/gen-dev-env.sh` and `scripts/init-db.sql` into `./testlookup`, authenticates the release checksums and exact application-image digests, generates `.env` with `scripts/gen-dev-env.sh --release` (an existing `.env` is reused), and starts Compose with a generated `docker-compose.images.yml` digest override. Read the script before piping it to a shell if your policy requires it. +It checks for Docker and Compose v2, downloads `docker-compose.release.yml`, `.env.example`, `scripts/gen-dev-env.sh` and `scripts/init-db.sql` into `./testlookup`, authenticates the release checksums and the complete application-and-infrastructure digest set, generates `.env` with `scripts/gen-dev-env.sh --release` (an existing `.env` is reused), and starts Compose with a generated `docker-compose.images.yml` digest override. Read the script before piping it to a shell if your policy requires it. `--release` fills every secret with a random value and keeps the secure defaults: `APP_ENV=production` and `DEV_AUTO_LOGIN_ENABLED=false`, so there is no passwordless login. It also writes a random `INITIAL_ADMIN_PASSWORD` into `.env`. On first start the `db-migrate` service runs `alembic upgrade head` and then `scripts/create_admin.py`, which creates the user `admin` with that password on a new database only (an existing admin is never modified) and requires a password change at the first sign-in. @@ -97,7 +97,7 @@ The installer also explains that port 3000 is plain HTTP bound to `127.0.0.1` by | Variable | Default | Effect | |---|---|---| | `TL_DIR` | `testlookup` | Install directory | -| `TL_REF` | the latest published release | Branch, tag or commit the files are downloaded from. With a release tag (`vX.Y.Z`) the installer authenticates `SHA256SUMS`, `release-manifest.json`, and every application-image digest before startup. With neither this nor `TESTLOOKUP_VERSION` set, it looks up the latest release; if the lookup fails it stops. `TL_REF=main` explicitly installs the unverified tip and uses `latest` | +| `TL_REF` | the latest published release | Branch, tag or commit the files are downloaded from. With a release tag (`vX.Y.Z`) the installer authenticates `SHA256SUMS`, `release-manifest.json`, and every application and infrastructure digest before startup. With neither this nor `TESTLOOKUP_VERSION` set, it looks up the latest release; if the lookup fails it stops. `TL_REF=main` explicitly installs the unverified tip and uses `latest` | | `TESTLOOKUP_VERSION` | the release in `TL_REF` | Release to install. With a release tag (`vX.Y.Z`) and no `TL_REF`, files follow the same release; when both are release tags they must match | | `TL_RAW_BASE` | `https://raw.githubusercontent.com/test-intelligence/testlookup` | Where the files are downloaded from (a mirror) | | `TL_RELEASE_BASE` | `https://github.com/test-intelligence/testlookup/releases/download` | Where `SHA256SUMS`, `release-manifest.json`, and the release's Sigstore bundle are downloaded from (a mirror) | @@ -110,7 +110,7 @@ With nothing set, the installer installs the latest published release. To instal ### Image tags -Images are `ghcr.io/test-intelligence/testlookup/backend`, `.../frontend` and `.../mcp`; `TESTLOOKUP_IMAGE` can repoint an install to a mirror while preserving each authenticated digest. CI publishes `latest` and the full commit SHA for every build of `main`, and the release workflow adds a `vX.Y.Z` alias after verification. The installer never relies on that mutable alias: `docker-compose.images.yml` names `repository@sha256:...` for every application service. Keep both `-f docker-compose.release.yml -f docker-compose.images.yml` in later Compose commands. +Application images are `ghcr.io/test-intelligence/testlookup/backend`, `.../frontend` and `.../mcp`; `TESTLOOKUP_IMAGE` can repoint them to a mirror while preserving each authenticated digest. CI publishes `latest` and the full commit SHA for every build of `main`, and the release workflow adds a `vX.Y.Z` alias after verification. The installer never relies on mutable aliases: `docker-compose.images.yml` names `repository@sha256:...` for every application and infrastructure service. Keep both `-f docker-compose.release.yml -f docker-compose.images.yml` in later Compose commands. ### Without the installer diff --git a/docs/operations/deploy-openshift.md b/docs/operations/deploy-openshift.md index d0c550ba2..17b5fd348 100644 --- a/docs/operations/deploy-openshift.md +++ b/docs/operations/deploy-openshift.md @@ -49,7 +49,8 @@ The committed overlay contains `*_PLACEHOLDER` tokens (registry, tag, storage cl ### Prerequisites on the build host -- `docker`, `oc` (or `kubectl`; Route certificate injection and the `anyuid` grant need `oc`), `curl`, `openssl`. +- Verified release: `gh`, `python3`, `skopeo`, Kustomize 5.7.1 (the tested version), `oc` (or `kubectl`; Route certificate injection and the `anyuid` grant need `oc`) and `openssl`. +- Deliberate non-release local build: `docker`, `curl`, `oc` (or `kubectl`) and `openssl`. - `oc login` to the target cluster. - Push access to the Artifactory repository. @@ -63,11 +64,13 @@ make k8s-deploy-openshift-artifactory Every value can also come from the environment (the environment wins). `ARTIFACTORY_ENV_FILE` points the scripts at another config file. Keep the filled-in file out of version control. +Setting either release input selects verified-release mode and requires both. Omitting both is retained only for deliberate local-image development: pre-seed the infrastructure repositories, pass `--skip-mirror`, and use the build/tag flags below. That mode does not claim release provenance. + | Variable | Required | Meaning | |---|---|---| | `ARTIFACTORY_REGISTRY` | yes | Docker repository base for every image, without scheme or trailing slash, e.g. `artifactory.example.com/testlookup-docker` | | `ARTIFACTORY_PULL_REGISTRY` | no | Address the cluster pulls from when it differs from the push address (for example a virtual repository); defaults to `ARTIFACTORY_REGISTRY` | -| `ARTIFACTORY_USERNAME`, `ARTIFACTORY_PASSWORD` | no | Used for `docker login` and for the in-cluster pull secret `artifactory-pull` (linked to the default service account). Use an API key or identity token as the password. Without them the script assumes Docker is already logged in and the cluster can pull anonymously | +| `ARTIFACTORY_USERNAME`, `ARTIFACTORY_PASSWORD` | no | Used for the registry-client login and for the in-cluster pull secret `artifactory-pull` (linked to the default service account and keyed to `ARTIFACTORY_PULL_REGISTRY`). Use an API key or identity token as the password. Without them the script assumes the client is already logged in and the cluster can pull anonymously | | `ARTIFACTORY_EMAIL` | no | Email on the pull secret | | `APPS_DOMAIN` | yes, unless all three hosts are set | The cluster's apps wildcard domain; hosts become `testlookup.`, `testlookup-api.` and `testlookup-mcp.` under it | | `ROUTE_HOST_FRONTEND`, `ROUTE_HOST_API`, `ROUTE_HOST_MCP` | no | Explicit Route hosts; override `APPS_DOMAIN` | @@ -77,15 +80,15 @@ Every value can also come from the environment (the environment wins). `ARTIFACT | `GRANT_ANYUID` | no | `true` grants the `anyuid` SCC to the `testlookup-anyuid` service account, which only the bundled data stores and Ollama use, so the stock images run with their expected UIDs (the application pods get `nonroot-v2`; `GRANT_NONROOT`, default `true`). An install from before this change keeps the old grant on `default` until one run with `REVOKE_DEFAULT_ANYUID=true`. `ENABLE_MONGO_AUTH=true` turns on MongoDB authentication (off by default; the bundled Valkey always gets a generated password); set `false` (or pass `--no-anyuid`) on hardened clusters with UID-agnostic images | | `ADMIN_USERNAME`, `ADMIN_EMAIL`, `ADMIN_FULL_NAME` | no | The first admin account | | `ADMIN_PASSWORD` | no | Leave empty: the script generates the password at first install and prints it once. Set it only to choose your own | -| `INFRA_IMAGES` | no | Space-separated third-party images to mirror. Empty derives the list from `deploy/images.manifest.txt`; set it only to mirror a subset | +| `RELEASE_MANIFEST`, `RELEASE_PROVENANCE_BUNDLE` | yes for a release, including `--skip-mirror` | Paths to the selected release's `release-manifest.json` and `.intoto.jsonl` provenance bundle; the script authenticates the complete schema-v2 image set before registry or cluster release work | | `PULL_OLLAMA_MODELS`, `OLLAMA_MODELS` | no | `true` pulls the listed models into the in-cluster Ollama after deploy. This needs a model mirror reachable from the cluster; otherwise load weights from an [offline model pack](../../user-guide/offline-model-pack.md) | | `APP_TAG` | no | With `--skip-build`, the existing `build-YYYYMMDD-HHMMSS` tag to deploy; empty picks the newest tag present for all three images | ### What the script does -1. Preflight: checks Docker, `curl`, cluster login and the configuration. -2. Builds the backend, frontend and MCP images and pushes them under an immutable `build-YYYYMMDD-HHMMSS` tag. -3. Mirrors the third-party images into the same Artifactory, keeping their repository paths. +1. Authenticates and validates the selected release's complete schema-v2 image manifest before registry, cluster or rendering work. +2. Copies every signed application and infrastructure manifest index, including all platforms, into Artifactory with `skopeo --all --preserve-digests`; `--skip-mirror` instead proves every destination `repository@sha256` exists. +3. Materializes the push and private cluster-pull registry mappings separately, then renders every workload and the migration Job with the cluster's `repository@sha256` reference. No application image is rebuilt in release mode. 4. Creates the project and the `artifactory-pull` image-pull secret, and grants `anyuid` when enabled. 5. Creates `testlookup-secrets` with generated values on first install (an existing Secret is kept) and writes the generated database and object-store credentials to `openshiftsetup/.openshift-credentials`, which Git ignores. 6. Resolves the StorageClass, substitutes the placeholders and runs the migration Job (before the apply on an upgrade, after it on a fresh install), then applies the overlay. @@ -93,9 +96,9 @@ Every value can also come from the environment (the environment wins). `ARTIFACT | Flag | Effect | |---|---| -| `--skip-build` | Reuse an existing tag instead of building | -| `--skip-push` | Build but do not push (local smoke test) | -| `--skip-mirror` | Do not mirror third-party images (already present). `make k8s-deploy-openshift-artifactory-update` uses this to redeploy new application images | +| `--skip-build` | Non-release mode only: reuse an existing tag instead of building | +| `--skip-push` | Non-release mode only: build but do not push (local smoke test) | +| `--skip-mirror` | Do not copy release images, but still authenticate the manifest and verify every signed destination digest before rendering | | `--no-anyuid` | Do not grant the `anyuid` SCC | | `--skip-admin` | Do not create the first admin | | `--dry-run` | Render the manifests and exit | @@ -104,7 +107,7 @@ Every value can also come from the environment (the environment wins). `ARTIFACT ### Pre-seed the registry separately -`openshiftsetup/mirror-images.sh` (or `make k8s-mirror-images-openshift`) mirrors only the third-party images, for teams that seed Artifactory ahead of time or refresh images without rebuilding the application. It reads the same `artifactory.env`, requires `ARTIFACTORY_REGISTRY`, derives the image list from `deploy/images.manifest.txt` unless `INFRA_IMAGES` is set, and accepts `--dry-run` to print the plan on a host without Docker. +`openshiftsetup/mirror-images.sh` (or `make k8s-mirror-images-openshift`) mirrors only the third-party images, for teams that seed Artifactory ahead of time. Pass the selected release's `release-manifest.json` and `.intoto.jsonl` bundle with `--manifest` and `--provenance` (or set `RELEASE_MANIFEST` and `RELEASE_PROVENANCE_BUNDLE`). The script requires `ARTIFACTORY_REGISTRY`, GitHub CLI and `skopeo`, authenticates schema v2, and copies exact multi-platform indexes to digest-addressed destination repositories. `--dry-run` prints that digest-only plan without invoking `skopeo`. MongoDB (`mongo:7`) is mirrored from its upstream image like the other datastores; it is licensed SSPL-1.0, so check that this fits your organization before mirroring it. diff --git a/e2e-runner/merge_upgrade.py b/e2e-runner/merge_upgrade.py index 59ca00752..1eb878e2b 100644 --- a/e2e-runner/merge_upgrade.py +++ b/e2e-runner/merge_upgrade.py @@ -10,7 +10,7 @@ from policy import evaluate from run import JOURNEYS, render -from upgrade import public_proof, qualifying_run, validate_manifest +from upgrade import APPLICATION_COMPONENTS, public_proof, qualifying_run, validate_manifest CASE = "TL-DEPLOY-001" STAGES = ( @@ -116,8 +116,8 @@ def bind_baseline(folder, candidate, candidate_hash, raw): and provenance["artifact"]["expired"] is False and all( previous["images"][k]["source_ref"].rsplit("@", 1)[-1] - != v["source_ref"].rsplit("@", 1)[-1] - for k, v in candidate["images"].items() + != candidate["images"][k]["source_ref"].rsplit("@", 1)[-1] + for k in APPLICATION_COMPONENTS ), "Previous verified build provenance does not match.", ) @@ -237,7 +237,7 @@ def verify_stages(raw, previous, candidate): and observed["expected_revision"] == observed["observed_revision"] == build["source_sha"] - and {i["component"] for i in observed["images"]} == set(build["images"]), + and {i["component"] for i in observed["images"]} == set(APPLICATION_COMPONENTS), "Running components or revision differ from the expected stage.", ) for image in observed["images"]: diff --git a/e2e-runner/run.py b/e2e-runner/run.py index cc974ffc6..dc77cb55b 100644 --- a/e2e-runner/run.py +++ b/e2e-runner/run.py @@ -19,7 +19,7 @@ ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "scripts/release")) -from release_manifest import validate_manifest # noqa: E402 - shared repository validator +from release_manifest import APPLICATION_COMPONENTS, validate_manifest # noqa: E402 - shared repository validator ROLES = ("VIEWER", "TESTER", "QA_ENGINEER", "QA_LEAD", "ADMIN") PUBLIC = ["TL-DEPLOY-002", "TL-AUTH-002"] @@ -406,7 +406,7 @@ def main(): if image_file: entries = json.loads(Path(image_file).read_text(encoding="utf-8-sig")) observed_images = {entry["component"]: entry for entry in entries} - same = set(observed_images) == set(manifest["images"]) + same = set(observed_images) == set(APPLICATION_COMPONENTS) for component, entry in observed_images.items(): wanted = manifest["images"][component]["source_ref"] digest = entry["running"].rsplit("@", 1)[-1] diff --git a/e2e-runner/test_merge_upgrade.py b/e2e-runner/test_merge_upgrade.py index bc6e573d7..fc729dd68 100644 --- a/e2e-runner/test_merge_upgrade.py +++ b/e2e-runner/test_merge_upgrade.py @@ -68,6 +68,7 @@ def inputs(tmp_path, monkeypatch): "matched": True, } for k, img in manifest["images"].items() + if k in merger.APPLICATION_COMPONENTS ], } for idx, manifest in ( diff --git a/e2e-runner/upgrade.py b/e2e-runner/upgrade.py index cd706238e..fc7a852bf 100644 --- a/e2e-runner/upgrade.py +++ b/e2e-runner/upgrade.py @@ -21,7 +21,7 @@ ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "scripts/release")) -from release_manifest import validate_manifest # noqa: E402 +from release_manifest import APPLICATION_COMPONENTS, validate_manifest # noqa: E402 class PreconditionError(RuntimeError): @@ -75,7 +75,8 @@ def verify_baseline(previous_file, candidate_file, provenance_file, archive_file if prior["source_sha"] == candidate["source_sha"]: raise PreconditionError("A true previous build must have a different source revision") if any(prior["images"][name]["source_ref"].rsplit("@", 1)[1] - == candidate["images"][name]["source_ref"].rsplit("@", 1)[1] for name in prior["images"]): + == candidate["images"][name]["source_ref"].rsplit("@", 1)[1] + for name in APPLICATION_COMPONENTS): raise PreconditionError("Every application component needs a distinct prior image") ancestry = subprocess.run(["git", "merge-base", "--is-ancestor", prior["source_sha"], candidate["source_sha"]], cwd=ROOT, capture_output=True) diff --git a/e2e-runner/upgrade_baseline.py b/e2e-runner/upgrade_baseline.py index 18bdc9855..4f26ec1fe 100644 --- a/e2e-runner/upgrade_baseline.py +++ b/e2e-runner/upgrade_baseline.py @@ -33,7 +33,7 @@ ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "scripts/release")) -from release_manifest import validate_manifest # noqa: E402 +from release_manifest import APPLICATION_COMPONENTS, validate_manifest # noqa: E402 MAX_ARCHIVE_BYTES = 8 * 1024 * 1024 MAX_MANIFEST_BYTES = 256 * 1024 @@ -179,7 +179,7 @@ def _archive_manifest(raw, expected_sha): def _distinct(prior, candidate): return all(prior["images"][component]["source_ref"].rsplit("@", 1)[1] != candidate["images"][component]["source_ref"].rsplit("@", 1)[1] - for component in candidate["images"]) + for component in APPLICATION_COMPONENTS) def _projection(value, keys): diff --git a/install.sh b/install.sh index 7d7ac5bc3..fd2fa863f 100755 --- a/install.sh +++ b/install.sh @@ -158,7 +158,7 @@ manifest_image_ref() { # manifest_image_ref verify_release_provenance() { # verify_release_provenance local stage="$1" manifest="$1/$IMAGE_MANIFEST" local bundle_name="testlookup-offline-${REF#v}.intoto.jsonl" - local bundle="$1/$bundle_name" manifest_version source_sha component ref ref_count + local bundle="$1/$bundle_name" manifest_version source_sha component ref ref_count expected digest fetch_release_asset "$IMAGE_MANIFEST" "$manifest" \ || die "could not download the authenticated image manifest for $REF. Nothing was installed or run." @@ -187,27 +187,47 @@ verify_release_provenance() { # verify_release_provenance [[ "$source_sha" =~ ^[0-9a-f]{40}$ ]] \ || die "the authenticated image manifest has an invalid source SHA. Nothing was installed or run." ref_count="$(awk '$1 == "\"source_ref\":" { count += 1 } END { print count + 0 }' "$manifest")" - [ "$ref_count" -eq 3 ] \ - || die "the authenticated image manifest must contain exactly three image references. Nothing was installed or run." + [ "$ref_count" -eq 10 ] \ + || die "the authenticated image manifest must contain exactly ten application and infrastructure image references. Nothing was installed or run." - for component in backend frontend mcp; do + for component in backend frontend mcp postgres valkey mongo versitygw busybox ollama chroma; do ref="$(manifest_image_ref "$manifest" "$component")" \ || die "the authenticated image manifest has no single $component reference. Nothing was installed or run." - [[ "$ref" =~ ^ghcr\.io/test-intelligence/testlookup/${component}@sha256:[0-9a-f]{64}$ ]] \ + case "$component" in + backend|frontend|mcp) expected="ghcr.io/test-intelligence/testlookup/$component" ;; + postgres) expected="postgres:16-alpine" ;; + valkey) expected="valkey/valkey:8.1-alpine" ;; + mongo) expected="mongo:7" ;; + versitygw) expected="ghcr.io/versity/versitygw:v1.8.0" ;; + busybox) expected="busybox:1.36" ;; + ollama) expected="ollama/ollama:0.40.10" ;; + chroma) expected="chromadb/chroma:1.5.9" ;; + esac + digest="${ref##*@}" + [ "${ref%@*}" = "$expected" ] && [[ "$digest" =~ ^sha256:[0-9a-f]{64}$ ]] \ || die "the authenticated image manifest has an invalid $component digest reference. Nothing was installed or run." - gh attestation verify "oci://$ref" \ - --repo "$ATTESTATION_REPOSITORY" \ - --signer-workflow "$IMAGE_SIGNER" \ - --source-ref refs/heads/main \ - --source-digest "$source_sha" >/dev/null \ - || die "the $component digest in the $REF manifest does not have trusted CI provenance for $source_sha. Nothing was installed or run." + if [[ " backend frontend mcp " == *" $component "* ]]; then + gh attestation verify "oci://$ref" \ + --repo "$ATTESTATION_REPOSITORY" \ + --signer-workflow "$IMAGE_SIGNER" \ + --source-ref refs/heads/main \ + --source-digest "$source_sha" >/dev/null \ + || die "the $component digest in the $REF manifest does not have trusted CI provenance for $source_sha. Nothing was installed or run." + fi case "$component" in backend) BACKEND_IMAGE_REF="$ref" ;; frontend) FRONTEND_IMAGE_REF="$ref" ;; mcp) MCP_IMAGE_REF="$ref" ;; + postgres) POSTGRES_IMAGE_REF="$ref" ;; + valkey) VALKEY_IMAGE_REF="$ref" ;; + mongo) MONGO_IMAGE_REF="$ref" ;; + versitygw) VERSITYGW_IMAGE_REF="$ref" ;; + busybox) BUSYBOX_IMAGE_REF="$ref" ;; + ollama) OLLAMA_IMAGE_REF="$ref" ;; + chroma) CHROMA_IMAGE_REF="$ref" ;; esac done - say "Authenticated the $REF manifest and all three CI image digests" + say "Authenticated the $REF manifest and all ten release image digests" } write_release_image_override() { # write_release_image_override @@ -224,8 +244,20 @@ write_release_image_override() { # write_release_image_override cat > "$destination" <HTTPS redirect) # ============================================================================ -# ROUTE_HOST_*_PLACEHOLDER tokens are substituted by +# Route hostnames are substituted by # openshiftsetup/deploy-openshift-artifactory.sh from APPS_DOMAIN (or explicit # ROUTE_HOST_* config). # diff --git a/openshiftsetup/artifactory.env.example b/openshiftsetup/artifactory.env.example index 2df0ca5af..82f7f21ce 100644 --- a/openshiftsetup/artifactory.env.example +++ b/openshiftsetup/artifactory.env.example @@ -97,13 +97,15 @@ ADMIN_PASSWORD="" ADMIN_EMAIL="admin@example.com" ADMIN_FULL_NAME="TestLookup Admin" -# ── Infra images to mirror into Artifactory ───────────────────────────────── -# Leave unset: the list is derived from deploy/images.manifest.txt (the single -# source of truth), so it always matches the manifests you deploy. Set it only -# to mirror a subset — space-separated upstream refs; the script pulls each on -# the (internet-connected) build host, retags under ARTIFACTORY_REGISTRY -# preserving the repo path, and pushes. Example: -# INFRA_IMAGES="postgres:16-alpine valkey/valkey:8.1-alpine mongo:7" +# ── Authenticated release images ──────────────────────────────────────────── +# Download release-manifest.json and the .intoto.jsonl provenance bundle from +# the selected release. The deploy script authenticates the complete schema-v2 +# application-and-infrastructure inventory before any release action. It copies +# exact multi-platform indexes with digest preservation, or, with --skip-mirror, +# verifies every signed digest already exists in Artifactory. Both paths remain +# required with --skip-mirror because skipping a copy never skips authentication. +RELEASE_MANIFEST="" +RELEASE_PROVENANCE_BUNDLE="" # MongoDB (mongo:7) is SSPL-1.0 and is pulled from its upstream registry by you. # Pull Ollama models into the in-cluster Ollama after deploy. In an air-gapped diff --git a/openshiftsetup/deploy-openshift-artifactory.sh b/openshiftsetup/deploy-openshift-artifactory.sh index bfd2eeedb..1d3e9c181 100755 --- a/openshiftsetup/deploy-openshift-artifactory.sh +++ b/openshiftsetup/deploy-openshift-artifactory.sh @@ -5,14 +5,12 @@ # Deploy the COMPLETE TestLookup stack to an air-gapped OpenShift cluster that # can reach ONLY one Artifactory registry (no public internet), over HTTPS. # -# What it does: -# 1. Builds the 3 app images locally (backend / frontend / mcp) and pushes -# them to Artifactory under one immutable build tag. -# 2. Mirrors every third-party infra image (postgres, valkey, mongo, -# versitygw, chromadb, ollama, busybox — the list comes from -# deploy/images.manifest.txt) into the SAME Artifactory, so the cluster -# pulls 100% of its images from that one registry. MongoDB is SSPL-1.0: -# it is pulled from its upstream registry here, on your host. +# What it does in verified-release mode (RELEASE_MANIFEST + provenance set): +# 1. Authenticates the complete schema-v2 release manifest before contacting +# the cluster or copying an image. Locally built app images are disabled. +# 2. Copies every signed application and infrastructure manifest index, all +# platforms, into Artifactory without changing its digest; --skip-mirror +# still verifies every destination digest before deployment. # 3. Creates the project, an Artifactory image-pull secret, app secrets # (with a generated Redis password; MongoDB authentication is opt-in, # ENABLE_MONGO_AUTH), and grants two SCCs: anyuid to the one @@ -29,7 +27,9 @@ # This is the OpenShift/Artifactory sibling of k3ssetup/deploy-k3s.sh. # # Prereqs on the BUILD host (which DOES have internet + Artifactory access): -# - docker, oc (or kubectl), curl, openssl +# - verified release: gh, python3, skopeo, kustomize 5.7.1 (tested), +# oc (or kubectl), openssl +# - deliberate local build: docker, curl, oc (or kubectl), openssl # - oc logged in to the target cluster (``oc login ...``) # - openshiftsetup/artifactory.env filled in (copy from .env.example) # @@ -39,10 +39,11 @@ # ./openshiftsetup/deploy-openshift-artifactory.sh [flags] # # Flags: -# --skip-build Don't rebuild app images; reuse an existing tag +# --skip-build Local-build mode only: reuse an existing app-image tag # (APP_TAG from config, else newest common build-* in Artifactory) # --skip-push Build images but don't push (local smoke test) -# --skip-mirror Don't mirror infra images (already present in Artifactory) +# --skip-mirror Don't copy release images; verify all signed destination +# digests already exist before rendering or deploying # --no-anyuid Don't grant the anyuid SCC to the data stores' account # (hardened clusters that pre-provision an SCC) # --skip-admin Don't create the initial admin user @@ -56,7 +57,7 @@ set -euo pipefail # ── Paths ─────────────────────────────────────────────────────────────────── REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)" -OVERLAY_DIR="$REPO_ROOT/k8s/overlays/openshift-artifactory" +OVERLAY_DIR="${OPENSHIFT_OVERLAY_DIR:-$REPO_ROOT/k8s/overlays/openshift-artifactory}" CONFIG_FILE="${ARTIFACTORY_ENV_FILE:-$REPO_ROOT/openshiftsetup/artifactory.env}" CREDS_FILE="$REPO_ROOT/openshiftsetup/.openshift-credentials" @@ -89,6 +90,10 @@ for arg in "$@"; do done # ── Load config ───────────────────────────────────────────────────────────── +RELEASE_MANIFEST_ENV_STATE="${RELEASE_MANIFEST+x}" +RELEASE_MANIFEST_ENV_VALUE="${RELEASE_MANIFEST:-}" +RELEASE_PROVENANCE_ENV_STATE="${RELEASE_PROVENANCE_BUNDLE+x}" +RELEASE_PROVENANCE_ENV_VALUE="${RELEASE_PROVENANCE_BUNDLE:-}" if [ -f "$CONFIG_FILE" ]; then log "Loading config from $CONFIG_FILE" # shellcheck disable=SC1090 @@ -96,6 +101,15 @@ if [ -f "$CONFIG_FILE" ]; then else warn "Config file $CONFIG_FILE not found — relying on environment variables." fi +# These release inputs are commonly selected per deployment rather than kept +# in the shared site config. Preserve the documented environment-over-config +# precedence even when the example config contains empty placeholders. +if [ "$RELEASE_MANIFEST_ENV_STATE" = x ]; then + RELEASE_MANIFEST="$RELEASE_MANIFEST_ENV_VALUE" +fi +if [ "$RELEASE_PROVENANCE_ENV_STATE" = x ]; then + RELEASE_PROVENANCE_BUNDLE="$RELEASE_PROVENANCE_ENV_VALUE" +fi # Defaults NAMESPACE="${NAMESPACE:-testlookup}" @@ -118,17 +132,20 @@ ADMIN_PASSWORD_GENERATED=false ADMIN_CREATED=false ADMIN_EMAIL="${ADMIN_EMAIL:-admin@example.com}" ADMIN_FULL_NAME="${ADMIN_FULL_NAME:-TestLookup Admin}" -# Derived from deploy/images.manifest.txt — see mirror-images.sh for the -# rationale (a hardcoded copy here is how the list drifted from k8s before). -# `external` rows (MongoDB, SSPL-1.0) are mirrored too: this host pulls them -# from upstream; only the offline bundle leaves them out. +# The catalogue supplies stable component names; a release manifest supplied +# by the operator supplies their signed immutable identities. `external` rows +# (MongoDB, SSPL-1.0) are mirrored too; only the offline bundle leaves them out. # shellcheck source=../scripts/release/image-manifest.sh . "$REPO_ROOT/scripts/release/image-manifest.sh" -INFRA_IMAGES="${INFRA_IMAGES:-$(manifest_refs k8s infra core,llm,external | tr '\n' ' ')}" +RELEASE_MANIFEST="${RELEASE_MANIFEST:-}" +RELEASE_PROVENANCE_BUNDLE="${RELEASE_PROVENANCE_BUNDLE:-}" PULL_OLLAMA_MODELS="${PULL_OLLAMA_MODELS:-false}" OLLAMA_MODELS="${OLLAMA_MODELS:-qwen2.5:7b-instruct nomic-embed-text:v1.5}" PULL_SECRET_NAME="artifactory-pull" APP_IMAGES=(backend frontend mcp) +RELEASE_COMPONENTS=(backend frontend mcp postgres valkey mongo versitygw busybox ollama chroma) +VERIFIED_RELEASE=false +declare -A RELEASE_SOURCE_REFS RELEASE_PUSH_REFS RELEASE_PULL_REFS # ── Pick the cluster CLI (oc preferred for Route/SCC support) ─────────────── if command -v oc >/dev/null 2>&1; then @@ -323,6 +340,68 @@ fi # ── Validate required config ──────────────────────────────────────────────── [ -n "${ARTIFACTORY_REGISTRY:-}" ] || error "ARTIFACTORY_REGISTRY is required (set it in $CONFIG_FILE)." +ARTIFACTORY_PULL_REGISTRY="${ARTIFACTORY_PULL_REGISTRY:-$ARTIFACTORY_REGISTRY}" + +# A release deployment begins here. The attestation covers the bytes of the +# complete manifest; schema validation then makes those authenticated bytes a +# closed ten-image identity. This block intentionally precedes Docker/Skopeo, +# cluster preflight, local builds, mirroring and overlay work. Supplying only +# one release input is always an error, including with --skip-mirror. +if [ -n "$RELEASE_MANIFEST" ] || [ -n "$RELEASE_PROVENANCE_BUNDLE" ]; then + [ -n "$RELEASE_MANIFEST" ] \ + || error "RELEASE_MANIFEST is required with RELEASE_PROVENANCE_BUNDLE, including with --skip-mirror." + [ -f "$RELEASE_MANIFEST" ] || error "Release manifest not found: $RELEASE_MANIFEST" + [ -n "$RELEASE_PROVENANCE_BUNDLE" ] \ + || error "RELEASE_PROVENANCE_BUNDLE is required with RELEASE_MANIFEST, including with --skip-mirror." + [ -f "$RELEASE_PROVENANCE_BUNDLE" ] || error "Release provenance bundle not found: $RELEASE_PROVENANCE_BUNDLE" + command -v gh >/dev/null 2>&1 || error "GitHub CLI (gh) is required to authenticate the release manifest." + command -v python3 >/dev/null 2>&1 || error "python3 is required to validate the release manifest." + gh attestation verify "$RELEASE_MANIFEST" \ + --repo test-intelligence/testlookup \ + --signer-workflow test-intelligence/testlookup/.github/workflows/offline-bundle.yml \ + --source-ref refs/heads/main \ + --bundle "$RELEASE_PROVENANCE_BUNDLE" >/dev/null \ + || error "Release manifest does not have trusted TestLookup release provenance." + python3 "$REPO_ROOT/scripts/release/release_manifest.py" validate \ + --manifest "$RELEASE_MANIFEST" --require-schema-version 2 >/dev/null \ + || error "Release manifest must be the complete authenticated schema-v2 image set." + + SOURCE_ROWS="$(python3 "$REPO_ROOT/scripts/release/release_manifest.py" refs \ + --manifest "$RELEASE_MANIFEST" --kind all)" \ + || error "Could not read source digests from the authenticated release manifest." + PUSH_ROWS="$(python3 "$REPO_ROOT/scripts/release/release_manifest.py" refs \ + --manifest "$RELEASE_MANIFEST" --kind all \ + --destination-prefix "$ARTIFACTORY_REGISTRY")" \ + || error "Could not materialize release digests for the Artifactory push repository." + PULL_ROWS="$(python3 "$REPO_ROOT/scripts/release/release_manifest.py" refs \ + --manifest "$RELEASE_MANIFEST" --kind all \ + --destination-prefix "$ARTIFACTORY_PULL_REGISTRY")" \ + || error "Could not materialize release digests for the cluster pull repository." + while IFS=$'\t' read -r component ref; do + [ -n "$component" ] && RELEASE_SOURCE_REFS["$component"]="$ref" + done <<< "$SOURCE_ROWS" + while IFS=$'\t' read -r component ref; do + [ -n "$component" ] && RELEASE_PUSH_REFS["$component"]="$ref" + done <<< "$PUSH_ROWS" + while IFS=$'\t' read -r component ref; do + [ -n "$component" ] && RELEASE_PULL_REFS["$component"]="$ref" + done <<< "$PULL_ROWS" + for component in "${RELEASE_COMPONENTS[@]}"; do + [ -n "${RELEASE_SOURCE_REFS[$component]:-}" ] \ + && [ -n "${RELEASE_PUSH_REFS[$component]:-}" ] \ + && [ -n "${RELEASE_PULL_REFS[$component]:-}" ] \ + || error "Authenticated release manifest did not materialize component $component." + done + [ -z "${INFRA_IMAGES:-}" ] \ + || error "INFRA_IMAGES cannot narrow a verified release; all signed release images are required." + if [ "$SKIP_PUSH" = true ] && [ "$SKIP_MIRROR" = false ]; then + error "--skip-push cannot be used while copying a verified release; use --skip-mirror for an already seeded registry." + fi + VERIFIED_RELEASE=true + log "Authenticated complete schema-v2 release manifest before release actions." +elif [ "$SKIP_MIRROR" = false ]; then + error "A release mirror requires RELEASE_MANIFEST and RELEASE_PROVENANCE_BUNDLE. For a deliberate non-release local build, pre-seed infrastructure images and pass --skip-mirror." +fi # Resolve route hosts: explicit values win, else derive from APPS_DOMAIN. if [ -z "${ROUTE_HOST_FRONTEND:-}" ] || [ -z "${ROUTE_HOST_API:-}" ] || [ -z "${ROUTE_HOST_MCP:-}" ]; then @@ -334,23 +413,37 @@ fi # ── Preflight ─────────────────────────────────────────────────────────────── header "Step 0 — Preflight" -command -v docker >/dev/null 2>&1 || error "docker is required." -command -v curl >/dev/null 2>&1 || error "curl is required." -docker info >/dev/null 2>&1 || error "Docker daemon not reachable. Start Docker first." +if [ "$VERIFIED_RELEASE" = true ]; then + command -v skopeo >/dev/null 2>&1 || error "skopeo is required for digest-preserving release copies." + command -v kustomize >/dev/null 2>&1 || error "kustomize is required to render verified destination digests." +else + command -v docker >/dev/null 2>&1 || error "docker is required for a non-release local build." + command -v curl >/dev/null 2>&1 || error "curl is required for a non-release local build." + docker info >/dev/null 2>&1 || error "Docker daemon not reachable. Start Docker first." +fi "$KCLI" whoami >/dev/null 2>&1 || "$KCLI" get nodes >/dev/null 2>&1 || error "Not logged in to a cluster. Run 'oc login ...' first." log "Cluster reachable as: $("$KCLI" whoami 2>/dev/null || echo 'unknown')" log "Push registry: $ARTIFACTORY_REGISTRY" log "Pull registry: $ARTIFACTORY_PULL_REGISTRY" log "Routes (HTTPS): https://$ROUTE_HOST_FRONTEND | https://$ROUTE_HOST_API | https://$ROUTE_HOST_MCP/sse" -# ── docker login to Artifactory ───────────────────────────────────────────── +# ── Registry login ────────────────────────────────────────────────────────── ARTIFACTORY_HOST="${ARTIFACTORY_REGISTRY%%/*}" # strip repo path → host[:port] +ARTIFACTORY_PULL_HOST="${ARTIFACTORY_PULL_REGISTRY%%/*}" if [ -n "${ARTIFACTORY_USERNAME:-}" ] && [ -n "${ARTIFACTORY_PASSWORD:-}" ]; then - log "docker login $ARTIFACTORY_HOST ..." - echo "$ARTIFACTORY_PASSWORD" | docker login "$ARTIFACTORY_HOST" -u "$ARTIFACTORY_USERNAME" --password-stdin \ - || error "docker login to $ARTIFACTORY_HOST failed." + if [ "$VERIFIED_RELEASE" = true ]; then + log "skopeo login $ARTIFACTORY_HOST ..." + printf '%s\n' "$ARTIFACTORY_PASSWORD" \ + | skopeo login "$ARTIFACTORY_HOST" --username "$ARTIFACTORY_USERNAME" --password-stdin \ + || error "skopeo login to $ARTIFACTORY_HOST failed." + else + log "docker login $ARTIFACTORY_HOST ..." + printf '%s\n' "$ARTIFACTORY_PASSWORD" \ + | docker login "$ARTIFACTORY_HOST" -u "$ARTIFACTORY_USERNAME" --password-stdin \ + || error "docker login to $ARTIFACTORY_HOST failed." + fi else - warn "ARTIFACTORY_USERNAME/PASSWORD not set — assuming docker is already logged in to $ARTIFACTORY_HOST." + warn "ARTIFACTORY_USERNAME/PASSWORD not set — assuming the registry client is already authenticated to $ARTIFACTORY_HOST." fi # ── Resolve the build tag ─────────────────────────────────────────────────── @@ -366,7 +459,11 @@ _artifactory_tags() { # $1 = repo path under the registry (e.g. testlookup/back | grep -E '^build-[0-9]{8}-[0-9]{6}$' || true } -if [ "$SKIP_BUILD" = true ]; then +if [ "$VERIFIED_RELEASE" = true ]; then + # This value only clears the committed tag placeholder before `kustomize + # edit` replaces every image with an authenticated destination digest. + APP_TAG="verified-release-digest" +elif [ "$SKIP_BUILD" = true ]; then if [ -n "${APP_TAG:-}" ]; then log "Reusing APP_TAG from config: $APP_TAG" else @@ -383,7 +480,10 @@ else fi # ── Step 1 — Build + push app images ──────────────────────────────────────── -if [ "$SKIP_BUILD" = false ]; then +if [ "$VERIFIED_RELEASE" = true ]; then + header "Step 1 — Use signed application images" + log "Local application builds are disabled for an authenticated release." +elif [ "$SKIP_BUILD" = false ]; then header "Step 1 — Build app images ($APP_TAG)" cd "$REPO_ROOT" @@ -425,21 +525,31 @@ else log "Skipping app image build (--skip-build), using tag $APP_TAG" fi -# ── Step 2 — Mirror infra images into the SAME Artifactory ────────────────── -if [ "$SKIP_MIRROR" = false ]; then - header "Step 2 — Mirror infra images into Artifactory" - warn "Pulling upstream infra images — the BUILD host needs internet for this step." - for ref in $INFRA_IMAGES; do - dest="${ARTIFACTORY_REGISTRY}/${ref}" - log "Mirroring ${ref} -> ${dest}" - docker pull "$ref" - docker tag "$ref" "$dest" - if [ "$SKIP_PUSH" = false ]; then - docker push "$dest" - fi +# ── Step 2 — Copy and verify the complete signed image set ────────────────── +if [ "$VERIFIED_RELEASE" = true ]; then + if [ "$SKIP_MIRROR" = false ]; then + header "Step 2 — Mirror signed release indexes into Artifactory" + warn "Copying signed release digests — the BUILD host needs upstream registry access." + for component in "${RELEASE_COMPONENTS[@]}"; do + source_ref="$(manifest_registry_ref "${RELEASE_SOURCE_REFS[$component]}")" + destination_ref="${RELEASE_PUSH_REFS[$component]}" + log "Mirroring $component: ${RELEASE_SOURCE_REFS[$component]} -> $destination_ref" + skopeo copy --all --preserve-digests \ + "docker://$source_ref" "docker://$destination_ref" \ + || error "Digest-preserving copy failed for release component $component." + done + else + header "Step 2 — Verify pre-seeded signed release indexes" + log "Skipping copies (--skip-mirror), but not destination digest verification." + fi + for component in "${RELEASE_COMPONENTS[@]}"; do + destination_ref="${RELEASE_PUSH_REFS[$component]}" + skopeo inspect --raw "docker://$destination_ref" >/dev/null \ + || error "Signed digest for $component is missing from destination repository: $destination_ref" + log "Verified destination digest for $component: $destination_ref" done else - log "Skipping infra image mirror (--skip-mirror)." + log "Skipping release-image mirror in deliberate non-release local-build mode." fi # ── Step 3 — Project / namespace ──────────────────────────────────────────── @@ -456,7 +566,7 @@ header "Step 4 — Artifactory image-pull secret" if [ -n "${ARTIFACTORY_USERNAME:-}" ] && [ -n "${ARTIFACTORY_PASSWORD:-}" ]; then "$KCLI" -n "$NAMESPACE" delete secret "$PULL_SECRET_NAME" --ignore-not-found >/dev/null 2>&1 || true create_secret "$PULL_SECRET_NAME" kubernetes.io/dockerconfigjson .dockerconfigjson \ - "$(dockerconfig_json "$ARTIFACTORY_HOST" "$ARTIFACTORY_USERNAME" "$ARTIFACTORY_PASSWORD" "$ARTIFACTORY_EMAIL")" + "$(dockerconfig_json "$ARTIFACTORY_PULL_HOST" "$ARTIFACTORY_USERNAME" "$ARTIFACTORY_PASSWORD" "$ARTIFACTORY_EMAIL")" # Link to the default SA so every pod pulls with it (covers app + infra). if [ "$KCLI" = "oc" ]; then oc -n "$NAMESPACE" secrets link default "$PULL_SECRET_NAME" --for=pull @@ -549,7 +659,7 @@ fi # ── Step 8 — Substitute placeholders (in place, restored by trap) ─────────── header "Step 8 — Render overlay" -SUBST_FILES=( kustomization.yaml route.yaml infra-postgres.yaml infra-mongo.yaml infra-minio.yaml infra-chromadb.yaml ) +SUBST_FILES=( kustomization.yaml route.yaml infra-postgres.yaml infra-mongo.yaml infra-redis.yaml infra-minio.yaml infra-chromadb.yaml ) restore_overlay() { for f in "${SUBST_FILES[@]}"; do [ -f "$OVERLAY_DIR/$f.deploy-bak" ] && mv -f "$OVERLAY_DIR/$f.deploy-bak" "$OVERLAY_DIR/$f" @@ -571,13 +681,53 @@ for f in "${SUBST_FILES[@]}"; do rm -f "$OVERLAY_DIR/$f.tmp" done +if [ "$VERIFIED_RELEASE" = true ]; then + for component in "${RELEASE_COMPONENTS[@]}"; do + source_name="$(manifest_ref_name "${RELEASE_SOURCE_REFS[$component]}")" + ( + cd "$OVERLAY_DIR" + kustomize edit set image "$source_name=${RELEASE_PULL_REFS[$component]}" + ) || error "Could not pin $component to its authenticated destination digest." + done +fi + if grep -rqE "ARTIFACTORY_REGISTRY_PLACEHOLDER|APP_TAG_PLACEHOLDER|STORAGE_CLASS_PLACEHOLDER|ROUTE_HOST_.*_PLACEHOLDER" "$OVERLAY_DIR"/*.yaml; then error "Unsubstituted placeholder remains in the overlay — aborting before apply." fi +RENDERED_OVERLAY="" +if [ "$VERIFIED_RELEASE" = true ]; then + RENDERED_OVERLAY="$(kustomize build "$OVERLAY_DIR")" \ + || error "Could not render the digest-pinned release overlay." + RELEASE_ALLOWED_REFS="" + for component in "${RELEASE_COMPONENTS[@]}"; do + RELEASE_ALLOWED_REFS="${RELEASE_ALLOWED_REFS}${RELEASE_PULL_REFS[$component]} +" + grep -Fq -- "${RELEASE_PULL_REFS[$component]}" <<< "$RENDERED_OVERLAY" \ + || error "Rendered overlay does not use the authenticated destination digest for $component." + done + while IFS= read -r rendered_ref; do + [ -n "$rendered_ref" ] || continue + case " +$RELEASE_ALLOWED_REFS" in + *" +$rendered_ref +"*) ;; + *) error "Rendered release contains an image outside the authenticated destination set: $rendered_ref" ;; + esac + done < <(awk '$1 == "image:" { gsub(/^"|"$/, "", $2); print $2 }' <<< "$RENDERED_OVERLAY") + case "$RENDERED_OVERLAY" in + *verified-release-digest*) error "Rendered release overlay retained a tag fallback." ;; + esac +fi + if [ "$DRY_RUN" = true ]; then header "DRY RUN — rendered manifests" - "$KCLI" kustomize "$OVERLAY_DIR" 2>/dev/null || "$KCLI" apply -k "$OVERLAY_DIR" --dry-run=client -o yaml + if [ "$VERIFIED_RELEASE" = true ]; then + printf '%s\n' "$RENDERED_OVERLAY" + else + "$KCLI" kustomize "$OVERLAY_DIR" 2>/dev/null || "$KCLI" apply -k "$OVERLAY_DIR" --dry-run=client -o yaml + fi restore_overlay; trap - EXIT INT TERM log "Dry run complete — nothing applied." exit 0 @@ -585,7 +735,11 @@ fi # ── Step 9 — Apply ────────────────────────────────────────────────────────── header "Step 9 — Apply to cluster" -MIGRATION_IMAGE="${ARTIFACTORY_PULL_REGISTRY}/testlookup/backend:${APP_TAG}" +if [ "$VERIFIED_RELEASE" = true ]; then + MIGRATION_IMAGE="${RELEASE_PULL_REFS[backend]}" +else + MIGRATION_IMAGE="${ARTIFACTORY_PULL_REGISTRY}/testlookup/backend:${APP_TAG}" +fi HAD_BACKEND=0 if "$KCLI" -n "$NAMESPACE" get deployment testlookup-backend >/dev/null 2>&1; then HAD_BACKEND=1 @@ -599,7 +753,11 @@ KCLI="$KCLI" bash "$REPO_ROOT/scripts/prepare-live-fanout-cutover.sh" "$NAMESPAC # an upgrade the still password-less Valkey refuses that until the apply below # replaces it. Keeping the two steps adjacent keeps that window short. ensure_redis_credentials -"$KCLI" apply -k "$OVERLAY_DIR" +if [ "$VERIFIED_RELEASE" = true ]; then + printf '%s\n' "$RENDERED_OVERLAY" | "$KCLI" apply -f - +else + "$KCLI" apply -k "$OVERLAY_DIR" +fi if [ "$HAD_BACKEND" -eq 0 ]; then log "Fresh install detected; migrating after datastore creation..." KCLI="$KCLI" bash "$REPO_ROOT/scripts/run-k8s-migrations.sh" "$NAMESPACE" "$MIGRATION_IMAGE" @@ -607,7 +765,7 @@ fi log "Manifests applied and database migrations completed." restore_overlay; trap - EXIT INT TERM -# `apply -k` never deletes. The single /health/ Route of earlier versions is +# `apply` never deletes. The single /health/ Route of earlier versions is # replaced by one Route per published endpoint (route.yaml); left in place it # would keep publishing the whole prefix. "$KCLI" -n "$NAMESPACE" delete route testlookup-api-health --ignore-not-found >/dev/null 2>&1 \ diff --git a/openshiftsetup/mirror-images.sh b/openshiftsetup/mirror-images.sh index 027bdb80f..a0bb18885 100755 --- a/openshiftsetup/mirror-images.sh +++ b/openshiftsetup/mirror-images.sh @@ -9,17 +9,18 @@ # pre-seed the registry independently, or refresh infra images without a full # app rebuild. # -# It mirrors INFRA images by default. Pass --with-app to ALSO pull + re-push -# pre-built app images from a source registry (rarely needed — the deploy -# script builds + pushes those itself). +# It mirrors infrastructure images only. The deployment script mirrors the +# complete signed release set, including application images, when it owns the +# release deployment. # # Config: reads openshiftsetup/artifactory.env (same file as the deploy -# script) or environment variables. Required: ARTIFACTORY_REGISTRY. +# script) or environment variables. Required: ARTIFACTORY_REGISTRY and the +# release-manifest.json and provenance bundle published with the selected release. # # Usage: -# ./openshiftsetup/mirror-images.sh # mirror infra images -# ./openshiftsetup/mirror-images.sh --dry-run # print the plan only -# INFRA_IMAGES="postgres:16-alpine" ./openshiftsetup/mirror-images.sh +# ./openshiftsetup/mirror-images.sh --manifest release-manifest.json --provenance release.intoto.jsonl +# ./openshiftsetup/mirror-images.sh --manifest release-manifest.json --provenance release.intoto.jsonl --dry-run +# INFRA_IMAGES="postgres:16-alpine@sha256:..." ./openshiftsetup/mirror-images.sh --manifest release-manifest.json --provenance release.intoto.jsonl # ============================================================================ set -euo pipefail @@ -32,52 +33,114 @@ warn() { echo -e "${YELLOW}[!]${NC} $1"; } error() { echo -e "${RED}[x]${NC} $1" >&2; exit 1; } DRY_RUN=false -for a in "$@"; do - case "$a" in +MANIFEST_ARG="" +PROVENANCE_ARG="" +while [ "$#" -gt 0 ]; do + case "$1" in --dry-run) DRY_RUN=true ;; + --manifest) + shift + [ "$#" -gt 0 ] || error "--manifest requires a path" + MANIFEST_ARG="$1" + ;; + --provenance) + shift + [ "$#" -gt 0 ] || error "--provenance requires a path" + PROVENANCE_ARG="$1" + ;; -h|--help) sed -n '2,30p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;; - *) error "Unknown flag: $a" ;; + *) error "Unknown flag: $1" ;; esac + shift done if [ -f "$CONFIG_FILE" ]; then set -a; . "$CONFIG_FILE"; set +a; fi [ -n "${ARTIFACTORY_REGISTRY:-}" ] || error "ARTIFACTORY_REGISTRY is required (config or env)." ARTIFACTORY_HOST="${ARTIFACTORY_REGISTRY%%/*}" -# The infra image list is DERIVED from deploy/images.manifest.txt (the single -# source of truth) rather than hardcoded here — a hardcoded copy is exactly how -# this list drifted from the k8s manifests before. An explicit INFRA_IMAGES in -# the environment still wins, for mirroring a subset. -# `external` rows (MongoDB, SSPL-1.0) are included: the offline bundle does not -# redistribute them, but this script runs on YOUR connected host and pulls them -# from their upstream registry, which is how an operator mirrors a prerequisite. +# The catalogue defines the expected names and the authenticated release +# manifest binds each one to the digest CI resolved for this release. An +# explicit INFRA_IMAGES may select a subset, but every selected ref must be an +# exact digest ref from that complete signed inventory. # shellcheck source=../scripts/release/image-manifest.sh . "$REPO_ROOT/scripts/release/image-manifest.sh" -INFRA_IMAGES="${INFRA_IMAGES:-$(manifest_refs k8s infra core,llm,external | tr '\n' ' ')}" +RELEASE_MANIFEST="${MANIFEST_ARG:-${RELEASE_MANIFEST:-}}" +RELEASE_PROVENANCE_BUNDLE="${PROVENANCE_ARG:-${RELEASE_PROVENANCE_BUNDLE:-}}" +[ -n "$RELEASE_MANIFEST" ] || error "--manifest release-manifest.json is required." +[ -f "$RELEASE_MANIFEST" ] || error "Release manifest not found: $RELEASE_MANIFEST" +[ -n "$RELEASE_PROVENANCE_BUNDLE" ] || error "--provenance release.intoto.jsonl is required." +[ -f "$RELEASE_PROVENANCE_BUNDLE" ] || error "Release provenance bundle not found: $RELEASE_PROVENANCE_BUNDLE" +command -v gh >/dev/null 2>&1 || error "GitHub CLI (gh) is required to authenticate the release manifest." +gh attestation verify "$RELEASE_MANIFEST" \ + --repo test-intelligence/testlookup \ + --signer-workflow test-intelligence/testlookup/.github/workflows/offline-bundle.yml \ + --source-ref refs/heads/main \ + --bundle "$RELEASE_PROVENANCE_BUNDLE" >/dev/null \ + || error "Release manifest does not have trusted TestLookup release provenance." +command -v python3 >/dev/null 2>&1 || error "python3 is required to validate the release manifest." +python3 "$REPO_ROOT/scripts/release/release_manifest.py" validate \ + --manifest "$RELEASE_MANIFEST" --require-schema-version 2 >/dev/null \ + || error "Release manifest must be the complete authenticated schema-v2 image set." +SIGNED_INFRA_ROWS="$(python3 "$REPO_ROOT/scripts/release/release_manifest.py" refs \ + --manifest "$RELEASE_MANIFEST" --kind infrastructure)" \ + || error "Could not read infrastructure digests from the release manifest." +DESTINATION_INFRA_ROWS="$(python3 "$REPO_ROOT/scripts/release/release_manifest.py" refs \ + --manifest "$RELEASE_MANIFEST" --kind infrastructure \ + --destination-prefix "$ARTIFACTORY_REGISTRY")" \ + || error "Could not materialize infrastructure digests for Artifactory." +SIGNED_INFRA="$(printf '%s\n' "$SIGNED_INFRA_ROWS" | cut -f2-)" +[ -n "$SIGNED_INFRA" ] || error "Release manifest does not contain the complete infrastructure digest set." +CATALOG_INFRA="$(manifest_refs k8s infra core,llm,external)" +for tagged_ref in $CATALOG_INFRA; do + matches="$(printf '%s\n' "$SIGNED_INFRA" | awk -v prefix="$tagged_ref@sha256:" 'index($0, prefix) == 1 { count += 1 } END { print count + 0 }')" + [ "$matches" -eq 1 ] || error "Release manifest does not contain one digest for catalogue image $tagged_ref." +done +INFRA_IMAGES="${INFRA_IMAGES:-$(printf '%s\n' "$SIGNED_INFRA" | tr '\n' ' ')}" +declare -A DESTINATION_REFS +while IFS=$'\t' read -r component ref; do + [ -n "$component" ] && DESTINATION_REFS["$component"]="$ref" +done <<< "$DESTINATION_INFRA_ROWS" +for ref in $INFRA_IMAGES; do + case " +$SIGNED_INFRA +" in + *" +$ref +"*) ;; + *) error "Infrastructure image is not an authenticated release digest: $ref" ;; + esac + component="$(manifest_ref_component "$ref")" + [ -n "${DESTINATION_REFS[$component]:-}" ] \ + || error "No authenticated Artifactory destination was materialized for $component." +done -# --dry-run only prints the plan, so it must work on a host without docker +# --dry-run only prints the plan, so it must work on a host without skopeo # (that is the whole point of asking for the plan first). if [ "$DRY_RUN" = false ]; then - command -v docker >/dev/null 2>&1 || error "docker is required." - docker info >/dev/null 2>&1 || error "Docker daemon not reachable." + command -v skopeo >/dev/null 2>&1 || error "skopeo is required for digest-preserving registry copies." fi if [ "$DRY_RUN" = false ] && [ -n "${ARTIFACTORY_USERNAME:-}" ] && [ -n "${ARTIFACTORY_PASSWORD:-}" ]; then - echo "$ARTIFACTORY_PASSWORD" | docker login "$ARTIFACTORY_HOST" -u "$ARTIFACTORY_USERNAME" --password-stdin \ - || error "docker login to $ARTIFACTORY_HOST failed." + printf '%s\n' "$ARTIFACTORY_PASSWORD" \ + | skopeo login "$ARTIFACTORY_HOST" --username "$ARTIFACTORY_USERNAME" --password-stdin \ + || error "skopeo login to $ARTIFACTORY_HOST failed." fi log "Mirroring infra images into ${ARTIFACTORY_REGISTRY}" for ref in $INFRA_IMAGES; do - dest="${ARTIFACTORY_REGISTRY}/${ref}" + component="$(manifest_ref_component "$ref")" + source_ref="$(manifest_registry_ref "$ref")" + dest="${DESTINATION_REFS[$component]}" if [ "$DRY_RUN" = true ]; then - echo " would: docker pull $ref && docker tag $ref $dest && docker push $dest" + echo " would: skopeo copy --all --preserve-digests docker://$source_ref docker://$dest" + echo " skopeo inspect --raw docker://$dest" continue fi log " $ref -> $dest" - docker pull "$ref" - docker tag "$ref" "$dest" - docker push "$dest" + skopeo copy --all --preserve-digests "docker://$source_ref" "docker://$dest" \ + || error "Digest-preserving copy failed for $component." + skopeo inspect --raw "docker://$dest" >/dev/null \ + || error "Signed digest for $component is missing from destination repository: $dest" done log "Done. ${ARTIFACTORY_REGISTRY} now holds the infra images the air-gapped cluster needs." diff --git a/scripts/deploy-k8s.sh b/scripts/deploy-k8s.sh index 9d49748e4..50e70f740 100755 --- a/scripts/deploy-k8s.sh +++ b/scripts/deploy-k8s.sh @@ -54,6 +54,20 @@ for arg in "$@"; do esac done +# A materialized release manifest is a deployment authorization, not merely a +# convenient source of image names. Validate its complete schema-v2 identity +# before selecting/copying an overlay or contacting a cluster. Schema v1 stays +# readable by release_manifest.py for legacy inspection, but it contains only +# the application images and therefore cannot authorize a deployment. +if [[ -n "$RELEASE_MANIFEST" ]]; then + [[ -f "$RELEASE_MANIFEST" ]] || { echo "ERROR: release manifest not found: $RELEASE_MANIFEST" >&2; exit 1; } + command -v python3 >/dev/null 2>&1 \ + || { echo "ERROR: python3 is required to validate a release manifest" >&2; exit 1; } + python3 scripts/release/release_manifest.py validate-materialized \ + --manifest "$RELEASE_MANIFEST" --require-schema-version 2 >/dev/null \ + || { echo "ERROR: release manifest is not a complete schema-v2 deployment manifest" >&2; exit 1; } +fi + case "$CLOUD" in aws|aws-eks) OVERLAY="k8s/overlays/aws-eks" ;; gcp|gcp-gke|gke) OVERLAY="k8s/overlays/gcp-gke" ;; @@ -149,15 +163,19 @@ prepare_temp_overlay() { } if [[ -n "$RELEASE_MANIFEST" ]]; then - [[ -f "$RELEASE_MANIFEST" ]] || { echo "ERROR: release manifest not found: $RELEASE_MANIFEST" >&2; exit 1; } - python3 scripts/release/release_manifest.py validate-materialized --manifest "$RELEASE_MANIFEST" >/dev/null BACKEND_IMAGE="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["destination_refs"]["backend"])' "$RELEASE_MANIFEST")" RELEASE_ID="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["source_sha"])' "$RELEASE_MANIFEST")" prepare_temp_overlay pushd "$TMP_OVERLAY" >/dev/null - for img in backend frontend mcp; do + for img in backend frontend mcp postgres valkey mongo versitygw busybox ollama chroma; do + source_ref="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["images"][sys.argv[2]]["source_ref"])' "$OLDPWD/$RELEASE_MANIFEST" "$img")" + source_name="${source_ref%@*}" + case "$img" in + backend|frontend|mcp) ;; + *) source_name="${source_name%:*}" ;; + esac ref="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["destination_refs"][sys.argv[2]])' "$OLDPWD/$RELEASE_MANIFEST" "$img")" - kubectl kustomize edit set image "${BASE_IMAGE_PREFIX}/$img=$ref" 2>/dev/null || kustomize edit set image "${BASE_IMAGE_PREFIX}/$img=$ref" + kubectl kustomize edit set image "$source_name=$ref" 2>/dev/null || kustomize edit set image "$source_name=$ref" done popd >/dev/null OVERLAY="$TMP_OVERLAY" diff --git a/scripts/release/check_image_drift.py b/scripts/release/check_image_drift.py index da75efbfe..094b35b49 100644 --- a/scripts/release/check_image_drift.py +++ b/scripts/release/check_image_drift.py @@ -328,7 +328,7 @@ def check(repo_root: Path) -> list[str]: for name in sorted(app_names - remapped_apps): errors.append(f"{OPENSHIFT_KUSTOMIZATION}: does NOT remap app image {name!r}") - # ── 5. The OpenShift shell scripts must derive from the manifest ──────── + # ── 5. OpenShift mirrors use the complete signed digest inventory ────── for rel in OPENSHIFT_SCRIPTS: path = repo_root / rel if not path.exists(): @@ -340,6 +340,36 @@ def check(repo_root: Path) -> list[str]: f"{rel}: does not source scripts/release/image-manifest.sh — its image list " "would drift from deploy/images.manifest.txt" ) + expected_kind = "--kind all" if rel.endswith("deploy-openshift-artifactory.sh") else "--kind infrastructure" + inventory_token = "RELEASE_COMPONENTS" if rel.endswith("deploy-openshift-artifactory.sh") else "SIGNED_INFRA" + if "release_manifest.py" not in text or expected_kind not in text or inventory_token not in text: + errors.append( + f"{rel}: does not derive its complete image digest set from a validated release manifest" + ) + if "gh attestation verify" not in text or "RELEASE_PROVENANCE_BUNDLE" not in text: + errors.append( + f"{rel}: does not authenticate the release manifest before mirroring" + ) + if "--require-schema-version 2" not in text: + errors.append( + f"{rel}: does not reject an incomplete legacy manifest before release work" + ) + if ( + "--destination-prefix" not in text + or "skopeo copy --all --preserve-digests" not in text + or "skopeo inspect --raw" not in text + ): + errors.append( + f"{rel}: mirror must preserve complete manifest indexes and verify destination digests" + ) + if rel.endswith("deploy-openshift-artifactory.sh") and ( + "RELEASE_PULL_REFS" not in text + or 'MIGRATION_IMAGE="${RELEASE_PULL_REFS[backend]}"' not in text + or "kustomize edit set image" not in text + ): + errors.append( + f"{rel}: verified overlay and migration must use private destination digest refs" + ) # A hardcoded default list (INFRA_IMAGES="postgres:16-alpine …") is the # exact drift this guard exists to prevent. A ${...} default is fine. for lineno, raw in enumerate(text.splitlines(), 1): diff --git a/scripts/release/image-manifest.sh b/scripts/release/image-manifest.sh index 0e0c5673e..8412162cb 100755 --- a/scripts/release/image-manifest.sh +++ b/scripts/release/image-manifest.sh @@ -62,6 +62,36 @@ manifest_ref_name() { printf '%s\n' "${tagged%:*}" } +# Stable release-manifest key for an infrastructure ref. The current image +# inventory has unique repository basenames (postgres, valkey, mongo, ...), so +# CI and deployment scripts can join the tag catalogue to its signed digest +# without maintaining a second hardcoded image list. +manifest_ref_component() { + local name + name="$(manifest_ref_name "$1")" + printf '%s\n' "${name##*/}" +} + +# Expand Docker Hub short names for registry-copy tools, which intentionally +# do not apply a workstation's interactive short-name resolution policy. +# The tag/digest suffix is preserved verbatim, so this changes only the +# spelling of the registry endpoint, never the authenticated image identity. +manifest_registry_ref() { + local ref="$1" name first + name="${ref%@sha256:*}" + name="${name%:*}" + case "$name" in + */*) + first="${name%%/*}" + case "$first" in + *.*|*:*|localhost) printf '%s\n' "$ref" ;; + *) printf 'docker.io/%s\n' "$ref" ;; + esac + ;; + *) printf 'docker.io/library/%s\n' "$ref" ;; + esac +} + # docker save/load preserves repository tags but not the registry index digest. # A separate namespace prevents the temporary alias overwriting a vendor tag. manifest_archive_ref() { diff --git a/scripts/release/pull-offline-telemetry-images.sh b/scripts/release/pull-offline-telemetry-images.sh new file mode 100755 index 000000000..273fe8a18 --- /dev/null +++ b/scripts/release/pull-offline-telemetry-images.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +# Preload the redistributable optional telemetry images for a tagged release. +# The offline bundle's release path uses --skip-pull, so a fresh runner must +# fetch these existing digest identities before invoking offline-bundle.sh. +set -euo pipefail + +REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +# shellcheck source=scripts/release/image-manifest.sh +. "$REPO_ROOT/scripts/release/image-manifest.sh" + +DOCKER="${DOCKER:-docker}" +command -v "$DOCKER" >/dev/null 2>&1 \ + || { echo "telemetry preload: container client '$DOCKER' not found" >&2; exit 1; } + +TELEMETRY_REFS="$(manifest_refs telemetry infra telemetry)" +[ -n "$TELEMETRY_REFS" ] \ + || { echo "telemetry preload: no redistributable telemetry images are catalogued" >&2; exit 1; } + +while IFS= read -r ref; do + [ -n "$ref" ] || continue + [[ "$ref" =~ @sha256:[0-9a-f]{64}$ ]] \ + || { echo "telemetry preload: mutable telemetry reference refused: $ref" >&2; exit 1; } + tagged_ref="${ref%@sha256:*}" + previous_id="$("$DOCKER" image inspect --format '{{.Id}}' "$tagged_ref" 2>/dev/null || true)" + "$DOCKER" pull "$ref" + source_id="$("$DOCKER" image inspect --format '{{.Id}}' "$ref")" \ + || { echo "telemetry preload: pulled digest is not locally inspectable: $ref" >&2; exit 1; } + [ -n "$source_id" ] \ + || { echo "telemetry preload: pulled digest has no local image ID: $ref" >&2; exit 1; } + "$DOCKER" tag "$source_id" "$(manifest_archive_ref "$ref")" + # busybox is also a signed core-release image. Pulling the pinned telemetry + # platform digest must not move that already-preloaded release tag. + if [ -n "$previous_id" ]; then + "$DOCKER" tag "$previous_id" "$tagged_ref" + fi +done <<< "$TELEMETRY_REFS" diff --git a/scripts/release/release_manifest.py b/scripts/release/release_manifest.py index e070d8d4d..5def594bd 100644 --- a/scripts/release/release_manifest.py +++ b/scripts/release/release_manifest.py @@ -1,10 +1,11 @@ #!/usr/bin/env python3 """Create and verify the immutable image set for a TestLookup release. -CI builds the three application images once and records their registry -digests here; a deployment can later materialize that same set under a -destination registry. A tag is deliberately not accepted as an -image identity: tags may be moved after verification while a digest cannot. +CI builds the three application images, resolves every production +infrastructure image, and records the complete registry-digest set here. A +deployment can later materialize that same set under a destination registry. +A tag is deliberately not accepted as an image identity: tags may be moved +after verification while a digest cannot. The module intentionally uses only the Python standard library so it can run in a GitHub Actions verification job before application dependencies exist. @@ -13,9 +14,11 @@ python scripts/release/release_manifest.py create \ --source-sha "$GITHUB_SHA" --version v1.2.3 \ - --image backend=ghcr.io/acme/testlookup/backend@sha256:... \ - --image frontend=ghcr.io/acme/testlookup/frontend@sha256:... \ - --image mcp=ghcr.io/acme/testlookup/mcp@sha256:... \ + --image backend=ghcr.io/test-intelligence/testlookup/backend@sha256:... \ + --image frontend=ghcr.io/test-intelligence/testlookup/frontend@sha256:... \ + --image mcp=ghcr.io/test-intelligence/testlookup/mcp@sha256:... \ + --image postgres=postgres:16-alpine@sha256:... \ + ... \ --output release-manifest.json python scripts/release/release_manifest.py materialize \ @@ -36,8 +39,31 @@ from typing import Any, Mapping -SCHEMA_VERSION = 1 -COMPONENTS = ("backend", "frontend", "mcp") +SCHEMA_VERSION = 2 +LEGACY_SCHEMA_VERSION = 1 +APPLICATION_COMPONENTS = ("backend", "frontend", "mcp") +INFRASTRUCTURE_COMPONENTS = ( + "postgres", + "valkey", + "mongo", + "versitygw", + "busybox", + "ollama", + "chroma", +) +COMPONENTS = APPLICATION_COMPONENTS + INFRASTRUCTURE_COMPONENTS +EXPECTED_SOURCE_NAMES = { + "backend": "ghcr.io/test-intelligence/testlookup/backend", + "frontend": "ghcr.io/test-intelligence/testlookup/frontend", + "mcp": "ghcr.io/test-intelligence/testlookup/mcp", + "postgres": "postgres:16-alpine", + "valkey": "valkey/valkey:8.1-alpine", + "mongo": "mongo:7", + "versitygw": "ghcr.io/versity/versitygw:v1.8.0", + "busybox": "busybox:1.36", + "ollama": "ollama/ollama:0.40.10", + "chroma": "chromadb/chroma:1.5.9", +} _SHA_RE = re.compile(r"^[0-9a-f]{40}$") _DIGEST_RE = re.compile(r"^sha256:[0-9a-f]{64}$") _IMMUTABLE_REF_RE = re.compile(r"^(?P[^\s@]+)@(?Psha256:[0-9a-f]{64})$") @@ -88,11 +114,11 @@ def _split_immutable_ref(ref: str) -> tuple[str, str]: return match.group("name"), match.group("digest") -def _validate_images(value: object) -> dict[str, dict[str, str]]: +def _validate_images(value: object, components: tuple[str, ...]) -> dict[str, dict[str, str]]: if not isinstance(value, Mapping): raise ManifestError("images must be an object keyed by component") names = set(value) - expected = set(COMPONENTS) + expected = set(components) if names != expected: missing = ", ".join(sorted(expected - names)) unexpected = ", ".join(sorted(names - expected)) @@ -100,16 +126,24 @@ def _validate_images(value: object) -> dict[str, dict[str, str]]: f"missing: {missing}" if missing else "", f"unexpected: {unexpected}" if unexpected else "", ) if part) - raise ManifestError(f"images must contain exactly {', '.join(COMPONENTS)} ({details})") + raise ManifestError(f"images must contain exactly {', '.join(components)} ({details})") images: dict[str, dict[str, str]] = {} seen_digests: set[str] = set() - for component in COMPONENTS: + for component in components: entry = value[component] if not isinstance(entry, Mapping) or set(entry) != {"source_ref"}: raise ManifestError(f"images.{component} must contain only source_ref") source_ref = _validate_immutable_ref(entry["source_ref"], f"images.{component}.source_ref") - _, digest = _split_immutable_ref(source_ref) + source_name, digest = _split_immutable_ref(source_ref) + if ( + components == COMPONENTS + and component in INFRASTRUCTURE_COMPONENTS + and source_name != EXPECTED_SOURCE_NAMES[component] + ): + raise ManifestError( + f"images.{component}.source_ref must lock {EXPECTED_SOURCE_NAMES[component]}" + ) if digest in seen_digests: raise ManifestError("each component must use a distinct immutable image digest") seen_digests.add(digest) @@ -138,20 +172,36 @@ def validate_manifest(manifest: object, *, expected_source_sha: str | None = Non f"unexpected: {unexpected}" if unexpected else "", ) if part) raise ManifestError(f"manifest fields must be exactly {', '.join(sorted(required))} ({details})") - if manifest["schema_version"] != SCHEMA_VERSION: - raise ManifestError(f"schema_version must be {SCHEMA_VERSION}") + schema_version = manifest["schema_version"] + if schema_version not in (LEGACY_SCHEMA_VERSION, SCHEMA_VERSION): + raise ManifestError(f"schema_version must be {LEGACY_SCHEMA_VERSION} or {SCHEMA_VERSION}") + components = APPLICATION_COMPONENTS if schema_version == LEGACY_SCHEMA_VERSION else COMPONENTS source_sha = _validate_sha(manifest["source_sha"]) if expected_source_sha is not None and source_sha != _validate_sha(expected_source_sha, "expected_source_sha"): raise ManifestError("manifest source_sha does not match the verified source SHA") return { - "schema_version": SCHEMA_VERSION, + "schema_version": schema_version, "source_sha": source_sha, "version": _validate_version(manifest["version"]), - "images": _validate_images(manifest["images"]), + "images": _validate_images(manifest["images"], components), } +def require_schema_version(manifest: Mapping[str, Any], required: int) -> None: + """Reject a valid legacy document when a deployment needs the complete set.""" + + actual = manifest["schema_version"] + if actual == required: + return + if actual == LEGACY_SCHEMA_VERSION and required == SCHEMA_VERSION: + raise ManifestError( + "schema_version 1 is supported for legacy inspection only; deployment requires " + "schema_version 2 with the complete application and infrastructure image set" + ) + raise ManifestError(f"schema_version {actual} does not satisfy required schema_version {required}") + + def create_manifest(*, source_sha: str, version: str, images: Mapping[str, str]) -> dict[str, Any]: """Create a normalized immutable release manifest from component refs.""" @@ -189,9 +239,15 @@ def materialize_destination_refs(manifest: object, *, destination_prefix: str) - normalized = validate_manifest(manifest) prefix = _validate_destination_prefix(destination_prefix) destination_refs: dict[str, str] = {} - for component in COMPONENTS: - _, digest = _split_immutable_ref(normalized["images"][component]["source_ref"]) - destination_refs[component] = f"{prefix}/testlookup/{component}@{digest}" + for component in normalized["images"]: + source_name, digest = _split_immutable_ref(normalized["images"][component]["source_ref"]) + if component in APPLICATION_COMPONENTS: + destination_name = f"testlookup/{component}" + else: + # Infrastructure refs retain the repository path established by + # deploy/images.manifest.txt. Only the registry prefix changes. + destination_name = source_name.rsplit(":", 1)[0] + destination_refs[component] = f"{prefix}/{destination_name}@{digest}" return {**normalized, "destination_prefix": prefix, "destination_refs": destination_refs} @@ -214,11 +270,17 @@ def validate_materialized_manifest( if expected_destination_prefix is not None and prefix != _validate_destination_prefix(expected_destination_prefix): raise ManifestError("materialized destination_prefix does not match the requested destination") refs = materialized["destination_refs"] - if not isinstance(refs, Mapping) or set(refs) != set(COMPONENTS): - raise ManifestError("destination_refs must contain exactly backend, frontend, mcp") - for component in COMPONENTS: - _, digest = _split_immutable_ref(base["images"][component]["source_ref"]) - expected = f"{prefix}/testlookup/{component}@{digest}" + components = tuple(base["images"]) + if not isinstance(refs, Mapping) or set(refs) != set(components): + raise ManifestError(f"destination_refs must contain exactly {', '.join(components)}") + for component in components: + source_name, digest = _split_immutable_ref(base["images"][component]["source_ref"]) + destination_name = ( + f"testlookup/{component}" + if component in APPLICATION_COMPONENTS + else source_name.rsplit(":", 1)[0] + ) + expected = f"{prefix}/{destination_name}@{digest}" if refs[component] != expected: raise ManifestError(f"destination_refs.{component} does not preserve the verified source digest") return {**base, "destination_prefix": prefix, "destination_refs": dict(refs)} @@ -279,6 +341,7 @@ def _parser() -> argparse.ArgumentParser: validate = commands.add_parser("validate", help="validate an immutable release manifest") validate.add_argument("--manifest", required=True) validate.add_argument("--expected-source-sha") + validate.add_argument("--require-schema-version", type=int, choices=(1, 2)) materialize = commands.add_parser("materialize", help="produce destination digest refs from a release manifest") materialize.add_argument("--manifest", required=True) @@ -289,6 +352,15 @@ def _parser() -> argparse.ArgumentParser: validate_destination.add_argument("--manifest", required=True) validate_destination.add_argument("--expected-source-sha") validate_destination.add_argument("--expected-destination-prefix") + validate_destination.add_argument("--require-schema-version", type=int, choices=(1, 2)) + + refs = commands.add_parser("refs", help="print validated immutable refs as component/ref TSV") + refs.add_argument("--manifest", required=True) + refs.add_argument("--kind", choices=("application", "infrastructure", "all"), default="all") + refs.add_argument( + "--destination-prefix", + help="emit refs materialized under this registry prefix instead of source refs", + ) return parser @@ -301,21 +373,42 @@ def main(argv: list[str] | None = None) -> int: args.output, ) elif args.command == "validate": - validate_manifest( + manifest = validate_manifest( json.loads(Path(args.manifest).read_text(encoding="utf-8")), expected_source_sha=args.expected_source_sha, ) + if args.require_schema_version is not None: + require_schema_version(manifest, args.require_schema_version) print(f"valid release manifest: {args.manifest}") elif args.command == "materialize": manifest = json.loads(Path(args.manifest).read_text(encoding="utf-8")) _write_json(materialize_destination_refs(manifest, destination_prefix=args.destination_prefix), args.output) elif args.command == "validate-materialized": - validate_materialized_manifest( + manifest = validate_materialized_manifest( json.loads(Path(args.manifest).read_text(encoding="utf-8")), expected_source_sha=args.expected_source_sha, expected_destination_prefix=args.expected_destination_prefix, ) + if args.require_schema_version is not None: + require_schema_version(manifest, args.require_schema_version) print(f"valid materialized release manifest: {args.manifest}") + elif args.command == "refs": + manifest = validate_manifest(json.loads(Path(args.manifest).read_text(encoding="utf-8"))) + selected = { + "application": APPLICATION_COMPONENTS, + "infrastructure": INFRASTRUCTURE_COMPONENTS, + "all": COMPONENTS, + }[args.kind] + refs_by_component = ( + materialize_destination_refs( + manifest, destination_prefix=args.destination_prefix + )["destination_refs"] + if args.destination_prefix + else {component: entry["source_ref"] for component, entry in manifest["images"].items()} + ) + for component in selected: + if component in manifest["images"]: + print(f"{component}\t{refs_by_component[component]}") else: # argparse makes this unreachable; keep the return contract total. raise ManifestError(f"unknown command: {args.command}") except (ManifestError, OSError, json.JSONDecodeError) as exc: diff --git a/scripts/release/scan_release_images.py b/scripts/release/scan_release_images.py index cd15078e2..45226074c 100644 --- a/scripts/release/scan_release_images.py +++ b/scripts/release/scan_release_images.py @@ -81,7 +81,7 @@ def scan_release( failed = version.returncode != 0 components: dict[str, dict[str, object]] = {} - for component in release_manifest.COMPONENTS: + for component in manifest["images"]: image_ref = manifest["images"][component]["source_ref"] vulnerability_path = output_dir / f"{component}.vulnerabilities.json" sbom_path = output_dir / f"{component}.cyclonedx.json" diff --git a/scripts/release/test_image_drift.py b/scripts/release/test_image_drift.py index ed6bd4510..5d20f51a9 100644 --- a/scripts/release/test_image_drift.py +++ b/scripts/release/test_image_drift.py @@ -212,7 +212,7 @@ def test_hardcoded_infra_images_in_mirror_script_fails(repo: Path): script = repo / "openshiftsetup/mirror-images.sh" _sub( script, - 'INFRA_IMAGES="${INFRA_IMAGES:-$(manifest_refs k8s infra core,llm,external | tr \'\\n\' \' \')}"', + 'INFRA_IMAGES="${INFRA_IMAGES:-$(printf \'%s\\n\' "$SIGNED_INFRA" | tr \'\\n\' \' \')}"', 'INFRA_IMAGES="postgres:16-alpine valkey/valkey:8.1-alpine"', ) errors = _joined(check(repo)) @@ -229,6 +229,57 @@ def test_script_not_sourcing_the_manifest_fails(repo: Path): assert "does not source" in errors +def test_mirror_without_signed_digest_inventory_fails(repo: Path): + script = repo / "openshiftsetup/mirror-images.sh" + _sub(script, "--kind infrastructure", "--kind application") + _sub(script, "--kind infrastructure", "--kind application") + + errors = _joined(check(repo)) + + assert "validated release manifest" in errors + + +def test_mirror_without_release_attestation_check_fails(repo: Path): + script = repo / "openshiftsetup/mirror-images.sh" + _sub(script, "gh attestation verify", "gh attestation inspect") + + errors = _joined(check(repo)) + + assert "authenticate the release manifest" in errors + + +@pytest.mark.parametrize( + ("old", "new"), + [ + ("skopeo copy --all --preserve-digests", "skopeo copy"), + ("skopeo inspect --raw", "skopeo inspect"), + ], +) +def test_mirror_without_digest_preservation_or_destination_verification_fails( + repo: Path, old: str, new: str +): + script = repo / "openshiftsetup/mirror-images.sh" + _sub(script, old, new) + _sub(script, old, new) + + errors = _joined(check(repo)) + + assert "preserve complete manifest indexes" in errors + + +def test_openshift_release_render_must_keep_destination_digests(repo: Path): + script = repo / "openshiftsetup/deploy-openshift-artifactory.sh" + _sub( + script, + 'MIGRATION_IMAGE="${RELEASE_PULL_REFS[backend]}"', + 'MIGRATION_IMAGE="${ARTIFACTORY_PULL_REGISTRY}/testlookup/backend:${APP_TAG}"', + ) + + errors = _joined(check(repo)) + + assert "overlay and migration" in errors + + # ── 3. Floating tags ──────────────────────────────────────────────────────── diff --git a/scripts/release/tests/test_release_manifest.py b/scripts/release/tests/test_release_manifest.py index 3d014e367..6cf266e45 100644 --- a/scripts/release/tests/test_release_manifest.py +++ b/scripts/release/tests/test_release_manifest.py @@ -15,14 +15,13 @@ SOURCE_SHA = "a" * 40 DIGESTS = { - "backend": "1" * 64, - "frontend": "2" * 64, - "mcp": "3" * 64, + component: format(index, "x") * 64 + for index, component in enumerate(manifests.COMPONENTS, start=1) } def image(component: str) -> str: - return f"ghcr.io/acme/testlookup/{component}@sha256:{DIGESTS[component]}" + return f"{manifests.EXPECTED_SOURCE_NAMES[component]}@sha256:{DIGESTS[component]}" def valid_manifest() -> dict: @@ -37,14 +36,39 @@ def test_create_and_validate_requires_all_release_components(): manifest = valid_manifest() assert manifests.validate_manifest(manifest, expected_source_sha=SOURCE_SHA) == manifest - assert list(manifest["images"]) == ["backend", "frontend", "mcp"] + assert list(manifest["images"]) == list(manifests.COMPONENTS) + + +def test_legacy_application_only_manifest_remains_readable(): + legacy = valid_manifest() + legacy["schema_version"] = manifests.LEGACY_SCHEMA_VERSION + legacy["images"] = { + component: legacy["images"][component] + for component in manifests.APPLICATION_COMPONENTS + } + + assert list(manifests.validate_manifest(legacy)["images"]) == list(manifests.APPLICATION_COMPONENTS) + + +def test_deployment_schema_gate_rejects_legacy_but_keeps_inspection_compatible(): + legacy = valid_manifest() + legacy["schema_version"] = manifests.LEGACY_SCHEMA_VERSION + legacy["images"] = { + component: legacy["images"][component] + for component in manifests.APPLICATION_COMPONENTS + } + + inspected = manifests.validate_manifest(legacy) + with pytest.raises(manifests.ManifestError, match="inspection only.*schema_version 2"): + manifests.require_schema_version(inspected, manifests.SCHEMA_VERSION) @pytest.mark.parametrize( ("mutate", "message"), [ - (lambda manifest: manifest["images"]["backend"].__setitem__("source_ref", "ghcr.io/acme/testlookup/backend:v1.2.3"), "immutable"), + (lambda manifest: manifest["images"]["backend"].__setitem__("source_ref", "ghcr.io/test-intelligence/testlookup/backend:v1.2.3"), "immutable"), (lambda manifest: manifest["images"].pop("mcp"), "exactly"), + (lambda manifest: manifest["images"]["postgres"].__setitem__("source_ref", image("mongo")), "must lock postgres"), (lambda manifest: manifest.__setitem__("source_sha", "A" * 40), "lowercase"), (lambda manifest: manifest.__setitem__("surprise", "unreviewed"), "unexpected"), ], @@ -62,10 +86,14 @@ def test_materialization_preserves_each_verified_digest_without_a_tag(): valid_manifest(), destination_prefix="us-central1-docker.pkg.dev/example/release" ) - assert materialized["destination_refs"] == { - component: f"us-central1-docker.pkg.dev/example/release/testlookup/{component}@sha256:{DIGESTS[component]}" - for component in manifests.COMPONENTS - } + expected = {} + for component in manifests.COMPONENTS: + if component in manifests.APPLICATION_COMPONENTS: + path = f"testlookup/{component}" + else: + path = manifests.EXPECTED_SOURCE_NAMES[component].rsplit(":", 1)[0] + expected[component] = f"us-central1-docker.pkg.dev/example/release/{path}@sha256:{DIGESTS[component]}" + assert materialized["destination_refs"] == expected assert all(":v" not in ref for ref in materialized["destination_refs"].values()) assert manifests.validate_materialized_manifest( materialized, @@ -139,7 +167,7 @@ def test_cli_returns_nonzero_when_a_mutable_tag_is_supplied(tmp_path: Path): "--output", str(tmp_path / "release.json"), ] - command.extend(("--image", "backend=ghcr.io/acme/testlookup/backend:v1.2.3")) + command.extend(("--image", "backend=ghcr.io/test-intelligence/testlookup/backend:v1.2.3")) result = subprocess.run( command, check=False, @@ -149,3 +177,45 @@ def test_cli_returns_nonzero_when_a_mutable_tag_is_supplied(tmp_path: Path): assert result.returncode == 2 assert "immutable" in result.stderr + + +def test_refs_cli_emits_the_complete_immutable_infrastructure_set(tmp_path: Path): + manifest = tmp_path / "release.json" + manifest.write_text(json.dumps(valid_manifest()), encoding="utf-8") + + result = subprocess.run( + [sys.executable, str(Path(manifests.__file__)), "refs", "--manifest", str(manifest), + "--kind", "infrastructure"], + check=False, + capture_output=True, + text=True, + ) + + assert result.returncode == 0 + assert result.stdout.splitlines() == [ + f"{component}\t{image(component)}" for component in manifests.INFRASTRUCTURE_COMPONENTS + ] + + +def test_refs_cli_materializes_private_registry_digests(tmp_path: Path): + manifest = tmp_path / "release.json" + manifest.write_text(json.dumps(valid_manifest()), encoding="utf-8") + + result = subprocess.run( + [sys.executable, str(Path(manifests.__file__)), "refs", "--manifest", str(manifest), + "--kind", "all", "--destination-prefix", "pull.internal.example/releases"], + check=False, + capture_output=True, + text=True, + ) + + assert result.returncode == 0 + refs = dict(line.split("\t", 1) for line in result.stdout.splitlines()) + assert refs["backend"] == ( + f"pull.internal.example/releases/testlookup/backend@sha256:{DIGESTS['backend']}" + ) + assert refs["versitygw"] == ( + "pull.internal.example/releases/ghcr.io/versity/versitygw" + f"@sha256:{DIGESTS['versitygw']}" + ) + assert all("@sha256:" in ref for ref in refs.values()) diff --git a/scripts/release/tests/test_release_transport.py b/scripts/release/tests/test_release_transport.py new file mode 100644 index 000000000..d89c62410 --- /dev/null +++ b/scripts/release/tests/test_release_transport.py @@ -0,0 +1,270 @@ +"""Offline regressions for authenticated release image transport.""" + +from __future__ import annotations + +import json +import os +import re +import shutil +import subprocess +import sys +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[3] +sys.path.insert(0, str(ROOT / "scripts" / "release")) +import release_manifest as manifests # noqa: E402 + + +SOURCE_SHA = "a" * 40 +DIGESTS = { + component: format(index, "x") * 64 + for index, component in enumerate(manifests.COMPONENTS, start=1) +} + + +def _source_ref(component: str) -> str: + return f"{manifests.EXPECTED_SOURCE_NAMES[component]}@sha256:{DIGESTS[component]}" + + +def _release_manifest() -> dict: + return manifests.create_manifest( + source_sha=SOURCE_SHA, + version="v1.2.3", + images={component: _source_ref(component) for component in manifests.COMPONENTS}, + ) + + +def _stub(directory: Path, name: str, body: str) -> Path: + path = directory / name + path.write_text(f"#!/usr/bin/env bash\nset -euo pipefail\n{body}\n", encoding="utf-8") + path.chmod(0o755) + return path + + +def _file_snapshot(directory: Path) -> dict[Path, bytes]: + return { + path.relative_to(directory): path.read_bytes() + for path in directory.rglob("*") + if path.is_file() + } + + +def _rendered_document(rendered: str, *, kind: str, name: str) -> str: + for document in re.split(r"^---\s*$", rendered, flags=re.MULTILINE): + if re.search(rf"^kind:\s*{re.escape(kind)}\s*$", document, flags=re.MULTILINE) and re.search( + rf"^\s+name:\s*{re.escape(name)}\s*$", document, flags=re.MULTILINE + ): + return document + raise AssertionError(f"rendered output has no {kind}/{name}") + + +@pytest.mark.parametrize("skip_mirror", [False, True], ids=["copy", "skip-mirror"]) +def test_openshift_release_authenticates_and_uses_destination_digests(tmp_path: Path, skip_mirror: bool): + """The signed complete set reaches copies, rendering and skip-mirror verification unchanged.""" + manifest_path = tmp_path / "release-manifest.json" + manifest_path.write_text(json.dumps(_release_manifest()), encoding="utf-8") + provenance_path = tmp_path / "release.intoto.jsonl" + provenance_path.write_text('{"stub":"attestation bundle"}\n', encoding="utf-8") + config_path = tmp_path / "artifactory.env" + config_path.write_text( + 'RELEASE_MANIFEST=""\nRELEASE_PROVENANCE_BUNDLE=""\n', encoding="utf-8" + ) + + push_prefix = "push.example.test/releases" + pull_prefix = "pull.internal.test/releases" + push_refs = manifests.materialize_destination_refs( + _release_manifest(), destination_prefix=push_prefix + )["destination_refs"] + pull_refs = manifests.materialize_destination_refs( + _release_manifest(), destination_prefix=pull_prefix + )["destination_refs"] + + stubs = tmp_path / "stubs" + stubs.mkdir() + log = tmp_path / "commands.log" + rendered_path = tmp_path / "rendered.yaml" + real_kustomize = shutil.which("kustomize") + assert real_kustomize is not None, "release transport tests require the CI-pinned Kustomize" + _stub(stubs, "gh", "printf 'gh\\t%s\\n' \"$*\" >> \"$STUB_LOG\"") + _stub(stubs, "skopeo", "printf 'skopeo\\t%s\\n' \"$*\" >> \"$STUB_LOG\"") + _stub( + stubs, + "kustomize", + "printf 'kustomize\\t%s\\n' \"$*\" >> \"$STUB_LOG\"\n" + "if [ \"${1:-}\" = build ]; then\n" + " \"$REAL_KUSTOMIZE\" \"$@\" | tee \"$STUB_RENDER_CAPTURE\"\n" + "else\n" + " exec \"$REAL_KUSTOMIZE\" \"$@\"\n" + "fi", + ) + _stub( + stubs, + "oc", + "printf 'oc\\t%s\\n' \"$*\" >> \"$STUB_LOG\"\n" + "if [ \"${1:-}\" = whoami ]; then printf 'stub-user\\n'; fi", + ) + _stub(stubs, "docker", "printf 'docker\\t%s\\n' \"$*\" >> \"$STUB_LOG\"; exit 99") + + k8s_tree = tmp_path / "k8s" + shutil.copytree(ROOT / "k8s", k8s_tree) + overlay = k8s_tree / "overlays" / "openshift-artifactory" + overlay_before = _file_snapshot(overlay) + env = os.environ.copy() + env.update( + { + "PATH": str(stubs) + os.pathsep + env["PATH"], + "STUB_LOG": str(log), + "REAL_KUSTOMIZE": real_kustomize, + "STUB_RENDER_CAPTURE": str(rendered_path), + "ARTIFACTORY_ENV_FILE": str(config_path), + "ARTIFACTORY_REGISTRY": push_prefix, + "ARTIFACTORY_PULL_REGISTRY": pull_prefix, + "ARTIFACTORY_USERNAME": "", + "ARTIFACTORY_PASSWORD": "", + "RELEASE_MANIFEST": str(manifest_path), + "RELEASE_PROVENANCE_BUNDLE": str(provenance_path), + "OPENSHIFT_OVERLAY_DIR": str(overlay), + "NAMESPACE": "release-test", + "STORAGE_CLASS": "stub-storage", + "ROUTE_HOST_FRONTEND": "app.example.test", + "ROUTE_HOST_API": "api.example.test", + "ROUTE_HOST_MCP": "mcp.example.test", + "GRANT_NONROOT": "false", + "GRANT_ANYUID": "false", + } + ) + command = [ + "bash", + str(ROOT / "openshiftsetup" / "deploy-openshift-artifactory.sh"), + "--dry-run", + "--skip-admin", + "--no-anyuid", + ] + if skip_mirror: + command.append("--skip-mirror") + + result = subprocess.run(command, cwd=ROOT, env=env, capture_output=True, text=True, check=False) + + assert result.returncode == 0, result.stderr + rendered = rendered_path.read_text(encoding="utf-8") + redis_pvc = _rendered_document(rendered, kind="PersistentVolumeClaim", name="redis-data") + assert re.search(r"^\s+storageClassName:\s*stub-storage\s*$", redis_pvc, flags=re.MULTILINE) + assert "STORAGE_CLASS_PLACEHOLDER" not in rendered + + rendered_images = re.findall(r"^\s+image:\s*(\S+)\s*$", rendered, flags=re.MULTILINE) + assert set(rendered_images) == set(pull_refs.values()) + assert all(re.fullmatch(r"[^@\s]+@sha256:[0-9a-f]{64}", ref) for ref in rendered_images) + assert _rendered_document(rendered, kind="Deployment", name="testlookup-backend") + assert _rendered_document(rendered, kind="Route", name="testlookup-frontend") + + assert _file_snapshot(overlay) == overlay_before + assert (overlay / "infra-redis.yaml").read_text(encoding="utf-8").count( + "STORAGE_CLASS_PLACEHOLDER" + ) == 1 + commands = log.read_text(encoding="utf-8").splitlines() + assert commands[0].startswith("gh\tattestation verify "), commands + inspections = [line for line in commands if line.startswith("skopeo\tinspect --raw ")] + assert len(inspections) == len(manifests.COMPONENTS) + assert all(any(push_refs[component] in line for line in inspections) for component in manifests.COMPONENTS) + + copies = [line for line in commands if line.startswith("skopeo\tcopy ")] + assert len(copies) == (0 if skip_mirror else len(manifests.COMPONENTS)) + assert all("--all --preserve-digests" in line and "@sha256:" in line for line in copies) + edits = [line for line in commands if line.startswith("kustomize\tedit set image ")] + assert len(edits) == len(manifests.COMPONENTS) + assert max(commands.index(line) for line in inspections) < min(commands.index(line) for line in edits) + assert all(any(pull_refs[component] in line for line in edits) for component in manifests.COMPONENTS) + builds = [line for line in commands if line == f"kustomize\tbuild {overlay}"] + assert len(builds) == 1 + assert not any(line.startswith("oc\tkustomize ") for line in commands) + assert not any(line.startswith("docker\t") for line in commands) + + deploy_source = (ROOT / "openshiftsetup" / "deploy-openshift-artifactory.sh").read_text(encoding="utf-8") + assert 'MIGRATION_IMAGE="${RELEASE_PULL_REFS[backend]}"' in deploy_source + assert "printf '%s\\n' \"$RENDERED_OVERLAY\" | \"$KCLI\" apply -f -" in deploy_source + + +def test_deploy_k8s_rejects_schema_one_before_cluster_or_overlay_work(tmp_path: Path): + legacy = _release_manifest() + legacy["schema_version"] = manifests.LEGACY_SCHEMA_VERSION + legacy["images"] = { + component: legacy["images"][component] + for component in manifests.APPLICATION_COMPONENTS + } + materialized = manifests.materialize_destination_refs( + legacy, destination_prefix="registry.example.test/releases" + ) + manifest_path = tmp_path / "legacy-materialized.json" + manifest_path.write_text(json.dumps(materialized), encoding="utf-8") + + stubs = tmp_path / "stubs" + stubs.mkdir() + log = tmp_path / "cluster.log" + _stub(stubs, "kubectl", "printf 'kubectl\\t%s\\n' \"$*\" >> \"$STUB_LOG\"") + _stub(stubs, "kustomize", "printf 'kustomize\\t%s\\n' \"$*\" >> \"$STUB_LOG\"") + env = os.environ.copy() + env.update({"PATH": str(stubs) + os.pathsep + env["PATH"], "STUB_LOG": str(log)}) + + result = subprocess.run( + ["bash", "scripts/deploy-k8s.sh", "--cloud=self-hosted", + f"--release-manifest={manifest_path}", "--dry-run"], + cwd=ROOT, + env=env, + capture_output=True, + text=True, + check=False, + ) + + assert result.returncode != 0 + assert "inspection only" in result.stderr + assert "complete schema-v2 deployment manifest" in result.stderr + assert not log.exists(), "schema rejection must happen before kubectl or kustomize is invoked" + + +def test_tagged_telemetry_preload_pulls_only_redistributable_digests(tmp_path: Path): + stubs = tmp_path / "stubs" + stubs.mkdir() + log = tmp_path / "docker.log" + docker = _stub( + stubs, + "docker", + "printf '%s\\n' \"$*\" >> \"$STUB_LOG\"\n" + "if [ \"${1:-}\" = image ] && [ \"${2:-}\" = inspect ]; then printf 'sha256:stub-image-id\\n'; fi", + ) + env = os.environ.copy() + env.update({"DOCKER": str(docker), "STUB_LOG": str(log)}) + + result = subprocess.run( + ["bash", str(ROOT / "scripts" / "release" / "pull-offline-telemetry-images.sh")], + cwd=ROOT, + env=env, + capture_output=True, + text=True, + check=False, + ) + + assert result.returncode == 0, result.stderr + rows = [] + for line in (ROOT / "deploy" / "images.manifest.txt").read_text(encoding="utf-8").splitlines(): + stripped = line.strip() + if not stripped or stripped.startswith("#"): + continue + ref, role, surfaces, bundle = stripped.split() + if role == "infra" and "telemetry" in surfaces.split(","): + rows.append((ref, bundle)) + expected = [ref for ref, bundle in rows if bundle == "telemetry"] + external = {ref for ref, bundle in rows if bundle == "telemetry-external"} + docker_commands = log.read_text(encoding="utf-8").splitlines() + pulled = [line.removeprefix("pull ") for line in docker_commands if line.startswith("pull ")] + assert pulled == expected + assert all(re.search(r"@sha256:[0-9a-f]{64}$", ref) for ref in pulled) + assert external.isdisjoint(pulled) + archive_tags = [line for line in docker_commands if line.startswith("tag ") and "localhost/testlookup-telemetry/" in line] + assert len(archive_tags) == len(expected) + + workflow = (ROOT / ".github" / "workflows" / "offline-bundle.yml").read_text(encoding="utf-8") + preload = workflow.index("bash scripts/release/pull-offline-telemetry-images.sh") + skip_pull = workflow.index("args+=(--skip-build --skip-pull)") + assert preload < skip_pull diff --git a/scripts/release/tests/test_scan_release_images.py b/scripts/release/tests/test_scan_release_images.py index e6e5bba59..b6a47976e 100644 --- a/scripts/release/tests/test_scan_release_images.py +++ b/scripts/release/tests/test_scan_release_images.py @@ -20,7 +20,9 @@ def _manifest(path: Path) -> dict: source_sha=SOURCE_SHA, version="v1.2.3", images={ - component: f"ghcr.io/acme/testlookup/{component}@sha256:{str(index) * 64}" + component: ( + f"{release_manifest.EXPECTED_SOURCE_NAMES[component]}@sha256:{format(index, 'x') * 64}" + ) for index, component in enumerate(release_manifest.COMPONENTS, start=1) }, ) @@ -64,7 +66,7 @@ def test_scan_uses_every_exact_digest_and_writes_complete_evidence(tmp_path: Pat assert scanner.scan_release(manifest_path, output, runner=trivy) == 0 image_commands = [command for command in trivy.commands if len(command) > 2] - assert len(image_commands) == 6 + assert len(image_commands) == 2 * len(release_manifest.COMPONENTS) vulnerability_commands = [command for command in image_commands if command[command.index("--format") + 1] == "json"] assert all("--ignore-unfixed" in command for command in vulnerability_commands) assert all(command[command.index("--severity") + 1] == "HIGH,CRITICAL" for command in vulnerability_commands) @@ -93,7 +95,7 @@ def test_one_policy_failure_still_scans_every_component(tmp_path: Path): assert summary["components"]["frontend"]["vulnerability_status"] == "blocked" assert summary["components"]["frontend"]["actionable_high_or_critical"] == 1 assert set(summary["components"]) == set(release_manifest.COMPONENTS) - assert len([command for command in trivy.commands if len(command) > 2]) == 6 + assert len([command for command in trivy.commands if len(command) > 2]) == 2 * len(release_manifest.COMPONENTS) def test_scanner_error_fails_closed_and_continues(tmp_path: Path): diff --git a/scripts/release/verify_kubernetes_rollout.py b/scripts/release/verify_kubernetes_rollout.py index 393eee857..7e369e33b 100644 --- a/scripts/release/verify_kubernetes_rollout.py +++ b/scripts/release/verify_kubernetes_rollout.py @@ -12,7 +12,7 @@ import sys import time -from release_manifest import ManifestError, validate_manifest +from release_manifest import APPLICATION_COMPONENTS, ManifestError, validate_manifest ROLES = { @@ -147,7 +147,10 @@ def main() -> int: try: source = args.manifest.read_bytes() manifest = validate_manifest(json.loads(source), expected_source_sha=args.source_sha) - image_refs = {name: record["source_ref"] for name, record in manifest["images"].items()} + image_refs = { + name: manifest["images"][name]["source_ref"] + for name in APPLICATION_COMPONENTS + } allowed = {name: runtime_digests(ref) for name, ref in image_refs.items()} command = ["kubectl", f"--namespace={args.namespace}", "--request-timeout=10s"] if args.context: diff --git a/user-guide/air-gapped-install.md b/user-guide/air-gapped-install.md index 617c55c0c..f6a672213 100644 --- a/user-guide/air-gapped-install.md +++ b/user-guide/air-gapped-install.md @@ -419,15 +419,23 @@ hostnames at import time: ``` If your build host *can* reach both the internet and the cluster's registry, -the older registry-to-registry path is still available and does the same job -without a tarball — it also mirrors `mongo:7` from upstream, creates the -buckets, and generates the first admin password (printed once at the end): +the registry-to-registry path is still available without a tarball. Download +the selected release's `release-manifest.json` and `.intoto.jsonl` provenance +bundle first. The scripts authenticate the complete schema-v2 image set, copy +exact multi-platform indexes by digest (including `mongo:7`), and deploy only +the resulting private `repository@sha256` references: ```bash -make k8s-mirror-images-openshift # seed Artifactory -make k8s-deploy-openshift-artifactory # build, push, deploy +make k8s-mirror-images-openshift \ + ARGS="--manifest release-manifest.json --provenance testlookup-offline-X.Y.Z.intoto.jsonl" +RELEASE_MANIFEST=release-manifest.json \ +RELEASE_PROVENANCE_BUNDLE=testlookup-offline-X.Y.Z.intoto.jsonl \ + make k8s-deploy-openshift-artifactory ``` +The deploy command verifies every destination digest again, even when +`ARGS=--skip-mirror`; it never rebuilds application images in release mode. + The offline bundle exists for the case that host does **not** exist. --- From 9b5ee03a42c6c13526543b795ef6ba9a18d1f155 Mon Sep 17 00:00:00 2001 From: Anand Topu Date: Sat, 28 Nov 2026 12:25:03 -0600 Subject: [PATCH 2/2] Test credential ordering in both OpenShift deployment paths Signed-off-by: Anand Topu --- ..._openshift_data_stores_require_a_password.py | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/backend/tests/regression/test_openshift_data_stores_require_a_password.py b/backend/tests/regression/test_openshift_data_stores_require_a_password.py index 730562a05..fefc281ae 100644 --- a/backend/tests/regression/test_openshift_data_stores_require_a_password.py +++ b/backend/tests/regression/test_openshift_data_stores_require_a_password.py @@ -297,13 +297,22 @@ def test_a_first_install_needs_no_running_server(run): assert "mongo-fresh: MONGO_AUTH_JUST_ENABLED=true" in stdout -def test_the_script_sets_the_credentials_before_it_applies(): +@pytest.mark.parametrize( + "apply_command", + [ + r"""printf '%s\n' "$RENDERED_OVERLAY" | "$KCLI" apply -f -""", + '"$KCLI" apply -k "$OVERLAY_DIR"', + ], + ids=["verified-release", "local-build"], +) +def test_the_script_sets_the_credentials_before_it_applies(apply_command: str): script = SCRIPT.read_text(encoding="utf-8") main = script[script.index("# <<< secret helpers"):] - apply_at = re.search(r'^"\$KCLI" apply -k "\$OVERLAY_DIR"$', main, re.MULTILINE).start() + apply_call = re.search(rf"^[ \t]*{re.escape(apply_command)}$", main, re.MULTILINE) + assert apply_call, f"missing deployment command: {apply_command}" for call in ("ensure_redis_credentials", "ensure_mongo_credentials"): - called_at = re.search(rf"^\s*{call}$", main, re.MULTILINE) - assert called_at and called_at.start() < apply_at, f"{call} does not run before the apply" + called_at = re.search(rf"^[ \t]*{call}$", main, re.MULTILINE) + assert called_at and called_at.start() < apply_call.start(), f"{call} does not run before {apply_command}" def test_a_dry_run_changes_no_credentials():