Skip to content

Commit b8d95f3

Browse files
committed
fix(http): narrow Host to the keyed URL authority
1 parent 623d714 commit b8d95f3

6 files changed

Lines changed: 75 additions & 8 deletions

File tree

‎.agents/http/key.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ Apply the method component to **both** key branches. A custom `getKey` defines c
2222

2323
Without authority, one handler instance that serves several hostnames stores one entry per path for all hosts. This is a normal nitro/h3 virtual-host deployment. Tenant A's rendering could be served to tenant B. h3#1524 finding #2 found this cross-application body leak. Per-instance storage closed it between processes but not between hosts in one instance. An attacker-controlled `Host` could also enter an absolute URL in a rendered canonical link, `Location`, or password-reset link. The shared key then stored that URL and advertised synthesized `s-maxage` to shared CDNs. The old mitigation, `varies: ["host"]`, was disabled by default. It also did nothing on adapters that omit `Host` from `req.headers`.
2424

25-
Derive authority from `event.url`, which the adapter resolved. **Never** read it from the `Host` header. If an adapter builds `url` from that header, a reverse proxy must still normalize it. Put authority in the hashed component, not in the human-readable `_pathname` prefix. `_pathname` exists only for debugging. Hash authority and `_path` as a **tuple** so no code can interpret the boundary in two ways. An opaque-scheme pathname does not need to start with `/`. This was a breaking key change, so GET keys moved once.
25+
Derive authority from `event.url`, which the adapter resolved. **Never** read it from the `Host` header. Narrowing closes the reverse gap by rewriting the handler-visible `Host` to this authority's host; see `.agents/http/request.md`. If an adapter builds `url` from that header, a reverse proxy must still normalize it. Put authority in the hashed component, not in the human-readable `_pathname` prefix. `_pathname` exists only for debugging. Hash authority and `_path` as a **tuple** so no code can interpret the boundary in two ways. An opaque-scheme pathname does not need to start with `/`. This was a breaking key change, so GET keys moved once.
2626

2727
`authority(url)` prefers `url.origin` because it canonicalizes values by lowercasing the host and removing a default port. For every **opaque** origin, `url.origin` is the literal string `"null"`. This includes non-special schemes that contain a real authority but do not expose it. For example, `new URL("x-proxy://a.example/p").origin === "null"`, as it does for `b.example`. In this case, use `${protocol}//${host}`. Otherwise, the cross-host collision returns. Authority-less schemes such as `file:`, `data:`, and `about:` use one constant per scheme. This is correct because their identity is entirely in the path, which the tuple also hashes.
2828

‎.agents/http/request.md‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ Return bypassed responses without changes. `serialize` runs outside the resolver
1616

1717
## What the handler sees
1818

19-
The header filter is an **allowlist**. A header reaches the handler only when it appears in `keyHeaderNames`, is `cookie` under the three-way rule below, or appears in `safeHeaderNames`. Remove every other header on cacheable calls.
19+
The header filter is an **allowlist**. A header reaches the handler only when it appears in `keyHeaderNames`, is `cookie` under the three-way rule below, or appears in `safeHeaderNames`. Remove every other header on cacheable calls. `host` is the one rewritten name: narrowing replaces its value with the keyed URL authority.
2020

2121
Forward `varies` headers. Their values are part of the key, so the handler can safely read them. Reading them is the reason to declare them. Earlier code removed declared `varies` headers instead of forwarding them. For example, `varies: ["accept-language"]` produced separate keys and correct `Vary`, but every entry contained the default rendering. Correct forwarding was therefore a breaking behavior change.
2222

