@friggframework/devtools 2.0.0--canary.461.ec909cf.0 → 2.0.0--canary.461.7b36f0f.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/frigg-cli/__tests__/unit/commands/build.test.js +6 -6
  2. package/frigg-cli/build-command/index.js +1 -1
  3. package/frigg-cli/deploy-command/index.js +6 -6
  4. package/frigg-cli/generate-command/index.js +2 -2
  5. package/frigg-cli/generate-iam-command.js +10 -10
  6. package/frigg-cli/start-command/index.js +1 -1
  7. package/frigg-cli/start-command/start-command.test.js +3 -3
  8. package/frigg-cli/utils/database-validator.js +14 -21
  9. package/infrastructure/REFACTOR.md +532 -0
  10. package/infrastructure/TRANSFORMATION-VISUAL.md +239 -0
  11. package/infrastructure/__tests__/postgres-config.test.js +1 -1
  12. package/infrastructure/create-frigg-infrastructure.js +1 -1
  13. package/infrastructure/{DEPLOYMENT-INSTRUCTIONS.md → docs/deployment-instructions.md} +3 -3
  14. package/infrastructure/{IAM-POLICY-TEMPLATES.md → docs/iam-policy-templates.md} +9 -10
  15. package/infrastructure/domains/database/aurora-discovery.js +81 -0
  16. package/infrastructure/domains/database/aurora-discovery.test.js +188 -0
  17. package/infrastructure/domains/integration/integration-builder.js +178 -0
  18. package/infrastructure/domains/integration/integration-builder.test.js +362 -0
  19. package/infrastructure/domains/integration/websocket-builder.js +69 -0
  20. package/infrastructure/domains/integration/websocket-builder.test.js +195 -0
  21. package/infrastructure/domains/networking/vpc-discovery.test.js +257 -0
  22. package/infrastructure/domains/parameters/ssm-builder.js +79 -0
  23. package/infrastructure/domains/parameters/ssm-builder.test.js +188 -0
  24. package/infrastructure/domains/parameters/ssm-discovery.js +84 -0
  25. package/infrastructure/domains/parameters/ssm-discovery.test.js +210 -0
  26. package/infrastructure/{iam-generator.js → domains/security/iam-generator.js} +2 -2
  27. package/infrastructure/domains/security/kms-builder.js +169 -0
  28. package/infrastructure/domains/security/kms-builder.test.js +354 -0
  29. package/infrastructure/domains/security/kms-discovery.js +80 -0
  30. package/infrastructure/domains/security/kms-discovery.test.js +176 -0
  31. package/infrastructure/domains/shared/base-builder.js +112 -0
  32. package/infrastructure/domains/shared/builder-orchestrator.js +212 -0
  33. package/infrastructure/domains/shared/builder-orchestrator.test.js +213 -0
  34. package/infrastructure/domains/shared/environment-builder.js +118 -0
  35. package/infrastructure/domains/shared/environment-builder.test.js +246 -0
  36. package/infrastructure/domains/shared/providers/aws-provider-adapter.test.js +366 -0
  37. package/infrastructure/domains/shared/providers/azure-provider-adapter.stub.js +93 -0
  38. package/infrastructure/domains/shared/providers/cloud-provider-adapter.js +136 -0
  39. package/infrastructure/domains/shared/providers/gcp-provider-adapter.stub.js +82 -0
  40. package/infrastructure/domains/shared/providers/provider-factory.js +108 -0
  41. package/infrastructure/domains/shared/providers/provider-factory.test.js +170 -0
  42. package/infrastructure/domains/shared/resource-discovery.js +132 -0
  43. package/infrastructure/domains/shared/resource-discovery.test.js +410 -0
  44. package/infrastructure/domains/shared/utilities/base-definition-factory.js.bak +338 -0
  45. package/infrastructure/domains/shared/utilities/base-definition-factory.test.js +248 -0
  46. package/infrastructure/domains/shared/utilities/handler-path-resolver.test.js +259 -0
  47. package/infrastructure/domains/shared/utilities/prisma-layer-manager.js +55 -0
  48. package/infrastructure/domains/shared/utilities/prisma-layer-manager.test.js +134 -0
  49. package/infrastructure/domains/shared/validation/env-validator.test.js +173 -0
  50. package/infrastructure/esbuild.config.js +53 -0
  51. package/infrastructure/infrastructure-composer.js +85 -0
  52. package/infrastructure/scripts/build-prisma-layer.js +60 -47
  53. package/infrastructure/{build-time-discovery.test.js → scripts/build-time-discovery.test.js} +5 -4
  54. package/layers/prisma/nodejs/package.json +8 -0
  55. package/management-ui/server/utils/environment/awsParameterStore.js +29 -18
  56. package/package.json +8 -8
  57. package/infrastructure/aws-discovery.js +0 -1704
  58. package/infrastructure/aws-discovery.test.js +0 -1666
  59. package/infrastructure/serverless-template.js +0 -2804
  60. package/infrastructure/serverless-template.test.js +0 -1897
  61. /package/infrastructure/{POSTGRES-CONFIGURATION.md → docs/POSTGRES-CONFIGURATION.md} +0 -0
  62. /package/infrastructure/{WEBSOCKET-CONFIGURATION.md → docs/WEBSOCKET-CONFIGURATION.md} +0 -0
  63. /package/infrastructure/{GENERATE-IAM-DOCS.md → docs/generate-iam-command.md} +0 -0
  64. /package/infrastructure/{iam-generator.test.js → domains/security/iam-generator.test.js} +0 -0
  65. /package/infrastructure/{frigg-deployment-iam-stack.yaml → domains/security/templates/frigg-deployment-iam-stack.yaml} +0 -0
  66. /package/infrastructure/{iam-policy-basic.json → domains/security/templates/iam-policy-basic.json} +0 -0
  67. /package/infrastructure/{iam-policy-full.json → domains/security/templates/iam-policy-full.json} +0 -0
  68. /package/infrastructure/{env-validator.js → domains/shared/validation/env-validator.js} +0 -0
  69. /package/infrastructure/{build-time-discovery.js → scripts/build-time-discovery.js} +0 -0
  70. /package/infrastructure/{run-discovery.js → scripts/run-discovery.js} +0 -0
