@friggframework/devtools 2.0.0-next.121 → 2.0.0-next.122

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 +30 -24
  2. package/frigg-cli/__tests__/unit/commands/doctor.test.js +10 -6
  3. package/frigg-cli/__tests__/unit/commands/install.test.js +7 -0
  4. package/frigg-cli/__tests__/unit/commands/ui.test.js +31 -30
  5. package/frigg-cli/__tests__/unit/dependencies.test.js +6 -2
  6. package/infrastructure/__tests__/postgres-config.test.js +241 -835
  7. package/infrastructure/__tests__/template-generation.test.js +36 -8
  8. package/infrastructure/domains/health/application/use-cases/__tests__/mismatch-analyzer-method-name.test.js +12 -8
  9. package/infrastructure/domains/health/application/use-cases/__tests__/repair-via-import-use-case.test.js +19 -7
  10. package/infrastructure/domains/health/application/use-cases/run-health-check-use-case.test.js +12 -8
  11. package/infrastructure/domains/health/domain/services/__tests__/import-progress-monitor.test.js +17 -18
  12. package/infrastructure/domains/health/domain/services/__tests__/update-progress-monitor.test.js +12 -2
  13. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-relationship-analysis.test.js +8 -1
  14. package/infrastructure/domains/health/infrastructure/adapters/aws-property-reconciler.test.js +4 -2
  15. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-detector.test.js +10 -0
  16. package/infrastructure/domains/networking/vpc-builder.js +18 -8
  17. package/infrastructure/domains/networking/vpc-builder.test.js +26 -12
  18. package/infrastructure/domains/shared/cloudformation-discovery.test.js +36 -6
  19. package/infrastructure/infrastructure-composer.test.js +268 -794
  20. package/infrastructure/scripts/build-prisma-layer.test.js +28 -7
  21. package/infrastructure/scripts/build-time-discovery.test.js +18 -3
  22. package/package.json +7 -7
  23. package/frigg-cli/index.test.js +0 -158
  24. package/infrastructure/integration.test.js +0 -381
@@ -35,8 +35,29 @@ 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
+
38
44
  const { gatherDiscoveredResources } = require('./domains/shared/resource-discovery');
39
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
+
40
61
  describe('composeServerlessDefinition', () => {
41
62
  let mockIntegration;
42
63
 
@@ -65,21 +86,11 @@ describe('composeServerlessDefinition', () => {
65
86
  process.argv = ['node', 'test'];
66
87
  });
67
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.
68
93
  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
- });
83
94
 
