diff --git a/.github/workflows/__test-action-docker-promote-images.yml b/.github/workflows/__test-action-docker-promote-images.yml index 640486ac..f5da47b8 100644 --- a/.github/workflows/__test-action-docker-promote-images.yml +++ b/.github/workflows/__test-action-docker-promote-images.yml @@ -22,3 +22,44 @@ jobs: lint: "" code-ql: '{"languages":"typescript","config-file":".github/codeql/config.yml"}' test: '{"comment":false,"report-group":"test-action-docker-promote-images"}' + + registry-copy: + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: read + services: + source: + image: registry:3.1.2@sha256:82f6ff4a7f982960c8aa51617fea3aabc485df6e55cce80d22deb1de36f1bc3c + ports: + - 5000/tcp + destination: + image: registry:3.1.2@sha256:82f6ff4a7f982960c8aa51617fea3aabc485df6e55cce80d22deb1de36f1bc3c + ports: + - 5000/tcp + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + with: + driver: docker + - uses: regclient/actions/regctl-installer@dd58ad94f76adb73d8ac1bf75ed25f01545d5b32 # v0.2.0 + with: + # renovate: datasource=github-releases depName=regclient/regclient + release: v0.11.7 + - name: Verify cross-registry manifests and attachments + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + SOURCE_REGISTRY: localhost:${{ job.services.source.ports['5000'] }} + DESTINATION_REGISTRY: localhost:${{ job.services.destination.ports['5000'] }} + REGCTL_CONFIG: ${{ runner.temp }}/regctl-copy-fixture.json + with: + script: | + const { pathToFileURL } = require('node:url'); + const { prepare, copyAndVerify } = await import(pathToFileURL(`${process.env.GITHUB_WORKSPACE}/tests/docker-promote-images/registry-fixture.mjs`)); + for (const registry of [process.env.SOURCE_REGISTRY, process.env.DESTINATION_REGISTRY]) { + await exec.exec('regctl', ['registry', 'set', registry, '--tls', 'disabled']); + } + const images = await prepare(exec, process.env.RUNNER_TEMP, process.env.SOURCE_REGISTRY, process.env.DESTINATION_REGISTRY); + await copyAndVerify(exec, images); diff --git a/.github/workflows/__test-workflow-docker-build-images-building.yml b/.github/workflows/__test-workflow-docker-build-images-building.yml index 74ec28b7..8c6701af 100644 --- a/.github/workflows/__test-workflow-docker-build-images-building.yml +++ b/.github/workflows/__test-workflow-docker-build-images-building.yml @@ -279,6 +279,15 @@ jobs: pull-requests: read with: job-results: ${{ toJSON(needs) }} + additional-destinations: | + { + "test-candidate-${{ github.run_id }}-${{ github.run_attempt }}-single": [ + "ghcr.io/${{ github.repository }}/test-promoted-${{ github.run_id }}-${{ github.run_attempt }}-single:1.2.3" + ], + "test-candidate-${{ github.run_id }}-${{ github.run_attempt }}-multi": [ + "ghcr.io/${{ github.repository }}/test-promoted-${{ github.run_id }}-${{ github.run_attempt }}-multi:1.2.3" + ] + } secrets: oci-registry-password: ${{ secrets.GITHUB_TOKEN }} @@ -305,12 +314,15 @@ jobs: env: CANDIDATES: ${{ needs.act-candidates.outputs.built-images }} PROMOTED: ${{ needs.promote-candidates.outputs.built-images }} + ADDITIONAL: ${{ needs.promote-candidates.outputs.additional-images }} GH_TOKEN: ${{ github.token }} with: script: | const assert = require('node:assert/strict'); const candidates = JSON.parse(process.env.CANDIDATES); const promoted = JSON.parse(process.env.PROMOTED); + const additional = JSON.parse(process.env.ADDITIONAL); + assert.deepEqual(Object.keys(additional).sort(), Object.keys(candidates).sort()); assert.deepEqual(Object.keys(promoted).sort(), Object.keys(candidates).sort()); for (const [name, candidate] of Object.entries(candidates)) { const image = promoted[name]; @@ -324,9 +336,15 @@ jobs: const before = await exec.getExecOutput('docker', ['buildx', 'imagetools', 'inspect', '--raw', `${reference}@${candidate.digest}`]); const after = await exec.getExecOutput('docker', ['buildx', 'imagetools', 'inspect', '--raw', `${reference}:1.2.3`]); assert.equal(after.stdout, before.stdout, 'Promotion must retain exact manifest bytes'); - await exec.exec('gh', ['attestation', 'verify', `oci://${image.images[0]}`, '--repo', process.env.GITHUB_REPOSITORY]); + const extra = `${reference.replace('/test-candidate-', '/test-promoted-')}:1.2.3`; + assert.deepEqual(additional[name], [`${extra}@${candidate.digest}`]); + const copied = await exec.getExecOutput('docker', ['buildx', 'imagetools', 'inspect', '--raw', extra]); + assert.equal(copied.stdout, before.stdout, 'Cross-repository copies must retain exact manifest bytes'); + for (const reference of [...image.images, ...additional[name]]) { + await exec.exec('gh', ['attestation', 'verify', `oci://${reference}`, '--repo', process.env.GITHUB_REPOSITORY]); + } } - core.setOutput('references', JSON.stringify(Object.values(promoted).flatMap(image => image.images))); + core.setOutput('references', JSON.stringify([...Object.values(promoted).flatMap(image => image.images), ...Object.values(additional).flat()])); - name: Verify retained image signatures uses: $/actions/docker/verify-images @@ -347,6 +365,15 @@ jobs: pull-requests: read with: job-results: ${{ toJSON(needs) }} + additional-destinations: | + { + "test-candidate-${{ github.run_id }}-${{ github.run_attempt }}-single": [ + "ghcr.io/${{ github.repository }}/test-promoted-${{ github.run_id }}-${{ github.run_attempt }}-single:1.2.3" + ], + "test-candidate-${{ github.run_id }}-${{ github.run_attempt }}-multi": [ + "ghcr.io/${{ github.repository }}/test-promoted-${{ github.run_id }}-${{ github.run_attempt }}-multi:1.2.3" + ] + } build-workflow: ${{ github.repository }}/.github/workflows/docker-build-images.yml secrets: oci-registry-password: ${{ secrets.GITHUB_TOKEN }} @@ -362,13 +389,21 @@ jobs: env: FIRST: ${{ needs.promote-candidates.outputs.built-images }} SECOND: ${{ needs.repeat-promotion.outputs.built-images }} + FIRST_ADDITIONAL: ${{ needs.promote-candidates.outputs.additional-images }} + SECOND_ADDITIONAL: ${{ needs.repeat-promotion.outputs.additional-images }} with: script: | const assert = require('node:assert/strict'); const images = JSON.parse(process.env.FIRST); assert.deepEqual(images, JSON.parse(process.env.SECOND)); + const additional = JSON.parse(process.env.FIRST_ADDITIONAL); + assert.deepEqual(additional, JSON.parse(process.env.SECOND_ADDITIONAL)); const destinations = Object.fromEntries(Object.values(images).flatMap(image => image.tags.map(tag => [`${image.registry}/${image.repository}:${tag}`, image.digest]))); + for (const reference of Object.values(additional).flat()) { + const [destination, digest] = reference.split('@'); + destinations[destination] = digest; + } const records = await github.paginate(github.rest.repos.listDeployments, { ...context.repo, environment: 'ci-image-promotion', task: 'ci-image-promotion', per_page: 100, }); @@ -434,8 +469,9 @@ jobs: - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 with: script: | - for (const suffix of ['single', 'multi', 'failed']) { - const name = `test-candidate-${context.runId}-${process.env.GITHUB_RUN_ATTEMPT}-${suffix}`; + for (const suffix of ['candidate-single', 'candidate-multi', 'candidate-failed', 'promoted-single', 'promoted-multi']) { + const [kind, platform] = suffix.split('-'); + const name = `test-${kind}-${context.runId}-${process.env.GITHUB_RUN_ATTEMPT}-${platform}`; try { await github.rest.packages.deletePackageForOrg({ package_type: 'container', package_name: `${context.repo.repo}/${name}`, org: context.repo.owner, @@ -448,12 +484,14 @@ jobs: const records = await github.paginate(github.rest.repos.listDeployments, { ...context.repo, environment: 'ci-image-promotion', task: 'ci-image-promotion', per_page: 100, }); - const prefix = `ghcr.io/${process.env.GITHUB_REPOSITORY.toLowerCase()}/test-candidate-${context.runId}-${process.env.GITHUB_RUN_ATTEMPT}-`; + const repository = process.env.GITHUB_REPOSITORY.toLowerCase(); + const run = `${context.runId}-${process.env.GITHUB_RUN_ATTEMPT}`; + const prefixes = ['candidate', 'promoted'].map(kind => `ghcr.io/${repository}/test-${kind}-${run}-`); for (const record of records) { const payload = record.payload; if (payload?.runId !== String(context.runId) || payload.attempt !== process.env.GITHUB_RUN_ATTEMPT) continue; const destinations = Object.keys(payload.destinations || {}); - if (!destinations.length || !destinations.every(destination => destination.startsWith(prefix))) continue; + if (!destinations.length || !destinations.every(destination => prefixes.some(prefix => destination.startsWith(prefix)))) continue; await github.rest.repos.createDeploymentStatus({ ...context.repo, deployment_id: record.id, state: 'inactive', auto_inactive: false }); await github.rest.repos.deleteDeployment({ ...context.repo, deployment_id: record.id }); } diff --git a/.github/workflows/docker-promote-images.md b/.github/workflows/docker-promote-images.md index d1e48664..bfa07e54 100644 --- a/.github/workflows/docker-promote-images.md +++ b/.github/workflows/docker-promote-images.md @@ -38,7 +38,7 @@ validate: promote: if: always() needs: [candidates, validate, lint] - uses: hoverkraft-tech/ci-github-container/.github/workflows/docker-promote-images.yml@7442ea53022a6365d3be7259634aaaf095bf5d3f + uses: hoverkraft-tech/ci-github-container/.github/workflows/docker-promote-images.yml@a5dc1ea7c1f4c2dffc3267c5be7304d01284f2ec # 4.2.1 permissions: actions: read attestations: read @@ -56,7 +56,25 @@ Pin the reusable workflow to a reviewed release SHA. The example assumes a `candidate: true` build and an existing application-specific validation script. Signatures and provenance from Docker build images are required. Promotion checks the candidate tag/digest, exact manifest bytes, source ref and current run/attempt. -Only same-repository tag updates within the configured registry/prefix are allowed. +Candidate metadata can only request same-repository tags in the authorized prefix. +To publish the validated digest elsewhere, explicitly configure `additional-destinations`. + +## Additional registries and repositories + +`additional-destinations` maps candidate image names to fully qualified tagged refs: +`{"app":["docker.io/example/app:1.2.3"]}`. Original destinations remain unchanged. +Each different registry requires its own credentials through the optional secret +`destination-credentials`: `{"docker.io":{"username":"...","password":"..."}}`. +Pass this JSON from a repository secret or construct it using `toJSON` for each +credential. Another repository on the source registry reuses its existing login. + +Copies preserve the digest, platforms, OCI referrers and legacy signature tags. +The destination signature and original build provenance are verified before its +consumer tag is written. This requires registry support for the copied metadata. +`regctl` is installed only when copying to another repository is required. +`built-images` retains the original repository metadata; `additional-images` maps +image names to arrays of additional `registry/repository:tag@sha256:...` references. +Both outputs are withheld on failure. No rebuild or new signature is performed. The trusted builder defaults to `docker-build-images.yml` in the promotion action's repository, resolved through `github.action_repository`. Forks therefore use their @@ -68,7 +86,7 @@ The builder must preserve the candidate metadata and current-run provenance cont ## Publication and recovery The workflow serializes promotions per calling repository and records validated -claims through GitHub deployments in `ci-image-promotion`. No app credentials or +claims for all original and additional destinations through GitHub deployments in `ci-image-promotion`. No app credentials or external database are required. All writers of the destinations must use this workflow. Retain these journal records while destinations may be reused; deleting them removes supersession protection. A newer claim blocks older runs even when @@ -81,7 +99,8 @@ new attempt; rerunning only promotion with old outputs fails. Cancellation check cannot revoke a registry request already in flight. No candidate, digest, signature or attestation is deleted. Use registry-specific -retention that preserves consumer-tagged content. See [ADR 0006](../../docs/adr/0006-promote-validated-image-digests.md). +retention that preserves consumer-tagged content. See [ADR 0006](../../docs/adr/0006-promote-validated-image-digests.md) +and [ADR 0013](../../docs/adr/0013-promote-to-additional-destinations.md). ### Permissions @@ -99,23 +118,25 @@ retention that preserves consumer-tagged content. See [ADR 0006](../../docs/adr/ ### Workflow Call Inputs -| **Input** | **Description** | **Required** | **Type** | **Default** | -| --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------ | ---------- | ------------------- | -| **`job-results`** | Direct dependency results from toJSON(needs), including candidate and validation outputs. | **true** | **string** | - | -| **`build-workflow`** | Trusted builder as owner/repository/.github/workflows/file.yml, without a ref. Defaults to docker-build-images.yml in the promotion action's repository. Used for both signatures and provenance; override when the builder lives elsewhere. | **false** | **string** | - | -| **`oci-registry`** | Authorized publication registry hostname. | **false** | **string** | `ghcr.io` | -| **`repository`** | Authorized image repository prefix; defaults to the calling repository. | **false** | **string** | - | -| **`oci-registry-username`** | Registry username; defaults to the calling repository owner. | **false** | **string** | - | -| **`runs-on`** | JSON array of runner labels. Requires Docker and GitHub CLI. | **false** | **string** | `["ubuntu-latest"]` | +| **Input** | **Description** | **Required** | **Type** | **Default** | +| ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------ | ---------- | ------------------- | +| **`job-results`** | Direct dependency results from toJSON(needs), including candidate and validation outputs. | **true** | **string** | - | +| **`build-workflow`** | Trusted builder as owner/repository/.github/workflows/file.yml, without a ref. Defaults to docker-build-images.yml in the promotion action's repository. Used for both signatures and provenance; override when the builder lives elsewhere. | **false** | **string** | - | +| **`additional-destinations`** | JSON object mapping validated image names to additional fully qualified tagged destinations. | **false** | **string** | `{}` | +| **`oci-registry`** | Authorized publication registry hostname. | **false** | **string** | `ghcr.io` | +| **`repository`** | Authorized image repository prefix; defaults to the calling repository. | **false** | **string** | - | +| **`oci-registry-username`** | Registry username; defaults to the calling repository owner. | **false** | **string** | - | +| **`runs-on`** | JSON array of runner labels. Requires Docker and GitHub CLI. | **false** | **string** | `["ubuntu-latest"]` | ## Outputs -| **Output** | **Description** | -| ------------------ | ----------------------------------------------------------------------------------- | -| **`built-images`** | Image metadata with verified consumer tags and unchanged digests; empty on failure. | +| **Output** | **Description** | +| ----------------------- | --------------------------------------------------------------------------------------------------- | +| **`built-images`** | Image metadata with verified consumer tags and unchanged digests; empty on failure. | +| **`additional-images`** | JSON object mapping image names to verified additional tag-and-digest references; empty on failure. | @@ -147,7 +168,7 @@ on: permissions: {} jobs: docker-promote-images: - uses: hoverkraft-tech/ci-github-container/.github/workflows/docker-promote-images.yml@7442ea53022a6365d3be7259634aaaf095bf5d3f # 4.0.0 + uses: hoverkraft-tech/ci-github-container/.github/workflows/docker-promote-images.yml@2518a5da86e89c9ffc661e5b8b7235eca6b905ce # feat/docker-mirror-image permissions: actions: read attestations: read @@ -159,6 +180,9 @@ jobs: # Registry password or token with write access to the authorized image repositories. # This input is required. oci-registry-password: "" + + # JSON object mapping each additional registry hostname to its username and password. + destination-credentials: "" with: # Direct dependency results from toJSON(needs), including candidate and validation outputs. # This input is required. @@ -167,6 +191,10 @@ jobs: # Trusted builder as owner/repository/.github/workflows/file.yml, without a ref. Defaults to docker-build-images.yml in the promotion action's repository. Used for both signatures and provenance; override when the builder lives elsewhere. build-workflow: "" + # JSON object mapping validated image names to additional fully qualified tagged destinations. + # Default: `{}` + additional-destinations: "{}" + # Authorized publication registry hostname. # Default: `ghcr.io` oci-registry: ghcr.io diff --git a/.github/workflows/docker-promote-images.yml b/.github/workflows/docker-promote-images.yml index de971574..79180ddc 100644 --- a/.github/workflows/docker-promote-images.yml +++ b/.github/workflows/docker-promote-images.yml @@ -23,7 +23,7 @@ # promote: # if: always() # needs: [candidates, validate, lint] -# uses: hoverkraft-tech/ci-github-container/.github/workflows/docker-promote-images.yml@7442ea53022a6365d3be7259634aaaf095bf5d3f +# uses: hoverkraft-tech/ci-github-container/.github/workflows/docker-promote-images.yml@a5dc1ea7c1f4c2dffc3267c5be7304d01284f2ec # 4.2.1 # permissions: # actions: read # attestations: read @@ -41,7 +41,25 @@ # `candidate: true` build and an existing application-specific validation script. # Signatures and provenance from Docker build images are required. Promotion checks # the candidate tag/digest, exact manifest bytes, source ref and current run/attempt. -# Only same-repository tag updates within the configured registry/prefix are allowed. +# Candidate metadata can only request same-repository tags in the authorized prefix. +# To publish the validated digest elsewhere, explicitly configure `additional-destinations`. +# +# ## Additional registries and repositories +# +# `additional-destinations` maps candidate image names to fully qualified tagged refs: +# `{"app":["docker.io/example/app:1.2.3"]}`. Original destinations remain unchanged. +# Each different registry requires its own credentials through the optional secret +# `destination-credentials`: `{"docker.io":{"username":"...","password":"..."}}`. +# Pass this JSON from a repository secret or construct it using `toJSON` for each +# credential. Another repository on the source registry reuses its existing login. +# +# Copies preserve the digest, platforms, OCI referrers and legacy signature tags. +# The destination signature and original build provenance are verified before its +# consumer tag is written. This requires registry support for the copied metadata. +# `regctl` is installed only when copying to another repository is required. +# `built-images` retains the original repository metadata; `additional-images` maps +# image names to arrays of additional `registry/repository:tag@sha256:...` references. +# Both outputs are withheld on failure. No rebuild or new signature is performed. # # The trusted builder defaults to `docker-build-images.yml` in the promotion action's # repository, resolved through `github.action_repository`. Forks therefore use their @@ -53,7 +71,7 @@ # ## Publication and recovery # # The workflow serializes promotions per calling repository and records validated -# claims through GitHub deployments in `ci-image-promotion`. No app credentials or +# claims for all original and additional destinations through GitHub deployments in `ci-image-promotion`. No app credentials or # external database are required. All writers of the destinations must use this # workflow. Retain these journal records while destinations may be reused; deleting # them removes supersession protection. A newer claim blocks older runs even when @@ -66,7 +84,8 @@ # cannot revoke a registry request already in flight. # # No candidate, digest, signature or attestation is deleted. Use registry-specific -# retention that preserves consumer-tagged content. See [ADR 0006](../../docs/adr/0006-promote-validated-image-digests.md). +# retention that preserves consumer-tagged content. See [ADR 0006](../../docs/adr/0006-promote-validated-image-digests.md) +# and [ADR 0013](../../docs/adr/0013-promote-to-additional-destinations.md). --- name: Docker promote images on: # yamllint disable-line rule:truthy @@ -83,6 +102,10 @@ on: # yamllint disable-line rule:truthy Used for both signatures and provenance; override when the builder lives elsewhere. type: string default: "" + additional-destinations: + description: JSON object mapping validated image names to additional fully qualified tagged destinations. + type: string + default: "{}" oci-registry: description: Authorized publication registry hostname. type: string @@ -103,10 +126,16 @@ on: # yamllint disable-line rule:truthy oci-registry-password: description: Registry password or token with write access to the authorized image repositories. required: true + destination-credentials: + description: JSON object mapping each additional registry hostname to its username and password. + required: false outputs: built-images: description: Image metadata with verified consumer tags and unchanged digests; empty on failure. value: ${{ jobs.promote.outputs.built-images }} + additional-images: + description: JSON object mapping image names to verified additional tag-and-digest references; empty on failure. + value: ${{ jobs.promote.outputs.additional-images }} permissions: {} jobs: promote: @@ -126,12 +155,15 @@ jobs: pull-requests: read outputs: built-images: ${{ job.status == 'success' && steps.promote.outputs.built-images || '' }} + additional-images: ${{ job.status == 'success' && steps.promote.outputs.additional-images || '' }} steps: - id: promote uses: $/actions/docker/promote-images with: job-results: ${{ inputs.job-results }} build-workflow: ${{ inputs.build-workflow }} + additional-destinations: ${{ inputs.additional-destinations }} + destination-credentials: ${{ secrets.destination-credentials || '{}' }} # zizmor: ignore[secrets-outside-env] oci-registry: ${{ inputs.oci-registry }} repository: ${{ inputs.repository || github.repository }} oci-registry-username: ${{ inputs.oci-registry-username || github.repository_owner }} diff --git a/actions/docker/promote-images/README.md b/actions/docker/promote-images/README.md index 372b7089..99afbc8e 100644 --- a/actions/docker/promote-images/README.md +++ b/actions/docker/promote-images/README.md @@ -26,23 +26,26 @@ or require OIDC write permission. ## Inputs -| **Input** | **Description** | **Required** | **Default** | -| --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------ | -------------------------------- | -| **`job-results`** | Direct dependency results, including built-images and validated-images outputs. | **true** | - | -| **`build-workflow`** | Trusted builder as owner/repository/.github/workflows/file.yml, without a ref. Defaults to docker-build-images.yml in this action's repository. Used for both signatures and provenance; override when the builder lives elsewhere. | **false** | - | -| **`oci-registry`** | Authorized publication registry hostname. | **false** | `ghcr.io` | -| **`repository`** | Authorized image repository prefix. | **false** | `${{ github.repository }}` | -| **`oci-registry-username`** | Registry username. | **false** | `${{ github.repository_owner }}` | -| **`oci-registry-password`** | Registry password or token. | **true** | - | +| **Input** | **Description** | **Required** | **Default** | +| ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------ | -------------------------------- | +| **`job-results`** | Direct dependency results, including built-images and validated-images outputs. | **true** | - | +| **`build-workflow`** | Trusted builder as owner/repository/.github/workflows/file.yml, without a ref. Defaults to docker-build-images.yml in this action's repository. Used for both signatures and provenance; override when the builder lives elsewhere. | **false** | - | +| **`additional-destinations`** | JSON object mapping validated image names to additional fully qualified tagged destinations, for example {"app":["docker.io/example/app:1.2.3"]}. Original candidate destinations are always retained. | **false** | `{}` | +| **`destination-credentials`** | JSON object mapping each additional registry hostname to its username and password. Required for destinations outside oci-registry; credentials are never shared between hosts. | **false** | `{}` | +| **`oci-registry`** | Authorized publication registry hostname. | **false** | `ghcr.io` | +| **`repository`** | Authorized image repository prefix. | **false** | `${{ github.repository }}` | +| **`oci-registry-username`** | Registry username. | **false** | `${{ github.repository_owner }}` | +| **`oci-registry-password`** | Registry password or token. | **true** | - | ## Outputs -| **Output** | **Description** | -| ------------------ | ----------------------------------------------------------------------------------- | -| **`built-images`** | Image metadata with verified consumer tags and unchanged digests; empty on failure. | +| **Output** | **Description** | +| ----------------------- | --------------------------------------------------------------------------------------------------- | +| **`built-images`** | Image metadata with verified consumer tags and unchanged digests; empty on failure. | +| **`additional-images`** | JSON object mapping image names to verified additional tag-and-digest references; empty on failure. | @@ -67,7 +70,7 @@ This documentation was automatically generated by [CI Dokumentor](https://github ## Usage ```yaml -- uses: hoverkraft-tech/ci-github-container/actions/docker/promote-images@3feb56e45f82273a7eded46ac3b9364c08337cee # 3.0.0 +- uses: hoverkraft-tech/ci-github-container/actions/docker/promote-images@2518a5da86e89c9ffc661e5b8b7235eca6b905ce # feat/docker-mirror-image with: # Direct dependency results, including built-images and validated-images outputs. # This input is required. @@ -76,6 +79,14 @@ This documentation was automatically generated by [CI Dokumentor](https://github # Trusted builder as owner/repository/.github/workflows/file.yml, without a ref. Defaults to docker-build-images.yml in this action's repository. Used for both signatures and provenance; override when the builder lives elsewhere. build-workflow: "" + # JSON object mapping validated image names to additional fully qualified tagged destinations, for example {"app":["docker.io/example/app:1.2.3"]}. Original candidate destinations are always retained. + # Default: `{}` + additional-destinations: "{}" + + # JSON object mapping each additional registry hostname to its username and password. Required for destinations outside oci-registry; credentials are never shared between hosts. + # Default: `{}` + destination-credentials: "{}" + # Authorized publication registry hostname. # Default: `ghcr.io` oci-registry: ghcr.io diff --git a/actions/docker/promote-images/action.yml b/actions/docker/promote-images/action.yml index 77b1cae6..48eeb65c 100644 --- a/actions/docker/promote-images/action.yml +++ b/actions/docker/promote-images/action.yml @@ -22,6 +22,17 @@ inputs: Defaults to docker-build-images.yml in this action's repository. Used for both signatures and provenance; override when the builder lives elsewhere. default: "" + additional-destinations: + description: >- + JSON object mapping validated image names to additional fully qualified tagged + destinations, for example {"app":["docker.io/example/app:1.2.3"]}. + Original candidate destinations are always retained. + default: "{}" + destination-credentials: + description: >- + JSON object mapping each additional registry hostname to its username and password. + Required for destinations outside oci-registry; credentials are never shared between hosts. + default: "{}" oci-registry: description: Authorized publication registry hostname. default: ghcr.io @@ -38,6 +49,9 @@ outputs: built-images: description: Image metadata with verified consumer tags and unchanged digests; empty on failure. value: ${{ steps.promote.outputs.built-images }} + additional-images: + description: JSON object mapping image names to verified additional tag-and-digest references; empty on failure. + value: ${{ steps.promote.outputs.additional-images }} runs: using: composite steps: @@ -50,6 +64,10 @@ runs: REPOSITORY: ${{ inputs.repository }} BUILD_WORKFLOW: ${{ inputs.build-workflow }} ACTION_REPOSITORY: ${{ github.action_repository }} + ADDITIONAL_DESTINATIONS: ${{ inputs.additional-destinations }} + DESTINATION_CREDENTIALS: ${{ inputs.destination-credentials }} + REGISTRY_USERNAME: ${{ inputs.oci-registry-username }} + REGISTRY_PASSWORD: ${{ inputs.oci-registry-password }} with: script: | const { pathToFileURL } = require('node:url'); @@ -63,14 +81,27 @@ runs: context, runId: process.env.GITHUB_RUN_ID, attempt: process.env.GITHUB_RUN_ATTEMPT, repositoryId: process.env.GITHUB_REPOSITORY_ID, }); + const { PromotionDestinations } = await import(pathToFileURL(`${process.env.ACTION_PATH}/src/destinations.js`)); + const destinations = new PromotionDestinations(images, process.env.ADDITIONAL_DESTINATIONS); + const authentication = destinations.authentication({ + registry: process.env.REGISTRY, + username: process.env.REGISTRY_USERNAME, + password: process.env.REGISTRY_PASSWORD, + credentials: process.env.DESTINATION_CREDENTIALS, + }); + for (const password of Object.values(authentication.passwords)) core.setSecret(password); + core.setOutput('registries', JSON.stringify(authentication.registries)); + core.setOutput('usernames', JSON.stringify(authentication.usernames)); + core.setOutput('passwords', JSON.stringify(authentication.passwords)); + core.setOutput('requires-copy', destinations.requiresCopy); core.setOutput('images', JSON.stringify(images)); core.setOutput('references', JSON.stringify(Object.values(images).flatMap(image => image.images))); - uses: $/actions/docker/setup with: - oci-registry: ${{ inputs.oci-registry }} - oci-registry-username: ${{ inputs.oci-registry-username }} - oci-registry-password: ${{ inputs.oci-registry-password }} + oci-registry: ${{ steps.validate.outputs.registries }} + oci-registry-username: ${{ steps.validate.outputs.usernames }} + oci-registry-password: ${{ steps.validate.outputs.passwords }} setup-docker: false # Promotion only uses registry commands; no BuildKit container is needed. buildx-driver: docker @@ -81,12 +112,19 @@ runs: images: ${{ steps.validate.outputs.references }} certificate-identity-regexp: ${{ steps.validate.outputs.builder-identity-regexp }} + - if: steps.validate.outputs.requires-copy == 'true' + uses: regclient/actions/regctl-installer@dd58ad94f76adb73d8ac1bf75ed25f01545d5b32 # v0.2.0 + with: + # renovate: datasource=github-releases depName=regclient/regclient + release: v0.11.7 + - id: promote uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: ACTION_PATH: ${{ github.action_path }} IMAGES: ${{ steps.validate.outputs.images }} VERIFIED_IMAGES: ${{ steps.verify.outputs.verified-images }} + ADDITIONAL_DESTINATIONS: ${{ inputs.additional-destinations }} BUILD_WORKFLOW: ${{ steps.validate.outputs.build-workflow }} GH_TOKEN: ${{ github.token }} with: @@ -98,6 +136,8 @@ runs: runId: process.env.GITHUB_RUN_ID, attempt: process.env.GITHUB_RUN_ATTEMPT, verifiedImages: JSON.parse(process.env.VERIFIED_IMAGES), buildWorkflow: process.env.BUILD_WORKFLOW, + additionalDestinations: process.env.ADDITIONAL_DESTINATIONS, }); const images = await promotion.promote(JSON.parse(process.env.IMAGES)); core.setOutput('built-images', JSON.stringify(images)); + core.setOutput('additional-images', JSON.stringify(promotion.additionalImages)); diff --git a/actions/docker/promote-images/src/destinations.js b/actions/docker/promote-images/src/destinations.js new file mode 100644 index 00000000..6497bbd4 --- /dev/null +++ b/actions/docker/promote-images/src/destinations.js @@ -0,0 +1,126 @@ +import assert from "node:assert/strict"; +import { promotionContract } from "./contract.js"; + +function parseObject(raw, name) { + let value; + try { + value = JSON.parse(raw); + } catch { + throw new Error(`${name} must be a JSON object`); + } + assert( + value && typeof value === "object" && !Array.isArray(value), + `${name} must be a JSON object`, + ); + return value; +} + +class PromotionDestinations { + constructor(images, raw = "{}") { + this.images = images; + this.additional = parseObject(raw, "additional-destinations"); + this.claim = promotionContract.destinations(images); + this.registries = new Set(); + this.requiresCopy = false; + const pattern = + /^(?[a-z0-9]+(?:[.-][a-z0-9]+)*(?::[0-9]+)?)\/(?[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*(?:\/[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*)*):(?[\w][\w.-]{0,127})$/; + for (const [name, destinations] of Object.entries(this.additional)) { + assert( + Object.hasOwn(images, name), + "Additional destinations must identify a validated image", + ); + assert( + Array.isArray(destinations) && destinations.length > 0, + "Each additional image destination list must be nonempty", + ); + const image = images[name]; + for (const destination of destinations) { + assert( + typeof destination === "string" && destination === destination.trim(), + "Destination references must be strings without surrounding whitespace", + ); + const match = destination.match(pattern); + assert( + match, + "Additional destinations require a fully qualified tagged image", + ); + const { registry, repository, tag } = match.groups; + assert( + registry.includes(".") || + registry.includes(":") || + registry === "localhost", + "Additional destinations require an explicit registry", + ); + assert( + !tag.startsWith("candidate-"), + "Additional destinations cannot overwrite candidate tags", + ); + assert( + !Object.hasOwn(this.claim, destination), + "Duplicate publication destination", + ); + this.claim[destination] = image.digest; + if (registry !== image.registry) this.registries.add(registry); + if ( + `${registry}/${repository}` !== + `${image.registry}/${image.repository}` + ) + this.requiresCopy = true; + } + } + } + + authentication({ registry, username, password, credentials = "{}" }) { + const extra = parseObject(credentials, "destination-credentials"); + for (const name of Object.keys(extra)) + assert( + this.registries.has(name), + "Credentials must identify a configured destination registry", + ); + const registries = { push: registry }; + const usernames = { push: username }; + const passwords = { push: password }; + for (const name of this.registries) { + const credential = extra[name]; + assert( + credential && + typeof credential === "object" && + !Array.isArray(credential), + "Explicit credentials are required for every additional registry", + ); + assert( + Object.keys(credential).every((key) => + ["username", "password"].includes(key), + ), + "Unknown destination credential field", + ); + assert( + typeof credential.username === "string" && + credential.username.trim() && + typeof credential.password === "string" && + credential.password.trim(), + "Destination credentials require a username and password", + ); + // Docker setup accepts named registry roles. Each destination gets its own + // credentials; the source token must never become a fallback for another host. + const role = `pull:${name}`; + registries[role] = name; + usernames[role] = credential.username; + passwords[role] = credential.password; + } + return { registries, usernames, passwords }; + } + + references() { + return Object.fromEntries( + Object.entries(this.additional).map(([name, destinations]) => [ + name, + destinations.map( + (destination) => `${destination}@${this.images[name].digest}`, + ), + ]), + ); + } +} + +export { PromotionDestinations }; diff --git a/actions/docker/promote-images/src/promote-images.test.js b/actions/docker/promote-images/src/promote-images.test.js index b531d81c..8739e977 100644 --- a/actions/docker/promote-images/src/promote-images.test.js +++ b/actions/docker/promote-images/src/promote-images.test.js @@ -2,6 +2,7 @@ import assert from "node:assert/strict"; import { createHash } from "node:crypto"; import { test } from "node:test"; import { promotionContract } from "./contract.js"; +import { PromotionDestinations } from "./destinations.js"; import { ImagePromotion } from "./promotion.js"; const raw = @@ -69,6 +70,7 @@ function claim(overrides = {}) { function harness(overrides = {}) { const state = { writes: [], + copies: [], records: [], statuses: [], commands: [], @@ -103,10 +105,18 @@ function harness(overrides = {}) { paginate: async () => state.records, }; const exec = { + exec: async (command, args) => { + state.commands.push([command, ...args]); + assert.equal(command, "cosign"); + return state.badDestinationSignature ? 1 : 0; + }, getExecOutput: async (command, args) => { state.commands.push([command, ...args]); if (command === "gh") { - if (state.badProvenance) + if ( + state.badProvenance || + (state.badDestinationProvenance && state.copies.length) + ) throw new Error("Provenance verification failed"); return { stdout: JSON.stringify([ @@ -132,6 +142,16 @@ function harness(overrides = {}) { ]), }; } + if (command === "regctl") { + assert( + state.records.length > 0, + "Copies must be journaled before registry writes", + ); + if (state.failCopy) throw new Error("Registry copy failed"); + state.copies.push(args.at(-1)); + if (state.cancelAfterCopy) state.run.status = "completed"; + return { stdout: "" }; + } if (args.includes("--dry-run")) return { stdout: `${state.manifest}\n` }; if (args.includes("inspect")) return { stdout: `Digest: ${state.badDigest || digest}\n` }; @@ -157,6 +177,7 @@ function harness(overrides = {}) { attempt: "1", verifiedImages: state.verifiedImages, buildWorkflow: state.buildWorkflow, + additionalDestinations: state.additionalDestinations, }); return { state, promotion, github }; } @@ -687,3 +708,191 @@ test("accepts a current run reported as queued while its promotion job executes" await promotion.promote({ backend: candidate() }); assert.equal(state.statuses.at(-1), "success"); }); + +const extraDestination = "docker.io/example/backend:1.2.3"; +const additionalDestinations = JSON.stringify({ backend: [extraDestination] }); + +test("explicit extra destinations retain original outputs and share one publication claim", async () => { + const { state, promotion } = harness({ additionalDestinations }); + const output = await promotion.promote({ backend: candidate() }); + assert.deepEqual(state.writes, [ + ...candidate().candidate.destinations, + extraDestination, + ]); + assert.deepEqual(state.records[0].payload.destinations, { + ...claim().destinations, + [extraDestination]: digest, + }); + assert.deepEqual( + output.backend.images, + candidate().candidate.destinations.map((ref) => `${ref}@${digest}`), + ); + assert.deepEqual(promotion.additionalImages, { + backend: [`${extraDestination}@${digest}`], + }); + const copy = state.commands.find(([command]) => command === "regctl"); + assert(copy.includes("--referrers") && copy.includes("--digest-tags")); + const verification = state.commands.find(([command]) => command === "cosign"); + assert.equal(verification.at(-1), `docker.io/example/backend@${digest}`); + assert.equal( + verification[verification.indexOf("--certificate-identity-regexp") + 1], + promotionContract.builder(state.buildWorkflow).identityRegexp, + ); + assert.equal( + state.commands.filter(([command]) => command === "gh").at(-1)[3], + `oci://docker.io/example/backend@${digest}`, + ); + assert.deepEqual(await promotion.promote({ backend: candidate() }), output); + assert.deepEqual(state.statuses, [ + "in_progress", + "success", + "in_progress", + "success", + ]); +}); + +test("an extra tag in the source repository needs no copy", async () => { + const { state, promotion } = harness({ + additionalDestinations: JSON.stringify({ + backend: ["ghcr.io/example/application/backend:stable"], + }), + }); + await promotion.promote({ backend: candidate() }); + assert.deepEqual(state.copies, []); + assert.equal( + state.writes.at(-1), + "ghcr.io/example/application/backend:stable", + ); +}); + +test("a newer claim overlapping only an additional destination blocks every write", async () => { + const { state, promotion } = harness({ + additionalDestinations, + records: [ + { + payload: claim({ + runId: "21", + destinations: { [extraDestination]: digest }, + }), + }, + ], + }); + await assert.rejects(promotion.promote({ backend: candidate() }), /newer/i); + assert.deepEqual(state.writes, []); + assert.deepEqual(state.copies, []); +}); + +for (const [name, override] of [ + ["copy failure", { failCopy: true }], + ["invalid copied signature", { badDestinationSignature: true }], + ["invalid copied provenance", { badDestinationProvenance: true }], + ["cancellation during copy", { cancelAfterCopy: true }], + ["extra tag write failure", { failDestination: extraDestination }], +]) { + test(`${name} retains the claim, withholds extra output and prevents the extra tag`, async () => { + const { state, promotion } = harness({ + additionalDestinations, + ...override, + }); + await assert.rejects(promotion.promote({ backend: candidate() })); + assert.equal(state.records.length, 1); + assert.equal( + state.records[0].payload.destinations[extraDestination], + digest, + ); + assert.deepEqual(state.writes, candidate().candidate.destinations); + assert.equal(promotion.additionalImages, undefined); + assert.deepEqual(state.statuses, ["in_progress", "failure"]); + Object.assign(state, { + failCopy: false, + badDestinationSignature: false, + badDestinationProvenance: false, + cancelAfterCopy: false, + failDestination: undefined, + }); + state.run.status = "in_progress"; + await promotion.promote({ backend: candidate() }); + assert.equal(state.statuses.at(-1), "success"); + assert.deepEqual(promotion.additionalImages, { + backend: [`${extraDestination}@${digest}`], + }); + }); +} + +for (const value of [ + "not JSON", + "null", + "[]", + '{"unknown":["docker.io/example/backend:1.2.3"]}', + '{"backend":[]}', + '{"backend":[42]}', + JSON.stringify({ backend: [extraDestination, extraDestination] }), + JSON.stringify({ backend: [candidate().candidate.destinations[0]] }), + ...[ + "example/backend:1.2.3", + "docker.io/example/backend", + "docker.io/example/backend:candidate-old", + `docker.io/example/backend@${digest}`, + "docker.io/example/backend:bad;tag", + " docker.io/example/backend:1.2.3", + ].map((ref) => JSON.stringify({ backend: [ref] })), +]) { + test(`rejects invalid additional destinations ${value}`, () => { + assert.throws( + () => new PromotionDestinations({ backend: candidate() }, value), + ); + }); +} + +test("registry credentials are explicit per host and never fall back to the source token", () => { + const destinations = new PromotionDestinations( + { backend: candidate() }, + additionalDestinations, + ); + const source = { + registry: "ghcr.io", + username: "source-user", + password: "source-token", + }; + assert.throws( + () => destinations.authentication(source), + /Explicit credentials/, + ); + for (const credentials of [ + '{"docker.io":{"username":"user"}}', + '{"docker.io":{"username":"user","password":"","typo":"secret"}}', + '{"unconfigured.example":{"username":"user","password":"other"}}', + '{"docker.io":{"username":"user","password":"secret"}', + ]) { + assert.throws( + () => destinations.authentication({ ...source, credentials }), + (error) => !error.message.includes("secret"), + ); + } + const auth = destinations.authentication({ + ...source, + credentials: JSON.stringify({ + "docker.io": { username: "dest-user", password: "dest-token" }, + }), + }); + assert.deepEqual(auth.registries, { + push: "ghcr.io", + "pull:docker.io": "docker.io", + }); + assert.deepEqual(auth.usernames, { + push: "source-user", + "pull:docker.io": "dest-user", + }); + assert.deepEqual(auth.passwords, { + push: "source-token", + "pull:docker.io": "dest-token", + }); + const sameRegistry = new PromotionDestinations( + { backend: candidate() }, + JSON.stringify({ backend: ["ghcr.io/other/backend:stable"] }), + ); + assert.equal(sameRegistry.requiresCopy, true); + assert.deepEqual(sameRegistry.authentication(source).passwords, { + push: "source-token", + }); +}); diff --git a/actions/docker/promote-images/src/promotion.js b/actions/docker/promote-images/src/promotion.js index c2a87a5f..42517dd0 100644 --- a/actions/docker/promote-images/src/promotion.js +++ b/actions/docker/promote-images/src/promotion.js @@ -1,6 +1,8 @@ import assert from "node:assert/strict"; import { createHash } from "node:crypto"; +import { ImageVerification } from "../../verify-images/src/verification.js"; import { promotionContract } from "./contract.js"; +import { PromotionDestinations } from "./destinations.js"; const journal = { environment: "ci-image-promotion", @@ -16,6 +18,7 @@ class ImagePromotion { attempt, verifiedImages, buildWorkflow, + additionalDestinations = "{}", }) { this.builder = promotionContract.builder(buildWorkflow); Object.assign(this, { @@ -26,6 +29,7 @@ class ImagePromotion { runId, attempt, verifiedImages, + additionalDestinations, }); } @@ -133,6 +137,10 @@ class ImagePromotion { assert(manifest.endsWith("\n"), "Unexpected Buildx dry-run output"); const digest = `sha256:${createHash("sha256").update(manifest.slice(0, -1)).digest("hex")}`; assert.equal(digest, image.digest, "Promotion would change manifest bytes"); + await this.verifyProvenance(image, reference); + } + + async verifyProvenance(image, reference) { const output = await this.command("gh", [ "attestation", "verify", @@ -165,14 +173,14 @@ class ImagePromotion { ); } - async recordClaim(images, run) { + async recordClaim(destinations, run) { const claim = { schema: 1, runId: this.runId, attempt: this.attempt, createdAt: run.created_at, revision: this.context.sha, - destinations: promotionContract.destinations(images), + destinations, }; const records = await this.github.paginate( this.github.rest.repos.listDeployments, @@ -210,6 +218,11 @@ class ImagePromotion { } async promote(images) { + this.additionalImages = undefined; + const destinations = new PromotionDestinations( + images, + this.additionalDestinations, + ); assert( Array.isArray(this.verifiedImages), "Missing signature verification output", @@ -228,23 +241,17 @@ class ImagePromotion { for (const image of Object.values(images)) await this.verifyCandidate(image); const run = await this.currentRun(); - const deploymentId = await this.recordClaim(images, run); + const deploymentId = await this.recordClaim(destinations.claim, run); try { await this.status(deploymentId, "in_progress"); const promoted = {}; for (const [name, image] of Object.entries(images)) { - const reference = `${image.registry}/${image.repository}@${image.digest}`; - for (const destination of image.candidate.destinations) { + for (const destination of [ + ...image.candidate.destinations, + ...(destinations.additional[name] || []), + ]) { await this.currentRun(); - await this.command("docker", [ - "buildx", - "imagetools", - "create", - "--prefer-index=false", - "--tag", - destination, - reference, - ]); + await this.publishDestination(image, destination); assert.equal( await this.digest(destination), image.digest, @@ -265,6 +272,7 @@ class ImagePromotion { } await this.currentRun(); await this.status(deploymentId, "success"); + this.additionalImages = destinations.references(); return promoted; } catch (error) { await this.status(deploymentId, "failure").catch(() => @@ -275,6 +283,39 @@ class ImagePromotion { throw error; } } + + async publishDestination(image, destination) { + const source = `${image.registry}/${image.repository}@${image.digest}`; + const repository = destination.slice(0, destination.lastIndexOf(":")); + const target = `${repository}@${image.digest}`; + if (target !== source) { + // Copy immutable content and its security evidence before exposing the tag. + await this.command("regctl", [ + "image", + "copy", + "--referrers", + "--digest-tags", + source, + target, + ]); + await new ImageVerification({ + images: JSON.stringify([target]), + identityRegexp: this.builder.identityRegexp, + issuer: "https://token.actions.githubusercontent.com", + }).verify(this.exec); + await this.verifyProvenance(image, target); + await this.currentRun(); + } + await this.command("docker", [ + "buildx", + "imagetools", + "create", + "--prefer-index=false", + "--tag", + destination, + target, + ]); + } } export { ImagePromotion }; diff --git a/docs/README.md b/docs/README.md index 06d5acd8..819e5ada 100644 --- a/docs/README.md +++ b/docs/README.md @@ -15,3 +15,4 @@ - [Concurrent PR-state lookup deduplication](adr/0010-deduplicate-concurrent-pr-state-lookups.md) - [Helm documentation generation and bundled formatting](adr/0011-skip-unchanged-helm-documentation.md) - [Release action artifact ownership](adr/0012-release-chart-artifact-input.md) +- [Promotion to additional destinations](adr/0013-promote-to-additional-destinations.md) diff --git a/docs/adr/0006-promote-validated-image-digests.md b/docs/adr/0006-promote-validated-image-digests.md index 99a493cf..57bfbb20 100644 --- a/docs/adr/0006-promote-validated-image-digests.md +++ b/docs/adr/0006-promote-validated-image-digests.md @@ -142,3 +142,9 @@ cover PR, branch and release tags; hosted PR tests do not claim a real release r - [GitHub deployments API](https://docs.github.com/en/rest/deployments/deployments) - [Attestation verification policy](https://cli.github.com/manual/gh_attestation_verify) - [Action repository context](https://docs.github.com/en/actions/reference/workflows-and-actions/contexts#github-context) + +## Extension + +[ADR 0013](0013-promote-to-additional-destinations.md) extends the same-repository +publication restriction with explicitly configured additional destinations, while +retaining the original candidate validation and journal guarantees. diff --git a/docs/adr/0013-promote-to-additional-destinations.md b/docs/adr/0013-promote-to-additional-destinations.md new file mode 100644 index 00000000..b65b5fd3 --- /dev/null +++ b/docs/adr/0013-promote-to-additional-destinations.md @@ -0,0 +1,55 @@ +# ADR 0013: Promote validated image digests to additional destinations + +- Status: Proposed +- Date: 2026-11-26 +- Extends: [ADR 0006](0006-promote-validated-image-digests.md) + +## Context + +HTTP Header Authenticator validates candidates in GHCR and publishes its released +image to Docker Hub before publishing its chart. A separate mirror workflow would +introduce a second publication operation outside the existing promotion lock and +journal. The destination restriction in ADR 0006 protects candidate metadata from +selecting arbitrary publication targets, but prevents this explicit release use. + +## Decision + +Extend the existing Docker promote images workflow and action with optional +`additional-destinations`, keyed by validated image name. Candidate metadata remains +restricted to its original repository. Callers explicitly authorize any additional +fully qualified tagged destinations in the promotion call. + +Every destination joins the same deployment claim and serialized publication. +Existing supersession, cancellation, partial failure and recovery rules apply to +all of them. Tags remain individually visible, with no rollback or atomicity across +registries. All writers must use the same calling repository's promotion journal. + +Additional registry hosts require explicit credentials through the +`destination-credentials` secret. Docker setup handles every login using separate +credential maps; the source token is never a fallback for another host. Another +repository on the same host reuses the source login and its permissions. + +For cross-repository copies, install pinned regctl and copy the immutable image, +its child manifests, OCI referrers and legacy digest tags. The installed Cosign +version's copy command only copies legacy tags, so it cannot preserve the OCI 1.1 +signatures used by our builder. Verify the destination signature and provenance +against the original source repository, revision, builder and run attempt before +writing its consumer tag. Do not rebuild or re-sign the image. + +Preserve `built-images` and expose additional immutable references through +`additional-images`. Withhold both outputs unless every destination and the final +journal status succeed. Calls without additional destinations keep their existing +behavior and do not install regctl. + +## Consequences + +There is one public publication workflow and action to maintain. The extra binary +is needed only for copies, and destination registries must support the copied +manifests and evidence. A failure can leave untagged copied content or some published +tags; the retained claim permits identical same-attempt recovery and blocks older +runs. Registry-specific retention remains the caller's responsibility. + +Native tests cover destination validation, credential isolation, overlapping claims +and failure recovery. Existing signed single-platform and multi-platform fixtures +exercise copies and verification without another build matrix. Two local registries +cover cross-host transport and attachment preservation without external credentials. diff --git a/tests/docker-promote-images/registry-fixture.mjs b/tests/docker-promote-images/registry-fixture.mjs new file mode 100644 index 00000000..8acac919 --- /dev/null +++ b/tests/docker-promote-images/registry-fixture.mjs @@ -0,0 +1,193 @@ +import assert from "node:assert/strict"; +import fs from "node:fs/promises"; +import path from "node:path"; + +export async function prepare( + exec, + temporaryRoot, + sourceRegistry, + destinationRegistry, +) { + const context = await fs.mkdtemp( + path.join(temporaryRoot, "promotion-fixture-"), + ); + const source = `${sourceRegistry}/promotion-test`; + try { + await fs.writeFile( + path.join(context, "Dockerfile"), + "FROM scratch\nCOPY payload /payload\n", + ); + await fs.writeFile( + path.join(context, "payload"), + "immutable image promotion fixture\n", + ); + for (const architecture of ["amd64", "arm64"]) { + await exec.exec("docker", [ + "buildx", + "build", + "--builder", + "default", + "--provenance=false", + "--platform", + `linux/${architecture}`, + "--tag", + `${source}:${architecture}`, + "--push", + context, + ]); + } + await exec.exec("docker", [ + "buildx", + "imagetools", + "create", + "--tag", + `${source}:multi`, + `${source}:amd64`, + `${source}:arm64`, + ]); + const images = {}; + for (const [name, tag] of [ + ["single", "amd64"], + ["multi", "multi"], + ]) { + const result = await exec.getExecOutput("docker", [ + "buildx", + "imagetools", + "inspect", + "--format", + "{{json .Manifest}}", + `${source}:${tag}`, + ]); + const { digest } = JSON.parse(result.stdout); + assert.match(digest, /^sha256:[a-f0-9]{64}$/); + await fs.writeFile( + path.join(context, "evidence.json"), + JSON.stringify({ fixture: name }), + ); + await exec.exec("regctl", [ + "artifact", + "put", + "--subject", + `${source}@${digest}`, + "--artifact-type", + "application/vnd.hoverkraft.test+json", + "--file", + path.join(context, "evidence.json"), + ]); + await exec.exec("regctl", [ + "artifact", + "put", + `${source}:sha256-${digest.slice(7)}.sig`, + "--artifact-type", + "application/vnd.hoverkraft.legacy-test+json", + "--file", + path.join(context, "evidence.json"), + ]); + images[name] = { + source: `${source}:${tag}@${digest}`, + destination: `${destinationRegistry}/promotion-test:${name}`, + }; + } + return images; + } finally { + await fs.rm(context, { recursive: true, force: true }); + } +} + +// These local registries exercise the copy tool's transport and attachment contract. +// The existing hosted promotion fixture verifies real builder signatures/provenance. +export async function copyAndVerify(exec, images) { + for (const [name, { source, destination }] of Object.entries(images)) { + const digest = source.split("@")[1]; + const targetRepository = destination.slice(0, destination.lastIndexOf(":")); + const target = `${targetRepository}@${digest}`; + await exec.exec("regctl", [ + "image", + "copy", + "--referrers", + "--digest-tags", + source, + target, + ]); + await exec.exec("docker", [ + "buildx", + "imagetools", + "create", + "--prefer-index=false", + "--tag", + destination, + target, + ]); + const result = await exec.getExecOutput("docker", [ + "buildx", + "imagetools", + "inspect", + "--format", + "{{json .Manifest}}", + destination, + ]); + assert.equal(JSON.parse(result.stdout).digest, digest); + const referrers = async (reference) => + JSON.parse( + ( + await exec.getExecOutput("regctl", [ + "artifact", + "list", + reference, + "--format", + "body", + ]) + ).stdout, + ) + .manifests.map((ref) => ref.digest) + .sort(); + const expectedReferrers = await referrers(source); + assert(expectedReferrers.length > 0, "Fixture must have OCI referrers"); + assert.deepEqual(await referrers(target), expectedReferrers); + const legacy = `sha256-${digest.slice(7)}.sig`; + const originalRepository = source.slice(0, source.indexOf("@")); + const original = originalRepository.slice( + 0, + originalRepository.lastIndexOf(":"), + ); + const legacyManifest = async (repository) => + ( + await exec.getExecOutput("docker", [ + "buildx", + "imagetools", + "inspect", + "--raw", + `${repository}:${legacy}`, + ]) + ).stdout; + assert.equal( + await legacyManifest(targetRepository), + await legacyManifest(original), + ); + const inspect = async (reference) => + JSON.parse( + ( + await exec.getExecOutput("docker", [ + "buildx", + "imagetools", + "inspect", + "--raw", + reference, + ]) + ).stdout, + ); + const expected = await inspect(source); + assert.deepEqual(await inspect(destination), expected); + if (name === "multi") { + assert.deepEqual( + expected.manifests.map(({ platform }) => platform.architecture).sort(), + ["amd64", "arm64"], + ); + } else { + assert( + !expected.manifests, + "A single-platform manifest must not be wrapped in an index", + ); + } + } +}