Skip to content
Draft
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
132 changes: 98 additions & 34 deletions .github/workflows/pr-preview-cleanup.yml
Original file line number Diff line number Diff line change
@@ -1,58 +1,122 @@
name: pr-preview-cleanup

# Deletes pr-<n>/ the moment its PR closes, merged or not. Same-repo PRs
# get a preview published by test.yml's publish-preview job; fork
# PRs never do (test.yml, same-repository guard), so this job
# is a no-op delete of a prefix that was never written for those — fine,
# `aws s3 rm --recursive` on an absent prefix is not an error.
#
# pull_request_target never checks out PR content — it only reads
# github.event.pull_request.number from the event payload the platform
# already validated — so it is safe to run unconditionally, including for
# forks. It also always runs the workflow file from the default branch, so
# a PR branch can't alter its own cleanup logic. This job gets its own
# GitHub Environment rather than reusing test.yml's docs-preview:
# whether pull_request_target's OIDC `sub` claim matches pull_request's
# documented repo:ORG/REPO:pull_request format is unverified
# (notes/research/06), so its trust-policy entry is kept separate and
# reviewed on its own.

on:
pull_request_target:
types: [closed]
schedule:
- cron: '17 * * * *'

permissions:
contents: read
id-token: write
permissions: {}

# The hourly sweep visits recent closures and rotates through history.
concurrency:
group: deploy-shell-pr-${{ github.event.pull_request.number }}
cancel-in-progress: false
group: site-preview-cleanup
queue: max

jobs:
plan:
runs-on: ubuntu-latest
timeout-minutes: 10
environment: docs-preview-cleanup
permissions:
contents: read
id-token: write
pull-requests: read
outputs:
prs: ${{ steps.probe.outputs.prs }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ github.sha }}
sparse-checkout: scripts/root-preview.mjs
sparse-checkout-cone-mode: false
persist-credentials: false
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: '26'
- name: Find closed pull requests
id: plan
env:
GH_TOKEN: ${{ github.token }}
run: |
set -euo pipefail
candidates=$(node scripts/root-preview.mjs plan)
printf 'candidates=%s\n' "$candidates" >> "$GITHUB_OUTPUT"

- if: steps.plan.outputs.candidates != '[]'
uses: aws-actions/configure-aws-credentials@45666896f5d8e0f10ae255413f3a4cdd03bdc8f5 # v6.3.1
with:
role-to-assume: ${{ secrets.LIBTMUX_DOCS_PREVIEW_CLEANUP_ROLE_ARN }}
aws-region: us-east-1

- name: Find existing preview prefixes
id: probe
env:
BUCKET: ${{ secrets.LIBTMUX_DOCS_BUCKET }}
CANDIDATES: ${{ steps.plan.outputs.candidates }}
run: |
set -euo pipefail
prs=$(node scripts/root-preview.mjs probe)
printf 'prs=%s\n' "$prs" >> "$GITHUB_OUTPUT"

cleanup:
needs: plan
if: needs.plan.outputs.prs != '[]'
strategy:
fail-fast: false
max-parallel: 4
matrix:
pr: ${{ fromJSON(needs.plan.outputs.prs) }}
# Share the audit's slot without replacing a pending reopen audit.
concurrency:
group: deploy-shell-pr-${{ matrix.pr }}
queue: max
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: read
id-token: write
pull-requests: read
environment: docs-preview-cleanup
steps:
- uses: aws-actions/configure-aws-credentials@v6
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ github.sha }}
sparse-checkout: scripts/root-preview.mjs
sparse-checkout-cone-mode: false
persist-credentials: false
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: '26'
- name: Recheck the closed pull request
id: review
env:
GH_TOKEN: ${{ github.token }}
PR: ${{ matrix.pr }}
run: |
set -euo pipefail
eligible=$(node scripts/root-preview.mjs check-deletion)
printf 'delete=%s\n' "$eligible" >> "$GITHUB_OUTPUT"

