interceptors icon indicating copy to clipboard operation
interceptors copied to clipboard

SocketInterceptor: a connection still pending at `dispose()` is passed through to the real network

Open luizfneves404 opened this issue 1 month ago • 3 comments

Summary

When the socket interceptor is disposed while a net/tls connection is still pending, interceptConnection's deferred check runs after dispose() has removed the last "connection" listener. It reads that as "nobody is handling connections" and calls controller.passthrough(), which opens a real socket. So a setupServer() whose close() runs in the same tick as a request it just intercepted sends that request to the real network.

This is a reduced, standalone repro of a problem I first saw in a Vitest suite: server.close() at file end routed requests created shortly before close to real DNS (one file emitted ~12 getaddrinfo ENOTFOUND for a reserved host after the last test finished).

Environment

  • @mswjs/interceptors 0.45.9 (latest; first seen on 0.45.7) via msw 3.0.3, setupServer
  • Node.js 24.20.0 (originally hit on Node 22)
  • Linux; reproduces on every run

Minimal reproduction

Install [email protected] (which resolves @mswjs/[email protected]), then run the script below with node repro.mjs.

import http from 'node:http'
import { http as mswHttp, HttpResponse } from 'msw'
import { setupServer } from 'msw/node'

// A real loopback server. Anything it receives escaped the interceptor.
const escaped = []
const realServer = http.createServer((req, res) => {
  escaped.push(req.method + ' ' + req.url)
  res.end('REAL')
})
await new Promise((resolve) => realServer.listen(0, '127.0.0.1', resolve))
const { port } = realServer.address()
const url = `http://127.0.0.1:${port}/x`

async function scenario(disposeBeforeTick) {
  const server = setupServer(
    mswHttp.get(url, () => HttpResponse.json({ mocked: true }))
  )
  server.listen({ onUnhandledRequest: 'error' })

  const before = escaped.length
  const outcome = new Promise((resolve) => {
    const req = http.get(url, (res) => {
      let body = ''
      res.on('data', (c) => (body += c))
      res.on('end', () => resolve(`status ${res.statusCode} body "${body}"`))
    })
    req.on('error', (error) => resolve(`error ${error.code || error.message}`))
  })

  // "handled": let interceptConnection()'s process.nextTick run first.
  // "disposed": tear down in the same tick, before that nextTick runs.
  if (!disposeBeforeTick) await new Promise((resolve) => setImmediate(resolve))
  server.close()

  const result = await outcome
  return { result, escaped: escaped.length - before }
}

const handled = await scenario(false)
const disposed = await scenario(true)

console.log('dispose AFTER the connection is handled: ', JSON.stringify(handled))
console.log('dispose BEFORE the connection is handled:', JSON.stringify(disposed))
console.log('real connections total:', escaped.length, escaped)

await new Promise((resolve) => realServer.close(resolve))
process.exit(0)

Output:

dispose AFTER the connection is handled:  {"result":"status 200 body \"{\"mocked\":true}\"","escaped":0}
dispose BEFORE the connection is handled: {"result":"status 200 body \"REAL\"","escaped":1}
real connections total: 1 [ 'GET /x' ]

The second case answered from the real server (body "REAL"), not the mock. Swap the loopback port for a non-listening port and it becomes connect ECONNREFUSED; use a name that does not resolve and it becomes getaddrinfo ENOTFOUND.

What happens

The interceptor defers the connection decision by one tick (src/interceptors/net/index.ts, v0.45.9, lines 162–182):

