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