forked from sid88in/serverless-appsync-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.test.js
801 lines (741 loc) · 23 KB
/
index.test.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
/* eslint-disable no-template-curly-in-string */
const fs = require('fs');
const chalk = require('chalk');
const Serverless = require('serverless/lib/Serverless');
const ServerlessAppsyncPlugin = require('./src');
const AwsProvider = require('serverless/lib/plugins/aws/provider/awsProvider.js');
let serverless;
let plugin;
let config;
jest.spyOn(Date, 'now').mockImplementation(() => 10000);
jest.mock('fs');
jest.spyOn(fs, 'readFileSync').mockImplementation(() => '');
beforeEach(() => {
const cli = {
log: jest.fn(),
consoleLog: jest.fn(),
};
serverless = new Serverless();
serverless.cli = cli;
const options = {
stage: 'dev',
region: 'us-east-1',
};
serverless.setProvider('aws', new AwsProvider(serverless, options));
plugin = new ServerlessAppsyncPlugin(serverless, {});
config = {
additionalAuthenticationProviders: [],
name: 'api',
dataSources: [],
region: 'us-east-1',
isSingleConfig: true,
mappingTemplatesLocation: 'mapping-templates',
substitutions: {},
};
});
describe('appsync display', () => {
test('appsync api keys are displayed', () => {
plugin.gatheredData.apiKeys = ['dummy-api-key-1', 'dummy-api-key-2'];
let expectedMessage = '';
expectedMessage += `${chalk.yellow('appsync api keys:')}`;
expectedMessage += '\n dummy-api-key-1';
expectedMessage += '\n dummy-api-key-2';
expect(plugin.displayApiKeys()).toEqual(expectedMessage);
});
test('appsync api keys are hidden when `--conceal` is given', () => {
plugin.options.conceal = true;
plugin.gatheredData.apiKeys = ['dummy-api-key-1', 'dummy-api-key-2'];
let expectedMessage = '';
expectedMessage += `${chalk.yellow('appsync api keys:')}`;
expectedMessage += '\n *** (concealed)';
expectedMessage += '\n *** (concealed)';
expect(plugin.displayApiKeys()).toEqual(expectedMessage);
});
});
describe('appsync config', () => {
test('appsync cloudwatch role is autogenerated', () => {
Object.assign(
config,
{
logConfig: {
level: 'ALL',
},
},
);
const role = plugin.getCloudWatchLogsRole(config);
expect(role).toMatchSnapshot();
});
test('appsync cloudwatch role is not autogenerated when Logs not enabled', () => {
const role = plugin.getCloudWatchLogsRole(config);
expect(role).toEqual({});
});
test('appsync cloudwatch role is not autogenerated when loggingRoleArn is specified', () => {
Object.assign(
config,
{
logConfig: {
level: 'ALL',
loggingRoleArn: 'arn:aws:iam::123456789012:role/service-role/appsyncRole',
},
},
);
const role = plugin.getCloudWatchLogsRole(config);
expect(role).toEqual({});
});
test('appsync cloudwatch log group is not created when are not logs enabled', () => {
const resources = plugin.getGraphQlApiEndpointResource(config);
expect(resources.GraphQlApiLogGroup).toBeUndefined();
});
test('appsync cloudwatch log group is created when logs enabled', () => {
serverless.service.provider.logRetentionInDays = 14;
const resources = plugin.getGraphQlApiEndpointResource({
...config,
logConfig: {
level: 'ALL',
},
});
expect(resources.GraphQlApiLogGroup).toMatchSnapshot();
});
test('Datasource generates lambdaFunctionArn from functionName', () => {
Object.assign(
config,
{
dataSources: [
{
type: 'AWS_LAMBDA',
name: 'lambdaSource',
description: 'lambdaSource Desc',
config: {
functionName: 'myFunc',
serviceRoleArn: 'arn:aws:iam::123456789012:role/service-role/myLambdaRole',
},
},
],
},
);
const dataSources = plugin.getDataSourceResources(config);
expect(dataSources).toMatchSnapshot();
});
test('Datasource uses lambdaFunctionArn when provided', () => {
Object.assign(
config,
{
dataSources: [
{
type: 'AWS_LAMBDA',
name: 'lambdaSource',
description: 'lambdaSource Desc',
config: {
functionName: 'myDummyFunc',
lambdaFunctionArn: { 'Fn::GetAtt': ['MyFuncLambdaFunction', 'Arn'] },
serviceRoleArn: 'arn:aws:iam::123456789012:role/service-role/myLambdaRole',
},
},
],
},
);
const dataSources = plugin.getDataSourceResources(config);
expect(dataSources).toMatchSnapshot();
});
test('Datasource generates HTTP authorization when authorizationConfig provided', () => {
Object.assign(
config,
{
dataSources: [
{
type: 'HTTP',
name: 'HTTPSource',
description: 'HTTPSource Desc',
config: {
endpoint: 'https://www.example.com/api',
serviceRoleArn: 'arn:aws:iam::123456789012:role/service-role/myHTTPRole',
authorizationConfig: {
authorizationType: 'AWS_IAM',
awsIamConfig: {
signingRegion: 'us-east-1',
signingServiceName: 'ses',
},
},
},
},
],
},
);
const dataSources = plugin.getDataSourceResources(config);
expect(dataSources).toMatchSnapshot();
});
test("HTTP Datasource defaults the IAM role signing region to the stack's region", () => {
Object.assign(
config,
{
dataSources: [
{
type: 'HTTP',
name: 'HTTPSource',
description: 'HTTPSource Desc',
config: {
endpoint: 'https://www.example.com/api',
serviceRoleArn: 'arn:aws:iam::123456789012:role/service-role/myHTTPRole',
authorizationConfig: {
authorizationType: 'AWS_IAM',
awsIamConfig: {
signingServiceName: 'ses',
},
},
},
},
],
},
);
const dataSources = plugin.getDataSourceResources(config);
expect(dataSources).toMatchSnapshot();
});
test('AMAZON_COGNITO_USER_POOLS config created', () => {
const resources = plugin.getGraphQlApiEndpointResource({
...config,
authenticationType: 'AMAZON_COGNITO_USER_POOLS',
userPoolConfig: {
defaultAction: 'ALLOW',
awsRegion: 'eu-central-1',
userPoolId: 'userPoolGenerateId',
appIdClientRegex: 'appIdClientRegex',
},
});
expect(resources.GraphQlApi.Properties.AuthenticationType).toBe('AMAZON_COGNITO_USER_POOLS');
expect(resources.GraphQlApi.Properties.UserPoolConfig).toEqual({
DefaultAction: 'ALLOW',
AwsRegion: 'eu-central-1',
UserPoolId: 'userPoolGenerateId',
AppIdClientRegex: 'appIdClientRegex',
});
});
test('Tags config created', () => {
const resources = plugin.getGraphQlApiEndpointResource({
...config,
tags: {
testKey: 'testValue',
},
});
expect(resources.GraphQlApi.Properties.Tags).toEqual(expect.arrayContaining([{
Key: 'testKey',
Value: 'testValue',
}]));
});
test('OPENID_CONNECT config created', () => {
const resources = plugin.getGraphQlApiEndpointResource({
...config,
authenticationType: 'OPENID_CONNECT',
openIdConnectConfig: {
issuer: 'issuer',
clientId: 'clientId',
iatTTL: 1000,
authTTL: 1000,
},
});
expect(resources.GraphQlApi.Properties.AuthenticationType).toBe('OPENID_CONNECT');
expect(resources.GraphQlApi.Properties.OpenIDConnectConfig).toEqual({
Issuer: 'issuer',
ClientId: 'clientId',
IatTTL: 1000,
AuthTTL: 1000,
});
});
test('API_KEY config created', () => {
const apiConfig = {
...config,
authenticationType: 'API_KEY',
};
const apiResources = plugin.getGraphQlApiEndpointResource(apiConfig);
const keyResources = plugin.getApiKeyResources(apiConfig);
const outputs = plugin.getApiKeyOutputs(apiConfig);
expect(apiResources.GraphQlApi.Properties.AuthenticationType).toBe('API_KEY');
expect(keyResources.GraphQlApiKeyDefault).toEqual({
Type: 'AWS::AppSync::ApiKey',
Properties: {
ApiId: { 'Fn::GetAtt': ['GraphQlApi', 'ApiId'] },
Description: 'serverless-appsync-plugin: AppSync API Key for GraphQlApiKeyDefault',
Expires: Math.floor(Date.now() / 1000) + (365 * 24 * 60 * 60),
},
});
expect(outputs).toEqual({
GraphQlApiKeyDefault: {
Value: { 'Fn::GetAtt': ['GraphQlApiKeyDefault', 'ApiKey'] },
},
});
});
test('Additional authentication providers created', () => {
const apiConfig = {
...config,
additionalAuthenticationProviders: [
{
authenticationType: 'AMAZON_COGNITO_USER_POOLS',
userPoolConfig: {
awsRegion: 'eu-central-1',
userPoolId: 'userPoolGenerateId',
appIdClientRegex: 'appIdClientRegex',
},
},
{
authenticationType: 'OPENID_CONNECT',
openIdConnectConfig: {
issuer: 'issuer',
clientId: 'clientId',
iatTTL: 1000,
authTTL: 1000,
},
},
{
authenticationType: 'API_KEY',
},
{
authenticationType: 'AWS_IAM',
},
],
};
const apiResources = plugin.getGraphQlApiEndpointResource(apiConfig);
const keyResources = plugin.getApiKeyResources(apiConfig);
const outputs = plugin.getApiKeyOutputs(apiConfig);
expect(apiResources.GraphQlApi.Properties.AdditionalAuthenticationProviders).toMatchSnapshot();
expect(keyResources.GraphQlApiKeyDefault).toMatchSnapshot();
expect(outputs).toEqual({
GraphQlApiKeyDefault: {
Value: { 'Fn::GetAtt': ['GraphQlApiKeyDefault', 'ApiKey'] },
},
});
});
});
describe('Caching', () => {
test('Disabled', () => {
const apiResources = plugin.getApiCachingResource(config);
expect(apiResources).toMatchSnapshot();
});
test('Minimum configuration', () => {
const apiConfig = {
...config,
caching: {
behavior: 'FULL_REQUEST_CACHING',
},
};
const apiResources = plugin.getApiCachingResource(apiConfig);
expect(apiResources).toMatchSnapshot();
});
test('Custom configuration', () => {
const apiConfig = {
...config,
caching: {
behavior: 'FULL_REQUEST_CACHING',
atRestEncryption: true,
transitEncryption: true,
ttl: 500,
type: 'T2_MEDIUM',
},
};
const apiResources = plugin.getApiCachingResource(apiConfig);
expect(apiResources).toMatchSnapshot();
});
test('Resolver min config', () => {
const apiConfig = {
...config,
caching: {
behavior: 'PER_RESOLVER_CACHING',
},
mappingTemplates: [
{
dataSource: 'ds',
type: 'Query',
field: 'field',
caching: true,
},
],
};
const apiResources = plugin.getResolverResources(apiConfig);
expect(apiResources).toMatchSnapshot();
});
test('Resolver custom config', () => {
const apiConfig = {
...config,
caching: {
behavior: 'PER_RESOLVER_CACHING',
},
mappingTemplates: [
{
dataSource: 'ds',
type: 'Query',
field: 'field',
caching: {
ttl: 1000,
keys: [
'$context.identity.sub',
'$context.arguments.id',
],
},
},
],
};
const apiResources = plugin.getResolverResources(apiConfig);
expect(apiResources).toMatchSnapshot();
});
test('Resolver with fallback', () => {
const apiConfig = {
...config,
caching: {
behavior: 'PER_RESOLVER_CACHING',
ttl: 2000,
},
mappingTemplates: [
{
dataSource: 'ds',
type: 'Query',
field: 'field',
caching: {
keys: [
'$context.identity.sub',
'$context.arguments.id',
],
},
},
],
};
const apiResources = plugin.getResolverResources(apiConfig);
expect(apiResources).toMatchSnapshot();
});
});
describe('iamRoleStatements', () => {
test('getDataSourceIamRolesResouces with Specific statements', () => {
Object.assign(
config,
{
dataSources: [
{
type: 'AWS_LAMBDA',
name: 'LambdaSource',
description: 'My Lambda Source',
config: {
lambdaFunctionArn: { 'Fn::GetAtt': ['MyTestFunctionLambdaFunction', 'Arn'] },
iamRoleStatements: [
{
Effect: 'Allow',
Action: ['lambda:invokeFunction'],
Resource: [
'arn:aws:lambda:us-east-1:123456789012:function:myTestFunction',
],
},
],
},
},
{
type: 'AMAZON_DYNAMODB',
name: 'DynamoDbSource',
description: 'My DynamoDb Source',
config: {
tableName: 'myTable',
iamRoleStatements: [
{
Effect: 'Allow',
Action: [
'dynamodb:Query',
'dynamodb:Scan',
],
Resource: [
'arn:aws:dynamodb:us-east-1:123456789012:table/myTable',
'arn:aws:dynamodb:us-east-1:123456789012:table/myTable/*',
],
},
],
},
},
{
type: 'RELATIONAL_DATABASE',
name: 'RelationalDatabaseSource',
description: 'Relational database Source',
config: {
region: 'us-east-1',
dbClusterIdentifier: 'aurora-cluster-id',
databaseName: 'myDatabaseName',
schema: 'mySchema',
awsSecretStoreArn: 'arn:aws:secretsmanager:us-east-1:123456789012:secret:rds-cluster-secret-XuztPa',
iamRoleStatements: [
{
Action: [
'rds-data:DeleteItems',
'rds-data:ExecuteSql',
'rds-data:GetItems',
'rds-data:InsertItems',
'rds-data:UpdateItems',
],
Resource: [
'arn:aws:rds:us-east-1:123456789012:cluster:aurora-cluster-id',
'arn:aws:rds:us-east-1:123456789012:cluster:aurora-cluster-id:*',
],
Effect: 'Allow',
},
{
Action: [
'secretsmanager:GetSecretValue',
],
Resource: [
'arn:aws:secretsmanager:us-east-1:123456789012:secret:rds-cluster-secret-XuztPa',
'arn:aws:secretsmanager:us-east-1:123456789012:secret:rds-cluster-secret-XuztPa:*',
],
Effect: 'Allow',
},
],
},
},
{
type: 'AMAZON_ELASTICSEARCH',
name: 'ElasticSearchSource',
description: 'My ElasticSearch Source',
config: {
region: 'us-east-1',
endpoint: 'https://search-my-domain-abcdefghijklmnop.us-east-1.es.amazonaws.com',
iamRoleStatements: [
{
Effect: 'Allow',
Action: [
'ES:ESHttpGet',
],
Resource: [
'arn:aws:es:us-east-1:123456789012:domain/my-domain',
],
},
],
},
},
{
type: 'AMAZON_ELASTICSEARCH',
name: 'ElasticSearchSource2',
description: 'other ES Source',
config: {
region: 'us-east-1',
endpoint: {
'Fn::GetAtt': [
'EsResource',
'DomainName',
],
},
iamRoleStatements: [
{
Effect: 'Allow',
Action: [
'ES:ESHttpGet',
],
Resource: [
{
'Fn::GetAtt': [
'EsResource',
'Arn',
],
},
],
},
],
},
},
],
},
);
const roles = plugin.getDataSourceIamRolesResouces(config);
expect(roles).toMatchSnapshot();
});
test('getDataSourceIamRolesResouces with Default generated statements', () => {
Object.assign(
config,
{
dataSources: [
{
type: 'AWS_LAMBDA',
name: 'LambdaSource',
description: 'My Lambda Source',
config: {
lambdaFunctionArn: { 'Fn::GetAtt': ['MyTestFunctionLambdaFunction', 'Arn'] },
},
},
{
type: 'AMAZON_DYNAMODB',
name: 'DynamoDbSource',
description: 'My DynamoDb Source',
config: {
tableName: 'myTable',
region: 'us-east-1',
},
},
{
type: 'RELATIONAL_DATABASE',
name: 'RelationalDbSource',
description: 'Relational Db Source',
config: {
region: 'us-east-1',
dbClusterIdentifier: 'aurora-cluster-id',
databaseName: 'myDatabaseName',
schema: 'mySchema',
awsSecretStoreArn: 'arn:aws:secretsmanager:us-east-1:123456789012:secret:rds-cluster-secret-XuztPa',
},
},
{
type: 'AMAZON_ELASTICSEARCH',
name: 'ElasticSearchSource',
description: 'My ElasticSearch Source',
config: {
region: 'us-east-1',
endpoint: 'https://search-my-domain-abcdefghijklmnop.us-east-1.es.amazonaws.com',
},
},
{
type: 'AMAZON_ELASTICSEARCH',
name: 'ElasticSearchSource2',
description: 'other ES Source',
config: {
region: 'us-east-1',
endpoint: {
'Fn::GetAtt': [
'EsResource',
'DomainName',
],
},
},
},
],
},
);
const roles = plugin.getDataSourceIamRolesResouces(config);
expect(roles).toMatchSnapshot();
});
test('using a serviceRoleArn should not generate any new Role', () => {
Object.assign(
config,
{
dataSources: [
{
type: 'AWS_LAMBDA',
name: 'LambdaSource',
description: 'My Lambda Source',
config: {
serviceRoleArn: 'arn:aws:iam::123456789012:role/service-role/myLambdaRole',
lambdaFunctionArn: { 'Fn::GetAtt': ['MyTestFunctionLambdaFunction', 'Arn'] },
},
},
{
type: 'AMAZON_DYNAMODB',
name: 'DynamoDbSource',
description: 'My DynamoDb Source',
config: {
tableName: 'myTable',
region: 'us-east-1',
serviceRoleArn: 'arn:aws:iam::123456789012:role/service-role/myDynamoDbRole',
},
},
{
type: 'RELATIONAL_DATABASE',
name: 'RelationalDbSource',
description: 'Relational Db Source',
config: {
region: 'us-east-1',
dbClusterIdentifier: 'aurora-cluster-id',
databaseName: 'myDatabaseName',
schema: 'mySchema',
awsSecretStoreArn: 'arn:aws:secretsmanager:us-east-1:123456789012:secret:rds-cluster-secret-XuztPa',
serviceRoleArn: 'arn:aws:iam::123456789012:role/service-role/myRelationalDbRole',
},
},
{
type: 'AMAZON_ELASTICSEARCH',
name: 'ElasticSearchSource',
description: 'My ElasticSearch Source',
config: {
serviceRoleArn: 'arn:aws:iam::123456789012:role/service-role/myEsRole',
region: 'us-east-1',
endpoint: 'https://search-my-domain-abcdefghijklmnop.us-east-1.es.amazonaws.com',
},
},
{
type: 'HTTP',
name: 'HTTPSource',
description: 'My HTTP Source',
config: {
serviceRoleArn: 'arn:aws:iam::123456789012:role/service-role/myHTTPRole',
region: 'us-east-1',
endpoint: 'https://www.example.com/api',
},
},
],
},
);
const roles = plugin.getDataSourceIamRolesResouces(config);
expect(roles).toEqual({});
});
test('Datasources of type NONE or HTTP should not generate any default role', () => {
Object.assign(
config,
{
dataSources: [
{
type: 'NONE',
name: 'NoneSource',
},
{
type: 'HTTP',
name: 'HttpSource',
config: {
endpoint: 'https://www.example.com/api',
},
},
],
},
);
const roles = plugin.getDataSourceIamRolesResouces(config);
expect(roles).toEqual({});
});
describe('template substitutions', () => {
test('Templates with substitutions should be transformed into Fn::Join with Fn::Sub objects', () => {
const template = '#set($partitionKey = "${globalPK}")\n' +
'{\n' +
'"version" : "2018-05-29",\n' +
'"operation" : "GetItem",\n' +
'"key" : {\n' +
'"partitionKey": { "S": "${globalPK}" },\n' +
'"sortKey": { "S": "${globalSK}" },\n' +
'}\n' +
'}';
const variables =
{
globalPK: 'PK',
globalSK: 'SK',
};
const transformedTemplate = plugin.substituteGlobalTemplateVariables(template, variables);
expect(transformedTemplate).toMatchSnapshot();
});
});
describe('individual template substitutions', () => {
test('Substitutions for individual template should override global substitutions.', () => {
const template = '#set($partitionKey = "${globalPK}")\n' +
'{\n' +
'"version" : "2018-05-29",\n' +
'"operation" : "GetItem",\n' +
'"key" : {\n' +
'"partitionKey": { "S": "${globalPK}" },\n' +
'"sortKey": { "S": "${globalSK}" },\n' +
'}\n' +
'}';
const configuration =
{
substitutions:
{
globalPK: 'WrongValue',
globalSK: 'WrongValue',
},
};
const individualSubstitutions =
{
globalPK: 'PK',
globalSK: 'SK',
};
const transformedTemplate = plugin.processTemplate(
template,
configuration,
individualSubstitutions,
);
expect(transformedTemplate).toMatchSnapshot();
});
});
});