Repository: nodejs/node
Pull request: http2: fix memory leak caused by premature listener removing

Http2Session should always call ondone into JS to detach the handle. In some case, ondone is defered to be called by the StreamListener through WriteWrap, we should be careful of this before getting rid of the StreamListener.

The test case destroys the socket governed by http2. This is not a good practice, but nodejs internal in some case does this too (e.g. when a TCP RESET is received, nodejs internal destroys the socket without bothering it is consumed by a http2 session or not) and it is the simplest code that I can come up with to produce this issue.

I stongly believe that this fixs https://github.com/nodejs/node/issues/42710 based on the issue's description

<!--
Before submitting a pull request, please read:

- the CONTRIBUTING guide at https://github.com/nodejs/node/blob/HEAD/CONTRIBUTING.md
- the commit message formatting guidelines at
  https://github.com/nodejs/node/blob/HEAD/doc/contributing/pull-requests.md#commit-message-guidelines

For code changes:
1. Include tests for any bug fixes or new features.
2. Update documentation if relevant.
3. Ensure that `make -j4 test` (UNIX), or `vcbuild test` (Windows) passes.

If you believe this PR should be highlighted in the Node.js CHANGELOG
please add the `notable-change` label.

Developer's Certificate of Origin 1.1

By making a contribution to this project, I certify that:

(a) The contribution was created in whole or in part by me and I
    have the right to submit it under the open source license
    indicated in the file; or

(b) The contribution is based upon previous work that, to the best
    of my knowledge, is covered under an appropriate open source
    license and I have the right under that license to submit that
    work with modifications, whether created in whole or in part
    by me, under the same open source license (unless I am
    permitted to submit under a different license), as indicated
    in the file; or

(c) The contribution was provided directly to me by some other
    person who certified (a), (b) or (c) and I have not modified
    it.

(d) I understand and agree that this project and the contribution
    are public and that a record of the contribution (including all
    personal information I submit with it, including my sign-off) is
    maintained indefinitely and may be redistributed consistent with
    this project or the open source license(s) involved.
-->


Changed files:
filename: src/node_http2.cc
patch: @@ -803,13 +803,15 @@ void Http2Session::Close(uint32_t code, bool socket_closed) {
     CHECK_EQ(nghttp2_session_terminate_session(session_.get(), code), 0);
     SendPendingData();
   } else if (stream_ != nullptr) {
+    // so that the previous listener of the socket, typically, JS code of a
+    // (tls) socket will be notified of any activity later
     stream_->RemoveStreamListener(this);
   }
 
   set_destroyed();
 
   // If we are writing we will get to make the callback in OnStreamAfterWrite.
-  if (!is_write_in_progress()) {
+  if (!is_write_in_progress() || !stream_) {
     Debug(this, "make done session callback");
     HandleScope scope(env()->isolate());
     MakeCallback(env()->ondone_string(), 0, nullptr);

filename: test/parallel/test-h2leak-destroy-session-on-socket-ended.js
patch: @@ -0,0 +1,80 @@
+'use strict';
+// Flags: --expose-gc
+
+const common = require('../common');
+if (!common.hasCrypto)
+  common.skip('missing crypto');
+const http2 = require('http2');
+const tls = require('tls');
+const fixtures = require('../common/fixtures');
+const assert = require('assert');
+
+const registry = new FinalizationRegistry(common.mustCall((name) => {
+  assert(name, 'session');
+}));
+
+const server = http2.createSecureServer({
+  key: fixtures.readKey('agent1-key.pem'),
+  cert: fixtures.readKey('agent1-cert.pem'),
+});
+
+let firstServerStream;
+
+
+server.on('secureConnection', (s) => {
+  console.log('secureConnection');
+  s.on('end', () => {
+    console.log(s.destroyed); // false !!
+    s.destroy();
+    firstServerStream.session.destroy();
+
+    firstServerStream = null;
+
+    setImmediate(() => {
+      global.gc();
+      global.gc();
+
+      server.close();
+    });
+  });
+});
+
+server.on('session', (s) => {
+  registry.register(s, 'session');
+});
+
+server.on('stream', (stream) => {
+  console.log('stream...');
+  stream.write('a'.repeat(1024));
+  firstServerStream = stream;
+  setImmediate(() => console.log('Draining setImmediate after writing'));
+});
+
+
+server.listen(() => {
+  client();
+});
+
+
+const h2fstStream = [
+  'UFJJICogSFRUUC8yLjANCg0KU00NCg0K',
+  // http message (1st stream:)
+  'AAAABAAAAAAA',
+  'AAAPAQUAAAABhIJBiqDkHROdCbjwHgeG',
+];
+function client() {
+  const client = tls.connect({
+    port: server.address().port,
+    host: 'localhost',
+    rejectUnauthorized: false,
+    ALPNProtocols: ['h2']
+  }, () => {
+    client.end(Buffer.concat(h2fstStream.map((s) => Buffer.from(s, 'base64'))), (err) => {
+      assert.ifError(err);
+    });
+  });
+
+  client.on('error', (error) => {
+    console.error('Connection error:', error);
+  });
+}