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
6 changes: 3 additions & 3 deletions .github/CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -805,9 +805,9 @@ Then open `/en/go/latest/guides/capturing-output/?panels=1`.

Apply the `no-preview` label before pushing a revision that needs CI validation
while publication awaits approval. CI still builds and audits the artifact and
runs the publisher dry run; the label holds the preview publishing job.
The guard reads the triggering event's labels. Adding the label later does
not stop an existing run.
runs the publisher dry run. The website publisher also checks current labels
before setting up AWS credentials. A label added before that check holds
publication for the existing run.

Keep commits focused on one topic. Explain the problem, resulting behavior,
and verification, including failures or skipped checks. Keep unrelated
Expand Down
20 changes: 19 additions & 1 deletion .github/workflows/reusable-deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -354,7 +354,25 @@ jobs:
exit 1
}

- name: Require current tested root pull request
id: root-preview
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: |
set -euo pipefail
publish=$(node publisher/scripts/root-preview.mjs check-upload)
printf 'publish=%s\n' "$publish" >> "$GITHUB_OUTPUT"
if [[ "$publish" == false ]]; then
echo 'Website preview held by no-preview'
fi

- uses: aws-actions/configure-aws-credentials@45666896f5d8e0f10ae255413f3a4cdd03bdc8f5 # v6.3.1
if: inputs.port != '' || inputs.version-kind != 'pr' || steps.root-preview.outputs.publish == 'true'
with:
role-to-assume: ${{ secrets.role-arn }}
aws-region: ${{ inputs.aws-region }}
Expand Down Expand Up @@ -391,7 +409,7 @@ jobs:
fi

- name: Sync to this call's own prefix
if: env.SKIP_SYNC != 'true'
if: env.SKIP_SYNC != 'true' && (inputs.port != '' || inputs.version-kind != 'pr' || steps.root-preview.outputs.publish == 'true')
env:
BUCKET: ${{ secrets.bucket }}
run: |
Expand Down
47 changes: 47 additions & 0 deletions scripts/root-preview.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
const env = process.env
const sha = /^[0-9a-f]{40}$/

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

async function checkUpload() {
const requested = Number(env.PR)
if (!/^[1-9][0-9]*$/.test(env.PR) || !Number.isSafeInteger(requested) ||
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')
}

const pr = await github(`pulls/${requested}`)
const sameRepository = [pr?.head, pr?.base].every(side => side?.repo?.full_name === env.GITHUB_REPOSITORY)
if (pr?.number !== requested || pr.state !== 'open' || pr.mergeable !== true || !sameRepository ||
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 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')
}

if (!Array.isArray(pr.labels) || !pr.labels.every(label => typeof label?.name === 'string')) {
throw new Error('GitHub returned invalid root preview labels')
}
return !pr.labels.some(label => label.name.toLowerCase() === 'no-preview')
}

