返回 CodeWhale
release-assets.test.js
根目录 / npm / codewhale / test / release-assets.test.js
1 const assert = require("node:assert/strict");
2 const { execFileSync } = require("node:child_process");
3 const fs = require("node:fs");
4 const os = require("node:os");
5 const path = require("node:path");
6 const test = require("node:test");
7
8 const pkg = require("../package.json");
9 const {
10 allReleaseAssetNames,
11 BUNDLE_ASSET_NAMES,
12 BUNDLE_CHECKSUM_MANIFEST,
13 CHECKSUM_MANIFEST,
14 checksummedReleaseAssetNames,
15 detectBinaryNames,
16 LEGACY_TUI_BRIDGE_ASSET_NAMES,
17 transportOptions,
18 } = require("../scripts/artifacts");
19 const {
20 assertChecksumManifestIncludes,
21 assertPackageVersionMatchesBinaryVersion,
22 assertReleaseAssetsFresh,
23 downloadJson,
24 downloadText,
25 findReleaseWorkflowRun,
26 limits,
27 requestStatus,
28 parseChecksumManifest,
29 } = require("../scripts/verify-release-assets");
30
31 test("parseChecksumManifest accepts GNU and BSD filename forms", () => {
32 const manifest = parseChecksumManifest(
33 [
34 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa codewhale-linux-x64",
35 "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb *codewhale-windows-x64.exe",
36 ].join("\n"),
37 );
38
39 assert.equal(manifest.get("codewhale-linux-x64"), "a".repeat(64));
40 assert.equal(manifest.get("codewhale-windows-x64.exe"), "b".repeat(64));
41 });
42
43 test("parseChecksumManifest rejects malformed checksum rows", () => {
44 assert.throws(
45 () => parseChecksumManifest("not-a-sha codewhale-linux-x64"),
46 /Invalid checksum manifest line/,
47 );
48 });
49
50 test("assertReleaseAssetsFresh rejects missing release assets", () => {
51 assert.throws(
52 () =>
53 assertReleaseAssetsFresh(
54 { assets: [{ name: "codewhale-linux-x64", state: "uploaded", updated_at: "2026-06-26T00:10:00Z" }] },
55 ["codewhale-linux-x64", "codewhale-artifacts-sha256.txt"],
56 { database_id: 123, created_at: "2026-06-26T00:00:00Z" },
57 ),
58 /missing required release asset/,
59 );
60 });
61
62 test("assertChecksumManifestIncludes rejects missing bundle manifest and archive rows", () => {
63 const manifest = parseChecksumManifest(
64 `${"a".repeat(64)} codewhale-linux-x64.tar.gz`,
65 );
66
67 assert.throws(
68 () =>
69 assertChecksumManifestIncludes(
70 manifest,
71 ["codewhale-linux-x64.tar.gz", "codewhale-bundles-sha256.txt"],
72 "Canonical checksum manifest",
73 ),
74 /Canonical checksum manifest is missing codewhale-bundles-sha256\.txt/,
75 );
76 });
77
78 test("bundle checksum rows use public archive basenames", () => {
79 const manifest = parseChecksumManifest(
80 `${"a".repeat(64)} bundles/codewhale-linux-x64.tar.gz`,
81 );
82
83 assert.throws(
84 () =>
85 assertChecksumManifestIncludes(
86 manifest,
87 ["codewhale-linux-x64.tar.gz"],
88 "Bundle checksum manifest",
89 ),
90 /Bundle checksum manifest is missing codewhale-linux-x64\.tar\.gz/,
91 );
92 });
93
94 test("assertReleaseAssetsFresh rejects assets older than the release workflow run", () => {
95 assert.throws(
96 () =>
97 assertReleaseAssetsFresh(
98 { assets: [{ name: "codewhale-linux-x64", state: "uploaded", updated_at: "2026-06-25T23:59:59Z" }] },
99 ["codewhale-linux-x64"],
100 { database_id: 123, created_at: "2026-06-26T00:00:00Z" },
101 ),
102 /asset set is stale/,
103 );
104 });
105
106 test("assertReleaseAssetsFresh rejects non-uploaded assets", () => {
107 assert.throws(
108 () =>
109 assertReleaseAssetsFresh(
110 { assets: [{ name: "codewhale-linux-x64", state: "new", updated_at: "2026-06-26T00:10:00Z" }] },
111 ["codewhale-linux-x64"],
112 { database_id: 123, created_at: "2026-06-26T00:00:00Z" },
113 ),
114 /asset set is stale/,
115 );
116 });
117
118 test("assertReleaseAssetsFresh accepts assets updated by the release workflow run", () => {
119 assert.doesNotThrow(() =>
120 assertReleaseAssetsFresh(
121 { assets: [{ name: "codewhale-linux-x64", state: "uploaded", updated_at: "2026-06-26T00:10:00Z" }] },
122 ["codewhale-linux-x64"],
123 { database_id: 123, created_at: "2026-06-26T00:00:00Z" },
124 ),
125 );
126 });
127
128 test("assertReleaseAssetsFresh accepts assets uploaded before a job-level rerun bumped run_started_at (#5429)", () => {
129 assert.doesNotThrow(() =>
130 assertReleaseAssetsFresh(
131 { assets: [{ name: "codewhale-linux-x64", state: "uploaded", updated_at: "2026-08-15T02:00:00Z" }] },
132 ["codewhale-linux-x64"],
133 {
134 database_id: 123,
135 // `gh run rerun --failed` moves the run-level start forward…
136 run_started_at: "2026-08-15T10:00:00Z",
137 // …but the release job that actually uploaded the assets is unchanged.
138 release_job_started_at: "2026-08-15T01:00:00Z",
139 },
140 ),
141 );
142 });
143
144 test("assertReleaseAssetsFresh still rejects assets older than the successful release job", () => {
145 assert.throws(
146 () =>
147 assertReleaseAssetsFresh(
148 { assets: [{ name: "codewhale-linux-x64", state: "uploaded", updated_at: "2026-08-15T00:30:00Z" }] },
149 ["codewhale-linux-x64"],
150 {
151 database_id: 123,
152 run_started_at: "2026-08-15T10:00:00Z",
153 release_job_started_at: "2026-08-15T01:00:00Z",
154 },
155 ),
156 /asset set is stale/,
157 );
158 });
159
160 test("findReleaseWorkflowRun accepts a successful release job when a downstream job failed", async () => {
161 const run = {
162 id: 123,
163 head_sha: "abc123",
164 head_branch: "v0.9.6",
165 event: "push",
166 conclusion: "failure",
167 updated_at: "2026-08-12T08:48:00Z",
168 };
169 const api = async (_repo, endpoint) => {
170 if (endpoint.includes("/workflows/release.yml/runs")) {
171 return { workflow_runs: [run] };
172 }
173 assert.equal(endpoint, "/actions/runs/123/jobs?per_page=100");
174 return {
175 jobs: [
176 { name: "release", conclusion: "success", started_at: "2026-08-12T07:30:00Z" },
177 { name: "npm", conclusion: "failure" },
178 ],
179 };
180 };
181
182 assert.deepEqual(await findReleaseWorkflowRun("owner/repo", "v0.9.6", "abc123", api), {
183 ...run,
184 release_job_started_at: "2026-08-12T07:30:00Z",
185 });
186 });
187
188 test("findReleaseWorkflowRun rejects runs without a successful release job", async () => {
189 const api = async (_repo, endpoint) => {
190 if (endpoint.includes("/workflows/release.yml/runs")) {
191 return {
192 workflow_runs: [
193 {
194 id: 123,
195 head_sha: "abc123",
196 head_branch: "v0.9.6",
197 event: "push",
198 conclusion: "failure",
199 updated_at: "2026-08-12T08:48:00Z",
200 },
201 ],
202 };
203 }
204 return { jobs: [{ name: "release", conclusion: "failure" }] };
205 };
206
207 await assert.rejects(
208 findReleaseWorkflowRun("owner/repo", "v0.9.6", "abc123", api),
209 /No successful asset-publishing job found/,
210 );
211 });
212
213 test("assertPackageVersionMatchesBinaryVersion allows packaging-only releases only with an explicit override", () => {
214 assert.doesNotThrow(() => assertPackageVersionMatchesBinaryVersion(pkg.version));
215 assert.throws(
216 () => assertPackageVersionMatchesBinaryVersion("0.0.0-packaging-test"),
217 /does not match codewhaleBinaryVersion/,
218 );
219
220 const previous = process.env.CODEWHALE_ALLOW_NPM_BINARY_MISMATCH;
221 process.env.CODEWHALE_ALLOW_NPM_BINARY_MISMATCH = "1";
222 try {
223 assert.doesNotThrow(() => assertPackageVersionMatchesBinaryVersion("0.0.0-packaging-test"));
224 } finally {
225 if (previous === undefined) {
226 delete process.env.CODEWHALE_ALLOW_NPM_BINARY_MISMATCH;
227 } else {
228 process.env.CODEWHALE_ALLOW_NPM_BINARY_MISMATCH = previous;
229 }
230 }
231 });
232
233 test("npm publication requires the checkout guard and canonical release-asset gate", () => {
234 assert.equal(
235 pkg.scripts.prepublishOnly,
236 "bash ../../scripts/release/require-release-tag-checkout.sh && " +
237 "bash ../../scripts/release/verify-release-assets.sh",
238 );
239 });
240
241 test("full local release fixture satisfies the public asset inventory", () => {
242 const repoRoot = path.resolve(__dirname, "..", "..", "..");
243 const fixtureRoot = fs.mkdtempSync(path.join(os.tmpdir(), "codewhale-assets-"));
244 const buildDir = path.join(fixtureRoot, "build");
245 const outputDir = path.join(fixtureRoot, "assets");
246 const executableSuffix = process.platform === "win32" ? ".exe" : "";
247
248 try {
249 fs.mkdirSync(buildDir, { recursive: true });
250 fs.writeFileSync(
251 path.join(buildDir, `codewhale${executableSuffix}`),
252 "fixture:codewhale\n",
253 );
254
255 execFileSync(
256 process.execPath,
257 [
258 path.join(repoRoot, "scripts", "release", "prepare-local-release-assets.js"),
259 outputDir,
260 buildDir,
261 ],
262 {
263 env: { ...process.env, DEEPSEEK_TUI_PREPARE_ALL_ASSETS: "1" },
264 stdio: "pipe",
265 },
266 );
267
268 for (const assetName of allReleaseAssetNames()) {
269 assert.equal(
270 fs.existsSync(path.join(outputDir, assetName)),
271 true,
272 `missing fixture asset ${assetName}`,
273 );
274 }
275
276 const { codewhale, codew } = detectBinaryNames();
277 assert.deepEqual(
278 fs.readFileSync(path.join(outputDir, codew)),
279 fs.readFileSync(path.join(outputDir, codewhale)),
280 "codew must contain the exact same runtime bytes as codewhale",
281 );
282 for (const legacyAsset of LEGACY_TUI_BRIDGE_ASSET_NAMES) {
283 const primaryAsset = legacyAsset.replace("codewhale-tui-", "codewhale-");
284 assert.deepEqual(
285 fs.readFileSync(path.join(outputDir, legacyAsset)),
286 fs.readFileSync(path.join(outputDir, primaryAsset)),
287 `${legacyAsset} must be a byte-identical compatibility copy`,
288 );
289 }
290
291 const canonicalChecksums = parseChecksumManifest(
292 fs.readFileSync(path.join(outputDir, CHECKSUM_MANIFEST), "utf8"),
293 );
294 assert.doesNotThrow(() =>
295 assertChecksumManifestIncludes(
296 canonicalChecksums,
297 checksummedReleaseAssetNames(),
298 "Canonical checksum manifest",
299 ),
300 );
301
302 const bundleChecksums = parseChecksumManifest(
303 fs.readFileSync(path.join(outputDir, BUNDLE_CHECKSUM_MANIFEST), "utf8"),
304 );
305 assert.doesNotThrow(() =>
306 assertChecksumManifestIncludes(
307 bundleChecksums,
308 BUNDLE_ASSET_NAMES,
309 "Bundle checksum manifest",
310 ),
311 );
312 } finally {
313 fs.rmSync(fixtureRoot, { recursive: true, force: true });
314 }
315 });
316
317 test("downloadJson confines credentials to the GitHub API origin across redirects", async (t) => {
318 const https = require("node:https");
319 const { PassThrough } = require("node:stream");
320 const { EventEmitter } = require("node:events");
321 const previous = process.env.GITHUB_TOKEN;
322 const previousAllowed = process.env.CODEWHALE_UPDATE_ALLOWED_HOSTS;
323 process.env.GITHUB_TOKEN = "test-release-token";
324 process.env.CODEWHALE_UPDATE_ALLOWED_HOSTS = "downloads.example.test";
325 t.after(() => {
326 if (previous === undefined) delete process.env.GITHUB_TOKEN;
327 else process.env.GITHUB_TOKEN = previous;
328 if (previousAllowed === undefined) delete process.env.CODEWHALE_UPDATE_ALLOWED_HOSTS;
329 else process.env.CODEWHALE_UPDATE_ALLOWED_HOSTS = previousAllowed;
330 });
331 const calls = [];
332 const replies = [
333 { status: 302, location: "/next" },
334 { status: 302, location: "https://downloads.example.test/metadata" },
335 { status: 200 },
336 { status: 302, location: "http://downloads.example.test/metadata" },
337 { status: 302, location: "ftp://downloads.example.test/metadata" },
338 { status: 200 },
339 ];
340 t.mock.method(https, "get", (url, options, callback) => {
341 calls.push({ url, headers: options.headers });
342 const reply = replies.shift();
343 assert.ok(reply, "unexpected metadata request");
344 const res = new PassThrough();
345 res.statusCode = reply.status;
346 res.headers = reply.location ? { location: reply.location } : {};
347 process.nextTick(() => { callback(res); res.end("{}"); });
348 return new EventEmitter();
349 });
350 t.mock.method(require("node:http"), "get", () => { throw new Error("unexpected HTTP request"); });
351 assert.deepEqual(await downloadJson("https://api.github.com/start"), {});
352 assert.equal(calls[0].headers.Authorization, "Bearer test-release-token");
353 assert.equal(calls[1].headers.Authorization, "Bearer test-release-token");
354 assert.equal(calls[2].headers.Authorization, undefined);
355 await assert.rejects(downloadJson("https://api.github.com/downgrade"), /requires HTTPS/);
356 await assert.rejects(downloadJson("https://api.github.com/other-scheme"), /requires HTTPS/);
357 assert.deepEqual(await downloadJson("https://api.github.com:444/metadata"), {});
358 assert.equal(calls.at(-1).headers.Authorization, undefined);
359 assert.equal(calls.length, 6);
360 });
361
362 function shrinkLimits(t, overrides) {
363 const previous = { ...limits };
364 Object.assign(limits, overrides);
365 t.after(() => Object.assign(limits, previous));
366 }
367
368 function listen(t, handler) {
369 const previousLoopback = transportOptions.allowLoopbackHttp;
370 transportOptions.allowLoopbackHttp = true;
371 t.after(() => {
372 transportOptions.allowLoopbackHttp = previousLoopback;
373 });
374 const http = require("node:http");
375 const server = http.createServer(handler);
376 t.after(() => {
377 server.closeAllConnections();
378 server.close();
379 });
380 return new Promise((resolve) =>
381 server.listen(0, "127.0.0.1", () => resolve(`http://127.0.0.1:${server.address().port}/x`)),
382 );
383 }
384
385 test("verifier requests give up on a server that never answers", async (t) => {
386 shrinkLimits(t, { idleMs: 150, totalMs: 5_000 });
387 const url = await listen(t, () => {});
388 await assert.rejects(requestStatus(url, "HEAD"), /timed out/);
389 await assert.rejects(downloadText(url), /timed out/);
390 });
391
392 test("verifier requests have a total deadline even while a body keeps trickling", async (t) => {
393 shrinkLimits(t, { idleMs: 5_000, totalMs: 300 });
394 const url = await listen(t, (req, res) => {
395 res.writeHead(200);
396 const timer = setInterval(() => res.write("x"), 50);
397 res.on("close", () => clearInterval(timer));
398 });
399 const started = Date.now();
400 await assert.rejects(downloadText(url), /exceeded/);
401 assert.ok(Date.now() - started < 3_000, "the deadline, not the server, ended the request");
402 });
403
404 test("verifier downloads refuse a body past the size cap and keep one within it", async (t) => {
405 shrinkLimits(t, { maxBodyBytes: 1024 });
406 const url = await listen(t, (req, res) => {
407 res.writeHead(200);
408 res.end("a".repeat(req.url.endsWith("big") ? 4096 : 512));
409 });
410 await assert.rejects(downloadText(`${url}big`), /exceeds 1024 bytes/);
411 assert.equal((await downloadText(url)).length, 512);
412 });
413
414 test("downloadJson destroys a metadata request that stalls", async (t) => {
415 const https = require("node:https");
416 const { EventEmitter } = require("node:events");
417 shrinkLimits(t, { idleMs: 40, totalMs: 5_000 });
418 let seen;
419 t.mock.method(https, "get", (url, options) => {
420 seen = options;
421 const req = new EventEmitter();
422 req.destroy = () => process.nextTick(() => req.emit("close"));
423 setTimeout(() => req.emit("timeout"), options.timeout);
424 return req;
425 });
426 await assert.rejects(downloadJson("https://api.github.com/stalled"), /timed out/);
427 assert.equal(seen.timeout, 40);
428 });
429
430 test("verifier requests refuse plain HTTP and disallowed redirect targets without connecting", async (t) => {
431 const http = require("node:http");
432 const https = require("node:https");
433 const { PassThrough } = require("node:stream");
434 const { EventEmitter } = require("node:events");
435 let hits = 0;
436 const server = http.createServer((_req, res) => {
437 hits += 1;
438 res.writeHead(200);
439 res.end("unexpected");
440 });
441 await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
442 t.after(() => {
443 server.closeAllConnections();
444 server.close();
445 });
446 const localHttpUrl = `http://127.0.0.1:${server.address().port}/asset`;
447
448 await assert.rejects(requestStatus(localHttpUrl, "HEAD"), /requires HTTPS/);
449 await assert.rejects(downloadText(localHttpUrl), /requires HTTPS/);
450 await assert.rejects(downloadJson(localHttpUrl), /requires HTTPS/);
451 await assert.rejects(downloadText("http://user:secret@github.com/asset"), (error) => {
452 assert.match(error.message, /requires HTTPS/);
453 assert.doesNotMatch(error.message, /secret/);
454 return true;
455 });
456
457 let nextRedirect = localHttpUrl;
458 const mockHandler = (_url, _options, callback) => {
459 const req = new EventEmitter();
460 req.destroy = () => {};
461 req.end = () => {};
462 const res = new PassThrough();
463 res.statusCode = 302;
464 res.headers = { location: nextRedirect };
465 process.nextTick(() => {
466 callback(res);
467 res.end();
468 });
469 return req;
470 };
471 t.mock.method(https, "get", mockHandler);
472 t.mock.method(https, "request", mockHandler);
473
474 await assert.rejects(requestStatus("https://github.com/start", "HEAD"), /requires HTTPS/);
475 await assert.rejects(downloadText("https://github.com/start"), /requires HTTPS/);
476 await assert.rejects(downloadJson("https://api.github.com/start"), /requires HTTPS/);
477
478 nextRedirect = "https://unlisted.example.test/asset";
479 await assert.rejects(requestStatus("https://github.com/start", "HEAD"), /not an allowed release host/);
480 await assert.rejects(downloadText("https://github.com/start"), /not an allowed release host/);
481 await assert.rejects(downloadJson("https://api.github.com/start"), /not an allowed release host/);
482 assert.equal(hits, 0);
483 });
484
484 lines JAVASCRIPT