Skip to content

Commit 7652bd9

Browse files
jasnelladuh95
authored andcommitted
quic: add stream idle timeout
Signed-off-by: James M Snell <jasnell@gmail.com> Assisted-by: Opencode:Opus 4.6 PR-URL: #63483 Backport-PR-URL: #64675 Reviewed-By: Stephen Belanger <admin@stephenbelanger.com> Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
1 parent e493f04 commit 7652bd9

18 files changed

Lines changed: 516 additions & 34 deletions

doc/api/quic.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1659,6 +1659,11 @@ added: v23.8.0
16591659

16601660
* Type: {bigint}
16611661

1662+
### `sessionStats.streamsIdleTimedOut`
1663+
1664+
* Type: {bigint} The total number of peer-initiated streams destroyed by the
1665+
stream idle timeout. Read only.
1666+
16621667
## Class: `QuicError`
16631668

16641669
<!-- YAML
@@ -3026,6 +3031,23 @@ reported as lost via the `ondatagramstatus` callback.
30263031

30273032
This option is immutable after session creation.
30283033

3034+
#### `sessionOptions.streamIdleTimeout`
3035+
3036+
* Type: {bigint|number}
3037+
* **Default:** `30000` (30 seconds)
3038+
3039+
The maximum time in milliseconds that a peer-initiated stream can be idle
3040+
(no data received) before it is automatically destroyed. This protects
3041+
against slowloris-style attacks where a remote peer opens streams but never
3042+
sends data, holding server resources indefinitely. Only peer-initiated
3043+
streams are checked — locally-initiated streams are the application's
3044+
responsibility. Set to `0` to disable.
3045+
3046+
The idle check runs as part of the normal send processing loop, so it adds
3047+
no additional timers or event loop overhead. The
3048+
`session.stats.streamsIdleTimedOut` counter tracks how many streams have been
3049+
destroyed by this mechanism.
3050+
30293051
#### `sessionOptions.maxDatagramSendAttempts`
30303052

30313053
* Type: {number}