84
95
  it('should run AWS discovery when VPC features are enabled', async () => {
85
96
  gatherDiscoveredResources.mockClear();
@@ -94,22 +105,6 @@ describe('composeServerlessDefinition', () => {
94
105
  expect(gatherDiscoveredResources).toHaveBeenCalledTimes(1);
95
106
  });
96
107
 
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
-
113
108
  it('should run AWS discovery when FRIGG_SKIP_AWS_DISCOVERY is not set', async () => {
114
109
  gatherDiscoveredResources.mockClear();
115
110
  delete process.env.FRIGG_SKIP_AWS_DISCOVERY;
@@ -420,11 +415,15 @@ describe('composeServerlessDefinition', () => {
420
415
  });
421
416
 
422
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.
423
420
  const appDefinition = {
424
421
  vpc: {
425
422
  enable: true,
426
- management: 'discover',
423
+ management: 'use-existing',
424
+ vpcId: 'vpc-123456',
427
425
  securityGroupIds: ['sg-custom-1', 'sg-custom-2'],
426
+ subnets: { ids: ['subnet-123456', 'subnet-789012'] },
428
427
  },
429
428
  integrations: [],
430
429
  };
@@ -438,27 +437,25 @@ describe('composeServerlessDefinition', () => {
438
437
  });
439
438
 
440
439
  it('should throw when discover mode finds no subnets and self-heal is disabled', async () => {
441
- const discoveryInstance = {
442
- discoverResources: jest.fn().mockResolvedValue(
443
- createDiscoveryResponse({
444
- privateSubnetId1: null,
445
- privateSubnetId2: null,
446
- })
447
- ),
448
- };
449
- AWSDiscovery.mockImplementation(() => discoveryInstance);
440
+ gatherDiscoveredResources.mockResolvedValue(
441
+ createDiscoveryResponse({
442
+ privateSubnetId1: null,
443
+ privateSubnetId2: null,
444
+ })
445
+ );
450
446
 
451
447
  const appDefinition = {
452
448
  vpc: {
453
449
  enable: true,
454
450
  management: 'discover',
451
+ selfHeal: false,
455
452
  subnets: { management: 'discover' },
456
453
  },
457
454
  integrations: [],
458
455
  };
459
456
 
460
457
  await expect(composeServerlessDefinition(appDefinition)).rejects.toThrow(
461
- '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.'
462
459
  );
463
460
  });
464
461
 
@@ -492,6 +489,11 @@ describe('composeServerlessDefinition', () => {
492
489
  });
493
490
 
494
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
+
495
497
  const appDefinition = {
496
498
  vpc: {
497
499
  enable: true,
@@ -510,7 +512,7 @@ describe('composeServerlessDefinition', () => {
510
512
  expect(result.resources.Resources.FriggLambdaRouteTable).toBeDefined();
511
513
 
512
514
  // Verify subnet associations
513
- expect(result.resources.Resources.FriggPublicSubnetRouteTableAssociation).toBeDefined();
515
+ expect(result.resources.Resources.FriggPublicSubnet1RouteTableAssociation).toBeDefined();
514
516
  expect(result.resources.Resources.FriggPrivateSubnet1RouteTableAssociation).toBeDefined();
515
517
  expect(result.resources.Resources.FriggPrivateSubnet2RouteTableAssociation).toBeDefined();
516
518
  });
@@ -524,8 +526,9 @@ describe('composeServerlessDefinition', () => {
524
526
  integrations: []
525
527
  };
526
528
 
527
- await expect(composeServerlessDefinition(appDefinition)).rejects.toThrow(
528
- '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"'
529
532
  );
530
533
  });
531
534
 
@@ -553,9 +556,11 @@ describe('composeServerlessDefinition', () => {
553
556
 
554
557
  const result = await composeServerlessDefinition(appDefinition);
555
558
 
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');
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');
559
564
  });
560
565
 
561
566
  it('should skip creating VPC endpoints when disabled explicitly', async () => {
@@ -570,9 +575,9 @@ describe('composeServerlessDefinition', () => {
570
575
 
571
576
  const result = await composeServerlessDefinition(appDefinition);
572
577
 
573
- expect(result.resources.Resources.VPCEndpointS3).toBeUndefined();
574
- expect(result.resources.Resources.VPCEndpointKMS).toBeUndefined();
575
- 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();
576
581
  });
577
582
 
578
583
  it('should add Secrets Manager endpoint only when enabled', async () => {
@@ -588,7 +593,8 @@ describe('composeServerlessDefinition', () => {
588
593
 
589
594
  const result = await composeServerlessDefinition(appDefinition);
590
595
 
591
- expect(result.resources.Resources.VPCEndpointSecretsManager).toBeDefined();
596
+ expect(result.resources.Resources.FriggSecretsManagerVPCEndpoint).toBeDefined();
597
+ expect(result.resources.Resources.FriggKMSVPCEndpoint).toBeDefined();
592
598
  });
593
599
 
594
600
  it('should allow Lambda security group access for VPC endpoints when security group is discovered', async () => {
@@ -602,7 +608,7 @@ describe('composeServerlessDefinition', () => {
602
608
  };
603
609
 
604
610
  const result = await composeServerlessDefinition(appDefinition);
605
- const endpointSg = result.resources.Resources.VPCEndpointSecurityGroup;
611
+ const endpointSg = result.resources.Resources.FriggVPCEndpointSecurityGroup;
606
612
 
607
613
  expect(endpointSg).toBeDefined();
608
614
  expect(endpointSg.Properties.SecurityGroupIngress).toEqual([
@@ -611,81 +617,39 @@ describe('composeServerlessDefinition', () => {
611
617
  FromPort: 443,
612
618
  ToPort: 443,
613
619
  SourceSecurityGroupId: 'sg-123456',
614
- Description: 'HTTPS from Lambda security group'
620
+ Description: 'HTTPS from Lambda'
615
621
  }
616
622
  ]);
617
623
  });
618
624
 
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
-
626
- const appDefinition = {
627
- vpc: {
628
- enable: true,
629
- management: 'discover',
630
- securityGroupIds: [
631
- {
632
- 'Fn::ImportValue': 'shared-lambda-security-group',
633
- },
634
- ],
635
- },
636
- encryption: { fieldLevelEncryptionMethod: 'kms' },
637
- integrations: [],
638
- };
639
-
640
- const result = await composeServerlessDefinition(appDefinition);
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
-
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' };
664
630
  const appDefinition = {
665
631
  vpc: {
666
632
  enable: true,
667
- management: 'discover',
668
- securityGroupIds: [
669
- {
670
- 'Fn::ImportValue': 'shared-lambda-security-group',
671
- },
672
- ],
633
+ management: 'use-existing',
634
+ vpcId: 'vpc-123456',
635
+ securityGroupIds: [importedSg],
636
+ subnets: { ids: ['subnet-123456', 'subnet-789012'] },
673
637
  },
674
638
  encryption: { fieldLevelEncryptionMethod: 'kms' },
675
639
  integrations: [],
676
640
  };
677
641
 
678
642
  const result = await composeServerlessDefinition(appDefinition);
679
- const endpointSg = result.resources.Resources.VPCEndpointSecurityGroup;
643
+ const endpointSg = result.resources.Resources.FriggVPCEndpointSecurityGroup;
680
644
 
681
- expect(endpointSg).toBeDefined();
645
+ expect(result.provider.vpc.securityGroupIds).toEqual([importedSg]);
682
646
  expect(endpointSg.Properties.SecurityGroupIngress).toEqual([
683
647
  {
684
648
  IpProtocol: 'tcp',
685
649
  FromPort: 443,
686
650
  ToPort: 443,
687
- CidrIp: '172.31.0.0/16',
688
- Description: 'HTTPS from default VPC range',
651
+ SourceSecurityGroupId: importedSg,
652
+ Description: 'HTTPS from Lambda',
689
653
  },
690
654
  ]);
691
655
  });
@@ -710,14 +674,7 @@ describe('composeServerlessDefinition', () => {
710
674
  FromPort: 443,
711
675
  ToPort: 443,
712
676
  SourceSecurityGroupId: { Ref: 'FriggLambdaSecurityGroup' },
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)'
677
+ Description: 'HTTPS from Lambda'
721
678
  }
722
679
  ]);
723
680
  });
@@ -731,7 +688,7 @@ describe('composeServerlessDefinition', () => {
731
688
  const result = await composeServerlessDefinition(appDefinition);
732
689
 
733
690
  expect(result.provider.vpc).toBeUndefined();
734
- expect(result.resources.Resources.VPCEndpointS3).toBeUndefined();
691
+ expect(result.resources.Resources.FriggS3VPCEndpoint).toBeUndefined();
735
692
  });
736
693
 
737
694
  it('should not add VPC configuration when vpc is not defined', async () => {
@@ -745,116 +702,87 @@ describe('composeServerlessDefinition', () => {
745
702
  });
746
703
  });
747
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.
748
709
  describe('NAT Gateway behaviour', () => {
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);
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
+ );
759
717
 
760
- const appDefinition = {
718
+ const result = await composeServerlessDefinition({
761
719
  vpc: {
762
720
  enable: true,
763
721
  management: 'discover',
764
722
  natGateway: { management: 'discover' },
765
723
  },
766
724
  integrations: [],
767
- };
768
-
769
- const result = await composeServerlessDefinition(appDefinition);
725
+ });
770
726
 
771
727
  expect(result.resources.Resources.FriggNATGateway).toBeUndefined();
772
- 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
+ });
773
733
  });
774
734
 
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);
735
+ it('should route through a provided NAT gateway ID', async () => {
736
+ gatherDiscoveredResources.mockResolvedValue(
737
+ createDiscoveryResponse({ existingNatGatewayId: null })
738
+ );
782
739
 
783
- const appDefinition = {
740
+ const result = await composeServerlessDefinition({
784
741
  vpc: {
785
742
  enable: true,
786
743
  management: 'discover',
787
744
  natGateway: { management: 'useExisting', id: 'nat-custom-001' },
788
745
  },
789
746
  integrations: [],
790
- };
791
-
792
- const result = await composeServerlessDefinition(appDefinition);
747
+ });
793
748
 
794
749
  expect(result.resources.Resources.FriggNATGateway).toBeUndefined();
795
- expect(result.resources.Resources.FriggNATRoute.Properties.NatGatewayId).toBe('nat-custom-001');
796
- });
797
-
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'
750
+ expect(result.resources.Resources.FriggPrivateRoute.Properties.NatGatewayId).toBe(
751
+ 'nat-custom-001'
824
752
  );
825
753
  });
826
754
 
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);
755
+ it('should create a retained NAT gateway in a public subnet with createAndManage', async () => {
756
+ gatherDiscoveredResources.mockResolvedValue(
757
+ createDiscoveryResponse({ existingNatGatewayId: null })
758
+ );
838
759
 
839
- const appDefinition = {
760
+ const result = await composeServerlessDefinition({
840
761
  vpc: {
841
762
  enable: true,
842
763
  management: 'discover',
843
764
  natGateway: { management: 'createAndManage' },
844
- selfHeal: true,
845
765
  },
846
766
  integrations: [],
847
- };
848
-
849
- const result = await composeServerlessDefinition(appDefinition);
767
+ });
850
768
 
851
- expect(result.resources.Resources.FriggPublicSubnet).toBeDefined();
852
- 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
+ });
853
779
  });
854
780
  });
855
781
 
856
782
  describe('KMS Configuration', () => {
857
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';
858
786
  const appDefinition = {
859
787
  encryption: { fieldLevelEncryptionMethod: 'kms' },
860
788
  integrations: []
@@ -862,7 +790,8 @@ describe('composeServerlessDefinition', () => {
862
790
 
863
791
  const result = await composeServerlessDefinition(appDefinition);
864
792
 
865
- // Check IAM permissions
793
+ // IAM: the Lambda role uses the discovered key directly (no
794
+ // serverless-kms-grants plugin, which KmsBuilder no longer uses).
866
795
  const kmsPermission = result.provider.iamRoleStatements.find(
867
796
  statement => statement.Action.includes('kms:GenerateDataKey')
868
797
  );
@@ -870,49 +799,26 @@ describe('composeServerlessDefinition', () => {
870
799
  Effect: 'Allow',
871
800
  Action: [
872
801
  'kms:GenerateDataKey',
873
- 'kms:Decrypt'
802
+ 'kms:Decrypt',
803
+ 'kms:Encrypt',
804
+ 'kms:DescribeKey'
874
805
  ],
875
- Resource: ['arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012']
806
+ Resource: keyArn
876
807
  });
877
808
 
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
- });
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();
899
814
  });
900
815
 
901
816
  it('should create new KMS key when encryption is enabled, no key found, and createResourceIfNoneFound is true', async () => {
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
- }));
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
+ );
916
822
 
917
823
  const appDefinition = {
918
824
  encryption: {
@@ -924,116 +830,25 @@ describe('composeServerlessDefinition', () => {
924
830
 
925
831
  const result = await composeServerlessDefinition(appDefinition);
926
832
 
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
- });
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);
985
837
 
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
838
+ const keyRef = { 'Fn::GetAtt': ['FriggKMSKey', 'Arn'] };
998
839
  const kmsPermission = result.provider.iamRoleStatements.find(
999
840
  statement => statement.Action.includes('kms:GenerateDataKey')
1000
841
  );
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
- });
842
+ expect(kmsPermission.Resource).toEqual(keyRef);
843
+ expect(result.provider.environment.KMS_KEY_ARN).toEqual(keyRef);
1020
844
  });
1021
845
 
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
- }));
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
+ );
1037
852
 
1038
853
  const appDefinition = {
1039
854
  encryption: {
@@ -1043,27 +858,22 @@ describe('composeServerlessDefinition', () => {
1043
858
  integrations: []
1044
859
  };
1045
860
 
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.'
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}'
1049
868
  );
1050
869
  });
1051
870
 
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
- }));
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
+ );
1067
877
 
1068
878
  const appDefinition = {
1069
879
  encryption: {
@@ -1073,10 +883,12 @@ describe('composeServerlessDefinition', () => {
1073
883
  integrations: []
1074
884
  };
1075
885
 
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
- );
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);
1080
892
  });
1081
893
 
