Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
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
28 changes: 28 additions & 0 deletions src/js/node/_http_server.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Hardcoded module "node:_http_server"
const EventEmitter: typeof import("node:events").EventEmitter = require("node:events");
const { Stream } = require("node:stream");
const { isIP } = require("internal/net/isIP");
const {
_checkInvalidHeaderChar: checkInvalidHeaderChar,
chunkExpression,
Expand Down Expand Up @@ -118,6 +119,12 @@ const DateNow = Date.now;

let cluster;

let BlockList;
function isBlockList(value) {
BlockList ??= $rust("node_net_binding.rs", "BlockList");
return BlockList.isBlockList(value);
}

function emitCloseServer(self: Server) {
// A native close promise belongs to one listener; Node's Server 'close' spans overlapping listeners and handed-off sockets (net.js _emitCloseIfDrained).
if (!self[kPendingDrainClose]) return;
Expand Down Expand Up @@ -409,6 +416,15 @@ function Server(options, callback): void {
requestCert: options.requestCert,
rejectUnauthorized: options.rejectUnauthorized,
});

// TLS-only like Node, where tls.Server passes its options through to net.Server and http.Server does not.
const blockList = options.blockList;
if (blockList) {
if (!isBlockList(blockList)) {
throw $ERR_INVALID_ARG_TYPE("options.blockList", "net.BlockList", blockList);
}
this.blockList = blockList;
}
Comment thread
robobun marked this conversation as resolved.
Resolved
} else {
this[tlsSymbol] = null;
}
Expand Down Expand Up @@ -1263,6 +1279,18 @@ function onServerConnection(this: Server, listenerGeneration, socketHandle) {
return;
}

// Node's onconnection checks server.blockList next and closes a blocked peer silently: no 'drop', no 'connection'.
const blockList = this.blockList;
if (blockList) {
const remoteAddress = socket.remoteAddress;
const addressType = isIP(remoteAddress);
if (addressType && blockList.check(remoteAddress, `ipv${addressType}`)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 (optional) Operators whose assigned server.blockList throws from check get the blocked peer served anyway, where Node never dispatches the request. The call at src/js/node/_http_server.ts:1287 runs inside the native accept callback with no guard; a throw leaves the socket undestroyed, skips the return, and the native dispatcher goes on to parse and serve the request after dispatch::fold reports the error (src/runtime/server/server_body.rs:3662). Any process with an 'uncaughtException' handler keeps running with the deny list bypassed. Fix: make the gate fail closed: destroy the socket when the check throws (try/finally around the check, or validate on assignment via a blockList accessor) so an erroring blockList never lets a connection through.

Why this was flagged

Trigger: server.blockList = obj after construction (the PR explicitly supports post-listen assignment, test case 'assigned after listen') where obj.check is missing or throws, or a check implementation that throws for a given address. onServerConnection at src/js/node/_http_server.ts:1284-1292 calls blockList.check(remoteAddress, ...) with no try; the exception propagates out of the callback invoked at src/runtime/server/server_body.rs:3509 and is folded by crate::dispatch::fold (src/runtime/dispatch.rs:1308-1318) into report_error_or_terminate. With an 'uncaughtException' handler installed (common in long-running servers) the process continues, the socket created at line 1260 is still live and tracked, and the native server proceeds to dispatch the request to the handler as if no list existed. In Node the throw happens before the client handle is wrapped, so the request is never served. REVIEW.md: security checks fail closed; if the check's prerequisite fails, fail the operation. Remedy: destroy the socket on any throw from check, or validate the value at assignment time.

Verification: Triggered when the operator assigns a server.blockList whose check throws and the process has an 'uncaughtException' handler. src/js/node/_http_server.ts:1283-1292 calls blockList.check(...) with no try/catch; a throw skips socket.destroy(); return;. fold (src/runtime/dispatch.rs:1308) reports and returns, so the request handler runs. Base does not enforce blockList at all.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reproduced. With server.blockList = { check() { throw new Error() } } and an uncaughtException handler, Node v26.3.0 never serves the peer, and this branch answers 200 for http and https.

The fix is to destroy the socket before the error propagates:

    if (addressType) {
      // The native listener serves this socket unless it is destroyed here, so a check() that throws must not admit it.
      let blocked = true;
      try {
        blocked = !!blockList.check(remoteAddress, `ipv${addressType}`);
      } finally {
        if (blocked) {
          tracked?.delete(socket);
          socket.destroy();
        }
      }
      if (blocked) return;
    }

The test runs an http server and an https server in a child process that handles uncaughtException. Without the change both serve the peer (200, one request). With it both close the connection (ECONNRESET, zero requests), and the error still reaches the handler.

An accessor that validates on assignment would reject objects that Node accepts, so the guard stays at the call.

The change is written and passes locally. It is not pushed, because the head is the diff that was verified for merge. It goes in with the accept-time check from the other thread, or into this PR first if a maintainer prefers. The description lists this case under Downsides until then.

tracked?.delete(socket);
socket.destroy();
return;
}
}
Comment on lines +1282 to +1292

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 (optional) Operators who put abusive IPs on an https server's blockList still pay a full server-side TLS handshake per blocked connection; Node closes at TCP accept. The check at src/js/node/_http_server.ts:1283-1291 runs from the uws open filter (1), which for TLS fires only in onHandshake after the handshake completed. The PR calls this a known difference needing a new accept hook, but uws already fires the filter with 2 at TCP accept for both transports and Rust already consumes it for connection counting; only the thunk at server_body.rs:3655 drops it. Fix: evaluate server.blockList against the peer address at the accept (2) notification, before any TLS work, for both http and https, while keeping 'connection'/'secureConnection' at the open (1) notification.

Why this was flagged

An https server created with { key, cert, blockList } receives a connection from a listed IP. HttpContext.h:224-227 fires every filter with 2 at TCP accept; the Rust thunk registered by server_set_on_connection at src/runtime/server/server_body.rs:3655 returns unless opened == 1, and for SSL the 1 notification is sent from onHandshake at HttpContext.h:173-177 after the handshake finished. So onServerConnection at src/js/node/_http_server.ts:1283-1291 only sees the peer once the server has done the key exchange and signed the handshake. The blocked peer is then destroyed. On Node the same peer is closed in onconnection before any TLS state is created, so a blocked IP costs no asymmetric crypto; after this merge a blocked IP can force the server into one full handshake per connection attempt. The PR text says a pre-handshake hook would need to be added to the uws/Rust accept path; src/runtime/server/mod.rs:498-519 shows on_connection_filter already receives and handles the 2 event, so the hook exists and only the node:http forwarding ignores it.

Verification: The Rust filter thunk at src/runtime/server/server_body.rs:3650-3657 does if opened != 1 { return; }. For SSL, uws sends 1 only from onHandshake at packages/bun-uws/src/HttpContext.h:172-177 (after isAuthorized = success). So a blocked https peer completes the full server-side TLS handshake before being destroyed, whereas Node's net.js onconnection closes at TCP accept.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed on current main. HttpContext::onOpen fires every filter with 2 at TCP accept for both transports (packages/bun-uws/src/HttpContext.h:223-227), and the node:http thunk in server_set_on_connection forwards only 1. #38660 added that event on 2026-08-17, after this PR was opened. The sentence in the description about a missing accept hook was out of date, and I corrected it.

The accept notification is the better place for this check. Node closes there, the peer never starts a TLS handshake, and a blocked peer can also skip the JS socket object. The accept loop already checks for a socket that closed during open, and onOpen receives the peer address. The remaining work is native: evaluate the list in the 2 handler, and return from onOpen before 1 fires for a socket that the handler closed.

This PR does not contain that change. The head is the diff that was verified for merge, rebased with no change to the added lines. I will send the accept-time check as a follow-up, or add it here first if a maintainer prefers to hold the merge.


// Node's connectionListener attaches the HTTPParser (socket.parser) before
// emitting 'connection'; expose the shim here so listeners see it populated.
socket.parser = createServerParserShim(socket);
Expand Down
151 changes: 151 additions & 0 deletions test/js/node/http/node-http-server-blocklist.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
import { describe, expect, test } from "bun:test";
import { tempDir, tls } from "harness";
import { once } from "node:events";
import http from "node:http";
import https from "node:https";
import type { AddressInfo } from "node:net";
import { BlockList } from "node:net";
import { join } from "node:path";

// Node stores the list as a plain property on the server (net.Server constructor).
type ServerWithBlockList = http.Server & { blockList?: BlockList };

type Outcome = { statusCode: number | undefined; body: string } | { error: string | undefined };

