@friggframework/devtools 2.0.0--canary.686.20eda6e.0 → 2.0.0--canary.710.9045bbc.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 (80) hide show
  1. package/frigg-cli/README.md +77 -30
  2. package/frigg-cli/__tests__/unit/commands/deploy.test.js +30 -24
  3. package/frigg-cli/__tests__/unit/commands/doctor.test.js +10 -6
  4. package/frigg-cli/__tests__/unit/commands/generate-iam.test.js +18 -0
  5. package/frigg-cli/__tests__/unit/commands/init.test.js +688 -0
  6. package/frigg-cli/__tests__/unit/commands/install.test.js +601 -341
  7. package/frigg-cli/__tests__/unit/commands/ui.test.js +31 -30
  8. package/frigg-cli/__tests__/unit/dependencies.test.js +6 -2
  9. package/frigg-cli/build-command/index.js +1 -32
  10. package/frigg-cli/deploy-command/index.js +2 -50
  11. package/frigg-cli/doctor-command/index.js +0 -7
  12. package/frigg-cli/generate-command/index.js +1 -0
  13. package/frigg-cli/generate-iam-command.js +1 -7
  14. package/frigg-cli/index.js +9 -4
  15. package/frigg-cli/init-command/backend-first-handler.js +397 -554
  16. package/frigg-cli/init-command/deployment-modes.js +7 -0
  17. package/frigg-cli/init-command/index.js +82 -35
  18. package/frigg-cli/init-command/safe-path.js +58 -0
  19. package/frigg-cli/init-command/scaffold-dependencies.js +202 -0
  20. package/frigg-cli/install-command/app-definition.js +174 -0
  21. package/frigg-cli/install-command/commit-changes.js +40 -8
  22. package/frigg-cli/install-command/environment-variables.js +15 -0
  23. package/frigg-cli/install-command/index.js +96 -21
  24. package/frigg-cli/install-command/install-package.js +77 -4
  25. package/frigg-cli/install-command/integration-file.js +20 -11
  26. package/frigg-cli/install-command/resolve-module.js +69 -0
  27. package/frigg-cli/install-command/template.js +102 -75
  28. package/frigg-cli/install-command/validate-package.js +36 -4
  29. package/frigg-cli/package.json +1 -1
  30. package/frigg-cli/repair-command/index.js +0 -7
  31. package/frigg-cli/start-command/index.js +0 -58
  32. package/frigg-cli/templates/backend/README.md +267 -0
  33. package/frigg-cli/templates/backend/env.example +20 -0
  34. package/frigg-cli/templates/backend/gitignore +10 -0
  35. package/frigg-cli/templates/backend/index.js +114 -0
  36. package/frigg-cli/templates/backend/infrastructure.js +20 -0
  37. package/frigg-cli/test/init-command.test.js +9 -2
  38. package/infrastructure/README.md +2 -4
  39. package/infrastructure/__tests__/postgres-config.test.js +241 -835
  40. package/infrastructure/__tests__/scaffold-default-infrastructure.test.js +148 -0
  41. package/infrastructure/__tests__/template-generation.test.js +33 -12
  42. package/infrastructure/create-frigg-infrastructure.js +0 -14
  43. package/infrastructure/docs/POSTGRES-CONFIGURATION.md +21 -1
  44. package/infrastructure/domains/admin-scripts/admin-script-builder.js +6 -2
  45. package/infrastructure/domains/admin-scripts/admin-script-builder.test.js +30 -0
  46. package/infrastructure/domains/database/aurora-builder.js +13 -2
  47. package/infrastructure/domains/database/aurora-builder.test.js +22 -0
  48. package/infrastructure/domains/health/application/use-cases/__tests__/mismatch-analyzer-method-name.test.js +12 -8
  49. package/infrastructure/domains/health/application/use-cases/__tests__/repair-via-import-use-case.test.js +19 -7
  50. package/infrastructure/domains/health/application/use-cases/run-health-check-use-case.test.js +12 -8
  51. package/infrastructure/domains/health/domain/services/__tests__/import-progress-monitor.test.js +17 -18
  52. package/infrastructure/domains/health/domain/services/__tests__/update-progress-monitor.test.js +12 -2
  53. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-relationship-analysis.test.js +8 -1
  54. package/infrastructure/domains/health/infrastructure/adapters/aws-property-reconciler.test.js +4 -2
  55. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-detector.test.js +10 -0
  56. package/infrastructure/domains/networking/vpc-builder.js +18 -8
  57. package/infrastructure/domains/networking/vpc-builder.test.js +32 -13
  58. package/infrastructure/domains/parameters/offload-utils.js +0 -1
  59. package/infrastructure/domains/security/iam-generator.js +112 -5
  60. package/infrastructure/domains/security/iam-generator.test.js +94 -0
  61. package/infrastructure/domains/shared/cloudformation-discovery.test.js +36 -6
  62. package/infrastructure/domains/shared/environment-builder.js +1 -12
  63. package/infrastructure/domains/shared/environment-builder.test.js +0 -20
  64. package/infrastructure/domains/shared/types/app-definition.js +1 -15
  65. package/infrastructure/domains/shared/utilities/base-definition-factory.js +17 -30
  66. package/infrastructure/domains/shared/utilities/base-definition-factory.test.js +22 -85
  67. package/infrastructure/infrastructure-composer.test.js +268 -801
  68. package/infrastructure/scripts/build-prisma-layer.js +5 -32
  69. package/infrastructure/scripts/build-prisma-layer.test.js +28 -42
  70. package/infrastructure/scripts/build-time-discovery.test.js +18 -3
  71. package/package.json +10 -8
  72. package/frigg-cli/__tests__/unit/commands/provider-dispatch.test.js +0 -140
  73. package/frigg-cli/index.test.js +0 -158
  74. package/frigg-cli/utils/provider-helper.js +0 -80
  75. package/infrastructure/__tests__/create-frigg-infrastructure-provider.test.js +0 -64
  76. package/infrastructure/__tests__/management-api-gateway-routes.test.js +0 -335
  77. package/infrastructure/integration.test.js +0 -381
  78. package/infrastructure/provider-build.js +0 -119
  79. package/test/npm-install-guard.js +0 -104
  80. package/test/npm-install-guard.test.js +0 -53
@@ -2,13 +2,6 @@ const {
2
2
  composeServerlessDefinition,
3
3
  applySsmPreloadNodeOptions,
4
4
  } = require('./infrastructure-composer');
5
- // Composing must not build the real Prisma layer: that runs npm install
6
- // under packages/devtools, and two workers doing it at once once pruned the
7
- // repository's root node_modules (test/npm-install-guard.js).
8
- jest.mock('./domains/shared/utilities/prisma-layer-manager', () => ({
9
- ensurePrismaLayerExists: jest.fn(async () => {}),
10
- }));
11
-
12
5
  const {
13
6
  SSM_PRELOAD_NODE_OPTIONS,
14
7
  } = require('./domains/parameters/offload-utils');
@@ -42,8 +35,29 @@ jest.mock('./domains/shared/resource-discovery', () => {
42
35
  };
43
36
  });
44
37
 
38
+ // The Prisma layer build runs `npm install` into packages/devtools/layers/prisma;
39
+ // a unit test must never do that (it took ~40 s and rewrote tracked files).
40
+ jest.mock('./domains/shared/utilities/prisma-layer-manager', () => ({
41
+ ensurePrismaLayerExists: jest.fn().mockResolvedValue(undefined),
42
+ }));
43
+
45
44
  const { gatherDiscoveredResources } = require('./domains/shared/resource-discovery');
46
45
 
