Skip to content
Closed
Show file tree
Hide file tree
Changes from 9 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
2 changes: 2 additions & 0 deletions src/js/internal/net/symbols.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,7 @@ 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"),
// Set while a TLS socket waits to adopt its transport's handle.
kUpgradePending: Symbol("kUpgradePending"),
kVerifyError: Symbol("kVerifyError"),
};
29 changes: 27 additions & 2 deletions src/js/node/net.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ const {
kDestroyOnRead,
kPreHandshakeWrite,
kSecureConnectDone,
kUpgradePending,
kVerifyError,
} = require("internal/net/symbols");

Expand Down Expand Up @@ -1325,6 +1326,8 @@ const SocketHandlers2: SocketHandler<NonNullable<import("node:net").Socket["_han
self.connecting = false;
if (callback) {
const writeChunk = self._pendingData;
// A write parked while the socket this one wraps was connecting reaches the engine here, not through _write.
if (self.secureConnecting) self[kPreHandshakeWrite] = true;
const res = socket.$write(writeChunk || "", self._pendingEncoding || "utf8");
if (res < 0) {
// The retried send failed for good (peer gone): $write returned -errno.
Expand Down Expand Up @@ -2006,6 +2009,7 @@ Socket.prototype.connect = function connect(...args) {
this.authorized = false;
this.secureConnecting = true;
this[kPreHandshakeWrite] = false;
this[kUpgradePending] = false;
this._secureEstablished = false;
this._securePending = true;
this[kConnectOptions] = options;
Expand Down Expand Up @@ -2073,7 +2077,8 @@ Socket.prototype.connect = function connect(...args) {
}
} else {
// wait to be connected
connection.once("connect", () => {
this[kUpgradePending] = true;
const onConnect = () => {
// The TLS socket may have been destroyed before the underlying
// socket connected (e.g. tls.connect({ socket }).destroy()); don't
// start a handshake on a dead socket.
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Expand Down Expand Up @@ -2121,7 +2126,20 @@ Socket.prototype.connect = function connect(...args) {
throw new Error("Invalid socket");
}
}
});
// destroyWhenUpgradedCloses took over above. An upgrade that threw keeps onClose.
connection.removeListener("close", onClose);
// The transport is connected. The stream-level engine opens on a later task and emits no 'connect' for _final to wait for.
this.connecting = false;
this[kUpgradePending] = false;
this.emit(kUpgradeAttached);
};
// https://github.com/nodejs/node/blob/v26.3.0/lib/internal/tls/wrap.js#L739-L741
const onClose = () => {
connection.removeListener("connect", onConnect);
this.destroy();
};
connection.once("connect", onConnect);
connection.once("close", onClose);
}
}
} catch (error) {
Expand Down Expand Up @@ -2279,6 +2297,10 @@ Socket.prototype._destroy = function _destroy(err, callback) {

Socket.prototype._final = function _final(callback) {
$debug("Socket.prototype._final");
// No TLS handle to shut down yet. Node has one from the constructor and waits on `connecting`: https://github.com/nodejs/node/blob/v26.3.0/lib/internal/tls/wrap.js#L964-L973
if (this[kUpgradePending]) {
return this.once(kUpgradeAttached, this._final.bind(this, callback));
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
if (this.connecting) {
return this.once("connect", this._final.bind(this, callback));
}
Expand Down Expand Up @@ -2410,6 +2432,7 @@ Socket.prototype[Symbol.for("::bunUpgradeServerTLS::")] = function (connection,
return;
}
this[kupgraded] = connection;
this[kUpgradePending] = true;
process.nextTick(() => {
if (this.destroyed || connection.destroyed) {
this.destroy();
Expand All @@ -2436,6 +2459,7 @@ Socket.prototype[Symbol.for("::bunUpgradeServerTLS::")] = function (connection,
connection.on("close", events[3]);
destroyWhenUpgradedCloses(this, connection);
this._handle = result;
this[kUpgradePending] = false;
this.emit(kUpgradeAttached);
return;
}
Expand All @@ -2462,6 +2486,7 @@ Socket.prototype[Symbol.for("::bunUpgradeServerTLS::")] = function (connection,
this.once("end", this[kCloseRawConnection]);
raw.connecting = false;
this._handle = tlsHandle;
this[kUpgradePending] = false;
this.emit(kUpgradeAttached);
});
};
Expand Down
14 changes: 12 additions & 2 deletions src/js/node/tls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,13 @@ const {
} = require("internal/validators");

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

const getBundledRootCertificates = $newCppFunction("NodeTLS.cpp", "getBundledRootCertificates", 1);
const getExtraCACertificates = $newCppFunction("NodeTLS.cpp", "getExtraCACertificates", 1);
Expand Down Expand Up @@ -897,7 +903,11 @@ TLSSocket.prototype._start = function _start() {
};

TLSSocket.prototype._final = function _final(callback) {
if (!this._handle) return callback();
if (!this._handle) {
// The handle is still on its way: net.Socket's _final waits for it.
if (this[kUpgradePending]) return NetSocket.prototype._final.$call(this, callback);
return callback();
}
// https://github.com/nodejs/node/blob/v26.3.0/src/crypto/crypto_tls.cc#L1119-L1133
if (this.secureConnecting && this[kPreHandshakeWrite]) {
return this.once(kSecureConnectDone, NetSocket.prototype._final.bind(this, callback));
Expand Down
152 changes: 152 additions & 0 deletions test/js/node/tls/node-tls-connect.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1943,6 +1943,98 @@ it.skipIf(!nodeExe())(
},
);

it("tls.connect({ socket }) closes when a 'connect' listener destroys the transport before the upgrade", async () => {
const accepted: net.Socket[] = [];
const server = net.createServer(socket => {
accepted.push(socket);
socket.on("error", () => {});
});
await once(server.listen(0, "127.0.0.1"), "listening");
try {
const raw = net.connect((server.address() as AddressInfo).port, "127.0.0.1");
raw.on("error", () => {});
// Registered first, so it runs before the listener that upgrades the socket.
raw.once("connect", () => raw.destroy());
const client = tls.connect({ socket: raw, rejectUnauthorized: false });
client.on("error", () => {});
const events: string[] = [];
client.on("finish", () => events.push("finish"));
client.end();
await new Promise<void>(resolve => client.once("close", () => resolve()));
expect({ events, destroyed: client.destroyed, transportDestroyed: raw.destroyed }).toEqual({
events: [],
destroyed: true,
transportDestroyed: true,
});
} finally {
for (const socket of accepted) socket.destroy();
server.close();
}
});

it("tls.connect({ socket }).end() finishes after a transport with queued plaintext connects", async () => {
const accepted: net.Socket[] = [];
const server = net.createServer(socket => {
accepted.push(socket);
socket.on("error", () => {});
socket.resume();
});
await once(server.listen(0, "127.0.0.1"), "listening");
const raw = net.connect((server.address() as AddressInfo).port, "127.0.0.1");
raw.on("error", () => {});
const client = tls.connect({ socket: raw, rejectUnauthorized: false });
const finished = Promise.withResolvers<void>();
client.on("error", finished.reject);
client.once("close", () => finished.reject(new Error("closed before 'finish'")));
try {
const events: string[] = [];
raw.on("connect", () => events.push("transport connect"));
client.on("finish", () => {
events.push("finish");
finished.resolve();
});
// Still queued when the transport connects, so the upgrade takes the stream-level engine.
raw.write("plain");
client.end();
await finished.promise;
expect(events).toEqual(["transport connect", "finish"]);
} finally {
client.destroy();
raw.destroy();
for (const socket of accepted) socket.destroy();
server.close();
}
});

// end() waits for a wrap's native handle only while that handle is still to
// attach. One that attached and then closed leaves nothing to wait for: the
// stream ends itself from the close, and that end() has to finish.
it("a server-side TLSSocket wrap finishes and closes after its native handle was closed", async () => {
const events: string[] = [];
const closed = Promise.withResolvers<void>();
let wrapped: TLSSocket | undefined;
const server = net.createServer(raw => {
raw.on("error", () => {});
wrapped = new TLSSocket(raw, { isServer: true, ...COMMON_CERT_ });
wrapped.on("error", closed.reject);
wrapped.on("secure", () => (wrapped as any)._handle.close());
for (const event of ["finish", "close"]) wrapped.on(event, () => events.push(event));
wrapped.on("close", () => closed.resolve());
});
await once(server.listen(0, "127.0.0.1"), "listening");
const { port } = server.address() as AddressInfo;
const client = tls.connect({ port, host: "127.0.0.1", rejectUnauthorized: false });
client.on("error", () => {});
try {
await closed.promise;
expect(events).toEqual(["finish", "close"]);
} finally {
client.destroy();
wrapped?.destroy();
server.close();
}
});

// The peer accepts the TCP connection and never answers the ClientHello (a dead
// TLS backend, a plaintext service on a TLS port). A caller that gives up must
// still finish its writable side and send the FIN, as node does:
Expand Down Expand Up @@ -1986,6 +2078,66 @@ describe.each([
});
});

// Both shapes shut the socket down before it has its TLS handle. The FIN waits
// for the transport, as node's _final does on `connecting`:
// https://github.com/nodejs/node/blob/v26.3.0/lib/internal/tls/wrap.js#L964-L973
describe.concurrent("before the TLS handle is attached", () => {
it.skipIf(!exe)("end() and destroySoon() wait for a tls.connect({ socket }) transport to connect", async () => {
const ended = {
log: ["transport connect", "finish"],
peerSawFin: true,
writableFinished: true,
readyState: "readOnly",
destroyed: false,
};
const destroyed = {
log: ["transport connect", "finish", "close"],
peerSawFin: true,
writableFinished: true,
readyState: "closed",
destroyed: true,
};
expect(await run("pending-transport")).toEqual({
"end connecting": ended,
"end unconnected": ended,
"destroySoon connecting": destroyed,
"destroySoon unconnected": destroyed,
});
});

// https://github.com/nodejs/node/blob/v26.3.0/lib/internal/tls/wrap.js#L739-L741
it.skipIf(!exe)(
"a tls.connect({ socket }) transport that closes before it connects closes the socket",
async () => {
const closed = { log: ["close"], writableFinished: false, readyState: "closed", destroyed: true };
expect(await run("closed-transport")).toEqual({
"end refused": closed,
"end destroyed": closed,
"destroySoon refused": closed,
"destroySoon destroyed": closed,
});
},
);

// https://github.com/nodejs/node/blob/v26.3.0/src/crypto/crypto_tls.cc#L1119-L1133
it.skipIf(!exe)(
"end('') over a tls.connect({ socket }) transport that is still connecting follows the handshake",
async () => {
expect(await run("end-over-connecting-socket")).toEqual({
log: ["end connecting=true", "secureConnect", "finish", "close"],
serverSawEnd: true,
});
},
);

it.skipIf(!exe)("a server-side TLSSocket end()s and destroySoon()s in the tick that wraps the socket", async () => {
expect(await run("server-same-tick")).toEqual({
end: { log: ["finish"], clientSawFin: true, writableFinished: true, destroyed: false },
destroySoon: { log: ["finish", "close"], clientSawFin: true, writableFinished: true, destroyed: true },
});
});
});

it.skipIf(!exe)("a server-side TLSSocket end()s while it waits for the client's first flight", async () => {
expect(await run("server-end")).toEqual({
log: ["end secureConnecting=true", "finish"],
Expand Down
Loading