Skip to content

fix(router): enforce the redirects size cap before and while reading - #228

Merged
nickvigilante merged 5 commits into
mainfrom
vigilante/docs-1350-enforce-the-routers-1-mib-redirects-cap-while-streaming-and
Oct 21, 2026
Merged

nickvigilante merged 5 commits into
mainfrom
vigilante/docs-1350-enforce-the-routers-1-mib-redirects-cap-while-streaming-and

Conversation

@nickvigilante

@nickvigilante nickvigilante commented Oct 21, 2026 •

Copy link
Copy Markdown
Collaborator

Merge order

Independent of the other router hardening PR; either can land first. Both are small and touch different lines, though the second also edits apps/router/lib/archive.ts.

Summary

The router capped a version's _redirects.json at 1 MiB only after streaming the whole object into a string, and cached the rejection for 60 seconds. An oversized object (the build job writes this file, and the publisher uploaded it without a size check) was therefore downloaded in full on every 404 under that version, once a minute per function instance. The publisher's read of _objects.json had the same unbounded pattern.

This addresses coder/security-assessments#385.

Fix

  • A new readTextWithLimit in @coder/docs-manifest decodes a stream as UTF-8 and cancels it once it passes a byte limit.
  • readVersionRedirectsText checks the size the store reports before touching the body, and falls back to the bounded reader when no size is reported. It now returns a small tagged result (absent, too-large, or the text) so the caller can tell the cases apart. The finding asked for null on an oversized object; the tag is what lets the loader cache that verdict separately.
  • An oversized object is cached for the same 10 minutes as a valid one, instead of the 60 seconds used for an absent object. Absent objects keep the short TTL so a republish that adds the file is picked up within a minute.
  • upload.mjs fails the publish when _redirects.json is over the cap, before anything is uploaded, rather than skipping it.
  • readRecordedObjects checks the reported size and reads with the same bounded reader, with a 16 MiB limit; a recorded file over it means a full upload instead of a reuse.
  • Both callers share readBlobTextWithLimit({ stream, size }, maxBytes) from @coder/docs-manifest, which refuses a limit that is not a non-negative safe integer and does not wait for the source's cancel on overflow.
  • The router's over-cap log line names the archive prefix and the size the store reported.
  • readVersionRedirects checks the byte size of the normalized _redirects.json, which can be larger than the source file because "permanent":true is added to rules that omit it, so such a file fails at sync-docs rather than only at upload.
  • apps/router/README.md and apps/docs/README.md describe the too-large case, its TTL, and the 16 MiB record limit.

QA

There is nothing to see on the site: this changes how the router reads one internal object and how the publisher validates it. The new tests in apps/router/lib/version-redirects.test.ts, apps/docs/scripts/publish/upload.test.mjs and packages/docs-manifest/src/bounded-read.test.ts show the behaviour, and the build & check run on this PR covers them.

Pages to compare

What to check Production Preview
Nothing visible changes n/a n/a

Testing

The behaviour tests fail on the previous code and pass now: an object reporting an oversized size is never pulled from the stream; an object reported as 0 or NaN bytes (what @vercel/blob reports for a missing or non-numeric Content-Length) is cut off shortly after the cap; the oversized verdict is read once within the longer TTL and again after it; upload.mjs rejects an over-cap _redirects.json before any put and accepts one exactly at the cap; an _objects.json that reports a huge size is not read and reuse is skipped; the over-cap log names the prefix and size; a NaN limit is refused; an overflow returns even when the source's cancel never settles; a normalized redirects file over the cap fails the build. Some tests pin behaviour that was already correct and pass either way: a file or object exactly at the cap, the 0 and NaN reported sizes, and the unlocked stream after a rejecting cancel. The router, docs publish-script and docs-manifest suites, typecheck, oxfmt and oxlint pass locally.

Review feedback applied in 7ceb6b1, 650d4be and d552494, with main merged in bba503e.

Upstream

No. This is specific to Coder's archive layout and router.

Linear: DOCS-1350


🤖 Built with AI assistance.

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
@vercel

vercel Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
coder-docs Ready Ready Preview Oct 21, 2026 9:00pm UTC
coder-docs-router Ready Ready Preview Oct 21, 2026 9:00pm UTC