46
+ // The orchestrator logs each builder's validation errors, then throws one
47
+ // summary error; assert both.
48
+ async function expectValidationError(appDefinition, message) {
49
+ const logSpy = jest.spyOn(console, 'log');
50
+ try {
51
+ await expect(composeServerlessDefinition(appDefinition)).rejects.toThrow(
52
+ 'Infrastructure validation failed'
53
+ );
54
+ const logged = logSpy.mock.calls.map((args) => args.join(' ')).join('\n');
55
+ expect(logged).toContain(message);
56
+ } finally {
57
+ logSpy.mockRestore();
58
+ }
59
+ }
60
+
47
61
  describe('composeServerlessDefinition', () => {
48
62
  let mockIntegration;
49
63
 
@@ -72,21 +86,11 @@ describe('composeServerlessDefinition', () => {
72
86
  process.argv = ['node', 'test'];
73
87
  });
74
88
 
89
+ // Whether discovery actually talks to AWS (no features need it, or
90
+ // FRIGG_SKIP_AWS_DISCOVERY=true) is decided inside gatherDiscoveredResources
91
+ // by shouldRunDiscovery(); see domains/shared/resource-discovery.test.js.
92
+ // The composer always calls it, so these tests only check the call happens.
75
93
  describe('AWS discovery gating', () => {
76
- it('should skip AWS discovery when no features require it', async () => {
77
- gatherDiscoveredResources.mockClear();
78
-
79
- const appDefinition = {
80
- integrations: [],
81
- vpc: { enable: false },
82
- encryption: { fieldLevelEncryptionMethod: 'aes' },
83
- ssm: { enable: false },
84
- };
85
-
86
- await composeServerlessDefinition(appDefinition);
87
-
88
- expect(gatherDiscoveredResources).not.toHaveBeenCalled();
89
- });
90
94
 
91
95
  it('should run AWS discovery when VPC features are enabled', async () => {
92
96
  gatherDiscoveredResources.mockClear();
@@ -101,22 +105,6 @@ describe('composeServerlessDefinition', () => {
101
105
  expect(gatherDiscoveredResources).toHaveBeenCalledTimes(1);
102
106
  });
103
107
 
104
- it('should skip AWS discovery when FRIGG_SKIP_AWS_DISCOVERY is set to true', async () => {
105
- gatherDiscoveredResources.mockClear();
106
- process.env.FRIGG_SKIP_AWS_DISCOVERY = 'true';
107
-
108
- const appDefinition = {
109
- integrations: [],
110
- vpc: { enable: true },
111
- encryption: { fieldLevelEncryptionMethod: 'kms' },
112
- ssm: { enable: true },
113
- };
114
-
115
- await composeServerlessDefinition(appDefinition);
116
-
117
- expect(gatherDiscoveredResources).not.toHaveBeenCalled();
118
- });
119
-
120
108
  it('should run AWS discovery when FRIGG_SKIP_AWS_DISCOVERY is not set', async () => {
121
109
  gatherDiscoveredResources.mockClear();
122
110
  delete process.env.FRIGG_SKIP_AWS_DISCOVERY;
@@ -427,11 +415,15 @@ describe('composeServerlessDefinition', () => {
427
415
  });
428
416
 
429
417
  it('should respect provided security group IDs when supplied', async () => {
418
+ // User-supplied security groups are honoured for an existing VPC
419
+ // (vpc.management 'use-existing'); every ID is attached, not just the first.
430
420
  const appDefinition = {
431
421
  vpc: {
432
422
  enable: true,
433
- management: 'discover',
423
+ management: 'use-existing',
424
+ vpcId: 'vpc-123456',
434
425
  securityGroupIds: ['sg-custom-1', 'sg-custom-2'],
426
+ subnets: { ids: ['subnet-123456', 'subnet-789012'] },
435
427
  },
436
428
  integrations: [],
437
429
  };
@@ -445,27 +437,25 @@ describe('composeServerlessDefinition', () => {
445
437
  });
446
438
 
447
439
  it('should throw when discover mode finds no subnets and self-heal is disabled', async () => {
448
- const discoveryInstance = {
449
- discoverResources: jest.fn().mockResolvedValue(
450
- createDiscoveryResponse({
451
- privateSubnetId1: null,
452
- privateSubnetId2: null,
453
- })
454
- ),
455
- };
456
- AWSDiscovery.mockImplementation(() => discoveryInstance);
440
+ gatherDiscoveredResources.mockResolvedValue(
441
+ createDiscoveryResponse({
442
+ privateSubnetId1: null,
443
+ privateSubnetId2: null,
444
+ })
445
+ );
457
446
 
458
447
  const appDefinition = {
459
448
  vpc: {
460
449
  enable: true,
461
450
  management: 'discover',
451
+ selfHeal: false,
462
452
  subnets: { management: 'discover' },
463
453
  },
464
454
  integrations: [],
465
455
  };
466
456
 
467
457
  await expect(composeServerlessDefinition(appDefinition)).rejects.toThrow(
468
- 'No subnets discovered and subnets.management is "discover". Either enable vpc.selfHeal, set subnets.management to "create", or provide subnet IDs.'
458
+ 'No subnets discovered. Enable vpc.selfHeal, set subnets.management to "create", or provide subnet IDs.'
469
459
  );
470
460
  });
471
461
 
@@ -499,6 +489,11 @@ describe('composeServerlessDefinition', () => {
499
489
  });
500
490
 
501
491
  it('should create route tables for subnets even without NAT Gateway management', async () => {
492
+ // A fresh account: nothing to reuse, so the stack builds its own routing.
493
+ gatherDiscoveredResources.mockResolvedValue(
494
+ createDiscoveryResponse({ existingNatGatewayId: null })
495
+ );
496
+
502
497
  const appDefinition = {
503
498
  vpc: {
504
499
  enable: true,
@@ -517,7 +512,7 @@ describe('composeServerlessDefinition', () => {
517
512
  expect(result.resources.Resources.FriggLambdaRouteTable).toBeDefined();
518
513
 
519
514
  // Verify subnet associations
520
- expect(result.resources.Resources.FriggPublicSubnetRouteTableAssociation).toBeDefined();
515
+ expect(result.resources.Resources.FriggPublicSubnet1RouteTableAssociation).toBeDefined();
521
516
  expect(result.resources.Resources.FriggPrivateSubnet1RouteTableAssociation).toBeDefined();
522
517
  expect(result.resources.Resources.FriggPrivateSubnet2RouteTableAssociation).toBeDefined();
523
518
  });
@@ -531,8 +526,9 @@ describe('composeServerlessDefinition', () => {
531
526
  integrations: []
532
527
  };
533
528
 
534
- await expect(composeServerlessDefinition(appDefinition)).rejects.toThrow(
535
- 'VPC management is set to "use-existing" but no vpcId was provided'
529
+ await expectValidationError(
530
+ appDefinition,
531
+ 'vpc.vpcId is required when management="use-existing"'
536
532
  );
537
533
  });
538
534
 
@@ -560,9 +556,11 @@ describe('composeServerlessDefinition', () => {
560
556
 
561
557
  const result = await composeServerlessDefinition(appDefinition);
562
558
 
563
- expect(result.resources.Resources.VPCEndpointS3).toBeDefined();
564
- expect(result.resources.Resources.VPCEndpointS3.Type).toBe('AWS::EC2::VPCEndpoint');
565
- expect(result.resources.Resources.VPCEndpointS3.Properties.VpcId).toBe('vpc-123456');
559
+ const s3Endpoint = result.resources.Resources.FriggS3VPCEndpoint;
560
+ expect(s3Endpoint).toBeDefined();
561
+ expect(s3Endpoint.Type).toBe('AWS::EC2::VPCEndpoint');
562
+ expect(s3Endpoint.Properties.VpcId).toBe('vpc-123456');
563
+ expect(s3Endpoint.Properties.VpcEndpointType).toBe('Gateway');
566
564
  });
567
565
 
568
566
  it('should skip creating VPC endpoints when disabled explicitly', async () => {
@@ -577,9 +575,9 @@ describe('composeServerlessDefinition', () => {
577
575
 
578
576
  const result = await composeServerlessDefinition(appDefinition);
579
577
 
580
- expect(result.resources.Resources.VPCEndpointS3).toBeUndefined();
581
- expect(result.resources.Resources.VPCEndpointKMS).toBeUndefined();
582
- expect(result.resources.Resources.VPCEndpointSecretsManager).toBeUndefined();
578
+ expect(result.resources.Resources.FriggS3VPCEndpoint).toBeUndefined();
579
+ expect(result.resources.Resources.FriggKMSVPCEndpoint).toBeUndefined();
580
+ expect(result.resources.Resources.FriggSecretsManagerVPCEndpoint).toBeUndefined();
583
581
  });
584
582
 
585
583
  it('should add Secrets Manager endpoint only when enabled', async () => {
@@ -595,7 +593,8 @@ describe('composeServerlessDefinition', () => {
595
593
 
596
594
  const result = await composeServerlessDefinition(appDefinition);
597
595
 
598
- expect(result.resources.Resources.VPCEndpointSecretsManager).toBeDefined();
596
+ expect(result.resources.Resources.FriggSecretsManagerVPCEndpoint).toBeDefined();
597
+ expect(result.resources.Resources.FriggKMSVPCEndpoint).toBeDefined();
599
598
  });
600
599
 
601
600
  it('should allow Lambda security group access for VPC endpoints when security group is discovered', async () => {
@@ -609,7 +608,7 @@ describe('composeServerlessDefinition', () => {
609
608
  };
610
609
 
611
610
  const result = await composeServerlessDefinition(appDefinition);
612
- const endpointSg = result.resources.Resources.VPCEndpointSecurityGroup;
611
+ const endpointSg = result.resources.Resources.FriggVPCEndpointSecurityGroup;
613
612
 
614
613
  expect(endpointSg).toBeDefined();
615
614
  expect(endpointSg.Properties.SecurityGroupIngress).toEqual([
@@ -618,81 +617,39 @@ describe('composeServerlessDefinition', () => {
618
617
  FromPort: 443,
619
618
  ToPort: 443,
620
619
  SourceSecurityGroupId: 'sg-123456',
621
- Description: 'HTTPS from Lambda security group'
620
+ Description: 'HTTPS from Lambda'
622
621
  }
623
622
  ]);
624
623
  });
625
624
 
626
- it('should fall back to VPC CIDR when Lambda security group identifier cannot be resolved', async () => {
627
- AWSDiscovery.mockImplementation(() => ({
628
- discoverResources: jest
629
- .fn()
630
- .mockResolvedValue(createDiscoveryResponse()),
631
- }));
632
-
625
+ it('should pass an imported Lambda security group through to the endpoint ingress rule', async () => {
626
+ // CloudFormation resolves Fn::ImportValue to the group ID at deploy
627
+ // time, so the endpoint SG can reference it directly (the old
628
+ // VPC-CIDR fallback for unresolvable groups is no longer needed).
629
+ const importedSg = { 'Fn::ImportValue': 'shared-lambda-security-group' };
633
630
  const appDefinition = {
634
631
  vpc: {
635
632
  enable: true,
636
- management: 'discover',
637
- securityGroupIds: [
638
- {
639
- 'Fn::ImportValue': 'shared-lambda-security-group',
640
- },
641
- ],
642
- },
643
- encryption: { fieldLevelEncryptionMethod: 'kms' },
644
- integrations: [],
645
- };
646
-
647
- const result = await composeServerlessDefinition(appDefinition);
648
- const endpointSg = result.resources.Resources.VPCEndpointSecurityGroup;
649
-
650
- expect(endpointSg).toBeDefined();
651
- expect(endpointSg.Properties.SecurityGroupIngress).toEqual([
652
- {
653
- IpProtocol: 'tcp',
654
- FromPort: 443,
655
- ToPort: 443,
656
- CidrIp: '172.31.0.0/16',
657
- Description: 'HTTPS from VPC CIDR (fallback)',
658
- },
659
- ]);
660
- });
661
-
662
- it('should fall back to default private ranges when neither Lambda security group nor VPC CIDR is available', async () => {
663
- AWSDiscovery.mockImplementation(() => ({
664
- discoverResources: jest
665
- .fn()
666
- .mockResolvedValue(
667
- createDiscoveryResponse({ vpcCidr: null })
668
- ),
669
- }));
670
-
671
- const appDefinition = {
672
- vpc: {
673
- enable: true,
674
- management: 'discover',
675
- securityGroupIds: [
676
- {
677
- 'Fn::ImportValue': 'shared-lambda-security-group',
678
- },
679
- ],
633
+ management: 'use-existing',
634
+ vpcId: 'vpc-123456',
635
+ securityGroupIds: [importedSg],
636
+ subnets: { ids: ['subnet-123456', 'subnet-789012'] },
680
637
  },
681
638
  encryption: { fieldLevelEncryptionMethod: 'kms' },
682
639
  integrations: [],
683
640
  };
684
641
 
685
642
  const result = await composeServerlessDefinition(appDefinition);
686
- const endpointSg = result.resources.Resources.VPCEndpointSecurityGroup;
643
+ const endpointSg = result.resources.Resources.FriggVPCEndpointSecurityGroup;
687
644
 
688
- expect(endpointSg).toBeDefined();
645
+ expect(result.provider.vpc.securityGroupIds).toEqual([importedSg]);
689
646
  expect(endpointSg.Properties.SecurityGroupIngress).toEqual([
690
647
  {
691
648
  IpProtocol: 'tcp',
692
649
  FromPort: 443,
693
650
  ToPort: 443,
694
- CidrIp: '172.31.0.0/16',
695
- Description: 'HTTPS from default VPC range',
651
+ SourceSecurityGroupId: importedSg,
652
+ Description: 'HTTPS from Lambda',
696
653
  },
697
654
  ]);
698
655
  });
@@ -717,14 +674,7 @@ describe('composeServerlessDefinition', () => {
717
674
  FromPort: 443,
718
675
  ToPort: 443,
719
676
  SourceSecurityGroupId: { Ref: 'FriggLambdaSecurityGroup' },
720
- Description: 'HTTPS from Lambda security group'
721
- },
722
- {
723
- IpProtocol: 'tcp',
724
- FromPort: 443,
725
- ToPort: 443,
726
- CidrIp: '10.0.0.0/16',
727
- Description: 'HTTPS from VPC CIDR (fallback)'
677
+ Description: 'HTTPS from Lambda'
728
678
  }
729
679
  ]);
730
680
  });
@@ -738,7 +688,7 @@ describe('composeServerlessDefinition', () => {
738
688
  const result = await composeServerlessDefinition(appDefinition);
739
689
 
740
690
  expect(result.provider.vpc).toBeUndefined();
741
- expect(result.resources.Resources.VPCEndpointS3).toBeUndefined();
691
+ expect(result.resources.Resources.FriggS3VPCEndpoint).toBeUndefined();
742
692
  });
743
693
 
744
694
  it('should not add VPC configuration when vpc is not defined', async () => {
@@ -752,116 +702,87 @@ describe('composeServerlessDefinition', () => {
752
702
  });
753
703
  });
754
704
 
705
+ // NAT placement rules (never reuse a NAT in a private subnet, self-heal,
706
+ // EIP reuse, route-table association repair) are VpcBuilder decisions and
707
+ // are covered in domains/networking/vpc-builder.test.js ('NAT Gateway
708
+ // handling') and vpc-resolver.test.js. These check the composed template.
755
709
  describe('NAT Gateway behaviour', () => {
756
- it('should reuse discovered NAT gateway in discover mode without creating new resources', async () => {
757
- const discoveryInstance = {
758
- discoverResources: jest.fn().mockResolvedValue(
759
- createDiscoveryResponse({
760
- existingNatGatewayId: 'nat-existing123',
761
- natGatewayInPrivateSubnet: false,
762
- })
763
- ),
764
- };
765
- AWSDiscovery.mockImplementation(() => discoveryInstance);
710
+ it('should route through a discovered NAT gateway without creating a new one', async () => {
711
+ gatherDiscoveredResources.mockResolvedValue(
712
+ createDiscoveryResponse({
713
+ existingNatGatewayId: 'nat-existing123',
714
+ natGatewayInPrivateSubnet: false,
715
+ })
716
+ );
766
717
 
767
- const appDefinition = {
718
+ const result = await composeServerlessDefinition({
768
719
  vpc: {
769
720
  enable: true,
770
721
  management: 'discover',
771
722
  natGateway: { management: 'discover' },
772
723
  },
773
724
  integrations: [],
774
- };
775
-
776
- const result = await composeServerlessDefinition(appDefinition);
725
+ });
777
726
 
778
727
  expect(result.resources.Resources.FriggNATGateway).toBeUndefined();
779
- expect(result.resources.Resources.FriggNATRoute).toBeDefined();
728
+ expect(result.resources.Resources.FriggPrivateRoute.Properties).toEqual({
729
+ RouteTableId: { Ref: 'FriggLambdaRouteTable' },
730
+ DestinationCidrBlock: '0.0.0.0/0',
731
+ NatGatewayId: 'nat-existing123',
732
+ });
780
733
  });
781
734
 
782
- it('should reference provided NAT gateway when management set to useExisting', async () => {
783
- const discoveryInstance = {
784
- discoverResources: jest.fn().mockResolvedValue(
785
- createDiscoveryResponse({ existingNatGatewayId: null })
786
- ),
787
- };
788
- AWSDiscovery.mockImplementation(() => discoveryInstance);
735
+ it('should route through a provided NAT gateway ID', async () => {
736
+ gatherDiscoveredResources.mockResolvedValue(
737
+ createDiscoveryResponse({ existingNatGatewayId: null })
738
+ );
789
739
 
790
- const appDefinition = {
740
+ const result = await composeServerlessDefinition({
791
741
  vpc: {
792
742
  enable: true,
793
743
  management: 'discover',
794
744
  natGateway: { management: 'useExisting', id: 'nat-custom-001' },
795
745
  },
796
746
  integrations: [],
797
- };
798
-
799
- const result = await composeServerlessDefinition(appDefinition);
747
+ });
800
748
 
801
749
  expect(result.resources.Resources.FriggNATGateway).toBeUndefined();
802
- expect(result.resources.Resources.FriggNATRoute.Properties.NatGatewayId).toBe('nat-custom-001');
803
- });
804
-
805
- it('should reuse existing elastic IP allocation when creating managed NAT', async () => {
806
- const discoveryInstance = {
807
- discoverResources: jest.fn().mockResolvedValue(
808
- createDiscoveryResponse({
809
- existingNatGatewayId: null,
810
- existingElasticIpAllocationId: 'eip-alloc-123',
811
- })
812
- ),
813
- };
814
- AWSDiscovery.mockImplementation(() => discoveryInstance);
815
-
816
- const appDefinition = {
817
- vpc: {
818
- enable: true,
819
- management: 'discover',
820
- natGateway: { management: 'createAndManage' },
821
- selfHeal: true,
822
- },
823
- integrations: [],
824
- };
825
-
826
- const result = await composeServerlessDefinition(appDefinition);
827
-
828
- expect(result.resources.Resources.FriggNATGatewayEIP).toBeUndefined();
829
- expect(result.resources.Resources.FriggNATGateway.Properties.AllocationId).toBe(
830
- 'eip-alloc-123'
750
+ expect(result.resources.Resources.FriggPrivateRoute.Properties.NatGatewayId).toBe(
751
+ 'nat-custom-001'
831
752
  );
832
753
  });
833
754
 
834
- it('should create a public subnet when discovery provides none', async () => {
835
- const discoveryInstance = {
836
- discoverResources: jest.fn().mockResolvedValue(
837
- createDiscoveryResponse({
838
- publicSubnetId: null,
839
- internetGatewayId: null,
840
- existingNatGatewayId: null,
841
- })
842
- ),
843
- };
844
- AWSDiscovery.mockImplementation(() => discoveryInstance);
755
+ it('should create a retained NAT gateway in a public subnet with createAndManage', async () => {
756
+ gatherDiscoveredResources.mockResolvedValue(
757
+ createDiscoveryResponse({ existingNatGatewayId: null })
758
+ );
845
759
 
846
- const appDefinition = {
760
+ const result = await composeServerlessDefinition({
847
761
  vpc: {
848
762
  enable: true,
849
763
  management: 'discover',
850
764
  natGateway: { management: 'createAndManage' },
851
- selfHeal: true,
852
765
  },
853
766
  integrations: [],
854
- };
855
-
856
- const result = await composeServerlessDefinition(appDefinition);
767
+ });
857
768
 
858
- expect(result.resources.Resources.FriggPublicSubnet).toBeDefined();
859
- expect(result.resources.Resources.FriggPublicRouteTable).toBeDefined();
769
+ const resources = result.resources.Resources;
770
+ expect(resources.FriggNATGateway.Type).toBe('AWS::EC2::NatGateway');
771
+ expect(resources.FriggNATGateway.DeletionPolicy).toBe('Retain');
772
+ expect(resources.FriggNATGateway.UpdateReplacePolicy).toBe('Retain');
773
+ expect(resources.FriggNATGateway.Properties.SubnetId).toBe('subnet-public-1');
774
+ expect(resources.FriggNATGatewayEIP).toBeDefined();
775
+ expect(resources.FriggPublicRoute).toBeDefined();
776
+ expect(resources.FriggPrivateRoute.Properties.NatGatewayId).toEqual({
777
+ Ref: 'FriggNATGateway',
778
+ });
860
779
  });
861
780
  });
862
781
 
863
782
  describe('KMS Configuration', () => {
864
783
  it('should add KMS configuration when encryption is enabled and key is found', async () => {
784
+ const keyArn =
785
+ 'arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012';
865
786
  const appDefinition = {
866
787
  encryption: { fieldLevelEncryptionMethod: 'kms' },
867
788
  integrations: []
@@ -869,7 +790,8 @@ describe('composeServerlessDefinition', () => {
869
790
 
870
791
  const result = await composeServerlessDefinition(appDefinition);
871
792
 
872
- // Check IAM permissions
793
+ // IAM: the Lambda role uses the discovered key directly (no
794
+ // serverless-kms-grants plugin, which KmsBuilder no longer uses).
873
795
  const kmsPermission = result.provider.iamRoleStatements.find(
874
796
  statement => statement.Action.includes('kms:GenerateDataKey')
875
797
  );
@@ -877,49 +799,26 @@ describe('composeServerlessDefinition', () => {
877
799
  Effect: 'Allow',
878
800
  Action: [
879
801
  'kms:GenerateDataKey',
880
- 'kms:Decrypt'
802
+ 'kms:Decrypt',
803
+ 'kms:Encrypt',
804
+ 'kms:DescribeKey'
881
805
  ],
882
- Resource: ['arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012']
806
+ Resource: keyArn
883
807
  });
884
808
 
885
- // Check environment variable
886
- expect(result.provider.environment.KMS_KEY_ARN).toBe('arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012');
887
-
888
- // Check plugin
889
- expect(result.plugins).toContain('serverless-kms-grants');
890
-
891
- // Check custom configuration
892
- expect(result.custom.kmsGrants).toEqual({
893
- kmsKeyId: 'arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012'
894
- });
895
-
896
- // Check KMS Alias resource is created for discovered key
897
- expect(result.resources.Resources.FriggKMSKeyAlias).toBeDefined();
898
- expect(result.resources.Resources.FriggKMSKeyAlias).toEqual({
899
- Type: 'AWS::KMS::Alias',
900
- DeletionPolicy: 'Retain',
901
- Properties: {
902
- AliasName: 'alias/${self:service}-${self:provider.stage}-frigg-kms',
903
- TargetKeyId: 'arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012'
904
- }
905
- });
809
+ expect(result.provider.environment.KMS_KEY_ARN).toBe(keyArn);
810
+ expect(result.plugins).not.toContain('serverless-kms-grants');
811
+ expect(result.custom.kmsGrants).toBeUndefined();
812
+ // A discovered key is referenced, not re-declared in the stack.
813
+ expect(result.resources.Resources.FriggKMSKey).toBeUndefined();
906
814
  });
907
815
 
908
816
  it('should create new KMS key when encryption is enabled, no key found, and createResourceIfNoneFound is true', async () => {
909
- // Mock AWS discovery to return no KMS key
910
- const { AWSDiscovery } = require('./aws-discovery');
911
- const mockDiscoverResources = jest.fn().mockResolvedValue({
912
- defaultVpcId: 'vpc-123456',
913
- defaultSecurityGroupId: 'sg-123456',
914
- privateSubnetId1: 'subnet-123456',
915
- privateSubnetId2: 'subnet-789012',
916
- publicSubnetId: 'subnet-public',
917
- defaultRouteTableId: 'rtb-123456',
918
- defaultKmsKeyId: null // No KMS key found
919
- });
920
- AWSDiscovery.mockImplementation(() => ({
921
- discoverResources: mockDiscoverResources
922
- }));
817
+ // Key policy, rotation and alias details are covered in
818
+ // domains/security/kms-builder.test.js.
819
+ gatherDiscoveredResources.mockResolvedValue(
820
+ createDiscoveryResponse({ defaultKmsKeyId: null })
821
+ );
923
822
 
924
823
  const appDefinition = {
925
824
  encryption: {
@@ -931,116 +830,25 @@ describe('composeServerlessDefinition', () => {
931
830
 
932
831
  const result = await composeServerlessDefinition(appDefinition);
933
832
 
934
- // Check that KMS key resource was created with DeletionPolicy
935
- expect(result.resources.Resources.FriggKMSKey).toEqual({
936
- Type: 'AWS::KMS::Key',
937
- DeletionPolicy: 'Retain',
938
- UpdateReplacePolicy: 'Retain',
939
- Properties: {
940
- EnableKeyRotation: true,
941
- Description: 'Frigg KMS key for field-level encryption',
942
- KeyPolicy: {
943
- Version: '2012-10-17',
944
- Statement: [
945
- {
946
- Sid: 'AllowRootAccountAdmin',
947
- Effect: 'Allow',
948
- Principal: {
949
- AWS: {
950
- 'Fn::Sub': 'arn:aws:iam::${AWS::AccountId}:root'
951
- }
952
- },
953
- Action: 'kms:*',
954
- Resource: '*'
955
- },
956
- {
957
- Sid: 'AllowLambdaService',
958
- Effect: 'Allow',
959
- Principal: {
960
- Service: 'lambda.amazonaws.com'
961
- },
962
- Action: [
963
- 'kms:GenerateDataKey',
964
- 'kms:Decrypt',
965
- 'kms:DescribeKey'
966
- ],
967
- Resource: '*',
968
- Condition: {
969
- StringEquals: {
970
- 'kms:ViaService': 'lambda.us-east-1.amazonaws.com'
971
- }
972
- }
973
- }
974
- ]
975
- },
976
- Tags: [
977
- {
978
- Key: 'Name',
979
- Value: '${self:service}-${self:provider.stage}-frigg-kms-key'
980
- },
981
- {
982
- Key: 'ManagedBy',
983
- Value: 'Frigg'
984
- },
985
- {
986
- Key: 'Purpose',
987
- Value: 'Field-level encryption for Frigg application'
988
- }
989
- ]
990
- }
991
- });
833
+ const key = result.resources.Resources.FriggKMSKey;
834
+ expect(key.Type).toBe('AWS::KMS::Key');
835
+ expect(key.DeletionPolicy).toBe('Retain');
836
+ expect(key.Properties.EnableKeyRotation).toBe(true);
992
837
 
993
- // Check KMS Alias resource is created for the new key
994
- expect(result.resources.Resources.FriggKMSKeyAlias).toBeDefined();
995
- expect(result.resources.Resources.FriggKMSKeyAlias).toEqual({
996
- Type: 'AWS::KMS::Alias',
997
- DeletionPolicy: 'Retain',
998
- Properties: {
999
- AliasName: 'alias/${self:service}-${self:provider.stage}-frigg-kms',
1000
- TargetKeyId: { 'Fn::GetAtt': ['FriggKMSKey', 'Arn'] }
1001
- }
1002
- });
1003
-
1004
- // Check IAM permissions for the new key
838
+ const keyRef = { 'Fn::GetAtt': ['FriggKMSKey', 'Arn'] };
1005
839
  const kmsPermission = result.provider.iamRoleStatements.find(
1006
840
  statement => statement.Action.includes('kms:GenerateDataKey')
1007
841
  );
1008
- expect(kmsPermission).toEqual({
1009
- Effect: 'Allow',
1010
- Action: ['kms:GenerateDataKey', 'kms:Decrypt'],
1011
- Resource: [{ 'Fn::GetAtt': ['FriggKMSKey', 'Arn'] }]
1012
- });
1013
-
1014
- // Check environment variable
1015
- expect(result.provider.environment.KMS_KEY_ARN).toEqual({
1016
- 'Fn::GetAtt': ['FriggKMSKey', 'Arn']
1017
- });
1018
-
1019
- // Check plugin
1020
- expect(result.plugins).toContain('serverless-kms-grants');
1021
-
1022
- // Check custom configuration
1023
- // When creating a new key, it should reference the CloudFormation resource
1024
- expect(result.custom.kmsGrants).toEqual({
1025
- kmsKeyId: { 'Fn::GetAtt': ['FriggKMSKey', 'Arn'] }
1026
- });
842
+ expect(kmsPermission.Resource).toEqual(keyRef);
843
+ expect(result.provider.environment.KMS_KEY_ARN).toEqual(keyRef);
1027
844
  });
1028
845
 
1029
- it('should throw error when encryption is enabled, no key found, and createResourceIfNoneFound is false', async () => {
1030
- // Mock AWS discovery to return no KMS key
1031
- const { AWSDiscovery } = require('./aws-discovery');
1032
- const mockDiscoverResources = jest.fn().mockResolvedValue({
1033
- defaultVpcId: 'vpc-123456',
1034
- defaultSecurityGroupId: 'sg-123456',
1035
- privateSubnetId1: 'subnet-123456',
1036
- privateSubnetId2: 'subnet-789012',
1037
- publicSubnetId: 'subnet-public',
1038
- defaultRouteTableId: 'rtb-123456',
1039
- defaultKmsKeyId: null // No KMS key found
1040
- });
1041
- AWSDiscovery.mockImplementation(() => ({
1042
- discoverResources: mockDiscoverResources
1043
- }));
846
+ it('should fall back to the AWS_DISCOVERY_KMS_KEY_ID env reference when encryption is enabled, no key found, and createResourceIfNoneFound is false', async () => {
847
+ // KmsBuilder no longer fails the build: it points the app at the
848
+ // key ID the deploy environment provides (AWS_DISCOVERY_KMS_KEY_ID).
849
+ gatherDiscoveredResources.mockResolvedValue(
850
+ createDiscoveryResponse({ defaultKmsKeyId: null })
851
+ );
1044
852
 
1045
853
  const appDefinition = {
1046
854
  encryption: {
@@ -1050,27 +858,22 @@ describe('composeServerlessDefinition', () => {
1050
858
  integrations: []
1051
859
  };
1052
860
 
1053
- await expect(composeServerlessDefinition(appDefinition)).rejects.toThrow(
1054
- 'KMS field-level encryption is enabled but no KMS key was found. ' +
1055
- 'Either provide an existing KMS key or set encryption.createResourceIfNoneFound to true to create a new key.'
861
+ const result = await composeServerlessDefinition(appDefinition);
862
+
863
+ // An explicit `false` keeps the legacy raw env reference (see
864
+ // kms-builder.test.js 'Error handling').
865
+ expect(result.resources.Resources.FriggKMSKey).toBeUndefined();
866
+ expect(result.provider.environment.KMS_KEY_ARN).toBe(
867
+ '${env:AWS_DISCOVERY_KMS_KEY_ID}'
1056
868
  );
1057
869
  });
1058
870
 
1059
- it('should throw error when encryption is enabled, no key found, and createResourceIfNoneFound is not specified', async () => {
1060
- // Mock AWS discovery to return no KMS key
1061
- const { AWSDiscovery } = require('./aws-discovery');
1062
- const mockDiscoverResources = jest.fn().mockResolvedValue({
1063
- defaultVpcId: 'vpc-123456',
1064
- defaultSecurityGroupId: 'sg-123456',
1065
- privateSubnetId1: 'subnet-123456',
1066
- privateSubnetId2: 'subnet-789012',
1067
- publicSubnetId: 'subnet-public',
1068
- defaultRouteTableId: 'rtb-123456',
1069
- defaultKmsKeyId: null // No KMS key found
1070
- });
1071
- AWSDiscovery.mockImplementation(() => ({
1072
- discoverResources: mockDiscoverResources
1073
- }));
871
+ it('should fall back to the AWS_DISCOVERY_KMS_KEY_ID env reference when encryption is enabled, no key found, and createResourceIfNoneFound is not specified', async () => {
872
+ // KmsBuilder no longer fails the build: it points the app at the
873
+ // key ID the deploy environment provides (AWS_DISCOVERY_KMS_KEY_ID).
874
+ gatherDiscoveredResources.mockResolvedValue(
875
+ createDiscoveryResponse({ defaultKmsKeyId: null })
876
+ );
1074
877
 
1075
878
  const appDefinition = {
1076
879
  encryption: {
@@ -1080,10 +883,12 @@ describe('composeServerlessDefinition', () => {
1080
883
  integrations: []
1081
884
  };
1082
885
 
1083
- await expect(composeServerlessDefinition(appDefinition)).rejects.toThrow(
1084
- 'KMS field-level encryption is enabled but no KMS key was found. ' +
1085
- 'Either provide an existing KMS key or set encryption.createResourceIfNoneFound to true to create a new key.'
1086
- );
886
+ const result = await composeServerlessDefinition(appDefinition);
887
+
888
+ const fallbackArn =
889
+ 'arn:aws:kms:${self:provider.region}:${aws:accountId}:key/${env:AWS_DISCOVERY_KMS_KEY_ID}';
890
+ expect(result.resources.Resources.FriggKMSKey).toBeUndefined();
891
+ expect(result.provider.environment.KMS_KEY_ARN).toBe(fallbackArn);
1087
892
  });
1088
893
 
1089
894
  it('should not add KMS configuration when encryption is disabled', async () => {
@@ -1241,8 +1046,9 @@ describe('composeServerlessDefinition', () => {
1241
1046
 
1242
1047
  const result = await composeServerlessDefinition(appDefinition);
1243
1048
 
1244
- // Check integration function
1245
- expect(result.functions.testIntegration).toEqual({
1049
+ // Check integration function (packaging/layers are covered by the
1050
+ // base-definition and integration-builder tests)
1051
+ expect(result.functions.testIntegration).toEqual(expect.objectContaining({
1246
1052
  handler: 'node_modules/@friggframework/core/handlers/routers/integration-defined-routers.handlers.testIntegration.handler',
1247
1053
  events: [{
1248
1054
  httpApi: {
@@ -1250,7 +1056,7 @@ describe('composeServerlessDefinition', () => {
1250
1056
  method: 'ANY'
1251
1057
  }
1252
1058
  }]
1253
- });
1059
+ }));
1254
1060
 
1255
1061
  // Check SQS Queue
1256
1062
  expect(result.resources.Resources.TestIntegrationQueue).toEqual({
@@ -1269,7 +1075,7 @@ describe('composeServerlessDefinition', () => {
1269
1075
  });
1270
1076
 
1271
1077
  // Check Queue Worker
1272
- expect(result.functions.testIntegrationQueueWorker).toEqual({
1078
+ expect(result.functions.testIntegrationQueueWorker).toEqual(expect.objectContaining({
1273
1079
  handler: 'node_modules/@friggframework/core/handlers/workers/integration-defined-workers.handlers.testIntegration.queueWorker',
1274
1080
  reservedConcurrency: 20,
1275
1081
  events: [{
@@ -1281,8 +1087,9 @@ describe('composeServerlessDefinition', () => {
1281
1087
  functionResponseType: 'ReportBatchItemFailures'
1282
1088
  }
1283
1089
  }],
1284
- timeout: 600
1285
- });
1090
+ // Lambda maximum; the queue's VisibilityTimeout stays above it
1091
+ timeout: 900
1092
+ }));
1286
1093
 
1287
1094
  // Check environment variable
1288
1095
  expect(result.provider.environment.TESTINTEGRATION_QUEUE_URL).toEqual({
@@ -1319,146 +1126,20 @@ describe('composeServerlessDefinition', () => {
1319
1126
  const fs = require('fs');
1320
1127
  const path = require('path');
1321
1128
 
1322
- it('should rewrite handler paths in offline mode', async () => {
1129
+ it('should keep node_modules handler paths in offline mode', async () => {
1130
+ // serverless-offline resolves node_modules from the working
1131
+ // directory, so handler paths are no longer rewritten to ../node_modules.
1323
1132
  process.argv = ['node', 'test', 'offline'];
1324
- const existsSpy = jest.spyOn(fs, 'existsSync');
1325
- const fallbackNodeModules = path.resolve(process.cwd(), '..', 'node_modules');
1326
- existsSpy.mockImplementation((p) => p === fallbackNodeModules);
1327
-
1328
- const appDefinition = { integrations: [] };
1329
1133
 
1330
- const result = await composeServerlessDefinition(appDefinition);
1331
-
1332
- expect(existsSpy).toHaveBeenCalled();
1333
- expect(result.functions.auth.handler.startsWith('../node_modules/')).toBe(true);
1134
+ const result = await composeServerlessDefinition({ integrations: [] });
1334
1135
 
1335
- existsSpy.mockRestore();
1136
+ expect(result.functions.auth.handler).toBe(
1137
+ 'node_modules/@friggframework/core/handlers/routers/auth.handler'
1138
+ );
1336
1139
  });
1337
1140
  });
1338
1141
 
1339
1142
  describe('NAT Gateway Management', () => {
1340
- it('should handle NAT Gateway with createAndManage mode', async () => {
1341
- const appDefinition = {
1342
- vpc: {
1343
- enable: true,
1344
- management: 'discover',
1345
- natGateway: {
1346
- management: 'createAndManage'
1347
- }
1348
- },
1349
- integrations: []
1350
- };
1351
-
1352
- const result = await composeServerlessDefinition(appDefinition);
1353
-
1354
- expect(result.resources.Resources.FriggLambdaRouteTable).toBeDefined();
1355
- expect(result.resources.Resources.FriggNATRoute).toBeDefined();
1356
- });
1357
-
1358
- it('should mark managed NAT Gateway resources for retention', async () => {
1359
- const appDefinition = {
1360
- vpc: {
1361
- enable: true,
1362
- management: 'discover',
1363
- natGateway: { management: 'createAndManage' },
1364
- selfHeal: true,
1365
- },
1366
- integrations: [],
1367
- };
1368
-
1369
- const result = await composeServerlessDefinition(appDefinition);
1370
-
1371
- expect(result.resources.Resources.FriggNATGateway).toBeDefined();
1372
- expect(result.resources.Resources.FriggNATGateway.DeletionPolicy).toBe('Retain');
1373
- expect(result.resources.Resources.FriggNATGateway.UpdateReplacePolicy).toBe('Retain');
1374
- });
1375
-
1376
- it('should handle NAT Gateway with discover mode', async () => {
1377
- // Mock discovery to return existing NAT Gateway
1378
- const { AWSDiscovery } = require('./aws-discovery');
1379
- const mockDiscoverResources = jest.fn().mockResolvedValue({
1380
- defaultVpcId: 'vpc-123456',
1381
- defaultSecurityGroupId: 'sg-123456',
1382
- privateSubnetId1: 'subnet-123456',
1383
- privateSubnetId2: 'subnet-789012',
1384
- publicSubnetId: 'subnet-public',
1385
- defaultRouteTableId: 'rtb-123456',
1386
- defaultKmsKeyId: null,
1387
- existingNatGatewayId: 'nat-existing123'
1388
- });
1389
- AWSDiscovery.mockImplementation(() => ({
1390
- discoverResources: mockDiscoverResources
1391
- }));
1392
-
1393
- const appDefinition = {
1394
- vpc: {
1395
- enable: true,
1396
- management: 'discover',
1397
- natGateway: {
1398
- management: 'discover'
1399
- }
1400
- },
1401
- integrations: []
1402
- };
1403
-
1404
- const result = await composeServerlessDefinition(appDefinition);
1405
-
1406
- expect(result.resources.Resources.FriggNATRoute).toBeDefined();
1407
- expect(result.resources.Resources.FriggNATRoute.Properties.NatGatewayId).toBe('nat-existing123');
1408
- });
1409
-
1410
- it('should handle NAT Gateway with useExisting mode and provided ID', async () => {
1411
- const appDefinition = {
1412
- vpc: {
1413
- enable: true,
1414
- management: 'discover',
1415
- natGateway: {
1416
- management: 'useExisting',
1417
- id: 'nat-custom456'
1418
- }
1419
- },
1420
- integrations: []
1421
- };
1422
-
1423
- const result = await composeServerlessDefinition(appDefinition);
1424
-
1425
- expect(result.resources.Resources.FriggNATRoute).toBeDefined();
1426
- expect(result.resources.Resources.FriggNATRoute.Properties.NatGatewayId).toBe('nat-custom456');
1427
- });
1428
-
1429
- it('should throw error when NAT Gateway not found in discover mode', async () => {
1430
- // Mock discovery to return no NAT Gateway
1431
- const { AWSDiscovery } = require('./aws-discovery');
1432
- const mockDiscoverResources = jest.fn().mockResolvedValue({
1433
- defaultVpcId: 'vpc-123456',
1434
- defaultSecurityGroupId: 'sg-123456',
1435
- privateSubnetId1: 'subnet-123456',
1436
- privateSubnetId2: 'subnet-789012',
1437
- publicSubnetId: 'subnet-public',
1438
- defaultRouteTableId: 'rtb-123456',
1439
- defaultKmsKeyId: null,
1440
- existingNatGatewayId: null // No NAT Gateway
1441
- });
1442
- AWSDiscovery.mockImplementation(() => ({
1443
- discoverResources: mockDiscoverResources
1444
- }));
1445
-
1446
- const appDefinition = {
1447
- vpc: {
1448
- enable: true,
1449
- management: 'discover',
1450
- natGateway: {
1451
- management: 'discover'
1452
- }
1453
- },
1454
- integrations: []
1455
- };
1456
-
1457
- await expect(composeServerlessDefinition(appDefinition)).rejects.toThrow(
1458
- 'No existing NAT Gateway found in discovery mode'
1459
- );
1460
- });
1461
-
1462
1143
  it('should enable self-healing when selfHeal is true', async () => {
1463
1144
  const appDefinition = {
1464
1145
  vpc: {
@@ -1496,15 +1177,13 @@ describe('composeServerlessDefinition', () => {
1496
1177
 
1497
1178
  const result = await composeServerlessDefinition(appDefinition);
1498
1179
 
1499
- // VPC
1180
+ // VPC (plus the interface endpoints KMS needs from private subnets)
1500
1181
  expect(result.provider.vpc).toBeDefined();
1501
- // custom.vpc doesn't exist in the serverless template
1502
- expect(result.resources.Resources.VPCEndpointS3).toBeDefined();
1182
+ expect(result.resources.Resources.FriggS3VPCEndpoint).toBeDefined();
1183
+ expect(result.resources.Resources.FriggKMSVPCEndpoint).toBeDefined();
1503
1184
 
1504
1185
  // KMS
1505
- expect(result.plugins).toContain('serverless-kms-grants');
1506
1186
  expect(result.provider.environment.KMS_KEY_ARN).toBeDefined();
1507
- expect(result.custom.kmsGrants).toBeDefined();
1508
1187
 
1509
1188
  // SSM (enabled without offload markers -> broad grant only, no offload env vars)
1510
1189
  const ssmPermission = result.provider.iamRoleStatements.find(
@@ -1517,14 +1196,12 @@ describe('composeServerlessDefinition', () => {
1517
1196
  expect(result.functions.testIntegration).toBeDefined();
1518
1197
  expect(result.resources.Resources.TestIntegrationQueue).toBeDefined();
1519
1198
 
1520
- // All plugins should be present
1199
+ // No feature adds a Serverless plugin of its own
1521
1200
  expect(result.plugins).toEqual([
1522
- 'serverless-jetpack',
1523
- 'serverless-dotenv-plugin',
1201
+ 'serverless-esbuild',
1524
1202
  'serverless-offline-sqs',
1525
1203
  'serverless-offline',
1526
1204
  '@friggframework/serverless-plugin',
1527
- 'serverless-kms-grants'
1528
1205
  ]);
1529
1206
  });
1530
1207
 
@@ -1545,10 +1222,13 @@ describe('composeServerlessDefinition', () => {
1545
1222
 
1546
1223
  // VPC and KMS should be present
1547
1224
  expect(result.provider.vpc).toBeDefined();
1548
- expect(result.custom.kmsGrants).toBeDefined();
1225
+ expect(result.provider.environment.KMS_KEY_ARN).toBeDefined();
1549
1226
 
1550
1227
  // SSM should not be present
1551
- expect(result.provider.layers).toBeUndefined();
1228
+ const ssmPermission = result.provider.iamRoleStatements.find(
1229
+ statement => statement.Action && statement.Action.includes('ssm:GetParameter')
1230
+ );
1231
+ expect(ssmPermission).toBeUndefined();
1552
1232
  expect(result.provider.environment.SSM_PARAMETER_PREFIX).toBeUndefined();
1553
1233
  });
1554
1234
  });
@@ -1572,10 +1252,14 @@ describe('composeServerlessDefinition', () => {
1572
1252
  expect(result.functions.user).toBeDefined();
1573
1253
  expect(result.functions.health).toBeDefined();
1574
1254
 
1575
- // Check default plugins
1576
- expect(result.plugins).toContain('serverless-jetpack');
1577
- expect(result.plugins).toContain('serverless-dotenv-plugin');
1578
- expect(result.plugins).toContain('@friggframework/serverless-plugin');
1255
+ // Check default plugins (esbuild replaced serverless-jetpack; env
1256
+ // vars come from the app definition, not serverless-dotenv-plugin)
1257
+ expect(result.plugins).toEqual([
1258
+ 'serverless-esbuild',
1259
+ 'serverless-offline-sqs',
1260
+ 'serverless-offline',
1261
+ '@friggframework/serverless-plugin',
1262
+ ]);
1579
1263
  });
1580
1264
 
1581
1265
  it('should always include default IAM permissions', async () => {
@@ -1605,8 +1289,14 @@ describe('composeServerlessDefinition', () => {
1605
1289
 
1606
1290
  const result = await composeServerlessDefinition(appDefinition);
1607
1291
 
1608
- expect(result.provider.environment.STAGE).toBe('${opt:stage, "dev"}');
1609
- expect(result.provider.environment.AWS_NODEJS_CONNECTION_REUSE_ENABLED).toBe(1);
1292
+ expect(result.provider.environment).toEqual(
1293
+ expect.objectContaining({
1294
+ STAGE: '${self:provider.stage}',
1295
+ FRIGG_STAGE: '${self:provider.stage}',
1296
+ FRIGG_STACK: '${self:service}',
1297
+ FRIGG_REGION: '${self:provider.region}',
1298
+ })
1299
+ );
1610
1300
  });
1611
1301
  });
1612
1302
 
@@ -1663,306 +1353,77 @@ describe('composeServerlessDefinition', () => {
1663
1353
  });
1664
1354
  });
1665
1355
 
1666
- describe('CRITICAL: NAT Gateway MUST be in PUBLIC Subnet', () => {
1667
- it('should NEVER reuse NAT Gateway in private subnet - throw error when selfHeal disabled', async () => {
1668
- // Mock NAT Gateway found in PRIVATE subnet (the original bug)
1669
- const mockDiscovery = require('./aws-discovery').AWSDiscovery;
1670
- const mockInstance = new mockDiscovery();
1671
- mockInstance.discoverResources = jest.fn().mockResolvedValue({
1672
- defaultVpcId: 'vpc-123456',
1673
- defaultSecurityGroupId: 'sg-123456',
1674
- privateSubnetId1: 'subnet-private1',
1675
- privateSubnetId2: 'subnet-private2',
1676
- publicSubnetId: 'subnet-public',
1677
- existingNatGatewayId: 'nat-in-private',
1678
- natGatewayInPrivateSubnet: true, // CRITICAL: NAT is in WRONG subnet
1679
- existingElasticIpAllocationId: 'eipalloc-123'
1680
- });
1681
- mockDiscovery.mockImplementation(() => mockInstance);
1682
-
1683
- const appDefinition = {
1684
- vpc: {
1685
- enable: true,
1686
- natGateway: { management: 'createAndManage' },
1687
- selfHeal: false
1688
- },
1689
- integrations: []
1690
- };
1691
-
1692
- // Should throw error because NAT is in private subnet
1693
- await expect(composeServerlessDefinition(appDefinition))
1694
- .rejects
1695
- .toThrow('CRITICAL: NAT Gateway is in PRIVATE subnet');
1696
- });
1697
-
1698
- it('should create NEW NAT in PUBLIC subnet when existing NAT is in private subnet with selfHeal', async () => {
1699
- const mockDiscovery = require('./aws-discovery').AWSDiscovery;
1700
- const mockInstance = new mockDiscovery();
1701
- mockInstance.discoverResources = jest.fn().mockResolvedValue({
1702
- defaultVpcId: 'vpc-123456',
1703
- defaultSecurityGroupId: 'sg-123456',
1704
- privateSubnetId1: 'subnet-private1',
1705
- privateSubnetId2: 'subnet-private2',
1706
- publicSubnetId: 'subnet-public',
1707
- existingNatGatewayId: 'nat-in-private',
1708
- natGatewayInPrivateSubnet: true, // NAT is in WRONG subnet
1709
- existingElasticIpAllocationId: 'eipalloc-123'
1710
- });
1711
- mockDiscovery.mockImplementation(() => mockInstance);
1712
-
1713
- const appDefinition = {
1714
- vpc: {
1715
- enable: true,
1716
- natGateway: { management: 'createAndManage' },
1717
- selfHeal: true
1718
- },
1719
- integrations: []
1720
- };
1721
-
1722
- const result = await composeServerlessDefinition(appDefinition);
1723
-
1724
- // MUST create new NAT Gateway (not reuse the one in private subnet)
1725
- expect(result.resources.Resources.FriggNATGateway).toBeDefined();
1726
-
1727
- // MUST be placed in PUBLIC subnet
1728
- const natSubnet = result.resources.Resources.FriggNATGateway.Properties.SubnetId;
1729
- expect(natSubnet).toEqual('subnet-public');
1730
-
1731
- // MUST create new EIP (cannot reuse the one associated with wrong NAT)
1732
- expect(result.resources.Resources.FriggNATGatewayEIP).toBeDefined();
1733
- });
1734
-
1735
- it('should create public subnet for NAT when none exists', async () => {
1736
- const mockDiscovery = require('./aws-discovery').AWSDiscovery;
1737
- const mockInstance = new mockDiscovery();
1738
- mockInstance.discoverResources = jest.fn().mockResolvedValue({
1739
- defaultVpcId: 'vpc-123456',
1740
- defaultSecurityGroupId: 'sg-123456',
1741
- privateSubnetId1: 'subnet-private1',
1742
- privateSubnetId2: 'subnet-private2',
1743
- publicSubnetId: null, // NO PUBLIC SUBNET EXISTS
1744
- existingNatGatewayId: null
1745
- });
1746
- mockDiscovery.mockImplementation(() => mockInstance);
1747
-
1748
- const appDefinition = {
1749
- vpc: {
1750
- enable: true,
1751
- natGateway: { management: 'createAndManage' },
1752
- selfHeal: true
1753
- },
1754
- integrations: []
1755
- };
1756
-
1757
- const result = await composeServerlessDefinition(appDefinition);
1758
-
1759
- // MUST create public subnet
1760
- expect(result.resources.Resources.FriggPublicSubnet).toBeDefined();
1761
- expect(result.resources.Resources.FriggPublicSubnet.Properties.MapPublicIpOnLaunch).toBe(true);
1762
-
1763
- // NAT Gateway MUST be in the newly created public subnet
1764
- expect(result.resources.Resources.FriggNATGateway.Properties.SubnetId)
1765
- .toEqual({ Ref: 'FriggPublicSubnet' });
1766
- });
1767
-
1768
- it('should reuse CORRECTLY placed NAT Gateway in public subnet', async () => {
1769
- const mockDiscovery = require('./aws-discovery').AWSDiscovery;
1770
- const mockInstance = new mockDiscovery();
1771
- mockInstance.discoverResources = jest.fn().mockResolvedValue({
1772
- defaultVpcId: 'vpc-123456',
1773
- defaultSecurityGroupId: 'sg-123456',
1774
- privateSubnetId1: 'subnet-private1',
1775
- privateSubnetId2: 'subnet-private2',
1776
- publicSubnetId: 'subnet-public',
1777
- existingNatGatewayId: 'nat-good',
1778
- natGatewayInPrivateSubnet: false, // NAT is CORRECTLY in public subnet
1779
- existingElasticIpAllocationId: 'eipalloc-123'
1780
- });
1781
- mockDiscovery.mockImplementation(() => mockInstance);
1782
-
1783
- const appDefinition = {
1784
- vpc: {
1785
- enable: true,
1786
- natGateway: { management: 'createAndManage' },
1787
- selfHeal: true
1788
- },
1789
- integrations: []
1790
- };
1791
-
1792
- const result = await composeServerlessDefinition(appDefinition);
1793
-
1794
- // Should NOT create new NAT Gateway (reuse the good one)
1795
- expect(result.resources.Resources.FriggNATGateway).toBeUndefined();
1796
- expect(result.resources.Resources.FriggNATGatewayEIP).toBeUndefined();
1797
-
1798
- // Should use existing NAT in routes
1799
- expect(result.resources.Resources.FriggNATRoute.Properties.NatGatewayId)
1800
- .toEqual('nat-good');
1801
- });
1802
-
1803
- it('should fix route table associations to prevent NAT misconfiguration', async () => {
1804
- const mockDiscovery = require('./aws-discovery').AWSDiscovery;
1805
- const mockInstance = new mockDiscovery();
1806
- mockInstance.discoverResources = jest.fn().mockResolvedValue({
1807
- defaultVpcId: 'vpc-123456',
1808
- defaultSecurityGroupId: 'sg-123456',
1809
- privateSubnetId1: 'subnet-private1',
1810
- privateSubnetId2: 'subnet-private2',
1811
- publicSubnetId: 'subnet-public',
1812
- existingNatGatewayId: 'nat-good',
1813
- natGatewayInPrivateSubnet: false
1814
- });
1815
- mockDiscovery.mockImplementation(() => mockInstance);
1816
-
1817
- const appDefinition = {
1818
- vpc: {
1819
- enable: true,
1820
- natGateway: { management: 'discover' },
1821
- selfHeal: true
1822
- },
1823
- integrations: []
1824
- };
1825
-
1826
- const result = await composeServerlessDefinition(appDefinition);
1827
-
1828
- // Should create route table to fix associations
1829
- expect(result.resources.Resources.FriggLambdaRouteTable).toBeDefined();
1830
-
1831
- // Should create NAT route pointing to good NAT
1832
- expect(result.resources.Resources.FriggNATRoute).toBeDefined();
1833
- expect(result.resources.Resources.FriggNATRoute.Properties.NatGatewayId)
1834
- .toEqual('nat-good');
1835
-
1836
- // Should associate private subnets with correct route table
1837
- expect(result.resources.Resources.FriggSubnet1RouteAssociation).toBeDefined();
1838
- expect(result.resources.Resources.FriggSubnet2RouteAssociation).toBeDefined();
1839
- });
1840
-
1841
- it('should handle EIP already associated error by reusing existing NAT', async () => {
1842
- const mockDiscovery = require('./aws-discovery').AWSDiscovery;
1843
- const mockInstance = new mockDiscovery();
1844
- mockInstance.discoverResources = jest.fn().mockResolvedValue({
1845
- defaultVpcId: 'vpc-123456',
1846
- defaultSecurityGroupId: 'sg-123456',
1847
- privateSubnetId1: 'subnet-private1',
1848
- privateSubnetId2: 'subnet-private2',
1849
- publicSubnetId: 'subnet-public',
1850
- existingNatGatewayId: 'nat-existing',
1851
- natGatewayInPrivateSubnet: false, // NAT is correctly placed
1852
- existingElasticIpAllocationId: 'eipalloc-inuse',
1853
- elasticIpAlreadyAssociated: true // EIP is already in use
1854
- });
1855
- mockDiscovery.mockImplementation(() => mockInstance);
1856
-
1857
- const appDefinition = {
1858
- vpc: {
1859
- enable: true,
1860
- natGateway: { management: 'createAndManage' },
1861
- selfHeal: true
1862
- },
1863
- integrations: []
1864
- };
1865
-
1866
- const result = await composeServerlessDefinition(appDefinition);
1867
-
1868
- // Should NOT create new NAT or EIP (reuse existing)
1869
- expect(result.resources.Resources.FriggNATGateway).toBeUndefined();
1870
- expect(result.resources.Resources.FriggNATGatewayEIP).toBeUndefined();
1871
-
1872
- // Should use existing NAT
1873
- expect(result.resources.Resources.FriggNATRoute.Properties.NatGatewayId)
1874
- .toEqual('nat-existing');
1875
- });
1876
- });
1356
+ // 'CRITICAL: NAT Gateway MUST be in PUBLIC Subnet' scenarios moved with the
1357
+ // NAT logic into VpcBuilder: see domains/networking/vpc-builder.test.js
1358
+ // ('NAT Gateway handling': 'should create new NAT when existing is in
1359
+ // private subnet', 'should reuse existing elastic IP allocation', ...).
1877
1360
 
1361
+ // The single manually-invoked dbMigrate function was replaced by an async
1362
+ // migration pipeline (3bae110e): dbMigrationRouter (HTTP) queues jobs on
1363
+ // DbMigrationQueue for dbMigrationWorker. Details: migration-builder.test.js.
1878
1364
  describe('Database Migration Lambda', () => {
1879
- it('should include dbMigrate function in all deployments', async () => {
1880
- const appDefinition = {
1881
- name: 'test-app',
1882
- integrations: []
1883
- };
1884
-
1885
- const result = await composeServerlessDefinition(appDefinition);
1365
+ it('should include the migration router and worker in all deployments', async () => {
1366
+ const result = await composeServerlessDefinition({ integrations: [] });
1886
1367
 
1887
- // Check dbMigrate function exists
1888
- expect(result.functions.dbMigrate).toBeDefined();
1889
- expect(result.functions.dbMigrate.handler).toBe(
1368
+ expect(result.functions.dbMigrationRouter.handler).toBe(
1369
+ 'node_modules/@friggframework/core/handlers/routers/db-migration.handler'
1370
+ );
1371
+ expect(result.functions.dbMigrationWorker.handler).toBe(
1890
1372
  'node_modules/@friggframework/core/handlers/workers/db-migration.handler'
1891
1373
  );
1374
+ expect(result.resources.Resources.DbMigrationQueue).toBeDefined();
1375
+ expect(result.resources.Resources.FriggMigrationStatusBucket).toBeDefined();
1892
1376
  });
1893
1377
 
1894
- it('should configure dbMigrate with correct settings', async () => {
1895
- const appDefinition = {
1896
- integrations: []
1897
- };
1898
-
1899
- const result = await composeServerlessDefinition(appDefinition);
1900
-
1901
- const dbMigrate = result.functions.dbMigrate;
1902
-
1903
- // Check timeout (5 minutes for long migrations)
1904
- expect(dbMigrate.timeout).toBe(300);
1905
-
1906
- // Check memory allocation (extra for Prisma CLI)
1907
- expect(dbMigrate.memorySize).toBe(512);
1378
+ it('should run migrations one at a time from the queue', async () => {
1379
+ const result = await composeServerlessDefinition({ integrations: [] });
1380
+ const worker = result.functions.dbMigrationWorker;
1908
1381
 
1909
- // Check description
1910
- expect(dbMigrate.description).toContain('database migrations');
1911
- expect(dbMigrate.description).toContain('Prisma');
1382
+ expect(worker.reservedConcurrency).toBe(1);
1383
+ expect(worker.timeout).toBe(900);
1384
+ expect(worker.events).toEqual([
1385
+ {
1386
+ sqs: {
1387
+ arn: { 'Fn::GetAtt': ['DbMigrationQueue', 'Arn'] },
1388
+ batchSize: 1,
1389
+ },
1390
+ },
1391
+ ]);
1912
1392
  });
1913
1393
 
1914
- it('should not have HTTP events (manual invocation only)', async () => {
1915
- const appDefinition = {
1916
- integrations: []
1917
- };
1918
-
1919
- const result = await composeServerlessDefinition(appDefinition);
1920
-
1921
- const dbMigrate = result.functions.dbMigrate;
1394
+ it('should expose the router under /admin/db-migrate', async () => {
1395
+ const result = await composeServerlessDefinition({ integrations: [] });
1396
+ const paths = result.functions.dbMigrationRouter.events.map(
1397
+ (e) => `${e.httpApi.method} ${e.httpApi.path}`
1398
+ );
1922
1399
 
1923
- // Should have no events (manually invoked via AWS CLI)
1924
- expect(dbMigrate.events).toBeUndefined();
1400
+ expect(paths).toEqual(
1401
+ expect.arrayContaining([
1402
+ 'POST /admin/db-migrate',
1403
+ 'GET /admin/db-migrate/status',
1404
+ ])
1405
+ );
1925
1406
  });
1926
1407
 
1927
- it('should include dbMigrate even with VPC enabled', async () => {
1928
- const appDefinition = {
1929
- vpc: {
1930
- enable: true,
1931
- management: 'discover'
1932
- },
1933
- integrations: []
1934
- };
1935
-
1936
- const result = await composeServerlessDefinition(appDefinition);
1937
-
1938
- // dbMigrate should exist with VPC configuration
1939
- expect(result.functions.dbMigrate).toBeDefined();
1408
+ it('should include the migration functions with VPC enabled', async () => {
1409
+ const result = await composeServerlessDefinition({
1410
+ vpc: { enable: true },
1411
+ integrations: [],
1412
+ });
1940
1413
 
1941
- // Should have same VPC access as other functions
1414
+ expect(result.functions.dbMigrationWorker).toBeDefined();
1415
+ expect(result.functions.dbMigrationRouter).toBeDefined();
1942
1416
  expect(result.provider.vpc).toBeDefined();
1943
1417
  });
1944
1418
 
1945
- it('should include dbMigrate with database configuration', async () => {
1946
- const appDefinition = {
1947
- vpc: {
1948
- enable: true,
1949
- management: 'discover'
1950
- },
1951
- database: {
1952
- postgres: {
1953
- enable: true,
1954
- management: 'discover'
1955
- }
1956
- },
1957
- integrations: []
1958
- };
1959
-
1960
- const result = await composeServerlessDefinition(appDefinition);
1419
+ it('should omit the migration pipeline when postgres is explicitly disabled', async () => {
1420
+ const result = await composeServerlessDefinition({
1421
+ database: { postgres: { enable: false }, mongoDB: { enable: true } },
1422
+ integrations: [],
1423
+ });
1961
1424
 
1962
- // dbMigrate should exist alongside database configuration
1963
- expect(result.functions.dbMigrate).toBeDefined();
1964
- expect(result.provider.environment.DB_TYPE).toBe('postgresql');
1965
- expect(result.provider.environment.DATABASE_URL).toBeDefined();
1425
+ expect(result.functions.dbMigrationWorker).toBeUndefined();
1426
+ expect(result.functions.dbMigrationRouter).toBeUndefined();
1966
1427
  });
1967
1428
  });
1968
1429
 
@@ -1991,7 +1452,10 @@ describe('composeServerlessDefinition', () => {
1991
1452
  integrations: [invalidIntegration]
1992
1453
  };
1993
1454
 
1994
- await expect(composeServerlessDefinition(appDefinition)).rejects.toThrow('Invalid integration: missing Definition or name');
1455
+ await expectValidationError(
1456
+ appDefinition,
1457
+ 'Integration at index 0 is missing Definition or name'
1458
+ );
1995
1459
  });
1996
1460
 
1997
1461
  it('should handle integration with missing name', async () => {
@@ -2002,7 +1466,10 @@ describe('composeServerlessDefinition', () => {
2002
1466
  integrations: [invalidIntegration]
2003
1467
  };
2004
1468
 
2005
- await expect(composeServerlessDefinition(appDefinition)).rejects.toThrow('Invalid integration: missing Definition or name');
1469
+ await expectValidationError(
1470
+ appDefinition,
1471
+ 'Integration at index 0 is missing Definition or name'
1472
+ );
2006
1473
  });
2007
1474
  });
2008
1475
  });