Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 10 additions & 45 deletions src/js/node/http2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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, {
Expand Down
79 changes: 78 additions & 1 deletion test/js/node/http2/node-http2.test.js
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -4070,6 +4070,83 @@
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" });
});
await new Promise(resolve => server.listen(0, resolve));
const client = http2.connect(`http://localhost:${server.address().port}`);

try {
const req = client.request({ ":path": "/" });
const response = await new Promise((resolve, reject) => {
req.on("error", reject);
req.on("response", resolve);
req.end();
});
let body = "";
req.setEncoding("utf8");
req.on("data", chunk => (body += chunk));
await new Promise(resolve => req.on("end", resolve));

Check warning on line 4132 in test/js/node/http2/node-http2.test.js

View check run for this annotation

Claude / Claude Code Review

Second await on req 'end' has no error path wired to reject

The second await only wires `resolve` — `req.on("error", reject)` at line 4125 belongs to the first promise, which has already settled on `response`, so a mid-body stream error here is a no-op reject and this await hangs until the runner timeout instead of failing with the actual error. Wire the failure path: `await new Promise((resolve, reject) => { req.on("end", resolve); req.on("error", reject); })`.
Comment thread
claude[bot] marked this conversation as resolved.
Resolved

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.
Expand Down