Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 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
6 changes: 6 additions & 0 deletions packages/bun-types/bun.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4065,6 +4065,12 @@ declare module "bun" {
clientRenegotiationLimit?: number;

clientRenegotiationWindow?: number;

/**
* Number of seconds a TLS session minted by this server stays resumable.
* When unset or 0, the TLS library's own default lifetime applies.
*/
sessionTimeout?: number;
}

interface SocketAddress {
Expand Down
9 changes: 9 additions & 0 deletions packages/bun-usockets/src/crypto/openssl.c
Original file line number Diff line number Diff line change
Expand Up @@ -1074,6 +1074,15 @@ SSL_CTX *us_ssl_ctx_build_raw(struct us_bun_socket_context_options_t options,
SSL_CTX_set_options(ssl_context, options.secure_options);
}

/* node:tls `sessionTimeout` stamps the lifetime into every session this
* context mints. BoringSSL splits TLS 1.3 off into a second knob, while
* OpenSSL (so Node) derives both versions from SSL_CTX_set_timeout(). */
if (options.session_timeout > 0) {
SSL_CTX_set_timeout(ssl_context, (uint32_t)options.session_timeout);
SSL_CTX_set_session_psk_dhe_timeout(ssl_context,
(uint32_t)options.session_timeout);
}

/* Surface resumable sessions through the new-session callback the way Node
* does: for TLS 1.3 the resumable session only exists once the peer's
* NewSessionTicket arrives, and BoringSSL only exposes it here. NO_INTERNAL
Expand Down
3 changes: 3 additions & 0 deletions packages/bun-usockets/src/libusockets.h
Original file line number Diff line number Diff line change
Expand Up @@ -433,6 +433,9 @@ struct us_bun_socket_context_options_t {
int request_cert;
unsigned int client_renegotiation_limit;
unsigned int client_renegotiation_window;
// Lifetime in seconds of sessions this context mints (node:tls
// `sessionTimeout`); <= 0 leaves BoringSSL's defaults in place.
int session_timeout;
};

enum create_bun_socket_error_t {
Expand Down
1 change: 1 addition & 0 deletions packages/bun-uws/src/App.h
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ namespace uWS {
int request_cert = 0;
unsigned int client_renegotiation_limit = 3;
unsigned int client_renegotiation_window = 600;
int session_timeout = 0;

/* Conversion operator used internally */
operator struct us_bun_socket_context_options_t() const {
Expand Down
10 changes: 10 additions & 0 deletions src/http/ssl_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ pub struct SSLConfig {
pub protos: CStrPtr,
pub client_renegotiation_limit: u32,
pub client_renegotiation_window: u32,
/// Lifetime in seconds of sessions the SSL_CTX mints (node:tls
/// `sessionTimeout`); 0 = unset/default.
pub session_timeout: i32,
pub requires_custom_request_ctx: bool,
pub is_using_default_ciphers: bool,
pub low_memory_mode: bool,
Expand Down Expand Up @@ -118,6 +121,7 @@ impl SSLConfig {
protos: core::ptr::null(),
client_renegotiation_limit: 0,
client_renegotiation_window: 0,
session_timeout: 0,
requires_custom_request_ctx: false,
is_using_default_ciphers: true,
low_memory_mode: false,
Expand Down Expand Up @@ -214,6 +218,7 @@ impl SSLConfig {
ctx_opts.secure_options = self.secure_options;
ctx_opts.client_renegotiation_limit = self.client_renegotiation_limit;
ctx_opts.client_renegotiation_window = self.client_renegotiation_window;
ctx_opts.session_timeout = self.session_timeout;

ctx_opts
}
Expand Down Expand Up @@ -298,6 +303,9 @@ impl SSLConfig {
if self.client_renegotiation_window != other.client_renegotiation_window {
return false;
}
if self.session_timeout != other.session_timeout {
return false;
}
if self.requires_custom_request_ctx != other.requires_custom_request_ctx {
return false;
}
Expand Down Expand Up @@ -356,6 +364,7 @@ impl SSLConfig {
hash_cstr!(protos);
hasher.update(&self.client_renegotiation_limit.to_ne_bytes());
hasher.update(&self.client_renegotiation_window.to_ne_bytes());
hasher.update(&self.session_timeout.to_ne_bytes());
hasher.update(&[u8::from(self.requires_custom_request_ctx)]);
hasher.update(&[u8::from(self.is_using_default_ciphers)]);
hasher.update(&[u8::from(self.low_memory_mode)]);
Expand Down Expand Up @@ -447,6 +456,7 @@ impl Clone for SSLConfig {
protos: clone_string(self.protos),
client_renegotiation_limit: self.client_renegotiation_limit,
client_renegotiation_window: self.client_renegotiation_window,
session_timeout: self.session_timeout,
requires_custom_request_ctx: self.requires_custom_request_ctx,
is_using_default_ciphers: self.is_using_default_ciphers,
low_memory_mode: self.low_memory_mode,
Expand Down
2 changes: 2 additions & 0 deletions src/js/node/_http_server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,8 @@
ca,
passphrase,
secureOptions,
// null means "not provided"; the native parser only reads undefined as absent.
sessionTimeout: options.sessionTimeout ?? undefined,

Check warning on line 314 in src/js/node/_http_server.ts

View check run for this annotation

Claude / Claude Code Review

https.createServer skips sessionTimeout validation

Unlike `tls.createServer` (which runs `validateSecureContextOptions` in `setSecureContext`), this path forwards `sessionTimeout` verbatim, so `https.createServer({ ..., sessionTimeout: -1 })` is silently accepted (skipped by the native `> 0` guard → default lifetime) instead of throwing `ERR_OUT_OF_RANGE` like Node, and `1.5` fails at `.listen()` with a bindgen error rather than synchronously with the Node code. Not blocking — this file has never called `validateSecureContextOptions` for any TLS
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
requestCert: options.requestCert,
rejectUnauthorized: options.rejectUnauthorized,
});
Expand Down
11 changes: 10 additions & 1 deletion src/js/node/tls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -754,7 +754,9 @@ function newNativeSecureContext(options, cached = true) {
minVersion = tlsStringToProtocolVersion(optMinVersion ?? DEFAULT_MIN_VERSION);
maxVersion = tlsStringToProtocolVersion(optMaxVersion ?? DEFAULT_MAX_VERSION);
}
options = { ...options, minVersion, maxVersion };
// A null sessionTimeout means "not provided" (Node's check is the same),
// but the native option parser only reads `undefined` as absent.
options = { ...options, minVersion, maxVersion, sessionTimeout: options.sessionTimeout ?? undefined };
}
}
const ctx = (cached ? NativeSecureContext.intern : NativeSecureContext.createPrivate)(options);
Expand Down Expand Up @@ -1247,6 +1249,7 @@ function Server(options, secureConnectionListener): void {
this.ca = undefined;
this.passphrase = undefined;
this.secureOptions = undefined;
this.sessionTimeout = undefined;
this._rejectUnauthorized = rejectUnauthorizedDefault();
this._requestCert = undefined;
this.servername = undefined;
Expand Down Expand Up @@ -1379,6 +1382,11 @@ function Server(options, secureConnectionListener): void {
}
this.secureOptions = secureOptions;

// validateSecureContextOptions already range-checked this, and exempts
// null the way Node does. Assign unconditionally so an omitted (or null)
// sessionTimeout clears a previous call's value on the next listen.
this.sessionTimeout = options.sessionTimeout ?? undefined;

const requestCert = options.requestCert || false;

if (requestCert) this._requestCert = requestCert;
Expand Down Expand Up @@ -1440,6 +1448,7 @@ function Server(options, secureConnectionListener): void {
ca: this.ca,
passphrase: this.passphrase,
secureOptions: this.secureOptions,
sessionTimeout: this.sessionTimeout,
rejectUnauthorized: this._rejectUnauthorized,
requestCert: isClient ? true : this._requestCert,
ALPNProtocols: this.ALPNProtocols,
Expand Down
3 changes: 3 additions & 0 deletions src/jsc/generated.rs
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,7 @@ pub struct SSLConfig {
pub ciphers: GenOpt<GenString>,
pub client_renegotiation_limit: u32,
pub client_renegotiation_window: u32,
pub session_timeout: i32,
}

// ── refcount release on drop ──────────────────────────────────────────────
Expand Down Expand Up @@ -560,6 +561,7 @@ struct ExternSSLConfig {
ciphers: RawWTFStringImpl,
client_renegotiation_limit: u32,
client_renegotiation_window: u32,
session_timeout: i32,
}

// safe: same handle/out-param contract as
Expand Down Expand Up @@ -594,6 +596,7 @@ impl SSLConfig {
ciphers: adopt_opt_string(ext.ciphers),
client_renegotiation_limit: ext.client_renegotiation_limit,
client_renegotiation_window: ext.client_renegotiation_window,
session_timeout: ext.session_timeout,
}
}

Expand Down
5 changes: 5 additions & 0 deletions src/runtime/socket/SSLConfig.bindv2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,5 +96,10 @@ export const SSLConfig = b.dictionary(
default: 0,
internalName: "client_renegotiation_window",
},
sessionTimeout: {
type: b.i32,
default: 0,
internalName: "session_timeout",
},
},
);
4 changes: 3 additions & 1 deletion src/runtime/socket/SSLConfig.rs
Original file line number Diff line number Diff line change
Expand Up @@ -231,10 +231,12 @@ impl SSLConfigFromJs for SSLConfig {

result.client_renegotiation_limit = generated.client_renegotiation_limit;
result.client_renegotiation_window = generated.client_renegotiation_window;
result.session_timeout = generated.session_timeout;
any = any
|| result.requires_custom_request_ctx
|| result.client_renegotiation_limit != 0
|| generated.client_renegotiation_window != 0;
|| generated.client_renegotiation_window != 0
|| result.session_timeout != 0;

// We don't need to deinit `result` if `any` is false.
if any { Ok(Some(result)) } else { Ok(None) }
Expand Down
5 changes: 5 additions & 0 deletions src/uws_sys/SocketContext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,9 @@ pub struct BunSocketContextOptions {
pub request_cert: i32,
pub client_renegotiation_limit: u32,
pub client_renegotiation_window: u32,
/// Lifetime in seconds of sessions this context mints (node:tls
/// `sessionTimeout`); <= 0 leaves BoringSSL's defaults in place.
pub session_timeout: i32,
}

impl Default for BunSocketContextOptions {
Expand All @@ -143,6 +146,7 @@ impl Default for BunSocketContextOptions {
request_cert: 0,
client_renegotiation_limit: 3,
client_renegotiation_window: 600,
session_timeout: 0,
}
}
}
Expand Down Expand Up @@ -243,6 +247,7 @@ impl BunSocketContextOptions {
h.update(bun_core::bytes_of(&self.request_cert));
h.update(bun_core::bytes_of(&self.client_renegotiation_limit));
h.update(bun_core::bytes_of(&self.client_renegotiation_window));
h.update(bun_core::bytes_of(&self.session_timeout));
let mut out = [0u8; 32];
h.final_(&mut out);
out
Expand Down
125 changes: 125 additions & 0 deletions test/js/node/tls/node-tls-session-timeout.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
// `sessionTimeout` is the server's session-lifetime policy: the number of
// seconds a ticket it mints stays resumable. A server must stamp it into every
// session it creates and refuse one that comes back after the window closed.
import { expect, test } from "bun:test";
import { tls as COMMON_CERT } from "harness";
import { once } from "node:events";
import https from "node:https";
import type { AddressInfo } from "node:net";
import tls, { connect, createServer } from "node:tls";

// The session clock has whole-second granularity, so a one-second lifetime is
// only guaranteed expired once two full seconds of wall clock have elapsed.
const SESSION_TIMEOUT_SECONDS = 1;
const PAST_THE_TIMEOUT_MS = SESSION_TIMEOUT_SECONDS * 2000 + 250;
const GET = "GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";

// `sessionTimeout` is exempt from validation when null, so tests pass it.
type Options = tls.TlsOptions & { sessionTimeout?: number | null };

async function startServer(label: string, options: Options, resumesAfterTheWait: boolean) {
const reusedServerSide: boolean[] = [];
const server = createServer({ ...COMMON_CERT, ...options }, socket => {
reusedServerSide.push(socket.isSessionReused());
socket.end();
});
server.listen(0, "127.0.0.1");
await once(server, "listening");
return { label, server, reusedServerSide, resumesAfterTheWait, port: (server.address() as AddressInfo).port };
}

// Resolves on close, which is after the NewSessionTicket a TLSv1.3 server only
// sends post-handshake. `ticket` stays undefined when the server resumes
// without minting a replacement; `request` drives servers that close on reply.
function handshake(port: number, session?: Buffer, request?: string) {
const { promise, resolve, reject } = Promise.withResolvers<{ reused: boolean; ticket?: Buffer }>();
let reused = false;
let ticket: Buffer | undefined;
const socket = connect({ port, host: "127.0.0.1", rejectUnauthorized: false, session }, () => {
reused = socket.isSessionReused();
if (request) socket.write(request);
});
socket.on("session", received => (ticket = received));
socket.on("data", () => {});
socket.on("error", reject);
socket.on("close", () => resolve({ reused, ticket }));
return promise;
}

test("tls.createServer refuses a ticket handed back after sessionTimeout has passed", async () => {
const servers = await Promise.all(
(["TLSv1.2", "TLSv1.3"] as const).flatMap(maxVersion => [
startServer(`${maxVersion} sessionTimeout=1`, { maxVersion, sessionTimeout: SESSION_TIMEOUT_SECONDS }, false),
// 0, null and "omitted" all mean the TLS library's own (hours-long)
// default. Same cert, key and version as the one-second server above, so
// these also pin that the SSL_CTX cache keys on sessionTimeout.
startServer(`${maxVersion} sessionTimeout=0`, { maxVersion, sessionTimeout: 0 }, true),
startServer(`${maxVersion} sessionTimeout=null`, { maxVersion, sessionTimeout: null }, true),
startServer(`${maxVersion} no sessionTimeout`, { maxVersion }, true),
]),
);
try {
const fresh = await Promise.all(servers.map(({ port }) => handshake(port)));
expect(fresh.map(({ reused, ticket }) => ({ reused, gotTicket: ticket !== undefined }))).toEqual(
servers.map(() => ({ reused: false, gotTicket: true })),
);

await Bun.sleep(PAST_THE_TIMEOUT_MS);

const again = await Promise.all(servers.map(({ port }, i) => handshake(port, fresh[i].ticket)));

expect(
servers.map(({ label, reusedServerSide }, i) => ({
label,
client: again[i].reused,
server: reusedServerSide[1],
})),
).toEqual(
servers.map(({ label, resumesAfterTheWait }) => ({
label,
client: resumesAfterTheWait,
server: resumesAfterTheWait,
})),
);
} finally {
for (const { server } of servers) server.close();
}
await Promise.all(servers.map(({ server }) => once(server, "close")));
});

test("https.createServer stamps sessionTimeout into its tickets too", async () => {
const server = https.createServer({ ...COMMON_CERT, sessionTimeout: SESSION_TIMEOUT_SECONDS }, (_, res) => res.end());
server.listen(0, "127.0.0.1");
await once(server, "listening");
try {
const port = (server.address() as AddressInfo).port;
const fresh = await handshake(port, undefined, GET);
expect({ reused: fresh.reused, gotTicket: fresh.ticket !== undefined }).toEqual({ reused: false, gotTicket: true });

await Bun.sleep(PAST_THE_TIMEOUT_MS);

expect((await handshake(port, fresh.ticket, GET)).reused).toBe(false);
} finally {
server.close();
}
await once(server, "close");
});

// A null sessionTimeout is exempt from validation (Node's check is the same) and
// has to reach the native option parser as `undefined`, which is the only value
// that parser reads as absent. The server cases above already cover
// tls.createServer; these are the other two paths that forward the option.
test("sessionTimeout: null is accepted as 'not provided'", async () => {
expect(tls.createSecureContext({ sessionTimeout: null } as Options)).toBeDefined();

const server = https.createServer({ ...COMMON_CERT, sessionTimeout: null } as Options, (_, res) => res.end());
server.listen(0, "127.0.0.1");
await once(server, "listening");
try {
const { reused } = await handshake((server.address() as AddressInfo).port, undefined, GET);
expect(reused).toBe(false);
} finally {
server.close();
}
await once(server, "close");
});
Loading