Skip to content
54 changes: 51 additions & 3 deletions src/js/node/http2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3688,6 +3688,9 @@ function scheduleSettingsAckGraceNT(session) {
function destroyIfNotDestroyedNT(target) {
if (!target.destroyed) target.destroy();
}
function rethrowUncaught(err) {
throw err;
}
function scheduleDestroyIfNotDestroyed(target) {
if (!target.destroyed) {
setImmediate(destroyIfNotDestroyedNT, target);
Expand Down Expand Up @@ -4918,6 +4921,15 @@ function streamRejectedByGoawaySession(stream: Http2Stream) {
stream.destroy(err);
}
}
// A request that was destroyed while it waited for the connect stays in the queue until the flush.
function hasLivePendingRequest(pendingRequests: Array<{ req: ClientHttp2Stream }> | null) {
if (pendingRequests !== null) {
for (let i = 0; i < pendingRequests.length; i++) {
if (!pendingRequests[i].req.destroyed) return true;
}
}
return false;
}
class ClientHttp2Session extends Http2Session {
/// close indicates that the session is shutting down (close() or destroy() was called)
#closed: boolean = false;
Expand Down Expand Up @@ -5641,13 +5653,31 @@ class ClientHttp2Session extends Http2Session {
this.#authority = needsBrackets ? `[${authorityHost}]:${port}` : `${authorityHost}:${port}`;
}

// An options.settings that validation rejected while the socket was still connecting.
let settingsRejected = false;
let settingsError;
function onConnect() {
// The parser's construction re-enters JS and can drain the tick queue, so a
// connect that fires from that drain arrives before the constructor finished.
if (this.#parser === undefined) {
process.nextTick(onConnect.bind(this));
return;
}
Comment thread
robobun marked this conversation as resolved.
Resolved
// node validates at this point unless the session is destroyed by then. Its close() destroys
// a session with no live request at once. close() here only schedules that destroy.
Comment thread
robobun marked this conversation as resolved.
Resolved
const destroyedInNode = this.destroyed || (this.#closed && !hasLivePendingRequest(this.#pendingRequests));
if (settingsRejected && !destroyedInNode) {
// node destroys the socket with the error. Here #onError drops a socket error once close()
// was called, so destroy the session.
Comment thread
robobun marked this conversation as resolved.
Resolved
try {
this.destroy(settingsError);
} catch (e) {
// An 'error' with no listener. The socket layer reports a throw from its connect
// callback on the socket, where this destroyed session no longer listens.
Comment thread
robobun marked this conversation as resolved.
Resolved
process.nextTick(rethrowUncaught, e);
}
return;
Comment thread
robobun marked this conversation as resolved.
Resolved
}
try {
this.#onConnect(arguments);
listener?.$call(this, this);
Expand All @@ -5673,6 +5703,9 @@ class ClientHttp2Session extends Http2Session {
connectOnNextTick = true;
}
} else {
// node builds the tls.connect() options with initializeTLSOptions, which throws for an
// options.settings that is not an object. No socket exists yet at that point.
Comment thread
robobun marked this conversation as resolved.
Resolved
if (protocol === "https:") assertIsObject(options.settings, "options.settings");
Comment thread
robobun marked this conversation as resolved.
Resolved
socket = connectWithProtocol(
protocol,
options
Expand All @@ -5695,10 +5728,25 @@ class ClientHttp2Session extends Http2Session {
const nativeSocket = socket._handle;
this[kDeferWriteCallback] = deferWriteCallbackForSocket(nativeSocket);

if (options?.settings !== undefined) {
validateSettings(options.settings);
// node reads options.settings in setupHandle, which runs once the socket is connected. It
// ignores a value that is not an object. A throw from validation there destroys the socket
// with that error, so the session emits 'error' and then 'close'. For a socket that is
// already connected, setupHandle runs inline and connect() throws.
// https://github.com/nodejs/node/blob/v26.3.0/lib/internal/http2/core.js#L1147
Comment thread
robobun marked this conversation as resolved.
Resolved
let settings = typeof options.settings === "object" ? options.settings : undefined;
if (settings !== undefined) {
try {
validateSettings(settings);
} catch (e) {
if (connectOnNextTick) throw e;
settingsRejected = true;
settingsError = e;
settings = undefined;
}
}
const nativeSettings = { ...options, ...options?.settings };
// The parser validates again and its throw leaves connect(), so it gets `settings` and never
// the raw options.settings.
Comment thread
robobun marked this conversation as resolved.
Resolved
const nativeSettings = { ...options, ...settings };
this.#localSettings = initialLocalSettings(nativeSettings);
// #onConnect attaches the native socket; frames written before that (the preface) queue.
this.#parser = new H2FrameParser({
Expand Down
127 changes: 127 additions & 0 deletions test/js/node/http2/http2-connect-settings.fixture.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
// Give http2.connect() an options.settings value it cannot use, over each kind of socket, and
// report what the caller observes. node-http2.test.js runs this in-process under Bun and as a
// script under Node.js: both must report the same outcomes.
const http2 = require("node:http2");
const net = require("node:net");
const { once } = require("node:events");
const { Duplex } = require("node:stream");

function serve(server) {
server.on("stream", stream => {
stream.respond({ ":status": 200 });
stream.end("ok");
});
server.listen(0, "127.0.0.1");
return once(server, "listening");
}

// What one connect() call does: the error it throws, or the session's events in order and the
// outcome of a request made while the socket was still connecting. The request's outcome is kept
// apart from the events, because which of the two errors comes first is not part of this test.
// `closeEarly` also calls close() before the socket connects.
function observe(url, options, closeEarly = false) {
const events = [];
let client;
try {
client = http2.connect(url, { rejectUnauthorized: false, ...options }, () => events.push("listener"));
} catch (e) {
return { thrown: `${e.code}: ${e.message}` };
}
client.on("connect", () => events.push("connect"));
client.on("error", e => events.push(`error ${e.code}: ${e.message}`));
const { promise, resolve } = Promise.withResolvers();
let request;
const req = client.request({ ":path": "/" });
req.on("response", headers => (request = `status ${headers[":status"]}`));
req.on("error", e => (request = `${e.code} caused by ${e.cause?.code}`));
req.on("close", () => client.close());
req.resume();
req.end();
if (closeEarly) client.close();
client.on("close", () => {
events.push("close");
resolve({ events, request });
});
return promise;
}

// A session that close() was called on before the socket connects, with no live request. node
// has destroyed it by then and never reads options.settings. Only the errors are the same on
// every run: whether 'connect' is seen depends on which of the connect and the destroy is first.
function observeClosedIdle(url, options, destroyedRequest) {
const errors = [];
const client = http2.connect(url, options);
client.on("error", e => errors.push(e.code));
if (destroyedRequest) {
const req = client.request({ ":path": "/" });
req.on("error", () => {});
req.destroy();
}
client.close();
return new Promise(resolve => client.on("close", () => resolve({ errors })));
}

async function observeConnectSettings(tlsOptions) {
const plain = http2.createServer();
const secure = http2.createSecureServer(tlsOptions);
try {
await Promise.all([serve(plain), serve(secure)]);
const port = plain.address().port;
const plainUrl = `http://127.0.0.1:${port}`;
const secureUrl = `https://127.0.0.1:${secure.address().port}`;
const invalid = { initialWindowSize: -1 };
const connectPlain = () => net.connect(port, "127.0.0.1");

// This connect() uses a socket that this function owns. If it throws, the socket is
// destroyed and the other cases do not run. A connect() that throws after it made its own
// socket leaves that socket connecting, and this process has no way to get rid of it.
const connecting = connectPlain();
const outcomes = {
"connecting socket": observe(plainUrl, { settings: invalid, createConnection: () => connecting }),
};
if (outcomes["connecting socket"].thrown) {
connecting.destroy();
return outcomes;
}

// A stream that is not connecting counts as connected: connect() sets the session up inline.
const connected = new Duplex({
read() {},
write(chunk, encoding, callback) {
callback();
},
});
outcomes["connected socket"] = observe(plainUrl, { settings: invalid, createConnection: () => connected });
connected.destroy();

// Every connect() below starts before the first of them settles.
Object.assign(outcomes, {
"http null": observe(plainUrl, { settings: null }),
"http array": observe(plainUrl, { settings: [] }),
"http invalid": observe(plainUrl, { settings: invalid }),
"http invalid, closed with a request pending": observe(plainUrl, { settings: invalid }, true),
"http invalid, closed with nothing pending": observeClosedIdle(plainUrl, { settings: invalid }, false),
"http invalid, closed after its request was destroyed": observeClosedIdle(plainUrl, { settings: invalid }, true),
"http number": observe(plainUrl, { settings: 1 }),
"http string": observe(plainUrl, { settings: "x" }),
"http boolean": observe(plainUrl, { settings: true }),
"http function": observe(plainUrl, { settings() {} }),
"https null": observe(secureUrl, { settings: null }),
"https array": observe(secureUrl, { settings: [] }),
"https number": observe(secureUrl, { settings: 1 }),
"https invalid": observe(secureUrl, { settings: invalid }),
"https null with createConnection": observe(secureUrl, { settings: null, createConnection: connectPlain }),
});
for (const name in outcomes) outcomes[name] = await outcomes[name];
return outcomes;
} finally {
plain.close();
secure.close();
}
}

module.exports = { observeConnectSettings };

if (require.main === module) {
observeConnectSettings(JSON.parse(process.argv[2])).then(outcomes => console.log(JSON.stringify(outcomes)));
}
87 changes: 87 additions & 0 deletions test/js/node/http2/node-http2.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { PerformanceObserver } from "node:perf_hooks";
import tls from "node:tls";
import { Duplex, duplexPair } from "stream";
import http2utils from "./helpers";
import { observeConnectSettings } from "./http2-connect-settings.fixture.js";
import { nodeEchoServer, TLS_CERT, TLS_OPTIONS } from "./http2-helpers";
const { describe, expect, it, beforeAll, afterAll, createCallCheckCtx, mock } = createTest(import.meta.path);
// bun-debug ships with ASAN but isn't named bun-asan, so isASAN is false
Expand Down Expand Up @@ -2681,6 +2682,92 @@ it("http2 client reports ECONNREFUSED for a refused connect, like Node.js", asyn
}
});

// node reads options.settings in setupHandle, which runs when the socket connects. It ignores a
// value whose typeof is not "object". null, an array, or a value that validation rejects
// destroys the session with that error. connect() throws in two cases only. The socket is
// already connected, so setupHandle runs inline. Or the URL is https and there is no
// createConnection: node then checks options.settings before it makes the socket.
describe("http2.connect reports a rejected options.settings where Node.js does", () => {
const sessionError = (code, message) => ({
events: [`error ${code}: ${message}`, "close"],
request: `ERR_HTTP2_STREAM_CANCEL caused by ${code}`,
});
const notAnObject = received =>
sessionError("ERR_INVALID_ARG_TYPE", `The "settings" argument must be of type object. Received ${received}`);
const notAnObjectProperty = received => ({
thrown: `ERR_INVALID_ARG_TYPE: The "options.settings" property must be of type object. Received ${received}`,
});
const invalidValue = ["ERR_HTTP2_INVALID_SETTING_VALUE", 'Invalid value for setting "initialWindowSize": -1'];
const ignored = { events: ["listener", "connect", "close"], request: "status 200" };
const expected = {
"connecting socket": sessionError(...invalidValue),
"connected socket": { thrown: invalidValue.join(": ") },
"http null": notAnObject("null"),
"http array": notAnObject("an instance of Array"),
"http invalid": sessionError(...invalidValue),
"http invalid, closed with a request pending": sessionError(...invalidValue),
"http invalid, closed with nothing pending": { errors: [] },
"http invalid, closed after its request was destroyed": { errors: [] },
"http number": ignored,
"http string": ignored,
"http boolean": ignored,
"http function": ignored,
"https null": notAnObjectProperty("null"),
"https array": notAnObjectProperty("an instance of Array"),
"https number": notAnObjectProperty("type number (1)"),
"https invalid": sessionError(...invalidValue),
"https null with createConnection": notAnObject("null"),
};

it("Bun", async () => {
expect(await observeConnectSettings(TLS_CERT)).toEqual(expected);
});

it.skipIf(!nodeExe())("Node.js", async () => {
const fixture = path.join(import.meta.dir, "http2-connect-settings.fixture.js");
await using proc = Bun.spawn({
cmd: [nodeExe(), fixture, JSON.stringify(TLS_CERT)],
env: bunEnv,
stdout: "pipe",
stderr: "inherit",
});
const [stdout, exitCode] = await Promise.all([proc.stdout.text(), proc.exited]);
expect(JSON.parse(stdout)).toEqual(expected);
expect(exitCode).toBe(0);
});

// With no 'error' listener the destroy throws. A throw from inside the socket's connect callback
// is reported on the socket, so the connect handler throws it again from the next tick.
const noErrorListener = `
const http2 = require("node:http2");
const server = http2.createServer();
server.listen(0, "127.0.0.1", () => {
process.on("uncaughtException", e => {
console.log("uncaughtException " + e.code);
process.exit(0);
});
http2.connect("http://127.0.0.1:" + server.address().port, { settings: { initialWindowSize: -1 } });
console.log("connect() returned");
});
`;
for (const [runtime, exe] of [
["Bun", bunExe()],
["Node.js", nodeExe()],
]) {
it.skipIf(!exe)(`with no 'error' listener the error is an uncaught exception (${runtime})`, async () => {
await using proc = Bun.spawn({
cmd: [exe, "-e", noErrorListener],
env: bunEnv,
stdout: "pipe",
stderr: "inherit",
});
const [stdout, exitCode] = await Promise.all([proc.stdout.text(), proc.exited]);
expect(stdout).toBe("connect() returned\nuncaughtException ERR_HTTP2_INVALID_SETTING_VALUE\n");
expect(exitCode).toBe(0);
});
}
});

it("http2 request.close() validates input and manages stream state", async done => {
const { mustCall } = createCallCheckCtx(done);
const server = http2.createServer();
Expand Down
Loading