Title: http2: client session leaks (no `'error'`, no `'close'`, socket never destroyed) when the server rejects the TLS handshake · Issue #67213 · nodejs/node · GitHub
Open Graph Title: http2: client session leaks (no `'error'`, no `'close'`, socket never destroyed) when the server rejects the TLS handshake · Issue #67213 · nodejs/node
X Title: http2: client session leaks (no `'error'`, no `'close'`, socket never destroyed) when the server rejects the TLS handshake · Issue #67213 · nodejs/node
Description: Version v22.22.2. Also reproduced on v18.20.4, v20.18.3, v22.14.0, v24.16.0 and v26.3.0. The code paths below are unchanged on main. Platform Darwin 25.6.0 arm64 (macOS). Also observed in production on Linux x64 (Node 22.22.2, OpenSSL 3....
Open Graph Description: Version v22.22.2. Also reproduced on v18.20.4, v20.18.3, v22.14.0, v24.16.0 and v26.3.0. The code paths below are unchanged on main. Platform Darwin 25.6.0 arm64 (macOS). Also observed in productio...
X Description: Version v22.22.2. Also reproduced on v18.20.4, v20.18.3, v22.14.0, v24.16.0 and v26.3.0. The code paths below are unchanged on main. Platform Darwin 25.6.0 arm64 (macOS). Also observed in productio...
Opengraph URL: https://github.com/nodejs/node/issues/67213
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"http2: client session leaks (no `'error'`, no `'close'`, socket never destroyed) when the server rejects the TLS handshake","articleBody":"### Version\n\nv22.22.2. Also reproduced on v18.20.4, v20.18.3, v22.14.0, v24.16.0 and v26.3.0. The code paths below are unchanged on `main`.\n\n### Platform\n\n```text\nDarwin 25.6.0 arm64 (macOS). Also observed in production on Linux x64 (Node 22.22.2, OpenSSL 3.5.5).\n```\n\n### Subsystem\n\nhttp2, tls\n\n### What steps will reproduce the bug?\n\nSave as `repro.js` and run `node --expose-gc repro.js`. It has no dependencies; the key and certificate are a throwaway self-signed pair for `CN=localhost`.\n\nThe server requires a client certificate (`requestCert` + `rejectUnauthorized`). The client sends none, so OpenSSL on the server side sends a fatal TLS alert (116 `certificate required`). With TLS 1.3 the client has already finished its side of the handshake when the alert arrives. In production we hit the same thing when a gRPC server rejected an expired client certificate (alert 45 `certificate expired`).\n\n```js\n'use strict';\n// Run: node --expose-gc repro.js [iterations]\nconst http2 = require('node:http2');\n\n// Throwaway self-signed test certificate for CN=localhost (not a secret).\nconst key = `-----BEGIN PRIVATE KEY-----\nMIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgCUEnXOaW6XdF+Uli\nxaXWH4jND4SgrxgWoCiPaseL04ihRANCAASmz8jUAlKXn9rtXvNEo/89lAIekPtG\nY03r5IK555fTgTPDm0kLbv9S43v9VXz/u1d/csVZcYYblXxETHYRkinf\n-----END PRIVATE KEY-----\n`;\nconst cert = `-----BEGIN CERTIFICATE-----\nMIIBczCCARigAwIBAgIUC1XONRc6u557juM0koDJlMoldCkwCgYIKoZIzj0EAwIw\nFDESMBAGA1UEAwwJbG9jYWxob3N0MB4XDTI2MTAyOTE1NTIzNloXDTM2MTAyNjE1\nNTIzNlowFDESMBAGA1UEAwwJbG9jYWxob3N0MFkwEwYHKoZIzj0CAQYIKoZIzj0D\nAQcDQgAEps/I1AJSl5/a7V7zRKP/PZQCHpD7RmNN6+SCueeX04Ezw5tJC27/UuN7\n/VV8/7tXf3LFWXGGG5V8REx2EZIp36NIMEYwHQYDVR0OBBYEFIwoK1GT0vaH2Ty2\nOEv2TwymxkviMA8GA1UdEwEB/wQFMAMBAf8wFAYDVR0RBA0wC4IJbG9jYWxob3N0\nMAoGCCqGSM49BAMCA0kAMEYCIQChoXNku5ZKVpPGLBCCt2sMeLJi3eRvIFM/PmEa\nxd3jQQIhAP6B0BXplq2wD0Hl179L7HRbCSBkUwbjJ3Fdg0HgvOpL\n-----END CERTIFICATE-----\n`;\n\n\n\n// The server requires a client certificate. Because the client sends none,\n// OpenSSL on the server side rejects it with a fatal TLS alert\n// (116 \"certificate required\"). With TLS 1.3 the client has already finished\n// its side of the handshake, so the alert arrives after 'connect'.\nconst server = http2.createSecureServer({\n key, cert, requestCert: true, rejectUnauthorized: true,\n});\nserver.on('tlsClientError', () => {});\n\nserver.listen(0, async () => {\n const url = `https://localhost:${server.address().port}`;\n const iterations = Number(process.argv[2] || 20);\n const sessions = [];\n\n for (let i = 0; i \u003c iterations; i++) {\n await new Promise((resolve) => {\n const session = http2.connect(url, { rejectUnauthorized: false });\n const rec = { ref: new WeakRef(session), error: false, close: false };\n sessions.push(rec);\n session.on('error', () => { rec.error = true; });\n session.on('close', () => { rec.close = true; resolve(); });\n setTimeout(resolve, 500); // give up waiting for 'close'\n });\n }\n\n server.close();\n for (let i = 0; i \u003c 5; i++) {\n globalThis.gc();\n await new Promise((r) => setTimeout(r, 100));\n }\n\n const alive = sessions.map((s) => s.ref.deref()).filter(Boolean);\n console.log({\n node: process.version,\n sessions: iterations,\n errorEmitted: sessions.filter((s) => s.error).length,\n closeEmitted: sessions.filter((s) => s.close).length,\n aliveAfterGC: alive.length,\n aliveAndDestroyed: alive.filter((s) => s.destroyed).length,\n aliveWithSocketNotDestroyed: alive.filter((s) => s.socket && !s.socket.destroyed).length,\n });\n process.exit(0);\n});\n```\n\n### How often does it reproduce? Is there a required condition?\n\nAlways (20/20 sessions on every version listed above).\n\nRequired conditions:\n- an `http2.connect()` client over TLS 1.3, and\n- the server sends a fatal alert **after** the client's handshake is complete, so the client is already `_secureEstablished`. A server rejecting the client certificate is the common real-world case: expired, unknown CA, missing, or revoked certificate.\n- The server keeps the TCP connection open after sending the alert, or at least doesn't close it before the client reacts. OpenSSL-based servers do this, as does Node's own server in the repro.\n\nIf the TCP connection is reset or closed right away, the session closes normally.\n\n### What is the expected behavior? Why is that the expected behavior?\n\n```text\nerrorEmitted: 20, closeEmitted: 20, aliveAfterGC: 0\n```\n\nThe TLS error should surface as an `'error'` event on the session, followed by `'close'`, and the session and its socket should be released.\n\n### What do you see instead?\n\n```text\n{ node: 'v22.22.2', sessions: 20, errorEmitted: 0, closeEmitted: 0, aliveAfterGC: 20, aliveAndDestroyed: 20, aliveWithSocketNotDestroyed: 20 }\n```\n\n- `session.destroyed === true`, but neither `'error'` nor `'close'` is ever emitted.\n- The underlying `TLSSocket` is never destroyed. Its handle and file descriptor stay open forever.\n- The session, the socket, the native `Http2Session` (nghttp2 state), a pending `WriteWrap`, and everything reachable from the listeners are never garbage-collected.\n\nGrowth over 1000 failed connections (`measure.js`, attached):\n\n```text\nbefore: { heapUsedMB: 4.5, rssMB: 48.4, openFds: 23, activeSocketHandles: 0 }\nafter: { heapUsedMB: 10.7, rssMB: 96.3, openFds: 1026, activeSocketHandles: 1000 }\n```\n\nIn production, a gRPC client (`@grpc/grpc-js`) kept reconnecting to a server that rejected its expired client certificate. A heap snapshot showed ~6,900 leaked `ClientHttp2Session` objects, each with a pending native `SimpleWriteWrap` and `Http2Settings` callback. Memory grew until the process was restarted, and file descriptors leaked along with it.\n\n\n### Additional information\n\n#### Analysis\n\nNative trace (`NODE_DEBUG_NATIVE=TLS,HTTP2SESSION`, client side, full log attached):\n\n```text\nTLSWrap Got SSL error (1), calling onerror\nHttp2Session destroying session\nHttp2Session closing session\nTLSWrap ReadStop()\nHttp2Session terminating session with code 2\nHttp2Session sending pending data\nHttp2Session nghttp2 has 17 bytes to send \u003c- GOAWAY\nTLSWrap DoWrite()\nTLSWrap Writing 17 bytes, written = -1\nTLSWrap Saving data for later write \u003c- write stays pending forever\nTLSWrap Trying to write encrypted output\nTLSWrap EncOut() write is scheduled\nTLSWrap No pending encrypted output\n \u003c- nothing else, ever: no \"make done session callback\"\n```\n\nStep by step (links to v22.22.2):\n\n1. The alert arrives after the TLS handshake is established, so the TLS `onerror` handler takes the `_emitTLSError(err)` branch. It emits `'error'` **without destroying the socket** ([lib/internal/tls/wrap.js#L480-L496](https://github.com/nodejs/node/blob/v22.22.2/lib/internal/tls/wrap.js#L480-L496)).\n2. http2's `socketOnError` calls `session.destroy(error)` ([lib/internal/http2/core.js#L3229-L3239](https://github.com/nodejs/node/blob/v22.22.2/lib/internal/http2/core.js#L3229-L3239)). `closeSession` then sets `handle.ondone = finishSessionClose` and calls `handle.destroy(code, socket.destroyed)` with `socket.destroyed === false` ([core.js#L1219-L1248](https://github.com/nodejs/node/blob/v22.22.2/lib/internal/http2/core.js#L1219-L1246)).\n3. `Http2Session::Close(code, socket_closed=false)` stops reading, terminates the nghttp2 session and calls `SendPendingData()` to send a GOAWAY ([src/node_http2.cc#L816-L855](https://github.com/nodejs/node/blob/v22.22.2/src/node_http2.cc#L816-L855)).\n4. In `TLSWrap::DoWrite`, `SSL_write()` returns `-1` on the dead TLS connection. `SSL_get_error()` returns something other than `SSL_ERROR_SSL`/`SSL_ERROR_SYSCALL`, so the data is kept \"for later write\" and `current_write_` stays set ([src/crypto/crypto_tls.cc#L1118-L1135](https://github.com/nodejs/node/blob/v22.22.2/src/crypto/crypto_tls.cc#L1118-L1135)). \"Later\" never comes: reading was stopped in step 3, and the TLS connection can't make progress after a fatal alert anyway.\n5. Back in `Http2Session::Close`, `is_write_in_progress()` is true, so `ondone` isn't called (\"If we are writing we will get to make the callback in OnStreamAfterWrite\", [node_http2.cc#L845-L856](https://github.com/nodejs/node/blob/v22.22.2/src/node_http2.cc#L845-L855)). `OnStreamAfterWrite` never runs.\n6. `ondone` is `finishSessionClose`, which is the only code that ends/destroys the socket and emits `'error'`/`'close'` ([core.js#L1187-L1217](https://github.com/nodejs/node/blob/v22.22.2/lib/internal/http2/core.js#L1187-L1217)). Because it never runs, nobody destroys the socket, and the session stays half-closed forever.\n\nThe result is a deadlock: the session waits for the write to finish before releasing the socket, and the write can only finish once something unblocks the socket.\n\n#### Workaround\n\nOwn the socket via `createConnection` and destroy it on `'error'` (`workaround.js`, attached; 20/20 sessions emit `'close'` and are collected):\n\n```js\nconst session = http2.connect(url, {\n createConnection: () => {\n const socket = tls.connect({ host, port, ALPNProtocols: ['h2'] /* ... */ });\n socket.on('error', () => socket.destroy());\n return socket;\n },\n});\n```\n\nThis doesn't help users of `http2.connect(url)` with default options, because `session.socket` is a proxy that forbids `destroy()`.\n\n#### Possible fixes (suggestions only, not verified)\n\n- In `socketOnError`, also destroy the socket for TLS errors on an established TLS socket, or pass `socket_closed = true` to the native side so `Close()` doesn't try to send a GOAWAY over a broken TLS connection.\n- In `TLSWrap::DoWrite`, treat `SSL_write()` failures after a fatal alert as fatal (return `UV_EPROTO` like the `SSL_ERROR_SSL`/`SSL_ERROR_SYSCALL` case) instead of queueing the data.\n- In `Http2Session::Close`, don't wait for an in-progress write that can't complete because reading has been stopped and the stream has errored.","author":{"url":"https://github.com/dvergnes","@type":"Person","name":"dvergnes"},"datePublished":"2026-11-03T03:33:31Z","url":"https://github.com/nodejs/node/issues/67213"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react-reconciler,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@d5750093facf |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:407e2046-bf6b-fcb4-c441-b2745061ccb7 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | 81E0:257BEE:7695E4:9D91B0:6AED24A0 |
| html-safe-nonce | cd3619ec2f37038241e3ade576a85cb7c869beb36283ae54c204044b48ad5530 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI4MUUwOjI1N0JFRTo3Njk1RTQ6OUQ5MUIwOjZBRUQyNEEwIiwidmlzaXRvcl9pZCI6IjcxMzM3MDI1Mjg4MDgzMzA0MDEiLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ== |
| visitor-hmac | 1d530624d3d02a728c703714017edf7784b4aa8f2639f7d7907c47acfe9d0555 |
| hovercard-subject-tag | issue:6175755448 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/nodejs/node/67213/issue_layout |
| twitter:image | https://opengraph.githubassets.com/a8b366839bebad581af81ad5ada2b8415446bd2db59ed25a167758ee7a2f35f8/nodejs/node/issues/67213 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/a8b366839bebad581af81ad5ada2b8415446bd2db59ed25a167758ee7a2f35f8/nodejs/node/issues/67213 |
| og:image:alt | Version v22.22.2. Also reproduced on v18.20.4, v20.18.3, v22.14.0, v24.16.0 and v26.3.0. The code paths below are unchanged on main. Platform Darwin 25.6.0 arm64 (macOS). Also observed in productio... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | dvergnes |
| hostname | github.com |
| expected-hostname | github.com |
| None | e3e0f7f63e50c6fe879198a93a0a023a648ecc0a5e9bc3b5e033ac57172237e6 |
| turbo-cache-control | no-preview |
| go-import | github.com/nodejs/node git https://github.com/nodejs/node.git |
| octolytics-dimension-user_id | 9950313 |
| octolytics-dimension-user_login | nodejs |
| octolytics-dimension-repository_id | 27193779 |
| octolytics-dimension-repository_nwo | nodejs/node |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 27193779 |
| octolytics-dimension-repository_network_root_nwo | nodejs/node |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 707a24b346ac8a82878b9c084efaa38a997660cb |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width