Skip to content

Commit 474ac29

Browse files
committed
fix(node): make send-failure recovery unable to throw
1 parent 4052594 commit 474ac29

3 files changed

Lines changed: 176 additions & 39 deletions

File tree

‎src/adapters/_node/adapter.ts‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import type {
88
import type { TrustProxyOption } from "../../_trust-proxy.ts";
99
import { fetchNodeHandler } from "../node.ts";
1010
import { NodeRequest } from "./request.ts";
11-
import { sendNodeResponse } from "./send.ts";
11+
import { handleSendError, sendNodeResponse } from "./send.ts";
1212

1313
export type AdapterMeta = {
1414
__nodeHandler?: NodeHttpHandler;
@@ -35,8 +35,8 @@ export function toNodeHandler(
3535
});
3636
const res = handler(request);
3737
return res instanceof Promise
38-
? res.then((resolvedRes) => sendNodeResponse(nodeRes, resolvedRes))
39-
: sendNodeResponse(nodeRes, res);
38+
? res.then((resolvedRes) => send(nodeRes, resolvedRes))
39+
: send(nodeRes, res);
4040
}
4141

4242
(convertedNodeHandler as AdapterMeta).__fetchHandler = handler;
@@ -45,6 +45,18 @@ export function toNodeHandler(
4545
return convertedNodeHandler;
4646
}
4747

48+
/**
49+
* `sendNodeResponse` reports a serialization failure (e.g. an invalid status code
50+
* or header value in `writeHead`) by rejecting. The handler returned here is
51+
* normally mounted on `node:http`/connect, which ignores its return value, so
52+
* nothing would handle that rejection and the default
53+
* `--unhandled-rejections=throw` takes the process down (#290). Answer a bare 500
54+
* and keep serving instead, matching what `serve()` does on the same failure.
55+
*/
56+
function send(nodeRes: NodeServerResponse, webRes: Response): Promise<void> {
57+
return sendNodeResponse(nodeRes, webRes).catch((error) => handleSendError(nodeRes, error));
58+
}
59+
4860
/**
4961
* Converts a Node.js HTTP handler into a Fetch API handler.
5062
*

‎src/adapters/_node/send.ts‎

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,12 @@ export function sendNodeResponseDetached(
4747
}
4848
}
4949

50-
function handleSendError(nodeRes: NodeServerResponse, error: unknown, silent?: boolean): void {
50+
/** @internal */
51+
export function handleSendError(
52+
nodeRes: NodeServerResponse,
53+
error: unknown,
54+
silent?: boolean,
55+
): void {
5156
// A synchronous throw here is almost always a serialization bug (e.g. an
5257
// invalid header name/value passed to `writeHead`). Without a diagnostic the
5358
// client just sees a bare 500 with no way to trace the cause. Surface the
@@ -98,6 +103,17 @@ function failResponse(nodeRes: NodeServerResponse): void {
98103
nodeRes.destroy();
99104
} else {
100105
nodeRes.statusCode = 500;
106+
// `writeHead` assigns `statusMessage` *before* validating it, so a throw from
107+
// an invalid reason phrase leaves the bad value behind on the response.
108+
// `end()` re-enters `writeHead` via `_implicitHeader()`, so without this reset
109+
// the recovery path throws the same error again -- out of the catch that was
110+
// meant to contain it, and fatally (#290). Empty lets Node fill in the
111+
// default phrase for the new status code.
112+
// HTTP/2 has no reason phrase (touching `statusMessage` there only emits a
113+
// process warning) and `writeHead` never sets one for it.
114+
if (nodeRes.req?.httpVersion !== "2.0") {
115+
nodeRes.statusMessage = "";
116+
}
101117
nodeRes.end();
102118
}
103119
}
@@ -160,11 +176,32 @@ function writeHead(
160176
nodeRes.writeHead(status, rawHeaders);
161177
} else {
162178
// @ts-expect-error
163-
nodeRes.writeHead(status, statusText, rawHeaders);
179+
nodeRes.writeHead(status, safeStatusText(statusText), rawHeaders);
164180
}
165181
}
166182
}
167183

