diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 0859eca33..02a5a640e 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -20,6 +20,9 @@ jobs:
- name: Scan for security vulnerabilities in Ruby dependencies
run: bin/brakeman --no-pager
+ - name: Validate preview deploy workflow hardening
+ run: ruby bin/preview_deploy_security_check.rb
+
scan_js:
runs-on: ubuntu-latest
timeout-minutes: 10
diff --git a/.github/workflows/preview-deploy.yml b/.github/workflows/preview-deploy.yml
index 06b9c61e0..654c170e0 100644
--- a/.github/workflows/preview-deploy.yml
+++ b/.github/workflows/preview-deploy.yml
@@ -16,18 +16,26 @@ jobs:
name: Deploy to Cloudflare Containers
runs-on: ubuntu-latest
timeout-minutes: 15
+ concurrency:
+ group: preview-deploy-${{ github.event.pull_request.number }}
+ cancel-in-progress: true
+ environment:
+ name: preview
permissions:
actions: read
contents: read
pull-requests: write
deployments: write
+ env:
+ PR_NUMBER: ${{ github.event.pull_request.number }}
+ HEAD_SHA: ${{ github.event.pull_request.head.sha }}
steps:
- name: Wait for PR CI to pass
- uses: actions/github-script@v7
+ uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7
with:
script: |
- const headSha = context.payload.pull_request.head.sha;
+ const headSha = process.env.HEAD_SHA;
const timeoutMs = 10 * 60 * 1000;
const pollMs = 15 * 1000;
const startedAt = Date.now();
@@ -65,35 +73,62 @@ jobs:
core.setFailed(`Timed out waiting for Pull Request workflow for ${headSha}. Last state: ${lastState}`);
- - name: Checkout code
- uses: actions/checkout@v5
+ - name: Checkout PR code
+ uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5
+ with:
+ path: pr
+ persist-credentials: false
+
+ - name: Checkout trusted preview tooling
+ uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5
+ with:
+ ref: ${{ github.event.pull_request.base.sha }}
+ path: trusted
+ persist-credentials: false
+ sparse-checkout: |
+ workers/preview
- name: Setup Node.js
- uses: actions/setup-node@v6
+ uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6
with:
node-version: "24"
- - name: Install Wrangler dependencies
- working-directory: workers/preview
- run: npm install
-
- - name: Configure preview files for this PR
- working-directory: workers/preview
+ - name: Prepare trusted preview deploy workspace
run: |
- sed -i "s/\${PR_NUMBER}/${{ github.event.pull_request.number }}/g" wrangler.toml
- sed -i "s/\${PR_NUMBER}/${{ github.event.pull_request.number }}/g" src/index.ts
- cat wrangler.toml
+ set -euo pipefail
+
+ preview_dir="$RUNNER_TEMP/sure-preview-worker"
+ rm -rf "$preview_dir"
+ mkdir -p "$preview_dir"
+
+ cp trusted/workers/preview/package.json "$preview_dir/package.json"
+ cp trusted/workers/preview/package-lock.json "$preview_dir/package-lock.json"
+ cp trusted/workers/preview/tsconfig.json "$preview_dir/tsconfig.json"
+ cp trusted/workers/preview/wrangler.toml "$preview_dir/wrangler.toml"
+ cp -R pr/workers/preview/src "$preview_dir/src"
+
+ sed -i "s/\${PR_NUMBER}/${PR_NUMBER}/g" "$preview_dir/wrangler.toml"
+ sed -i "s/\${PR_NUMBER}/${PR_NUMBER}/g" "$preview_dir/src/index.ts"
+ sed -i \
+ "s#image = \"../../Dockerfile.preview\"#image = \"${GITHUB_WORKSPACE}/pr/Dockerfile.preview\"#" \
+ "$preview_dir/wrangler.toml"
+
+ cat "$preview_dir/wrangler.toml"
+ cd "$preview_dir"
+ npm ci --ignore-scripts --no-audit --no-fund
- name: Create GitHub Deployment
id: deployment
- uses: actions/github-script@v7
+ uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7
with:
script: |
+ const prNumber = process.env.PR_NUMBER;
+ const headSha = process.env.HEAD_SHA;
const deployment = await github.rest.repos.createDeployment({
owner: context.repo.owner,
repo: context.repo.repo,
- ref: context.payload.pull_request.head.sha,
- environment: `preview-pr-${{ github.event.pull_request.number }}`,
+ ref: headSha,
+ environment: `preview-pr-${prNumber}`,
auto_merge: false,
required_contexts: [],
description: 'PR Preview Deployment'
@@ -103,15 +138,18 @@ jobs:
- name: Deploy to Cloudflare Containers
id: deploy
- working-directory: workers/preview
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
+ CLOUDFLARE_WORKERS_SUBDOMAIN: ${{ secrets.CLOUDFLARE_WORKERS_SUBDOMAIN }}
run: |
- npx wrangler deploy --var "PR_NUMBER:${{ github.event.pull_request.number }}"
+ set -euo pipefail
+
+ cd "$RUNNER_TEMP/sure-preview-worker"
+ ./node_modules/.bin/wrangler deploy --config wrangler.toml --var "PR_NUMBER:${PR_NUMBER}"
# Get the deployment URL
- PREVIEW_URL="https://sure-preview-${{ github.event.pull_request.number }}.${{ secrets.CLOUDFLARE_WORKERS_SUBDOMAIN }}.workers.dev"
+ PREVIEW_URL="https://sure-preview-${PR_NUMBER}.${CLOUDFLARE_WORKERS_SUBDOMAIN}.workers.dev"
echo "preview_url=${PREVIEW_URL}" >> "$GITHUB_OUTPUT"
- name: Warm preview container
@@ -123,25 +161,33 @@ jobs:
- name: Update Deployment Status
if: always() && steps.deployment.outputs.result
- uses: actions/github-script@v7
+ uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7
+ env:
+ DEPLOYMENT_ID: ${{ steps.deployment.outputs.result }}
+ PREVIEW_URL: ${{ steps.deploy.outputs.preview_url }}
with:
script: |
const state = '${{ job.status }}' === 'success' ? 'success' : 'failure';
+ const previewUrl = process.env.PREVIEW_URL || undefined;
await github.rest.repos.createDeploymentStatus({
owner: context.repo.owner,
repo: context.repo.repo,
- deployment_id: ${{ steps.deployment.outputs.result }},
+ deployment_id: Number(process.env.DEPLOYMENT_ID),
state: state,
- environment_url: state === 'success' ? '${{ steps.deploy.outputs.preview_url }}' : undefined,
+ environment_url: state === 'success' ? previewUrl : undefined,
description: state === 'success' ? 'Preview deployed successfully' : 'Preview deployment failed'
});
- name: Comment on PR
if: success()
- uses: actions/github-script@v7
+ uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7
+ env:
+ PREVIEW_URL: ${{ steps.deploy.outputs.preview_url }}
with:
script: |
- const previewUrl = '${{ steps.deploy.outputs.preview_url }}';
+ const previewUrl = process.env.PREVIEW_URL;
+ const issueNumber = Number(process.env.PR_NUMBER);
+ const headSha = process.env.HEAD_SHA;
const commentBody = `## 🚀 Preview Deployment Ready
Your preview environment has been deployed to Cloudflare Containers with the PR's Docker image.
@@ -152,13 +198,13 @@ jobs:
> 💤 The container will sleep after 30 minutes of inactivity and wake on the next request.
---
- Deployed from commit ${{ github.event.pull_request.head.sha }}`;
+ Deployed from commit ${headSha}`;
// Find existing comment
const { data: comments } = await github.rest.issues.listComments({
owner: context.repo.owner,
repo: context.repo.repo,
- issue_number: ${{ github.event.pull_request.number }}
+ issue_number: issueNumber
});
const botComment = comments.find(comment =>
@@ -177,15 +223,14 @@ jobs:
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
- issue_number: ${{ github.event.pull_request.number }},
+ issue_number: issueNumber,
body: commentBody
});
}
- name: Store cleanup metadata
if: success()
- uses: actions/upload-artifact@v6
+ uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6
with:
- name: preview-cleanup-pr-${{ github.event.pull_request.number }}
- path: |
- workers/preview/wrangler.toml
+ name: preview-cleanup-pr-${{ env.PR_NUMBER }}
+ path: ${{ runner.temp }}/sure-preview-worker/wrangler.toml
retention-days: 2
diff --git a/bin/preview_deploy_security_check.rb b/bin/preview_deploy_security_check.rb
new file mode 100644
index 000000000..fa4eb493d
--- /dev/null
+++ b/bin/preview_deploy_security_check.rb
@@ -0,0 +1,136 @@
+#!/usr/bin/env ruby
+# frozen_string_literal: true
+
+%w[json pathname yaml].each { |library| require library }
+
+ROOT = File.expand_path("..", __dir__)
+WORKFLOW_PATH = File.join(ROOT, ".github/workflows/preview-deploy.yml")
+LOCKFILE_PATH = File.join(ROOT, "workers/preview/package-lock.json")
+PINNED_ACTION = /\A[^@\s]+@[a-f0-9]{40}\z/
+INLINE_SECRET_EXPRESSION = /\$\{\{\s*secrets\s*(?:\.|\[)/i
+INLINE_PR_EXPRESSION = /
+ \$\{\{\s*
+ github\s*
+ (?:\.\s*event|\[\s*['"]event['"]\s*\])\s*
+ (?:\.\s*pull_request|\[\s*['"]pull_request['"]\s*\])
+/ix
+PR_CONTROLLED_WORKDIR = %r{\A(?:pr|workers/preview)(?:/|\z)}
+GITHUB_WORKSPACE_PREFIX = %r{
+ \A
+ (?:
+ \$GITHUB_WORKSPACE |
+ \$\{\{\s*github\s*(?:\.\s*workspace|\[\s*['"]workspace['"]\s*\])\s*\}\}
+ )
+ (?:/|\z)
+}ix
+EXPECTED_PERMISSIONS = { "actions" => "read", "contents" => "read", "pull-requests" => "write", "deployments" => "write" }.freeze
+EXPECTED_SECRET_ENV = %w[CLOUDFLARE_ACCOUNT_ID CLOUDFLARE_API_TOKEN CLOUDFLARE_WORKERS_SUBDOMAIN].freeze
+REQUIRED_PREPARE_LINES = [
+ 'cp trusted/workers/preview/package.json "$preview_dir/package.json"',
+ 'cp trusted/workers/preview/package-lock.json "$preview_dir/package-lock.json"',
+ 'cp trusted/workers/preview/tsconfig.json "$preview_dir/tsconfig.json"',
+ 'cp trusted/workers/preview/wrangler.toml "$preview_dir/wrangler.toml"',
+ 'cp -R pr/workers/preview/src "$preview_dir/src"',
+ 'image = \"${GITHUB_WORKSPACE}/pr/Dockerfile.preview\"',
+ "npm ci --ignore-scripts --no-audit --no-fund"
+].freeze
+
+def fail_check(message)
+ warn "preview-deploy security check failed: #{message}"
+ exit 1
+end
+
+def assert(value, message)
+ fail_check(message) unless value
+end
+
+def step!(steps, name)
+ steps.find { |step| step["name"] == name } || fail_check("missing #{name.inspect} step")
+end
+
+def run(step)
+ step.fetch("run", "")
+end
+
+def assert_run_includes(step, *needles)
+ script = run(step)
+ needles.each { |needle| assert(script.include?(needle), "#{step["name"]} must include #{needle.inspect}") }
+ script
+end
+
+def normalized_working_directory(value)
+ path = value.to_s.strip.sub(GITHUB_WORKSPACE_PREFIX, "")
+ normalized = Pathname.new(path).cleanpath.to_s
+
+ normalized == "." ? "" : normalized
+end
+
+def environment_name(job)
+ environment = job["environment"]
+ environment.is_a?(Hash) ? environment["name"] : environment
+end
+
+workflow = YAML.safe_load_file(WORKFLOW_PATH, aliases: true)
+lockfile = JSON.parse(File.read(LOCKFILE_PATH))
+job = workflow.fetch("jobs").fetch("deploy-preview")
+steps = job.fetch("steps")
+step_names = steps.map { |step| step["name"] }
+pr_checkout = step!(steps, "Checkout PR code")
+trusted_checkout = step!(steps, "Checkout trusted preview tooling")
+prepare = step!(steps, "Prepare trusted preview deploy workspace")
+deploy = step!(steps, "Deploy to Cloudflare Containers")
+wrangler = lockfile.fetch("packages").fetch("node_modules/wrangler")
+
+[
+ [ "job permissions", job.fetch("permissions"), EXPECTED_PERMISSIONS ],
+ [ "job environment", environment_name(job), "preview" ],
+ [ "concurrency group", job.dig("concurrency", "group"), "preview-deploy-${{ github.event.pull_request.number }}" ],
+ [ "concurrency cancellation", job.dig("concurrency", "cancel-in-progress"), true ],
+ [ "PR_NUMBER env", job.dig("env", "PR_NUMBER"), "${{ github.event.pull_request.number }}" ],
+ [ "HEAD_SHA env", job.dig("env", "HEAD_SHA"), "${{ github.event.pull_request.head.sha }}" ],
+ [ "PR checkout path", pr_checkout.dig("with", "path"), "pr" ],
+ [ "PR checkout credentials", pr_checkout.dig("with", "persist-credentials"), false ],
+ [ "trusted checkout ref", trusted_checkout.dig("with", "ref"), "${{ github.event.pull_request.base.sha }}" ],
+ [ "trusted checkout path", trusted_checkout.dig("with", "path"), "trusted" ],
+ [ "trusted checkout credentials", trusted_checkout.dig("with", "persist-credentials"), false ],
+ [ "deploy secret env", deploy.fetch("env").keys.sort, EXPECTED_SECRET_ENV ],
+ [ "Wrangler binary", wrangler.dig("bin", "wrangler"), "bin/wrangler.js" ]
+].each { |label, actual, expected| assert(actual == expected, "#{label}: expected #{actual.inspect} to equal #{expected.inspect}") }
+
+assert(lockfile.dig("packages", "", "devDependencies", "wrangler"), "Wrangler must stay a root dev dependency")
+assert(lockfile.fetch("lockfileVersion") >= 3, "preview tooling lockfile must preserve npm ci integrity metadata")
+assert(wrangler.fetch("resolved").start_with?("https://registry.npmjs.org/wrangler/-/wrangler-"), "Wrangler must resolve from npm registry")
+assert(wrangler.fetch("integrity").start_with?("sha512-"), "Wrangler lockfile entry must keep npm integrity metadata")
+assert(trusted_checkout.dig("with", "sparse-checkout").to_s.include?("workers/preview"), "trusted checkout must include preview tooling")
+assert(step_names.compact.uniq == step_names.compact, "workflow step names must stay unique for security checks")
+assert([ pr_checkout, trusted_checkout, prepare, deploy ].map { |step| steps.index(step) }.each_cons(2).all? { |left, right| left < right }, "checkout, preparation, and deploy steps must stay ordered")
+assert(job.fetch("env").keys.none? { |name| name.start_with?("CLOUDFLARE_") }, "Cloudflare secrets must not be job-wide")
+assert(EXPECTED_SECRET_ENV.all? { |name| deploy.fetch("env").fetch(name).start_with?("${{ secrets.") }, "deploy secret env must be sourced from GitHub secrets")
+
+steps.each do |step|
+ uses = step["uses"]
+ assert(uses.start_with?("./") || uses.match?(PINNED_ACTION), "#{step["name"] || uses} must pin external actions") if uses
+end
+
+inline_scripts = steps.flat_map { |step| [ run(step), step.dig("with", "script") ] }.compact.join("\n")
+assert(!inline_scripts.match?(INLINE_SECRET_EXPRESSION), "secrets must enter scripts through env")
+assert(!inline_scripts.match?(INLINE_PR_EXPRESSION), "PR fields must enter scripts through env")
+assert(steps.none? { |step| normalized_working_directory(step["working-directory"]).match?(PR_CONTROLLED_WORKDIR) }, "steps must not run from PR-controlled dirs")
+assert(steps.none? { |step| run(step).include?("npx wrangler") }, "workflow must not use npx wrangler")
+
+prepare_run = assert_run_includes(prepare, *REQUIRED_PREPARE_LINES)
+assert(!prepare_run.include?("npm install"), "prepare step must not use npm install")
+assert(!prepare_run.include?("CLOUDFLARE_API_TOKEN"), "prepare step must not receive Cloudflare secrets")
+assert([ prepare, deploy ].all? { |step| run(step).include?("set -euo pipefail") }, "trusted setup and deploy scripts must fail closed")
+assert(prepare_run.include?('preview_dir="$RUNNER_TEMP/sure-preview-worker"'), "trusted workspace must be created under RUNNER_TEMP")
+assert(steps.select { |step| run(step).match?(/npm (ci|install)/) }.map { |step| step["name"] } == [ prepare["name"] ], "only prepare may install deploy tooling")
+
+secret_steps = steps.select { |step| step.fetch("env", {}).then { |env| env.key?("CLOUDFLARE_API_TOKEN") || env.key?("CLOUDFLARE_ACCOUNT_ID") } }
+assert(secret_steps.map { |step| step["name"] } == [ deploy["name"] ], "only deploy may receive Cloudflare secrets")
+secret_steps.each do |step|
+ assert(step["working-directory"].nil?, "#{step["name"]} must not run from a PR-controlled working directory")
+ assert(!run(step).match?(/npx wrangler|npm (ci|install)/), "#{step["name"]} must not execute PR-controlled tooling with secrets")
+end
+
+assert_run_includes(deploy, 'cd "$RUNNER_TEMP/sure-preview-worker"', "./node_modules/.bin/wrangler deploy --config wrangler.toml", '--var "PR_NUMBER:${PR_NUMBER}"')
+puts "preview-deploy security check passed"