Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

workflow-credentials.test.cjs

344 lines13.4 KB

1const assert = require("node:assert/strict");
2const { execFileSync, spawnSync } = require("node:child_process");
3const {
4 chmodSync,
5 mkdirSync,
6 mkdtempSync,
7 readFileSync,
8 rmSync,
9 writeFileSync,
10} = require("node:fs");
11const { tmpdir } = require("node:os");
12const { join } = require("node:path");
13const { test } = require("node:test");
14​
15const { setMobileVersion } = require("./set-mobile-version.cjs");
16const { RELEASE_PACKAGE_FILES, setReleaseVersion } = require("./set-release-version.cjs");
17​
18const read = (path) => readFileSync(join(__dirname, "..", path), "utf8");
19​
20function jobs(path) {
21 const body = read(path).split(/^jobs:\n/m)[1];
22 const found = {};
23 for (const block of body.split(/^(?= [\w-]+:\n)/m)) {
24 const name = /^ ([\w-]+):\n/.exec(block)?.[1];
25 if (name) found[name] = block;
26 }
27 return found;
29​
30const steps = (block) => block.split(/^ {4,6}- /m).slice(1);
31const runsProjectCode = (block) =>
32 /setup-vp@|setup-ci-deps|eas-local-build|expo-github-action|\b(?:vp|pnpm|npm|npx|eas) /.test(
33 block,
34 );
35​
36test("npm publishing is bound to the environment that admits only main and v* tags", () => {
37 const publish = jobs("workflows/release.yml").publish_cli;
38 assert.match(publish, /^ {6}id-token: write$/m);
39 assert.match(publish, /^ {4}environment: production$/m);
40});
41​
42test("the web preview gives the Vercel token to the deploy step only, after an install without lifecycle scripts", () => {
43 const deploy = jobs("workflows/web-preview.yml").deploy;
44 assert.doesNotMatch(deploy.split(/^ {4}steps:\n/m)[0], /secrets\./);
45 const withSecrets = steps(deploy).filter((step) => step.includes("secrets."));
46 assert.equal(withSecrets.length, 1);
47 assert.match(withSecrets[0], /name: Deploy preview/);
48 assert.match(deploy, /run-install: \|\n {12}args:\n {14}- --ignore-scripts\n/);
49});
50​
51const mobileWorkflows = [
52 "workflows/mobile-eas-preview.yml",
53 "workflows/mobile-eas-preview-build.yml",
54 "workflows/mobile-eas-production.yml",
55 "workflows/mobile-eas-production-build.yml",
56];
57​
58for (const path of mobileWorkflows) {
59 test(`${path}: no job that installs or builds can push to the repository`, () => {
60 for (const [name, block] of Object.entries(jobs(path))) {
61 if (/^ {4}uses: /m.test(block)) continue;
62 const writes = /contents: write|write-all|record-build-tag|create-github-app-token/.test(
63 block,
64 );
65 assert.match(block, /^ {4}permissions:\n/m, `${name} declares its permissions`);
66 assert.ok(!(writes && runsProjectCode(block)), `${name} holds a write token and runs code`);
67 }
68 });
70​
71test("the build record is pushed by the record job of each build workflow", () => {
72 for (const path of [
73 "workflows/mobile-eas-preview-build.yml",
74 "workflows/mobile-eas-production-build.yml",
75 ]) {
76 const { record, ...builds } = jobs(path);
77 assert.match(record, /uses: \.\/\.github\/actions\/record-build-tag/);
78 assert.match(record, /^ {6}contents: write/m);
79 for (const block of Object.values(builds)) assert.match(block, /^ {6}contents: read$/m);
80 }
81});
82​
83test("jobs that push run this workflow's own actions", () => {
84 for (const file of mobileWorkflows) {
85 for (const [name, block] of Object.entries(jobs(file))) {
86 if (!/contents: write|create-github-app-token/.test(block)) continue;
87 const jobSteps = steps(block);
88 const checkout = jobSteps.findIndex((step) => /^ +ref: .*\b(?:inputs|needs)\./m.test(step));
89 if (checkout === -1) continue;
90 const local = jobSteps.slice(checkout).filter((step) => /^ +uses: \.\//m.test(step));
91 assert.equal(local.length, 0, `${file} ${name} runs a local action from another checkout`);
92 }
93 }
94});
95​
96const recordScript = read("actions/record-build-tag/action.yml")
97 .split(/^ {6}run: \|\n/m)[1]
98 .replace(/^ {8}/gm, "")
99 .replace(/^remote=.*$/m, 'remote="$TEST_REMOTE"');
100​
101function recordTag(commitOf, failedFetches = 0) {
102 const directory = mkdtempSync(join(tmpdir(), "t3-record-tag-"));
103 const git = (cwd, ...args) => execFileSync("git", args, { cwd, encoding: "utf8" }).trim();
104 try {
105 const remote = join(directory, "remote.git");
106 const work = join(directory, "work");
107 git(directory, "init", "--quiet", "--bare", remote);
108 git(directory, "init", "--quiet", "--initial-branch=main", work);
109 const commit = (message) => {
110 git(
111 work,
112 "-c",
113 "user.name=t",
114 "-c",
115 "user.email=t@example.com",
116 "commit",
117 "--quiet",
118 "--allow-empty",
119 "-m",
120 message,
121 );
122 return git(work, "rev-parse", "HEAD");
123 };
124 const shas = { first: commit("first") };
125 shas.head = commit("second");
126 git(work, "push", "--quiet", remote, "main");
127 git(work, "checkout", "--quiet", "--detach");
128 shas.elsewhere = commit("not on main");
129 git(work, "push", "--quiet", remote, "HEAD:refs/heads/other");
130 git(work, "checkout", "--quiet", "main");
131 // The first fetches fail, and the waits between attempts are skipped.
132 const bin = join(directory, "bin");
133 mkdirSync(bin);
134 writeFileSync(
135 join(bin, "git"),
136 `#!/bin/bash\nif [ "$1" = fetch ] && [ "$(wc -l < "$FETCHES")" -lt "$FAILED_FETCHES" ]; then echo x >> "$FETCHES"; exit 1; fi\nexec "$REAL_GIT" "$@"\n`,
137 );
138 writeFileSync(join(bin, "sleep"), "#!/bin/bash\n");
139 chmodSync(join(bin, "git"), 0o755);
140 chmodSync(join(bin, "sleep"), 0o755);
141 writeFileSync(join(directory, "fetches"), "");
142 const result = spawnSync("bash", ["-c", recordScript], {
143 cwd: work,
144 encoding: "utf8",
145 env: {
146 PATH: `${bin}:${process.env.PATH}`,
147 REAL_GIT: execFileSync("bash", ["-c", "command -v git"], { encoding: "utf8" }).trim(),
148 FETCHES: join(directory, "fetches"),
149 FAILED_FETCHES: String(failedFetches),
150 HOME: directory,
151 TEST_REMOTE: remote,
152 GITHUB_REF: "refs/heads/main",
153 TAG: "build/1",
154 MESSAGE: "",
155 REPLACE: "false",
156 COMMIT: commitOf(shas),
157 },
158 });
159 const tagged = git(directory, "ls-remote", remote, "refs/tags/build/1").split(/\s/)[0];
160 return { status: result.status, tagged, shas };
161 } finally {
162 rmSync(directory, { recursive: true, force: true });
163 }
165​
166test("the build record tags the named commit only when it is on the workflow's ref", () => {
167 const onRef = recordTag((shas) => shas.first);
168 assert.deepEqual([onRef.status, onRef.tagged], [0, onRef.shas.first]);
169 const retried = recordTag((shas) => shas.first, 2);
170 assert.deepEqual([retried.status, retried.tagged], [0, retried.shas.first]);
171 assert.equal(recordTag((shas) => shas.first, 3).status, 1);
172 const head = recordTag(() => "");
173 assert.deepEqual([head.status, head.tagged], [0, head.shas.head]);
174 for (const commitOf of [(shas) => shas.elsewhere, () => "main", () => "0".repeat(40)]) {
175 const refused = recordTag(commitOf);
176 assert.deepEqual([refused.status, refused.tagged], [1, ""]);
177 }
178});
179​
180test("the store build record job runs the workflow's own action and passes the built commit as data", () => {
181 const { record } = jobs("workflows/mobile-eas-production-build.yml");
182 assert.doesNotMatch(record, /^ +ref: /m);
183 assert.match(record, /^ {10}commit: \$\{\{ inputs\.sha \}\}$/m);
184});
185​
186test("release deploys give the Vercel token to the deploy step only", () => {
187 const all = jobs("workflows/release.yml");
188 for (const name of ["build_web", "build_marketing"]) {
189 assert.doesNotMatch(all[name].split(/^ {4}steps:\n/m)[0], /secrets\.VERCEL/);
190 const withToken = steps(all[name]).filter((step) => step.includes("secrets.VERCEL_TOKEN"));
191 assert.equal(withToken.length, 1);
192 assert.match(withToken[0], /name: Build staged deployment/);
193 }
194});
195​
196test("the version override token covers this repository only", () => {
197 const { version, production } = jobs("workflows/mobile-eas-production.yml");
198 const mint = steps(version).find((step) => step.includes("create-github-app-token"));
199 assert.doesNotMatch(mint, /^\s+(?:owner|repositories):/m);
200 assert.match(mint, /^\s+permission-contents: write$/m);
201 assert.doesNotMatch(production, /RELEASE_APP|create-github-app-token/);
202});
203​
204test("the release version bump is pushed by a job that installs nothing, with a token for this repository only", () => {
205 const { finalize } = jobs("workflows/release.yml");
206 const mint = steps(finalize).find((step) => step.includes("create-github-app-token"));
207 assert.doesNotMatch(mint, /^\s+(?:owner|repositories):/m);
208 assert.match(mint, /^\s+permission-contents: write$/m);
209 assert.ok(!runsProjectCode(finalize), "finalize holds a write token and runs code");
210 assert.match(finalize, /run: node \.github\/scripts\/set-release-version\.cjs /);
211});
212​
213test("the Vite+ toolchain is cached before the job installs or runs project code", () => {
214 const names = Array.from(
215 read("actions/setup-ci-deps/action.yml").matchAll(
216 /^ {4}- name: (.+)\n(?: {6}.*\n)*? {6}uses: (\S+)|^ {4}- name: (.+)$/gm,
217 ),
218 (match) => ({ name: match[1] ?? match[3], uses: match[2] ?? "" }),
219 );
220 const index = (name) => names.findIndex((step) => step.name === name);
221 assert.match(names[index("Restore Vite+")].uses, /^actions\/cache\/restore@/);
222 assert.match(names[index("Save Vite+")].uses, /^actions\/cache\/save@/);
223 assert.ok(index("Save Vite+") < index("Resolve pnpm store"));
224 assert.ok(index("Save Vite+") < index("Install dependencies"));
225 // The combined action saves at the end of the job, after everything ran.
226 assert.ok(names.every((step) => !step.uses.startsWith("actions/cache@")));
227});
228​
229const consumeScript = steps(jobs("workflows/mobile-eas-preview-fork.yml").preview)
230 .find((step) => step.startsWith("id: consume\n"))
231 .split(/^ {10}script: \|\n/m)[1]
232 .replace(/^ {12}/gm, "");
233const consume = new (Object.getPrototypeOf(async () => {}).constructor)(
234 "github",
235 "context",
236 "core",
237 consumeScript,
238);
239​
240async function runConsume(permission, removeStatus, removed = []) {
241 const outputs = {};
242 await consume(
243 {
244 rest: {
245 repos: {
246 async getCollaboratorPermissionLevel({ username }) {
247 assert.equal(username, "labeler");
248 if (permission === undefined) throw Object.assign(new Error("denied"), { status: 403 });
249 return { data: { permission } };
250 },
251 },
252 issues: {
253 async removeLabel(params) {
254 if (removeStatus) throw Object.assign(new Error("gone"), { status: removeStatus });
255 removed.push(params.name);
256 },
257 },
258 },
259 },
260 {
261 repo: { owner: "example", repo: "app" },
262 payload: {
263 sender: { login: "labeler" },
264 label: { name: "deploy" },
265 pull_request: { number: 7 },
266 },
267 },
268 { info() {}, warning() {}, setOutput: (name, value) => (outputs[name] = value) },
269 );
270 return { outputs, removed };
272​
273for (const [permission, consumed] of [
274 ["admin", "true"],
275 ["maintain", "true"],
276 ["write", "true"],
277 ["triage", "false"],
278 ["read", "false"],
279 ["none", "false"],
280]) {
281 test(`a fork preview label from ${permission} access is removed and ${consumed === "true" ? "builds" : "builds nothing"}`, async () => {
282 assert.deepEqual(await runConsume(permission), {
283 outputs: { consumed },
284 removed: ["deploy"],
285 });
286 });
288​
289test("a fork preview label is removed even when the access lookup fails", async () => {
290 const removed = [];
291 await assert.rejects(runConsume(undefined, undefined, removed), { status: 403 });
292 assert.deepEqual(removed, ["deploy"]);
293});
294​
295test("a fork preview label removed before the run builds nothing", async () => {
296 assert.deepEqual(await runConsume("admin", 404), { outputs: { consumed: "false" }, removed: [] });
297});
298​
299test("a version override rewrites only the app version", () => {
300 const config = read("../apps/mobile/app.config.ts");
301 const next = setMobileVersion(config, "9.8.7");
302 assert.match(next, /^ {2}version: repoEnv\.T3CODE_MOBILE_VERSION \?\? "9\.8\.7",$/m);
303 assert.equal(setMobileVersion(next, "9.8.7"), next);
304 assert.deepEqual(
305 next.split("\n").filter((line, index) => line !== config.split("\n")[index]).length,
306 1,
307 );
308 for (const version of ["", "1", "1.2.3.4", "1.2-beta", '1.2", extra: "x']) {
309 assert.throws(() => setMobileVersion(config, version), /two or three dot-separated integers/);
310 }
311 assert.throws(() => setMobileVersion("export default {};", "1.2.3"), /Could not update/);
312});
313​
314test("a release version bump rewrites only the version of each release manifest", () => {
315 const listed = /releasePackageFiles = \[\n([^\]]+)\]/.exec(
316 read("../scripts/lib/tagged-source-version.ts"),
317 )[1];
318 assert.deepEqual(
319 RELEASE_PACKAGE_FILES,
320 Array.from(listed.matchAll(/"([^"]+)"/g), (m) => m[1]),
321 );
322 for (const file of RELEASE_PACKAGE_FILES) {
323 const manifest = read(`../${file}`);
324 const next = setReleaseVersion(manifest, "98.7.6");
325 assert.equal(JSON.parse(next).version, "98.7.6");
326 assert.deepEqual(
327 { ...JSON.parse(next), version: "" },
328 { ...JSON.parse(manifest), version: "" },
329 );
330 assert.equal(setReleaseVersion(next, "98.7.6"), next);
331 assert.deepEqual(
332 next.split("\n").filter((line, index) => line !== manifest.split("\n")[index]).length,
333 1,
334 );
335 }
336 for (const version of ["", "1", "1.2", "v1.2.3", '1.2.3", "x": "y']) {
337 assert.throws(() => setReleaseVersion('{\n "version": "1.0.0"\n}\n', version), /Invalid/);
338 }
339 assert.equal(
340 setReleaseVersion('{\n "version": "1.0.0"\n}\n', "1.2.3-rc.1"),
341 '{\n "version": "1.2.3-rc.1"\n}\n',
342 );
343 assert.throws(() => setReleaseVersion('{\n "name": "x"\n}\n', "1.2.3"), /exactly one/);
344});