Commit 2130f41710c for nodejs
commit 2130f41710c2a284129e51e0c0f723e6fcc0db12
Author: James M Snell <jasnell@gmail.com>
Date: Fri Nov 27 23:10:33 2026 +0000
net: report pre-validation psk callback errors on the endpoint
Under DTLS 1.3 the server's psk callback runs for the first ClientHello,
before a session exists. An exception it threw was dropped; it now
reaches endpoint.onerror, which is documented.
Assisted-by: Claude Opus 5.5
Signed-off-by: James M Snell <jasnell@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/67837
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com>
diff --git a/doc/api/dtls.md b/doc/api/dtls.md
index d625ae3bb23..4a87066137a 100644
--- a/doc/api/dtls.md
+++ b/doc/api/dtls.md
@@ -378,8 +378,9 @@ What changes under DTLS 1.3:
peer's address is validated, because the HelloRetryRequest commits to it.
A client the server refuses at that point, for want of a common cipher
suite or because it offered a pre-shared key identity the server does not
- know, is sent an alert, but no session is created for it and the server's
- application is told nothing.
+ know, is sent an alert, but no session is created for it. An exception
+ thrown by the server's `psk` callback at that point is reported on
+ [`endpoint.onerror`][].
* The server issues resumption tickets after the handshake rather than during
it, so [`session.session`][] is `undefined` when `session.opened` settles.
Use [`session.onsessionticket`][]; see [Session resumption][].
@@ -831,6 +832,28 @@ Immediately destroys the endpoint without sending `close_notify` alerts.
Equivalent to calling `endpoint.close()`.
+### `endpoint.onerror`
+
+<!-- YAML
+added: REPLACEME
+-->
+
+* {Function}
+ * `error` {Error}
+
+Set to receive errors that belong to the endpoint rather than to any one
+session. Neither closes the endpoint. They are:
+
+* A failure reported by the UDP socket while receiving.
+* An exception thrown by the server's `psk` callback for a DTLS 1.3 client
+ whose address has not yet been validated. The callback is first asked
+ about the client's opening ClientHello, before there is a session to
+ report to, so the exception is passed here, as thrown, and the client is
+ refused. A peer that has not proven its address can cause this once for
+ each ClientHello it sends, so the handler should be cheap.
+
+Without a handler these errors are discarded.
+
## Class: `DTLSEndpoint.Stats`
<!-- YAML
@@ -1413,6 +1436,7 @@ The minimum allowed MTU is 256 bytes. The maximum is 65535.
[`dtls.connect()`]: #dtlsconnecthost-port-options
[`dtls.createSecureContext()`]: #dtlscreatesecurecontextoptions
[`dtls.listen()`]: #dtlslistencallback-options
+[`endpoint.onerror`]: #endpointonerror
[`endpointStats.serverRefusedCount`]: #endpointstatsserverrefusedcount
[`handshakeTimeout`]: #handshake-timeout
[`session.authorizationError`]: #sessionauthorizationerror
diff --git a/lib/internal/dtls/dtls.js b/lib/internal/dtls/dtls.js
index 7ffb3567930..7102bc84fa3 100644
--- a/lib/internal/dtls/dtls.js
+++ b/lib/internal/dtls/dtls.js
@@ -809,8 +809,12 @@ class DTLSEndpoint {
}
#onEndpointError(message) {
+ // A string is the binding's own report. Anything else is an exception a
+ // callback threw during a handshake that had no session to report it
+ // on, and is passed on as it was thrown, as a session does.
if (this.#onerror) {
- this.#onerror(new ERR_INVALID_STATE(message));
+ this.#onerror(typeof message === 'string' ?
+ new ERR_INVALID_STATE(message) : message);
}
}
diff --git a/src/dtls/dtls_context.cc b/src/dtls/dtls_context.cc
index 3ac2707bcbe..ef2e7b5d891 100644
--- a/src/dtls/dtls_context.cc
+++ b/src/dtls/dtls_context.cc
@@ -805,8 +805,18 @@ void DTLSContext::ReportCallbackError(SSL* ssl, TryCatch* try_catch) {
// entered with an exception still pending.
try_catch->Reset();
- if (session != nullptr && !exception.IsEmpty()) {
+ if (exception.IsEmpty()) return;
+ if (session != nullptr) {
session->SetPendingError(exception);
+ return;
+ }
+ // A DTLS 1.3 first ClientHello is processed before the peer's address has
+ // been validated, by a pending handshake with no session behind it. Keep
+ // the first exception for the endpoint to report.
+ PendingHandshakeState* pending = GetPendingState(ssl);
+ DTLSContext* ctx = FromSSL(ssl);
+ if (pending != nullptr && ctx != nullptr && pending->error.IsEmpty()) {
+ pending->error.Reset(ctx->env()->isolate(), exception);
}
}
diff --git a/src/dtls/dtls_context.h b/src/dtls/dtls_context.h
index a29646e09bd..cbf4d4c060a 100644
--- a/src/dtls/dtls_context.h
+++ b/src/dtls/dtls_context.h
@@ -29,6 +29,10 @@ struct PendingHandshakeState {
// HelloRetryRequest for DTLS 1.3) has been generated. The next
// ClientHello is the one expected to carry the cookie back.
bool cookie_sent = false;
+ // An exception thrown by a callback while this handshake was being driven.
+ // There is no session to report it to, so the endpoint reports it once
+ // OpenSSL has returned.
+ v8::Global<v8::Value> error;
};
// DTLSContext wraps an SSL_CTX configured for DTLS.
diff --git a/src/dtls/dtls_endpoint.cc b/src/dtls/dtls_endpoint.cc
index 98907900998..1f6c57676b6 100644
--- a/src/dtls/dtls_endpoint.cc
+++ b/src/dtls/dtls_endpoint.cc
@@ -877,14 +877,39 @@ void DTLSEndpoint::DrivePendingHandshake(const uint8_t* data,
SendTo(remote, buf.out(), n);
}
- if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) return;
- if (err != SSL_ERROR_WANT_CLIENT_HELLO_CB) {
+ // A callback that threw while OpenSSL processed this datagram -- the
+ // server's psk callback is the one that runs this early -- is reported on
+ // the endpoint, now that OpenSSL has returned and running JavaScript is
+ // safe. It is reported whether or not the handshake goes on: a throw is
+ // treated as declining, and a server with a certificate can continue
+ // without a PSK.
+ v8::Global<Value> error = std::move(pending->state.error);
+
+ bool keep = err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE ||
+ err == SSL_ERROR_WANT_CLIENT_HELLO_CB;
+ if (!keep) {
// A ClientHello OpenSSL would not accept, or -- which the cookie
// exchange rules out -- a handshake that finished without one.
pending_.erase(it);
- return;
}
+ if (!error.IsEmpty()) {
+ HandleScope handle_scope(env()->isolate());
+ Context::Scope context_scope(env()->context());
+ Local<Value> argv[] = {error.Get(env()->isolate())};
+ error.Reset();
+ // Held across the callback, which may close or destroy the endpoint.
+ BaseObjectPtr<DTLSEndpoint> strong(this);
+ Local<Function> cb = GetCallback(DTLS_CB_ENDPOINT_ERROR);
+ if (!cb.IsEmpty()) MakeCallback(cb, 1, argv);
+ // The callback may have closed the endpoint, taking the pending
+ // handshake with it.
+ it = pending_.find(remote);
+ if (it == pending_.end() || it->second.get() != pending) return;
+ }
+
+ if (err != SSL_ERROR_WANT_CLIENT_HELLO_CB) return;
+
// Suspended at the ClientHello that should carry the cookie back. From
// here on the handshake runs through a DTLSSession, so that what follows
// cookie verification -- SNI, PSK, key derivation and its keylog lines --
diff --git a/test/parallel/test-dtls-psk.mjs b/test/parallel/test-dtls-psk.mjs
index c1e10b215fb..7fbaff41807 100644
--- a/test/parallel/test-dtls-psk.mjs
+++ b/test/parallel/test-dtls-psk.mjs
@@ -343,23 +343,29 @@ for (const [versions, hint, calls] of [
// Under DTLS 1.3 the server's callback is first asked about the ClientHello
// that precedes the cookie exchange, and a throw there fails a handshake
-// that has no session yet. The client is refused, the process is not taken
-// down, and the endpoint goes on serving.
+// that has no session yet. The error is reported on the endpoint instead,
+// as thrown; the client is refused, the process is not taken down, and the
+// endpoint goes on serving.
{
process.on('uncaughtException', mustNotCall());
- const endpoint = listen(() => {}, {
+ const thrown = new Error('from the psk callback');
+ // Called once, for the connection that works.
+ const endpoint = listen(mustCall(), {
psk: (identity) => {
- if (identity === 'throws') throw new Error('from the psk callback');
+ if (identity === 'throws') throw thrown;
return KEY;
},
host: HOST, port: 0, ...V13,
});
+ const reported = Promise.withResolvers();
+ endpoint.onerror = mustCall((err) => reported.resolve(err));
const failing = open(endpoint, {
psk: { identity: 'throws', key: KEY }, ...V13,
});
await assert.rejects(failing.opened, { name: 'Error' });
+ assert.strictEqual(await reported.promise, thrown);
const working = open(endpoint, {
psk: { identity: 'device-42', key: KEY }, ...V13,