From 791545512cf4a3cc5f3ca2d27bd744397eac8f08 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Tue, 10 Nov 2026 16:25:38 -0500 Subject: [PATCH 1/4] fix: tolerate npm publish-time scanning delays --- docs/RELEASING.md | 16 +++++++ scripts/release-registry.mjs | 15 +++++-- tests/release/registry.test.mjs | 77 +++++++++++++++++++++++++++++++-- 3 files changed, 102 insertions(+), 6 deletions(-) diff --git a/docs/RELEASING.md b/docs/RELEASING.md index 6550cc0..ccb46d0 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -214,6 +214,22 @@ Never overwrite a version, rebuild from another checkout, move a tag, or treat an npm error as proof of absence. A conflict requires maintainer investigation and a separately reviewed release decision. +npm accepts uploads before its +[publish-time malware scan](https://github.blog/changelog/2026-07-28-npm-publish-time-malware-scanning-and-dual-use-metadata/) +makes the version available. This normally takes about five minutes and can take +15 minutes or longer. After one accepted upload, publication polls only exact +version reads, at most 41 times, with up to 30 seconds between checks and a +20-minute deadline (in-flight metadata and tarball verification can take up to +60 additional seconds). +Unknown registry states and conflicting bytes still fail immediately. The +30-minute job timeout remains the outer bound. An unavailable version at the +deadline is not proof that the upload failed: check npm scanning or review status +and preserve the original artifact rather than uploading again blindly. Once +the exact version is visible, run read-only `preflight` with the original +artifact ID, independent manifest digest, tag, and commit. If it matches, rerun +only the failed jobs in the original Publish run; publication skips the matching +existing version and the separate registry/provenance verification must pass. + ## Registry verification and availability After publication, the separate unprivileged job runs strict verification. The diff --git a/scripts/release-registry.mjs b/scripts/release-registry.mjs index 1a0df12..92dd7a2 100644 --- a/scripts/release-registry.mjs +++ b/scripts/release-registry.mjs @@ -597,18 +597,27 @@ async function registryConsumer(verified, options, seams) { } async function confirmRegistry(record, seams) { + // npm accepts uploads before its publish-time malware scan makes them public. + // Bound both elapsed time and physical lookups; never publish again while waiting. + const now = seams.now ?? Date.now; + const deadline = now() + 20 * 60_000; const sleep = seams.sleep ?? ((milliseconds) => new Promise((resolve_) => setTimeout(resolve_, milliseconds))); - for (let attempt = 0; attempt < 6; attempt += 1) { + for (let attempt = 0; attempt < 41; attempt += 1) { + if (attempt > 0 && now() >= deadline) break; if ( (await registryRecord(record, seams.fetch ?? globalThis.fetch)) !== null ) return; - if (attempt < 5) await sleep(2 ** attempt * 1000); + const remaining = deadline - now(); + if (attempt === 40 || remaining <= 0) break; + await sleep(Math.min(30_000, remaining)); } - fail("published registry version was not visible after bounded verification"); + fail( + "npm accepted the upload but the exact registry version is not yet visible; preserve the artifact and check npm scanning or review status before retrying", + ); } async function verifyPublishedBytes(verified, seams) { diff --git a/tests/release/registry.test.mjs b/tests/release/registry.test.mjs index 84d58c7..7661213 100644 --- a/tests/release/registry.test.mjs +++ b/tests/release/registry.test.mjs @@ -139,11 +139,14 @@ function trustedEnvironment() { function publisher(fixture, state) { const calls = []; const sleeps = []; + let elapsed = 0; const seams = { + now: () => elapsed, env: trustedEnvironment(), fetch: state.fetch, sleep: async (milliseconds) => { sleeps.push(milliseconds); + elapsed += milliseconds; }, run: async (command, arguments_, context) => { calls.push({ command, arguments_, context }); @@ -526,9 +529,35 @@ test("a matching version published concurrently is reverified and skipped immedi ); }); +test("publication waits through npm scanning and verifies bytes without publishing twice", async (t) => { + const prepared = await fixture(t); + const state = fakeRegistry(prepared, []); + const publishing = publisher(prepared, state); + state.metadata = () => + publishing.calls.some(({ arguments_ }) => arguments_[1] === "publish") && + publishing.seams.now() < 16 * 60_000 + ? jsonResponse({ error: "Not found" }, 404) + : undefined; + const result = await publishPreparedRelease( + prepared.options, + publishing.seams, + ); + assert.deepEqual( + result.published, + prepared.artifacts.map(({ name }) => name), + ); + assert.equal(publishing.sleeps.length, 32); + assert.equal( + publishing.calls.filter(({ arguments_ }) => arguments_[1] === "publish") + .length, + 1, + ); + assert.ok(state.requests.some(({ kind }) => kind === "tarball")); +}); + test("post-publication absence has a bounded retry budget and unknown states fail immediately", async (t) => { - for (const problem of ["404", "network"]) { - await t.test(problem, async (t) => { + for (const problem of ["404", "network", 401, 429, 503]) { + await t.test(String(problem), async (t) => { const prepared = await fixture(t); const state = fakeRegistry(prepared, []); let published = false; @@ -543,6 +572,7 @@ test("post-publication absence has a bounded retry budget and unknown states fai if (!published) return undefined; if (problem === "network") throw new Error("synthetic unknown network state"); + if (typeof problem === "number") return jsonResponse({}, problem); return jsonResponse({ error: "Not found" }, 404); }; await assert.rejects( @@ -555,12 +585,53 @@ test("post-publication absence has a bounded retry budget and unknown states fai ); assert.deepEqual( publishing.sleeps, - problem === "404" ? [1000, 2000, 4000, 8000, 16000] : [], + problem === "404" ? Array(40).fill(30_000) : [], ); }); } }); +test("publication polling is bounded even when the clock does not advance", async (t) => { + const prepared = await fixture(t); + const state = fakeRegistry(prepared, []); + const publishing = publisher(prepared, state); + publishing.seams.now = () => 0; + state.metadata = () => jsonResponse({}, 404); + await assert.rejects( + publishPreparedRelease(prepared.options, publishing.seams), + /check npm scanning or review status/, + ); + // Two pre-upload lookups, then at most 41 post-upload lookups. + assert.equal(state.requests.length, 43); + assert.equal(publishing.sleeps.length, 40); +}); + +test("publication polling counts lookup time toward its deadline", async (t) => { + const prepared = await fixture(t); + const state = fakeRegistry(prepared, []); + const publishing = publisher(prepared, state); + const originalNow = publishing.seams.now; + let lookupTime = 0; + let lookups = 0; + publishing.seams.now = () => originalNow() + lookupTime; + state.metadata = () => { + if ( + publishing.calls.some(({ arguments_ }) => arguments_[1] === "publish") + ) { + lookupTime += 30_000; + lookups += 1; + } + return jsonResponse({}, 404); + }; + await assert.rejects( + publishPreparedRelease(prepared.options, publishing.seams), + /check npm scanning or review status/, + ); + assert.equal(publishing.seams.now(), 20 * 60_000); + assert.equal(lookups, 20); + assert.equal(publishing.sleeps.length, 20); +}); + test("privileged publication requires the exact hosted release workflow identity and rejects inherited npm authority", () => { assert.doesNotThrow(() => assertTrustedPublishingEnvironment(trustedEnvironment(), identity), From c198236d4104f93f4bc85b510c45e9e26a343636 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Wed, 11 Nov 2026 14:57:44 -0500 Subject: [PATCH 2/4] Check final registry visibility using a monotonic polling clock --- docs/RELEASING.md | 19 ++++-- scripts/release-registry.mjs | 6 +- tests/release/registry.test.mjs | 114 +++++++++++++++++++++++++++++++- 3 files changed, 129 insertions(+), 10 deletions(-) diff --git a/docs/RELEASING.md b/docs/RELEASING.md index ccb46d0..22a1f7c 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -217,16 +217,23 @@ and a separately reviewed release decision. npm accepts uploads before its [publish-time malware scan](https://github.blog/changelog/2026-07-28-npm-publish-time-malware-scanning-and-dual-use-metadata/) makes the version available. This normally takes about five minutes and can take -15 minutes or longer. After one accepted upload, publication polls only exact +15 minutes or longer; these are typical timings, not service guarantees. +After one accepted upload, publication polls only exact version reads, at most 41 times, with up to 30 seconds between checks and a -20-minute deadline (in-flight metadata and tarball verification can take up to -60 additional seconds). +20-minute monotonic elapsed-time budget. The final scheduled sleep is followed +by one bounded lookup, whose metadata and tarball verification can take up to +60 additional seconds. Unknown registry states and conflicting bytes still fail immediately. The -30-minute job timeout remains the outer bound. An unavailable version at the +30-minute job timeout remains the outer bound and can interrupt publication or +byte verification; it does not guarantee enough time for every worst-case step. +An unavailable version at the deadline is not proof that the upload failed: check npm scanning or review status and preserve the original artifact rather than uploading again blindly. Once -the exact version is visible, run read-only `preflight` with the original -artifact ID, independent manifest digest, tag, and commit. If it matches, rerun +the exact version is visible, download the original immutable workflow artifact +by its artifact ID into a fresh prepared directory. Run the read-only `preflight` +command above with `--prepared-dir` pointing to those downloaded files and the +original independent manifest digest, tag, and commit. The artifact ID selects +the workflow download; it is not a `preflight` argument. If it matches, rerun only the failed jobs in the original Publish run; publication skips the matching existing version and the separate registry/provenance verification must pass. diff --git a/scripts/release-registry.mjs b/scripts/release-registry.mjs index 92dd7a2..4e690f6 100644 --- a/scripts/release-registry.mjs +++ b/scripts/release-registry.mjs @@ -11,6 +11,7 @@ import { } from "node:fs/promises"; import { tmpdir } from "node:os"; import { basename, dirname, isAbsolute, join, resolve } from "node:path"; +import { performance } from "node:perf_hooks"; import { RELEASE_PACKAGES, RELEASE_REPOSITORY } from "./release-contract.mjs"; import { validatePreparedManifest, @@ -599,14 +600,15 @@ async function registryConsumer(verified, options, seams) { async function confirmRegistry(record, seams) { // npm accepts uploads before its publish-time malware scan makes them public. // Bound both elapsed time and physical lookups; never publish again while waiting. - const now = seams.now ?? Date.now; + const now = seams.now ?? (() => performance.now()); const deadline = now() + 20 * 60_000; const sleep = seams.sleep ?? ((milliseconds) => new Promise((resolve_) => setTimeout(resolve_, milliseconds))); for (let attempt = 0; attempt < 41; attempt += 1) { - if (attempt > 0 && now() >= deadline) break; + // A sleep scheduled within the budget still gets its final bounded lookup, + // including when the timer resumes at or just after the deadline. if ( (await registryRecord(record, seams.fetch ?? globalThis.fetch)) !== null ) diff --git a/tests/release/registry.test.mjs b/tests/release/registry.test.mjs index 7661213..af15fec 100644 --- a/tests/release/registry.test.mjs +++ b/tests/release/registry.test.mjs @@ -1,6 +1,7 @@ import assert from "node:assert/strict"; import { mkdir, readFile, symlink, writeFile } from "node:fs/promises"; import { basename, dirname, join } from "node:path"; +import { performance } from "node:perf_hooks"; import test from "node:test"; import { assertTrustedPublishingEnvironment, @@ -606,6 +607,115 @@ test("publication polling is bounded even when the clock does not advance", asyn assert.equal(publishing.sleeps.length, 40); }); +test("publication checks visibility after the final scheduled sleep", async (t) => { + for (const [name, lookupLatency, timerOvershoot] of [ + ["instant lookups", 0, 0], + ["lookup latency", 30_000, 0], + ["final timer overshoot", 0, 1], + ]) { + await t.test(name, async (t) => { + const prepared = await fixture(t); + const state = fakeRegistry(prepared, []); + const publishing = publisher(prepared, state); + const originalNow = publishing.seams.now; + const originalSleep = publishing.seams.sleep; + let lookupTime = 0; + let overshoot = 0; + const postUploadLookups = []; + publishing.seams.now = () => originalNow() + lookupTime + overshoot; + publishing.seams.sleep = async (milliseconds) => { + await originalSleep(milliseconds); + if (publishing.seams.now() === 20 * 60_000) overshoot += timerOvershoot; + }; + state.metadata = () => { + if ( + !publishing.calls.some( + ({ arguments_ }) => arguments_[1] === "publish", + ) + ) + return undefined; + postUploadLookups.push(publishing.seams.now()); + lookupTime += lookupLatency; + return publishing.seams.now() < 19 * 60_000 + 45_000 + ? jsonResponse({ error: "Not found" }, 404) + : undefined; + }; + const result = await publishPreparedRelease( + prepared.options, + publishing.seams, + ); + const polls = lookupLatency === 0 ? 41 : 21; + assert.deepEqual( + postUploadLookups.slice(0, -1), + Array.from( + { length: polls }, + (_, index) => + index * (30_000 + lookupLatency) + + (index === polls - 1 ? timerOvershoot : 0), + ), + ); + // The extra lookup is the unchanged independent post-poll byte check. + assert.equal(postUploadLookups.length, polls + 1); + assert.equal(publishing.sleeps.length, polls - 1); + assert.equal( + publishing.calls.filter(({ arguments_ }) => arguments_[1] === "publish") + .length, + 1, + ); + assert.equal(result.verified, true); + assert.deepEqual(result.skipped, []); + assert.deepEqual( + result.published, + prepared.artifacts.map(({ name }) => name), + ); + }); + } +}); + +test("production polling deadline ignores forward and backward wall-clock adjustments", async (t) => { + for (const direction of [1, -1]) { + await t.test(direction === 1 ? "forward" : "backward", async (t) => { + const prepared = await fixture(t); + const state = fakeRegistry(prepared, []); + const publishing = publisher(prepared, state); + const originalSleep = publishing.seams.sleep; + let elapsed = 0; + let wall = Date.now(); + let lookups = 0; + delete publishing.seams.now; + t.mock.method(performance, "now", () => elapsed); + t.mock.method(Date, "now", () => wall); + publishing.seams.sleep = async (milliseconds) => { + await originalSleep(milliseconds); + elapsed += milliseconds; + wall += milliseconds + direction * 60 * 60_000; + }; + state.metadata = () => { + if ( + publishing.calls.some(({ arguments_ }) => arguments_[1] === "publish") + ) { + elapsed += 30_000; + wall += 30_000; + lookups += 1; + } + return jsonResponse({}, 404); + }; + await assert.rejects( + publishPreparedRelease(prepared.options, publishing.seams), + /check npm scanning or review status/, + ); + assert.equal(elapsed, 20 * 60_000 + 30_000); + assert.equal(lookups, 21); + assert.equal(publishing.sleeps.length, 20); + assert.equal( + publishing.calls.filter(({ arguments_ }) => arguments_[1] === "publish") + .length, + 1, + ); + }); + } +}); + test("publication polling counts lookup time toward its deadline", async (t) => { const prepared = await fixture(t); const state = fakeRegistry(prepared, []); @@ -627,8 +737,8 @@ test("publication polling counts lookup time toward its deadline", async (t) => publishPreparedRelease(prepared.options, publishing.seams), /check npm scanning or review status/, ); - assert.equal(publishing.seams.now(), 20 * 60_000); - assert.equal(lookups, 20); + assert.equal(publishing.seams.now(), 20 * 60_000 + 30_000); + assert.equal(lookups, 21); assert.equal(publishing.sleeps.length, 20); }); From c96de2eade2638dd80db35d62d17e52e6f82dda1 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Wed, 11 Nov 2026 15:32:01 -0500 Subject: [PATCH 3/4] Retry bounded transient reads after one accepted npm upload --- docs/RELEASING.md | 12 +- scripts/release-registry.mjs | 119 ++++++++++++--- tests/release/registry.test.mjs | 258 +++++++++++++++++++++++++++++++- 3 files changed, 362 insertions(+), 27 deletions(-) diff --git a/docs/RELEASING.md b/docs/RELEASING.md index 22a1f7c..106ab18 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -219,11 +219,19 @@ npm accepts uploads before its makes the version available. This normally takes about five minutes and can take 15 minutes or longer; these are typical timings, not service guarantees. After one accepted upload, publication polls only exact -version reads, at most 41 times, with up to 30 seconds between checks and a +version reads, at most 41 times, normally 30 seconds apart, with a 20-minute monotonic elapsed-time budget. The final scheduled sleep is followed by one bounded lookup, whose metadata and tarball verification can take up to 60 additional seconds. -Unknown registry states and conflicting bytes still fail immediately. The +Only this post-upload confirmation can wait through transport failures or HTTP +408, 429, 500, 502, 503 and 504. These remain unconfirmed states, never evidence +of absence or permission for another upload. A valid `Retry-After` can lengthen +the normal delay within the remaining budget; if it cannot fit, confirmation +stops without polling early or extending the deadline. Authentication failures, +malformed metadata and conflicting metadata or bytes still fail immediately. +Ordinary preflight, recovery, the last pre-write lookup and the separate final +byte verification remain strict. Success requires matching metadata and verified +tarball bytes; exhausting the confirmation budget is not success. The 30-minute job timeout remains the outer bound and can interrupt publication or byte verification; it does not guarantee enough time for every worst-case step. An unavailable version at the diff --git a/scripts/release-registry.mjs b/scripts/release-registry.mjs index 4e690f6..206d288 100644 --- a/scripts/release-registry.mjs +++ b/scripts/release-registry.mjs @@ -23,6 +23,14 @@ export const RELEASE_WORKFLOW = ".github/workflows/publish.yml"; const registry = "https://registry.npmjs.org/"; const provenanceType = "https://slsa.dev/provenance/v1"; const temporaryPrefix = "agent-access-registry-"; +const confirmationBudgetMs = 20 * 60_000; + +class RegistryConfirmationRetry extends Error { + constructor(retryAfterMs = 0) { + super("accepted upload registry confirmation is temporarily unavailable"); + this.retryAfterMs = retryAfterMs; + } +} function fail(message) { // Never surface native command output, registry response bodies, or credentials. @@ -56,7 +64,7 @@ function tarballUrl(record) { return `${registry}${record.name}/-/${record.name.split("/")[1]}-${record.version}.tgz`; } -async function responseBytes(response, maximum) { +async function responseBytes(response, maximum, confirmation = false) { const length = response.headers?.get("content-length"); if ( length !== null && @@ -70,17 +78,35 @@ async function responseBytes(response, maximum) { let size = 0; if (response.body === null || response.body === undefined) return Buffer.alloc(0); - for await (const chunk of response.body) { - size += chunk.length; - if (size > maximum) { - fail("registry response exceeded its release verification limit"); + const reader = response.body.getReader(); + try { + for (;;) { + let item; + try { + item = await reader.read(); + } catch (error) { + if (confirmation) throw new RegistryConfirmationRetry(); + throw error; + } + if (item.done) break; + size += item.value.length; + if (size > maximum) { + fail("registry response exceeded its release verification limit"); + } + chunks.push(Buffer.from(item.value)); } - chunks.push(Buffer.from(chunk)); + } finally { + try { + await reader.cancel(); + } catch { + // Preserve the verification/transport result if stream cleanup fails. + } + reader.releaseLock(); } return Buffer.concat(chunks, size); } -async function request(url, fetch) { +async function request(url, fetch, confirmation = false) { try { return await fetch(url, { redirect: "error", @@ -88,17 +114,49 @@ async function request(url, fetch) { headers: { accept: "application/json" }, }); } catch { + if (confirmation) throw new RegistryConfirmationRetry(); fail("registry lookup failed; package availability is unknown"); } } -async function registryRecord(record, fetch) { +async function retryTransientConfirmation(response, confirmation) { + if ( + !confirmation || + ![408, 429, 500, 502, 503, 504].includes(response.status) + ) + return; + const value = response.headers?.get("retry-after"); + let delay = 0; + if (value !== null && value !== undefined) { + if (/^\d+$/u.test(value)) { + delay = Number(value) * 1000; + } else { + const serverTime = Date.parse(response.headers?.get("date") ?? ""); + delay = + Date.parse(value) - + (Number.isFinite(serverTime) ? serverTime : Date.now()); + } + } + const retryAfterMs = + delay > 0 ? Math.min(delay, confirmationBudgetMs + 1) : 0; + try { + await response.body?.cancel(); + } catch { + // Cleanup cannot turn a known transient response into a successful check. + } + throw new RegistryConfirmationRetry(retryAfterMs); +} + +async function registryRecord(record, fetch, confirmation = false) { const response = await request( `${registry}${encodeURIComponent(record.name)}/${record.version}`, fetch, + confirmation, ); - // Authentication errors, throttling, server errors, redirects, and malformed - // responses are unknown states. Only this exact response establishes absence. + // Only the accepted-upload confirmation caller may wait through transient + // unknown states. Ordinary preflight and pre-write checks remain strict. + await retryTransientConfirmation(response, confirmation); + // Only this exact response establishes absence, regardless of caller mode. if (response.status === 404) { await response.body?.cancel(); return null; @@ -110,9 +168,12 @@ async function registryRecord(record, fetch) { let metadata; try { metadata = JSON.parse( - (await responseBytes(response, 2 * 1024 * 1024)).toString("utf8"), + (await responseBytes(response, 2 * 1024 * 1024, confirmation)).toString( + "utf8", + ), ); - } catch { + } catch (error) { + if (error instanceof RegistryConfirmationRetry) throw error; fail("registry package metadata verification failed"); } if ( @@ -131,15 +192,17 @@ async function registryRecord(record, fetch) { ) { fail("registry version conflicts with the prepared release"); } - const tarball = await request(metadata.dist.tarball, fetch); + const tarball = await request(metadata.dist.tarball, fetch, confirmation); + await retryTransientConfirmation(tarball, confirmation); if (tarball.status !== 200) { await tarball.body?.cancel(); fail("registry tarball verification failed"); } let bytes; try { - bytes = await responseBytes(tarball, record.size); - } catch { + bytes = await responseBytes(tarball, record.size, confirmation); + } catch (error) { + if (error instanceof RegistryConfirmationRetry) throw error; fail("registry tarball verification failed"); } if ( @@ -601,7 +664,7 @@ async function confirmRegistry(record, seams) { // npm accepts uploads before its publish-time malware scan makes them public. // Bound both elapsed time and physical lookups; never publish again while waiting. const now = seams.now ?? (() => performance.now()); - const deadline = now() + 20 * 60_000; + const deadline = now() + confirmationBudgetMs; const sleep = seams.sleep ?? ((milliseconds) => @@ -609,16 +672,28 @@ async function confirmRegistry(record, seams) { for (let attempt = 0; attempt < 41; attempt += 1) { // A sleep scheduled within the budget still gets its final bounded lookup, // including when the timer resumes at or just after the deadline. - if ( - (await registryRecord(record, seams.fetch ?? globalThis.fetch)) !== null - ) - return; + let retryAfterMs = 0; + try { + if ( + (await registryRecord( + record, + seams.fetch ?? globalThis.fetch, + true, + )) !== null + ) + return; + } catch (error) { + if (!(error instanceof RegistryConfirmationRetry)) throw error; + retryAfterMs = error.retryAfterMs; + } const remaining = deadline - now(); if (attempt === 40 || remaining <= 0) break; - await sleep(Math.min(30_000, remaining)); + // Never extend the deadline or retry before a server's requested delay. + if (retryAfterMs > remaining) break; + await sleep(Math.min(Math.max(30_000, retryAfterMs), remaining)); } fail( - "npm accepted the upload but the exact registry version is not yet visible; preserve the artifact and check npm scanning or review status before retrying", + "npm accepted the upload but the exact registry version could not be confirmed; preserve the artifact and check npm scanning or review status before retrying", ); } diff --git a/tests/release/registry.test.mjs b/tests/release/registry.test.mjs index af15fec..f262d54 100644 --- a/tests/release/registry.test.mjs +++ b/tests/release/registry.test.mjs @@ -556,8 +556,8 @@ test("publication waits through npm scanning and verifies bytes without publishi assert.ok(state.requests.some(({ kind }) => kind === "tarball")); }); -test("post-publication absence has a bounded retry budget and unknown states fail immediately", async (t) => { - for (const problem of ["404", "network", 401, 429, 503]) { +test("post-publication absence and transient failures share a bounded budget while authentication fails immediately", async (t) => { + for (const problem of ["404", "network", 401, 403, 429, 503]) { await t.test(String(problem), async (t) => { const prepared = await fixture(t); const state = fakeRegistry(prepared, []); @@ -578,6 +578,9 @@ test("post-publication absence has a bounded retry budget and unknown states fai }; await assert.rejects( publishPreparedRelease(prepared.options, publishing.seams), + problem === 401 || problem === 403 + ? /package availability is unknown/ + : /could not be confirmed/, ); assert.equal( publishing.calls.filter(({ arguments_ }) => arguments_[1] === "publish") @@ -586,7 +589,256 @@ test("post-publication absence has a bounded retry budget and unknown states fai ); assert.deepEqual( publishing.sleeps, - problem === "404" ? Array(40).fill(30_000) : [], + problem === 401 || problem === 403 ? [] : Array(40).fill(30_000), + ); + assert.equal( + state.requests.filter(({ kind }) => kind === "metadata").length, + problem === 401 || problem === 403 ? 3 : 43, + ); + }); + } +}); + +test("accepted-upload confirmation survives a late transient registry failure without another upload", async (t) => { + for (const problem of ["network", 429, 503]) { + await t.test(String(problem), async (t) => { + const prepared = await fixture(t); + const state = fakeRegistry(prepared, []); + const publishing = publisher(prepared, state); + let transient = false; + state.metadata = () => { + if ( + !publishing.calls.some( + ({ arguments_ }) => arguments_[1] === "publish", + ) + ) + return undefined; + if (publishing.seams.now() < 19 * 60_000) return jsonResponse({}, 404); + if (!transient) { + transient = true; + if (problem === "network") + throw new Error("synthetic transport failure"); + return jsonResponse({}, problem); + } + return undefined; + }; + const result = await publishPreparedRelease( + prepared.options, + publishing.seams, + ); + assert.equal(transient, true); + assert.equal(result.verified, true); + assert.equal(publishing.seams.now(), 19 * 60_000 + 30_000); + assert.equal(publishing.sleeps.length, 39); + assert.equal( + publishing.calls.filter(({ arguments_ }) => arguments_[1] === "publish") + .length, + 1, + ); + assert.equal( + state.requests.filter(({ kind }) => kind === "tarball").length, + 2, + ); + }); + } +}); + +test("accepted-upload confirmation retries only designated transient responses and interrupted bodies", async (t) => { + const prepared = await fixture(t); + const state = fakeRegistry(prepared, []); + const publishing = publisher(prepared, state); + const failures = [408, 500, 502, 504, "metadata body"]; + state.metadata = () => { + if (!publishing.calls.some(({ arguments_ }) => arguments_[1] === "publish")) + return undefined; + const problem = failures.shift(); + if (problem === undefined) return undefined; + if (problem === "metadata body") + return new Response( + new ReadableStream({ + start(controller) { + controller.error(new Error("synthetic transport failure")); + }, + }), + ); + return jsonResponse({}, problem); + }; + const result = await publishPreparedRelease( + prepared.options, + publishing.seams, + ); + assert.equal(result.verified, true); + assert.deepEqual(failures, []); + assert.deepEqual(publishing.sleeps, Array(5).fill(30_000)); + assert.equal( + publishing.calls.filter(({ arguments_ }) => arguments_[1] === "publish") + .length, + 1, + ); +}); + +test("accepted-upload tarball confirmation retries transport and transient status without accepting unverified bytes", async (t) => { + const prepared = await fixture(t); + const state = fakeRegistry(prepared, []); + const publishing = publisher(prepared, state); + const failures = ["network", 429, 503, "body"]; + state.blob = () => { + const problem = failures.shift(); + if (problem === undefined) return undefined; + if (problem === "network") throw new Error("synthetic transport failure"); + if (problem === "body") + return new Response( + new ReadableStream({ + start(controller) { + controller.error(new Error("synthetic transport failure")); + }, + }), + ); + return new Response(null, { status: problem }); + }; + const result = await publishPreparedRelease( + prepared.options, + publishing.seams, + ); + assert.equal(result.verified, true); + assert.deepEqual(failures, []); + assert.deepEqual(publishing.sleeps, Array(4).fill(30_000)); + assert.equal( + publishing.calls.filter(({ arguments_ }) => arguments_[1] === "publish") + .length, + 1, + ); + assert.equal( + state.requests.filter(({ kind }) => kind === "tarball").length, + 6, + ); +}); + +test("accepted-upload confirmation honors bounded Retry-After without extending its deadline", async (t) => { + for (const [name, headers, expectedDelay] of [ + ["seconds", { "retry-after": "90" }, 90_000], + [ + "HTTP date", + { + date: "Wed, 11 Nov 2026 00:00:00 GMT", + "retry-after": "Wed, 11 Nov 2026 00:01:30 GMT", + }, + 90_000, + ], + ["shorter than cadence", { "retry-after": "5" }, 30_000], + ["invalid", { "retry-after": "invalid" }, 30_000], + ["beyond budget", { "retry-after": "1201" }, null], + ["overflow", { "retry-after": "9".repeat(400) }, null], + ]) { + await t.test(name, async (t) => { + const prepared = await fixture(t); + const state = fakeRegistry(prepared, []); + const publishing = publisher(prepared, state); + let transient = false; + state.metadata = () => { + if ( + !publishing.calls.some( + ({ arguments_ }) => arguments_[1] === "publish", + ) || + transient + ) + return undefined; + transient = true; + return new Response(null, { status: 429, headers }); + }; + if (expectedDelay === null) { + await assert.rejects( + publishPreparedRelease(prepared.options, publishing.seams), + /could not be confirmed/, + ); + assert.deepEqual(publishing.sleeps, []); + } else { + const result = await publishPreparedRelease( + prepared.options, + publishing.seams, + ); + assert.equal(result.verified, true); + assert.deepEqual(publishing.sleeps, [expectedDelay]); + assert.equal(publishing.seams.now(), expectedDelay); + } + assert.equal( + publishing.calls.filter(({ arguments_ }) => arguments_[1] === "publish") + .length, + 1, + ); + }); + } +}); + +test("accepted-upload confirmation still rejects authentication, malformed metadata and byte conflicts immediately", async (t) => { + for (const problem of [ + 401, + 403, + "malformed", + "dependency", + "tarball bytes", + ]) { + await t.test(String(problem), async (t) => { + const prepared = await fixture(t); + const state = fakeRegistry(prepared, []); + const publishing = publisher(prepared, state); + state.metadata = (record) => { + if ( + !publishing.calls.some( + ({ arguments_ }) => arguments_[1] === "publish", + ) + ) + return undefined; + if (typeof problem === "number") return jsonResponse({}, problem); + if (problem === "malformed") return new Response("not JSON"); + if (problem === "dependency") { + const value = metadata(record); + value.dependencies.extra = "1.0.0"; + return jsonResponse(value); + } + return undefined; + }; + if (problem === "tarball bytes") + state.blob = (record) => { + const bytes = Buffer.from(prepared.blobs.get(record.name)); + bytes[0] ^= 1; + return new Response(bytes); + }; + await assert.rejects( + publishPreparedRelease(prepared.options, publishing.seams), + ); + assert.deepEqual(publishing.sleeps, []); + assert.equal( + publishing.calls.filter(({ arguments_ }) => arguments_[1] === "publish") + .length, + 1, + ); + }); + } +}); + +test("the last pre-write lookup remains strict before any upload", async (t) => { + for (const problem of [401, 429, 503, "network"]) { + await t.test(String(problem), async (t) => { + const prepared = await fixture(t); + const state = fakeRegistry(prepared, []); + const publishing = publisher(prepared, state); + let lookups = 0; + state.metadata = () => { + if (++lookups === 1) return undefined; + if (problem === "network") + throw new Error("synthetic transport failure"); + return jsonResponse({}, problem); + }; + await assert.rejects( + publishPreparedRelease(prepared.options, publishing.seams), + ); + assert.equal(lookups, 2); + assert.deepEqual(publishing.sleeps, []); + assert.equal( + publishing.calls.filter(({ arguments_ }) => arguments_[1] === "publish") + .length, + 0, ); }); } From a79480e1bb96df2da8e0b0059e0fa21f5068c13a Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Wed, 11 Nov 2026 16:55:18 -0500 Subject: [PATCH 4/4] Keep registry response cleanup best effort --- scripts/release-registry.mjs | 29 +++--- tests/release/registry.test.mjs | 157 ++++++++++++++++++++++++++++++++ 2 files changed, 172 insertions(+), 14 deletions(-) diff --git a/scripts/release-registry.mjs b/scripts/release-registry.mjs index 206d288..7517b48 100644 --- a/scripts/release-registry.mjs +++ b/scripts/release-registry.mjs @@ -64,6 +64,15 @@ function tarballUrl(record) { return `${registry}${record.name}/-/${record.name.split("/")[1]}-${record.version}.tgz`; } +function discardBody(body) { + try { + // Cleanup cannot replace a known status or hold the confirmation deadline. + void Promise.resolve(body?.cancel()).catch(() => {}); + } catch { + // Preserve the verification result if cancellation throws synchronously. + } +} + async function responseBytes(response, maximum, confirmation = false) { const length = response.headers?.get("content-length"); if ( @@ -71,7 +80,7 @@ async function responseBytes(response, maximum, confirmation = false) { length !== undefined && (!/^\d+$/u.test(length) || Number(length) > maximum) ) { - await response.body?.cancel(); + discardBody(response.body); fail("registry response exceeded its release verification limit"); } const chunks = []; @@ -96,11 +105,7 @@ async function responseBytes(response, maximum, confirmation = false) { chunks.push(Buffer.from(item.value)); } } finally { - try { - await reader.cancel(); - } catch { - // Preserve the verification/transport result if stream cleanup fails. - } + discardBody(reader); reader.releaseLock(); } return Buffer.concat(chunks, size); @@ -139,11 +144,7 @@ async function retryTransientConfirmation(response, confirmation) { } const retryAfterMs = delay > 0 ? Math.min(delay, confirmationBudgetMs + 1) : 0; - try { - await response.body?.cancel(); - } catch { - // Cleanup cannot turn a known transient response into a successful check. - } + discardBody(response.body); throw new RegistryConfirmationRetry(retryAfterMs); } @@ -158,11 +159,11 @@ async function registryRecord(record, fetch, confirmation = false) { await retryTransientConfirmation(response, confirmation); // Only this exact response establishes absence, regardless of caller mode. if (response.status === 404) { - await response.body?.cancel(); + discardBody(response.body); return null; } if (response.status !== 200) { - await response.body?.cancel(); + discardBody(response.body); fail("registry lookup failed; package availability is unknown"); } let metadata; @@ -195,7 +196,7 @@ async function registryRecord(record, fetch, confirmation = false) { const tarball = await request(metadata.dist.tarball, fetch, confirmation); await retryTransientConfirmation(tarball, confirmation); if (tarball.status !== 200) { - await tarball.body?.cancel(); + discardBody(tarball.body); fail("registry tarball verification failed"); } let bytes; diff --git a/tests/release/registry.test.mjs b/tests/release/registry.test.mjs index f262d54..eb2b780 100644 --- a/tests/release/registry.test.mjs +++ b/tests/release/registry.test.mjs @@ -47,6 +47,20 @@ function jsonResponse(value, status = 200) { }); } +function unsettledCleanupResponse(status, cleanup, onCancel) { + return new Response( + new ReadableStream({ + cancel() { + onCancel(); + return cleanup === "rejecting" + ? Promise.reject(new Error("synthetic body cleanup failure")) + : new Promise(() => {}); + }, + }), + { status }, + ); +} + async function fixture(t) { const prepared = await preparedFixture(t); const written = await writePreparedManifest(prepared); @@ -599,6 +613,149 @@ test("post-publication absence and transient failures share a bounded budget whi } }); +test("accepted-upload 404 cleanup cannot override a later exact registry result", async (t) => { + for (const cleanup of ["rejecting", "never settling"]) { + await t.test(cleanup, { timeout: 5_000 }, async (t) => { + const prepared = await fixture(t); + const state = fakeRegistry(prepared, []); + const publishing = publisher(prepared, state); + let lookups = 0; + let cancellations = 0; + state.metadata = () => { + if ( + !publishing.calls.some( + ({ arguments_ }) => arguments_[1] === "publish", + ) + ) + return undefined; + if (++lookups !== 1) return undefined; + return unsettledCleanupResponse(404, cleanup, () => { + cancellations += 1; + }); + }; + const result = await publishPreparedRelease( + prepared.options, + publishing.seams, + ); + assert.equal(cancellations, 1); + assert.equal(result.verified, true); + assert.deepEqual( + result.published, + prepared.artifacts.map(({ name }) => name), + ); + assert.deepEqual(result.skipped, []); + assert.deepEqual(publishing.sleeps, [30_000]); + assert.equal(publishing.seams.now(), 30_000); + assert.equal(lookups, 3); + assert.equal( + publishing.calls.filter(({ arguments_ }) => arguments_[1] === "publish") + .length, + 1, + ); + assert.equal( + state.requests.filter(({ kind }) => kind === "tarball").length, + 2, + ); + }); + } +}); + +test("unsettled 404 cleanup cannot extend the accepted-upload polling budget", async (t) => { + for (const cleanup of ["rejecting", "never settling"]) { + await t.test(cleanup, { timeout: 5_000 }, async (t) => { + const prepared = await fixture(t); + const state = fakeRegistry(prepared, []); + const publishing = publisher(prepared, state); + let cancellations = 0; + state.metadata = () => { + if ( + !publishing.calls.some( + ({ arguments_ }) => arguments_[1] === "publish", + ) + ) + return undefined; + return unsettledCleanupResponse(404, cleanup, () => { + cancellations += 1; + }); + }; + await assert.rejects( + publishPreparedRelease(prepared.options, publishing.seams), + /could not be confirmed/, + ); + assert.equal(cancellations, 41); + assert.deepEqual(publishing.sleeps, Array(40).fill(30_000)); + assert.equal(publishing.seams.now(), 20 * 60_000); + assert.equal( + state.requests.filter(({ kind }) => kind === "metadata").length, + 43, + ); + assert.equal( + publishing.calls.filter(({ arguments_ }) => arguments_[1] === "publish") + .length, + 1, + ); + assert.equal( + state.requests.filter(({ kind }) => kind === "tarball").length, + 0, + ); + }); + } +}); + +test("404 cleanup cannot bypass later authentication or exact-byte refusal", async (t) => { + for (const cleanup of ["rejecting", "never settling"]) { + for (const problem of [401, 403, "byte conflict"]) { + await t.test(`${cleanup}/${problem}`, { timeout: 5_000 }, async (t) => { + const prepared = await fixture(t); + const state = fakeRegistry(prepared, []); + const publishing = publisher(prepared, state); + let lookups = 0; + let cancellations = 0; + const response = (status) => + unsettledCleanupResponse(status, cleanup, () => { + cancellations += 1; + }); + state.metadata = () => { + if ( + !publishing.calls.some( + ({ arguments_ }) => arguments_[1] === "publish", + ) + ) + return undefined; + if (++lookups === 1) return response(404); + return typeof problem === "number" ? response(problem) : undefined; + }; + if (problem === "byte conflict") + state.blob = (record) => { + const bytes = Buffer.from(prepared.blobs.get(record.name)); + bytes[0] ^= 1; + return new Response(bytes); + }; + await assert.rejects( + publishPreparedRelease(prepared.options, publishing.seams), + typeof problem === "number" + ? /package availability is unknown/ + : /tarball conflicts with the prepared release/, + ); + assert.equal(cancellations, typeof problem === "number" ? 2 : 1); + assert.equal(lookups, 2); + assert.deepEqual(publishing.sleeps, [30_000]); + assert.equal(publishing.seams.now(), 30_000); + assert.equal( + publishing.calls.filter( + ({ arguments_ }) => arguments_[1] === "publish", + ).length, + 1, + ); + assert.equal( + state.requests.filter(({ kind }) => kind === "metadata").length, + 4, + ); + }); + } + } +}); + test("accepted-upload confirmation survives a late transient registry failure without another upload", async (t) => { for (const problem of ["network", 429, 503]) { await t.test(String(problem), async (t) => {