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
18 changes: 11 additions & 7 deletions packages/bun-usockets/src/crypto/openssl.c
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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) {
Expand Down Expand Up @@ -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().
Expand All @@ -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;
Expand Down Expand Up @@ -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;
}
Expand Down
16 changes: 8 additions & 8 deletions src/runtime/socket/socket_body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3186,14 +3186,14 @@ impl<const SSL: bool> NewSocket<SSL> {
// `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
Comment thread
robobun marked this conversation as resolved.
Resolved
// (`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);
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
Expand Down
71 changes: 71 additions & 0 deletions test/regression/issue/40401.test.ts
Original file line number Diff line number Diff line change
@@ -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<number>(resolve =>
server.listen(0, "127.0.0.1", () => resolve((server.address() as net.AddressInfo).port)),
);
Comment thread
claude[bot] marked this conversation as resolved.
Resolved

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<void>();
const clientClosed = Promise.withResolvers<void>();
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());
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
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();

Check warning on line 70 in test/regression/issue/40401.test.ts

View check run for this annotation

Claude / Claude Code Review

Test server cleanup runs after assertions, leaks on failure

Server cleanup (`proxy.close()`/`target.close()`) runs after the assertions at lines 58 and 66, so on the pre-fix build — where `teardownBytes` is nonzero — the test throws before either server is closed. Wrap the body in `try { ... } finally { proxy.close(); target.close(); }` so cleanup runs on failure too, per REVIEW.md's "release every resource … registered BEFORE the assertions" rule.
Comment thread
robobun marked this conversation as resolved.
Resolved
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Loading