Skip to content
Closed
Show file tree
Hide file tree
Changes from 8 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/sql_jsc/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ pub mod shared {
#[path = "SQLDataCell.rs"]
pub mod sql_data_cell;

pub mod socket_teardown;

pub use cached_structure::CachedStructure;
pub(crate) use query_binding_iterator::QueryBindingIterator;
}
5 changes: 4 additions & 1 deletion src/sql_jsc/mysql/MySQLConnection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ use crate::mysql::js_mysql_connection::JSMySQLConnection;
use crate::mysql::js_mysql_query::JSMySQLQuery;
use crate::mysql::my_sql_request_queue::MySQLRequestQueue;
use crate::mysql::my_sql_statement::{self as mysql_statement, MySQLStatement, Param};
use crate::shared::socket_teardown;
use bun_ptr::RefPtr;

pub use bun_sql::mysql::protocol::error_packet::ErrorPacket;
Expand Down Expand Up @@ -282,8 +283,10 @@ impl MySQLConnection {
}

pub(crate) fn close(&mut self) {
self.socket.close(uws::CloseKind::Normal);
self.write_buffer = OffsetByteList::default();
// A copy: the close dispatches `on_close`, which detaches `self.socket`.
let socket = self.socket;
socket_teardown::close_now(&socket);
}

