diff --git a/.github/workflows/ci-cd.yml b/.github/workflows/ci-cd.yml index 933dc59..cd61237 100644 --- a/.github/workflows/ci-cd.yml +++ b/.github/workflows/ci-cd.yml @@ -1,5 +1,4 @@ name: CI/CD - on: push: branches: [main] @@ -7,184 +6,131 @@ on: pull_request: repository_dispatch: types: [docker-php-updated] - permissions: contents: read - concurrency: - group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && format('pr-{0}', github.event.pull_request.number) || github.ref }} + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} cancel-in-progress: ${{ github.event_name == 'pull_request' }} - jobs: - workflow-tests: + checks: runs-on: ubuntu-24.04 - services: - registry: - image: registry:2 - ports: - - 5000:5000 + outputs: + tags: ${{ steps.tags.outputs.tags }} steps: - - uses: actions/checkout@v4 - - uses: docker/setup-buildx-action@v3 - - name: Test release metadata and publication guards - run: python3 -m unittest discover -s tasks -p 'test_release.py' -v - - name: Test manifest promotion against a local registry - run: python3 tasks/test_release_registry.py - - name: Install actionlint - env: - GOBIN: ${{ runner.temp }}/actionlint - run: go install github.com/rhysd/actionlint/cmd/actionlint@v1.7.12 - - name: Lint workflow - run: ${{ runner.temp }}/actionlint/actionlint - + - uses: actions/checkout@v7 + - name: Check generated contexts + run: | + docker run --rm -v "$PWD:/app" fireworkweb/fwd:v1.0 fwd template + git diff --exit-code + - id: tags + run: echo "tags=$(jq -c '[.builds[].name]' fwd-template.json)" >> "$GITHUB_OUTPUT" build: - runs-on: ${{ matrix.runner }} - - services: - registry: - image: registry:2 - ports: - - 5000:5000 - + needs: checks + runs-on: ${{ matrix.platform.runner }} strategy: + fail-fast: false matrix: version: ['8.2-swoole', '8.3-swoole', '8.4-swoole', '8.5-swoole', '8.4-debian-swoole', '8.5-debian-swoole'] type: ['', '-prod'] - arch: [amd64, arm64] - include: - - arch: amd64 - runner: ubuntu-24.04 - - arch: arm64 - runner: ubuntu-24.04-arm - + platform: + - {arch: amd64, runner: ubuntu-24.04} + - {arch: arm64, runner: ubuntu-24.04-arm} + env: + BASE: ${{ matrix.version }}${{ matrix.type }} + NGINX: ${{ matrix.version }}-nginx${{ matrix.type }} + ARCH: ${{ matrix.platform.arch }} steps: - - name: Checkout code - uses: actions/checkout@v4 - - - name: Setup Docker Buildx - uses: docker/setup-buildx-action@v3 + - uses: actions/checkout@v7 + - uses: kool-dev/action/image-build@6a6d04e8d1e1c66afc178e32c7d77d76169c7717 with: - driver-opts: network=host # needed to push to local registry - - - name: Build and export to Docker - uses: docker/build-push-action@v6 + arch: ${{ env.ARCH }} + - name: Build fresh base + id: base + uses: docker/build-push-action@v7 with: - context: ${{ matrix.version }}${{ matrix.type }} - platforms: linux/${{ matrix.arch }} - provenance: false + context: ${{ env.BASE }} + platforms: linux/${{ env.ARCH }} pull: true - push: true - tags: localhost:5000/kooldev/php:${{ matrix.version }}${{ matrix.type }} - - - name: Build and export to Docker (nginx) - uses: docker/build-push-action@v6 + provenance: false + load: true + tags: kooldev/php:${{ env.BASE }} + - name: Build nginx from same-job base (never force-pull) + id: nginx + uses: docker/build-push-action@v7 with: - context: ${{ matrix.version }}-nginx${{ matrix.type }} - platforms: linux/${{ matrix.arch }} + context: ${{ env.NGINX }} + platforms: linux/${{ env.ARCH }} provenance: false - pull: true - push: true - tags: localhost:5000/kooldev/php:${{ matrix.version }}-nginx${{ matrix.type }} - build-contexts: | - kooldev/php:${{ matrix.version }}${{ matrix.type }}=docker-image://localhost:5000/kooldev/php:${{ matrix.version }}${{ matrix.type }} - + load: true + tags: kooldev/php:${{ env.NGINX }} + - uses: kool-dev/action/image-parent@6a6d04e8d1e1c66afc178e32c7d77d76169c7717 + with: + base-ref: kooldev/php:${{ env.BASE }} + base-id: ${{ steps.base.outputs.imageid }} + image-id: ${{ steps.nginx.outputs.imageid }} - name: Tests + env: + BASE_ID: ${{ steps.base.outputs.imageid }} + NGINX_ID: ${{ steps.nginx.outputs.imageid }} run: | - docker run --rm localhost:5000/kooldev/php:${{ matrix.version }}${{ matrix.type }} php -r "exit(extension_loaded('swoole') ? 0 : 1);" - docker run --rm localhost:5000/kooldev/php:${{ matrix.version }}-nginx${{ matrix.type }} nginx -v - docker run --rm localhost:5000/kooldev/php:${{ matrix.version }}-nginx${{ matrix.type }} nginx -t - docker run --rm localhost:5000/kooldev/php:${{ matrix.version }}-nginx${{ matrix.type }} supervisord --version - docker run --rm localhost:5000/kooldev/php:${{ matrix.version }}${{ matrix.type }} dockerize --version - docker run --rm localhost:5000/kooldev/php:${{ matrix.version }}-nginx${{ matrix.type }} dockerize --version - docker run --rm localhost:5000/kooldev/php:${{ matrix.version }}${{ matrix.type }} sh -c 'echo "{{ .Env.TEST_VAR }}" > /tmp/test.tmpl && TEST_VAR=hello dockerize -template /tmp/test.tmpl:/tmp/test.out && test "$(cat /tmp/test.out)" = hello' - docker run --rm -e ASUSER=1000 localhost:5000/kooldev/php:${{ matrix.version }}-nginx${{ matrix.type }} php -r "exit(posix_getuid() === 1000 ? 0 : 1);" - - - name: Test Supervisor lifecycle - run: bash tasks/test-supervisor.sh localhost:5000/kooldev/php:${{ matrix.version }}-nginx${{ matrix.type }} - + docker run --rm "$BASE_ID" php -r "exit(extension_loaded('swoole') ? 0 : 1);" + docker run --rm "$NGINX_ID" nginx -v + docker run --rm "$NGINX_ID" nginx -t + docker run --rm "$NGINX_ID" supervisord --version + docker run --rm "$BASE_ID" dockerize --version + docker run --rm "$NGINX_ID" dockerize --version + docker run --rm "$BASE_ID" sh -c 'echo "{{ .Env.TEST_VAR }}" > /tmp/test.tmpl && TEST_VAR=hello dockerize -template /tmp/test.tmpl:/tmp/test.out && test "$(cat /tmp/test.out)" = hello' + docker run --rm -e ASUSER=1000 "$NGINX_ID" php -r "exit(posix_getuid() === 1000 ? 0 : 1);" + bash tasks/test-supervisor.sh "$NGINX_ID" - name: Tests (dev) if: matrix.type == '' + env: + BASE_ID: ${{ steps.base.outputs.imageid }} + NGINX_ID: ${{ steps.nginx.outputs.imageid }} run: | - docker run --rm localhost:5000/kooldev/php:${{ matrix.version }}${{ matrix.type }} node -v - docker run --rm localhost:5000/kooldev/php:${{ matrix.version }}${{ matrix.type }} yarn -v - docker run --rm localhost:5000/kooldev/php:${{ matrix.version }}-nginx${{ matrix.type }} node -v - docker run --rm localhost:5000/kooldev/php:${{ matrix.version }}-nginx${{ matrix.type }} yarn -v - - - name: Login to DockerHub - if: contains(fromJSON('["push", "workflow_dispatch", "repository_dispatch"]'), github.event_name) && github.ref == 'refs/heads/main' && github.repository == 'kool-dev/docker-php-swoole' - uses: docker/login-action@v3 + docker run --rm "$BASE_ID" node -v + docker run --rm "$BASE_ID" yarn -v + docker run --rm "$NGINX_ID" node -v + docker run --rm "$NGINX_ID" yarn -v + - uses: kool-dev/action/image-stage@6a6d04e8d1e1c66afc178e32c7d77d76169c7717 + if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' && github.repository == 'kool-dev/docker-php-swoole' with: + canonical-repository: kool-dev/docker-php-swoole + default-branch: main + repository: kooldev/php + arch: ${{ env.ARCH }} + group: ${{ env.BASE }} + images: >- + [{"tag":"${{ env.BASE }}","id":"${{ steps.base.outputs.imageid }}"}, + {"tag":"${{ env.NGINX }}","id":"${{ steps.nginx.outputs.imageid }}"}] username: ${{ secrets.DOCKER_USERNAME }} password: ${{ secrets.DOCKER_PASSWORD }} - - - name: Stage exact tested images - if: contains(fromJSON('["push", "workflow_dispatch", "repository_dispatch"]'), github.event_name) && github.ref == 'refs/heads/main' && github.repository == 'kool-dev/docker-php-swoole' - env: - VERSION: ${{ matrix.version }} - TYPE: ${{ matrix.type }} - ARCH: ${{ matrix.arch }} - run: python3 tasks/release.py stage "$VERSION" "$TYPE" "$ARCH" release-metadata - - - name: Upload immutable release metadata - if: contains(fromJSON('["push", "workflow_dispatch", "repository_dispatch"]'), github.event_name) && github.ref == 'refs/heads/main' && github.repository == 'kool-dev/docker-php-swoole' - uses: actions/upload-artifact@v7.0.2 - with: - name: swoole-${{ github.run_id }}-${{ github.run_attempt }}-${{ matrix.version }}${{ matrix.type }}-${{ matrix.arch }} - path: release-metadata/*.json - if-no-files-found: error - retention-days: 7 - publish: - needs: [build, workflow-tests] - if: contains(fromJSON('["push", "workflow_dispatch", "repository_dispatch"]'), github.event_name) && github.ref == 'refs/heads/main' && github.repository == 'kool-dev/docker-php-swoole' + needs: [checks, build] + if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' && github.repository == 'kool-dev/docker-php-swoole' runs-on: ubuntu-24.04 steps: - - uses: actions/checkout@v4 - - uses: docker/setup-buildx-action@v3 - - uses: actions/download-artifact@v8.0.2 - with: - pattern: swoole-${{ github.run_id }}-${{ github.run_attempt }}-* - path: release-metadata - - name: Login to DockerHub - uses: docker/login-action@v3 + - uses: kool-dev/action/image-publish@6a6d04e8d1e1c66afc178e32c7d77d76169c7717 with: + canonical-repository: kool-dev/docker-php-swoole + default-branch: main + repository: kooldev/php + tags: ${{ needs.checks.outputs.tags }} username: ${{ secrets.DOCKER_USERNAME }} password: ${{ secrets.DOCKER_PASSWORD }} - - name: Preflight all digests and promote manifests only - run: python3 tasks/release.py promote release-metadata - dispatch: needs: publish - if: contains(fromJSON('["push", "workflow_dispatch", "repository_dispatch"]'), github.event_name) && github.ref == 'refs/heads/main' && github.repository == 'kool-dev/docker-php-swoole' - runs-on: ubuntu-latest + if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' && github.repository == 'kool-dev/docker-php-swoole' + runs-on: ubuntu-24.04 timeout-minutes: 5 - env: - GH_TOKEN: ${{ secrets.DISPATCH_TOKEN || secrets.WORKFLOW_TOKEN }} steps: - - name: Check dispatch credential - id: credential + - name: Notify OCI8 after complete publication + env: + GH_TOKEN: ${{ secrets.DISPATCH_TOKEN || secrets.WORKFLOW_TOKEN }} run: | - if [ -z "$GH_TOKEN" ]; then - echo "::error::Set DISPATCH_TOKEN or WORKFLOW_TOKEN with dispatch access to kool-dev/docker-php-oci8." + if [[ -z "$GH_TOKEN" ]]; then + echo "::error::Configure DISPATCH_TOKEN or WORKFLOW_TOKEN for OCI8 dispatch." exit 1 fi - - - name: Notify OCI8 after all Swoole tags are published - id: notify - run: | - gh api --method POST repos/kool-dev/docker-php-oci8/dispatches \ - -f event_type=docker-php-swoole-updated - - - name: Summarize publication and downstream notification - if: always() - env: - CREDENTIAL_OUTCOME: ${{ steps.credential.outcome }} - DISPATCH_OUTCOME: ${{ steps.notify.outcome }} - run: | - { - echo "### Swoole release propagation" - echo "- All 24 Swoole stable manifests: published successfully." - echo "- Dispatch credential check: $CREDENTIAL_OUTCOME." - echo "- OCI8 docker-php-swoole-updated dispatch: $DISPATCH_OUTCOME." - echo "- Dispatch acceptance does not confirm OCI8 build or publication completion." - } >> "$GITHUB_STEP_SUMMARY" + gh api --method POST repos/kool-dev/docker-php-oci8/dispatches -f event_type=docker-php-swoole-updated + echo "- OCI8: dispatch accepted (not downstream completion)." >> "$GITHUB_STEP_SUMMARY" diff --git a/README.md b/README.md index 1283d2b..d1eba06 100644 --- a/README.md +++ b/README.md @@ -54,9 +54,9 @@ Please refer to [kooldev/php](https://github.com/kool-dev/docker-php). PHP's scheduled rebuild sends `docker-php-updated` after publication to start a Swoole rebuild. Swoole has no separate cron schedule; manual workflow runs remain available for recovery. Builds explicitly pull parents. Main-branch releases share a concurrency group and are not canceled in progress; only superseded PR runs are canceled. GitHub may replace pending runs and does not promise FIFO ordering. -The 24 native jobs use `ubuntu-24.04` for amd64 and `ubuntu-24.04-arm` for arm64. Each builds and tests a base/NGINX pair through a job-local registry; NGINX consumes that same job's fresh base. After all tests in a job pass, trusted main-branch runs retag those exact tested daemon images (without rebuilding) to `kooldev/php:ci-swoole-RUN_ID-RUN_ATTEMPT-VARIANT-ARCH`. PRs, forks, and manual feature-branch runs never log in, stage, publish, or notify OCI8. +The 24 native jobs use `ubuntu-24.04` for amd64 and `ubuntu-24.04-arm` for arm64. Each builds and tests a base/NGINX pair using Docker's same-job local image store; NGINX never force-pulls a stale public base. A shared check verifies the tested base ID and full layer ancestry. After all runtime/Supervisor/dev tests pass, trusted main-branch runs stage those exact immutable IDs without rebuilding. PRs, forks, and manual feature-branch runs never log in, stage, publish, or notify OCI8. -A single manifest-only job requires every native job and the workflow checks to succeed. It validates all 24 stable tags × both architectures, run/attempt scope, repository, unique tag/platform entries, digest format, and every remote digest's platform before updating any stable tag. Stable manifests reference the recorded immutable Docker Hub digests, never staging tag lookups or rebuilt images. Metadata artifacts are retained for seven days. There is no cross-tag transaction: a registry failure during promotion can still leave a partially updated release. +CI uses [shared Bash/`jq` actions](https://github.com/kool-dev/action/blob/master/image-ci.md), pinned in the workflow. One publisher validates the complete 24-tag × two-architecture release before stable updates. Swoole builds, generation checks and runtime tests stay here. Recovery requires **Re-run all jobs**, not just failed jobs: artifacts and staging tags are scoped to the current run ID **and attempt**, and incomplete attempts fail closed. A new manual main-branch workflow run also rebuilds/tests the complete release. Do not combine artifacts from previous attempts. @@ -64,7 +64,7 @@ Only after all 24 stable manifests succeed, one bounded notification sends `dock The notification uses `DISPATCH_TOKEN`, falling back to `WORKFLOW_TOKEN`. The selected credential must permit repository dispatch to OCI8; secret presence alone does not verify access. Missing credentials or failed dispatches fail the notification job visibly, without undoing published images. The job summary distinguishes publication from notification; an accepted dispatch does not prove OCI8 completed. Investigate and retry a failed notification with a manual workflow run; there is no independent downstream schedule to mask a broken chain. This is not an atomic release or digest-pinned parent chain. -Release logic has offline coverage via `python3 -m unittest discover -s tasks -p 'test_release.py' -v`; CI also runs actionlint and `python3 tasks/test_release_registry.py` against a disposable local registry. The latter stages tiny scratch fixtures and verifies all 24 two-platform manifests without touching Docker Hub (set `RELEASE_TEST_REGISTRY=localhost:PORT` to use another local port). It does not execute ARM code. Native amd64/arm64 image tests remain required to validate the actual runtime images. +Shared Bash contract and real loopback-registry tests live in the tooling repository. Here CI runs the real template generator and native image/Supervisor tests. Synthetic registry fixtures do not execute ARM application code. ### Update images with templates diff --git a/tasks/release.py b/tasks/release.py deleted file mode 100644 index 135f720..0000000 --- a/tasks/release.py +++ /dev/null @@ -1,125 +0,0 @@ -#!/usr/bin/env python3 -"""Stage tested daemon images, then promote only a complete run's digests.""" - -import json -import os -from pathlib import Path -import re -import subprocess -import sys - -REPOSITORY = "kooldev/php" -VERSIONS = ("8.2-swoole", "8.3-swoole", "8.4-swoole", "8.5-swoole", - "8.4-debian-swoole", "8.5-debian-swoole") -TAGS = tuple(f"{version}{nginx}{kind}" for version in VERSIONS - for nginx in ("", "-nginx") for kind in ("", "-prod")) -ARCHES = ("amd64", "arm64") -DIGEST = re.compile(r"sha256:[0-9a-f]{64}") - - -def command(*args): - return subprocess.check_output(args, text=True).strip() - - -def release_scope(): - if (os.environ.get("GITHUB_REPOSITORY") != "kool-dev/docker-php-swoole" - or os.environ.get("GITHUB_REF") != "refs/heads/main" - or os.environ.get("GITHUB_EVENT_NAME") not in - ("push", "workflow_dispatch", "repository_dispatch")): - raise ValueError("Publication requires a trusted main-branch event") - scope = (os.environ["GITHUB_RUN_ID"], os.environ["GITHUB_RUN_ATTEMPT"]) - if not all(re.fullmatch(r"[1-9][0-9]*", value) for value in scope): - raise ValueError("Invalid run ID/attempt") - return scope - - -def staging_tag(run, attempt, tag, arch): - return f"ci-swoole-{run}-{attempt}-{tag}-{arch}" - - -def stage(version, kind, arch, directory): - run, attempt = release_scope() - if version not in VERSIONS or kind not in ("", "-prod") or arch not in ARCHES: - raise ValueError("Invalid build variant/platform") - records = [] - for tag in (f"{version}{kind}", f"{version}-nginx{kind}"): - source = f"localhost:5000/{REPOSITORY}:{tag}" - # No pull or rebuild: these are the daemon images used by docker run tests. - image = json.loads(command("docker", "image", "inspect", source))[0] - image_id = image["Id"] - if (not DIGEST.fullmatch(image_id) or image["Architecture"] != arch - or image["Os"] != "linux"): - raise ValueError(f"Unexpected tested image: {source}") - staging = staging_tag(run, attempt, tag, arch) - target = f"{REPOSITORY}:{staging}" - command("docker", "tag", image_id, target) - if command("docker", "image", "inspect", "--format", "{{.Id}}", target) != image_id: - raise ValueError("Staging tag is not the tested image") - command("docker", "push", "--quiet", target) - descriptor = json.loads(command("docker", "buildx", "imagetools", "inspect", - target, "--format", "{{json .Manifest}}")) - digest = descriptor["digest"] - if not isinstance(digest, str) or not DIGEST.fullmatch(digest): - raise ValueError(f"Invalid pushed digest: {digest}") - records.append(dict(repository=REPOSITORY, run_id=run, run_attempt=attempt, - tag=tag, arch=arch, staging_tag=staging, - digest=digest, image_id=image_id)) - path = Path(directory) - path.mkdir(parents=True, exist_ok=True) - (path / f"{version}{kind}-{arch}.json").write_text(json.dumps(records) + "\n") - - -def load_records(directory, run, attempt): - records = {} - for path in sorted(Path(directory).rglob("*.json")): - batch = json.loads(path.read_text()) - if not isinstance(batch, list): - raise ValueError(f"Invalid artifact: {path}") - for record in batch: - if not isinstance(record, dict) or set(record) != { - "repository", "run_id", "run_attempt", "tag", "arch", - "staging_tag", "digest", "image_id" - }: - raise ValueError("Malformed metadata") - tag, arch = record["tag"], record["arch"] - if (record["repository"] != REPOSITORY - or record["run_id"] != run or record["run_attempt"] != attempt - or tag not in TAGS or arch not in ARCHES - or record["staging_tag"] != staging_tag(run, attempt, tag, arch) - or not isinstance(record["digest"], str) - or not DIGEST.fullmatch(record["digest"]) - or not isinstance(record["image_id"], str) - or not DIGEST.fullmatch(record["image_id"])): - raise ValueError("Invalid repository, scope, tag, architecture or digest") - key = (tag, arch) - if key in records: - raise ValueError(f"Duplicate metadata: {key}") - records[key] = record - if set(records) != {(tag, arch) for tag in TAGS for arch in ARCHES}: - raise ValueError("Incomplete release: require all 24 tags on both architectures") - return records - - -def promote(directory): - run, attempt = release_scope() - records = load_records(directory, run, attempt) - # Resolve every immutable reference and platform before changing ANY stable tag. - for (tag, arch), record in records.items(): - reference = f"{REPOSITORY}@{record['digest']}" - image = json.loads(command("docker", "buildx", "imagetools", "inspect", - reference, "--format", "{{json .Image}}")) - if image["architecture"] != arch or image["os"] != "linux": - raise ValueError(f"Wrong platform for {tag}/{arch}") - for tag in TAGS: - command("docker", "buildx", "imagetools", "create", "--tag", - f"{REPOSITORY}:{tag}", - *(f"{REPOSITORY}@{records[tag, arch]['digest']}" for arch in ARCHES)) - - -if __name__ == "__main__": - if len(sys.argv) == 6 and sys.argv[1] == "stage": - stage(*sys.argv[2:]) - elif len(sys.argv) == 3 and sys.argv[1] == "promote": - promote(sys.argv[2]) - else: - sys.exit("Usage: release.py stage VERSION TYPE ARCH DIRECTORY | promote DIRECTORY") diff --git a/tasks/test_release.py b/tasks/test_release.py deleted file mode 100644 index 0d3994e..0000000 --- a/tasks/test_release.py +++ /dev/null @@ -1,195 +0,0 @@ -"""Offline tests for the release boundary.""" - -import copy -import json -import os -from pathlib import Path -import tempfile -import unittest -from unittest.mock import patch - -import release - - -TRUSTED = dict(GITHUB_REPOSITORY="kool-dev/docker-php-swoole", - GITHUB_REF="refs/heads/main", GITHUB_EVENT_NAME="push", - GITHUB_RUN_ID="12345", GITHUB_RUN_ATTEMPT="2") - - -class ReleaseTests(unittest.TestCase): - def setUp(self): - self.temp = tempfile.TemporaryDirectory() - self.addCleanup(self.temp.cleanup) - self.directory = Path(self.temp.name) - env = patch.dict(os.environ, TRUSTED, clear=True) - env.start() - self.addCleanup(env.stop) - self.records = [ - dict(repository=release.REPOSITORY, run_id="12345", run_attempt="2", - tag=tag, arch=arch, digest=f"sha256:{index:064x}", - image_id=f"sha256:{index + 100:064x}", - staging_tag=release.staging_tag("12345", "2", tag, arch)) - for index, (tag, arch) in enumerate( - (tag, arch) for tag in release.TAGS for arch in release.ARCHES) - ] - - def write(self, records=None): - (self.directory / "records.json").write_text( - json.dumps(self.records if records is None else records)) - - def test_complete_metadata(self): - self.write() - self.assertEqual(len(release.load_records(self.directory, "12345", "2")), 48) - - def test_invalid_metadata_never_touches_registry(self): - cases = [self.records[:-1], self.records + [self.records[0]], [], {}] - for field, value in ( - ("repository", "attacker/php"), ("run_attempt", "1"), ("run_id", "999"), - ("tag", "latest"), ("arch", "s390x"), ("staging_tag", "old-attempt"), - ("digest", "sha256:bad"), ("digest", "sha256:" + "g" * 64), - ("digest", "sha256:" + "a" * 64 + ";echo bad"), - ("digest", None), ("image_id", "bad"), - ): - records = copy.deepcopy(self.records) - records[0][field] = value - cases.append(records) - records = copy.deepcopy(self.records) - del records[0]["digest"] - cases.append(records) - for records in cases: - with self.subTest(records=str(records)[:150]): - self.write(records) - with patch.object(release, "command") as command: - with self.assertRaises(ValueError): - release.promote(self.directory) - command.assert_not_called() - - def test_all_remote_platforms_preflight_before_manifest_updates(self): - self.write() - commands = [] - platforms = {record["digest"]: record["arch"] for record in self.records} - - def docker(*args): - commands.append(args) - if "inspect" in args: - digest = args[4].split("@")[1] - return json.dumps(dict(os="linux", architecture=platforms[digest])) - return "" - - with patch.object(release, "command", side_effect=docker): - release.promote(self.directory) - self.assertEqual(len(commands), 72) - self.assertTrue(all(cmd[3] == "inspect" for cmd in commands[:48])) - for tag, cmd in zip(release.TAGS, commands[48:]): - self.assertEqual(cmd[:6], ("docker", "buildx", "imagetools", "create", - "--tag", f"kooldev/php:{tag}")) - self.assertEqual(cmd[6:], tuple( - f"kooldev/php@{record['digest']}" for record in self.records - if record["tag"] == tag)) - self.assertFalse(any("build" in cmd or "pull" in cmd for cmd in commands)) - - def test_last_bad_remote_platform_prevents_all_stable_updates(self): - self.write() - responses = [json.dumps(dict(os="linux", architecture=r["arch"])) - for r in self.records] - responses[-1] = '{"os":"linux","architecture":"amd64"}' - with patch.object(release, "command", side_effect=responses) as command: - with self.assertRaises(ValueError): - release.promote(self.directory) - self.assertEqual(command.call_count, 48) - self.assertTrue(all(call.args[3] == "inspect" for call in command.call_args_list)) - - def test_registry_failure_prevents_all_stable_updates(self): - self.write() - with patch.object(release, "command", side_effect=RuntimeError("registry unavailable")): - with self.assertRaises(RuntimeError): - release.promote(self.directory) - - def test_stage_retags_tested_image_ids_without_pull_or_build(self): - image_ids = ["sha256:" + "a" * 64, "sha256:" + "b" * 64] - commands = [] - - def docker(*args): - commands.append(args) - image_id = image_ids[0 if len(commands) <= 5 else 1] - if args[:3] == ("docker", "image", "inspect"): - if "--format" in args: - return image_id - return json.dumps([dict(Id=image_id, Architecture="amd64", Os="linux")]) - if "imagetools" in args: - return json.dumps(dict(digest="sha256:" + "c" * 64)) - return "" - - with patch.object(release, "command", side_effect=docker): - release.stage("8.5-swoole", "-prod", "amd64", self.directory) - self.assertEqual(len(commands), 10) - for offset, image_id in ((0, image_ids[0]), (5, image_ids[1])): - self.assertEqual(commands[offset + 1][:3], ("docker", "tag", image_id)) - self.assertEqual(commands[offset + 2][-1], commands[offset + 1][-1]) - self.assertEqual(commands[offset + 3][-1], commands[offset + 1][-1]) - records = json.loads(next(self.directory.glob("*.json")).read_text()) - self.assertEqual([record["image_id"] for record in records], image_ids) - self.assertTrue(all(record["staging_tag"].startswith("ci-swoole-12345-2-") - for record in records)) - self.assertFalse(any("build" in cmd or "pull" in cmd for cmd in commands)) - - def test_retag_mismatch_prevents_push(self): - image = dict(Id="sha256:" + "a" * 64, Architecture="amd64", Os="linux") - with patch.object(release, "command", - side_effect=[json.dumps([image]), "", "sha256:" + "b" * 64]) as command: - with self.assertRaises(ValueError): - release.stage("8.5-swoole", "", "amd64", self.directory) - self.assertFalse(any(call.args[1] == "push" for call in command.call_args_list)) - self.assertEqual(list(self.directory.iterdir()), []) - - def test_untrusted_events_cannot_stage_or_promote(self): - for override in ( - dict(GITHUB_EVENT_NAME="pull_request"), - dict(GITHUB_EVENT_NAME="pull_request_target"), - dict(GITHUB_EVENT_NAME="workflow_dispatch", GITHUB_REF="refs/heads/feature"), - dict(GITHUB_REPOSITORY="fork/docker-php-swoole"), - dict(GITHUB_RUN_ATTEMPT="0"), - ): - with self.subTest(override=override), patch.dict(os.environ, override): - with patch.object(release, "command") as command: - for action in (lambda: release.promote(self.directory), - lambda: release.stage("8.5-swoole", "", "amd64", self.directory)): - with self.assertRaises(ValueError): - action() - command.assert_not_called() - - def test_workflow_publication_boundary(self): - workflow = (Path(__file__).resolve().parents[1] / - ".github/workflows/ci-cd.yml").read_text() - build = workflow.split(" build:\n")[1].split(" publish:\n")[0] - publish = workflow.split(" publish:\n")[1].split(" dispatch:\n")[0] - dispatch = workflow.split(" dispatch:\n")[1] - guard = ("contains(fromJSON('[\"push\", \"workflow_dispatch\", \"repository_dispatch\"]'), " - "github.event_name) && github.ref == 'refs/heads/main' && " - "github.repository == 'kool-dev/docker-php-swoole'") - self.assertEqual(build.count("if: " + guard), 3) - self.assertIn("if: " + guard, publish) - self.assertIn("if: " + guard, dispatch) - self.assertIn("needs: [build, workflow-tests]", publish) - self.assertIn("needs: publish", dispatch) - self.assertLess(build.index("Test Supervisor lifecycle"), build.index("Login to DockerHub")) - self.assertLess(build.index("Tests (dev)"), build.index("Login to DockerHub")) - self.assertEqual(workflow.count("uses: docker/build-push-action@"), 2) - self.assertNotIn("setup-qemu", workflow) - self.assertNotIn("build-push-action", publish) - self.assertIn("kooldev/php:${{ matrix.version }}${{ matrix.type }}=" - "docker-image://localhost:5000/", build) - self.assertIn("runner: ubuntu-24.04\n", build) - self.assertIn("runner: ubuntu-24.04-arm\n", build) - self.assertIn("name: swoole-${{ github.run_id }}-${{ github.run_attempt }}-", build) - self.assertIn("pattern: swoole-${{ github.run_id }}-${{ github.run_attempt }}-*", publish) - self.assertIn("actions/upload-artifact@v7.0.2", build) - self.assertIn("actions/download-artifact@v8.0.2", publish) - self.assertNotIn("schedule:", workflow) - self.assertIn("cancel-in-progress: ${{ github.event_name == 'pull_request' }}", workflow) - self.assertIn("secrets.DISPATCH_TOKEN || secrets.WORKFLOW_TOKEN", dispatch) - self.assertIn("timeout-minutes: 5", dispatch) - - -if __name__ == "__main__": - unittest.main() diff --git a/tasks/test_release_registry.py b/tasks/test_release_registry.py deleted file mode 100644 index 52036a7..0000000 --- a/tasks/test_release_registry.py +++ /dev/null @@ -1,88 +0,0 @@ -"""Opt-in real registry boundary test; only writes to the specified loopback registry.""" - -import json -import os -from pathlib import Path -import re -import subprocess -import tempfile -from unittest.mock import patch - -import release - - -def main(): - registry = os.environ.get("RELEASE_TEST_REGISTRY", "localhost:5000") - if not re.fullmatch(r"localhost:[0-9]+", registry): - raise ValueError("Integration test requires a loopback registry") - repository = f"{registry}/swoole-release-test/php" - original = release.command - commands = [] - - def local_command(*args): - # Production code stays hard-coded to Docker Hub. Only this test rewrites - # references; no credentials, production writes, or production reads. - mapped = [] - for arg in args: - for prefix in ("localhost:5000/kooldev/php", "kooldev/php"): - if arg.startswith(prefix + ":") or arg.startswith(prefix + "@"): - arg = repository + arg[len(prefix):] - break - mapped.append(arg) - commands.append(mapped) - return original(*mapped) - - with tempfile.TemporaryDirectory() as temporary: - root = Path(temporary) - (root / "Dockerfile").write_text("FROM scratch\nLABEL purpose=swoole-release-test\n") - digests, ids = {}, {} - for arch in release.ARCHES: - target = f"{repository}:fixture-{arch}" - subprocess.run(["docker", "buildx", "build", "--platform", f"linux/{arch}", - "--provenance=false", "--load", "--tag", target, - str(root)], check=True) - ids[arch] = original("docker", "image", "inspect", "--format", "{{.Id}}", target) - original("docker", "push", "--quiet", target) - digests[arch] = json.loads(original( - "docker", "buildx", "imagetools", "inspect", target, - "--format", "{{json .Manifest}}"))["digest"] - - # The inspected daemon IDs are our tested fixture images. Stage them by - # ID through the unmodified production code, with registry-only routing. - for tag in ("8.5-swoole-prod", "8.5-swoole-nginx-prod"): - original("docker", "tag", ids["amd64"], f"{repository}:{tag}") - env = dict(GITHUB_REPOSITORY="kool-dev/docker-php-swoole", - GITHUB_REF="refs/heads/main", GITHUB_EVENT_NAME="push", - GITHUB_RUN_ID="12345", GITHUB_RUN_ATTEMPT="2") - with patch.dict(os.environ, env), patch.object(release, "command", local_command): - release.stage("8.5-swoole", "-prod", "amd64", root / "staged") - staged = json.loads(next((root / "staged").glob("*.json")).read_text()) - assert all(record["image_id"] == ids["amd64"] for record in staged) - assert all(record["digest"] == digests["amd64"] for record in staged) - # Expand the two tiny native-config fixtures over the complete release - # shape. This tests real remote preflight and all stable manifest writes. - records = [ - dict(repository=release.REPOSITORY, run_id="12345", run_attempt="2", - tag=tag, arch=arch, digest=digests[arch], image_id=ids[arch], - staging_tag=release.staging_tag("12345", "2", tag, arch)) - for tag in release.TAGS for arch in release.ARCHES - ] - metadata = root / "metadata" - metadata.mkdir() - (metadata / "records.json").write_text(json.dumps(records)) - commands.clear() - release.promote(metadata) - assert len(commands) == 72 - assert all(cmd[3] == "inspect" for cmd in commands[:48]) - for tag in release.TAGS: - manifest = json.loads(original( - "docker", "buildx", "imagetools", "inspect", - f"{repository}:{tag}", "--raw")) - assert {entry["platform"]["architecture"] for entry in manifest["manifests"]} == { - "amd64", "arm64"} - assert {entry["digest"] for entry in manifest["manifests"]} == set(digests.values()) - print("PASS: exact daemon-ID staging and 24 two-platform manifest-only promotions, loopback only") - - -if __name__ == "__main__": - main()