Skip to content

node:tls: emit the server 'newSession' and 'resumeSession' events - #32965

Closed
robobun wants to merge 2 commits into
mainfrom
claude/farm/f3268c04/tls-server-session-events
Closed

robobun wants to merge 2 commits into
mainfrom
claude/farm/f3268c04/tls-server-session-events

Conversation

@robobun

@robobun robobun commented Jun 28, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes the server side of node:tls session-ID resumption: tls.Server never emitted the 'newSession' / 'resumeSession' events, so an external TLS session cache (Redis / memcached behind a multi-process TLS terminator) wired up the documented way was silently never consulted and never populated. The listeners attach without error and just never fire.

Fixes #25185

Reproduction

import tls from "node:tls";
import constants from "node:constants";

let newSession = 0, resumeSession = 0;
const srv = tls.createServer({
  key, cert,
  maxVersion: "TLSv1.2",
  secureOptions: constants.SSL_OP_NO_TICKET,
});
srv.on("newSession", (id, data, cb) => { newSession++; cb(); });
srv.on("resumeSession", (id, cb) => { resumeSession++; cb(null, null); });
srv.on("secureConnection", s => s.end());
srv.listen(0, () => { /* connect a node TLS client, then reconnect offering the session */ });

node v26.3.0: { newSession: 2, resumeSession: 1 }
bun: { newSession: 0, resumeSession: 0 }

Cause

No session-cache plumbing on the server side. us_ssl_new_session_cb parked only the serialized session (not SSL_SESSION_get_id) and the server handler table had no session member, so server-minted sessions were discarded. SSL_CTX_sess_set_get_cb was never registered, so 'resumeSession' could not exist.

The other half of the original repro, secureOptions never reaching SSL_CTX_set_options (so SSL_OP_NO_TICKET, the switch that puts a BoringSSL server into session-ID resumption, had no effect), was fixed independently in #33072 while this PR sat. That part is no longer in this diff. Everything below is the session-cache plumbing only.

Fix

  • openssl.c: park SSL_SESSION_get_id alongside the i2d_SSL_SESSION blob and register SSL_CTX_sess_set_get_cb. The get-session callback parks the offered id and returns SSL_magic_pending_session_ptr() so the handshake suspends (SSL_ERROR_PENDING_SESSION); the JS reply comes back through us_socket_session_resolve, which re-drives the handshake with the d2i'd session. A dispatched/resolved state split keeps a spurious poll re-drive from emitting the event twice.
  • The suspension is gated on a new per-SSL marker set only on real us_socket_t attaches. The TLS-over-duplex / named-pipe SSL wrapper carries the existing parked-session marker but has no handshake-suspension resume path, so suspending it would hang the connection forever; it falls through to a full handshake instead.
  • A server's new session is flushed BEFORE the handshake callback so 'newSession' fires before 'secureConnection' (Node's order: the external store runs before the connection listener).
  • net.ts: ServerHandlers gained session (emits newSession(id, data, done)) and resumeSession (emits resumeSession(id, cb)). secureConnection is held until the newSession done callback runs, mirroring Node's _newSessionPending deferral, and the handshakeTimeout stays armed across that deferral so a listener that never calls done is still bounded.