try {
if (process.argv[2] !== 'check-upload') throw new Error('Expected check-upload')
console.log(await checkUpload())
} catch (error) {
console.error(error.message)
process.exitCode = 1
}
2 changes: 1 addition & 1 deletion site/test/deploy-workflow.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -761,7 +761,7 @@ describe('current PR publication guard', () => {
const aws = reusable.indexOf(' - uses: aws-actions/configure-aws-credentials')
expect(start).toBeGreaterThan(reusable.indexOf(' - name: Verify artifact and build provenance'))
expect(start).toBeLessThan(aws)
const check = reusable.slice(start, aws)
const check = reusable.slice(start).split('\n - ', 1)[0]
expect(check).toContain("inputs.version-kind == 'pr' &&")
expect(check).toContain("(inputs.require-current-pr || (github.event_name == 'workflow_dispatch' && inputs.port == 'lua'))")
expect(check).toContain('TESTED_MERGE: ${{ github.sha }}')
Expand Down
119 changes: 119 additions & 0 deletions site/test/root-preview-upload.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
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 repo = 'libtmux/docs'
const root = fileURLToPath(new URL('../../', import.meta.url))
const workflow = readFileSync(new URL('../../.github/workflows/reusable-deploy.yml', import.meta.url), 'utf8')
const steps = workflow.split('\n - ')
const check = steps.find(block => block.startsWith('name: Require current tested root pull request\n'))
const checkBody = check?.match(/^ {8}run: \|\n((?: {10}[^\n]*\n|\n)*)/m)?.[1].replace(/^ {10}/gm, '')
const head = 'a'.repeat(40)
const merge = 'b'.repeat(40)
const base = 'c'.repeat(40)
const owned = { full_name: repo }
const openPr = {
number: 42,
state: 'open',
draft: false,
labels: [] as { name: string }[],
head: { repo: owned, sha: head },
base: { repo: owned, sha: base },
mergeable: true,
merge_commit_sha: merge,
}
const testedMerge = { sha: merge, parents: [{ sha: base }, { sha: head }] }

async function rootUpload(pr: unknown, object: unknown = testedMerge, prefix = 'pr-42', status = 200) {
// On the original workflow the current-PR check was absent and the publisher continued.
if (!checkBody) return { status: 0, output: '', requests: [] }
const directory = mkdtempSync(join(tmpdir(), 'libtmux-root-preview-'))
const output = join(directory, 'output')
writeFileSync(output, '')
symlinkSync(root, join(directory, 'publisher'), 'dir')
const requests: string[] = []
const pullPath = `/repos/${repo}/pulls/42`
const mergePath = `/repos/${repo}/git/commits/${merge}`
const server = createServer((request, response) => {
const path = request.url ?? ''
requests.push(path)
if (request.method !== 'GET' || request.headers.authorization || ![pullPath, mergePath].includes(path)) {
response.writeHead(403).end()
return
}
response.writeHead(path === pullPath ? status : 200, { 'Content-Type': 'application/json' })
.end(JSON.stringify(path === pullPath ? pr : object))
})
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve))
try {
const address = server.address()
if (!address || typeof address === 'string') throw new Error('Fixture server has no port')
const status = await new Promise<number>(resolve => {
execFile('bash', ['-e', '-o', 'pipefail', '-c', checkBody], {
cwd: directory, timeout: 3000, env: {
PATH: process.env.PATH,
GITHUB_API_URL: `http://127.0.0.1:${address.port}`,
GITHUB_REPOSITORY: repo, GITHUB_OUTPUT: output, EVENT: 'pull_request',
PR: '42', PREFIX: prefix, EXPECTED_HEAD: head, TESTED_MERGE: merge,
},
}, error => resolve(error ? Number(error.code) || 99 : 0))
})
return { status, output: readFileSync(output, 'utf8'), requests }
} finally {
server.closeAllConnections()
await new Promise<void>(resolve => server.close(() => resolve()))
rmSync(directory, { recursive: true, force: true })
}
}

describe('website preview upload after the audit', () => {
it.each([false, true])('allows the matching open website PR with draft=%s', async draft => {
const result = await rootUpload({ ...openPr, draft, labels: [{ name: 'documentation' }] })
expect(result).toEqual({
status: 0, output: 'publish=true\n',
requests: [`/repos/${repo}/pulls/42`, `/repos/${repo}/git/commits/${merge}`],
})
})

it.each(['no-preview', 'No-Preview'])('successfully holds upload for live %s', async name => {
const result = await rootUpload({ ...openPr, labels: [{ name }] })
expect(result.status).toBe(0)
expect(result.output).toBe('publish=false\n')
})

it('requires the live root decision before either credentials or storage writes', () => {
const permitted = "inputs.port != '' || inputs.version-kind != 'pr' || steps.root-preview.outputs.publish == 'true'"
const credentials = steps.find(block => block.startsWith('uses: aws-actions/configure-aws-credentials@'))
const sync = steps.find(block => block.startsWith("name: Sync to this call's own prefix\n"))
expect(check).toContain(" if: inputs.port == '' && inputs.version-kind == 'pr'\n")
expect(check).toContain(' id: root-preview\n')
expect(credentials).toContain(` if: ${permitted}\n`)
expect(sync).toContain(` if: env.SKIP_SYNC != 'true' && (${permitted})\n`)
})

it.each([
['closed PR', { ...openPr, state: 'closed' }],
['fork', { ...openPr, head: { ...openPr.head, repo: { full_name: 'fork/docs' } } }],
['new head with an opt-out', { ...openPr, head: { ...openPr.head, sha: base }, labels: [{ name: 'no-preview' }] }],
['new merge', { ...openPr, merge_commit_sha: base }],
['still computing mergeability', { ...openPr, mergeable: null }],
['malformed labels', { ...openPr, labels: null }],
])('fails closed for %s', async (_name, response) => {
expect(await rootUpload(response)).toMatchObject({ status: 1, output: '' })
})

it('rejects the old merge after the base moves', async () => {
const result = await rootUpload({ ...openPr, base: { ...openPr.base, sha: head } })
expect(result).toMatchObject({ status: 1, output: '' })
expect(result.requests).toHaveLength(2)
})

it('rejects an invalid prefix and a failed lookup', async () => {
expect(await rootUpload(openPr, testedMerge, 'pr-420')).toMatchObject({ status: 1, requests: [] })
expect(await rootUpload(openPr, testedMerge, 'pr-42', 503)).toMatchObject({ status: 1, output: '' })
})
})