Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 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
3 changes: 3 additions & 0 deletions src/js/internal/net/symbols.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,8 @@ export default {
// Internal handshake-settled signal: server-side sockets emit no user
// 'secureConnect' (node parity), so internal deferrals park on this instead.
kSecureConnectDone: Symbol("kSecureConnectDone"),
// tls.Server.prototype slot for Node's tlsConnectionListener. node:http's TLS-mode Server (an
// https.Server, a tls.Server in Node but not here) registers the same listener through it.
Comment thread
robobun marked this conversation as resolved.
Resolved
kTlsConnectionListener: Symbol("kTlsConnectionListener"),
kVerifyError: Symbol("kVerifyError"),
};
66 changes: 61 additions & 5 deletions src/js/node/_http_server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const {
validateBoolean,
validateInteger,
validateFunction,
validateNumber,
validateOneOf,
} = require("internal/validators");
const { ConnResetException, hasObserver, startPerf, stopPerf, kInternalSendOptions } = require("internal/shared");
Expand Down Expand Up @@ -67,7 +68,12 @@ const {
} = require("node:_http_outgoing");
const OutgoingMessagePrototype = OutgoingMessage.prototype;
const { kIncomingMessage } = require("node:_http_common");
const { kTlsConnectionListener } = require("internal/net/symbols");
const kSharedCreds = Symbol.for("::buntlssharedcreds::");
let http1Fallback;
let nodeTls;
const lazyTls = () => (nodeTls ??= require("node:tls"));
let tlsConnectionListener;
const kConnectionsCheckingInterval = Symbol("http.server.connectionsCheckingInterval");
const kTrackedConnections = Symbol("http.server.trackedConnections");
const kHttpAllowHalfOpen = Symbol("http.server.httpAllowHalfOpen");
Expand Down Expand Up @@ -250,16 +256,38 @@ function normalizeServerTls(tls) {
// Node registers connectionListener on every http.Server so `server.emit("connection", socket)`
// works for foreign Duplex sockets. The native listener handles its own sockets end to end;
// this picks up the rest. https://github.com/nodejs/node/blob/main/lib/_http_server.js
// An https.Server is a tls.Server there: 'connection' runs tls.Server's tlsConnectionListener,
// which puts the server-side TLS layer over the fed duplex, and the parser attaches on the
// 'secureConnection' its handshake emits. https://github.com/nodejs/node/blob/v26.3.0/lib/https.js#L93-L99
Comment thread
robobun marked this conversation as resolved.
Resolved
function connectionListener(this: Server, socket) {
if (NodeHTTPServerSocket && socket instanceof NodeHTTPServerSocket) return;
(http1Fallback ??= require("internal/http1_server_fallback")).connectionListenerHTTP1(this, socket, {
if (this[tlsSymbol]) {
tlsConnectionListener ??= lazyTls().Server.prototype[kTlsConnectionListener];
if (socket) tlsConnectionListener.$call(this, socket);
return;
}
httpConnectionListener(this, socket);
}

function secureConnectionListener(this: Server, socket) {
if (NodeHTTPServerSocket && socket instanceof NodeHTTPServerSocket) return;
httpConnectionListener(this, socket);
}

function httpConnectionListener(server: Server, socket) {
(http1Fallback ??= require("internal/http1_server_fallback")).connectionListenerHTTP1(server, socket, {
http1Options: {
IncomingMessage: this[kIncomingMessage],
ServerResponse: this[kServerResponse],
IncomingMessage: server[kIncomingMessage],
ServerResponse: server[kServerResponse],
},
});
}

// https://github.com/nodejs/node/blob/v26.3.0/lib/https.js#L107-L110
function onTlsClientError(this: Server, err, conn) {
if (!this.emit("clientError", err, conn)) conn.destroy(err);
}

function Server(options, callback): void {
if (!(this instanceof Server)) return new Server(options, callback);
EventEmitter.$call(this);
Expand Down Expand Up @@ -353,7 +381,7 @@ function Server(options, callback): void {
minVersion = tlsStringToProtocolVersion(options.minVersion);
maxVersion = tlsStringToProtocolVersion(options.maxVersion);
}
this[tlsSymbol] = normalizeServerTls({
const tls = (this[tlsSymbol] = normalizeServerTls({
serverName,
key,
cert,
Expand All @@ -365,7 +393,24 @@ function Server(options, callback): void {
ciphers: typeof options.ciphers === "string" && options.ciphers ? options.ciphers : undefined,
requestCert: options.requestCert,
rejectUnauthorized: options.rejectUnauthorized,
});
}));
// The tls.Server fields its tlsConnectionListener reads for a fed connection (with
// [kSharedCreds] below). https://github.com/nodejs/node/blob/v26.3.0/lib/internal/tls/wrap.js#L1367-L1391
Comment thread
robobun marked this conversation as resolved.
Resolved
this._requestCert = tls.requestCert;
this._rejectUnauthorized = tls.rejectUnauthorized;
const { SNICallback, ALPNCallback } = options;
if (SNICallback != null) validateFunction(SNICallback, "options.SNICallback");
if (ALPNCallback != null) {
validateFunction(ALPNCallback, "options.ALPNCallback");
if (options.ALPNProtocols) throw $ERR_TLS_ALPN_CALLBACK_WITH_PROTOCOLS();
}
this._SNICallback = SNICallback;
this._ALPNCallback = ALPNCallback;
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
const handshakeTimeout = options.handshakeTimeout || 120 * 1000;
validateNumber(handshakeTimeout, "options.handshakeTimeout");
this._handshakeTimeout = handshakeTimeout;
this.on("secureConnection", secureConnectionListener);
this.on("tlsClientError", onTlsClientError);
} else {
this[tlsSymbol] = null;
}
Expand All @@ -385,6 +430,17 @@ Server.prototype[kServerResponse] = undefined;

Server.prototype[kConnectionsCheckingInterval] = undefined;

// Node's https.Server inherits _sharedCreds from tls.Server. The native listener builds its own
// context from this[tlsSymbol]; this one serves fed connections (tlsConnectionListener) and is
// built on first use, with tls.Server's server-cipher-preference default.
Comment thread
robobun marked this conversation as resolved.
Resolved
Server.prototype[kSharedCreds] = function () {
const options = this[optionsSymbol];
return (this._sharedCreds ??= lazyTls().createSecureContext({
...options,
honorCipherOrder: options.honorCipherOrder !== false,
}));
};
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

function rethrowUncaught(err) {
throw err;
}
Expand Down
59 changes: 37 additions & 22 deletions src/js/node/tls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,12 @@ const {
} = require("internal/validators");

const { Server: NetServer, Socket: NetSocket } = net;
const { kArmHandshakeTimeout, kSecureConnectDone, kVerifyError } = require("internal/net/symbols");
const {
kArmHandshakeTimeout,
kSecureConnectDone,
kTlsConnectionListener,
kVerifyError,
} = require("internal/net/symbols");

const getBundledRootCertificates = $newCppFunction("NodeTLS.cpp", "getBundledRootCertificates", 1);
const getExtraCACertificates = $newCppFunction("NodeTLS.cpp", "getExtraCACertificates", 1);
Expand Down Expand Up @@ -1497,27 +1502,7 @@ function Server(options, secureConnectionListener): void {
// TLS layer, like Node's tls.Server wraps any injected duplex
// (node v26.3.0 lib/_tls_wrap.js, Server's connection listener).
if (!socket || (socket.encrypted && socket.server === this)) return;
let secureContext;
try {
secureContext = this[kSharedCreds]();
} catch (err) {
socket.destroy();
this.emit("error", err);
return;
}
const wrapped = new TLSSocket(socket, {
secureContext,
isServer: true,
requestCert: this._requestCert,
rejectUnauthorized: this._rejectUnauthorized,
SNICallback: this._SNICallback,
ALPNProtocols: this.ALPNProtocols,
ALPNCallback: this._ALPNCallback,
});
wrapped.server = this;
wrapped._requestCert = this._requestCert;
wrapped._rejectUnauthorized = this._rejectUnauthorized;
this[kArmHandshakeTimeout](wrapped);
tlsConnectionListener.$call(this, socket);
});

// Node registers the createServer callback as a plain "secureConnection"
Expand All @@ -1532,6 +1517,36 @@ Server.prototype[kSharedCreds] = function () {
return this._sharedCreds || buildSharedCreds(this);
};

// Node's tlsConnectionListener: puts the server-side TLS layer over a duplex the server was fed
// through 'connection'. The handshake then emits 'secureConnection' on `this` (net.ts
// ServerHandlers). `this` is a tls.Server or node:http's TLS-mode Server, which is not a
// tls.Server here but carries the fields read below.
// https://github.com/nodejs/node/blob/v26.3.0/lib/internal/tls/wrap.js#L1259-L1286
Comment thread
robobun marked this conversation as resolved.
Resolved
function tlsConnectionListener(this: Server, socket) {
let secureContext;
try {
secureContext = this[kSharedCreds]();
} catch (err) {
socket.destroy();
this.emit("error", err);
return;
}
const wrapped = new TLSSocket(socket, {
secureContext,
isServer: true,
requestCert: this._requestCert,
rejectUnauthorized: this._rejectUnauthorized,
SNICallback: this._SNICallback,
ALPNProtocols: this.ALPNProtocols,
ALPNCallback: this._ALPNCallback,
});
wrapped.server = this;
wrapped._requestCert = this._requestCert;
wrapped._rejectUnauthorized = this._rejectUnauthorized;
NetServer.prototype[kArmHandshakeTimeout].$call(this, wrapped);
}
Server.prototype[kTlsConnectionListener] = tlsConnectionListener;

function createServer(options, connectionListener) {
return new Server(options, connectionListener);
}
Expand Down
147 changes: 146 additions & 1 deletion test/js/node/http/node-http.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import { connect, createServer as createNetServer } from "node:net";
import { tmpdir } from "node:os";
import * as path from "node:path";
import { Duplex, duplexPair, PassThrough, Writable } from "node:stream";
import { connect as tlsConnect } from "node:tls";
import { createServer as createTlsServer, connect as tlsConnect, TLSSocket } from "node:tls";
import tunnel from "tunnel";
import { run as runHTTPProxyTest } from "./node-http-proxy.js";
const { describe, expect, it, beforeAll, afterAll, createDoneDotAll, mock, test } = createTest(import.meta.path);
Expand Down Expand Up @@ -4242,6 +4242,151 @@ it("connectionListener hands off Upgrade and CONNECT like Node", async () => {
}
});

// One front port hands its accepted sockets to an https.Server that never listens itself (the
// httpolyglot / SNI-router shape). Node's https.Server is a tls.Server: 'connection' runs the
// server-side TLS handshake over the fed duplex and 'secureConnection' attaches the HTTP parser.
describe("https.Server adopts connections fed through emit()", () => {
async function serveThroughFront(feed: "connection" | "secureConnection") {
const events = { connection: 0, secureConnection: 0, request: 0 };
const sockets: any[] = [];
const server = createHttpsServer(tlsCert, (req, res) => {
events.request++;
sockets.push(req.socket);
let body = 0;
req.on("data", d => (body += d.length));
req.on("end", () => res.end(`${req.method} ${req.url} ${body}`));
});
server.on("connection", () => events.connection++);
server.on("secureConnection", () => events.secureConnection++);
const front =
feed === "connection"
? createNetServer(socket => server.emit("connection", socket))
: createTlsServer(tlsCert, socket => server.emit("secureConnection", socket));
await once(front.listen(0, "127.0.0.1"), "listening");
const agent = new https.Agent({ keepAlive: true, maxSockets: 1 });
try {
const send = (method: string, path: string, body?: Buffer) =>
new Promise<string>((resolve, reject) => {
const req = https.request(
{
host: "127.0.0.1",
port: (front.address() as AddressInfo).port,
method,
path,
agent,
rejectUnauthorized: false,
},
res => {
let text = "";
res.setEncoding("utf8");
res.on("data", d => (text += d));
res.on("end", () => resolve(`${res.statusCode} ${text}`));
},
);
req.on("error", reject);
req.end(body);
});
expect(await send("GET", "/a")).toBe("200 GET /a 0");
expect(await send("POST", "/b", Buffer.alloc(70_000, "x"))).toBe("200 POST /b 70000");
} finally {
agent.destroy();
front.close();
}
return { server, events, sockets };
}

it("emit('connection', socket) runs the TLS handshake, then parses HTTP", async () => {
const { server, events, sockets } = await serveThroughFront("connection");
expect(events).toEqual({ connection: 1, secureConnection: 1, request: 2 });
expect(sockets[1]).toBe(sockets[0]);
expect(sockets[0]).toBeInstanceOf(TLSSocket);
expect(sockets[0].encrypted).toBe(true);
expect(sockets[0].server).toBe(server);
});

it("emit('secureConnection', tlsSocket) parses HTTP over that socket", async () => {
const { events } = await serveThroughFront("secureConnection");
expect(events).toEqual({ connection: 0, secureConnection: 1, request: 2 });
});

it("a fed socket that does not speak TLS reaches 'clientError' and gets no plaintext reply", async () => {
const events: string[] = [];
const server = createHttpsServer(tlsCert, (req, res) => {
events.push("request");
res.end();
});
server.on("tlsClientError", (err: any) => events.push("tlsClientError " + err.code));
server.on("clientError", (err: any, socket) => {
events.push("clientError " + err.code);
socket.destroy();
});
const front = createNetServer(socket => server.emit("connection", socket));
await once(front.listen(0, "127.0.0.1"), "listening");
const client = connect((front.address() as AddressInfo).port, "127.0.0.1");
try {
let received = "";
client.on("data", d => (received += d.toString("latin1")));
client.on("error", () => {});
await once(client, "connect");
client.write("GET / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n");
await once(client, "close");
expect(received).toBe("");
// https.Server turns 'tlsClientError' into 'clientError' from a listener it registers first.
expect(events).toEqual(["clientError ERR_SSL_HTTP_REQUEST", "tlsClientError ERR_SSL_HTTP_REQUEST"]);
} finally {
client.destroy();
front.close();
}
});

it("a fed connection runs the server's SNICallback and ALPNCallback", async () => {
const calls: string[] = [];
const server = createHttpsServer(
{
...tlsCert,
SNICallback: (servername, cb) => {
calls.push(`SNI ${servername}`);
cb(null, undefined);
},
ALPNCallback: ({ servername, protocols }) => {
calls.push(`ALPN ${servername} ${protocols.join(",")}`);
return "http/1.1";
},
},
(req, res) => res.end(`${(req.socket as TLSSocket).alpnProtocol} ${(req.socket as TLSSocket).servername}`),
);
const front = createNetServer(socket => server.emit("connection", socket));
await once(front.listen(0, "127.0.0.1"), "listening");
try {
const result = await new Promise<string>((resolve, reject) => {
https
.get(
{
host: "127.0.0.1",
port: (front.address() as AddressInfo).port,
servername: "localhost",
ALPNProtocols: ["h2", "http/1.1"],
rejectUnauthorized: false,
agent: false,
},
res => {
let text = "";
res.setEncoding("utf8");
res.on("data", d => (text += d));
res.on("end", () => resolve(`${res.statusCode} ${(res.socket as TLSSocket).alpnProtocol} ${text}`));
},
)
.on("error", reject);
});
expect(result).toBe("200 http/1.1 http/1.1 localhost");
// The TLS library decides which ClientHello extension it processes first.
expect(calls.sort()).toEqual(["ALPN localhost h2,http/1.1", "SNI localhost"]);
} finally {
front.close();
}
});
});

// A TLS client that is mid-handshake when an https server with a 'clientError' listener is closed still
// belongs to that server: once its handshake completes, a malformed request from it reaches 'clientError'
// (as in Node). The connection used to go uncounted until the handshake finished, so close() considered the
Expand Down
Loading