-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathindex.js
More file actions
658 lines (577 loc) · 16.5 KB
/
index.js
File metadata and controls
658 lines (577 loc) · 16.5 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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
// @ts-check
'use strict'
const http = require('http')
const https = require('https')
const util = require('util')
const url = require('url')
const assert = require('assert')
const URL = require('url').URL
const ChildProcessWorker = require('./child-process-worker')
/**
@typedef {{
resource: string;
path: string;
httpMethod: string;
headers: Record<string, string>;
multiValueHeaders: Record<string, string[]>;
queryStringParameters: Record<string, string>;
multiValueQueryStringParameters: Record<string, string[]>;
pathParameters: Record<string, string>;
stageVariables: Record<string, string>;
requestContext: object;
body: string;
isBase64Encoded: boolean;
}} LambdaEvent
@typedef {{
(eventObject: LambdaEvent): Promise<object> | object;
}} PopulateRequestContextFn
@typedef {{
port?: number;
httpsPort?: number;
httpsKey?: string;
httpsCert?: string;
enableCors?: boolean;
silent?: boolean;
populateRequestContext?: PopulateRequestContextFn;
tmp?: string;
}} Options
@typedef {{
isBase64Encoded: boolean;
statusCode: number;
headers: Record<string, string>;
multiValueHeaders?: Record<string, string[]>;
body: string;
}} LambdaResult
@typedef {{
path: string,
functionName: string,
worker: ChildProcessWorker
}} FunctionInfo
*/
class FakeApiGatewayLambda {
/**
* @param {Options} options
*/
constructor (options) {
/** @type {http.Server | null} */
this.httpServer = http.createServer()
this._tmp = options.tmp
/** @type {https.Server | null} */
this.httpsServer = null
if (options.httpsKey && options.httpsCert && options.httpsPort) {
this.httpsServer = https.createServer({
key: options.httpsKey,
cert: options.httpsCert
})
}
/** @type {number | null} */
this.httpsPort = options.httpsPort || null
/** @type {number} */
this.port = options.port || 0
/** @type {Record<string, FunctionInfo>} */
this.functions = {}
/** @type {boolean} */
this.enableCors = options.enableCors || false
/** @type {boolean} */
this.silent = options.silent || false
/** @type {string | null} */
this.hostPort = null
/**
* @type {Map<string, {
* req: http.IncomingMessage,
* res: http.ServerResponse,
* id: string
* }>}
*/
this.pendingRequests = new Map()
/** @type {string} */
this.gatewayId = cuuid()
/** @type {PopulateRequestContextFn | null} */
this.populateRequestContext = options.populateRequestContext || null
}
async bootstrap () {
if (!this.httpServer) {
throw new Error('cannot bootstrap closed server')
}
this.httpServer.on('request', (
/** @type {http.IncomingMessage} */ req,
/** @type {http.ServerResponse} */ res
) => {
this._handleServerRequest(req, res)
})
if (this.httpsServer) {
this.httpsServer.on('request', (
/** @type {http.IncomingMessage} */ req,
/** @type {http.ServerResponse} */ res
) => {
this._handleServerRequest(req, res)
})
const httpsServer = this.httpsServer
await util.promisify((cb) => {
httpsServer.listen(this.httpsPort, '127.0.0.1', () => {
cb(null, null)
})
})()
}
const server = this.httpServer
try {
await util.promisify((cb) => {
server.on('listening', () => {
cb(null, null)
})
server.on('error', (err) => {
cb(err)
})
server.listen(this.port, '127.0.0.1')
})()
} catch (err) {
return { err }
}
const addr = this.httpServer.address()
if (!addr || typeof addr === 'string') {
throw new Error('invalid http server address')
}
this.hostPort = `127.0.0.1:${addr.port}`
return { data: this.hostPort }
}
/**
* @param {number} newPort
*/
async changePort (newPort) {
this.port = newPort
if (this.httpServer) {
this.httpServer.close()
this.httpServer = null
this.httpServer = http.createServer()
}
if (this.httpsServer) {
this.httpsServer.close()
this.httpsServer = null
}
return await this.bootstrap()
}
hasWorker (httpPath) {
return Object.values(this.functions).some((f) => {
return f.path === httpPath
})
}
getWorker (httpPath) {
return Object.values(this.functions).find((f) => {
return f.path === httpPath
})
}
/**
* @param {{
* stdout?: object,
* stderr?: object,
* handler?: string,
* env?: Record<string, string>,
* entry: string,
* functionName: string,
* runtime?: string
* httpPath: string
* }} info
* @returns {FunctionInfo}
*/
updateWorker (info) {
assert(info.functionName, 'functionName required')
assert(info.handler, 'info.handler required')
assert(info.runtime, 'info.runtime required')
assert(info.entry, 'info.entry required')
const opts = {
env: info.env,
runtime: info.runtime,
stdout: info.stdout,
stderr: info.stderr,
tmp: this._tmp,
handler: info.handler,
entry: info.entry
}
/** @type {FunctionInfo} */
const fun = {
worker: new ChildProcessWorker(opts),
functionName: info.functionName,
path: info.httpPath
}
this.functions[info.functionName] = fun
return fun
}
/**
* @returns {Promise<void>}
*/
async close () {
if (this.httpServer) {
await util.promisify((cb) => {
this.httpServer.close(() => {
cb(null, null)
})
})()
this.httpServer = null
}
if (this.httpsServer) {
await util.promisify((cb) => {
this.httpsServer.close(() => {
cb(null, null)
})
})()
this.httpsServer = null
}
await Promise.all(Object.values(this.functions).map(f => {
return f.worker.close()
}))
}
/**
* @param {string} id
* @param {object} eventObject
* @returns {Promise<object>}
*/
async _dispatch (id, eventObject) {
const url = new URL(eventObject.path, 'http://localhost:80')
const functions = Object.values(this.functions)
const matched = matchRoute(functions, url.pathname)
if (matched) {
eventObject.resource = matched.path
return matched.worker.request(id, eventObject)
} else {
return {
isBase64Encoded: false,
statusCode: 404, // the real api-gateway does a 403.
headers: {},
body: JSON.stringify({ message: 'NotFound: The local server does not have this URL path' }),
multiValueHeaders: {}
}
}
// before, the error didn't happen until it got to the worker,
// but now the worker only has one lambda so it's here now.
}
/**
* @param {string} id
* @returns {any}
*/
_hasPendingRequest (id) {
return this.pendingRequests.has(id)
}
/**
* @param {string} id
* @param {LambdaResult} result
* @returns {void}
*/
_handleLambdaResult (id, result) {
const pending = this.pendingRequests.get(id)
if (!pending) {
/**
* @raynos TODO: gracefully handle this edgecase.
*/
throw new Error('response without request: should never happen')
}
this.pendingRequests.delete(id)
const res = pending.res
res.statusCode = result.statusCode
for (const key of Object.keys(result.headers || {})) {
res.setHeader(key, result.headers[key])
}
if (result.multiValueHeaders) {
for (const key of Object.keys(result.multiValueHeaders)) {
res.setHeader(key, result.multiValueHeaders[key])
}
}
res.end(result.body)
}
/**
* @param {http.IncomingMessage} req
* @param {http.ServerResponse} res
* @returns {void}
*/
_handleServerRequest (
req,
res
) {
if (this.enableCors) {
res.setHeader('Access-Control-Allow-Origin',
req.headers.origin || '*'
)
res.setHeader('Access-Control-Allow-Methods',
'POST, GET, PUT, DELETE, OPTIONS, XMODIFY'
)
res.setHeader('Access-Control-Allow-Credentials', 'true')
res.setHeader('Access-Control-Max-Age', '86400')
res.setHeader('Access-Control-Allow-Headers',
'X-Requested-With, X-HTTP-Method-Override, ' +
'Content-Type, Accept, Authorization'
)
}
if (this.enableCors && req.method === 'OPTIONS') {
res.end()
return
}
const reqUrl = req.url || '/'
// eslint-disable-next-line node/no-deprecated-api
const uriObj = url.parse(reqUrl, true)
if (reqUrl.startsWith('/___FAKE_API_GATEWAY_LAMBDA___RAW___')) {
this._dispatchRaw(req, uriObj, res)
return
}
// if a referer header is present,
// check that the request is from a page we hosted
// otherwise, the request could be a locally open web page.
// which could be an attacker.
if (!this.enableCors && req.headers.referer) {
// eslint-disable-next-line node/no-deprecated-api
const referer = url.parse(req.headers.referer)
if (referer.hostname !== 'localhost' && referer.hostname !== '127.0.0.1') {
res.statusCode = 403
return res.end(JSON.stringify({ message: 'expected request from localhost' }, null, 2))
}
// allow other ports. locally running apps are trusted, because the user had to start them.
}
// if the host header is not us, the request *thought* it was going to something else
// this could be a DNS poisoning attack.
const host = req.headers.host && req.headers.host.split(':')[0]
if (host !== 'localhost' && host !== '127.0.0.1') {
// error - dns poisoning attack
res.statusCode = 403
return res.end(JSON.stringify({ message: 'unexpected host header' }, null, 2))
}
let body = ''
req.on('data', (/** @type {Buffer} */ chunk) => {
body += chunk.toString()
})
req.on('end', () => {
const eventObject = {
resource: null,
path: req.url ? req.url : '/',
httpMethod: req.method ? req.method : 'GET',
headers: flattenHeaders(req.rawHeaders),
multiValueHeaders: multiValueHeaders(req.rawHeaders),
queryStringParameters:
singleValueQueryString(uriObj.query),
multiValueQueryStringParameters:
multiValueObject(uriObj.query),
pathParameters: {},
stageVariables: {},
requestContext: {},
body,
isBase64Encoded: false
}
this._dispatchPayload(req, res, eventObject)
})
}
async _dispatchRaw (req, uriObj, res) {
const functionName = uriObj.query.functionName
const func = this.functions[functionName]
if (!func) {
res.statusCode = 404
return res.end(JSON.stringify({
message: `Not Found (${functionName})`
}))
}
// get req body
let body = ''
req.on('data', (/** @type {Buffer} */ chunk) => {
body += chunk.toString()
})
req.once('end', async () => {
const eventObject = JSON.parse(body)
const id = cuuid()
let result
try {
result = await func.worker.request(id, eventObject, true)
} catch (err) {
const str = JSON.stringify({
message: err.message,
stack: err.errorString
? err.errorString.split('\n')
: undefined
}, null, 2)
res.statusCode = 500
res.setHeader('Content-Type', 'application/json')
res.end(str)
return
}
res.statusCode = 200
res.setHeader('Content-Type', 'application/json')
res.end(JSON.stringify(result))
})
}
async _dispatchPayload (req, res, eventObject) {
/**
* @raynos TODO: Need to identify what concrete value
* to use for `event.resource` and for `event.pathParameters`
* since these are based on actual configuration in AWS
* API Gateway. Maybe these should come from the `routes`
* options object itself
*/
if (this.populateRequestContext) {
const reqContext = await this.populateRequestContext(eventObject)
eventObject.requestContext = reqContext
}
const id = cuuid()
this.pendingRequests.set(id, { req, res, id })
let lambdaResult
try {
lambdaResult = await this._dispatch(id, eventObject)
const isValid = checkResult(lambdaResult)
if (!isValid) {
throw new Error('Lambda returned invalid HTTP result')
}
} catch (err) {
this._handleLambdaResult(id, {
statusCode: 500,
isBase64Encoded: false,
headers: {},
body: JSON.stringify({
message: err.message,
stack: err.errorString
? err.errorString.split('\n')
: undefined
}, null, 2)
})
return
}
this._handleLambdaResult(id, lambdaResult)
}
}
exports.FakeApiGatewayLambda = FakeApiGatewayLambda
/**
* @param {Record<string, string | string[]>} qs
* @returns {Record<string, string>}
*/
function singleValueQueryString (qs) {
/** @type {Record<string, string>} */
const out = {}
for (const key of Object.keys(qs)) {
const v = qs[key]
out[key] = typeof v === 'string' ? v : v[v.length - 1]
}
return out
}
/**
* @param {Record<string, string | string[] | undefined>} h
* @returns {Record<string, string[]>}
*/
function multiValueObject (h) {
/** @type {Record<string, string[]>} */
const out = {}
for (const key of Object.keys(h)) {
const v = h[key]
if (typeof v === 'string') {
out[key] = [v]
} else if (Array.isArray(v)) {
out[key] = v
}
}
return out
}
/**
* @param {string[]} h
* @returns {Record<string, string[]>}
*/
function multiValueHeaders (h) {
/** @type {Record<string, string[]>} */
const out = {}
for (let i = 0; i < h.length; i += 2) {
const headerName = h[i]
const headerValue = h[i + 1]
if (!(headerName in out)) {
out[headerName] = [headerValue]
} else {
out[headerName].push(headerValue)
}
}
return out
}
/**
* @param {string[]} h
* @returns {Record<string, string>}
*/
function flattenHeaders (h) {
/** @type {Record<string, string>} */
const out = {}
/** @type {string[]} */
const deleteList = []
for (let i = 0; i < h.length; i += 2) {
const headerName = h[i]
const headerValue = h[i + 1]
if (!(headerName in out)) {
out[headerName] = headerValue
} else {
deleteList.push(headerName)
}
}
for (const key of deleteList) {
delete out[key]
}
return out
}
/**
* @returns {string}
*/
function cuuid () {
const str = (Date.now().toString(16) + Math.random().toString(16).slice(2) + Math.random().toString(16).slice(2) + Math.random().toString(16).slice(2)).slice(0, 32)
return str.slice(0, 8) + '-' + str.slice(8, 12) + '-' + str.slice(12, 16) + '-' + str.slice(16, 20) + '-' + str.slice(20)
}
/**
* @param {FunctionInfo[]} functions
* @param {string} pathname
* @returns {FunctionInfo | null}
*/
function matchRoute (functions, pathname) {
// what if a path has more than one pattern element?
return functions.find(fun => {
const route = fun.path
if (!route) {
return false
}
const routeSegments = route.split('/').slice(1)
const pathSegments = pathname.split('/').slice(1)
const endsInGlob = route.endsWith('+}')
if (
!endsInGlob &&
routeSegments.length !== pathSegments.length
) {
return false
}
for (let i = 0; i < routeSegments.length; i++) {
const routeSegment = routeSegments[i]
const pathSegment = pathSegments[i]
if (!pathSegment && pathSegment !== '') {
return false
}
if (!routeSegment.startsWith('{')) {
if (routeSegment !== pathSegment) {
return false
}
}
if (routeSegment.startsWith('{') && pathSegment === '') {
return false
}
}
return true
})
}
/**
* @param {unknown} v
*/
function checkResult (v) {
if (typeof v !== 'object' || !v) {
return false
}
const objValue = v
if (typeof Reflect.get(objValue, 'isBase64Encoded') !== 'boolean') {
return false
}
if (typeof Reflect.get(objValue, 'statusCode') !== 'number') {
return false
}
if (typeof Reflect.get(objValue, 'headers') !== 'object') {
return false
}
const mvHeaders = /** @type {unknown} */ (Reflect.get(objValue, 'multiValueHeaders'))
if (mvHeaders && typeof mvHeaders !== 'object') {
return false
}
if (typeof Reflect.get(objValue, 'body') !== 'string') {
return false
}
return true
}