Commit f9257a013f5 for nodejs

commit f9257a013f5964f9c0fe5dc649182fa26fea1c4e
Author: Matteo Collina <hello@matteocollina.com>
Date:   Mon Nov 30 18:27:51 2026 +0100

    quic: pin session and stream lifetimes across re-entrant JS

    Sessions and streams are detached from JavaScript ownership: the
    SessionManager and the session's streams map hold the sole
    BaseObjectPtr references. Synchronous JavaScript callbacks made during
    Stream::Destroy(), Session::SendPendingData(), Session::SendDatagram()
    and Session::TryWritePendingDatagram() can destroy the session, dropping
    the last owning reference and freeing the C++ object while native code
    still touches it, resulting in a heap use-after-free (observed as a
    crash in Session::SendPendingDataScope::~SendPendingDataScope()).

    Pin the session with a strong BaseObjectPtr<Session> in
    SendPendingDataScope and in SendPendingData()/SendDatagram(), and pin
    the stream with a BaseObjectPtr<Stream> in Stream::Destroy(). Guard the
    re-entrant JavaScript call sites (StreamDataBlocked -> EmitBlocked,
    DatagramStatus) with is_destroyed() checks before continuing, so the
    send loop never dereferences a destroyed session's impl_.

    Signed-off-by: Matteo Collina <hello@matteocollina.com>
    PR-URL: https://github.com/nodejs/node/pull/67744
    Reviewed-By: James M Snell <jasnell@gmail.com>
    Reviewed-By: Ethan Arrowood <ethan@arrowood.dev>

diff --git a/src/quic/session.cc b/src/quic/session.cc
index 66899f43ad6..b9e5338ed98 100644
--- a/src/quic/session.cc
+++ b/src/quic/session.cc
@@ -1802,7 +1802,7 @@ Session::SendPendingDataScope::SendPendingDataScope(Session* session)

 Session::SendPendingDataScope::SendPendingDataScope(
     const BaseObjectPtr<Session>& session)
