From f5bbd90c3b4329aba491f2b25a5f65b0b7c82b34 Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 21 Oct 2026 17:24:33 +0000 Subject: [PATCH 1/4] fix(router): enforce the redirects size cap before and while reading The router streamed a version's `_redirects.json` in full and only then compared its length to the 1 MiB cap, so an oversized object was pulled through the function on every miss under that version, and the rejection was cached for just a minute. The router now rejects an object whose reported size is over the cap without reading its body, reads with a byte-limited reader that cancels past the cap when no size is reported, and keeps the oversized verdict for as long as a valid file. The publisher refuses a `_redirects.json` over the cap, and bounds its read of a recorded `_objects.json` the same way. Assisted-by: AI --- apps/docs/scripts/publish/upload.mjs | 32 +++++++-- apps/docs/scripts/publish/upload.test.mjs | 56 +++++++++++++++ apps/router/lib/archive.ts | 25 +++++-- apps/router/lib/version-redirects.test.ts | 69 +++++++++++++++++++ apps/router/lib/version-rules.ts | 15 ++-- .../docs-manifest/src/bounded-read.test.ts | 32 +++++++++ packages/docs-manifest/src/bounded-read.ts | 29 ++++++++ packages/docs-manifest/src/index.ts | 1 + 8 files changed, 244 insertions(+), 15 deletions(-) create mode 100644 packages/docs-manifest/src/bounded-read.test.ts create mode 100644 packages/docs-manifest/src/bounded-read.ts diff --git a/apps/docs/scripts/publish/upload.mjs b/apps/docs/scripts/publish/upload.mjs index 2f058453..732395f0 100644 --- a/apps/docs/scripts/publish/upload.mjs +++ b/apps/docs/scripts/publish/upload.mjs @@ -1,9 +1,16 @@ #!/usr/bin/env node // Upload a laid-out version to the private archive under its immutable prefix. import { createHash } from "node:crypto"; -import { readFile, readdir } from "node:fs/promises"; +import { readFile, readdir, stat } from "node:fs/promises"; import path from "node:path"; -import { DEV_KEY, lineKey, tagKey } from "@coder/docs-manifest"; +import { + DEV_KEY, + MAX_VERSION_REDIRECTS_BYTES, + VERSION_REDIRECTS_KEY, + lineKey, + readTextWithLimit, + tagKey, +} from "@coder/docs-manifest"; import { copy, get, put } from "@vercel/blob"; import { contentTypeFor } from "../archive-layout-helpers.mjs"; import { logBlobRetry, withBlobRetry } from "./blob-retry.mjs"; @@ -110,6 +117,9 @@ export function liveArchivePrefix({ items, plan }) { // `_publish.json` hashes are the untrusted build's claims. const OBJECTS_KEY = "_objects.json"; +// Far above a real record (one short entry per file); refuses a runaway one. +const MAX_RECORDED_OBJECTS_BYTES = 16 * 1024 * 1024; + async function readRecordedObjects({ prefix, token, blobGet, onReuseSkipped }) { try { const result = await withBlobRetry( @@ -117,9 +127,13 @@ async function readRecordedObjects({ prefix, token, blobGet, onReuseSkipped }) { { key: `${prefix}/${OBJECTS_KEY}` }, ); if (!result?.stream) throw new Error("not found"); - const recorded = JSON.parse( - Buffer.from(await new Response(result.stream).arrayBuffer()).toString("utf8"), - ); + if (result.blob?.size > MAX_RECORDED_OBJECTS_BYTES) { + void result.stream.cancel().catch(() => {}); + throw new Error(`larger than ${MAX_RECORDED_OBJECTS_BYTES} bytes`); + } + const text = await readTextWithLimit(result.stream, MAX_RECORDED_OBJECTS_BYTES); + if (text === null) throw new Error(`larger than ${MAX_RECORDED_OBJECTS_BYTES} bytes`); + const recorded = JSON.parse(text); if (recorded?.version !== 1 || typeof recorded.files !== "object" || recorded.files === null) { throw new Error("unrecognised format"); } @@ -180,6 +194,14 @@ export async function uploadDir({ .toSorted(); if (files.length === 0) throw new Error(`upload: ${dir} has no files to upload (besides _publish.json)`); + if (files.includes(VERSION_REDIRECTS_KEY)) { + const { size } = await stat(path.join(dir, VERSION_REDIRECTS_KEY)); + if (size > MAX_VERSION_REDIRECTS_BYTES) { + throw new Error( + `upload: ${VERSION_REDIRECTS_KEY} is larger than ${MAX_VERSION_REDIRECTS_BYTES} bytes (${size})`, + ); + } + } const reusable = reuseFrom === undefined || reuseFrom === prefix ? new Map() diff --git a/apps/docs/scripts/publish/upload.test.mjs b/apps/docs/scripts/publish/upload.test.mjs index 63b216ac..7a3168e9 100644 --- a/apps/docs/scripts/publish/upload.test.mjs +++ b/apps/docs/scripts/publish/upload.test.mjs @@ -4,6 +4,7 @@ import { mkdir, mkdtemp, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { test } from "node:test"; +import { MAX_VERSION_REDIRECTS_BYTES } from "@coder/docs-manifest"; import { BlobServiceRateLimited } from "@vercel/blob"; import { DEFAULT_UPLOAD_CONCURRENCY, @@ -592,3 +593,58 @@ test("liveArchivePrefix finds the prefix the manifest serves this version from", assert.equal(liveArchivePrefix({ items, plan: { kind: "line", id: "2.36" } }), undefined); assert.equal(liveArchivePrefix({ items, plan: { kind: "line", id: "2.35" } }), undefined); }); + +test("a _redirects.json over the cap fails the upload before anything is put", async () => { + const dir = await archiveFixture([entry("index.html"), entry("_redirects.json")]); + await writeFile(path.join(dir, "_redirects.json"), "x".repeat(MAX_VERSION_REDIRECTS_BYTES + 1)); + const store = recordingStore(); + await assert.rejects( + () => uploadDir({ dir, prefix: `versions/2.36/${sha}`, token: "t", concurrency: 1, ...store }), + /_redirects\.json is larger than/, + ); + assert.equal(store.puts.length, 0); +}); + +test("a _redirects.json at the cap is uploaded", async () => { + const dir = await archiveFixture([ + entry("index.html"), + entry("_next/static/chunks/a.js"), + entry("_redirects.json"), + ]); + await writeFile(path.join(dir, "_redirects.json"), "x".repeat(MAX_VERSION_REDIRECTS_BYTES)); + const store = recordingStore(); + await uploadDir({ dir, prefix: `versions/2.36/${sha}`, token: "t", concurrency: 1, ...store }); + assert.ok(store.puts.some((p) => p.key.endsWith("/_redirects.json"))); +}); + +test("a recorded _objects.json that reports a size over the limit is not read, and reuse is skipped", async () => { + const dir = await archiveFixture([entry("index.html"), entry("_next/static/chunks/a.js")]); + const store = recordingStore(); + let streamed = false; + store.blobGet = async () => ({ + blob: { size: 10 * 1024 * 1024 * 1024 }, + stream: new ReadableStream( + { + pull(controller) { + streamed = true; + controller.close(); + }, + }, + { highWaterMark: 0 }, + ), + }); + const skipped = []; + const result = await uploadDir({ + dir, + prefix: `versions/2.36/${sha}`, + token: "t", + concurrency: 1, + reuseFrom: previous, + onReuseSkipped: (info) => skipped.push(info.reason), + ...store, + }); + assert.equal(streamed, false); + assert.equal(result.copied, 0); + assert.equal(skipped.length, 1); + assert.match(skipped[0], /larger than/); +}); diff --git a/apps/router/lib/archive.ts b/apps/router/lib/archive.ts index 6befd891..f47c7fb2 100644 --- a/apps/router/lib/archive.ts +++ b/apps/router/lib/archive.ts @@ -1,10 +1,12 @@ import { analyticsEnabled, docsContentSecurityPolicy } from "@coder/docs-config"; import { + MAX_VERSION_REDIRECTS_BYTES, type ObjectPath, type RouteTarget, VERSION_REDIRECTS_KEY, hasUnsafePathSegment, objectPath, + readTextWithLimit, } from "@coder/docs-manifest"; import { get as blobGet } from "@vercel/blob"; @@ -233,21 +235,34 @@ export async function serveNotFoundPage( return new Response(result.stream, { status: 404, headers }); } +/** What the store holds at a version's `_redirects.json`. */ +export type VersionRedirectsRead = + | { kind: "absent" } + | { kind: "too-large" } + | { kind: "text"; text: string }; + /** * The version's own redirects object, `_redirects.json` beside `_publish.json` - * under the deployment's archive prefix, as text; null when the prefix has none - * (published before the object existed). A store failure throws. + * under the deployment's archive prefix. An object over the size cap is + * reported as `too-large` without its body being read: the store's reported + * size is checked first, and the read itself stops at the cap in case the + * size is missing or wrong. A store failure throws. */ export async function readVersionRedirectsText( deployment: string, request: Request, deps: ArchiveDeps, -): Promise { +): Promise { const prefix = prefixFor({ deployment, path: "/", versionId: "" }); const key = prefix ? `${prefix}/${VERSION_REDIRECTS_KEY}` : VERSION_REDIRECTS_KEY; const result = await readObject(key, { access: "private" }, request, deps); - if (!result?.stream) return null; - return new Response(result.stream).text(); + if (!result?.stream) return { kind: "absent" }; + if (result.blob.size > MAX_VERSION_REDIRECTS_BYTES) { + void result.stream.cancel().catch(() => {}); + return { kind: "too-large" }; + } + const text = await readTextWithLimit(result.stream, MAX_VERSION_REDIRECTS_BYTES); + return text === null ? { kind: "too-large" } : { kind: "text", text }; } /** diff --git a/apps/router/lib/version-redirects.test.ts b/apps/router/lib/version-redirects.test.ts index c9a8bb59..61a3589e 100644 --- a/apps/router/lib/version-redirects.test.ts +++ b/apps/router/lib/version-redirects.test.ts @@ -3,6 +3,7 @@ import { mock, test } from "node:test"; import { CANONICAL_LAYOUT, DEV_KEY, + MAX_VERSION_REDIRECTS_BYTES, type ManifestReader, type VersionRedirect, lineKey, @@ -460,3 +461,71 @@ test("a destination fragment is kept after the query, and only the route is prob assert.equal(missing.response.status, 404); assert.equal(missing.response.headers.has("location"), false); }); + +const TOO_LARGE = MAX_VERSION_REDIRECTS_BYTES + 1; + +function oversizedGetter(options: { reportSize: boolean }, pulled: { bytes: number }): Getter { + const working = storeGetter(store); + return async (pathname) => { + if (!pathname.endsWith(`${prefix("2.38")}/_redirects.json`)) return working(pathname); + const chunk = new Uint8Array(64 * 1024); + return { + statusCode: 200, + stream: new ReadableStream( + { + pull(controller) { + if (pulled.bytes >= 16 * TOO_LARGE) return controller.close(); + pulled.bytes += chunk.length; + controller.enqueue(chunk); + }, + }, + { highWaterMark: 0 }, + ), + blob: { + contentType: "application/json", + etag: '"e"', + ...(options.reportSize ? { size: 16 * TOO_LARGE } : {}), + }, + }; + }; +} + +test("a rules object whose reported size is over the cap is never streamed", async () => { + const pulled = { bytes: 0 }; + const { response } = await serve({ + get: oversizedGetter({ reportSize: true }, pulled), + }).fetch("/v2.38/templates"); + assert.equal(response.status, 404); + assert.equal(response.headers.has("location"), false); + assert.equal(pulled.bytes, 0); +}); + +test("a rules object with no reported size is cut off once it passes the cap", async () => { + const pulled = { bytes: 0 }; + const { response } = await serve({ + get: oversizedGetter({ reportSize: false }, pulled), + }).fetch("/v2.38/templates"); + assert.equal(response.status, 404); + assert.equal(pulled.bytes < 2 * TOO_LARGE, true, `streamed ${pulled.bytes} bytes`); +}); + +test("an oversized rules object is remembered as long as a valid one, not re-fetched every minute", async () => { + const objects = { ...store }; + const calls: string[] = []; + const oversized = oversizedGetter({ reportSize: true }, { bytes: 0 }); + const get: Getter = async (pathname) => { + calls.push(pathname); + return oversized(pathname); + }; + let clock = 0; + const { fetch } = serve({ get, objects, now: () => clock }); + const reads = () => calls.filter((key) => key === `${prefix("2.38")}/_redirects.json`).length; + + await fetch("/v2.38/nothing"); + clock += ABSENT_TTL_MS + 1; + await fetch("/v2.38/nothing"); + assert.equal(reads(), 1); + clock += PRESENT_TTL_MS; + await fetch("/v2.38/nothing"); + assert.equal(reads(), 2); +}); diff --git a/apps/router/lib/version-rules.ts b/apps/router/lib/version-rules.ts index 33b67cdd..847cea2b 100644 --- a/apps/router/lib/version-rules.ts +++ b/apps/router/lib/version-rules.ts @@ -11,8 +11,9 @@ type Loaded = { rules: VersionRedirect[] | null; expires: number }; /** * Loads a version's own redirects, once per archive prefix. A present object - * is kept for `PRESENT_TTL_MS`; an absent or unreadable one (null) is asked - * about again after `ABSENT_TTL_MS`. A store failure is not cached and + * is kept for `PRESENT_TTL_MS`, and so is an oversized one (null), so a bad + * object is not fetched again every minute; an absent or unparseable one (null) + * is asked about again after `ABSENT_TTL_MS`. A store failure is not cached and * rejects, so the caller can answer with a response the edge does not keep. */ export function createVersionRules(deps: { @@ -24,14 +25,18 @@ export function createVersionRules(deps: { async function load(deployment: string): Promise { // Not the request's own signal: the read is shared by every request that waits on it. - const text = await readVersionRedirectsText( + const read = await readVersionRedirectsText( deployment, new Request(new URL("/", deployment)), deps.archive(), ); - if (text === null) return { rules: null, expires: now() + ABSENT_TTL_MS }; + if (read.kind === "absent") return { rules: null, expires: now() + ABSENT_TTL_MS }; + if (read.kind === "too-large") { + console.error("docs-router: version redirects object is over the size cap"); + return { rules: null, expires: now() + PRESENT_TTL_MS }; + } try { - return { rules: parseVersionRedirectsArtifact(text), expires: now() + PRESENT_TTL_MS }; + return { rules: parseVersionRedirectsArtifact(read.text), expires: now() + PRESENT_TTL_MS }; } catch (error) { console.error("docs-router: version redirects object is invalid", error); return { rules: null, expires: now() + ABSENT_TTL_MS }; diff --git a/packages/docs-manifest/src/bounded-read.test.ts b/packages/docs-manifest/src/bounded-read.test.ts new file mode 100644 index 00000000..bac2e844 --- /dev/null +++ b/packages/docs-manifest/src/bounded-read.test.ts @@ -0,0 +1,32 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { readTextWithLimit } from "./bounded-read.js"; + +function chunked(chunks: Uint8Array[], pulled: { count: number }, cancelled: { value: boolean }) { + let next = 0; + return new ReadableStream({ + pull(controller) { + pulled.count += 1; + if (next < chunks.length) controller.enqueue(chunks[next++]); + else controller.close(); + }, + cancel() { + cancelled.value = true; + }, + }); +} + +test("a body within the limit is decoded in full, including a character split across chunks", async () => { + const bytes = new TextEncoder().encode("héllo"); + const stream = chunked([bytes.slice(0, 2), bytes.slice(2)], { count: 0 }, { value: false }); + assert.equal(await readTextWithLimit(stream, bytes.length), "héllo"); +}); + +test("a body past the limit stops the read, cancels the stream and yields null", async () => { + const pulled = { count: 0 }; + const cancelled = { value: false }; + const chunks = Array.from({ length: 1000 }, () => new Uint8Array(1024)); + assert.equal(await readTextWithLimit(chunked(chunks, pulled, cancelled), 4096), null); + assert.equal(cancelled.value, true); + assert.equal(pulled.count < 20, true, `pulled ${pulled.count} chunks`); +}); diff --git a/packages/docs-manifest/src/bounded-read.ts b/packages/docs-manifest/src/bounded-read.ts new file mode 100644 index 00000000..8f580693 --- /dev/null +++ b/packages/docs-manifest/src/bounded-read.ts @@ -0,0 +1,29 @@ +/** + * Decode a byte stream as UTF-8 text, or return null once it has produced + * more than `maxBytes` (the stream is cancelled at that point, so an oversized + * body is never pulled in full). + */ +export async function readTextWithLimit( + stream: ReadableStream, + maxBytes: number, +): Promise { + const reader = stream.getReader(); + const decoder = new TextDecoder(); + let total = 0; + let text = ""; + try { + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + total += value.byteLength; + if (total > maxBytes) { + await reader.cancel().catch(() => {}); + return null; + } + text += decoder.decode(value, { stream: true }); + } + } finally { + reader.releaseLock(); + } + return text + decoder.decode(); +} diff --git a/packages/docs-manifest/src/index.ts b/packages/docs-manifest/src/index.ts index eabf0f04..8f33880a 100644 --- a/packages/docs-manifest/src/index.ts +++ b/packages/docs-manifest/src/index.ts @@ -1,3 +1,4 @@ +export * from "./bounded-read.js"; export * from "./items.js"; export * from "./path-safety.js"; export * from "./reader.js"; From 7ceb6b19e395e7f5d1ab67e7bb9e47739220314f Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 21 Oct 2026 13:36:32 -0700 Subject: [PATCH 2/4] fix(router): share the bounded blob read and name the version over the cap The router and the uploader each repeated the same sequence for a store object: check the reported size, cancel, read with a byte limit. Moving it into readBlobTextWithLimit in @coder/docs-manifest keeps the two callers from drifting apart. The exported helper also accepted a NaN limit, which silently removed the cap, so a limit that is not a non-negative safe integer now throws. Its overflow path no longer awaits the source's cancel, so a source whose cancel never settles can't hang the read; this matches the other cancel sites. When a version's rules object is over the cap, every rule for that version disappears for the long TTL, and the log line was the only signal without saying which version. It now names the archive prefix and the size the store reported. The router tests use the sizes @vercel/blob actually reports (0 and NaN, never undefined) and pin an object reported at exactly the cap. Assisted-by: AI --- apps/docs/scripts/publish/upload.mjs | 11 ++- apps/router/lib/archive.ts | 16 ++-- apps/router/lib/version-redirects.test.ts | 80 ++++++++++++++----- apps/router/lib/version-rules.ts | 4 +- .../docs-manifest/src/bounded-read.test.ts | 64 ++++++++++++++- packages/docs-manifest/src/bounded-read.ts | 26 +++++- 6 files changed, 162 insertions(+), 39 deletions(-) diff --git a/apps/docs/scripts/publish/upload.mjs b/apps/docs/scripts/publish/upload.mjs index 732395f0..9013a1ef 100644 --- a/apps/docs/scripts/publish/upload.mjs +++ b/apps/docs/scripts/publish/upload.mjs @@ -8,7 +8,7 @@ import { MAX_VERSION_REDIRECTS_BYTES, VERSION_REDIRECTS_KEY, lineKey, - readTextWithLimit, + readBlobTextWithLimit, tagKey, } from "@coder/docs-manifest"; import { copy, get, put } from "@vercel/blob"; @@ -127,11 +127,10 @@ async function readRecordedObjects({ prefix, token, blobGet, onReuseSkipped }) { { key: `${prefix}/${OBJECTS_KEY}` }, ); if (!result?.stream) throw new Error("not found"); - if (result.blob?.size > MAX_RECORDED_OBJECTS_BYTES) { - void result.stream.cancel().catch(() => {}); - throw new Error(`larger than ${MAX_RECORDED_OBJECTS_BYTES} bytes`); - } - const text = await readTextWithLimit(result.stream, MAX_RECORDED_OBJECTS_BYTES); + const text = await readBlobTextWithLimit( + { stream: result.stream, size: result.blob?.size }, + MAX_RECORDED_OBJECTS_BYTES, + ); if (text === null) throw new Error(`larger than ${MAX_RECORDED_OBJECTS_BYTES} bytes`); const recorded = JSON.parse(text); if (recorded?.version !== 1 || typeof recorded.files !== "object" || recorded.files === null) { diff --git a/apps/router/lib/archive.ts b/apps/router/lib/archive.ts index f47c7fb2..bafca192 100644 --- a/apps/router/lib/archive.ts +++ b/apps/router/lib/archive.ts @@ -6,7 +6,7 @@ import { VERSION_REDIRECTS_KEY, hasUnsafePathSegment, objectPath, - readTextWithLimit, + readBlobTextWithLimit, } from "@coder/docs-manifest"; import { get as blobGet } from "@vercel/blob"; @@ -238,7 +238,7 @@ export async function serveNotFoundPage( /** What the store holds at a version's `_redirects.json`. */ export type VersionRedirectsRead = | { kind: "absent" } - | { kind: "too-large" } + | { kind: "too-large"; reportedSize: number } | { kind: "text"; text: string }; /** @@ -257,12 +257,12 @@ export async function readVersionRedirectsText( const key = prefix ? `${prefix}/${VERSION_REDIRECTS_KEY}` : VERSION_REDIRECTS_KEY; const result = await readObject(key, { access: "private" }, request, deps); if (!result?.stream) return { kind: "absent" }; - if (result.blob.size > MAX_VERSION_REDIRECTS_BYTES) { - void result.stream.cancel().catch(() => {}); - return { kind: "too-large" }; - } - const text = await readTextWithLimit(result.stream, MAX_VERSION_REDIRECTS_BYTES); - return text === null ? { kind: "too-large" } : { kind: "text", text }; + const { stream, blob } = result; + const text = await readBlobTextWithLimit( + { stream, size: blob.size }, + MAX_VERSION_REDIRECTS_BYTES, + ); + return text === null ? { kind: "too-large", reportedSize: blob.size } : { kind: "text", text }; } /** diff --git a/apps/router/lib/version-redirects.test.ts b/apps/router/lib/version-redirects.test.ts index 61a3589e..51880e9f 100644 --- a/apps/router/lib/version-redirects.test.ts +++ b/apps/router/lib/version-redirects.test.ts @@ -464,7 +464,8 @@ test("a destination fragment is kept after the query, and only the route is prob const TOO_LARGE = MAX_VERSION_REDIRECTS_BYTES + 1; -function oversizedGetter(options: { reportSize: boolean }, pulled: { bytes: number }): Getter { +// The size @vercel/blob reports: Content-Length, 0 when it is missing, NaN when it is not a number. +function oversizedGetter(size: number, pulled: { bytes: number }): Getter { const working = storeGetter(store); return async (pathname) => { if (!pathname.endsWith(`${prefix("2.38")}/_redirects.json`)) return working(pathname); @@ -481,38 +482,71 @@ function oversizedGetter(options: { reportSize: boolean }, pulled: { bytes: numb }, { highWaterMark: 0 }, ), - blob: { - contentType: "application/json", - etag: '"e"', - ...(options.reportSize ? { size: 16 * TOO_LARGE } : {}), - }, + blob: { contentType: "application/json", etag: '"e"', size }, }; }; } +async function quietly(run: () => Promise): Promise { + const error = mock.method(console, "error", () => {}); + try { + return await run(); + } finally { + error.mock.restore(); + } +} + test("a rules object whose reported size is over the cap is never streamed", async () => { const pulled = { bytes: 0 }; - const { response } = await serve({ - get: oversizedGetter({ reportSize: true }, pulled), - }).fetch("/v2.38/templates"); + const { response } = await quietly(() => + serve({ get: oversizedGetter(16 * TOO_LARGE, pulled) }).fetch("/v2.38/templates"), + ); assert.equal(response.status, 404); assert.equal(response.headers.has("location"), false); assert.equal(pulled.bytes, 0); }); -test("a rules object with no reported size is cut off once it passes the cap", async () => { - const pulled = { bytes: 0 }; +test("a rules object reported as 0 or NaN bytes is cut off once it passes the cap", async () => { + for (const size of [0, Number.NaN]) { + const pulled = { bytes: 0 }; + const { response } = await quietly(() => + serve({ get: oversizedGetter(size, pulled) }).fetch("/v2.38/templates"), + ); + assert.equal(response.status, 404, String(size)); + assert.equal( + pulled.bytes < 2 * TOO_LARGE, + true, + `size ${size}: streamed ${pulled.bytes} bytes`, + ); + } +}); + +test("a rules object reported at exactly the cap is read and applied", async () => { + const body = artifact(...rules238).trimEnd(); + const padded = body + " ".repeat(MAX_VERSION_REDIRECTS_BYTES - body.length); const { response } = await serve({ - get: oversizedGetter({ reportSize: false }, pulled), + objects: { ...store, [`${prefix("2.38")}/_redirects.json`]: padded }, }).fetch("/v2.38/templates"); - assert.equal(response.status, 404); - assert.equal(pulled.bytes < 2 * TOO_LARGE, true, `streamed ${pulled.bytes} bytes`); + assert.equal(response.status, 308); + assert.equal(location(response), "/beta-docs/v2.38/admin/templates"); +}); + +test("an oversized rules object is logged with its archive prefix and reported size", async () => { + const error = mock.method(console, "error", () => {}); + try { + await serve({ get: oversizedGetter(16 * TOO_LARGE, { bytes: 0 }) }).fetch("/v2.38/templates"); + const logged = error.mock.calls.map((call) => call.arguments.join(" ")).join("\n"); + assert.match(logged, new RegExp(`over the size cap.*/${prefix("2.38")}`)); + assert.match(logged, new RegExp(`${16 * TOO_LARGE}`)); + } finally { + error.mock.restore(); + } }); test("an oversized rules object is remembered as long as a valid one, not re-fetched every minute", async () => { const objects = { ...store }; const calls: string[] = []; - const oversized = oversizedGetter({ reportSize: true }, { bytes: 0 }); + const oversized = oversizedGetter(16 * TOO_LARGE, { bytes: 0 }); const get: Getter = async (pathname) => { calls.push(pathname); return oversized(pathname); @@ -521,11 +555,13 @@ test("an oversized rules object is remembered as long as a valid one, not re-fet const { fetch } = serve({ get, objects, now: () => clock }); const reads = () => calls.filter((key) => key === `${prefix("2.38")}/_redirects.json`).length; - await fetch("/v2.38/nothing"); - clock += ABSENT_TTL_MS + 1; - await fetch("/v2.38/nothing"); - assert.equal(reads(), 1); - clock += PRESENT_TTL_MS; - await fetch("/v2.38/nothing"); - assert.equal(reads(), 2); + await quietly(async () => { + await fetch("/v2.38/nothing"); + clock += ABSENT_TTL_MS + 1; + await fetch("/v2.38/nothing"); + assert.equal(reads(), 1); + clock += PRESENT_TTL_MS; + await fetch("/v2.38/nothing"); + assert.equal(reads(), 2); + }); }); diff --git a/apps/router/lib/version-rules.ts b/apps/router/lib/version-rules.ts index 847cea2b..888c10d9 100644 --- a/apps/router/lib/version-rules.ts +++ b/apps/router/lib/version-rules.ts @@ -32,7 +32,9 @@ export function createVersionRules(deps: { ); if (read.kind === "absent") return { rules: null, expires: now() + ABSENT_TTL_MS }; if (read.kind === "too-large") { - console.error("docs-router: version redirects object is over the size cap"); + console.error( + `docs-router: version redirects object is over the size cap at ${new URL(deployment).pathname} (reported size ${read.reportedSize})`, + ); return { rules: null, expires: now() + PRESENT_TTL_MS }; } try { diff --git a/packages/docs-manifest/src/bounded-read.test.ts b/packages/docs-manifest/src/bounded-read.test.ts index bac2e844..ddf6d07a 100644 --- a/packages/docs-manifest/src/bounded-read.test.ts +++ b/packages/docs-manifest/src/bounded-read.test.ts @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import { test } from "node:test"; -import { readTextWithLimit } from "./bounded-read.js"; +import { readBlobTextWithLimit, readTextWithLimit } from "./bounded-read.js"; function chunked(chunks: Uint8Array[], pulled: { count: number }, cancelled: { value: boolean }) { let next = 0; @@ -30,3 +30,65 @@ test("a body past the limit stops the read, cancels the stream and yields null", assert.equal(cancelled.value, true); assert.equal(pulled.count < 20, true, `pulled ${pulled.count} chunks`); }); + +test("the stream is unlocked after an overflow, and a rejecting cancel is swallowed", async () => { + const stream = new ReadableStream({ + pull(controller) { + controller.enqueue(new Uint8Array(1024)); + }, + cancel() { + return Promise.reject(new Error("cancel failed")); + }, + }); + assert.equal(await readTextWithLimit(stream, 100), null); + assert.equal(stream.locked, false); +}); + +test("an overflow returns without waiting for a cancel that never settles", async () => { + const stream = new ReadableStream({ + pull(controller) { + controller.enqueue(new Uint8Array(1024)); + }, + cancel() { + return new Promise(() => {}); + }, + }); + const timeout = new Promise((resolve) => setTimeout(() => resolve("timed out"), 500)); + assert.equal(await Promise.race([readTextWithLimit(stream, 100), timeout]), null); +}); + +test("a limit that is not a non-negative safe integer is refused", async () => { + for (const limit of [Number.NaN, -1, 1.5, Number.POSITIVE_INFINITY]) { + const stream = new Blob(["x".repeat(50 * 1024)]).stream(); + await assert.rejects(() => readTextWithLimit(stream, limit), RangeError, String(limit)); + await assert.rejects( + () => readBlobTextWithLimit({ stream, size: 1 }, limit), + RangeError, + String(limit), + ); + } +}); + +test("a blob whose reported size is over the limit is cancelled without being pulled", async () => { + const pulled = { count: 0 }; + const cancelled = { value: false }; + const stream = chunked([new Uint8Array(10)], pulled, cancelled); + assert.equal(await readBlobTextWithLimit({ stream, size: 4097 }, 4096), null); + assert.equal(cancelled.value, true); + assert.equal(pulled.count <= 1, true, `pulled ${pulled.count} chunks`); +}); + +test("a blob reported at exactly the limit is read", async () => { + const stream = new Blob(["x".repeat(4096)]).stream(); + assert.equal(await readBlobTextWithLimit({ stream, size: 4096 }, 4096), "x".repeat(4096)); +}); + +test("a blob whose reported size is 0, NaN or missing is still cut off at the limit", async () => { + for (const size of [0, Number.NaN, undefined]) { + const pulled = { count: 0 }; + const chunks = Array.from({ length: 1000 }, () => new Uint8Array(1024)); + const stream = chunked(chunks, pulled, { value: false }); + assert.equal(await readBlobTextWithLimit({ stream, size }, 4096), null, String(size)); + assert.equal(pulled.count < 20, true, `pulled ${pulled.count} chunks`); + } +}); diff --git a/packages/docs-manifest/src/bounded-read.ts b/packages/docs-manifest/src/bounded-read.ts index 8f580693..fb12f684 100644 --- a/packages/docs-manifest/src/bounded-read.ts +++ b/packages/docs-manifest/src/bounded-read.ts @@ -1,3 +1,9 @@ +function assertByteLimit(maxBytes: number): void { + if (!Number.isSafeInteger(maxBytes) || maxBytes < 0) { + throw new RangeError(`maxBytes must be a non-negative safe integer, not ${maxBytes}`); + } +} + /** * Decode a byte stream as UTF-8 text, or return null once it has produced * more than `maxBytes` (the stream is cancelled at that point, so an oversized @@ -7,6 +13,7 @@ export async function readTextWithLimit( stream: ReadableStream, maxBytes: number, ): Promise { + assertByteLimit(maxBytes); const reader = stream.getReader(); const decoder = new TextDecoder(); let total = 0; @@ -17,7 +24,7 @@ export async function readTextWithLimit( if (done) break; total += value.byteLength; if (total > maxBytes) { - await reader.cancel().catch(() => {}); + void reader.cancel().catch(() => {}); return null; } text += decoder.decode(value, { stream: true }); @@ -27,3 +34,20 @@ export async function readTextWithLimit( } return text + decoder.decode(); } + +/** + * `readTextWithLimit` for a store object: a reported `size` over the limit + * returns null without reading, and a missing or wrong one (`@vercel/blob` + * reports 0 or NaN) still stops at the limit while streaming. + */ +export async function readBlobTextWithLimit( + { stream, size }: { stream: ReadableStream; size?: number }, + maxBytes: number, +): Promise { + assertByteLimit(maxBytes); + if (size !== undefined && size > maxBytes) { + void stream.cancel().catch(() => {}); + return null; + } + return readTextWithLimit(stream, maxBytes); +} From 650d4bec9d3d5b87e25ef1542d6e3d566c6f840b Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 21 Oct 2026 13:36:32 -0700 Subject: [PATCH 3/4] fix(docs): fail the build when normalized redirects exceed the router cap parseVersionRedirectsFile checks the size of the source file, but normalization adds "permanent":true to every rule that omits it, so a source under 1 MiB can produce a _redirects.json over it. Such a file passed sync-docs and archive-layout and was only refused at upload. Checking the serialized size in readVersionRedirects surfaces the authoring defect at sync time instead; the upload check stays as the guard at the trust boundary. Assisted-by: AI --- apps/docs/scripts/version-redirects.mjs | 15 +++++++++++++-- apps/docs/scripts/version-redirects.test.mjs | 12 +++++++++++- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/apps/docs/scripts/version-redirects.mjs b/apps/docs/scripts/version-redirects.mjs index 0ddfa4c2..26fee52b 100644 --- a/apps/docs/scripts/version-redirects.mjs +++ b/apps/docs/scripts/version-redirects.mjs @@ -1,7 +1,11 @@ // Read and validate the `docs/redirects.json` of the exact content commit a version is built from. import { readFile } from "node:fs/promises"; import path from "node:path"; -import { parseVersionRedirectsFile, serializeVersionRedirects } from "@coder/docs-manifest"; +import { + MAX_VERSION_REDIRECTS_BYTES, + parseVersionRedirectsFile, + serializeVersionRedirects, +} from "@coder/docs-manifest"; /** * The artifact body for a docs tree: the file's rules, validated and @@ -29,5 +33,12 @@ export async function readVersionRedirects(docsRoot) { `docs/redirects.json is invalid, so this version is not published: ${error.message}`, ); } - return { body: serializeVersionRedirects(rules), count: rules.length }; + const body = serializeVersionRedirects(rules); + const size = Buffer.byteLength(body); + if (size > MAX_VERSION_REDIRECTS_BYTES) { + throw new Error( + `docs/redirects.json is invalid, so this version is not published: its normalized rules are larger than ${MAX_VERSION_REDIRECTS_BYTES} bytes (${size})`, + ); + } + return { body, count: rules.length }; } diff --git a/apps/docs/scripts/version-redirects.test.mjs b/apps/docs/scripts/version-redirects.test.mjs index d14b6c52..43021d60 100644 --- a/apps/docs/scripts/version-redirects.test.mjs +++ b/apps/docs/scripts/version-redirects.test.mjs @@ -3,7 +3,7 @@ import { mkdtemp, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { test } from "node:test"; -import { parseVersionRedirectsArtifact } from "@coder/docs-manifest"; +import { MAX_VERSION_REDIRECTS_BYTES, parseVersionRedirectsArtifact } from "@coder/docs-manifest"; import { readVersionRedirects } from "./version-redirects.mjs"; async function withDocs(redirects, run) { @@ -64,3 +64,13 @@ test("an invalid file fails the build and names the file and the rule", async () ); await assert.rejects(() => withDocs("{}", readVersionRedirects), /JSON array/); }); + +test("a file under the cap whose normalized rules are over it fails the build", async () => { + const rules = Array.from({ length: 25_000 }, (_, i) => ({ source: `r${i}`, destination: "d" })); + const text = JSON.stringify(rules); + assert.equal(Buffer.byteLength(text) < MAX_VERSION_REDIRECTS_BYTES, true); + await assert.rejects( + () => withDocs(text, readVersionRedirects), + /docs\/redirects\.json is invalid.*larger than/, + ); +}); From d55249477e62d44456eb4935b3ca463316e85b27 Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 21 Oct 2026 13:36:32 -0700 Subject: [PATCH 4/4] docs: describe the redirects and object-record size caps The router README still said an object that fails the check is treated as absent and listed only the present and absent TTLs, but an oversized rules object is now a third case, kept as no rules for the long TTL. The docs app README didn't say that a publish fails on a _redirects.json over 1 MiB, or that an _objects.json over 16 MiB falls back to a full upload. Assisted-by: AI --- apps/docs/README.md | 3 ++- apps/router/README.md | 2 ++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/apps/docs/README.md b/apps/docs/README.md index 9caeb2f2..5ce7d3b7 100644 --- a/apps/docs/README.md +++ b/apps/docs/README.md @@ -249,6 +249,7 @@ The object is always written: a missing file or an empty array yields `{"version `_redirects.json` is listed in `_publish.json` and uploaded like any other object, so it is read back and hashed by `publish:verify`. One invalid rule fails the whole file, as it does for `apps/router/redirects.json`: the version's build fails, nothing is uploaded, and the previous publish keeps serving. The error names the rule; the fix is a commit to `docs/redirects.json` on that branch. +The normalized `_redirects.json` must be at most 1 MiB (`MAX_VERSION_REDIRECTS_BYTES`), which the router will not read past; `sync-docs.mjs` and `archive-layout.mjs` check its serialized size, and the upload checks the file again and fails the publish before anything is put. The router applies the rules on a miss inside that version (`apps/router/README.md`, "Redirects"); the check that a destination exists belongs to `coder/coder`'s CI and to the router's probe, not to the publisher. A change to only `docs/redirects.json` changes the docs tree, so reconcile sees the version as behind and republishes it within the hourly cycle. @@ -256,7 +257,7 @@ A change to only `docs/redirects.json` changes the docs tree, so reconcile sees Every upload writes `_objects.json` beside `_publish.json`, recording the SHA-256 and size of each object as the publish job itself read it; the untrusted `build` job never writes it. With the variable set to `true`, the publish job reads the manifest before uploading, finds the prefix this version is served from now, and copies each object whose bytes hash to what that prefix's `_objects.json` recorded with a server-side `copy()` instead of uploading it again. The storage layout does not change: every prefix still holds a full copy of its version, so the router, cleanup, and rollback are untouched. -A missing record, a failed manifest read, or a failed copy falls back to a plain upload, and the "Upload to the archive" step's log line reports how many objects were copied and how many megabytes were sent. +A missing record, a record over 16 MiB (which is not read), a failed manifest read, or a failed copy falls back to a plain upload, and the "Upload to the archive" step's log line reports how many objects were copied and how many megabytes were sent. Three settings must instead be **repository**-level, never environment-scoped, because `publish-version.yml`'s `build` job carries no `environment:` at all and could not read an environment-scoped value: diff --git a/apps/router/README.md b/apps/router/README.md index bbcc9063..65e41468 100644 --- a/apps/router/README.md +++ b/apps/router/README.md @@ -42,6 +42,7 @@ Its older content rules stay until each version's own file is live, and are then A version's rules are its `docs/redirects.json` from the `coder/coder` commit it was built from, validated at publish and stored as `_redirects.json` at its archive prefix root, beside `_publish.json` (`apps/docs/README.md`, "Version redirects"). `parseVersionRedirectsArtifact` in `@coder/docs-manifest` reads it back as strictly as the publisher wrote it, because the build job that produced it compiles untrusted content; an object that fails the check is logged and treated as absent. +An object over the 1 MiB cap (`MAX_VERSION_REDIRECTS_BYTES`) is not read past the cap: it is logged with its archive prefix and the size the store reported, and the version gets no rules of its own. The object is `{"version":1,"rules":[{"source","destination","permanent"}]}`, with routes relative to the version's docs root. A request path is matched relative to that root, ignoring one trailing slash: `/v2.38/a/b` and `/@main/a/b` match `a/b`, and so does `/a/b` on the mainline served at the root. Matching is case-insensitive, as for the static rules, so `/v2.38/A/B` matches `a/b` too; the part a wildcard matched keeps the request's case. @@ -63,6 +64,7 @@ A version whose own rule matched but whose destination page is missing gets its The router loads the object once per archive prefix and keeps it for ten minutes, which bounds how long a warm instance serves old rules after a forced tag republish rewrites the prefix in place. A prefix with no object (published before this existed) is asked again after a minute, so a republish that adds one is picked up; until then the version behaves as before, with only the static rules. +An object that fails the check is also asked again after a minute, but one over the size cap is kept as no rules for the full ten minutes, so an oversized object is not fetched again every minute. A store failure while reading the object is not cached: the reader gets the version's not-found page with `cache-control: no-store`, as for a failed probe, and the static rules still run. `lib/version-redirects.test.ts` covers it.