@@ -30,10 +30,17 @@ This rule is the request-side counterpart to `hasUnkeyedVary` in `.agents/http/r
3030

3131
`filters.ts` defines these exemptions beside the cookie and query filters. No module may create its own list. Each exempt header cannot vary a rendering and cannot usefully be placed in `varies`:
3232

33-
- **`host`** is already covered by the URL authority that `resolveKey` hashes.
3433
- **`if-none-match` / `if-modified-since`** remain visible because `defaultHandleCacheHeaders` reads them from `event.req` in `http/index.ts` after narrowing replaces that request. If narrowing removed them, 304 responses worked on a HIT but never on a MISS. They are safe to forward. The only conditional responses that a handler can derive from them are 304 and 412, and those statuses are not in `cacheableStatuses`. The cache never stores such output.
3534
- **`traceparent`, `tracestate`, `x-request-id`, `x-correlation-id`** support logging and trace propagation. They are unique per request by design. Adding one to `varies` would create one entry per request, so no useful keyed configuration exists. A handler that renders one into output creates data that no cache key can cover.
3635

36+
### `host`
37+
38+
`host` is **not** in `safeHeaderNames`. Narrowing removes the raw header and sets `host` to `(event.url ?? new URL(event.req.url)).host` — the host component of the very authority `resolveKey` hashes. A handler that renders a canonical link, an absolute asset URL, or a `Location` from `host` therefore renders from keyed data by construction.
39+
40+
The old exemption assumed the two always agree. They agree only on adapters that build the URL _from_ `Host`. An adapter that resolves `event.url` from the connection, from a fixed base, or from a trusted proxy header leaves `Host` attacker-controlled and unkeyed. `Host: a.example` and `Host: b.example` on one resolved authority then shared an entry, and the first tenant's rendering was replayed under a synthesized `max-age` with no `Vary`. This is the same defect that `x-forwarded-host` has, reached through the one header the allowlist still exempted.
41+
42+
Normalizing, rather than removing, keeps host-dependent rendering working on the adapters where it was already correct. An authority-less URL (`file:`, `data:`) has no host to give, so the handler sees none. `varies: ["host"]` still puts `host` in `keyHeaderNames`; the raw header is then keyed, so narrowing forwards it unchanged and skips normalization.
43+
3744
Do **not** exempt `user-agent` or `baggage`. Device and bot branching commonly use `user-agent`. OTel `baggage` is designed for application values such as tenant IDs and feature flags. This differs from the opaque `traceparent` and `tracestate` pair. Declare both headers in `varies` when they affect output.
3845

3946
### Cookies (request side)

‎docs/5.handler.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,8 @@ The request **origin** is part of the automatically generated key. The origin in
115115
116116
The origin comes from `event.url`, or from `new URL(event.req.url)` when `event.url` is not available. It is the value that your adapter resolved, not the raw `Host` request header. Some adapters build the URL _from_ `Host`, so these values match. A reverse proxy before your app must still be trusted to normalize `Host` and `X-Forwarded-Host`.
117117
118+
Because only the resolved origin is in the key, ocache also **rewrites the `Host` header** that your handler reads to the host of that origin. A handler that builds a canonical link or an absolute URL from `Host` therefore builds it from a value the key covers, on every adapter. Declare `varies: ["host"]` if you need the raw header instead; the value then becomes part of the key and appears in `Vary`.
119+
118120
> [!NOTE]
119121
> A custom [`getKey`](/guide/query-params#edge-cases) replaces the full automatic key, including the origin. If your handler renders host-dependent content, add the origin to your key. Examples include canonical links, absolute asset URLs, and `Location`.
120122
@@ -176,7 +178,7 @@ You can use either of these fixes:
176178
- **`varies: ["x-api-key"]`** — the header becomes part of the entry key and reaches the handler. ocache also advertises it in the response `Vary`. Each distinct value gets one entry.
177179
- **[`shouldBypassCache`](#cacheable-requests)** — keep these requests out of the cache. A bypassed request reaches the handler unchanged.
178180
179-
ocache does not remove a small set of headers because a cache key cannot usefully cover them. These are `Host`, which the URL authority already covers; `If-None-Match` and `If-Modified-Since`, which ocache uses for [`304`](#conditional-requests--304); and the trace headers `traceparent`, `tracestate`, `X-Request-Id`, and `X-Correlation-Id`. `User-Agent` is **not** exempt. Output for different devices or bots needs separate keys. Add `User-Agent` to `varies` if you render from it.
181+
ocache does not remove a small set of headers because a cache key cannot usefully cover them. These are `If-None-Match` and `If-Modified-Since`, which ocache uses for [`304`](#conditional-requests--304), and the trace headers `traceparent`, `tracestate`, `X-Request-Id`, and `X-Correlation-Id`. `Host` also stays visible, but with the [resolved origin's host](#multi-host-deployments) as its value rather than the raw one. `User-Agent` is **not** exempt. Output for different devices or bots needs separate keys. Add `User-Agent` to `varies` if you render from it.
180182
181183
> [!NOTE]
182184
> ocache narrows only cacheable (`GET` and `HEAD`) requests. It narrows only the request that the handler receives. Your middleware, framework, and runtime still receive the original request.

‎src/http/filters.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,14 @@ import type { HandlerConfig } from "./config.ts";
55
import type { HTTPEvent } from "../types.ts";
66

77
/**
8-
* Headers that remain visible without separate key components.
8+
* Headers that remain visible unchanged without separate key components.
99
*
10-
* URL authority already covers `host`.
1110
* Conditional headers can produce only non-storable responses.
1211
* Trace headers support propagation but must not affect rendered output.
12+
*
13+
* `host` is not one of them: `request.ts` replaces it with the keyed URL authority.
1314
*/
1415
export const safeHeaderNames = new Set([
15-
"host",
1616
"if-modified-since",
1717
"if-none-match",
1818
"traceparent",

‎src/http/request.ts‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,10 +35,19 @@ export function narrowRequest<E extends HTTPEvent>(
3535

3636
const { keyHeaderNames, allowedCookieNames, allowedQueryNames } = config;
3737

38+
// The same URL `resolveKey` derives the keyed authority from.
39+
const _url = event.url ?? new URL(event.req.url);
40+
const _hostIsKeyed = keyHeaderNames.includes("host");
41+
3842
// Remove every header that is neither keyed nor explicitly safe.
3943
const filteredHeaders = [...event.req.headers.entries()].flatMap(([key, value]) => {
4044
const name = key.toLowerCase();
4145
if (name !== "cookie") {
46+
// Undeclared `host` is covered by the keyed authority, not by its raw value,
47+
// which the adapter may never have resolved from; replace it below.
48+
if (name === "host" && !_hostIsKeyed) {
49+
return [];
50+
}
4251
return keyHeaderNames.includes(name) || safeHeaderNames.has(name)
4352
? [[key, value] as [string, string]]
4453
: [];
@@ -50,11 +59,14 @@ export function narrowRequest<E extends HTTPEvent>(
5059
const cookie = filterCookie(value, allowedCookieNames);
5160
return cookie ? [["cookie", cookie] as [string, string]] : [];
5261
});
62+
// An authority-less URL (`file:`, `data:`) leaves the handler no host at all.
63+
if (!_hostIsKeyed && _url.host) {
64+
filteredHeaders.push(["host", _url.host]);
65+
}
5366

5467
// Remove query values that the key does not cover.
5568
let _reqUrl = event.req.url;
5669
if (allowedQueryNames) {
57-
const _url = event.url ?? new URL(event.req.url);
5870
const _filteredUrl = new URL(_url);
5971
_filteredUrl.search = filteredSearch(config, event, _url);
6072
_reqUrl = _filteredUrl.href;

‎test/index.test.ts‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5432,6 +5432,52 @@ describe("defineCachedHandler", () => {
54325432
expect(await b.text()).toBe("site:canonical");
54335433
});
54345434

5435+
it("normalizes host to the keyed URL authority instead of the raw header", async () => {
5436+
const seen: (string | null)[] = [];
5437+
const path = uniquePath();
5438+
const handler = defineCachedHandler(
5439+
(event) => {
5440+
const host = event.req.headers.get("host");
5441+
seen.push(host);
5442+
return new Response(`site:${host ?? "canonical"}`);
5443+
},
5444+
{ maxAge: 10 },
5445+
);
5446+
5447+
// `makeEvent` resolves every URL to `http://localhost`, the shape of an adapter that
5448+
// builds `event.url` from the connection (or a fixed base) rather than from `Host`. Only
5449+
// that authority is in the key, so a raw `Host` reaching the handler is the h3#1524
5450+
// cross-tenant replay through the one header the allowlist still exempts.
5451+
const a = (await handler(makeEvent(path, { headers: { host: "a.example" } }))) as Response;
5452+
const b = (await handler(makeEvent(path, { headers: { host: "b.example" } }))) as Response;
5453+
5454+
expect(seen).toEqual(["localhost"]);
5455+
expect(await a.text()).toBe("site:localhost");
5456+
expect(await b.text()).toBe("site:localhost");
5457+
});
5458+
5459+
it("forwards the raw host when varies declares it, which keys the value", async () => {
5460+
const seen: (string | null)[] = [];
5461+
const path = uniquePath();
5462+
const handler = defineCachedHandler(
5463+
(event) => {
5464+
const host = event.req.headers.get("host");
5465+
seen.push(host);
5466+
return new Response(`site:${host ?? "canonical"}`);
5467+
},
5468+
{ maxAge: 10, varies: ["host"] },
5469+
);
5470+
5471+
const a = (await handler(makeEvent(path, { headers: { host: "a.example" } }))) as Response;
5472+
const b = (await handler(makeEvent(path, { headers: { host: "b.example" } }))) as Response;
5473+
5474+
// Declared ⇒ keyed ⇒ visible unchanged, the same contract every `varies` header has.
5475+
expect(seen).toEqual(["a.example", "b.example"]);
5476+
expect(await a.text()).toBe("site:a.example");
5477+
expect(await b.text()).toBe("site:b.example");
5478+
expect(b.headers.get("vary")).toContain("host");
5479+
});
5480+
54355481
it("forwards host and the propagation headers, but not user-agent or baggage", async () => {
54365482
const seen: Array<Record<string, string | null>> = [];
54375483
const path = uniquePath();

0 commit comments

Comments
 (0)