-
-
Notifications
You must be signed in to change notification settings - Fork 734
/
intercepted_request_router.js
303 lines (256 loc) · 8.76 KB
/
intercepted_request_router.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
'use strict'
const debug = require('debug')('nock.request_overrider')
const {
IncomingMessage,
ClientRequest,
request: originalHttpRequest,
} = require('http')
const { request: originalHttpsRequest } = require('https')
const propagate = require('propagate')
const common = require('./common')
const globalEmitter = require('./global_emitter')
const Socket = require('./socket')
const { playbackInterceptor } = require('./playback_interceptor')
/**
* Given a group of interceptors, appropriately route an outgoing request.
* Identify which interceptor ought to respond, if any, then delegate to
* `playbackInterceptor()` to consume the request itself.
*/
class InterceptedRequestRouter {
constructor({ req, options, interceptors }) {
this.req = req
this.options = {
// We may be changing the options object and we don't want those changes
// affecting the user so we use a clone of the object.
...options,
// We use lower-case header field names throughout Nock.
headers: common.headersFieldNamesToLowerCase(options.headers || {}),
}
this.interceptors = interceptors
this.socket = new Socket(options)
this.response = new IncomingMessage(this.socket)
this.playbackStarted = false
this.requestBodyBuffers = []
this.attachToReq()
}
attachToReq() {
const { req, response, socket, options } = this
response.req = req
for (const [name, val] of Object.entries(options.headers)) {
req.setHeader(name.toLowerCase(), val)
}
if (options.auth && !options.headers.authorization) {
req.setHeader(
// We use lower-case header field names throughout Nock.
'authorization',
`Basic ${Buffer.from(options.auth).toString('base64')}`
)
}
req.path = options.path
req.method = options.method
// ClientRequest.connection is an alias for ClientRequest.socket
// https://nodejs.org/api/http.html#http_request_socket
// https://github.com/nodejs/node/blob/b0f75818f39ed4e6bd80eb7c4010c1daf5823ef7/lib/_http_client.js#L640-L641
// The same Socket is shared between the request and response to mimic native behavior.
req.socket = req.connection = socket
propagate(['error', 'timeout'], req.socket, req)
req.write = (...args) => this.handleWrite(...args)
req.end = (...args) => this.handleEnd(...args)
req.flushHeaders = (...args) => this.handleFlushHeaders(...args)
req.abort = (...args) => this.handleAbort(...args)
// https://github.com/nock/nock/issues/256
if (options.headers.expect === '100-continue') {
common.setImmediate(() => {
debug('continue')
req.emit('continue')
})
}
// Emit a fake socket event on the next tick to mimic what would happen on a real request.
// Some clients listen for a 'socket' event to be emitted before calling end(),
// which causes nock to hang.
process.nextTick(() => {
req.emit('socket', socket)
// https://nodejs.org/api/net.html#net_event_connect
socket.emit('connect')
// https://nodejs.org/api/tls.html#tls_event_secureconnect
if (socket.authorized) {
socket.emit('secureConnect')
}
})
}
emitError(error) {
const { req } = this
process.nextTick(() => {
req.emit('error', error)
})
}
handleWrite(buffer, encoding, callback) {
debug('write', arguments)
const { req } = this
if (!req.aborted) {
if (buffer) {
if (!Buffer.isBuffer(buffer)) {
buffer = Buffer.from(buffer, encoding)
}
this.requestBodyBuffers.push(buffer)
}
if (callback instanceof Function) {
callback()
}
} else {
this.emitError(new Error('Request aborted'))
}
common.setImmediate(function() {
req.emit('drain')
})
return false
}
handleEnd(chunk, encoding, callback) {
debug('req.end')
const { req } = this
if (chunk instanceof Function) {
callback = chunk
chunk = null
} else if (encoding instanceof Function) {
callback = encoding
encoding = null
}
if (!req.aborted && !this.playbackStarted) {
req.write(chunk, encoding, () => {
if (callback instanceof Function) {
callback()
}
this.startPlayback()
req.emit('finish')
req.emit('end')
})
}
if (req.aborted) {
this.emitError(new Error('Request aborted'))
}
}
handleFlushHeaders() {
debug('req.flushHeaders')
const { req } = this
if (!req.aborted && !this.playbackStarted) {
this.startPlayback()
}
if (req.aborted) {
this.emitError(new Error('Request aborted'))
}
}
handleAbort() {
debug('req.abort')
const { req, response, socket } = this
if (req.aborted) {
return
}
req.aborted = Date.now()
if (!this.playbackStarted) {
this.startPlayback()
}
const err = new Error()
err.code = 'aborted'
response.emit('close', err)
socket.destroy()
req.emit('abort')
const connResetError = new Error('socket hang up')
connResetError.code = 'ECONNRESET'
this.emitError(connResetError)
}
/**
* Set request headers of the given request. This is needed both during the
* routing phase, in case header filters were specified, and during the
* interceptor-playback phase, to correctly pass mocked request headers.
* TODO There are some problems with this; see https://github.com/nock/nock/issues/1718
*/
setHostHeaderUsingInterceptor(interceptor) {
const { req, options } = this
// If a filtered scope is being used we have to use scope's host in the
// header, otherwise 'host' header won't match.
// NOTE: We use lower-case header field names throughout Nock.
const HOST_HEADER = 'host'
if (interceptor.__nock_filteredScope && interceptor.__nock_scopeHost) {
options.headers[HOST_HEADER] = interceptor.__nock_scopeHost
req.setHeader(HOST_HEADER, interceptor.__nock_scopeHost)
} else {
// For all other cases, we always add host header equal to the requested
// host unless it was already defined.
if (options.host && !req.getHeader(HOST_HEADER)) {
let hostHeader = options.host
if (options.port === 80 || options.port === 443) {
hostHeader = hostHeader.split(':')[0]
}
req.setHeader(HOST_HEADER, hostHeader)
}
}
}
startPlayback() {
debug('ending')
this.playbackStarted = true
const { req, response, socket, options, interceptors } = this
Object.assign(options, {
// Re-update `options` with the current value of `req.path` because badly
// behaving agents like superagent like to change `req.path` mid-flight.
path: req.path,
// Similarly, node-http-proxy will modify headers in flight, so we have
// to put the headers back into options.
// https://github.com/nock/nock/pull/1484
headers: req.getHeaders(),
// Fixes https://github.com/nock/nock/issues/976
protocol: `${options.proto}:`,
})
interceptors.forEach(interceptor => {
this.setHostHeaderUsingInterceptor(interceptor)
})
const requestBodyBuffer = Buffer.concat(this.requestBodyBuffers)
// When request body is a binary buffer we internally use in its hexadecimal
// representation.
const requestBodyIsUtf8Representable = common.isUtf8Representable(
requestBodyBuffer
)
const requestBodyString = requestBodyBuffer.toString(
requestBodyIsUtf8Representable ? 'utf8' : 'hex'
)
const matchedInterceptor = interceptors.find(i =>
i.match(req, options, requestBodyString)
)
if (matchedInterceptor) {
debug('interceptor identified, starting mocking')
playbackInterceptor({
req,
socket,
options,
requestBodyString,
requestBodyIsUtf8Representable,
response,
interceptor: matchedInterceptor,
})
} else {
globalEmitter.emit('no match', req, options, requestBodyString)
// Try to find a hostname match that allows unmocked.
const allowUnmocked = interceptors.some(
i => i.matchHostName(options) && i.options.allowUnmocked
)
if (allowUnmocked && req instanceof ClientRequest) {
const newReq =
options.proto === 'https'
? originalHttpsRequest(options)
: originalHttpRequest(options)
propagate(newReq, req)
// We send the raw buffer as we received it, not as we interpreted it.
newReq.end(requestBodyBuffer)
} else {
const err = new Error(
`Nock: No match for request ${common.stringifyRequest(
options,
requestBodyString
)}`
)
err.statusCode = err.status = 404
this.emitError(err)
}
}
}
}
module.exports = { InterceptedRequestRouter }