Skip to content

Commit a11765b

Browse files
committed
fix(node): normalize absolute-form request targets instead of trusting them
1 parent 8d9c958 commit a11765b

7 files changed

Lines changed: 403 additions & 16 deletions

File tree

‎docs/1.guide/05.options.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,17 @@ Real proxies **append** to `X-Forwarded-*`, so the chain grows left-to-right (ou
237237

238238
This is why a spoofed prefix cannot poison `request.ip`: with `trustProxy: "loopback"` and a request carrying `X-Forwarded-For: 9.9.9.9`, the trusted proxy appends the real client address, so the forged `9.9.9.9` is skipped rather than returned. The same model gates the forwarded protocol and host: only the value contributed by the trusted proxy is honored, so an attacker cannot poison `request.url` (e.g. cache keys or password-reset links).
239239

240+
#### Absolute-form request targets
241+
242+
An HTTP/1.1 client may send the request target in absolute-form (`GET http://example.com/path HTTP/1.1`), which [RFC 9112 §3.2.2](https://www.rfc-editor.org/rfc/rfc9112#name-absolute-form) requires origin servers to accept. srvx accepts it and honors its authority in place of `Host`, but rebuilds the URL so it cannot be used to route around the guarantee above:
243+
244+
- The scheme always comes from the transport (and, behind a trusted proxy, `X-Forwarded-Proto`) — a client can never make a plaintext request look like `https:`, or downgrade a TLS request to `http:`.
245+
- The authority is validated exactly like a `Host` header, and replaced with `_invalid_` when it is malformed.
246+
- Any userinfo (`http://user@host/`) is dropped.
247+
- Targets that are not `http:`/`https:` (e.g. `file://`, `ftp://`) are answered with `400`.
248+
249+
So `new URL(request.url).protocol` always reflects the real connection, not the request line.
250+
240251
**Example:**
241252

242253
```js

‎src/adapters/_node/url.ts‎

Lines changed: 50 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,8 +58,56 @@ export class NodeRequestURL extends FastURL {
5858
// Deno. Other non-conforming targets are rejected by the adapter.
5959
super({ protocol, host, pathname: "/*", search: "" });
6060
} else {
61-
// absolute-form (e.g. proxy request)
62-
super(path);
61+
// absolute-form (RFC 9112 §3.2.2), e.g. `GET https://host/p HTTP/1.1`.
62+
// Origin servers MUST accept it and its authority supersedes `Host` — but
63+
// srvx is not a proxy, so it must not become a way around the guarantees
64+
// above. The transport-derived `protocol` stays authoritative (a client
65+
// must never be able to claim `https:` on a plaintext socket, or `http:`
66+
// on TLS), the request-line authority is `HOST_RE`-validated exactly like
67+
// a `Host` header, and userinfo is dropped (`new Request()` throws on a
68+
// URL that includes credentials — see `_request` in ./request.ts, which
69+
// would otherwise turn any such target into an unauthenticated 500).
70+
// `serve()` additionally answers 400 for targets that aren't http(s)
71+
// absolute-form; this branch is what keeps `toNodeHandler`, which has no
72+
// target gate, safe as well.
73+
// (`URL.parse` is unusable here: `engines.node` is >=20.16.0 and
74+
// `URL.parse` only landed in 20.18.)
75+
const target = URL.canParse(path) ? new URL(path) : undefined;
76+
if (target) {
77+
// WHATWG parsing already lowercased the authority and stripped a
78+
// default port; `target.host` excludes any userinfo.
79+
const targetHost = target.host;
80+
// An authority-less target (e.g. `file:///x`, only reachable via
81+
// `toNodeHandler`) falls back to the validated `Host`-derived host.
82+
const targetPath = target.pathname;
83+
super({
84+
protocol,
85+
host: targetHost ? (HOST_RE.test(targetHost) ? targetHost : "_invalid_") : host,
86+
pathname: targetPath ? (targetPath[0] === "/" ? targetPath : `/${targetPath}`) : "/",
87+
search: target.search,
88+
});
89+
} else {
90+
// Unparseable target (`serve()` already answers 400 for these; only
91+
// reachable via `toNodeHandler`, which has no target gate).
92+
super({ protocol, host, pathname: "/", search: "" });
93+
}
6394
}
6495
}
6596
}
97+
98+
/**
99+
* Whether `target` is an absolute-form request-target (RFC 9112 §3.2.2) that srvx
100+
* can serve as an origin server: parseable as a Fetch URL, http(s), and carrying
101+
* an authority.
102+
*
103+
* llhttp delivers any hierarchical `scheme://…` target (`file://`, `ftp://`,
104+
* `zzz://`), so schemes srvx does not serve are answered with 400 per RFC 9110
105+
* §7.4 instead of being silently normalized into an http(s) URL.
106+
*/
107+
export function isValidAbsoluteForm(target: string): boolean {
108+
if (!URL.canParse(target)) {
109+
return false;
110+
}
111+
const url = new URL(target);
112+
return (url.protocol === "http:" || url.protocol === "https:") && url.host !== "";
113+
}

