Repository navigation
fix(ext/node): implement ALPNCallback and SNICallback for TLS server - #33360
Conversation
Implements ALPNCallback and SNICallback options for node:tls server, fixing protocol negotiation and certificate selection that previously reported false/null. Uses rustls's Acceptor API to intercept the ClientHello before creating the ServerConnection, allowing JS callbacks to select certificates and ALPN protocols per-connection. The fast path (no callbacks) is preserved. Also adds getServername() support for server-side TLS connections, NoApplicationProtocol alert mapping, and ALPN callback validation (ERR_TLS_ALPN_CALLBACK_INVALID_RESULT, ERR_TLS_ALPN_CALLBACK_WITH_PROTOCOLS). Closes #33346
bartlomieju
left a comment
There was a problem hiding this comment.
Good implementation overall. The two-phase Acceptor design is clean -- preserving the fast path when no callbacks are set, and only using the Acceptor when enableClientHelloCb() is called. The EmitCtx / do_emit_* patterns are followed correctly, and reentrancy safety through cycling looks correct.
Test coverage: The three spec tests cover the happy paths well. Consider adding tests for:
ALPNCallbackreturning a protocol not in the client's list (ERR_TLS_ALPN_CALLBACK_INVALID_RESULT)ALPNCallbackreturningnull/undefined(rejection/destroy path)ALPNCallback+ALPNProtocolsmutual exclusion (ERR_TLS_ALPN_CALLBACK_WITH_PROTOCOLSthrow)SNICallbackreturning an error
Inline comments below on specific spots.
| } | ||
| Err((_err, _alert)) => { | ||
| self.acceptor = None; | ||
| self.error = Some("TLS accept error".to_string()); |
There was a problem hiding this comment.
The _err contains the actual rustls error and _alert has the AlertDescription. Consider including them in the error message for debuggability:
self.error = Some(format!("TLS accept error: {_err}"));This would match the pattern used in finish_accept (format!("TLS accept error: {e}")).
| if got_hello && let Some(ctx) = extract_emit_ctx(ptr) { | ||
| do_emit_client_hello(&ctx); | ||
| } | ||
| return; |
There was a problem hiding this comment.
If process_acceptor() sets self.error (e.g. on the Err match arm), this early return means the error is never emitted to JS. After the acceptor is None and tls_conn is also None, subsequent cycles would likely produce confusing behavior.
Consider also emitting an error event to JS on the failure path, similar to how clear_out_process errors are handled.
| inner | ||
| .client_hello_alpn | ||
| .iter() | ||
| .filter_map(|p| std::str::from_utf8(p).ok().map(|s| s.to_string())) |
There was a problem hiding this comment.
Nit: filter_map silently drops non-UTF8 ALPN protocol names. While ALPN identifiers are practically always ASCII, silently dropping entries could mask negotiation issues. A brief comment noting this is intentional would be helpful.
| if (owner.destroyed) return; | ||
| const context = ctx | ||
| ? (ctx.context || ctx) | ||
| : owner._tlsOptions.secureContext?.context; |
There was a problem hiding this comment.
If SNICallback passes null/undefined for ctx and there is no secureContext on _tlsOptions, context will be undefined and finishAccept will call build_server_config with an invalid object, setting inner.error but not emitting it. Consider guarding:
if (!context) {
owner.destroy(new Error("No SecureContext available"));
return;
}| if (selectedAlpn == null) { | ||
| // Callback returned undefined/null -- reject ALPN. | ||
| // Destroy the socket which sends a connection reset. | ||
| owner.destroy(); |
There was a problem hiding this comment.
Minor: owner.destroy() without an error means no "error" event fires on the socket. Node.js sends a no_application_protocol alert in this case. The current behavior silently resets the connection, which may confuse users who expect an error event or alert. Fine for now, but worth noting as a future improvement.
fibibot
left a comment
There was a problem hiding this comment.
LGTM. The Acceptor-based handshake split is a clean way to expose the ClientHello to JS without touching the existing static-config fast path. Spot-checked the rustls integration — process_acceptor correctly drains the cursor by the bytes returned from read_tls, accept() is &mut self so leaving the Acceptor in place when it returns Ok(None) matches the rustls contract, and the post-callback finish_accept rebuilds the per-connection ServerConfig, drives into_connection, and re-enters cycle() to kick off the server-hello write. The new AD::NoApplicationProtocol arm in rustls_error_to_node_error matches Node’s ERR_SSL_TLSV1_ALERT_NO_APPLICATION_PROTOCOL. CI is fully green. One non-blocking note inline.
| if (selectedAlpn == null) { | ||
| // Callback returned undefined/null -- reject ALPN. | ||
| // Destroy the socket which sends a connection reset. | ||
| owner.destroy(); |
There was a problem hiding this comment.
Non-blocking, but worth filing as a follow-up: Node sends a no_application_protocol TLS alert (mapped from tls.ALPNCallback returning undefined) before tearing the connection down — clients see ERR_SSL_TLSV1_ALERT_NO_APPLICATION_PROTOCOL rather than a bare RST. The mapping arm is already in rustls_error_to_node_error, so the missing piece is wiring this branch to the rustls server-side alert path (e.g. via a fresh ServerConnection whose alpn_protocols is empty so the handshake fails with that alert) instead of owner.destroy().
- Surface acceptor errors to JS via do_emit_error instead of silently setting self.error (which was never delivered) - Include actual rustls error in process_acceptor failure message - Guard against missing SecureContext in finish callback - Use owner.destroy() for ALPN invalid result (was _emitTLSError which doesn't close the socket, causing hangs during pre-handshake phase) - Add comment explaining intentional non-UTF8 ALPN filter - Add error-path spec tests: invalid ALPN result, ALPNCallback + ALPNProtocols mutual exclusion, SNICallback error
fibibot
left a comment
There was a problem hiding this comment.
Follow-up commit 41ae620 cleanly addresses both review threads from my earlier APPROVED pass and the test-coverage gaps from the earlier maintainer review:
- Acceptor errors no longer hang silently —
process_acceptornow returns the rustls error message (rather than the bare"TLS accept error"constant), and the cycle path surfaces it to JS viado_emit_errorwithERR_SSL_SSLV3_ALERT_HANDSHAKE_FAILUREwhen noclient_hellowas produced. - Three new negative-path tests added:
alpn_callback_invalid_result.ts,alpn_callback_with_protocols.ts,sni_callback_error.ts— covers the three cases the earlier maintainer review asked about. _tls_wrap.jsnowdestroy()s on null SecureContext from SNICallback and on ALPN-protocol-mismatch (instead of_emitTLSErrorwhich was leaving the socket in a half-open state). Cleaner shutdown.
One small note inline. CI has only 2 checks reporting (license/cla + lint title) — full suite hasn't kicked off on this rebase. Holding COMMENT until the substance shards land green; substance walk is otherwise clean and I'd flip back to APPROVE.
| // Acceptor failed (e.g. malformed ClientHello). Surface the | ||
| // error to JS so the socket doesn't silently hang. | ||
| if let Some(ctx) = extract_emit_ctx(ptr) { | ||
| do_emit_error( |
There was a problem hiding this comment.
Subtle ordering: (*ptr).error.take() consumes the error before checking for extract_emit_ctx(ptr). If extract_emit_ctx returns None (no JS context to deliver on), the error is silently dropped — the take() already moved it out of (*ptr).error.
In practice this is unreachable: if there's no JS context registered for this TLSWrap, no one is consuming events anyway. But for code-shape symmetry with the got_hello arm above (which also uses if let Some(ctx) = extract_emit_ctx(ptr) as the outer guard), consider:
} else if let Some(ctx) = extract_emit_ctx(ptr) {
if let Some(error) = (*ptr).error.take() {
do_emit_error(&ctx, &error, "ERR_SSL_SSLV3_ALERT_HANDSHAKE_FAILURE");
}
}Same visible behavior, but the error stays in (*ptr).error if there's no context to deliver it to — preserving it for any later cycle that can. Non-blocking; current code works for the realistic case where every TLSWrap with an active acceptor has a registered emit context.
Resolve conflicts: - tls_wrap.rs: keep CertificateRequired match arm from main, keep acceptor-based handshake methods from PR, fix build_server_config tuple return type in finish_accept, remove duplicate server_name impl on TlsConnection
Check for emit context before taking the error so it stays in (*ptr).error if there's no JS context to deliver it to, preserving it for any later cycle.
fibibot
left a comment
There was a problem hiding this comment.
Two updates since v2 — one substance fix, one merge-fallout that's blocking CI.
Substance fix (resolved)
49f09ea swaps the error.take() / extract_emit_ctx ordering in the acceptor error path exactly as my v2 inline asked:
} else if let Some(ctx) = extract_emit_ctx(ptr) {
// Check for emit context first so the error stays in
// (*ptr).error if there's no context to deliver it to.
if let Some(error) = (*ptr).error.take() {
do_emit_error(&ctx, &error, "ERR_SSL_SSLV3_ALERT_HANDSHAKE_FAILURE");
}
}Now symmetric with the got_hello arm above, and the error stays in (*ptr).error if there's no context yet (so a later cycle can still deliver it). ✓
Merge-fallout blocker
12 CI jobs failing. Lint fails with:
error[no-dupe-keys]: Duplicate key 'ERR_TLS_ALPN_CALLBACK_WITH_PROTOCOLS'
--> ext/node/polyfills/internal/errors.ts:3160:16
The class is declared twice in internal/errors.ts:
- Line 2210:
export class ERR_TLS_ALPN_CALLBACK_WITH_PROTOCOLS extends NodeTypeError— added by this PR. - Line 2273:
export class ERR_TLS_ALPN_CALLBACK_WITH_PROTOCOLS extends NodeError— added by another PR that merged to main since this PR's last rebase.
The merge main into fix/tls-alpn-sni-callbacks commit (879f6f1) didn't catch this — both declarations were preserved. One needs to win; the second variant (extends NodeError) probably matches main's choice since that's what landed independently. Drop the first, keep the second. After fixing, the codes.ERR_TLS_ALPN_CALLBACK_WITH_PROTOCOLS = ERR_TLS_ALPN_CALLBACK_WITH_PROTOCOLS registration line at :3160 still works either way.
All 12 failing jobs are downstream of this lint issue (build fails because TS rejects the duplicate, lint fails on the no-dupe-keys rule). One-line fix unblocks them.
CI
12 fail / 56 pass / 12 skipping. Holding COMMENT rather than REQUEST_CHANGES — the duplicate is trivial to resolve and CI itself blocks the merge, so a manual unblock from REQUEST_CHANGES would just add friction. Once the duplicate is removed and CI lands green, this is ready from my side.
Drop the PR's copy (extends NodeTypeError) in favor of main's (extends NodeError) that landed independently. Also remove the duplicate codes registration. Fixes the no-dupe-keys lint failure.
fibibot
left a comment
There was a problem hiding this comment.
Duplicate-class lint blocker from v3 is now resolved by e09bd23 — that's the right fix, dropping the PR's extends NodeTypeError copy in favor of main's extends NodeError declaration. ✓
Build is now green, which unmasked two real test failures in the newly-enabled tests. Both reproduce across all 4 platforms × debug & release shards (so it's not flake; both are deterministic regressions in the new SNI/ALPN code).
1. parallel/test-tls-empty-sni-context.js — hangs (20s timeout)
Newly enabled by this PR (tests/node_compat/config.jsonc:3207). The test exercises the edge case where SNICallback returns a tls.createSecureContext() with no cert/key configured — i.e. a deliberately-empty context. Node's expected behavior is:
- Server emits
tlsClientErrorwith/no suitable signature algorithm/i - Client receives
ERR_SSL_SSL/TLS_ALERT_HANDSHAKE_FAILURE
Deno hangs instead — neither side fires its event. Likely the finish_accept path doesn't recognize an empty SecureContext returned by the JS SNICallback as a fatal error, so the rustls ServerConnection is built with no cert chain and the handshake stalls instead of sending the alert. Worth checking what SecureContext::new() returns to JS and how finish_accept handles the case where cert / key are null/empty on the post-callback path.
2. parallel/test-http2-origin.js — assertion: SNI hostname leaks IP
Newly enabled (tests/node_compat/config.jsonc:1747). Failing assertion at test-http2-origin.js:151:
+ actual: 'https://127.0.0.1:49950'
- expected: 'https://localhost:49950'
The client connected by hostname (localhost) but client.originSet is reporting the IP (127.0.0.1). Stack trace points at Http2Session.onOrigin (node:http2:842:11) → TLSSocket.<anonymous> (node:http2:2995:14) → TLSWrap.onStreamRead. The new SNICallback path in _tls_wrap.js is most likely returning the resolved IP from the underlying TCP socket where it should be returning the SNI hostname the client actually used. Suggests getServername() (or whatever feeds originSet) isn't picking up the SNI from the new Acceptor-based client-hello extraction.
CI
134 pass / 16 fail / 12 skip (the 16 failures are these two tests cascading across all node_compat shards × platforms). Holding COMMENT rather than REQUEST_CHANGES — the failure modes are clear from CI directly, and this is your PR so the merge gate isn't the blocker; just want to make sure the regression direction is named in writing before this lands.
…backs # Conflicts: # ext/node/ops/tls_wrap.rs # ext/node/polyfills/internal/errors.ts
…ext default SNI
- Handle requestCert: true with empty root cert store (NodeClientCertVerifierNoRoots)
- Tolerate X.509v1 certs in client cert signature verification
- Tolerate X.509v1 certs in client-side with_client_auth_cert (StaticClientCertResolver)
- Detect invalid SNI context (empty {}) and emit "Invalid SNI context" error
- Merge requestCert/rejectUnauthorized into SNI context for finishAccept
- Add default SNICallback when addContext() is used without explicit callback
- Pass op_state to finish_accept for build_server_config compatibility
- Enable test-tls-sni-option.js and test-tls-sni-server-client.js node compat tests
initializeTLSOptions converts ALPNCallback into a static ALPNProtocols list but left ALPNCallback on the options object, causing tls.Server constructor to throw ERR_TLS_ALPN_CALLBACK_WITH_PROTOCOLS.
Two fixes: 1. _finishInit: treat null from getServername() the same as "" so client-side TLS sockets fall through to _tlsOptions.servername instead of setting servername=null (which made HTTP/2 origin use 127.0.0.1 instead of localhost). 2. finish_accept: when into_connection() fails (e.g. empty SecureContext with no cert), translate the rustls error via rustls_error_to_node_error and emit it via do_emit_error so it surfaces as a tlsClientError event instead of silently hanging.
… failure - Remove `op_state: &mut OpState` parameter from `finish_accept` and borrow it in a limited scope instead. The mutable borrow was held for the entire op duration, but cycle()/do_emit_error() re-enter V8 which can trigger prepare_stack_trace_callback → format_stack_trace, which also borrows op_state — causing a RefCell panic. - When `into_connection()` fails (e.g. empty SecureContext with no cert/key), flush the AcceptedAlert bytes to the client so it receives a proper TLS handshake_failure alert instead of ECONNRESET.
fibibot
left a comment
There was a problem hiding this comment.
LGTM — re-confirming after the two test failures from my e09bd230 COMMENT are fixed and CI fully lands green.
Both prior blockers are resolved
1. test-tls-empty-sni-context.js 20-second hang — addressed by a994e4d1 ("avoid RefCell double-borrow in finish_accept, flush TLS alert on failure"). The post-callback path now correctly detects when the JS-returned SecureContext lacks usable cert/key material and fires the TLS alert instead of stalling the rustls ServerConnection mid-handshake. The accompanying 99642972 ("handle requestCert with empty CA store, v1 client certs, addContext default SNI") rounds out the empty-context surface.
2. test-http2-origin.js SNI hostname leaks IP — addressed by 7fb983d5 ("handle null servername for clients, emit error on accept failure") plus the addContext default SNI work in 99642972. The IP-as-SNI case is now filtered before the callback fires.
Other PR-specific commits since e09bd230
282e2755—cargo fmton the benchmark filesd75d5efe— dropALPNCallbackafter converting toALPNProtocolsin http2 (cleaning up the http2 path so the static-ALPN fast path is preferred when the user just wants protocol negotiation)91a7358a,991952a5— main rebasese6e1fe99— drop unrelatedlibs/core/benchmark files from the PR (good scope hygiene)
CI: 135 checks, 0 fail
100 checks: 99 success | 1 skipped (publish canary)
35 checks: 34 success | 1 skipped
All test node_compat, test unit_node, test integration, test specs, test unit shards green across all 4 platforms × debug + release. The newly-enabled parallel/test-tls-empty-sni-context.js and parallel/test-http2-origin.js (the two that I'd flagged as hanging/failing) now pass on every shard.
Substance recap
For my own re-review trail across this PR:
999583a0— original Acceptor-based handshake split (my first APPROVE)41ae6206— three negative-path tests + cleaner shutdown on null SecureContext / ALPN-protocol-mismatch6178053e—error.take() / extract_emit_ctxordering symmetric withgot_helloarme09bd230— duplicate-class lint blocker resolved (kept main'sextends NodeError)99642972+7fb983d5+a994e4d1— fixed the two test hangs/failures that had unmasked when build went green
Good to ship.
|
Was this successfully merged in? Which version of Deno does this fix come in? |
|
2.8.0 |
…enoland#33360) ## Summary Implements `ALPNCallback` and `SNICallback` options for `node:tls.createServer()`, which were previously accepted but never invoked. - **ALPNCallback**: Called during TLS handshake with the client's offered protocols, returns the selected protocol - **SNICallback**: Called with the client's SNI hostname, returns a `SecureContext` for certificate selection - **getServername()**: Now returns the client's SNI on server-side TLS connections - **Validation**: `ERR_TLS_ALPN_CALLBACK_WITH_PROTOCOLS` when both `ALPNCallback` and `ALPNProtocols` are set, `ERR_TLS_ALPN_CALLBACK_INVALID_RESULT` when callback returns a protocol not in the client's list - **Alert mapping**: `NoApplicationProtocol` alert now correctly maps to `ERR_SSL_TLSV1_ALERT_NO_APPLICATION_PROTOCOL` ### Approach Uses rustls's `Acceptor` API to intercept the `ClientHello` before creating the `ServerConnection`. This allows extracting SNI and ALPN from the client hello, calling back to JS for callback-based selection, then building a per-connection `ServerConfig`. The existing fast path (direct `ServerConnection::new`) is preserved when no callbacks are set. Closes denoland#33346
Summary
Implements
ALPNCallbackandSNICallbackoptions fornode:tls.createServer(), which were previously accepted but never invoked.SecureContextfor certificate selectionERR_TLS_ALPN_CALLBACK_WITH_PROTOCOLSwhen bothALPNCallbackandALPNProtocolsare set,ERR_TLS_ALPN_CALLBACK_INVALID_RESULTwhen callback returns a protocol not in the client's listNoApplicationProtocolalert now correctly maps toERR_SSL_TLSV1_ALERT_NO_APPLICATION_PROTOCOLApproach
Uses rustls's
AcceptorAPI to intercept theClientHellobefore creating theServerConnection. This allows extracting SNI and ALPN from the client hello, calling back to JS for callback-based selection, then building a per-connectionServerConfig. The existing fast path (directServerConnection::new) is preserved when no callbacks are set.Closes #33346
Test plan
tests/specs/node/tls_alpn_sni_callbacks/(ALPNCallback, SNICallback, both together)tls_jsstreamsocket_close,tls-connect-simple)ALPNProtocols(without callback) still workscargo clippyclean