Under BoringSSL a TLS 1.3 server is ticket-only (stateless) and never invokes the session-ID cache callbacks, so these events fire only for TLS <= 1.2 servers that negotiate session-ID resumption. That matches the mode the events serve in Node (Node's own test-tls-session-cache.js asserts they are 0 with tickets enabled).

Prerequisite: bindgenv2's generated headers were not declared to ninja

ServerHandlers gains a member, which grows the SocketConfigHandlers bindgen dictionary. That turned out not to be buildable incrementally, and the first commit here fixes why.

src/codegen/bindgenv2/script.ts's list-outputs reported only the .cpp files, so every Generated<Type>.h was an undeclared side effect of the codegen edge. Ninja treats an undeclared file as a plain source, so a build that rewrites a header cannot dirty the .cpp files that include it but were not themselves regenerated, and restat prunes them. GeneratedSocketConfig.cpp embeds SocketConfigHandlers but is byte-identical when that dictionary grows, so its object kept the 112-byte layout while the regenerated GeneratedSocketConfigHandlers.cpp.o used the new 120-byte one. The link mixes both, and convertDictionary<SocketConfigHandlers> writes 120 bytes into a temporary the stale object sized at 112:

ERROR: AddressSanitizer: stack-buffer-overflow
WRITE of size 120 at 0x7fff00c4d650 thread T0
  #1 convertDictionary<SocketConfigHandlers>  codegen/GeneratedSocketConfigHandlers.cpp:204
  #4 convertDictionary<SocketConfig>          codegen/GeneratedSocketConfig.cpp:33
  #7 bindgenConvertJSToSocketConfig           codegen/GeneratedSocketConfig.cpp:188
  #13 <bun_runtime::socket::listener::Listener>::listen  src/runtime/socket/Listener.rs:185

Clean builds (CI) are unaffected, and a second bun bd self-heals, which is why the debian-13-x64-asan lane was green while bun bd on this branch produced a corrupt binary. Declaring the headers restores the invariant scripts/build/CLAUDE.md already states ("Codegen headers stay order-only: they're declared outputs with restat, so depfile tracking is exact"). bindgen.ts, generate-node-errors.ts and bundle-modules.ts still under-report outputs the same way; that is left alone here, and the comment at the top of scripts/build/codegen.ts now says so plainly instead of claiming it works.

Verification

test/js/node/tls/node-tls-server-session-events.test.ts: 7 tests, each differential-tested against node v26.3.0.

  • newSession / resumeSession ordering vs secureConnection, a synchronous resume hit, an asynchronous resume hit, isSessionReused() true after a resumption.
  • secureConnection is deferred until the async newSession done callback, and the asynchronous resumeSession cache miss falls through to a full handshake and mints a fresh session.
  • A resumeSession callback that replies with a non-Buffer (a string from an external cache) is treated as a cache miss: the handshake completes as a full handshake instead of staying suspended until handshakeTimeout.
  • A synchronously throwing newSession or resumeSession listener still completes the handshake, and the throw surfaces as an uncaughtException the way Node reports it.
  • A TLS 1.3 client leaves both listeners inert.
  • A server-side TLSSocket over a generic Duplex (the SSL-wrapper path) survives a TLS 1.2 session-id reconnect; this test hangs if the suspension gate is removed.

Without the src/ and packages/ changes the session-event assertions fail because neither event ever fires, and the Duplex test hangs. With them: 7 pass, 0 fail.

test/expectations.txt also quarantines test/js/node/test/parallel/test-net-connect-memleak.js on linux-x64-musl. It is the net (non-TLS) variant of test-tls-connect-memleak.js, which is already quarantined on that one lane for the same JSC FinalizationRegistry-vs-setImmediate timing window, and it flipped the two alpine x64 lanes of an earlier build here while passing on every glibc and darwin lane. This diff does not touch the client net.Socket path the test exercises.


[review] gate passed · iteration 16 · 22 files touched

fails on main (without fix)
ASAN without fix: BUILD FAILED (no junit output)
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/js/node/tls/node-tls-server-session-events.test.ts
info: syncing channel updates for nightly-2026-05-06-x86_64-unknown-linux-gnu
info: latest update on 2026-05-06 for version 1.97.0-nightly (e95e73209 2026-05-05)
info: component rust-src is up to date
info: checking for self-update (current version: 1.29.0)
bun test v1.4.0 (4e6897964)

test/js/node/tls/node-tls-server-session-events.test.ts:
=================================================================
==29851==ERROR: AddressSanitizer: stack-buffer-overflow on address 0x7fffc2262140 at pc 0x000007d7ccc2 bp 0x7fffc22616b0 sp 0x7fffc2260e70
WRITE of size 360 at 0x7fffc2262140 thread T0
    #0 0x000007d7ccc1 in __asan_memcpy crtstuff.c
    #1 0x00000a51bd5b in bindgenConvertJSToSocketConfig /workspace/bun/build/debug/codegen/GeneratedSocketConfig.cpp:193:13
    #2 0x00000e8a92a4 in <bun_jsc::generated::SocketConfig>::from_js::{closure#0} /workspace/bun/src/jsc/generated.rs:723:13
    #3 0x00000e923381 in bun_jsc::top_exception_scope::call_false_is_throw_at::<<bun_jsc::generated::
... (truncated)

release without fix: 5 FAILED
bun test v1.4.0-canary.1 (1498d7b77)

test/js/node/tls/node-tls-server-session-events.test.ts:
57 |   const port = (server.address() as AddressInfo).port;
58 |   try {
59 |     // First connection: full handshake, the server mints a resumable session.
60 |     const session1 = await connectOnce(port, undefined);
61 |     // Node emits newSession (the external-cache store) BEFORE secureConnection.
62 |     expect(events).toEqual(["newSession", "secureConnection"]);
                        ^
error: expect(received).toEqual(expected)

  [
-   "newSession",
    "secureConnection",
  ]

- Expected  - 1
+ Received  + 0

      at <anonymous> (/workspace/bun/test/js/node/tls/node-tls-server-session-events.test.ts:62:20)
(fail) tls.Server emits 'newSession' and 'resumeSession' for session-ID resumption [17.52ms]
117 |   server.listen(0, "127.0.0.1", onListen);
118 |   await listening;
119 |   const port = (server.address() as AddressInfo).port;
120 |   try {
121 |     const session1 = await connectOnce(port, undefined);
122 |     expect(newSessionCount).toBe(1);
                                  ^
error: expect(received).toBe(expected)

Expected: 1
Received: 0

      at <ano
... (truncated)
passes on PR (with fix)
ASAN with fix: all passed
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/js/node/tls/node-tls-server-session-events.test.ts
info: syncing channel updates for nightly-2026-05-06-x86_64-unknown-linux-gnu
info: latest update on 2026-05-06 for version 1.97.0-nightly (e95e73209 2026-05-05)
info: component rust-src is up to date
info: checking for self-update (current version: 1.29.0)
bun test v1.4.0 (4e6897964)

test/js/node/tls/node-tls-server-session-events.test.ts:
(pass) tls.Server emits 'newSession' and 'resumeSession' for session-ID resumption [841.98ms]
(pass) tls.Server defers secureConnection until the async 'newSession' callback and handles a cache miss [188.86ms]
(pass) tls.Server session-cache listeners are inert for a TLS 1.3 client [125.72ms]
(pass) tls.Server treats a non-Buffer 'resumeSession' reply as a cache miss [166.33ms]
(pass) a throwing 'newSession' listener completes the handshake and surfaces the throw [1771.97ms]
(pass) a throwing 'resumeSession' listener completes the handshake and surfaces the throw [1853.65ms]
(pass) server-side TLSSocket over a generic duplex survives a TLS 1.2
... (truncated)

release with fix: all passed
$ bun scripts/build.ts --profile=release
info: syncing channel updates for nightly-2026-05-06-x86_64-unknown-linux-gnu
info: latest update on 2026-05-06 for version 1.97.0-nightly (e95e73209 2026-05-05)
info: component rust-src is up to date
info: checking for self-update (current version: 1.29.0)
[configured] bun-profile → bun (stripped)
  target       linux-x64-gnu
  build type   Release
  build dir    ./build/release
  revision     4e68979648
  features     (none)

22 deps, 114 codegen, 1168 objects in 883ms

ninja: Entering directory `/workspace/bun/build/release'
[1/1231] install /workspace/bun
bun install v1.4.0-canary.1 (1498d7b77)

Checked 124 installs across 170 packages (no changes) [11.00ms]
[2/1231] gen ErrorCode+*.h
[3/1231] install /workspace/bun/packages/bun-error
bun install v1.4.0-canary.1 (1498d7b77)

Checked 1 install across 2 packages (no changes) [4.00ms]
[4/1231] install /workspace/bun/src/node-fallbacks
bun install v1.4.0-canary.1 (1498d7b77)

Checked 129 installs across 147 packages (no changes) [12.00ms]
[5/1231] gen bindgenv2
[6/1231] gen .bind.ts → GeneratedBindings.cpp
[7/1231] fetch tinycc
[tinycc] up to date
[8/1230] fetch libjpeg-t
... (truncated)
diff hotspot
packages/bun-usockets/src/crypto/openssl.c         | 239 +++++++++--
 packages/bun-usockets/src/internal/internal.h      |   3 +-
 packages/bun-usockets/src/libusockets.h            |  12 +-
 scripts/build/codegen.ts                           |  21 +-
 src/codegen/bindgenv2/script.ts                    |   4 +
 src/js/node/net.ts                                 | 180 +++++++--
 src/jsc/bindings/JSSocketHandlers.h                |   7 +-
 src/jsc/generated.rs                               |   3 +
 src/runtime/socket/Handlers.rs                     |   5 +
 src/runtime/socket/JSSocketHandlers.rs             |   6 +-
 src/runtime/socket/SocketConfig.bindv2.ts          |   1 +
 src/runtime/socket/UpgradedDuplex.rs               |  11 +-
 src/runtime/socket/WindowsNamedPipe.rs             |  15 +-
 src/runtime/socket/WindowsNamedPipeContext.rs      |   6 +-
 src/runtime/socket/socket_body.rs                  | 145 +++++--
 src/runtime/socket/sockets.classes.ts              |   4 +
 src/runtime/socket/uws_dispatch.rs                 |  52 ++-
 src/uws/lib.rs                                     |  23 +-
 src/uws_sys/socket.rs                              |   9 +
 src/uws_sys/us_socket_t.rs                         |  19 +
 test/expectations.txt                              |   4 +
 .../tls/node-tls-server-session-events.test.ts     | 446 +++++++++++++++++++++
 22 files changed, 1081 insertions(+), 134 deletions(-)

gate history · 2 passed · 0 rejected · iteration 16

evidence per changed file
file                                           reads  edits  tests
packages/bun-usockets/src/crypto/openssl.c       115    203     58
packages/bun-usockets/src/internal/internal.h     10     12     58
packages/bun-usockets/src/libusockets.h           14     17     58
scripts/build/codegen.ts                           2      2     58
src/codegen/bindgenv2/script.ts                    2      2     58
src/js/node/net.ts                                31     39     58
src/jsc/bindings/JSSocketHandlers.h                1      1     58
src/jsc/generated.rs                              12     21     58
src/runtime/socket/Handlers.rs                    27     88     61
src/runtime/socket/JSSocketHandlers.rs             2      4     58
src/runtime/socket/SocketConfig.bindv2.ts         11     21     58
src/runtime/socket/UpgradedDuplex.rs              11     22     58
src/runtime/socket/WindowsNamedPipe.rs            10     25     58
src/runtime/socket/WindowsNamedPipeContext.rs     14     19     58
src/runtime/socket/socket_body.rs                 52     62     58
src/runtime/socket/sockets.classes.ts             10     14     58
(+ 6 more files)

@coderabbitai

coderabbitai Bot commented Jun 28, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

Adds server-side TLS session-id resumption with async resumeSession handling, carries session-id bytes through native and Rust TLS paths, defers Node.js server handshake completion while newSession is pending, and adds tests for session events and reconnect behavior.

Changes

TLS Session-ID Resumption

Layer / File(s) Summary
Native resume state and headers
packages/bun-usockets/src/crypto/openssl.c, packages/bun-usockets/src/libusockets.h, packages/bun-usockets/src/internal/internal.h
Updates native session resume state, parked-session storage, and public/session dispatch declarations to carry session-id lengths and expose session resolution.
Rust FFI, dispatch, and socket resolve
src/uws_sys/us_socket_t.rs, src/uws_sys/socket.rs, src/runtime/socket/uws_dispatch.rs, src/uws/lib.rs
Adds Rust wrappers for native session resolution, extends dispatch shims to split session-id bytes from session payloads, and routes resume requests through the socket bridge.
Socket callback and prototype wiring
src/jsc/generated.rs, src/runtime/socket/Handlers.rs, src/runtime/socket/SocketConfig.bindv2.ts, src/runtime/socket/sockets.classes.ts
Adds on_resume_session across generated bindings, runtime handler storage, callback iteration, validation, and the socket prototype.
TLS session payload forwarding
src/uws/lib.rs, src/runtime/socket/UpgradedDuplex.rs, src/runtime/socket/WindowsNamedPipe.rs, src/runtime/socket/WindowsNamedPipeContext.rs, src/runtime/socket/socket_body.rs
Changes TLS session callbacks to carry both session and session-id bytes, updates buffer copying, and forwards the new session-id argument through duplex and Windows named-pipe TLS paths.
JS TLS server flow
src/js/node/net.ts
Adds deferred secure-handshake completion state, centralizes the server secure tail, defers completion while newSession is pending, and updates resumeSession lookup handling.
SSL config propagation
src/http/ssl_config.rs
Copies secure_options into BunSocketContextOptions during SSLConfig::as_usockets conversion.
TLS session tests
test/js/node/tls/node-tls-server-session-events.test.ts, test/js/node/tls/renegotiation.test.ts
Adds TLS session-cache tests for event ordering, async deferral, TLS 1.3 inactivity, invalid resume payload handling, and Duplex-backed reconnects, plus a helper for single TLS 1.2 client round-trips.

Suggested reviewers

  • Jarred-Sumner
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title is concise and accurately summarizes the main change: server-side node:tls session-event emission.
Description check ✅ Passed The description explains the change and includes verification details, covering the template's two required sections.

Comment @coderabbitai help to get the list of available commands.

@robobun

robobun commented Jun 28, 2026 •

Copy link
Copy Markdown
Collaborator Author

@github-actions

Copy link
Copy Markdown
Contributor

Found 1 issue this PR may fix:

  1. Auto-enable TLS1.2 and TLS1.3 Session Resumption #25185 - This issue requests TLS session resumption via newSession/resumeSession callbacks and SSL_CTX_sess_set_new_cb/SSL_CTX_sess_set_get_cb, which is exactly what this PR implements

If this is helpful, copy the block below into the PR description to auto-close this issue on merge.

Fixes #25185

🤖 Generated with Claude Code

@robobun

robobun commented Jun 28, 2026

Copy link
Copy Markdown
Collaborator Author

Good catch. #25185 asks for exactly this (the newSession/resumeSession callbacks backed by SSL_CTX_sess_set_new_cb/SSL_CTX_sess_set_get_cb), so I added Fixes #25185 to the description.

One note on scope relative to that issue: session-ticket resumption (TLS 1.2 and TLS 1.3) was already handled natively by BoringSSL and needed no callbacks. The piece that was missing, and what this PR adds, is the session-identifier path: the external-cache callbacks these events exist for.

Comment thread src/runtime/socket/Handlers.rs Resolved
Comment thread src/http/ssl_config.rs Resolved
Comment thread src/http/ssl_config.rs Resolved
@robobun

robobun commented Jun 28, 2026 •

Copy link
Copy Markdown
Collaborator Author

Status

Reproduced: tls.createServer with newSession / resumeSession listeners never fires either event on the released bun, so an external TLS session cache is never populated or consulted.

Root cause: the server session-cache plumbing does not exist. The new-session callback discarded SSL_SESSION_get_id, the server handler table had no session member, and SSL_CTX_sess_set_get_cb was never registered, so 'resumeSession' could not exist at all.

A second gap in the original repro, SSLConfig::as_usockets() dropping secure_options so SSL_OP_NO_TICKET never reached the SSL_CTX, was fixed independently in #33072 while this PR sat. It is no longer part of this diff.

Verified against node v26.3.0 as the reference: newSession / resumeSession ordering vs secureConnection, the deferred secureConnection until the newSession done callback, the synchronous and asynchronous resume hit, the asynchronous cache miss, a non-Buffer resumeSession reply, synchronously throwing newSession and resumeSession listeners, a TLS 1.3 client leaving both listeners inert, and a server-side TLSSocket over a generic Duplex surviving a TLS 1.2 session-id reconnect.

test/js/node/tls/node-tls-server-session-events.test.ts: 7 pass, 0 fail with the debug build. Without the src/ and packages/ changes the session-event assertions fail because neither event ever fires, and the Duplex test hangs.

Two commits, at 4e689796:

  1. build: declare bindgenv2's generated headers as ninja outputs. A prerequisite: list-outputs reported only the .cpp files, so a header rewrite could not dirty the .cpp files that include it but were not themselves regenerated. Growing SocketConfigHandlers (this PR does) therefore linked a 112-byte and a 120-byte view of the same struct into one binary. Without it, bun bd on this branch aborts under ASAN with a stack-buffer-overflow in convertDictionary<SocketConfigHandlers>. Clean builds are unaffected.
  2. node:tls: emit the server 'newSession' and 'resumeSession' events. The change itself, rebased onto socket: hold Bun.listen/Bun.connect callbacks in a GC-visited internal-fields cell #31859's GC-visited JSSocketHandlers cell: on_resume_session is rooted as a 15th internal field of that cell instead of through protect(), and the dispatch entry points use the new ThisPtr<Self> shape. All four ssl_trigger_handshake(s, 1) sites now flush the parked session first, so the 'newSession'-before-'secureConnection' ordering holds on the on_writable → SSL_do_handshake completion path too.

All review threads resolved. The automated review cleared this revision with no bugs found and asked for a maintainer sign-off on the security-sensitive TLS handshake-suspension machinery.

CI. Build 71519's red leaves are test/js/web/fetch/fetch-gzip.test.ts, corrupt compressed responses > followed redirect with a malformed chunked body rejects fetch(), across x64-asan, 2019 x64, 2019 x64-baseline, and windows 11 aarch64. That failure is pre-existing on main, not this diff:

  • Reproduced 5/5 on a build of main's own src/ + packages/ with all of this PR's changes reverted.
  • 19 other branches rebased onto the same main commit are failing the same test in CI (builds 71485–71518).
  • main's own build 71494 at c1076ce (my exact base) is "passed", but it only has 55 jobs vs the 287 a PR build runs; it doesn't include the lanes that catch this.
  • The test case was added by fetch: resolve the promise once headers arrive even if body decompression fails #33710 (fetch: resolve the promise once headers arrive even if body decompression fails); the assertion expects code === "InvalidHTTPResponse" but fetch follows the redirect to http://127.0.0.1:1/ and gets "ConnectionRefused". The fetch implementation lives in src/http/ / src/runtime/webcore/fetch/, neither of which this diff touches.

The diff is green and ready for a maintainer; the remaining failure is a main breakage every rebased PR is hitting, not this change.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All three rounds of my earlier feedback are addressed and the bug hunter found nothing new, but this adds handshake-suspension machinery to the BoringSSL crypto path across 19 files — worth a human pass before merging.

Extended reasoning...

Overview

This PR implements node:tls server 'newSession' / 'resumeSession' events end to end: a new SSL_CTX_sess_set_get_cb registration in packages/bun-usockets/src/crypto/openssl.c that can suspend the handshake via SSL_magic_pending_session_ptr() → SSL_ERROR_PENDING_SESSION, a per-listener opt-in flag (us_listen_socket_enable_session_callbacks), a new us_socket_session_resolve re-drive path, Rust FFI plumbing through uws_sys / uws_dispatch / socket_body, a new resolveSession JS host fn, and the JS-side ServerHandlers.session / resumeSession callbacks in net.ts. It also fixes secureOptions and clientRenegotiationLimit/Window being silently dropped in SSLConfig::as_usockets(), and refactors Handlers::protect()/unprotect() to use for_each_callback_field! so the field list can't drift again. ~500 net lines across 19 files (C, Rust, TS), plus a new test file and a new renegotiation test case.

Security risks

The change sits squarely in TLS-handshake-critical code: it registers a get-session callback on every SSL_CTX, adds a new ex_data slot with a free function, dispatches into JS from inside SSL_do_handshake, and adds a new suspend/resume state to the handshake driver. The opt-in gate (ls->session_callbacks) keeps Bun.serve/Bun.listen off the JS-dispatch path, and the synchronous-resolution and socket-destroyed-during-dispatch cases are handled, but the surface area (manual SSL_SESSION_free ownership, d2i_SSL_SESSION on user-supplied bytes, re-entrancy into the loop BIO state) is exactly the kind of thing that benefits from a second pair of eyes.

Level of scrutiny

High. This is production crypto/networking code with manual memory management at the C/Rust FFI boundary, a new handshake state, and JS re-entrancy from inside BoringSSL callbacks. It is well-commented and follows the existing async-SNI pattern closely, but it is neither small nor mechanical.

Other factors

I reviewed this PR across three prior rounds: a real GC-root gap on on_resume_session (fixed in 0df1196 by deriving protect()/unprotect() from the macro), the pre-existing clientRenegotiationLimit/Window drop in as_usockets() (fixed in c5f675e), and an overstated code comment about the limit: 0 case (fixed in 6d6762b). All are resolved; the bug hunter found nothing new on the current head. Test coverage is solid (4 new session-event tests covering sync/microtask/setImmediate resolution + a default-version smoke test, plus a new renegotiation-limit test). Given the scope and the security-sensitive subsystem, deferring to a human reviewer rather than auto-approving.

@robobun
robobun force-pushed the claude/farm/f3268c04/tls-server-session-events branch 2 times, most recently from 5110790 to 91596ee Compare June 28, 2026 10:49

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/js/node/net.ts`:
- Around line 146-149: The explanatory comment blocks in net.ts exceed the
repo’s 3-line comment limit. Trim the affected comments near the
handshake/session handling logic in the relevant sections (including the
deferred handshake, session store acknowledgement, and verifyError notes) so
each stays within 3 lines, keeping only the essential summary and moving any
extra context to the PR description.

In `@src/runtime/socket/Handlers.rs`:
- Line 39: `on_resume_session` is missing GC rooting in `Handlers` and can be
collected before `NewSocket::on_resume_session` calls it after the async
suspend. Update both `protect()` and `unprotect()` to treat `on_resume_session`
the same as the other callback fields, alongside `on_session`, so every
long-lived `JSValue` is rooted and released consistently. Make sure the manual
callback enumeration in those methods includes the new field in the same order
as the struct fields.

In `@src/uws_sys/us_socket_t.rs`:
- Around line 519-523: The `us_socket_session_resolve` shim uses a `(ptr, len)`
buffer contract but is currently declared `safe fn`, which conflicts with the
surrounding convention and hides the fact that the callee reads `length` bytes
from `data`. Change `us_socket_session_resolve` in `us_socket_t` back to
`unsafe`, matching the sibling shims like `us_socket_write`,
`us_socket_raw_write`, and `us_socket_write_check_error`, and then update the
`session_resolve` call site to wrap that call in an `unsafe` block.

In `@src/uws/lib.rs`:
- Around line 1184-1192: The `undocumented_unsafe_blocks` lint is failing
because the `// SAFETY:` comment is no longer directly attached to the `unsafe`
block in the `us_ssl_pop_pending_session` section. Move the `let mut id_len:
c_int = 0;` declaration above the safety comment so the `SAFETY` note
immediately precedes the `unsafe` block, keeping the documentation for that
block intact.

In `@test/js/node/tls/node-tls-server-session-events.test.ts`:
- Around line 160-167: The TLS client helpers in the session event tests are
only rejecting on "error" and registering "close" after the success await, which
lets premature socket shutdowns hang until timeout. Update both helper paths
around the tls.connect usage to arm the "close" failure handler before awaiting
the session/secure-connect promise, and make that handler reject the same
Promise.withResolvers promise so any early peer close fails immediately instead
of relying on the test timeout.
- Around line 145-168: The TLS 1.3 session-events test only checks handshake
success, so it does not verify that the cache hooks stay unused. Update the test
around tls.createServer, newSession, and resumeSession to count each callback
invocation and assert both remain at 0 for the TLS 1.3 connection path, while
still keeping the existing secureConnection and close flow intact.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 88401a4e-22c6-4c27-8874-a6b86da3c170

📥 Commits

Reviewing files that changed from the base of the PR and between a1c39de and cdb0eab.

📒 Files selected for processing (18)
  • packages/bun-usockets/src/crypto/openssl.c
  • packages/bun-usockets/src/internal/internal.h
  • packages/bun-usockets/src/libusockets.h
  • src/http/ssl_config.rs
  • src/js/node/net.ts
  • src/jsc/generated.rs
  • src/runtime/socket/Handlers.rs
  • src/runtime/socket/SocketConfig.bindv2.ts
  • src/runtime/socket/UpgradedDuplex.rs
  • src/runtime/socket/WindowsNamedPipe.rs
  • src/runtime/socket/WindowsNamedPipeContext.rs
  • src/runtime/socket/socket_body.rs
  • src/runtime/socket/sockets.classes.ts
  • src/runtime/socket/uws_dispatch.rs
  • src/uws/lib.rs
  • src/uws_sys/socket.rs
  • src/uws_sys/us_socket_t.rs
  • test/js/node/tls/node-tls-server-session-events.test.ts

Comment thread src/js/node/net.ts Resolved
Comment thread src/runtime/socket/Handlers.rs Resolved
Comment thread src/uws_sys/us_socket_t.rs Resolved
Comment thread src/uws/lib.rs Resolved
Comment thread src/runtime/socket/Handlers.rs Resolved
Comment thread src/runtime/socket/socket_body.rs Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/uws/lib.rs (1)

345-350: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Keep this doc comment within the 3-line limit.

This updated comment runs past the repository’s local comment-length rule; compress it and leave extra context in the PR description. As per coding guidelines, “Keep code comments to 3 lines max.”

Proposed trim
-        /// A new resumable TLS session arrived (serialized SSL_SESSION bytes,
-        /// plus its `SSL_SESSION_get_id` bytes) - node's `'session'` event
-        /// (and the server's `'newSession'`). `None` opts the SSL out of
-        /// session parking entirely (fetch / WebSocket tunnels have no
-        /// consumer).
+        /// A new resumable TLS session arrived: serialized SSL_SESSION bytes
+        /// plus `SSL_SESSION_get_id` bytes. `None` opts out when there is no
+        /// session consumer.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/uws/lib.rs` around lines 345 - 350, The doc comment on the `on_session`
field in `src/uws/lib.rs` exceeds the 3-line comment limit. Shorten the
`on_session` field comment to at most three lines while keeping only the
essential summary of the resumable TLS session behavior; move any extra
explanation into the PR description instead.

Source: Coding guidelines

src/runtime/socket/socket_body.rs (1)

1802-1807: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Trim these TLS session comments to the 3-line limit.

Both changed doc blocks exceed the repository’s comment-length rule. As per coding guidelines, “Keep code comments to 3 lines max.”

Proposed trim
-    /// A new resumable TLS session arrived (the peer's NewSessionTicket was
-    /// processed during an earlier `SSL_read`, or a TLS <= 1.2 server minted
-    /// one). Hands the serialized session (and its `SSL_SESSION_get_id`) to
-    /// the JS `session` handler, mirroring Node's `onnewsession` callback.
-    /// Dispatched from `ssl_flush_pending_session()` after the SSL stack has
-    /// unwound, so the JS handler may safely destroy the socket.
+    /// A new resumable TLS session arrived. Hands the serialized session and
+    /// `SSL_SESSION_get_id` to JS after the SSL stack unwinds, so the handler
+    /// may safely destroy the socket.
@@
-    /// A TLS <= 1.2 server handshake is suspended on the external session-id
-    /// lookup (node:tls server `'resumeSession'`). Hands the offered
-    /// `session_id` to the JS `resumeSession` handler; the handler must call
-    /// `handle.resolveSession(dataOrNull)` to complete the handshake. A
-    /// missing handler resolves immediately as a cache miss so the handshake
-    /// never stalls.
+    /// A TLS <= 1.2 server handshake is suspended on external session lookup.
+    /// Dispatches `resumeSession`; missing handlers resolve as cache misses so
+    /// the handshake never stalls.

Also applies to: 1859-1864

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/runtime/socket/socket_body.rs` around lines 1802 - 1807, The TLS session
doc comments in socket_body.rs exceed the 3-line comment limit and need to be
trimmed. Shorten the affected doc blocks around the resumable TLS session
handling and the other referenced block so each comment stays within three lines
while still identifying the callback flow in ssl_flush_pending_session and the
JS session handler.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@test/js/node/tls/renegotiation.test.ts`:
- Around line 284-290: Shorten the explanatory comment in the renegotiation test
body to no more than 3 lines, keeping only the essential invariant about
clientRenegotiationLimit flowing through SSLConfig::as_usockets() to
us_reneg_policy. Remove the extra PR-context narrative and any repeated
explanation of the bug, and leave the comment concise enough to match the test
comment guideline while still identifying the Bun.connect({ tls }) / SSLWrapper
distinction if needed.
- Around line 332-346: The socket error handler in the Bun.connect test is
swallowing failures, which can leave the Promise.withResolvers outcome pending;
update the socket callbacks in renegotiation.test.ts so the error path rejects
or otherwise settles the awaited promise instead of using an empty error
handler. Use the existing outcome resolver setup around Bun.connect and the
socket.data/close/error callbacks to wire any failure event to a rejection path,
ensuring the test completes on error rather than timing out.

---

Outside diff comments:
In `@src/runtime/socket/socket_body.rs`:
- Around line 1802-1807: The TLS session doc comments in socket_body.rs exceed
the 3-line comment limit and need to be trimmed. Shorten the affected doc blocks
around the resumable TLS session handling and the other referenced block so each
comment stays within three lines while still identifying the callback flow in
ssl_flush_pending_session and the JS session handler.

In `@src/uws/lib.rs`:
- Around line 345-350: The doc comment on the `on_session` field in
`src/uws/lib.rs` exceeds the 3-line comment limit. Shorten the `on_session`
field comment to at most three lines while keeping only the essential summary of
the resumable TLS session behavior; move any extra explanation into the PR
description instead.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 5e088a10-2aa7-45ae-9d49-d47b02d84376

📥 Commits

Reviewing files that changed from the base of the PR and between cdb0eab and 86310ce.

📒 Files selected for processing (8)
  • src/http/ssl_config.rs
  • src/js/node/net.ts
  • src/runtime/socket/Handlers.rs
  • src/runtime/socket/socket_body.rs
  • src/uws/lib.rs
  • src/uws_sys/us_socket_t.rs
  • test/js/node/tls/node-tls-server-session-events.test.ts
  • test/js/node/tls/renegotiation.test.ts

Comment thread test/js/node/tls/renegotiation.test.ts Resolved
Comment thread test/js/node/tls/renegotiation.test.ts Resolved
Comment thread src/js/node/net.ts Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/bun-usockets/src/crypto/openssl.c (1)

1889-1893: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Trim the added block comments to the 3-line limit.

Several changed comments exceed the repo’s comment-length rule. Please condense them while keeping only the durable ordering/lifetime invariant.

Suggested shape
-      /* Same ordering as the no-app-data branch above: a TLS <= 1.2 server
-       * whose client False-Starts (app data piggybacked on CKE+CCS+Finished)
-       * parks the new session in this very SSL_read, and 'newSession' must
-       * reach JS before the handshake callback emits secureConnection. The
-       * client side parks its 'session' until secureConnect in JS. */
+      /* Preserve Node ordering for TLS <= 1.2 False Start: the new-session
+       * callback parked data in this SSL_read, so flush before secureConnection.
+       * Client 'session' remains parked until secureConnect in JS. */

As per coding guidelines, “Keep code comments to 3 lines max.”

Also applies to: 1951-1960, 2022-2028, 2066-2070, 2123-2126

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/bun-usockets/src/crypto/openssl.c` around lines 1889 - 1893, The
added block comments in openssl.c exceed the 3-line comment limit and should be
condensed. Update the affected comment blocks around the SSL_read/session-id
marker logic to keep only the durable ordering/lifetime invariant, and trim the
related comments in the other listed sections so each stays within 3 lines while
preserving the intent. Focus on the comments near the SSL_read callback handling
and the marker/lazy-attach explanation.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@test/js/node/tls/node-tls-server-session-events.test.ts`:
- Around line 227-272: The current test for the throwing `newSession` listener
only verifies that `secureConnection` is eventually unblocked, but it does not
assert that the synchronous exception is still surfaced. Update the
`tls.createServer` / `server.on("newSession")` test to capture and assert the
expected error path (for example via an uncaught exception or equivalent
rejection/throw observation) in addition to `threw === 1`, so the test proves
both cleanup and rethrow behavior.

---

Outside diff comments:
In `@packages/bun-usockets/src/crypto/openssl.c`:
- Around line 1889-1893: The added block comments in openssl.c exceed the 3-line
comment limit and should be condensed. Update the affected comment blocks around
the SSL_read/session-id marker logic to keep only the durable ordering/lifetime
invariant, and trim the related comments in the other listed sections so each
stays within 3 lines while preserving the intent. Focus on the comments near the
SSL_read callback handling and the marker/lazy-attach explanation.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 25f0f508-148a-4345-8a3f-b941684d85b9

📥 Commits

Reviewing files that changed from the base of the PR and between 86310ce and c65080c.

📒 Files selected for processing (6)
  • packages/bun-usockets/src/crypto/openssl.c
  • src/js/node/net.ts
  • src/runtime/socket/socket_body.rs
  • src/uws/lib.rs
  • test/js/node/tls/node-tls-server-session-events.test.ts
  • test/js/node/tls/renegotiation.test.ts

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@test/js/node/tls/node-tls-server-session-events.test.ts`:
- Around line 276-279: The combined expectation in
node-tls-server-session-events.test.ts is weakening stderr into a boolean via
stderr.includes("boom"), so unrelated subprocess output can slip through. Update
the assertion near the stdout/stderr check to compare the normalized stderr
string itself against the exact expected value, keeping the rest of the
expectation in place. Use the existing stdout/stderr capture and the expectation
block around the session events test to locate the change.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 9c7df8f6-7ac0-4ae2-a9d7-29ff908a03bc

📥 Commits

Reviewing files that changed from the base of the PR and between c65080c and 642cd9c.

📒 Files selected for processing (3)
  • packages/bun-usockets/src/crypto/openssl.c
  • src/js/node/net.ts
  • test/js/node/tls/node-tls-server-session-events.test.ts

Comment thread src/js/node/net.ts Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

♻️ Duplicate comments (2)
test/js/node/tls/node-tls-server-session-events.test.ts (2)

286-290: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Trim these comment blocks to the repo’s 3-line limit.

Both explanatory blocks exceed the local maximum; move the extra rationale to the PR description or collapse it into the test name. As per coding guidelines, “Keep code comments to 3 lines max”.

Also applies to: 343-347

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/js/node/tls/node-tls-server-session-events.test.ts` around lines 286 -
290, Trim the explanatory comment blocks in
node-tls-server-session-events.test.ts to the repo’s 3-line limit by shortening
the notes near the resumeSession and uncaughtException cases; keep only the
essential test intent in those comments and move the extra rationale into the PR
description or the test name. Use the nearby comment blocks around the
session-resume subprocess tests as the target for the edit.

Source: Coding guidelines


318-334: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Fail fast when the first connection never mints a session.

This subprocess only progresses from first.on("session"). If the first TLS 1.2 leg errors or closes before emitting a session, the server stays open and the outer test waits on proc.exited until the suite timeout instead of failing on the real regression. Register the close/error failure path before waiting for session and terminate the subprocess from that branch. As per coding guidelines, “Await conditions, wire failures to reject … rather than relying on the test timeout.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/js/node/tls/node-tls-server-session-events.test.ts` around lines 318 -
334, The TLS session test flow in the first connection path can hang if first
never emits "session", because the subprocess only continues from
first.on("session"). Update the logic around first, first.on("error"), and
first.on("close") to register a fail-fast branch before waiting for the session
event, so any premature error/close rejects or terminates the subprocess
immediately instead of leaving server open and relying on the suite timeout.
Keep the existing second connection reuse check intact, but make the failure
path explicit in the same TLS test block.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Duplicate comments:
In `@test/js/node/tls/node-tls-server-session-events.test.ts`:
- Around line 286-290: Trim the explanatory comment blocks in
node-tls-server-session-events.test.ts to the repo’s 3-line limit by shortening
the notes near the resumeSession and uncaughtException cases; keep only the
essential test intent in those comments and move the extra rationale into the PR
description or the test name. Use the nearby comment blocks around the
session-resume subprocess tests as the target for the edit.
- Around line 318-334: The TLS session test flow in the first connection path
can hang if first never emits "session", because the subprocess only continues
from first.on("session"). Update the logic around first, first.on("error"), and
first.on("close") to register a fail-fast branch before waiting for the session
event, so any premature error/close rejects or terminates the subprocess
immediately instead of leaving server open and relying on the suite timeout.
Keep the existing second connection reuse check intact, but make the failure
path explicit in the same TLS test block.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 2a7af67c-5b33-4316-afd2-f06fef40362a

📥 Commits

Reviewing files that changed from the base of the PR and between 642cd9c and 662c1b2.

📒 Files selected for processing (2)
  • src/js/node/net.ts
  • test/js/node/tls/node-tls-server-session-events.test.ts

@robobun

robobun commented Jun 28, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed the review in f2c9ccc.

  • The throwing-resumeSession subprocess now registers its close handler unconditionally and prints + exits on a missing session, so a first leg that errors before minting a session fails the parent's assertion instead of hanging until the suite timeout.
  • Trimmed every over-limit comment block in the test file to the 3-line maximum, not just the two the review sampled (8 total).

All 7 tests in the file still pass with the debug build.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No new issues found and all prior threads are resolved, but this adds a handshake-suspension state machine to openssl.c and threads new FFI through the TLS server path across C/Rust/TS — worth a human pass over the SSL_ERROR_PENDING_SESSION machinery and the GC-rooting change in Handlers.rs.

Extended reasoning...

Overview

This PR implements the server-side 'newSession' / 'resumeSession' events for node:tls (fixes #25185). It spans 19 files across three layers:

  • C (openssl.c): a new per-SSL us_ssl_resume_pending_t state machine (states 0/1/2/3) that suspends the server handshake via SSL_magic_pending_session_ptr() / SSL_ERROR_PENDING_SESSION, dispatches the offered session_id to JS, and re-drives the handshake on us_socket_session_resolve. Also adds a second per-SSL ex_data marker (us_ssl_can_suspend_ex_idx) gating suspension to real us_socket_t attaches only, parks SSL_SESSION_get_id alongside the i2d blob, and reorders ssl_flush_pending_session to run before both ssl_trigger_handshake sites.
  • Rust: new us_dispatch_resume_session / session_resolve FFI shims, on_resume_session callback field threaded through Handlers (with protect()/unprotect() rewritten to use for_each_callback_field!), a new resolveSession host fn, and signature changes to on_session across UpgradedDuplex / WindowsNamedPipe / SSLWrapper to carry the id.
  • TS (net.ts): completeServerHandshake extracted from ServerHandlers.handshake; new session / resumeSession handlers with _newSessionPending / kdeferredSecure deferral; try/catch + process.nextTick(reportError) around both emits.
  • Rider: SSLConfig::as_usockets() now forwards secure_options and client_renegotiation_limit/window (previously dropped).

Security risks

This is TLS-handshake-critical code. The new suspension path means every TLS ≤1.2 server connection that offers a session_id now runs through a new 4-state machine in C with manual SSL_SESSION ownership transfer (d2i_SSL_SESSION → pending->resolved → handed to BoringSSL with *out_copy = 0). The gating on us_ssl_can_suspend_ex_idx is what prevents the SSLWrapper (TLS-over-duplex / named pipe) path from wedging forever, and the state-1-vs-3 split is what prevents double-dispatch on a spurious poll. A bug in either would hang or double-free. The secure_options rider also means SSL_OP_* flags now actually reach SSL_CTX_set_options for the first time on the Bun.listen/Bun.connect/createSecureContext paths — a behavior change for any code that was passing them.

Level of scrutiny

High. This is a new feature in production TLS server handshake code with new C-side state, new unsafe Rust FFI, GC-rooting changes, and a refactor of the server secureConnection emission path. It is well-tested (7 new tests differential-checked against Node, plus the renegotiation rider test) and has been through several review rounds (a real GC-root gap, a dropped-rebase, a non-Buffer hang, a False-Start ordering gap, and two throwing-listener swallows were all caught and fixed). But the blast radius — every accepted TLS connection on a Bun socket — and the subtlety of the C-side suspend/resume/re-drive interaction warrant a maintainer's eyes.

Other factors

  • All 18 review threads (mine and CodeRabbit's) are resolved; the author's responses were substantive and each fix landed with a test or rationale.
  • The bug-hunting system found nothing on the current revision (f2c9ccc).
  • CI shows musl build failures on the latest commit; the author's earlier status comment attributes prior CI red to unrelated flakes/build-type issues, but the current build state should be confirmed before merge.
  • The Handlers::protect()/unprotect() rewrite to for_each_callback_field! is a net improvement (prevents future drift) but changes rooting for all 14 callback fields, not just the new one — worth a quick sanity check that JSValue::ZERO.protect() is indeed a no-op as the author asserts.

@robobun
robobun requested a review from Jarred-Sumner as a code owner June 28, 2026 16:14
@robobun

robobun commented Jun 28, 2026

Copy link
Copy Markdown
Collaborator Author

Confirmed the build state for the automated review's open question.

Build 66448 (at f2c9ccc) had two red leaves, neither from this diff:

  • test/js/node/test/parallel/test-net-connect-memleak.js failed only on the two alpine x64 lanes and passed on every glibc and darwin lane. It is the net variant of test-tls-connect-memleak.js, which test/expectations.txt already quarantines on linux-x64-musl for the same JSC FinalizationRegistry-vs-setImmediate timing window. 238ff7b adds the net variant to the same entry with the same scoping, so it no longer flips the alpine lanes.
  • bun-plugin-svelte is a bundler-output assertion that also fails on main at a1c39de; no overlap with this diff.

All review threads are resolved and the diff is otherwise green.

@robobun

robobun commented Jun 28, 2026

Copy link
Copy Markdown
Collaborator Author

Independently re-verified this from a clean main checkout before picking the branch back up, without reference to the existing diff, and converged on the same two root causes (no server-side dispatch for the new-session callback and no SSL_CTX_sess_set_get_cb; SSLConfig::as_usockets() dropping secure_options) and the same design. Two data points from that pass that are not already on the record here:

OpenSSL-client differential. Node's own spec test for these events (test/js/node/test/parallel/test-tls-session-cache.js) drives the server with openssl s_client -reconnect: one full handshake plus five session-ID resumptions from one cached session, all from a real OpenSSL client rather than the runtime's own. It skips under Bun because common.opensslCli looks for an openssl-cli binary next to the executable. Running that exact shape by hand against this branch (maxVersion: TLSv1.2, secureOptions: SSL_OP_NO_TICKET, newSession and resumeSession both resolving via setImmediate, OpenSSL 3.5.6 client):

node v26.3.0: {"code":0,"reqCount":6,"newCount":1,"resumeCount":5}
bun (branch): {"code":0,"reqCount":6,"newCount":1,"resumeCount":5}

That also exercises the PENDING_SESSION suspend/resume across five sequential asynchronous lookups against an independent TLS stack, which the bun-client tests cannot.

Blast-radius differential. Ran test/js/bun/net/socket.test.ts and test/js/bun/net/tcp-server.test.ts on both this branch and main in the same environment: 14 failures on each, and the two failure sets are identical (they are a local localhost -> ::1-first resolution artifact, unrelated to TLS). http2: 287 pass, 0 fail. The node compat tests touching the changed surface (test-tls-secure-session, test-tls-keylog-tlsv13, test-tls-enable-keylog-cli, test-tls-sni-option, test-tls-sni-server-client, test-tls-snicallback-error, test-tls-session-timeout-errors, test-https-agent-session-eviction) all exit 0. test-https-agent-session-eviction.js is notable: it sets secureOptions: SSL_OP_NO_TICKET, which this branch is the first to actually honor, and it still passes.

Not pushing anything: the two remaining darwin 14 lanes are still queued and the diff is done. The bun-plugin-svelte check is also red on main at a1c39de, and the one failed buildkite job (darwin 26 aarch64) was an artifact-download timeout whose retry passed.

@robobun
robobun force-pushed the claude/farm/f3268c04/tls-server-session-events branch from 238ff7b to e282d23 Compare July 4, 2026 22:22
@robobun

robobun commented Jul 4, 2026

Copy link
Copy Markdown
Collaborator Author

Rebased onto main (the branch had gone conflicting) and force-pushed as e282d23. CodeRabbit's walkthrough above describes the pre-rebase diff; two files it lists are no longer in it.

What changed in the diff

Re-verified on the rebased tree

  • bun bd test test/js/node/tls/node-tls-server-session-events.test.ts: 7 pass, 0 fail.
  • bun run rust:check-all: 10/10 targets, so the WindowsNamedPipe* cfg-gated changes still type-check.
  • node-tls-server.test.ts and bun/net/socket.test.ts have pre-existing ECONNREFUSED-to-the-just-bound-port failures in this sandbox that reproduce identically with the released bun, so they are environmental and not from this diff.

The test/expectations.txt entry stays: test-net-connect-memleak.js exercises the client net.Socket connect path, which this diff does not touch, and its TLS sibling is already quarantined on the same linux-x64-musl lane for the same FinalizationRegistry timing window.

@robobun
robobun force-pushed the claude/farm/f3268c04/tls-server-session-events branch from e282d23 to 8c7b793 Compare July 4, 2026 22:57
@robobun

robobun commented Jul 4, 2026

Copy link
Copy Markdown
Collaborator Author

Amended the commit message in 8c7b793 so it describes only what the commit contains, and re-applied the PR description edit (the first one silently no-op'd, which is why the automated review read the stale Rider section). The description now says 7 tests, names #33072 as where the secureOptions forwarding landed, and has no Rider.

CodeRabbit's walkthrough above is from before the rebase (its reviews are paused): src/http/ssl_config.rs and test/js/node/tls/renegotiation.test.ts are not in this diff. 18 files, all session-cache plumbing.

Why the clientRenegotiationLimit test is not here

It proved that client_renegotiation_limit survives SSLConfig::as_usockets(). That assignment now lives entirely in #33072's diff, so in this PR the test passes with and without the change: it exercises nothing here, and it would be unrelated scope in a session-events PR.

The gap the automated review flags is real, though: #33072 landed the secure_options / client_renegotiation_limit / client_renegotiation_window assignments with no test, so nothing in the tree proves those three reach the SSL_CTX. Parking the test here so it is not lost. Happy to open it as a standalone PR against test/js/node/tls/renegotiation.test.ts if that's wanted; it passed on the debug build when it was part of this branch.

The dropped test
it("Bun.connect honors tls.clientRenegotiationLimit on the native socket path", async () => {
  // Covers the uSockets `Bun.connect({ tls })` path: `clientRenegotiationLimit`
  // must survive `SSLConfig::as_usockets()`, so limit=1 must reject the second
  // renegotiation instead of falling back to the default limit of 3.
  await using attacker = Bun.spawn({
    cmd: [
      "node",
      "-e",
      `
        const tls = require("tls");
        const server = tls.createServer(
          {
            cert: process.env.SERVER_CERT,
            key: process.env.SERVER_KEY,
            minVersion: "TLSv1.2",
            maxVersion: "TLSv1.2",
          },
          socket => {
            socket.on("error", () => {});
            let renegs = 0;
            const again = () => {
              if (renegs >= 2) {
                socket.write("DONE");
                return;
              }
              socket.renegotiate({ rejectUnauthorized: false }, err => {
                if (err) return;
                renegs++;
                again();
              });
            };
            again();
          },
        );
        server.listen(0, () => console.log(server.address().port));
      `,
    ],
    stdout: "pipe",
    stderr: "inherit",
    stdin: "ignore",
    env: { ...bunEnv, SERVER_CERT: tls.cert, SERVER_KEY: tls.key },
  });
  const { value } = await attacker.stdout.getReader().read();
  const port = Number(new TextDecoder().decode(value).trim());

  const { promise: outcome, resolve, reject } = Promise.withResolvers<string>();
  let received = "";
  const sock = await Bun.connect({
    hostname: "127.0.0.1",
    port,
    tls: { rejectUnauthorized: false, clientRenegotiationLimit: 1 },
    socket: {
      data(_s, chunk) {
        received += chunk.toString();
        if (received.includes("DONE")) resolve("got-response");
      },
      // The expected teardown (limit exceeded) arrives as close(); a
      // dispatched error() is an unexpected failure and must surface.
      close() {
        resolve("closed");
      },
      error(_s, err) {
        reject(err);
      },
    },
  });
  try {
    // limit 1: the first renegotiation is allowed, the second exceeds it and
    // the connection is torn down before the server can deliver DONE.
    expect(await outcome).toBe("closed");
  } finally {
    sock.end();
  }
});

@robobun
robobun force-pushed the claude/farm/f3268c04/tls-server-session-events branch from 8c7b793 to d9e25e1 Compare July 5, 2026 00:05
@robobun

robobun commented Jul 5, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed d9e25e1, now two commits. The second is the TLS change, unchanged; the first is a build fix that turned out to be a prerequisite, and it is worth a separate look because it is not specific to this PR.

What happened

Adding resumeSession to the SocketConfigHandlers bindgen dictionary grows that struct by one member. Building that incrementally produces a corrupt binary:

ERROR: AddressSanitizer: stack-buffer-overflow
WRITE of size 120 at 0x7fff00c4d650 thread T0
  #1 convertDictionary<SocketConfigHandlers>  codegen/GeneratedSocketConfigHandlers.cpp:204
  #4 convertDictionary<SocketConfig>          codegen/GeneratedSocketConfig.cpp:33
  #7 bindgenConvertJSToSocketConfig           codegen/GeneratedSocketConfig.cpp:188
  #13 <bun_runtime::socket::listener::Listener>::listen   src/runtime/socket/Listener.rs:185

bindgenv2's list-outputs reported only the .cpp files, so every Generated<Type>.h was an undeclared side effect of the codegen edge. Ninja treats an undeclared file as a plain source, so a build that rewrites a header cannot dirty the .cpp files that include it but were not themselves regenerated, and restat prunes them.

GeneratedSocketConfig.cpp embeds SocketConfigHandlers but is byte-identical when that dictionary grows, so GeneratedSocketConfig.cpp.o kept the 112-byte layout while the regenerated GeneratedSocketConfigHandlers.cpp.o got the 120-byte one. The link mixes both ABIs. Under ASAN you get the overflow above; a release build corrupts the stack silently.

Evidence

Before, in a build dir that had just built the previous revision:

codegen/GeneratedSocketConfigHandlers.h          23:07:22   (rewritten)
obj/codegen/GeneratedSocketConfigHandlers.cpp.o  23:07:38   (recompiled)
obj/codegen/GeneratedSocketConfig.cpp.o          23:06:52   (NOT recompiled)

ninja -t query codegen/GeneratedSocketConfigHandlers.h showed no producing edge, and ninja -n obj/codegen/GeneratedSocketConfig.cpp.o reported it dirty only on the next build, after the damage was linked.

After declaring the headers, the same sequence (build previous revision, then build this one) recompiles the consumer in the same build and the binary is correct:

codegen/GeneratedSocketConfigHandlers.h          00:02:07
obj/codegen/GeneratedSocketConfig.cpp.o          00:02:23

bun bd test test/js/node/tls/node-tls-server-session-events.test.ts then passes 7/7 under ASAN on exactly the build sequence that previously aborted. A second bun bd is a no-op, and --profile=release --configure-only still configures.

Scope

The change is two lines of substance: list-outputs emits cppHeaderPath(type) when type.hasCppHeader, and scripts/build/codegen.ts stops asserting that nothing but .cpp comes back. Headers go into the codegen edge's declared outputs; only the .cpp files are compiled, as before.

This restores the invariant scripts/build/CLAUDE.md already states: "Codegen headers stay order-only: they're declared outputs with restat, so depfile tracking is exact."

bindgen.ts, generate-node-errors.ts and bundle-modules.ts under-report their outputs the same way and are deliberately left alone; the comment at the top of scripts/build/codegen.ts now describes the hazard accurately instead of claiming it works.

Clean builds are unaffected, which is why debian-13-x64-asan-test-bun was green on earlier pushes of this branch while bun bd locally produced a bad binary. Anyone who checks out this branch and builds incrementally would hit it, so it belongs here rather than in a follow-up.

@robobun
robobun force-pushed the claude/farm/f3268c04/tls-server-session-events branch from d9e25e1 to 5f58566 Compare July 5, 2026 01:05
@robobun

robobun commented Jul 5, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed 5f58566.

Review fix

The automated review caught a real invariant break in us_ssl_new_session_cb: prepending the session_id made pending->length equal id_len + i2d_len, but the cap still tested i2d_len alone against US_SSL_PENDING_SESSION_MAX. A parked entry could therefore reach 65568 bytes, which makes the len > out_cap branch in us_ssl_pop_pending (commented as unreachable) reachable on the TLS-over-Duplex / named-pipe path, silently dropping the 'newSession' event. The cap now subtracts the id prefix, so pending->length <= US_SSL_PENDING_SESSION_MAX holds again and both that comment and the SAFETY note in src/uws/lib.rs are accurate. Unreachable in practice (a serialized SSL_SESSION here is a few hundred bytes), but the invariant is worth keeping true rather than documented around.

On the red x64-asan lane

Build 68393 failed one test, test/js/node/tls/tls-syscall-fault.test.ts, on the debian-13 x64-asan lane. It is not from this diff, and it is not reproducible:

  • Build 68382, at 8c7b793c, ran that exact file on that exact lane and reported 11 pass, 0 fail. The runtime source at 8c7b793c and d9e25e16 is byte-identical; the only difference is the two build-script files.
  • bun bd test test/js/node/tls/tls-syscall-fault.test.ts is 11/11 locally, and 12/12 together with socket-syscall-fault.test.ts.
  • Nothing in this diff touches us_internal_init_loop_ssl_data, Bun__outOfMemory, the crash handler, or the fault injector.

The failing assertion is stderr.includes("Bun ran out of memory"). That string is printed by src/crash_handler/lib.rs:1011 only when debug_trace is set; otherwise the handler prints "oh no: Bun has run out of memory.". debug_trace comes from Environment::SHOW_CRASH_TRACE, which is IS_DEBUG || IS_TEST || ENABLE_ASAN (src/bun_core/env.rs:53) — true on this lane, which is why the test normally passes there. In the failing run the handler took the non-trace branch and the child's crash was captured as a report (runner.node.mjs:1419 turns a captured report into "crash reported"), so the test file failed twice over.

I did not chase down what flips SHOW_CRASH_TRACE-gated output between two runs of the same binary, since it is outside this PR. Worth noting for whoever owns #33326: the assertion is coupled to a crash-handler output shape that is evidently not stable on that lane, and Bun ran out of memory vs Bun has run out of memory are two different strings emitted by two branches of the same handler.

@robobun
robobun force-pushed the claude/farm/f3268c04/tls-server-session-events branch from 5f58566 to 43e01f1 Compare July 9, 2026 00:54
@robobun

robobun commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

Rebased onto main (81 commits) and pushed as 43e01f1; mergeable again.

The only non-trivial conflict was #31859, which replaced the 13 protect()/unprotect()-ed JSValue fields on Handlers with a GC-visited JSSocketHandlers internal-fields cell, and the *mut Self dispatch entry points with bun_ptr::ThisPtr<Self>. Everything this PR touched in that layer was rewritten onto the new idiom rather than merged line by line:

  • on_resume_session is now a 15th field of Bun::JSSocketHandlers (JSInternalFieldObjectImpl<15>) and the Rust Field enum, inserted next to Session, so it is rooted through the same visited cell as the other callbacks instead of protect(). The for_each_callback_field! macro I had added no longer exists; CALLBACK_COUNT is derived from the enum, so nothing to hand-update.
  • on_session / on_resume_session / on_keylog in socket_body.rs take ThisPtr<Self> and read their callback through the new handlers.on_xxx() accessors, matching on_session's neighbours exactly. exit_scope has the new single-argument shape.
  • us_dispatch_resume_session and the on_session id-prefix split read the ext slot as Option<ThisPtr<TLSSocket>> and call the safe methods, the same way us_dispatch_session / us_dispatch_keylog do on main.
  • WindowsNamedPipeContext / DuplexUpgradeContext on_session forward the id slice through tls.this_ptr().

No behaviour change; handlers.on_resume_session() resolving through the cell is what rooting through the wrapper's visited handlers slot gives you, which is the point of #31859.

Re-verified on the rebased tree: 7/7 in node-tls-server-session-events.test.ts under bun bd (ASAN); 5 fail with USE_SYSTEM_BUN=1 as before; tls-syscall-fault.test.ts and node-tls-connect.test.ts 26 pass / 0 fail; rust:check-all 10/10 targets, covering the cfg(windows) named-pipe changes.

#33348 landed the tls-syscall-fault.test.ts fix I'd written up two wakes ago, so that note can be ignored.

@robobun
robobun force-pushed the claude/farm/f3268c04/tls-server-session-events branch from 43e01f1 to f719e28 Compare July 9, 2026 01:25
@robobun

robobun commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed f719e28 with the fourth ssl_trigger_handshake(s, 1) site covered.

The automated review found the same bug class as the False-Start ordering fix, at a site that fix did not audit: ssl_update_handshake at what was line 1859. A TLS 1.2 server whose final CCS+Finished write hits WANT_WRITE and then completes via on_writable → SSL_do_handshake runs do_finish_server_handshake → ssl_update_cache → us_ssl_new_session_cb inside that call, so the session is parked when ssl_trigger_handshake(s, 1) fires. 'secureConnection' would reach JS before 'newSession' and the _newSessionPending deferral is bypassed.

Now all four success sites flush the parked session and keylog first. Both ssl_update_handshake sites (the SSL_is_init_finished early check and the SSL_do_handshake == 1 tail) match the two on_data sites. No save/restore: every caller of ssl_update_handshake runs ssl_set_loop_data(s) first, which zeroes the BIO read-input buffer, and the flush functions themselves never touch loop_ssl_data. A flush with nothing parked is a two-check early return, so the benign sites cost nothing.

33 pass / 0 fail across node-tls-server-session-events.test.ts, tls-syscall-fault.test.ts, and node-tls-connect.test.ts.

Build 70752's one hard failure (windows 2019 x64, test/js/sql/postgres-binary-array-bounds.test.ts, every case ERR_POSTGRES_CONNECTION_REFUSED) is a mock-server port race on one agent: the sibling x64-baseline lane and four other x64 shards passed, and both postgres files pass 17/17 under bun bd locally. The same shard also flaked bun-install.test.ts with an unrelated error.

CodeRabbit's walkthrough above is from before the first rebase and lists src/http/ssl_config.rs and test/js/node/tls/renegotiation.test.ts, neither of which is in this diff.

robobun added 2 commits July 10, 2026 12:59
`list-outputs` reported only the `.cpp` files, so every `Generated<Type>.h`
was an undeclared side effect of the codegen edge. Ninja treats an undeclared
file as a plain source, so a build that rewrites a header cannot dirty the
`.cpp` files that include it but were not themselves regenerated; `restat`
prunes them. Those objects keep the previous struct layout while the
regenerated ones get the new one, and the link silently mixes two ABIs. The
depfile only catches it on the next build.

Adding a member to a dictionary that another dictionary embeds is enough to
trigger it: `GeneratedSocketConfigHandlers.h` grows, `GeneratedSocketConfig.cpp`
is byte-identical and is not recompiled, and `convertDictionary<SocketConfigHandlers>`
then writes 120 bytes into a temporary that the stale object sized at 112.
ASAN reports a stack-buffer-overflow; release corrupts the stack silently.

Restores the invariant scripts/build/CLAUDE.md already states: "Codegen
headers stay order-only: they're declared outputs with restat, so depfile
tracking is exact."
tls.Server never emitted 'newSession' or 'resumeSession', so an external
TLS session cache wired up the documented way was never populated and
never consulted.

- openssl.c parks SSL_SESSION_get_id alongside the i2d_SSL_SESSION blob
  and registers SSL_CTX_sess_set_get_cb. The get-session callback parks
  the offered id and returns SSL_magic_pending_session_ptr() so the
  handshake suspends; the JS reply returns through
  us_socket_session_resolve, which re-drives the handshake.
- Suspension is gated on a per-SSL marker set only on real us_socket_t
  attaches. The TLS-over-duplex wrapper has no handshake-resume path, so
  suspending it would hang the connection forever.
- net.ts: ServerHandlers gained session and resumeSession, and holds
  secureConnection until the newSession done callback runs, mirroring
  Node's _newSessionPending deferral.

Under BoringSSL a TLS 1.3 server is ticket-only, so these events fire
only for TLS <= 1.2 servers that negotiate session-id resumption. That
needs SSL_OP_NO_TICKET to reach the SSL_CTX, which SSLConfig::as_usockets()
has forwarded since #33072.

Fixes #25185
@robobun
robobun force-pushed the claude/farm/f3268c04/tls-server-session-events branch from f719e28 to 4e68979 Compare July 10, 2026 13:14
@robobun

robobun commented Jul 10, 2026

Copy link
Copy Markdown
Collaborator Author

Rebased onto main at 4e68979 (32 commits behind); trivial this time.

The only conflict was socket_body.rs: #33755 inserted two new helper fns (reset_client_tls_flags, reject_unauthorized_connection) immediately above on_session, where this PR's modified doc-comment sits. Kept both. openssl.c auto-merged clean against #33803 and #33359.

7/7 in node-tls-server-session-events.test.ts under bun bd (ASAN); rust:check-all 10/10 targets.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't find any bugs in this revision, but this is a large security-sensitive change (new TLS handshake-suspension state machine in openssl.c, JSSocketHandlers internal-field-count bump shared with C++, cross-language FFI across three transport backends, plus a build-system fix) — worth a human look before merging.

Extended reasoning...

Overview

This PR wires up the server side of node:tls session-ID resumption ('newSession' / 'resumeSession' events), which previously never fired. It spans 22 files and ~1080 insertions across four layers: C (packages/bun-usockets/src/crypto/openssl.c, +239 lines — new SSL_CTX_sess_set_get_cb registration, a per-SSL suspension state struct on a new ex_data index, SSL_magic_pending_session_ptr() handshake suspension, and a new us_ssl_can_suspend_ex_idx gate distinguishing real us_socket_t attaches from the SSLWrapper), Rust FFI/dispatch (uws_sys, uws_dispatch.rs, socket_body.rs, three transport backends), the GC-visited JSSocketHandlers cell (14→15 internal fields, ABI-shared between JSSocketHandlers.h and JSSocketHandlers.rs), the node:net built-in module (ServerHandlers.session/resumeSession, _newSessionPending deferral of secureConnection), and a prerequisite build fix declaring bindgenv2's generated headers as ninja outputs.

Security risks

TLS session resumption is security-sensitive. The specific surfaces to scrutinize: (1) the d2i_SSL_SESSION call in us_socket_session_resolve deserializes attacker-influenceable bytes (whatever the user's external cache returns) — the code correctly treats a NULL parse as a miss, but this is BoringSSL's parser on user-supplied data; (2) the new us_ssl_can_suspend_ex_idx gate is what prevents the SSLWrapper path from wedging forever on a session-id offer — if that marker is ever set on an SSL without a resume path, connections hang; (3) the state machine (0/1/2/3) in us_ssl_resume_pending_t must not admit a double-dispatch or a stuck-suspended state. I did not find defects in any of these, and the PR has a dedicated test that hangs if the suspension gate is removed.

Level of scrutiny

High. This is production TLS handshake code in C with a new async-suspension mechanism, cross-language memory ownership (parked session buffers, ex_data lifetimes, JSValue rooting through the internal-fields cell), and an ABI-shared struct layout bump. The build-system change is also load-bearing (without it, incremental builds silently link mixed-ABI object files). The PR has been through 15 review iterations; every prior finding I raised (GC-root gap, non-Buffer resolveSession hang, throwing-listener swallowing, False-Start and WANT_WRITE ordering at all four ssl_trigger_handshake sites, parking-cap invariant) was addressed with tests where testable, and the differential-tested suite (7 tests vs node v26.3.0) plus an OpenSSL-client cross-check are documented.

Other factors

All 15 prior review threads are resolved. The bug-hunting system found nothing new in this revision. CI on the last reported build (70767) was green except for expired darwin-14-aarch64 agent slots. The test/expectations.txt addition quarantines an unrelated musl-only FinalizationRegistry timing flake. Test coverage is thorough for the reachable paths; the two untested edge cases (False-Start ordering, WANT_WRITE completion) are documented as unreachable with scriptable clients. Given the scope, cross-language complexity, and TLS/crypto sensitivity, this needs a maintainer's sign-off rather than bot approval.

@robobun

robobun commented Jul 10, 2026

Copy link
Copy Markdown
Collaborator Author

Agreed on all three points; nothing to add to the verdict. For whoever reviews, here is where to look for each.

d2i_SSL_SESSION on external-cache bytes. us_socket_session_resolve (packages/bun-usockets/src/crypto/openssl.c) runs d2i_SSL_SESSION(NULL, &p, (long)length) on whatever the 'resumeSession' callback's cb(null, sessionData) supplied, which is the user's external store and is attacker-influenceable only in the sense that the user's own cache is. A NULL parse is treated as a miss (full handshake); the parsed session is handed to BoringSSL's resumption path, which re-validates it against the SSL_CTX's constraints. This is the same contract Node's LoadSessionCallback honours: the callback's bytes must be a Buffer, anything else falls through to a full handshake in net.ts's onresume, and resolveSession in socket_body.rs resolves as a miss and throws ERR_INVALID_ARG_TYPE if the native side is somehow reached with a non-Buffer.

The us_ssl_can_suspend_ex_idx gate. Set only inside us_internal_ssl_attach on a real us_socket_t, never on an SSLWrapper SSL (us_ssl_enable_pending_events, which the SSLWrapper path uses, sets the parked-events marker but not the can-suspend marker). get_session_cb checks it before returning SSL_magic_pending_session_ptr(); without it, the callback returns NULL (miss) and the handshake proceeds. The last test in node-tls-server-session-events.test.ts (server-side TLSSocket over a generic Duplex) hangs in under one RTT if that check is removed, which is what makes the gate load-bearing rather than advisory.

The resume-pending state machine. struct us_ssl_resume_pending_t on its own ex_data index, states 0 parked / 1 dispatched / 2 resolved-with-session / 3 resolved-miss. ssl_dispatch_pending_resume transitions 0→1 and hands the id to JS exactly once; a spurious poll re-drive sees state != 0 and returns without re-emitting. us_socket_session_resolve is the only writer of 2/3 and tolerates being called once per connection (a second call is a no-op because the re-driven get_session_cb consumes it and frees the struct). ssl_update_handshake's SSL_ERROR_PENDING_SESSION arm is the only reader of state == 0; the SSL_ERROR_PENDING_CERTIFICATE arm it sits next to is the existing async-SNI mechanism, and the two share the same re-drive shape.

Nothing else outstanding. Build 71519 is running on 4e68979.

@robobun

robobun commented Sep 13, 2026

Copy link
Copy Markdown
Collaborator Author

Closing as part of a cleanup of stale pull requests. This PR has had no new commits since 2026-07-10, it conflicts with main, and its last CI run failed. This is not a judgment on the fix itself. The linked issue (#25185) stays open. If the problem still reproduces on a current build, reopen this PR after a rebase or open a new one against main.

@robobun robobun closed this Sep 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Auto-enable TLS1.2 and TLS1.3 Session Resumption

1 participant