Repository navigation
fix(router): enforce the redirects size cap before and while reading - #228
Conversation
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
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
/coder-agents-review |
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 |
Jesswinters
left a comment
There was a problem hiding this comment.
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.
| 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"); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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)) { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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(() => {}); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 } : {}), |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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" }; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
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
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.jsonat 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.jsonhad the same unbounded pattern.This addresses coder/security-assessments#385.
Fix
readTextWithLimitin@coder/docs-manifestdecodes a stream as UTF-8 and cancels it once it passes a byte limit.readVersionRedirectsTextchecks 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 fornullon an oversized object; the tag is what lets the loader cache that verdict separately.upload.mjsfails the publish when_redirects.jsonis over the cap, before anything is uploaded, rather than skipping it.readRecordedObjectschecks 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.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.readVersionRedirectschecks the byte size of the normalized_redirects.json, which can be larger than the source file because"permanent":trueis added to rules that omit it, so such a file fails atsync-docsrather than only at upload.apps/router/README.mdandapps/docs/README.mddescribe 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.mjsandpackages/docs-manifest/src/bounded-read.test.tsshow the behaviour, and thebuild & checkrun on this PR covers them.Pages to compare
Testing
The behaviour tests fail on the previous code and pass now: an object reporting an oversized
sizeis never pulled from the stream; an object reported as 0 or NaN bytes (what@vercel/blobreports 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.mjsrejects an over-cap_redirects.jsonbefore any put and accepts one exactly at the cap; an_objects.jsonthat 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.