From 203c6f214153eafe0b9e40c2658b171a1fefbc2f Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 5 Dec 2026 12:40:52 -0600 Subject: [PATCH] feat(ci[lua]) Verify manual PR preview dispatches why: Lua maintainers can rebuild a pull request preview from a dispatch. The shared workflows need to verify its tested merge. what: - Resolve open Lua pull requests to their tested merge before building. - Recheck the artifact's merge, base and head before preview upload. - Keep the dispatch opt-in and restrict forks to build-only artifacts. --- .github/workflows/port-docs.yml | 6 +- .github/workflows/reusable-deploy.yml | 30 +++++- scripts/lua-preview-source.sh | 57 +++++++++++ scripts/port-docs-identity.sh | 21 +++- site/test/deploy-workflow.test.ts | 3 +- site/test/lua-preview-dispatch.test.ts | 133 +++++++++++++++++++++++++ 6 files changed, 244 insertions(+), 6 deletions(-) create mode 100644 scripts/lua-preview-source.sh create mode 100644 site/test/lua-preview-dispatch.test.ts diff --git a/.github/workflows/port-docs.yml b/.github/workflows/port-docs.yml index ab5d4e332..be84209ad 100644 --- a/.github/workflows/port-docs.yml +++ b/.github/workflows/port-docs.yml @@ -34,7 +34,9 @@ on: type: boolean default: false publish-previews: - description: Publish same-repository pull requests under their pr-N version using the caller's preview role. + description: > + Publish same-repository pull requests under their pr-N version using + the caller's preview role. Lua also accepts manual PR dispatches. required: false type: boolean default: false @@ -127,6 +129,8 @@ jobs: REF_TYPE: ${{ github.ref_type }} DEFAULT_BRANCH: ${{ github.event.repository.default_branch }} TAG_PREFIX: ${{ inputs.tag-prefix }} + PORT: ${{ inputs.port }} + SOURCE_REPOSITORY: ${{ inputs.source-repository || github.repository }} INPUT_SOURCE_REF: ${{ inputs.source-ref }} INPUT_VERSION: ${{ inputs.version }} INPUT_KIND: ${{ inputs.version-kind }} diff --git a/.github/workflows/reusable-deploy.yml b/.github/workflows/reusable-deploy.yml index ae2cd413c..b973f327a 100644 --- a/.github/workflows/reusable-deploy.yml +++ b/.github/workflows/reusable-deploy.yml @@ -79,8 +79,9 @@ on: require-current-pr: description: > Before PR publication, require the current open, same-repository - PR to match this run's tested source. Callers serialize publication - and cleanup in the same workflow queue. Non-PR versions are unchanged. + PR to match this run's tested source. Required for manual Lua PR + previews. Callers serialize publication and cleanup in the same + workflow queue. Non-PR versions are unchanged. required: false type: boolean default: false @@ -299,7 +300,9 @@ jobs: # upstream job outputs, but must query current PR state on every upload # attempt. Match the verified artifact source to the tested merge too. - name: Require current tested pull request - if: inputs.require-current-pr && inputs.version-kind == 'pr' + if: >- + inputs.version-kind == 'pr' && + (inputs.require-current-pr || (github.event_name == 'workflow_dispatch' && inputs.port == 'lua')) env: GH_TOKEN: ${{ github.token }} EVENT: ${{ github.event_name }} @@ -309,8 +312,29 @@ jobs: TESTED_MERGE: ${{ github.sha }} PORT: ${{ inputs.port }} VERSION: ${{ inputs.version }} + REQUIRE_CURRENT_PR: ${{ inputs.require-current-pr }} + PREVIEW_ENVIRONMENT: ${{ inputs.environment }} run: | set -euo pipefail + if [[ "$EVENT" == workflow_dispatch && "$PORT" == lua ]]; then + [[ "$REPOSITORY" == libtmux/libtmux-lua && "$REQUIRE_CURRENT_PR" == true && "$PREVIEW_ENVIRONMENT" == docs-preview ]] || { + echo '::error::manual Lua previews require the current PR check and docs-preview environment' >&2 + exit 1 + } + # Dispatch github.sha is the workflow ref. The verified descriptor + # supplies the tested source; GitHub must still report that merge. + tested_merge=$(jq -er '.sourceSha' publication/publication.json) + [[ "$tested_merge" =~ ^[0-9a-f]{40}$ ]] || { + echo '::error::manual Lua preview artifact requires an exact source SHA' >&2 + exit 1 + } + preview=$(bash publisher/scripts/lua-preview-source.sh "$VERSION" "$tested_merge") + jq -e '.sameRepository == true' <<< "$preview" > /dev/null || { + echo '::error::fork previews cannot publish' >&2 + exit 1 + } + exit 0 + fi [[ "$EVENT" == pull_request && -n "$PORT" && "$PR" =~ ^[1-9][0-9]*$ && "$VERSION" == "pr-$PR" && "$EXPECTED_HEAD" =~ ^[0-9a-f]{40}$ && "$TESTED_MERGE" =~ ^[0-9a-f]{40}$ ]] || { echo '::error::invalid tested pull request identity' >&2 exit 1 diff --git a/scripts/lua-preview-source.sh b/scripts/lua-preview-source.sh new file mode 100644 index 000000000..8ad7c3736 --- /dev/null +++ b/scripts/lua-preview-source.sh @@ -0,0 +1,57 @@ +#!/usr/bin/env bash +# Resolve an open Lua PR's GitHub test merge for a manual preview. The builder +# and publisher call this independently so an older artifact cannot be reused +# after the PR closes or its test merge changes. +set -euo pipefail + +version=$1 +source_ref=$2 +repository=libtmux/libtmux-lua + +[[ "$version" =~ ^pr-([1-9][0-9]*)$ ]] || { + echo '::error::a manual Lua preview requires version pr-N' >&2 + exit 1 +} +number=${BASH_REMATCH[1]} +merge_ref="refs/pull/$number/merge" +[[ "$source_ref" == "$merge_ref" || "$source_ref" =~ ^[0-9a-f]{40}$ ]] || { + echo "::error::source-ref must be $merge_ref or its exact commit SHA" >&2 + exit 1 +} + +# Both endpoints are public for Lua. The reusable callers need no new token permissions. +github_get() { + curl --fail --silent --show-error --connect-timeout 10 --max-time 30 \ + --header 'Accept: application/vnd.github+json' --header 'Cache-Control: no-cache' \ + "https://api.github.com/repos/$repository/$1" +} + +pull=$(github_get "pulls/$number" | jq -ces --arg number "$number" --arg repo "$repository" ' + def sha: type == "string" and test("^[0-9a-f]{40}$"); + select(length == 1) | .[0] | select( + (.number | type == "number" and tostring == $number) and + .state == "open" and .mergeable == true and .base.repo.full_name == $repo and + (.head.repo.full_name | type == "string" and length > 0) and + (.head.sha | sha) and (.base.sha | sha) and (.merge_commit_sha | sha) + ) | {merge: .merge_commit_sha, head: .head.sha, base: .base.sha, sameRepository: (.head.repo.full_name == $repo)} +') || { + echo "::error::cannot verify an open, mergeable Lua PR $number" >&2 + exit 1 +} + +merge=$(jq -r '.merge' <<< "$pull") +[[ "$source_ref" == "$merge_ref" || "$source_ref" == "$merge" ]] || { + echo "::error::source-ref differs from Lua PR $number's current tested merge" >&2 + exit 1 +} + +# GitHub can report the previous merge while it recomputes one for a new head +# or base. Verify both parents before accepting the reported merge. +github_get "git/commits/$merge" | jq -es --argjson pull "$pull" ' + length == 1 and (.[0] | .sha == $pull.merge and [.parents[].sha] == [$pull.base, $pull.head]) +' > /dev/null || { + echo "::error::Lua PR $number has no tested merge of its current base and head" >&2 + exit 1 +} + +jq -c '{merge, sameRepository}' <<< "$pull" diff --git a/scripts/port-docs-identity.sh b/scripts/port-docs-identity.sh index 90dcdba02..5ec0d3831 100755 --- a/scripts/port-docs-identity.sh +++ b/scripts/port-docs-identity.sh @@ -18,6 +18,8 @@ # TAG_PREFIX is stripped first, so libtmux-rs's `libtmux@v0.1.0` publishes # `v0.1.0`. # - A dispatch publishes exactly what its inputs name, at any ref. +# A Lua PR dispatch with previews enabled verifies the requested PR and +# builds its pinned merge commit. Forks remain build-only. # - A schedule builds exactly what its inputs name and never publishes: the # docs repository's port-heads.yml builds each port's head this way. # @@ -108,6 +110,17 @@ case "$EVENT" in exit 1 } case "$INPUT_KIND" in + pr) + [[ "$EVENT" == workflow_dispatch && "${PORT:-}" == lua && "${PUBLISH_PREVIEWS:-false}" == true && + "${GITHUB_REPOSITORY:-}" == libtmux/libtmux-lua && "${SOURCE_REPOSITORY:-}" == "$GITHUB_REPOSITORY" ]] || { + echo "invalid version-kind: $INPUT_KIND" >&2 + exit 1 + } + [[ "${INPUT_DEFAULT:-false}" == false ]] || { + echo 'PR previews cannot be defaults' >&2 + exit 1 + } + ;; trunk | tag | alias) ;; *) echo "invalid version-kind: $INPUT_KIND" >&2; exit 1 ;; esac @@ -119,7 +132,13 @@ case "$EVENT" in echo 'resolves-to applies only to aliases' >&2 exit 1 fi - entries=$(entry "$INPUT_VERSION" "$INPUT_KIND" "${INPUT_DEFAULT:-false}" "$INPUT_RESOLVES_TO" "${INPUT_PUBLISH:-false}") + publish=${INPUT_PUBLISH:-false} + if [[ "$INPUT_KIND" == pr ]]; then + preview=$(bash "$(dirname "$0")/lua-preview-source.sh" "$INPUT_VERSION" "$source_ref") + source_ref=$(jq -r '.merge' <<< "$preview") + [[ $(jq -r '.sameRepository' <<< "$preview") == true ]] || publish=false + fi + entries=$(entry "$INPUT_VERSION" "$INPUT_KIND" "${INPUT_DEFAULT:-false}" "$INPUT_RESOLVES_TO" "$publish") ;; *) echo "unsupported event: $EVENT" >&2 diff --git a/site/test/deploy-workflow.test.ts b/site/test/deploy-workflow.test.ts index 9b763a434..e6a7d7fbd 100644 --- a/site/test/deploy-workflow.test.ts +++ b/site/test/deploy-workflow.test.ts @@ -762,7 +762,8 @@ describe('current PR publication guard', () => { expect(start).toBeGreaterThan(reusable.indexOf(' - name: Verify artifact and build provenance')) expect(start).toBeLessThan(aws) const check = reusable.slice(start, aws) - expect(check).toContain("if: inputs.require-current-pr && inputs.version-kind == 'pr'") + 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 }}') expect(check).toContain('EXPECTED_HEAD: ${{ github.event.pull_request.head.sha }}') expect(check).toContain('GH_TOKEN: ${{ github.token }}') diff --git a/site/test/lua-preview-dispatch.test.ts b/site/test/lua-preview-dispatch.test.ts new file mode 100644 index 000000000..2a0f657f1 --- /dev/null +++ b/site/test/lua-preview-dispatch.test.ts @@ -0,0 +1,133 @@ +import { spawnSync } from 'node:child_process' +import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { describe, expect, it } from 'vitest' + +const root = fileURLToPath(new URL('../../', import.meta.url)) +const workflow = readFileSync(join(root, '.github/workflows/reusable-deploy.yml'), 'utf8') +const guard = /- name: Require current tested pull request[\s\S]*? run: \|\n((?: {10}[^\n]*\n|\n)*)/.exec(workflow)![1].replace(/^ {10}/gm, '') +const repository = 'libtmux/libtmux-lua' +const mergeRef = 'refs/pull/42/merge' +const merge = 'a'.repeat(40) +const head = 'b'.repeat(40) +const base = 'c'.repeat(40) +const other = 'd'.repeat(40) +const pr = { + number: 42, state: 'open', mergeable: true, merge_commit_sha: merge, + head: { repo: { full_name: repository }, sha: head }, + base: { repo: { full_name: repository }, sha: base }, +} +const fork = { ...pr, head: { ...pr.head, repo: { full_name: 'someone/libtmux-lua' } } } +const commit = { sha: merge, parents: [{ sha: base }, { sha: head }] } + +interface Dispatch { + env?: Record + pull?: unknown + mergeCommit?: unknown + artifactSource?: string + publishJob?: boolean +} + +function runDispatch({ env, pull = pr, mergeCommit = commit, artifactSource = merge, publishJob = false }: Dispatch = {}) { + const cwd = mkdtempSync(join(tmpdir(), 'libtmux-lua-dispatch-')) + try { + const output = join(cwd, 'output') + const calls = join(cwd, 'calls') + writeFileSync(output, '') + writeFileSync(calls, '') + mkdirSync(join(cwd, 'publication')) + writeFileSync(join(cwd, 'publication/publication.json'), JSON.stringify({ sourceSha: artifactSource })) + symlinkSync(root, join(cwd, 'publisher'), 'dir') + writeFileSync(join(cwd, 'curl'), `#!${process.execPath} +const fs = require('node:fs') +const url = process.argv.at(-1) +fs.appendFileSync(${JSON.stringify(calls)}, url + '\\n') +const responses = ${JSON.stringify({ + [`https://api.github.com/repos/${repository}/pulls/42`]: pull, + [`https://api.github.com/repos/${repository}/git/commits/${merge}`]: mergeCommit, + })} +if (responses[url] == null) process.exit(22) +process.stdout.write(JSON.stringify(responses[url])) +`, { mode: 0o755 }) + const result = spawnSync('bash', publishJob ? ['-c', guard] : [join(root, 'scripts/port-docs-identity.sh')], { + cwd, encoding: 'utf8', timeout: 10000, + env: { + PATH: `${cwd}:${process.env.PATH}`, GITHUB_OUTPUT: output, + EVENT: 'workflow_dispatch', PORT: 'lua', GITHUB_REPOSITORY: repository, + SOURCE_REPOSITORY: repository, REPOSITORY: repository, PUBLISH_PREVIEWS: 'true', + INPUT_SOURCE_REF: mergeRef, INPUT_VERSION: 'pr-42', INPUT_KIND: 'pr', + INPUT_DEFAULT: 'false', INPUT_RESOLVES_TO: '', INPUT_PUBLISH: 'true', + REQUIRE_CURRENT_PR: 'true', PREVIEW_ENVIRONMENT: 'docs-preview', VERSION: 'pr-42', + // A dispatch's own commit is deliberately different from the selected PR's merge. + SHA: other, TESTED_MERGE: other, PR: '', EXPECTED_HEAD: '', ...env, + }, + }) + expect(result.error).toBeUndefined() + return { + ...result, + outputs: readFileSync(output, 'utf8'), + calls: readFileSync(calls, 'utf8').trim().split('\n').filter(Boolean), + } + } finally { + rmSync(cwd, { recursive: true, force: true }) + } +} + +describe('manual Lua preview dispatch', () => { + it.each([mergeRef, merge])('builds the tested merge for %s', (source) => { + const result = runDispatch({ env: { INPUT_SOURCE_REF: source } }) + expect(result.status, result.stderr).toBe(0) + expect(result.outputs).toContain(`source_ref=${merge}\n`) + expect(result.outputs).toContain('"version":"pr-42","kind":"pr","isDefault":false,"resolvesTo":"","publish":true') + expect(result.outputs).toContain('should_publish=true\n') + }) + + it.each([{ env: { INPUT_PUBLISH: 'false' } }, { pull: fork }])('keeps a nonpublishing request or fork build-only', (options) => { + const result = runDispatch(options) + expect(result.status, result.stderr).toBe(0) + expect(result.outputs).toContain(`source_ref=${merge}\n`) + expect(result.outputs).toContain('should_publish=false\n') + }) + + it.each>([ + { EVENT: 'schedule', INPUT_PUBLISH: 'false' }, { PORT: 'rs' }, { PUBLISH_PREVIEWS: 'false' }, + { GITHUB_REPOSITORY: 'someone/libtmux-lua' }, { SOURCE_REPOSITORY: 'someone/libtmux-lua' }, + { INPUT_VERSION: 'pr-042' }, { INPUT_VERSION: 'latest' }, { INPUT_DEFAULT: 'true' }, + { INPUT_RESOLVES_TO: 'latest' }, { INPUT_SOURCE_REF: 'refs/pull/42/head' }, { INPUT_SOURCE_REF: 'refs/pull/43/merge' }, + ])('rejects an ineligible dispatch before contacting GitHub: %j', (env) => { + const result = runDispatch({ env }) + expect(result.status).toBe(1) + expect(result.outputs).toBe('') + expect(result.calls).toEqual([]) + }) + + it('validates the artifact merge instead of the dispatcher commit', () => { + const result = runDispatch({ publishJob: true }) + expect(result.status, result.stderr).toBe(0) + expect(result.calls).toEqual([ + `https://api.github.com/repos/${repository}/pulls/42`, + `https://api.github.com/repos/${repository}/git/commits/${merge}`, + ]) + }) + + it.each([ + { artifactSource: other }, { artifactSource: mergeRef }, { pull: fork }, + { pull: { ...pr, state: 'closed' } }, { pull: { ...pr, mergeable: null } }, + { pull: { ...pr, number: 43 } }, { pull: { ...pr, merge_commit_sha: other } }, + { pull: { ...pr, head: { ...pr.head, sha: other } } }, { pull: { ...pr, base: { ...pr.base, sha: other } } }, + { pull: null }, { mergeCommit: null }, { mergeCommit: { ...commit, parents: [{ sha: head }] } }, + ])('refuses publication when live metadata cannot prove the artifact source: %j', (options) => { + expect(runDispatch({ ...options, publishJob: true }).status).not.toBe(0) + }) + + it.each>([ + { REQUIRE_CURRENT_PR: 'false' }, { PREVIEW_ENVIRONMENT: 'docs' }, + { REPOSITORY: 'someone/libtmux-lua' }, { VERSION: 'pr-042' }, + ])('rejects a publisher call without the preview identity and environment: %j', (env) => { + const result = runDispatch({ env, publishJob: true }) + expect(result.status).toBe(1) + expect(result.calls).toEqual([]) + }) +})