moll / node-mitm

Intercept and mock outgoing Node.js network TCP connections and HTTP requests for testing. Intercepts and gives you a Net.Socket, Http.IncomingMessage and Http.ServerResponse to test and respond with. Super useful when testing code that hits remote servers.
Other
641 stars 48 forks source link

Bypass on Request Basis #16

Closed arb closed 9 years ago

arb commented 9 years ago

Is there a way to examine the request path and determine if you want it intercepted or not? I see you can do it on the "connection" event, but not at the request event level.

papandreou commented 9 years ago

Would be a nice feature, but it's not currently supported.

As a workaround you can do the actual http request in the request listener. It's a bit involved, but I did that in the recording mode of unexpected-mitm: https://github.com/unexpectedjs/unexpected-mitm/blob/master/lib/unexpectedMitm.js#L386-L408

... Remember not to intercept the next connection event :)

moll commented 9 years ago

Hey,

Indeed that's not supported and probably won't be either (at least not in the core lib) as there's no way to know the path before HTTP sets up its TCP connection. Mitm.js intercepts the whole TCP connection.

In practice however, some request libraries do "leak" their options object to the underlying TCP connection setup calls. See if yours does it too by printing out the opts argument of the connectevent:

mitm.on("connect", function(socket, opts) { console.log(opts) })

If it does, you can call socket.bypass() after some conditionals there.

PS. Thanks, @papandreou, for a quick reply to @arb. PS2. I'll close this issue as there's not much to do now, but we can continue the chat.