diff --git a/.github/workflows/docker-merge-group.yml b/.github/workflows/docker-merge-group.yml index d04db07ceb9..cefaa46d0c4 100644 --- a/.github/workflows/docker-merge-group.yml +++ b/.github/workflows/docker-merge-group.yml @@ -6,7 +6,7 @@ name: Docker merge-queue build # commit, docker.yml pushes these exact bytes (scripts/merge-group-image.mjs) # instead of rebuilding them. Without a matching successful run, docker.yml # builds from source as before. Nothing here can publish: this workflow has no -# registry credentials, no secrets, and read-only contents access. +# registry credentials, no secrets, and read-only access. # # Inert until the merge queue is enabled for master: no merge_group event fires # before then. @@ -28,9 +28,88 @@ jobs: contents: read actions: read + runner_image: + name: Resolve the Runner image of this commit + if: vars.RUNNER_IMAGE_CONSUME_ENABLED == 'true' && github.repository == 'paperclipai/paperclip' && github.repository_id == '1170821064' && github.event.merge_group.base_ref == 'refs/heads/master' + continue-on-error: true + runs-on: ubuntu-latest + timeout-minutes: 20 + permissions: + contents: read + actions: read + attestations: read + outputs: + mode: ${{ steps.verify.outputs.mode || 'inline' }} + inputs_digest: ${{ steps.verify.outputs.inputs_digest }} + build_contexts: ${{ steps.verify.outputs.build_contexts }} + labels: ${{ steps.verify.outputs.labels }} + build_args: ${{ steps.verify.outputs.build_args }} + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + persist-credentials: false + + - name: Setup pnpm + uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6 + with: + version: 9.15.4 + run_install: false + + - name: Setup Node.js + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7 + with: + node-version: 24 + package-manager-cache: false + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@37fe631027851001ddb9b187196cc803df7f5f0e # v4 + with: + buildkitd-config-inline: | + [registry."docker.io"] + mirrors = ["mirror.gcr.io"] + + - name: Compute the Runner inputs of this commit + timeout-minutes: 5 + run: node scripts/runner-image-resolve.mjs inputs --dir "$RUNNER_TEMP/runner-image-resolve" + + - name: Find the published Runner image of these inputs + id: resolve + timeout-minutes: 5 + run: node scripts/runner-image-resolve.mjs resolve --dir "$RUNNER_TEMP/runner-image-resolve" + + - name: Verify the attestation of the Runner image + id: verify + if: steps.resolve.outputs.mode == 'published' + timeout-minutes: 5 + env: + GH_TOKEN: ${{ github.token }} + IMAGE: ${{ steps.resolve.outputs.image }} + INPUTS_DIGEST: ${{ steps.resolve.outputs.inputs_digest }} + LABELS: ${{ steps.resolve.outputs.labels }} + BUILD_ARGS: ${{ steps.resolve.outputs.build_args }} + run: | + set -euo pipefail + if ! gh attestation verify "oci://$IMAGE" \ + --repo paperclipai/paperclip \ + --signer-workflow paperclipai/paperclip/.github/workflows/runner-image.yml \ + --source-ref refs/heads/master; then + echo "::warning title=Runner image not verified::The attestation of $IMAGE did not verify. The image build makes its own Runner." + exit 1 + fi + { + echo "mode=published" + echo "inputs_digest=$INPUTS_DIGEST" + echo "build_contexts=runner-artifacts=docker-image://$IMAGE" + echo "build_args=$BUILD_ARGS" + echo "labels<> "$GITHUB_OUTPUT" + build: - needs: macos_runner_runtime - if: github.repository == 'paperclipai/paperclip' && github.repository_id == '1170821064' && github.event.merge_group.base_ref == 'refs/heads/master' + needs: [macos_runner_runtime, runner_image] + if: ${{ !cancelled() && needs.macos_runner_runtime.result == 'success' && github.repository == 'paperclipai/paperclip' && github.repository_id == '1170821064' && github.event.merge_group.base_ref == 'refs/heads/master' }} strategy: fail-fast: false matrix: @@ -42,8 +121,10 @@ jobs: runner: ubuntu-24.04-arm arch: arm64 # GitHub-hosted runners: the protected release fleets admit only - # docker.yml on master. - runs-on: ${{ matrix.runner }} + # docker.yml on master. amd64 merge-queue builds for canonical master use + # the larger GitHub-hosted runner (cloud-release-32) so pre-merge builds + # finish quickly while commits wait in the queue. + runs-on: ${{ matrix.arch == 'amd64' && (vars.CORE_PUBLICATION_RUNNER || 'cloud-release-32') || matrix.runner }} timeout-minutes: 60 permissions: contents: read @@ -88,6 +169,7 @@ jobs: node-version: 24 - name: Refresh lockfile for Docker build context + if: needs.runner_image.outputs.mode != 'published' run: | set -euo pipefail pnpm install --resolution-only --ignore-scripts --no-frozen-lockfile @@ -101,11 +183,31 @@ jobs: - name: Free runner disk run: | set -euo pipefail - pnpm store prune || true - sudo apt-get clean || true - sudo rm -rf /usr/share/dotnet /usr/share/swift /usr/local/lib/android /usr/local/share/boost \ - /usr/local/share/powershell /opt/ghc /opt/hostedtoolcache/CodeQL /opt/hostedtoolcache/PyPy /opt/hostedtoolcache/Ruby || true - docker system prune -af || true + avail_kb="$(df -Pk / | awk 'NR==2 {print $4}')" + if [ "${avail_kb:-0}" -ge 52428800 ]; then + echo "Root filesystem already has >= 50 GiB free; skipping cleanup." + df -h + exit 0 + fi + pids=() + (pnpm store prune || true) & pids+=("$!") + (sudo apt-get clean || true) & pids+=("$!") + (docker system prune -af || true) & pids+=("$!") + for dir in \ + /usr/share/dotnet \ + /usr/share/swift \ + /usr/local/lib/android \ + /usr/local/share/boost \ + /usr/local/share/powershell \ + /opt/ghc \ + /opt/hostedtoolcache/CodeQL \ + /opt/hostedtoolcache/PyPy \ + /opt/hostedtoolcache/Ruby; do + (sudo rm -rf "$dir" || true) & pids+=("$!") + done + for pid in "${pids[@]}"; do + wait "$pid" || true + done df -h - name: Set up Docker Buildx @@ -148,11 +250,15 @@ jobs: PAPERCLIP_BUILD_COMMIT=${{ github.sha }} PAPERCLIP_MACOS_RUNTIME_INPUTS_DIGEST=${{ needs.macos_runner_runtime.outputs.inputs_digest }} CLI_TOOLS_CACHE_EPOCH=${{ steps.tools-epoch.outputs.epoch }} + ${{ needs.runner_image.outputs.build_args }} + build-contexts: ${{ needs.runner_image.outputs.build_contexts }} platforms: ${{ matrix.platform }} push: false outputs: type=oci,dest=${{ runner.temp }}/merge-group-image/image.tar,name=paperclip-merge-group:${{ matrix.arch }} cache-from: type=registry,ref=ghcr.io/${{ github.repository }}:buildcache-${{ matrix.arch }} - labels: ${{ steps.meta.outputs.labels }} + labels: | + ${{ steps.meta.outputs.labels }} + ${{ needs.runner_image.outputs.labels }} # PID 1 must be an init that reaps adopted orphans; see docker.yml. - name: Verify PID 1 reaps orphaned processes @@ -168,7 +274,16 @@ jobs: # Written only after the probe passes. Promotion trusts nothing without it. - name: Record the verified image - run: node scripts/merge-group-image.mjs record --arch "${{ matrix.arch }}" --archive "${{ runner.temp }}/merge-group-image/image.tar" --out "${{ runner.temp }}/merge-group-image/record.json" + env: + ARCH: ${{ matrix.arch }} + RUNNER_INPUTS_DIGEST: ${{ needs.runner_image.outputs.inputs_digest }} + run: | + set -euo pipefail + node scripts/merge-group-image.mjs record \ + --arch "$ARCH" \ + --archive "$RUNNER_TEMP/merge-group-image/image.tar" \ + --out "$RUNNER_TEMP/merge-group-image/record.json" \ + --runner-inputs-digest "$RUNNER_INPUTS_DIGEST" - name: Upload the verified image uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index c78abd73b47..014e35f1589 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -51,6 +51,7 @@ jobs: attestations: read outputs: mode: ${{ steps.verify.outputs.mode || 'inline' }} + inputs_digest: ${{ steps.verify.outputs.inputs_digest }} build_contexts: ${{ steps.verify.outputs.build_contexts }} labels: ${{ steps.verify.outputs.labels }} build_args: ${{ steps.verify.outputs.build_args }} @@ -104,6 +105,7 @@ jobs: env: GH_TOKEN: ${{ github.token }} IMAGE: ${{ steps.resolve.outputs.image }} + INPUTS_DIGEST: ${{ steps.resolve.outputs.inputs_digest }} LABELS: ${{ steps.resolve.outputs.labels }} BUILD_ARGS: ${{ steps.resolve.outputs.build_args }} run: | @@ -118,6 +120,7 @@ jobs: fi { echo "mode=published" + echo "inputs_digest=$INPUTS_DIGEST" echo "build_contexts=runner-artifacts=docker-image://$IMAGE" echo "build_args=$BUILD_ARGS" echo "labels< "$trusted" # Verify without writing a step output: the digest is set only after # the exact bytes are in the registry. - verified="$(GITHUB_OUTPUT='' node "$trusted" verify --arch "$ARCH" --dir "$DIRECTORY" --since "$BEFORE")" + verified="$(GITHUB_OUTPUT='' node "$trusted" verify --arch "$ARCH" --dir "$DIRECTORY" --since "$BEFORE" --runner-inputs-digest "$RUNNER_INPUTS_DIGEST")" digest="$(printf '%s\n' "$verified" | sed -n 's/^digest=//p')" printf '%s' "$digest" | grep -Eq '^sha256:[a-f0-9]{64}$' # --preserve-digests fails rather than re-encode, so the registry diff --git a/scripts/merge-group-image.mjs b/scripts/merge-group-image.mjs index 93ebf0bc022..1d610bb7857 100644 --- a/scripts/merge-group-image.mjs +++ b/scripts/merge-group-image.mjs @@ -22,10 +22,12 @@ const architectures = ["amd64", "arm64"]; const indexTypes = ["application/vnd.oci.image.index.v1+json", "application/vnd.docker.distribution.manifest.list.v2+json"]; const manifestTypes = ["application/vnd.oci.image.manifest.v1+json", "application/vnd.docker.distribution.manifest.v2+json"]; // How long a master push waits for a merge-queue build that is still running. -// A build takes about 12 minutes and the exact-source gate about 14. -const findWaitMs = 15 * 60_000; -const findPollMs = 20_000; +// Capped at 3 minutes so a master push on a fast AWS runner falls back to +// building from source instead of stalling behind a slower merge-group leg. +const findWaitMs = 3 * 60_000; +const findPollMs = 15_000; const fullSha = /^[a-f0-9]{40}$/; +const hex64 = /^[a-f0-9]{64}$/; const digestPattern = /^sha256:[a-f0-9]{64}$/; const sha256 = bytes => `sha256:${createHash("sha256").update(bytes).digest("hex")}`; @@ -92,20 +94,31 @@ export function archiveImageDigest({ readEntry, arch }) { } /** What the merge-group build attests about the archive it uploads. */ -export function createRecord({ sha, tree, arch, digest }) { +export function createRecord({ sha, tree, arch, digest, runnerInputsDigest = "" }) { assert.match(sha ?? "", fullSha); assert.match(tree ?? "", fullSha); assert.ok(architectures.includes(arch)); assert.match(digest ?? "", digestPattern); - return { schema: recordSchema, repository, sha, tree, arch, digest }; + assert.ok(runnerInputsDigest === "" || hex64.test(runnerInputsDigest), "runnerInputsDigest must be empty or 64 lowercase hex characters"); + return { + schema: recordSchema, + repository, + sha, + tree, + arch, + digest, + ...(runnerInputsDigest ? { runnerInputsDigest } : {}), + }; } /** * Prove the archive is the build of the tree this master push publishes. The * commit SHA covers its tree; the tree is compared too, so a record can never - * vouch for different content under a reused name. + * vouch for different content under a reused name. When master resolved a + * published Runner image, the merge-group record must name the exact same + * Runner inputs digest (and vice versa for inline builds). */ -export function verifyRecord({ record, sha, tree, arch, archiveDigest }) { +export function verifyRecord({ record, sha, tree, arch, archiveDigest, runnerInputsDigest = "" }) { assert.equal(record?.schema, recordSchema, "Unknown merge-group image record"); assert.equal(record.repository, repository); assert.equal(record.sha, sha, "The merge-group build is for a different commit"); @@ -113,6 +126,12 @@ export function verifyRecord({ record, sha, tree, arch, archiveDigest }) { assert.equal(record.arch, arch, "The merge-group build is for a different architecture"); assert.match(record.digest ?? "", digestPattern); assert.equal(archiveDigest, record.digest, "The archive is not the image the merge-group build recorded"); + assert.ok(runnerInputsDigest === "" || hex64.test(runnerInputsDigest), "runnerInputsDigest must be empty or 64 lowercase hex characters"); + assert.equal( + record.runnerInputsDigest ?? "", + runnerInputsDigest, + "The merge-group build used a different Runner image than master resolved", + ); return record.digest; } @@ -124,7 +143,21 @@ export function verifyRecord({ record, sha, tree, arch, archiveDigest }) { * check from the copy of this script in the push's `before` commit, so a push * cannot remove the check it is subject to. */ -export const pipelineFiles = [workflowPath, ".github/workflows/docker.yml", ".github/workflows/macos-runner-runtime.yml", "scripts/macos-runner-runtime.mjs", "scripts/macos-runner-runtime-cache.mjs", "scripts/merge-group-image.mjs", "scripts/assert-orphan-reaping.sh"]; +export const pipelineFiles = [ + workflowPath, + ".github/workflows/docker.yml", + ".github/workflows/macos-runner-runtime.yml", + "scripts/macos-runner-runtime.mjs", + "scripts/macos-runner-runtime-cache.mjs", + "scripts/runner-image-resolve.mjs", + "scripts/runner-image-publish.mjs", + "scripts/runner-image-identity.mjs", + "scripts/runner-image-layout.mjs", + "scripts/runner-image-oci.mjs", + "scripts/standard-image-contract.mjs", + "scripts/merge-group-image.mjs", + "scripts/assert-orphan-reaping.sh", +]; export function assertPipelineUnchanged(changedFiles) { const changed = changedFiles.filter(file => pipelineFiles.includes(file)); @@ -146,6 +179,12 @@ const option = name => { assert.ok(value, `--${name} is required`); return value; }; +const optionalOption = name => { + const index = process.argv.indexOf(`--${name}`); + if (index <= 0) return ""; + const value = process.argv[index + 1]; + return value === undefined || value.startsWith("--") ? "" : value; +}; const output = async (key, value) => { if (process.env.GITHUB_OUTPUT) await appendFile(process.env.GITHUB_OUTPUT, `${key}=${value}\n`); console.log(`${key}=${value}`); @@ -158,7 +197,8 @@ async function main(command) { // Runs in the credential-free merge-group build. assert.equal(process.env.GITHUB_EVENT_NAME, "merge_group", "Records are written only by merge-group builds"); const digest = archiveImageDigest({ readEntry: tarReader(option("archive")), arch }); - await writeFile(option("out"), `${JSON.stringify(createRecord({ sha, tree: gitTree(), arch, digest }), null, 2)}\n`); + const runnerInputsDigest = optionalOption("runner-inputs-digest"); + await writeFile(option("out"), `${JSON.stringify(createRecord({ sha, tree: gitTree(), arch, digest, runnerInputsDigest }), null, 2)}\n`); return output("digest", digest); } assert.ok(process.env.GITHUB_REPOSITORY === repository && process.env.GITHUB_REF === "refs/heads/master" && @@ -173,8 +213,8 @@ async function main(command) { return response.json(); }; // Publication waits for the exact-source gate in any case, so waiting here - // for an unfinished build costs nothing while the build is the shorter of - // the two. Past the deadline the push builds from source. + // briefly for an almost-finished build costs nothing; past the deadline the + // push builds from source. const deadline = Date.now() + findWaitMs; let run; for (;;) { @@ -195,7 +235,8 @@ async function main(command) { assertPipelineUnchanged(changedSince(option("since"))); const record = JSON.parse(await readFile(`${directory}/record.json`, "utf8")); const archiveDigest = archiveImageDigest({ readEntry: tarReader(`${directory}/image.tar`), arch }); - return output("digest", verifyRecord({ record, sha, tree: gitTree(), arch, archiveDigest })); + const runnerInputsDigest = optionalOption("runner-inputs-digest"); + return output("digest", verifyRecord({ record, sha, tree: gitTree(), arch, archiveDigest, runnerInputsDigest })); } throw new Error(`Unknown command: ${command}`); } diff --git a/scripts/merge-group-image.test.mjs b/scripts/merge-group-image.test.mjs index 1f9cf3930a7..89c3f537e92 100644 --- a/scripts/merge-group-image.test.mjs +++ b/scripts/merge-group-image.test.mjs @@ -96,10 +96,16 @@ test("reads a real tar archive through the system tar", () => { } finally { rmSync(directory, { recursive: true, force: true }); } }); -test("promotion proves commit, tree, architecture and archive digest", () => { +test("promotion proves commit, tree, architecture, Runner inputs digest and archive digest", () => { const digest = `sha256:${"e".repeat(64)}`; + const runnerInputsDigest = "1".repeat(64); const record = createRecord({ sha, tree, arch: "amd64", digest }); assert.equal(verifyRecord({ record, sha, tree, arch: "amd64", archiveDigest: digest }), digest); + const publishedRecord = createRecord({ sha, tree, arch: "amd64", digest, runnerInputsDigest }); + assert.equal(verifyRecord({ record: publishedRecord, sha, tree, arch: "amd64", archiveDigest: digest, runnerInputsDigest }), digest); + assert.throws(() => verifyRecord({ record: publishedRecord, sha, tree, arch: "amd64", archiveDigest: digest, runnerInputsDigest: "" }), /different Runner image/); + assert.throws(() => verifyRecord({ record, sha, tree, arch: "amd64", archiveDigest: digest, runnerInputsDigest }), /different Runner image/); + assert.throws(() => verifyRecord({ record: publishedRecord, sha, tree, arch: "amd64", archiveDigest: digest, runnerInputsDigest: "2".repeat(64) }), /different Runner image/); for (const [change, pattern] of [ [{ sha: "f".repeat(40) }, /different commit/], [{ tree: "f".repeat(40) }, /different tree/], @@ -113,8 +119,19 @@ test("promotion proves commit, tree, architecture and archive digest", () => { test("a push that changes the merge-group pipeline is built from source, not promoted", () => { assert.doesNotThrow(() => assertPipelineUnchanged([])); - assert.doesNotThrow(() => assertPipelineUnchanged(["Dockerfile", "server/src/index.ts", "scripts/standard-image-contract.mjs"])); - for (const file of [".github/workflows/docker-merge-group.yml", ".github/workflows/docker.yml", "scripts/merge-group-image.mjs", "scripts/assert-orphan-reaping.sh"]) { + assert.doesNotThrow(() => assertPipelineUnchanged(["Dockerfile", "server/src/index.ts"])); + for (const file of [ + ".github/workflows/docker-merge-group.yml", + ".github/workflows/docker.yml", + "scripts/runner-image-resolve.mjs", + "scripts/runner-image-publish.mjs", + "scripts/runner-image-identity.mjs", + "scripts/runner-image-layout.mjs", + "scripts/runner-image-oci.mjs", + "scripts/standard-image-contract.mjs", + "scripts/merge-group-image.mjs", + "scripts/assert-orphan-reaping.sh", + ]) { assert.throws(() => assertPipelineUnchanged(["server/src/index.ts", file]), /changes the merge-group image pipeline/, file); } }); @@ -162,7 +179,7 @@ test("the CLI refuses to record outside a merge group or promote outside a canon ]) for (const command of ["find", "verify"]) assert.match(run(command, env), /only for canonical master pushes/); }); -test("the merge-queue build has no publishing credentials or paid infrastructure", () => { +test("the merge-queue build has no publishing credentials or AWS release fleet access", () => { const workflow = readFileSync(path.join(root, ".github", "workflows", "docker-merge-group.yml"), "utf8"); const triggers = workflow.split("\non:\n")[1].split("\n\n")[0]; assert.equal(triggers.trim(), "merge_group:", "only the merge queue triggers this build"); @@ -170,9 +187,9 @@ test("the merge-queue build has no publishing credentials or paid infrastructure const permissions = [...workflow.matchAll(/^ permissions:\n((?: {6}.+\n)+)/gm)].map(match => match[1].trim()); assert.ok(permissions.length > 0); for (const block of permissions) { - assert.ok(block.split("\n").map(line => line.trim()).every(line => /^(contents|actions): read$/.test(line))); + assert.ok(block.split("\n").map(line => line.trim()).every(line => /^(contents|actions|attestations): read$/.test(line))); } - assert.doesNotMatch(workflow, /secrets\.|packages: write|id-token|attestations|docker\/login-action|cache-to:|push: true|environment:|runs-on\//); + assert.doesNotMatch(workflow, /secrets\.|packages: write|id-token|attestations: write|docker\/login-action|cache-to:|push: true|environment:|runs-on\//); assert.doesNotMatch(workflow, /pull_request_target|workflow_run|workflow_dispatch/); assert.match(workflow, /persist-credentials: false/); assert.match(workflow, /github\.event\.merge_group\.base_ref == 'refs\/heads\/master'/); @@ -190,7 +207,7 @@ test("master promotes only after proof and otherwise builds exactly as before", const step = name => { const found = steps.find(item => item.startsWith(` - name: ${name}\n`)); assert.ok(found, name); return found; }; const order = name => steps.indexOf(step(name)); assert.match(step("Find the merge-queue build of this commit"), - /if: needs.runner_image.outputs.mode != 'published' && github.repository == 'paperclipai\/paperclip' && github.repository_id == '1170821064' && github.event_name == 'push' && github.ref == 'refs\/heads\/master'/); + /if: github.repository == 'paperclipai\/paperclip' && github.repository_id == '1170821064' && github.event_name == 'push' && github.ref == 'refs\/heads\/master'/); for (const name of ["Find the merge-queue build of this commit", "Download the merge-queue image", "Promote the merge-queue image"]) { assert.match(step(name), /continue-on-error: true/, `${name} must fall back to the build`); } @@ -202,7 +219,7 @@ test("master promotes only after proof and otherwise builds exactly as before", assert.match(step(name), /git show "\$BEFORE:scripts\/merge-group-image.mjs" > "\$trusted"/); assert.doesNotMatch(step(name), /node scripts\/merge-group-image\.mjs/); } - assert.match(promote, /node "\$trusted" verify --arch "\$ARCH" --dir "\$DIRECTORY" --since "\$BEFORE"/); + assert.match(promote, /node "\$trusted" verify --arch "\$ARCH" --dir "\$DIRECTORY" --since "\$BEFORE" --runner-inputs-digest "\$RUNNER_INPUTS_DIGEST"/); assert.ok(promote.indexOf('"$trusted" verify') < promote.indexOf("skopeo copy")); assert.ok(promote.indexOf("skopeo copy --all --preserve-digests") < promote.indexOf('echo "digest=$digest" >> "$GITHUB_OUTPUT"'), "the promoted digest becomes an output only after the exact bytes are pushed"); diff --git a/server/src/__tests__/docker-build-stamp.test.ts b/server/src/__tests__/docker-build-stamp.test.ts index e3cc4544a04..fb0a4906458 100644 --- a/server/src/__tests__/docker-build-stamp.test.ts +++ b/server/src/__tests__/docker-build-stamp.test.ts @@ -175,9 +175,10 @@ describe("Application image Runner", () => { for (const [name, source] of [["standard", workflow], ["preview", previewWorkflow], ["merge group", mergeGroupWorkflow], ["pull request", appCheckWorkflow]]) { expect(source, name).toContain("PAPERCLIP_BUILD_COMMIT="); expect(source, name).not.toMatch(/PAPERCLIP_RUNNER_(?:SOURCE_REVISION|IMAGE_PUBLICATION)/); - if (name !== "standard") expect(source, name).not.toMatch(/runner-artifacts|build-contexts?\b/); + if (name !== "standard" && name !== "merge group") expect(source, name).not.toMatch(/runner-artifacts|build-contexts?\b/); } expect(workflow.match(/runner-artifacts|build-contexts?\b/g)).toEqual(["runner-artifacts", "build-contexts"]); + expect(mergeGroupWorkflow.match(/runner-artifacts|build-contexts?\b/g)).toEqual(["runner-artifacts", "build-contexts"]); }); }); diff --git a/server/src/__tests__/docker-runner-workflows.test.ts b/server/src/__tests__/docker-runner-workflows.test.ts index 3cee2b4aa7f..4d8ea887652 100644 --- a/server/src/__tests__/docker-runner-workflows.test.ts +++ b/server/src/__tests__/docker-runner-workflows.test.ts @@ -81,7 +81,7 @@ const IMAGE = `ghcr.io/paperclipai/paperclip-runner@sha256:${"c".repeat(64)}`; const INPUTS = "1".repeat(64); const LABELS = `io.paperclip.runner.image=${IMAGE}\nio.paperclip.runner.inputs-digest=${INPUTS}`; const BUILD_ARGS = `PAPERCLIP_RUNNER_EXPECT_INPUTS_DIGEST=${INPUTS}`; -const published = { mode: "published", build_contexts: `runner-artifacts=docker-image://${IMAGE}`, labels: LABELS, build_args: BUILD_ARGS }; +const published = { mode: "published", inputs_digest: INPUTS, build_contexts: `runner-artifacts=docker-image://${IMAGE}`, labels: LABELS, build_args: BUILD_ARGS }; const canonical = "github.repository == 'paperclipai/paperclip' && github.repository_id == '1170821064'"; const VERIFY = "Verify the attestation of the Runner image"; @@ -110,9 +110,7 @@ describe("the Runner image an application image build copies in docker.yml", () expect(condition(resolver, 4)).toBe(`vars.RUNNER_IMAGE_CONSUME_ENABLED == 'true' && ${canonical}`); expect(workflow.match(/RUNNER_IMAGE_CONSUME_ENABLED/g)).toHaveLength(1); expect(Object.keys(jobs).filter((name) => jobs[name].includes("runner-image-resolve.mjs"))).toEqual(["runner_image"]); - for (const name of ["docker-merge-group.yml", "docker-app-check.yml"]) { - expect(read(name)).not.toMatch(/runner-image-resolve|RUNNER_IMAGE_CONSUME_ENABLED|build-contexts|--build-context|io\.paperclip\.runner|runner_image/); - } + expect(read("docker-app-check.yml")).not.toMatch(/runner-image-resolve|RUNNER_IMAGE_CONSUME_ENABLED|build-contexts|--build-context|io\.paperclip\.runner|runner_image/); }); it("keeps inline Runner arguments and includes the macOS runtime identity without a published Runner", () => { @@ -123,7 +121,7 @@ describe("the Runner image an application image build copies in docker.yml", () it("gives both architectures the one answer: the context, the labels and the expected inputs of the verified image", () => { expect(/^ {4}needs: \[(.+)\]$/m.exec(legs)![1].split(", ")).toContain("runner_image"); const reads = [...legs.matchAll(/needs\.runner_image\.[a-z_.]+/g)].map((match) => match[0]); - expect(new Set(reads)).toEqual(new Set(["mode", "build_args", "build_contexts", "labels"].map((name) => `needs.runner_image.outputs.${name}`))); + expect(new Set(reads)).toEqual(new Set(["mode", "inputs_digest", "build_args", "build_contexts", "labels"].map((name) => `needs.runner_image.outputs.${name}`))); for (const line of legs.split("\n").filter((entry) => entry.includes("needs.runner_image"))) expect(line).not.toContain("matrix."); expect(buildInputs(published)).toEqual({ buildArgs: [...inlineBuild.buildArgs, BUILD_ARGS], @@ -136,6 +134,7 @@ describe("the Runner image an application image build copies in docker.yml", () const declared = /\n {4}outputs:\n((?: {6}.+\n)+)/.exec(resolver)![1].trimEnd().split("\n").map((line) => line.trim()); expect(declared).toEqual([ "mode: ${{ steps.verify.outputs.mode || 'inline' }}", + "inputs_digest: ${{ steps.verify.outputs.inputs_digest }}", "build_contexts: ${{ steps.verify.outputs.build_contexts }}", "labels: ${{ steps.verify.outputs.labels }}", "build_args: ${{ steps.verify.outputs.build_args }}", @@ -143,7 +142,7 @@ describe("the Runner image an application image build copies in docker.yml", () const verify = named(resolver, VERIFY); expect(verify).toContain("\n id: verify\n"); expect(condition(verify, 8)).toBe("steps.resolve.outputs.mode == 'published'"); - const env = { IMAGE, LABELS, BUILD_ARGS, GH_TOKEN: "token-for-the-test" }; + const env = { IMAGE, INPUTS_DIGEST: INPUTS, LABELS, BUILD_ARGS, GH_TOKEN: "token-for-the-test" }; const gh = (status: number) => ({ gh: `printf '%s\\n' "$*" >> "$CALLS"\nexit ${status}` }); const verified = runStep(verify, env, gh(0)); @@ -209,13 +208,14 @@ describe("the Runner image an application image build copies in docker.yml", () expectPinnedAndExpressionFree(resolver); }); - it("does not promote a merge-queue image for a commit that copies a published Runner", () => { + it("promotes a verified merge-queue image only when its Runner inputs digest matches master", () => { const find = named(legs, "Find the merge-queue build of this commit"); - expect(condition(find, 8)).toBe(`needs.runner_image.outputs.mode != 'published' && ${canonical} && ${masterPush}`); + expect(condition(find, 8)).toBe(`${canonical} && ${masterPush}`); for (const name of ["Download the merge-queue image", "Promote the merge-queue image"]) { expect(condition(named(legs, name), 8)).toBe("steps.find.outputs.run_id != ''"); } expect(legs.match(/steps\.find\.outputs\.run_id/g)).toHaveLength(3); + expect(named(legs, "Promote the merge-queue image")).toContain("RUNNER_INPUTS_DIGEST: ${{ needs.runner_image.outputs.inputs_digest }}"); expect(condition(named(legs, "Build and push by digest"), 8)).toBe("steps.promote.outputs.digest == ''"); }); @@ -230,6 +230,81 @@ describe("the Runner image an application image build copies in docker.yml", () }); }); +describe("the merge-queue build's Runner image in docker-merge-group.yml", () => { + const workflow = read("docker-merge-group.yml"); + const jobs = jobsOf(workflow); + const resolver = jobs.runner_image; + const buildJob = jobs.build; + const buildInputs = (resolved: Record) => + listInputs(named(buildJob, "Build image archive"), "needs.runner_image.outputs", resolved); + const inlineBuild = { + buildArgs: [ + "PAPERCLIP_BUILD_VERSION=${{ steps.build-version.outputs.version }}", + "PAPERCLIP_BUILD_COMMIT=${{ github.sha }}", + "PAPERCLIP_MACOS_RUNTIME_INPUTS_DIGEST=${{ needs.macos_runner_runtime.outputs.inputs_digest }}", + "CLI_TOOLS_CACHE_EPOCH=${{ steps.tools-epoch.outputs.epoch }}", + ], + buildContexts: [], + labels: ["${{ steps.meta.outputs.labels }}"], + }; + + it("gates resolution to canonical master merge groups when RUNNER_IMAGE_CONSUME_ENABLED is true and stays read-only", () => { + expect(condition(resolver, 4)).toBe( + `vars.RUNNER_IMAGE_CONSUME_ENABLED == 'true' && ${canonical} && github.event.merge_group.base_ref == 'refs/heads/master'`, + ); + expect(permissions(resolver)).toEqual(["contents: read", "actions: read", "attestations: read"]); + expect(resolver).toContain("\n continue-on-error: true\n"); + expect(resolver).toContain("persist-credentials: false"); + expect(resolver).not.toMatch(registryWrite); + expectPinnedAndExpressionFree(resolver); + // Non-blocking lookup in the merge queue: never passes --wait. + expect(named(resolver, "Find the published Runner image of these inputs")).not.toContain("--wait"); + }); + + it("hands build only attested published outputs and falls back cleanly on inline or failed attestation", () => { + const declared = /\n {4}outputs:\n((?: {6}.+\n)+)/.exec(resolver)![1].trimEnd().split("\n").map((line) => line.trim()); + expect(declared).toEqual([ + "mode: ${{ steps.verify.outputs.mode || 'inline' }}", + "inputs_digest: ${{ steps.verify.outputs.inputs_digest }}", + "build_contexts: ${{ steps.verify.outputs.build_contexts }}", + "labels: ${{ steps.verify.outputs.labels }}", + "build_args: ${{ steps.verify.outputs.build_args }}", + ]); + + const verify = named(resolver, VERIFY); + expect(condition(verify, 8)).toBe("steps.resolve.outputs.mode == 'published'"); + const env = { IMAGE, INPUTS_DIGEST: INPUTS, LABELS, BUILD_ARGS, GH_TOKEN: "token-for-the-test" }; + const gh = (status: number) => ({ gh: `printf '%s\\n' "$*" >> "$CALLS"\nexit ${status}` }); + + const verified = runStep(verify, env, gh(0)); + expect(verified.status, verified.stderr).toBe(0); + expect(outputs(verified.output)).toEqual(published); + expect(verified.stdout).not.toContain("::warning"); + + for (const status of [1, 4]) { + const refused = runStep(verify, env, gh(status)); + expect(refused.status, refused.stderr).toBe(1); + expect(refused.output).toBe(""); + expect(refused.stdout).toContain("::warning title=Runner image not verified::"); + } + + expect(buildInputs({})).toEqual(inlineBuild); + expect(buildInputs({ mode: "inline" })).toEqual(inlineBuild); + expect(buildInputs(published)).toEqual({ + buildArgs: [...inlineBuild.buildArgs, BUILD_ARGS], + buildContexts: [`runner-artifacts=docker-image://${IMAGE}`], + labels: [...inlineBuild.labels, ...LABELS.split("\n")], + }); + }); + + it("records the attested Runner inputs digest for master promotion verification", () => { + expect(condition(named(buildJob, "Refresh lockfile for Docker build context"), 8)).toBe("needs.runner_image.outputs.mode != 'published'"); + const record = named(buildJob, "Record the verified image"); + expect(record).toContain("RUNNER_INPUTS_DIGEST: ${{ needs.runner_image.outputs.inputs_digest }}"); + expect(record).toContain('--runner-inputs-digest "$RUNNER_INPUTS_DIGEST"'); + }); +}); + describe("the pull-request check of the application image's Runner path", () => { const workflow = read("docker-app-check.yml"); const jobs = jobsOf(workflow);