Open History to see the last commit
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;
28}
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 });
69}
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 }
164}
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 forkPreview = jobs("workflows/mobile-eas-preview-fork.yml");
230const forkPreviewScript = (id) =>
231 new (Object.getPrototypeOf(async () => {}).constructor)(
232 "github",
233 "context",
234 "core",
235 steps(forkPreview.request)
236 .find((step) => step.startsWith(`id: ${id}\n`))
237 .split(/^ {10}script: \|\n/m)[1]
238 .split(/^ {0,11}\S/m)[0]
239 .replace(/^ {12}/gm, ""),
240 );
241const consume = forkPreviewScript("consume");
242const pin = forkPreviewScript("pin");
243const forkPreviewEnvironment = /^ {10}ENVIRONMENT: (\S+)$/m.exec(forkPreview.request)[1];
244
245test("a fork preview is requested by a job that reads no secrets and checks out nothing", () => {
246 const { request } = forkPreview;
247 assert.doesNotMatch(request, /secrets\.|actions\/checkout|^ {4}environment:/m);
248 assert.ok(!runsProjectCode(request), "request runs project code");
249 assert.match(request, /^ {6}sha: \$\{\{ steps\.pin\.outputs\.sha \}\}$/m);
250 const pinStep = steps(request).find((step) => step.startsWith("id: pin\n"));
251 assert.match(pinStep, /^ {8}if: steps\.consume\.outputs\.consumed == 'true'$/m);
252});
253
254test("every fork preview job that reads a secret or runs the PR's code waits in the environment and builds the requested commit", () => {
255 const { request: _request, comment, ...gated } = forkPreview;
256 assert.deepEqual(Object.keys(gated), ["preview", "android-build", "ios-build"]);
257 for (const [name, block] of Object.entries(gated)) {
258 assert.match(block, /^ {4}needs: (?:request|\[request, preview\])$/m, name);
259 assert.ok(
260 block.includes(`\n environment:\n name: ${forkPreviewEnvironment}\n`),
261 `${name} waits in ${forkPreviewEnvironment}`,
262 );
263 assert.doesNotMatch(block, /github\.event\.pull_request\.head/, name);
264 const refs = Array.from(block.matchAll(/^ {10}ref: (.+)$/gm), (match) => match[1]);
265 assert.deepEqual(refs, ["${{ needs.request.outputs.sha }}"], name);
266 const jobSteps = steps(block);
267 assert.match(jobSteps[0], /^name: Confirm the PR is still open\n/, name);
268 assert.ok(jobSteps.findIndex((step) => /secrets\.|actions\/checkout/.test(step)) > 0, name);
269 }
270 assert.match(gated.preview, /^ {4}if: needs\.request\.outputs\.sha != ''$/m);
271 assert.doesNotMatch(comment, /secrets\.|^ +ref: |github\.event\.pull_request\.head/m);
272});
273
274async function runPin(environment, sha = "a".repeat(40)) {
275 const outputs = {};
276 const written = { comments: [], summary: "", failed: "" };
277 await pin(
278 {
279 async request(route, params) {
280 assert.equal(route, "GET /repos/{owner}/{repo}/environments/{environment_name}");
281 assert.equal(params.environment_name, forkPreviewEnvironment);
282 if (!environment) throw Object.assign(new Error("missing"), { status: 404 });
283 return { data: environment };
284 },
285 rest: { issues: { createComment: async ({ body }) => written.comments.push(body) } },
286 },
287 {
288 repo: { owner: "example", repo: "app" },
289 serverUrl: "https://github.example",
290 runId: 99,
291 payload: { sender: { login: "labeler" }, pull_request: { number: 7, head: { sha } } },
292 },
293 {
294 setFailed: (message) => (written.failed = message),
295 setOutput: (name, value) => (outputs[name] = value),
296 summary: {
297 addRaw(text) {
298 written.summary += text;
299 return this;
300 },
301 async write() {},
302 },
303 },
304 );
305 return { outputs, ...written };
306}
307
308test("a fork preview request names the commit where the reviewer reads it", async () => {
309 process.env.ENVIRONMENT = forkPreviewEnvironment;
310 const sha = "a".repeat(40);
311 const reviewers = { type: "required_reviewers", reviewers: [{ type: "Team" }] };
312 const named = await runPin({ protection_rules: [{ type: "branch_policy" }, reviewers] });
313 assert.deepEqual(named.outputs, { sha });
314 assert.equal(named.failed, "");
315 assert.deepEqual(named.comments, [named.summary]);
316 assert.ok(named.summary.includes(`https://github.example/example/app/pull/7/commits/${sha}`));
317 assert.ok(named.summary.includes("https://github.example/example/app/actions/runs/99"));
318 // Quoted, or YAML would end the title at the " #".
319 assert.match(
320 read("workflows/mobile-eas-preview-fork.yml"),
321 /^run-name: "\$\{\{ .*format\('Mobile preview of #\{0\} at \{1\}', github\.event\.pull_request\.number, github\.event\.pull_request\.head\.sha\) \|\| '' \}\}"$/m,
322 );
323});
324
325test("a fork preview request builds nothing unless the environment has required reviewers", async () => {
326 process.env.ENVIRONMENT = forkPreviewEnvironment;
327 for (const environment of [
328 undefined,
329 {},
330 { protection_rules: [] },
331 { protection_rules: [{ type: "branch_policy" }, { type: "wait_timer", wait_timer: 5 }] },
332 { protection_rules: [{ type: "required_reviewers", reviewers: [] }] },
333 ]) {
334 const refused = await runPin(environment);
335 assert.deepEqual([refused.outputs, refused.comments, refused.summary], [{}, [], ""]);
336 assert.match(refused.failed, /no required reviewers/);
337 }
338 const noCommit = await runPin(
339 { protection_rules: [{ type: "required_reviewers", reviewers: [{ type: "User" }] }] },
340 "main",
341 );
342 assert.deepEqual([noCommit.outputs, noCommit.comments], [{}, []]);
343 assert.match(noCommit.failed, /no head commit/);
344});
345
346async function runConsume(permission, removeStatus, removed = []) {
347 const outputs = {};
348 await consume(
349 {
350 rest: {
351 repos: {
352 async getCollaboratorPermissionLevel({ username }) {
353 assert.equal(username, "labeler");
354 if (permission === undefined) throw Object.assign(new Error("denied"), { status: 403 });
355 return { data: { permission } };
356 },
357 },
358 issues: {
359 async removeLabel(params) {
360 if (removeStatus) throw Object.assign(new Error("gone"), { status: removeStatus });
361 removed.push(params.name);
362 },
363 },
364 },
365 },
366 {
367 repo: { owner: "example", repo: "app" },
368 payload: {
369 sender: { login: "labeler" },
370 label: { name: "deploy" },
371 pull_request: { number: 7 },
372 },
373 },
374 { info() {}, warning() {}, setOutput: (name, value) => (outputs[name] = value) },
375 );
376 return { outputs, removed };
377}
378
379for (const [permission, consumed] of [
380 ["admin", "true"],
381 ["maintain", "true"],
382 ["write", "true"],
383 ["triage", "false"],
384 ["read", "false"],
385 ["none", "false"],
386]) {
387 test(`a fork preview label from ${permission} access is removed and ${consumed === "true" ? "builds" : "builds nothing"}`, async () => {
388 assert.deepEqual(await runConsume(permission), {
389 outputs: { consumed },
390 removed: ["deploy"],
391 });
392 });
393}
394
395test("a fork preview label is removed even when the access lookup fails", async () => {
396 const removed = [];
397 await assert.rejects(runConsume(undefined, undefined, removed), { status: 403 });
398 assert.deepEqual(removed, ["deploy"]);
399});
400
401test("a fork preview label removed before the run builds nothing", async () => {
402 assert.deepEqual(await runConsume("admin", 404), { outputs: { consumed: "false" }, removed: [] });
403});
404
405test("a version override rewrites only the app version", () => {
406 const config = read("../apps/mobile/app.config.ts");
407 const next = setMobileVersion(config, "9.8.7");
408 assert.match(next, /^ {2}version: repoEnv\.T3CODE_MOBILE_VERSION \?\? "9\.8\.7",$/m);
409 assert.equal(setMobileVersion(next, "9.8.7"), next);
410 assert.deepEqual(
411 next.split("\n").filter((line, index) => line !== config.split("\n")[index]).length,
412 1,
413 );
414 for (const version of ["", "1", "1.2.3.4", "1.2-beta", '1.2", extra: "x']) {
415 assert.throws(() => setMobileVersion(config, version), /two or three dot-separated integers/);
416 }
417 assert.throws(() => setMobileVersion("export default {};", "1.2.3"), /Could not update/);
418});
419
420test("a release version bump rewrites only the version of each release manifest", () => {
421 const listed = /releasePackageFiles = \[\n([^\]]+)\]/.exec(
422 read("../scripts/lib/tagged-source-version.ts"),
423 )[1];
424 assert.deepEqual(
425 RELEASE_PACKAGE_FILES,
426 Array.from(listed.matchAll(/"([^"]+)"/g), (m) => m[1]),
427 );
428 for (const file of RELEASE_PACKAGE_FILES) {
429 const manifest = read(`../${file}`);
430 const next = setReleaseVersion(manifest, "98.7.6");
431 assert.equal(JSON.parse(next).version, "98.7.6");
432 assert.deepEqual(
433 { ...JSON.parse(next), version: "" },
434 { ...JSON.parse(manifest), version: "" },
435 );
436 assert.equal(setReleaseVersion(next, "98.7.6"), next);
437 assert.deepEqual(
438 next.split("\n").filter((line, index) => line !== manifest.split("\n")[index]).length,
439 1,
440 );
441 }
442 for (const version of ["", "1", "1.2", "v1.2.3", '1.2.3", "x": "y']) {
443 assert.throws(() => setReleaseVersion('{\n "version": "1.0.0"\n}\n', version), /Invalid/);
444 }
445 assert.equal(
446 setReleaseVersion('{\n "version": "1.0.0"\n}\n', "1.2.3-rc.1"),
447 '{\n "version": "1.2.3-rc.1"\n}\n',
448 );
449 assert.throws(() => setReleaseVersion('{\n "name": "x"\n}\n', "1.2.3"), /exactly one/);
450});