Repository navigation
198 lines (186 loc) · 9.54 KB
/
Copy pathpublish-bundle.yml
File metadata and controls
198 lines (186 loc) · 9.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
name: Publish rebuilt action bundle
# Maintainers dispatch this publisher on main after reviewing a completed build.
# Never check out PR code, restore its caches, or execute downloaded artifacts.
on:
workflow_dispatch:
inputs:
run_id:
description: "Successful Rebuild action bundle run ID to publish."
required: true
type: string
permissions: {}
jobs:
publish:
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
actions: read
contents: read
pull-requests: read
steps:
- name: Validate the build request
id: request
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
env:
BUILD_RUN_ID: ${{ inputs.run_id }}
with:
script: |
const runId = process.env.BUILD_RUN_ID;
if (!/^[1-9][0-9]*$/.test(runId) || !Number.isSafeInteger(Number(runId)) ||
String(Number(runId)) !== runId) {
throw new Error('Enter a valid build run ID.');
}
const { data: run } = await github.rest.actions.getWorkflowRun({
...context.repo, run_id: Number(runId),
});
const repository = `${context.repo.owner}/${context.repo.repo}`;
const path = '.github/workflows/rebuild-bundle.yml';
if (run.event !== 'pull_request' || run.status !== 'completed' || run.conclusion !== 'success' ||
run.path !== path || run.head_repository?.full_name !== repository) {
throw new Error('Select a successful, completed same-repository PR rebuild.');
}
const match = /^Rebuild PR #([1-9][0-9]*) at ([0-9a-f]{40})$/.exec(run.display_title);
if (!match || match[2] !== run.head_sha) {
throw new Error('The build title must identify the PR and the run head SHA.');
}
// Reject altered triggers, checkout refs, and run-name expressions.
const { data: trusted } = await github.rest.repos.getContent({
...context.repo, path, ref: context.sha,
});
const { data: requested } = await github.rest.repos.getContent({
...context.repo, path, ref: run.head_sha,
});
if (trusted.type !== 'file' || requested.type !== 'file' || trusted.sha !== requested.sha) {
throw new Error('Update the PR branch: rebuild-bundle.yml must match the default branch.');
}
const { data: pr } = await github.rest.pulls.get({
...context.repo, pull_number: Number(match[1]),
});
if (pr.state !== 'open' || pr.head.sha !== run.head_sha ||
pr.head.repo?.full_name !== repository || pr.base.repo.full_name !== repository ||
pr.head.ref !== run.head_branch || pr.head.ref === pr.base.ref ||
pr.head.ref === context.payload.repository.default_branch ||
!pr.labels.some(label => label.name === 'needs-bundle-rebuild')) {
core.info('The PR changed or is no longer eligible for a bundle rebuild.');
return;
}
core.setOutput('pr-number', pr.number);
core.setOutput('branch', pr.head.ref);
core.setOutput('head-sha', run.head_sha);
core.setOutput('run-id', run.id);
core.setOutput('run-attempt', run.run_attempt);
core.setOutput('ready', 'true');
- name: Download bundles from this build attempt
if: steps.request.outputs.ready == 'true'
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
name: rebuilt-bundles-${{ steps.request.outputs.run-attempt }}
path: ${{ runner.temp }}/rebuilt-bundles
github-token: ${{ github.token }}
run-id: ${{ steps.request.outputs.run-id }}
- name: Validate bundles and prepare commit
id: prepare
if: steps.request.outputs.ready == 'true'
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
env:
PR_NUMBER: ${{ steps.request.outputs.pr-number }}
PR_BRANCH: ${{ steps.request.outputs.branch }}
PR_HEAD_SHA: ${{ steps.request.outputs.head-sha }}
with:
script: |
const fs = require('node:fs');
const path = require('node:path');
const { createHash } = require('node:crypto');
const expected = {
number: Number(process.env.PR_NUMBER),
head: { sha: process.env.PR_HEAD_SHA, ref: process.env.PR_BRANCH },
};
const repository = `${context.repo.owner}/${context.repo.repo}`;
const { data: pr } = await github.rest.pulls.get({
...context.repo, pull_number: expected.number,
});
if (pr.state !== 'open' || pr.head.sha !== expected.head.sha ||
pr.head.ref !== expected.head.ref || pr.head.repo?.full_name !== repository ||
!pr.labels.some(label => label.name === 'needs-bundle-rebuild')) {
core.info('The PR changed or no longer qualifies for a bundle rebuild; skip this result.');
return;
}
const files = ['index.mjs', 'gitlab/index.mjs', 'azure/index.mjs'];
const directories = ['', 'gitlab', 'azure'];
const root = path.join(process.env.RUNNER_TEMP, 'rebuilt-bundles');
// Reject unexpected paths, symlinks, and non-regular files before reading data.
for (const directory of directories) {
const absolute = path.join(root, directory);
if (!fs.lstatSync(absolute).isDirectory()) {
throw new Error(`Expected a bundle directory: ${directory}`);
}
for (const entry of fs.readdirSync(absolute, { withFileTypes: true })) {
const relative = directory ? `${directory}/${entry.name}` : entry.name;
if (directories.includes(relative) && entry.isDirectory()) continue;
if (files.includes(relative) && entry.isFile()) continue;
throw new Error(`Unexpected bundle artifact entry: ${relative}`);
}
}
const { data: commit } = await github.rest.git.getCommit({
...context.repo, commit_sha: expected.head.sha,
});
const { data: tree } = await github.rest.git.getTree({
...context.repo, tree_sha: commit.tree.sha, recursive: 'true',
});
if (tree.truncated) throw new Error('Cannot verify a truncated repository tree.');
const additions = [];
for (const file of files) {
const absolute = path.join(root, file);
const stat = fs.lstatSync(absolute);
if (!stat.isFile() || stat.size === 0 || stat.size > 10 * 1024 * 1024) {
throw new Error(`Invalid bundle file: ${file}`);
}
const content = fs.readFileSync(absolute);
const destination = `dist/${file}`;
const previous = tree.tree.find(entry => entry.path === destination);
if (previous && (previous.type !== 'blob' || previous.mode !== '100644')) {
throw new Error(`Expected a regular repository file: ${destination}`);
}
const sha = createHash('sha1').update(`blob ${content.length}\0`).update(content).digest('hex');
if (sha !== previous?.sha) {
additions.push({ path: destination, contents: content.toString('base64') });
}
}
if (additions.length === 0) {
core.info('Bundle already up to date; nothing to push.');
return;
}
fs.writeFileSync(path.join(process.env.RUNNER_TEMP, 'bundle-commit.json'), JSON.stringify({
branch: { repositoryNameWithOwner: repository, refName: `refs/heads/${expected.head.ref}` },
expectedHeadOid: expected.head.sha,
message: { headline: 'chore: rebuild action bundle for dependency update' },
fileChanges: { additions },
}));
core.setOutput('changed', 'true');
# Create the narrowly scoped token only after validation on this runner.
# The App identity ensures the commit triggers the PR's required checks.
- uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0
if: steps.prepare.outputs.changed == 'true'
id: app-token
with:
client-id: ${{ secrets.APP_ID }}
private-key: ${{ secrets.APP_PRIVATE_KEY }}
repositories: ${{ github.event.repository.name }}
permission-contents: write
- name: Commit the rebuilt bundles
if: steps.prepare.outputs.changed == 'true'
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
with:
github-token: ${{ steps.app-token.outputs.token }}
script: |
const fs = require('node:fs');
const path = require('node:path');
const input = JSON.parse(fs.readFileSync(path.join(process.env.RUNNER_TEMP, 'bundle-commit.json'), 'utf8'));
// The API atomically checks the head SHA, so a concurrent push or rebase
// cannot receive bundles built from an older revision.
await github.graphql(`
mutation($input: CreateCommitOnBranchInput!) {
createCommitOnBranch(input: $input) { commit { oid } }
}
`, { input });