- if: steps.review.outputs.delete == 'true'
uses: aws-actions/configure-aws-credentials@45666896f5d8e0f10ae255413f3a4cdd03bdc8f5 # v6.3.1
with:
role-to-assume: ${{ secrets.LIBTMUX_DOCS_PREVIEW_CLEANUP_ROLE_ARN }}
aws-region: us-east-1

- name: Delete pr-<n>/
if: steps.review.outputs.delete == 'true'
env:
BUCKET: ${{ secrets.LIBTMUX_DOCS_BUCKET }}
PR: ${{ github.event.pull_request.number }}
GH_TOKEN: ${{ github.token }}
PR: ${{ matrix.pr }}
run: |
set -euo pipefail
if [[ -z "$PR" || ! "$PR" =~ ^[0-9]+$ ]]; then
echo "::error::no numeric PR number in event payload" >&2
if [[ -z "$BUCKET" || ! "$PR" =~ ^[1-9][0-9]*$ ]]; then
echo '::error::missing cleanup bucket or invalid PR number' >&2
exit 1
fi
aws s3 rm "s3://$BUCKET/pr-$PR/" --recursive
eligible=$(node scripts/root-preview.mjs check-deletion)
if [[ "$eligible" == true ]]; then
aws s3 rm "s3://$BUCKET/pr-$PR/" --recursive
fi

# No invalidation. The preview's objects are gone, and the prefix was
# written with `s-maxage=300`, so the edge stops serving what is left of
# it within five minutes. Paying a path to shave that off a URL whose
# pull request is already closed is the clearest case of an invalidation
# buying nothing.
# Preview pages retain their five-minute shared cache lifetime.
13 changes: 12 additions & 1 deletion .github/workflows/reusable-deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ jobs:
scripts
site/src/lib
persist-credentials: false
- if: inputs.port != ''
- if: inputs.port != '' || inputs.version-kind == 'pr'
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: '26'
Expand Down Expand Up @@ -330,6 +330,17 @@ jobs:
exit 1
}

- name: Require current tested root pull request
if: inputs.port == '' && inputs.version-kind == 'pr'
env:
EVENT: ${{ github.event_name }}
PR: ${{ github.event.pull_request.number }}
EXPECTED_HEAD: ${{ github.event.pull_request.head.sha }}
TESTED_MERGE: ${{ github.sha }}
PREFIX: ${{ inputs.path-prefix }}
run: |
node publisher/scripts/root-preview.mjs check-upload

- uses: aws-actions/configure-aws-credentials@45666896f5d8e0f10ae255413f3a4cdd03bdc8f5 # v6.3.1
with:
role-to-assume: ${{ secrets.role-arn }}
Expand Down
41 changes: 22 additions & 19 deletions docs/ci.md
Original file line number Diff line number Diff line change
Expand Up @@ -479,28 +479,31 @@ or checkout of PR code under `pull_request_target`.
The PR workflow shares `deploy-shell-pr-<n>` concurrency with preview cleanup.
A superseding PR commit cancels the old audit/preview; production publication
keeps its separate serialized, non-cancelling queue in `deploy-shell.yml`.
Before assuming the preview role, the upload job checks that the PR is still
open and that the tested merge has its current base and head as parents.
A retry checks again, even when it reuses the audited artifact.

## `pr-preview-cleanup.yml`

Deletes `pr-<n>/` when its PR closes, merged or not — including for fork
PRs, which never had a preview published in the first place, making the
delete a harmless no-op. It triggers on `pull_request_target: types:
[closed]` and reads only `github.event.pull_request.number`, validated as
numeric before use; it never checks out PR content, so it is safe to run
unconditionally regardless of the PR's origin. It shares its concurrency
group (`deploy-shell-pr-<n>`) with `publish-preview` so a preview publish
in flight can't race a close event and leave stale files behind.

