Repository navigation
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughAdds server-side TLS session-id resumption with async ChangesTLS Session-ID Resumption
Suggested reviewers
🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Comment |
|
Found 1 issue this PR may fix:
🤖 Generated with Claude Code |
|
Good catch. #25185 asks for exactly this (the 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. |
|
Status Reproduced: Root cause: the server session-cache plumbing does not exist. The new-session callback discarded A second gap in the original repro, Verified against node v26.3.0 as the reference:
Two commits, at
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
The diff is green and ready for a maintainer; the remaining failure is a |
There was a problem hiding this comment.
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.
5110790 to
91596ee
Compare
There was a problem hiding this comment.
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
📒 Files selected for processing (18)
packages/bun-usockets/src/crypto/openssl.cpackages/bun-usockets/src/internal/internal.hpackages/bun-usockets/src/libusockets.hsrc/http/ssl_config.rssrc/js/node/net.tssrc/jsc/generated.rssrc/runtime/socket/Handlers.rssrc/runtime/socket/SocketConfig.bindv2.tssrc/runtime/socket/UpgradedDuplex.rssrc/runtime/socket/WindowsNamedPipe.rssrc/runtime/socket/WindowsNamedPipeContext.rssrc/runtime/socket/socket_body.rssrc/runtime/socket/sockets.classes.tssrc/runtime/socket/uws_dispatch.rssrc/uws/lib.rssrc/uws_sys/socket.rssrc/uws_sys/us_socket_t.rstest/js/node/tls/node-tls-server-session-events.test.ts
There was a problem hiding this comment.
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 winKeep 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 winTrim 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
📒 Files selected for processing (8)
src/http/ssl_config.rssrc/js/node/net.tssrc/runtime/socket/Handlers.rssrc/runtime/socket/socket_body.rssrc/uws/lib.rssrc/uws_sys/us_socket_t.rstest/js/node/tls/node-tls-server-session-events.test.tstest/js/node/tls/renegotiation.test.ts
There was a problem hiding this comment.
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 winTrim 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
📒 Files selected for processing (6)
packages/bun-usockets/src/crypto/openssl.csrc/js/node/net.tssrc/runtime/socket/socket_body.rssrc/uws/lib.rstest/js/node/tls/node-tls-server-session-events.test.tstest/js/node/tls/renegotiation.test.ts
There was a problem hiding this comment.
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
📒 Files selected for processing (3)
packages/bun-usockets/src/crypto/openssl.csrc/js/node/net.tstest/js/node/tls/node-tls-server-session-events.test.ts
There was a problem hiding this comment.
♻️ Duplicate comments (2)
test/js/node/tls/node-tls-server-session-events.test.ts (2)
286-290: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winTrim 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 winFail 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 onproc.exiteduntil the suite timeout instead of failing on the real regression. Register the close/error failure path before waiting forsessionand 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
📒 Files selected for processing (2)
src/js/node/net.tstest/js/node/tls/node-tls-server-session-events.test.ts
|
Addressed the review in f2c9ccc.
All 7 tests in the file still pass with the debug build. |
There was a problem hiding this comment.
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-SSLus_ssl_resume_pending_tstate machine (states 0/1/2/3) that suspends the server handshake viaSSL_magic_pending_session_ptr()/SSL_ERROR_PENDING_SESSION, dispatches the offered session_id to JS, and re-drives the handshake onus_socket_session_resolve. Also adds a second per-SSL ex_data marker (us_ssl_can_suspend_ex_idx) gating suspension to realus_socket_tattaches only, parksSSL_SESSION_get_idalongside the i2d blob, and reordersssl_flush_pending_sessionto run before bothssl_trigger_handshakesites. - Rust: new
us_dispatch_resume_session/session_resolveFFI shims,on_resume_sessioncallback field threaded throughHandlers(withprotect()/unprotect()rewritten to usefor_each_callback_field!), a newresolveSessionhost fn, and signature changes toon_sessionacross UpgradedDuplex / WindowsNamedPipe / SSLWrapper to carry the id. - TS (
net.ts):completeServerHandshakeextracted fromServerHandlers.handshake; newsession/resumeSessionhandlers with_newSessionPending/kdeferredSecuredeferral; try/catch +process.nextTick(reportError)around both emits. - Rider:
SSLConfig::as_usockets()now forwardssecure_optionsandclient_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 tofor_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 thatJSValue::ZERO.protect()is indeed a no-op as the author asserts.
|
Confirmed the build state for the automated review's open question. Build 66448 (at f2c9ccc) had two red leaves, neither from this diff:
All review threads are resolved and the diff is otherwise green. |
|
Independently re-verified this from a clean OpenSSL-client differential. Node's own spec test for these events ( That also exercises the Blast-radius differential. Ran Not pushing anything: the two remaining |
238ff7b to
e282d23
Compare
|
Rebased onto What changed in the diff
Re-verified on the rebased tree
The |
e282d23 to
8c7b793
Compare
|
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 CodeRabbit's walkthrough above is from before the rebase (its reviews are paused): Why the
|
8c7b793 to
d9e25e1
Compare
|
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 happenedAdding
EvidenceBefore, in a build dir that had just built the previous revision:
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:
ScopeThe change is two lines of substance: This restores the invariant
Clean builds are unaffected, which is why |
d9e25e1 to
5f58566
Compare
|
Pushed 5f58566. Review fixThe automated review caught a real invariant break in On the red
|
5f58566 to
43e01f1
Compare
|
Rebased onto The only non-trivial conflict was #31859, which replaced the 13
No behaviour change; Re-verified on the rebased tree: 7/7 in #33348 landed the |
43e01f1 to
f719e28
Compare
|
Pushed f719e28 with the fourth The automated review found the same bug class as the False-Start ordering fix, at a site that fix did not audit: Now all four success sites flush the parked session and keylog first. Both 33 pass / 0 fail across Build 70752's one hard failure ( CodeRabbit's walkthrough above is from before the first rebase and lists |
`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
f719e28 to
4e68979
Compare
|
Rebased onto The only conflict was 7/7 in |
There was a problem hiding this comment.
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.
|
Agreed on all three points; nothing to add to the verdict. For whoever reviews, here is where to look for each.
The The resume-pending state machine. Nothing else outstanding. Build 71519 is running on |
|
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. |
Fixes the server side of
node:tlssession-ID resumption:tls.Servernever 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
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_cbparked only the serialized session (notSSL_SESSION_get_id) and the server handler table had nosessionmember, so server-minted sessions were discarded.SSL_CTX_sess_set_get_cbwas never registered, so'resumeSession'could not exist.The other half of the original repro,
secureOptionsnever reachingSSL_CTX_set_options(soSSL_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: parkSSL_SESSION_get_idalongside thei2d_SSL_SESSIONblob and registerSSL_CTX_sess_set_get_cb. The get-session callback parks the offered id and returnsSSL_magic_pending_session_ptr()so the handshake suspends (SSL_ERROR_PENDING_SESSION); the JS reply comes back throughus_socket_session_resolve, which re-drives the handshake with thed2i'd session. A dispatched/resolved state split keeps a spurious poll re-drive from emitting the event twice.us_socket_tattaches. 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.'newSession'fires before'secureConnection'(Node's order: the external store runs before the connection listener).net.ts:ServerHandlersgainedsession(emitsnewSession(id, data, done)) andresumeSession(emitsresumeSession(id, cb)).secureConnectionis held until thenewSessiondone callback runs, mirroring Node's_newSessionPendingdeferral, and thehandshakeTimeoutstays armed across that deferral so a listener that never callsdoneis 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.jsasserts they are 0 with tickets enabled).Prerequisite: bindgenv2's generated headers were not declared to ninja
ServerHandlersgains a member, which grows theSocketConfigHandlersbindgen dictionary. That turned out not to be buildable incrementally, and the first commit here fixes why.src/codegen/bindgenv2/script.ts'slist-outputsreported only the.cppfiles, so everyGenerated<Type>.hwas 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.cppfiles that include it but were not themselves regenerated, andrestatprunes them.GeneratedSocketConfig.cppembedsSocketConfigHandlersbut is byte-identical when that dictionary grows, so its object kept the 112-byte layout while the regeneratedGeneratedSocketConfigHandlers.cpp.oused the new 120-byte one. The link mixes both, andconvertDictionary<SocketConfigHandlers>writes 120 bytes into a temporary the stale object sized at 112:Clean builds (CI) are unaffected, and a second
bun bdself-heals, which is why the debian-13-x64-asan lane was green whilebun bdon this branch produced a corrupt binary. Declaring the headers restores the invariantscripts/build/CLAUDE.mdalready states ("Codegen headers stay order-only: they're declared outputs with restat, so depfile tracking is exact").bindgen.ts,generate-node-errors.tsandbundle-modules.tsstill under-report outputs the same way; that is left alone here, and the comment at the top ofscripts/build/codegen.tsnow 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/resumeSessionordering vssecureConnection, a synchronous resume hit, an asynchronous resume hit,isSessionReused()trueafter a resumption.secureConnectionis deferred until the asyncnewSessiondone callback, and the asynchronousresumeSessioncache miss falls through to a full handshake and mints a fresh session.resumeSessioncallback 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 untilhandshakeTimeout.newSessionorresumeSessionlistener still completes the handshake, and the throw surfaces as an uncaughtException the way Node reports it.TLSSocketover 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/andpackages/changes the session-event assertions fail because neither event ever fires, and the Duplex test hangs. With them: 7 pass, 0 fail.test/expectations.txtalso quarantinestest/js/node/test/parallel/test-net-connect-memleak.jsonlinux-x64-musl. It is the net (non-TLS) variant oftest-tls-connect-memleak.js, which is already quarantined on that one lane for the same JSC FinalizationRegistry-vs-setImmediatetiming 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 clientnet.Socketpath the test exercises.[review] gate passed · iteration 16 · 22 files touched
fails on main (without fix)
passes on PR (with fix)
diff hotspot
gate history · 2 passed · 0 rejected · iteration 16
evidence per changed file