From 8b8a5c6bae12361e7fa003d9ac381b3765a5dc94 Mon Sep 17 00:00:00 2001 From: Md Nurnobi Date: Mon, 23 Nov 2026 17:36:57 +0000 Subject: [PATCH] ci(provenance): add fail-closed imported Login source and pinned OCI image material attestations --- tests/ci/login_image/provenance.py | 348 +++++++++++++++++++++++++++++ 1 file changed, 348 insertions(+) create mode 100644 tests/ci/login_image/provenance.py diff --git a/tests/ci/login_image/provenance.py b/tests/ci/login_image/provenance.py new file mode 100644 index 0000000..5c3b25e --- /dev/null +++ b/tests/ci/login_image/provenance.py @@ -0,0 +1,348 @@ +#!/usr/bin/env python3 +"""CI-only, fail-closed provenance for a disposable, nonpublished Login image. + +All diagnostics are fixed markers. Do not print JSON from docker inspect, any +environment variables, raw artifacts, tokens or package-manager output. +""" +from __future__ import annotations + +import argparse +import copy +import datetime +import json +import os +from pathlib import Path +import re +import subprocess +import sys + +ROOT = Path(__file__).resolve().parents[3] +LOCK_PATH = ROOT / "tests/ci/login_image/provenance-lock.json" +SHA = re.compile(r"^[0-9a-f]{40}$") +DIGEST = re.compile(r"^sha256:[0-9a-f]{64}$") +EXPECTED = { + "schema": 1, + "platform": "linux/amd64", + "upstream": { + "tag": "v4.20.4", + "revision": "384bb9ec96b501ad39dc232ee2061a40fe180bbd", + }, + "source": { + "tree": "76683086acb5d4ccf3b2094f894e19a8aa0fafa9", + "pnpm_lock": "d37471c041f45aad4c1403c628d175b7ca984032", + "dockerfile": "c737bef057035882a0ca959bc641ead6ffb9cc5b", + "entrypoint": "2da2aca45348afeb7480323e02cf98902d479db3", + "package": "f9a180ba5ee73b126f668537d4695da6dd7c2e70", + }, + "package_manager": "pnpm@10.30.3", + "builder": { + "ref": "node:22-bookworm@sha256:e13726ca604184d7a91fcacab1fc09eefd642dc28e79ac34e85540dd93b78cfb", + "index": "sha256:e13726ca604184d7a91fcacab1fc09eefd642dc28e79ac34e85540dd93b78cfb", + "amd64_child": "sha256:69c6e263db01e9946c7743bbbe9f7b1ba0df384d27ec09e08e5832d6acd3daf3", + }, + "runtime": { + "ref": "node:24-alpine@sha256:116b800c3754b440ee0aa3ed2f20f5bf3d99a554bfd9adeea09ea8017f6e85f5", + "index": "sha256:116b800c3754b440ee0aa3ed2f20f5bf3d99a554bfd9adeea09ea8017f6e85f5", + "amd64_child": "sha256:d8d97e479cdc64f052f81f129362168717c59783ade8dcc1abd22e1cca8dbd7c", + }, +} +ENTRYPOINT = ["/app/entrypoint.sh", "node", "apps/login/server.js"] +SOURCE_BLOBS = { + "tree": "auth/ui/v2", + "pnpm_lock": "auth/ui/v2/pnpm-lock.yaml", + "dockerfile": "auth/ui/v2/apps/login/Dockerfile", + "entrypoint": "auth/ui/v2/apps/login/scripts/entrypoint.sh", + "package": "auth/ui/v2/package.json", +} + + +class GateError(Exception): + pass + + +def require(ok: bool, code: str) -> None: + if not ok: + raise GateError(code) + + +def load_lock() -> dict: + value = json.loads(LOCK_PATH.read_text(encoding="utf-8")) + validate_lock(value) + return value + + +def validate_lock(value: object) -> None: + require(type(value) is dict and value == EXPECTED, "LOCK_IDENTITY") + for role in ("builder", "runtime"): + image = value[role] + for field in ("index", "amd64_child"): + require(type(image[field]) is str and DIGEST.fullmatch(image[field]) is not None, "LOCK_DIGEST") + require(image["ref"].endswith("@" + image["index"]), "LOCK_REFERENCE") + + +def git(*args: str) -> str: + result = subprocess.run(["git", *args], cwd=ROOT, check=True, + capture_output=True, text=True) + return result.stdout.strip() + + +def verify_source(lock: dict) -> str: + current = git("rev-parse", "HEAD") + require(SHA.fullmatch(current) is not None, "SOURCE_REVISION") + require(git("status", "--porcelain", "--untracked-files=no", + "--", "auth/ui/v2") == "", "SOURCE_WORKTREE_DIRTY") + for name, path in SOURCE_BLOBS.items(): + require(git("rev-parse", "HEAD:" + path) == lock["source"][name], + "SOURCE_GIT_" + name.upper()) + mode = git("ls-tree", "HEAD", "--", SOURCE_BLOBS["entrypoint"]) + require(mode.split()[0] == "100644", "SOURCE_ENTRYPOINT_GIT_MODE") + origin = (ROOT / SOURCE_BLOBS["dockerfile"]).read_text(encoding="utf-8") + require(origin.startswith("FROM node:24-alpine\n") + and origin.count("\nFROM ") == 0, "SOURCE_DOCKERFILE_BASE") + require("USER nextjs\n" in origin and + 'ENTRYPOINT ["/app/entrypoint.sh", "node", "apps/login/server.js"]' in origin, + "SOURCE_DOCKERFILE_NONROOT") + app = json.loads((ROOT / "auth/ui/v2/package.json").read_text(encoding="utf-8")) + require(app.get("packageManager") == lock["package_manager"], "SOURCE_PNPM_PIN") + require((ROOT / SOURCE_BLOBS["pnpm_lock"]).is_file(), "SOURCE_PNPM_LOCK") + print("ZITPLANE_P10_SOURCE_TREE_GIT_AND_LOCK_PIN_PASS", flush=True) + return current + + +def run_id() -> str: + value = os.environ.get("GITHUB_RUN_ID", "") + require(value.isascii() and value.isdecimal() and len(value) <= 16, + "RUN_ID_UNSAFE") + return value + + +def owned_context() -> Path: + base = Path("/tmp/zitplane-login-build-" + run_id()) + require(base.is_dir() and not base.is_symlink() and + (base / (".zitplane-owned-" + run_id())).is_file(), + "CONTEXT_NOT_RUN_OWNED") + return base + + +def pin_dockerfile(lock: dict, dest: str) -> None: + base = owned_context() + p = Path(dest) + require(p == base / "Dockerfile" and not p.is_symlink() and p.is_file(), + "TEMP_DOCKERFILE_PATH") + original = (ROOT / SOURCE_BLOBS["dockerfile"]).read_bytes() + require(p.read_bytes() == original, "TEMP_DOCKERFILE_NOT_ORIGINAL") + old = b"FROM node:24-alpine\n" + require(original.startswith(old) and original.count(b"\nFROM ") == 0, + "TEMP_DOCKERFILE_FROM") + replacement = ("FROM " + lock["runtime"]["ref"] + "\n").encode("ascii") + p.write_bytes(replacement + original[len(old):]) + require(p.read_bytes() == replacement + original[len(old):], "TEMP_DOCKERFILE_PIN") + print("ZITPLANE_P10_DISPOSABLE_DOCKERFILE_BASE_DIGEST_PIN_PASS", flush=True) + + +def docker_inspect(ref: str) -> dict: + result = subprocess.run(["docker", "image", "inspect", ref], + check=True, capture_output=True, text=True) + value = json.loads(result.stdout) + require(type(value) is list and len(value) == 1 and + type(value[0]) is dict, "OCI_INSPECT_SHAPE") + return value[0] + + +def expected_labels(lock: dict, git_sha: str, rid: str) -> dict: + return { + "zitplane.login.run": rid, + "org.opencontainers.image.revision": git_sha, + "zitplane.login.source_tree": lock["source"]["tree"], + "zitplane.login.builder_digest": lock["builder"]["index"], + "zitplane.login.runtime_digest": lock["runtime"]["index"], + } + + +def validate_image(image: object, labels: dict) -> None: + require(type(image) is dict, "IMAGE_SHAPE") + require(type(image.get("Id")) is str and + DIGEST.fullmatch(image["Id"]) is not None, "IMAGE_ID") + require(image.get("Os") == "linux" and image.get("Architecture") == "amd64", + "IMAGE_PLATFORM") + cfg = image.get("Config") + require(type(cfg) is dict, "IMAGE_CONFIG") + require(cfg.get("User") == "nextjs", "IMAGE_NONROOT") + require(cfg.get("Entrypoint") == ENTRYPOINT, "IMAGE_ENTRYPOINT") + actual_labels = cfg.get("Labels") + require(type(actual_labels) is dict and + all(actual_labels.get(key) == value for key, value in labels.items()), + "IMAGE_PROVENANCE_LABELS") + env = cfg.get("Env", []) + require(type(env) is list and + all(type(e) is str and "=" in e for e in env), "IMAGE_ENV_TYPE") + denied = re.compile(r"(SECRET|PASSWORD|TOKEN|PAT|MASTERKEY|DATABASE|AUTH_|PRIVATE_KEY)", re.I) + for e in env: + key = e.split("=", 1)[0] + require(not denied.search(key), "IMAGE_SECRET_ENV_KEY") + require("NODE_ENV=production" in env, "IMAGE_PRODUCTION_ENV") + + +def verify_builder(lock: dict) -> None: + builder = docker_inspect(lock["builder"]["ref"]) + require(builder.get("Os") == "linux" and builder.get("Architecture") == "amd64", + "BUILDER_PLATFORM") + digests = builder.get("RepoDigests") + require(type(digests) is list and any( + type(x) is str and x.endswith("@" + lock["builder"]["index"]) + for x in digests), "BUILDER_INDEX_IDENTITY") + print("ZITPLANE_P10_PINNED_BUILDER_OS_ARCH_INDEX_PASS", flush=True) + + +def write_material_attestations(lock: dict, img: dict, current: str) -> None: + dest = owned_context() + labels = expected_labels(lock, current, run_id()) + validate_image(img, labels) + created = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + # Source/base material inventory: deliberately NOT a comprehensive OS or + # transitive-package SBOM. Complete scanner SBOM remains a release blocker. + packages = [ + ("zitadel-login-source", lock["upstream"]["tag"]), + ("node-builder-oci-index", lock["builder"]["index"]), + ("node-runtime-oci-index", lock["runtime"]["index"]), + ("pnpm-locked-workspace", lock["package_manager"]), + ] + sbom = { + "spdxVersion": "SPDX-2.3", "dataLicense": "CC0-1.0", + "SPDXID": "SPDXRef-DOCUMENT", + "name": "ZitPlane-disposable-Login-source-and-base-materials", + "documentNamespace": "https://example.invalid/spdx/zitplane-login/" + current, + "creationInfo": {"created": created, "creators": ["Tool: zitplane-provenance-1"]}, + "packages": [ + {"name": name, "SPDXID": "SPDXRef-Material-" + str(i), + "versionInfo": version, "downloadLocation": "NOASSERTION", + "filesAnalyzed": False} + for i, (name, version) in enumerate(packages, start=1) + ], + "documentComment": "Partial source/base materials only; not a transitive package or OS-image vulnerability SBOM.", + } + attestation = { + "schema": 1, "kind": "CI-only-disposable-unsigned-material-provenance", + "source_git_sha": current, "source_git_tree": lock["source"]["tree"], + "upstream_revision_claim": lock["upstream"]["revision"], + "pnpm_lock_blob": lock["source"]["pnpm_lock"], + "platform": lock["platform"], + "builder_oci_index": lock["builder"]["index"], + "runtime_oci_index": lock["runtime"]["index"], + "local_image_id": img["Id"], + "original_entrypoint_git_mode": "100644", + "temporary_entrypoint_mode": "0755", + "container_user": "nextjs", + "signatures": "NOT_SIGNED", "registry_release": "NOT_PUBLISHED", + "sbom_completeness": "PARTIAL_SOURCE_AND_BASE_MATERIALS_ONLY", + } + for name, obj in (("materials.spdx.json", sbom), ("provenance.json", attestation)): + target = dest / name + require(not target.exists() and not target.is_symlink(), "ATTESTATION_PREEXISTS") + target.write_text(json.dumps(obj, sort_keys=True, indent=2) + "\n", + encoding="utf-8") + require(target.stat().st_size < 16000, "ATTESTATION_SIZE") + print("ZITPLANE_P10_UNSIGNED_MATERIAL_SPDX_LITE_AND_PROVENANCE_PASS", flush=True) + + +def negative_cases(lock: dict) -> None: + mutation = [ + ("SOURCE_TREE", ("source", "tree"), "0" * 40), + ("PNPM_LOCK", ("source", "pnpm_lock"), "0" * 40), + ("BUILDER_INDEX", ("builder", "index"), "sha256:" + "0" * 64), + ("RUNTIME_REF", ("runtime", "ref"), "node:24-alpine"), + ("PLATFORM", ("platform",), "linux/arm64"), + ("UNKNOWN_KEY", ("unsafe",), True), + ] + for name, keys, value in mutation: + changed = copy.deepcopy(lock) + node = changed + for key in keys[:-1]: + node = node[key] + node[keys[-1]] = value + try: + validate_lock(changed) + except GateError as exc: + require(str(exc) in ("LOCK_IDENTITY", "LOCK_REFERENCE", "LOCK_DIGEST"), + "NEGATIVE_WRONG_ERROR_" + name) + else: + raise GateError("NEGATIVE_ACCEPTED_" + name) + print("ZITPLANE_P10_LOCK_NEGATIVE_" + name + "_PASS", flush=True) + + rid = run_id() + current = git("rev-parse", "HEAD") + expected = expected_labels(lock, current, rid) + base = { + "Id": "sha256:" + "a" * 64, "Os": "linux", "Architecture": "amd64", + "Config": {"User": "nextjs", "Entrypoint": ENTRYPOINT, + "Labels": expected, "Env": ["NODE_ENV=production"]}, + } + validate_image(base, expected) + invalid = [ + ("ROOT_USER", "IMAGE_NONROOT", lambda c: c["Config"].update(User="root")), + ("WRONG_ARCH", "IMAGE_PLATFORM", lambda c: c.update(Architecture="arm64")), + ("NO_SOURCE_LABEL", "IMAGE_PROVENANCE_LABELS", + lambda c: c["Config"]["Labels"].pop("zitplane.login.source_tree")), + ("WRONG_ENTRYPOINT", "IMAGE_ENTRYPOINT", + lambda c: c["Config"].update(Entrypoint=["/bin/sh"])), + ("SECRET_ENV", "IMAGE_SECRET_ENV_KEY", + lambda c: c["Config"]["Env"].append("AUTH_SECRET=synthetic_test")), + ("INVALID_IMAGE_ID", "IMAGE_ID", lambda c: c.update(Id="sha256:bad")), + ] + for name, expected_error, change in invalid: + mutated = copy.deepcopy(base) + change(mutated) + try: + validate_image(mutated, expected) + except GateError as exc: + require(str(exc) == expected_error, "NEGATIVE_WRONG_ERROR_" + name) + else: + raise GateError("NEGATIVE_ACCEPTED_" + name) + print("ZITPLANE_P10_OCI_NEGATIVE_" + name + "_PASS", flush=True) + print("ZITPLANE_P10_ALL_12_PROVENANCE_NEGATIVES_PASS", flush=True) + + +def main() -> None: + p = argparse.ArgumentParser() + group = p.add_mutually_exclusive_group(required=True) + group.add_argument("--preflight", action="store_true") + group.add_argument("--field", choices=("builder_ref", "runtime_ref", "builder_index", + "runtime_index", "platform")) + group.add_argument("--pin-dockerfile") + group.add_argument("--verify-image", action="store_true") + group.add_argument("--negative", action="store_true") + args = p.parse_args() + lock = load_lock() + if args.field: + typ, _, field = args.field.partition("_") + if args.field == "platform": + print(lock["platform"]) + else: + print(lock[typ]["ref" if field == "ref" else "index"]) + return + if args.preflight: + verify_source(lock) + print("ZITPLANE_P10_PINNED_BASE_INPUTS_PREFLIGHT_PASS", flush=True) + elif args.pin_dockerfile: + verify_source(lock) + pin_dockerfile(lock, args.pin_dockerfile) + elif args.verify_image: + current = verify_source(lock) + verify_builder(lock) + image = docker_inspect("zitplane-login-ci:" + run_id()) + validate_image(image, expected_labels(lock, current, run_id())) + write_material_attestations(lock, image, current) + print("ZITPLANE_P10_IMAGE_ID_NONROOT_ENTRYPOINT_PROVENANCE_PASS", flush=True) + elif args.negative: + negative_cases(lock) + + +if __name__ == "__main__": + try: + main() + except (GateError, OSError, subprocess.SubprocessError, ValueError, KeyError, + TypeError, json.JSONDecodeError) as exc: + # Do not echo input/CLI/JSON from exceptions. + label = str(exc) if type(exc) is GateError else "UNSAFE_INPUT_OR_TOOL_ERROR" + print("ZITPLANE_P10_FAIL_CLOSED_" + label, file=sys.stderr, flush=True) + sys.exit(1)