diff --git a/apps/docs/README.md b/apps/docs/README.md index 5b2af58b..62a297ae 100644 --- a/apps/docs/README.md +++ b/apps/docs/README.md @@ -251,6 +251,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. @@ -258,7 +259,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/docs/scripts/publish/upload.mjs b/apps/docs/scripts/publish/upload.mjs index 92625da7..09406c97 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, + readBlobTextWithLimit, + 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; + /** Written first by every upload, so cleanup can tell a prefix being re-uploaded from an idle orphan. */ export const UPLOADING_KEY = "_uploading.json"; @@ -120,9 +130,12 @@ 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"), + 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) { throw new Error("unrecognised format"); } @@ -183,6 +196,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 01941e75..d7163046 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, @@ -609,6 +610,61 @@ test("liveArchivePrefix finds the prefix the manifest serves this version from", 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/); +}); + test("the upload marker is written before any object, so a cleanup sweep sees the prefix as in flight", async () => { const dir = await archiveFixture([entry("index.html"), entry("_next/static/chunks/a.js")]); const prefix = `versions/main/${sha}`; 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/, + ); +}); diff --git a/apps/router/README.md b/apps/router/README.md index 614de7ab..69e21594 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. diff --git a/apps/router/lib/archive.ts b/apps/router/lib/archive.ts index 6befd891..bafca192 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, + readBlobTextWithLimit, } 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"; reportedSize: number } + | { 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" }; + 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 c9a8bb59..51880e9f 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,107 @@ 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; + +// 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); + 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"', 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 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 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({ + objects: { ...store, [`${prefix("2.38")}/_redirects.json`]: padded }, + }).fetch("/v2.38/templates"); + 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(16 * TOO_LARGE, { 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 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 33b67cdd..888c10d9 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,20 @@ 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 at ${new URL(deployment).pathname} (reported size ${read.reportedSize})`, + ); + 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..ddf6d07a --- /dev/null +++ b/packages/docs-manifest/src/bounded-read.test.ts @@ -0,0 +1,94 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { readBlobTextWithLimit, 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`); +}); + +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 new file mode 100644 index 00000000..fb12f684 --- /dev/null +++ b/packages/docs-manifest/src/bounded-read.ts @@ -0,0 +1,53 @@ +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 + * body is never pulled in full). + */ +export async function readTextWithLimit( + stream: ReadableStream, + maxBytes: number, +): Promise { + assertByteLimit(maxBytes); + 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) { + void reader.cancel().catch(() => {}); + return null; + } + text += decoder.decode(value, { stream: true }); + } + } finally { + reader.releaseLock(); + } + 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); +} 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";