// Every client in this file connects from 127.0.0.1.
function blockListCoveringLocalhost() {
const blockList = new BlockList();
blockList.addAddress("127.0.0.1");
return blockList;
}

function blockListNotCoveringLocalhost() {
const blockList = new BlockList();
blockList.addSubnet("10.0.0.0", 8);
return blockList;
}

async function listen(server: http.Server) {
server.listen(0, "127.0.0.1");
await once(server, "listening");
return (server.address() as AddressInfo).port;
}

function request(mod: typeof http | typeof https, port: number): Promise<Outcome> {
return new Promise(resolve => {
mod
.get({ host: "127.0.0.1", port, agent: false, rejectUnauthorized: false }, res => {
let body = "";
res.setEncoding("utf8");
res.on("data", chunk => (body += chunk));
res.on("end", () => resolve({ statusCode: res.statusCode, body }));
})
.on("error", (error: NodeJS.ErrnoException) => resolve({ error: error.code }));
});
}

describe("https server blockList option", () => {
const constructors: [string, (options: https.ServerOptions, listener: http.RequestListener) => https.Server][] = [
["https.createServer()", (options, listener) => https.createServer(options, listener)],
["new https.Server()", (options, listener) => new https.Server(options, listener)],
];

test.each(constructors)(
"%s: a blocked peer is closed before 'connection' and never reaches the request handler",
async (_name, construct) => {
const blockList = blockListCoveringLocalhost();
const events: string[] = [];
const server = construct({ ...tls, blockList }, (_req, res) => {
events.push("request");
res.end("served");
}) as ServerWithBlockList;
server.on("connection", () => events.push("connection"));
server.on("secureConnection", () => events.push("secureConnection"));
// Node only emits 'drop' for maxConnections; a blocked peer is closed silently.
server.on("drop", () => events.push("drop"));
try {
const port = await listen(server);
expect(await request(https, port)).toEqual({ error: "ECONNRESET" });
expect(events).toEqual([]);
expect(server.blockList).toBe(blockList);
} finally {
server.close();
}
},
);

test("a peer outside the list is served", async () => {
const server = https.createServer({ ...tls, blockList: blockListNotCoveringLocalhost() }, (_req, res) => {
res.end("served");
});
try {
const port = await listen(server);
expect(await request(https, port)).toEqual({ statusCode: 200, body: "served" });
} finally {
server.close();
}
});

test("a value that is not a net.BlockList is rejected", () => {
const notABlockList = { check: () => true } as any;
expect(() => https.createServer({ ...tls, blockList: notABlockList })).toThrowWithCode(
TypeError,
"ERR_INVALID_ARG_TYPE",
);
});
});

describe("http.Server blockList", () => {
test("server.blockList assigned after listen() applies to the next connection", async () => {
let requests = 0;
const server = http.createServer((_req, res) => {
requests++;
res.end("served");
}) as ServerWithBlockList;
try {
const port = await listen(server);
expect(await request(http, port)).toEqual({ statusCode: 200, body: "served" });

server.blockList = blockListCoveringLocalhost();
expect(await request(http, port)).toEqual({ error: "ECONNRESET" });
expect(requests).toBe(1);

server.blockList = undefined;
expect(await request(http, port)).toEqual({ statusCode: 200, body: "served" });
expect(requests).toBe(2);
} finally {
server.close();
}
});

test("a unix socket peer has no IP address to check and is served", async () => {
using dir = tempDir("http-blocklist", {});
const socketPath = join(String(dir), "server.sock");
const server = http.createServer((_req, res) => {
res.end("served");
}) as ServerWithBlockList;
server.blockList = blockListCoveringLocalhost();
try {
server.listen(socketPath);
await once(server, "listening");
const response = await fetch("http://localhost/", { unix: socketPath, headers: { connection: "close" } });
expect({ statusCode: response.status, body: await response.text() }).toEqual({ statusCode: 200, body: "served" });
} finally {
server.close();
}
});

test("the constructor option is ignored on a plain http server, like Node's http.Server", async () => {
const options = { blockList: blockListCoveringLocalhost() } as any;
const server = http.createServer(options, (_req, res) => {
res.end("served");
}) as ServerWithBlockList;
try {
expect(server.blockList).toBeUndefined();
const port = await listen(server);
expect(await request(http, port)).toEqual({ statusCode: 200, body: "served" });
} finally {
server.close();
}
});
});
Loading