-    : session(session.get()) {
+    : session(session) {
   CHECK_NOT_NULL(session);
   CHECK(!session->is_destroyed());
   ++session->impl_->send_scope_depth_;
@@ -1811,7 +1811,8 @@ Session::SendPendingDataScope::SendPendingDataScope(
 Session::SendPendingDataScope::~SendPendingDataScope() {
   if (session->is_destroyed()) return;
   DCHECK_GE(session->impl_->send_scope_depth_, 1);
-  Debug(session, "Send Scope Depth %zu", session->impl_->send_scope_depth_);
+  Debug(
+      session.get(), "Send Scope Depth %zu", session->impl_->send_scope_depth_);
   if (--session->impl_->send_scope_depth_ == 0 &&
       session->impl_->application_ && !session->impl_->handshake_deferred_) {
     session->SendPendingData();
@@ -1868,7 +1869,11 @@ ssize_t Session::TryWritePendingDatagram(PathStorage* path,
           "Datagram %" PRIu64 " abandoned after %u attempts",
           front.id,
           front.send_attempts);
+    // DatagramStatus -> EmitDatagramStatus can call into JS and destroy the
+    // session. Bail out before touching impl_ again.
     DatagramStatus(front.id, DatagramStatus::ABANDONED);
+    if (is_destroyed()) [[unlikely]]
+      return 0;
     PopPendingDatagram();
   }

@@ -1929,7 +1934,11 @@ ssize_t Session::TryWritePendingDatagram(PathStorage* path,
       // Non-fatal error cases. Peer either does not support datagrams
       // or the datagram is too large for the peer's max.
       // Abandon the datagram and signal skip by returning std::nullopt.
+      // DatagramStatus -> EmitDatagramStatus can call into JS and destroy the
+      // session. Bail out before touching impl_ again.
       DatagramStatus(dg.id, DatagramStatus::ABANDONED);
+      if (is_destroyed()) [[unlikely]]
+        return 0;
       PopPendingDatagram();
       return 0;
     }
@@ -1953,6 +1962,13 @@ ssize_t Session::TryWritePendingDatagram(PathStorage* path,
 // and make sure to test thoroughly. When in doubt... don't change it.
 void Session::SendPendingData() {
   DCHECK(!is_destroyed());
+  // Pin the session for the duration of this method. The session is detached
+  // from JS ownership (SessionManager holds the sole BaseObjectPtr<Session>)
+  // and the synchronous JS callbacks below (StreamCommit, StreamDataBlocked,
+  // DatagramStatus, ...) can destroy and free it. Pinning keeps the Session
+  // object alive so the is_destroyed() guards and the update_stats scope-exit
+  // lambda never touch freed heap memory.
+  BaseObjectPtr<Session> self(this);
   if (!can_send_packets()) [[unlikely]] {
     return;
   }
@@ -2143,7 +2159,14 @@ void Session::SendPendingData() {
           // We should only have received this error if there was an actual
           // stream identified in the stream data, but let's double check.
           DCHECK_GE(stream_data.id, 0);
+          // StreamDataBlocked -> BlockStream -> EmitBlocked can call into JS
+          // and destroy the session. Bail out before continuing the loop; the
+          // next iteration would dereference the (now null) impl_.
           StreamDataBlocked(stream_data.id);
+          if (is_destroyed()) [[unlikely]] {
+            closed = true;
+            return;
+          }
           continue;
         }
         case NGTCP2_ERR_STREAM_SHUT_WR: {
@@ -2173,6 +2196,12 @@ void Session::SendPendingData() {
           if (HasPendingDatagrams()) {
             auto result = TryWritePendingDatagram(
                 &path, packet->data(), packet->length(), ts);
+            // TryWritePendingDatagram -> DatagramStatus can call into JS and
+            // destroy the session.
+            if (is_destroyed()) [[unlikely]] {
+              closed = true;
+              return;
+            }
             // When result is 0, either the datagram was congestion controlled,
             // didn't fit in the packet, or was abandoned. Skip and continue.

@@ -2234,6 +2263,12 @@ void Session::SendPendingData() {
       }
       auto result =
           TryWritePendingDatagram(&path, packet->data(), packet->length(), ts);
+      // TryWritePendingDatagram -> DatagramStatus can call into JS and destroy
+      // the session.
+      if (is_destroyed()) [[unlikely]] {
+        closed = true;
+        return;
+      }
       if (result > 0) {
         Debug(this, "Sending datagram packet with %zd bytes", result);
         enqueue_packet(packet, static_cast<size_t>(result), PacketInfo());
@@ -3140,6 +3175,10 @@ void Session::Send(Packet::Ptr packet, const PathStorage& path) {

 datagram_id Session::SendDatagram(Store&& data) {
   DCHECK(!is_destroyed());
+  // Pin the session. DatagramStatus below can call into JS and destroy the
+  // session; the pin keeps the Session object alive so is_destroyed() guards
+  // and trailing impl_ accesses are safe.
+  BaseObjectPtr<Session> self(this);

   // Sending a datagram is best effort. If we cannot send it for any reason,
   // we just return 0 to indicate that the datagram was not sent an the
@@ -3186,12 +3225,16 @@ datagram_id Session::SendDatagram(Store&& data) {
             "Datagram queue full, dropping oldest datagram %" PRIu64,
             oldest.id);
       DatagramStatus(oldest.id, DatagramStatus::ABANDONED);
+      if (is_destroyed()) [[unlikely]]
+        return 0;
       impl_->pending_datagrams_.pop_front();
     } else {
       // DROP_NEWEST: reject the incoming datagram.
       Debug(
           this, "Datagram queue full, dropping newest datagram %" PRIu64, did);
       DatagramStatus(did, DatagramStatus::ABANDONED);
+      if (is_destroyed()) [[unlikely]]
+        return 0;
       return did;
     }
   }
diff --git a/src/quic/session.h b/src/quic/session.h
index 941351c7b7b..dae2fb19d6f 100644
--- a/src/quic/session.h
+++ b/src/quic/session.h
@@ -364,7 +364,14 @@ class Session final : public AsyncWrap, private SessionTicket::AppData::Source {
   // exits. Scopes can be nested. When nested, pending data will be sent
   // only when the outermost scope is exited.
   struct SendPendingDataScope final {
-    Session* session;
+    // Sessions are detached from JS ownership: SessionManager::sessions_ holds
+    // the sole BaseObjectPtr<Session>. Synchronous JS callbacks made while the
+    // scope is active (BeginShutdown, EmitClose, DatagramStatus, EmitBlocked,
+    // EmitWantTrailers) can destroy the session and free it. Pinning the
+    // session with a strong BaseObjectPtr keeps the Session object alive for
+    // the lifetime of the scope so the destructor never dereferences freed
+    // heap memory.
+    BaseObjectPtr<Session> session;
     explicit SendPendingDataScope(Session* session);
     explicit SendPendingDataScope(const BaseObjectPtr<Session>& session);
     ~SendPendingDataScope();
diff --git a/src/quic/streams.cc b/src/quic/streams.cc
index 1951a7d3e1e..3e18a580986 100644
--- a/src/quic/streams.cc
+++ b/src/quic/streams.cc
@@ -1563,6 +1563,15 @@ void Stream::CapReadable(std::optional<uint64_t> maybe_final_size) {
 void Stream::Destroy(QuicError error) {
   if (is_destroyed()) return;

+  // Pin the stream for the duration of Destroy(). Stream objects are detached
+  // from JS ownership (the session's streams_ map holds the sole
+  // BaseObjectPtr<Stream>). ReturnFlowControlCredit and EmitClose below can
+  // call into JS, and a JS callback may destroy the session — which releases
+  // the last BaseObjectPtr<Stream> and frees `this` before the remaining
+  // teardown (id(), ReleaseArenaSlots(), RemoveStream()) runs. The pin keeps
+  // the Stream object alive through the whole function.
+  BaseObjectPtr<Stream> self(this);
+
   // Record the destroyed at timestamp before notifying the JavaScript side
   // that the stream is being destroyed.
   STAT_RECORD_TIMESTAMP(Stats, destroyed_at);
diff --git a/test/parallel/test-quic-session-close-after-drain.mjs b/test/parallel/test-quic-session-close-after-drain.mjs
new file mode 100644
index 00000000000..933a03ad6d4
--- /dev/null
+++ b/test/parallel/test-quic-session-close-after-drain.mjs
@@ -0,0 +1,101 @@
+// Flags: --experimental-quic --experimental-stream-iter --no-warnings
+
+// Regression test for a heap-use-after-free in the QUIC session close path.
+//
+// When a server responds to an HTTP/3 request and then calls session.close()
+// after the stream has fully drained (and been removed from the session's
+// streams map), Session::Close(GRACEFUL) takes the "no open streams" branch
+// and calls FinishClose(). FinishClose() emits the close event to JavaScript,
+// and that synchronous JS callback can destroy the session — releasing the
+// sole BaseObjectPtr<Session> held by SessionManager and freeing the Session
+// object — while the SendPendingDataScope created at the top of Close() is
+// still active. The scope's destructor then dereferences the freed session
+// (SendPendingDataScope::~SendPendingDataScope() use-after-free).
+//
+// The fix pins the Session with a strong BaseObjectPtr<Session> for the
+// lifetime of SendPendingDataScope (and of SendPendingData itself) so the
+// destructor and trailing member accesses never operate on freed heap memory.
+
+import { hasQuic, skip, mustCall } from '../common/index.mjs';
+import assert from 'node:assert';
+import * as fixtures from '../common/fixtures.mjs';
+
+if (!hasQuic) {
+  skip('QUIC is not enabled');
+}
+
+const { listen, connect } = await import('node:quic');
+const { createPrivateKey } = await import('node:crypto');
+const { bytes } = await import('stream/iter');
+
+const key = createPrivateKey(fixtures.readKey('agent1-key.pem'));
+const cert = fixtures.readKey('agent1-cert.pem');
+const decoder = new TextDecoder();
+const encoder = new TextEncoder();
+
+{
+  let serverSession;
+  let requestCount = 0;
+  const serverDone = Promise.withResolvers();
+
+  const serverEndpoint = await listen(mustCall((ss) => {
+    serverSession = ss;
+    ss.closed.catch(() => {});
+    ss.onstream = mustCall((stream) => {
+      stream.closed.catch(() => {});
+      stream.onheaders = mustCall((headers) => {
+        const reqPath = headers[':path'] || '/';
+        stream.sendHeaders({ ':status': '200' });
+        stream.writer.writeSync(encoder.encode('ok'));
+        stream.writer.endSync();
+
+        // Once the request stream has fully drained, close the session.
+        // Deferring via setTimeout ensures the
+        // stream has been removed from the session's streams map before
+        // close() is called, so Close(GRACEFUL) immediately finishes the
+        // close and emits the close event to JS synchronously while a
+        // SendPendingDataScope is alive — the path that previously used a
+        // freed Session.
+        if (++requestCount === 1) {
+          assert.strictEqual(reqPath, '/poc');
+          stream.closed.then(mustCall(() => {
+            setTimeout(mustCall(() => {
+              if (!serverSession.destroyed) {
+                serverSession.close();
+              }
+              serverDone.resolve();
+            }), 50);
+          })).catch(() => {});
+        }
+      });
+    });
+  }), {
+    sni: { '*': { keys: [key], certs: [cert] } },
+  });
+
+  const clientSession = await connect(serverEndpoint.address, {
+    servername: 'localhost',
+    verifyPeer: 'manual',
+  });
+  await clientSession.opened;
+  clientSession.closed.catch(() => {});
+
+  const stream = await clientSession.createBidirectionalStream({
+    headers: {
+      ':method': 'GET',
+      ':path': '/poc',
+      ':scheme': 'https',
+      ':authority': 'localhost',
+    },
+  });
+
+  const body = await bytes(stream);
+  assert.strictEqual(decoder.decode(body), 'ok');
+  await stream.closed;
+
+  await serverDone.promise;
+  await clientSession.closed.catch(() => {});
+
+  await clientSession.close().catch(() => {});
+  await serverEndpoint.close();
+}