Request Review

@nickvigilante

Copy link
Copy Markdown
Collaborator Author

/coder-agents-review

@linear-code

linear-code Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
DOCS-1350 Enforce the router's 1 MiB redirects cap while streaming, and cache misses

Low. https://github.com/coder/security-assessments/issues/385

The router reads a version's _redirects.json in full before applying the 1 MiB cap, and re-downloads it every 60 s on 404s (reproduced with a 64 MiB object). Fix: check content-length and abort the stream once it passes the cap, and cache the over-limit or missing result so it isn't refetched on every 404.

Review in Linear

@Jesswinters Jesswinters left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving: I found no blockers. The streaming byte count is the real limit and the reported size is only an early exit, so no Content-Length quirk gets past it. I checked missing, abc, -5, 1e6, a multi-value header, +2000000, padded values and 1e20 against undici and the @vercel/blob size parsing. Each value either reaches the stream counter or is correctly refused early. Decoded bytes are counted, so an 8 MiB gzip bomb with Content-Length: 8176 is cut off and returns null. A body exactly at the cap is allowed everywhere. A UTF-8 character split across chunks decodes correctly, and one split by the cap returns null. On overflow the reader lock is released and a rejected cancel is swallowed. The cap and the key both come from @coder/docs-manifest, and the tagged result separates absent, too large and store failure cleanly.

The inline comments are non-blocking. The most useful ones are: the over-cap log line doesn't name the version, the READMEs don't describe the new third outcome, and the exported helper accepts a NaN limit, which removes the cap entirely.

