-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
Copy pathintercept-request.ts
291 lines (222 loc) · 7.95 KB
/
intercept-request.ts
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
import _ from 'lodash'
import concatStream from 'concat-stream'
import Debug from 'debug'
import minimatch from 'minimatch'
import url from 'url'
import {
CypressIncomingRequest,
RequestMiddleware,
} from '@packages/proxy'
import {
BackendRoute,
BackendRequest,
NetStubbingState,
} from './types'
import {
RouteMatcherOptions,
CyHttpMessages,
NetEventFrames,
SERIALIZABLE_REQ_PROPS,
} from '../types'
import { getAllStringMatcherFields, sendStaticResponse, emit, setResponseFromFixture } from './util'
import CyServer from '@packages/server'
const debug = Debug('cypress:net-stubbing:server:intercept-request')
/**
* Returns `true` if `req` matches all supplied properties on `routeMatcher`, `false` otherwise.
*/
export function _doesRouteMatch (routeMatcher: RouteMatcherOptions, req: CypressIncomingRequest) {
const matchable = _getMatchableForRequest(req)
// get a list of all the fields which exist where a rule needs to be succeed
const stringMatcherFields = getAllStringMatcherFields(routeMatcher)
const booleanFields = _.filter(_.keys(routeMatcher), _.partial(_.includes, ['https', 'webSocket']))
const numberFields = _.filter(_.keys(routeMatcher), _.partial(_.includes, ['port']))
for (let i = 0; i < stringMatcherFields.length; i++) {
const field = stringMatcherFields[i]
const matcher = _.get(routeMatcher, field)
let value = _.get(matchable, field, '')
if (typeof value !== 'string') {
value = String(value)
}
if (matcher.test) {
if (!matcher.test(value)) {
return false
}
continue
}
if (field === 'url') {
if (value.includes(matcher)) {
continue
}
}
if (!minimatch(value, matcher, { matchBase: true })) {
return false
}
}
for (let i = 0; i < booleanFields.length; i++) {
const field = booleanFields[i]
const matcher = _.get(routeMatcher, field)
const value = _.get(matchable, field)
if (matcher !== value) {
return false
}
}
for (let i = 0; i < numberFields.length; i++) {
const field = numberFields[i]
const matcher = _.get(routeMatcher, field)
const value = _.get(matchable, field)
if (matcher.length) {
if (!matcher.includes(value)) {
return false
}
continue
}
if (matcher !== value) {
return false
}
}
return true
}
export function _getMatchableForRequest (req: CypressIncomingRequest) {
let matchable: any = _.pick(req, ['headers', 'method', 'webSocket'])
const authorization = req.headers['authorization']
if (authorization) {
const [mechanism, credentials] = authorization.split(' ', 2)
if (mechanism && credentials && mechanism.toLowerCase() === 'basic') {
const [username, password] = Buffer.from(credentials, 'base64').toString().split(':', 2)
matchable.auth = { username, password }
}
}
const proxiedUrl = url.parse(req.proxiedUrl, true)
_.assign(matchable, _.pick(proxiedUrl, ['hostname', 'path', 'pathname', 'port', 'query']))
matchable.url = req.proxiedUrl
matchable.https = proxiedUrl.protocol && (proxiedUrl.protocol.indexOf('https') === 0)
if (!matchable.port) {
matchable.port = matchable.https ? 443 : 80
}
return matchable
}
function _getRouteForRequest (routes: BackendRoute[], req: CypressIncomingRequest, prevRoute?: BackendRoute) {
const possibleRoutes = prevRoute ? routes.slice(_.findIndex(routes, prevRoute) + 1) : routes
return _.find(possibleRoutes, (route) => {
return _doesRouteMatch(route.routeMatcher, req)
})
}
/**
* Called when a new request is received in the proxy layer.
* @param project
* @param req
* @param res
* @param cb Can be called to resume the proxy's normal behavior. If `res` is not handled and this is not called, the request will hang.
*/
export const InterceptRequest: RequestMiddleware = function () {
const route = _getRouteForRequest(this.netStubbingState.routes, this.req)
if (!route) {
// not intercepted, carry on normally...
return this.next()
}
const requestId = _.uniqueId('interceptedRequest')
debug('intercepting request %o', { requestId, route, req: _.pick(this.req, 'url') })
const request: BackendRequest = {
requestId,
route,
continueRequest: this.next,
onResponse: this.onResponse,
req: this.req,
res: this.res,
}
// attach requestId to the original req object for later use
this.req.requestId = requestId
this.netStubbingState.requests[requestId] = request
_interceptRequest(this.netStubbingState, request, route, this.socket)
}
function _interceptRequest (state: NetStubbingState, request: BackendRequest, route: BackendRoute, socket: CyServer.Socket) {
const notificationOnly = !route.hasInterceptor
const frame: NetEventFrames.HttpRequestReceived = {
routeHandlerId: route.handlerId!,
requestId: request.req.requestId,
req: _.extend(_.pick(request.req, SERIALIZABLE_REQ_PROPS), {
url: request.req.proxiedUrl,
}) as CyHttpMessages.IncomingRequest,
notificationOnly,
}
request.res.once('finish', () => {
emit(socket, 'http:request:complete', {
requestId: request.requestId,
routeHandlerId: route.handlerId!,
})
debug('request/response finished, cleaning up %o', { requestId: request.requestId })
delete state.requests[request.requestId]
})
const emitReceived = () => {
emit(socket, 'http:request:received', frame)
}
const ensureBody = (cb: () => void) => {
if (frame.req.body) {
return cb()
}
request.req.pipe(concatStream((reqBody) => {
request.req.body = frame.req.body = reqBody.toString()
cb()
}))
}
if (route.staticResponse) {
const { staticResponse } = route
return ensureBody(() => {
emitReceived()
sendStaticResponse(request.res, staticResponse, request.onResponse!)
})
}
if (notificationOnly) {
return ensureBody(() => {
emitReceived()
const nextRoute = getNextRoute(state, request.req, frame.routeHandlerId)
if (!nextRoute) {
return request.continueRequest()
}
_interceptRequest(state, request, nextRoute, socket)
})
}
ensureBody(emitReceived)
}
/**
* If applicable, return the route that is next in line after `prevRouteHandlerId` to handle `req`.
*/
function getNextRoute (state: NetStubbingState, req: CypressIncomingRequest, prevRouteHandlerId: string): BackendRoute | undefined {
const prevRoute = _.find(state.routes, { handlerId: prevRouteHandlerId })
if (!prevRoute) {
return
}
return _getRouteForRequest(state.routes, req, prevRoute)
}
export async function onRequestContinue (state: NetStubbingState, frame: NetEventFrames.HttpRequestContinue, socket: CyServer.Socket) {
const backendRequest = state.requests[frame.requestId]
if (!backendRequest) {
debug('onRequestContinue received but no backendRequest exists %o', { frame })
return
}
frame.req.url = url.resolve(backendRequest.req.proxiedUrl, frame.req.url)
// modify the original paused request object using what the client returned
_.assign(backendRequest.req, _.pick(frame.req, SERIALIZABLE_REQ_PROPS))
// proxiedUrl is used to initialize the new request
backendRequest.req.proxiedUrl = frame.req.url
// update problematic headers
// update content-length if available
if (backendRequest.req.headers['content-length'] && frame.req.body) {
backendRequest.req.headers['content-length'] = frame.req.body.length
}
if (frame.hasResponseHandler) {
backendRequest.waitForResponseContinue = true
}
if (frame.tryNextRoute) {
const nextRoute = getNextRoute(state, backendRequest.req, frame.routeHandlerId)
if (!nextRoute) {
return backendRequest.continueRequest()
}
return _interceptRequest(state, backendRequest, nextRoute, socket)
}
if (frame.staticResponse) {
await setResponseFromFixture(backendRequest.route.getFixture, frame.staticResponse)
return sendStaticResponse(backendRequest.res, frame.staticResponse, backendRequest.onResponse!)
}
backendRequest.continueRequest()
}