pub(crate) fn clean_queue_and_close(
Expand Down
7 changes: 5 additions & 2 deletions src/sql_jsc/postgres/PostgresSQLConnection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ use crate::postgres::postgres_sql_statement::{Error as StatementError, Status as
use crate::postgres::sasl::SASLStatus;
use crate::shared::CachedStructure as PostgresCachedStructure;
use crate::shared::connection_ctor_args::ConnectionCtorArgs;
use crate::shared::socket_teardown;
use bun_sql::postgres::AnyPostgresError;
use bun_sql::postgres::PostgresErrorOptions;
use bun_sql::postgres::PostgresProtocol as protocol;
Expand Down Expand Up @@ -1484,11 +1485,13 @@ impl PostgresSQLConnection {
fn ref_and_close(&self, js_reason: Option<JSValue>) {
// refAndClose is always called when we wanna to disconnect or when we are closed

if !self.socket.get().is_closed() {
// A copy: the close dispatches `on_close`, which detaches `self.socket`.
let socket = *self.socket.get();
if !socket.is_closed() {
// event loop need to be alive to close the socket
self.poll_ref.with_mut(|r| r.ref_(self.vm_ctx()));
// will unref on socket close
self.socket.get().close(uws::CloseKind::Normal);
socket_teardown::close_now(&socket);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

// cleanup requests
Expand Down
17 changes: 17 additions & 0 deletions src/sql_jsc/shared/socket_teardown.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
//! Teardown of a database socket the client has given up on.

use bun_uws::{AnySocket, CloseCode};

/// Closes `socket` before this returns, whatever the peer does.
/// `CloseCode::Normal` on a TLS socket would wait for the peer's close_notify.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub(crate) fn close_now(socket: &AnySocket) {
// shutdown() before the handshake finished makes usockets report the handshake as failed
if matches!(socket, AnySocket::SocketTls(_)) && socket.is_ssl_handshake_finished() {
socket.shutdown();
}
socket.close(CloseCode::FastShutdown);
// usockets defers a fast shutdown while ciphertext is stuck behind a full kernel buffer
if !socket.is_closed() {
socket.close(CloseCode::Failure);
}
}
11 changes: 11 additions & 0 deletions src/uws_sys/socket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,16 @@ impl<const IS_SSL: bool> NewSocketHandler<IS_SSL> {
)
}

/// Always true for a plain TCP socket. False while connecting or once detached.
pub fn is_ssl_handshake_finished(&self) -> bool {
on_socket!(self.socket;
connected s => s.is_ssl_handshake_finished(),
duplex d => d.is_established(),
pipe p => p.is_established(),
else => false,
)
}

#[inline]
pub fn is_closed_or_has_error(&self) -> bool {
self.is_closed() || self.is_shutdown() || self.get_error() != 0
Expand Down Expand Up @@ -939,6 +949,7 @@ impl AnySocket {
fn is_closed(&self) -> bool;
fn is_shutdown(&self) -> bool;
fn is_established(&self) -> bool;
fn is_ssl_handshake_finished(&self) -> bool;
fn close(&self, code: CloseCode);
fn write(&self, data: &[u8]) -> i32;
fn set_timeout(&self, seconds: c_uint);
Expand Down
6 changes: 6 additions & 0 deletions src/uws_sys/us_socket_t.rs
Original file line number Diff line number Diff line change
Expand Up @@ -465,6 +465,11 @@ impl us_socket_t {
c::us_socket_is_established(self) > 0
}

/// Always true for a plain TCP socket.
pub(crate) fn is_ssl_handshake_finished(&self) -> bool {
c::us_socket_is_ssl_handshake_finished(self) > 0
}

pub(crate) fn queued_input(&self) -> QueuedInput {
match c::us_socket_queued_input(self) {
LIBUS_QUEUED_INPUT_DATA => QueuedInput::Data,
Expand Down Expand Up @@ -579,6 +584,7 @@ mod c {
pub(super) safe fn us_socket_verify_error(s: &us_socket_t) -> us_bun_verify_error_t;
pub(super) safe fn us_socket_get_error(s: &us_socket_t) -> c_int;
pub(super) safe fn us_socket_is_established(s: &us_socket_t) -> i32;
pub(super) safe fn us_socket_is_ssl_handshake_finished(s: &us_socket_t) -> i32;
pub(super) safe fn us_socket_queued_input(s: &us_socket_t) -> c_int;

/// ssl_ctx is required (the whole point); sni may be null.
Expand Down
230 changes: 228 additions & 2 deletions test/js/sql/sql-close-pending-connection.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,23 @@
// connectionTimeout: 0 disables the connect timer, so close() is the only
// thing that can tear the connection down — without the fix these tests hang.

import { SQL } from "bun";
import { SQL, type Socket } from "bun";
import { expect, mock, test } from "bun:test";
import { listeningServer, neverAnsweringServer, pgAuthenticationOk, pgReadyForQuery } from "./wire-frames";
import { bunEnv, bunExe, tls as tlsCert } from "harness";
import {
listeningServer,
MYSQL_CLIENT_SSL,
MYSQL_DEFAULT_CAPABILITIES,
mysqlAckSessionSetup,
mysqlHandshakeV10,
mysqlOkPacket,
mysqlRawPacket,
mysqlReadPackets,
neverAnsweringServer,
pgAuthenticationOk,
pgReadyForQuery,
pgSSLResponse,
} from "./wire-frames";

const drivers = [
["postgres", "postgres://postgres@", "ERR_POSTGRES_CONNECTION_CLOSED"],
Expand Down Expand Up @@ -179,3 +193,215 @@ test("pool scans tolerate unassigned connection slots during pool start", async
server.close();
}
});

// A TLS peer that stays silent after the client's close_notify: it answers
// the handshake, reports itself ready, and then holds its side of the
// connection open (a half-open proxy, a partition at shutdown). The client
// used to send close_notify and keep the fd until the peer replied, so the
// pool's close() never settled and the process never exited. Teardown of a
// connection the client has given up on must not depend on the peer.
//
// Bun.listen peers instead of node:tls: a TLSSocket wrapped over a net.Socket
// always ends its own side when the client's close_notify arrives, which is
// exactly the reply a holding peer never sends.
type HoldingPeer = { port: number; ended: Promise<void>; closed: Promise<void>; [Symbol.dispose](): void };

function holdingTlsPeer(
greeting: Buffer | null,
// the length of the client's plaintext SSL request, once enough of it has arrived to tell
sslRequestLength: (buffered: Buffer) => number | undefined,
// answers the complete plaintext SSL request
onSslRequest: (raw: Socket) => void,
onSecureData: (socket: Socket, chunk: Buffer) => void,
): HoldingPeer {
const ended = Promise.withResolvers<void>();
const closed = Promise.withResolvers<void>();
const listener = Bun.listen<Buffer | "upgraded" | undefined>({
hostname: "127.0.0.1",
port: 0,
allowHalfOpen: true,
socket: {
open(raw) {
if (greeting) raw.write(greeting);
},
data(raw, chunk) {
// the raw socket keeps observing bytes after the upgrade
if (raw.data === "upgraded") return;
const buffered = raw.data ? Buffer.concat([raw.data, chunk]) : chunk;
const length = sslRequestLength(buffered);
if (length === undefined || buffered.length < length) {
raw.data = buffered;
return;
}
raw.data = "upgraded";
onSslRequest(raw);
raw.upgradeTLS({
isServer: true,
initialData: buffered.subarray(length),
tls: { key: tlsCert.key, cert: tlsCert.cert },
socket: {
handshake() {},
data: onSecureData,
// the client's close_notify; hold the connection open. The probe
// write only fails, and so only closes this side, once the
// client's fd is gone: the kernel answers it with a reset.
end(socket) {
ended.resolve();
socket.write("probe");
},
close() {
closed.resolve();
},
error() {},
},
});
},
close() {},
error() {},
},
});
return {
port: listener.port,
ended: ended.promise,
closed: closed.promise,
[Symbol.dispose]() {
listener.stop(true);
},
};
}

// `startupReply` answers the StartupMessage
function holdingPostgresPeer(
startupReply: Buffer = Buffer.concat([pgAuthenticationOk(), pgReadyForQuery("I")]),
): HoldingPeer {
let started = false;
return holdingTlsPeer(
null,
// the 8-byte SSLRequest; the client sends nothing else until it sees 'S'
() => 8,
raw => raw.write(pgSSLResponse("S")),
(socket, _chunk) => {
if (started) return;
started = true;
socket.write(startupReply);
},
);
}

// `authReply` answers the HandshakeResponse that carries sequence id `seq`
function holdingMysqlPeer(authReply: (seq: number) => Buffer = seq => mysqlOkPacket(seq + 1)): HoldingPeer {
let buffered = Buffer.alloc(0);
let authed = false;
return holdingTlsPeer(
mysqlHandshakeV10({ capabilities: MYSQL_DEFAULT_CAPABILITIES | MYSQL_CLIENT_SSL }),
// the SSLRequest packet: a 3-byte payload length, a sequence id, the payload
buffered => (buffered.length >= 4 ? 4 + (buffered[0] | (buffered[1] << 8) | (buffered[2] << 16)) : undefined),
() => {},
(socket, chunk) => {
buffered = mysqlReadPackets(Buffer.concat([buffered, chunk]), (seq, payload) => {
if (!authed) {
authed = true;
socket.write(authReply(seq));
return;
}
mysqlAckSessionSetup(socket, payload);
});
},
);
}

const postgresTlsUrl = (port: number) => `postgres://u:p@127.0.0.1:${port}/db?sslmode=require`;
const mysqlTlsUrl = (port: number) => `mysql://root:pw@127.0.0.1:${port}/db`;

const holdingPeers = [
["postgres", holdingPostgresPeer, postgresTlsUrl],
["mysql", holdingMysqlPeer, mysqlTlsUrl],
] as const;

for (const [name, peer, url] of holdingPeers) {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
test.concurrent(`${name}: close() settles against a TLS peer that never answers close_notify`, async () => {
using server = peer();
const sql = new SQL({ url: url(server.port), max: 1, tls: { rejectUnauthorized: false } });
await sql.connect();
await sql.close({ timeout: 0 });
await server.ended;
await server.closed;
});

test.concurrent(
`${name}: idleTimeout eviction settles against a TLS peer that never answers close_notify`,
async () => {
using server = peer();
const closed = Promise.withResolvers<void>();
const sql = new SQL({
url: url(server.port),
max: 1,
idleTimeout: 1,
tls: { rejectUnauthorized: false },
onclose: () => closed.resolve(),
});
await sql.connect();
await closed.promise;
await server.ended;
await server.closed;
await sql.close();
},
);
}

// The peer answers the startup with a message the client rejects: a
// ReadyForQuery before any Authentication message, resp. an auth reply whose
// header byte no auth packet uses. The client fails the connection from
// inside the TLS data dispatch, the same path an ErrorResponse during
// authentication takes.
const protocolViolations = [
["postgres", () => holdingPostgresPeer(pgReadyForQuery("I")), postgresTlsUrl, "ERR_POSTGRES_UNEXPECTED_MESSAGE"],
[
"mysql",
() => holdingMysqlPeer(seq => mysqlRawPacket(seq + 1, Buffer.from([0x42]))),
mysqlTlsUrl,
"ERR_MYSQL_UNEXPECTED_PACKET",
],
] as const;

for (const [name, peer, url, code] of protocolViolations) {
test.concurrent(
`${name}: a protocol violation closes the socket against a TLS peer that never answers close_notify`,
async () => {
using server = peer();
const sql = new SQL({ url: url(server.port), max: 1, tls: { rejectUnauthorized: false } });
const settled = await sql.connect().then(
() => "connected",
e => e.code,
);
expect(settled).toBe(code);
await server.ended;
await server.closed;
await sql.close();
Comment thread
robobun marked this conversation as resolved.
Resolved
},
);
}

test.concurrent("postgres: a rejected certificate over a holding TLS peer does not pin the process", async () => {
using server = holdingPostgresPeer();
await using proc = Bun.spawn({
cmd: [
bunExe(),
"-e",
`
import { SQL } from "bun";
const sql = new SQL("postgres://u:p@127.0.0.1:${server.port}/db?sslmode=verify-full", { max: 1 });
const code = await sql.connect().then(() => "connected", e => e.code);
console.log(code);
// the socket the client gave up on must not keep the event loop alive
setTimeout(() => process.exit(7), 2000).unref();
`,
],
env: bunEnv,
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
expect(stdout).toBe("DEPTH_ZERO_SELF_SIGNED_CERT\n");
expect(stderr).toBe("");
expect(exitCode).toBe(0);
});
Loading