From e8bd81eb506404d63f0304b02ff254e5fd2f0ce5 Mon Sep 17 00:00:00 2001 From: Emilien Escalle Date: Thu, 26 Nov 2026 08:08:34 +0100 Subject: [PATCH 1/5] feat: mirror immutable images across registries --- .github/workflows/__shared-ci.yml | 10 ++ .../__test-action-docker-mirror-image.yml | 77 +++++++++++++ .github/workflows/docker-mirror-image.yml | 79 ++++++++++++++ README.md | 4 + actions/docker/mirror-image/action.yml | 84 +++++++++++++++ actions/docker/mirror-image/package-lock.json | 13 +++ actions/docker/mirror-image/package.json | 14 +++ actions/docker/mirror-image/src/mirror.js | 71 ++++++++++++ .../docker/mirror-image/src/mirror.test.js | 73 +++++++++++++ tests/docker-mirror-image/fixture.mjs | 102 ++++++++++++++++++ 10 files changed, 527 insertions(+) create mode 100644 .github/workflows/__test-action-docker-mirror-image.yml create mode 100644 .github/workflows/docker-mirror-image.yml create mode 100644 actions/docker/mirror-image/action.yml create mode 100644 actions/docker/mirror-image/package-lock.json create mode 100644 actions/docker/mirror-image/package.json create mode 100644 actions/docker/mirror-image/src/mirror.js create mode 100644 actions/docker/mirror-image/src/mirror.test.js create mode 100644 tests/docker-mirror-image/fixture.mjs diff --git a/.github/workflows/__shared-ci.yml b/.github/workflows/__shared-ci.yml index ee3eb81f..732311f9 100644 --- a/.github/workflows/__shared-ci.yml +++ b/.github/workflows/__shared-ci.yml @@ -29,6 +29,16 @@ jobs: with: comment: false + test-action-docker-mirror-image: + needs: lint + uses: $/.github/workflows/__test-action-docker-mirror-image.yml + permissions: + contents: read + id-token: write + packages: read + pull-requests: write + security-events: write + test-action-docker-promote-images: needs: lint uses: $/.github/workflows/__test-action-docker-promote-images.yml diff --git a/.github/workflows/__test-action-docker-mirror-image.yml b/.github/workflows/__test-action-docker-mirror-image.yml new file mode 100644 index 00000000..eea03765 --- /dev/null +++ b/.github/workflows/__test-action-docker-mirror-image.yml @@ -0,0 +1,77 @@ +--- +name: Test for "docker/mirror-image" action + +"on": + workflow_call: + +permissions: {} + +jobs: + continuous-integration: + uses: hoverkraft-tech/ci-github-nodejs/.github/workflows/continuous-integration.yml@191d7230d57982bfc11d57f68b005f386a6d7fbf # 3.1.1 + permissions: + contents: read + id-token: write + packages: read + pull-requests: write + security-events: write + with: + working-directory: actions/docker/mirror-image + build: "" + lint: "" + code-ql: '{"languages":"typescript","config-file":".github/codeql/config.yml"}' + test: '{"comment":false,"report-group":"test-action-docker-mirror-image"}' + + 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 + - id: fixture + 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'] }} + with: + script: | + const { pathToFileURL } = require('node:url'); + const { prepare } = await import(pathToFileURL(`${process.env.GITHUB_WORKSPACE}/tests/docker-mirror-image/fixture.mjs`)); + const images = await prepare(exec, process.env.RUNNER_TEMP, process.env.SOURCE_REGISTRY, process.env.DESTINATION_REGISTRY); + core.setOutput('images', images); + - id: single + uses: $/actions/docker/mirror-image + with: + source-image: ${{ fromJSON(steps.fixture.outputs.images).single.source }} + destination-image: ${{ fromJSON(steps.fixture.outputs.images).single.destination }} + - id: multi + uses: $/actions/docker/mirror-image + with: + source-image: ${{ fromJSON(steps.fixture.outputs.images).multi.source }} + destination-image: ${{ fromJSON(steps.fixture.outputs.images).multi.destination }} + - name: Verify unchanged manifests, digests and platforms + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + IMAGES: ${{ steps.fixture.outputs.images }} + SINGLE: ${{ steps.single.outputs.image }} + MULTI: ${{ steps.multi.outputs.image }} + with: + script: | + const { pathToFileURL } = require('node:url'); + const { verify } = await import(pathToFileURL(`${process.env.GITHUB_WORKSPACE}/tests/docker-mirror-image/fixture.mjs`)); + await verify(exec, JSON.parse(process.env.IMAGES), { single: process.env.SINGLE, multi: process.env.MULTI }); diff --git a/.github/workflows/docker-mirror-image.yml b/.github/workflows/docker-mirror-image.yml new file mode 100644 index 00000000..92bd96d7 --- /dev/null +++ b/.github/workflows/docker-mirror-image.yml @@ -0,0 +1,79 @@ +# Mirror a validated immutable image to another registry without rebuilding it. +# Require successful source validation or promotion through the calling job's needs. +# Pass a digest-qualified source and one explicit destination tag. The workflow +# serializes writes to that destination and returns its verified immutable reference. +# It preserves image manifests and indexes, but does not copy separate signatures +# or referrers. Source validation remains the caller's responsibility. +# +# Registry credentials are supplied as secrets. The GitHub job token is used only +# for ghcr.io sources; other private source registries require explicit credentials. +# No credentials are needed to read public source registries. An optional environment +# protects registry publication. No source checkout or application build is performed. +--- +name: Docker mirror image +"on": + workflow_call: + inputs: + source-image: + description: Validated source image including an immutable SHA-256 digest. + type: string + required: true + destination-image: + description: Destination registry, repository and explicit tag. + type: string + required: true + source-registry-username: + description: Source registry username. Defaults to the GitHub actor for ghcr.io. + type: string + default: "" + destination-registry-username: + description: Destination registry username. Use the secret when sensitive. + type: string + default: "" + environment: + description: Optional GitHub environment protecting destination publication. + type: string + default: "" + secrets: + source-registry-username: + description: Optional private source registry username; overrides the input. + required: false + source-registry-password: + description: Source credential. Defaults to the job token only for ghcr.io sources. + required: false + destination-registry-username: + description: Optional private destination registry username; overrides the input. + required: false + destination-registry-password: + description: Credential authorized to publish the destination image. + required: true + outputs: + image: + description: Published destination qualified by the unchanged source digest. + value: ${{ jobs.mirror.outputs.image }} +permissions: {} +jobs: + mirror: + runs-on: ubuntu-latest + timeout-minutes: 15 + environment: ${{ inputs.environment }} + concurrency: + group: image-mirror-${{ github.repository_id }}-${{ inputs.destination-image }} + cancel-in-progress: false + permissions: + contents: read + packages: read + outputs: + image: ${{ steps.mirror.outputs.image }} + steps: + - id: mirror + uses: $/actions/docker/mirror-image + with: + source-image: ${{ inputs.source-image }} + destination-image: ${{ inputs.destination-image }} + source-registry-username: >- + ${{ secrets.source-registry-username || inputs.source-registry-username || + (startsWith(inputs.source-image, 'ghcr.io/') && github.actor) || '' }} + source-registry-password: ${{ secrets.source-registry-password || (startsWith(inputs.source-image, 'ghcr.io/') && github.token) || '' }} + destination-registry-username: ${{ secrets.destination-registry-username || inputs.destination-registry-username }} + destination-registry-password: ${{ secrets.destination-registry-password }} diff --git a/README.md b/README.md index 3d5d3955..6e586025 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,8 @@ _Actions that operate on OCI images across their build, metadata, and lifecycle #### - [Get image name](actions/docker/get-image-name/README.md) +#### - [Mirror image](actions/docker/mirror-image/README.md) + #### - [Promote images](actions/docker/promote-images/README.md) #### - [Prune pull requests image tags](actions/docker/prune-pull-requests-image-tags/README.md) @@ -73,6 +75,8 @@ _Orchestrated workflows you can plug directly into repositories to automate cont ### - [Docker build images](.github/workflows/docker-build-images.md) +### - [Docker mirror image](.github/workflows/docker-mirror-image.md) + ### - [Docker promote images](.github/workflows/docker-promote-images.md) ### - [Helm chart CI](.github/workflows/helm-chart-ci.md) diff --git a/actions/docker/mirror-image/action.yml b/actions/docker/mirror-image/action.yml new file mode 100644 index 00000000..ba84adfa --- /dev/null +++ b/actions/docker/mirror-image/action.yml @@ -0,0 +1,84 @@ +# Copy an already validated image to one explicit registry tag without rebuilding. +# The source must include its immutable SHA-256 digest. Single-platform manifests +# and multi-platform indexes retain their digest; a changed digest fails the action. +# Registry signatures and referrers are not copied separately. Verify the source +# before calling and use the shared mirror workflow to serialize destination writes. +# Requires Docker and a Linux runner. Credentials are optional for local test registries. +--- +name: Docker - Mirror image +description: Copy an immutable image to another registry without changing its digest. +author: hoverkraft +branding: + icon: copy + color: blue +inputs: + source-image: + description: Fully qualified source image including its SHA-256 digest. + required: true + destination-image: + description: Fully qualified destination image with an explicit tag. + required: true + source-registry-username: + description: Source registry username, paired with its password. + default: "" + source-registry-password: + description: Source registry password or token. Empty skips authentication. + default: "" + destination-registry-username: + description: Destination registry username, paired with its password. + default: "" + destination-registry-password: + description: Destination registry password or token. Empty skips authentication. + default: "" +outputs: + image: + description: Destination tag qualified by the unchanged source digest. + value: ${{ steps.copy.outputs.image }} +runs: + using: composite + steps: + - name: Validate immutable source and tagged destination + id: references + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + ACTION_PATH: ${{ github.action_path }} + SOURCE: ${{ inputs.source-image }} + DESTINATION: ${{ inputs.destination-image }} + with: + script: | + const { pathToFileURL } = require('node:url'); + const { ImageMirror } = await import(pathToFileURL(`${process.env.ACTION_PATH}/src/mirror.js`)); + const mirror = new ImageMirror(process.env.SOURCE, process.env.DESTINATION); + core.setOutput('source-registry', mirror.sourceRegistry); + core.setOutput('destination-registry', mirror.destinationRegistry); + - name: Authenticate to the source registry + if: inputs.source-registry-password != '' + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 + with: + registry: ${{ steps.references.outputs.source-registry }} + username: ${{ inputs.source-registry-username }} + password: ${{ inputs.source-registry-password }} + - name: Authenticate to the destination registry + if: inputs.destination-registry-password != '' + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 + with: + registry: ${{ steps.references.outputs.destination-registry }} + username: ${{ inputs.destination-registry-username }} + password: ${{ inputs.destination-registry-password }} + - name: Set up registry tooling + uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + with: + driver: docker + - name: Copy the retained manifest and layers + id: copy + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + ACTION_PATH: ${{ github.action_path }} + SOURCE: ${{ inputs.source-image }} + DESTINATION: ${{ inputs.destination-image }} + with: + script: | + const { pathToFileURL } = require('node:url'); + const { ImageMirror } = await import(pathToFileURL(`${process.env.ACTION_PATH}/src/mirror.js`)); + const image = await new ImageMirror(process.env.SOURCE, process.env.DESTINATION).copy(exec, process.env.RUNNER_TEMP); + core.setOutput('image', image); diff --git a/actions/docker/mirror-image/package-lock.json b/actions/docker/mirror-image/package-lock.json new file mode 100644 index 00000000..0a061d16 --- /dev/null +++ b/actions/docker/mirror-image/package-lock.json @@ -0,0 +1,13 @@ +{ + "name": "mirror-image", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "mirror-image", + "engines": { + "node": ">=24.0.0" + } + } + } +} diff --git a/actions/docker/mirror-image/package.json b/actions/docker/mirror-image/package.json new file mode 100644 index 00000000..40b02087 --- /dev/null +++ b/actions/docker/mirror-image/package.json @@ -0,0 +1,14 @@ +{ + "name": "mirror-image", + "private": true, + "type": "module", + "engines": { + "node": ">=24.0.0" + }, + "scripts": { + "test": "node --test", + "test:watch": "node --test --watch", + "pretest:ci": "node -e \"require('node:fs').mkdirSync('coverage', { recursive: true })\"", + "test:ci": "node --experimental-test-coverage --test-reporter=spec --test-reporter-destination=stdout --test-reporter=junit --test-reporter-destination=coverage/junit.xml --test-reporter=lcov --test-reporter-destination=coverage/lcov.info --test" + } +} diff --git a/actions/docker/mirror-image/src/mirror.js b/actions/docker/mirror-image/src/mirror.js new file mode 100644 index 00000000..4d8fa6b7 --- /dev/null +++ b/actions/docker/mirror-image/src/mirror.js @@ -0,0 +1,71 @@ +import assert from "node:assert/strict"; +import fs from "node:fs/promises"; +import path from "node:path"; + +class ImageMirror { + constructor(source, destination) { + const pattern = + /^(?[a-z0-9]+(?:[.-][a-z0-9]+)*(?::[0-9]+)?)(?(?:\/[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*)+)(?::(?[\w][\w.-]{0,127}))?(?:@(?sha256:[a-f0-9]{64}))?$/; + const parse = (value) => { + assert.equal(typeof value, "string", "Image references must be strings"); + assert.equal( + value, + value.trim(), + "Image references must not contain surrounding whitespace", + ); + const match = value.match(pattern); + assert(match, "Expected an explicit OCI image reference"); + const { registry } = match.groups; + assert( + registry.includes(".") || + registry.includes(":") || + registry === "localhost", + "Image references require an explicit registry", + ); + return match.groups; + }; + const from = parse(source); + const to = parse(destination); + assert(from.digest, "The source image must be pinned by digest"); + assert( + to.tag && !to.digest, + "The destination image must have an explicit tag and no digest", + ); + this.source = `${from.registry}${from.repository}@${from.digest}`; + this.destination = destination; + this.sourceRegistry = from.registry; + this.destinationRegistry = to.registry; + this.digest = from.digest; + } + + async copy(exec, temporaryRoot) { + const directory = await fs.mkdtemp( + path.join(temporaryRoot, "mirror-image-"), + ); + const metadata = path.join(directory, "result.json"); + try { + await exec.exec("docker", [ + "buildx", + "imagetools", + "create", + "--prefer-index=false", + "--metadata-file", + metadata, + "--tag", + this.destination, + this.source, + ]); + const result = JSON.parse(await fs.readFile(metadata, "utf8")); + assert.equal( + result["containerimage.descriptor"]?.digest, + this.digest, + "Mirrored digest differs from the source digest", + ); + return `${this.destination}@${this.digest}`; + } finally { + await fs.rm(directory, { recursive: true, force: true }); + } + } +} + +export { ImageMirror }; diff --git a/actions/docker/mirror-image/src/mirror.test.js b/actions/docker/mirror-image/src/mirror.test.js new file mode 100644 index 00000000..4e31dc95 --- /dev/null +++ b/actions/docker/mirror-image/src/mirror.test.js @@ -0,0 +1,73 @@ +import assert from "node:assert/strict"; +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { ImageMirror } from "./mirror.js"; + +const digest = `sha256:${"a".repeat(64)}`; +const source = `ghcr.io/example/app:validated@${digest}`; +const destination = "docker.io/example/app:1.2.3"; + +test("mirroring requires an immutable source and an explicit registry tag", () => { + const mirror = new ImageMirror(source, destination); + assert.equal(mirror.source, `ghcr.io/example/app@${digest}`); + assert.equal(mirror.sourceRegistry, "ghcr.io"); + assert.equal(mirror.destinationRegistry, "docker.io"); + for (const invalid of [ + "ghcr.io/example/app:latest", + `example/app@${digest}`, + "--help", + `${source}\nextra`, + `${source}\n`, + ]) { + assert.throws(() => new ImageMirror(invalid, destination)); + } + for (const invalid of [ + "docker.io/example/app", + source, + "example/app:latest", + "docker.io/example/app:bad tag", + `${destination}\n`, + ]) { + assert.throws(() => new ImageMirror(source, invalid)); + } +}); + +test("mirroring reports the unchanged digest and cleans its metadata", async (t) => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), "mirror-contract-")); + t.after(() => fs.rm(root, { recursive: true, force: true })); + const mirror = new ImageMirror(source, destination); + const execute = (publishedDigest) => ({ + exec: async (_command, args) => { + await fs.writeFile( + args[args.indexOf("--metadata-file") + 1], + JSON.stringify({ + "containerimage.descriptor": { digest: publishedDigest }, + }), + ); + }, + }); + assert.equal( + await mirror.copy(execute(digest), root), + `${destination}@${digest}`, + ); + assert.deepEqual(await fs.readdir(root), []); + await assert.rejects( + mirror.copy(execute(`sha256:${"b".repeat(64)}`), root), + /Mirrored digest differs/, + ); + assert.deepEqual(await fs.readdir(root), []); + await assert.rejects( + mirror.copy( + { + exec: async () => { + throw new Error("denied"); + }, + }, + root, + ), + /denied/, + ); + assert.deepEqual(await fs.readdir(root), []); +}); diff --git a/tests/docker-mirror-image/fixture.mjs b/tests/docker-mirror-image/fixture.mjs new file mode 100644 index 00000000..3f5711b6 --- /dev/null +++ b/tests/docker-mirror-image/fixture.mjs @@ -0,0 +1,102 @@ +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, "mirror-fixture-")); + const source = `${sourceRegistry}/mirror-test`; + try { + await fs.writeFile( + path.join(context, "Dockerfile"), + "FROM scratch\nCOPY payload /payload\n", + ); + await fs.writeFile( + path.join(context, "payload"), + "immutable image mirror 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}$/); + images[name] = { + source: `${source}:${tag}@${digest}`, + destination: `${destinationRegistry}/mirror-test:${name}`, + }; + } + return images; + } finally { + await fs.rm(context, { recursive: true, force: true }); + } +} + +export async function verify(exec, images, outputs) { + for (const [name, { source, destination }] of Object.entries(images)) { + const digest = source.split("@")[1]; + assert.equal(outputs[name], `${destination}@${digest}`); + 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", + ); + } + } +} From a3584451e5b6a068b5857a940bd1901a0b203d54 Mon Sep 17 00:00:00 2001 From: Emilien Escalle Date: Thu, 26 Nov 2026 08:12:00 +0100 Subject: [PATCH 2/5] docs: generate immutable image mirroring references --- .github/workflows/docker-mirror-image.md | 107 +++++++++++++++++++++++ actions/docker/mirror-image/README.md | 77 ++++++++++++++++ 2 files changed, 184 insertions(+) create mode 100644 .github/workflows/docker-mirror-image.md create mode 100644 actions/docker/mirror-image/README.md diff --git a/.github/workflows/docker-mirror-image.md b/.github/workflows/docker-mirror-image.md new file mode 100644 index 00000000..ca3f1e9d --- /dev/null +++ b/.github/workflows/docker-mirror-image.md @@ -0,0 +1,107 @@ + + +# GitHub Reusable Workflow: Docker mirror image + +
+ Docker mirror image +
+ +--- + + + + +## Overview + +Mirror a validated immutable image to another registry without rebuilding it. +Require successful source validation or promotion through the calling job's needs. +Pass a digest-qualified source and one explicit destination tag. The workflow +serializes writes to that destination and returns its verified immutable reference. +It preserves image manifests and indexes, but does not copy separate signatures +or referrers. Source validation remains the caller's responsibility. + +Registry credentials are supplied as secrets. The GitHub job token is used only +for ghcr.io sources; other private source registries require explicit credentials. +No credentials are needed to read public source registries. An optional environment +protects registry publication. No source checkout or application build is performed. + +### Permissions + +- **`contents`**: `read` +- **`packages`**: `read` + + + + +## Usage + +```yaml +name: Docker mirror image +on: + push: + branches: + - main +permissions: {} +jobs: + docker-mirror-image: + uses: hoverkraft-tech/ci-github-container/.github/workflows/docker-mirror-image.yml@e8bd81eb506404d63f0304b02ff254e5fd2f0ce5 # feat/docker-mirror-image + permissions: + contents: read + packages: read + secrets: + # Optional private source registry username; overrides the input. + source-registry-username: "" + + # Source credential. Defaults to the job token only for ghcr.io sources. + source-registry-password: "" + + # Optional private destination registry username; overrides the input. + destination-registry-username: "" + + # Credential authorized to publish the destination image. + # This input is required. + destination-registry-password: "" + with: + # Validated source image including an immutable SHA-256 digest. + # This input is required. + source-image: "" + + # Destination registry, repository and explicit tag. + # This input is required. + destination-image: "" + + # Source registry username. Defaults to the GitHub actor for ghcr.io. + source-registry-username: "" + + # Destination registry username. Use the secret when sensitive. + destination-registry-username: "" + + # Optional GitHub environment protecting destination publication. + environment: "" +``` + + + + +## Inputs + +### Workflow Call Inputs + +| **Input** | **Description** | **Required** | **Type** | **Default** | +| ----------------------------------- | ------------------------------------------------------------------- | ------------ | ---------- | ----------- | +| **`source-image`** | Validated source image including an immutable SHA-256 digest. | **true** | **string** | - | +| **`destination-image`** | Destination registry, repository and explicit tag. | **true** | **string** | - | +| **`source-registry-username`** | Source registry username. Defaults to the GitHub actor for ghcr.io. | **false** | **string** | - | +| **`destination-registry-username`** | Destination registry username. Use the secret when sensitive. | **false** | **string** | - | +| **`environment`** | Optional GitHub environment protecting destination publication. | **false** | **string** | - | + + + + +## Outputs + +| **Output** | **Description** | +| ----------- | --------------------------------------------------------------- | +| **`image`** | Published destination qualified by the unchanged source digest. | + + diff --git a/actions/docker/mirror-image/README.md b/actions/docker/mirror-image/README.md new file mode 100644 index 00000000..fb213420 --- /dev/null +++ b/actions/docker/mirror-image/README.md @@ -0,0 +1,77 @@ + + +# ![Icon](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9ImN1cnJlbnRDb2xvciIgc3Ryb2tlLXdpZHRoPSIyIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiIGNsYXNzPSJmZWF0aGVyIGZlYXRoZXItY29weSIgY29sb3I9ImJsdWUiPjxyZWN0IHg9IjkiIHk9IjkiIHdpZHRoPSIxMyIgaGVpZ2h0PSIxMyIgcng9IjIiIHJ5PSIyIj48L3JlY3Q+PHBhdGggZD0iTTUgMTVINGEyIDIgMCAwIDEtMi0yVjRhMiAyIDAgMCAxIDItMmg5YTIgMiAwIDAgMSAyIDJ2MSI+PC9wYXRoPjwvc3ZnPg==) GitHub Action: Docker - Mirror image + +
+ Docker - Mirror image +
+ +--- + + + + +## Overview + +Copy an immutable image to another registry without changing its digest. + +Copy an already validated image to one explicit registry tag without rebuilding. +The source must include its immutable SHA-256 digest. Single-platform manifests +and multi-platform indexes retain their digest; a changed digest fails the action. +Registry signatures and referrers are not copied separately. Verify the source +before calling and use the shared mirror workflow to serialize destination writes. +Requires Docker and a Linux runner. Credentials are optional for local test registries. + + + + +## Usage + +```yaml +- uses: hoverkraft-tech/ci-github-container/actions/docker/mirror-image@e8bd81eb506404d63f0304b02ff254e5fd2f0ce5 # feat/docker-mirror-image + with: + # Fully qualified source image including its SHA-256 digest. + # This input is required. + source-image: "" + + # Fully qualified destination image with an explicit tag. + # This input is required. + destination-image: "" + + # Source registry username, paired with its password. + source-registry-username: "" + + # Source registry password or token. Empty skips authentication. + source-registry-password: "" + + # Destination registry username, paired with its password. + destination-registry-username: "" + + # Destination registry password or token. Empty skips authentication. + destination-registry-password: "" +``` + + + + +## Inputs + +| **Input** | **Description** | **Required** | **Default** | +| ----------------------------------- | ------------------------------------------------------------------- | ------------ | ----------- | +| **`source-image`** | Fully qualified source image including its SHA-256 digest. | **true** | - | +| **`destination-image`** | Fully qualified destination image with an explicit tag. | **true** | - | +| **`source-registry-username`** | Source registry username, paired with its password. | **false** | - | +| **`source-registry-password`** | Source registry password or token. Empty skips authentication. | **false** | - | +| **`destination-registry-username`** | Destination registry username, paired with its password. | **false** | - | +| **`destination-registry-password`** | Destination registry password or token. Empty skips authentication. | **false** | - | + + + + +## Outputs + +| **Output** | **Description** | +| ----------- | --------------------------------------------------------- | +| **`image`** | Destination tag qualified by the unchanged source digest. | + + From 4607697f79c215d772b4956e33067ec538a16d2b Mon Sep 17 00:00:00 2001 From: Emilien Escalle Date: Thu, 26 Nov 2026 08:14:50 +0100 Subject: [PATCH 3/5] docs: use consistent image index terminology --- .github/workflows/docker-mirror-image.md | 4 ++-- .github/workflows/docker-mirror-image.yml | 2 +- actions/docker/mirror-image/README.md | 4 ++-- actions/docker/mirror-image/action.yml | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/docker-mirror-image.md b/.github/workflows/docker-mirror-image.md index ca3f1e9d..9a441e87 100644 --- a/.github/workflows/docker-mirror-image.md +++ b/.github/workflows/docker-mirror-image.md @@ -17,7 +17,7 @@ Mirror a validated immutable image to another registry without rebuilding it. Require successful source validation or promotion through the calling job's needs. Pass a digest-qualified source and one explicit destination tag. The workflow serializes writes to that destination and returns its verified immutable reference. -It preserves image manifests and indexes, but does not copy separate signatures +It preserves image manifests and indices, but does not copy separate signatures or referrers. Source validation remains the caller's responsibility. Registry credentials are supplied as secrets. The GitHub job token is used only @@ -44,7 +44,7 @@ on: permissions: {} jobs: docker-mirror-image: - uses: hoverkraft-tech/ci-github-container/.github/workflows/docker-mirror-image.yml@e8bd81eb506404d63f0304b02ff254e5fd2f0ce5 # feat/docker-mirror-image + uses: hoverkraft-tech/ci-github-container/.github/workflows/docker-mirror-image.yml@a3584451e5b6a068b5857a940bd1901a0b203d54 # feat/docker-mirror-image permissions: contents: read packages: read diff --git a/.github/workflows/docker-mirror-image.yml b/.github/workflows/docker-mirror-image.yml index 92bd96d7..3cf81f71 100644 --- a/.github/workflows/docker-mirror-image.yml +++ b/.github/workflows/docker-mirror-image.yml @@ -2,7 +2,7 @@ # Require successful source validation or promotion through the calling job's needs. # Pass a digest-qualified source and one explicit destination tag. The workflow # serializes writes to that destination and returns its verified immutable reference. -# It preserves image manifests and indexes, but does not copy separate signatures +# It preserves image manifests and indices, but does not copy separate signatures # or referrers. Source validation remains the caller's responsibility. # # Registry credentials are supplied as secrets. The GitHub job token is used only diff --git a/actions/docker/mirror-image/README.md b/actions/docker/mirror-image/README.md index fb213420..8f998c08 100644 --- a/actions/docker/mirror-image/README.md +++ b/actions/docker/mirror-image/README.md @@ -17,7 +17,7 @@ Copy an immutable image to another registry without changing its digest. Copy an already validated image to one explicit registry tag without rebuilding. The source must include its immutable SHA-256 digest. Single-platform manifests -and multi-platform indexes retain their digest; a changed digest fails the action. +and multi-platform indices retain their digest; a changed digest fails the action. Registry signatures and referrers are not copied separately. Verify the source before calling and use the shared mirror workflow to serialize destination writes. Requires Docker and a Linux runner. Credentials are optional for local test registries. @@ -28,7 +28,7 @@ Requires Docker and a Linux runner. Credentials are optional for local test regi ## Usage ```yaml -- uses: hoverkraft-tech/ci-github-container/actions/docker/mirror-image@e8bd81eb506404d63f0304b02ff254e5fd2f0ce5 # feat/docker-mirror-image +- uses: hoverkraft-tech/ci-github-container/actions/docker/mirror-image@a3584451e5b6a068b5857a940bd1901a0b203d54 # feat/docker-mirror-image with: # Fully qualified source image including its SHA-256 digest. # This input is required. diff --git a/actions/docker/mirror-image/action.yml b/actions/docker/mirror-image/action.yml index ba84adfa..fc1bc1f5 100644 --- a/actions/docker/mirror-image/action.yml +++ b/actions/docker/mirror-image/action.yml @@ -1,6 +1,6 @@ # Copy an already validated image to one explicit registry tag without rebuilding. # The source must include its immutable SHA-256 digest. Single-platform manifests -# and multi-platform indexes retain their digest; a changed digest fails the action. +# and multi-platform indices retain their digest; a changed digest fails the action. # Registry signatures and referrers are not copied separately. Verify the source # before calling and use the shared mirror workflow to serialize destination writes. # Requires Docker and a Linux runner. Credentials are optional for local test registries. From 2518a5da86e89c9ffc661e5b8b7235eca6b905ce Mon Sep 17 00:00:00 2001 From: Emilien Escalle Date: Thu, 26 Nov 2026 09:17:39 +0100 Subject: [PATCH 4/5] feat: promote validated digests to additional destinations --- .github/workflows/__shared-ci.yml | 10 - .../__test-action-docker-mirror-image.yml | 77 ------- .../__test-action-docker-promote-images.yml | 41 ++++ ...-workflow-docker-build-images-building.yml | 50 ++++- .github/workflows/docker-mirror-image.md | 107 --------- .github/workflows/docker-mirror-image.yml | 79 ------- .github/workflows/docker-promote-images.yml | 40 +++- README.md | 4 - actions/docker/mirror-image/README.md | 77 ------- actions/docker/mirror-image/action.yml | 84 ------- actions/docker/mirror-image/package-lock.json | 13 -- actions/docker/mirror-image/package.json | 14 -- actions/docker/mirror-image/src/mirror.js | 71 ------ .../docker/mirror-image/src/mirror.test.js | 73 ------ actions/docker/promote-images/action.yml | 46 +++- .../docker/promote-images/src/destinations.js | 126 +++++++++++ .../promote-images/src/promote-images.test.js | 211 +++++++++++++++++- .../docker/promote-images/src/promotion.js | 69 ++++-- docs/README.md | 1 + .../0006-promote-validated-image-digests.md | 6 + ...0013-promote-to-additional-destinations.md | 55 +++++ tests/docker-mirror-image/fixture.mjs | 102 --------- .../registry-fixture.mjs | 193 ++++++++++++++++ 23 files changed, 810 insertions(+), 739 deletions(-) delete mode 100644 .github/workflows/__test-action-docker-mirror-image.yml delete mode 100644 .github/workflows/docker-mirror-image.md delete mode 100644 .github/workflows/docker-mirror-image.yml delete mode 100644 actions/docker/mirror-image/README.md delete mode 100644 actions/docker/mirror-image/action.yml delete mode 100644 actions/docker/mirror-image/package-lock.json delete mode 100644 actions/docker/mirror-image/package.json delete mode 100644 actions/docker/mirror-image/src/mirror.js delete mode 100644 actions/docker/mirror-image/src/mirror.test.js create mode 100644 actions/docker/promote-images/src/destinations.js create mode 100644 docs/adr/0013-promote-to-additional-destinations.md delete mode 100644 tests/docker-mirror-image/fixture.mjs create mode 100644 tests/docker-promote-images/registry-fixture.mjs diff --git a/.github/workflows/__shared-ci.yml b/.github/workflows/__shared-ci.yml index 732311f9..ee3eb81f 100644 --- a/.github/workflows/__shared-ci.yml +++ b/.github/workflows/__shared-ci.yml @@ -29,16 +29,6 @@ jobs: with: comment: false - test-action-docker-mirror-image: - needs: lint - uses: $/.github/workflows/__test-action-docker-mirror-image.yml - permissions: - contents: read - id-token: write - packages: read - pull-requests: write - security-events: write - test-action-docker-promote-images: needs: lint uses: $/.github/workflows/__test-action-docker-promote-images.yml diff --git a/.github/workflows/__test-action-docker-mirror-image.yml b/.github/workflows/__test-action-docker-mirror-image.yml deleted file mode 100644 index eea03765..00000000 --- a/.github/workflows/__test-action-docker-mirror-image.yml +++ /dev/null @@ -1,77 +0,0 @@ ---- -name: Test for "docker/mirror-image" action - -"on": - workflow_call: - -permissions: {} - -jobs: - continuous-integration: - uses: hoverkraft-tech/ci-github-nodejs/.github/workflows/continuous-integration.yml@191d7230d57982bfc11d57f68b005f386a6d7fbf # 3.1.1 - permissions: - contents: read - id-token: write - packages: read - pull-requests: write - security-events: write - with: - working-directory: actions/docker/mirror-image - build: "" - lint: "" - code-ql: '{"languages":"typescript","config-file":".github/codeql/config.yml"}' - test: '{"comment":false,"report-group":"test-action-docker-mirror-image"}' - - 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 - - id: fixture - 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'] }} - with: - script: | - const { pathToFileURL } = require('node:url'); - const { prepare } = await import(pathToFileURL(`${process.env.GITHUB_WORKSPACE}/tests/docker-mirror-image/fixture.mjs`)); - const images = await prepare(exec, process.env.RUNNER_TEMP, process.env.SOURCE_REGISTRY, process.env.DESTINATION_REGISTRY); - core.setOutput('images', images); - - id: single - uses: $/actions/docker/mirror-image - with: - source-image: ${{ fromJSON(steps.fixture.outputs.images).single.source }} - destination-image: ${{ fromJSON(steps.fixture.outputs.images).single.destination }} - - id: multi - uses: $/actions/docker/mirror-image - with: - source-image: ${{ fromJSON(steps.fixture.outputs.images).multi.source }} - destination-image: ${{ fromJSON(steps.fixture.outputs.images).multi.destination }} - - name: Verify unchanged manifests, digests and platforms - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - env: - IMAGES: ${{ steps.fixture.outputs.images }} - SINGLE: ${{ steps.single.outputs.image }} - MULTI: ${{ steps.multi.outputs.image }} - with: - script: | - const { pathToFileURL } = require('node:url'); - const { verify } = await import(pathToFileURL(`${process.env.GITHUB_WORKSPACE}/tests/docker-mirror-image/fixture.mjs`)); - await verify(exec, JSON.parse(process.env.IMAGES), { single: process.env.SINGLE, multi: process.env.MULTI }); 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-mirror-image.md b/.github/workflows/docker-mirror-image.md deleted file mode 100644 index 9a441e87..00000000 --- a/.github/workflows/docker-mirror-image.md +++ /dev/null @@ -1,107 +0,0 @@ - - -# GitHub Reusable Workflow: Docker mirror image - -
- Docker mirror image -
- ---- - - - - -## Overview - -Mirror a validated immutable image to another registry without rebuilding it. -Require successful source validation or promotion through the calling job's needs. -Pass a digest-qualified source and one explicit destination tag. The workflow -serializes writes to that destination and returns its verified immutable reference. -It preserves image manifests and indices, but does not copy separate signatures -or referrers. Source validation remains the caller's responsibility. - -Registry credentials are supplied as secrets. The GitHub job token is used only -for ghcr.io sources; other private source registries require explicit credentials. -No credentials are needed to read public source registries. An optional environment -protects registry publication. No source checkout or application build is performed. - -### Permissions - -- **`contents`**: `read` -- **`packages`**: `read` - - - - -## Usage - -```yaml -name: Docker mirror image -on: - push: - branches: - - main -permissions: {} -jobs: - docker-mirror-image: - uses: hoverkraft-tech/ci-github-container/.github/workflows/docker-mirror-image.yml@a3584451e5b6a068b5857a940bd1901a0b203d54 # feat/docker-mirror-image - permissions: - contents: read - packages: read - secrets: - # Optional private source registry username; overrides the input. - source-registry-username: "" - - # Source credential. Defaults to the job token only for ghcr.io sources. - source-registry-password: "" - - # Optional private destination registry username; overrides the input. - destination-registry-username: "" - - # Credential authorized to publish the destination image. - # This input is required. - destination-registry-password: "" - with: - # Validated source image including an immutable SHA-256 digest. - # This input is required. - source-image: "" - - # Destination registry, repository and explicit tag. - # This input is required. - destination-image: "" - - # Source registry username. Defaults to the GitHub actor for ghcr.io. - source-registry-username: "" - - # Destination registry username. Use the secret when sensitive. - destination-registry-username: "" - - # Optional GitHub environment protecting destination publication. - environment: "" -``` - - - - -## Inputs - -### Workflow Call Inputs - -| **Input** | **Description** | **Required** | **Type** | **Default** | -| ----------------------------------- | ------------------------------------------------------------------- | ------------ | ---------- | ----------- | -| **`source-image`** | Validated source image including an immutable SHA-256 digest. | **true** | **string** | - | -| **`destination-image`** | Destination registry, repository and explicit tag. | **true** | **string** | - | -| **`source-registry-username`** | Source registry username. Defaults to the GitHub actor for ghcr.io. | **false** | **string** | - | -| **`destination-registry-username`** | Destination registry username. Use the secret when sensitive. | **false** | **string** | - | -| **`environment`** | Optional GitHub environment protecting destination publication. | **false** | **string** | - | - - - - -## Outputs - -| **Output** | **Description** | -| ----------- | --------------------------------------------------------------- | -| **`image`** | Published destination qualified by the unchanged source digest. | - - diff --git a/.github/workflows/docker-mirror-image.yml b/.github/workflows/docker-mirror-image.yml deleted file mode 100644 index 3cf81f71..00000000 --- a/.github/workflows/docker-mirror-image.yml +++ /dev/null @@ -1,79 +0,0 @@ -# Mirror a validated immutable image to another registry without rebuilding it. -# Require successful source validation or promotion through the calling job's needs. -# Pass a digest-qualified source and one explicit destination tag. The workflow -# serializes writes to that destination and returns its verified immutable reference. -# It preserves image manifests and indices, but does not copy separate signatures -# or referrers. Source validation remains the caller's responsibility. -# -# Registry credentials are supplied as secrets. The GitHub job token is used only -# for ghcr.io sources; other private source registries require explicit credentials. -# No credentials are needed to read public source registries. An optional environment -# protects registry publication. No source checkout or application build is performed. ---- -name: Docker mirror image -"on": - workflow_call: - inputs: - source-image: - description: Validated source image including an immutable SHA-256 digest. - type: string - required: true - destination-image: - description: Destination registry, repository and explicit tag. - type: string - required: true - source-registry-username: - description: Source registry username. Defaults to the GitHub actor for ghcr.io. - type: string - default: "" - destination-registry-username: - description: Destination registry username. Use the secret when sensitive. - type: string - default: "" - environment: - description: Optional GitHub environment protecting destination publication. - type: string - default: "" - secrets: - source-registry-username: - description: Optional private source registry username; overrides the input. - required: false - source-registry-password: - description: Source credential. Defaults to the job token only for ghcr.io sources. - required: false - destination-registry-username: - description: Optional private destination registry username; overrides the input. - required: false - destination-registry-password: - description: Credential authorized to publish the destination image. - required: true - outputs: - image: - description: Published destination qualified by the unchanged source digest. - value: ${{ jobs.mirror.outputs.image }} -permissions: {} -jobs: - mirror: - runs-on: ubuntu-latest - timeout-minutes: 15 - environment: ${{ inputs.environment }} - concurrency: - group: image-mirror-${{ github.repository_id }}-${{ inputs.destination-image }} - cancel-in-progress: false - permissions: - contents: read - packages: read - outputs: - image: ${{ steps.mirror.outputs.image }} - steps: - - id: mirror - uses: $/actions/docker/mirror-image - with: - source-image: ${{ inputs.source-image }} - destination-image: ${{ inputs.destination-image }} - source-registry-username: >- - ${{ secrets.source-registry-username || inputs.source-registry-username || - (startsWith(inputs.source-image, 'ghcr.io/') && github.actor) || '' }} - source-registry-password: ${{ secrets.source-registry-password || (startsWith(inputs.source-image, 'ghcr.io/') && github.token) || '' }} - destination-registry-username: ${{ secrets.destination-registry-username || inputs.destination-registry-username }} - destination-registry-password: ${{ secrets.destination-registry-password }} 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/README.md b/README.md index 6e586025..3d5d3955 100644 --- a/README.md +++ b/README.md @@ -35,8 +35,6 @@ _Actions that operate on OCI images across their build, metadata, and lifecycle #### - [Get image name](actions/docker/get-image-name/README.md) -#### - [Mirror image](actions/docker/mirror-image/README.md) - #### - [Promote images](actions/docker/promote-images/README.md) #### - [Prune pull requests image tags](actions/docker/prune-pull-requests-image-tags/README.md) @@ -75,8 +73,6 @@ _Orchestrated workflows you can plug directly into repositories to automate cont ### - [Docker build images](.github/workflows/docker-build-images.md) -### - [Docker mirror image](.github/workflows/docker-mirror-image.md) - ### - [Docker promote images](.github/workflows/docker-promote-images.md) ### - [Helm chart CI](.github/workflows/helm-chart-ci.md) diff --git a/actions/docker/mirror-image/README.md b/actions/docker/mirror-image/README.md deleted file mode 100644 index 8f998c08..00000000 --- a/actions/docker/mirror-image/README.md +++ /dev/null @@ -1,77 +0,0 @@ - - -# ![Icon](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9ImN1cnJlbnRDb2xvciIgc3Ryb2tlLXdpZHRoPSIyIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiIGNsYXNzPSJmZWF0aGVyIGZlYXRoZXItY29weSIgY29sb3I9ImJsdWUiPjxyZWN0IHg9IjkiIHk9IjkiIHdpZHRoPSIxMyIgaGVpZ2h0PSIxMyIgcng9IjIiIHJ5PSIyIj48L3JlY3Q+PHBhdGggZD0iTTUgMTVINGEyIDIgMCAwIDEtMi0yVjRhMiAyIDAgMCAxIDItMmg5YTIgMiAwIDAgMSAyIDJ2MSI+PC9wYXRoPjwvc3ZnPg==) GitHub Action: Docker - Mirror image - -
- Docker - Mirror image -
- ---- - - - - -## Overview - -Copy an immutable image to another registry without changing its digest. - -Copy an already validated image to one explicit registry tag without rebuilding. -The source must include its immutable SHA-256 digest. Single-platform manifests -and multi-platform indices retain their digest; a changed digest fails the action. -Registry signatures and referrers are not copied separately. Verify the source -before calling and use the shared mirror workflow to serialize destination writes. -Requires Docker and a Linux runner. Credentials are optional for local test registries. - - - - -## Usage - -```yaml -- uses: hoverkraft-tech/ci-github-container/actions/docker/mirror-image@a3584451e5b6a068b5857a940bd1901a0b203d54 # feat/docker-mirror-image - with: - # Fully qualified source image including its SHA-256 digest. - # This input is required. - source-image: "" - - # Fully qualified destination image with an explicit tag. - # This input is required. - destination-image: "" - - # Source registry username, paired with its password. - source-registry-username: "" - - # Source registry password or token. Empty skips authentication. - source-registry-password: "" - - # Destination registry username, paired with its password. - destination-registry-username: "" - - # Destination registry password or token. Empty skips authentication. - destination-registry-password: "" -``` - - - - -## Inputs - -| **Input** | **Description** | **Required** | **Default** | -| ----------------------------------- | ------------------------------------------------------------------- | ------------ | ----------- | -| **`source-image`** | Fully qualified source image including its SHA-256 digest. | **true** | - | -| **`destination-image`** | Fully qualified destination image with an explicit tag. | **true** | - | -| **`source-registry-username`** | Source registry username, paired with its password. | **false** | - | -| **`source-registry-password`** | Source registry password or token. Empty skips authentication. | **false** | - | -| **`destination-registry-username`** | Destination registry username, paired with its password. | **false** | - | -| **`destination-registry-password`** | Destination registry password or token. Empty skips authentication. | **false** | - | - - - - -## Outputs - -| **Output** | **Description** | -| ----------- | --------------------------------------------------------- | -| **`image`** | Destination tag qualified by the unchanged source digest. | - - diff --git a/actions/docker/mirror-image/action.yml b/actions/docker/mirror-image/action.yml deleted file mode 100644 index fc1bc1f5..00000000 --- a/actions/docker/mirror-image/action.yml +++ /dev/null @@ -1,84 +0,0 @@ -# Copy an already validated image to one explicit registry tag without rebuilding. -# The source must include its immutable SHA-256 digest. Single-platform manifests -# and multi-platform indices retain their digest; a changed digest fails the action. -# Registry signatures and referrers are not copied separately. Verify the source -# before calling and use the shared mirror workflow to serialize destination writes. -# Requires Docker and a Linux runner. Credentials are optional for local test registries. ---- -name: Docker - Mirror image -description: Copy an immutable image to another registry without changing its digest. -author: hoverkraft -branding: - icon: copy - color: blue -inputs: - source-image: - description: Fully qualified source image including its SHA-256 digest. - required: true - destination-image: - description: Fully qualified destination image with an explicit tag. - required: true - source-registry-username: - description: Source registry username, paired with its password. - default: "" - source-registry-password: - description: Source registry password or token. Empty skips authentication. - default: "" - destination-registry-username: - description: Destination registry username, paired with its password. - default: "" - destination-registry-password: - description: Destination registry password or token. Empty skips authentication. - default: "" -outputs: - image: - description: Destination tag qualified by the unchanged source digest. - value: ${{ steps.copy.outputs.image }} -runs: - using: composite - steps: - - name: Validate immutable source and tagged destination - id: references - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - env: - ACTION_PATH: ${{ github.action_path }} - SOURCE: ${{ inputs.source-image }} - DESTINATION: ${{ inputs.destination-image }} - with: - script: | - const { pathToFileURL } = require('node:url'); - const { ImageMirror } = await import(pathToFileURL(`${process.env.ACTION_PATH}/src/mirror.js`)); - const mirror = new ImageMirror(process.env.SOURCE, process.env.DESTINATION); - core.setOutput('source-registry', mirror.sourceRegistry); - core.setOutput('destination-registry', mirror.destinationRegistry); - - name: Authenticate to the source registry - if: inputs.source-registry-password != '' - uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 - with: - registry: ${{ steps.references.outputs.source-registry }} - username: ${{ inputs.source-registry-username }} - password: ${{ inputs.source-registry-password }} - - name: Authenticate to the destination registry - if: inputs.destination-registry-password != '' - uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 - with: - registry: ${{ steps.references.outputs.destination-registry }} - username: ${{ inputs.destination-registry-username }} - password: ${{ inputs.destination-registry-password }} - - name: Set up registry tooling - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 - with: - driver: docker - - name: Copy the retained manifest and layers - id: copy - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - env: - ACTION_PATH: ${{ github.action_path }} - SOURCE: ${{ inputs.source-image }} - DESTINATION: ${{ inputs.destination-image }} - with: - script: | - const { pathToFileURL } = require('node:url'); - const { ImageMirror } = await import(pathToFileURL(`${process.env.ACTION_PATH}/src/mirror.js`)); - const image = await new ImageMirror(process.env.SOURCE, process.env.DESTINATION).copy(exec, process.env.RUNNER_TEMP); - core.setOutput('image', image); diff --git a/actions/docker/mirror-image/package-lock.json b/actions/docker/mirror-image/package-lock.json deleted file mode 100644 index 0a061d16..00000000 --- a/actions/docker/mirror-image/package-lock.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name": "mirror-image", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "mirror-image", - "engines": { - "node": ">=24.0.0" - } - } - } -} diff --git a/actions/docker/mirror-image/package.json b/actions/docker/mirror-image/package.json deleted file mode 100644 index 40b02087..00000000 --- a/actions/docker/mirror-image/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "mirror-image", - "private": true, - "type": "module", - "engines": { - "node": ">=24.0.0" - }, - "scripts": { - "test": "node --test", - "test:watch": "node --test --watch", - "pretest:ci": "node -e \"require('node:fs').mkdirSync('coverage', { recursive: true })\"", - "test:ci": "node --experimental-test-coverage --test-reporter=spec --test-reporter-destination=stdout --test-reporter=junit --test-reporter-destination=coverage/junit.xml --test-reporter=lcov --test-reporter-destination=coverage/lcov.info --test" - } -} diff --git a/actions/docker/mirror-image/src/mirror.js b/actions/docker/mirror-image/src/mirror.js deleted file mode 100644 index 4d8fa6b7..00000000 --- a/actions/docker/mirror-image/src/mirror.js +++ /dev/null @@ -1,71 +0,0 @@ -import assert from "node:assert/strict"; -import fs from "node:fs/promises"; -import path from "node:path"; - -class ImageMirror { - constructor(source, destination) { - const pattern = - /^(?[a-z0-9]+(?:[.-][a-z0-9]+)*(?::[0-9]+)?)(?(?:\/[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*)+)(?::(?[\w][\w.-]{0,127}))?(?:@(?sha256:[a-f0-9]{64}))?$/; - const parse = (value) => { - assert.equal(typeof value, "string", "Image references must be strings"); - assert.equal( - value, - value.trim(), - "Image references must not contain surrounding whitespace", - ); - const match = value.match(pattern); - assert(match, "Expected an explicit OCI image reference"); - const { registry } = match.groups; - assert( - registry.includes(".") || - registry.includes(":") || - registry === "localhost", - "Image references require an explicit registry", - ); - return match.groups; - }; - const from = parse(source); - const to = parse(destination); - assert(from.digest, "The source image must be pinned by digest"); - assert( - to.tag && !to.digest, - "The destination image must have an explicit tag and no digest", - ); - this.source = `${from.registry}${from.repository}@${from.digest}`; - this.destination = destination; - this.sourceRegistry = from.registry; - this.destinationRegistry = to.registry; - this.digest = from.digest; - } - - async copy(exec, temporaryRoot) { - const directory = await fs.mkdtemp( - path.join(temporaryRoot, "mirror-image-"), - ); - const metadata = path.join(directory, "result.json"); - try { - await exec.exec("docker", [ - "buildx", - "imagetools", - "create", - "--prefer-index=false", - "--metadata-file", - metadata, - "--tag", - this.destination, - this.source, - ]); - const result = JSON.parse(await fs.readFile(metadata, "utf8")); - assert.equal( - result["containerimage.descriptor"]?.digest, - this.digest, - "Mirrored digest differs from the source digest", - ); - return `${this.destination}@${this.digest}`; - } finally { - await fs.rm(directory, { recursive: true, force: true }); - } - } -} - -export { ImageMirror }; diff --git a/actions/docker/mirror-image/src/mirror.test.js b/actions/docker/mirror-image/src/mirror.test.js deleted file mode 100644 index 4e31dc95..00000000 --- a/actions/docker/mirror-image/src/mirror.test.js +++ /dev/null @@ -1,73 +0,0 @@ -import assert from "node:assert/strict"; -import fs from "node:fs/promises"; -import os from "node:os"; -import path from "node:path"; -import test from "node:test"; -import { ImageMirror } from "./mirror.js"; - -const digest = `sha256:${"a".repeat(64)}`; -const source = `ghcr.io/example/app:validated@${digest}`; -const destination = "docker.io/example/app:1.2.3"; - -test("mirroring requires an immutable source and an explicit registry tag", () => { - const mirror = new ImageMirror(source, destination); - assert.equal(mirror.source, `ghcr.io/example/app@${digest}`); - assert.equal(mirror.sourceRegistry, "ghcr.io"); - assert.equal(mirror.destinationRegistry, "docker.io"); - for (const invalid of [ - "ghcr.io/example/app:latest", - `example/app@${digest}`, - "--help", - `${source}\nextra`, - `${source}\n`, - ]) { - assert.throws(() => new ImageMirror(invalid, destination)); - } - for (const invalid of [ - "docker.io/example/app", - source, - "example/app:latest", - "docker.io/example/app:bad tag", - `${destination}\n`, - ]) { - assert.throws(() => new ImageMirror(source, invalid)); - } -}); - -test("mirroring reports the unchanged digest and cleans its metadata", async (t) => { - const root = await fs.mkdtemp(path.join(os.tmpdir(), "mirror-contract-")); - t.after(() => fs.rm(root, { recursive: true, force: true })); - const mirror = new ImageMirror(source, destination); - const execute = (publishedDigest) => ({ - exec: async (_command, args) => { - await fs.writeFile( - args[args.indexOf("--metadata-file") + 1], - JSON.stringify({ - "containerimage.descriptor": { digest: publishedDigest }, - }), - ); - }, - }); - assert.equal( - await mirror.copy(execute(digest), root), - `${destination}@${digest}`, - ); - assert.deepEqual(await fs.readdir(root), []); - await assert.rejects( - mirror.copy(execute(`sha256:${"b".repeat(64)}`), root), - /Mirrored digest differs/, - ); - assert.deepEqual(await fs.readdir(root), []); - await assert.rejects( - mirror.copy( - { - exec: async () => { - throw new Error("denied"); - }, - }, - root, - ), - /denied/, - ); - assert.deepEqual(await fs.readdir(root), []); -}); 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-mirror-image/fixture.mjs b/tests/docker-mirror-image/fixture.mjs deleted file mode 100644 index 3f5711b6..00000000 --- a/tests/docker-mirror-image/fixture.mjs +++ /dev/null @@ -1,102 +0,0 @@ -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, "mirror-fixture-")); - const source = `${sourceRegistry}/mirror-test`; - try { - await fs.writeFile( - path.join(context, "Dockerfile"), - "FROM scratch\nCOPY payload /payload\n", - ); - await fs.writeFile( - path.join(context, "payload"), - "immutable image mirror 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}$/); - images[name] = { - source: `${source}:${tag}@${digest}`, - destination: `${destinationRegistry}/mirror-test:${name}`, - }; - } - return images; - } finally { - await fs.rm(context, { recursive: true, force: true }); - } -} - -export async function verify(exec, images, outputs) { - for (const [name, { source, destination }] of Object.entries(images)) { - const digest = source.split("@")[1]; - assert.equal(outputs[name], `${destination}@${digest}`); - 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", - ); - } - } -} 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", + ); + } + } +} From c9feed706862fc88f0fd33d287e6d6c12e738f74 Mon Sep 17 00:00:00 2001 From: Emilien Escalle Date: Thu, 26 Nov 2026 09:21:39 +0100 Subject: [PATCH 5/5] docs: regenerate promotion workflow and action references --- .github/workflows/docker-promote-images.md | 60 ++++++++++++++++------ actions/docker/promote-images/README.md | 35 ++++++++----- 2 files changed, 67 insertions(+), 28 deletions(-) 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/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