-
Notifications
You must be signed in to change notification settings - Fork 214
Expand file tree
/
Copy pathconfigure-proxy.js
More file actions
389 lines (358 loc) · 14 KB
/
configure-proxy.js
File metadata and controls
389 lines (358 loc) · 14 KB
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
/*
* Copyright (c) 2022, Salesforce, Inc.
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import {createProxyMiddleware} from 'http-proxy-middleware'
import cookie from 'cookie'
import {rewriteProxyRequestHeaders, rewriteProxyResponseHeaders} from '../ssr-proxying'
import {proxyConfigs} from '../ssr-shared'
import {processExpressResponse} from './process-express-response'
import {isRemote, localDevLog, verboseProxyLogging, isScapiDomain} from './utils'
import logger from '../logger-instance'
import {getEnvBasePath} from '../ssr-namespace-paths'
export const ALLOWED_CACHING_PROXY_REQUEST_METHODS = ['HEAD', 'GET', 'OPTIONS']
/**
* This path matching RE matches on /mobify/proxy and then skips one path
* element. For example, /mobify/proxy/heffalump/woozle would be converted to
* /woozle on whatever host /mobify/proxy/heffalump maps to.
* Group 2 is the full path on the proxied host.
* @private
* @type {RegExp}
*/
const generalProxyPathRE = /^\/mobify\/proxy\/([^/]+)(\/.*)$/
/**
* Apply the Authorization header with the shopper's access token (Bearer token) to a proxy request.
*
* This function is intended to be called from within a proxy's onProxyReq method.
* It reads the access token from HttpOnly cookies and sets it as the Authorization header
* for applicable SCAPI endpoints.
*
* Logic for determining if Bearer token should be applied:
* 1. Caching proxies never use auth (skip)
* 2. x-site-id header must be present (skip if not)
* 3. Target must be SCAPI domain (skip if not)
*
* @private
* @function
* @param proxyRequest {http.ClientRequest} the request that will be sent to the target host
* @param incomingRequest {http.IncomingMessage} the request made to this Express app
* @param caching {Boolean} true for a caching proxy, false for a standard proxy
* @param targetHost {String} the target hostname (host+port)
*/
export const setScapiAuthRequestHeaders = ({
proxyRequest,
incomingRequest,
caching,
targetHost
}) => {
const url = incomingRequest.url
const resolvedSiteId = incomingRequest.headers?.['x-site-id']
// Skip if: caching proxy, not SCAPI domain, or no URL
if (caching || !isScapiDomain(targetHost) || !url) {
return
}
if (!resolvedSiteId) {
logger.warn(
'x-site-id header is missing on SCAPI proxy request. Bearer token injection skipped.',
{namespace: 'configureProxy.setScapiAuthRequestHeaders'}
)
return
}
// Get access token from HttpOnly cookie
const cookieHeader = incomingRequest.headers.cookie
if (!cookieHeader) return
const cookies = cookie.parse(cookieHeader)
const tokenKey = `cc-at_${resolvedSiteId}`
const accessToken = cookies[tokenKey]
if (accessToken) {
// Always override - cookie-based auth takes precedence
proxyRequest.setHeader('authorization', `Bearer ${accessToken}`)
}
}
/**
* Apply proxy headers to a request that is being proxied.
*
* This function is intended to be called from within a proxy's
* onProxyReq method.
*
* For more details on the headers being applied,
* see ssr-proxying.js rewriteProxyRequestHeaders method
* @private
* @function
* @param proxyRequest {http.ClientRequest} the request that will be
* sent to the target host
* @param incomingRequest {http.IncomingMessage} the request made to
* this Express app that prompted the proxying
* @param caching {Boolean} true for a caching proxy, false for a standard proxy
* @param logging {Boolean} true to log operations
* @param proxyPath {String} the path being proxied (e.g. /mobify/proxy/base/
* or /mobify/caching/base/)
* @param targetHost {String} the target hostname (host+port)
* @param targetProtocol {String} the protocol to use to make requests to
* the target ('http' or 'https')
*/
export const applyProxyRequestHeaders = ({
proxyRequest,
incomingRequest,
caching = false,
logging = !isRemote() && verboseProxyLogging,
proxyPath,
targetHost,
targetProtocol
}) => {
const url = incomingRequest.url
const headers = incomingRequest.headers
/* istanbul ignore next */
if (logging) {
logger.info(
`Proxy: request for ${proxyPath}${url} => ${targetProtocol}://${targetHost}/${url}`,
{
namespace: 'configureProxy.applyProxyRequestHeaders',
additionalProperties: {
proxyPath,
targetProtocol,
targetHost,
url
}
}
)
}
const newHeaders = rewriteProxyRequestHeaders({
caching,
headers,
headerFormat: 'http',
logging,
proxyPath,
targetHost,
targetProtocol
})
// Copy any new and updated headers to the proxyRequest
// using setHeader.
Object.entries(newHeaders).forEach(
// setHeader always replaces any current value.
([key, value]) => proxyRequest.setHeader(key, value)
)
// Handle deletion of headers.
// Iterate over the keys of incomingRequest.headers - for every
// key, if the value is not present in newHeaders, we remove
// that value from proxyRequest's headers.
Object.keys(headers).forEach((key) => {
// We delete the header on any falsy value, since
// there's no use case where we supply an empty header
// value.
if (!newHeaders[key]) {
proxyRequest.removeHeader(key)
}
})
}
/**
* Configure proxying for a path.
* @private
* @function
* @param appHostname {String} the hostname (host+port) under which the
* Express app is running (e.g. localhost:3443 for a local dev server)
* @param proxyPath {String} the path being proxied (e.g. /mobify/proxy/base/
* or /mobify/caching/base/)
* @param targetProtocol {String} the protocol to use to make requests to
* the target ('http' or 'https')
* @param targetHost {String} the target hostname (host+port)
* @param appProtocol {String} the protocol to use to make requests to
* the origin ('http' or 'https', defaults to 'https')
* @param caching {Boolean} true for a caching proxy, false for a
* standard proxy.
* @returns {middleware} function to pass to expressApp.use()
*/
export const configureProxy = ({
appHostname,
proxyPath,
targetProtocol,
targetHost,
appProtocol = /* istanbul ignore next */ 'https',
caching
}) => {
// This configuration must match the behaviour of the proxying
// in CloudFront.
const targetOrigin = `${targetProtocol}://${targetHost}`
const config = {
// The name of the changeOrigin option is misleading - it configures
// the proxying code in http-proxy to rewrite the Host header (not
// any Origin header) of the outgoing request. The Host header is
// also fixed up in rewriteProxyRequestHeaders, but that
// doesn't work correctly with http-proxy, because the https
// connection to the target is made *before* the request headers
// are modified by the onProxyReq event handler. So we set this
// flag true to get correct behaviour.
changeOrigin: true,
// Rewrite the domain in set-cookie headers in responses, if it
// matches the targetHost.
cookieDomainRewrite: {
targetHost: appHostname
},
// We don't do cookie *path* rewriting - it's complex.
cookiePathRewrite: false,
// Neither CloudFront nor the local Express app will follow redirect
// responses to proxy requests. The responses are returned to the
// client.
followRedirects: false,
logLevel: 'warn',
onError: (err, req, res) => {
/* istanbul ignore next */
if (!isRemote() && verboseProxyLogging) {
logger.error(`Proxy: error ${err} for request ${proxyPath}/${req.url}`, {
namespace: 'configureProxy.onError',
additionalProperties: {
proxyPath,
url: req.url,
error: err
}
})
}
res.writeHead(500, {
'Content-Type': 'text/plain'
})
res.end(`Error in proxy request to ${req.url}: ${err}`)
},
/**
* Handler for all outgoing proxied requests. This is called
* irrespective of the source of the request (i.e., it could
* be from fetch, XmlHttpRequest or an external request to
* a /mobify/proxy path).
*
* Note also that this is called *after* a request is intercepted
* in outgoingRequestHook.
*
* @private
* @param proxyRequest {http.ClientRequest} the request that will be
* sent to the target host
* @param incomingRequest {http.IncomingMessage} the request made to
* this Express app that prompted the proxying
*/
onProxyReq: (proxyRequest, incomingRequest) => {
// First, apply standard proxy headers (Host, Origin, etc.)
applyProxyRequestHeaders({
proxyRequest,
incomingRequest,
caching,
proxyPath,
targetHost,
targetProtocol
})
// Apply Authorization header with shopper's access token from HttpOnly cookie
if (process.env.MRT_ENABLE_HTTPONLY_SESSION_COOKIES === 'true') {
setScapiAuthRequestHeaders({
proxyRequest,
incomingRequest,
caching,
targetHost
})
}
},
onProxyRes: (proxyResponse, req) => {
/* istanbul ignore next */
if (!isRemote() && verboseProxyLogging) {
logger.info(
`Proxy: ${proxyResponse.statusCode} response from ${proxyPath}${req.url}`,
{
namespace: 'configureProxy.onProxyRes',
additionalProperties: {
statusCode: proxyResponse.statusCode,
proxyPath,
url: req.url
}
}
)
}
// In this function, req.originalUrl is the path
// part of the original incoming request URL, containing
// the /mobify/proxy/.../ part. We need to strip that off
// before passing it to rewriteProxyResponseHeaders. If we
// match, group 2 is the full path on the target host, including
// query parameters.
const matchedUrl = generalProxyPathRE.exec(req.originalUrl)
// Rewrite key headers
proxyResponse.headers = rewriteProxyResponseHeaders({
appHostname,
caching,
targetHost,
targetProtocol,
appProtocol,
proxyPath,
statusCode: proxyResponse.statusCode,
headers: proxyResponse.headers,
headerFormat: 'http',
logging: !isRemote() && verboseProxyLogging,
requestUrl: matchedUrl && matchedUrl[2]
})
// Also handle binary responses
if (isRemote()) {
processExpressResponse(proxyResponse)
}
},
// Rewrite the request's path to remove the /mobify/proxy/... prefix.
// This cannot be modified by any express middleware
// So we need to use the built in pathRewrite to remove the base path if present
pathRewrite: (path) => {
const basePathRegexEntry = getEnvBasePath() ? `${getEnvBasePath()}?` : ''
const regex = new RegExp(`^${basePathRegexEntry}${proxyPath}`)
return path.replace(regex, '')
},
// The origin (protocol + host) to which we proxy
target: targetOrigin
}
const proxyFunc = createProxyMiddleware(config)
// For a standard proxy, we're done
if (!caching) {
return proxyFunc
}
// For caching proxies, we need to validate the request method. We can't
// do that in the onProxyReq handler, because there's no way to send
// an HTTP error response from that function. Instead, we do it here,
// in a wrapper around the actual proxying function.
return (req, res, next) => {
// This function will only be called for requests for the
// current proxy config.
if (!ALLOWED_CACHING_PROXY_REQUEST_METHODS.includes(req.method)) {
return res
.status(405)
.send(`Method ${req.method} not supported for caching proxy`)
.end()
}
return proxyFunc(req, res, next)
}
}
/**
* Called by the Express app after updatePackageMobify has modified the
* proxyConfigs list, to create the actual proxying objects.
* @param {String} appHostname - the application hostname (the hostname
* to which requests are sent to the Express app)
* @param {String} appProtocol {String} the protocol to use to make requests to
* the origin ('http' or 'https', defaults to 'https')
* @private
*/
export const configureProxyConfigs = (appHostname, appProtocol) => {
localDevLog('')
proxyConfigs.forEach((config) => {
localDevLog(
`Proxying ${config.proxyPath} and ${config.cachingPath} to ${config.protocol}://${config.host}`
)
config.proxy = configureProxy({
proxyPath: config.proxyPath,
targetProtocol: config.protocol,
targetHost: config.host,
appProtocol,
appHostname,
caching: false
})
config.cachingProxy = configureProxy({
proxyPath: config.cachingPath,
targetProtocol: config.protocol,
targetHost: config.host,
appProtocol,
appHostname,
caching: true
})
})
localDevLog('')
}