Commit eda8de765bc for nodejs

commit eda8de765bcc738142677553613ac908a41b69e0
Author: Tim Perry <pimterry@gmail.com>
Date:   Thu Nov 19 20:14:15 2026 +0100

    http2: don't fail response reads after clean RST_STREAM

    Signed-off-by: Tim Perry <pimterry@gmail.com>
    PR-URL: https://github.com/nodejs/node/pull/67558
    Reviewed-By: James M Snell <jasnell@gmail.com>
    Reviewed-By: Matteo Collina <matteo.collina@gmail.com>

diff --git a/lib/internal/http2/core.js b/lib/internal/http2/core.js
index 926a72c8f1f..f24dbf2e250 100644
--- a/lib/internal/http2/core.js
+++ b/lib/internal/http2/core.js
@@ -354,6 +354,7 @@ const STREAM_FLAGS_HEAD_REQUEST = 0x8;
 const STREAM_FLAGS_ABORTED = 0x10;
 const STREAM_FLAGS_HAS_TRAILERS = 0x20;
 const STREAM_FLAGS_RST_DEFERRED = 0x40;
+const STREAM_FLAGS_CLEAN_REQUEST_RESET = 0x80;

 const SESSION_FLAGS_PENDING = 0x0;
 const SESSION_FLAGS_READY = 0x1;
@@ -611,7 +612,8 @@ function streamNaturalCloseSettled(stream) {
   return (stream._readableState.endEmitted ||
           !!stream._readableState.errored) &&
          (stream._writableState.finished ||
-          !!stream._writableState.errored);
+          !!stream._writableState.errored ||
+          !!(stream[kState].flags & STREAM_FLAGS_CLEAN_REQUEST_RESET));
 }

 // Shared 'end'/'finish'/'error' listener for the natural-close path of