184+
// Anything outside the chars Node accepts in a reason phrase (RFC 9110
185+
// `reason-phrase`, plus the deprecated `obs-text` range Node still allows).
186+
const INVALID_REASON_PHRASE_RE = /[^\t\u0020-\u007E\u0080-\u00FF]/g;
187+
188+
/**
189+
* Strips characters that are invalid in a status line reason phrase.
190+
*
191+
* `FastResponse` skips the `statusText` validation native `Response` does in its
192+
* constructor (kept out for speed, see #262), so a CR/LF can reach the wire here.
193+
* Node throws `ERR_INVALID_CHAR` for it -- fatally before #290 -- and runtimes
194+
* that don't validate would emit a split response instead. Sanitize at the write
195+
* boundary so neither is possible. Untouched for the common empty phrase.
196+
*/
197+
function safeStatusText(statusText: string): string {
198+
// A non-string phrase is left alone: `writeHead` ignores it and fills in the
199+
// default phrase for the status code.
200+
return typeof statusText === "string" && statusText
201+
? statusText.replace(INVALID_REASON_PHRASE_RE, "")
202+
: statusText;
203+
}
204+
168205
function endNodeResponse(nodeRes: NodeServerResponse, detached?: boolean): Promise<void> | void {
169206
if (detached) {
170207
nodeRes.end();

‎test/node-error-paths.test.ts‎

Lines changed: 122 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,48 +1,51 @@
1+
import { createServer } from "node:http";
12
import { afterEach, describe, expect, test } from "vitest";
2-
import { serve } from "../src/adapters/node.ts";
3+
import { FastResponse, serve, toNodeHandler } from "../src/adapters/node.ts";
4+
import type { NodeHttp1Handler, ServerRequest } from "../src/types.ts";
35
import { addExecUnhandledThrowTests } from "./_error-tests.ts";
46

7+
// Shared by the suites below: each captures process-level errors to assert that
8+
// none escape the adapter.
9+
let restore: (() => void) | undefined;
10+
11+
afterEach(() => {
12+
restore?.();
13+
restore = undefined;
14+
});
15+
16+
/** Captures (and swallows) process-level errors raised during the test. */
17+
function captureProcessErrors(event: "uncaughtException" | "unhandledRejection"): unknown[] {
18+
const captured: unknown[] = [];
19+
const onError = (error: unknown) => captured.push(error);
20+
process.prependListener(event, onError);
21+
restore = () => process.removeListener(event, onError);
22+
return captured;
23+
}
24+
25+
async function withServer(
26+
handler: (req: ServerRequest) => Response | Promise<Response>,
27+
fn: (url: string) => Promise<void>,
28+
) {
29+
// `silent` also gates the adapter's error log: these throws are intentional
30+
// and would only add noise to the vitest output.
31+
const server = serve({ hostname: "localhost", port: 0, silent: true, fetch: handler });
32+
await server.ready();
33+
try {
34+
await fn(server.url!);
35+
} finally {
36+
await server.close(true);
37+
}
38+
}
39+
540
// F9 (error paths): with no `error` option the `errorPlugin` no-ops, so the
641
// adapter itself is the last line of defense for a handler that fails. It
742
// answers a bare 500 and keeps serving, matching the Bun/Deno runtimes (see
843
// `test/_error-tests.ts` for those counterparts).
944
//
1045
// Before #244 the failure escaped the request listener as a process-level
1146
// `uncaughtException`/`unhandledRejection` -- fatal for an unguarded process --
12-
// and left the client socket hanging until it timed out. Each test captures
13-
// process-level errors to assert none escape.
47+
// and left the client socket hanging until it timed out.
1448
describe("node adapter unhandled errors (F9)", () => {
15-
let restore: (() => void) | undefined;
16-
17-
afterEach(() => {
18-
restore?.();
19-
restore = undefined;
20-
});
21-
22-
/** Captures (and swallows) process-level errors raised during the test. */
23-
function captureProcessErrors(event: "uncaughtException" | "unhandledRejection"): unknown[] {
24-
const captured: unknown[] = [];
25-
const onError = (error: unknown) => captured.push(error);
26-
process.prependListener(event, onError);
27-
restore = () => process.removeListener(event, onError);
28-
return captured;
29-
}
30-
31-
async function withServer(
32-
handler: (req: Request) => Response | Promise<Response>,
33-
fn: (url: string) => Promise<void>,
34-
) {
35-
// `silent` also gates the adapter's error log: these throws are intentional
36-
// and would only add noise to the vitest output.
37-
const server = serve({ hostname: "localhost", port: 0, silent: true, fetch: handler });
38-
await server.ready();
39-
try {
40-
await fn(server.url!);
41-
} finally {
42-
await server.close(true);
43-
}
44-
}
45-
4649
for (const [name, event, fail] of [
4750
[
4851
"sync throw",
@@ -85,6 +88,91 @@ describe("node adapter unhandled errors (F9)", () => {
8588
}
8689
});
8790

91+
// https://github.com/h3js/srvx/issues/290: a malformed response must not be able
92+
// to escalate to a process exit, and the recovery path must not be able to throw.
93+
describe("node adapter malformed responses (#290)", () => {
94+
const injected = "OK\r\nX-Inj: pwned";
95+
96+
test("invalid statusText is sanitized instead of crashing", async () => {
97+
const captured = captureProcessErrors("uncaughtException");
98+
99+
await withServer(
100+
() => new FastResponse("body", { statusText: injected }),
101+
async (url) => {
102+
const res = await fetch(url, { signal: AbortSignal.timeout(1000) });
103+
expect(res.status).toBe(200);
104+
expect(await res.text()).toBe("body");
105+
// CR/LF stripped from the reason phrase, so the trailer can't be parsed
106+
// as a header of its own (response splitting).
107+
expect(res.statusText).toBe("OKX-Inj: pwned");
108+
expect(res.headers.get("x-inj")).toBe(null);
109+
110+
await new Promise((r) => setTimeout(r, 50));
111+
expect(captured).toEqual([]);
112+
},
113+
);
114+
});
115+
116+
// `writeHead` assigns `statusMessage` before validating it, so a failed call
117+
// leaves the bad value behind. Before the fix `failResponse()` reset only the
118+
// status code, and its `end()` threw ERR_INVALID_CHAR a second time -- out of
119+
// the catch that was supposed to contain it.
120+
test("recovery survives a poisoned statusMessage", async () => {
121+
const captured = captureProcessErrors("uncaughtException");
122+
123+
await withServer(
124+
(req) => {
125+
if (new URL(req.url).pathname === "/throw") {
126+
req.runtime!.node!.res!.statusMessage = injected;
127+
throw new Error("unhandled error after poisoning statusMessage");
128+
}
129+
return new Response("ok");
130+
},
131+
async (url) => {
132+
const res = await fetch(url + "throw", { signal: AbortSignal.timeout(1000) });
133+
expect(res.status).toBe(500);
134+
// Reset to empty, so Node fills in the phrase for the new status code.
135+
expect(res.statusText).toBe("Internal Server Error");
136+
expect(res.headers.get("x-inj")).toBe(null);
137+
expect(await res.text()).toBe("");
138+
139+
await new Promise((r) => setTimeout(r, 50));
140+
expect(captured).toEqual([]);
141+
142+
// The server keeps serving.
143+
expect((await fetch(url)).status).toBe(200);
144+
},
145+
);
146+
});
147+
148+
// node:http ignores the request listener's return value, so a rejection from
149+
// `sendNodeResponse` has no consumer and would surface as a fatal
150+
// `unhandledRejection` -- the `serve()` path answers 500 for the same failure.
151+
test("toNodeHandler answers 500 for an unserializable response", async () => {
152+
const captured = captureProcessErrors("unhandledRejection");
153+
154+
const server = createServer(
155+
toNodeHandler(() => new FastResponse("x", { status: 99 })) as NodeHttp1Handler,
156+
);
157+
// Intentional failure: silence the adapter's diagnostic for this test.
158+
const consoleError = console.error;
159+
console.error = () => {};
160+
await new Promise<void>((resolve) => server.listen(0, "localhost", resolve));
161+
try {
162+
const { port } = server.address() as { port: number };
163+
const res = await fetch(`http://localhost:${port}/`, { signal: AbortSignal.timeout(1000) });
164+
expect(res.status).toBe(500);
165+
expect(await res.text()).toBe("");
166+
167+
await new Promise((r) => setTimeout(r, 50));
168+
expect(captured).toEqual([]);
169+
} finally {
170+
console.error = consoleError;
171+
await new Promise((resolve) => server.close(resolve));
172+
}
173+
});
174+
});
175+
88176
// The in-process tests above run inside vitest, which installs its own
89177
// process-level error handlers -- so they can prove no error escapes, but not
90178
// that an *unguarded* process survives one. Spawn the shared fixture to check

0 commit comments

Comments
 (0)