Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
42 changes: 26 additions & 16 deletions src/js/node/net.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2019,10 +2019,7 @@ Socket.prototype.connect = function connect(...args) {
tls,
socket: this[khandlers],
});
connection.on("data", events[0]);
connection.on("end", events[1]);
connection.on("drain", events[2]);
connection.on("close", events[3]);
attachUpgradedDuplex(this, connection, events);
this._handle = result;
} else {
// upgradeTLS requires an established socket; a socket that is still
Expand Down Expand Up @@ -2070,10 +2067,7 @@ Socket.prototype.connect = function connect(...args) {
tls,
socket: this[khandlers],
});
connection.on("data", events[0]);
connection.on("end", events[1]);
connection.on("drain", events[2]);
connection.on("close", events[3]);
attachUpgradedDuplex(this, connection, events);
this._handle = result;
} else {
this[kupgraded] = connection;
Expand Down Expand Up @@ -2303,6 +2297,28 @@ function hasUnflushedWrites(connection) {
return connection.writableLength > 0 || connection[kwriteCallback] != null;
}

// Wire a transport driven by the stream-level TLS engine (a generic Duplex, a
// named pipe, a socket with unflushed writes) to `self`, the TLS socket over
// it. events[0..3] are the native data/end/drain/close thunks the engine is
// fed from.
//
// The destroy goes on before the native 'close' thunk. Node tears the TLS
// socket down from its stream wrap's 'close' the same way
// (`wrap.on('close', () => this.destroy())`,
// https://github.com/nodejs/node/blob/v26.3.0/lib/internal/tls/wrap.js#L739-L741),
// and the order is what makes the teardown match: the engine's own close
// unwinds the pending handshake, and a socket destroyed first reports neither
// that aborted handshake as an error nor a second 'close'. A transport that
// goes away before the engine exists (the engine is created on a later
// event-loop turn) is reported by this listener alone.
Comment thread
robobun marked this conversation as resolved.
Resolved
function attachUpgradedDuplex(self, connection, events) {
connection.on("close", () => self.destroy());
connection.on("data", events[0]);
connection.on("end", events[1]);
connection.on("drain", events[2]);
connection.on("close", events[3]);
}

function drainOnreadTail(self, fromRead?) {
if (self[kOnreadTail] === undefined) return false;
if (fromRead) self[kOnreadReadRequested] = true;
Expand Down Expand Up @@ -2372,10 +2388,7 @@ Socket.prototype[Symbol.for("::bunUpgradeServerTLS::")] = function (connection,
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]);
attachUpgradedDuplex(this, connection, events);
this[kupgraded] = connection;
this._handle = result;
return;
Expand All @@ -2401,10 +2414,7 @@ Socket.prototype[Symbol.for("::bunUpgradeServerTLS::")] = function (connection,
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]);
attachUpgradedDuplex(this, connection, events);
this._handle = result;
this.emit(kUpgradeAttached);
return;
Expand Down
21 changes: 18 additions & 3 deletions src/runtime/socket/UpgradedDuplex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,13 @@ pub(crate) struct UpgradedDuplex {
/// Replayed by [`Self::drain_pending`] after the staged bytes, preserving
/// the original data-then-EOF order.
pub pending_end: Cell<bool>,
/// The transport closed before the TLS engine existed. Same window as
/// [`Self::pending_data`]: [`Self::close`] has no SSL to shut down, so no
/// close callback fires and nothing else reports the close.
/// `DuplexUpgradeContext::run_event` consumes this when the `StartTLS`
/// task runs and tears the socket down instead of starting an engine for
/// a transport that is already gone.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub pending_close: Cell<bool>,
/// The transport delivered EOF (its 'end' event fired). Teardown payloads
/// (close_notify) are dropped after this; see [`Self::call_write_or_end`].
pub transport_eof: Cell<bool>,
Expand Down Expand Up @@ -408,6 +415,7 @@ impl UpgradedDuplex {
current_timeout: Cell::new(0),
pending_data: JsCell::new(Vec::new()),
pending_end: Cell::new(false),
pending_close: Cell::new(false),
transport_eof: Cell::new(false),
}
}
Expand Down Expand Up @@ -542,9 +550,15 @@ impl UpgradedDuplex {

#[uws_callback(export = "UpgradedDuplex__close")]
pub(crate) fn close(&self) {
if let Some(w) = self.wrapper_ref() {
let _ = w.shutdown(true);
}
let Some(w) = self.wrapper_ref() else {
// `start_tls` is still queued, so there is no SSL to shut down and
// the wrapper's close callback - the whole teardown chain - was
// never registered. Stage the close for `run_event`; see
// [`Self::pending_close`].
Comment thread
robobun marked this conversation as resolved.
Resolved
self.pending_close.set(true);
return;
};
let _ = w.shutdown(true);
}

#[uws_callback(export = "UpgradedDuplex__shutdown")]
Expand Down Expand Up @@ -679,6 +693,7 @@ impl UpgradedDuplex {
self.ssl_error.set(CertError::default());
self.pending_data.set(Vec::new());
self.pending_end.set(false);
self.pending_close.set(false);
self.transport_eof.set(false);
}
}
Expand Down
11 changes: 11 additions & 0 deletions src/runtime/socket/socket_body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4399,6 +4399,17 @@ impl DuplexUpgradeContext {
unsafe { Self::deinit(this.as_ptr()) };
return;
}
// The transport closed while this task was queued.
// `UpgradedDuplex::close` had no engine to shut down then, so
// it staged the close instead. A closed transport can carry no
// handshake: report the close through the normal teardown
// rather than starting an engine that nothing can drive (which
// would also leave this context, its SSL and its strong refs
// alive until the VM stops).
Comment thread
robobun marked this conversation as resolved.
Resolved
if this.upgrade.pending_close.replace(false) {
Self::on_close(this);
return;
}
log!(
"DuplexUpgradeContext.startTLS mode={}",
<&'static str>::from(this.mode)
Expand Down
26 changes: 26 additions & 0 deletions test/js/node/tls/node-tls-connect.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1031,6 +1031,32 @@ describe("application data written over a Duplex transport before the handshake
});
});