It runs under its own `docs-preview-cleanup` environment rather than reusing
`publish-preview`'s `docs-preview` — whether `pull_request_target`'s OIDC
`sub` claim matches `pull_request`'s documented
`repo:ORG/REPO:pull_request` format is unverified, so its trust-policy entry
is kept separate and reviewed on its own.

An S3 lifecycle rule expiring objects under `pr-*/` after roughly two weeks
is the backstop for any cleanup run that never fires (a workflow disabled,
a run that errors before the delete step) — that rule is `infra/`'s
concern, not this workflow's.
The default branch schedules a sweep at 17 minutes past each hour. It reads
the eight most recently updated closed PRs and one creation-ordered page of
twenty PRs. The workflow run number cycles through the historical pages so
older previews are revisited even after a failed sweep or a retry of an old
publisher. Each sweep lists at most one object under each eligible closed
same-repository PR's exact `pr-<n>/` prefix. Only a nonempty prefix gets a
cleanup job. An incomplete GitHub listing stops the sweep. A failed storage
lookup keeps that prefix for a later sweep while verified ones can proceed.
GitHub may delay a sweep.

Each cleanup uses `deploy-shell-pr-<n>` and waits for an upload already in
that slot. It checks the live PR after acquiring the slot and again after
assuming the `docs-preview-cleanup` role. The job deletes only `pr-<n>/`
when the second read reports the PR closed. Reopening after that read can
require a fresh upload through the same slot to restore the preview.
Preview pages can stay cached for up to five minutes after deletion.

Hosting can configure an independent S3 lifecycle rule on preview objects
to cover periods when the workflow is disabled.

## Header destination check (`verify-destinations.yml`)

Expand Down
135 changes: 135 additions & 0 deletions scripts/root-preview.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
import { execFileSync } from 'node:child_process'

const env = process.env
const historyPageSize = 20
const recentPageSize = 8

const validNumber = value => Number.isSafeInteger(value) && value > 0

function number(value, name) {
const parsed = Number(value)
if (!/^[1-9][0-9]*$/.test(value) || !validNumber(parsed)) throw new Error(`Invalid ${name}`)
return parsed
}

async function github(path, token = env.GH_TOKEN) {
const headers = { Accept: 'application/vnd.github+json', 'Cache-Control': 'no-cache' }
if (token) headers.Authorization = `Bearer ${token}`
const response = await fetch(`${env.GITHUB_API_URL}/repos/${env.GITHUB_REPOSITORY}/${path}`, {
headers, redirect: 'error', signal: AbortSignal.timeout(15_000),
})
if (!response.ok) throw new Error(`GitHub returned HTTP ${response.status} for ${path}`)
return { data: await response.json(), links: response.headers.get('link') }
}

const sameRepository = pr => [pr.head, pr.base].every(side => side?.repo?.full_name === env.GITHUB_REPOSITORY)

function closedInPage(data, min, max, expectedStates) {
if (!Array.isArray(data) || data.length < min || data.length > max ||
!data.every(pr => validNumber(pr?.number) && expectedStates.includes(pr.state))) {
throw new Error('GitHub returned an incomplete or invalid pull request page')
}
return data.filter(pr => pr.state === 'closed' && sameRepository(pr)).map(pr => pr.number)
}

async function plan() {
const run = number(env.GITHUB_RUN_NUMBER, 'cleanup run number')
const historyPath = `pulls?state=all&sort=created&direction=asc&per_page=${historyPageSize}&page=`
const first = await github(`${historyPath}1`)
const lastLink = first.links?.match(/<([^>]+)>;\s*rel="last"/)?.[1]
if (first.links && !lastLink) throw new Error('GitHub did not identify the last historical pull request page')
const last = lastLink ? number(new URL(lastLink).searchParams.get('page'), 'last pull request page') : 1
const page = (run - 1) % last + 1
const historyStates = ['open', 'closed']
const firstCandidates = closedInPage(first.data, last > 1 ? historyPageSize : 0, historyPageSize, historyStates)
const historical = page === 1 ? firstCandidates : closedInPage(
(await github(`${historyPath}${page}`)).data,
page < last ? historyPageSize : 1,
historyPageSize,
historyStates,
)
const recent = await github(`pulls?state=closed&sort=updated&direction=desc&per_page=${recentPageSize}&page=1`)
const latest = closedInPage(recent.data, recent.links ? recentPageSize : 0, recentPageSize, ['closed'])
return [...new Set([...historical, ...latest])].sort((a, b) => a - b)
}

