From 09dd3a55df8b949f25385c660c46844b542ea348 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 13:35:06 +0000 Subject: [PATCH 1/2] deploy(pm-console): use cf Worker Versions --- .github/workflows/pm-console-edge-deploy.yml | 104 +++++++++++++++---- pm-stack/console/edge/cloudflare.config.ts | 34 ++++++ pm-stack/console/edge/wrangler.config.ts | 4 + 3 files changed, 120 insertions(+), 22 deletions(-) create mode 100644 pm-stack/console/edge/cloudflare.config.ts create mode 100644 pm-stack/console/edge/wrangler.config.ts diff --git a/.github/workflows/pm-console-edge-deploy.yml b/.github/workflows/pm-console-edge-deploy.yml index 0e6425a8cd..4757f896b6 100644 --- a/.github/workflows/pm-console-edge-deploy.yml +++ b/.github/workflows/pm-console-edge-deploy.yml @@ -6,10 +6,10 @@ name: pm-console-edge deploy # Deploys the Worker that serves the PM app from the edge # (pm-stack/console/edge): every push to main that touches the console, # or a manual run, runs the console's tests (which drive the Worker's -# routing and state against the host's real handler), bundles the -# Worker, and uploads it with the CLOUDFLARE_API_TOKEN and -# CLOUDFLARE_ACCOUNT_ID repository secrets, the ones message-bridge -# deploys with. +# routing and state against the host's real handler), bundles the Worker, +# uploads a cf Worker version, explicitly promotes it, and uses the +# CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID repository secrets (the +# same credentials used by message-bridge). # # The Worker has no secrets: the keys it uses it makes itself, or are # published by the host. It has no route here either. The host's @@ -47,6 +47,9 @@ concurrency: jobs: deploy: name: deploy pm-console-edge + # workflow_dispatch can select a non-main ref. Never expose repository + # Cloudflare secrets to a workflow copy from another ref. + if: github.ref == 'refs/heads/main' runs-on: ubuntu-latest timeout-minutes: 15 steps: @@ -62,43 +65,100 @@ jobs: echo "ready=false" >> "$GITHUB_OUTPUT" echo "Skipped the upload: set the CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID repository secrets to deploy pm-console-edge from the repo." >> "$GITHUB_STEP_SUMMARY" fi - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: DeterminateSystems/nix-installer-action@3138316df39ed29be04236d7ffc686fa525866aa # v23 + - uses: DeterminateSystems/magic-nix-cache-action@84c0677f58dcedf3b91f8223ce36a9ea5b3c84b7 # v15 - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 - - uses: actions/setup-node@v7 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: - node-version: 24 + node-version: 24.22.0 - name: Test the console and its edge working-directory: pm-stack/console run: bun test - name: Install the deploy tool working-directory: pm-stack/console/edge run: npm ci --no-audit --no-fund + - name: Build the repo-pinned cf CLI + env: + NIXPKGS_ALLOW_UNFREE: "1" + run: | + # Reuse the cf and Wrangler packages already pinned by the repo flake. + nix build --impure .#messageBridgeDeploy --print-build-logs --out-link "$RUNNER_TEMP/messageBridgeDeploy" + cf_path="$(nix path-info --recursive "$RUNNER_TEMP/messageBridgeDeploy" | awk -F/ '$NF ~ /^cf-[0-9]/ {print; exit}')" + if [ -z "$cf_path" ]; then + echo "cf package was not in the message-bridge deployment closure" >&2 + exit 1 + fi + echo "$cf_path/bin" >> "$GITHUB_PATH" + echo "CF_MODULE=$cf_path/lib/node_modules/cf" >> "$GITHUB_ENV" + test "$("$cf_path/bin/cf" --version)" = "1.0.0-beta.20" + - name: Link cf project config + working-directory: pm-stack/console/edge + run: | + mkdir -p node_modules + ln -s "$CF_MODULE" node_modules/cf - name: Bundle the Worker working-directory: pm-stack/console/edge run: | node build.mjs - npx wrangler deploy --dry-run --outdir .wrangler/dry - - name: Deploy - if: steps.secrets.outputs.ready == 'true' + cf -q workers versions create --worker pm-console-edge \ + --tag "git-${GITHUB_SHA}" \ + --message "git ${GITHUB_SHA}" \ + --dry-run + - name: Upload Worker version + id: upload + if: steps.secrets.outputs.ready == 'true' && inputs.rollback_version == '' + working-directory: pm-stack/console/edge + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} + VERSION_TAG: git-${{ github.sha }} + run: | + cf -q workers versions create --worker pm-console-edge \ + --tag "$VERSION_TAG" \ + --message "git ${GITHUB_SHA}" + version_id="$(cf -q workers versions list --worker-id pm-console-edge | VERSION_TAG="$VERSION_TAG" node -e ' + const data = JSON.parse(require("node:fs").readFileSync(0, "utf8")); + const items = [data, data?.result, data?.result?.items, data?.items, data?.versions].find(Array.isArray); + if (!items) throw new Error("cf workers versions list returned an unexpected response"); + const tag = process.env.VERSION_TAG; + const matches = items.filter((v) => (v.annotations?.["workers/tag"] ?? v.metadata?.annotations?.["workers/tag"]) === tag); + matches.sort((a, b) => Date.parse(b.metadata?.created_on ?? b.created_on ?? 0) - Date.parse(a.metadata?.created_on ?? a.created_on ?? 0)); + if (!matches[0]?.id) throw new Error(`uploaded version with tag ${tag} was not found`); + process.stdout.write(matches[0].id); + ')" + if ! printf '%s' "$version_id" | grep -Eq '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'; then + echo "cf returned an invalid Worker version id" >&2 + exit 1 + fi + echo "version_id=$version_id" >> "$GITHUB_OUTPUT" + - name: Promote uploaded version + if: steps.secrets.outputs.ready == 'true' && inputs.rollback_version == '' + working-directory: pm-stack/console/edge + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} + VERSION_ID: ${{ steps.upload.outputs.version_id }} + run: | + versions="$(jq -cn --arg id "$VERSION_ID" '[{version_id:$id,percentage:100}]')" + cf -q workers deployments create --worker pm-console-edge --strategy percentage --versions "$versions" + echo "Promoted pm-console-edge version ${VERSION_ID} from ${GITHUB_SHA}." >> "$GITHUB_STEP_SUMMARY" + - name: Promote rollback version + if: steps.secrets.outputs.ready == 'true' && inputs.rollback_version != '' working-directory: pm-stack/console/edge env: CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} ROLLBACK_VERSION: ${{ inputs.rollback_version }} run: | - # The input goes through the env, never into the script text, - # and must look like a version id before it is used. - if [ -n "${ROLLBACK_VERSION:-}" ]; then - if ! printf '%s' "$ROLLBACK_VERSION" | grep -Eq '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'; then - echo "rollback_version is not a version id" >&2 - exit 2 - fi - npx wrangler rollback "$ROLLBACK_VERSION" --yes --message "rollback from workflow run ${GITHUB_RUN_ID}" - echo "Put pm-console-edge back to version ${ROLLBACK_VERSION}." >> "$GITHUB_STEP_SUMMARY" - else - npx wrangler deploy --var "VERSION:${GITHUB_SHA::12}" --message "git ${GITHUB_SHA}" - echo "Deployed pm-console-edge from ${GITHUB_SHA}." >> "$GITHUB_STEP_SUMMARY" + # The input stays in the environment and must be a version id. + if ! printf '%s' "$ROLLBACK_VERSION" | grep -Eq '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'; then + echo "rollback_version is not a version id" >&2 + exit 2 fi + versions="$(jq -cn --arg id "$ROLLBACK_VERSION" '[{version_id:$id,percentage:100}]')" + cf -q workers deployments create --worker pm-console-edge --strategy percentage --versions "$versions" + echo "Put pm-console-edge back to version ${ROLLBACK_VERSION}." >> "$GITHUB_STEP_SUMMARY" - name: Check the deployed Worker answers if: steps.secrets.outputs.ready == 'true' && inputs.rollback_version == '' env: diff --git a/pm-stack/console/edge/cloudflare.config.ts b/pm-stack/console/edge/cloudflare.config.ts new file mode 100644 index 0000000000..03c4950c14 --- /dev/null +++ b/pm-stack/console/edge/cloudflare.config.ts @@ -0,0 +1,34 @@ +import { bindings, defineConfig, exports } from "cf/config"; +import { env as processEnv } from "node:process"; +import * as entrypoint from "./src/worker.ts" with { type: "cf-worker" }; + +// Deploy-time config for the cf Workers Versions flow. wrangler.jsonc remains +// the local-dev source; keep its bindings and SQLite migration in sync here. +// The v1 new_sqlite_classes migration maps to the PmEdge SQLite export below. +// Deliberately no route is declared: expose.py assigns/removes it after health. +export default defineConfig({ + worker: { + name: "pm-console-edge", + compatibilityDate: "2026-10-01", + compatibilityFlags: ["nodejs_compat"], + entrypoint, + workersDev: true, + previewUrls: false, + observability: { enabled: true }, + assets: { + htmlHandling: "none", + notFoundHandling: "none", + runWorkerFirst: true, + }, + exports: { + PmEdge: exports.durableObject({ storage: "sqlite" }), + }, + env: { + PUBLIC_HOST: bindings.text("pm.security.cab"), + // The health check verifies the commit currently serving on workers.dev. + VERSION: bindings.text(processEnv.GITHUB_SHA?.slice(0, 12) ?? "local"), + PM: bindings.durableObject({ worker: "pm-console-edge", exportName: "PmEdge" }), + ASSETS: bindings.assets(), + }, + }, +}); diff --git a/pm-stack/console/edge/wrangler.config.ts b/pm-stack/console/edge/wrangler.config.ts new file mode 100644 index 0000000000..0dec0255c8 --- /dev/null +++ b/pm-stack/console/edge/wrangler.config.ts @@ -0,0 +1,4 @@ +import { defineWranglerConfig } from "wrangler/experimental-config"; + +// The cf CLI uses Wrangler's bundler bridge for the existing dist/ assets. +export default defineWranglerConfig({ assetsDirectory: "./dist" }); From d111164e9118726106fc990dff1703699404759d Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 13:54:38 +0000 Subject: [PATCH 2/2] deploy(pm-console): stage protected cf release --- .../workflows/pm-console-edge-cf-release.yml | 341 ++++++++++++++++++ .github/workflows/pm-console-edge-deploy.yml | 104 ++---- 2 files changed, 363 insertions(+), 82 deletions(-) create mode 100644 .github/workflows/pm-console-edge-cf-release.yml diff --git a/.github/workflows/pm-console-edge-cf-release.yml b/.github/workflows/pm-console-edge-cf-release.yml new file mode 100644 index 0000000000..05e530045e --- /dev/null +++ b/.github/workflows/pm-console-edge-cf-release.yml @@ -0,0 +1,341 @@ +name: pm-console-edge cf release (opt-in) + +# Staged alternative to pm-console-edge-deploy.yml. The existing automatic +# Wrangler publisher remains the production path until this manual flow has +# passed parity checks and its environments are protected in repository settings. +# Do not dispatch until both environments exist with required reviewers and a +# main-only deployment policy; GitHub creates missing environments unprotected. +on: + workflow_dispatch: + inputs: + stage: + description: Upload a candidate only, or upload and request production promotion + type: choice + required: true + default: upload-only + options: + - upload-only + - release + +permissions: + contents: read + +concurrency: + group: pm-console-edge-cf-release + cancel-in-progress: false + +jobs: + parity: + name: compare Wrangler and cf builds + if: github.ref == 'refs/heads/main' + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: DeterminateSystems/nix-installer-action@3138316df39ed29be04236d7ffc686fa525866aa # v23 + - uses: DeterminateSystems/magic-nix-cache-action@84c0677f58dcedf3b91f8223ce36a9ea5b3c84b7 # v15 + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 24.22.0 + - name: Test the console and its edge + working-directory: pm-stack/console + run: bun test + - name: Install the deploy tool + working-directory: pm-stack/console/edge + run: npm ci --no-audit --no-fund + - name: Build the repo-pinned cf CLI + env: + NIXPKGS_ALLOW_UNFREE: "1" + run: | + nix build --impure .#messageBridgeDeploy --print-build-logs --out-link "$RUNNER_TEMP/messageBridgeDeploy" + cf_path="$(nix path-info --recursive "$RUNNER_TEMP/messageBridgeDeploy" | awk -F/ '$NF ~ /^cf-[0-9]/ {print; exit}')" + if [ -z "$cf_path" ]; then + echo "cf package was not in the message-bridge deployment closure" >&2 + exit 1 + fi + echo "$cf_path/bin" >> "$GITHUB_PATH" + echo "CF_MODULE=$cf_path/lib/node_modules/cf" >> "$GITHUB_ENV" + test "$("$cf_path/bin/cf" --version)" = "1.0.0-beta.20" + - name: Link cf project config + working-directory: pm-stack/console/edge + run: | + mkdir -p node_modules + ln -s "$CF_MODULE" node_modules/cf + - name: Compare dry-run bindings and bundle size + working-directory: pm-stack/console/edge + run: | + node build.mjs + npx wrangler deploy --dry-run --outdir "$RUNNER_TEMP/wrangler-dry" \ + --var "VERSION:${GITHUB_SHA::12}" > "$RUNNER_TEMP/wrangler.log" 2>&1 + cf -q workers versions create --worker pm-console-edge \ + --tag "parity-${GITHUB_RUN_ID}" --message "parity only" --dry-run \ + > "$RUNNER_TEMP/cf.log" 2>&1 + + grep -Eo 'env\.[A-Z][A-Z0-9_]*' "$RUNNER_TEMP/wrangler.log" | sort -u > "$RUNNER_TEMP/wrangler-bindings" + grep -Eo 'env\.[A-Z][A-Z0-9_]*' "$RUNNER_TEMP/cf.log" | sort -u > "$RUNNER_TEMP/cf-bindings" + diff -u "$RUNNER_TEMP/wrangler-bindings" "$RUNNER_TEMP/cf-bindings" + grep -F 'env.PM (PmEdge' "$RUNNER_TEMP/wrangler.log" "$RUNNER_TEMP/cf.log" + wrangler_size="$(grep -Eo 'Total Upload: [^[:cntrl:]]+' "$RUNNER_TEMP/wrangler.log" | head -n 1)" + cf_size="$(grep -Eo 'Total Upload: [^[:cntrl:]]+' "$RUNNER_TEMP/cf.log" | head -n 1)" + test -n "$wrangler_size" && test "$wrangler_size" = "$cf_size" + grep -F '"tag": "v1"' wrangler.jsonc + grep -F '"new_sqlite_classes": ["PmEdge"]' wrangler.jsonc + grep -F 'PmEdge: exports.durableObject({ storage: "sqlite" })' cloudflare.config.ts + if grep -Eq '^[[:space:]]*(routes|triggers):' cloudflare.config.ts; then + echo "cf config must leave routes and triggers to the existing host flow" >&2 + exit 1 + fi + echo "Wrangler/cf parity passed: bindings, upload size, and the v1 SQLite class declaration match." >> "$GITHUB_STEP_SUMMARY" + + upload: + name: upload cf version (protected) + if: github.ref == 'refs/heads/main' && needs.parity.result == 'success' + needs: parity + runs-on: ubuntu-latest + timeout-minutes: 30 + environment: + name: pm-console-edge-upload + outputs: + version_id: ${{ steps.upload.outputs.version_id }} + version_tag: ${{ steps.upload.outputs.version_tag }} + version_message: ${{ steps.upload.outputs.version_message }} + source_sha: ${{ steps.upload.outputs.source_sha }} + current_version_id: ${{ steps.preflight.outputs.current_version_id }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: DeterminateSystems/nix-installer-action@3138316df39ed29be04236d7ffc686fa525866aa # v23 + - uses: DeterminateSystems/magic-nix-cache-action@84c0677f58dcedf3b91f8223ce36a9ea5b3c84b7 # v15 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 24.22.0 + - name: Install the deploy tool + working-directory: pm-stack/console/edge + run: npm ci --no-audit --no-fund + - name: Build the repo-pinned cf CLI + env: + NIXPKGS_ALLOW_UNFREE: "1" + run: | + nix build --impure .#messageBridgeDeploy --print-build-logs --out-link "$RUNNER_TEMP/messageBridgeDeploy" + cf_path="$(nix path-info --recursive "$RUNNER_TEMP/messageBridgeDeploy" | awk -F/ '$NF ~ /^cf-[0-9]/ {print; exit}')" + if [ -z "$cf_path" ]; then + echo "cf package was not in the message-bridge deployment closure" >&2 + exit 1 + fi + echo "$cf_path/bin" >> "$GITHUB_PATH" + echo "CF_MODULE=$cf_path/lib/node_modules/cf" >> "$GITHUB_ENV" + test "$("$cf_path/bin/cf" --version)" = "1.0.0-beta.20" + - name: Link cf project config + working-directory: pm-stack/console/edge + run: | + mkdir -p node_modules + ln -s "$CF_MODULE" node_modules/cf + - name: Build candidate + working-directory: pm-stack/console/edge + run: node build.mjs + - name: Check upload environment secrets + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CF_PM_EDGE_UPLOAD_API_TOKEN }} + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CF_PM_EDGE_UPLOAD_ACCOUNT_ID }} + run: | + if [ -z "$CLOUDFLARE_API_TOKEN" ] || [ -z "$CLOUDFLARE_ACCOUNT_ID" ]; then + echo "Configure CF_PM_EDGE_UPLOAD_API_TOKEN and CF_PM_EDGE_UPLOAD_ACCOUNT_ID as secrets in the pm-console-edge-upload environment." >&2 + exit 1 + fi + - name: Capture current serving version + id: preflight + working-directory: pm-stack/console/edge + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CF_PM_EDGE_UPLOAD_API_TOKEN }} + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CF_PM_EDGE_UPLOAD_ACCOUNT_ID }} + run: | + current_version_id="$(cf -q workers deployments list --worker pm-console-edge | node -e ' + const data = JSON.parse(require("node:fs").readFileSync(0, "utf8")); + const items = [data, data?.result, data?.result?.items, data?.items, data?.deployments].find(Array.isArray); + if (!items?.length) throw new Error("could not read Worker deployments"); + const time = (item) => Date.parse(item.metadata?.created_on ?? item.created_on ?? 0) || 0; + const latest = [...items].sort((a, b) => time(b) - time(a))[0]; + const active = (latest.versions ?? []).filter((v) => Number(v.percentage) > 0); + if (active.length !== 1 || Number(active[0].percentage) !== 100 || !active[0].version_id) { + throw new Error("current deployment is not a single version at 100%; refusing to stage"); + } + process.stdout.write(active[0].version_id); + ')" + if ! printf '%s' "$current_version_id" | grep -Eq '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'; then + echo "Cloudflare returned an invalid current Worker version id" >&2 + exit 1 + fi + echo "current_version_id=$current_version_id" >> "$GITHUB_OUTPUT" + - name: Upload candidate version + id: upload + working-directory: pm-stack/console/edge + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CF_PM_EDGE_UPLOAD_API_TOKEN }} + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CF_PM_EDGE_UPLOAD_ACCOUNT_ID }} + run: | + version_tag="git-${GITHUB_SHA}-r${GITHUB_RUN_ID}a${GITHUB_RUN_ATTEMPT}" + version_message="github-run=${GITHUB_RUN_ID} attempt=${GITHUB_RUN_ATTEMPT} sha=${GITHUB_SHA}" + cf -q workers versions create --worker pm-console-edge \ + --tag "$version_tag" --message "$version_message" + version_id="$(cf -q workers versions list --worker-id pm-console-edge | VERSION_TAG="$version_tag" node -e ' + const data = JSON.parse(require("node:fs").readFileSync(0, "utf8")); + const items = [data, data?.result, data?.result?.items, data?.items, data?.versions].find(Array.isArray); + if (!items) throw new Error("cf workers versions list returned an unexpected response"); + const tag = process.env.VERSION_TAG; + const matches = items.filter((v) => (v.annotations?.["workers/tag"] ?? v.metadata?.annotations?.["workers/tag"]) === tag); + matches.sort((a, b) => Date.parse(b.metadata?.created_on ?? b.created_on ?? 0) - Date.parse(a.metadata?.created_on ?? a.created_on ?? 0)); + if (!matches[0]?.id) throw new Error(`uploaded version with tag ${tag} was not found`); + process.stdout.write(matches[0].id); + ')" + if ! printf '%s' "$version_id" | grep -Eq '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'; then + echo "cf returned an invalid Worker version id" >&2 + exit 1 + fi + echo "version_id=$version_id" >> "$GITHUB_OUTPUT" + echo "version_tag=$version_tag" >> "$GITHUB_OUTPUT" + echo "version_message=$version_message" >> "$GITHUB_OUTPUT" + echo "source_sha=$GITHUB_SHA" >> "$GITHUB_OUTPUT" + echo "Uploaded candidate ${version_id} from ${GITHUB_SHA} (tag ${version_tag}); production was not changed." >> "$GITHUB_STEP_SUMMARY" + + promote: + name: promote cf version (protected) + if: github.ref == 'refs/heads/main' && inputs.stage == 'release' && needs.upload.result == 'success' + needs: upload + runs-on: ubuntu-latest + timeout-minutes: 20 + # Match the legacy workflow's group so the two production promoters cannot race. + concurrency: + group: pm-console-edge deploy + cancel-in-progress: false + environment: + name: pm-console-edge-production + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ needs.upload.outputs.source_sha }} + fetch-depth: 0 + - uses: DeterminateSystems/nix-installer-action@3138316df39ed29be04236d7ffc686fa525866aa # v23 + - uses: DeterminateSystems/magic-nix-cache-action@84c0677f58dcedf3b91f8223ce36a9ea5b3c84b7 # v15 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 24.22.0 + - name: Build the repo-pinned cf CLI + env: + NIXPKGS_ALLOW_UNFREE: "1" + run: | + nix build --impure .#messageBridgeDeploy --print-build-logs --out-link "$RUNNER_TEMP/messageBridgeDeploy" + cf_path="$(nix path-info --recursive "$RUNNER_TEMP/messageBridgeDeploy" | awk -F/ '$NF ~ /^cf-[0-9]/ {print; exit}')" + if [ -z "$cf_path" ]; then + echo "cf package was not in the message-bridge deployment closure" >&2 + exit 1 + fi + echo "$cf_path/bin" >> "$GITHUB_PATH" + test "$("$cf_path/bin/cf" --version)" = "1.0.0-beta.20" + - name: Check promotion environment secrets + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CF_PM_EDGE_PROMOTE_API_TOKEN }} + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CF_PM_EDGE_PROMOTE_ACCOUNT_ID }} + run: | + if [ -z "$CLOUDFLARE_API_TOKEN" ] || [ -z "$CLOUDFLARE_ACCOUNT_ID" ]; then + echo "Configure CF_PM_EDGE_PROMOTE_API_TOKEN and CF_PM_EDGE_PROMOTE_ACCOUNT_ID as secrets in the pm-console-edge-production environment." >&2 + exit 1 + fi + - name: Verify candidate provenance and serving version + id: verify + working-directory: pm-stack/console/edge + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CF_PM_EDGE_PROMOTE_API_TOKEN }} + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CF_PM_EDGE_PROMOTE_ACCOUNT_ID }} + VERSION_ID: ${{ needs.upload.outputs.version_id }} + VERSION_TAG: ${{ needs.upload.outputs.version_tag }} + VERSION_MESSAGE: ${{ needs.upload.outputs.version_message }} + SOURCE_SHA: ${{ needs.upload.outputs.source_sha }} + EXPECTED_CURRENT_VERSION_ID: ${{ needs.upload.outputs.current_version_id }} + run: | + if [ "$SOURCE_SHA" != "$GITHUB_SHA" ]; then + echo "candidate source SHA does not match this protected workflow run" >&2 + exit 1 + fi + git fetch origin main + if ! git merge-base --is-ancestor "$SOURCE_SHA" origin/main; then + echo "candidate source commit is no longer an ancestor of main" >&2 + exit 1 + fi + cf -q workers versions list --worker-id pm-console-edge | node -e ' + const data = JSON.parse(require("node:fs").readFileSync(0, "utf8")); + const items = [data, data?.result, data?.result?.items, data?.items, data?.versions].find(Array.isArray); + const version = items?.find((v) => v.id === process.env.VERSION_ID); + const tag = version?.annotations?.["workers/tag"] ?? version?.metadata?.annotations?.["workers/tag"]; + const message = version?.annotations?.["workers/message"] ?? version?.metadata?.annotations?.["workers/message"]; + if (!version || tag !== process.env.VERSION_TAG || message !== process.env.VERSION_MESSAGE) { + throw new Error("candidate version id/tag/message provenance check failed"); + } + ' + current_version_id="$(cf -q workers deployments list --worker pm-console-edge | node -e ' + const data = JSON.parse(require("node:fs").readFileSync(0, "utf8")); + const items = [data, data?.result, data?.result?.items, data?.items, data?.deployments].find(Array.isArray); + if (!items?.length) throw new Error("could not read current Worker deployment"); + const time = (item) => Date.parse(item.metadata?.created_on ?? item.created_on ?? 0) || 0; + const latest = [...items].sort((a, b) => time(b) - time(a))[0]; + const active = (latest.versions ?? []).filter((v) => Number(v.percentage) > 0); + if (active.length !== 1 || Number(active[0].percentage) !== 100 || !active[0].version_id) { + throw new Error("current deployment is not a single version at 100%; refusing promotion"); + } + process.stdout.write(active[0].version_id); + ')" + if [ "$current_version_id" != "$EXPECTED_CURRENT_VERSION_ID" ]; then + echo "current serving version changed since upload; refusing stale promotion" >&2 + exit 1 + fi + echo "Candidate provenance verified; expected current version still serves at 100%." >> "$GITHUB_STEP_SUMMARY" + - name: Promote candidate version + working-directory: pm-stack/console/edge + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CF_PM_EDGE_PROMOTE_API_TOKEN }} + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CF_PM_EDGE_PROMOTE_ACCOUNT_ID }} + VERSION_ID: ${{ needs.upload.outputs.version_id }} + run: | + versions="$(VERSION_ID="$VERSION_ID" node -e 'process.stdout.write(JSON.stringify([{version_id:process.env.VERSION_ID,percentage:100}]))')" + cf -q workers deployments create --worker pm-console-edge --strategy percentage --versions "$versions" + - name: Check deployed version and production health + working-directory: pm-stack/console/edge + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CF_PM_EDGE_PROMOTE_API_TOKEN }} + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CF_PM_EDGE_PROMOTE_ACCOUNT_ID }} + VERSION_ID: ${{ needs.upload.outputs.version_id }} + SOURCE_SHA: ${{ needs.upload.outputs.source_sha }} + run: | + serving_version="" + for attempt in $(seq 1 20); do + serving_version="$(cf -q workers deployments list --worker pm-console-edge | node -e ' + const data = JSON.parse(require("node:fs").readFileSync(0, "utf8")); + const items = [data, data?.result, data?.result?.items, data?.items, data?.deployments].find(Array.isArray); + if (!items?.length) process.exit(0); + const time = (item) => Date.parse(item.metadata?.created_on ?? item.created_on ?? 0) || 0; + const latest = [...items].sort((a, b) => time(b) - time(a))[0]; + const active = (latest.versions ?? []).filter((v) => Number(v.percentage) > 0); + if (active.length === 1 && Number(active[0].percentage) === 100) process.stdout.write(active[0].version_id ?? ""); + ' 2>/dev/null || true)" + [ "$serving_version" = "$VERSION_ID" ] && break + sleep 6 + done + if [ "$serving_version" != "$VERSION_ID" ]; then + echo "the latest deployment does not serve candidate ${VERSION_ID} at 100%" >&2 + exit 1 + fi + sub="$(curl -fsS -H "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}" \ + "https://api.cloudflare.com/client/v4/accounts/${CLOUDFLARE_ACCOUNT_ID}/workers/subdomain" \ + | python3 -c 'import json,sys; print(json.load(sys.stdin)["result"]["subdomain"])')" + url="https://pm-console-edge.${sub}.workers.dev/console/health" + want="${SOURCE_SHA::12}" + got="" + for attempt in $(seq 1 20); do + got="$(curl -fsS --max-time 10 "$url" | python3 -c 'import json,sys; d=json.load(sys.stdin); print(d.get("version") if d.get("ok") and d.get("edge") else "")' 2>/dev/null || true)" + [ "$got" = "$want" ] && break + sleep 6 + done + if [ "$got" != "$want" ]; then + echo "pm-console-edge did not pass its health check for ${want} (last answer: ${got:-none})" >&2 + exit 1 + fi + echo "Promoted and verified pm-console-edge version ${VERSION_ID} from ${SOURCE_SHA}." >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/pm-console-edge-deploy.yml b/.github/workflows/pm-console-edge-deploy.yml index 4757f896b6..0e6425a8cd 100644 --- a/.github/workflows/pm-console-edge-deploy.yml +++ b/.github/workflows/pm-console-edge-deploy.yml @@ -6,10 +6,10 @@ name: pm-console-edge deploy # Deploys the Worker that serves the PM app from the edge # (pm-stack/console/edge): every push to main that touches the console, # or a manual run, runs the console's tests (which drive the Worker's -# routing and state against the host's real handler), bundles the Worker, -# uploads a cf Worker version, explicitly promotes it, and uses the -# CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID repository secrets (the -# same credentials used by message-bridge). +# routing and state against the host's real handler), bundles the +# Worker, and uploads it with the CLOUDFLARE_API_TOKEN and +# CLOUDFLARE_ACCOUNT_ID repository secrets, the ones message-bridge +# deploys with. # # The Worker has no secrets: the keys it uses it makes itself, or are # published by the host. It has no route here either. The host's @@ -47,9 +47,6 @@ concurrency: jobs: deploy: name: deploy pm-console-edge - # workflow_dispatch can select a non-main ref. Never expose repository - # Cloudflare secrets to a workflow copy from another ref. - if: github.ref == 'refs/heads/main' runs-on: ubuntu-latest timeout-minutes: 15 steps: @@ -65,100 +62,43 @@ jobs: echo "ready=false" >> "$GITHUB_OUTPUT" echo "Skipped the upload: set the CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID repository secrets to deploy pm-console-edge from the repo." >> "$GITHUB_STEP_SUMMARY" fi - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - uses: DeterminateSystems/nix-installer-action@3138316df39ed29be04236d7ffc686fa525866aa # v23 - - uses: DeterminateSystems/magic-nix-cache-action@84c0677f58dcedf3b91f8223ce36a9ea5b3c84b7 # v15 + - uses: actions/checkout@v7 - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 - - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + - uses: actions/setup-node@v7 with: - node-version: 24.22.0 + node-version: 24 - name: Test the console and its edge working-directory: pm-stack/console run: bun test - name: Install the deploy tool working-directory: pm-stack/console/edge run: npm ci --no-audit --no-fund - - name: Build the repo-pinned cf CLI - env: - NIXPKGS_ALLOW_UNFREE: "1" - run: | - # Reuse the cf and Wrangler packages already pinned by the repo flake. - nix build --impure .#messageBridgeDeploy --print-build-logs --out-link "$RUNNER_TEMP/messageBridgeDeploy" - cf_path="$(nix path-info --recursive "$RUNNER_TEMP/messageBridgeDeploy" | awk -F/ '$NF ~ /^cf-[0-9]/ {print; exit}')" - if [ -z "$cf_path" ]; then - echo "cf package was not in the message-bridge deployment closure" >&2 - exit 1 - fi - echo "$cf_path/bin" >> "$GITHUB_PATH" - echo "CF_MODULE=$cf_path/lib/node_modules/cf" >> "$GITHUB_ENV" - test "$("$cf_path/bin/cf" --version)" = "1.0.0-beta.20" - - name: Link cf project config - working-directory: pm-stack/console/edge - run: | - mkdir -p node_modules - ln -s "$CF_MODULE" node_modules/cf - name: Bundle the Worker working-directory: pm-stack/console/edge run: | node build.mjs - cf -q workers versions create --worker pm-console-edge \ - --tag "git-${GITHUB_SHA}" \ - --message "git ${GITHUB_SHA}" \ - --dry-run - - name: Upload Worker version - id: upload - if: steps.secrets.outputs.ready == 'true' && inputs.rollback_version == '' - working-directory: pm-stack/console/edge - env: - CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} - CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} - VERSION_TAG: git-${{ github.sha }} - run: | - cf -q workers versions create --worker pm-console-edge \ - --tag "$VERSION_TAG" \ - --message "git ${GITHUB_SHA}" - version_id="$(cf -q workers versions list --worker-id pm-console-edge | VERSION_TAG="$VERSION_TAG" node -e ' - const data = JSON.parse(require("node:fs").readFileSync(0, "utf8")); - const items = [data, data?.result, data?.result?.items, data?.items, data?.versions].find(Array.isArray); - if (!items) throw new Error("cf workers versions list returned an unexpected response"); - const tag = process.env.VERSION_TAG; - const matches = items.filter((v) => (v.annotations?.["workers/tag"] ?? v.metadata?.annotations?.["workers/tag"]) === tag); - matches.sort((a, b) => Date.parse(b.metadata?.created_on ?? b.created_on ?? 0) - Date.parse(a.metadata?.created_on ?? a.created_on ?? 0)); - if (!matches[0]?.id) throw new Error(`uploaded version with tag ${tag} was not found`); - process.stdout.write(matches[0].id); - ')" - if ! printf '%s' "$version_id" | grep -Eq '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'; then - echo "cf returned an invalid Worker version id" >&2 - exit 1 - fi - echo "version_id=$version_id" >> "$GITHUB_OUTPUT" - - name: Promote uploaded version - if: steps.secrets.outputs.ready == 'true' && inputs.rollback_version == '' - working-directory: pm-stack/console/edge - env: - CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} - CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} - VERSION_ID: ${{ steps.upload.outputs.version_id }} - run: | - versions="$(jq -cn --arg id "$VERSION_ID" '[{version_id:$id,percentage:100}]')" - cf -q workers deployments create --worker pm-console-edge --strategy percentage --versions "$versions" - echo "Promoted pm-console-edge version ${VERSION_ID} from ${GITHUB_SHA}." >> "$GITHUB_STEP_SUMMARY" - - name: Promote rollback version - if: steps.secrets.outputs.ready == 'true' && inputs.rollback_version != '' + npx wrangler deploy --dry-run --outdir .wrangler/dry + - name: Deploy + if: steps.secrets.outputs.ready == 'true' working-directory: pm-stack/console/edge env: CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} ROLLBACK_VERSION: ${{ inputs.rollback_version }} run: | - # The input stays in the environment and must be a version id. - if ! printf '%s' "$ROLLBACK_VERSION" | grep -Eq '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'; then - echo "rollback_version is not a version id" >&2 - exit 2 + # The input goes through the env, never into the script text, + # and must look like a version id before it is used. + if [ -n "${ROLLBACK_VERSION:-}" ]; then + if ! printf '%s' "$ROLLBACK_VERSION" | grep -Eq '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'; then + echo "rollback_version is not a version id" >&2 + exit 2 + fi + npx wrangler rollback "$ROLLBACK_VERSION" --yes --message "rollback from workflow run ${GITHUB_RUN_ID}" + echo "Put pm-console-edge back to version ${ROLLBACK_VERSION}." >> "$GITHUB_STEP_SUMMARY" + else + npx wrangler deploy --var "VERSION:${GITHUB_SHA::12}" --message "git ${GITHUB_SHA}" + echo "Deployed pm-console-edge from ${GITHUB_SHA}." >> "$GITHUB_STEP_SUMMARY" fi - versions="$(jq -cn --arg id "$ROLLBACK_VERSION" '[{version_id:$id,percentage:100}]')" - cf -q workers deployments create --worker pm-console-edge --strategy percentage --versions "$versions" - echo "Put pm-console-edge back to version ${ROLLBACK_VERSION}." >> "$GITHUB_STEP_SUMMARY" - name: Check the deployed Worker answers if: steps.secrets.outputs.ready == 'true' && inputs.rollback_version == '' env: