Skip to content
Closed
Show file tree
Hide file tree
Changes from 3 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
155 changes: 92 additions & 63 deletions src/js/node/net.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2352,78 +2352,107 @@ Socket.prototype.pause = function pause() {
// state carried via `data` (mirrors tls.createServer's one-handler-for-all model).
Socket.prototype[Symbol.for("::bunUpgradeServerTLS::")] = function (connection, tls) {
const socket = connection._handle;
if (!socket || connection.encrypted || hasUnflushedWrites(connection)) {
// No adoptable fd (generic Duplex / not yet connected), TLS over TLS (the
// fd belongs to the outer SSL layer), or pending plain writes that must
// flush first: run the TLS engine over the stream itself.
const [result, events] = upgradeDuplexToTLS(connection, {
data: this,
tls,
socket: serverHandlersFor(this),
isServer: true,
});
connection.on("data", events[0]);
connection.on("end", events[1]);
connection.on("drain", events[2]);
connection.on("close", events[3]);
if (!socket || isNamedPipeSocket(socket) || connection.encrypted || hasUnflushedWrites(connection)) {
// Nothing to adopt (generic Duplex, or a Windows named pipe, which has no
// us_socket_t; the client path routes pipes the same way), TLS over TLS
// (the fd belongs to the outer SSL layer), or pending plain writes that
// must flush first: run the TLS engine over the stream itself.
Comment thread
robobun marked this conversation as resolved.
Resolved
attachServerTLSEngine(this, connection, tls);
this[kupgraded] = connection;
this._handle = result;
return;
}
this[kupgraded] = connection;
process.nextTick(() => {
if (this.destroyed || connection.destroyed) {
this.destroy();
return;
}
const handle = connection._handle;
if (!handle) {
if (connection.connecting) {
// Adoption needs the established socket, so wait for it the way the
// client path does; a connection that fails first takes the wrap down
// with it, as adoptServerTLS does for one destroyed in the meantime.
Comment thread
robobun marked this conversation as resolved.
Resolved
const onConnect = () => {
connection.removeListener("close", onClose);
process.nextTick(adoptServerTLS, this, connection, tls);
};
const onClose = () => {
connection.removeListener("connect", onConnect);
this.destroy();
return;
}
// Writes may have been queued between the wrap and this tick (a user
// 'connection' listener runs after the server's): those bytes must flush
// before any TLS output, so fall back to the stream-level engine.
if (hasUnflushedWrites(connection)) {
const [result, events] = upgradeDuplexToTLS(connection, {
data: this,
tls,
socket: serverHandlersFor(this),
isServer: true,
});
connection.on("data", events[0]);
connection.on("end", events[1]);
connection.on("drain", events[2]);
connection.on("close", events[3]);
this._handle = result;
this.emit(kUpgradeAttached);
return;
}
// Bytes that already arrived before the wrap were pulled off the fd into
// the connection's readable buffer; hand them to the TLS engine so the
// handshake doesn't stall.
const pending = connection.read();
const result = handle.upgradeTLS({
data: this,
};
connection.once("connect", onConnect);
connection.once("close", onClose);
return;
}
process.nextTick(adoptServerTLS, this, connection, tls);
};

function attachServerTLSEngine(self, connection, tls) {
const [result, events] = upgradeDuplexToTLS(connection, {
data: self,
tls,
socket: serverHandlersFor(self),
isServer: true,
});
connection.on("data", events[0]);
connection.on("end", events[1]);
connection.on("drain", events[2]);
connection.on("close", events[3]);
self._handle = result;
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

// The deferred half of the server-side wrap. Runs a tick after the wrap (or
// after the connection's 'connect'), so that writes the user queued on the
// plain connection in between are seen below.
Comment thread
robobun marked this conversation as resolved.
Resolved
function adoptServerTLS(self, connection, tls) {
if (self.destroyed || connection.destroyed) {
self.destroy();
return;
}
Comment thread
robobun marked this conversation as resolved.
Resolved
// Re-read: a connection that was still connecting when wrapped may have
// swapped handles (family autoselection) or turned out to be a named pipe.
Comment thread
robobun marked this conversation as resolved.
Resolved
const handle = connection._handle;
if (!handle) {
self.destroy();
return;
}
// Queued plain writes (a user 'connection' listener runs after the
// server's) must flush before any TLS output, so they, like a pipe, take
// the stream-level engine.
Comment thread
robobun marked this conversation as resolved.
Resolved
if (isNamedPipeSocket(handle) || hasUnflushedWrites(connection)) {
attachServerTLSEngine(self, connection, tls);
self.emit(kUpgradeAttached);
return;
}
// Bytes that already arrived before the wrap were pulled off the fd into
// the connection's readable buffer; hand them to the TLS engine so the
// handshake doesn't stall.
Comment thread
robobun marked this conversation as resolved.
Resolved
const pending = connection.read();
let result;
try {
result = handle.upgradeTLS({
data: self,
tls,
socket: serverHandlersFor(this),
socket: serverHandlersFor(self),
isServer: true,
initialData: pending || undefined,
});
if (!result) {
this._handle = null;
this.destroy(new Error("Invalid socket"));
return;
}
const [raw, tlsHandle] = result;
connection._handle = raw;
raw[kAdoptedTLSRaw] = true;
this.once("end", this[kCloseRawConnection]);
raw.connecting = false;
this._handle = tlsHandle;
this.emit(kUpgradeAttached);
});
};
} catch (err) {
// The constructor already returned, so a throw here would be an uncaught
// exception. Reachable when the native socket closed under a connection
// that is not destroyed yet (peer reset with unread bytes still buffered):
// the handle object survives but has nothing left to adopt.
Comment thread
robobun marked this conversation as resolved.
Resolved
self._handle = null;
self.destroy(err);
return;
Comment thread
robobun marked this conversation as resolved.
Resolved
}
if (!result) {
self._handle = null;
self.destroy(new Error("Invalid socket"));
return;
}
const [raw, tlsHandle] = result;
connection._handle = raw;
raw[kAdoptedTLSRaw] = true;
self.once("end", self[kCloseRawConnection]);
raw.connecting = false;
self._handle = tlsHandle;
self.emit(kUpgradeAttached);
}

Socket.prototype.read = function read(size) {
if (!this.connecting && !drainOnreadTail(this, true)) {
Expand Down
59 changes: 58 additions & 1 deletion test/js/node/tls/node-tls-namedpipes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { expectMaxObjectTypeCount, isWindows, tls } from "harness";
import { randomUUID } from "node:crypto";
import { once } from "node:events";
import net from "node:net";
import { connect, createServer } from "node:tls";
import { connect, createServer, TLSSocket } from "node:tls";

it.if(isWindows)("should work with named pipes and tls", async () => {
await expectMaxObjectTypeCount(expect, "TLSSocket", 0);
Expand Down Expand Up @@ -94,3 +94,60 @@ it.if(isWindows)("should be able to upgrade a named pipe connection to TLS", asy
await test(`\\\\.\\pipe\\test\\${randomUUID()}`);
await expectMaxObjectTypeCount(expect, "TLSSocket", 3);
});

// Server-side wraps of an accepted named-pipe connection. A pipe has no fd for
// the native upgrade to adopt; the wrap has to run the TLS engine over the
// stream, the way tls.connect({ socket }) already does for pipes. It used to
// throw "upgradeTLS requires an established socket" from nextTick, uncaught.
type ServerWrap = (accepted: net.Socket, echo: (secure: TLSSocket) => void, fail: (err: Error) => void) => void;

async function serverWrapRoundTrip(wrap: ServerWrap) {
const pipeName = `\\\\.\\pipe\\test\\${randomUUID()}`;
const echoed = Promise.withResolvers<string>();
const server = net.createServer(accepted => {
accepted.on("error", echoed.reject);
wrap(
accepted,
secure => {
secure.on("error", echoed.reject);
secure.on("data", chunk => secure.end(`echo:${chunk}`));
},
echoed.reject,
);
});
let client: TLSSocket | undefined;
try {
server.listen(pipeName);
await once(server, "listening");
Comment thread
robobun marked this conversation as resolved.
Resolved
client = connect({ socket: net.connect(pipeName), rejectUnauthorized: false }, () => client!.write("ping"));
client.on("error", echoed.reject);
// Read through to the server's close_notify before tearing down: a pipe
// write is only complete once the peer has read it, so closing on the
// first data chunk would fail the server's still-pending close_notify
// write with EPIPE.
let received = "";
client.on("data", chunk => (received += chunk));
client.on("end", () => echoed.resolve(received));
expect(await echoed.promise).toBe("echo:ping");
} finally {
client?.destroy();
server.close();
}
}

it.if(isWindows)("new TLSSocket(pipeSocket, { isServer: true }) completes a handshake over a named pipe", async () => {
await serverWrapRoundTrip((accepted, echo) => echo(new TLSSocket(accepted, { isServer: true, ...tls })));
});

it.if(isWindows)("tls.Server wraps a named-pipe connection handed in via emit('connection')", async () => {
const tlsServer = createServer(tls);
try {
await serverWrapRoundTrip((accepted, echo, fail) => {
tlsServer.once("secureConnection", echo);
tlsServer.once("tlsClientError", fail);
tlsServer.emit("connection", accepted);
});
} finally {
tlsServer.close();
}
});
135 changes: 135 additions & 0 deletions test/js/node/tls/node-tls-server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2019,6 +2019,141 @@ it("destroys a server wrap whose socket was destroyed before the deferred upgrad
}
});

// Node wraps the handle synchronously whatever state it is in. Bun's deferred
// native adoption needs an established socket, so a socket wrapped while its
// lookup is still in flight is adopted once it connects (or the wrap closes
// with it if it never does); it used to throw "upgradeTLS requires an
// established socket" from nextTick, uncaught. The lookup settles on a later
// turn, so the wrap and the tick after it both run before the socket has a
// handle to adopt.
function connectLater(port: number, lookupError: Error | null = null) {
const outgoing = net.connect({
port,
host: "localhost",
family: 4,
lookup: (_host, _options, callback) => setImmediate(callback, lookupError, "127.0.0.1", 4),
});
expect(outgoing.connecting).toBe(true);
return outgoing;
}

it("adopts a socket that was still connecting when wrapped as the server side", async () => {
const echoed = Promise.withResolvers<string>();
// The wrap must end up on the fd like a wrap of a connected socket does,
// which is observable as the peer's address; the stream-level engine has no
// fd and reports none.
const peer = Promise.withResolvers<{ remoteAddress: string | undefined; remotePort: number | undefined }>();
// The listener plays the TLS client over the connection it accepts; the
// outgoing socket below is the side wrapped as the TLS server.
const rawServer = net.createServer(accepted => {
const client = connect({ socket: accepted, rejectUnauthorized: false }, () => client.write("ping"));
client.on("error", echoed.reject);
client.once("data", chunk => {
echoed.resolve(chunk.toString());
client.end();
});
});
let outgoing: net.Socket | undefined;
let wrapped: TLSSocket | undefined;
try {
const listening = Promise.withResolvers<void>();
rawServer.once("error", listening.reject);
rawServer.listen(0, "127.0.0.1", listening.resolve);
await listening.promise;
const port = (rawServer.address() as AddressInfo).port;
outgoing = connectLater(port);
const outgoingClosed = once(outgoing, "close");
wrapped = new TLSSocket(outgoing, { isServer: true, ...COMMON_CERT });
wrapped.on("error", echoed.reject);
wrapped.on("data", chunk => {
peer.resolve({ remoteAddress: wrapped!.remoteAddress, remotePort: wrapped!.remotePort });
wrapped!.end(`echo:${chunk}`);
});
expect(await echoed.promise).toBe("echo:ping");
expect(await peer.promise).toEqual({ remoteAddress: "127.0.0.1", remotePort: port });
// Ending the exchange releases the wrapped connection as well.
await outgoingClosed;
} finally {
wrapped?.destroy();
outgoing?.destroy();
rawServer.close();
}
});

it("closes a server wrap whose connecting socket fails to connect", async () => {
// Node closes the wrap, without an error of its own, when the wrapped
// socket fails; the failure itself is reported on that socket.
const outgoing = connectLater(1, Object.assign(new Error("getaddrinfo ENOTFOUND localhost"), { code: "ENOTFOUND" }));
const outgoingFailed = Promise.withResolvers<string>();
outgoing.on("error", err => outgoingFailed.resolve((err as NodeJS.ErrnoException).code!));
const wrapped = new TLSSocket(outgoing, { isServer: true, ...COMMON_CERT });
try {
const events: string[] = [];
const wrapClosed = Promise.withResolvers<void>();
wrapped.on("error", err => events.push(`error: ${err.message}`));
wrapped.on("close", hadError => {
events.push(`close: hadError=${hadError}`);
wrapClosed.resolve();
});
expect(await outgoingFailed.promise).toBe("ENOTFOUND");
await wrapClosed.promise;
expect(events).toEqual(["close: hadError=false"]);
} finally {
wrapped.destroy();
outgoing.destroy();
}
});

it("fails a server wrap on the wrap's 'error' when the connection's handle is already gone", async () => {
// A peer reset behind an unread byte closes the native socket without
// ending the net.Socket (the byte is still buffered), so the connection
// still carries a handle, but one with nothing left to adopt. The deferred
// adoption's refusal belongs to the wrap (Node surfaces every failure of a
// wrapped socket on the TLSSocket); it used to escape nextTick as an
// uncaught exception.
const accepted = Promise.withResolvers<net.Socket>();
const rawServer = net.createServer(socket => {
socket.write("x");
accepted.resolve(socket);
});
let outgoing: net.Socket | undefined;
let wrapped: TLSSocket | undefined;
try {
const listening = Promise.withResolvers<void>();
rawServer.once("error", listening.reject);
rawServer.listen(0, "127.0.0.1", listening.resolve);
await listening.promise;
outgoing = net.connect((rawServer.address() as AddressInfo).port, "127.0.0.1");
// No 'error' listener on purpose: with one, the reset would destroy the
// socket and the wrap would take the handle-less path instead.
const byteBuffered = Promise.withResolvers<void>();
const eofBuffered = Promise.withResolvers<void>();
let readableEvents = 0;
outgoing.on("readable", () => (++readableEvents === 1 ? byteBuffered : eofBuffered).resolve());
// Nothing reads the byte, so it stays buffered; the 'readable' that
// follows the reset is the EOF the close pushed in behind it.
await byteBuffered.promise;
(await accepted.promise).resetAndDestroy();
await eofBuffered.promise;
expect({ destroyed: outgoing.destroyed, pending: outgoing.pending }).toEqual({ destroyed: false, pending: false });

wrapped = new TLSSocket(outgoing, { isServer: true, ...COMMON_CERT });
const events: string[] = [];
const closed = Promise.withResolvers<void>();
wrapped.on("error", err => events.push(`error: ${err.message}`));
wrapped.on("close", () => {
events.push("close");
closed.resolve();
});
await closed.promise;
expect(events).toEqual(["error: upgradeTLS requires an established socket", "close"]);
} finally {
wrapped?.destroy();
outgoing?.destroy();
rawServer.close();
}
});

it("exposes the server-side peer verification result via socket.ssl.verifyError()", async () => {
// Node's server path consults the same TLSWrap.verifyError() that clients
// use, so the shim must be populated for server sockets too:
Expand Down