Checks I ran on f5bbd90: docs-manifest 114 of 114 and router 134 of 134, both typecheck clean, scripts/publish/*.test.mjs 93 of 93, and oxlint and oxfmt clean. With the old archive.ts, version-rules.ts and upload.mjs restored, the 3 new router tests and 2 of the 3 new upload tests fail; the third checks a file exactly at the cap, which passes either way. CI is green.

Overlap with the other open PRs: this merges cleanly with #232. With #232's readObject, a non-router 4xx on _redirects.json becomes absent, not a store failure, so it's cached for 60 s and nothing marks the page no-store; I've raised that on #232. #234 adds a private REDIRECTS_FILE to upload.mjs where this PR imports VERSION_REDIRECTS_KEY, so whichever lands second should use the import. #236 and this PR both add a constant after OBJECTS_KEY and both append to upload.test.mjs, which is a trivial conflict (keep both).

Generated by Coder Agents on behalf of @Jesswinters.

Comment thread apps/router/lib/version-rules.ts Outdated
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");

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should fix: when the cap is hit, every redirect rule for that version disappears for the 10-minute TTL on each instance, and this line is the only signal. It doesn't name the deployment or prefix, so with several versions live an operator can't tell which one it was. Log new URL(deployment).pathname and the reported size.

Also, apps/router/README.md:44 still says an object that fails the check "is logged and treated as absent", and lines 63 and 64 list only the present and absent TTLs. Too large is now a third case, cached for the long TTL.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 7ceb6b1: the log line now names the archive prefix (new URL(deployment).pathname) and the size the store reported, and a router test asserts both appear. The README is fixed in d552494: line 44 now describes the too-large case separately from a failed check, and the TTL paragraph says an oversized object is kept as no rules for the full ten minutes.

.toSorted();
if (files.length === 0)
throw new Error(`upload: ${dir} has no files to upload (besides _publish.json)`);
if (files.includes(VERSION_REDIRECTS_KEY)) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should fix, docs outside the diff: apps/docs/README.md (around lines 247 to 260) doesn't mention that a publish now fails when _redirects.json is over 1 MiB, or that an _objects.json over 16 MiB now means a full upload instead of a reuse. One sentence for each would do.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in d552494: the "Version redirects" section now says a normalized _redirects.json over 1 MiB fails the version at sync and layout and again at upload, and the DOCS_UPLOAD_REUSE paragraph lists a record over 16 MiB (not read) among the cases that fall back to a plain upload.

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) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: parseVersionRedirectsFile checks the size of the source file, but the normalised _redirects.json can be bigger because "permanent":true is added to each rule that omits it. With a scratch file, an 837,781-byte source passed sync-docs and archive-layout and produced a 1,177,804-byte object, so the publish only failed here. That still fails closed, but AGENTS.md prefers surfacing authoring defects at build time. Checking the size of the serialised output in readVersionRedirects would catch it there, and this check can stay as the guard at the trust boundary.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 650d4be: readVersionRedirects now checks the byte length of the serialized output and fails with the same "docs/redirects.json is invalid" error, so the case you found fails at sync-docs. The new test builds a 25,000-rule source under 1 MiB whose normalized output is over it. The upload check stays as the guard at the trust boundary.

*/
export async function readTextWithLimit(
stream: ReadableStream<Uint8Array>,
maxBytes: number,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: maxBytes isn't validated. With NaN, total > maxBytes is never true, and I confirmed that a 50 KiB stream comes back whole. Today's callers pass constants, but this is an exported shared helper, and AGENTS.md says to fail closed. if (!Number.isSafeInteger(maxBytes) || maxBytes < 0) throw new RangeError(...) makes it safe for future callers.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 7ceb6b1: both readTextWithLimit and the new readBlobTextWithLimit throw a RangeError unless the limit is a non-negative safe integer. The test covers NaN, -1, 1.5 and Infinity; it fails on the old code.

if (done) break;
total += value.byteLength;
if (total > maxBytes) {
await reader.cancel().catch(() => {});

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: await reader.cancel() waits for the source to finish cancelling. If a source's cancel never settles, the read never returns; my scratch test was still pending after 500 ms. undici cancels promptly, so this isn't a live bug, but the other two cancel sites in this PR (archive.ts:261, upload.mjs:131) don't wait. void reader.cancel().catch(() => {}) would match them.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 7ceb6b1: the overflow path is now void reader.cancel().catch(() => {}). A new test with a cancel that never settles returns null within the timeout; on the old code it times out.

blob: {
contentType: "application/json",
etag: '"e"',
...(options.reportSize ? { size: 16 * TOO_LARGE } : {}),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: @vercel/blob 2.8.0 reports size: 0 when Content-Length is missing and NaN when it isn't a number, never undefined. Using size: 0, plus a NaN variant, would test what the SDK actually returns. It would also be worth testing an object whose reported size is exactly the cap, and asserting stream.locked === false and that a rejecting cancel is swallowed in bounded-read.test.ts. I checked both by hand and they behave correctly, but nothing pins them.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 7ceb6b1: the router tests now use size: 0 and size: NaN instead of omitting it, and a new test serves an object padded to exactly the cap with that reported size and checks its rule still redirects. bounded-read.test.ts now asserts stream.locked === false after an overflow with a rejecting cancel, plus the 0, NaN and missing reported sizes for the blob helper.

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" };

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: this sequence (check the reported size, cancel, bounded read, treat null as too large) is repeated almost line for line at upload.mjs:130 to 135. An exported readBlobTextWithLimit({ stream, size }, max) next to readTextWithLimit would stop the two callers drifting apart.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 7ceb6b1: readBlobTextWithLimit({ stream, size }, maxBytes) is exported next to readTextWithLimit, and both archive.ts and upload.mjs use it instead of their own copies of the sequence.

…e 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
… 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
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
Main gained the upload marker, which adds a constant after OBJECTS_KEY in
upload.mjs and appends tests to upload.test.mjs, the same spots this branch
touches. Both constants and both sets of tests are kept.

Assisted-by: AI
@vercel
vercel Bot temporarily deployed to Preview – coder-docs-router October 21, 2026 20:56 Inactive
@nickvigilante
nickvigilante merged commit 8a02702 into main Oct 21, 2026
29 checks passed
@nickvigilante
nickvigilante deleted the vigilante/docs-1350-enforce-the-routers-1-mib-redirects-cap-while-streaming-and branch October 21, 2026 21:01
nickvigilante added a commit that referenced this pull request Oct 21, 2026
Brings in the redirects size cap (#228) and the rest of main; the two branches edit different functions in archive.ts and merged without conflict.

Assisted-by: AI

This branch was successfully deployed

1 active and 1 inactive deployments
Preview – coder-docs — bba503e1 Deployed Oct 21, 2026 by vercel[bot]
Preview – coder-docs-router — bba503e1 Deployed Oct 21, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants