@friggframework/devtools 2.0.0--canary.710.9045bbc.0 → 2.0.0--canary.711.f8b6445.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 (24) hide show
  1. package/frigg-cli/__tests__/unit/commands/deploy.test.js +24 -30
  2. package/frigg-cli/__tests__/unit/commands/doctor.test.js +6 -10
  3. package/frigg-cli/__tests__/unit/commands/install.test.js +0 -7
  4. package/frigg-cli/__tests__/unit/commands/ui.test.js +30 -31
  5. package/frigg-cli/__tests__/unit/dependencies.test.js +2 -6
  6. package/frigg-cli/index.test.js +158 -0
  7. package/infrastructure/__tests__/postgres-config.test.js +835 -241
  8. package/infrastructure/__tests__/template-generation.test.js +8 -36
  9. package/infrastructure/domains/health/application/use-cases/__tests__/mismatch-analyzer-method-name.test.js +8 -12
  10. package/infrastructure/domains/health/application/use-cases/__tests__/repair-via-import-use-case.test.js +7 -19
  11. package/infrastructure/domains/health/application/use-cases/run-health-check-use-case.test.js +8 -12
  12. package/infrastructure/domains/health/domain/services/__tests__/import-progress-monitor.test.js +18 -17
  13. package/infrastructure/domains/health/domain/services/__tests__/update-progress-monitor.test.js +2 -12
  14. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-relationship-analysis.test.js +1 -8
  15. package/infrastructure/domains/health/infrastructure/adapters/aws-property-reconciler.test.js +2 -4
  16. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-detector.test.js +0 -10
  17. package/infrastructure/domains/networking/vpc-builder.js +8 -18
  18. package/infrastructure/domains/networking/vpc-builder.test.js +13 -32
  19. package/infrastructure/domains/shared/cloudformation-discovery.test.js +6 -36
  20. package/infrastructure/infrastructure-composer.test.js +794 -268
  21. package/infrastructure/integration.test.js +381 -0
  22. package/infrastructure/scripts/build-prisma-layer.test.js +7 -28
  23. package/infrastructure/scripts/build-time-discovery.test.js +3 -18
  24. package/package.json +7 -7
@@ -35,29 +35,8 @@ jest.mock('./domains/shared/resource-discovery', () => {
35
35
  };
36
36
  });
37
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
-
44
38
  const { gatherDiscoveredResources } = require('./domains/shared/resource-discovery');
