diff --git a/.github/scripts/devcontainer/publication.py b/.github/scripts/devcontainer/publication.py new file mode 100644 index 0000000..561b1fe --- /dev/null +++ b/.github/scripts/devcontainer/publication.py @@ -0,0 +1,78 @@ +"""Small GHCR publication contract.""" + +import argparse +import json +import re + + +SHA = re.compile(r"[0-9a-f]{40}\Z") +DIGEST = re.compile(r"sha256:[0-9a-f]{64}\Z") + + +def _identity_tag(prefix, source_sha, run_id, attempt): + if not SHA.fullmatch(source_sha): + raise ValueError("Invalid source SHA") + if type(run_id) is not int or run_id <= 0 or type(attempt) is not int or attempt <= 0: + raise ValueError("Run identity must be positive integers") + tag = f"{prefix}-{source_sha}-run-{run_id}-attempt-{attempt}" + if len(tag + "-stage-amd64") > 128: + raise ValueError("Image staging tag exceeds 128 characters") + return tag + + +def durable_tag(source_sha, run_id, attempt): + return _identity_tag("build", source_sha, run_id, attempt) + + +def candidate_tag(pr, source_sha, run_id, attempt): + if type(pr) is not int or pr <= 0: + raise ValueError("PR number must be positive") + return _identity_tag(f"pr-{pr}", source_sha, run_id, attempt) + + +def validate_digest(value): + if not isinstance(value, str) or not DIGEST.fullmatch(value): + raise ValueError("Invalid image digest") + return value + + +def verify_index(index): + found = {} + for descriptor in index.get("manifests", []): + digest = validate_digest(descriptor.get("digest")) + annotations = descriptor.get("annotations", {}) + if annotations.get("vnd.docker.reference.type") == "attestation-manifest": + continue + platform = descriptor.get("platform", {}) + key = f"{platform.get('os')}/{platform.get('architecture')}" + if key not in ("linux/amd64", "linux/arm64") or key in found: + raise ValueError("Unexpected or duplicate runnable platform") + found[key] = digest + if set(found) != {"linux/amd64", "linux/arm64"}: + raise ValueError("Both native platforms are required") + return found + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("command", choices=("tag", "candidate", "verify-index", "validate-digest")) + parser.add_argument("--source-sha") + parser.add_argument("--run-id", type=int) + parser.add_argument("--attempt", type=int) + parser.add_argument("--pr", type=int) + parser.add_argument("--index") + parser.add_argument("--digest") + args = parser.parse_args() + if args.command == "tag": + print(durable_tag(args.source_sha, args.run_id, args.attempt)) + elif args.command == "candidate": + print(candidate_tag(args.pr, args.source_sha, args.run_id, args.attempt)) + elif args.command == "validate-digest": + validate_digest(args.digest) + else: + with open(args.index, encoding="utf-8") as stream: + print(json.dumps(verify_index(json.load(stream)), sort_keys=True)) + + +if __name__ == "__main__": + main() diff --git a/.github/tests/devcontainer/test_publication.py b/.github/tests/devcontainer/test_publication.py new file mode 100644 index 0000000..89120ce --- /dev/null +++ b/.github/tests/devcontainer/test_publication.py @@ -0,0 +1,105 @@ +"""Small GHCR publication contract tests.""" + +import importlib.util +from pathlib import Path +import subprocess +import unittest + + +MODULE = Path(__file__).resolve().parents[3] / ".github/scripts/devcontainer/publication.py" + + +def load_module(): + spec = importlib.util.spec_from_file_location("publication", MODULE) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +class PublicationTests(unittest.TestCase): + def setUp(self): + self.publication = load_module() + self.source = "a" * 40 + + def test_durable_tag_contains_source_run_and_attempt(self): + self.assertEqual( + self.publication.durable_tag(self.source, 44964975569, 2), + "build-" + self.source + "-run-44964975569-attempt-2", + ) + + def test_candidate_tag_uses_pr_merge_sha_run_and_attempt(self): + self.assertEqual( + self.publication.candidate_tag(123, self.source, 44964975569, 2), + "pr-123-" + self.source + "-run-44964975569-attempt-2", + ) + + def test_tags_reject_invalid_identity(self): + for function, args in ( + (self.publication.durable_tag, ("bad", 1, 1)), + (self.publication.candidate_tag, (0, self.source, 1, 1)), + (self.publication.candidate_tag, (123, "bad", 1, 1)), + (self.publication.durable_tag, (self.source, 0, 1)), + ): + with self.assertRaises(ValueError): + function(*args) + + def test_digest_validation(self): + digest = "sha256:" + "1" * 64 + self.assertEqual(self.publication.validate_digest(digest), digest) + for value in ("", "sha256:bad", "sha256:" + "1" * 63): + with self.assertRaises(ValueError): + self.publication.validate_digest(value) + + def test_validate_digest_cli_accepts_valid_digest(self): + digest = "sha256:" + "1" * 64 + result = subprocess.run( + ["python3", str(MODULE), "validate-digest", "--digest", digest], + check=False, + capture_output=True, + text=True, + ) + self.assertEqual(result.returncode, 0, result.stderr) + + def test_validate_digest_cli_rejects_invalid_digest(self): + result = subprocess.run( + ["python3", str(MODULE), "validate-digest", "--digest", "sha256:bad"], + check=False, + capture_output=True, + text=True, + ) + self.assertNotEqual(result.returncode, 0) + + def test_index_requires_exactly_amd64_and_arm64(self): + index = {"manifests": [ + {"digest": "sha256:" + "1" * 64, + "platform": {"os": "linux", "architecture": "amd64"}}, + {"digest": "sha256:" + "2" * 64, + "platform": {"os": "linux", "architecture": "arm64"}}, + ]} + self.assertEqual(self.publication.verify_index(index), { + "linux/amd64": "sha256:" + "1" * 64, + "linux/arm64": "sha256:" + "2" * 64, + }) + index_with_attestation = { + "manifests": index["manifests"] + [{ + "digest": "sha256:" + "3" * 64, + "mediaType": "application/vnd.oci.image.manifest.v1+json", + "platform": {"os": "unknown", "architecture": "unknown"}, + "annotations": { + "vnd.docker.reference.type": "attestation-manifest", + }, + }], + } + self.assertEqual(self.publication.verify_index(index_with_attestation), { + "linux/amd64": "sha256:" + "1" * 64, + "linux/arm64": "sha256:" + "2" * 64, + }) + for manifests in (index["manifests"][:1], index["manifests"] + [index["manifests"][0]], + index["manifests"] + [{"digest": "sha256:" + "3" * 64, + "platform": {"os": "linux", "architecture": "s390x"}}]): + with self.assertRaises(ValueError): + self.publication.verify_index({"manifests": manifests}) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/devcontainer.yml b/.github/workflows/devcontainer.yml new file mode 100644 index 0000000..9b5a895 --- /dev/null +++ b/.github/workflows/devcontainer.yml @@ -0,0 +1,122 @@ +name: devcontainer GHCR publication + +on: + workflow_call: + inputs: + candidate: + type: boolean + required: false + default: false + outputs: + image_ref: + description: Verified immutable image reference. + value: ${{ jobs.publish.outputs.image_ref }} + +permissions: + contents: read + +jobs: + prepare: + if: github.repository == 'WasmEdge/devcontainer' && (github.ref == format('refs/heads/{0}', github.event.repository.default_branch) || inputs.candidate) + runs-on: ubuntu-latest + outputs: + tag: ${{ steps.identity.outputs.tag }} + steps: + - uses: actions/checkout@v7 + with: + ref: ${{ github.sha }} + persist-credentials: false + - id: identity + env: + SOURCE_SHA: ${{ github.sha }} + RUN_ID: ${{ github.run_id }} + ATTEMPT: ${{ github.run_attempt }} + run: | + if [ '${{ inputs.candidate }}' = true ]; then + tag=$(python3 .github/scripts/devcontainer/publication.py candidate --pr '${{ github.event.number }}' \ + --source-sha "$SOURCE_SHA" --run-id "$RUN_ID" --attempt "$ATTEMPT") + else + tag=$(python3 .github/scripts/devcontainer/publication.py tag \ + --source-sha "$SOURCE_SHA" --run-id "$RUN_ID" --attempt "$ATTEMPT") + fi + echo "tag=$tag" >> "$GITHUB_OUTPUT" + + build: + needs: prepare + if: github.repository == 'WasmEdge/devcontainer' && (github.ref == format('refs/heads/{0}', github.event.repository.default_branch) || inputs.candidate) + runs-on: ${{ matrix.runner }} + permissions: + contents: read + packages: write + strategy: + fail-fast: false + matrix: + include: + - runner: ubuntu-latest + target: x86_64 + arch: amd64 + - runner: ubuntu-24.04-arm + target: aarch64 + arch: arm64 + steps: + - uses: actions/checkout@v7 + with: + ref: ${{ github.sha }} + persist-credentials: false + - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + - uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ github.token }} + - name: Build and push native platform + uses: docker/bake-action@59cb1203cd42bcefd40a1b6d73b589e48c86040e # v7.5.0 + with: + source: . + files: docker-bake.ci-image-base.hcl + targets: ${{ matrix.target }} + push: true + set: | + ${{ matrix.target }}.tags=ghcr.io/wasmedge/devcontainer:${{ needs.prepare.outputs.tag }}-stage-${{ matrix.arch }} + ${{ matrix.target }}.labels.org.opencontainers.image.source=https://github.com/WasmEdge/devcontainer + ${{ matrix.target }}.labels.org.opencontainers.image.revision=${{ github.sha }} + + publish: + needs: + - prepare + - build + if: needs.build.result == 'success' + runs-on: ubuntu-latest + permissions: + contents: read + packages: write + outputs: + image_ref: ${{ steps.publish.outputs.image_ref }} + steps: + - uses: actions/checkout@v7 + with: + ref: ${{ github.sha }} + persist-credentials: false + - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + - uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ github.token }} + - name: Assemble and verify multi-platform index + id: publish + env: + TAG: ${{ needs.prepare.outputs.tag }} + run: | + image=ghcr.io/wasmedge/devcontainer + docker buildx imagetools create --tag "$image:$TAG" \ + "$image:$TAG-stage-amd64" "$image:$TAG-stage-arm64" + docker buildx imagetools inspect --raw "$image:$TAG" > index.json + python3 .github/scripts/devcontainer/publication.py verify-index --index index.json + digest=$(docker buildx imagetools inspect "$image:$TAG" \ + --format '{{json .Manifest.Digest}}' | tr -d '"') + python3 .github/scripts/devcontainer/publication.py validate-digest --digest "$digest" + if [ '${{ inputs.candidate }}' != true ]; then + docker buildx imagetools create --tag "$image:latest" "$image@$digest" + fi + echo "image_ref=$image@$digest" >> "$GITHUB_OUTPUT" diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 407fb47..c4994cc 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -10,6 +10,7 @@ on: - main paths: - '.github/workflows/docker.yml' + - '.github/workflows/devcontainer.yml' - 'Dockerfile.*' - 'docker-bake.*.hcl' - 'SHA256SUM.*' @@ -29,8 +30,6 @@ on: - 'scripts/opencvmini/**' - 'scripts/wasi-crypto/**' - 'scripts/wasi-nn/**' - schedule: - - cron: "0 0 */7 * *" permissions: contents: read @@ -54,9 +53,7 @@ jobs: run: | DOCKER_IMAGE=wasmedge/wasmedge VERSION=noop - if [ "${{ github.event_name }}" = "schedule" ]; then - VERSION=nightly - elif [[ $GITHUB_REF == refs/tags/* ]]; then + if [[ $GITHUB_REF == refs/tags/* ]]; then VERSION=${GITHUB_REF#refs/tags/} elif [[ $GITHUB_REF == refs/heads/* ]]; then VERSION=$(printf '%s\n' "${GITHUB_REF#refs/heads/}" | sed -r 's#/+#-#g') @@ -98,6 +95,7 @@ jobs: filters: | ci-image-base: - '.github/workflows/docker.yml' + - '.github/workflows/devcontainer.yml' - 'docker-bake.ci-image-base.hcl' - 'Dockerfile.ci-image-base' alpine-base: @@ -153,11 +151,23 @@ jobs: files: docker-bake.ci-image-base.hcl push: ${{ github.event_name != 'pull_request' }} + devcontainer-ghcr: + needs: [prep, paths-filter] + name: devcontainer GHCR publication + permissions: + contents: read + packages: write + # Fork-origin PR package permissions remain a rollout decision; keep this + # path free of fork-specific handling until that behavior is verified. + uses: ./.github/workflows/devcontainer.yml + with: + candidate: ${{ github.event_name == 'pull_request' && needs.paths-filter.outputs.ci-image-base == 'true' }} + build-alpine-base-images: needs: - prep - paths-filter - # Only run if files changed or if it's a scheduled/merge build + # Only run if files changed or if it's a merge build if: ${{ needs.paths-filter.outputs.alpine-base == 'true' }} name: Alpine Base (3.23) @@ -199,7 +209,8 @@ jobs: - prep - paths-filter - bake-base-images - if: ${{ needs.paths-filter.outputs.ubuntu == 'true' }} + - devcontainer-ghcr + if: ${{ !cancelled() && needs.prep.result == 'success' && needs.paths-filter.result == 'success' && needs.paths-filter.outputs.ubuntu == 'true' && (needs.paths-filter.outputs.ci-image-base != 'true' || needs.devcontainer-ghcr.result == 'success' || needs.devcontainer-ghcr.result == 'skipped') }} strategy: fail-fast: false @@ -210,8 +221,11 @@ jobs: name: Ubuntu runs-on: ubuntu-latest + permissions: + contents: read + packages: read container: - image: wasmedge/wasmedge:ci-image-base + image: ${{ needs.devcontainer-ghcr.result == 'success' && needs.devcontainer-ghcr.outputs.image_ref || 'wasmedge/wasmedge:ci-image-base' }} steps: - name: Harden the runner (Audit all outbound calls) @@ -249,7 +263,8 @@ jobs: - prep - paths-filter - bake-base-images - if: ${{ needs.paths-filter.outputs.manylinux == 'true' }} + - devcontainer-ghcr + if: ${{ !cancelled() && needs.prep.result == 'success' && needs.paths-filter.result == 'success' && needs.paths-filter.outputs.manylinux == 'true' && (needs.paths-filter.outputs.ci-image-base != 'true' || needs.devcontainer-ghcr.result == 'success' || needs.devcontainer-ghcr.result == 'skipped') }} strategy: fail-fast: false @@ -268,8 +283,11 @@ jobs: name: ${{ matrix.name }} runs-on: ${{ matrix.host_runner }} + permissions: + contents: read + packages: read container: - image: ${{ matrix.host_container }} + image: ${{ needs.devcontainer-ghcr.result == 'success' && needs.devcontainer-ghcr.outputs.image_ref || matrix.host_container }} steps: - name: Harden the runner (Audit all outbound calls) diff --git a/README.md b/README.md index 4db1b3f..4fbd93c 100644 --- a/README.md +++ b/README.md @@ -19,4 +19,4 @@ are retained, but CI does not build them or OpenWrt images. | `SHA256SUM.*` | Checksums used by the manylinux image definitions. | | `build-manylinux.sh` | Legacy manylinux image build helper. | | `scripts/` | Dockerfile-consumed dependency installers, build helpers, test data helpers, and patches, grouped by dependency family. | -| `.github/workflows/` | Consolidated image build/publication workflow (`docker.yml`) and repository lint workflow (`super-linter.yml`). | +| `.github/workflows/` | Image orchestration (`docker.yml`) and repository lint workflow (`super-linter.yml`). |