From 5d4934633832f35dcd756422967a397c924bcbae Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 13:21:02 +0000 Subject: [PATCH 1/4] feat(queue-transport-alert): add trusted GHA deployment flow --- .../queue-transport-alert-deploy.yml | 107 ++++++++++++++++++ pkgs/queue-transport-alert/worker/deploy.mjs | 46 +++++++- pkgs/queue-transport-alert/worker/deploy.sh | 3 + 3 files changed, 154 insertions(+), 2 deletions(-) create mode 100644 .github/workflows/queue-transport-alert-deploy.yml diff --git a/.github/workflows/queue-transport-alert-deploy.yml b/.github/workflows/queue-transport-alert-deploy.yml new file mode 100644 index 0000000000..a39fd5d3ef --- /dev/null +++ b/.github/workflows/queue-transport-alert-deploy.yml @@ -0,0 +1,107 @@ +name: queue-transport-alert Worker deployment + +on: + workflow_dispatch: + inputs: + action: + description: Upload a new version or promote an existing version + required: true + type: choice + options: [upload, promote] + version_id: + description: Upload workflow run ID that produced the version handoff artifact + required: false + type: string + +permissions: + actions: read + contents: read + +concurrency: + group: queue-transport-alert-cloudflare-deploy + cancel-in-progress: false + +jobs: + deploy: + if: github.repository == 'developing-today/code' && github.ref == 'refs/heads/main' + runs-on: ubuntu-latest + timeout-minutes: 20 + environment: cloudflare-queue-transport-alert + steps: + - uses: actions/checkout@v7 + with: + ref: main + - uses: DeterminateSystems/nix-installer-action@v21 + - name: Build pinned deploy application + run: nix build .#queue-transport-alert-deploy + - name: Validate inputs + env: + ACTION: ${{ inputs.action }} + VERSION_ID: ${{ inputs.version_id }} + run: | + if [[ "$ACTION" == promote ]]; then + [[ "$VERSION_ID" =~ ^[A-Za-z0-9_-]{8,128}$ ]] || { echo 'promote requires a valid version_id' >&2; exit 2; } + elif [[ -n "$VERSION_ID" ]]; then + echo 'version_id is only valid for promote' >&2; exit 2 + fi + - name: Upload a new version (does not promote) + if: inputs.action == 'upload' + env: + QTA_GHA: '1' + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + ACCESS_CLIENT_ID: ${{ secrets.ACCESS_CLIENT_ID }} + ACCESS_CLIENT_SECRET: ${{ secrets.ACCESS_CLIENT_SECRET }} + GITHUB_TOKEN: ${{ secrets.WORKER_GITHUB_TOKEN }} + TELEGRAM_BOT_TOKEN: ${{ secrets.TELEGRAM_BOT_TOKEN }} + BROKER_AGENT_TOKEN: ${{ secrets.BROKER_AGENT_TOKEN }} + QTA_HANDOFF_FILE: ${{ runner.temp }}/qta-version.json + run: ./result/bin/queue-transport-alert-deploy + - name: Save version handoff + if: inputs.action == 'upload' + uses: actions/upload-artifact@v4 + with: + name: qta-version-${{ github.run_id }} + path: ${{ runner.temp }}/qta-version.json + if-no-files-found: error + retention-days: 14 + - name: Download handoff from exact successful upload run + if: inputs.action == 'promote' + uses: actions/download-artifact@v4 + with: + name: qta-version-${{ inputs.version_id }} + run-id: ${{ inputs.version_id }} + github-token: ${{ github.token }} + path: ${{ runner.temp }}/qta-handoff + - name: Check out uploaded source commit + if: inputs.action == 'promote' + uses: actions/checkout@v7 + with: + ref: main + - name: Validate handoff source is still trusted main history + if: inputs.action == 'promote' + id: handoff + env: + RUN_ID: ${{ inputs.version_id }} + HANDOFF: ${{ runner.temp }}/qta-handoff/qta-version.json + run: | + source_sha=$(jq -r .source_sha "$HANDOFF") + [[ "$source_sha" =~ ^[0-9a-f]{40}$ ]] + test "$(jq -r .worker "$HANDOFF")" = queue-transport-alert + test "$(jq -r .upload_run_id "$HANDOFF")" = "$RUN_ID" + git fetch origin "$source_sha" + git merge-base --is-ancestor "$source_sha" origin/main + echo "source_sha=$source_sha" >> "$GITHUB_OUTPUT" + - name: Promote explicit existing version + if: inputs.action == 'promote' + env: + QTA_GHA: '1' + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + QTA_HANDOFF_FILE: ${{ runner.temp }}/qta-handoff/qta-version.json + QTA_SOURCE_SHA: ${{ steps.handoff.outputs.source_sha }} + QTA_UPLOAD_RUN_ID: ${{ inputs.version_id }} + run: | + test "$(jq -r .upload_run_id "$QTA_HANDOFF_FILE")" = "$QTA_UPLOAD_RUN_ID" + version_id=$(jq -r .version_id "$QTA_HANDOFF_FILE") + ./result/bin/queue-transport-alert-deploy --deploy-version "$version_id" diff --git a/pkgs/queue-transport-alert/worker/deploy.mjs b/pkgs/queue-transport-alert/worker/deploy.mjs index 2802979000..3faea5028c 100644 --- a/pkgs/queue-transport-alert/worker/deploy.mjs +++ b/pkgs/queue-transport-alert/worker/deploy.mjs @@ -55,6 +55,8 @@ try { } if (!process.env.CLOUDFLARE_ACCOUNT_ID) throw new Error("CLOUDFLARE_ACCOUNT_ID is not set; run deploy.sh"); +const gha = process.env.QTA_GHA === "1"; +if (gha && !process.env.CLOUDFLARE_API_TOKEN) throw new Error("CLOUDFLARE_API_TOKEN is required in GHA mode"); const names = { cf: process.env.QTA_CF_TOKEN_SECRET ?? "cloudflare.api-token-day-to-day", accessId: process.env.QTA_ACCESS_ID_SECRET ?? "cloudflare.access.queue-broker-client-id", @@ -62,13 +64,13 @@ const names = { github: process.env.QTA_GITHUB_TOKEN_SECRET ?? "github.developing-today-code-automation", telegram: process.env.QTA_TELEGRAM_SECRET ?? "openclaw.telegram-bot-token", }; -const vault = JSON.parse(execFileSync("bws", ["secret", "list", "-o", "json"], { encoding: "utf8" })); +const vault = gha ? [] : JSON.parse(execFileSync("bws", ["secret", "list", "-o", "json"], { encoding: "utf8" })); const byName = (name) => { const value = vault.find((s) => s.key === name)?.value; if (!value) throw new Error(`no Bitwarden secret named ${name}`); return value.replace(/\r?\n$/, ""); }; -const env = { ...process.env, CLOUDFLARE_API_TOKEN: byName(names.cf) }; +const env = { ...process.env, CLOUDFLARE_API_TOKEN: gha ? process.env.CLOUDFLARE_API_TOKEN : byName(names.cf) }; // Stage a writable copy (the store path is read-only and cf writes // .cloudflare/ build output next to the config) with node_modules @@ -154,12 +156,52 @@ async function verify(versionId) { console.log(`verified: version ${versionId} serves 100%; ${url} reports the broker ${status.status ?? "unknown"}`); } +if (gha && deployVersion === null) { + const required = ["ACCESS_CLIENT_ID", "ACCESS_CLIENT_SECRET", "GITHUB_TOKEN", "TELEGRAM_BOT_TOKEN"]; + for (const key of required) if (!process.env[key]) throw new Error(`${key} is required in GHA mode`); + const workerSecrets = Object.fromEntries(required.map((key) => [key, process.env[key]])); + if (process.env.BROKER_AGENT_TOKEN) workerSecrets.BROKER_AGENT_TOKEN = process.env.BROKER_AGENT_TOKEN; + const sha = execFileSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" }).trim(); + const tag = `git-${sha.slice(0, 12)}`; + const message = `deploy ${sha} via GitHub Actions`; + runCfWithSecrets(["workers", "versions", "create", "--worker", WORKER, "--tag", tag, "--message", message], workerSecrets); + const versions = listItems(parseJsonOutput(runCf(["workers", "versions", "list", "--worker-id", WORKER], { capture: true })), "versions"); + const version = newestWithTag(versions, tag); + if (!version) throw new Error(`uploaded version with tag ${tag} not found in the versions list`); + const handoff = { + worker: WORKER, + source_sha: sha, + tag, + version_id: version.id, + upload_run_id: process.env.GITHUB_RUN_ID, + upload_run_attempt: process.env.GITHUB_RUN_ATTEMPT, + }; + if (!handoff.upload_run_id || !handoff.upload_run_attempt || !process.env.QTA_HANDOFF_FILE) { + throw new Error("GHA upload requires GITHUB_RUN_ID, GITHUB_RUN_ATTEMPT and QTA_HANDOFF_FILE"); + } + await (await import("node:fs/promises")).writeFile(process.env.QTA_HANDOFF_FILE, `${JSON.stringify(handoff, null, 2)}\n`, { mode: 0o600 }); + console.log(`uploaded version ${version.id}; handoff manifest saved`); + process.exit(0); +} + if (deployVersion !== null) { + if (gha) { + const handoff = JSON.parse(readFileSync(process.env.QTA_HANDOFF_FILE ?? "", "utf8")); + if (handoff.worker !== WORKER || handoff.version_id !== deployVersion || handoff.source_sha !== process.env.QTA_SOURCE_SHA || + handoff.upload_run_id !== process.env.QTA_UPLOAD_RUN_ID || handoff.tag !== `git-${handoff.source_sha.slice(0, 12)}`) { + throw new Error("handoff manifest does not bind this version to the expected Worker, source SHA, tag and upload run"); + } + const versions = listItems(parseJsonOutput(runCf(["workers", "versions", "list", "--worker-id", WORKER], { capture: true })), "versions"); + const match = versions.find((v) => v.id === deployVersion && + (v.annotations?.["workers/tag"] ?? v.metadata?.annotations?.["workers/tag"]) === handoff.tag); + if (!match) throw new Error("requested Worker version is absent or is not associated with the handoff tag"); + } if (dryRun) { console.log(`dry run: would deploy ${WORKER} at existing version ${deployVersion} (100%); nothing created`); process.exit(0); } createDeployment(deployVersion); + if (gha) runCf(["workers", "triggers", "deploy", "--worker", WORKER]); await verify(deployVersion); console.log(`live: ${WORKER_URL} at version ${deployVersion}`); process.exit(0); diff --git a/pkgs/queue-transport-alert/worker/deploy.sh b/pkgs/queue-transport-alert/worker/deploy.sh index be736a13da..f1f19834c3 100755 --- a/pkgs/queue-transport-alert/worker/deploy.sh +++ b/pkgs/queue-transport-alert/worker/deploy.sh @@ -7,6 +7,9 @@ cd "$(dirname "${BASH_SOURCE[0]}")" # Check arguments before Bitwarden or sops are touched, so a typo never # triggers a credential prompt, a decrypt or a deploy of HEAD. node deploy-lib.mjs "$@" +if [ "${QTA_GHA:-}" = 1 ]; then + exec node deploy.mjs "$@" +fi repo_root=$(git rev-parse --show-toplevel) if [ -z "${BWS_ACCESS_TOKEN:-}" ]; then # shellcheck source=/dev/null From a4fcb25a0a19bc424d0014f5d33ab3b19c63abc6 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 13:43:33 +0000 Subject: [PATCH 2/4] fix(queue-transport-alert): keep GHA releases code-only --- .../queue-transport-alert-deploy.yml | 116 ++++++++++-------- .../worker/deploy-lib.mjs | 9 ++ pkgs/queue-transport-alert/worker/deploy.mjs | 22 ++-- .../worker/test/deploy-lib.test.mjs | 9 +- 4 files changed, 98 insertions(+), 58 deletions(-) diff --git a/.github/workflows/queue-transport-alert-deploy.yml b/.github/workflows/queue-transport-alert-deploy.yml index a39fd5d3ef..2600849514 100644 --- a/.github/workflows/queue-transport-alert-deploy.yml +++ b/.github/workflows/queue-transport-alert-deploy.yml @@ -4,12 +4,12 @@ on: workflow_dispatch: inputs: action: - description: Upload a new version or promote an existing version + description: Upload a code-only version or promote an uploaded version required: true type: choice options: [upload, promote] - version_id: - description: Upload workflow run ID that produced the version handoff artifact + upload_run_id: + description: Successful upload workflow run ID for promotion required: false type: string @@ -28,71 +28,86 @@ jobs: timeout-minutes: 20 environment: cloudflare-queue-transport-alert steps: - - uses: actions/checkout@v7 - with: - ref: main - - uses: DeterminateSystems/nix-installer-action@v21 - - name: Build pinned deploy application - run: nix build .#queue-transport-alert-deploy - - name: Validate inputs + - name: Validate dispatch inputs env: ACTION: ${{ inputs.action }} - VERSION_ID: ${{ inputs.version_id }} + RUN_ID: ${{ inputs.upload_run_id }} run: | if [[ "$ACTION" == promote ]]; then - [[ "$VERSION_ID" =~ ^[A-Za-z0-9_-]{8,128}$ ]] || { echo 'promote requires a valid version_id' >&2; exit 2; } - elif [[ -n "$VERSION_ID" ]]; then - echo 'version_id is only valid for promote' >&2; exit 2 + [[ "$RUN_ID" =~ ^[0-9]{1,20}$ ]] || { echo 'promote requires upload_run_id' >&2; exit 2; } + elif [[ -n "$RUN_ID" ]]; then + echo 'upload_run_id is only valid for promote' >&2; exit 2 fi - - name: Upload a new version (does not promote) - if: inputs.action == 'upload' - env: - QTA_GHA: '1' - CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} - CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} - ACCESS_CLIENT_ID: ${{ secrets.ACCESS_CLIENT_ID }} - ACCESS_CLIENT_SECRET: ${{ secrets.ACCESS_CLIENT_SECRET }} - GITHUB_TOKEN: ${{ secrets.WORKER_GITHUB_TOKEN }} - TELEGRAM_BOT_TOKEN: ${{ secrets.TELEGRAM_BOT_TOKEN }} - BROKER_AGENT_TOKEN: ${{ secrets.BROKER_AGENT_TOKEN }} - QTA_HANDOFF_FILE: ${{ runner.temp }}/qta-version.json - run: ./result/bin/queue-transport-alert-deploy - - name: Save version handoff - if: inputs.action == 'upload' - uses: actions/upload-artifact@v4 - with: - name: qta-version-${{ github.run_id }} - path: ${{ runner.temp }}/qta-version.json - if-no-files-found: error - retention-days: 14 - - name: Download handoff from exact successful upload run + - name: Download handoff from exact upload run if: inputs.action == 'promote' uses: actions/download-artifact@v4 with: - name: qta-version-${{ inputs.version_id }} - run-id: ${{ inputs.version_id }} + name: qta-version-${{ inputs.upload_run_id }} + run-id: ${{ inputs.upload_run_id }} github-token: ${{ github.token }} path: ${{ runner.temp }}/qta-handoff - - name: Check out uploaded source commit - if: inputs.action == 'promote' - uses: actions/checkout@v7 - with: - ref: main - - name: Validate handoff source is still trusted main history + - name: Verify upload provenance and baseline receipt if: inputs.action == 'promote' id: handoff env: - RUN_ID: ${{ inputs.version_id }} + GH_TOKEN: ${{ github.token }} + RUN_ID: ${{ inputs.upload_run_id }} HANDOFF: ${{ runner.temp }}/qta-handoff/qta-version.json run: | + set -euo pipefail + run=$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${RUN_ID}") source_sha=$(jq -r .source_sha "$HANDOFF") [[ "$source_sha" =~ ^[0-9a-f]{40}$ ]] test "$(jq -r .worker "$HANDOFF")" = queue-transport-alert test "$(jq -r .upload_run_id "$HANDOFF")" = "$RUN_ID" - git fetch origin "$source_sha" - git merge-base --is-ancestor "$source_sha" origin/main + test "$(jq -r .upload_run_attempt "$HANDOFF")" = "$(jq -r .run_attempt <<<"$run")" + test "$(jq -r .upload_event "$HANDOFF")" = workflow_dispatch + test "$(jq -r .upload_ref "$HANDOFF")" = refs/heads/main + test "$(jq -r .upload_workflow_path "$HANDOFF")" = .github/workflows/queue-transport-alert-deploy.yml + test "$(jq -r .path <<<"$run")" = .github/workflows/queue-transport-alert-deploy.yml + test "$(jq -r .event <<<"$run")" = workflow_dispatch + test "$(jq -r .head_branch <<<"$run")" = main + test "$(jq -r .head_sha <<<"$run")" = "$source_sha" + test "$(jq -r .status <<<"$run")" = completed + test "$(jq -r .conclusion <<<"$run")" = success + test "$(jq -r .worker "$HANDOFF")" = queue-transport-alert echo "source_sha=$source_sha" >> "$GITHUB_OUTPUT" - - name: Promote explicit existing version + - name: Check out exact uploaded source + if: inputs.action == 'promote' + uses: actions/checkout@v7 + with: + ref: ${{ steps.handoff.outputs.source_sha }} + - name: Check out trusted dispatch source + if: inputs.action == 'upload' + uses: actions/checkout@v7 + with: + ref: main + - uses: DeterminateSystems/nix-installer-action@v21 + - name: Build pinned deploy application from verified source + run: nix build .#queue-transport-alert-deploy + - name: Upload code-only Worker version + if: inputs.action == 'upload' + env: + QTA_GHA: '1' + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + GITHUB_RUN_ID: ${{ github.run_id }} + GITHUB_RUN_ATTEMPT: ${{ github.run_attempt }} + GITHUB_EVENT_NAME: ${{ github.event_name }} + GITHUB_REF: ${{ github.ref }} + GITHUB_WORKFLOW_REF: ${{ github.workflow_ref }} + GITHUB_REPOSITORY: ${{ github.repository }} + QTA_HANDOFF_FILE: ${{ runner.temp }}/qta-version.json + run: ./result/bin/queue-transport-alert-deploy + - name: Save version handoff + if: inputs.action == 'upload' + uses: actions/upload-artifact@v4 + with: + name: qta-version-${{ github.run_id }} + path: ${{ runner.temp }}/qta-version.json + if-no-files-found: error + retention-days: 14 + - name: Promote verified version only if: inputs.action == 'promote' env: QTA_GHA: '1' @@ -100,8 +115,9 @@ jobs: CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} QTA_HANDOFF_FILE: ${{ runner.temp }}/qta-handoff/qta-version.json QTA_SOURCE_SHA: ${{ steps.handoff.outputs.source_sha }} - QTA_UPLOAD_RUN_ID: ${{ inputs.version_id }} + QTA_UPLOAD_RUN_ID: ${{ inputs.upload_run_id }} run: | - test "$(jq -r .upload_run_id "$QTA_HANDOFF_FILE")" = "$QTA_UPLOAD_RUN_ID" + set -euo pipefail version_id=$(jq -r .version_id "$QTA_HANDOFF_FILE") + [[ "$version_id" =~ ^[A-Za-z0-9_-]{8,128}$ ]] ./result/bin/queue-transport-alert-deploy --deploy-version "$version_id" diff --git a/pkgs/queue-transport-alert/worker/deploy-lib.mjs b/pkgs/queue-transport-alert/worker/deploy-lib.mjs index 11d0f54e97..c48d367fda 100644 --- a/pkgs/queue-transport-alert/worker/deploy-lib.mjs +++ b/pkgs/queue-transport-alert/worker/deploy-lib.mjs @@ -80,6 +80,15 @@ export function servingCheck(deployments, versionId) { return { ok: false, serving }; } +// Return one unambiguous 100% serving version for code-only upload inheritance. +export function singleServingVersion(deployments) { + const latest = [...deployments].sort((a, b) => createdOn(b) - createdOn(a))[0]; + const active = (latest?.versions ?? []).filter((v) => Number(v.percentage) > 0); + return active.length === 1 && Number(active[0].percentage) === 100 && active[0].version_id + ? active[0].version_id + : null; +} + if (process.argv[1] === fileURLToPath(import.meta.url)) { try { parseArgs(process.argv.slice(2)); diff --git a/pkgs/queue-transport-alert/worker/deploy.mjs b/pkgs/queue-transport-alert/worker/deploy.mjs index 3faea5028c..6ec993a71d 100644 --- a/pkgs/queue-transport-alert/worker/deploy.mjs +++ b/pkgs/queue-transport-alert/worker/deploy.mjs @@ -38,7 +38,7 @@ import { homedir, tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; -import { listItems, newestWithTag, parseArgs, parseJsonOutput, servingCheck } from "./deploy-lib.mjs"; +import { listItems, newestWithTag, parseArgs, parseJsonOutput, servingCheck, singleServingVersion } from "./deploy-lib.mjs"; const here = dirname(fileURLToPath(import.meta.url)); const WORKER = "queue-transport-alert"; @@ -157,14 +157,15 @@ async function verify(versionId) { } if (gha && deployVersion === null) { - const required = ["ACCESS_CLIENT_ID", "ACCESS_CLIENT_SECRET", "GITHUB_TOKEN", "TELEGRAM_BOT_TOKEN"]; - for (const key of required) if (!process.env[key]) throw new Error(`${key} is required in GHA mode`); - const workerSecrets = Object.fromEntries(required.map((key) => [key, process.env[key]])); - if (process.env.BROKER_AGENT_TOKEN) workerSecrets.BROKER_AGENT_TOKEN = process.env.BROKER_AGENT_TOKEN; + const currentDeployments = listItems(parseJsonOutput(runCf(["workers", "deployments", "list", "--worker", WORKER], { capture: true })), "deployments"); + const baselineVersion = singleServingVersion(currentDeployments); + if (!baselineVersion) { + throw new Error("cannot upload code-only version: no single 100% serving baseline version to inherit runtime bindings from"); + } const sha = execFileSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" }).trim(); const tag = `git-${sha.slice(0, 12)}`; const message = `deploy ${sha} via GitHub Actions`; - runCfWithSecrets(["workers", "versions", "create", "--worker", WORKER, "--tag", tag, "--message", message], workerSecrets); + runCf(["workers", "versions", "create", "--worker", WORKER, "--tag", tag, "--message", message]); const versions = listItems(parseJsonOutput(runCf(["workers", "versions", "list", "--worker-id", WORKER], { capture: true })), "versions"); const version = newestWithTag(versions, tag); if (!version) throw new Error(`uploaded version with tag ${tag} not found in the versions list`); @@ -175,6 +176,10 @@ if (gha && deployVersion === null) { version_id: version.id, upload_run_id: process.env.GITHUB_RUN_ID, upload_run_attempt: process.env.GITHUB_RUN_ATTEMPT, + upload_event: process.env.GITHUB_EVENT_NAME, + upload_ref: process.env.GITHUB_REF, + upload_workflow_path: process.env.GITHUB_WORKFLOW_REF?.split("@")[0]?.replace(`${process.env.GITHUB_REPOSITORY}/`, ""), + baseline_version_id: baselineVersion, }; if (!handoff.upload_run_id || !handoff.upload_run_attempt || !process.env.QTA_HANDOFF_FILE) { throw new Error("GHA upload requires GITHUB_RUN_ID, GITHUB_RUN_ATTEMPT and QTA_HANDOFF_FILE"); @@ -195,13 +200,16 @@ if (deployVersion !== null) { const match = versions.find((v) => v.id === deployVersion && (v.annotations?.["workers/tag"] ?? v.metadata?.annotations?.["workers/tag"]) === handoff.tag); if (!match) throw new Error("requested Worker version is absent or is not associated with the handoff tag"); + const deployments = listItems(parseJsonOutput(runCf(["workers", "deployments", "list", "--worker", WORKER], { capture: true })), "deployments"); + if (singleServingVersion(deployments) !== handoff.baseline_version_id) { + throw new Error("serving baseline changed since code-only upload; refusing promotion because inherited runtime bindings cannot be established"); + } } if (dryRun) { console.log(`dry run: would deploy ${WORKER} at existing version ${deployVersion} (100%); nothing created`); process.exit(0); } createDeployment(deployVersion); - if (gha) runCf(["workers", "triggers", "deploy", "--worker", WORKER]); await verify(deployVersion); console.log(`live: ${WORKER_URL} at version ${deployVersion}`); process.exit(0); diff --git a/pkgs/queue-transport-alert/worker/test/deploy-lib.test.mjs b/pkgs/queue-transport-alert/worker/test/deploy-lib.test.mjs index f351da0b07..475c92a9ba 100644 --- a/pkgs/queue-transport-alert/worker/test/deploy-lib.test.mjs +++ b/pkgs/queue-transport-alert/worker/test/deploy-lib.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { test } from "node:test"; -import { listItems, newestWithTag, parseArgs, parseJsonOutput, servingCheck } from "../deploy-lib.mjs"; +import { listItems, newestWithTag, parseArgs, parseJsonOutput, servingCheck, singleServingVersion } from "../deploy-lib.mjs"; test("parseArgs accepts the three shapes", () => { assert.deepEqual(parseArgs([]), { dryRun: false, deployVersion: null }); @@ -58,3 +58,10 @@ test("servingCheck requires the latest deployment to serve the version at 100%", const split = [{ created_on: "2026-11-19T03:00:00Z", versions: [{ version_id: "v2", percentage: 50 }, { version_id: "v3", percentage: 50 }] }]; assert.match(servingCheck(split, "v2").serving, /v2@50%, v3@50%/); }); + +test("code-only upload inheritance requires one serving baseline at 100%", () => { + assert.equal(singleServingVersion([{ created_on: "2026-11-19T01:00:00Z", versions: [{ version_id: "base", percentage: 100 }] }]), "base"); + assert.equal(singleServingVersion([]), null); + assert.equal(singleServingVersion([{ versions: [{ version_id: "a", percentage: 50 }, { version_id: "b", percentage: 50 }] }]), null); + assert.equal(singleServingVersion([{ versions: [{ version_id: "a", percentage: 0 }] }]), null); +}); From 15af356324f56499bea0cd6a24f6ea8e5400c37c Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 01:07:57 -0600 Subject: [PATCH 3/4] fix(qta): bind manual deployment to exact upload provenance --- .../queue-transport-alert-deploy.yml | 42 +++++++++++++++---- pkgs/queue-transport-alert/worker/README.md | 18 ++++++++ .../worker/deploy-lib.mjs | 29 +++++++++++++ pkgs/queue-transport-alert/worker/deploy.mjs | 41 +++++++++++------- .../worker/test/deploy-lib.test.mjs | 21 +++++++++- 5 files changed, 128 insertions(+), 23 deletions(-) diff --git a/.github/workflows/queue-transport-alert-deploy.yml b/.github/workflows/queue-transport-alert-deploy.yml index 2600849514..52d7ec9bee 100644 --- a/.github/workflows/queue-transport-alert-deploy.yml +++ b/.github/workflows/queue-transport-alert-deploy.yml @@ -8,6 +8,11 @@ on: required: true type: choice options: [upload, promote] + confirm: + description: Confirm the selected Cloudflare operation + required: true + type: boolean + default: false upload_run_id: description: Successful upload workflow run ID for promotion required: false @@ -22,8 +27,29 @@ concurrency: cancel-in-progress: false jobs: + verify-environment: + if: github.repository == 'developing-today/code' && github.ref == 'refs/heads/main' && inputs.confirm + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - name: Require an existing reviewed main-only environment + env: + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + endpoint="repos/$GITHUB_REPOSITORY/environments/cloudflare-queue-transport-alert" + gh api "$endpoint" | jq -e ' + .name == "cloudflare-queue-transport-alert" + and .deployment_branch_policy.custom_branch_policies == true + and .deployment_branch_policy.protected_branches == false + and any(.protection_rules[]; + .type == "required_reviewers" and .prevent_self_review == true + and (.reviewers | length) > 0)' >/dev/null + gh api "$endpoint/deployment-branch-policies?per_page=100" | jq -e ' + .total_count == 1 and (.branch_policies | length) == 1 + and .branch_policies[0].type == "branch" and .branch_policies[0].name == "main"' >/dev/null deploy: - if: github.repository == 'developing-today/code' && github.ref == 'refs/heads/main' + needs: verify-environment runs-on: ubuntu-latest timeout-minutes: 20 environment: cloudflare-queue-transport-alert @@ -81,7 +107,8 @@ jobs: if: inputs.action == 'upload' uses: actions/checkout@v7 with: - ref: main + ref: ${{ github.sha }} + persist-credentials: false - uses: DeterminateSystems/nix-installer-action@v21 - name: Build pinned deploy application from verified source run: nix build .#queue-transport-alert-deploy @@ -89,8 +116,9 @@ jobs: if: inputs.action == 'upload' env: QTA_GHA: '1' - CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} - CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + CLOUDFLARE_ACCOUNT_ID: ${{ vars.QTA_WORKER_PRODUCTION_ACCOUNT_ID }} + CLOUDFLARE_API_TOKEN: ${{ secrets.QTA_WORKER_PRODUCTION_CF_API_TOKEN }} + QTA_SOURCE_SHA: ${{ github.sha }} GITHUB_RUN_ID: ${{ github.run_id }} GITHUB_RUN_ATTEMPT: ${{ github.run_attempt }} GITHUB_EVENT_NAME: ${{ github.event_name }} @@ -111,13 +139,13 @@ jobs: if: inputs.action == 'promote' env: QTA_GHA: '1' - CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} - CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + CLOUDFLARE_ACCOUNT_ID: ${{ vars.QTA_WORKER_PRODUCTION_ACCOUNT_ID }} + CLOUDFLARE_API_TOKEN: ${{ secrets.QTA_WORKER_PRODUCTION_CF_API_TOKEN }} QTA_HANDOFF_FILE: ${{ runner.temp }}/qta-handoff/qta-version.json QTA_SOURCE_SHA: ${{ steps.handoff.outputs.source_sha }} QTA_UPLOAD_RUN_ID: ${{ inputs.upload_run_id }} run: | set -euo pipefail version_id=$(jq -r .version_id "$QTA_HANDOFF_FILE") - [[ "$version_id" =~ ^[A-Za-z0-9_-]{8,128}$ ]] + [[ "$version_id" =~ ^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$ ]] ./result/bin/queue-transport-alert-deploy --deploy-version "$version_id" diff --git a/pkgs/queue-transport-alert/worker/README.md b/pkgs/queue-transport-alert/worker/README.md index b7c3537ee6..72331d9b0f 100644 --- a/pkgs/queue-transport-alert/worker/README.md +++ b/pkgs/queue-transport-alert/worker/README.md @@ -120,3 +120,21 @@ node --test test/*.test.mjs They also run in the package's `checkPhase`, so a flake build fails on a broken contract. + +### Optional GitHub Actions release + +The source-only workflow is manual, main-only, and off without explicit confirmation. +It does not replace the existing Nix operator command or manage its cron. Before +any dispatch, an administrator must separately configure +`cloudflare-queue-transport-alert` with an independent required reviewer, no +self-review or admin bypass, and only the `main` branch. Use an environment-only +`QTA_WORKER_PRODUCTION_CF_API_TOKEN` scoped to the existing Worker and set that +environment's `QTA_WORKER_PRODUCTION_ACCOUNT_ID` variable. Do not put this token +at repository or organization scope or supply runtime secret values to CI. + +Upload is code only; it requires the latest uploaded version to be the current +single 100% serving version so binding inheritance cannot silently use an +abandoned candidate. Promotion is a separate dispatch using the exact successful +upload run. If a candidate is abandoned or verification fails after a promotion, +stop and have the operator reconcile the serving version using the existing +operator runbook; the workflow does not perform automatic rollback. diff --git a/pkgs/queue-transport-alert/worker/deploy-lib.mjs b/pkgs/queue-transport-alert/worker/deploy-lib.mjs index c48d367fda..a9e11330f9 100644 --- a/pkgs/queue-transport-alert/worker/deploy-lib.mjs +++ b/pkgs/queue-transport-alert/worker/deploy-lib.mjs @@ -89,6 +89,35 @@ export function singleServingVersion(deployments) { : null; } +const VERSION_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; + +export function ghaUploadIdentity({ sha, runId, attempt }) { + if (!/^[0-9a-f]{40}$/.test(sha ?? "") || !/^[0-9]{1,20}$/.test(runId ?? "") || + !/^[0-9]{1,10}$/.test(attempt ?? "")) { + throw new Error("invalid GitHub upload provenance"); + } + return { tag: sha, message: "queue-transport-alert upload " + sha + " run " + runId + " attempt " + attempt }; +} + +// Pinned cf 1.0.0-beta.20 emits this machine record to WRANGLER_OUTPUT_FILE_PATH. +export function uploadedVersionId(raw, worker) { + const item = JSON.parse(raw); + if (item?.type !== "version-upload" || item.version !== 1 || item.worker_name !== worker || + item.worker_name_overridden !== false || item.wrangler_environment || + !VERSION_UUID.test(item.version_id ?? "")) { + throw new Error("cf upload did not return a version UUID for the exact Worker"); + } + return item.version_id; +} + +export function hasExactUpload(versions, id, { tag, message }) { + if (!VERSION_UUID.test(id ?? "")) return false; + const matches = versions.filter((item) => item.id === id); + if (matches.length !== 1) return false; + const annotations = matches[0].annotations ?? matches[0].metadata?.annotations; + return annotations?.["workers/tag"] === tag && annotations?.["workers/message"] === message; +} + if (process.argv[1] === fileURLToPath(import.meta.url)) { try { parseArgs(process.argv.slice(2)); diff --git a/pkgs/queue-transport-alert/worker/deploy.mjs b/pkgs/queue-transport-alert/worker/deploy.mjs index 6ec993a71d..ff2702da2b 100644 --- a/pkgs/queue-transport-alert/worker/deploy.mjs +++ b/pkgs/queue-transport-alert/worker/deploy.mjs @@ -38,7 +38,7 @@ import { homedir, tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; -import { listItems, newestWithTag, parseArgs, parseJsonOutput, servingCheck, singleServingVersion } from "./deploy-lib.mjs"; +import { listItems, newestWithTag, parseArgs, parseJsonOutput, servingCheck, singleServingVersion, ghaUploadIdentity, uploadedVersionId, hasExactUpload } from "./deploy-lib.mjs"; const here = dirname(fileURLToPath(import.meta.url)); const WORKER = "queue-transport-alert"; @@ -56,6 +56,7 @@ try { if (!process.env.CLOUDFLARE_ACCOUNT_ID) throw new Error("CLOUDFLARE_ACCOUNT_ID is not set; run deploy.sh"); const gha = process.env.QTA_GHA === "1"; +if (gha && dryRun && deployVersion === null) throw new Error("GHA upload does not accept --dry-run"); if (gha && !process.env.CLOUDFLARE_API_TOKEN) throw new Error("CLOUDFLARE_API_TOKEN is required in GHA mode"); const names = { cf: process.env.QTA_CF_TOKEN_SECRET ?? "cloudflare.api-token-day-to-day", @@ -98,10 +99,10 @@ for (const [name, variable] of [["cf", "QTA_CF_MODULE"], ["wrangler", "QTA_WRANG symlinkSync(target, join(stage, "node_modules", name)); } -function runCf(args, { capture = false } = {}) { +function runCf(args, { capture = false, outputFile } = {}) { return execFileSync("cf", ["-q", ...args], { cwd: stage, - env, + env: outputFile ? { ...env, WRANGLER_OUTPUT_FILE_PATH: outputFile } : env, encoding: "utf8", stdio: ["inherit", capture ? "pipe" : "inherit", "inherit"], }); @@ -162,18 +163,27 @@ if (gha && deployVersion === null) { if (!baselineVersion) { throw new Error("cannot upload code-only version: no single 100% serving baseline version to inherit runtime bindings from"); } + // Inherits against the latest uploaded version, not necessarily the serving one. + const priorVersions = listItems(parseJsonOutput(runCf(["workers", "versions", "list", "--worker-id", WORKER, "--per-page", "1"], { capture: true })), "versions"); + if (priorVersions[0]?.id !== baselineVersion) { + throw new Error("latest upload is not the serving baseline; refusing runtime binding inheritance"); + } const sha = execFileSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" }).trim(); - const tag = `git-${sha.slice(0, 12)}`; - const message = `deploy ${sha} via GitHub Actions`; - runCf(["workers", "versions", "create", "--worker", WORKER, "--tag", tag, "--message", message]); + if (sha !== process.env.QTA_SOURCE_SHA) throw new Error("checkout does not match dispatch SHA"); + if (!process.env.QTA_HANDOFF_FILE) throw new Error("GHA upload requires a handoff path"); + const identity = ghaUploadIdentity({ sha, runId: process.env.GITHUB_RUN_ID, attempt: process.env.GITHUB_RUN_ATTEMPT }); + const outputFile = join(stage, "cf-versions-upload-result.json"); + runCf(["workers", "versions", "create", "--worker", WORKER, "--tag", identity.tag, "--message", identity.message], { outputFile }); + const versionId = uploadedVersionId(readFileSync(outputFile, "utf8"), WORKER); const versions = listItems(parseJsonOutput(runCf(["workers", "versions", "list", "--worker-id", WORKER], { capture: true })), "versions"); - const version = newestWithTag(versions, tag); - if (!version) throw new Error(`uploaded version with tag ${tag} not found in the versions list`); + if (!hasExactUpload(versions, versionId, identity)) throw new Error("provider did not read back the exact created version and provenance"); + const current = listItems(parseJsonOutput(runCf(["workers", "deployments", "list", "--worker", WORKER], { capture: true })), "deployments"); + if (singleServingVersion(current) !== baselineVersion) throw new Error("serving baseline changed during upload"); const handoff = { worker: WORKER, source_sha: sha, - tag, - version_id: version.id, + tag: identity.tag, + version_id: versionId, upload_run_id: process.env.GITHUB_RUN_ID, upload_run_attempt: process.env.GITHUB_RUN_ATTEMPT, upload_event: process.env.GITHUB_EVENT_NAME, @@ -185,21 +195,22 @@ if (gha && deployVersion === null) { throw new Error("GHA upload requires GITHUB_RUN_ID, GITHUB_RUN_ATTEMPT and QTA_HANDOFF_FILE"); } await (await import("node:fs/promises")).writeFile(process.env.QTA_HANDOFF_FILE, `${JSON.stringify(handoff, null, 2)}\n`, { mode: 0o600 }); - console.log(`uploaded version ${version.id}; handoff manifest saved`); + console.log(`uploaded version ${versionId}; handoff manifest saved`); process.exit(0); } if (deployVersion !== null) { if (gha) { const handoff = JSON.parse(readFileSync(process.env.QTA_HANDOFF_FILE ?? "", "utf8")); + const identity = ghaUploadIdentity({ sha: handoff.source_sha, runId: handoff.upload_run_id, attempt: handoff.upload_run_attempt }); if (handoff.worker !== WORKER || handoff.version_id !== deployVersion || handoff.source_sha !== process.env.QTA_SOURCE_SHA || - handoff.upload_run_id !== process.env.QTA_UPLOAD_RUN_ID || handoff.tag !== `git-${handoff.source_sha.slice(0, 12)}`) { + handoff.upload_run_id !== process.env.QTA_UPLOAD_RUN_ID || handoff.tag !== identity.tag) { throw new Error("handoff manifest does not bind this version to the expected Worker, source SHA, tag and upload run"); } const versions = listItems(parseJsonOutput(runCf(["workers", "versions", "list", "--worker-id", WORKER], { capture: true })), "versions"); - const match = versions.find((v) => v.id === deployVersion && - (v.annotations?.["workers/tag"] ?? v.metadata?.annotations?.["workers/tag"]) === handoff.tag); - if (!match) throw new Error("requested Worker version is absent or is not associated with the handoff tag"); + if (!hasExactUpload(versions, deployVersion, identity)) { + throw new Error("requested Worker version lacks the verified immutable upload provenance"); + } const deployments = listItems(parseJsonOutput(runCf(["workers", "deployments", "list", "--worker", WORKER], { capture: true })), "deployments"); if (singleServingVersion(deployments) !== handoff.baseline_version_id) { throw new Error("serving baseline changed since code-only upload; refusing promotion because inherited runtime bindings cannot be established"); diff --git a/pkgs/queue-transport-alert/worker/test/deploy-lib.test.mjs b/pkgs/queue-transport-alert/worker/test/deploy-lib.test.mjs index 475c92a9ba..73db808e9d 100644 --- a/pkgs/queue-transport-alert/worker/test/deploy-lib.test.mjs +++ b/pkgs/queue-transport-alert/worker/test/deploy-lib.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { test } from "node:test"; -import { listItems, newestWithTag, parseArgs, parseJsonOutput, servingCheck, singleServingVersion } from "../deploy-lib.mjs"; +import { listItems, newestWithTag, parseArgs, parseJsonOutput, servingCheck, singleServingVersion, ghaUploadIdentity, uploadedVersionId, hasExactUpload } from "../deploy-lib.mjs"; test("parseArgs accepts the three shapes", () => { assert.deepEqual(parseArgs([]), { dryRun: false, deployVersion: null }); @@ -65,3 +65,22 @@ test("code-only upload inheritance requires one serving baseline at 100%", () => assert.equal(singleServingVersion([{ versions: [{ version_id: "a", percentage: 50 }, { version_id: "b", percentage: 50 }] }]), null); assert.equal(singleServingVersion([{ versions: [{ version_id: "a", percentage: 0 }] }]), null); }); + +test("GHA handoff requires the pinned exact-worker UUID and immutable full-run label", () => { + const worker = "queue-transport-alert"; + const id = "00000000-0000-4000-8000-000000000001"; + const record = { type: "version-upload", version: 1, worker_name: worker, worker_name_overridden: false, version_id: id }; + const sha = "a".repeat(40); + const upload = ghaUploadIdentity({ sha, runId: "123", attempt: "1" }); + assert.equal(upload.tag, sha); + assert.equal(uploadedVersionId(JSON.stringify(record), worker), id); + for (const wrong of [{ version_id: "latest" }, { worker_name: "other" }, { worker_name_overridden: true }, { version: 2 }, { wrangler_environment: "other" }]) { + assert.throws(() => uploadedVersionId(JSON.stringify({ ...record, ...wrong }), worker), /exact Worker/); + } + assert.throws(() => ghaUploadIdentity({ sha: sha.slice(0, 12), runId: "123", attempt: "1" }), /provenance/); + const item = { id, annotations: { "workers/tag": upload.tag, "workers/message": upload.message } }; + assert.equal(hasExactUpload([item], id, upload), true); + assert.equal(hasExactUpload([item, item], id, upload), false); + assert.equal(hasExactUpload([item], id, ghaUploadIdentity({ sha, runId: "123", attempt: "2" })), false); + assert.equal(hasExactUpload([item], id.replace(/1$/, "2"), upload), false); +}); From c2e6423386e0b65f25e21745f627d43ab144967d Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 01:10:28 -0600 Subject: [PATCH 4/4] fix(qta): require owner attestation for production environment bypass --- .github/workflows/queue-transport-alert-deploy.yml | 9 ++++++++- pkgs/queue-transport-alert/worker/README.md | 5 +++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/.github/workflows/queue-transport-alert-deploy.yml b/.github/workflows/queue-transport-alert-deploy.yml index 52d7ec9bee..bea08b3a56 100644 --- a/.github/workflows/queue-transport-alert-deploy.yml +++ b/.github/workflows/queue-transport-alert-deploy.yml @@ -13,6 +13,11 @@ on: required: true type: boolean default: false + attest_admin_bypass_disabled: + description: Owner attests the environment was checked separately and administrator bypass is disabled + required: true + type: boolean + default: false upload_run_id: description: Successful upload workflow run ID for promotion required: false @@ -28,7 +33,7 @@ concurrency: jobs: verify-environment: - if: github.repository == 'developing-today/code' && github.ref == 'refs/heads/main' && inputs.confirm + if: github.repository == 'developing-today/code' && github.ref == 'refs/heads/main' && inputs.confirm && inputs.attest_admin_bypass_disabled runs-on: ubuntu-latest timeout-minutes: 5 steps: @@ -40,6 +45,7 @@ jobs: endpoint="repos/$GITHUB_REPOSITORY/environments/cloudflare-queue-transport-alert" gh api "$endpoint" | jq -e ' .name == "cloudflare-queue-transport-alert" + and ((has("can_admins_bypass") | not) or .can_admins_bypass == false) and .deployment_branch_policy.custom_branch_policies == true and .deployment_branch_policy.protected_branches == false and any(.protection_rules[]; @@ -103,6 +109,7 @@ jobs: uses: actions/checkout@v7 with: ref: ${{ steps.handoff.outputs.source_sha }} + persist-credentials: false - name: Check out trusted dispatch source if: inputs.action == 'upload' uses: actions/checkout@v7 diff --git a/pkgs/queue-transport-alert/worker/README.md b/pkgs/queue-transport-alert/worker/README.md index 72331d9b0f..f84fbfdcf7 100644 --- a/pkgs/queue-transport-alert/worker/README.md +++ b/pkgs/queue-transport-alert/worker/README.md @@ -131,6 +131,11 @@ self-review or admin bypass, and only the `main` branch. Use an environment-only `QTA_WORKER_PRODUCTION_CF_API_TOKEN` scoped to the existing Worker and set that environment's `QTA_WORKER_PRODUCTION_ACCOUNT_ID` variable. Do not put this token at repository or organization scope or supply runtime secret values to CI. +The REST environment response need not expose administrator bypass. Before +dispatch, the environment owner must inspect the environment settings +separately and tick `attest_admin_bypass_disabled` only if it is disabled. +Stop if that fact cannot be verified. If GitHub returns the field and it is +not false, the preflight rejects the dispatch regardless of attestation. Upload is code only; it requires the latest uploaded version to be the current single 100% serving version so binding inheritance cannot silently use an