mirror of
https://github.com/we-promise/sure.git
synced 2026-05-30 07:49:01 +00:00
Pulls `github.event.pull_request.number` and
`github.event.pull_request.head.sha` out of every shell `run:` block
and `actions/github-script` body into job-level env vars. The PR
number is nominally an integer (no immediate injection risk), but the
*pattern* of inlining a `github.event.*` expression into a privileged
workflow's shell scripts is what the SAST finding wants to eliminate:
- The workflow holds `CLOUDFLARE_API_TOKEN` and
`CLOUDFLARE_ACCOUNT_ID`.
- A future copy/paste of one of these step bodies onto a user-
controlled string (branch name, PR title, commit message) would
silently become an arbitrary command-injection path.
Touches:
- Job-level `env: { PR_NUMBER, HEAD_SHA }` so every step inherits.
- "Configure preview files": `sed` substitution now reads
`${PR_NUMBER}` from the shell env (the literal-placeholder side
stays escaped as `\${PR_NUMBER}`).
- "Delete existing preview container app" + "Delete existing preview
Worker": shell var assignments use `${PR_NUMBER}`.
- "Create GitHub Deployment" github-script: `process.env.PR_NUMBER`
inside the JS template literal instead of GHA template
interpolation.
- "Deploy to Cloudflare Containers": `${PR_NUMBER}` in the shell;
`CLOUDFLARE_WORKERS_SUBDOMAIN` also lifted into the step's `env:`
block so the URL template uses `${CLOUDFLARE_WORKERS_SUBDOMAIN}`,
not a templated secret expression in the shell command.
- "Comment on PR" github-script: replaces the four
`${{ github.event.pull_request.* }}` interpolations with
`process.env.PR_NUMBER` / `process.env.HEAD_SHA` and lifts the
preview URL via step env. `issue_number` is `Number(...)`-coerced
since env values are strings.
- "Store cleanup metadata" artifact name: uses `${{ env.PR_NUMBER }}`
(template context, not shell).
YAML still validates (`ruby -ryaml -e 'YAML.load_file(...)'`). The
only remaining `github.event.pull_request.*` references are the job-
gate `if:` condition and the env-extraction definitions themselves —
both safe contexts.
238 lines
8.8 KiB
YAML
238 lines
8.8 KiB
YAML
name: Deploy PR Preview
|
|
|
|
on:
|
|
pull_request:
|
|
types: [opened, synchronize, reopened, labeled]
|
|
paths-ignore:
|
|
- 'charts/**'
|
|
- 'docs/**'
|
|
- '*.md'
|
|
|
|
jobs:
|
|
deploy-preview:
|
|
if: |
|
|
contains(github.event.pull_request.labels.*.name, 'preview-cf') &&
|
|
(github.event.action != 'labeled' || github.event.label.name == 'preview-cf')
|
|
name: Deploy to Cloudflare Containers
|
|
runs-on: ubuntu-latest
|
|
timeout-minutes: 15
|
|
permissions:
|
|
actions: read
|
|
contents: read
|
|
pull-requests: write
|
|
deployments: write
|
|
env:
|
|
# Defense-in-depth: pull `github.event.*` expressions out of shell
|
|
# and JS contexts so a future copy/paste of one of these step
|
|
# bodies onto a user-controlled string (branch name, PR title,
|
|
# commit message) doesn't open a command-injection path into a
|
|
# workflow that carries CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID.
|
|
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
|
|
with:
|
|
script: |
|
|
const headSha = context.payload.pull_request.head.sha;
|
|
const timeoutMs = 10 * 60 * 1000;
|
|
const pollMs = 15 * 1000;
|
|
const startedAt = Date.now();
|
|
let lastState = 'not found';
|
|
|
|
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
|
|
while (Date.now() - startedAt < timeoutMs) {
|
|
const { data } = await github.rest.actions.listWorkflowRunsForRepo({
|
|
owner: context.repo.owner,
|
|
repo: context.repo.repo,
|
|
event: 'pull_request',
|
|
head_sha: headSha,
|
|
per_page: 20,
|
|
});
|
|
|
|
const prRun = data.workflow_runs.find((run) => run.name === 'Pull Request' && run.head_sha === headSha);
|
|
|
|
if (prRun) {
|
|
lastState = `${prRun.status}/${prRun.conclusion ?? 'pending'}`;
|
|
core.info(`Pull Request workflow ${prRun.id}: ${lastState}`);
|
|
|
|
if (prRun.status === 'completed') {
|
|
if (prRun.conclusion === 'success') {
|
|
return;
|
|
}
|
|
|
|
core.setFailed(`Pull Request workflow concluded with ${prRun.conclusion}`);
|
|
return;
|
|
}
|
|
}
|
|
|
|
await sleep(pollMs);
|
|
}
|
|
|
|
core.setFailed(`Timed out waiting for Pull Request workflow for ${headSha}. Last state: ${lastState}`);
|
|
|
|
- name: Checkout code
|
|
uses: actions/checkout@v5
|
|
|
|
- name: Setup Node.js
|
|
uses: actions/setup-node@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
|
|
run: |
|
|
sed -i "s/\${PR_NUMBER}/${PR_NUMBER}/g" wrangler.toml
|
|
sed -i "s/\${PR_NUMBER}/${PR_NUMBER}/g" src/index.ts
|
|
cat wrangler.toml
|
|
|
|
- name: Delete existing preview container app before redeploy
|
|
env:
|
|
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
|
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
|
working-directory: workers/preview
|
|
run: |
|
|
set -euo pipefail
|
|
CONTAINER_NAME="sure-preview-${PR_NUMBER}-railscontainer"
|
|
echo "Looking for stale preview container app: $CONTAINER_NAME"
|
|
|
|
CONTAINER_ID=$(npx wrangler containers list --json | jq -r --arg NAME "$CONTAINER_NAME" '
|
|
map(select((.name // .application_name // .app_name // "") == $NAME))
|
|
| first
|
|
| (.id // .container_id // .application_id // empty)
|
|
')
|
|
|
|
if [ -n "$CONTAINER_ID" ]; then
|
|
echo "Deleting stale preview container app $CONTAINER_NAME ($CONTAINER_ID)"
|
|
npx wrangler containers delete "$CONTAINER_ID"
|
|
else
|
|
echo "No stale preview container app found; continuing"
|
|
fi
|
|
|
|
- name: Delete existing preview Worker before redeploy
|
|
env:
|
|
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
|
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
|
working-directory: workers/preview
|
|
run: |
|
|
WORKER_NAME="sure-preview-${PR_NUMBER}"
|
|
echo "Ensuring fresh preview deployment for $WORKER_NAME"
|
|
npx wrangler delete --name "$WORKER_NAME" --force || echo "Existing preview not found; continuing"
|
|
|
|
- name: Create GitHub Deployment
|
|
id: deployment
|
|
uses: actions/github-script@v7
|
|
with:
|
|
script: |
|
|
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-${process.env.PR_NUMBER}`,
|
|
auto_merge: false,
|
|
required_contexts: [],
|
|
description: 'PR Preview Deployment'
|
|
});
|
|
return deployment.data.id;
|
|
result-encoding: string
|
|
|
|
- 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:${PR_NUMBER}"
|
|
|
|
# Get the deployment URL
|
|
PREVIEW_URL="https://sure-preview-${PR_NUMBER}.${CLOUDFLARE_WORKERS_SUBDOMAIN}.workers.dev"
|
|
echo "preview_url=${PREVIEW_URL}" >> "$GITHUB_OUTPUT"
|
|
|
|
- name: Warm preview container
|
|
env:
|
|
PREVIEW_URL: ${{ steps.deploy.outputs.preview_url }}
|
|
run: |
|
|
echo "Triggering preview wake-up..."
|
|
curl -fsS "$PREVIEW_URL/" >/dev/null || true
|
|
|
|
- name: Update Deployment Status
|
|
if: always() && steps.deployment.outputs.result
|
|
uses: actions/github-script@v7
|
|
with:
|
|
script: |
|
|
const state = '${{ job.status }}' === 'success' ? 'success' : 'failure';
|
|
await github.rest.repos.createDeploymentStatus({
|
|
owner: context.repo.owner,
|
|
repo: context.repo.repo,
|
|
deployment_id: ${{ steps.deployment.outputs.result }},
|
|
state: state,
|
|
environment_url: state === 'success' ? '${{ steps.deploy.outputs.preview_url }}' : undefined,
|
|
description: state === 'success' ? 'Preview deployed successfully' : 'Preview deployment failed'
|
|
});
|
|
|
|
- name: Comment on PR
|
|
if: success()
|
|
uses: actions/github-script@v7
|
|
env:
|
|
PREVIEW_URL: ${{ steps.deploy.outputs.preview_url }}
|
|
with:
|
|
script: |
|
|
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.
|
|
|
|
**Preview URL:** ${previewUrl}
|
|
|
|
> ⏰ This preview is intended to be cleaned up after **24 hours** of the last deployment once the cleanup workflow is live on the default branch.
|
|
> 💤 The container will sleep after 30 minutes of inactivity and wake on the next request.
|
|
|
|
---
|
|
<sub>Deployed from commit ${headSha}</sub>`;
|
|
|
|
// Find existing comment
|
|
const { data: comments } = await github.rest.issues.listComments({
|
|
owner: context.repo.owner,
|
|
repo: context.repo.repo,
|
|
issue_number: issueNumber
|
|
});
|
|
|
|
const botComment = comments.find(comment =>
|
|
comment.user.type === 'Bot' &&
|
|
comment.body.includes('Preview Deployment Ready')
|
|
);
|
|
|
|
if (botComment) {
|
|
await github.rest.issues.updateComment({
|
|
owner: context.repo.owner,
|
|
repo: context.repo.repo,
|
|
comment_id: botComment.id,
|
|
body: commentBody
|
|
});
|
|
} else {
|
|
await github.rest.issues.createComment({
|
|
owner: context.repo.owner,
|
|
repo: context.repo.repo,
|
|
issue_number: issueNumber,
|
|
body: commentBody
|
|
});
|
|
}
|
|
- name: Store cleanup metadata
|
|
if: success()
|
|
uses: actions/upload-artifact@v6
|
|
with:
|
|
name: preview-cleanup-pr-${{ env.PR_NUMBER }}
|
|
path: |
|
|
workers/preview/wrangler.toml
|
|
retention-days: 2
|