Commit cdc1dacdd56 for nodejs
commit cdc1dacdd568d9f0a95631bc63f6364fc4c31b58
Author: Gabe De Mesa <gdemesa@opengov.com>
Date: Tue Nov 17 05:26:40 2026 -0800
http2: enforce maxSessionMemory for client requests
The documentation for `maxSessionMemory` says new streams are rejected
while the limit is exceeded. That was only enforced for streams opened
by the peer (`Http2Session::CanAddStream()`). `session.request()` went
straight to `nghttp2_submit_request()`, so a client whose socket
stopped draining could keep queuing requests in nghttp2 without bound.
Check the session memory before submitting a request. If it is over
the limit, reject only that request with the new
`ERR_HTTP2_SESSION_MEMORY_EXCEEDED` error. Nothing is sent to the peer,
so the request can be retried, and the session stays usable. As with
response headers, request bodies queued for flow control are not
counted, so large uploads do not block unrelated requests on the same
session.
Refs: https://github.com/nodejs/undici/issues/6181
Assisted-by: a closed-source coding agent
Signed-off-by: Gabe De Mesa <gdemesa@opengov.com>
PR-URL: https://github.com/nodejs/node/pull/67361
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
diff --git a/doc/api/errors.md b/doc/api/errors.md
index e6ab55bab05..881e98f9558 100644
--- a/doc/api/errors.md
+++ b/doc/api/errors.md
@@ -1757,6 +1757,14 @@ provided.
The `Http2Session` closed with a non-zero error code.
+<a id="ERR_HTTP2_SESSION_MEMORY_EXCEEDED"></a>
+
+### `ERR_HTTP2_SESSION_MEMORY_EXCEEDED`
+
+A request was rejected before being sent because the `Http2Session` was using
+more memory than its `maxSessionMemory` setting allows. Nothing was sent to the
+peer, so the request can be retried. The session remains usable.
+
<a id="ERR_HTTP2_SETTINGS_CANCEL"></a>
### `ERR_HTTP2_SETTINGS_CANCEL`
diff --git a/lib/internal/errors.js b/lib/internal/errors.js
index 88518563bc6..78d3de196a5 100644
--- a/lib/internal/errors.js
+++ b/lib/internal/errors.js
@@ -1325,6 +1325,9 @@ E('ERR_HTTP2_SEND_FILE', 'Directories cannot be sent', Error);
E('ERR_HTTP2_SEND_FILE_NOSEEK',
'Offset or length can only be specified for regular files', Error);
E('ERR_HTTP2_SESSION_ERROR', 'Session closed with error code %s', Error);
+E('ERR_HTTP2_SESSION_MEMORY_EXCEEDED',
+ 'The request was not sent because the session exceeded maxSessionMemory',
+ Error);
E('ERR_HTTP2_SETTINGS_CANCEL', 'HTTP2 session settings canceled', Error);
E('ERR_HTTP2_SOCKET_BOUND',
'The socket is already bound to an Http2Session', Error);
diff --git a/lib/internal/http2/core.js b/lib/internal/http2/core.js
index 44822c2ea01..e31050cb4ce 100644
--- a/lib/internal/http2/core.js
+++ b/lib/internal/http2/core.js
@@ -93,6 +93,7 @@ const {
ERR_HTTP2_SEND_FILE,
ERR_HTTP2_SEND_FILE_NOSEEK,
ERR_HTTP2_SESSION_ERROR,
+ ERR_HTTP2_SESSION_MEMORY_EXCEEDED,
ERR_HTTP2_SETTINGS_CANCEL,
ERR_HTTP2_SOCKET_BOUND,
ERR_HTTP2_SOCKET_UNBOUND,
@@ -894,6 +895,13 @@ function requestOnConnect(headersList, options) {
// For the first two, emit the error on the session,
// For the third, emit the error on the stream, it will bubble up to the
// session if not handled.
+ if (ret === false) {
+ // The session is over its `maxSessionMemory` budget. The request was never
+ // submitted to nghttp2, so nothing reached the peer; only this request is
+ // rejected and the session itself stays usable.
+ this.destroy(new ERR_HTTP2_SESSION_MEMORY_EXCEEDED());
+ return;
+ }
if (typeof ret === 'number') {
let err;
switch (ret) {
diff --git a/src/node_http2.cc b/src/node_http2.cc
index f00a7a65c32..3a357eaf449 100644
--- a/src/node_http2.cc
+++ b/src/node_http2.cc
@@ -3166,6 +3166,19 @@ void Http2Session::Request(const FunctionCallbackInfo<Value>& args) {
return;
}
+ // maxSessionMemory is documented to reject new streams while the limit is
+ // exceeded. CanAddStream() enforces that for peer-initiated streams; apply
+ // the same memory check to locally initiated requests so that a session
+ // whose socket is not draining cannot queue frames without bound. Like the
+ // response header check, queued request bodies are not counted, so large
+ // uploads do not prevent unrelated requests on the same session.
+ if (!session->has_available_session_memory(sizeof(Http2Stream),
+ /* exclude_outbound */ true))
+ [[unlikely]] {
+ Debug(session, "not submitting request: session memory limit exceeded");
+ return args.GetReturnValue().Set(false);
+ }
+
Debug(session, "request submitted");
int32_t ret = 0;
diff --git a/test/parallel/test-http2-max-session-memory-client-request.js b/test/parallel/test-http2-max-session-memory-client-request.js
new file mode 100644
index 00000000000..96abde18ebd
--- /dev/null
+++ b/test/parallel/test-http2-max-session-memory-client-request.js
@@ -0,0 +1,167 @@
+'use strict';
+
+const common = require('../common');
+if (!common.hasCrypto)
+ common.skip('missing crypto');
+
+const assert = require('assert');
+const http2 = require('http2');
+const net = require('net');
+const { once } = require('events');
+
+// maxSessionMemory is documented to reject new streams while the limit is
+// exceeded. Make sure that also holds for requests initiated by a client
+// session, so that a peer that does not read cannot make the client queue
+// frames without bound. As for response headers, request bodies that are
+// queued waiting for flow control are not counted, so a large upload does not
+// prevent unrelated requests on the same session.
+
+async function queuedUploadDoesNotBlockRequests() {
+ // The server never opens its flow-control window, so the upload stays queued
+ // in the client session.
+ const server = http2.createServer({ settings: { initialWindowSize: 0 } });
+ server.on('stream', common.mustCall((stream) => {
+ stream.on('error', () => {});
+ }, 2));
+ server.listen(0);
+ await once(server, 'listening');
+
+ const client = http2.connect(`http://localhost:${server.address().port}`, {
+ maxSessionMemory: 1,
+ });
+ client.on('error', common.mustNotCall());
+ await once(client, 'remoteSettings');
+
+ const uploadArrived = once(server, 'stream');
+ const upload = client.request({ ':method': 'POST', ':path': '/upload' });
+ upload.on('error', () => {});
+ upload.end(Buffer.alloc(4 * 1024 * 1024));
+ await uploadArrived;
+
+ const other = client.request({ ':path': '/other' });
+ other.on('error', () => {});
+ await once(server, 'stream');
+
+ other.destroy();
+ upload.destroy();
+ client.destroy();
+ server.close();
+}
+
+// A minimal HTTP/2 peer on a plain TCP socket, so that it can genuinely stop
+// reading. It acknowledges SETTINGS and answers every request with
+// `:status: 200` and END_STREAM, which closes the stream.
+function respondingPeer(socket) {
+ socket.write(Buffer.from([0, 0, 0, 4, 0, 0, 0, 0, 0])); // SETTINGS
+ let buffered = Buffer.alloc(0);
+ let prefaceSeen = false;
+ socket.on('data', (chunk) => {
+ buffered = Buffer.concat([buffered, chunk]);
+ if (!prefaceSeen) {
+ if (buffered.length < 24) return;
+ buffered = buffered.subarray(24);
+ prefaceSeen = true;
+ }
+ while (buffered.length >= 9) {
+ const length = buffered.readUIntBE(0, 3);
+ if (buffered.length < 9 + length) return;
+ const type = buffered[3];
+ const flags = buffered[4];
+ const streamId = buffered.readUInt32BE(5) & 0x7fffffff;
+ buffered = buffered.subarray(9 + length);
+ if (type === 4 && !(flags & 1)) {
+ socket.write(Buffer.from([0, 0, 0, 4, 1, 0, 0, 0, 0])); // SETTINGS ACK
+ } else if (type === 1) {
+ // HEADERS, END_STREAM | END_HEADERS, ':status: 200' (static index 8).
+ const frame = Buffer.from([0, 0, 1, 1, 5, 0, 0, 0, 0, 0x88]);
+ frame.writeUInt32BE(streamId, 5);
+ socket.write(frame);
+ }
+ }
+ });
+}
+
+async function stalledPeerRejectsRequestsAndSessionRecovers(stall) {
+ // Requests are submitted in batches that yield to the event loop, so their
+ // frames are written to the socket. While the peer answers them, streams
+ // close and nothing is rejected; once it stops reading, no responses arrive,
+ // so streams stay open and accumulate until maxSessionMemory rejects new
+ // requests.
+ let peerSocket;
+ const server = net.createServer((socket) => {
+ peerSocket = socket;
+ respondingPeer(socket);
+ });
+ server.listen(0);
+ await once(server, 'listening');
+
+ const client = http2.connect(`http://localhost:${server.address().port}`, {
+ maxSessionMemory: 1,
+ });
+ client.on('error', () => {});
+ await once(client, 'remoteSettings');
+ if (stall) peerSocket.pause();
+
+ let rejection;
+ const closed = [];
+ for (let batch = 0; batch < 200 && rejection === undefined; batch++) {
+ const batchClosed = [];
+ for (let i = 0; i < 100; i++) {
+ const req = client.request({ ':path': '/' });
+ req.on('error', (err) => {
+ if (err.code === 'ERR_HTTP2_SESSION_MEMORY_EXCEEDED') rejection ??= err;
+ });
+ batchClosed.push(new Promise((resolve) => req.once('close', resolve)));
+ req.end();
+ }
+ closed.push(...batchClosed);
+ // With a responsive peer, wait for the batch to finish so that the number
+ // of open streams does not depend on how quickly the peer answers.
+ await (stall ? new Promise(setImmediate) : Promise.all(batchClosed));
+ }
+
+ if (!stall) {
+ assert.strictEqual(rejection, undefined);
+ client.destroy();
+ peerSocket.destroy();
+ server.close();
+ return;
+ }
+
+ assert.ok(rejection, 'expected a request to be rejected');
+ assert.strictEqual(
+ rejection.message,
+ 'The request was not sent because the session exceeded maxSessionMemory');
+ assert.strictEqual(client.destroyed, false);
+ assert.strictEqual(client.closed, false);
+
+ // Once the peer reads again it answers the open streams, which close and
+ // free session memory, so a request that was rejected can be retried on the
+ // same session.
+ peerSocket.resume();
+ await Promise.all(closed);
+ let retry;
+ for (;;) {
+ retry = client.request({ ':path': '/retry' });
+ retry.resume();
+ retry.end();
+ // An accepted request gets its stream ID synchronously.
+ if (!retry.pending) break;
+ const [err] = await once(retry, 'error');
+ assert.strictEqual(err.code, 'ERR_HTTP2_SESSION_MEMORY_EXCEEDED');
+ await new Promise(setImmediate);
+ }
+ await once(retry, 'close');
+ assert.strictEqual(retry.rstCode, 0);
+ assert.strictEqual(client.destroyed, false);
+
+ client.destroy();
+ peerSocket.destroy();
+ server.close();
+}
+
+(async () => {
+ await queuedUploadDoesNotBlockRequests();
+ await stalledPeerRejectsRequestsAndSessionRecovers(false);
+ await stalledPeerRejectsRequestsAndSessionRecovers(true);
+})().then(common.mustCall());