From 8b1640b8c570c31ac503dfa3110b97fc19698a86 Mon Sep 17 00:00:00 2001 From: Michael Recachinas Date: Tue, 11 Aug 2026 11:01:18 -0400 Subject: [PATCH 1/3] Migrate Explore triage commenter off pull_request_target Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../explore-triage-commenter-writer.yml | 262 ++++++++++++++++++ .../workflows/explore-triage-commenter.yml | 253 +++++++++-------- 2 files changed, 388 insertions(+), 127 deletions(-) create mode 100644 .github/workflows/explore-triage-commenter-writer.yml diff --git a/.github/workflows/explore-triage-commenter-writer.yml b/.github/workflows/explore-triage-commenter-writer.yml new file mode 100644 index 000000000000..a6505529b739 --- /dev/null +++ b/.github/workflows/explore-triage-commenter-writer.yml @@ -0,0 +1,262 @@ +name: Explore PR Triage Commenter Writer + +on: + workflow_run: + workflows: [Explore PR Triage Commenter] + types: [completed] + +permissions: + actions: read + issues: write + pull-requests: read + +jobs: + upsert-comment: + if: >- + ${{ github.event.workflow_run.conclusion == 'success' && + github.event.workflow_run.event == 'pull_request' }} + runs-on: ubuntu-latest + steps: + - name: Download triage comment data + id: artifact + env: + GH_TOKEN: ${{ github.token }} + REPOSITORY: ${{ github.repository }} + RUN_ID: ${{ github.event.workflow_run.id }} + run: | + set -euo pipefail + mkdir -p "$RUNNER_TEMP/explore-triage" + artifact_id="$(gh api "repos/$REPOSITORY/actions/runs/$RUN_ID/artifacts" \ + --jq '.artifacts[] | select(.name == "explore-triage-comment" and .expired == false) | .id' | head -n 1)" + if [ -z "$artifact_id" ]; then + echo "No explore triage artifact found for run $RUN_ID" + echo "found=false" >> "$GITHUB_OUTPUT" + exit 0 + fi + gh api "repos/$REPOSITORY/actions/artifacts/$artifact_id/zip" > "$RUNNER_TEMP/explore-triage/artifact.zip" + unzip -p "$RUNNER_TEMP/explore-triage/artifact.zip" explore-triage-comment.json > "$RUNNER_TEMP/explore-triage/comment.json" + echo "found=true" >> "$GITHUB_OUTPUT" + + - name: Upsert sticky comment + if: steps.artifact.outputs.found == 'true' + uses: actions/github-script@v9 + env: + COMMENT_DATA_PATH: ${{ runner.temp }}/explore-triage/comment.json + MARKER: '' + with: + script: | + const fs = require('fs'); + + const marker = process.env.MARKER; + const owner = context.repo.owner; + const repo = context.repo.repo; + const expectedRepo = `${owner}/${repo}`; + const run = context.payload.workflow_run; + const runPr = Array.isArray(run.pull_requests) && run.pull_requests[0]; + if (!runPr || !runPr.number) { + core.info('Workflow run is not associated with a pull request; skipping.'); + return; + } + + const data = JSON.parse(fs.readFileSync(process.env.COMMENT_DATA_PATH, 'utf8')); + validateIdentity(data, runPr.number); + + const { data: pr } = await github.rest.pulls.get({ + owner, + repo, + pull_number: runPr.number, + }); + + if (pr.base.repo.full_name !== expectedRepo) { + throw new Error(`Unexpected base repo: ${pr.base.repo.full_name}`); + } + if (pr.state !== 'open') { + core.info(`PR #${pr.number} is ${pr.state}; skipping.`); + return; + } + if (data.headSha !== pr.head.sha) { + core.info(`Stale triage data for ${data.headSha}; current PR head is ${pr.head.sha}.`); + return; + } + if (!data.hasChanges) { + core.info('No topic or collection changes were reported; skipping.'); + return; + } + + validatePayload(data); + const body = renderComment(data); + + const comments = await github.paginate(github.rest.issues.listComments, { + owner, + repo, + issue_number: pr.number, + per_page: 100, + }); + const existing = comments.find(c => c.body && c.body.startsWith(marker)); + + if (existing) { + await github.rest.issues.updateComment({ + owner, + repo, + comment_id: existing.id, + body, + }); + core.info(`Updated comment ${existing.id}`); + } else { + await github.rest.issues.createComment({ + owner, + repo, + issue_number: pr.number, + body, + }); + core.info('Created new comment'); + } + + function validateIdentity(data, prNumber) { + if (!data || data.schema !== 'explore-triage-comment/v1') { + throw new Error('Unexpected artifact schema.'); + } + if (data.owner !== owner || data.repo !== repo) { + throw new Error(`Artifact repo mismatch: ${data.owner}/${data.repo}`); + } + if (!Number.isInteger(data.prNumber) || data.prNumber !== prNumber) { + throw new Error(`Artifact PR mismatch: ${data.prNumber} !== ${prNumber}`); + } + if (data.baseRepoFullName !== `${owner}/${repo}`) { + throw new Error(`Artifact base repo mismatch: ${data.baseRepoFullName}`); + } + if (!/^[0-9a-f]{40}$/i.test(data.headSha)) { + throw new Error('Artifact head SHA is invalid.'); + } + } + + function validatePayload(data) { + if (!Array.isArray(data.topics) || !Array.isArray(data.collections)) { + throw new Error('Artifact topics/collections must be arrays.'); + } + if (data.topics.length > 100 || data.collections.length > 100) { + throw new Error('Artifact contains too many topic or collection entries.'); + } + for (const topic of data.topics) { + validateSlug(topic.slug); + if (topic.count !== null && (!Number.isInteger(topic.count) || topic.count < 0)) { + throw new Error(`Invalid topic count for ${topic.slug}.`); + } + } + for (const collection of data.collections) { + validateSlug(collection.slug); + if (!['ok', 'not-found', 'error'].includes(collection.readStatus)) { + throw new Error(`Invalid read status for ${collection.slug}.`); + } + if (!Array.isArray(collection.items) || collection.items.length > 500) { + throw new Error(`Invalid item list for ${collection.slug}.`); + } + for (const item of collection.items) validateItem(item); + } + } + + function validateSlug(slug) { + if (typeof slug !== 'string' || !/^[a-z0-9](?:[a-z0-9-]{0,80}[a-z0-9])?$/i.test(slug)) { + throw new Error(`Invalid slug: ${slug}`); + } + } + + function validateItem(item) { + if (!item || typeof item.name !== 'string' || item.name.length > 140) { + throw new Error('Invalid item name.'); + } + if (item.valid === false) { + if (!/^[A-Za-z0-9._/-]+$/.test(item.name)) { + throw new Error(`Unsafe invalid item token: ${item.name}`); + } + return; + } + if (item.valid !== true || !/^[\w.-]+\/[\w.-]+$/.test(item.name)) { + throw new Error(`Invalid repository item: ${item.name}`); + } + if (!['ok', 'not-found', 'error'].includes(item.lookupStatus)) { + throw new Error(`Invalid lookup status for ${item.name}.`); + } + if (item.lookupStatus === 'ok') { + if (!Number.isInteger(item.stars) || item.stars < 0) throw new Error(`Invalid stars for ${item.name}.`); + if (item.pushed !== null && !/^\d{4}-\d{2}-\d{2}$/.test(item.pushed)) throw new Error(`Invalid pushed date for ${item.name}.`); + if (typeof item.ownerType !== 'string' || !/^[A-Za-z]+$/.test(item.ownerType)) throw new Error(`Invalid owner type for ${item.name}.`); + if (!Array.isArray(item.notes)) throw new Error(`Invalid notes for ${item.name}.`); + for (const note of item.notes) { + if (!['possible-self-submission', 'archived', 'disabled'].includes(note)) { + throw new Error(`Invalid note for ${item.name}: ${note}`); + } + } + } + } + + function renderComment(data) { + const sections = []; + + if (data.topics.length > 0) { + const lines = ['### Topics', '']; + for (const topic of data.topics) { + const url = `https://github.com/topics/${encodeURIComponent(topic.slug)}`; + if (topic.count === null) { + lines.push(`- **${topic.slug}** — [topic page](${url}) _(repo count lookup failed)_`); + } else { + lines.push(`- **${topic.slug}** — ${topic.count.toLocaleString()} repositories — [topic page](${url})`); + } + } + sections.push(lines.join('\n')); + } + + for (const collection of data.collections) { + const lines = [`### Collection \`${collection.slug}\``, '']; + if (collection.readStatus !== 'ok') { + lines.push(`_Could not read \`collections/${collection.slug}/index.md\` at PR head (\`${collection.errorStatus || collection.readStatus}\`)._`); + sections.push(lines.join('\n')); + continue; + } + if (collection.items.length === 0) { + lines.push('_No `items:` list found in frontmatter._'); + sections.push(lines.join('\n')); + continue; + } + + lines.push('| Item | Stars | Last push | Owner type | Notes |'); + lines.push('| --- | ---: | --- | --- | --- |'); + + for (const item of collection.items) { + if (item.valid === false) { + lines.push(`| \`${escapeTableToken(item.name)}\` | – | – | – | invalid format |`); + continue; + } + if (item.lookupStatus === 'ok') { + const notes = item.notes.map(noteText).join(', ') || '–'; + lines.push(`| [\`${item.name}\`](https://github.com/${item.name}) | ${item.stars.toLocaleString()} | ${item.pushed || '–'} | ${item.ownerType} | ${notes} |`); + } else { + const note = item.lookupStatus === 'not-found' ? 'not found' : `error (${item.errorStatus || '?'})`; + lines.push(`| \`${item.name}\` | – | – | – | ${note} |`); + } + } + lines.push(''); + sections.push(lines.join('\n')); + } + + return [ + marker, + '', + '', + '## Maintainer triage', + '', + ...sections, + ].join('\n'); + } + + function noteText(note) { + return { + 'possible-self-submission': '⚠️ possible self-submission', + archived: 'archived', + disabled: 'disabled', + }[note]; + } + + function escapeTableToken(value) { + return value.replace(/`/g, "'").replace(/\\/g, '\\\\').replace(/\|/g, '\\|'); + } diff --git a/.github/workflows/explore-triage-commenter.yml b/.github/workflows/explore-triage-commenter.yml index d1215fdc26c6..9d418d53f272 100644 --- a/.github/workflows/explore-triage-commenter.yml +++ b/.github/workflows/explore-triage-commenter.yml @@ -1,16 +1,11 @@ name: Explore PR Triage Commenter -# Posts a sticky comment on PRs that touch topic or collection pages, -# surfacing the facts maintainers normally look up by hand: -# - topics: repo count for the topic -# - collections: per-item stars, last push, owner type, plus a flag if -# the PR author looks like one of the item owners (self-submission) -# -# Edit-in-place: subsequent runs (synchronize, reopen) update the same -# comment instead of posting a new one. Marker: +# Computes maintainer triage data for Explore PRs in an unprivileged +# pull_request workflow. A separate workflow_run workflow writes the sticky +# comment after re-fetching PR state; no privileged job checks out PR code. on: - pull_request_target: + pull_request: types: [opened, synchronize, reopened] paths: - 'topics/**' @@ -22,26 +17,40 @@ concurrency: permissions: contents: read - pull-requests: write + pull-requests: read jobs: - triage: + build-comment-data: runs-on: ubuntu-latest steps: - - uses: actions/github-script@v9 + - name: Build triage comment data + uses: actions/github-script@v9 env: - MARKER: '' + OUTPUT_PATH: ${{ runner.temp }}/explore-triage-comment.json with: script: | - const marker = process.env.MARKER; + const fs = require('fs'); + const pr = context.payload.pull_request; + const baseOwner = context.repo.owner; + const baseRepo = context.repo.repo; const prNumber = pr.number; const prAuthor = pr.user.login.toLowerCase(); const headSha = pr.head.sha; - const baseOwner = context.repo.owner; - const baseRepo = context.repo.repo; - // List files in the PR (paginated). + const payload = { + schema: 'explore-triage-comment/v1', + owner: baseOwner, + repo: baseRepo, + prNumber, + headSha, + baseRepoFullName: pr.base.repo.full_name, + headRepoFullName: pr.head.repo && pr.head.repo.full_name, + hasChanges: false, + topics: [], + collections: [], + }; + const files = await github.paginate(github.rest.pulls.listFiles, { owner: baseOwner, repo: baseRepo, @@ -49,14 +58,12 @@ jobs: per_page: 100, }); - // Detect topic and collection slugs touched. - // Skip removed files; only validate slug shape we'd ever expect on disk. const SLUG = /^[a-z0-9](?:[a-z0-9-]{0,80}[a-z0-9])?$/i; const topics = new Set(); const collections = new Set(); for (const f of files) { if (f.status === 'removed') continue; - const m = f.filename.match(/^(topics|collections)\/([^\/]+)\//); + const m = f.filename.match(/^(topics|collections)\/([^/]+)\//); if (!m) continue; const slug = m[2]; if (!SLUG.test(slug)) continue; @@ -66,134 +73,114 @@ jobs: if (topics.size === 0 && collections.size === 0) { core.info('No topic or collection changes detected; nothing to do.'); + writePayload(payload); return; } - const sections = []; + payload.hasChanges = true; + + for (const slug of [...topics].sort()) { + const topic = { slug, count: null }; + try { + const res = await github.rest.search.repos({ + q: `topic:${slug}`, + per_page: 1, + }); + topic.count = res.data.total_count; + } catch (err) { + core.warning(`Search failed for topic '${slug}': ${err.message}`); + } + payload.topics.push(topic); + } + + for (const slug of [...collections].sort()) { + const collection = { + slug, + readStatus: 'ok', + errorStatus: null, + items: [], + }; + + let content; + try { + content = await readCollectionIndex(slug); + } catch (err) { + collection.readStatus = err.status === 404 ? 'not-found' : 'error'; + collection.errorStatus = String(err.status || 'error'); + payload.collections.push(collection); + continue; + } + + const items = parseCollectionItems(content); + for (const item of items) { + if (!/^[\w.-]+\/[\w.-]+$/.test(item)) { + collection.items.push({ name: item, valid: false }); + continue; + } - // ---- Topic section ---- - if (topics.size > 0) { - const lines = ['### Topics', '']; - for (const slug of topics) { - let count = null; + const [owner, repo] = item.split('/'); try { - const res = await github.rest.search.repos({ - q: `topic:${slug}`, - per_page: 1, + const r = await github.rest.repos.get({ owner, repo }); + const notes = []; + if (owner.toLowerCase() === prAuthor) notes.push('possible-self-submission'); + if (r.data.archived) notes.push('archived'); + if (r.data.disabled) notes.push('disabled'); + collection.items.push({ + name: item, + valid: true, + lookupStatus: 'ok', + stars: r.data.stargazers_count, + pushed: r.data.pushed_at ? r.data.pushed_at.slice(0, 10) : null, + ownerType: r.data.owner.type, + notes, }); - count = res.data.total_count; } catch (err) { - core.warning(`Search failed for topic '${slug}': ${err.message}`); - } - const url = `https://github.com/topics/${encodeURIComponent(slug)}`; - if (count == null) { - lines.push(`- **${slug}** — [topic page](${url}) _(repo count lookup failed)_`); - } else { - lines.push(`- **${slug}** — ${count.toLocaleString()} repositories — [topic page](${url})`); + collection.items.push({ + name: item, + valid: true, + lookupStatus: err.status === 404 ? 'not-found' : 'error', + errorStatus: String(err.status || 'error'), + }); } } - sections.push(lines.join('\n')); + + payload.collections.push(collection); } - // ---- Collection section ---- - if (collections.size > 0) { - for (const slug of collections) { - const lines = [`### Collection \`${slug}\``, '']; + writePayload(payload); + + async function readCollectionIndex(slug) { + const attempts = []; + if (pr.head.repo) { + attempts.push({ + owner: pr.head.repo.owner.login, + repo: pr.head.repo.name, + ref: headSha, + }); + } + attempts.push({ owner: baseOwner, repo: baseRepo, ref: headSha }); - // Read collection's index.md at the PR head SHA. - // PR commits from forks are mirrored into the base repo's network, - // so we can fetch from the base repo with the head SHA — simpler - // and avoids any cross-repo token concerns. - let content; + let lastError; + for (const attempt of attempts) { try { const res = await github.rest.repos.getContent({ - owner: baseOwner, - repo: baseRepo, + ...attempt, path: `collections/${slug}/index.md`, - ref: headSha, }); - content = Buffer.from(res.data.content, 'base64').toString('utf8'); - } catch (err) { - lines.push(`_Could not read \`collections/${slug}/index.md\` at PR head (\`${err.status || 'error'}\`)._`); - sections.push(lines.join('\n')); - continue; - } - - const items = parseCollectionItems(content); - if (items.length === 0) { - lines.push('_No `items:` list found in frontmatter._'); - sections.push(lines.join('\n')); - continue; - } - - lines.push('| Item | Stars | Last push | Owner type | Notes |'); - lines.push('| --- | ---: | --- | --- | --- |'); - - for (const item of items) { - if (!/^[\w.-]+\/[\w.-]+$/.test(item)) { - const safeItem = item.replace(/`/g, "'").replace(/\\/g, '\\\\').replace(/\|/g, '\\|'); - lines.push(`| \`${safeItem}\` | – | – | – | invalid format |`); - continue; - } - const [owner, repo] = item.split('/'); - try { - const r = await github.rest.repos.get({ owner, repo }); - const stars = r.data.stargazers_count.toLocaleString(); - const pushed = r.data.pushed_at ? r.data.pushed_at.slice(0, 10) : '–'; - const ownerType = r.data.owner.type; - const notes = []; - if (owner.toLowerCase() === prAuthor) notes.push('⚠️ possible self-submission'); - if (r.data.archived) notes.push('archived'); - if (r.data.disabled) notes.push('disabled'); - lines.push(`| [\`${item}\`](https://github.com/${item}) | ${stars} | ${pushed} | ${ownerType} | ${notes.join(', ') || '–'} |`); - } catch (err) { - const note = err.status === 404 ? 'not found' : `error (${err.status || '?'})`; - lines.push(`| \`${item}\` | – | – | – | ${note} |`); + if (Array.isArray(res.data) || res.data.type !== 'file' || !res.data.content) { + const err = new Error('Collection index is not a file'); + err.status = 'invalid'; + throw err; } + return Buffer.from(res.data.content, 'base64').toString('utf8'); + } catch (err) { + lastError = err; } - lines.push(''); - sections.push(lines.join('\n')); } - } - - const body = [ - marker, - '', - '', - '## Maintainer triage', - '', - ...sections, - ].join('\n'); - - // Edit-in-place via marker. - const comments = await github.paginate(github.rest.issues.listComments, { - owner: baseOwner, - repo: baseRepo, - issue_number: prNumber, - per_page: 100, - }); - const existing = comments.find(c => c.body && c.body.startsWith(marker)); - - if (existing) { - await github.rest.issues.updateComment({ - owner: baseOwner, - repo: baseRepo, - comment_id: existing.id, - body, - }); - core.info(`Updated comment ${existing.id}`); - } else { - await github.rest.issues.createComment({ - owner: baseOwner, - repo: baseRepo, - issue_number: prNumber, - body, - }); - core.info('Created new comment'); + throw lastError; } function parseCollectionItems(text) { - // Frontmatter between leading --- lines. const fmMatch = text.match(/^---\n([\s\S]*?)\n---/); if (!fmMatch) return []; const lines = fmMatch[1].split('\n'); @@ -201,7 +188,6 @@ jobs: let inItems = false; for (const line of lines) { if (/^items:\s*$/.test(line)) { inItems = true; continue; } - // Next top-level key ends the items block. if (inItems && /^[a-zA-Z_]\w*\s*:/.test(line)) break; if (inItems) { const m = line.match(/^\s*-\s*([^\s#]+)/); @@ -210,3 +196,16 @@ jobs: } return items; } + + function writePayload(data) { + fs.writeFileSync(process.env.OUTPUT_PATH, JSON.stringify(data, null, 2)); + core.info(`Wrote ${process.env.OUTPUT_PATH}`); + } + + - name: Upload triage comment data + uses: actions/upload-artifact@v4 + with: + name: explore-triage-comment + path: ${{ runner.temp }}/explore-triage-comment.json + if-no-files-found: error + retention-days: 1 From 1cb527c54a6905c873401de57baf742f3a4ade24 Mon Sep 17 00:00:00 2001 From: Michael Recachinas Date: Tue, 11 Aug 2026 11:11:48 -0400 Subject: [PATCH 2/3] Fix Explore triage writer for fork PR workflow runs Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../explore-triage-commenter-writer.yml | 43 ++++++++++++++----- 1 file changed, 33 insertions(+), 10 deletions(-) diff --git a/.github/workflows/explore-triage-commenter-writer.yml b/.github/workflows/explore-triage-commenter-writer.yml index a6505529b739..b8b780302b9b 100644 --- a/.github/workflows/explore-triage-commenter-writer.yml +++ b/.github/workflows/explore-triage-commenter-writer.yml @@ -10,6 +10,10 @@ permissions: issues: write pull-requests: read +concurrency: + group: explore-triage-commenter-writer-${{ github.event.workflow_run.head_repository.full_name || github.event.workflow_run.head_sha }}-${{ github.event.workflow_run.head_branch || github.event.workflow_run.head_sha }} + cancel-in-progress: false + jobs: upsert-comment: if: >- @@ -52,21 +56,25 @@ jobs: const repo = context.repo.repo; const expectedRepo = `${owner}/${repo}`; const run = context.payload.workflow_run; - const runPr = Array.isArray(run.pull_requests) && run.pull_requests[0]; - if (!runPr || !runPr.number) { - core.info('Workflow run is not associated with a pull request; skipping.'); - return; - } const data = JSON.parse(fs.readFileSync(process.env.COMMENT_DATA_PATH, 'utf8')); - validateIdentity(data, runPr.number); + validateIdentity(data); + + const runHeadSha = await getWorkflowRunHeadSha(run); + if (!/^[0-9a-f]{40}$/i.test(runHeadSha)) { + throw new Error(`Workflow run head SHA is invalid: ${runHeadSha}`); + } const { data: pr } = await github.rest.pulls.get({ owner, repo, - pull_number: runPr.number, + pull_number: data.prNumber, }); + if (pr.head.sha !== runHeadSha) { + core.info(`PR #${pr.number} head ${pr.head.sha} does not match workflow run head ${runHeadSha}; skipping.`); + return; + } if (pr.base.repo.full_name !== expectedRepo) { throw new Error(`Unexpected base repo: ${pr.base.repo.full_name}`); } @@ -112,15 +120,30 @@ jobs: core.info('Created new comment'); } - function validateIdentity(data, prNumber) { + async function getWorkflowRunHeadSha(run) { + if (typeof run.head_sha === 'string' && run.head_sha.length > 0) { + return run.head_sha; + } + if (!run.id) { + throw new Error('Workflow run id is missing.'); + } + const { data: workflowRun } = await github.rest.actions.getWorkflowRun({ + owner, + repo, + run_id: run.id, + }); + return workflowRun.head_sha; + } + + function validateIdentity(data) { if (!data || data.schema !== 'explore-triage-comment/v1') { throw new Error('Unexpected artifact schema.'); } if (data.owner !== owner || data.repo !== repo) { throw new Error(`Artifact repo mismatch: ${data.owner}/${data.repo}`); } - if (!Number.isInteger(data.prNumber) || data.prNumber !== prNumber) { - throw new Error(`Artifact PR mismatch: ${data.prNumber} !== ${prNumber}`); + if (!Number.isInteger(data.prNumber) || data.prNumber <= 0) { + throw new Error(`Artifact PR number is invalid: ${data.prNumber}`); } if (data.baseRepoFullName !== `${owner}/${repo}`) { throw new Error(`Artifact base repo mismatch: ${data.baseRepoFullName}`); From 836e053f8f1dbbe22632ea58f2a95084406fb608 Mon Sep 17 00:00:00 2001 From: Michael Recachinas Date: Wed, 12 Aug 2026 10:40:34 -0400 Subject: [PATCH 3/3] Harden Explore triage writer trust boundaries Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 512eb347-ec89-4250-8bf1-87048974b01d --- .../explore-triage-commenter-writer.yml | 185 ++++++++++++++++-- 1 file changed, 171 insertions(+), 14 deletions(-) diff --git a/.github/workflows/explore-triage-commenter-writer.yml b/.github/workflows/explore-triage-commenter-writer.yml index b8b780302b9b..e1d8409e9315 100644 --- a/.github/workflows/explore-triage-commenter-writer.yml +++ b/.github/workflows/explore-triage-commenter-writer.yml @@ -27,18 +27,85 @@ jobs: GH_TOKEN: ${{ github.token }} REPOSITORY: ${{ github.repository }} RUN_ID: ${{ github.event.workflow_run.id }} + MAX_ARTIFACT_BYTES: 1048576 + MAX_JSON_BYTES: 131072 run: | set -euo pipefail mkdir -p "$RUNNER_TEMP/explore-triage" - artifact_id="$(gh api "repos/$REPOSITORY/actions/runs/$RUN_ID/artifacts" \ - --jq '.artifacts[] | select(.name == "explore-triage-comment" and .expired == false) | .id' | head -n 1)" - if [ -z "$artifact_id" ]; then + artifact_rows="$( + gh api --paginate "repos/$REPOSITORY/actions/runs/$RUN_ID/artifacts" \ + --jq '.artifacts[] | select(.name == "explore-triage-comment" and .expired == false) | [.id, .size_in_bytes] | @tsv' + )" + artifacts=() + if [ -n "$artifact_rows" ]; then + mapfile -t artifacts <<< "$artifact_rows" + fi + if (( ${#artifacts[@]} == 0 )); then echo "No explore triage artifact found for run $RUN_ID" echo "found=false" >> "$GITHUB_OUTPUT" exit 0 fi - gh api "repos/$REPOSITORY/actions/artifacts/$artifact_id/zip" > "$RUNNER_TEMP/explore-triage/artifact.zip" - unzip -p "$RUNNER_TEMP/explore-triage/artifact.zip" explore-triage-comment.json > "$RUNNER_TEMP/explore-triage/comment.json" + if (( ${#artifacts[@]} != 1 )); then + echo "Expected exactly one explore triage artifact, found ${#artifacts[@]}" >&2 + exit 1 + fi + + IFS=$'\t' read -r artifact_id artifact_size <<< "${artifacts[0]}" + if ! [[ "$artifact_id" =~ ^[0-9]+$ && "$artifact_size" =~ ^[0-9]+$ ]]; then + echo "Artifact metadata is invalid" >&2 + exit 1 + fi + if (( artifact_size == 0 || artifact_size > MAX_ARTIFACT_BYTES )); then + echo "Artifact archive size $artifact_size is outside the allowed range" >&2 + exit 1 + fi + + artifact_zip="$RUNNER_TEMP/explore-triage/artifact.zip" + comment_json="$RUNNER_TEMP/explore-triage/comment.json" + gh api "repos/$REPOSITORY/actions/artifacts/$artifact_id/zip" > "$artifact_zip" + + actual_artifact_size="$(stat -c '%s' "$artifact_zip")" + if ! [[ "$actual_artifact_size" =~ ^[0-9]+$ ]] || + (( actual_artifact_size == 0 || actual_artifact_size > MAX_ARTIFACT_BYTES )); then + echo "Downloaded artifact archive size $actual_artifact_size is outside the allowed range" >&2 + exit 1 + fi + + ARTIFACT_ZIP="$artifact_zip" COMMENT_JSON="$comment_json" python3 - <<'PY' + import os + import zipfile + + archive_path = os.environ["ARTIFACT_ZIP"] + output_path = os.environ["COMMENT_JSON"] + max_json_bytes = int(os.environ["MAX_JSON_BYTES"]) + expected_name = "explore-triage-comment.json" + + with zipfile.ZipFile(archive_path) as archive: + matches = [entry for entry in archive.infolist() if entry.filename == expected_name] + if len(matches) != 1: + raise ValueError(f"Expected exactly one {expected_name} entry, found {len(matches)}") + + entry = matches[0] + if entry.is_dir() or entry.flag_bits & 0x1: + raise ValueError("Artifact JSON entry must be an unencrypted regular file") + if entry.file_size == 0 or entry.file_size > max_json_bytes: + raise ValueError( + f"Artifact JSON entry size {entry.file_size} is outside the allowed range" + ) + + total = 0 + with archive.open(entry) as source, open(output_path, "xb") as destination: + while chunk := source.read(65536): + total += len(chunk) + if total > max_json_bytes: + raise ValueError("Artifact JSON exceeded the allowed size while extracting") + destination.write(chunk) + + if total != entry.file_size: + raise ValueError( + f"Extracted JSON size {total} did not match declared size {entry.file_size}" + ) + PY echo "found=true" >> "$GITHUB_OUTPUT" - name: Upsert sticky comment @@ -59,22 +126,38 @@ jobs: const data = JSON.parse(fs.readFileSync(process.env.COMMENT_DATA_PATH, 'utf8')); validateIdentity(data); + validatePayload(data); const runHeadSha = await getWorkflowRunHeadSha(run); if (!/^[0-9a-f]{40}$/i.test(runHeadSha)) { throw new Error(`Workflow run head SHA is invalid: ${runHeadSha}`); } + const associatedPrNumber = await getAssociatedPullRequestNumber(run, runHeadSha); + if (associatedPrNumber === null) return; + if (data.prNumber !== associatedPrNumber) { + core.info(`Artifact PR #${data.prNumber} is not the PR associated with workflow run ${run.id}; skipping.`); + return; + } + const { data: pr } = await github.rest.pulls.get({ owner, repo, - pull_number: data.prNumber, + pull_number: associatedPrNumber, }); if (pr.head.sha !== runHeadSha) { core.info(`PR #${pr.number} head ${pr.head.sha} does not match workflow run head ${runHeadSha}; skipping.`); return; } + if (run.head_repository && pr.head.repo && pr.head.repo.full_name !== run.head_repository.full_name) { + core.info(`PR #${pr.number} head repository does not match the workflow run; skipping.`); + return; + } + if (run.head_branch && pr.head.ref !== run.head_branch) { + core.info(`PR #${pr.number} head branch does not match the workflow run; skipping.`); + return; + } if (pr.base.repo.full_name !== expectedRepo) { throw new Error(`Unexpected base repo: ${pr.base.repo.full_name}`); } @@ -91,8 +174,10 @@ jobs: return; } - validatePayload(data); const body = renderComment(data); + if (Buffer.byteLength(body, 'utf8') > 60000) { + throw new Error('Rendered triage comment exceeds the allowed size.'); + } const comments = await github.paginate(github.rest.issues.listComments, { owner, @@ -135,6 +220,49 @@ jobs: return workflowRun.head_sha; } + async function getAssociatedPullRequestNumber(run, runHeadSha) { + const runPullRequests = Array.isArray(run.pull_requests) ? run.pull_requests : []; + if (runPullRequests.length > 0) { + const associatedNumbers = runPullRequests + .map(pull => pull && pull.number) + .filter(number => Number.isSafeInteger(number) && number > 0); + if (!associatedNumbers.includes(data.prNumber)) { + core.info(`Artifact PR #${data.prNumber} is not in the workflow run pull request association; skipping.`); + return null; + } + return data.prNumber; + } + + const headRepo = run.head_repository; + const headBranch = run.head_branch; + const headOwner = headRepo && headRepo.owner && headRepo.owner.login; + if (!headRepo || typeof headRepo.full_name !== 'string' || + typeof headOwner !== 'string' || typeof headBranch !== 'string' || + headOwner.length === 0 || headBranch.length === 0) { + throw new Error('Workflow run is missing the trusted head repository or branch association.'); + } + + const candidates = await github.paginate(github.rest.pulls.list, { + owner, + repo, + state: 'all', + head: `${headOwner}:${headBranch}`, + per_page: 100, + }); + const matches = candidates.filter(pull => + Number.isSafeInteger(pull.number) && + pull.head && pull.head.sha === runHeadSha && + pull.head.ref === headBranch && + pull.head.repo && pull.head.repo.full_name === headRepo.full_name && + pull.base && pull.base.repo && pull.base.repo.full_name === expectedRepo + ); + if (matches.length !== 1) { + core.warning(`Could not uniquely associate workflow run ${run.id} with a pull request; found ${matches.length} matches.`); + return null; + } + return matches[0].number; + } + function validateIdentity(data) { if (!data || data.schema !== 'explore-triage-comment/v1') { throw new Error('Unexpected artifact schema.'); @@ -142,7 +270,7 @@ jobs: if (data.owner !== owner || data.repo !== repo) { throw new Error(`Artifact repo mismatch: ${data.owner}/${data.repo}`); } - if (!Number.isInteger(data.prNumber) || data.prNumber <= 0) { + if (!Number.isSafeInteger(data.prNumber) || data.prNumber <= 0) { throw new Error(`Artifact PR number is invalid: ${data.prNumber}`); } if (data.baseRepoFullName !== `${owner}/${repo}`) { @@ -151,6 +279,9 @@ jobs: if (!/^[0-9a-f]{40}$/i.test(data.headSha)) { throw new Error('Artifact head SHA is invalid.'); } + if (typeof data.hasChanges !== 'boolean') { + throw new Error('Artifact hasChanges flag is invalid.'); + } } function validatePayload(data) { @@ -161,16 +292,27 @@ jobs: throw new Error('Artifact contains too many topic or collection entries.'); } for (const topic of data.topics) { + if (!topic || typeof topic !== 'object') { + throw new Error('Invalid topic entry.'); + } validateSlug(topic.slug); - if (topic.count !== null && (!Number.isInteger(topic.count) || topic.count < 0)) { + if (topic.count !== null && (!Number.isSafeInteger(topic.count) || topic.count < 0)) { throw new Error(`Invalid topic count for ${topic.slug}.`); } } for (const collection of data.collections) { + if (!collection || typeof collection !== 'object') { + throw new Error('Invalid collection entry.'); + } validateSlug(collection.slug); if (!['ok', 'not-found', 'error'].includes(collection.readStatus)) { throw new Error(`Invalid read status for ${collection.slug}.`); } + validateOptionalStatusToken( + collection.errorStatus, + `collection ${collection.slug}`, + collection.readStatus !== 'ok' + ); if (!Array.isArray(collection.items) || collection.items.length > 500) { throw new Error(`Invalid item list for ${collection.slug}.`); } @@ -185,11 +327,11 @@ jobs: } function validateItem(item) { - if (!item || typeof item.name !== 'string' || item.name.length > 140) { + if (!item || typeof item.name !== 'string' || item.name.length === 0 || item.name.length > 140) { throw new Error('Invalid item name.'); } if (item.valid === false) { - if (!/^[A-Za-z0-9._/-]+$/.test(item.name)) { + if (/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/u.test(item.name)) { throw new Error(`Unsafe invalid item token: ${item.name}`); } return; @@ -200,11 +342,16 @@ jobs: if (!['ok', 'not-found', 'error'].includes(item.lookupStatus)) { throw new Error(`Invalid lookup status for ${item.name}.`); } + validateOptionalStatusToken( + item.errorStatus, + `item ${item.name}`, + item.lookupStatus !== 'ok' + ); if (item.lookupStatus === 'ok') { - if (!Number.isInteger(item.stars) || item.stars < 0) throw new Error(`Invalid stars for ${item.name}.`); + if (!Number.isSafeInteger(item.stars) || item.stars < 0) throw new Error(`Invalid stars for ${item.name}.`); if (item.pushed !== null && !/^\d{4}-\d{2}-\d{2}$/.test(item.pushed)) throw new Error(`Invalid pushed date for ${item.name}.`); - if (typeof item.ownerType !== 'string' || !/^[A-Za-z]+$/.test(item.ownerType)) throw new Error(`Invalid owner type for ${item.name}.`); - if (!Array.isArray(item.notes)) throw new Error(`Invalid notes for ${item.name}.`); + if (typeof item.ownerType !== 'string' || !/^[A-Za-z]{1,32}$/.test(item.ownerType)) throw new Error(`Invalid owner type for ${item.name}.`); + if (!Array.isArray(item.notes) || item.notes.length > 3) throw new Error(`Invalid notes for ${item.name}.`); for (const note of item.notes) { if (!['possible-self-submission', 'archived', 'disabled'].includes(note)) { throw new Error(`Invalid note for ${item.name}: ${note}`); @@ -213,6 +360,16 @@ jobs: } } + function validateOptionalStatusToken(value, label, required) { + if (value === null || value === undefined) { + if (required) throw new Error(`Missing error status for ${label}.`); + return; + } + if (typeof value !== 'string' || !/^[A-Za-z0-9_-]{1,32}$/.test(value)) { + throw new Error(`Invalid error status for ${label}.`); + } + } + function renderComment(data) { const sections = [];