lib/internal/quic/quic.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -436,6 +436,7 @@ const endpointRegistry = new SafeSet();
436436
* @property {number} [drainingPeriodMultiplier] Multiplier applied to the
437437
* draining period (3 * PTO) used by ngtcp2. Range `3..255`.
438438
* **Default:** `3`.
439+
* @property {bigint|number} [streamIdleTimeout] Time in ms before idle peer-initiated streams are destroyed
439440
* @property {number} [maxDatagramSendAttempts] Maximum number of times a
440441
* datagram is retried before being abandoned. Range `1..255`.
441442
* **Default:** `5`.
@@ -922,6 +923,17 @@ setCallbacks({
922923
// from QuicError::ToV8Value. Convert to a proper Node.js Error.
923924
if (error !== undefined) {
924925
error = convertQuicError(error);
926+
} else if (this[kOwner] && !this[kOwner].destroyed) {
927+
// The stream is closing cleanly, but it may have been reset by the
928+
// peer (ReceiveStreamReset) or locally (resetStream). The C++ side
929+
// records the reset code in state.resetCode. If set, surface the
930+
// reset as the close error so stream.closed rejects -- the reset
931+
// was an abnormal termination even if the session closed cleanly.
932+
const resetCode = getQuicStreamState(this[kOwner]).resetCode;
933+
if (resetCode !== undefined && resetCode > 0n) {
934+
error = new ERR_QUIC_APPLICATION_ERROR(
935+
resetCode, `stream reset with code ${resetCode}`);
936+
}
925937
}
926938
debug(`stream ${this[kOwner].id} closed callback with error: ${error}`);
927939
this[kOwner][kFinishClose](error);
@@ -5015,6 +5027,7 @@ function processSessionOptions(options, config = kEmptyObject) {
50155027
datagramDropPolicy = 'drop-oldest',
50165028
drainingPeriodMultiplier = 3,
50175029
maxDatagramSendAttempts = 5,
5030+
streamIdleTimeout,
50185031
verifyPeer = 'auto',
50195032
// HTTP/3 application-specific options. Nested under `application`
50205033
// to separate protocol-specific settings from transport-level ones.
@@ -5136,6 +5149,7 @@ function processSessionOptions(options, config = kEmptyObject) {
51365149
datagramDropPolicy,
51375150
drainingPeriodMultiplier,
51385151
maxDatagramSendAttempts,
5152+
streamIdleTimeout,
51395153
application,
51405154
onerror,
51415155
onstream,

lib/internal/quic/stats.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,7 @@ const {
101101
IDX_STATS_SESSION_DATAGRAMS_SENT,
102102
IDX_STATS_SESSION_DATAGRAMS_ACKNOWLEDGED,
103103
IDX_STATS_SESSION_DATAGRAMS_LOST,
104+
IDX_STATS_SESSION_STREAMS_IDLE_TIMED_OUT,
104105
IDX_STATS_SESSION_COUNT,
105106

106107
IDX_STATS_STREAM_CREATED_AT,
@@ -169,6 +170,7 @@ assert(IDX_STATS_SESSION_DATAGRAMS_RECEIVED !== undefined);
169170
assert(IDX_STATS_SESSION_DATAGRAMS_SENT !== undefined);
170171
assert(IDX_STATS_SESSION_DATAGRAMS_ACKNOWLEDGED !== undefined);
171172
assert(IDX_STATS_SESSION_DATAGRAMS_LOST !== undefined);
173+
assert(IDX_STATS_SESSION_STREAMS_IDLE_TIMED_OUT !== undefined);
172174
assert(IDX_STATS_STREAM_CREATED_AT !== undefined);
173175
assert(IDX_STATS_STREAM_OPENED_AT !== undefined);
174176
assert(IDX_STATS_STREAM_RECEIVED_AT !== undefined);
@@ -689,6 +691,13 @@ class QuicSessionStats {
689691
return this.#handle[this.#offset + IDX_STATS_SESSION_DATAGRAMS_LOST];
690692
}
691693

694+
/** @type {bigint} */
695+
get streamsIdleTimedOut() {
696+
assertIsQuicSessionStats(this);
697+
return this.#handle[this.#offset +
698+
IDX_STATS_SESSION_STREAMS_IDLE_TIMED_OUT];
699+
}
700+
692701
toString() {
693702
return JSONStringify(this.toJSON());
694703
}
@@ -726,6 +735,7 @@ class QuicSessionStats {
726735
datagramsSent,
727736
datagramsAcknowledged,
728737
datagramsLost,
738+
streamsIdleTimedOut,
729739
} = this;
730740
return {
731741
__proto__: null,
@@ -762,6 +772,7 @@ class QuicSessionStats {
762772
datagramsSent: `${datagramsSent}`,
763773
datagramsAcknowledged: `${datagramsAcknowledged}`,
764774
datagramsLost: `${datagramsLost}`,
775+
streamsIdleTimedOut: `${streamsIdleTimedOut}`,
765776
};
766777
}
767778

@@ -807,6 +818,7 @@ class QuicSessionStats {
807818
datagramsSent,
808819
datagramsAcknowledged,
809820
datagramsLost,
821+
streamsIdleTimedOut,
810822
} = this;
811823

812824
return `QuicSessionStats ${inspect({
@@ -841,6 +853,7 @@ class QuicSessionStats {
841853
datagramsSent,
842854
datagramsAcknowledged,
843855
datagramsLost,
856+
streamsIdleTimedOut,
844857
}, opts)}`;
845858
}
846859

src/quic/application.cc

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -724,8 +724,11 @@ class DefaultApplication final : public Session::Application {
724724

725725
void EarlyDataRejected() override {
726726
// Destroy all open streams — ngtcp2 has already discarded their
727-
// internal state when it rejected the early data.
728-
session().DestroyAllStreams(QuicError::ForApplication(0));
727+
// internal state when it rejected the early data. Use the
728+
// application's internal error code since this is an error
729+
// condition (code 0 would be treated as a clean close).
730+
session().DestroyAllStreams(
731+
QuicError::ForApplication(GetInternalErrorCode()));
729732
if (!session().is_destroyed()) {
730733
session().EmitEarlyDataRejected();
731734
}

src/quic/bindingdata.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,7 @@ class SessionManager;
113113
V(max_connections_total, "maxConnectionsTotal") \
114114
V(max_datagram_frame_size, "maxDatagramFrameSize") \
115115
V(max_datagram_send_attempts, "maxDatagramSendAttempts") \
116+
V(stream_idle_timeout, "streamIdleTimeout") \
116117
V(max_field_section_size, "maxFieldSectionSize") \
117118
V(max_header_length, "maxHeaderLength") \
118119
V(max_header_pairs, "maxHeaderPairs") \

src/quic/data.cc

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -365,12 +365,12 @@ std::optional<int> QuicError::get_crypto_error() const {
365365

366366
MaybeLocal<Value> QuicError::ToV8Value(Environment* env) const {
367367
if ((type() == Type::TRANSPORT && code() == NGTCP2_NO_ERROR) ||
368-
(type() == Type::APPLICATION && code() == NGHTTP3_H3_NO_ERROR) ||
368+
(type() == Type::APPLICATION &&
369+
(code() == 0 || code() == NGHTTP3_H3_NO_ERROR)) ||
369370
type() == Type::IDLE_CLOSE) {
370-
// Note that we only return undefined for *known* no-error application
371-
// codes. It is possible that other application types use other specific
372-
// no-error codes, but since we don't know which application is being used,
373-
// we'll just return the error code value for those below.
371+
// Application code 0 is the default no-error code for raw QUIC
372+
// applications (DefaultApplication::GetNoErrorCode() returns 0).
373+
// NGHTTP3_H3_NO_ERROR (0x100) is the HTTP/3 no-error code.
374374
// Idle close is always clean — the session timed out normally.
375375
return Undefined(env->isolate());
376376
}

src/quic/http3.cc

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -177,10 +177,13 @@ class Http3ApplicationImpl final : public Session::Application {
177177
// When 0-RTT is rejected, destroy the nghttp3 connection and all
178178
// open streams — ngtcp2 has discarded their internal state.
179179
// Reset started_ so Start() is called again via on_receive_rx_key
180-
// at 1RTT to recreate the nghttp3 connection.
180+
// at 1RTT to recreate the nghttp3 connection. Use the
181+
// application's internal error code since this is an error
182+
// condition (code 0 would be treated as a clean close).
181183
conn_.reset();
182184
started_ = false;
183-
session().DestroyAllStreams(QuicError::ForApplication(0));
185+
session().DestroyAllStreams(
186+
QuicError::ForApplication(GetInternalErrorCode()));
184187
if (!session().is_destroyed()) {
185188
session().EmitEarlyDataRejected();
186189
}

src/quic/session.cc

Lines changed: 76 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,8 @@ uint64_t MaxDatagramPayload(uint64_t max_frame_size) {
174174
V(DATAGRAMS_RECEIVED, datagrams_received) \
175175
V(DATAGRAMS_SENT, datagrams_sent) \
176176
V(DATAGRAMS_ACKNOWLEDGED, datagrams_acknowledged) \
177-
V(DATAGRAMS_LOST, datagrams_lost)
177+
V(DATAGRAMS_LOST, datagrams_lost) \
178+
V(STREAMS_IDLE_TIMED_OUT, streams_idle_timed_out)
178179

179180
#define NO_SIDE_EFFECT true
180181
#define SIDE_EFFECT false
@@ -617,7 +618,8 @@ Maybe<Session::Options> Session::Options::From(Environment* env,
617618
!SET(keep_alive_timeout) || !SET(max_stream_window) || !SET(max_window) ||
618619
!SET(max_payload_size) || !SET(unacknowledged_packet_threshold) ||
619620
!SET(cc_algorithm) || !SET(draining_period_multiplier) ||
620-
!SET(max_datagram_send_attempts)) {
621+
!SET(max_datagram_send_attempts) ||
622+
!SET(stream_idle_timeout)) {
621623
return Nothing<Options>();
622624
}
623625

@@ -2819,24 +2821,36 @@ void Session::ShutdownStream(stream_id id, QuicError error) {
28192821
DCHECK(!is_destroyed());
28202822
Debug(this, "Shutting down stream %" PRIi64 " with error %s", id, error);
28212823
SendPendingDataScope send_scope(this);
2822-
ngtcp2_conn_shutdown_stream(*this,
2823-
0,
2824-
id,
2825-
error.type() == QuicError::Type::APPLICATION
2826-
? error.code()
2827-
: application().GetNoErrorCode());
2824+
// STOP_SENDING and RESET_STREAM frames carry application-level error
2825+
// codes (RFC 9000 §19.4, §19.5). Map the QuicError to an appropriate
2826+
// application code: APPLICATION errors pass through directly; transport
2827+
// no-error maps to the application's no-error code; any other error
2828+
// maps to the application's internal error code.
2829+
error_code code;
2830+
if (error.type() == QuicError::Type::APPLICATION) {
2831+
code = error.code();
2832+
} else if (error.code() == NGTCP2_NO_ERROR) {
2833+
code = application().GetNoErrorCode();
2834+
} else {
2835+
code = application().GetInternalErrorCode();
2836+
}
2837+
ngtcp2_conn_shutdown_stream(*this, 0, id, code);
28282838
}
28292839

2830-
void Session::ShutdownStreamWrite(stream_id id, QuicError code) {
2840+
void Session::ShutdownStreamWrite(stream_id id, QuicError error) {
28312841
DCHECK(!is_destroyed());
2832-
Debug(this, "Shutting down stream %" PRIi64 " write with error %s", id, code);
2842+
Debug(this, "Shutting down stream %" PRIi64 " write with error %s",
2843+
id, error);
28332844
SendPendingDataScope send_scope(this);
2834-
ngtcp2_conn_shutdown_stream_write(*this,
2835-
0,
2836-
id,
2837-
code.type() == QuicError::Type::APPLICATION
2838-
? code.code()
2839-
: application().GetNoErrorCode());
2845+
error_code code;
2846+
if (error.type() == QuicError::Type::APPLICATION) {
2847+
code = error.code();
2848+
} else if (error.code() == NGTCP2_NO_ERROR) {
2849+
code = application().GetNoErrorCode();
2850+
} else {
2851+
code = application().GetInternalErrorCode();
2852+
}
2853+
ngtcp2_conn_shutdown_stream_write(*this, 0, id, code);
28402854
}
28412855

28422856
void Session::StreamDataBlocked(stream_id id) {
@@ -3035,6 +3049,41 @@ void Session::UpdateDataStats() {
30353049
std::max(STAT_GET(Stats, max_bytes_in_flight), info.bytes_in_flight));
30363050
}
30373051

3052+
void Session::CheckStreamIdleTimeout(uint64_t now) {
3053+
if (is_destroyed()) return;
3054+
uint64_t timeout = options().stream_idle_timeout;
3055+
if (timeout == 0) return;
3056+
3057+
uint64_t timeout_ns = timeout * NGTCP2_MILLISECONDS;
3058+
auto all_streams = streams();
3059+
3060+
for (const auto& [id, stream] : all_streams) {
3061+
if (!stream) continue;
3062+
3063+
// Only check peer-initiated streams. Locally-initiated streams
3064+
// that haven't been written to are the application's concern.
3065+
if (ngtcp2_conn_is_local_stream(*this, id)) continue;
3066+
3067+
uint64_t last_activity = stream->last_activity_timestamp();
3068+
if (last_activity > 0 && (now - last_activity) > timeout_ns) {
3069+
Debug(this,
3070+
"Stream %" PRId64 " idle timeout exceeded, destroying",
3071+
id);
3072+
// Notify the peer before destroying. ShutdownStream sends both
3073+
// STOP_SENDING and RESET_STREAM as appropriate, using the
3074+
// application's no-error code for non-APPLICATION errors (since
3075+
// these frames carry application-level error codes per RFC 9000).
3076+
// Without this, the peer's stream sits orphaned until the
3077+
// session closes.
3078+
auto error = QuicError::ForTransport(NGTCP2_ERR_PROTO,
3079+
"stream idle timeout");
3080+
ShutdownStream(id, error);
3081+
stream->Destroy(error);
3082+
STAT_INCREMENT(Stats, streams_idle_timed_out);
3083+
}
3084+
}
3085+
}
3086+
30383087
void Session::SendConnectionClose() {
30393088
// Method is a non-op if the session is already destroyed or the
30403089
// endpoint cannot send. Note: we intentionally do NOT check
@@ -3119,6 +3168,8 @@ void Session::OnTimeout() {
31193168
if (is_destroyed()) return;
31203169
if (NGTCP2_OK(ret) && !is_in_closing_period() && !is_in_draining_period()) {
31213170
application().SendPendingData();
3171+
if (is_destroyed()) return;
3172+
CheckStreamIdleTimeout(uv_hrtime());
31223173
return;
31233174
}
31243175
if (is_destroyed()) return;
@@ -3165,6 +3216,15 @@ void Session::UpdateTimer() {
31653216
auto timeout = (expiry - now) / NGTCP2_MILLISECONDS;
31663217
Debug(this, "Updating timeout to %zu milliseconds", timeout);
31673218

3219+
// If a stream idle timeout is configured, ensure the timer fires at
3220+
// least that often so CheckStreamIdleTimeout runs. Without this, an
3221+
// idle session with idle streams might not fire the timer until the
3222+
// connection idle timeout, which could be much longer.
3223+
uint64_t stream_idle = options().stream_idle_timeout;
3224+
if (stream_idle > 0 && timeout > stream_idle) {
3225+
timeout = stream_idle;
3226+
}
3227+
31683228
// If timeout is zero here, it means our timer is less than a millisecond
31693229
// off from expiry. Let's bump the timer to 1.
31703230
impl_->timer_.Update(timeout == 0 ? 1 : timeout);

src/quic/session.h

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,14 @@ class Session final : public AsyncWrap, private SessionTicket::AppData::Source {
227227
// 10.2 requires at least 3x PTO. Range: 3-255. Default: 3.
228228
uint8_t draining_period_multiplier = 3;
229229

230+
// The amount of time (in milliseconds) that a stream can be idle
231+
// (no data received) before it is automatically destroyed. This
232+
// protects against slowloris-style attacks where a peer opens streams
233+
// but never sends data, holding server resources indefinitely.
234+
// Only applies to peer-initiated streams. Set to 0 to disable.
235+
static constexpr uint64_t DEFAULT_STREAM_IDLE_TIMEOUT = 30'000;
236+
uint64_t stream_idle_timeout = DEFAULT_STREAM_IDLE_TIMEOUT;
237+
230238
// An optional NEW_TOKEN from a previous connection to the same
231239
// server. When set, the token is included in the Initial packet
232240
// to skip address validation. Client-side only.
@@ -569,6 +577,7 @@ class Session final : public AsyncWrap, private SessionTicket::AppData::Source {
569577
// Has to be called after certain operations that generate packets.
570578
void UpdatePacketTxTime();
571579
void UpdateDataStats();
580+
void CheckStreamIdleTimeout(uint64_t now);
572581
void UpdatePath(const PathStorage& path);
573582

574583
void ProcessPendingBidiStreams();

src/quic/streams.cc

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1270,7 +1270,8 @@ void Stream::NotifyStreamOpened(stream_id id) {
12701270
// Headers were enqueued while the application was not yet known
12711271
// (headers_supported == 0), and the negotiated application does
12721272
// not support headers. This is a fatal mismatch.
1273-
Destroy(QuicError::ForApplication(0));
1273+
Destroy(QuicError::ForApplication(
1274+
session().application().GetInternalErrorCode()));
12741275
return;
12751276
}
12761277
decltype(pending_headers_queue_) queue;
@@ -1347,6 +1348,11 @@ Session& Stream::session() const {
13471348
return *session_;
13481349
}
13491350

1351+
uint64_t Stream::last_activity_timestamp() const {
1352+
uint64_t ts = stats()->received_at;
1353+
return ts != 0 ? ts : stats()->created_at;
1354+
}
1355+
13501356
bool Stream::is_local_unidirectional() const {
13511357
return direction() == Direction::UNIDIRECTIONAL &&
13521358
ngtcp2_conn_is_local_stream(*session_, id());
@@ -1625,6 +1631,7 @@ void Stream::EndReadable(std::optional<uint64_t> maybe_final_size) {
16251631

16261632
void Stream::Destroy(QuicError error) {
16271633
if (stats()->destroyed_at != 0) return;
1634+
16281635
// Record the destroyed at timestamp before notifying the JavaScript side
16291636
// that the stream is being destroyed.
16301637
STAT_RECORD_TIMESTAMP(Stats, destroyed_at);

0 commit comments

Comments
 (0)