@@ -1,1897 +0,0 @@
1
- const { composeServerlessDefinition } = require('./serverless-template');
2
-
3
- // Helper to build discovery responses with overridable fields
4
- const createDiscoveryResponse = (overrides = {}) => ({
5
- defaultVpcId: 'vpc-123456',
6
- vpcCidr: '172.31.0.0/16', // Provide VPC CIDR so security group fallbacks can be tested
7
- defaultSecurityGroupId: 'sg-123456',
8
- privateSubnetId1: 'subnet-123456',
9
- privateSubnetId2: 'subnet-789012',
10
- publicSubnetId: 'subnet-public', // Keep for backward compat
11
- publicSubnetId1: 'subnet-public-1',
12
- publicSubnetId2: 'subnet-public-2',
13
- defaultRouteTableId: 'rtb-123456',
14
- defaultKmsKeyId:
15
- 'arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012',
16
- existingNatGatewayId: 'nat-default123',
17
- ...overrides,
18
- });
19
-
20
- // Mock AWS Discovery to prevent actual AWS calls
21
- jest.mock('./aws-discovery', () => {
22
- return {
23
- AWSDiscovery: jest.fn().mockImplementation(() => ({
24
- discoverResources: jest
25
- .fn()
26
- .mockResolvedValue(createDiscoveryResponse()),
27
- })),
28
- };
29
- });
30
-
31
- const { AWSDiscovery } = require('./aws-discovery');
32
-
33
- describe('composeServerlessDefinition', () => {
34
- let mockIntegration;
35
-
36
- beforeEach(() => {
37
- AWSDiscovery.mockImplementation(() => ({
38
- discoverResources: jest
39
- .fn()
40
- .mockResolvedValue(createDiscoveryResponse()),
41
- }));
42
-
43
- mockIntegration = {
44
- Definition: {
45
- name: 'testIntegration'
46
- }
47
- };
48
-
49
- // Mock process.argv to avoid offline mode during tests
50
- process.argv = ['node', 'test'];
51
-
52
- // Clear AWS_REGION for tests
53
- delete process.env.AWS_REGION;
54
- });
55
-
56
- afterEach(() => {
57
- jest.restoreAllMocks();
58
- // Restore env
59
- delete process.env.AWS_REGION;
60
- delete process.env.FRIGG_SKIP_AWS_DISCOVERY;
61
- process.argv = ['node', 'test'];
62
- });
63
-
64
- describe('AWS discovery gating', () => {
65
- it('should skip AWS discovery when no features require it', async () => {
66
- AWSDiscovery.mockClear();
67
-
68
- const appDefinition = {
69
- integrations: [],
70
- vpc: { enable: false },
71
- encryption: { fieldLevelEncryptionMethod: 'aes' },
72
- ssm: { enable: false },
73
- };
74
-
75
- await composeServerlessDefinition(appDefinition);
76
-
77
- expect(AWSDiscovery).not.toHaveBeenCalled();
78
- });
79
-
80
- it('should run AWS discovery when VPC features are enabled', async () => {
81
- AWSDiscovery.mockClear();
82
-
83
- const appDefinition = {
84
- integrations: [],
85
- vpc: { enable: true },
86
- };
87
-
88
- await composeServerlessDefinition(appDefinition);
89
-
90
- expect(AWSDiscovery).toHaveBeenCalledTimes(1);
91
- });
92
-
93
- it('should skip AWS discovery when FRIGG_SKIP_AWS_DISCOVERY is set to true', async () => {
94
- AWSDiscovery.mockClear();
95
- process.env.FRIGG_SKIP_AWS_DISCOVERY = 'true';
96
-
97
- const appDefinition = {
98
- integrations: [],
99
- vpc: { enable: true },
100
- encryption: { fieldLevelEncryptionMethod: 'kms' },
101
- ssm: { enable: true },
102
- };
103
-
104
- await composeServerlessDefinition(appDefinition);
105
-
106
- expect(AWSDiscovery).not.toHaveBeenCalled();
107
- });
108
-
109
- it('should run AWS discovery when FRIGG_SKIP_AWS_DISCOVERY is not set', async () => {
110
- AWSDiscovery.mockClear();
111
- delete process.env.FRIGG_SKIP_AWS_DISCOVERY;
112
-
113
- const appDefinition = {
114
- integrations: [],
115
- vpc: { enable: true },
116
- };
117
-
118
- await composeServerlessDefinition(appDefinition);
119
-
120
- expect(AWSDiscovery).toHaveBeenCalledTimes(1);
121
- });
122
-
123
- it('should skip VPC configuration when FRIGG_SKIP_AWS_DISCOVERY is true', async () => {
124
- process.env.FRIGG_SKIP_AWS_DISCOVERY = 'true';
125
-
126
- const appDefinition = {
127
- integrations: [],
128
- vpc: { enable: true, management: 'discover' },
129
- };
130
-
131
- const result = await composeServerlessDefinition(appDefinition);
132
-
133
- // VPC configuration should not be present when skipped
134
- expect(result.provider.vpc).toBeUndefined();
135
- });
136
- });
137
-
138
- describe('Basic Configuration', () => {
139
- it('should create basic serverless definition with minimal app definition', async () => {
140
- const appDefinition = {
141
- name: 'test-app',
142
- integrations: []
143
- };
144
-
145
- const result = await composeServerlessDefinition(appDefinition);
146
-
147
- expect(result.service).toBe('test-app');
148
- expect(result.provider.name).toBe('aws');
149
- expect(result.provider.runtime).toBe('nodejs20.x');
150
- expect(result.provider.region).toBe('us-east-1');
151
- expect(result.provider.stage).toBe('${opt:stage}');
152
- expect(result.frameworkVersion).toBe('>=3.17.0');
153
- });
154
-
155
- it('should use default service name when name not provided', async () => {
156
- const appDefinition = {
157
- integrations: []
158
- };
159
-
160
- const result = await composeServerlessDefinition(appDefinition);
161
-
162
- expect(result.service).toBe('create-frigg-app');
163
- });
164
-
165
- it('should use custom provider when specified', async () => {
166
- const appDefinition = {
167
- provider: 'custom-provider',
168
- integrations: []
169
- };
170
-
171
- const result = await composeServerlessDefinition(appDefinition);
172
-
173
- expect(result.provider.name).toBe('custom-provider');
174
- });
175
-
176
- it('should use AWS_REGION environment variable when set', async () => {
177
- process.env.AWS_REGION = 'eu-west-1';
178
-
179
- const appDefinition = {
180
- name: 'test-app',
181
- integrations: []
182
- };
183
-
184
- const result = await composeServerlessDefinition(appDefinition);
185
-
186
- expect(result.provider.region).toBe('eu-west-1');
187
- expect(result.custom['serverless-offline-sqs'].region).toBe('eu-west-1');
188
- });
189
-
190
- it('should default to us-east-1 when AWS_REGION is not set', async () => {
191
- delete process.env.AWS_REGION;
192
-
193
- const appDefinition = {
194
- name: 'test-app',
195
- integrations: []
196
- };
197
-
198
- const result = await composeServerlessDefinition(appDefinition);
199
-
200
- expect(result.provider.region).toBe('us-east-1');
201
- expect(result.custom['serverless-offline-sqs'].region).toBe('us-east-1');
202
- });
203
- });
204
-
205
- describe('Environment variables', () => {
206
- it('should include only non-reserved environment flags', async () => {
207
- const appDefinition = {
208
- integrations: [],
209
- environment: {
210
- CUSTOM_FLAG: true,
211
- AWS_REGION: true,
212
- OPTIONAL_DISABLED: false,
213
- },
214
- };
215
-
216
- const result = await composeServerlessDefinition(appDefinition);
217
-
218
- expect(result.provider.environment.CUSTOM_FLAG).toBe("${env:CUSTOM_FLAG, ''}");
219
- expect(result.provider.environment).not.toHaveProperty('AWS_REGION');
220
- expect(result.provider.environment).not.toHaveProperty('OPTIONAL_DISABLED');
221
- });
222
-
223
- it('should ignore string-valued environment entries', async () => {
224
- const appDefinition = {
225
- integrations: [],
226
- environment: {
227
- CUSTOM_FLAG: 'enabled',
228
- },
229
- };
230
-
231
- const result = await composeServerlessDefinition(appDefinition);
232
-
233
- expect(result.provider.environment).not.toHaveProperty('CUSTOM_FLAG');
234
- });
235
- });
236
-
237
- describe('VPC Configuration', () => {
238
- it('should add VPC configuration when vpc.enable is true with discover mode', async () => {
239
- const appDefinition = {
240
- vpc: {
241
- enable: true,
242
- management: 'discover'
243
- },
244
- integrations: []
245
- };
246
-
247
- const result = await composeServerlessDefinition(appDefinition);
248
-
249
- expect(result.provider.vpc).toBeDefined();
250
- expect(result.provider.vpc.securityGroupIds).toEqual(['sg-123456']);
251
- expect(result.provider.vpc.subnetIds).toEqual(['subnet-123456', 'subnet-789012']);
252
- });
253
-
254
- it('should create new VPC infrastructure when management is create-new', async () => {
255
- const appDefinition = {
256
- vpc: {
257
- enable: true,
258
- management: 'create-new'
259
- },
260
- integrations: []
261
- };
262
-
263
- const result = await composeServerlessDefinition(appDefinition);
264
-
265
- expect(result.provider.vpc).toBeDefined();
266
- expect(result.provider.vpc.securityGroupIds).toEqual([{ Ref: 'FriggLambdaSecurityGroup' }]);
267
- expect(result.provider.vpc.subnetIds).toEqual([
268
- { Ref: 'FriggPrivateSubnet1' },
269
- { Ref: 'FriggPrivateSubnet2' }
270
- ]);
271
- expect(result.resources.Resources.FriggVPC).toBeDefined();
272
- expect(result.resources.Resources.FriggLambdaSecurityGroup).toBeDefined();
273
- });
274
-
275
- it('should use provided VPC resources when management is use-existing', async () => {
276
- const appDefinition = {
277
- vpc: {
278
- enable: true,
279
- management: 'use-existing',
280
- vpcId: 'vpc-custom123',
281
- subnets: {
282
- ids: ['subnet-custom1', 'subnet-custom2']
283
- }
284
- },
285
- integrations: []
286
- };
287
-
288
- const result = await composeServerlessDefinition(appDefinition);
289
-
290
- expect(result.provider.vpc).toBeDefined();
291
- expect(result.provider.vpc.subnetIds).toEqual(['subnet-custom1', 'subnet-custom2']);
292
- });
293
-
294
- // Test all 9 combinations of VPC and Subnet management modes
295
- it('should handle create-new VPC with create subnets', async () => {
296
- const appDefinition = {
297
- vpc: {
298
- enable: true,
299
- management: 'create-new',
300
- subnets: { management: 'create' }
301
- },
302
- integrations: []
303
- };
304
-
305
- const result = await composeServerlessDefinition(appDefinition);
306
-
307
- expect(result.resources.Resources.FriggVPC).toBeDefined();
308
- expect(result.resources.Resources.FriggPrivateSubnet1).toBeDefined();
309
- expect(result.resources.Resources.FriggPrivateSubnet2).toBeDefined();
310
- expect(result.provider.vpc.subnetIds).toEqual([
311
- { Ref: 'FriggPrivateSubnet1' },
312
- { Ref: 'FriggPrivateSubnet2' }
313
- ]);
314
- });
315
-
316
- it('should handle discover VPC with create subnets', async () => {
317
- const appDefinition = {
318
- vpc: {
319
- enable: true,
320
- management: 'discover',
321
- subnets: { management: 'create' }
322
- },
323
- integrations: []
324
- };
325
-
326
- const result = await composeServerlessDefinition(appDefinition);
327
-
328
- expect(result.resources.Resources.FriggVPC).toBeUndefined();
329
- expect(result.resources.Resources.FriggPrivateSubnet1).toBeDefined();
330
- expect(result.resources.Resources.FriggPrivateSubnet2).toBeDefined();
331
- expect(result.resources.Resources.FriggPrivateSubnet1.Properties.VpcId).toBe('vpc-123456');
332
- });
333
-
334
- it('should handle use-existing VPC with create subnets', async () => {
335
- const appDefinition = {
336
- vpc: {
337
- enable: true,
338
- management: 'use-existing',
339
- vpcId: 'vpc-existing123',
340
- subnets: { management: 'create' }
341
- },
342
- integrations: []
343
- };
344
-
345
- const result = await composeServerlessDefinition(appDefinition);
346
-
347
- expect(result.resources.Resources.FriggVPC).toBeUndefined();
348
- expect(result.resources.Resources.FriggPrivateSubnet1).toBeDefined();
349
- expect(result.resources.Resources.FriggPrivateSubnet2).toBeDefined();
350
- expect(result.resources.Resources.FriggPrivateSubnet1.Properties.VpcId).toBe('vpc-existing123');
351
- });
352
-
353
- it('should handle use-existing VPC with use-existing subnets', async () => {
354
- const appDefinition = {
355
- vpc: {
356
- enable: true,
357
- management: 'use-existing',
358
- vpcId: 'vpc-custom',
359
- subnets: {
360
- management: 'use-existing',
361
- ids: ['subnet-explicit1', 'subnet-explicit2']
362
- }
363
- },
364
- integrations: []
365
- };
366
-
367
- const result = await composeServerlessDefinition(appDefinition);
368
-
369
- expect(result.resources.Resources.FriggPrivateSubnet1).toBeUndefined();
370
- expect(result.resources.Resources.FriggPrivateSubnet2).toBeUndefined();
371
- expect(result.provider.vpc.subnetIds).toEqual(['subnet-explicit1', 'subnet-explicit2']);
372
- });
373
-
374
- it('should respect provided security group IDs when supplied', async () => {
375
- const appDefinition = {
376
- vpc: {
377
- enable: true,
378
- management: 'discover',
379
- securityGroupIds: ['sg-custom-1', 'sg-custom-2'],
380
- },
381
- integrations: [],
382
- };
383
-
384
- const result = await composeServerlessDefinition(appDefinition);
385
-
386
- expect(result.provider.vpc.securityGroupIds).toEqual([
387
- 'sg-custom-1',
388
- 'sg-custom-2',
389
- ]);
390
- });
391
-
392
- it('should throw when discover mode finds no subnets and self-heal is disabled', async () => {
393
- const discoveryInstance = {
394
- discoverResources: jest.fn().mockResolvedValue(
395
- createDiscoveryResponse({
396
- privateSubnetId1: null,
397
- privateSubnetId2: null,
398
- })
399
- ),
400
- };
401
- AWSDiscovery.mockImplementation(() => discoveryInstance);
402
-
403
- const appDefinition = {
404
- vpc: {
405
- enable: true,
406
- management: 'discover',
407
- subnets: { management: 'discover' },
408
- },
409
- integrations: [],
410
- };
411
-
412
- await expect(composeServerlessDefinition(appDefinition)).rejects.toThrow(
413
- 'No subnets discovered and subnets.management is "discover". Either enable vpc.selfHeal, set subnets.management to "create", or provide subnet IDs.'
414
- );
415
- });
416
-
417
- it('should use Fn::Cidr for subnet CIDR blocks in new VPC to avoid conflicts', async () => {
418
- const appDefinition = {
419
- vpc: {
420
- enable: true,
421
- management: 'create-new',
422
- subnets: { management: 'create' }
423
- },
424
- integrations: []
425
- };
426
-
427
- const result = await composeServerlessDefinition(appDefinition);
428
-
429
- // Verify new VPC uses 10.0.0.0/16
430
- expect(result.resources.Resources.FriggVPC.Properties.CidrBlock).toBe('10.0.0.0/16');
431
-
432
- // Verify subnets use Fn::Cidr to generate non-conflicting CIDRs
433
- const subnet1Cidr = result.resources.Resources.FriggPrivateSubnet1.Properties.CidrBlock;
434
- const subnet2Cidr = result.resources.Resources.FriggPrivateSubnet2.Properties.CidrBlock;
435
- const publicSubnetCidr = result.resources.Resources.FriggPublicSubnet.Properties.CidrBlock;
436
-
437
- // Check that CIDRs are generated using Fn::Cidr and Fn::Select
438
- expect(subnet1Cidr).toHaveProperty('Fn::Select');
439
- expect(subnet1Cidr['Fn::Select'][0]).toBe(0);
440
- expect(subnet2Cidr).toHaveProperty('Fn::Select');
441
- expect(subnet2Cidr['Fn::Select'][0]).toBe(1);
442
- expect(publicSubnetCidr).toHaveProperty('Fn::Select');
443
- expect(publicSubnetCidr['Fn::Select'][0]).toBe(2);
444
- });
445
-
446
- it('should create route tables for subnets even without NAT Gateway management', async () => {
447
- const appDefinition = {
448
- vpc: {
449
- enable: true,
450
- management: 'create-new',
451
- subnets: { management: 'create' },
452
- natGateway: { management: 'discover' }
453
- },
454
- integrations: []
455
- };
456
-
457
- const result = await composeServerlessDefinition(appDefinition);
458
-
459
- // Verify route tables are created
460
- expect(result.resources.Resources.FriggPublicRouteTable).toBeDefined();
461
- expect(result.resources.Resources.FriggPublicRoute).toBeDefined();
462
- expect(result.resources.Resources.FriggLambdaRouteTable).toBeDefined();
463
-
464
- // Verify subnet associations
465
- expect(result.resources.Resources.FriggPublicSubnetRouteTableAssociation).toBeDefined();
466
- expect(result.resources.Resources.FriggPrivateSubnet1RouteTableAssociation).toBeDefined();
467
- expect(result.resources.Resources.FriggPrivateSubnet2RouteTableAssociation).toBeDefined();
468
- });
469
-
470
- it('should throw error when use-existing mode without vpcId', async () => {
471
- const appDefinition = {
472
- vpc: {
473
- enable: true,
474
- management: 'use-existing'
475
- },
476
- integrations: []
477
- };
478
-
479
- await expect(composeServerlessDefinition(appDefinition)).rejects.toThrow(
480
- 'VPC management is set to "use-existing" but no vpcId was provided'
481
- );
482
- });
483
-
484
- it('should default to discover mode when management not specified', async () => {
485
- const appDefinition = {
486
- vpc: { enable: true },
487
- integrations: []
488
- };
489
-
490
- const result = await composeServerlessDefinition(appDefinition);
491
-
492
- expect(result.provider.vpc).toBeDefined();
493
- expect(result.provider.vpc.securityGroupIds).toEqual(['sg-123456']);
494
- expect(result.provider.vpc.subnetIds).toEqual(['subnet-123456', 'subnet-789012']);
495
- });
496
-
497
- it('should add VPC endpoint for S3 when VPC is enabled', async () => {
498
- const appDefinition = {
499
- vpc: {
500
- enable: true,
501
- management: 'discover'
502
- },
503
- integrations: []
504
- };
505
-
506
- const result = await composeServerlessDefinition(appDefinition);
507
-
508
- expect(result.resources.Resources.VPCEndpointS3).toBeDefined();
509
- expect(result.resources.Resources.VPCEndpointS3.Type).toBe('AWS::EC2::VPCEndpoint');
510
- expect(result.resources.Resources.VPCEndpointS3.Properties.VpcId).toBe('vpc-123456');
511
- });
512
-
513
- it('should skip creating VPC endpoints when disabled explicitly', async () => {
514
- const appDefinition = {
515
- vpc: {
516
- enable: true,
517
- management: 'discover',
518
- enableVPCEndpoints: false,
519
- },
520
- integrations: [],
521
- };
522
-
523
- const result = await composeServerlessDefinition(appDefinition);
524
-
525
- expect(result.resources.Resources.VPCEndpointS3).toBeUndefined();
526
- expect(result.resources.Resources.VPCEndpointKMS).toBeUndefined();
527
- expect(result.resources.Resources.VPCEndpointSecretsManager).toBeUndefined();
528
- });
529
-
530
- it('should add Secrets Manager endpoint only when enabled', async () => {
531
- const appDefinition = {
532
- vpc: {
533
- enable: true,
534
- management: 'discover',
535
- },
536
- secretsManager: { enable: true },
537
- encryption: { fieldLevelEncryptionMethod: 'kms' },
538
- integrations: [],
539
- };
540
-
541
- const result = await composeServerlessDefinition(appDefinition);
542
-
543
- expect(result.resources.Resources.VPCEndpointSecretsManager).toBeDefined();
544
- });
545
-
546
- it('should allow Lambda security group access for VPC endpoints when security group is discovered', async () => {
547
- const appDefinition = {
548
- vpc: {
549
- enable: true,
550
- management: 'discover'
551
- },
552
- encryption: { fieldLevelEncryptionMethod: 'kms' },
553
- integrations: []
554
- };
555
-
556
- const result = await composeServerlessDefinition(appDefinition);
557
- const endpointSg = result.resources.Resources.VPCEndpointSecurityGroup;
558
-
559
- expect(endpointSg).toBeDefined();
560
- expect(endpointSg.Properties.SecurityGroupIngress).toEqual([
561
- {
562
- IpProtocol: 'tcp',
563
- FromPort: 443,
564
- ToPort: 443,
565
- SourceSecurityGroupId: 'sg-123456',
566
- Description: 'HTTPS from Lambda security group'
567
- }
568
- ]);
569
- });
570
-
571
- it('should fall back to VPC CIDR when Lambda security group identifier cannot be resolved', async () => {
572
- AWSDiscovery.mockImplementation(() => ({
573
- discoverResources: jest
574
- .fn()
575
- .mockResolvedValue(createDiscoveryResponse()),
576
- }));
577
-
578
- const appDefinition = {
579
- vpc: {
580
- enable: true,
581
- management: 'discover',
582
- securityGroupIds: [
583
- {
584
- 'Fn::ImportValue': 'shared-lambda-security-group',
585
- },
586
- ],
587
- },
588
- encryption: { fieldLevelEncryptionMethod: 'kms' },
589
- integrations: [],
590
- };
591
-
592
- const result = await composeServerlessDefinition(appDefinition);
593
- const endpointSg = result.resources.Resources.VPCEndpointSecurityGroup;
594
-
595
- expect(endpointSg).toBeDefined();
596
- expect(endpointSg.Properties.SecurityGroupIngress).toEqual([
597
- {
598
- IpProtocol: 'tcp',
599
- FromPort: 443,
600
- ToPort: 443,
601
- CidrIp: '172.31.0.0/16',
602
- Description: 'HTTPS from VPC CIDR (fallback)',
603
- },
604
- ]);
605
- });
606
-
607
- it('should fall back to default private ranges when neither Lambda security group nor VPC CIDR is available', async () => {
608
- AWSDiscovery.mockImplementation(() => ({
609
- discoverResources: jest
610
- .fn()
611
- .mockResolvedValue(
612
- createDiscoveryResponse({ vpcCidr: null })
613
- ),
614
- }));
615
-
616
- const appDefinition = {
617
- vpc: {
618
- enable: true,
619
- management: 'discover',
620
- securityGroupIds: [
621
- {
622
- 'Fn::ImportValue': 'shared-lambda-security-group',
623
- },
624
- ],
625
- },
626
- encryption: { fieldLevelEncryptionMethod: 'kms' },
627
- integrations: [],
628
- };
629
-
630
- const result = await composeServerlessDefinition(appDefinition);
631
- const endpointSg = result.resources.Resources.VPCEndpointSecurityGroup;
632
-
633
- expect(endpointSg).toBeDefined();
634
- expect(endpointSg.Properties.SecurityGroupIngress).toEqual([
635
- {
636
- IpProtocol: 'tcp',
637
- FromPort: 443,
638
- ToPort: 443,
639
- CidrIp: '172.31.0.0/16',
640
- Description: 'HTTPS from default VPC range',
641
- },
642
- ]);
643
- });
644
-
645
- it('should reference the Lambda security group when creating a new VPC', async () => {
646
- const appDefinition = {
647
- vpc: {
648
- enable: true,
649
- management: 'create-new'
650
- },
651
- encryption: { fieldLevelEncryptionMethod: 'kms' },
652
- integrations: []
653
- };
654
-
655
- const result = await composeServerlessDefinition(appDefinition);
656
- const endpointSg = result.resources.Resources.FriggVPCEndpointSecurityGroup;
657
-
658
- expect(endpointSg).toBeDefined();
659
- expect(endpointSg.Properties.SecurityGroupIngress).toEqual([
660
- {
661
- IpProtocol: 'tcp',
662
- FromPort: 443,
663
- ToPort: 443,
664
- SourceSecurityGroupId: { Ref: 'FriggLambdaSecurityGroup' },
665
- Description: 'HTTPS from Lambda security group'
666
- },
667
- {
668
- IpProtocol: 'tcp',
669
- FromPort: 443,
670
- ToPort: 443,
671
- CidrIp: '10.0.0.0/16',
672
- Description: 'HTTPS from VPC CIDR (fallback)'
673
- }
674
- ]);
675
- });
676
-
677
- it('should not add VPC configuration when vpc.enable is false', async () => {
678
- const appDefinition = {
679
- vpc: { enable: false },
680
- integrations: []
681
- };
682
-
683
- const result = await composeServerlessDefinition(appDefinition);
684
-
685
- expect(result.provider.vpc).toBeUndefined();
686
- expect(result.resources.Resources.VPCEndpointS3).toBeUndefined();
687
- });
688
-
689
- it('should not add VPC configuration when vpc is not defined', async () => {
690
- const appDefinition = {
691
- integrations: []
692
- };
693
-
694
- const result = await composeServerlessDefinition(appDefinition);
695
-
696
- expect(result.provider.vpc).toBeUndefined();
697
- });
698
- });
699
-
700
- describe('NAT Gateway behaviour', () => {
701
- it('should reuse discovered NAT gateway in discover mode without creating new resources', async () => {
702
- const discoveryInstance = {
703
- discoverResources: jest.fn().mockResolvedValue(
704
- createDiscoveryResponse({
705
- existingNatGatewayId: 'nat-existing123',
706
- natGatewayInPrivateSubnet: false,
707
- })
708
- ),
709
- };
710
- AWSDiscovery.mockImplementation(() => discoveryInstance);
711
-
712
- const appDefinition = {
713
- vpc: {
714
- enable: true,
715
- management: 'discover',
716
- natGateway: { management: 'discover' },
717
- },
718
- integrations: [],
719
- };
720
-
721
- const result = await composeServerlessDefinition(appDefinition);
722
-
723
- expect(result.resources.Resources.FriggNATGateway).toBeUndefined();
724
- expect(result.resources.Resources.FriggNATRoute).toBeDefined();
725
- });
726
-
727
- it('should reference provided NAT gateway when management set to useExisting', async () => {
728
- const discoveryInstance = {
729
- discoverResources: jest.fn().mockResolvedValue(
730
- createDiscoveryResponse({ existingNatGatewayId: null })
731
- ),
732
- };
733
- AWSDiscovery.mockImplementation(() => discoveryInstance);
734
-
735
- const appDefinition = {
736
- vpc: {
737
- enable: true,
738
- management: 'discover',
739
- natGateway: { management: 'useExisting', id: 'nat-custom-001' },
740
- },
741
- integrations: [],
742
- };
743
-
744
- const result = await composeServerlessDefinition(appDefinition);
745
-
746
- expect(result.resources.Resources.FriggNATGateway).toBeUndefined();
747
- expect(result.resources.Resources.FriggNATRoute.Properties.NatGatewayId).toBe('nat-custom-001');
748
- });
749
-
750
- it('should reuse existing elastic IP allocation when creating managed NAT', async () => {
751
- const discoveryInstance = {
752
- discoverResources: jest.fn().mockResolvedValue(
753
- createDiscoveryResponse({
754
- existingNatGatewayId: null,
755
- existingElasticIpAllocationId: 'eip-alloc-123',
756
- })
757
- ),
758
- };
759
- AWSDiscovery.mockImplementation(() => discoveryInstance);
760
-
761
- const appDefinition = {
762
- vpc: {
763
- enable: true,
764
- management: 'discover',
765
- natGateway: { management: 'createAndManage' },
766
- selfHeal: true,
767
- },
768
- integrations: [],
769
- };
770
-
771
- const result = await composeServerlessDefinition(appDefinition);
772
-
773
- expect(result.resources.Resources.FriggNATGatewayEIP).toBeUndefined();
774
- expect(result.resources.Resources.FriggNATGateway.Properties.AllocationId).toBe(
775
- 'eip-alloc-123'
776
- );
777
- });
778
-
779
- it('should create a public subnet when discovery provides none', async () => {
780
- const discoveryInstance = {
781
- discoverResources: jest.fn().mockResolvedValue(
782
- createDiscoveryResponse({
783
- publicSubnetId: null,
784
- internetGatewayId: null,
785
- existingNatGatewayId: null,
786
- })
787
- ),
788
- };
789
- AWSDiscovery.mockImplementation(() => discoveryInstance);
790
-
791
- const appDefinition = {
792
- vpc: {
793
- enable: true,
794
- management: 'discover',
795
- natGateway: { management: 'createAndManage' },
796
- selfHeal: true,
797
- },
798
- integrations: [],
799
- };
800
-
801
- const result = await composeServerlessDefinition(appDefinition);
802
-
803
- expect(result.resources.Resources.FriggPublicSubnet).toBeDefined();
804
- expect(result.resources.Resources.FriggPublicRouteTable).toBeDefined();
805
- });
806
- });
807
-
808
- describe('KMS Configuration', () => {
809
- it('should add KMS configuration when encryption is enabled and key is found', async () => {
810
- const appDefinition = {
811
- encryption: { fieldLevelEncryptionMethod: 'kms' },
812
- integrations: []
813
- };
814
-
815
- const result = await composeServerlessDefinition(appDefinition);
816
-
817
- // Check IAM permissions
818
- const kmsPermission = result.provider.iamRoleStatements.find(
819
- statement => statement.Action.includes('kms:GenerateDataKey')
820
- );
821
- expect(kmsPermission).toEqual({
822
- Effect: 'Allow',
823
- Action: [
824
- 'kms:GenerateDataKey',
825
- 'kms:Decrypt'
826
- ],
827
- Resource: ['arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012']
828
- });
829
-
830
- // Check environment variable
831
- expect(result.provider.environment.KMS_KEY_ARN).toBe('arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012');
832
-
833
- // Check plugin
834
- expect(result.plugins).toContain('serverless-kms-grants');
835
-
836
- // Check custom configuration
837
- expect(result.custom.kmsGrants).toEqual({
838
- kmsKeyId: 'arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012'
839
- });
840
-
841
- // Check KMS Alias resource is created for discovered key
842
- expect(result.resources.Resources.FriggKMSKeyAlias).toBeDefined();
843
- expect(result.resources.Resources.FriggKMSKeyAlias).toEqual({
844
- Type: 'AWS::KMS::Alias',
845
- DeletionPolicy: 'Retain',
846
- Properties: {
847
- AliasName: 'alias/${self:service}-${self:provider.stage}-frigg-kms',
848
- TargetKeyId: 'arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012'
849
- }
850
- });
851
- });
852
-
853
- it('should create new KMS key when encryption is enabled, no key found, and createResourceIfNoneFound is true', async () => {
854
- // Mock AWS discovery to return no KMS key
855
- const { AWSDiscovery } = require('./aws-discovery');
856
- const mockDiscoverResources = jest.fn().mockResolvedValue({
857
- defaultVpcId: 'vpc-123456',
858
- defaultSecurityGroupId: 'sg-123456',
859
- privateSubnetId1: 'subnet-123456',
860
- privateSubnetId2: 'subnet-789012',
861
- publicSubnetId: 'subnet-public',
862
- defaultRouteTableId: 'rtb-123456',
863
- defaultKmsKeyId: null // No KMS key found
864
- });
865
- AWSDiscovery.mockImplementation(() => ({
866
- discoverResources: mockDiscoverResources
867
- }));
868
-
869
- const appDefinition = {
870
- encryption: {
871
- fieldLevelEncryptionMethod: 'kms',
872
- createResourceIfNoneFound: true
873
- },
874
- integrations: []
875
- };
876
-
877
- const result = await composeServerlessDefinition(appDefinition);
878
-
879
- // Check that KMS key resource was created with DeletionPolicy
880
- expect(result.resources.Resources.FriggKMSKey).toEqual({
881
- Type: 'AWS::KMS::Key',
882
- DeletionPolicy: 'Retain',
883
- UpdateReplacePolicy: 'Retain',
884
- Properties: {
885
- EnableKeyRotation: true,
886
- Description: 'Frigg KMS key for field-level encryption',
887
- KeyPolicy: {
888
- Version: '2012-10-17',
889
- Statement: [
890
- {
891
- Sid: 'AllowRootAccountAdmin',
892
- Effect: 'Allow',
893
- Principal: {
894
- AWS: {
895
- 'Fn::Sub': 'arn:aws:iam::${AWS::AccountId}:root'
896
- }
897
- },
898
- Action: 'kms:*',
899
- Resource: '*'
900
- },
901
- {
902
- Sid: 'AllowLambdaService',
903
- Effect: 'Allow',
904
- Principal: {
905
- Service: 'lambda.amazonaws.com'
906
- },
907
- Action: [
908
- 'kms:GenerateDataKey',
909
- 'kms:Decrypt',
910
- 'kms:DescribeKey'
911
- ],
912
- Resource: '*',
913
- Condition: {
914
- StringEquals: {
915
- 'kms:ViaService': 'lambda.us-east-1.amazonaws.com'
916
- }
917
- }
918
- }
919
- ]
920
- },
921
- Tags: [
922
- {
923
- Key: 'Name',
924
- Value: '${self:service}-${self:provider.stage}-frigg-kms-key'
925
- },
926
- {
927
- Key: 'ManagedBy',
928
- Value: 'Frigg'
929
- },
930
- {
931
- Key: 'Purpose',
932
- Value: 'Field-level encryption for Frigg application'
933
- }
934
- ]
935
- }
936
- });
937
-
938
- // Check KMS Alias resource is created for the new key
939
- expect(result.resources.Resources.FriggKMSKeyAlias).toBeDefined();
940
- expect(result.resources.Resources.FriggKMSKeyAlias).toEqual({
941
- Type: 'AWS::KMS::Alias',
942
- DeletionPolicy: 'Retain',
943
- Properties: {
944
- AliasName: 'alias/${self:service}-${self:provider.stage}-frigg-kms',
945
- TargetKeyId: { 'Fn::GetAtt': ['FriggKMSKey', 'Arn'] }
946
- }
947
- });
948
-
949
- // Check IAM permissions for the new key
950
- const kmsPermission = result.provider.iamRoleStatements.find(
951
- statement => statement.Action.includes('kms:GenerateDataKey')
952
- );
953
- expect(kmsPermission).toEqual({
954
- Effect: 'Allow',
955
- Action: ['kms:GenerateDataKey', 'kms:Decrypt'],
956
- Resource: [{ 'Fn::GetAtt': ['FriggKMSKey', 'Arn'] }]
957
- });
958
-
959
- // Check environment variable
960
- expect(result.provider.environment.KMS_KEY_ARN).toEqual({
961
- 'Fn::GetAtt': ['FriggKMSKey', 'Arn']
962
- });
963
-
964
- // Check plugin
965
- expect(result.plugins).toContain('serverless-kms-grants');
966
-
967
- // Check custom configuration
968
- // When creating a new key, it should reference the CloudFormation resource
969
- expect(result.custom.kmsGrants).toEqual({
970
- kmsKeyId: { 'Fn::GetAtt': ['FriggKMSKey', 'Arn'] }
971
- });
972
- });
973
-
974
- it('should throw error when encryption is enabled, no key found, and createResourceIfNoneFound is false', async () => {
975
- // Mock AWS discovery to return no KMS key
976
- const { AWSDiscovery } = require('./aws-discovery');
977
- const mockDiscoverResources = jest.fn().mockResolvedValue({
978
- defaultVpcId: 'vpc-123456',
979
- defaultSecurityGroupId: 'sg-123456',
980
- privateSubnetId1: 'subnet-123456',
981
- privateSubnetId2: 'subnet-789012',
982
- publicSubnetId: 'subnet-public',
983
- defaultRouteTableId: 'rtb-123456',
984
- defaultKmsKeyId: null // No KMS key found
985
- });
986
- AWSDiscovery.mockImplementation(() => ({
987
- discoverResources: mockDiscoverResources
988
- }));
989
-
990
- const appDefinition = {
991
- encryption: {
992
- fieldLevelEncryptionMethod: 'kms',
993
- createResourceIfNoneFound: false
994
- },
995
- integrations: []
996
- };
997
-
998
- await expect(composeServerlessDefinition(appDefinition)).rejects.toThrow(
999
- 'KMS field-level encryption is enabled but no KMS key was found. ' +
1000
- 'Either provide an existing KMS key or set encryption.createResourceIfNoneFound to true to create a new key.'
1001
- );
1002
- });
1003
-
1004
- it('should throw error when encryption is enabled, no key found, and createResourceIfNoneFound is not specified', async () => {
1005
- // Mock AWS discovery to return no KMS key
1006
- const { AWSDiscovery } = require('./aws-discovery');
1007
- const mockDiscoverResources = jest.fn().mockResolvedValue({
1008
- defaultVpcId: 'vpc-123456',
1009
- defaultSecurityGroupId: 'sg-123456',
1010
- privateSubnetId1: 'subnet-123456',
1011
- privateSubnetId2: 'subnet-789012',
1012
- publicSubnetId: 'subnet-public',
1013
- defaultRouteTableId: 'rtb-123456',
1014
- defaultKmsKeyId: null // No KMS key found
1015
- });
1016
- AWSDiscovery.mockImplementation(() => ({
1017
- discoverResources: mockDiscoverResources
1018
- }));
1019
-
1020
- const appDefinition = {
1021
- encryption: {
1022
- fieldLevelEncryptionMethod: 'kms'
1023
- // createResourceIfNoneFound not specified, defaults to false
1024
- },
1025
- integrations: []
1026
- };
1027
-
1028
- await expect(composeServerlessDefinition(appDefinition)).rejects.toThrow(
1029
- 'KMS field-level encryption is enabled but no KMS key was found. ' +
1030
- 'Either provide an existing KMS key or set encryption.createResourceIfNoneFound to true to create a new key.'
1031
- );
1032
- });
1033
-
1034
- it('should not add KMS configuration when encryption is disabled', async () => {
1035
- const appDefinition = {
1036
- encryption: { fieldLevelEncryptionMethod: 'aes' },
1037
- integrations: []
1038
- };
1039
-
1040
- const result = await composeServerlessDefinition(appDefinition);
1041
-
1042
- const kmsPermission = result.provider.iamRoleStatements.find(
1043
- statement => statement.Action && statement.Action.includes('kms:GenerateDataKey')
1044
- );
1045
- expect(kmsPermission).toBeUndefined();
1046
- expect(result.provider.environment.KMS_KEY_ARN).toBeUndefined();
1047
- expect(result.plugins).not.toContain('serverless-kms-grants');
1048
- expect(result.custom.kmsGrants).toBeUndefined();
1049
- });
1050
-
1051
- it('should not add KMS configuration when encryption is not defined', async () => {
1052
- const appDefinition = {
1053
- integrations: []
1054
- };
1055
-
1056
- const result = await composeServerlessDefinition(appDefinition);
1057
-
1058
- const kmsPermission = result.provider.iamRoleStatements.find(
1059
- statement => statement.Action && statement.Action.includes('kms:GenerateDataKey')
1060
- );
1061
- expect(kmsPermission).toBeUndefined();
1062
- expect(result.custom.kmsGrants).toBeUndefined();
1063
- });
1064
- });
1065
-
1066
- describe('SSM Configuration', () => {
1067
- it('should add SSM configuration when ssm.enable is true', async () => {
1068
- const appDefinition = {
1069
- ssm: { enable: true },
1070
- integrations: []
1071
- };
1072
-
1073
- const result = await composeServerlessDefinition(appDefinition);
1074
-
1075
- // Check lambda layers
1076
- expect(result.provider.layers).toEqual([
1077
- 'arn:aws:lambda:${self:provider.region}:177933569100:layer:AWS-Parameters-and-Secrets-Lambda-Extension:11'
1078
- ]);
1079
-
1080
- // Check IAM permissions
1081
- const ssmPermission = result.provider.iamRoleStatements.find(
1082
- statement => statement.Action.includes('ssm:GetParameter')
1083
- );
1084
- expect(ssmPermission).toEqual({
1085
- Effect: 'Allow',
1086
- Action: [
1087
- 'ssm:GetParameter',
1088
- 'ssm:GetParameters',
1089
- 'ssm:GetParametersByPath'
1090
- ],
1091
- Resource: [
1092
- 'arn:aws:ssm:${self:provider.region}:*:parameter/${self:service}/${self:provider.stage}/*'
1093
- ]
1094
- });
1095
-
1096
- // Check environment variable
1097
- expect(result.provider.environment.SSM_PARAMETER_PREFIX).toBe('/${self:service}/${self:provider.stage}');
1098
- });
1099
-
1100
- it('should not add SSM configuration when ssm.enable is false', async () => {
1101
- const appDefinition = {
1102
- ssm: { enable: false },
1103
- integrations: []
1104
- };
1105
-
1106
- const result = await composeServerlessDefinition(appDefinition);
1107
-
1108
- expect(result.provider.layers).toBeUndefined();
1109
-
1110
- const ssmPermission = result.provider.iamRoleStatements.find(
1111
- statement => statement.Action && statement.Action.includes('ssm:GetParameter')
1112
- );
1113
- expect(ssmPermission).toBeUndefined();
1114
- expect(result.provider.environment.SSM_PARAMETER_PREFIX).toBeUndefined();
1115
- });
1116
-
1117
- it('should not add SSM configuration when ssm is not defined', async () => {
1118
- const appDefinition = {
1119
- integrations: []
1120
- };
1121
-
1122
- const result = await composeServerlessDefinition(appDefinition);
1123
-
1124
- expect(result.provider.layers).toBeUndefined();
1125
- expect(result.provider.environment.SSM_PARAMETER_PREFIX).toBeUndefined();
1126
- });
1127
- });
1128
-
1129
- describe('Integration Configuration', () => {
1130
- it('should add integration-specific resources and functions', async () => {
1131
- const appDefinition = {
1132
- integrations: [mockIntegration]
1133
- };
1134
-
1135
- const result = await composeServerlessDefinition(appDefinition);
1136
-
1137
- // Check integration function
1138
- expect(result.functions.testIntegration).toEqual({
1139
- handler: 'node_modules/@friggframework/core/handlers/routers/integration-defined-routers.handlers.testIntegration.handler',
1140
- events: [{
1141
- httpApi: {
1142
- path: '/api/testIntegration-integration/{proxy+}',
1143
- method: 'ANY'
1144
- }
1145
- }]
1146
- });
1147
-
1148
- // Check SQS Queue
1149
- expect(result.resources.Resources.TestIntegrationQueue).toEqual({
1150
- Type: 'AWS::SQS::Queue',
1151
- Properties: {
1152
- QueueName: '${self:custom.TestIntegrationQueue}',
1153
- MessageRetentionPeriod: 60,
1154
- VisibilityTimeout: 1800,
1155
- RedrivePolicy: {
1156
- maxReceiveCount: 1,
1157
- deadLetterTargetArn: {
1158
- 'Fn::GetAtt': ['InternalErrorQueue', 'Arn']
1159
- }
1160
- }
1161
- }
1162
- });
1163
-
1164
- // Check Queue Worker
1165
- expect(result.functions.testIntegrationQueueWorker).toEqual({
1166
- handler: 'node_modules/@friggframework/core/handlers/workers/integration-defined-workers.handlers.testIntegration.queueWorker',
1167
- reservedConcurrency: 5,
1168
- events: [{
1169
- sqs: {
1170
- arn: {
1171
- 'Fn::GetAtt': ['TestIntegrationQueue', 'Arn']
1172
- },
1173
- batchSize: 1
1174
- }
1175
- }],
1176
- timeout: 600
1177
- });
1178
-
1179
- // Check environment variable
1180
- expect(result.provider.environment.TESTINTEGRATION_QUEUE_URL).toEqual({
1181
- Ref: 'TestIntegrationQueue'
1182
- });
1183
-
1184
- // Check custom queue name
1185
- expect(result.custom.TestIntegrationQueue).toBe('${self:service}--${self:provider.stage}-TestIntegrationQueue');
1186
- });
1187
-
1188
- it('should handle multiple integrations', async () => {
1189
- const secondIntegration = {
1190
- Definition: {
1191
- name: 'secondIntegration'
1192
- }
1193
- };
1194
-
1195
- const appDefinition = {
1196
- integrations: [mockIntegration, secondIntegration]
1197
- };
1198
-
1199
- const result = await composeServerlessDefinition(appDefinition);
1200
-
1201
- expect(result.functions.testIntegration).toBeDefined();
1202
- expect(result.functions.secondIntegration).toBeDefined();
1203
- expect(result.functions.testIntegrationQueueWorker).toBeDefined();
1204
- expect(result.functions.secondIntegrationQueueWorker).toBeDefined();
1205
- expect(result.resources.Resources.TestIntegrationQueue).toBeDefined();
1206
- expect(result.resources.Resources.SecondIntegrationQueue).toBeDefined();
1207
- });
1208
- });
1209
-
1210
- describe('Handler path adjustments', () => {
1211
- const fs = require('fs');
1212
- const path = require('path');
1213
-
1214
- it('should rewrite handler paths in offline mode', async () => {
1215
- process.argv = ['node', 'test', 'offline'];
1216
- const existsSpy = jest.spyOn(fs, 'existsSync');
1217
- const fallbackNodeModules = path.resolve(process.cwd(), '..', 'node_modules');
1218
- existsSpy.mockImplementation((p) => p === fallbackNodeModules);
1219
-
1220
- const appDefinition = { integrations: [] };
1221
-
1222
- const result = await composeServerlessDefinition(appDefinition);
1223
-
1224
- expect(existsSpy).toHaveBeenCalled();
1225
- expect(result.functions.auth.handler.startsWith('../node_modules/')).toBe(true);
1226
-
1227
- existsSpy.mockRestore();
1228
- });
1229
- });
1230
-
1231
- describe('NAT Gateway Management', () => {
1232
- it('should handle NAT Gateway with createAndManage mode', async () => {
1233
- const appDefinition = {
1234
- vpc: {
1235
- enable: true,
1236
- management: 'discover',
1237
- natGateway: {
1238
- management: 'createAndManage'
1239
- }
1240
- },
1241
- integrations: []
1242
- };
1243
-
1244
- const result = await composeServerlessDefinition(appDefinition);
1245
-
1246
- expect(result.resources.Resources.FriggLambdaRouteTable).toBeDefined();
1247
- expect(result.resources.Resources.FriggNATRoute).toBeDefined();
1248
- });
1249
-
1250
- it('should mark managed NAT Gateway resources for retention', async () => {
1251
- const appDefinition = {
1252
- vpc: {
1253
- enable: true,
1254
- management: 'discover',
1255
- natGateway: { management: 'createAndManage' },
1256
- selfHeal: true,
1257
- },
1258
- integrations: [],
1259
- };
1260
-
1261
- const result = await composeServerlessDefinition(appDefinition);
1262
-
1263
- expect(result.resources.Resources.FriggNATGateway).toBeDefined();
1264
- expect(result.resources.Resources.FriggNATGateway.DeletionPolicy).toBe('Retain');
1265
- expect(result.resources.Resources.FriggNATGateway.UpdateReplacePolicy).toBe('Retain');
1266
- });
1267
-
1268
- it('should handle NAT Gateway with discover mode', async () => {
1269
- // Mock discovery to return existing NAT Gateway
1270
- const { AWSDiscovery } = require('./aws-discovery');
1271
- const mockDiscoverResources = jest.fn().mockResolvedValue({
1272
- defaultVpcId: 'vpc-123456',
1273
- defaultSecurityGroupId: 'sg-123456',
1274
- privateSubnetId1: 'subnet-123456',
1275
- privateSubnetId2: 'subnet-789012',
1276
- publicSubnetId: 'subnet-public',
1277
- defaultRouteTableId: 'rtb-123456',
1278
- defaultKmsKeyId: null,
1279
- existingNatGatewayId: 'nat-existing123'
1280
- });
1281
- AWSDiscovery.mockImplementation(() => ({
1282
- discoverResources: mockDiscoverResources
1283
- }));
1284
-
1285
- const appDefinition = {
1286
- vpc: {
1287
- enable: true,
1288
- management: 'discover',
1289
- natGateway: {
1290
- management: 'discover'
1291
- }
1292
- },
1293
- integrations: []
1294
- };
1295
-
1296
- const result = await composeServerlessDefinition(appDefinition);
1297
-
1298
- expect(result.resources.Resources.FriggNATRoute).toBeDefined();
1299
- expect(result.resources.Resources.FriggNATRoute.Properties.NatGatewayId).toBe('nat-existing123');
1300
- });
1301
-
1302
- it('should handle NAT Gateway with useExisting mode and provided ID', async () => {
1303
- const appDefinition = {
1304
- vpc: {
1305
- enable: true,
1306
- management: 'discover',
1307
- natGateway: {
1308
- management: 'useExisting',
1309
- id: 'nat-custom456'
1310
- }
1311
- },
1312
- integrations: []
1313
- };
1314
-
1315
- const result = await composeServerlessDefinition(appDefinition);
1316
-
1317
- expect(result.resources.Resources.FriggNATRoute).toBeDefined();
1318
- expect(result.resources.Resources.FriggNATRoute.Properties.NatGatewayId).toBe('nat-custom456');
1319
- });
1320
-
1321
- it('should throw error when NAT Gateway not found in discover mode', async () => {
1322
- // Mock discovery to return no NAT Gateway
1323
- const { AWSDiscovery } = require('./aws-discovery');
1324
- const mockDiscoverResources = jest.fn().mockResolvedValue({
1325
- defaultVpcId: 'vpc-123456',
1326
- defaultSecurityGroupId: 'sg-123456',
1327
- privateSubnetId1: 'subnet-123456',
1328
- privateSubnetId2: 'subnet-789012',
1329
- publicSubnetId: 'subnet-public',
1330
- defaultRouteTableId: 'rtb-123456',
1331
- defaultKmsKeyId: null,
1332
- existingNatGatewayId: null // No NAT Gateway
1333
- });
1334
- AWSDiscovery.mockImplementation(() => ({
1335
- discoverResources: mockDiscoverResources
1336
- }));
1337
-
1338
- const appDefinition = {
1339
- vpc: {
1340
- enable: true,
1341
- management: 'discover',
1342
- natGateway: {
1343
- management: 'discover'
1344
- }
1345
- },
1346
- integrations: []
1347
- };
1348
-
1349
- await expect(composeServerlessDefinition(appDefinition)).rejects.toThrow(
1350
- 'No existing NAT Gateway found in discovery mode'
1351
- );
1352
- });
1353
-
1354
- it('should enable self-healing when selfHeal is true', async () => {
1355
- const appDefinition = {
1356
- vpc: {
1357
- enable: true,
1358
- management: 'discover',
1359
- natGateway: {
1360
- management: 'discover'
1361
- },
1362
- selfHeal: true
1363
- },
1364
- integrations: []
1365
- };
1366
-
1367
- const result = await composeServerlessDefinition(appDefinition);
1368
-
1369
- // With self-healing enabled, it should handle misconfigured NAT Gateways
1370
- expect(result.resources.Resources.FriggLambdaRouteTable).toBeDefined();
1371
- });
1372
- });
1373
-
1374
- describe('Combined Configurations', () => {
1375
- it('should combine VPC, KMS, and SSM configurations', async () => {
1376
- const appDefinition = {
1377
- vpc: {
1378
- enable: true,
1379
- natGateway: { management: 'createAndManage' } // Explicitly set NAT management mode
1380
- },
1381
- encryption: {
1382
- fieldLevelEncryptionMethod: 'kms',
1383
- createResourceIfNoneFound: true // Allow creating KMS key if not found
1384
- },
1385
- ssm: { enable: true },
1386
- integrations: [mockIntegration]
1387
- };
1388
-
1389
- const result = await composeServerlessDefinition(appDefinition);
1390
-
1391
- // VPC
1392
- expect(result.provider.vpc).toBeDefined();
1393
- // custom.vpc doesn't exist in the serverless template
1394
- expect(result.resources.Resources.VPCEndpointS3).toBeDefined();
1395
-
1396
- // KMS
1397
- expect(result.plugins).toContain('serverless-kms-grants');
1398
- expect(result.provider.environment.KMS_KEY_ARN).toBeDefined();
1399
- expect(result.custom.kmsGrants).toBeDefined();
1400
-
1401
- // SSM
1402
- expect(result.provider.layers).toBeDefined();
1403
- expect(result.provider.environment.SSM_PARAMETER_PREFIX).toBeDefined();
1404
-
1405
- // Integration
1406
- expect(result.functions.testIntegration).toBeDefined();
1407
- expect(result.resources.Resources.TestIntegrationQueue).toBeDefined();
1408
-
1409
- // All plugins should be present
1410
- expect(result.plugins).toEqual([
1411
- 'serverless-jetpack',
1412
- 'serverless-dotenv-plugin',
1413
- 'serverless-offline-sqs',
1414
- 'serverless-offline',
1415
- '@friggframework/serverless-plugin',
1416
- 'serverless-kms-grants'
1417
- ]);
1418
- });
1419
-
1420
- it('should handle partial configuration combinations', async () => {
1421
- const appDefinition = {
1422
- vpc: {
1423
- enable: true,
1424
- natGateway: { management: 'createAndManage' } // Explicitly set NAT management mode
1425
- },
1426
- encryption: {
1427
- fieldLevelEncryptionMethod: 'kms',
1428
- createResourceIfNoneFound: true // Allow creating KMS key if not found
1429
- },
1430
- integrations: []
1431
- };
1432
-
1433
- const result = await composeServerlessDefinition(appDefinition);
1434
-
1435
- // VPC and KMS should be present
1436
- expect(result.provider.vpc).toBeDefined();
1437
- expect(result.custom.kmsGrants).toBeDefined();
1438
-
1439
- // SSM should not be present
1440
- expect(result.provider.layers).toBeUndefined();
1441
- expect(result.provider.environment.SSM_PARAMETER_PREFIX).toBeUndefined();
1442
- });
1443
- });
1444
-
1445
- describe('Default Resources', () => {
1446
- it('should always include default resources', async () => {
1447
- const appDefinition = {
1448
- integrations: []
1449
- };
1450
-
1451
- const result = await composeServerlessDefinition(appDefinition);
1452
-
1453
- // Check default resources are always present
1454
- expect(result.resources.Resources.InternalErrorQueue).toBeDefined();
1455
- expect(result.resources.Resources.InternalErrorBridgeTopic).toBeDefined();
1456
- expect(result.resources.Resources.InternalErrorBridgePolicy).toBeDefined();
1457
- expect(result.resources.Resources.ApiGatewayAlarm5xx).toBeDefined();
1458
-
1459
- // Check default functions
1460
- expect(result.functions.auth).toBeDefined();
1461
- expect(result.functions.user).toBeDefined();
1462
- expect(result.functions.health).toBeDefined();
1463
-
1464
- // Check default plugins
1465
- expect(result.plugins).toContain('serverless-jetpack');
1466
- expect(result.plugins).toContain('serverless-dotenv-plugin');
1467
- expect(result.plugins).toContain('@friggframework/serverless-plugin');
1468
- });
1469
-
1470
- it('should always include default IAM permissions', async () => {
1471
- const appDefinition = {
1472
- integrations: []
1473
- };
1474
-
1475
- const result = await composeServerlessDefinition(appDefinition);
1476
-
1477
- // Check SNS publish permission
1478
- const snsPermission = result.provider.iamRoleStatements.find(
1479
- statement => statement.Action.includes('sns:Publish')
1480
- );
1481
- expect(snsPermission).toBeDefined();
1482
-
1483
- // Check SQS permissions
1484
- const sqsPermission = result.provider.iamRoleStatements.find(
1485
- statement => statement.Action.includes('sqs:SendMessage')
1486
- );
1487
- expect(sqsPermission).toBeDefined();
1488
- });
1489
-
1490
- it('should include default environment variables', async () => {
1491
- const appDefinition = {
1492
- integrations: []
1493
- };
1494
-
1495
- const result = await composeServerlessDefinition(appDefinition);
1496
-
1497
- expect(result.provider.environment.STAGE).toBe('${opt:stage, "dev"}');
1498
- expect(result.provider.environment.AWS_NODEJS_CONNECTION_REUSE_ENABLED).toBe(1);
1499
- });
1500
- });
1501
-
1502
- describe('WebSocket Configuration', () => {
1503
- it('should add websocket function when websockets.enable is true', async () => {
1504
- const appDefinition = {
1505
- websockets: { enable: true },
1506
- integrations: []
1507
- };
1508
-
1509
- const result = await composeServerlessDefinition(appDefinition);
1510
-
1511
- expect(result.functions.defaultWebsocket).toEqual({
1512
- handler: 'node_modules/@friggframework/core/handlers/routers/websocket.handler',
1513
- events: [
1514
- {
1515
- websocket: {
1516
- route: '$connect',
1517
- },
1518
- },
1519
- {
1520
- websocket: {
1521
- route: '$default',
1522
- },
1523
- },
1524
- {
1525
- websocket: {
1526
- route: '$disconnect',
1527
- },
1528
- },
1529
- ],
1530
- });
1531
- });
1532
-
1533
- it('should not add websocket function when websockets.enable is false', async () => {
1534
- const appDefinition = {
1535
- websockets: { enable: false },
1536
- integrations: []
1537
- };
1538
-
1539
- const result = await composeServerlessDefinition(appDefinition);
1540
-
1541
- expect(result.functions.defaultWebsocket).toBeUndefined();
1542
- });
1543
-
1544
- it('should not add websocket function when websockets is not defined', async () => {
1545
- const appDefinition = {
1546
- integrations: []
1547
- };
1548
-
1549
- const result = await composeServerlessDefinition(appDefinition);
1550
-
1551
- expect(result.functions.defaultWebsocket).toBeUndefined();
1552
- });
1553
- });
1554
-
1555
- describe('CRITICAL: NAT Gateway MUST be in PUBLIC Subnet', () => {
1556
- it('should NEVER reuse NAT Gateway in private subnet - throw error when selfHeal disabled', async () => {
1557
- // Mock NAT Gateway found in PRIVATE subnet (the original bug)
1558
- const mockDiscovery = require('./aws-discovery').AWSDiscovery;
1559
- const mockInstance = new mockDiscovery();
1560
- mockInstance.discoverResources = jest.fn().mockResolvedValue({
1561
- defaultVpcId: 'vpc-123456',
1562
- defaultSecurityGroupId: 'sg-123456',
1563
- privateSubnetId1: 'subnet-private1',
1564
- privateSubnetId2: 'subnet-private2',
1565
- publicSubnetId: 'subnet-public',
1566
- existingNatGatewayId: 'nat-in-private',
1567
- natGatewayInPrivateSubnet: true, // CRITICAL: NAT is in WRONG subnet
1568
- existingElasticIpAllocationId: 'eipalloc-123'
1569
- });
1570
- mockDiscovery.mockImplementation(() => mockInstance);
1571
-
1572
- const appDefinition = {
1573
- vpc: {
1574
- enable: true,
1575
- natGateway: { management: 'createAndManage' },
1576
- selfHeal: false
1577
- },
1578
- integrations: []
1579
- };
1580
-
1581
- // Should throw error because NAT is in private subnet
1582
- await expect(composeServerlessDefinition(appDefinition))
1583
- .rejects
1584
- .toThrow('CRITICAL: NAT Gateway is in PRIVATE subnet');
1585
- });
1586
-
1587
- it('should create NEW NAT in PUBLIC subnet when existing NAT is in private subnet with selfHeal', async () => {
1588
- const mockDiscovery = require('./aws-discovery').AWSDiscovery;
1589
- const mockInstance = new mockDiscovery();
1590
- mockInstance.discoverResources = jest.fn().mockResolvedValue({
1591
- defaultVpcId: 'vpc-123456',
1592
- defaultSecurityGroupId: 'sg-123456',
1593
- privateSubnetId1: 'subnet-private1',
1594
- privateSubnetId2: 'subnet-private2',
1595
- publicSubnetId: 'subnet-public',
1596
- existingNatGatewayId: 'nat-in-private',
1597
- natGatewayInPrivateSubnet: true, // NAT is in WRONG subnet
1598
- existingElasticIpAllocationId: 'eipalloc-123'
1599
- });
1600
- mockDiscovery.mockImplementation(() => mockInstance);
1601
-
1602
- const appDefinition = {
1603
- vpc: {
1604
- enable: true,
1605
- natGateway: { management: 'createAndManage' },
1606
- selfHeal: true
1607
- },
1608
- integrations: []
1609
- };
1610
-
1611
- const result = await composeServerlessDefinition(appDefinition);
1612
-
1613
- // MUST create new NAT Gateway (not reuse the one in private subnet)
1614
- expect(result.resources.Resources.FriggNATGateway).toBeDefined();
1615
-
1616
- // MUST be placed in PUBLIC subnet
1617
- const natSubnet = result.resources.Resources.FriggNATGateway.Properties.SubnetId;
1618
- expect(natSubnet).toEqual('subnet-public');
1619
-
1620
- // MUST create new EIP (cannot reuse the one associated with wrong NAT)
1621
- expect(result.resources.Resources.FriggNATGatewayEIP).toBeDefined();
1622
- });
1623
-
1624
- it('should create public subnet for NAT when none exists', async () => {
1625
- const mockDiscovery = require('./aws-discovery').AWSDiscovery;
1626
- const mockInstance = new mockDiscovery();
1627
- mockInstance.discoverResources = jest.fn().mockResolvedValue({
1628
- defaultVpcId: 'vpc-123456',
1629
- defaultSecurityGroupId: 'sg-123456',
1630
- privateSubnetId1: 'subnet-private1',
1631
- privateSubnetId2: 'subnet-private2',
1632
- publicSubnetId: null, // NO PUBLIC SUBNET EXISTS
1633
- existingNatGatewayId: null
1634
- });
1635
- mockDiscovery.mockImplementation(() => mockInstance);
1636
-
1637
- const appDefinition = {
1638
- vpc: {
1639
- enable: true,
1640
- natGateway: { management: 'createAndManage' },
1641
- selfHeal: true
1642
- },
1643
- integrations: []
1644
- };
1645
-
1646
- const result = await composeServerlessDefinition(appDefinition);
1647
-
1648
- // MUST create public subnet
1649
- expect(result.resources.Resources.FriggPublicSubnet).toBeDefined();
1650
- expect(result.resources.Resources.FriggPublicSubnet.Properties.MapPublicIpOnLaunch).toBe(true);
1651
-
1652
- // NAT Gateway MUST be in the newly created public subnet
1653
- expect(result.resources.Resources.FriggNATGateway.Properties.SubnetId)
1654
- .toEqual({ Ref: 'FriggPublicSubnet' });
1655
- });
1656
-
1657
- it('should reuse CORRECTLY placed NAT Gateway in public subnet', async () => {
1658
- const mockDiscovery = require('./aws-discovery').AWSDiscovery;
1659
- const mockInstance = new mockDiscovery();
1660
- mockInstance.discoverResources = jest.fn().mockResolvedValue({
1661
- defaultVpcId: 'vpc-123456',
1662
- defaultSecurityGroupId: 'sg-123456',
1663
- privateSubnetId1: 'subnet-private1',
1664
- privateSubnetId2: 'subnet-private2',
1665
- publicSubnetId: 'subnet-public',
1666
- existingNatGatewayId: 'nat-good',
1667
- natGatewayInPrivateSubnet: false, // NAT is CORRECTLY in public subnet
1668
- existingElasticIpAllocationId: 'eipalloc-123'
1669
- });
1670
- mockDiscovery.mockImplementation(() => mockInstance);
1671
-
1672
- const appDefinition = {
1673
- vpc: {
1674
- enable: true,
1675
- natGateway: { management: 'createAndManage' },
1676
- selfHeal: true
1677
- },
1678
- integrations: []
1679
- };
1680
-
1681
- const result = await composeServerlessDefinition(appDefinition);
1682
-
1683
- // Should NOT create new NAT Gateway (reuse the good one)
1684
- expect(result.resources.Resources.FriggNATGateway).toBeUndefined();
1685
- expect(result.resources.Resources.FriggNATGatewayEIP).toBeUndefined();
1686
-
1687
- // Should use existing NAT in routes
1688
- expect(result.resources.Resources.FriggNATRoute.Properties.NatGatewayId)
1689
- .toEqual('nat-good');
1690
- });
1691
-
1692
- it('should fix route table associations to prevent NAT misconfiguration', async () => {
1693
- const mockDiscovery = require('./aws-discovery').AWSDiscovery;
1694
- const mockInstance = new mockDiscovery();
1695
- mockInstance.discoverResources = jest.fn().mockResolvedValue({
1696
- defaultVpcId: 'vpc-123456',
1697
- defaultSecurityGroupId: 'sg-123456',
1698
- privateSubnetId1: 'subnet-private1',
1699
- privateSubnetId2: 'subnet-private2',
1700
- publicSubnetId: 'subnet-public',
1701
- existingNatGatewayId: 'nat-good',
1702
- natGatewayInPrivateSubnet: false
1703
- });
1704
- mockDiscovery.mockImplementation(() => mockInstance);
1705
-
1706
- const appDefinition = {
1707
- vpc: {
1708
- enable: true,
1709
- natGateway: { management: 'discover' },
1710
- selfHeal: true
1711
- },
1712
- integrations: []
1713
- };
1714
-
1715
- const result = await composeServerlessDefinition(appDefinition);
1716
-
1717
- // Should create route table to fix associations
1718
- expect(result.resources.Resources.FriggLambdaRouteTable).toBeDefined();
1719
-
1720
- // Should create NAT route pointing to good NAT
1721
- expect(result.resources.Resources.FriggNATRoute).toBeDefined();
1722
- expect(result.resources.Resources.FriggNATRoute.Properties.NatGatewayId)
1723
- .toEqual('nat-good');
1724
-
1725
- // Should associate private subnets with correct route table
1726
- expect(result.resources.Resources.FriggSubnet1RouteAssociation).toBeDefined();
1727
- expect(result.resources.Resources.FriggSubnet2RouteAssociation).toBeDefined();
1728
- });
1729
-
1730
- it('should handle EIP already associated error by reusing existing NAT', async () => {
1731
- const mockDiscovery = require('./aws-discovery').AWSDiscovery;
1732
- const mockInstance = new mockDiscovery();
1733
- mockInstance.discoverResources = jest.fn().mockResolvedValue({
1734
- defaultVpcId: 'vpc-123456',
1735
- defaultSecurityGroupId: 'sg-123456',
1736
- privateSubnetId1: 'subnet-private1',
1737
- privateSubnetId2: 'subnet-private2',
1738
- publicSubnetId: 'subnet-public',
1739
- existingNatGatewayId: 'nat-existing',
1740
- natGatewayInPrivateSubnet: false, // NAT is correctly placed
1741
- existingElasticIpAllocationId: 'eipalloc-inuse',
1742
- elasticIpAlreadyAssociated: true // EIP is already in use
1743
- });
1744
- mockDiscovery.mockImplementation(() => mockInstance);
1745
-
1746
- const appDefinition = {
1747
- vpc: {
1748
- enable: true,
1749
- natGateway: { management: 'createAndManage' },
1750
- selfHeal: true
1751
- },
1752
- integrations: []
1753
- };
1754
-
1755
- const result = await composeServerlessDefinition(appDefinition);
1756
-
1757
- // Should NOT create new NAT or EIP (reuse existing)
1758
- expect(result.resources.Resources.FriggNATGateway).toBeUndefined();
1759
- expect(result.resources.Resources.FriggNATGatewayEIP).toBeUndefined();
1760
-
1761
- // Should use existing NAT
1762
- expect(result.resources.Resources.FriggNATRoute.Properties.NatGatewayId)
1763
- .toEqual('nat-existing');
1764
- });
1765
- });
1766
-
1767
- describe('Database Migration Lambda', () => {
1768
- it('should include dbMigrate function in all deployments', async () => {
1769
- const appDefinition = {
1770
- name: 'test-app',
1771
- integrations: []
1772
- };
1773
-
1774
- const result = await composeServerlessDefinition(appDefinition);
1775
-
1776
- // Check dbMigrate function exists
1777
- expect(result.functions.dbMigrate).toBeDefined();
1778
- expect(result.functions.dbMigrate.handler).toBe(
1779
- 'node_modules/@friggframework/core/handlers/workers/db-migration.handler'
1780
- );
1781
- });
1782
-
1783
- it('should configure dbMigrate with correct settings', async () => {
1784
- const appDefinition = {
1785
- integrations: []
1786
- };
1787
-
1788
- const result = await composeServerlessDefinition(appDefinition);
1789
-
1790
- const dbMigrate = result.functions.dbMigrate;
1791
-
1792
- // Check timeout (5 minutes for long migrations)
1793
- expect(dbMigrate.timeout).toBe(300);
1794
-
1795
- // Check memory allocation (extra for Prisma CLI)
1796
- expect(dbMigrate.memorySize).toBe(512);
1797
-
1798
- // Check description
1799
- expect(dbMigrate.description).toContain('database migrations');
1800
- expect(dbMigrate.description).toContain('Prisma');
1801
- });
1802
-
1803
- it('should not have HTTP events (manual invocation only)', async () => {
1804
- const appDefinition = {
1805
- integrations: []
1806
- };
1807
-
1808
- const result = await composeServerlessDefinition(appDefinition);
1809
-
1810
- const dbMigrate = result.functions.dbMigrate;
1811
-
1812
- // Should have no events (manually invoked via AWS CLI)
1813
- expect(dbMigrate.events).toBeUndefined();
1814
- });
1815
-
1816
- it('should include dbMigrate even with VPC enabled', async () => {
1817
- const appDefinition = {
1818
- vpc: {
1819
- enable: true,
1820
- management: 'discover'
1821
- },
1822
- integrations: []
1823
- };
1824
-
1825
- const result = await composeServerlessDefinition(appDefinition);
1826
-
1827
- // dbMigrate should exist with VPC configuration
1828
- expect(result.functions.dbMigrate).toBeDefined();
1829
-
1830
- // Should have same VPC access as other functions
1831
- expect(result.provider.vpc).toBeDefined();
1832
- });
1833
-
1834
- it('should include dbMigrate with database configuration', async () => {
1835
- const appDefinition = {
1836
- vpc: {
1837
- enable: true,
1838
- management: 'discover'
1839
- },
1840
- database: {
1841
- postgres: {
1842
- enable: true,
1843
- management: 'discover'
1844
- }
1845
- },
1846
- integrations: []
1847
- };
1848
-
1849
- const result = await composeServerlessDefinition(appDefinition);
1850
-
1851
- // dbMigrate should exist alongside database configuration
1852
- expect(result.functions.dbMigrate).toBeDefined();
1853
- expect(result.provider.environment.DB_TYPE).toBe('postgresql');
1854
- expect(result.provider.environment.DATABASE_URL).toBeDefined();
1855
- });
1856
- });
1857
-
1858
- describe('Edge Cases', () => {
1859
- it('should handle empty app definition', async () => {
1860
- const appDefinition = {};
1861
-
1862
- await expect(composeServerlessDefinition(appDefinition)).resolves.not.toThrow();
1863
- const result = await composeServerlessDefinition(appDefinition);
1864
- expect(result.service).toBe('create-frigg-app');
1865
- });
1866
-
1867
- it('should handle null/undefined integrations', async () => {
1868
- const appDefinition = {
1869
- integrations: null
1870
- };
1871
-
1872
- // Should not throw, just ignore invalid integrations
1873
- const result = await composeServerlessDefinition(appDefinition);
1874
- expect(result).toBeDefined();
1875
- });
1876
-
1877
- it('should handle integration with missing Definition', async () => {
1878
- const invalidIntegration = {};
1879
- const appDefinition = {
1880
- integrations: [invalidIntegration]
1881
- };
1882
-
1883
- await expect(composeServerlessDefinition(appDefinition)).rejects.toThrow('Invalid integration: missing Definition or name');
1884
- });
1885
-
1886
- it('should handle integration with missing name', async () => {
1887
- const invalidIntegration = {
1888
- Definition: {}
1889
- };
1890
- const appDefinition = {
1891
- integrations: [invalidIntegration]
1892
- };
1893
-
1894
- await expect(composeServerlessDefinition(appDefinition)).rejects.toThrow('Invalid integration: missing Definition or name');
1895
- });
1896
- });
1897
- });