45
39
 
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
-
61
40
  describe('composeServerlessDefinition', () => {
62
41
  let mockIntegration;
63
42
 
@@ -86,11 +65,21 @@ describe('composeServerlessDefinition', () => {
86
65
  process.argv = ['node', 'test'];
87
66
  });
88
67
 
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.
93
68
  describe('AWS discovery gating', () => {
69
+ it('should skip AWS discovery when no features require it', async () => {
70
+ gatherDiscoveredResources.mockClear();
71
+
72
+ const appDefinition = {
73
+ integrations: [],
74
+ vpc: { enable: false },
75
+ encryption: { fieldLevelEncryptionMethod: 'aes' },
76
+ ssm: { enable: false },
77
+ };
78
+
79
+ await composeServerlessDefinition(appDefinition);
80
+
81
+ expect(gatherDiscoveredResources).not.toHaveBeenCalled();
82
+ });
94
83
 
95
84
  it('should run AWS discovery when VPC features are enabled', async () => {
96
85
  gatherDiscoveredResources.mockClear();
@@ -105,6 +94,22 @@ describe('composeServerlessDefinition', () => {
105
94
  expect(gatherDiscoveredResources).toHaveBeenCalledTimes(1);
106
95
  });
107
96
 
97
+ it('should skip AWS discovery when FRIGG_SKIP_AWS_DISCOVERY is set to true', async () => {
98
+ gatherDiscoveredResources.mockClear();
99
+ process.env.FRIGG_SKIP_AWS_DISCOVERY = 'true';
100
+
101
+ const appDefinition = {
102
+ integrations: [],
103
+ vpc: { enable: true },
104
+ encryption: { fieldLevelEncryptionMethod: 'kms' },
105
+ ssm: { enable: true },
106
+ };
107
+
108
+ await composeServerlessDefinition(appDefinition);
109
+
110
+ expect(gatherDiscoveredResources).not.toHaveBeenCalled();
111
+ });
112
+
108
113
  it('should run AWS discovery when FRIGG_SKIP_AWS_DISCOVERY is not set', async () => {
109
114
  gatherDiscoveredResources.mockClear();
110
115
  delete process.env.FRIGG_SKIP_AWS_DISCOVERY;
@@ -415,15 +420,11 @@ describe('composeServerlessDefinition', () => {
415
420
  });
416
421
 
417
422
  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.
420
423
  const appDefinition = {
421
424
  vpc: {
422
425
  enable: true,
423
- management: 'use-existing',
424
- vpcId: 'vpc-123456',
426
+ management: 'discover',
425
427
  securityGroupIds: ['sg-custom-1', 'sg-custom-2'],
426
- subnets: { ids: ['subnet-123456', 'subnet-789012'] },
427
428
  },
428
429
  integrations: [],
429
430
  };
@@ -437,25 +438,27 @@ describe('composeServerlessDefinition', () => {
437
438
  });
438
439
 
439
440
  it('should throw when discover mode finds no subnets and self-heal is disabled', async () => {
440
- gatherDiscoveredResources.mockResolvedValue(
441
- createDiscoveryResponse({
442
- privateSubnetId1: null,
443
- privateSubnetId2: null,
444
- })
445
- );
441
+ const discoveryInstance = {
442
+ discoverResources: jest.fn().mockResolvedValue(
443
+ createDiscoveryResponse({
444
+ privateSubnetId1: null,
445
+ privateSubnetId2: null,
446
+ })
447
+ ),
448
+ };
449
+ AWSDiscovery.mockImplementation(() => discoveryInstance);
446
450
 
447
451
  const appDefinition = {
448
452
  vpc: {
449
453
  enable: true,
450
454
  management: 'discover',
451
- selfHeal: false,
452
455
  subnets: { management: 'discover' },
453
456
  },
454
457
  integrations: [],
455
458
  };
456
459
 
457
460
  await expect(composeServerlessDefinition(appDefinition)).rejects.toThrow(
458
- 'No subnets discovered. Enable vpc.selfHeal, set subnets.management to "create", or provide subnet IDs.'
461
+ 'No subnets discovered and subnets.management is "discover". Either enable vpc.selfHeal, set subnets.management to "create", or provide subnet IDs.'
459
462
  );
460
463
  });
461
464
 
@@ -489,11 +492,6 @@ describe('composeServerlessDefinition', () => {
489
492
  });
490
493
 
491
494
  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
-
497
495
  const appDefinition = {
498
496
  vpc: {
499
497
  enable: true,
@@ -512,7 +510,7 @@ describe('composeServerlessDefinition', () => {
512
510
  expect(result.resources.Resources.FriggLambdaRouteTable).toBeDefined();
513
511
 
514
512
  // Verify subnet associations
515
- expect(result.resources.Resources.FriggPublicSubnet1RouteTableAssociation).toBeDefined();
513
+ expect(result.resources.Resources.FriggPublicSubnetRouteTableAssociation).toBeDefined();
516
514
  expect(result.resources.Resources.FriggPrivateSubnet1RouteTableAssociation).toBeDefined();
517
515
  expect(result.resources.Resources.FriggPrivateSubnet2RouteTableAssociation).toBeDefined();
518
516
  });
@@ -526,9 +524,8 @@ describe('composeServerlessDefinition', () => {
526
524
  integrations: []
527
525
  };
528
526
 
529
- await expectValidationError(
530
- appDefinition,
531
- 'vpc.vpcId is required when management="use-existing"'
527
+ await expect(composeServerlessDefinition(appDefinition)).rejects.toThrow(
528
+ 'VPC management is set to "use-existing" but no vpcId was provided'
532
529
  );
533
530
  });
534
531
 
@@ -556,11 +553,9 @@ describe('composeServerlessDefinition', () => {
556
553
 
557
554
  const result = await composeServerlessDefinition(appDefinition);
558
555
 
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');
556
+ expect(result.resources.Resources.VPCEndpointS3).toBeDefined();
557
+ expect(result.resources.Resources.VPCEndpointS3.Type).toBe('AWS::EC2::VPCEndpoint');
558
+ expect(result.resources.Resources.VPCEndpointS3.Properties.VpcId).toBe('vpc-123456');
564
559
  });
565
560
 
566
561
  it('should skip creating VPC endpoints when disabled explicitly', async () => {
@@ -575,9 +570,9 @@ describe('composeServerlessDefinition', () => {
575
570
 
576
571
  const result = await composeServerlessDefinition(appDefinition);
577
572
 
578
- expect(result.resources.Resources.FriggS3VPCEndpoint).toBeUndefined();
579
- expect(result.resources.Resources.FriggKMSVPCEndpoint).toBeUndefined();
580
- expect(result.resources.Resources.FriggSecretsManagerVPCEndpoint).toBeUndefined();
573
+ expect(result.resources.Resources.VPCEndpointS3).toBeUndefined();
574
+ expect(result.resources.Resources.VPCEndpointKMS).toBeUndefined();
575
+ expect(result.resources.Resources.VPCEndpointSecretsManager).toBeUndefined();
581
576
  });
582
577
 
583
578
  it('should add Secrets Manager endpoint only when enabled', async () => {
@@ -593,8 +588,7 @@ describe('composeServerlessDefinition', () => {
593
588
 
594
589
  const result = await composeServerlessDefinition(appDefinition);
595
590
 
596
- expect(result.resources.Resources.FriggSecretsManagerVPCEndpoint).toBeDefined();
597
- expect(result.resources.Resources.FriggKMSVPCEndpoint).toBeDefined();
591
+ expect(result.resources.Resources.VPCEndpointSecretsManager).toBeDefined();
598
592
  });
599
593
 
600
594
  it('should allow Lambda security group access for VPC endpoints when security group is discovered', async () => {
@@ -608,7 +602,7 @@ describe('composeServerlessDefinition', () => {
608
602
  };
609
603
 
610
604
  const result = await composeServerlessDefinition(appDefinition);
611
- const endpointSg = result.resources.Resources.FriggVPCEndpointSecurityGroup;
605
+ const endpointSg = result.resources.Resources.VPCEndpointSecurityGroup;
612
606
 
613
607
  expect(endpointSg).toBeDefined();
614
608
  expect(endpointSg.Properties.SecurityGroupIngress).toEqual([
@@ -617,39 +611,81 @@ describe('composeServerlessDefinition', () => {
617
611
  FromPort: 443,
618
612
  ToPort: 443,
619
613
  SourceSecurityGroupId: 'sg-123456',
620
- Description: 'HTTPS from Lambda'
614
+ Description: 'HTTPS from Lambda security group'
621
615
  }
622
616
  ]);
623
617
  });
624
618
 
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' };
619
+ it('should fall back to VPC CIDR when Lambda security group identifier cannot be resolved', async () => {
620
+ AWSDiscovery.mockImplementation(() => ({
621
+ discoverResources: jest
622
+ .fn()
623
+ .mockResolvedValue(createDiscoveryResponse()),
624
+ }));
625
+
630
626
  const appDefinition = {
631
627
  vpc: {
632
628
  enable: true,
633
- management: 'use-existing',
634
- vpcId: 'vpc-123456',
635
- securityGroupIds: [importedSg],
636
- subnets: { ids: ['subnet-123456', 'subnet-789012'] },
629
+ management: 'discover',
630
+ securityGroupIds: [
631
+ {
632
+ 'Fn::ImportValue': 'shared-lambda-security-group',
633
+ },
634
+ ],
637
635
  },
638
636
  encryption: { fieldLevelEncryptionMethod: 'kms' },
639
637
  integrations: [],
640
638
  };
641
639
 
642
640
  const result = await composeServerlessDefinition(appDefinition);
643
- const endpointSg = result.resources.Resources.FriggVPCEndpointSecurityGroup;
641
+ const endpointSg = result.resources.Resources.VPCEndpointSecurityGroup;
642
+
643
+ expect(endpointSg).toBeDefined();
644
+ expect(endpointSg.Properties.SecurityGroupIngress).toEqual([
645
+ {
646
+ IpProtocol: 'tcp',
647
+ FromPort: 443,
648
+ ToPort: 443,
649
+ CidrIp: '172.31.0.0/16',
650
+ Description: 'HTTPS from VPC CIDR (fallback)',
651
+ },
652
+ ]);
653
+ });
654
+
655
+ it('should fall back to default private ranges when neither Lambda security group nor VPC CIDR is available', async () => {
656
+ AWSDiscovery.mockImplementation(() => ({
657
+ discoverResources: jest
658
+ .fn()
659
+ .mockResolvedValue(
660
+ createDiscoveryResponse({ vpcCidr: null })
661
+ ),
662
+ }));
663
+
664
+ const appDefinition = {
665
+ vpc: {
666
+ enable: true,
667
+ management: 'discover',
668
+ securityGroupIds: [
669
+ {
670
+ 'Fn::ImportValue': 'shared-lambda-security-group',
671
+ },
672
+ ],
673
+ },
674
+ encryption: { fieldLevelEncryptionMethod: 'kms' },
675
+ integrations: [],
676
+ };
677
+
678
+ const result = await composeServerlessDefinition(appDefinition);
679
+ const endpointSg = result.resources.Resources.VPCEndpointSecurityGroup;
644
680
 
645
- expect(result.provider.vpc.securityGroupIds).toEqual([importedSg]);
681
+ expect(endpointSg).toBeDefined();
646
682
  expect(endpointSg.Properties.SecurityGroupIngress).toEqual([
647
683
  {
648
684
  IpProtocol: 'tcp',
649
685
  FromPort: 443,
650
686
  ToPort: 443,
651
- SourceSecurityGroupId: importedSg,
652
- Description: 'HTTPS from Lambda',
687
+ CidrIp: '172.31.0.0/16',
688
+ Description: 'HTTPS from default VPC range',
653
689
  },
654
690
  ]);
655
691
  });
@@ -674,7 +710,14 @@ describe('composeServerlessDefinition', () => {
674
710
  FromPort: 443,
675
711
  ToPort: 443,
676
712
  SourceSecurityGroupId: { Ref: 'FriggLambdaSecurityGroup' },
677
- Description: 'HTTPS from Lambda'
713
+ Description: 'HTTPS from Lambda security group'
714
+ },
715
+ {
716
+ IpProtocol: 'tcp',
717
+ FromPort: 443,
718
+ ToPort: 443,
719
+ CidrIp: '10.0.0.0/16',
720
+ Description: 'HTTPS from VPC CIDR (fallback)'
678
721
  }
679
722
  ]);
680
723
  });
@@ -688,7 +731,7 @@ describe('composeServerlessDefinition', () => {
688
731
  const result = await composeServerlessDefinition(appDefinition);
689
732
 
690
733
  expect(result.provider.vpc).toBeUndefined();
691
- expect(result.resources.Resources.FriggS3VPCEndpoint).toBeUndefined();
734
+ expect(result.resources.Resources.VPCEndpointS3).toBeUndefined();
692
735
  });
693
736
 
694
737
  it('should not add VPC configuration when vpc is not defined', async () => {
@@ -702,87 +745,116 @@ describe('composeServerlessDefinition', () => {
702
745
  });
703
746
  });
704
747
 
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.
709
748
  describe('NAT Gateway behaviour', () => {
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
- );
749
+ it('should reuse discovered NAT gateway in discover mode without creating new resources', async () => {
750
+ const discoveryInstance = {
751
+ discoverResources: jest.fn().mockResolvedValue(
752
+ createDiscoveryResponse({
753
+ existingNatGatewayId: 'nat-existing123',
754
+ natGatewayInPrivateSubnet: false,
755
+ })
756
+ ),
757
+ };
758
+ AWSDiscovery.mockImplementation(() => discoveryInstance);
717
759
 
718
- const result = await composeServerlessDefinition({
760
+ const appDefinition = {
719
761
  vpc: {
720
762
  enable: true,
721
763
  management: 'discover',
722
764
  natGateway: { management: 'discover' },
723
765
  },
724
766
  integrations: [],
725
- });
767
+ };
768
+
769
+ const result = await composeServerlessDefinition(appDefinition);
726
770
 
727
771
  expect(result.resources.Resources.FriggNATGateway).toBeUndefined();
728
- expect(result.resources.Resources.FriggPrivateRoute.Properties).toEqual({
729
- RouteTableId: { Ref: 'FriggLambdaRouteTable' },
730
- DestinationCidrBlock: '0.0.0.0/0',
731
- NatGatewayId: 'nat-existing123',
732
- });
772
+ expect(result.resources.Resources.FriggNATRoute).toBeDefined();
733
773
  });
734
774
 
735
- it('should route through a provided NAT gateway ID', async () => {
736
- gatherDiscoveredResources.mockResolvedValue(
737
- createDiscoveryResponse({ existingNatGatewayId: null })
738
- );
775
+ it('should reference provided NAT gateway when management set to useExisting', async () => {
776
+ const discoveryInstance = {
777
+ discoverResources: jest.fn().mockResolvedValue(
778
+ createDiscoveryResponse({ existingNatGatewayId: null })
779
+ ),
780
+ };
781
+ AWSDiscovery.mockImplementation(() => discoveryInstance);
739
782
 
740
- const result = await composeServerlessDefinition({
783
+ const appDefinition = {
741
784
  vpc: {
742
785
  enable: true,
743
786
  management: 'discover',
744
787
  natGateway: { management: 'useExisting', id: 'nat-custom-001' },
745
788
  },
746
789
  integrations: [],
747
- });
790
+ };
791
+
792
+ const result = await composeServerlessDefinition(appDefinition);
748
793
 
749
794
  expect(result.resources.Resources.FriggNATGateway).toBeUndefined();
750
- expect(result.resources.Resources.FriggPrivateRoute.Properties.NatGatewayId).toBe(
751
- 'nat-custom-001'
752
- );
795
+ expect(result.resources.Resources.FriggNATRoute.Properties.NatGatewayId).toBe('nat-custom-001');
753
796
  });
754
797
 
755
- it('should create a retained NAT gateway in a public subnet with createAndManage', async () => {
756
- gatherDiscoveredResources.mockResolvedValue(
757
- createDiscoveryResponse({ existingNatGatewayId: null })
798
+ it('should reuse existing elastic IP allocation when creating managed NAT', async () => {
799
+ const discoveryInstance = {
800
+ discoverResources: jest.fn().mockResolvedValue(
801
+ createDiscoveryResponse({
802
+ existingNatGatewayId: null,
803
+ existingElasticIpAllocationId: 'eip-alloc-123',
804
+ })
805
+ ),
806
+ };
807
+ AWSDiscovery.mockImplementation(() => discoveryInstance);
808
+
809
+ const appDefinition = {
810
+ vpc: {
811
+ enable: true,
812
+ management: 'discover',
813
+ natGateway: { management: 'createAndManage' },
814
+ selfHeal: true,
815
+ },
816
+ integrations: [],
817
+ };
818
+
819
+ const result = await composeServerlessDefinition(appDefinition);
820
+
821
+ expect(result.resources.Resources.FriggNATGatewayEIP).toBeUndefined();
822
+ expect(result.resources.Resources.FriggNATGateway.Properties.AllocationId).toBe(
823
+ 'eip-alloc-123'
758
824
  );
825
+ });
759
826
 
760
- const result = await composeServerlessDefinition({
827
+ it('should create a public subnet when discovery provides none', async () => {
828
+ const discoveryInstance = {
829
+ discoverResources: jest.fn().mockResolvedValue(
830
+ createDiscoveryResponse({
831
+ publicSubnetId: null,
832
+ internetGatewayId: null,
833
+ existingNatGatewayId: null,
834
+ })
835
+ ),
836
+ };
837
+ AWSDiscovery.mockImplementation(() => discoveryInstance);
838
+
839
+ const appDefinition = {
761
840
  vpc: {
762
841
  enable: true,
763
842
  management: 'discover',
764
843
  natGateway: { management: 'createAndManage' },
844
+ selfHeal: true,
765
845
  },
766
846
  integrations: [],
767
- });
847
+ };
768
848
 
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
- });
849
+ const result = await composeServerlessDefinition(appDefinition);
850
+
851
+ expect(result.resources.Resources.FriggPublicSubnet).toBeDefined();
852
+ expect(result.resources.Resources.FriggPublicRouteTable).toBeDefined();
779
853
  });
780
854
  });
781
855
 
782
856
  describe('KMS Configuration', () => {
783
857
  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';
786
858
  const appDefinition = {
787
859
  encryption: { fieldLevelEncryptionMethod: 'kms' },
788
860
  integrations: []
@@ -790,8 +862,7 @@ describe('composeServerlessDefinition', () => {
790
862
 
791
863
  const result = await composeServerlessDefinition(appDefinition);
792
864
 
793
- // IAM: the Lambda role uses the discovered key directly (no
794
- // serverless-kms-grants plugin, which KmsBuilder no longer uses).
865
+ // Check IAM permissions
795
866
  const kmsPermission = result.provider.iamRoleStatements.find(
796
867
  statement => statement.Action.includes('kms:GenerateDataKey')
797
868
  );
@@ -799,26 +870,49 @@ describe('composeServerlessDefinition', () => {
799
870
  Effect: 'Allow',
800
871
  Action: [
801
872
  'kms:GenerateDataKey',
802
- 'kms:Decrypt',
803
- 'kms:Encrypt',
804
- 'kms:DescribeKey'
873
+ 'kms:Decrypt'
805
874
  ],
806
- Resource: keyArn
875
+ Resource: ['arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012']
807
876
  });
808
877
 
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();
878
+ // Check environment variable
879
+ expect(result.provider.environment.KMS_KEY_ARN).toBe('arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012');
880
+
881
+ // Check plugin
882
+ expect(result.plugins).toContain('serverless-kms-grants');
883
+
884
+ // Check custom configuration
885
+ expect(result.custom.kmsGrants).toEqual({
886
+ kmsKeyId: 'arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012'
887
+ });
888
+
889
+ // Check KMS Alias resource is created for discovered key
890
+ expect(result.resources.Resources.FriggKMSKeyAlias).toBeDefined();
891
+ expect(result.resources.Resources.FriggKMSKeyAlias).toEqual({
892
+ Type: 'AWS::KMS::Alias',
893
+ DeletionPolicy: 'Retain',
894
+ Properties: {
895
+ AliasName: 'alias/${self:service}-${self:provider.stage}-frigg-kms',
896
+ TargetKeyId: 'arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012'
897
+ }
898
+ });
814
899
  });
815
900
 
816
901
  it('should create new KMS key when encryption is enabled, no key found, and createResourceIfNoneFound is true', async () => {
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
- );
902
+ // Mock AWS discovery to return no KMS key
903
+ const { AWSDiscovery } = require('./aws-discovery');
904
+ const mockDiscoverResources = jest.fn().mockResolvedValue({
905
+ defaultVpcId: 'vpc-123456',
906
+ defaultSecurityGroupId: 'sg-123456',
907
+ privateSubnetId1: 'subnet-123456',
908
+ privateSubnetId2: 'subnet-789012',
909
+ publicSubnetId: 'subnet-public',
910
+ defaultRouteTableId: 'rtb-123456',
911
+ defaultKmsKeyId: null // No KMS key found
912
+ });
913
+ AWSDiscovery.mockImplementation(() => ({
914
+ discoverResources: mockDiscoverResources
915
+ }));
822
916
 
823
917
  const appDefinition = {
824
918
  encryption: {
@@ -830,25 +924,116 @@ describe('composeServerlessDefinition', () => {
830
924
 
831
925
  const result = await composeServerlessDefinition(appDefinition);
832
926
 
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);
927
+ // Check that KMS key resource was created with DeletionPolicy
928
+ expect(result.resources.Resources.FriggKMSKey).toEqual({
929
+ Type: 'AWS::KMS::Key',
930
+ DeletionPolicy: 'Retain',
931
+ UpdateReplacePolicy: 'Retain',
932
+ Properties: {
933
+ EnableKeyRotation: true,
934
+ Description: 'Frigg KMS key for field-level encryption',
935
+ KeyPolicy: {
936
+ Version: '2012-10-17',
937
+ Statement: [
938
+ {
939
+ Sid: 'AllowRootAccountAdmin',
940
+ Effect: 'Allow',
941
+ Principal: {
942
+ AWS: {
943
+ 'Fn::Sub': 'arn:aws:iam::${AWS::AccountId}:root'
944
+ }
945
+ },
946
+ Action: 'kms:*',
947
+ Resource: '*'
948
+ },
949
+ {
950
+ Sid: 'AllowLambdaService',
951
+ Effect: 'Allow',
952
+ Principal: {
953
+ Service: 'lambda.amazonaws.com'
954
+ },
955
+ Action: [
956
+ 'kms:GenerateDataKey',
957
+ 'kms:Decrypt',
958
+ 'kms:DescribeKey'
959
+ ],
960
+ Resource: '*',
961
+ Condition: {
962
+ StringEquals: {
963
+ 'kms:ViaService': 'lambda.us-east-1.amazonaws.com'
964
+ }
965
+ }
966
+ }
967
+ ]
968
+ },
969
+ Tags: [
970
+ {
971
+ Key: 'Name',
972
+ Value: '${self:service}-${self:provider.stage}-frigg-kms-key'
973
+ },
974
+ {
975
+ Key: 'ManagedBy',
976
+ Value: 'Frigg'
977
+ },
978
+ {
979
+ Key: 'Purpose',
980
+ Value: 'Field-level encryption for Frigg application'
981
+ }
982
+ ]
983
+ }
984
+ });
837
985
 
838
- const keyRef = { 'Fn::GetAtt': ['FriggKMSKey', 'Arn'] };
986
+ // Check KMS Alias resource is created for the new key
987
+ expect(result.resources.Resources.FriggKMSKeyAlias).toBeDefined();
988
+ expect(result.resources.Resources.FriggKMSKeyAlias).toEqual({
989
+ Type: 'AWS::KMS::Alias',
990
+ DeletionPolicy: 'Retain',
991
+ Properties: {
992
+ AliasName: 'alias/${self:service}-${self:provider.stage}-frigg-kms',
993
+ TargetKeyId: { 'Fn::GetAtt': ['FriggKMSKey', 'Arn'] }
994
+ }
995
+ });
996
+
997
+ // Check IAM permissions for the new key
839
998
  const kmsPermission = result.provider.iamRoleStatements.find(
840
999
  statement => statement.Action.includes('kms:GenerateDataKey')
841
1000
  );
842
- expect(kmsPermission.Resource).toEqual(keyRef);
843
- expect(result.provider.environment.KMS_KEY_ARN).toEqual(keyRef);
1001
+ expect(kmsPermission).toEqual({
1002
+ Effect: 'Allow',
1003
+ Action: ['kms:GenerateDataKey', 'kms:Decrypt'],
1004
+ Resource: [{ 'Fn::GetAtt': ['FriggKMSKey', 'Arn'] }]
1005
+ });
1006
+
1007
+ // Check environment variable
1008
+ expect(result.provider.environment.KMS_KEY_ARN).toEqual({
1009
+ 'Fn::GetAtt': ['FriggKMSKey', 'Arn']
1010
+ });
1011
+
1012
+ // Check plugin
1013
+ expect(result.plugins).toContain('serverless-kms-grants');
1014
+
1015
+ // Check custom configuration
1016
+ // When creating a new key, it should reference the CloudFormation resource
1017
+ expect(result.custom.kmsGrants).toEqual({
1018
+ kmsKeyId: { 'Fn::GetAtt': ['FriggKMSKey', 'Arn'] }
1019
+ });
844
1020
  });
845
1021
 
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
- );
1022
+ it('should throw error when encryption is enabled, no key found, and createResourceIfNoneFound is false', async () => {
1023
+ // Mock AWS discovery to return no KMS key
1024
+ const { AWSDiscovery } = require('./aws-discovery');
1025
+ const mockDiscoverResources = jest.fn().mockResolvedValue({
1026
+ defaultVpcId: 'vpc-123456',
1027
+ defaultSecurityGroupId: 'sg-123456',
1028
+ privateSubnetId1: 'subnet-123456',
1029
+ privateSubnetId2: 'subnet-789012',
1030
+ publicSubnetId: 'subnet-public',
1031
+ defaultRouteTableId: 'rtb-123456',
1032
+ defaultKmsKeyId: null // No KMS key found
1033
+ });
1034
+ AWSDiscovery.mockImplementation(() => ({
1035
+ discoverResources: mockDiscoverResources
1036
+ }));
852
1037
 
853
1038
  const appDefinition = {
854
1039
  encryption: {
@@ -858,22 +1043,27 @@ describe('composeServerlessDefinition', () => {
858
1043
  integrations: []
859
1044
  };
860
1045
 
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}'
1046
+ await expect(composeServerlessDefinition(appDefinition)).rejects.toThrow(
1047
+ 'KMS field-level encryption is enabled but no KMS key was found. ' +
1048
+ 'Either provide an existing KMS key or set encryption.createResourceIfNoneFound to true to create a new key.'
868
1049
  );
869
1050
  });
870
1051
 
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
- );
1052
+ it('should throw error when encryption is enabled, no key found, and createResourceIfNoneFound is not specified', async () => {
1053
+ // Mock AWS discovery to return no KMS key
1054
+ const { AWSDiscovery } = require('./aws-discovery');
1055
+ const mockDiscoverResources = jest.fn().mockResolvedValue({
1056
+ defaultVpcId: 'vpc-123456',
1057
+ defaultSecurityGroupId: 'sg-123456',
1058
+ privateSubnetId1: 'subnet-123456',
1059
+ privateSubnetId2: 'subnet-789012',
1060
+ publicSubnetId: 'subnet-public',
1061
+ defaultRouteTableId: 'rtb-123456',
1062
+ defaultKmsKeyId: null // No KMS key found
1063
+ });
1064
+ AWSDiscovery.mockImplementation(() => ({
1065
+ discoverResources: mockDiscoverResources
1066
+ }));
877
1067
 
878
1068
  const appDefinition = {
879
1069
  encryption: {
@@ -883,12 +1073,10 @@ describe('composeServerlessDefinition', () => {
883
1073
  integrations: []
884
1074
  };
885
1075
 
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);
1076
+ await expect(composeServerlessDefinition(appDefinition)).rejects.toThrow(
1077
+ 'KMS field-level encryption is enabled but no KMS key was found. ' +
1078
+ 'Either provide an existing KMS key or set encryption.createResourceIfNoneFound to true to create a new key.'
1079
+ );
892
1080
  });
893
1081
 
894
1082
  it('should not add KMS configuration when encryption is disabled', async () => {
@@ -1046,9 +1234,8 @@ describe('composeServerlessDefinition', () => {
1046
1234
 
1047
1235
  const result = await composeServerlessDefinition(appDefinition);
1048
1236
 
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({
1237
+ // Check integration function
1238
+ expect(result.functions.testIntegration).toEqual({
1052
1239
  handler: 'node_modules/@friggframework/core/handlers/routers/integration-defined-routers.handlers.testIntegration.handler',
1053
1240
  events: [{
1054
1241
  httpApi: {
@@ -1056,7 +1243,7 @@ describe('composeServerlessDefinition', () => {
1056
1243
  method: 'ANY'
1057
1244
  }
1058
1245
  }]
1059
- }));
1246
+ });
1060
1247
 
1061
1248
  // Check SQS Queue
1062
1249
  expect(result.resources.Resources.TestIntegrationQueue).toEqual({
@@ -1075,7 +1262,7 @@ describe('composeServerlessDefinition', () => {
1075
1262
  });
1076
1263
 
1077
1264
  // Check Queue Worker
1078
- expect(result.functions.testIntegrationQueueWorker).toEqual(expect.objectContaining({
1265
+ expect(result.functions.testIntegrationQueueWorker).toEqual({
1079
1266
  handler: 'node_modules/@friggframework/core/handlers/workers/integration-defined-workers.handlers.testIntegration.queueWorker',
1080
1267
  reservedConcurrency: 20,
1081
1268
  events: [{
@@ -1087,9 +1274,8 @@ describe('composeServerlessDefinition', () => {
1087
1274
  functionResponseType: 'ReportBatchItemFailures'
1088
1275
  }
1089
1276
  }],
1090
- // Lambda maximum; the queue's VisibilityTimeout stays above it
1091
- timeout: 900
1092
- }));
1277
+ timeout: 600
1278
+ });
1093
1279
 
1094
1280
  // Check environment variable
1095
1281
  expect(result.provider.environment.TESTINTEGRATION_QUEUE_URL).toEqual({
@@ -1126,20 +1312,146 @@ describe('composeServerlessDefinition', () => {
1126
1312
  const fs = require('fs');
1127
1313
  const path = require('path');
1128
1314
 
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.
1315
+ it('should rewrite handler paths in offline mode', async () => {
1132
1316
  process.argv = ['node', 'test', 'offline'];
1317
+ const existsSpy = jest.spyOn(fs, 'existsSync');
1318
+ const fallbackNodeModules = path.resolve(process.cwd(), '..', 'node_modules');
1319
+ existsSpy.mockImplementation((p) => p === fallbackNodeModules);
1133
1320
 
1134
- const result = await composeServerlessDefinition({ integrations: [] });
1321
+ const appDefinition = { integrations: [] };
1135
1322
 
1136
- expect(result.functions.auth.handler).toBe(
1137
- 'node_modules/@friggframework/core/handlers/routers/auth.handler'
1138
- );
1323
+ const result = await composeServerlessDefinition(appDefinition);
1324
+
1325
+ expect(existsSpy).toHaveBeenCalled();
1326
+ expect(result.functions.auth.handler.startsWith('../node_modules/')).toBe(true);
1327
+
1328
+ existsSpy.mockRestore();
1139
1329
  });
1140
1330
  });
1141
1331
 
1142
1332
  describe('NAT Gateway Management', () => {
1333
+ it('should handle NAT Gateway with createAndManage mode', async () => {
1334
+ const appDefinition = {
1335
+ vpc: {
1336
+ enable: true,
1337
+ management: 'discover',
1338
+ natGateway: {
1339
+ management: 'createAndManage'
1340
+ }
1341
+ },
1342
+ integrations: []
1343
+ };
1344
+
1345
+ const result = await composeServerlessDefinition(appDefinition);
1346
+
1347
+ expect(result.resources.Resources.FriggLambdaRouteTable).toBeDefined();
1348
+ expect(result.resources.Resources.FriggNATRoute).toBeDefined();
1349
+ });
1350
+
1351
+ it('should mark managed NAT Gateway resources for retention', async () => {
1352
+ const appDefinition = {
1353
+ vpc: {
1354
+ enable: true,
1355
+ management: 'discover',
1356
+ natGateway: { management: 'createAndManage' },
1357
+ selfHeal: true,
1358
+ },
1359
+ integrations: [],
1360
+ };
1361
+
1362
+ const result = await composeServerlessDefinition(appDefinition);
1363
+
1364
+ expect(result.resources.Resources.FriggNATGateway).toBeDefined();
1365
+ expect(result.resources.Resources.FriggNATGateway.DeletionPolicy).toBe('Retain');
1366
+ expect(result.resources.Resources.FriggNATGateway.UpdateReplacePolicy).toBe('Retain');
1367
+ });
1368
+
1369
+ it('should handle NAT Gateway with discover mode', async () => {
1370
+ // Mock discovery to return existing NAT Gateway
1371
+ const { AWSDiscovery } = require('./aws-discovery');
1372
+ const mockDiscoverResources = jest.fn().mockResolvedValue({
1373
+ defaultVpcId: 'vpc-123456',
1374
+ defaultSecurityGroupId: 'sg-123456',
1375
+ privateSubnetId1: 'subnet-123456',
1376
+ privateSubnetId2: 'subnet-789012',
1377
+ publicSubnetId: 'subnet-public',
1378
+ defaultRouteTableId: 'rtb-123456',
1379
+ defaultKmsKeyId: null,
1380
+ existingNatGatewayId: 'nat-existing123'
1381
+ });
1382
+ AWSDiscovery.mockImplementation(() => ({
1383
+ discoverResources: mockDiscoverResources
1384
+ }));
1385
+
1386
+ const appDefinition = {
1387
+ vpc: {
1388
+ enable: true,
1389
+ management: 'discover',
1390
+ natGateway: {
1391
+ management: 'discover'
1392
+ }
1393
+ },
1394
+ integrations: []
1395
+ };
1396
+
1397
+ const result = await composeServerlessDefinition(appDefinition);
1398
+
1399
+ expect(result.resources.Resources.FriggNATRoute).toBeDefined();
1400
+ expect(result.resources.Resources.FriggNATRoute.Properties.NatGatewayId).toBe('nat-existing123');
1401
+ });
1402
+
1403
+ it('should handle NAT Gateway with useExisting mode and provided ID', async () => {
1404
+ const appDefinition = {
1405
+ vpc: {
1406
+ enable: true,
1407
+ management: 'discover',
1408
+ natGateway: {
1409
+ management: 'useExisting',
1410
+ id: 'nat-custom456'
1411
+ }
1412
+ },
1413
+ integrations: []
1414
+ };
1415
+
1416
+ const result = await composeServerlessDefinition(appDefinition);
1417
+
1418
+ expect(result.resources.Resources.FriggNATRoute).toBeDefined();
1419
+ expect(result.resources.Resources.FriggNATRoute.Properties.NatGatewayId).toBe('nat-custom456');
1420
+ });
1421
+
1422
+ it('should throw error when NAT Gateway not found in discover mode', async () => {
1423
+ // Mock discovery to return no NAT Gateway
1424
+ const { AWSDiscovery } = require('./aws-discovery');
1425
+ const mockDiscoverResources = jest.fn().mockResolvedValue({
1426
+ defaultVpcId: 'vpc-123456',
1427
+ defaultSecurityGroupId: 'sg-123456',
1428
+ privateSubnetId1: 'subnet-123456',
1429
+ privateSubnetId2: 'subnet-789012',
1430
+ publicSubnetId: 'subnet-public',
1431
+ defaultRouteTableId: 'rtb-123456',
1432
+ defaultKmsKeyId: null,
1433
+ existingNatGatewayId: null // No NAT Gateway
1434
+ });
1435
+ AWSDiscovery.mockImplementation(() => ({
1436
+ discoverResources: mockDiscoverResources
1437
+ }));
1438
+
1439
+ const appDefinition = {
1440
+ vpc: {
1441
+ enable: true,
1442
+ management: 'discover',
1443
+ natGateway: {
1444
+ management: 'discover'
1445
+ }
1446
+ },
1447
+ integrations: []
1448
+ };
1449
+
1450
+ await expect(composeServerlessDefinition(appDefinition)).rejects.toThrow(
1451
+ 'No existing NAT Gateway found in discovery mode'
1452
+ );
1453
+ });
1454
+
1143
1455
  it('should enable self-healing when selfHeal is true', async () => {
1144
1456
  const appDefinition = {
1145
1457
  vpc: {
@@ -1177,13 +1489,15 @@ describe('composeServerlessDefinition', () => {
1177
1489
 
1178
1490
  const result = await composeServerlessDefinition(appDefinition);
1179
1491
 
1180
- // VPC (plus the interface endpoints KMS needs from private subnets)
1492
+ // VPC
1181
1493
  expect(result.provider.vpc).toBeDefined();
1182
- expect(result.resources.Resources.FriggS3VPCEndpoint).toBeDefined();
1183
- expect(result.resources.Resources.FriggKMSVPCEndpoint).toBeDefined();
1494
+ // custom.vpc doesn't exist in the serverless template
1495
+ expect(result.resources.Resources.VPCEndpointS3).toBeDefined();
1184
1496
 
1185
1497
  // KMS
1498
+ expect(result.plugins).toContain('serverless-kms-grants');
1186
1499
  expect(result.provider.environment.KMS_KEY_ARN).toBeDefined();
1500
+ expect(result.custom.kmsGrants).toBeDefined();
1187
1501
 
1188
1502
  // SSM (enabled without offload markers -> broad grant only, no offload env vars)
1189
1503
  const ssmPermission = result.provider.iamRoleStatements.find(
@@ -1196,12 +1510,14 @@ describe('composeServerlessDefinition', () => {
1196
1510
  expect(result.functions.testIntegration).toBeDefined();
1197
1511
  expect(result.resources.Resources.TestIntegrationQueue).toBeDefined();
1198
1512
 
1199
- // No feature adds a Serverless plugin of its own
1513
+ // All plugins should be present
1200
1514
  expect(result.plugins).toEqual([
1201
- 'serverless-esbuild',
1515
+ 'serverless-jetpack',
1516
+ 'serverless-dotenv-plugin',
1202
1517
  'serverless-offline-sqs',
1203
1518
  'serverless-offline',
1204
1519
  '@friggframework/serverless-plugin',
1520
+ 'serverless-kms-grants'
1205
1521
  ]);
1206
1522
  });
1207
1523
 
@@ -1222,13 +1538,10 @@ describe('composeServerlessDefinition', () => {
1222
1538
 
1223
1539
  // VPC and KMS should be present
1224
1540
  expect(result.provider.vpc).toBeDefined();
1225
- expect(result.provider.environment.KMS_KEY_ARN).toBeDefined();
1541
+ expect(result.custom.kmsGrants).toBeDefined();
1226
1542
 
1227
1543
  // SSM should not be present
1228
- const ssmPermission = result.provider.iamRoleStatements.find(
1229
- statement => statement.Action && statement.Action.includes('ssm:GetParameter')
1230
- );
1231
- expect(ssmPermission).toBeUndefined();
1544
+ expect(result.provider.layers).toBeUndefined();
1232
1545
  expect(result.provider.environment.SSM_PARAMETER_PREFIX).toBeUndefined();
1233
1546
  });
1234
1547
  });
@@ -1252,14 +1565,10 @@ describe('composeServerlessDefinition', () => {
1252
1565
  expect(result.functions.user).toBeDefined();
1253
1566
  expect(result.functions.health).toBeDefined();
1254
1567
 
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
- ]);
1568
+ // Check default plugins
1569
+ expect(result.plugins).toContain('serverless-jetpack');
1570
+ expect(result.plugins).toContain('serverless-dotenv-plugin');
1571
+ expect(result.plugins).toContain('@friggframework/serverless-plugin');
1263
1572
  });
1264
1573
 
1265
1574
  it('should always include default IAM permissions', async () => {
@@ -1289,14 +1598,8 @@ describe('composeServerlessDefinition', () => {
1289
1598
 
1290
1599
  const result = await composeServerlessDefinition(appDefinition);
1291
1600
 
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
- );
1601
+ expect(result.provider.environment.STAGE).toBe('${opt:stage, "dev"}');
1602
+ expect(result.provider.environment.AWS_NODEJS_CONNECTION_REUSE_ENABLED).toBe(1);
1300
1603
  });
1301
1604
  });
1302
1605
 
@@ -1353,77 +1656,306 @@ describe('composeServerlessDefinition', () => {
1353
1656
  });
1354
1657
  });
1355
1658
 
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', ...).
1659
+ describe('CRITICAL: NAT Gateway MUST be in PUBLIC Subnet', () => {
1660
+ it('should NEVER reuse NAT Gateway in private subnet - throw error when selfHeal disabled', async () => {
1661
+ // Mock NAT Gateway found in PRIVATE subnet (the original bug)
1662
+ const mockDiscovery = require('./aws-discovery').AWSDiscovery;
1663
+ const mockInstance = new mockDiscovery();
1664
+ mockInstance.discoverResources = jest.fn().mockResolvedValue({
1665
+ defaultVpcId: 'vpc-123456',
1666
+ defaultSecurityGroupId: 'sg-123456',
1667
+ privateSubnetId1: 'subnet-private1',
1668
+ privateSubnetId2: 'subnet-private2',
1669
+ publicSubnetId: 'subnet-public',
1670
+ existingNatGatewayId: 'nat-in-private',
1671
+ natGatewayInPrivateSubnet: true, // CRITICAL: NAT is in WRONG subnet
1672
+ existingElasticIpAllocationId: 'eipalloc-123'
1673
+ });
1674
+ mockDiscovery.mockImplementation(() => mockInstance);
1675
+
1676
+ const appDefinition = {
1677
+ vpc: {
1678
+ enable: true,
1679
+ natGateway: { management: 'createAndManage' },
1680
+ selfHeal: false
1681
+ },
1682
+ integrations: []
1683
+ };
1684
+
1685
+ // Should throw error because NAT is in private subnet
1686
+ await expect(composeServerlessDefinition(appDefinition))
1687
+ .rejects
1688
+ .toThrow('CRITICAL: NAT Gateway is in PRIVATE subnet');
1689
+ });
1690
+
1691
+ it('should create NEW NAT in PUBLIC subnet when existing NAT is in private subnet with selfHeal', async () => {
1692
+ const mockDiscovery = require('./aws-discovery').AWSDiscovery;
1693
+ const mockInstance = new mockDiscovery();
1694
+ mockInstance.discoverResources = jest.fn().mockResolvedValue({
1695
+ defaultVpcId: 'vpc-123456',
1696
+ defaultSecurityGroupId: 'sg-123456',
1697
+ privateSubnetId1: 'subnet-private1',
1698
+ privateSubnetId2: 'subnet-private2',
1699
+ publicSubnetId: 'subnet-public',
1700
+ existingNatGatewayId: 'nat-in-private',
1701
+ natGatewayInPrivateSubnet: true, // NAT is in WRONG subnet
1702
+ existingElasticIpAllocationId: 'eipalloc-123'
1703
+ });
1704
+ mockDiscovery.mockImplementation(() => mockInstance);
1705
+
1706
+ const appDefinition = {
1707
+ vpc: {
1708
+ enable: true,
1709
+ natGateway: { management: 'createAndManage' },
1710
+ selfHeal: true
1711
+ },
1712
+ integrations: []
1713
+ };
1714
+
1715
+ const result = await composeServerlessDefinition(appDefinition);
1716
+
1717
+ // MUST create new NAT Gateway (not reuse the one in private subnet)
1718
+ expect(result.resources.Resources.FriggNATGateway).toBeDefined();
1719
+
1720
+ // MUST be placed in PUBLIC subnet
1721
+ const natSubnet = result.resources.Resources.FriggNATGateway.Properties.SubnetId;
1722
+ expect(natSubnet).toEqual('subnet-public');
1723
+
1724
+ // MUST create new EIP (cannot reuse the one associated with wrong NAT)
1725
+ expect(result.resources.Resources.FriggNATGatewayEIP).toBeDefined();
1726
+ });
1727
+
1728
+ it('should create public subnet for NAT when none exists', async () => {
1729
+ const mockDiscovery = require('./aws-discovery').AWSDiscovery;
1730
+ const mockInstance = new mockDiscovery();
1731
+ mockInstance.discoverResources = jest.fn().mockResolvedValue({
1732
+ defaultVpcId: 'vpc-123456',
1733
+ defaultSecurityGroupId: 'sg-123456',
1734
+ privateSubnetId1: 'subnet-private1',
1735
+ privateSubnetId2: 'subnet-private2',
1736
+ publicSubnetId: null, // NO PUBLIC SUBNET EXISTS
1737
+ existingNatGatewayId: null
1738
+ });
1739
+ mockDiscovery.mockImplementation(() => mockInstance);
1740
+
1741
+ const appDefinition = {
1742
+ vpc: {
1743
+ enable: true,
1744
+ natGateway: { management: 'createAndManage' },
1745
+ selfHeal: true
1746
+ },
1747
+ integrations: []
1748
+ };
1749
+
1750
+ const result = await composeServerlessDefinition(appDefinition);
1751
+
1752
+ // MUST create public subnet
1753
+ expect(result.resources.Resources.FriggPublicSubnet).toBeDefined();
1754
+ expect(result.resources.Resources.FriggPublicSubnet.Properties.MapPublicIpOnLaunch).toBe(true);
1755
+
1756
+ // NAT Gateway MUST be in the newly created public subnet
1757
+ expect(result.resources.Resources.FriggNATGateway.Properties.SubnetId)
1758
+ .toEqual({ Ref: 'FriggPublicSubnet' });
1759
+ });
1760
+
1761
+ it('should reuse CORRECTLY placed NAT Gateway in public subnet', async () => {
1762
+ const mockDiscovery = require('./aws-discovery').AWSDiscovery;
1763
+ const mockInstance = new mockDiscovery();
1764
+ mockInstance.discoverResources = jest.fn().mockResolvedValue({
1765
+ defaultVpcId: 'vpc-123456',
1766
+ defaultSecurityGroupId: 'sg-123456',
1767
+ privateSubnetId1: 'subnet-private1',
1768
+ privateSubnetId2: 'subnet-private2',
1769
+ publicSubnetId: 'subnet-public',
1770
+ existingNatGatewayId: 'nat-good',
1771
+ natGatewayInPrivateSubnet: false, // NAT is CORRECTLY in public subnet
1772
+ existingElasticIpAllocationId: 'eipalloc-123'
1773
+ });
1774
+ mockDiscovery.mockImplementation(() => mockInstance);
1775
+
1776
+ const appDefinition = {
1777
+ vpc: {
1778
+ enable: true,
1779
+ natGateway: { management: 'createAndManage' },
1780
+ selfHeal: true
1781
+ },
1782
+ integrations: []
1783
+ };
1784
+
1785
+ const result = await composeServerlessDefinition(appDefinition);
1786
+
1787
+ // Should NOT create new NAT Gateway (reuse the good one)
1788
+ expect(result.resources.Resources.FriggNATGateway).toBeUndefined();
1789
+ expect(result.resources.Resources.FriggNATGatewayEIP).toBeUndefined();
1790
+
1791
+ // Should use existing NAT in routes
1792
+ expect(result.resources.Resources.FriggNATRoute.Properties.NatGatewayId)
1793
+ .toEqual('nat-good');
1794
+ });
1795
+
1796
+ it('should fix route table associations to prevent NAT misconfiguration', async () => {
1797
+ const mockDiscovery = require('./aws-discovery').AWSDiscovery;
1798
+ const mockInstance = new mockDiscovery();
1799
+ mockInstance.discoverResources = jest.fn().mockResolvedValue({
1800
+ defaultVpcId: 'vpc-123456',
1801
+ defaultSecurityGroupId: 'sg-123456',
1802
+ privateSubnetId1: 'subnet-private1',
1803
+ privateSubnetId2: 'subnet-private2',
1804
+ publicSubnetId: 'subnet-public',
1805
+ existingNatGatewayId: 'nat-good',
1806
+ natGatewayInPrivateSubnet: false
1807
+ });
1808
+ mockDiscovery.mockImplementation(() => mockInstance);
1809
+
1810
+ const appDefinition = {
1811
+ vpc: {
1812
+ enable: true,
1813
+ natGateway: { management: 'discover' },
1814
+ selfHeal: true
1815
+ },
1816
+ integrations: []
1817
+ };
1818
+
1819
+ const result = await composeServerlessDefinition(appDefinition);
1820
+
1821
+ // Should create route table to fix associations
1822
+ expect(result.resources.Resources.FriggLambdaRouteTable).toBeDefined();
1823
+
1824
+ // Should create NAT route pointing to good NAT
1825
+ expect(result.resources.Resources.FriggNATRoute).toBeDefined();
1826
+ expect(result.resources.Resources.FriggNATRoute.Properties.NatGatewayId)
1827
+ .toEqual('nat-good');
1828
+
1829
+ // Should associate private subnets with correct route table
1830
+ expect(result.resources.Resources.FriggSubnet1RouteAssociation).toBeDefined();
1831
+ expect(result.resources.Resources.FriggSubnet2RouteAssociation).toBeDefined();
1832
+ });
1833
+
1834
+ it('should handle EIP already associated error by reusing existing NAT', async () => {
1835
+ const mockDiscovery = require('./aws-discovery').AWSDiscovery;
1836
+ const mockInstance = new mockDiscovery();
1837
+ mockInstance.discoverResources = jest.fn().mockResolvedValue({
1838
+ defaultVpcId: 'vpc-123456',
1839
+ defaultSecurityGroupId: 'sg-123456',
1840
+ privateSubnetId1: 'subnet-private1',
1841
+ privateSubnetId2: 'subnet-private2',
1842
+ publicSubnetId: 'subnet-public',
1843
+ existingNatGatewayId: 'nat-existing',
1844
+ natGatewayInPrivateSubnet: false, // NAT is correctly placed
1845
+ existingElasticIpAllocationId: 'eipalloc-inuse',
1846
+ elasticIpAlreadyAssociated: true // EIP is already in use
1847
+ });
1848
+ mockDiscovery.mockImplementation(() => mockInstance);
1849
+
1850
+ const appDefinition = {
1851
+ vpc: {
1852
+ enable: true,
1853
+ natGateway: { management: 'createAndManage' },
1854
+ selfHeal: true
1855
+ },
1856
+ integrations: []
1857
+ };
1858
+
1859
+ const result = await composeServerlessDefinition(appDefinition);
1860
+
1861
+ // Should NOT create new NAT or EIP (reuse existing)
1862
+ expect(result.resources.Resources.FriggNATGateway).toBeUndefined();
1863
+ expect(result.resources.Resources.FriggNATGatewayEIP).toBeUndefined();
1864
+
1865
+ // Should use existing NAT
1866
+ expect(result.resources.Resources.FriggNATRoute.Properties.NatGatewayId)
1867
+ .toEqual('nat-existing');
1868
+ });
1869
+ });
1360
1870
 
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.
1364
1871
  describe('Database Migration Lambda', () => {
1365
- it('should include the migration router and worker in all deployments', async () => {
1366
- const result = await composeServerlessDefinition({ integrations: [] });
1872
+ it('should include dbMigrate function in all deployments', async () => {
1873
+ const appDefinition = {
1874
+ name: 'test-app',
1875
+ integrations: []
1876
+ };
1367
1877
 
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(
1878
+ const result = await composeServerlessDefinition(appDefinition);
1879
+
1880
+ // Check dbMigrate function exists
1881
+ expect(result.functions.dbMigrate).toBeDefined();
1882
+ expect(result.functions.dbMigrate.handler).toBe(
1372
1883
  'node_modules/@friggframework/core/handlers/workers/db-migration.handler'
1373
1884
  );
1374
- expect(result.resources.Resources.DbMigrationQueue).toBeDefined();
1375
- expect(result.resources.Resources.FriggMigrationStatusBucket).toBeDefined();
1376
1885
  });
1377
1886
 
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;
1887
+ it('should configure dbMigrate with correct settings', async () => {
1888
+ const appDefinition = {
1889
+ integrations: []
1890
+ };
1381
1891
 
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
- ]);
1892
+ const result = await composeServerlessDefinition(appDefinition);
1893
+
1894
+ const dbMigrate = result.functions.dbMigrate;
1895
+
1896
+ // Check timeout (5 minutes for long migrations)
1897
+ expect(dbMigrate.timeout).toBe(300);
1898
+
1899
+ // Check memory allocation (extra for Prisma CLI)
1900
+ expect(dbMigrate.memorySize).toBe(512);
1901
+
1902
+ // Check description
1903
+ expect(dbMigrate.description).toContain('database migrations');
1904
+ expect(dbMigrate.description).toContain('Prisma');
1392
1905
  });
1393
1906
 
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
- );
1907
+ it('should not have HTTP events (manual invocation only)', async () => {
1908
+ const appDefinition = {
1909
+ integrations: []
1910
+ };
1399
1911
 
1400
- expect(paths).toEqual(
1401
- expect.arrayContaining([
1402
- 'POST /admin/db-migrate',
1403
- 'GET /admin/db-migrate/status',
1404
- ])
1405
- );
1912
+ const result = await composeServerlessDefinition(appDefinition);
1913
+
1914
+ const dbMigrate = result.functions.dbMigrate;
1915
+
1916
+ // Should have no events (manually invoked via AWS CLI)
1917
+ expect(dbMigrate.events).toBeUndefined();
1406
1918
  });
1407
1919
 
1408
- it('should include the migration functions with VPC enabled', async () => {
1409
- const result = await composeServerlessDefinition({
1410
- vpc: { enable: true },
1411
- integrations: [],
1412
- });
1920
+ it('should include dbMigrate even with VPC enabled', async () => {
1921
+ const appDefinition = {
1922
+ vpc: {
1923
+ enable: true,
1924
+ management: 'discover'
1925
+ },
1926
+ integrations: []
1927
+ };
1928
+
1929
+ const result = await composeServerlessDefinition(appDefinition);
1413
1930
 
1414
- expect(result.functions.dbMigrationWorker).toBeDefined();
1415
- expect(result.functions.dbMigrationRouter).toBeDefined();
1931
+ // dbMigrate should exist with VPC configuration
1932
+ expect(result.functions.dbMigrate).toBeDefined();
1933
+
1934
+ // Should have same VPC access as other functions
1416
1935
  expect(result.provider.vpc).toBeDefined();
1417
1936
  });
1418
1937
 
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
- });
1938
+ it('should include dbMigrate with database configuration', async () => {
1939
+ const appDefinition = {
1940
+ vpc: {
1941
+ enable: true,
1942
+ management: 'discover'
1943
+ },
1944
+ database: {
1945
+ postgres: {
1946
+ enable: true,
1947
+ management: 'discover'
1948
+ }
1949
+ },
1950
+ integrations: []
1951
+ };
1952
+
1953
+ const result = await composeServerlessDefinition(appDefinition);
1424
1954
 
1425
- expect(result.functions.dbMigrationWorker).toBeUndefined();
1426
- expect(result.functions.dbMigrationRouter).toBeUndefined();
1955
+ // dbMigrate should exist alongside database configuration
1956
+ expect(result.functions.dbMigrate).toBeDefined();
1957
+ expect(result.provider.environment.DB_TYPE).toBe('postgresql');
1958
+ expect(result.provider.environment.DATABASE_URL).toBeDefined();
1427
1959
  });
1428
1960
  });
1429
1961
 
@@ -1452,10 +1984,7 @@ describe('composeServerlessDefinition', () => {
1452
1984
  integrations: [invalidIntegration]
1453
1985
  };
1454
1986
 
1455
- await expectValidationError(
1456
- appDefinition,
1457
- 'Integration at index 0 is missing Definition or name'
1458
- );
1987
+ await expect(composeServerlessDefinition(appDefinition)).rejects.toThrow('Invalid integration: missing Definition or name');
1459
1988
  });
1460
1989
 
1461
1990
  it('should handle integration with missing name', async () => {
@@ -1466,10 +1995,7 @@ describe('composeServerlessDefinition', () => {
1466
1995
  integrations: [invalidIntegration]
1467
1996
  };
1468
1997
 
1469
- await expectValidationError(
1470
- appDefinition,
1471
- 'Integration at index 0 is missing Definition or name'
1472
- );
1998
+ await expect(composeServerlessDefinition(appDefinition)).rejects.toThrow('Invalid integration: missing Definition or name');
1473
1999
  });
1474
2000
  });
1475
2001
  });