Skip to content

Commit 12f09f0

Browse files
committed
fix(http): respect shouldBypassCache when narrowing requests
1 parent 660bee6 commit 12f09f0

7 files changed

Lines changed: 253 additions & 29 deletions

File tree

‎AGENTS.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ Never touch contents inside `<!-- automd -->` in README.md. They are auto genera
4545

4646
### HTTP handler caching (`http/`)
4747

48-
Split across the modules listed under Project Structure. The bullets below are about the handler as a whole; each mechanism lives in the module its name suggests — the derived cookie/header/query lists (`HandlerConfig`) in `config.ts`, `shouldBypassCache` + request narrowing in `request.ts`, `resolveKey`/`methodKey`/`cacheableMethods` in `key.ts`, the `filterCookie`/`filteredSearch` allowlists those two share in `filters.ts`, the internal `serialize` hook **and its read-side mirror** `deserializeEntry` (plus the base64 codec, the transport-header strip and the null-body statuses, all private) in `entry.ts`, the `validate` hook + the status allowlist in `validate.ts`, the `Cache-Control` directive parser those decisions read in `cache-control.ts`, `Vary` mechanics in `vary.ts`, and the 304 exchange in `conditional.ts`. `index.ts` holds only the wiring: the `CacheOptions` hooks handed to `cachedFunction`, the resolver, the serve path and the revalidation helpers. Two modules are named for the `CacheOptions` hook they implement (`entry.ts`'s `serialize`, `validate.ts`), and the dependency graph is a DAG — `cache-control.ts`, `vary.ts`, `conditional.ts` and `config.ts` import nothing from the directory.
48+
Split across the modules listed under Project Structure. The bullets below are about the handler as a whole; each mechanism lives in the module its name suggests — the derived cookie/header/query lists (`HandlerConfig`) in `config.ts`, the composed bypass (`resolveBypass`) + request narrowing in `request.ts`, `resolveKey`/`methodKey`/`cacheableMethods` in `key.ts`, the `filterCookie`/`filteredSearch` allowlists those two share in `filters.ts`, the internal `serialize` hook **and its read-side mirror** `deserializeEntry` (plus the base64 codec, the transport-header strip and the null-body statuses, all private) in `entry.ts`, the `validate` hook + the status allowlist in `validate.ts`, the `Cache-Control` directive parser those decisions read in `cache-control.ts`, `Vary` mechanics in `vary.ts`, and the 304 exchange in `conditional.ts`. `index.ts` holds only the wiring: the `CacheOptions` hooks handed to `cachedFunction`, the resolver, the serve path and the revalidation helpers. Two modules are named for the `CacheOptions` hook they implement (`entry.ts`'s `serialize`, `validate.ts`), and the dependency graph is a DAG — `cache-control.ts`, `vary.ts`, `conditional.ts` and `config.ts` import nothing from the directory.
4949

5050
- `defineCachedHandler<E extends HTTPEvent>(handler, opts)` — wraps an `EventHandler` with response caching (generic over event type)
5151
- Cache key `name`: resolved with `cache.ts`'s shared `resolveName(opts.name, handler)` **before** the `defaultHandlerOptions()` merge (`config.ts`'s own defaults — deliberately not `cache.ts`'s `defaultCacheOptions()`, since only the HTTP layer has a `cacheStatusHeader`, and named apart so neither can be imported for the other), exactly like `defineCachedFunction`. Merging first (the old order) left `opts.name` permanently `"_"` by the time `cachedFunction` re-derived it, so issue #53's fix never reached the HTTP layer and **every** handler keyed as `name: "_"`. Two handlers sharing one `storage` (the configuration `types.ts` recommends) that can see the same path then collided: identical source ⇒ identical integrity ⇒ one served the other's cached response (cross-handler leak); differing source ⇒ every read failed the other's integrity check ⇒ permanent thrash at 0% hit rate. **Breaking key change**, not a behavior change: every existing handler entry goes cold once (the key gains a real name segment). The `HEAD:` method component still sits directly after the name segment, so key shape is otherwise unchanged. Same **documented caveat** as `defineCachedFunction`, and it bites harder here because the shared-`storage` setup turns it into a leak: `hash(handler)` sees only source, so handlers from one factory (`(tenant) => defineCachedHandler(() => render(tenant), { storage })`) share a name _and_ an integrity — pass an explicit `name` per instance. A per-instance discriminator (counter/WeakMap/randomness) is inadmissible: keys must be deterministic across process restarts for persistent/shared backends, which is exactly why a source hash is the right fallback
@@ -71,7 +71,7 @@ Split across the modules listed under Project Structure. The bullets below are a
7171
- Authorization: **by default `authorization` / `proxy-authorization` do not participate in caching** (secure default, same rigor as cookies) — both are stripped from the handler-visible request on cacheable calls, so a handler cannot render per-user content from a credential that isn't in the cache key. Previously they were forwarded untouched but never keyed, so a token-authenticated route failed **open**: the first caller's private response was stored under the anonymous key, replayed to everyone, and advertised `public, s-maxage=N` for shared CDNs (cookie-authenticated routes already failed safe — that asymmetry was the defect). `allowAuthorization: true` opts both names back in by folding them into both header lists (deduped against `opts.varies`, sorted), which in one step makes them vary the key, appear in the response `Vary`, and stay visible to the handler. Listing either name in `varies` counts as the same opt-in. Callers opting in own the consequence: one entry per distinct credential value, shared by everyone presenting it. A **breaking behavior change** — handlers needing the credential must set `allowAuthorization`, or bypass those requests (`shouldBypassCache`)
7272
- Transport headers (`content-encoding`, `content-length`, `content-range`, `transfer-encoding`) are stripped in `serialize` before storage (`transportHeaders`): the body is stored fully decoded and re-buffered, so replaying an upstream `content-encoding: gzip` against a decompressed body (or a stale `content-length`/wire `transfer-encoding`) would desync the headers from the served body and yield malformed responses (nitro#2109). The runtime recomputes `content-length` from the served body on read. `content-range` is there for the same reason and **not** because a 206 could reach storage (it can't — `Range` requests bypass and `validate` rejects the status): it describes a _partial_ body, so on an entry we do store — always a complete representation — it is meaningless at best and a lie about the served bytes at worst. Realistic source: a proxying handler copying upstream headers onto a 200
7373
- `varies` headers are **forwarded to the handler** — their values are part of the cache key, so reading them is safe and is the point of declaring them. **`cookie` is no longer an exception**: it too is forwarded (raw) when listed in `varies` with no `allowCookies`, which is what makes that listing a real opt-in rather than pure key fragmentation. They used to be the only headers filtered out, which meant `varies: ["accept-language"]` produced correct per-language keys and `Vary` while every entry held the _default_ rendering (**breaking behavior change**). Request narrowing is now driven by `keyHeaderNames` alone — a declared header is visible, an undeclared credential header (`authorization`/`proxy-authorization`/`cookie`) is stripped — plus the finer `allowCookies` filter and `allowQuery` on the URL
74-
- Request narrowing (cookie stripping, authorization stripping, query narrowing) only applies to cacheable calls: non-GET/HEAD requests **and any request carrying a `Range` header** 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. Narrowing **mutates the caller's event** (`event.req`, plus `event.url` under `allowQuery`) and never restores it, so after a MISS the caller observes the narrowed request while after a HIT or a bypass it does not — downstream middleware and logging see different headers depending on cache state. Not restored in a `finally` on purpose: a handler's body producer can run _after_ the resolver returns (an async `ReadableStream.pull` is drained by `serialize`'s `res.arrayBuffer()`), so a restore would hand the original credentialed request back to a lazy read whose output is then cached and replayed — re-opening exactly what narrowing exists to close. It would also still leave the SWR window, where the background refresh swaps the stale reader's event after its response was already returned. The real fix is to stop mutating the caller's event at all (hand the handler a narrowed copy), which needs a design decision because `E` is an arbitrary framework event — tracked separately
74+
- Request narrowing (cookie stripping, authorization stripping, query narrowing) only applies to cacheable calls: non-GET/HEAD requests **and any request carrying a `Range` header** bypass the cache (the built-in half of `resolveBypass`, composed with any caller `shouldBypassCache`) and reach the handler with their request untouched — including the body, which the rewritten `Request` would otherwise drop. Gated on the **composed** verdict, never the built-in half alone (finding 09): the built-in check said "cacheable" for a GET the caller had excluded, so `shouldBypassCache` stripped credentials off the very requests it exempted from the cache — and it is the escape hatch the credential defaults document ("set `allowAuthorization`, or bypass those requests"), so following that advice served the anonymous/401 rendering to every authenticated user, on every request. `narrowRequest` gates itself rather than trusting its call site, so the two can't disagree. The verdict is produced **exactly once per call** — the caller's hook may be async, expensive or side-effecting — by `resolveBypass`, which `cache.ts` awaits to decide its short-circuit to the raw resolver and which memoizes the answer on the event in a per-handler-instance `WeakMap` (`config.bypassed`, the `searchCache` pattern) for the resolver to read. Per-call state keyed by the event, deliberately not a module-level "last verdict" slot, which would be a cross-request bug; threaded through `config` rather than through the resolver's arguments because `cache.ts` calls `fn(...args)` with the caller's args and nothing else. `narrowRequest`'s fallback to the built-in check covers only a resolver reached without `resolveBypass`, which `cachedFunction` cannot do. Narrowing **mutates the caller's event** (`event.req`, plus `event.url` under `allowQuery`) and never restores it, so after a MISS the caller observes the narrowed request while after a HIT or a bypass it does not — downstream middleware and logging see different headers depending on cache state. Not restored in a `finally` on purpose: a handler's body producer can run _after_ the resolver returns (an async `ReadableStream.pull` is drained by `serialize`'s `res.arrayBuffer()`), so a restore would hand the original credentialed request back to a lazy read whose output is then cached and replayed — re-opening exactly what narrowing exists to close. It would also still leave the SWR window, where the background refresh swaps the stale reader's event after its response was already returned. The real fix is to stop mutating the caller's event at all (hand the handler a narrowed copy), which needs a design decision because `E` is an arbitrary framework event — tracked separately
7575
- **`Range` requests bypass the cache** (finding 07), whatever their method — the request-side half of the 206 fix, paired with `206`'s absence from the cacheable-status allowlist. `Range` is forwarded to the handler but is neither in the key nor a `Vary` dimension, so a range-honoring handler (static files, media, `serveStatic`) resolved a **partial** representation under the range-free key: one `curl -r 0-0` stored a one-byte body plus the `Content-Range` describing it, and every later `Range`-less GET was served that truncation for the whole TTL, propagated to shared CDNs by the synthesized `s-maxage` (RFC 9110 §15.3.7 / RFC 9111 §3.3 — a 206 answers only the request that named the range; combining/re-slicing partials is out of scope). Bypassing on the request side is the cheaper half: the handler never runs under a key, so nothing partial is stored, `serialize` never buffers a large partial body, and a ranged request can't thrash the plain entry. **Breaking behavior change**: a ranged request now also skips request narrowing (the standard bypass contract — untouched request in, live `Response` out) and gets no `x-cache`/`etag`/`cache-control` synthesis
7676
- 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)!`)
7777
- `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

‎docs/1.guide/5.handler.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,8 @@ const handler = defineCachedHandler(myHandler, {
7171
});
7272
```
7373

74+
A request you exclude this way gets the same treatment as a `POST`: it reaches the handler **untouched**, with its `Authorization` header, its cookies and its full query string intact. That is what makes `shouldBypassCache` a usable alternative to [`allowAuthorization`](#credential-headers) — the handler can read the credential precisely because the response is never stored or shared.
75+
7476
## Cache key name
7577

7678
Every key carries a `name` component, resolved exactly like a [cached function's](/guide/functions#cache-keys): `opts.name || handler.name || anon_<hash(handler)>`. It is what keeps two handlers that share one `storage` and can see the same path from colliding.
@@ -185,7 +187,7 @@ Opting in folds both header names into `varies`: they vary the cache key, they a
185187
> });
186188
> ```
187189
188-
Only cacheable requests are affected: `POST` and friends bypass the cache and reach the handler with their credentials intact.
190+
Only cacheable requests are affected: `POST` and friends — and anything your own `shouldBypassCache` excludes — bypass the cache and reach the handler with their credentials intact.
189191
190192
## Conditional requests & 304
191193

‎src/http/config.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,19 @@ export interface HandlerConfig<E extends HTTPEvent> {
6363
* Scoped to this handler instance, so a shared event can't pick up another's allowlist.
6464
*/
6565
searchCache: WeakMap<HTTPEvent, string>;
66+
67+
/**
68+
* The *composed* bypass verdict (built-in ∨ the caller's `shouldBypassCache`) for the
69+
* call in flight: written by `resolveBypass`, read by `narrowRequest`. Two consumers,
70+
* one evaluation — `cache.ts` short-circuits to the raw resolver on `true`, and the
71+
* resolver must gate narrowing on the very same answer, while the caller's hook may be
72+
* async, expensive or side-effecting and must not be asked twice.
73+
*
74+
* Keyed by the event and scoped to this handler instance (the {@link searchCache}
75+
* pattern), which is what makes it per-call state: a module-level slot would leak one
76+
* request's verdict into the next.
77+
*/
78+
bypassed: WeakMap<HTTPEvent, boolean>;
6679
}
6780

6881
// Derives the per-handler configuration from the caller's options. `name` is resolved BEFORE
@@ -123,6 +136,7 @@ export function resolveHandlerConfig<E extends HTTPEvent>(
123136
varyHeaderNames,
124137
statusHeader,
125138
searchCache: new WeakMap<HTTPEvent, string>(),
139+
bypassed: new WeakMap<HTTPEvent, boolean>(),
126140
};
127141
}
128142

‎src/http/index.ts‎

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import { integrityOpts, resolveHandlerConfig } from "./config.ts";
1111
import { defaultHandleCacheHeaders, notModifiedHeaders } from "./conditional.ts";
1212
import { deserializeEntry, serializeResponse } from "./entry.ts";
1313
import { cacheableMethods, methodKey, resolveKey } from "./key.ts";
14-
import { narrowRequest, shouldBypassCache } from "./request.ts";
14+
import { narrowRequest, resolveBypass } from "./request.ts";
1515
import { validateEntry } from "./validate.ts";
1616

1717
import type {
@@ -114,14 +114,10 @@ export function defineCachedHandler<E extends HTTPEvent = HTTPEvent>(
114114
// the entry. Runs once per resolution, and outside the resolver so bypassed requests —
115115
// which never reach it — get their live `Response` back untouched.
116116
serialize: (entry) => serializeResponse(config, entry.value as unknown as Response),
117-
// Compose the built-in bypass with the caller's check rather than clobbering it:
118-
// assigning the built-in here used to discard `opts.shouldBypassCache` (issue #50).
119-
shouldBypassCache: async (event: HTTPEvent) => {
120-
if (shouldBypassCache(event)) {
121-
return true;
122-
}
123-
return (await opts.shouldBypassCache?.(event as E)) === true;
124-
},
117+
// The built-in bypass composed with the caller's check (see `request.ts`). The single
118+
// evaluation of that composition per call: `cache.ts` short-circuits to the raw resolver
119+
// on `true`, and the resolver's narrowing reads the same memoized verdict.
120+
shouldBypassCache: (event: HTTPEvent) => resolveBypass(config, event),
125121
// Key = resource identity + method component; see `key.ts` for both halves.
126122
getKey: async (event: HTTPEvent) =>
127123
methodKey(await resolveKey(config, event), event.req.method),
@@ -136,9 +132,9 @@ export function defineCachedHandler<E extends HTTPEvent = HTTPEvent>(
136132
// `Response`. Serialization happens in the `serialize` hook above, which a bypassed
137133
// request skips entirely — so it flows back out untouched.
138134
const cachedFn = cachedFunction<Response>(async (event: HTTPEvent) => {
139-
if (!shouldBypassCache(event)) {
140-
narrowRequest(config, event);
141-
}
135+
// Cacheable calls only — `narrowRequest` gates itself on the composed bypass verdict, so
136+
// a request the caller excluded reaches the handler with its credentials and query intact.
137+
narrowRequest(config, event);
142138

143139
// Call handler
144140
const rawValue = await handler(event as E);

0 commit comments

Comments
 (0)