-
-
Notifications
You must be signed in to change notification settings - Fork 797
/
ApiGateway.js
1150 lines (976 loc) · 38.4 KB
/
ApiGateway.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
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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
const fs = require('fs');
const path = require('path');
const { performance, PerformanceObserver } = require('perf_hooks');
const hapi = require('@hapi/hapi');
const h2o2 = require('@hapi/h2o2');
const debugLog = require('./debugLog');
const jsonPath = require('./jsonPath');
const LambdaContext = require('./LambdaContext.js');
const createVelocityContext = require('./createVelocityContext');
const createLambdaProxyEvent = require('./createLambdaProxyEvent');
const renderVelocityTemplateObject = require('./renderVelocityTemplateObject');
const createAuthScheme = require('./createAuthScheme');
const functionHelper = require('./functionHelper');
const Endpoint = require('./Endpoint');
const parseResources = require('./parseResources');
const { detectEncoding, createUniqueId } = require('./utils');
const authFunctionNameExtractor = require('./authFunctionNameExtractor');
module.exports = class ApiGateway {
constructor(serverless, options, velocityContextOptions) {
this.service = serverless.service;
this.log = serverless.cli.log.bind(serverless.cli);
this.options = options;
this.requests = {};
this.lastRequestOptions = null;
this.velocityContextOptions = velocityContextOptions;
}
printBlankLine() {
console.log();
}
logPluginIssue() {
this.log(
'If you think this is an issue with the plugin please submit it, thanks!',
);
this.log('https://github.com/dherault/serverless-offline/issues');
}
_createServer() {
const { host, port } = this.options;
const serverOptions = {
host,
port,
router: {
stripTrailingSlash: !this.options.preserveTrailingSlash, // removes trailing slashes on incoming paths.
},
};
const httpsDir = this.options.httpsProtocol;
// HTTPS support
if (typeof httpsDir === 'string' && httpsDir.length > 0) {
serverOptions.tls = {
cert: fs.readFileSync(path.resolve(httpsDir, 'cert.pem'), 'ascii'),
key: fs.readFileSync(path.resolve(httpsDir, 'key.pem'), 'ascii'),
};
}
serverOptions.state = this.options.enforceSecureCookies
? {
isHttpOnly: true,
isSameSite: false,
isSecure: true,
}
: {
isHttpOnly: false,
isSameSite: false,
isSecure: false,
};
// Hapijs server creation
this.server = hapi.server(serverOptions);
this.server.register(h2o2).catch((err) => this.log(err));
// Enable CORS preflight response
this.server.ext('onPreResponse', (request, h) => {
if (request.headers.origin) {
const response = request.response.isBoom
? request.response.output
: request.response;
response.headers['access-control-allow-origin'] =
request.headers.origin;
response.headers['access-control-allow-credentials'] = 'true';
if (request.method === 'options') {
response.statusCode = 200;
response.headers['access-control-expose-headers'] =
'content-type, content-length, etag';
response.headers['access-control-max-age'] = 60 * 10;
if (request.headers['access-control-request-headers']) {
response.headers['access-control-allow-headers'] =
request.headers['access-control-request-headers'];
}
if (request.headers['access-control-request-method']) {
response.headers['access-control-allow-methods'] =
request.headers['access-control-request-method'];
}
}
}
return h.continue;
});
return this.server;
}
_extractAuthFunctionName(endpoint) {
const result = authFunctionNameExtractor(endpoint, this.log);
return result.unsupportedAuth ? null : result.authorizerName;
}
_configureAuthorization(
endpoint,
funName,
method,
epath,
servicePath,
serviceRuntime,
) {
if (!endpoint.authorizer) {
return null;
}
const authFunctionName = this._extractAuthFunctionName(endpoint);
if (!authFunctionName) {
return null;
}
this.log(`Configuring Authorization: ${endpoint.path} ${authFunctionName}`);
const authFunction = this.service.getFunction(authFunctionName);
if (!authFunction)
return this.log(
`WARNING: Authorization function ${authFunctionName} does not exist`,
);
const authorizerOptions = {
identitySource: 'method.request.header.Authorization',
identityValidationExpression: '(.*)',
resultTtlInSeconds: '300',
};
if (typeof endpoint.authorizer === 'string') {
authorizerOptions.name = authFunctionName;
} else {
Object.assign(authorizerOptions, endpoint.authorizer);
}
// Create a unique scheme per endpoint
// This allows the methodArn on the event property to be set appropriately
const authKey = `${funName}-${authFunctionName}-${method}-${epath}`;
const authSchemeName = `scheme-${authKey}`;
const authStrategyName = `strategy-${authKey}`; // set strategy name for the route config
debugLog(`Creating Authorization scheme for ${authKey}`);
// Create the Auth Scheme for the endpoint
const scheme = createAuthScheme(
authFunction,
authorizerOptions,
authFunctionName,
epath,
this.options,
this.log,
servicePath,
serviceRuntime,
this.service,
);
// Set the auth scheme and strategy on the server
this.server.auth.scheme(authSchemeName, scheme);
this.server.auth.strategy(authStrategyName, authSchemeName);
return authStrategyName;
}
// All done, we can listen to incomming requests
async _listen() {
try {
await this.server.start();
} catch (e) {
console.error(
`Unexpected error while starting serverless-offline server on port ${this.options.port}:`,
e,
);
process.exit(1);
}
this.printBlankLine();
this.log(
`Offline [HTTP] listening on http${
this.options.httpsProtocol ? 's' : ''
}://${this.options.host}:${this.options.port}`,
);
this.log('Enter "rp" to replay the last request');
process.openStdin().addListener('data', (data) => {
// note: data is an object, and when converted to a string it will
// end with a linefeed. so we (rather crudely) account for that
// with toString() and then trim()
if (data.toString().trim() === 'rp') {
this._injectLastRequest();
}
});
}
_createRoutes(
event,
funOptions,
protectedRoutes,
funName,
servicePath,
serviceRuntime,
defaultContentType,
key,
fun,
) {
// Handle Simple http setup, ex. - http: GET users/index
if (typeof event.http === 'string') {
const [method, path] = event.http.split(' ');
event.http = { method, path };
}
// generate an enpoint via the endpoint class
const endpoint = new Endpoint(event.http, funOptions).generate();
const integration = endpoint.integration || 'lambda-proxy';
const epath = endpoint.path;
const method = endpoint.method.toUpperCase();
const { requestTemplates } = endpoint;
// Prefix must start and end with '/' BUT path must not end with '/'
let fullPath =
this.options.prefix + (epath.startsWith('/') ? epath.slice(1) : epath);
if (fullPath !== '/' && fullPath.endsWith('/'))
fullPath = fullPath.slice(0, -1);
fullPath = fullPath.replace(/\+}/g, '*}');
if (event.http.private) {
protectedRoutes.push(`${method}#${fullPath}`);
}
this.log(`${method} ${fullPath}`);
// If the endpoint has an authorization function, create an authStrategy for the route
const authStrategyName = this.options.noAuth
? null
: this._configureAuthorization(
endpoint,
funName,
method,
epath,
servicePath,
serviceRuntime,
);
let cors = null;
if (endpoint.cors) {
cors = {
credentials:
endpoint.cors.credentials || this.options.corsConfig.credentials,
exposedHeaders: this.options.corsConfig.exposedHeaders,
headers: endpoint.cors.headers || this.options.corsConfig.headers,
origin: endpoint.cors.origins || this.options.corsConfig.origin,
};
}
// Route creation
const routeMethod = method === 'ANY' ? '*' : method;
const state = this.options.disableCookieValidation
? {
failAction: 'ignore',
parse: false,
}
: {
failAction: 'error',
parse: true,
};
const routeConfig = {
auth: authStrategyName,
cors,
state,
timeout: { socket: false },
};
// skip HEAD routes as hapi will fail with 'Method name not allowed: HEAD ...'
// for more details, check https://github.com/dherault/serverless-offline/issues/204
if (routeMethod === 'HEAD') {
this.log(
'HEAD method event detected. Skipping HAPI server route mapping ...',
);
return;
}
if (routeMethod !== 'HEAD' && routeMethod !== 'GET') {
// maxBytes: Increase request size from 1MB default limit to 10MB.
// Cf AWS API GW payload limits.
routeConfig.payload = {
maxBytes: 1024 * 1024 * 10,
parse: false,
};
}
this.server.route({
config: routeConfig,
method: routeMethod,
path: fullPath,
handler: (request, h) => {
// Here we go
// Store current request as the last one
this.lastRequestOptions = {
headers: request.headers,
method: request.method,
payload: request.payload,
url: request.url.href,
};
if (request.auth.credentials && request.auth.strategy) {
this.lastRequestOptions.auth = request.auth;
}
// Payload processing
const encoding = detectEncoding(request);
request.payload = request.payload && request.payload.toString(encoding);
request.rawPayload = request.payload;
// Headers processing
// Hapi lowercases the headers whereas AWS does not
// so we recreate a custom headers object from the raw request
const headersArray = request.raw.req.rawHeaders;
// During tests, `server.inject` uses *shot*, a package
// for performing injections that does not entirely mimick
// Hapi's usual request object. rawHeaders are then missing
// Hence the fallback for testing
// Normal usage
if (headersArray) {
request.unprocessedHeaders = {};
request.multiValueHeaders = {};
for (let i = 0; i < headersArray.length; i += 2) {
request.unprocessedHeaders[headersArray[i]] = headersArray[i + 1];
request.multiValueHeaders[headersArray[i]] = (
request.multiValueHeaders[headersArray[i]] || []
).concat(headersArray[i + 1]);
}
}
// Lib testing
else {
request.unprocessedHeaders = request.headers;
}
// Incomming request message
this.printBlankLine();
this.log(`${method} ${request.path} (λ: ${funName})`);
// Check for APIKey
if (
(protectedRoutes.includes(`${routeMethod}#${fullPath}`) ||
protectedRoutes.includes(`ANY#${fullPath}`)) &&
!this.options.noAuth
) {
const errorResponse = () =>
h
.response({ message: 'Forbidden' })
.code(403)
.type('application/json')
.header('x-amzn-ErrorType', 'ForbiddenException');
if ('x-api-key' in request.headers) {
const requestToken = request.headers['x-api-key'];
if (requestToken !== this.options.apiKey) {
debugLog(
`Method ${method} of function ${funName} token ${requestToken} not valid`,
);
return errorResponse();
}
} else if (
request.auth &&
request.auth.credentials &&
'usageIdentifierKey' in request.auth.credentials
) {
const { usageIdentifierKey } = request.auth.credentials;
if (usageIdentifierKey !== this.options.apiKey) {
debugLog(
`Method ${method} of function ${funName} token ${usageIdentifierKey} not valid`,
);
return errorResponse();
}
} else {
debugLog(`Missing x-api-key on private function ${funName}`);
return errorResponse();
}
}
// Shared mutable state is the root of all evil they say
const requestId = createUniqueId();
this.requests[requestId] = { done: false };
this.currentRequestId = requestId;
const response = h.response();
const contentType = request.mime || defaultContentType;
// default request template to '' if we don't have a definition pushed in from serverless or endpoint
const requestTemplate =
typeof requestTemplates !== 'undefined' && integration === 'lambda'
? requestTemplates[contentType]
: '';
// https://hapijs.com/api#route-configuration doesn't seem to support selectively parsing
// so we have to do it ourselves
const contentTypesThatRequirePayloadParsing = [
'application/json',
'application/vnd.api+json',
];
if (
contentTypesThatRequirePayloadParsing.includes(contentType) &&
request.payload &&
request.payload.length > 1
) {
try {
if (!request.payload || request.payload.length < 1) {
request.payload = '{}';
}
request.payload = JSON.parse(request.payload);
} catch (err) {
debugLog('error in converting request.payload to JSON:', err);
}
}
debugLog('requestId:', requestId);
debugLog('contentType:', contentType);
debugLog('requestTemplate:', requestTemplate);
debugLog('payload:', request.payload);
/* HANDLER LAZY LOADING */
let userHandler; // The lambda function
Object.assign(process.env, this.originalEnvironment);
try {
if (this.options.noEnvironment) {
// This evict errors in server when we use aws services like ssm
const baseEnvironment = {
AWS_REGION: 'dev',
};
if (!process.env.AWS_PROFILE) {
baseEnvironment.AWS_ACCESS_KEY_ID = 'dev';
baseEnvironment.AWS_SECRET_ACCESS_KEY = 'dev';
}
process.env = Object.assign(baseEnvironment, process.env);
} else {
Object.assign(
process.env,
{ AWS_REGION: this.service.provider.region },
this.service.provider.environment,
this.service.functions[key].environment,
);
}
process.env._HANDLER = fun.handler;
userHandler = functionHelper.createHandler(funOptions, this.options);
} catch (err) {
return this._reply500(
response,
`Error while loading ${funName}`,
err,
);
}
/* REQUEST TEMPLATE PROCESSING (event population) */
let event = {};
if (integration === 'lambda') {
if (requestTemplate) {
try {
debugLog('_____ REQUEST TEMPLATE PROCESSING _____');
// Velocity templating language parsing
const velocityContext = createVelocityContext(
request,
this.velocityContextOptions,
request.payload || {},
);
event = renderVelocityTemplateObject(
requestTemplate,
velocityContext,
);
} catch (err) {
return this._reply500(
response,
`Error while parsing template "${contentType}" for ${funName}`,
err,
);
}
} else if (typeof request.payload === 'object') {
event = request.payload || {};
}
} else if (integration === 'lambda-proxy') {
event = createLambdaProxyEvent(
request,
this.options,
this.velocityContextOptions.stageVariables,
);
}
event.isOffline = true;
if (this.service.custom && this.service.custom.stageVariables) {
event.stageVariables = this.service.custom.stageVariables;
} else if (integration !== 'lambda-proxy') {
event.stageVariables = {};
}
debugLog('event:', event);
return new Promise((resolve) => {
// We create the context, its callback (context.done/succeed/fail) will send the HTTP response
const lambdaContext = new LambdaContext(
fun,
this.service.provider,
(err, data, fromPromise) => {
// Everything in this block happens once the lambda function has resolved
debugLog('_____ HANDLER RESOLVED _____');
// User should not call context.done twice
if (!this.requests[requestId] || this.requests[requestId].done) {
this.printBlankLine();
const warning = fromPromise
? `Warning: handler '${funName}' returned a promise and also uses a callback!\nThis is problematic and might cause issues in your lambda.`
: `Warning: context.done called twice within handler '${funName}'!`;
this.log(warning);
debugLog('requestId:', requestId);
return;
}
this.requests[requestId].done = true;
let result = data;
let responseName = 'default';
const { contentHandling, responseContentType } = endpoint;
/* RESPONSE SELECTION (among endpoint's possible responses) */
// Failure handling
let errorStatusCode = 0;
if (err) {
// Since the --useSeparateProcesses option loads the handler in
// a separate process and serverless-offline communicates with it
// over IPC, we are unable to catch JavaScript unhandledException errors
// when the handler code contains bad JavaScript. Instead, we "catch"
// it here and reply in the same way that we would have above when
// we lazy-load the non-IPC handler function.
if (this.options.useSeparateProcesses && err.ipcException) {
return resolve(
this._reply500(
response,
`Error while loading ${funName}`,
err,
),
);
}
const errorMessage = (err.message || err).toString();
const re = /\[(\d{3})]/;
const found = errorMessage.match(re);
if (found && found.length > 1) {
[, errorStatusCode] = found;
} else {
errorStatusCode = '500';
}
// Mocks Lambda errors
result = {
errorMessage,
errorType: err.constructor.name,
stackTrace: this._getArrayStackTrace(err.stack),
};
this.log(`Failure: ${errorMessage}`);
if (!this.options.hideStackTraces) {
console.error(err.stack);
}
for (const key in endpoint.responses) {
if (
key !== 'default' &&
errorMessage.match(
`^${endpoint.responses[key].selectionPattern || key}$`,
)
) {
responseName = key;
break;
}
}
}
debugLog(`Using response '${responseName}'`);
const chosenResponse = endpoint.responses[responseName];
/* RESPONSE PARAMETERS PROCCESSING */
const { responseParameters } = chosenResponse;
if (responseParameters) {
const responseParametersKeys = Object.keys(responseParameters);
debugLog('_____ RESPONSE PARAMETERS PROCCESSING _____');
debugLog(
`Found ${responseParametersKeys.length} responseParameters for '${responseName}' response`,
);
// responseParameters use the following shape: "key": "value"
Object.entries(responseParametersKeys).forEach(
([key, value]) => {
const keyArray = key.split('.'); // eg: "method.response.header.location"
const valueArray = value.split('.'); // eg: "integration.response.body.redirect.url"
debugLog(
`Processing responseParameter "${key}": "${value}"`,
);
// For now the plugin only supports modifying headers
if (
key.startsWith('method.response.header') &&
keyArray[3]
) {
const headerName = keyArray.slice(3).join('.');
let headerValue;
debugLog('Found header in left-hand:', headerName);
if (value.startsWith('integration.response')) {
if (valueArray[2] === 'body') {
debugLog('Found body in right-hand');
headerValue = (valueArray[3]
? jsonPath(result, valueArray.slice(3).join('.'))
: result
).toString();
} else {
this.printBlankLine();
this.log(
`Warning: while processing responseParameter "${key}": "${value}"`,
);
this.log(
`Offline plugin only supports "integration.response.body[.JSON_path]" right-hand responseParameter. Found "${value}" instead. Skipping.`,
);
this.logPluginIssue();
this.printBlankLine();
}
} else {
headerValue = value.match(/^'.*'$/)
? value.slice(1, -1)
: value; // See #34
}
// Applies the header;
debugLog(
`Will assign "${headerValue}" to header "${headerName}"`,
);
response.header(headerName, headerValue);
} else {
this.printBlankLine();
this.log(
`Warning: while processing responseParameter "${key}": "${value}"`,
);
this.log(
`Offline plugin only supports "method.response.header.PARAM_NAME" left-hand responseParameter. Found "${key}" instead. Skipping.`,
);
this.logPluginIssue();
this.printBlankLine();
}
},
);
}
let statusCode = 200;
if (integration === 'lambda') {
const endpointResponseHeaders =
(endpoint.response && endpoint.response.headers) || {};
Object.entries(endpointResponseHeaders)
.filter(
([, value]) =>
typeof value === 'string' && /^'.*?'$/.test(value),
)
.forEach(([key, value]) =>
response.header(key, value.slice(1, -1)),
);
/* LAMBDA INTEGRATION RESPONSE TEMPLATE PROCCESSING */
// If there is a responseTemplate, we apply it to the result
const { responseTemplates } = chosenResponse;
if (typeof responseTemplates === 'object') {
const responseTemplatesKeys = Object.keys(responseTemplates);
if (responseTemplatesKeys.length) {
// BAD IMPLEMENTATION: first key in responseTemplates
const responseTemplate =
responseTemplates[responseContentType];
if (responseTemplate && responseTemplate !== '\n') {
debugLog('_____ RESPONSE TEMPLATE PROCCESSING _____');
debugLog(
`Using responseTemplate '${responseContentType}'`,
);
try {
const reponseContext = createVelocityContext(
request,
this.velocityContextOptions,
result,
);
result = renderVelocityTemplateObject(
{ root: responseTemplate },
reponseContext,
).root;
} catch (error) {
this.log(
`Error while parsing responseTemplate '${responseContentType}' for lambda ${funName}:`,
);
console.log(error.stack);
}
}
}
}
/* LAMBDA INTEGRATION HAPIJS RESPONSE CONFIGURATION */
statusCode =
errorStatusCode !== 0
? errorStatusCode
: chosenResponse.statusCode || 200;
if (!chosenResponse.statusCode) {
this.printBlankLine();
this.log(
`Warning: No statusCode found for response "${responseName}".`,
);
}
response.header('Content-Type', responseContentType, {
override: false, // Maybe a responseParameter set it already. See #34
});
response.statusCode = statusCode;
if (contentHandling === 'CONVERT_TO_BINARY') {
response.encoding = 'binary';
response.source = Buffer.from(result, 'base64');
response.variety = 'buffer';
} else {
if (
result &&
result.body &&
typeof result.body !== 'string'
) {
return this._reply500(
response,
'According to the API Gateway specs, the body content must be stringified. Check your Lambda response and make sure you are invoking JSON.stringify(YOUR_CONTENT) on your body object',
{},
);
}
response.source = result;
}
} else if (integration === 'lambda-proxy') {
/* LAMBDA PROXY INTEGRATION HAPIJS RESPONSE CONFIGURATION */
response.statusCode = statusCode =
(result || {}).statusCode || 200;
const headers = {};
if (result && result.headers) {
Object.keys(result.headers).forEach((header) => {
headers[header] = (headers[header] || []).concat(
result.headers[header],
);
});
}
if (result && result.multiValueHeaders) {
Object.keys(result.multiValueHeaders).forEach((header) => {
headers[header] = (headers[header] || []).concat(
result.multiValueHeaders[header],
);
});
}
debugLog('headers', headers);
Object.keys(headers).forEach((header) => {
if (header.toLowerCase() === 'set-cookie') {
headers[header].forEach((headerValue) => {
const cookieName = headerValue.slice(
0,
headerValue.indexOf('='),
);
const cookieValue = headerValue.slice(
headerValue.indexOf('=') + 1,
);
h.state(cookieName, cookieValue, {
encoding: 'none',
strictHeader: false,
});
});
} else {
headers[header].forEach((headerValue) => {
// it looks like Hapi doesn't support multiple headers with the same name,
// appending values is the closest we can come to the AWS behavior.
response.header(header, headerValue, { append: true });
});
}
});
response.header('Content-Type', 'application/json', {
duplicate: false,
override: false,
});
if (result && typeof result.body !== 'undefined') {
if (result.isBase64Encoded) {
response.encoding = 'binary';
response.source = Buffer.from(result.body, 'base64');
response.variety = 'buffer';
} else {
if (
result &&
result.body &&
typeof result.body !== 'string'
) {
return this._reply500(
response,
'According to the API Gateway specs, the body content must be stringified. Check your Lambda response and make sure you are invoking JSON.stringify(YOUR_CONTENT) on your body object',
{},
);
}
response.source = result.body;
}
}
}
// Log response
let whatToLog = result;
try {
whatToLog = JSON.stringify(result);
} catch (error) {
// nothing
} finally {
if (this.options.printOutput)
this.log(
err
? `Replying ${statusCode}`
: `[${statusCode}] ${whatToLog}`,
);
debugLog('requestId:', requestId);
}
// Bon voyage!
resolve(response);
},
);
// Now we are outside of new LambdaContext, so this happens before the handler gets called:
// We cannot use Hapijs's timeout feature because the logic above can take a significant time, so we implement it ourselves
this.requests[requestId].timeout = this.options.noTimeout
? null
: setTimeout(
this._replyTimeout.bind(
this,
response,
resolve,
funName,
funOptions.funTimeout,
requestId,
),
funOptions.funTimeout,
);
// Finally we call the handler
debugLog('_____ CALLING HANDLER _____');
const cleanup = () => {
this._clearTimeout(requestId);
delete this.requests[requestId];
};
let x;
if (this.options.showDuration) {
performance.mark(`${requestId}-start`);
const obs = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
this.log(
`Duration ${entry.duration.toFixed(2)} ms (λ: ${entry.name})`,
);
}
obs.disconnect();
});
obs.observe({ entryTypes: ['measure'] });
}
try {
x = userHandler(event, lambdaContext, (err, result) => {
setTimeout(cleanup, 0);
if (this.options.showDuration) {
performance.mark(`${requestId}-end`);
performance.measure(
funName,
`${requestId}-start`,
`${requestId}-end`,
);
}
return lambdaContext.done(err, result);
});
// Promise support
if (!this.requests[requestId].done) {
if (x && typeof x.then === 'function') {
x.then(lambdaContext.succeed)
.catch(lambdaContext.fail)
.then(cleanup, cleanup);
} else if (x instanceof Error) {
lambdaContext.fail(x);
}
}
} catch (error) {
cleanup();
return resolve(
this._reply500(
response,
`Uncaught error in your '${funName}' handler`,
error,
),
);
}
});
},
});
}
// Bad news
_reply500(response, message, error) {
this.log(message);
console.error(error);
response.header('Content-Type', 'application/json');
/* eslint-disable no-param-reassign */
response.statusCode = 200; // APIG replies 200 by default on failures;
response.source = {
errorMessage: message,
errorType: error.constructor.name,
offlineInfo:
'If you believe this is an issue with serverless-offline please submit it, thanks. https://github.com/dherault/serverless-offline/issues',
stackTrace: this._getArrayStackTrace(error.stack),
};
/* eslint-enable no-param-reassign */
return response;
}
_replyTimeout(response, resolve, funName, funTimeout, requestId) {
if (this.currentRequestId !== requestId) return;
this.log(`Replying timeout after ${funTimeout}ms`);
/* eslint-disable no-param-reassign */