‎src/adapters/node.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { sendErrorResponse, sendNodeResponseDetached } from "./_node/send.ts";
22
import { NodeRequest } from "./_node/request.ts";
3+
import { isValidAbsoluteForm } from "./_node/url.ts";
34
import {
45
fmtURL,
56
resolveTLSOptions,
@@ -69,8 +70,13 @@ class NodeServer implements Server {
6970
// anything that isn't origin-form (/...), absolute-form, or the RFC 9110
7071
// §7.1 asterisk-form (`*`). Bun/Deno reject these at the parser layer;
7172
// Node leaves it to us. (Hot path is a single char compare.)
73+
// Absolute-form must additionally name an http(s) authority: srvx is an
74+
// origin server, not a proxy, so `file://`/`ftp://`/`zzz://` targets —
75+
// which llhttp does deliver — are 400, per RFC 9110 §7.4. The ones that
76+
// pass are normalized in `NodeRequestURL` (transport scheme wins, the
77+
// authority is `HOST_RE`-validated, userinfo is dropped).
7278
const reqUrl = nodeReq.url;
73-
if (reqUrl && reqUrl[0] !== "/" && reqUrl !== "*" && !URL.canParse(reqUrl)) {
79+
if (reqUrl && reqUrl[0] !== "/" && reqUrl !== "*" && !isValidAbsoluteForm(reqUrl)) {
7480
nodeRes.statusCode = 400;
7581
nodeRes.end();
7682
return;

‎test/_tests.ts‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -382,7 +382,31 @@ export function addTests(opts: {
382382
expect(data.pathname).toBe("/bar/baz");
383383
});
384384

385-
// TODO: Write test to make sure it is forbidden for http2/tls (https://github.com/h3js/srvx/issues/236)
385+
// HTTP/2 forbids an absolute-form `:path` outright (nghttp2 answers
386+
// PROTOCOL_ERROR before the handler runs), so absolute-form is an HTTP/1-only
387+
// concern. On HTTP/1 it is a MUST-accept (RFC 9112 §3.2.2); the security
388+
// normalization of its scheme/authority/userinfo is covered by
389+
// test/url.test.ts, test/node-host-header.test.ts and test/node.test.ts.
390+
// (closes https://github.com/h3js/srvx/issues/236)
391+
test.runIf(opts.http2)("absolute URI in :path is rejected by HTTP/2", async () => {
392+
const _url = new URL(url("/"));
393+
const client = http2.connect(_url.origin, { ca: opts.ca });
394+
try {
395+
for (const path of ["https://evil.example.com/x", "http://evil.example.com/x"]) {
396+
const req = client.request({ ":path": path, ":authority": "localhost" });
397+
const error = await new Promise<Error | undefined>((resolve) => {
398+
req.on("response", () => resolve(undefined));
399+
req.on("error", resolve);
400+
req.on("end", () => resolve(undefined));
401+
});
402+
expect(error, path).toBeInstanceOf(Error);
403+
expect((error as any).code, path).toBe("ERR_HTTP2_STREAM_ERROR");
404+
}
405+
} finally {
406+
client.close();
407+
}
408+
});
409+
386410
test.skipIf(opts.http2)("absolute path in request line", async () => {
387411
const _url = new URL(url("/"));
388412

‎test/node-host-header.test.ts‎

Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515

1616
import { afterEach, describe, expect, test } from "vitest";
1717
import http from "node:http";
18+
import net from "node:net";
1819
import { serve } from "../src/adapters/node.ts";
1920
import type { Server } from "../src/types.ts";
2021

@@ -202,3 +203,147 @@ describe("malformed Host header handling", () => {
202203
expect(result.body).toContain(String(port));
203204
});
204205
});
206+
207+
/**
208+
* RFC 9112 §3.2.2 makes absolute-form (`GET http://host/p HTTP/1.1`) a
209+
* MUST-accept for origin servers, and §3.3 says its authority supersedes
210+
* `Host` — but srvx is not a proxy, so the request-line target must not become
211+
* a way around the guarantees `Host` already gets. These assert the invariants
212+
* end-to-end on a plaintext listener with the default `trustProxy: false`.
213+
*/
214+
describe("absolute-form request target", () => {
215+
let server: Server;
216+
217+
afterEach(async () => {
218+
if (server) {
219+
await server.close(true);
220+
}
221+
});
222+
223+
/** Responses are chunked-encoded on the wire; pull the JSON body out. */
224+
function jsonBody(body: string): any {
225+
return JSON.parse(body.match(/\{.*\}/s)![0]);
226+
}
227+
228+
/** Send an arbitrary raw request line (http.request rewrites some of these). */
229+
function rawLine(
230+
port: number,
231+
requestLine: string,
232+
host = "good.example",
233+
): Promise<{ statusCode: number; body: string }> {
234+
return new Promise((resolve, reject) => {
235+
const socket = net.connect(port, "127.0.0.1", () => {
236+
socket.write(`${requestLine}\r\nHost: ${host}\r\nConnection: close\r\n\r\n`);
237+
});
238+
let data = "";
239+
socket.on("data", (chunk) => {
240+
data += chunk.toString();
241+
});
242+
socket.on("end", () => {
243+
const statusLine = data.split("\r\n")[0] || "";
244+
resolve({
245+
statusCode: Number.parseInt(statusLine.split(" ")[1], 10),
246+
body: data.split("\r\n\r\n").slice(1).join("\r\n\r\n"),
247+
});
248+
});
249+
socket.on("error", reject);
250+
socket.setTimeout(2000, () => {
251+
socket.destroy();
252+
reject(new Error("socket timed out"));
253+
});
254+
});
255+
}
256+
257+
async function serveURLInfo(): Promise<number> {
258+
server = serve({
259+
port: 0,
260+
fetch(request) {
261+
// `clone()` builds the native Request, which throws on a URL with
262+
// credentials — a userinfo target used to become an unauthenticated 500.
263+
request.clone();
264+
const url = new URL(request.url);
265+
return new Response(
266+
JSON.stringify({
267+
url: request.url,
268+
protocol: url.protocol,
269+
host: url.host,
270+
origin: url.origin,
271+
username: url.username,
272+
}),
273+
);
274+
},
275+
});
276+
await server.ready();
277+
return getPort(server);
278+
}
279+
280+
test("cannot claim https: on a plaintext socket", async () => {
281+
const port = await serveURLInfo();
282+
const result = await rawLine(port, "GET https://evil.example.com/x HTTP/1.1");
283+
expect(result.statusCode).toBe(200);
284+
const data = jsonBody(result.body);
285+
expect(data.protocol).toBe("http:");
286+
expect(data.origin).toBe("http://evil.example.com");
287+
expect(data.url).toBe("http://evil.example.com/x");
288+
});
289+
290+
test("userinfo is dropped instead of crashing the native Request (500)", async () => {
291+
const port = await serveURLInfo();
292+
const result = await rawLine(port, "GET http://[email protected]/admin HTTP/1.1");
293+
expect(result.statusCode).toBe(200);
294+
const data = jsonBody(result.body);
295+
expect(data.username).toBe("");
296+
expect(data.host).toBe("real.example");
297+
expect(data.url).toBe("http://real.example/admin");
298+
});
299+
300+
test("a HOST_RE-invalid request-line authority becomes _invalid_", async () => {
301+
const port = await serveURLInfo();
302+
const result = await rawLine(port, "GET http://evil.example.com./x HTTP/1.1");
303+
expect(result.statusCode).toBe(200);
304+
expect(jsonBody(result.body).host).toBe("_invalid_");
305+
});
306+
307+
test("non-http(s) schemes are rejected with 400", async () => {
308+
const port = await serveURLInfo();
309+
for (const line of [
310+
"GET file:///etc/passwd HTTP/1.1",
311+
"GET file://hehe/x HTTP/1.1",
312+
"GET ftp://evil.com/ HTTP/1.1",
313+
"GET zzz://evil/x HTTP/1.1",
314+
]) {
315+
expect((await rawLine(port, line)).statusCode, line).toBe(400);
316+
}
317+
});
318+
319+
test("control: x-forwarded-* stays ignored with trustProxy: false", async () => {
320+
const port = await serveURLInfo();
321+
const result = await new Promise<{ statusCode: number; body: string }>((resolve, reject) => {
322+
const socket = net.connect(port, "127.0.0.1", () => {
323+
socket.write(
324+
"GET /foo HTTP/1.1\r\nHost: good.example\r\n" +
325+
"X-Forwarded-Host: evil.example.com\r\nX-Forwarded-Proto: https\r\n" +
326+
"Connection: close\r\n\r\n",
327+
);
328+
});
329+
let data = "";
330+
socket.on("data", (chunk) => {
331+
data += chunk.toString();
332+
});
333+
socket.on("end", () =>
334+
resolve({
335+
statusCode: Number.parseInt((data.split("\r\n")[0] || "").split(" ")[1], 10),
336+
body: data.split("\r\n\r\n").slice(1).join("\r\n\r\n"),
337+
}),
338+
);
339+
socket.on("error", reject);
340+
socket.setTimeout(2000, () => {
341+
socket.destroy();
342+
reject(new Error("socket timed out"));
343+
});
344+
});
345+
expect(result.statusCode).toBe(200);
346+
const data = jsonBody(result.body);
347+
expect(data.url).toBe("http://good.example/foo");
348+
});
349+
});

‎test/node.test.ts‎

Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
import { describe, beforeAll, afterAll } from "vitest";
1+
import { connect as tlsConnect } from "node:tls";
2+
import { describe, beforeAll, afterAll, expect, test } from "vitest";
23
import { fetch, Agent } from "undici";
34
import { addTests } from "./_tests.ts";
45
import { serve, FastResponse } from "../src/adapters/node.ts";
@@ -87,6 +88,59 @@ for (const config of testConfigs) {
8788
});
8889
}
8990

91+
// An absolute-form request target (RFC 9112 §3.2.2) must never define the
92+
// scheme: on a TLS listener a `http://...` target used to downgrade
93+
// `request.url` to `http:`, defeating handler secure-request checks.
94+
describe.skipIf(isDeno || isBun)(`${runtime} (absolute-form over TLS)`, () => {
95+
let server: ReturnType<typeof serve> | undefined;
96+
97+
beforeAll(async () => {
98+
server = serve({
99+
port: 0,
100+
tls: { cert: tls.cert, key: tls.key },
101+
fetch: (request) => new Response(request.url),
102+
});
103+
await server!.ready();
104+
});
105+
106+
afterAll(async () => {
107+
await server!.close(true);
108+
});
109+
110+
function rawTLS(requestLine: string): Promise<string> {
111+
const address = server!.node!.server!.address() as { port: number };
112+
return new Promise((resolve, reject) => {
113+
const socket = tlsConnect(
114+
{ port: address.port, host: "127.0.0.1", rejectUnauthorized: false },
115+
() => {
116+
socket.write(`${requestLine}\r\nHost: good.example\r\nConnection: close\r\n\r\n`);
117+
},
118+
);
119+
let data = "";
120+
socket.on("data", (chunk) => {
121+
data += chunk.toString();
122+
});
123+
socket.on("end", () => resolve(data));
124+
socket.on("error", reject);
125+
socket.setTimeout(3000, () => {
126+
socket.destroy();
127+
reject(new Error("socket timed out"));
128+
});
129+
});
130+
}
131+
132+
test("origin-form keeps https:", async () => {
133+
expect(await rawTLS("GET /foo HTTP/1.1")).toContain("https://good.example/foo");
134+
});
135+
136+
test("an http: absolute-form target cannot downgrade request.url", async () => {
137+
const response = await rawTLS("GET http://evil.example.com/x HTTP/1.1");
138+
expect(response).toMatch(/^HTTP\/1\.1 200 /);
139+
expect(response).toContain("https://evil.example.com/x");
140+
expect(response).not.toContain("http://evil.example.com/x");
141+
});
142+
});
143+
90144
function getHttpClient(h2?: boolean) {
91145
if (!h2) {
92146
return {

0 commit comments

Comments
 (0)