From c4d215f0009519c37f385bc4a7eeef5add725384 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sun, 6 Dec 2026 02:51:28 -0600 Subject: [PATCH 1/2] test(site[previews]) Exercise closed and reopened website previews why: A website preview can finish uploading after its pull request closes. The cleanup and upload jobs need tests for both orders of events. what: - Run the workflow commands against a local GitHub API and S3 fixtures. - Cover reopen, late upload, permission denial and historical cleanup. --- site/test/preview-cleanup.outer.test.ts | 339 ++++++++++++++++++++++++ 1 file changed, 339 insertions(+) create mode 100644 site/test/preview-cleanup.outer.test.ts diff --git a/site/test/preview-cleanup.outer.test.ts b/site/test/preview-cleanup.outer.test.ts new file mode 100644 index 000000000..cf6661086 --- /dev/null +++ b/site/test/preview-cleanup.outer.test.ts @@ -0,0 +1,339 @@ +import { execFile } from 'node:child_process' +import { mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' +import { createServer } from 'node:http' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { describe, expect, it } from 'vitest' + +const repoRoot = fileURLToPath(new URL('../../', import.meta.url)) +const workflow = readFileSync(new URL('../../.github/workflows/pr-preview-cleanup.yml', import.meta.url), 'utf8') +const publisher = readFileSync(new URL('../../.github/workflows/test.yml', import.meta.url), 'utf8') +const reusable = readFileSync(new URL('../../.github/workflows/reusable-deploy.yml', import.meta.url), 'utf8') +const prefix = '/repos/libtmux/docs' +const pulls = `${prefix}/pulls` +const owned = { full_name: 'libtmux/docs' } +const foreign = { full_name: 'fork/docs' } + +function pr(number: number, state = 'closed', updated = '2026-12-06T07:43:32Z', head: typeof owned | null = owned) { + return { number, state, updated_at: updated, head: { repo: head }, base: { repo: owned } } +} + +function step(name: string, source = workflow) { + const index = source.indexOf(` - name: ${name}\n`) + if (index < 0) return undefined + const block = source.slice(index).split('\n - ', 1)[0] + const body = /^ {8}run: \|\n((?: {10}[^\n]*(?:\n|$)|\n)*)/m.exec(block)?.[1] + return body?.replace(/^ {10}/gm, '') +} + +interface Reply { + body: unknown + status?: number + links?: string +} + +const remaining = ['en/index.html', 'en/lua/pr-383/en/index.html', 'en/lua/v0.1.1/index.html', 'pr-3830/en/index.html', 'pr-384/en/index.html'] +const before = [...remaining, 'pr-383/en/index.html', 'pr-383/_astro/late.css'] +const historyLinks = '; rel="next", ; rel="last"' + +interface Fixture { + run: (body: string, extra?: Record) => Promise<{ status: number, stderr: string }> + output: () => string + objects: () => string[] + addObject: (key: string) => void + storageCalls: () => string[][] + requests: URL[] +} + +async function withApi(route: (request: URL) => Reply, exercise: (fixture: Fixture) => Promise) { + const directory = mkdtempSync(join(tmpdir(), 'libtmux-preview-cleanup-')) + const output = join(directory, 'output') + const state = join(directory, 'objects.json') + const calls = join(directory, 'storage-calls.jsonl') + writeFileSync(output, '') + writeFileSync(state, JSON.stringify(before)) + writeFileSync(calls, '') + symlinkSync(join(repoRoot, 'scripts'), join(directory, 'scripts'), 'dir') + symlinkSync(repoRoot, join(directory, 'publisher'), 'dir') + writeFileSync(join(directory, 'aws'), `#!${process.execPath} +const { appendFileSync, readFileSync, writeFileSync } = require('node:fs') +const assert = require('node:assert/strict') +const args = process.argv.slice(2) +appendFileSync(process.env.TEST_STORAGE_CALLS, JSON.stringify(args) + '\\n') +const path = process.env.TEST_OBJECTS +const objects = JSON.parse(readFileSync(path, 'utf8')) +if (args[0] === 's3api') { + const prefix = args[5] + assert(prefix.endsWith('/') && /^pr-[1-9][0-9]*$/.test(prefix.slice(0, -1))) + assert.deepEqual(args, ['s3api', 'list-objects-v2', '--bucket', 'fixture-only', '--prefix', prefix, '--max-keys', '1', '--no-paginate', '--output', 'json']) + if (process.env.FAIL_LIST?.split(',').includes(prefix)) process.exit(42) + const matches = objects.filter(key => key.startsWith(prefix)) + console.log(JSON.stringify({ Name: 'fixture-only', Prefix: prefix, KeyCount: Math.min(matches.length, 1), + IsTruncated: matches.length > 1, Contents: matches.slice(0, 1).map(Key => ({ Key })) })) +} else { + assert.deepEqual(args, ['s3', 'rm', 's3://fixture-only/pr-383/', '--recursive']) + writeFileSync(path, JSON.stringify(objects.filter(p => !p.startsWith('pr-383/')))) +} +`, { mode: 0o700 }) + + const requests: URL[] = [] + const server = createServer((incoming, response) => { + const isFixtureToken = incoming.headers.authorization === 'Bearer fixture-only' + const isAnonymousLookup = incoming.headers.authorization === undefined && + (incoming.url === `${pulls}/383` || incoming.url === `${prefix}/git/commits/${'b'.repeat(40)}`) + if (incoming.method !== 'GET' || (!isFixtureToken && !isAnonymousLookup)) { + response.writeHead(401).end() + return + } + const url = new URL(incoming.url!, 'http://127.0.0.1') + requests.push(url) + const result = route(url) + if (result.links) response.setHeader('Link', result.links) + response.writeHead(result.status ?? 200, { 'Content-Type': 'application/json' }).end(JSON.stringify(result.body)) + }) + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)) + const address = server.address() + if (!address || typeof address === 'string') throw new Error('Fixture server has no port') + const objects = () => JSON.parse(readFileSync(state, 'utf8')) as string[] + try { + await exercise({ + run: (body, extra = {}) => new Promise(resolve => { + execFile('bash', ['-e', '-c', body], { + cwd: directory, timeout: 3000, env: { + PATH: `${directory}:${process.env.PATH}`, GITHUB_API_URL: `http://127.0.0.1:${address.port}`, + GITHUB_OUTPUT: output, GITHUB_REPOSITORY: 'libtmux/docs', GITHUB_RUN_NUMBER: '1', + GH_TOKEN: 'fixture-only', TEST_OBJECTS: state, TEST_STORAGE_CALLS: calls, + BUCKET: 'fixture-only', PR: '383', ...extra, + }, + }, (error, _stdout, stderr) => resolve({ status: error ? Number(error.code) || 99 : 0, stderr })) + }), + output: () => readFileSync(output, 'utf8'), + objects, + addObject: key => writeFileSync(state, JSON.stringify([...objects(), key])), + storageCalls: () => readFileSync(calls, 'utf8').trim().split('\n').filter(Boolean).map(line => JSON.parse(line)), + requests, + }) + } finally { + server.closeAllConnections() + await new Promise(resolve => server.close(() => resolve())) + rmSync(directory, { recursive: true, force: true }) + } +} + +function planStep() { + const body = step('Find closed pull requests') + expect(body, 'the scheduled workflow runs a real closed-PR inventory step').toBeDefined() + return body! +} + +async function planner(fixture: Fixture, env: Record = {}) { + const result = await fixture.run(planStep(), env) + if (result.status !== 0) return result + const candidates = fixture.output().trim().split('\n').at(-1)?.replace(/^candidates=/, '') + const probe = step('Find existing preview prefixes') + expect(probe, 'the workflow probes existing exact preview leaves').toBeDefined() + return fixture.run(probe!, { ...env, CANDIDATES: candidates! }) +} + +async function cleanup(fixture: Fixture, afterEligibility?: () => void) { + const eligibility = step('Recheck the closed pull request') + if (eligibility) { + const result = await fixture.run(eligibility) + if (result.status !== 0 || fixture.output().trim().split('\n').at(-1) !== 'delete=true') return result + } + afterEligibility?.() + return fixture.run(step('Delete pr-/')!) +} + +describe('scheduled root preview cleanup', () => { + it('uses the existing per-PR lock and retains a newer pending publisher', () => { + expect(workflow).toMatch(/^on:\n schedule:\n/m) + const lock = /^ cleanup:\n[\s\S]*? concurrency:\n((?: {6}[^\n]+\n)+)/m.exec(workflow)?.[1] + expect(lock).toContain('group: deploy-shell-pr-${{ matrix.pr }}') + expect(lock).toContain('queue: max') + expect(publisher).toContain("format('deploy-shell-pr-{0}', github.event.pull_request.number)") + }) + + it('queues slow sweeps without replacing the pending historical page', () => { + const sweepLock = /^concurrency:\n((?: {2}[^\n]+\n)+)/m.exec(workflow)?.[1] + expect(sweepLock).toContain('queue: max') + }) + + it('reconciles recent and historical PRs and schedules only a nonempty closed leaf', async () => { + await withApi(url => url.searchParams.get('state') === 'all' ? + { body: [pr(383), pr(384, 'open'), pr(3830, 'closed', undefined, foreign)] } : + { body: [pr(383), pr(379)] }, async (fixture) => { + fixture.addObject('pr-3790/en/index.html') + expect(await planner(fixture)).toEqual({ status: 0, stderr: '' }) + expect(fixture.output()).toBe('candidates=[379,383]\nprs=[383]\n') + expect(fixture.storageCalls().map(call => call[5])).toEqual(['pr-379/', 'pr-383/']) + expect(fixture.objects()).toEqual([...before, 'pr-3790/en/index.html']) + expect(fixture.requests.map(x => x.searchParams.get('sort'))).toEqual(['created', 'updated']) + }) + }) + + it('rotates to a page beyond a 64-PR backlog, including pre-fix reruns with old PR dates', async () => { + await withApi(url => { + if (url.searchParams.get('state') === 'closed') return { body: [] } + if (url.searchParams.get('page') === '4') return { body: [pr(383, 'closed', '2025-12-01T23:59:59Z')] } + return { body: Array.from({ length: 20 }, (_, index) => pr(index + 1)), links: historyLinks } + }, async (fixture) => { + expect(await planner(fixture, { GITHUB_RUN_NUMBER: '4' })).toEqual({ status: 0, stderr: '' }) + expect(fixture.output()).toBe('candidates=[383]\nprs=[383]\n') + expect(fixture.requests.filter(x => x.searchParams.get('state') === 'all').map(x => x.searchParams.get('page'))).toEqual(['1', '4']) + expect(fixture.storageCalls()).toHaveLength(1) + }) + }) + + it.each([ + { status: 429, body: { message: 'API rate limit exceeded' } }, + { status: 200, body: { message: 'incomplete page' } }, + { status: 200, body: [], links: historyLinks }, + ])('does not emit any cleanup jobs after a rate limit or incomplete page: %j', async (failed) => { + const body = planStep() + await withApi(url => url.searchParams.get('page') === '1' ? + { body: Array.from({ length: 20 }, (_, index) => pr(index + 1)), links: historyLinks } : failed, async ({ run, output, objects }) => { + expect((await run(body, { GITHUB_RUN_NUMBER: '4' })).status).not.toBe(0) + expect(output()).toBe('') + expect(objects()).toEqual(before) + }) + }) + + it('does not probe historical candidates if GitHub returns a truncated recent page', async () => { + await withApi(url => url.searchParams.get('state') === 'all' ? { body: [pr(383)] } : + { body: [], links: historyLinks }, async (fixture) => { + expect((await planner(fixture)).status).not.toBe(0) + expect(fixture.output()).toBe('') + expect(fixture.storageCalls()).toEqual([]) + }) + }) + + it('retains a denied leaf and queues an independently verified prefix', async () => { + await withApi(() => ({ body: [pr(383), pr(384)] }), async (fixture) => { + expect(await planner(fixture, { FAIL_LIST: 'pr-384/' })).toMatchObject({ status: 0, stderr: expect.stringContaining('pr-384/') }) + expect(fixture.output()).toBe('candidates=[383,384]\nprs=[383]\n') + expect(fixture.storageCalls()).toHaveLength(2) + expect(fixture.objects()).toEqual(before) + }) + }) + + it('fails the sweep and emits no cleanup target if all exact-prefix probes fail', async () => { + await withApi(() => ({ body: [pr(383), pr(384)] }), async (fixture) => { + expect((await planner(fixture, { FAIL_LIST: 'pr-383/,pr-384/' })).status).not.toBe(0) + expect(fixture.output()).toBe('candidates=[383,384]\n') + expect(fixture.storageCalls()).toHaveLength(2) + }) + }) + + it('leaves an open preview alone even when cleanup was queued while closed', async () => { + await withApi(() => ({ body: pr(383, 'open') }), async (fixture) => { + expect((await cleanup(fixture)).status).toBe(0) + expect(fixture.objects()).toEqual(before) + expect(fixture.requests.map(x => x.pathname)).toEqual([`${pulls}/383`]) + }) + }) + + it('leaves a preview alone when its PR reopens during credential exchange', async () => { + let state = 'closed' + await withApi(() => ({ body: pr(383, state) }), async (fixture) => { + expect((await cleanup(fixture, () => { state = 'open' })).status).toBe(0) + expect(fixture.objects()).toEqual(before) + expect(fixture.requests.map(x => x.pathname)).toEqual([`${pulls}/383`, `${pulls}/383`]) + }) + }) + + it.each([pr(384), pr(383, 'closed', undefined, foreign), pr(383, 'closed', undefined, null)])('contains a mismatched live identity: %j', async (live) => { + await withApi(() => ({ body: live }), async (fixture) => { + await cleanup(fixture) + expect(fixture.objects()).toEqual(before) + }) + }) + + it('does not delete when live eligibility cannot be verified', async () => { + await withApi(() => ({ status: 429, body: { message: 'rate limited' } }), async (fixture) => { + expect((await cleanup(fixture)).status).not.toBe(0) + expect(fixture.objects()).toEqual(before) + }) + }) + + it('removes a finished upload and any partial files at just its exact leaf, including on retry', async () => { + await withApi(() => ({ body: pr(383) }), async (fixture) => { + expect((await cleanup(fixture)).status).toBe(0) + expect((await cleanup(fixture)).status).toBe(0) + expect(fixture.objects()).toEqual(remaining) + expect(fixture.requests.map(x => x.pathname)).toEqual(Array.from({ length: 4 }, () => `${pulls}/383`)) + }) + }) +}) + +describe('root preview publication after the audit', () => { + const head = 'a'.repeat(40) + const merge = 'b'.repeat(40) + const base = 'c'.repeat(40) + const mergePath = `${prefix}/git/commits/${merge}` + const open = { + ...pr(383, 'open'), head: { repo: owned, sha: head }, base: { repo: owned, sha: base }, + mergeable: true, merge_commit_sha: merge, + } + const tested = { sha: merge, parents: [{ sha: base }, { sha: head }] } + + async function publish(fixture: Fixture, attempt: string, pathPrefix = 'pr-383') { + const caller = publisher.split('\n publish-preview:', 2)[1] + const configured = caller?.includes('version-kind: pr') && !/^ port:/m.test(caller) + const body = step('Require current tested root pull request', reusable) + if (!configured || !body) return { status: 0 } + return fixture.run(body, { + GITHUB_RUN_ATTEMPT: attempt, EVENT: 'pull_request', REPOSITORY: 'libtmux/docs', + PORT: '', VERSION: '', PREFIX: pathPrefix, EXPECTED_HEAD: head, TESTED_MERGE: merge, + }) + } + + it('refuses a late uploader or a retried publisher after its PR closed', async () => { + await withApi(() => ({ body: { ...open, state: 'closed' } }), async (fixture) => { + expect((await publish(fixture, '1')).status).not.toBe(0) + expect((await publish(fixture, '2')).status).not.toBe(0) + expect(fixture.requests.map(x => x.pathname)).toEqual([`${pulls}/383`, `${pulls}/383`]) + }) + }) + + it('allows the reopened PR at the tested source and refuses a newer merge and an invalid destination', async () => { + let result = open + await withApi(url => ({ body: url.pathname === mergePath ? tested : result }), async (fixture) => { + expect((await publish(fixture, '1')).status).toBe(0) + result = { ...open, merge_commit_sha: 'c'.repeat(40) } + expect((await publish(fixture, '2')).status).not.toBe(0) + expect((await publish(fixture, '2', 'pr-3830')).status).not.toBe(0) + expect(fixture.requests.map(x => x.pathname)).toEqual([`${pulls}/383`, mergePath, `${pulls}/383`]) + }) + }) + + it('refuses cached merge metadata while GitHub recomputes the merge or has advanced the base', async () => { + const newerBase = { repo: owned, sha: 'd'.repeat(40) } + let ready: boolean | null = null + await withApi(url => ({ body: url.pathname === mergePath ? tested : { ...open, base: newerBase, mergeable: ready } }), async (fixture) => { + expect((await publish(fixture, '2')).status).not.toBe(0) + ready = true + expect((await publish(fixture, '2')).status).not.toBe(0) + expect(fixture.requests.map(x => x.pathname)).toEqual([`${pulls}/383`, `${pulls}/383`, mergePath]) + }) + }) + + it('removes the finished post-close write and retains the preview published after reopening', async () => { + let state = 'open' + await withApi(url => ({ body: url.pathname === mergePath ? tested : { ...open, state } }), async (fixture) => { + expect((await publish(fixture, '1')).status).toBe(0) + state = 'closed' + fixture.addObject('pr-383/en/finished-after-close.html') + expect((await cleanup(fixture)).status).toBe(0) + expect(fixture.objects()).toEqual(remaining) + + state = 'open' + expect((await publish(fixture, '1')).status).toBe(0) + const reopened = 'pr-383/en/reopened.html' + fixture.addObject(reopened) + expect((await cleanup(fixture)).status).toBe(0) + expect(fixture.objects()).toEqual([...remaining, reopened]) + }) + }) +}) From fff443bde3e82878f11577105c3ff54ead130239 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sun, 6 Dec 2026 02:51:28 -0600 Subject: [PATCH 2/2] fix(site[previews]) Retire closed website previews why: GitHub rejected the close workflow before it could remove a merged preview. An upload already in progress could recreate the closed page. what: - Discover closed previews with an hourly check of recent and older PRs. - Recheck each PR in its upload queue before deleting its preview. - Require the current open PR and its tested merge before uploading. --- .github/workflows/pr-preview-cleanup.yml | 132 ++++++++++++++++------ .github/workflows/reusable-deploy.yml | 13 ++- docs/ci.md | 41 +++---- scripts/root-preview.mjs | 135 +++++++++++++++++++++++ 4 files changed, 267 insertions(+), 54 deletions(-) create mode 100644 scripts/root-preview.mjs diff --git a/.github/workflows/pr-preview-cleanup.yml b/.github/workflows/pr-preview-cleanup.yml index 3976e3ce6..516a0b6e8 100644 --- a/.github/workflows/pr-preview-cleanup.yml +++ b/.github/workflows/pr-preview-cleanup.yml @@ -1,58 +1,122 @@ name: pr-preview-cleanup -# Deletes pr-/ 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-/ + 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. diff --git a/.github/workflows/reusable-deploy.yml b/.github/workflows/reusable-deploy.yml index ae2cd413c..ad532aac9 100644 --- a/.github/workflows/reusable-deploy.yml +++ b/.github/workflows/reusable-deploy.yml @@ -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' @@ -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 }} diff --git a/docs/ci.md b/docs/ci.md index 0a65b3907..c056f3375 100644 --- a/docs/ci.md +++ b/docs/ci.md @@ -479,28 +479,31 @@ or checkout of PR code under `pull_request_target`. The PR workflow shares `deploy-shell-pr-` 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-/` 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-`) 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-/` 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-` 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-/` +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`) diff --git a/scripts/root-preview.mjs b/scripts/root-preview.mjs new file mode 100644 index 000000000..b1f322611 --- /dev/null +++ b/scripts/root-preview.mjs @@ -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 +}