|
| 1 | +import { createServer } from "node:http"; |
1 | 2 | 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"; |
3 | 5 | import { addExecUnhandledThrowTests } from "./_error-tests.ts"; |
4 | 6 |
|
| 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 | + |
5 | 40 | // F9 (error paths): with no `error` option the `errorPlugin` no-ops, so the |
6 | 41 | // adapter itself is the last line of defense for a handler that fails. It |
7 | 42 | // answers a bare 500 and keeps serving, matching the Bun/Deno runtimes (see |
8 | 43 | // `test/_error-tests.ts` for those counterparts). |
9 | 44 | // |
10 | 45 | // Before #244 the failure escaped the request listener as a process-level |
11 | 46 | // `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. |
14 | 48 | 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 | | - |
46 | 49 | for (const [name, event, fail] of [ |
47 | 50 | [ |
48 | 51 | "sync throw", |
@@ -85,6 +88,91 @@ describe("node adapter unhandled errors (F9)", () => { |
85 | 88 | } |
86 | 89 | }); |
87 | 90 |
|
| 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 | + |
88 | 176 | // The in-process tests above run inside vitest, which installs its own |
89 | 177 | // process-level error handlers -- so they can prove no error escapes, but not |
90 | 178 | // that an *unguarded* process survives one. Spawn the shared fixture to check |
|
0 commit comments