1082
894
  it('should not add KMS configuration when encryption is disabled', async () => {
@@ -1234,8 +1046,9 @@ describe('composeServerlessDefinition', () => {
1234
1046
 
1235
1047
  const result = await composeServerlessDefinition(appDefinition);
1236
1048
 
1237
- // Check integration function
1238
- 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({
1239
1052
  handler: 'node_modules/@friggframework/core/handlers/routers/integration-defined-routers.handlers.testIntegration.handler',
1240
1053
  events: [{
1241
1054
  httpApi: {
@@ -1243,7 +1056,7 @@ describe('composeServerlessDefinition', () => {
1243
1056
  method: 'ANY'
1244
1057
  }
1245
1058
  }]
1246
- });
1059
+ }));
1247
1060
 
1248
1061
  // Check SQS Queue
1249
1062
  expect(result.resources.Resources.TestIntegrationQueue).toEqual({
@@ -1262,7 +1075,7 @@ describe('composeServerlessDefinition', () => {
1262
1075
  });
1263
1076
 
1264
1077
  // Check Queue Worker
1265
- expect(result.functions.testIntegrationQueueWorker).toEqual({
1078
+ expect(result.functions.testIntegrationQueueWorker).toEqual(expect.objectContaining({
1266
1079
  handler: 'node_modules/@friggframework/core/handlers/workers/integration-defined-workers.handlers.testIntegration.queueWorker',
1267
1080
  reservedConcurrency: 20,
1268
1081
  events: [{
@@ -1274,8 +1087,9 @@ describe('composeServerlessDefinition', () => {
1274
1087
  functionResponseType: 'ReportBatchItemFailures'
1275
1088
  }
1276
1089
  }],
1277
- timeout: 600
1278
- });
1090
+ // Lambda maximum; the queue's VisibilityTimeout stays above it
1091
+ timeout: 900
1092
+ }));
1279
1093
 
1280
1094
  // Check environment variable
1281
1095
  expect(result.provider.environment.TESTINTEGRATION_QUEUE_URL).toEqual({
@@ -1312,146 +1126,20 @@ describe('composeServerlessDefinition', () => {
1312
1126
  const fs = require('fs');
1313
1127
  const path = require('path');
1314
1128
 
1315
- 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.
1316
1132
  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);
1320
-
1321
- const appDefinition = { integrations: [] };
1322
1133
 
1323
- const result = await composeServerlessDefinition(appDefinition);
1324
-
1325
- expect(existsSpy).toHaveBeenCalled();
1326
- expect(result.functions.auth.handler.startsWith('../node_modules/')).toBe(true);
1134
+ const result = await composeServerlessDefinition({ integrations: [] });
1327
1135
 
1328
- existsSpy.mockRestore();
1136
+ expect(result.functions.auth.handler).toBe(
1137
+ 'node_modules/@friggframework/core/handlers/routers/auth.handler'
1138
+ );
1329
1139
  });
1330
1140
  });
1331
1141
 
1332
1142
  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
-
1455
1143
  it('should enable self-healing when selfHeal is true', async () => {
1456
1144
  const appDefinition = {
1457
1145
  vpc: {
@@ -1489,15 +1177,13 @@ describe('composeServerlessDefinition', () => {
1489
1177
 
1490
1178
  const result = await composeServerlessDefinition(appDefinition);
1491
1179
 
1492
- // VPC
1180
+ // VPC (plus the interface endpoints KMS needs from private subnets)
1493
1181
  expect(result.provider.vpc).toBeDefined();
1494
- // custom.vpc doesn't exist in the serverless template
1495
- expect(result.resources.Resources.VPCEndpointS3).toBeDefined();
1182
+ expect(result.resources.Resources.FriggS3VPCEndpoint).toBeDefined();
1183
+ expect(result.resources.Resources.FriggKMSVPCEndpoint).toBeDefined();
1496
1184
 
1497
1185
  // KMS
1498
- expect(result.plugins).toContain('serverless-kms-grants');
1499
1186
  expect(result.provider.environment.KMS_KEY_ARN).toBeDefined();
1500
- expect(result.custom.kmsGrants).toBeDefined();
1501
1187
 
1502
1188
  // SSM (enabled without offload markers -> broad grant only, no offload env vars)
1503
1189
  const ssmPermission = result.provider.iamRoleStatements.find(
@@ -1510,14 +1196,12 @@ describe('composeServerlessDefinition', () => {
1510
1196
  expect(result.functions.testIntegration).toBeDefined();
1511
1197
  expect(result.resources.Resources.TestIntegrationQueue).toBeDefined();
1512
1198
 
1513
- // All plugins should be present
1199
+ // No feature adds a Serverless plugin of its own
1514
1200
  expect(result.plugins).toEqual([
1515
- 'serverless-jetpack',
1516
- 'serverless-dotenv-plugin',
1201
+ 'serverless-esbuild',
1517
1202
  'serverless-offline-sqs',
1518
1203
  'serverless-offline',
1519
1204
  '@friggframework/serverless-plugin',
1520
- 'serverless-kms-grants'
1521
1205
  ]);
1522
1206
  });
1523
1207
 
@@ -1538,10 +1222,13 @@ describe('composeServerlessDefinition', () => {
1538
1222
 
1539
1223
  // VPC and KMS should be present
1540
1224
  expect(result.provider.vpc).toBeDefined();
1541
- expect(result.custom.kmsGrants).toBeDefined();
1225
+ expect(result.provider.environment.KMS_KEY_ARN).toBeDefined();
1542
1226
 
1543
1227
  // SSM should not be present
1544
- 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();
1545
1232
  expect(result.provider.environment.SSM_PARAMETER_PREFIX).toBeUndefined();
1546
1233
  });
1547
1234
  });
@@ -1565,10 +1252,14 @@ describe('composeServerlessDefinition', () => {
1565
1252
  expect(result.functions.user).toBeDefined();
1566
1253
  expect(result.functions.health).toBeDefined();
1567
1254
 
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');
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
+ ]);
1572
1263
  });
1573
1264
 
1574
1265
  it('should always include default IAM permissions', async () => {
@@ -1598,8 +1289,14 @@ describe('composeServerlessDefinition', () => {
1598
1289
 
1599
1290
  const result = await composeServerlessDefinition(appDefinition);
1600
1291
 
1601
- expect(result.provider.environment.STAGE).toBe('${opt:stage, "dev"}');
1602
- 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
+ );
1603
1300
  });
1604
1301
  });
1605
1302
 
@@ -1656,306 +1353,77 @@ describe('composeServerlessDefinition', () => {
1656
1353
  });
1657
1354
  });
1658
1355
 
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
- });
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', ...).
1870
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.
1871
1364
  describe('Database Migration Lambda', () => {
1872
- it('should include dbMigrate function in all deployments', async () => {
1873
- const appDefinition = {
1874
- name: 'test-app',
1875
- integrations: []
1876
- };
1877
-
1878
- const result = await composeServerlessDefinition(appDefinition);
1365
+ it('should include the migration router and worker in all deployments', async () => {
1366
+ const result = await composeServerlessDefinition({ integrations: [] });
1879
1367
 
1880
- // Check dbMigrate function exists
1881
- expect(result.functions.dbMigrate).toBeDefined();
1882
- 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(
1883
1372
  'node_modules/@friggframework/core/handlers/workers/db-migration.handler'
1884
1373
  );
1374
+ expect(result.resources.Resources.DbMigrationQueue).toBeDefined();
1375
+ expect(result.resources.Resources.FriggMigrationStatusBucket).toBeDefined();
1885
1376
  });
1886
1377
 
1887
- it('should configure dbMigrate with correct settings', async () => {
1888
- const appDefinition = {
1889
- integrations: []
1890
- };
1891
-
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);
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;
1901
1381
 
1902
- // Check description
1903
- expect(dbMigrate.description).toContain('database migrations');
1904
- 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
+ ]);
1905
1392
  });
1906
1393
 
1907
- it('should not have HTTP events (manual invocation only)', async () => {
1908
- const appDefinition = {
1909
- integrations: []
1910
- };
1911
-
1912
- const result = await composeServerlessDefinition(appDefinition);
1913
-
1914
- 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
+ );
1915
1399
 
1916
- // Should have no events (manually invoked via AWS CLI)
1917
- expect(dbMigrate.events).toBeUndefined();
1400
+ expect(paths).toEqual(
1401
+ expect.arrayContaining([
1402
+ 'POST /admin/db-migrate',
1403
+ 'GET /admin/db-migrate/status',
1404
+ ])
1405
+ );
1918
1406
  });
1919
1407
 
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);
1930
-
1931
- // dbMigrate should exist with VPC configuration
1932
- 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
+ });
1933
1413
 
1934
- // Should have same VPC access as other functions
1414
+ expect(result.functions.dbMigrationWorker).toBeDefined();
1415
+ expect(result.functions.dbMigrationRouter).toBeDefined();
1935
1416
  expect(result.provider.vpc).toBeDefined();
1936
1417
  });
1937
1418
 
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);
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
+ });
1954
1424
 
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();
1425
+ expect(result.functions.dbMigrationWorker).toBeUndefined();
1426
+ expect(result.functions.dbMigrationRouter).toBeUndefined();
1959
1427
  });
1960
1428
  });
1961
1429
 
@@ -1984,7 +1452,10 @@ describe('composeServerlessDefinition', () => {
1984
1452
  integrations: [invalidIntegration]
1985
1453
  };
1986
1454
 
1987
- 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
+ );
1988
1459
  });
1989
1460
 
1990
1461
  it('should handle integration with missing name', async () => {
@@ -1995,7 +1466,10 @@ describe('composeServerlessDefinition', () => {
1995
1466
  integrations: [invalidIntegration]
1996
1467
  };
1997
1468
 
1998
- 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
+ );
1999
1473
  });
2000
1474
  });
2001
1475
  });