it("tls.connect({ socket: duplex }) closes when the transport is destroyed before the handshake starts", async () => {
// The engine over a Duplex transport is created on a later event-loop turn,
// so this destroy lands before it exists. Node wraps the stream at once and
// destroys the TLS socket from the wrap's 'close'
// (https://github.com/nodejs/node/blob/v26.3.0/lib/internal/tls/wrap.js#L739-L741),
// which reports 'close' with hadError === false wherever the destroy lands.
const transport = new Duplex({
read() {},
write(_chunk, _encoding, callback) {
callback();
},
});
const client = tls.connect({ socket: transport, rejectUnauthorized: false });
const events: string[] = [];
const closed = Promise.withResolvers<void>();
client.on("error", (err: NodeJS.ErrnoException) => events.push(`error:${err.code}`));
client.on("close", hadError => {
events.push(`close:${hadError}`);
closed.resolve();
});
transport.destroy();
await closed.promise;
expect(events).toEqual(["close:false"]);
expect(client.destroyed).toBe(true);
});

it("delivers 'session' even when the data handler destroys the socket immediately", async () => {
// The TLS1.3 NewSessionTickets ride in the same read pass as the response
// bytes. If the parked session were only flushed after the data dispatch,
Expand Down
90 changes: 90 additions & 0 deletions test/js/node/tls/node-tls-server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import https from "https";
import net, { AddressInfo } from "net";
import { createTest } from "node-harness";
import { once } from "node:events";
import stream from "node:stream";
import { tmpdir } from "os";
import { join } from "path";
import type { PeerCertificate } from "tls";
Expand Down Expand Up @@ -2033,6 +2034,95 @@ it("destroys a server wrap whose socket was destroyed before the deferred upgrad
}
});

describe("a server wrap over a generic Duplex follows the transport's teardown", () => {
// Node wraps a stream that has no fd in a JSStreamSocket and destroys the
// TLS socket when that wrap closes:
// https://github.com/nodejs/node/blob/v26.3.0/lib/internal/tls/wrap.js#L739-L741
// So a destroyed transport always reaches the TLS socket as 'close' with
// hadError === false. Bun runs a TLS engine over the stream instead, and
// that engine is created on a later event-loop turn, so the cases below
// cover both sides of that turn.
const makeTransport = () =>
new stream.Duplex({
read() {},
write(_chunk, _encoding, callback) {
callback();
},
});
// Resolves with the events the socket emitted, in order.
const recordTeardown = (socket: TLSSocket) => {
const events: string[] = [];
const closed = Promise.withResolvers<string[]>();
socket.on("error", (err: Error & { code?: string }) => events.push(`error:${err.code}`));
socket.on("close", hadError => {
events.push(`close:${hadError}`);
closed.resolve(events);
});
return closed.promise;
};

it("destroying the transport in the same tick as the wrap closes the TLS socket", async () => {
// The engine does not exist yet, so the close has to be held and reported
// when it starts. Without that the socket never closes at all.
const transport = makeTransport();
const wrapped = new TLSSocket(transport, { isServer: true, ...COMMON_CERT });
const teardown = recordTeardown(wrapped);
transport.destroy();
expect(await teardown).toEqual(["close:false"]);
expect(wrapped.destroyed).toBe(true);
});

it("destroying the transport after the engine started closes the TLS socket", async () => {
// The engine is up and its handshake is still pending. The aborted
// handshake must not surface as an ECONNRESET instead of the close.
const transport = makeTransport();
const wrapped = new TLSSocket(transport, { isServer: true, ...COMMON_CERT });
const teardown = recordTeardown(wrapped);
// 'secure' never fires without a peer, but the upgrade task that creates
// the engine is queued ahead of this one.
await new Promise<void>(resolve => setImmediate(resolve));
transport.destroy();
expect(await teardown).not.toContain("error:ECONNRESET");
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
expect(wrapped.destroyed).toBe(true);
});

it("destroying the transport of an established connection closes the TLS socket", async () => {
// Each side's _write pushes into the other, so this handshakes for real
// over two in-memory duplexes (what Playwright's client-certificate proxy
// does with its browser-facing transport).
const makeSide = (peer: () => stream.Duplex) =>
new stream.Duplex({
read() {},
write(chunk, _encoding, callback) {
peer().push(chunk);
callback();
},
final(callback) {
peer().push(null);
callback();
},
});
const clientSide: stream.Duplex = makeSide(() => serverSide);
const serverSide: stream.Duplex = makeSide(() => clientSide);
const wrapped = new TLSSocket(serverSide, { isServer: true, ...COMMON_CERT });
const client = connect({ socket: clientSide, rejectUnauthorized: false });
try {
const secured = Promise.withResolvers<void>();
client.on("error", secured.reject);
wrapped.on("error", secured.reject);
wrapped.on("secure", () => secured.resolve());
await secured.promise;
const teardown = recordTeardown(wrapped);
serverSide.destroy();
expect(await teardown).toEqual(["close:false"]);
expect(wrapped.destroyed).toBe(true);
} finally {
client.destroy();
wrapped.destroy();
}
});
});

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
Loading