@@ -632,7 +634,9 @@ function maybeDestroyNaturalClose() {
 // Clean code = NO_ERROR or CANCEL.
 //
 // Natural close defers destroy until 'end' and 'finish' - nghttp2 can
-// fire on_stream_close ahead of our last frame leaving the socket.
+// fire on_stream_close ahead of our last frame leaving the socket. On the
+// client, a clean reset for a request after a response END_STREAM just defers
+// until 'end', so the buffered response stays readable, with writes ignored.
 function onStreamClose(code, peerReset) {
   const stream = this[kOwner];
   if (!stream || stream.destroyed)
@@ -672,7 +676,12 @@ function onStreamClose(code, peerReset) {

   // Peer END_STREAMed - reads will complete. Only the writable half can
   // still be in flight at the protocol layer.
-  if (peerReset) {
+  const keepResponse = cleanCode &&
+    stream[kSession][kType] === NGHTTP2_SESSION_CLIENT;
+  if (peerReset && keepResponse) {
+    stream[kState].flags |= STREAM_FLAGS_CLEAN_REQUEST_RESET;
+    process.nextTick(settleWrite, stream);
+  } else if (peerReset) {
     if (!cleanCode && !stream._writableState.finished) {
       stream.destroy(
         new ERR_HTTP2_STREAM_ERROR(nameForErrorCode[code] || code));
@@ -2131,6 +2140,18 @@ function finishWrite(stream) {
   cb(err);
 }

+// A write in flight may never get its native completion callback once the
+// stream is closed; settle it so the Writable can make progress.
+function settleWrite(stream, err) {
+  const state = stream[kState];
+  if (state.writeCb !== null) {
+    const writeCb = state.writeCb;
+    state.writeCb = null;
+    state.writePending = 0;
+    writeCb(err);
+  }
+}
+
 // Runs on the tick after a write was dispatched: if the write turned out to
 // be the last chunk of an ending writable, shut the writable side down right
 // away so the final DATA frame can include the END_STREAM flag.
@@ -2507,6 +2528,10 @@ class Http2Stream extends Duplex {
     if (this.destroyed)
       return;

+    // The server no longer wants the rest of the request; discard it quietly.
+    if (this[kState].flags & STREAM_FLAGS_CLEAN_REQUEST_RESET)
+      return cb();
+
     this[kUpdateTimer]();
     if (!this.headersSent)
       this[kProceed]();
@@ -2594,6 +2619,8 @@ class Http2Stream extends Duplex {
       this.once('ready', () => this._final(cb));
       return;
     }
+    if (this[kState].flags & STREAM_FLAGS_CLEAN_REQUEST_RESET)
+      return cb();
     debugStreamObj(this, 'shutting down writable on _final');
     shutdownWritable.call(this, cb);

@@ -2793,14 +2820,7 @@ class Http2Stream extends Duplex {
       }
     }

-    // A write in flight may never get its native completion callback once the
-    // stream tears down; settle it so the Writable can clean up.
-    if (state.writeCb !== null) {
-      const writeCb = state.writeCb;
-      state.writeCb = null;
-      state.writePending = 0;
-      writeCb(err);
-    }
+    settleWrite(this, err);
     callback(err);
   }
   // The Http2Stream can be destroyed if it has closed and if the readable
diff --git a/test/common/README.md b/test/common/README.md
index bc27da028c4..ee13afcb4c7 100644
--- a/test/common/README.md
+++ b/test/common/README.md
@@ -884,6 +884,24 @@ socket.write(frame.data);

 The serialized `Buffer` may be retrieved using the `frame.data` property.

+### Class: `DataFrame`
+
+The `http2.DataFrame` is a subclass of `http2.Frame` that serializes a `DATA`
+frame.
+
+<!-- eslint-disable no-undef, node-core/require-common-first, node-core/required-modules -->
+
+```js
+// id is the 32-bit stream identifier
+// payload is a Buffer containing the DATA payload
+// padlen is an 8-bit integer giving the number of padding bytes to include
+// final is a boolean indicating whether the End-of-stream flag should be set,
+// defaults to false.
+const frame = new http2.DataFrame(id, payload, padlen, final);
+
+socket.write(frame.data);
+```
+
 ### Class: `HeadersFrame`

 The `http2.HeadersFrame` is a subclass of `http2.Frame` that serializes a
@@ -903,6 +921,21 @@ const frame = new http2.HeadersFrame(id, payload, padlen, final);
 socket.write(frame.data);
 ```

+### Class: `RstStreamFrame`
+
+The `http2.RstStreamFrame` is a subclass of `http2.Frame` that serializes an
+`RST_STREAM` frame.
+
+<!-- eslint-disable no-undef, node-core/require-common-first, node-core/required-modules -->
+
+```js
+// id is the 32-bit stream identifier
+// code is the 32-bit error code, defaults to 0 (NO_ERROR).
+const frame = new http2.RstStreamFrame(id, code);
+
+socket.write(frame.data);
+```
+
 ### Class: `SettingsFrame`

 The `http2.SettingsFrame` is a subclass of `http2.Frame` that serializes an
diff --git a/test/common/http2.js b/test/common/http2.js
index 1968b5bcfd3..b198ec758c1 100644
--- a/test/common/http2.js
+++ b/test/common/http2.js
@@ -99,6 +99,33 @@ class HeadersFrame extends Frame {
   }
 }

+class DataFrame extends Frame {
+  constructor(id, payload, padlen = 0, final = false) {
+    let len = payload.length;
+    let flags = 0;
+    if (final) flags |= FLAG_EOS;
+    const buffers = [payload];
+    if (padlen > 0) {
+      buffers.unshift(Buffer.from([padlen]));
+      buffers.push(PADDING.slice(0, padlen));
+      len += padlen + 1;
+      flags |= FLAG_PADDED;
+    }
+    super(len, 0, flags, id);
+    buffers.unshift(this[kFrameData]);
+    this[kFrameData] = Buffer.concat(buffers);
+  }
+}
+
+class RstStreamFrame extends Frame {
+  constructor(id, code = 0) {
+    super(4, 3, 0, id);
+    const payload = Buffer.alloc(4);
+    write32BE(payload, 0, code);
+    this[kFrameData] = Buffer.concat([this[kFrameData], payload]);
+  }
+}
+
 class PingFrame extends Frame {
   constructor(ack = false) {
     const buffers = [Buffer.alloc(8)];
@@ -120,7 +147,9 @@ class AltSvcFrame extends Frame {
 module.exports = {
   Frame,
   AltSvcFrame,
+  DataFrame,
   HeadersFrame,
+  RstStreamFrame,
   SettingsFrame,
   PingFrame,
   kFakeRequestHeaders,
diff --git a/test/parallel/test-http2-client-reset-after-response.js b/test/parallel/test-http2-client-reset-after-response.js
new file mode 100644
index 00000000000..0ad67dae03e
--- /dev/null
+++ b/test/parallel/test-http2-client-reset-after-response.js
@@ -0,0 +1,61 @@
+'use strict';
+
+// RFC 9113 section 8.1 allows a server to send RST_STREAM(NO_ERROR) after a
+// complete response while the request is still open, and clients must not
+// discard the response because of it. This is how servers send clients a
+// response that cancels a request (e.g. politely rejecting an upload).
+// The response should still stay fully readable and end cleanly, while the
+// rest of the request is quietly discarded.
+// Refs: https://github.com/nodejs/node/issues/66693
+
+const common = require('../common');
+if (!common.hasCrypto)
+  common.skip('missing crypto');
+
+const assert = require('assert');
+const http2 = require('http2');
+const { once } = require('events');
+
+const body = 'upload rejected';
+
+const server = http2.createServer();
+server.on('stream', common.mustCall((stream) => {
+  stream.respond({ ':status': 413 });
+  stream.once('data', common.mustCall(() => {
+    stream.end(body);
+    stream.close(http2.constants.NGHTTP2_NO_ERROR);
+  }));
+}));
+
+server.listen(0, common.mustCall(async () => {
+  const session = http2.connect(`http://localhost:${server.address().port}`);
+  const request = session.request({ ':method': 'POST' });
+  request.on('error', common.mustNotCall());
+  const [headers] = await once(request, 'response');
+  assert.strictEqual(headers[':status'], 413);
+
+  // Keep uploading without reading the response. The reset arrives partway
+  // through, and neither the write in flight then nor later ones may stall.
+  const chunk = Buffer.alloc(16 * 1024);
+  for (let i = 0; i < 20; i++) {
+    await new Promise((resolve) => {
+      request.write(chunk, common.mustSucceed(resolve));
+    });
+  }
+  assert.strictEqual(request.closed, true);
+  assert.strictEqual(request.rstCode, http2.constants.NGHTTP2_NO_ERROR);
+  assert.strictEqual(request.destroyed, false);
+
+  request.end();
+  await once(request, 'finish');
+
+  let received = '';
+  request.setEncoding('utf8');
+  request.on('data', (chunk) => { received += chunk; });
+  request.on('end', common.mustCall());
+  await once(request, 'close');
+  assert.strictEqual(received, body);
+
+  session.close();
+  server.close();
+}));
diff --git a/test/parallel/test-http2-client-reset-after-trailers.js b/test/parallel/test-http2-client-reset-after-trailers.js
new file mode 100644
index 00000000000..b93c67fcd01
--- /dev/null
+++ b/test/parallel/test-http2-client-reset-after-trailers.js
@@ -0,0 +1,107 @@
+'use strict';
+
+// A server may send the final DATA, trailers with END_STREAM and
+// RST_STREAM(NO_ERROR) together while the request is still open (RFC 9113
+// section 8.1), as gRPC servers do. A client that has paused partway through
+// the response must still be able to read the rest, and likewise for
+// RST_STREAM(CANCEL), which should only affect the request.
+// This closely reproduces https://github.com/nodejs/node/issues/66693
+// which requires some raw frame writes to match the reset behaviour.
+
+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');
+const { setImmediate: setImmediateAsync } = require('timers/promises');
+const h2test = require('../common/http2');
+
+const first = Buffer.from('first chunk');
+const last = Buffer.from('last chunk');
+// HPACK: indexed :status 200.
+const responseHeaders = Buffer.from([0x88]);
+// HPACK: literal without indexing, grpc-status: 0.
+const responseTrailers = Buffer.concat([
+  Buffer.from([0x00, 11]), Buffer.from('grpc-status'),
+  Buffer.from([1]), Buffer.from('0'),
+]);
+const streamId = 1;
+const startRequest = 'start of request';
+const continueRequest = 'more of request';
+
+async function startServer(code) {
+  const server = net.createServer(common.mustCall((socket) => {
+    // Client request -> response frames flow for the server:
+    const replies = [
+      [startRequest, [
+        new h2test.HeadersFrame(streamId, responseHeaders),
+        new h2test.DataFrame(streamId, first),
+      ]],
+      [continueRequest, [
+        new h2test.DataFrame(streamId, last),
+        new h2test.HeadersFrame(streamId, responseTrailers, 0, true),
+        new h2test.RstStreamFrame(streamId, code),
+      ]],
+    ];
+
+    let received = Buffer.alloc(0);
+    socket.on('error', () => {});
+    socket.on('data', (chunk) => {
+      received = Buffer.concat([received, chunk]);
+      while (replies.length > 0 && received.includes(replies[0][0])) {
+        const [, frames] = replies.shift();
+        socket.write(Buffer.concat(frames.map((frame) => frame.data)));
+      }
+    });
+
+    // Write settings to start the session:
+    socket.write(new h2test.SettingsFrame().data);
+    socket.write(new h2test.SettingsFrame(true).data);
+  }));
+  server.listen(0);
+  await once(server, 'listening');
+  return server;
+}
+
+(async () => {
+  for (const code of [
+    http2.constants.NGHTTP2_NO_ERROR,
+    http2.constants.NGHTTP2_CANCEL,
+  ]) {
+    const server = await startServer(code);
+    const session = http2.connect(`http://localhost:${server.address().port}`);
+    const request = session.request({ ':method': 'POST' });
+    request.on('error', common.mustNotCall());
+    request.on('response', common.mustCall());
+
+    // Read the first response chunk, then stop reading.
+    request.write(startRequest);
+    const [chunk] = await once(request, 'data');
+    assert.deepStrictEqual(chunk, first);
+    request.pause();
+
+    // Trigger the last response chunk + trailers + RST_STREAM.
+    request.write(continueRequest);
+    const [trailers] = await once(request, 'trailers');
+    assert.strictEqual(trailers['grpc-status'], '0');
+
+    while (!request.closed)
+      await setImmediateAsync();
+    assert.strictEqual(request.rstCode, code);
+    assert.strictEqual(request.destroyed, false);
+
+    // Check that we can still read the response after the RST:
+    const chunks = [];
+    request.on('data', (chunk) => chunks.push(chunk));
+    request.on('end', common.mustCall());
+    request.resume();
+    await once(request, 'close');
+    assert.deepStrictEqual(Buffer.concat(chunks), last);
+
+    session.destroy();
+    server.close();
+  }
+})().then(common.mustCall());