From 44756b9e414cb071f2bb3bc5e95725f31f2a3ef3 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 25 Aug 2026 04:46:34 +0000 Subject: [PATCH 1/6] tls: close a destroyed TLS socket with a bare FIN, no close_notify Destroying a TLS socket (code 2, the _handle.close() path) sent a close_notify alert before it closed the fd. Node sends the alert only from the end() path and closes a destroyed socket with a bare FIN. The destroy-time alert lands in the peer's receive buffer ahead of the FIN. A peer whose stream is paused never reads it, so that stream's 'end' and 'close' are withheld forever. undici's SOCKS5 + requestTls flow leaks one proxy connection per HTTPS request because of this. Fixes #40401 --- packages/bun-usockets/src/crypto/openssl.c | 18 +++--- src/runtime/socket/socket_body.rs | 16 ++--- test/regression/issue/40401.test.ts | 71 ++++++++++++++++++++++ 3 files changed, 90 insertions(+), 15 deletions(-) create mode 100644 test/regression/issue/40401.test.ts diff --git a/packages/bun-usockets/src/crypto/openssl.c b/packages/bun-usockets/src/crypto/openssl.c index 9a590a5c412a..d5136f6647b1 100644 --- a/packages/bun-usockets/src/crypto/openssl.c +++ b/packages/bun-usockets/src/crypto/openssl.c @@ -1849,7 +1849,7 @@ static int ssl_renegotiate(struct us_socket_t *s) { /* Returns 1 if shutdown is complete (or impossible) and the TCP socket may be * closed; 0 if we sent close_notify but must wait for the peer's. */ -static int ssl_handle_shutdown(struct us_socket_t *s, int force_fast_shutdown) { +static int ssl_handle_shutdown(struct us_socket_t *s) { if (!s->ssl || us_internal_ssl_is_shut_down(s) || s->ssl_fatal_error || !SSL_is_init_finished(s_ssl(s))) return 1; @@ -1859,7 +1859,6 @@ static int ssl_handle_shutdown(struct us_socket_t *s, int force_fast_shutdown) { if (!sent_shutdown || !received_shutdown) { ssl_set_loop_data(s); int ret = SSL_shutdown(s_ssl(s)); - if (ret == 0 && force_fast_shutdown) ret = SSL_shutdown(s_ssl(s)); if (ret < 0) { int err = SSL_get_error(s_ssl(s), ret); if (err == SSL_ERROR_SSL || err == SSL_ERROR_SYSCALL) { @@ -1942,9 +1941,14 @@ struct us_socket_t *us_internal_ssl_close(struct us_socket_t *s, int code, void if (ssl_gone(s)) return s; } - /* code == 2 (forceful — `_destroy()` / `_handle.close()`): send close_notify - * best-effort and raw-close now. The destroy path detaches + poll_ref.unref() - * right after, so deferring would orphan the us_socket_t. + /* code == 2 (forceful — `_destroy()` / `_handle.close()`): raw-close now, + * with no close_notify — a bare FIN, like node's destroy (crypto_tls.cc + * only sends the alert from DoShutdown, the end() path). A destroy-time + * alert would land in the peer's receive buffer ahead of the FIN, and a + * peer whose stream is paused never reads it, which holds that stream's + * 'end'/'close' back forever (node semantics). The destroy path also + * detaches + poll_ref.unref() right after, so deferring would orphan the + * us_socket_t. * * code == 1 (reset — terminate() / abort): no close_notify, only the RST, * like node's resetAndDestroy(). @@ -1957,7 +1961,7 @@ struct us_socket_t *us_internal_ssl_close(struct us_socket_t *s, int code, void * under low-prio fan-out (connectionListener race). The actual raw-close * happens via on_end/ZERO_RETURN re-entering this function with * SSL_SENT_SHUTDOWN already set (ssl_handle_shutdown then returns 1). */ - if (code == LIBUS_SOCKET_CLOSE_CODE_CONNECTION_RESET || ssl_handle_shutdown(s, code != 0)) { + if (code != LIBUS_SOCKET_CLOSE_CODE_CLEAN_SHUTDOWN || ssl_handle_shutdown(s)) { return us_internal_socket_close_raw(s, code, reason); } return s; @@ -2608,7 +2612,7 @@ void us_internal_ssl_shutdown(struct us_socket_t *s) { /* ssl_handle_shutdown sends the close_notify (BoringSSL's do_tls_write * prepends any pending TLS 1.3 NewSessionTicket flight to the alert, so * tickets are still delivered) and owns the error handling. */ - ssl_handle_shutdown(s, 0); + ssl_handle_shutdown(s); us_internal_socket_raw_shutdown(s); return; } diff --git a/src/runtime/socket/socket_body.rs b/src/runtime/socket/socket_body.rs index 11dbb7473836..2291a8d62415 100644 --- a/src/runtime/socket/socket_body.rs +++ b/src/runtime/socket/socket_body.rs @@ -3186,14 +3186,14 @@ impl NewSocket { // `on_connecting_error` synchronously inside `close()` and so does // its own `deref()`; double-releasing it would underflow. let is_semi_connect = socket.socket.get().is_some() && !socket.is_established(); - // `_handle.close()` is the net.Socket `_destroy()` path — Node emits close_notify - // once and closes the fd without waiting for the peer's reply. `.fast_shutdown` - // makes `ssl_handle_shutdown` take the fast branch so the raw close runs - // synchronously (with `.normal` the SSL layer defers waiting for the peer, but we - // detach + unref immediately below, orphaning the `us_socket_t`). NOT `.failure`: - // that arms SO_LINGER{1,0} → RST and drops any data still in the kernel send - // buffer, which `destroy()` after `write()` must not do. The SSL layer may - // defer this close behind its own ciphertext write spill + // `_handle.close()` is the net.Socket `_destroy()` path — Node closes the fd + // with no close_notify (crypto_tls.cc only sends the alert from DoShutdown, + // the end() path), so `.fast_shutdown` raw-closes synchronously: a bare FIN + // (with `.normal` the SSL layer sends close_notify and defers waiting for the + // peer, but we detach + unref immediately below, orphaning the `us_socket_t`). + // NOT `.failure`: that arms SO_LINGER{1,0} → RST and drops any data still in + // the kernel send buffer, which `destroy()` after `write()` must not do. The + // SSL layer may defer this close behind its own ciphertext write spill // (`ssl_close_after_spill`) until the kernel takes the spill or the peer's // FIN arrives, with no timeout; a peer that stopped reading holds it open. socket.close(uws::CloseCode::FastShutdown); diff --git a/test/regression/issue/40401.test.ts b/test/regression/issue/40401.test.ts new file mode 100644 index 000000000000..4a7c84050402 --- /dev/null +++ b/test/regression/issue/40401.test.ts @@ -0,0 +1,71 @@ +// https://github.com/oven-sh/bun/issues/40401 +// Destroying a TLS socket layered over a caller-supplied socket (undici's +// SOCKS5 + requestTls flow) must tear the connection down like node: a bare +// FIN, with no close_notify written from the destroy path (node only sends +// the alert from the end() path). A destroy-time alert lands in the tunnel +// proxy's receive buffer ahead of the FIN. The proxy's socket is paused once +// its pipe target is gone, the alert is never read, and node stream +// semantics then withhold 'end'/'close' forever, so the proxy leaks one +// connection per request. +import { expect, test } from "bun:test"; +import { tls as tlsCert } from "harness"; +import { once } from "node:events"; +import net from "node:net"; +import tls from "node:tls"; + +const listen = (server: net.Server) => + new Promise(resolve => + server.listen(0, "127.0.0.1", () => resolve((server.address() as net.AddressInfo).port)), + ); + +test("destroying a TLS socket over a tunneled net.Socket sends a bare FIN", async () => { + // TLS echo target. It never closes its side, so every byte the tunnel sees + // from the client after the reply comes from the client's own teardown. + const target = tls.createServer({ cert: tlsCert.cert, key: tlsCert.key }, socket => { + socket.on("error", () => {}); + socket.on("data", () => socket.write("ok")); + }); + const targetPort = await listen(target); + + // Byte-piping tunnel proxy, as a SOCKS5 proxy is after CONNECT. + let countTeardownBytes = false; + let teardownBytes = 0; + const clientEnded = Promise.withResolvers(); + const clientClosed = Promise.withResolvers(); + const proxy = net.createServer(client => { + client.on("error", () => {}); + client.on("data", chunk => { + if (countTeardownBytes) teardownBytes += chunk.length; + }); + client.on("end", () => clientEnded.resolve()); + client.on("close", () => clientClosed.resolve()); + const up = net.connect(targetPort, "127.0.0.1"); + up.on("error", () => {}); + client.pipe(up); + up.pipe(client); + }); + const proxyPort = await listen(proxy); + + // The client: a raw socket through the tunnel, TLS layered on top. + const raw = net.connect(proxyPort, "127.0.0.1"); + await once(raw, "connect"); + const secure = tls.connect({ socket: raw, ca: tlsCert.cert, servername: "localhost" }); + secure.on("error", () => {}); + await once(secure, "secureConnect"); + + secure.write("hello"); + const [reply] = await once(secure, "data"); + expect(reply.toString()).toBe("ok"); + + // Destroy, as undici does when a response carries 'connection: close'. + // Node sends nothing here, only the FIN. + countTeardownBytes = true; + secure.destroy(); + + await clientEnded.promise; + expect(teardownBytes).toBe(0); + await clientClosed.promise; + + proxy.close(); + target.close(); +}); From 2c7f234282f289ffa81cb5231b17d7e1a5830474 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 25 Aug 2026 04:51:40 +0000 Subject: [PATCH 2/6] test: clean up sockets and listeners on every exit path --- test/regression/issue/40401.test.ts | 37 ++++++++++++++++------------- 1 file changed, 20 insertions(+), 17 deletions(-) diff --git a/test/regression/issue/40401.test.ts b/test/regression/issue/40401.test.ts index 4a7c84050402..a3915a49f243 100644 --- a/test/regression/issue/40401.test.ts +++ b/test/regression/issue/40401.test.ts @@ -48,24 +48,27 @@ test("destroying a TLS socket over a tunneled net.Socket sends a bare FIN", asyn // The client: a raw socket through the tunnel, TLS layered on top. const raw = net.connect(proxyPort, "127.0.0.1"); - await once(raw, "connect"); - const secure = tls.connect({ socket: raw, ca: tlsCert.cert, servername: "localhost" }); - secure.on("error", () => {}); - await once(secure, "secureConnect"); + try { + await once(raw, "connect"); + const secure = tls.connect({ socket: raw, ca: tlsCert.cert, servername: "localhost" }); + secure.on("error", () => {}); + await once(secure, "secureConnect"); - secure.write("hello"); - const [reply] = await once(secure, "data"); - expect(reply.toString()).toBe("ok"); + secure.write("hello"); + const [reply] = await once(secure, "data"); + expect(reply.toString()).toBe("ok"); - // Destroy, as undici does when a response carries 'connection: close'. - // Node sends nothing here, only the FIN. - countTeardownBytes = true; - secure.destroy(); + // Destroy, as undici does when a response carries 'connection: close'. + // Node sends nothing here, only the FIN. + countTeardownBytes = true; + secure.destroy(); - await clientEnded.promise; - expect(teardownBytes).toBe(0); - await clientClosed.promise; - - proxy.close(); - target.close(); + await clientEnded.promise; + expect(teardownBytes).toBe(0); + await clientClosed.promise; + } finally { + raw.destroy(); + proxy.close(); + target.close(); + } }); From bf1e844c2ef39699256d2d8d56193808e3f91e10 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 25 Aug 2026 04:53:27 +0000 Subject: [PATCH 3/6] Condense the close-code comment in the close host fn --- src/runtime/socket/socket_body.rs | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/src/runtime/socket/socket_body.rs b/src/runtime/socket/socket_body.rs index 2291a8d62415..75ad557a854e 100644 --- a/src/runtime/socket/socket_body.rs +++ b/src/runtime/socket/socket_body.rs @@ -3186,16 +3186,14 @@ impl NewSocket { // `on_connecting_error` synchronously inside `close()` and so does // its own `deref()`; double-releasing it would underflow. let is_semi_connect = socket.socket.get().is_some() && !socket.is_established(); - // `_handle.close()` is the net.Socket `_destroy()` path — Node closes the fd - // with no close_notify (crypto_tls.cc only sends the alert from DoShutdown, - // the end() path), so `.fast_shutdown` raw-closes synchronously: a bare FIN - // (with `.normal` the SSL layer sends close_notify and defers waiting for the - // peer, but we detach + unref immediately below, orphaning the `us_socket_t`). - // NOT `.failure`: that arms SO_LINGER{1,0} → RST and drops any data still in - // the kernel send buffer, which `destroy()` after `write()` must not do. The - // SSL layer may defer this close behind its own ciphertext write spill - // (`ssl_close_after_spill`) until the kernel takes the spill or the peer's - // FIN arrives, with no timeout; a peer that stopped reading holds it open. + // `_handle.close()` is the net.Socket `_destroy()` path. Node closes the fd + // with no close_notify (crypto_tls.cc sends the alert only from DoShutdown, + // the end() path), so `.fast_shutdown` raw-closes synchronously: a bare FIN. + // Not `.normal`: that defers for the peer's reply while we detach + unref + // below, orphaning the `us_socket_t`. Not `.failure`: that arms + // SO_LINGER{1,0} → RST and drops data still in the kernel send buffer, + // which `destroy()` after `write()` must not do. The SSL layer may still + // defer behind its ciphertext write spill (`ssl_close_after_spill`). socket.close(uws::CloseCode::FastShutdown); this.socket.set(SocketHandler::::DETACHED); let _ = global; From 0a56294419d3fe1f9a87587d900ee24af241f554 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 25 Aug 2026 05:22:37 +0000 Subject: [PATCH 4/6] tls(duplex): drop teardown bytes after the transport delivered EOF A TLS socket over a generic Duplex replied a close_notify from its graceful shutdown after the transport's 'end' event. Node writes nothing there. A transport that forwards to an auto-ended net.Socket throws writeAfterFIN (EPIPE) on that write. Track the transport EOF on UpgradedDuplex and extend the existing teardown-bytes guard with it. --- src/runtime/socket/UpgradedDuplex.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/runtime/socket/UpgradedDuplex.rs b/src/runtime/socket/UpgradedDuplex.rs index 95e90be36307..bde4313a37b8 100644 --- a/src/runtime/socket/UpgradedDuplex.rs +++ b/src/runtime/socket/UpgradedDuplex.rs @@ -65,6 +65,11 @@ pub(crate) struct UpgradedDuplex { /// Replayed by [`Self::drain_pending`] after the staged bytes, preserving /// the original data-then-EOF order. pub pending_end: Cell, + /// The transport delivered EOF (its 'end' event fired). Teardown-phase + /// bytes (close_notify, the trailing end()) are dropped after this: node + /// writes nothing into a transport that already ended, and a transport + /// that forwards to an auto-ended net.Socket throws writeAfterFIN (EPIPE). + pub transport_eof: Cell, } bun_event_loop::impl_timer_owner!(UpgradedDuplex; from_timer_ptr => event_loop_timer); @@ -231,6 +236,9 @@ impl UpgradedDuplex { // probe so write-after-end still errors like node. let teardown = data.is_none() || self.wrapper_ref().is_some_and(|w| w.is_shutdown()); if teardown { + if self.transport_eof.get() { + return; + } match duplex.get(&global, "writableEnded") { Ok(Some(ended)) if ended.to_boolean() => return, Ok(_) => {} @@ -397,6 +405,7 @@ impl UpgradedDuplex { current_timeout: Cell::new(0), pending_data: JsCell::new(Vec::new()), pending_end: Cell::new(false), + transport_eof: Cell::new(false), } } @@ -677,6 +686,7 @@ impl UpgradedDuplex { self.ssl_error.set(CertError::default()); self.pending_data.set(Vec::new()); self.pending_end.set(false); + self.transport_eof.set(false); } } @@ -735,6 +745,7 @@ fn on_end(_global: &JSGlobalObject, frame: &CallFrame) -> JsResult { // SAFETY: see host-fn note above. let this = unsafe { &*self_ptr.cast::() }; + this.transport_eof.set(true); if this.wrapper_ref().is_some() { (this.handlers.on_end)(this.handlers.ctx); } else { From 23bbd8c3b3508d5492c9fe0e0549bc768c6ea617 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 25 Aug 2026 05:50:21 +0000 Subject: [PATCH 5/6] tls(duplex): suppress only teardown payloads after transport EOF The trailing end() goes back through the writableEnded probe, so a half-open transport still sees our FIN. Reject the listen promise on the server error event in the regression test and close the listeners on the failure paths. --- src/runtime/socket/UpgradedDuplex.rs | 14 +++++++++----- test/regression/issue/40401.test.ts | 20 ++++++++++++-------- 2 files changed, 21 insertions(+), 13 deletions(-) diff --git a/src/runtime/socket/UpgradedDuplex.rs b/src/runtime/socket/UpgradedDuplex.rs index bde4313a37b8..79e09cd6bf84 100644 --- a/src/runtime/socket/UpgradedDuplex.rs +++ b/src/runtime/socket/UpgradedDuplex.rs @@ -65,10 +65,8 @@ pub(crate) struct UpgradedDuplex { /// Replayed by [`Self::drain_pending`] after the staged bytes, preserving /// the original data-then-EOF order. pub pending_end: Cell, - /// The transport delivered EOF (its 'end' event fired). Teardown-phase - /// bytes (close_notify, the trailing end()) are dropped after this: node - /// writes nothing into a transport that already ended, and a transport - /// that forwards to an auto-ended net.Socket throws writeAfterFIN (EPIPE). + /// 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, } @@ -236,7 +234,13 @@ impl UpgradedDuplex { // probe so write-after-end still errors like node. let teardown = data.is_none() || self.wrapper_ref().is_some_and(|w| w.is_shutdown()); if teardown { - if self.transport_eof.get() { + // A teardown payload (close_notify) after the transport's readable + // side ended has no reader behind it: node writes nothing there, + // and a transport that forwards into an auto-ended net.Socket + // throws writeAfterFIN (EPIPE). The trailing end() is not a write + // and still goes through the writableEnded probe below, so a + // half-open transport sees our FIN. + if data.is_some() && self.transport_eof.get() { return; } match duplex.get(&global, "writableEnded") { diff --git a/test/regression/issue/40401.test.ts b/test/regression/issue/40401.test.ts index a3915a49f243..79117e2eb4f3 100644 --- a/test/regression/issue/40401.test.ts +++ b/test/regression/issue/40401.test.ts @@ -14,9 +14,10 @@ import net from "node:net"; import tls from "node:tls"; const listen = (server: net.Server) => - new Promise(resolve => - server.listen(0, "127.0.0.1", () => resolve((server.address() as net.AddressInfo).port)), - ); + new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(0, "127.0.0.1", () => resolve((server.address() as net.AddressInfo).port)); + }); test("destroying a TLS socket over a tunneled net.Socket sends a bare FIN", async () => { // TLS echo target. It never closes its side, so every byte the tunnel sees @@ -25,11 +26,11 @@ test("destroying a TLS socket over a tunneled net.Socket sends a bare FIN", asyn socket.on("error", () => {}); socket.on("data", () => socket.write("ok")); }); - const targetPort = await listen(target); // Byte-piping tunnel proxy, as a SOCKS5 proxy is after CONNECT. let countTeardownBytes = false; let teardownBytes = 0; + let targetPort = 0; const clientEnded = Promise.withResolvers(); const clientClosed = Promise.withResolvers(); const proxy = net.createServer(client => { @@ -44,11 +45,14 @@ test("destroying a TLS socket over a tunneled net.Socket sends a bare FIN", asyn client.pipe(up); up.pipe(client); }); - const proxyPort = await listen(proxy); - // The client: a raw socket through the tunnel, TLS layered on top. - const raw = net.connect(proxyPort, "127.0.0.1"); + let raw: net.Socket | undefined; try { + targetPort = await listen(target); + const proxyPort = await listen(proxy); + + // The client: a raw socket through the tunnel, TLS layered on top. + raw = net.connect(proxyPort, "127.0.0.1"); await once(raw, "connect"); const secure = tls.connect({ socket: raw, ca: tlsCert.cert, servername: "localhost" }); secure.on("error", () => {}); @@ -67,7 +71,7 @@ test("destroying a TLS socket over a tunneled net.Socket sends a bare FIN", asyn expect(teardownBytes).toBe(0); await clientClosed.promise; } finally { - raw.destroy(); + raw?.destroy(); proxy.close(); target.close(); } From 89ee539113bbe0e56adc3c84cc316154715eee00 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 25 Aug 2026 06:11:15 +0000 Subject: [PATCH 6/6] test: reject the awaited end on a proxy client error --- test/regression/issue/40401.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/test/regression/issue/40401.test.ts b/test/regression/issue/40401.test.ts index 79117e2eb4f3..7f74dd76bf71 100644 --- a/test/regression/issue/40401.test.ts +++ b/test/regression/issue/40401.test.ts @@ -34,7 +34,9 @@ test("destroying a TLS socket over a tunneled net.Socket sends a bare FIN", asyn const clientEnded = Promise.withResolvers(); const clientClosed = Promise.withResolvers(); const proxy = net.createServer(client => { - client.on("error", () => {}); + // A client error (an RST regression in the destroy path) must fail the + // awaited 'end', not hang the test to its timeout. + client.on("error", clientEnded.reject); client.on("data", chunk => { if (countTeardownBytes) teardownBytes += chunk.length; });