const interceptConnection = (socket, controller, connectionOptions) => {
  socketControllers.set(socket, controller)

  process.nextTick(async () => {
    if (socket.destroyed) return

    if (interceptor.listenerCount('connection') === 0) {
      controller.passthrough()   // <- opens a real socket
      return
    }
    ...

dispose() removes every listener on the way out (src/interceptor.ts, lines 87–99):

public dispose(owner: object = this): void {
  if (!this.#owners.delete(owner)) return
  if (this.#owners.size > 0) return

  super.dispose()
  this.emitter.removeAllListeners()   // <- listenerCount('connection') becomes 0
  this.readyState = InterceptorReadyState.DISPOSED
  ...

By the time the deferred callback runs, the listener that was present for the whole life of the request is gone, so listenerCount('connection') === 0 can no longer tell "no consumer subscribed" apart from "the interceptor was disposed". The passthrough() it calls (SocketController.passthrough, src/interceptors/net/socket-controller.ts:402; the real socket is built in TcpSocketController.passthrough) dials the original target. MSW's request events never fire for it, because the connection was never claimed.

Expected vs actual

  • Expected: a connection that is still PENDING when the interceptor is disposed should not open a real socket on the interceptor's behalf. Either claim/destroy it, or leave it for the caller to deal with.
  • Actual: it is passed through to the real network, silently, after the interceptor has been torn down.

A PENDING controller at dispose is by definition a connection the interceptor never handled, so opening it for real is the surprising half.

Proposed fix

Interceptor already tracks readyState (public, src/interceptor.ts:26) and sets it to DISPOSED, so the deferred callback can distinguish the two cases cheaply:

process.nextTick(async () => {
  if (socket.destroyed) return

  if (interceptor.readyState === InterceptorReadyState.DISPOSED) {
    socket.destroy()
    return
  }

  if (interceptor.listenerCount('connection') === 0) {
    controller.passthrough()
    return
  }
  ...

Alternatively, have dispose() destroy every controller it is still tracking, so nothing can open after teardown.

Related

  • #858 — "socket hang up" when dispose before response is complete (same teardown family: work in flight when dispose() lands).
  • #862 — the read-first passthrough() in src/interceptors/http/source.ts. Different trigger (a client whose first write is later than one setImmediate), but the same shape of symptom: a request the interceptor was supposed to handle reaches the real network and emits no request event.

I found this while chasing stray ENOTFOUND errors in our own test suite. I used an AI coding assistant to help narrow it down and write up the source walk-through; I ran the repro above myself on the versions listed.

luizfneves404 avatar Oct 22 '26 12:10 luizfneves404

Same root cause as this issue, with a worse outcome than a stray request. If the real connect succeeds for a TLS socket, the pass-through starts a second TLS handshake and Node aborts the whole process.

Repro ([email protected] / @mswjs/[email protected], node repro.mjs):

import net from 'node:net'
import https from 'node:https'
import { http, HttpResponse } from 'msw'
import { setupServer } from 'msw/node'

const tcp = net.createServer().listen(0)   // anything that accepts a TCP connection
await new Promise((r) => tcp.once('listening', r))
const url = `https://127.0.0.1:${tcp.address().port}/`

const server = setupServer(http.get(url, () => HttpResponse.text('mocked')))
server.listen()
https.get(url, (res) => console.log('mocked response:', res.statusCode)).on('error', () => {})
server.close()                             // same tick as the request
setTimeout(() => process.exit(0), 500)

Result:

node[…]: static void node::crypto::TLSWrap::Start(...) at ../src/crypto/crypto_tls.cc:644
Assertion failed: !wrap->flags_.started
exit code 134 (SIGABRT)

Changing server.close() to await new Promise((r) => setImmediate(r)); server.close() prints mocked response: 200 and exits 0. So it's the dispose timing alone. fetch() (undici) aborts the same way.

Why: after dispose() removes the "connection" listener, interceptConnection's deferred listenerCount('connection') === 0 check calls controller.passthrough(). The real connect succeeds, #onRealSocketConnect (net-….js:736 in the built output) emits "connect", and TLSSocket._start runs TLSWrap::Start a second time on the same socket. Node's assertion kills the process, not just the request.

Where we hit it: a Vitest suite on CI (Node 24.22.1) where server.close() in afterAll ran with a few fetch calls still in flight. Every test passed, but the worker aborted and the run failed. It never fails on a laptop that can't reach the host (the connect fails instead). The repro above also aborts on Node 26.13.

The readyState === DISPOSED check proposed in the issue would avoid both. Our workaround is to wait for in-flight requests before server.close().

jburnhams avatar Nov 04 '26 11:11 jburnhams

Patch here https://github.com/jburnhams/interceptors/tree/fix/880-pending-connection-dispose

jburnhams avatar Nov 04 '26 11:11 jburnhams

Released: v0.45.13 🎉

This has been released in v0.45.13.

Get these changes by running the following command:

npm i @mswjs/interceptors@latest

Predictable release automation by Release.

kettanaito avatar Nov 26 '26 04:11 kettanaito