Skip to content

Commit d975131

Browse files
committed
fix(http): never store or replay null-body statuses (204/205/304)
1 parent 19175c2 commit d975131

3 files changed

Lines changed: 123 additions & 10 deletions

File tree

‎AGENTS.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ Never touch contents inside `<!-- automd -->` in README.md. They are auto genera
5151
- Request narrowing (cookie stripping, authorization stripping, query narrowing) only applies to cacheable calls: non-GET/HEAD requests bypass the cache (`_shouldBypassCache`, composed with any caller `shouldBypassCache`) and reach the handler with their request untouched — including the body, which the rewritten `Request` would otherwise drop
5252
- Bypassed responses pass through untouched: because `serialize` lives outside the resolver, a bypassed call (`cachedFunction` returns the resolver output raw — no `serialize`/`transform`) yields the handler's live `Response`, which the outer wrapper detects (`value instanceof Response`) and returns as-is. No body buffering (streaming/binary bodies survive), no synthesized cache headers, and no bogus `304` for a non-cacheable method — a **breaking behavior change** vs. the old always-serialize path (`fix(http)!`)
5353
- `validate` rejects a **missing** body (`value.body === undefined`) but accepts `""`: a zero-byte 200 is a legal response and rejecting it would only cost hit rate. The dangerous empty body (a body-less HEAD response replayed to GET clients) is prevented by the method component in the key, not here — an empty entry is only readable by requests of the method that produced it. Documented in-place at the check so it isn't re-litigated
54+
- Null-body statuses (`204`/`205`/`304`, `_nullBodyStatuses`) are handled on **two** sides. `validate` refuses to store them: a 204/205 has no representation to replay, and a 304 is an answer to a conditional request, not a representation — a handler doing its own conditional handling (h3 `serveStatic`, nitro public assets, an upstream-proxying route) returns one on demand, so a single crafted `If-Modified-Since: <far future>` used to store a 304 that every later **unconditional** request was served for the whole TTL. And the read path forces `body → null` for those statuses before `createResponse`, because `serialize` stores a body-less response as `""` (not nullish, so `?? null` doesn't catch it) and `new Response("", { status: 204 })` **throws** — including on the MISS, which is served through the freshly serialized entry regardless of `validate`'s verdict. Rejecting on read as well as on write means an entry written by an older ocache heals on first access. Both guards are needed: `validate` alone leaves the MISS crashing, the read-path guard alone keeps storing an unservable 304
5455
- `.resolveKeys(event)` / `.invalidate(event)` / `.expire(event)` on the returned handler (issue #71) target the **resource, not one method variant**: they cover every cacheable method's variant of the event's resource key regardless of which method the passed event carries, so purging `/article/hello` can't leave a sibling HEAD entry advertising the dead etag/last-modified for downstream caches to revalidate against. `resolveKeys` enumerates the same set (one key per base prefix **per method variant**), the event's own variant first, so `keys[0]` is still exactly the key that event reads/writes. Implemented by feeding each variant key to the standalone `cache.ts` helpers as a fixed `getKey` — `_resolveKey` is method-free, so no event is ever cloned or mutated. `_variantOptions` calls `_resolveStorage(_opts)` first: it spreads `_opts` into one fresh options object per variant, so without pre-resolving, a purge issued before the first request would leave each copy to resolve its own storage (re-running a `storage` factory once per variant)
5556
- Storage memo asymmetry vs `cache.ts`: `defineCachedHandler` reassigns `opts` to a merged clone on entry and clones again into `_opts`, so **the caller's own options object never receives the resolved storage** — unlike `defineCachedFunction`, which writes it back to `_optsRef`. So `invalidateCache({ options: myHandlerOpts })` will _not_ reach a handler's default storage. Deliberate: never-works is clearer than sometimes-works (the memo would otherwise land only when a purge happened to run before the first request), and reconstructing a handler key by hand is the error-prone path issue #71 exists to avoid — use the handler's own `.invalidate(event)`/`.expire(event)`/`.resolveKeys(event)`, or pass an explicit `storage` if a standalone helper must reach it
5657
- Framework integration hooks on `CachedEventHandlerOptions`:

‎src/http.ts‎

Lines changed: 38 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -371,14 +371,30 @@ export function defineCachedHandler<E extends HTTPEvent = HTTPEvent>(
371371
if (value.status >= 400) {
372372
return false;
373373
}
374+
// Null-body statuses are never a servable stored representation. A 204/205 carries
375+
// nothing to replay, and a 304 is an *answer to a conditional request*, not a
376+
// representation at all — yet a handler doing its own conditional handling (h3
377+
// `serveStatic`, nitro public assets, any route proxying `If-Modified-Since`
378+
// upstream) returns one on request. Stored, it would be served to every later
379+
// *unconditional* request for the rest of the TTL, so a single crafted
380+
// `If-Modified-Since: <far future>` takes the route down until the entry dies (the
381+
// handler is never re-invoked, so nothing self-heals). Rejecting on read as well as
382+
// on write means an entry written by an older ocache heals on first access.
383+
if (_nullBodyStatuses.has(value.status)) {
384+
return false;
385+
}
374386
// Only a *missing* body (`serialize` never ran / a malformed foreign entry) is
375387
// rejected — an empty string is a legitimate entry and stays cacheable. A zero-byte
376-
// 200 is a valid GET response, so rejecting `""` would only cost hit rate. The one
377-
// dangerous empty body — a body-less HEAD response replayed to GET clients — is
378-
// handled where it belongs, in `getKey`'s method component: an empty entry is now
379-
// only ever readable by requests of the method that produced it (h3#1524 audit,
380-
// finding #3). Rejecting `""` here would neither have closed that hole (the poisoned
381-
// entry would just be re-poisoned on the next HEAD) nor be the right layer for it.
388+
// 200 is a valid GET response, so rejecting `""` would only cost hit rate. The two
389+
// dangerous empty bodies are each handled on their own axis, not here: a body-less
390+
// HEAD response replayed to GET clients is prevented by `getKey`'s method component
391+
// (an empty entry is only ever readable by requests of the method that produced it —
392+
// h3#1524 audit, finding #3), and a body-less *status* (204/205/304, where `""` is
393+
// not just useless but illegal to reconstruct a `Response` from) is prevented by the
394+
// status check directly above. Rejecting `""` here would have closed neither (the
395+
// HEAD entry would just be re-poisoned on the next HEAD; the status crash also fires
396+
// on the MISS, which is served before `validate` can refuse storage) nor be the right
397+
// layer for either.
382398
if (value.body === undefined) {
383399
return false;
384400
}
@@ -526,10 +542,17 @@ export function defineCachedHandler<E extends HTTPEvent = HTTPEvent>(
526542
});
527543
}
528544

529-
// Send Response. Binary bodies were stored base64-encoded; decode them back to raw
530-
// bytes so the Response carries the original payload untouched (no UTF-8 mangling).
531-
const body =
532-
response.base64 && typeof response.body === "string"
545+
// Send Response. A null-body status must be reconstructed with a literally `null`
546+
// body — `new Response("", { status: 204 })` throws — and `serialize` stores a
547+
// body-less response as `""` (or as empty base64), neither of which is nullish, so
548+
// this is an explicit status check rather than a `?? null`. `validate` refuses to
549+
// *store* these statuses, but the MISS path serves the freshly serialized entry
550+
// regardless of that verdict, so the guard belongs here too. Binary bodies were
551+
// stored base64-encoded; decode them back to raw bytes so the Response carries the
552+
// original payload untouched (no UTF-8 mangling).
553+
const body = _nullBodyStatuses.has(response.status)
554+
? null
555+
: response.base64 && typeof response.body === "string"
533556
? _base64ToBytes(response.body)
534557
: (response.body ?? null);
535558
return _createResponse(body, {
@@ -605,6 +628,11 @@ const _transportHeaders = ["content-encoding", "content-length", "transfer-encod
605628
// addition here; the key scheme below already accommodates it.
606629
const _cacheableMethods = ["GET", "HEAD"];
607630

631+
// Statuses whose responses must carry no body at all: the `Response` constructor throws
632+
// for any non-null body on these. Used on both sides — `validate` refuses to store them,
633+
// and the read path forces the body to `null` (see each site for why both are needed).
634+
const _nullBodyStatuses = new Set([204, 205, 304]);
635+
608636
/**
609637
* Prefixes a resource key with its method component. GET is the implicit default and
610638
* carries none, so its keys are unchanged; every other cacheable method gets a

‎test/index.test.ts‎

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3919,6 +3919,90 @@ describe("defineCachedHandler", () => {
39193919
expect(await testStorage.get(key)).toMatchObject({ stale: true });
39203920
}
39213921
});
3922+
3923+
// --- Null-body statuses (204 / 205 / 304) ---
3924+
3925+
// `serialize` stores a body-less response as `""`, which is not nullish, so replaying it
3926+
// as `new Response("", { status: 204 })` used to throw — on the MISS too, since the miss
3927+
// is served through the freshly serialized entry. Two guards: the read path forces the
3928+
// body to `null` for these statuses, and `validate` refuses to store them at all.
3929+
for (const status of [204, 205, 304]) {
3930+
it(`serves a ${status} response without throwing and never stores it`, async () => {
3931+
let callCount = 0;
3932+
const path = uniquePath();
3933+
const handler = defineCachedHandler(
3934+
() => {
3935+
callCount++;
3936+
return new Response(null, { status });
3937+
},
3938+
{ maxAge: 100 },
3939+
);
3940+
3941+
const r1 = (await handler(makeEvent(path))) as Response;
3942+
expect(r1.status).toBe(status);
3943+
expect(r1.body).toBeNull();
3944+
3945+
const r2 = (await handler(makeEvent(path))) as Response;
3946+
expect(r2.status).toBe(status);
3947+
expect(r2.body).toBeNull();
3948+
3949+
// Not a servable stored representation: nothing is kept, so every request re-resolves.
3950+
const [key] = await handler.resolveKeys(makeEvent(path));
3951+
expect(await testStorage.get(key!)).toBeFalsy();
3952+
expect(callCount).toBe(2);
3953+
expect(r2.headers.get("x-cache")).toBe("MISS");
3954+
});
3955+
}
3956+
3957+
it("does not let a handler's own 304 poison the unconditional path", async () => {
3958+
let callCount = 0;
3959+
const path = uniquePath();
3960+
const handler = defineCachedHandler(
3961+
(event) => {
3962+
callCount++;
3963+
// A handler doing its own conditional handling (h3 `serveStatic`, nitro public
3964+
// assets, any route proxying the conditional headers upstream).
3965+
return event.req.headers.get("if-modified-since")
3966+
? new Response(null, { status: 304 })
3967+
: new Response("fresh body", { status: 200 });
3968+
},
3969+
{ maxAge: 100 },
3970+
);
3971+
3972+
// One crafted conditional request used to store a 304 that every later unconditional
3973+
// request was then served (and crashed on).
3974+
const attacker = (await handler(
3975+
makeEvent(path, { headers: { "if-modified-since": "Fri, 31 Dec 2999 23:59:59 GMT" } }),
3976+
)) as Response;
3977+
expect(attacker.status).toBe(304);
3978+
3979+
const [key] = await handler.resolveKeys(makeEvent(path));
3980+
expect(await testStorage.get(key!)).toBeFalsy();
3981+
3982+
// The unconditional path still reaches the handler and gets the real representation.
3983+
const victim = (await handler(makeEvent(path))) as Response;
3984+
expect(victim.status).toBe(200);
3985+
expect(await victim.text()).toBe("fresh body");
3986+
expect(callCount).toBe(2);
3987+
});
3988+
3989+
it("serves HEAD against a 204 route", async () => {
3990+
const path = uniquePath();
3991+
const handler = defineCachedHandler(() => new Response(null, { status: 204 }), {
3992+
maxAge: 100,
3993+
// A spec-compliant host nulls a HEAD body — the same shape a 204 already has.
3994+
toResponse: headStrippingToResponse,
3995+
});
3996+
3997+
const r1 = (await handler(makeEvent(path, { method: "HEAD" }))) as Response;
3998+
expect(r1.status).toBe(204);
3999+
expect(r1.body).toBeNull();
4000+
4001+
const r2 = (await handler(makeEvent(path, { method: "HEAD" }))) as Response;
4002+
expect(r2.status).toBe(204);
4003+
expect(r2.body).toBeNull();
4004+
expect(r2.headers.get("x-cache")).toBe("MISS");
4005+
});
39224006
});
39234007

39244008
describe("resolveCacheKeys", () => {

0 commit comments

Comments
 (0)