function existingPreviews() {
const candidates = JSON.parse(env.CANDIDATES)
if (!Array.isArray(candidates) || candidates.length > historyPageSize + recentPageSize || !candidates.every(validNumber)) {
throw new Error('Invalid preview candidates')
}
if (candidates.length && !env.BUCKET) throw new Error('Missing preview bucket')

let failed = 0
const existing = candidates.filter(pr => {
const prefix = `pr-${pr}/`
try {
const response = JSON.parse(execFileSync('aws', [
's3api', 'list-objects-v2', '--bucket', env.BUCKET, '--prefix', prefix,
'--max-keys', '1', '--no-paginate', '--output', 'json',
], { encoding: 'utf8', timeout: 15_000 }))
const keys = response?.Contents ?? []
if (response?.Prefix !== prefix || !Array.isArray(keys) || keys.length > 1 || response.KeyCount !== keys.length ||
!keys.every(entry => typeof entry?.Key === 'string' && entry.Key.startsWith(prefix)) || (!keys.length && response.IsTruncated)) {
throw new Error('Invalid preview inventory')
}
return keys.length > 0
} catch {
failed++
console.warn(`::warning::Could not inspect the preview at ${prefix}`)
return false
}
})
if (failed && failed === candidates.length) throw new Error('Could not inspect any eligible preview prefix')
return existing
}

async function checkDeletion() {
const requested = number(env.PR, 'root preview pull request number')
const { data: pr } = await github(`pulls/${requested}`)
if (pr?.number !== requested || !['open', 'closed'].includes(pr.state)) {
throw new Error('GitHub returned an invalid pull request identity')
}
return pr.state === 'closed' && sameRepository(pr)
}

async function checkUpload() {
const requested = number(env.PR, 'root preview pull request number')
const sha = /^[0-9a-f]{40}$/
if (env.EVENT !== 'pull_request' || env.PREFIX !== `pr-${requested}` || !sha.test(env.EXPECTED_HEAD) || !sha.test(env.TESTED_MERGE)) {
throw new Error('Invalid tested root preview identity')
}
// The root website and its PR data are public. The upload job keeps its existing token permissions.
const { data: pr } = await github(`pulls/${requested}`, '')
if (pr?.number !== requested || pr.state !== 'open' || pr.mergeable !== true || !sameRepository(pr) ||
pr.head.sha !== env.EXPECTED_HEAD || !sha.test(pr.base.sha) || pr.merge_commit_sha !== env.TESTED_MERGE) {
throw new Error('Current PR is closed or differs from the tested root preview')
}
const { data: merge } = await github(`git/commits/${env.TESTED_MERGE}`, '')
if (merge?.sha !== env.TESTED_MERGE || !Array.isArray(merge.parents) || merge.parents.length !== 2 ||
merge.parents[0]?.sha !== pr.base.sha || merge.parents[1]?.sha !== pr.head.sha) {
throw new Error('Tested root preview does not merge the current base and head')
}
}

try {
switch (process.argv[2]) {
case 'plan':
console.log(JSON.stringify(await plan()))
break
case 'probe':
console.log(JSON.stringify(existingPreviews()))
break
case 'check-deletion':
console.log(await checkDeletion())
break
case 'check-upload':
await checkUpload()
break
default:
throw new Error('Expected plan, probe, check-deletion or check-upload')
}
} catch (error) {
console.error(error.message)
process.exitCode = 1
}
Loading
Loading