Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
158 changes: 158 additions & 0 deletions .github/workflows/queue-transport-alert-deploy.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
name: queue-transport-alert Worker deployment

on:
workflow_dispatch:
inputs:
action:
description: Upload a code-only version or promote an uploaded version
required: true
type: choice
options: [upload, promote]
confirm:
description: Confirm the selected Cloudflare operation
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
type: string

permissions:
actions: read
contents: read

concurrency:
group: queue-transport-alert-cloudflare-deploy
cancel-in-progress: false

jobs:
verify-environment:
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:
- 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 ((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[];
.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:
needs: verify-environment
runs-on: ubuntu-latest
timeout-minutes: 20
environment: cloudflare-queue-transport-alert
steps:
- name: Validate dispatch inputs
env:
ACTION: ${{ inputs.action }}
RUN_ID: ${{ inputs.upload_run_id }}
run: |
if [[ "$ACTION" == promote ]]; then
[[ "$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: Download handoff from exact upload run
if: inputs.action == 'promote'
uses: actions/download-artifact@v4
with:
name: qta-version-${{ inputs.upload_run_id }}
run-id: ${{ inputs.upload_run_id }}
github-token: ${{ github.token }}
path: ${{ runner.temp }}/qta-handoff
- name: Verify upload provenance and baseline receipt
if: inputs.action == 'promote'
id: handoff
env:
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"
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: Check out exact uploaded source
if: inputs.action == 'promote'
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
with:
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
- name: Upload code-only Worker version
if: inputs.action == 'upload'
env:
QTA_GHA: '1'
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 }}
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'
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" =~ ^[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"
23 changes: 23 additions & 0 deletions pkgs/queue-transport-alert/worker/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -120,3 +120,26 @@ 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.
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
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.
38 changes: 38 additions & 0 deletions pkgs/queue-transport-alert/worker/deploy-lib.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,44 @@ 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;
}

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));
Expand Down
71 changes: 66 additions & 5 deletions pkgs/queue-transport-alert/worker/deploy.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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, ghaUploadIdentity, uploadedVersionId, hasExactUpload } from "./deploy-lib.mjs";

const here = dirname(fileURLToPath(import.meta.url));
const WORKER = "queue-transport-alert";
Expand All @@ -55,20 +55,23 @@ 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",
accessId: process.env.QTA_ACCESS_ID_SECRET ?? "cloudflare.access.queue-broker-client-id",
accessSecret: process.env.QTA_ACCESS_SECRET_SECRET ?? "cloudflare.access.queue-broker-client-secret",
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
Expand Down Expand Up @@ -96,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"],
});
Expand Down Expand Up @@ -154,7 +157,65 @@ async function verify(versionId) {
console.log(`verified: version ${versionId} serves 100%; ${url} reports the broker ${status.status ?? "unknown"}`);
}

if (gha && deployVersion === null) {
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");
}
// 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();
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");
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: 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,
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");
}
await (await import("node:fs/promises")).writeFile(process.env.QTA_HANDOFF_FILE, `${JSON.stringify(handoff, null, 2)}\n`, { mode: 0o600 });
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 !== 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");
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");
}
}
if (dryRun) {
console.log(`dry run: would deploy ${WORKER} at existing version ${deployVersion} (100%); nothing created`);
process.exit(0);
Expand Down
3 changes: 3 additions & 0 deletions pkgs/queue-transport-alert/worker/deploy.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading