Skip to content

Commit 35c0ae5

Browse files
authored
fix(router)!: ctx.request.headers and getRequestContext().cookie()/cookies() refuse where cookies() does (#976) (#999)
The identity guards covered cookies(), headers(), the theme reads and a { cache: false } variable, but three raw reads went around them: ctx.request.headers (the same Request in handlers, middleware, loaders and getRequestContext().request) and getRequestContext().cookie()/cookies(). A "use cache" function keys a ctx or Request argument by route and URL only, so a header read in its body stored the first caller's value for every caller; a handler under cache() or on a ppr route stored it in the shared record or shell, and a loader's own cache() without key() stored it in its entry. - The request every ctx exposes gets an own, non-enumerable headers getter (server/request-headers.ts shadowRequestHeaders, guarded by cookie-store.ts guardRequestHeaders) that runs guardIdentityRead: the same scopes, order and error style as headers(), and recorded at the read for a loader cache() fill. createRequestContext installs it, and createHandlerContext for a request the router builds and matches (the progressive-enhancement re-render, a navigation-only capture). No Proxy: fetch(ctx.request) and new Request(ctx.request) copy the headers natively and never call the getter (they are not guarded; the docs say not to make them in a cached body). clone() is shadowed to return a guarded clone. A lazy srvx NodeRequest's _request (Node dev and preview servers, vercel output) and Node's util.inspect hook run with the guard off, so srvx's own clone/body reads and console.log(ctx.request) are not reads; the facade stays lazy, so a buffered rawBody is still read. - Router code reads a request's headers only through requestHeaders(), which bypasses the getter (state cookie rotation, request classification, HMR and prefetch markers, origin guard, cf-ray, ...). - getRequestContext().cookie()/cookies() run guardRawCookieRead; the cookies() store reads the unguarded _readCookie()/_readCookies(). - key(), a store keyGenerator, condition(), tags() and onError run under runIdentityExempt (cache/cache-exec-scope.ts): identity reads there are allowed and record nothing. A ppr capture resolves its doc record key and the record's tags again under the capture context, so a keyGenerator or tags() reading the request (or cookies()) refused every capture of its route. The exemption is async-local, so a "use cache" body, a loader body and a segment funnel end it on entry: a key() that awaited a cached function reading cookies() stored the first visitor's cookie. Breaking: a handler under cache() or on a ppr route, or a "use cache" body, that reads ctx.request.headers (or a clone's headers) now throws or refuses the capture. Copy the value in middleware (ctx.set) and include it in key(), read it in a live loader, or pass it into the "use cache" function as an argument. The test fixtures and the test-app, cloudflare-basic and vite-rsc-demo pages that rendered a partition header from a cached handler now render the middleware copy; vite-rsc-demo's unreferenced PostRoute is removed. getRequestContext().theme has been guarded since #979. Tests: request-headers.test.ts (the getter; fetch, new Request, clone and util.inspect in every refusing scope on undici; the srvx facade, lazy rawBody; onError), identity-exempt-scope.test.ts (a cached body, loader body and funnel started inside an exempt callback are guarded), the SCOPES table in cookie-store.test.ts (three new surfaces, exempt rows, clone recording), request-raw-reads.rsc-test.tsx through serveShellRequest (keyGenerator, condition() and tags() at capture), and dev + production e2e identity-raw-reads in the router test-app and cloudflare-basic (on workerd, fetch, new Request and clone inside a cache() boundary).
1 parent bad36a6 commit 35c0ae5

77 files changed

Lines changed: 3478 additions & 954 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎apps/docs/content/docs/rango/concepts/freshness.mdx‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -78,12 +78,12 @@ That loader exemption is also the default contract of `cache()`: cached UI plus
7878

7979
Rango's caches are built so a hit can't serve another user's data or lose a response side effect. Two guard models, both blocking anything that would be wrong on a hit:
8080

81-
- **`cache()` boundary guard** — fires while the handler runs on a miss. `cookies()`, `headers()` and the visitor's theme (`ctx.theme`, `getRequestContext().theme`) throw (request-scoped data would bake into the shared shell); response side effects such as `ctx.headers.set()` and cookie writes throw even on a miss, because they'd be skipped on a hit and produce inconsistent responses. `ctx.set()` of a cacheable var is allowed — children are cached too and can read it.
81+
- **`cache()` boundary guard** — fires while the handler runs on a miss. `cookies()`, `headers()`, the raw reads `ctx.request.headers` and `getRequestContext().cookie()` / `.cookies()`, and the visitor's theme (`ctx.theme`, `getRequestContext().theme`) throw (request-scoped data would bake into the shared shell); response side effects such as `ctx.headers.set()` and cookie writes throw even on a miss, because they'd be skipped on a hit and produce inconsistent responses. `ctx.set()` of a cacheable var is allowed — children are cached too and can read it.
8282
- **`"use cache"` exec guard** — the same request-scoped APIs (the theme reads included) and response writes throw inside the cached function, plus `ctx.set()`, `ctx.setTheme()`, `ctx.setLocationState()`. The guard runs only on the cached path: with no store configured the function runs uncached and nothing throws.
8383

84-
Loaders are exempt from both — they always run fresh, so read request data there. Headers that must appear on every response belong in middleware, outside any boundary.
84+
Loaders are exempt from both — they always run fresh, so read request data there. Headers that must appear on every response belong in middleware, outside any boundary. A cache's own callbacks — a `key()`, a store `keyGenerator`, a `condition()`, a `tags()` function — read request identity freely in every scope: the value picks or labels the entry, it isn't rendered into it. A `"use cache"` function or loader they call is guarded as usual. To render a value a `key()` partitions by, copy it in middleware with `ctx.set()` and read `ctx.get()` in the handler.
8585

86-
A loader bound with its own `cache()` is the one loader that doesn't run fresh: its value is stored under the loader, host, path and params. A miss whose body read `cookies()`, `headers()` or a non-cacheable `ctx.get()` fails, and stores nothing (a stale entry's background refresh too), unless the loader's `cache()` has a `key()` or its store a `keyGenerator`. Either one switches the check off, so it must itself include the value.
86+
A loader bound with its own `cache()` is the one loader that doesn't run fresh: its value is stored under the loader, host, path and params. A miss whose body read `cookies()`, `headers()`, `ctx.request.headers` or a non-cacheable `ctx.get()` fails, and stores nothing (a stale entry's background refresh too), unless the loader's `cache()` has a `key()` or its store a `keyGenerator`. Either one switches the check off, so it must itself include the value.
8787

8888
Context variables get a third, targeted guard. `createVar({ cache: false })` (or a `ctx.set(var, value, { cache: false })` write — least cacheable wins) taints a value as request-scoped, and a **direct** `ctx.get()` of it inside a `cache()` boundary throws — the guard against serving user A's data to user B. The same read throws inside a `"use cache"` function body, where the value would be stored without being part of the key; pass it in as an argument instead. The guarantee is deliberately narrow: a value _derived_ from a tainted var outside the boundary and cached later is not tracked. Don't read this as "you can't cache user data" — the safe pattern is the natural one: **read tainted context at the point of use, in the path that needs it (a loader or live segment) — never extract user data into a plain value and cache that.**
8989

‎apps/docs/content/docs/rango/features/caching.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ export const router = createRouter({
4848

4949
This is a Flight segment cache: HTML is still rendered on every request. Caching the rendered HTML shell and resuming only the holes is a separate layer, the `ppr` path option ([PPR](/docs/rango/guides/ppr)). Function-level caching uses the `"use cache"` directive ([use cache](/docs/rango/guides/use-cache)), and a loader's data caches with an explicit opt-in (`loader(Fn, () => [cache({ ttl })])`).
5050

51-
The guards are correctness-first: `cookies()` and `headers()` throw inside cache scopes rather than silently baking one visitor's data into a shared shell. Read request-scoped data in a loader instead. A loader with its own `cache()` stores its value too, so there a miss fails unless the loader's `cache()` has a `key()`, which must then include it ([Loaders](/docs/rango/features/loaders#live-by-default-even-inside-caches)). [Freshness](/docs/rango/concepts/freshness) covers keys, SWR, nesting, and every guard.
51+
The guards are correctness-first: `cookies()` and `headers()` throw inside cache scopes rather than silently baking one visitor's data into a shared shell, and so do the raw reads `ctx.request.headers` and `getRequestContext().cookie()` / `.cookies()`. Read request-scoped data in a loader instead. A cache's own `key()`, store `keyGenerator`, `condition()` and `tags()` read the request freely: the value picks or labels the entry, it isn't rendered into it. A loader with its own `cache()` stores its value too, so there a miss fails unless the loader's `cache()` has a `key()`, which must then include it ([Loaders](/docs/rango/features/loaders#live-by-default-even-inside-caches)). [Freshness](/docs/rango/concepts/freshness) covers keys, SWR, nesting, and every guard.
5252

5353
## Tags and invalidation
5454

‎apps/docs/content/docs/rango/features/loaders.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ loader(ProductLoader, () => [cache({ ttl: 60 })]),
6262

6363
A hit skips the loader body, so the handle pushes it made on the miss (a `Meta` title, `Breadcrumbs`) are stored with the data and replayed on every hit, stale hits included.
6464

65-
The entry is keyed by the loader, host, path and params — not by the route's `cache()` key — so one entry serves every user. A body that reads `cookies()`, `headers()` or a `createVar({ cache: false })` variable therefore fails on a miss unless the loader's `cache()` has a `key()`. Any `key()` (or a store `keyGenerator`) switches that check off, so it must include the value:
65+
The entry is keyed by the loader, host, path and params — not by the route's `cache()` key — so one entry serves every user. A body that reads `cookies()`, `headers()`, `ctx.request.headers` or a `createVar({ cache: false })` variable therefore fails on a miss unless the loader's `cache()` has a `key()`. Any `key()` (or a store `keyGenerator`) switches that check off, so it must include the value:
6666

6767
```tsx
6868
loader(AccountLoader, () => [

‎apps/docs/content/docs/rango/features/middleware.mdx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,8 @@ export const authMiddleware: Middleware = async (ctx, next) => {
7979

8080
Every middleware must either call `next()` or return (or throw) a `Response`. Returning or throwing a `Response` short-circuits the chain and becomes the HTTP response; headers and cookies already set are merged into it. `ctx.env` carries your platform bindings; `ctx.set()` shares data with everything downstream.
8181

82+
Middleware reads request headers and cookies freely. A handler under `cache()` or on a `ppr` route can't: there `ctx.request.headers`, like `headers()`, throws or refuses the shell capture, since the value would be stored for every visitor. Copy what the handler renders in middleware with `ctx.set()`, and include it in the route's `cache()` `key()` so each value gets its own entry ([Freshness](/docs/rango/concepts/freshness)).
83+
8284
Cookies and request headers are free functions, not `ctx` members: `cookies().get("session")` and `headers().get("accept-language")`, both imported from `@rangojs/router`. To set a response header, call `ctx.header(name, value)`; after `await next()` it writes to the real downstream response:
8385

8486
```ts

‎apps/docs/content/docs/rango/guides/ppr.mdx‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -282,17 +282,17 @@ The shell is shared per host + URL across all users (per request partition too,
282282

283283
What the guards refuse:
284284

285-
- `cookies()`, `headers()`, and `ctx.get()` of a `{ cache: false }` variable **throw during the capture render**, wherever the capture waits for them: a handler, a promise it passes or pushes, an async server component, a bake-lane loader, and a loader a handler awaits (`await ctx.use(Loader)`). The capture is refused even if your code catches the throw, and the route keeps serving MISSes with a once-per-key warning. `ctx.dynamic()` called there refuses the capture too. Live-lane loaders (every loader without `ssr: false`) are exempt: they never run at capture.
285+
- `cookies()`, `headers()`, the raw reads `ctx.request.headers` and `getRequestContext().cookie()` / `.cookies()`, and `ctx.get()` of a `{ cache: false }` variable **throw during the capture render**, wherever the capture waits for them: a handler, a promise it passes or pushes, an async server component, a bake-lane loader, and a loader a handler awaits (`await ctx.use(Loader)`). The capture is refused even if your code catches the throw, and the route keeps serving MISSes with a once-per-key warning. `ctx.dynamic()` called there refuses the capture too. Live-lane loaders (every loader without `ssr: false`) are exempt: they never run at capture.
286286
- `ctx.theme` and `getRequestContext().theme` are the visitor's theme cookie, so reading either anywhere the capture waits for refuses it the same way (warned once per key) and the route keeps serving MISSes. Read the theme with `useTheme()` in a client component, or in a live loader with `cookies().get("theme")`. The shell carries the no-cookie default theme, whoever captured it: a `useTheme()` reader shows the default to a visitor with no stored theme, and switches to a stored theme after hydration. The `<html>` theme class is right before paint either way.
287-
- The guard sees only those reads. A handler or bake-lane loader reading a normal middleware-provided session object (`ctx.get("session")`), or raw request headers, refuses nothing — whatever it renders or returns as plain data is photographed as the capturing user's state. `return { user: session.user }` bakes that user into the shared shell for every visitor. Creating the variable with `createVar({ cache: false })` turns such a read into a refusal instead.
287+
- The guard sees only those reads. A handler or bake-lane loader reading a normal middleware-provided session object (`ctx.get("session")`) refuses nothing — whatever it renders or returns as plain data is photographed as the capturing user's state. `return { user: session.user }` bakes that user into the shared shell for every visitor. Creating the variable with `createVar({ cache: false })` turns such a read into a refusal instead.
288288
- Inside a bake-lane loader, nested promises are the escape hatch for such data, and they hold regardless of timing: the capture masks every promise nested in a bake-lane container (even an already-resolved `Promise.resolve(null)`), so the consumer's `<Suspense>` becomes a hole that streams the fresh value on every HIT. They are not an escape for `cookies()`/`headers()`: the promise body still runs during capture and trips the guard. A promise in handler output is no escape at all — it bakes.
289289
- Rule of thumb: per-user data on a PPR page lives in a live-lane loader (no `ssr: false`) consumed client-side with `useLoader` under `loading()` or an inline `<Suspense>`, or in a nested promise in bake-lane loader data.
290290

291291
## Pitfalls
292292

293293
- **Handler and loader header writes throw.** On a `ppr` route only middleware writes response headers. A handler or loader calling `ctx.headers.set()`, `cookies().set()`, `ctx.setTheme()`, or the request-context `header()`/`setStatus()` throws on every render: handlers never run on HITs (their output is replayed, so the write would differ between MISS and HIT), and loaders settle after the shell's headers have flushed. Move the write into route middleware, which runs on every request including HITs. The one exception: a handler that calls `ctx.dynamic()` first may write its own headers, because that render never HITs.
294294
- **A pending handler promise expected to be a hole** — it is not. A promise the handler passes under `<Suspense>`, an async server component, or a promise nested in a handler's handle push is awaited at capture and served frozen on every HIT. Move per-request data into a live-lane loader read with `useLoader` under `loading()` or an inline `<Suspense>`.
295-
- **A request-scoped read the capture waits for** (`cookies()`, `headers()`, a `{ cache: false }` variable, `ctx.dynamic()`) — the capture is refused (warned once per key) and the route keeps serving MISSes. Move the read onto the live lane: a loader without `ssr: false`, read under `loading()` or an inline `<Suspense>`.
295+
- **A request-scoped read the capture waits for** (`cookies()`, `headers()`, `ctx.request.headers`, a `{ cache: false }` variable, `ctx.dynamic()`) — the capture is refused (warned once per key) and the route keeps serving MISSes. Move the read onto the live lane: a loader without `ssr: false`, read under `loading()` or an inline `<Suspense>`.
296296
- **A loader a handler awaits (`await ctx.use(Loader)`) that reads `cookies()` or `headers()`** — refuses the capture like any other read the capture waits for: every request is `x-rango-shell: MISS`, and the warning names the loader. Register the loader with `loading()` and read it with `useLoader` instead. On a route without `ppr`, `cache()` still allows it.
297297
- **A bake-lane container that must be fresh per document GET** — it is snapshot-pinned for the shell's lifetime by design. Use the live lane (drop `ssr: false`) or a nested promise.
298298
- **Handler output or a bake-lane loader slower than `ppr.captureTimeout` (15s by default)** — the capture stores nothing rather than a partial shell. Make the slow part cheaper with `cache()`/`"use cache"`, move it into a live loader, or raise the budget.

‎apps/docs/content/docs/rango/guides/use-cache.mdx‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,7 @@ The guards are correctness-first: anything that would bake one user's request in
104104
| Call | Inside `"use cache"` | Why |
105105
| ----------------------------------------------------------------------------------------------------------------------- | -------------------- | -------------------------------------------------------------------------------- |
106106
| `cookies()`, `headers()` | Throws | Per-request values aren't in the cache key — one user's data would serve another |
107+
| `ctx.request.headers` (any `ctx` passed in), `getRequestContext().cookie()` / `.cookies()` | Throws | Same reason: a `ctx` or `Request` argument is keyed by its route and URL only |
107108
| `ctx.set()`, `ctx.headers.set()` (and the other mutating `Headers` methods), `ctx.setTheme()`, `ctx.setLocationState()` | Throws | Effects are lost on a hit (the body is skipped) |
108109
| Request-context writers: `header()`, `setCookie()`, `deleteCookie()`, `setStatus()`, `onResponse()` | Throws | Same reason |
109110
| `ctx.get()` | Allowed | It's a read |
@@ -116,8 +117,14 @@ For cookie- or header-dependent data, extract the value first and pass it as an
116117
```ts
117118
const locale = cookies().get("locale")?.value ?? "en";
118119
const data = await getCachedData(locale); // locale is now in the cache key
120+
121+
// the same for a header read from ctx.request
122+
const language = ctx.request.headers.get("accept-language") ?? "en";
123+
const greeting = await getGreeting(language);
119124
```
120125

126+
A `ctx` or `Request` argument keys the entry by its route and URL only. `ctx.request.clone()` is guarded like `ctx.request.headers`. `fetch(ctx.request)` and `new Request(ctx.request)` don't throw, but the guard can't see through them: a fetch forwards the visitor's `Cookie` and `Authorization`, so its response is per visitor, and the copy's headers are the visitor's. Don't make either inside a cached body; fetch outside it, or pass the values the fetch depends on in as arguments.
127+
121128
And keep ctx side effects outside the cached function:
122129

123130
```tsx

‎docs/design/caching.md‎

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -922,8 +922,27 @@ Response directives (`invalidateClientCache()`, `keepClientCache()`) and cookie
922922
writes record nothing: a `key()` cannot make a skipped body's side effect
923923
reach a HIT.
924924

925-
What stays out of reach, the same as for `"use cache"`: raw reads
926-
(`ctx.request.headers`, `getRequestContext().cookie()`), and a value computed
925+
The raw reads record too (#976): `ctx.request.headers` is an own getter on
926+
the request every ctx exposes (`guardRequestHeaders`,
927+
`src/server/cookie-store.ts`, over `shadowRequestHeaders`,
928+
`src/server/request-headers.ts`), and `getRequestContext().cookie()` /
929+
`.cookies()` call `guardRawCookieRead`; both go through `guardIdentityRead`
930+
and record at the access. The router's own header reads go through
931+
`requestHeaders()`, and the cookies() store through the unguarded
932+
`_readCookie()` / `_readCookies()`, so neither records.
933+
934+
A cache's own callbacks record nothing and refuse nothing
935+
(`runIdentityExempt`, `src/cache/cache-exec-scope.ts`): `key()`, a store
936+
`keyGenerator` (`resolveCacheKey`, `src/cache/cache-policy.ts`),
937+
`condition()` and a `tags()` function (`resolveTagsOption`) pick or label
938+
the entry; their reads are never rendered. So does `onError`
939+
(`invokeOnError`), which only observes. The exemption is async-local, so a
940+
`"use cache"` body (`runWithCacheExecScope`), a loader body
941+
(`runInsideLoaderBodyScope`) and a funnel (`runWithStore`) end it on entry:
942+
a `key()` that awaited a cached function reading `cookies()` stored the
943+
first visitor's cookie and served it to the next.
944+
945+
What stays out of reach, the same as for `"use cache"`: a value computed
927946
outside any loader execution and handed in, such as a per-request memo a
928947
handler filled from `cookies()` before the loader awaited it. The read ran in
929948
no loader's set, so nothing links it to the fill.

‎docs/design/shell-fast-path.md‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -96,15 +96,18 @@ already encodes the purity contract:
9696
Fizz errors do) but which calls the same `captureAndStoreShell`. The
9797
document cache applies the same rule to a whole response.
9898
- The capture guard refuses captures that read request-scoped data
99-
(`cookies()`, `headers()`, `ctx.get` of a `createVar({ cache: false })`
100-
variable) or call `ctx.dynamic()`, anywhere the capture waits: a handler, a
99+
(`cookies()`, `headers()`, `ctx.request.headers`,
100+
`getRequestContext().cookie()` / `.cookies()`, `ctx.get` of a
101+
`createVar({ cache: false })` variable) or call `ctx.dynamic()`, anywhere
102+
the capture waits: a handler, a
101103
promise it passes or pushes, an async server component, a bake-lane loader,
102104
and a loader a handler awaits (`guardIdentityRead`,
103105
`src/server/context.ts`; `refuseOnCaptureGuard`, `src/rsc/shell-capture.ts`).
104106
So an entry never encodes a handler that branches on the requester. A
105-
normal `ctx.get()` value and raw `ctx.request.headers` reads are not guarded:
106-
they bake, and shell material is shared per host+URL and request partition
107-
(the route's `cache({ key })` or the store's `keyGenerator`).
107+
normal `ctx.get()` value is not guarded: it bakes, and shell material is
108+
shared per host+URL and request partition (the route's `cache({ key })` or
109+
the store's `keyGenerator`, which read the request freely at capture too,
110+
`runIdentityExempt`).
108111
- The handler layer must settle within `ppr.captureTimeout` (default 15s). A
109112
capture whose handler output is still pending at the deadline stores nothing.
110113
- Per-REQUEST divergence (auth walls, entitlement) lives in middleware —

0 commit comments

Comments
 (0)