diff --git a/src/js/node/http2.ts b/src/js/node/http2.ts index ff7409618401..d78571204ad4 100644 --- a/src/js/node/http2.ts +++ b/src/js/node/http2.ts @@ -284,20 +284,9 @@ function getPackedSettings(settings?: any): Buffer { return buf; } -function getUnpackedSettings(buf?: any, options?: any): any { - if (buf === undefined) { - return { ...kDefaultSettings }; - } - - if (!Buffer.isBuffer(buf) && !isTypedArray(buf)) { - { - // node renders this as instance-of (class names), not of-type. - const err = new TypeError( - `The "buf" argument must be an instance of Buffer or TypedArray. Received ` + receivedValueLabel(buf), - ); - err.code = "ERR_INVALID_ARG_TYPE"; - throw err; - } +function getUnpackedSettings(buf: any, options?: any): any { + if (!isTypedArray(buf)) { + throw $ERR_INVALID_ARG_TYPE("buf", ["Buffer", "TypedArray"], buf); } if (buf.length % 6 !== 0) { @@ -3564,18 +3553,10 @@ class ServerHttp2Stream extends Http2Stream { fs.open(path, "r", afterOpen.bind(this, options || {}, headers)); } respondWithFD(fd, headers, options) { - if (typeof fd !== "number") { - // node accepts a FileHandle too; unwrap its descriptor. - if (fd !== null && typeof fd === "object" && typeof fd.fd === "number") { - fd = fd.fd; - } else { - const err = new TypeError( - `The "fd" argument must be of type number or an instance of FileHandle.` + - ` Received ${receivedValueLabel(fd)}`, - ); - err.code = "ERR_INVALID_ARG_TYPE"; - throw err; - } + if (fd instanceof FileHandle) { + fd = fd.fd; + } else if (typeof fd !== "number") { + throw $ERR_INVALID_ARG_TYPE("fd", ["number", "FileHandle"], fd); } if (this.destroyed) { throw $ERR_HTTP2_INVALID_STREAM(); @@ -3628,11 +3609,7 @@ class ServerHttp2Stream extends Http2Stream { // stream.end() right after it is a no-op instead of ending the stream before the file. closeWritableForFileResponse(this); } - if (fd instanceof FileHandle) { - fs.fstat(fd.fd, doSendFileFD.bind(this, options, fd, headers)); - } else { - fs.fstat(fd, doSendFileFD.bind(this, options, fd, headers)); - } + fs.fstat(fd, doSendFileFD.bind(this, options, fd, headers)); } additionalHeaders(headers) { if (this.destroyed || this.closed || this.session === undefined) { @@ -4035,17 +4012,6 @@ function assertSingleValueHeaders(headers) { } } -// Renders a received value the way node's determineSpecificType does for error messages. -function receivedValueLabel(value) { - if (value === null) return "null"; - if (typeof value === "object") return "an instance of " + (value.constructor?.name || "Object"); - if (typeof value === "function") return `function ${value.name}`; - if (typeof value === "string") return `type string ('${value}')`; - if (typeof value === "symbol") return `type symbol (${String(value)})`; - if (typeof value === "number") return `type number (${String(value)})`; - return `type ${typeof value} (${JSON.stringify(value)})`; -} - function buildSensitiveNames(headers, sensitives) { const map = {}; if (sensitives) { @@ -6860,9 +6826,8 @@ function performServerHandshake(socket, options = {}) { options = initializeOptions(options); return new ServerHttp2Session(socket, options, undefined); } -function getDefaultSettings() { - // return default settings - return getUnpackedSettings(); +function getDefaultSettings(): any { + return { ...kDefaultSettings }; } Object.defineProperty(connect, promisify.custom, { diff --git a/test/js/node/http2/node-http2.test.js b/test/js/node/http2/node-http2.test.js index 26f4f42a1597..a9393d9fdf04 100644 --- a/test/js/node/http2/node-http2.test.js +++ b/test/js/node/http2/node-http2.test.js @@ -1,4 +1,4 @@ -import { bunEnv, bunExe, isASAN, isCI, isDebug, nodeExe } from "harness"; +import { bunEnv, bunExe, isASAN, isCI, isDebug, nodeExe, tempDir } from "harness"; import { createTest } from "node-harness"; import { AsyncLocalStorage } from "node:async_hooks"; import dc from "node:diagnostics_channel"; @@ -4070,6 +4070,90 @@ it("http2 stream.respond accepts raw-headers arrays; respondWithFD/respondWithFi server.close(); } }); + +// Rejected values paired with how node v26.3.0's ERR_INVALID_ARG_TYPE describes each of them. +const invalidArgTypeCases = [ + [1n, "type bigint (1n)"], + ["a".repeat(40), "type string ('aaaaaaaaaaaaaaaaaaaaaaaaa...')"], + ["it's", `type string ("it's")`], + [Object.create(null), "[Object: null prototype] {}"], + [undefined, "undefined"], + [null, "null"], + [true, "type boolean (true)"], + [{}, "an instance of Object"], + [new DataView(new ArrayBuffer(6)), "an instance of DataView"], +]; + +function collectInvalidArgTypeErrors(cases, invoke) { + return cases.map(([value]) => { + try { + invoke(value); + return "did not throw"; + } catch (err) { + return { name: err.constructor.name, code: err.code, message: err.message }; + } + }); +} + +it("http2 getUnpackedSettings() reports a bad buf argument like node", () => { + expect(collectInvalidArgTypeErrors(invalidArgTypeCases, value => http2.getUnpackedSettings(value))).toEqual( + invalidArgTypeCases.map(([, received]) => ({ + name: "TypeError", + code: "ERR_INVALID_ARG_TYPE", + message: `The "buf" argument must be an instance of Buffer or TypedArray. Received ${received}`, + })), + ); +}); + +it("http2 stream.respondWithFD() reports a bad fd argument like node and accepts a FileHandle", async () => { + using dir = tempDir("http2-respond-with-fd", { "body.txt": "served from a FileHandle" }); + const fileHandle = await fs.promises.open(path.join(String(dir), "body.txt"), "r"); + // Only a real FileHandle stands in for a number; node rejects other objects carrying an fd property. + const cases = [...invalidArgTypeCases, [{ fd: fileHandle.fd }, "an instance of Object"]]; + let errors; + const server = http2.createServer(); + server.on("stream", stream => { + errors = collectInvalidArgTypeErrors(cases, value => stream.respondWithFD(value)); + stream.respondWithFD(fileHandle, { "content-type": "text/plain" }); + }); + let client; + + try { + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(0, resolve); + }); + client = http2.connect(`http://localhost:${server.address().port}`); + + const { promise: finished, resolve, reject } = Promise.withResolvers(); + client.on("error", reject); + const req = client.request({ ":path": "/" }); + req.on("error", reject); + let response; + req.on("response", headers => (response = headers)); + let body = ""; + req.setEncoding("utf8"); + req.on("data", chunk => (body += chunk)); + req.on("end", resolve); + req.end(); + await finished; + + expect(errors).toEqual( + cases.map(([, received]) => ({ + name: "TypeError", + code: "ERR_INVALID_ARG_TYPE", + message: `The "fd" argument must be of type number or an instance of FileHandle. Received ${received}`, + })), + ); + expect(response[":status"]).toBe(200); + expect(body).toBe("served from a FileHandle"); + } finally { + client?.close(); + server.close(); + await fileHandle.close(); + } +}); + it("http2 client.request() on a destroyed or closed session uses the right error codes", async () => { // Node: destroyed session -> ERR_HTTP2_INVALID_SESSION, // closed (GOAWAY-pending) session -> ERR_HTTP2_GOAWAY_SESSION.