@friggframework/devtools 2.0.0--canary.686.df38e8e.0 → 2.0.0--canary.710.9045bbc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/frigg-cli/README.md +77 -30
  2. package/frigg-cli/__tests__/unit/commands/deploy.test.js +30 -24
  3. package/frigg-cli/__tests__/unit/commands/doctor.test.js +10 -6
  4. package/frigg-cli/__tests__/unit/commands/generate-iam.test.js +18 -0
  5. package/frigg-cli/__tests__/unit/commands/init.test.js +688 -0
  6. package/frigg-cli/__tests__/unit/commands/install.test.js +601 -341
  7. package/frigg-cli/__tests__/unit/commands/ui.test.js +31 -30
  8. package/frigg-cli/__tests__/unit/dependencies.test.js +6 -2
  9. package/frigg-cli/build-command/index.js +1 -32
  10. package/frigg-cli/deploy-command/index.js +2 -50
  11. package/frigg-cli/doctor-command/index.js +0 -7
  12. package/frigg-cli/generate-command/index.js +1 -0
  13. package/frigg-cli/generate-iam-command.js +1 -7
  14. package/frigg-cli/index.js +9 -4
  15. package/frigg-cli/init-command/backend-first-handler.js +397 -554
  16. package/frigg-cli/init-command/deployment-modes.js +7 -0
  17. package/frigg-cli/init-command/index.js +82 -35
  18. package/frigg-cli/init-command/safe-path.js +58 -0
  19. package/frigg-cli/init-command/scaffold-dependencies.js +202 -0
  20. package/frigg-cli/install-command/app-definition.js +174 -0
  21. package/frigg-cli/install-command/commit-changes.js +40 -8
  22. package/frigg-cli/install-command/environment-variables.js +15 -0
  23. package/frigg-cli/install-command/index.js +96 -21
  24. package/frigg-cli/install-command/install-package.js +77 -4
  25. package/frigg-cli/install-command/integration-file.js +20 -11
  26. package/frigg-cli/install-command/resolve-module.js +69 -0
  27. package/frigg-cli/install-command/template.js +102 -75
  28. package/frigg-cli/install-command/validate-package.js +36 -4
  29. package/frigg-cli/package.json +1 -1
  30. package/frigg-cli/repair-command/index.js +0 -7
  31. package/frigg-cli/start-command/index.js +0 -58
  32. package/frigg-cli/templates/backend/README.md +267 -0
  33. package/frigg-cli/templates/backend/env.example +20 -0
  34. package/frigg-cli/templates/backend/gitignore +10 -0
  35. package/frigg-cli/templates/backend/index.js +114 -0
  36. package/frigg-cli/templates/backend/infrastructure.js +20 -0
  37. package/frigg-cli/test/init-command.test.js +9 -2
  38. package/infrastructure/README.md +2 -4
  39. package/infrastructure/__tests__/postgres-config.test.js +241 -835
  40. package/infrastructure/__tests__/scaffold-default-infrastructure.test.js +148 -0
  41. package/infrastructure/__tests__/template-generation.test.js +33 -12
  42. package/infrastructure/create-frigg-infrastructure.js +0 -14
  43. package/infrastructure/docs/POSTGRES-CONFIGURATION.md +21 -1
  44. package/infrastructure/domains/admin-scripts/admin-script-builder.js +6 -2
  45. package/infrastructure/domains/admin-scripts/admin-script-builder.test.js +30 -0
  46. package/infrastructure/domains/database/aurora-builder.js +13 -2
  47. package/infrastructure/domains/database/aurora-builder.test.js +22 -0
  48. package/infrastructure/domains/health/application/use-cases/__tests__/mismatch-analyzer-method-name.test.js +12 -8
  49. package/infrastructure/domains/health/application/use-cases/__tests__/repair-via-import-use-case.test.js +19 -7
  50. package/infrastructure/domains/health/application/use-cases/run-health-check-use-case.test.js +12 -8
  51. package/infrastructure/domains/health/domain/services/__tests__/import-progress-monitor.test.js +17 -18
  52. package/infrastructure/domains/health/domain/services/__tests__/update-progress-monitor.test.js +12 -2
  53. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-relationship-analysis.test.js +8 -1
  54. package/infrastructure/domains/health/infrastructure/adapters/aws-property-reconciler.test.js +4 -2
  55. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-detector.test.js +10 -0
  56. package/infrastructure/domains/networking/vpc-builder.js +18 -8
  57. package/infrastructure/domains/networking/vpc-builder.test.js +32 -13
  58. package/infrastructure/domains/parameters/offload-utils.js +0 -1
  59. package/infrastructure/domains/security/iam-generator.js +112 -5
  60. package/infrastructure/domains/security/iam-generator.test.js +94 -0
  61. package/infrastructure/domains/shared/cloudformation-discovery.test.js +36 -6
  62. package/infrastructure/domains/shared/environment-builder.js +1 -12
  63. package/infrastructure/domains/shared/environment-builder.test.js +0 -20
  64. package/infrastructure/domains/shared/types/app-definition.js +1 -15
  65. package/infrastructure/domains/shared/utilities/base-definition-factory.js +17 -30
  66. package/infrastructure/domains/shared/utilities/base-definition-factory.test.js +22 -85
  67. package/infrastructure/infrastructure-composer.test.js +268 -801
  68. package/infrastructure/scripts/build-prisma-layer.js +5 -32
  69. package/infrastructure/scripts/build-prisma-layer.test.js +28 -42
  70. package/infrastructure/scripts/build-time-discovery.test.js +18 -3
  71. package/package.json +10 -8
  72. package/frigg-cli/__tests__/unit/commands/provider-dispatch.test.js +0 -140
  73. package/frigg-cli/index.test.js +0 -158
  74. package/frigg-cli/utils/provider-helper.js +0 -80
  75. package/infrastructure/__tests__/create-frigg-infrastructure-provider.test.js +0 -64
  76. package/infrastructure/__tests__/management-api-gateway-routes.test.js +0 -335
  77. package/infrastructure/integration.test.js +0 -381
  78. package/infrastructure/provider-build.js +0 -119
  79. package/test/npm-install-guard.js +0 -104
  80. package/test/npm-install-guard.test.js +0 -53
@@ -82,7 +82,14 @@ jest.mock('@aws-sdk/client-kms', () => ({
82
82
  ListAliasesCommand: jest.fn(),
83
83
  }));
84
84
 
85
- describe('Orphan Detection with Relationship Analysis (TDD)', () => {
85
+ // SKIPPED: red-phase TDD spec for a feature that was never implemented.
86
+ // AWSResourceDetector has no findOrphanedResourcesWithRelationships() or
87
+ // _extractReferencedResourceIds(); the design is in
88
+ // domains/health/docs/ORPHAN-DETECTION-ANALYSIS.md. (A template-based variant of
89
+ // the reference analysis lives in RepairViaImportUseCase._extractReferencedIdsFromTemplate.)
90
+ // Un-skip when the relationship analysis is implemented.
91
+ // Tracked in https://github.com/friggframework/frigg/issues/709
92
+ describe.skip('Orphan Detection with Relationship Analysis (TDD)', () => {
86
93
  let detector;
87
94
  let mockEC2Send;
88
95
  let mockRDSSend;
@@ -447,7 +447,9 @@ describe('AWSPropertyReconciler', () => {
447
447
  );
448
448
 
449
449
  expect(strategy.supportsTemplateUpdate).toBe(true);
450
- expect(strategy.supportsResourceUpdate).toBe(false);
450
+ // Lambda supports direct resource-mode reconciliation
451
+ // (UpdateFunctionConfiguration) since 6a0bba7b; template is still preferred.
452
+ expect(strategy.supportsResourceUpdate).toBe(true);
451
453
  expect(strategy.recommendedMode).toBe('template');
452
454
  expect(strategy.limitations).toContain(
453
455
  'VpcConfig changes may take several minutes to propagate'
@@ -659,7 +661,7 @@ describe('AWSPropertyReconciler', () => {
659
661
 
660
662
  expect(strategy).toEqual({
661
663
  supportsTemplateUpdate: true,
662
- supportsResourceUpdate: false,
664
+ supportsResourceUpdate: true, // resource mode via UpdateFunctionConfiguration
663
665
  recommendedMode: 'template',
664
666
  limitations: expect.arrayContaining([
665
667
  'VpcConfig changes may take several minutes to propagate',
@@ -441,6 +441,16 @@ describe('AWSResourceDetector', () => {
441
441
  describe('findOrphanedResources', () => {
442
442
  const StackIdentifier = require('../../domain/value-objects/stack-identifier');
443
443
 
444
+ beforeEach(() => {
445
+ // findOrphanedResources() scans every supported resource type
446
+ // (EC2, RDS and KMS), not just the types in the stack, so every
447
+ // client needs an (empty) response; each test overrides the one
448
+ // service it is about.
449
+ mockEC2Send.mockResolvedValue({});
450
+ mockRDSSend.mockResolvedValue({});
451
+ mockKMSSend.mockResolvedValue({});
452
+ });
453
+
444
454
  it('should find orphaned RDS DBCluster with frigg:stack tag', async () => {
445
455
  const stackIdentifier = new StackIdentifier({
446
456
  stackName: 'my-app-prod',
@@ -439,8 +439,14 @@ class VpcBuilder extends InfrastructureBuilder {
439
439
  translated.vpc.ownership.subnets = 'external';
440
440
  }
441
441
 
442
+ // Legacy options that warnIgnoredOptions() reports as ignored under
443
+ // managementMode='managed' must really be ignored: applying them would
444
+ // undo the ownership chosen above (e.g. vpc.management='discover' turning
445
+ // managed+isolated's ownership.vpc='stack' back into 'auto').
446
+ const honorLegacyModes = globalMode !== 'managed';
447
+
442
448
  // Handle legacy vpc.management modes
443
- const vpcManagement = appDefinition.vpc?.management;
449
+ const vpcManagement = honorLegacyModes ? appDefinition.vpc?.management : undefined;
444
450
  if (vpcManagement === 'create-new') {
445
451
  translated.vpc.ownership.vpc = 'stack';
446
452
  translated.vpc.ownership.securityGroup = 'stack';
@@ -466,7 +472,7 @@ class VpcBuilder extends InfrastructureBuilder {
466
472
  }
467
473
 
468
474
  // Handle legacy shareAcrossStages
469
- if (appDefinition.vpc?.shareAcrossStages !== undefined) {
475
+ if (honorLegacyModes && appDefinition.vpc?.shareAcrossStages !== undefined) {
470
476
  if (appDefinition.vpc.shareAcrossStages) {
471
477
  // Shared VPC - discover and reuse
472
478
  translated.vpc.ownership.vpc = 'auto';
@@ -481,7 +487,7 @@ class VpcBuilder extends InfrastructureBuilder {
481
487
  }
482
488
 
483
489
  // Handle legacy NAT Gateway management
484
- if (appDefinition.vpc?.natGateway?.management === 'createAndManage') {
490
+ if (honorLegacyModes && appDefinition.vpc?.natGateway?.management === 'createAndManage') {
485
491
  // Use 'auto' to allow discovering and reusing properly placed external NAT Gateways
486
492
  // The resolver will check if there's a good external NAT Gateway and reuse it,
487
493
  // or create a new one if needed (or if the existing one is misplaced)
@@ -493,9 +499,10 @@ class VpcBuilder extends InfrastructureBuilder {
493
499
  }
494
500
 
495
501
  // Handle legacy subnet management
496
- if (appDefinition.vpc?.subnets?.management === 'create') {
502
+ const subnetManagement = honorLegacyModes ? appDefinition.vpc?.subnets?.management : undefined;
503
+ if (subnetManagement === 'create') {
497
504
  translated.vpc.ownership.subnets = 'stack';
498
- } else if (appDefinition.vpc?.subnets?.management === 'use-existing' && appDefinition.vpc.subnets.ids) {
505
+ } else if (subnetManagement === 'use-existing' && appDefinition.vpc.subnets.ids) {
499
506
  translated.vpc.ownership.subnets = 'external';
500
507
  translated.vpc.external.subnetIds = appDefinition.vpc.subnets.ids;
501
508
  }
@@ -691,8 +698,11 @@ class VpcBuilder extends InfrastructureBuilder {
691
698
  result.vpcConfig.securityGroupIds = [{ Ref: 'FriggLambdaSecurityGroup' }];
692
699
  console.log(' ✅ Security Group added to template');
693
700
  } else if (decision.ownership === ResourceOwnership.EXTERNAL) {
694
- // Use external security group IDs
695
- const sgIds = Array.isArray(decision.physicalId) ? decision.physicalId : [decision.physicalId];
701
+ // Use external security group IDs. createExternalDecision keeps the
702
+ // full list in physicalIds; physicalId is only the first of them.
703
+ const sgIds = decision.physicalIds?.length
704
+ ? decision.physicalIds
705
+ : Array.isArray(decision.physicalId) ? decision.physicalId : [decision.physicalId];
696
706
  result.vpcConfig.securityGroupIds = sgIds;
697
707
  console.log(` ✓ Using external security group(s): ${sgIds.join(', ')}`);
698
708
  }
@@ -1175,7 +1185,7 @@ class VpcBuilder extends InfrastructureBuilder {
1175
1185
  const vpcId = result.vpcId;
1176
1186
 
1177
1187
  // Determine logical IDs based on what exists in stack for backwards compatibility
1178
- // CRITICAL: Frontify production uses OLD naming (VPCEndpointS3, not FriggS3VPCEndpoint)
1188
+ // CRITICAL: older production stacks use OLD naming (VPCEndpointS3, not FriggS3VPCEndpoint)
1179
1189
  const existingLogicalIds = discoveredResources?.existingLogicalIds || [];
1180
1190
 
1181
1191
 
@@ -293,10 +293,10 @@ describe('VpcBuilder', () => {
293
293
  ]);
294
294
  expect(result.resources.FriggPrivateSubnet1).toBeDefined();
295
295
  expect(result.resources.FriggPrivateSubnet2).toBeDefined();
296
- // In discover mode, we create FriggLambdaSecurityGroup in the discovered VPC
297
- expect(result.vpcConfig.securityGroupIds).toEqual([{ Ref: 'FriggLambdaSecurityGroup' }]);
298
- expect(result.resources.FriggLambdaSecurityGroup).toBeDefined();
299
- expect(result.resources.FriggLambdaSecurityGroup.Properties.VpcId).toBe('vpc-discovered');
296
+ // In discover mode with no stack-managed Lambda SG, the resolver reuses
297
+ // the discovered default security group instead of creating one (37a354e8)
298
+ expect(result.vpcConfig.securityGroupIds).toEqual(['sg-discovered']);
299
+ expect(result.resources.FriggLambdaSecurityGroup).toBeUndefined();
300
300
  });
301
301
 
302
302
  it('should allow sharing discovered subnets when explicitly configured', async () => {
@@ -330,6 +330,8 @@ describe('VpcBuilder', () => {
330
330
  management: 'discover',
331
331
  selfHeal: true,
332
332
  },
333
+ // The DynamoDB gateway endpoint is opt-in since 37a354e8
334
+ database: { dynamodb: { enable: true } },
333
335
  };
334
336
 
335
337
  const discoveredResources = {
@@ -462,6 +464,8 @@ describe('VpcBuilder', () => {
462
464
  const appDefinition = {
463
465
  vpc: { enable: true },
464
466
  encryption: { fieldLevelEncryptionMethod: 'kms' },
467
+ // The DynamoDB gateway endpoint is opt-in since 37a354e8
468
+ database: { dynamodb: { enable: true } },
465
469
  };
466
470
 
467
471
  // Structured discovery from CloudFormation
@@ -522,6 +526,8 @@ describe('VpcBuilder', () => {
522
526
  const appDefinition = {
523
527
  vpc: { enable: true, enableVPCEndpoints: true, selfHeal: true },
524
528
  encryption: { fieldLevelEncryptionMethod: 'kms' },
529
+ // The DynamoDB gateway endpoint is opt-in since 37a354e8
530
+ database: { dynamodb: { enable: true } },
525
531
  };
526
532
  const discoveredResources = {
527
533
  defaultVpcId: 'vpc-123',
@@ -815,7 +821,9 @@ describe('VpcBuilder', () => {
815
821
  };
816
822
 
817
823
  const discoveredResources = {
818
- vpcId: 'vpc-123',
824
+ // Discovery reports the VPC as defaultVpcId (e6fc7c76); with no VPC
825
+ // the resolver refuses to create one implicitly (37a354e8).
826
+ defaultVpcId: 'vpc-123',
819
827
  privateSubnetId1: 'subnet-existing-1',
820
828
  privateSubnetId2: 'subnet-existing-2',
821
829
  natGatewayId: 'nat-existing',
@@ -825,9 +833,15 @@ describe('VpcBuilder', () => {
825
833
 
826
834
  const result = await vpcBuilder.build(appDefinition, discoveredResources);
827
835
 
836
+ // The builder always emits the new association logical IDs, even when
837
+ // the stack still has the old FriggSubnetNRouteAssociation ones, so
838
+ // CloudFormation replaces drifted associations (see createNatGatewayRouting).
839
+ expect(result.resources.FriggSubnet1RouteAssociation).toBeUndefined();
840
+ expect(result.resources.FriggSubnet2RouteAssociation).toBeUndefined();
841
+
828
842
  // Verify associations have UpdateReplacePolicy to force recreation
829
- expect(result.resources.FriggSubnet1RouteAssociation.UpdateReplacePolicy).toBe('Delete');
830
- expect(result.resources.FriggSubnet2RouteAssociation.UpdateReplacePolicy).toBe('Delete');
843
+ expect(result.resources.FriggPrivateSubnet1RouteTableAssociation.UpdateReplacePolicy).toBe('Delete');
844
+ expect(result.resources.FriggPrivateSubnet2RouteTableAssociation.UpdateReplacePolicy).toBe('Delete');
831
845
 
832
846
  // This forces CloudFormation to delete old associations and create new ones
833
847
  // instead of trying to update them in-place (which doesn't work)
@@ -1522,7 +1536,7 @@ describe('VpcBuilder', () => {
1522
1536
  });
1523
1537
 
1524
1538
  it('should use OLD logical IDs for backwards compatibility (FriggNATRoute, VPCEndpointS3 pattern)', async () => {
1525
- // CRITICAL TEST: Real Frontify production stack uses OLD naming convention
1539
+ // CRITICAL TEST: A real production stack uses OLD naming convention
1526
1540
  // Stack currently has: FriggNATRoute, VPCEndpointS3, VPCEndpointDynamoDB
1527
1541
  // We MUST use these same logical IDs to avoid AlreadyExists errors
1528
1542
  const appDefinition = {
@@ -1541,7 +1555,7 @@ describe('VpcBuilder', () => {
1541
1555
  }
1542
1556
  };
1543
1557
 
1544
- // Discovery results matching ACTUAL Frontify production stack
1558
+ // Discovery results matching an actual production stack
1545
1559
  const discoveredResources = {
1546
1560
  fromCloudFormationStack: true,
1547
1561
  stackName: 'create-frigg-app-production',
@@ -1589,10 +1603,13 @@ describe('VpcBuilder', () => {
1589
1603
  expect(result.resources.FriggNATRoute.Type).toBe('AWS::EC2::Route');
1590
1604
  expect(result.resources.FriggPrivateRoute).toBeUndefined(); // Should NOT create new ID
1591
1605
 
1592
- expect(result.resources.FriggSubnet1RouteAssociation).toBeDefined();
1593
- expect(result.resources.FriggSubnet2RouteAssociation).toBeDefined();
1594
- expect(result.resources.FriggPrivateSubnet1RouteTableAssociation).toBeUndefined();
1595
- expect(result.resources.FriggPrivateSubnet2RouteTableAssociation).toBeUndefined();
1606
+ // Subnet associations are the exception: the builder deliberately moves
1607
+ // them to the new logical IDs (with UpdateReplacePolicy: Delete) so
1608
+ // drifted associations are recreated rather than updated in place.
1609
+ expect(result.resources.FriggSubnet1RouteAssociation).toBeUndefined();
1610
+ expect(result.resources.FriggSubnet2RouteAssociation).toBeUndefined();
1611
+ expect(result.resources.FriggPrivateSubnet1RouteTableAssociation).toBeDefined();
1612
+ expect(result.resources.FriggPrivateSubnet2RouteTableAssociation).toBeDefined();
1596
1613
 
1597
1614
  expect(result.resources.VPCEndpointS3).toBeDefined();
1598
1615
  expect(result.resources.VPCEndpointS3.Type).toBe('AWS::EC2::VPCEndpoint');
@@ -1814,6 +1831,8 @@ describe('VpcBuilder', () => {
1814
1831
  const appDefinition = {
1815
1832
  vpc: { enable: true },
1816
1833
  encryption: { fieldLevelEncryptionMethod: 'kms' },
1834
+ // The DynamoDB gateway endpoint is opt-in since 37a354e8
1835
+ database: { dynamodb: { enable: true } },
1817
1836
  };
1818
1837
 
1819
1838
  const discoveredResources = {
@@ -40,7 +40,6 @@ const FRAMEWORK_ENV_BLOCKLIST = new Set([
40
40
  'KMS_KEY_ARN',
41
41
  'AES_KEY',
42
42
  'AES_KEY_ID',
43
- 'FRIGG_ENCRYPTION_DISABLED',
44
43
  'DATABASE_URL',
45
44
  'DATABASE_HOST',
46
45
  'DATABASE_PORT',
@@ -4,6 +4,11 @@ const path = require('path');
4
4
  * Generate IAM CloudFormation template
5
5
  * @param {Object} options - Generation options
6
6
  * @param {string} [options.appName='Frigg'] - Application name
7
+ * @param {string} [options.serviceName] - The osls service name the app deploys
8
+ * under (Definition.name). Resource grants that match `*frigg*` are also
9
+ * granted for `*<serviceName>*`, because `frigg deploy` names the stack,
10
+ * functions, role, queues, topics, alarms, log groups, layer and buckets
11
+ * after the service, not after "frigg".
7
12
  * @param {Object} [options.features={}] - Enabled features { vpc, kms, ssm, websockets }
8
13
  * @param {string} [options.userPrefix='frigg-deployment-user'] - IAM user name prefix
9
14
  * @param {string} [options.stackName='frigg-deployment-iam'] - CloudFormation stack name
@@ -16,7 +21,8 @@ function generateIAMCloudFormation(options = {}) {
16
21
  features = {},
17
22
  userPrefix = 'frigg-deployment-user',
18
23
  stackName = 'frigg-deployment-iam',
19
- ssmKmsKeyArn
24
+ ssmKmsKeyArn,
25
+ serviceName,
20
26
  } = options;
21
27
 
22
28
  const deploymentUserName = userPrefix;
@@ -525,6 +531,51 @@ function generateIAMCloudFormation(options = {}) {
525
531
  },
526
532
  ];
527
533
 
534
+ coreStatements.push(
535
+ {
536
+ Sid: 'FriggLambdaLayers',
537
+ Effect: 'Allow',
538
+ Action: [
539
+ 'lambda:PublishLayerVersion',
540
+ 'lambda:DeleteLayerVersion',
541
+ 'lambda:GetLayerVersion',
542
+ ],
543
+ Resource: [
544
+ {
545
+ 'Fn::Sub':
546
+ 'arn:aws:lambda:*:${AWS::AccountId}:layer:*frigg*',
547
+ },
548
+ {
549
+ 'Fn::Sub':
550
+ 'arn:aws:lambda:*:${AWS::AccountId}:layer:*frigg*:*',
551
+ },
552
+ ],
553
+ },
554
+ {
555
+ // Buckets the app's stack creates (e.g. the migration-status
556
+ // bucket); CloudFormation names them after the stack, in lower case.
557
+ Sid: 'FriggAppBuckets',
558
+ Effect: 'Allow',
559
+ Action: [
560
+ 's3:CreateBucket',
561
+ 's3:DeleteBucket',
562
+ 's3:PutBucketPolicy',
563
+ 's3:DeleteBucketPolicy',
564
+ 's3:PutBucketVersioning',
565
+ 's3:PutBucketPublicAccessBlock',
566
+ 's3:PutEncryptionConfiguration',
567
+ 's3:PutLifecycleConfiguration',
568
+ 's3:PutBucketTagging',
569
+ 's3:GetBucketLocation',
570
+ 's3:ListBucket',
571
+ 's3:GetObject',
572
+ 's3:PutObject',
573
+ 's3:DeleteObject',
574
+ ],
575
+ Resource: ['arn:aws:s3:::*frigg*', 'arn:aws:s3:::*frigg*/*'],
576
+ }
577
+ );
578
+
528
579
  template.Resources.FriggCoreDeploymentPolicy = {
529
580
  Type: 'AWS::IAM::ManagedPolicy',
530
581
  Properties: {
@@ -768,10 +819,59 @@ function generateIAMCloudFormation(options = {}) {
768
819
  },
769
820
  };
770
821
 
822
+ expandResourceNamePatterns(template, serviceName);
823
+
771
824
  // Convert to YAML
772
825
  return convertToYAML(template);
773
826
  }
774
827
 
828
+ const FRIGG_NAME_PATTERN = '*frigg*';
829
+
830
+ /**
831
+ * Next to every policy resource that matches `*frigg*`, add the same
832
+ * resource for `*<serviceName>*` (lower case for S3 bucket ARNs), so an app
833
+ * that is not named "frigg" can manage its own stack resources.
834
+ *
835
+ * @param {Object} template - CloudFormation template (mutated)
836
+ * @param {string} [serviceName]
837
+ */
838
+ function expandResourceNamePatterns(template, serviceName) {
839
+ if (!serviceName || /frigg/i.test(serviceName)) {
840
+ return;
841
+ }
842
+ const servicePattern = `*${serviceName}*`;
843
+ const expand = (resource) => {
844
+ const value =
845
+ typeof resource === 'string'
846
+ ? resource
847
+ : resource && resource['Fn::Sub'];
848
+ if (typeof value !== 'string' || !value.includes(FRIGG_NAME_PATTERN)) {
849
+ return [resource];
850
+ }
851
+ const pattern = value.startsWith('arn:aws:s3:::')
852
+ ? servicePattern.toLowerCase()
853
+ : servicePattern;
854
+ const scoped = value.split(FRIGG_NAME_PATTERN).join(pattern);
855
+ return [
856
+ resource,
857
+ typeof resource === 'string' ? scoped : { 'Fn::Sub': scoped },
858
+ ];
859
+ };
860
+
861
+ for (const resource of Object.values(template.Resources)) {
862
+ const statements = resource?.Properties?.PolicyDocument?.Statement;
863
+ if (!Array.isArray(statements)) continue;
864
+ for (const statement of statements) {
865
+ if (statement.Resource === undefined) continue;
866
+ const expanded = [].concat(statement.Resource).flatMap(expand);
867
+ statement.Resource =
868
+ Array.isArray(statement.Resource) || expanded.length > 1
869
+ ? expanded
870
+ : expanded[0];
871
+ }
872
+ }
873
+ }
874
+
775
875
  /**
776
876
  * Convert JavaScript object to CloudFormation YAML
777
877
  * @param {Object} obj - JavaScript object
@@ -796,8 +896,7 @@ function getFeatureSummary(appDefinition) {
796
896
  const features = {
797
897
  core: true, // Always enabled
798
898
  vpc: appDefinition.vpc?.enable === true,
799
- kms:
800
- appDefinition.encryption?.fieldLevelEncryptionMethod === 'kms',
899
+ kms: appDefinition.encryption?.fieldLevelEncryptionMethod === 'kms',
801
900
  ssm: appDefinition.ssm?.enable === true,
802
901
  websockets: appDefinition.websockets?.enable === true,
803
902
  };
@@ -808,6 +907,8 @@ function getFeatureSummary(appDefinition) {
808
907
  features,
809
908
  integrationCount,
810
909
  appName: appDefinition.name || 'Unnamed Frigg App',
910
+ // What createBaseDefinition uses as the osls service name.
911
+ serviceName: appDefinition.name || 'create-frigg-app',
811
912
  ssmKmsKeyArn: appDefinition.ssm?.kmsKeyArn,
812
913
  };
813
914
  }
@@ -817,7 +918,10 @@ function getFeatureSummary(appDefinition) {
817
918
  * @returns {Object} Basic IAM policy document
818
919
  */
819
920
  function generateBasicIAMPolicy() {
820
- const basicPolicyPath = path.join(__dirname, 'templates/iam-policy-basic.json');
921
+ const basicPolicyPath = path.join(
922
+ __dirname,
923
+ 'templates/iam-policy-basic.json'
924
+ );
821
925
  return require(basicPolicyPath);
822
926
  }
823
927
 
@@ -826,7 +930,10 @@ function generateBasicIAMPolicy() {
826
930
  * @returns {Object} Full IAM policy document
827
931
  */
828
932
  function generateFullIAMPolicy() {
829
- const fullPolicyPath = path.join(__dirname, 'templates/iam-policy-full.json');
933
+ const fullPolicyPath = path.join(
934
+ __dirname,
935
+ 'templates/iam-policy-full.json'
936
+ );
830
937
  return require(fullPolicyPath);
831
938
  }
832
939
 
@@ -313,4 +313,98 @@ describe('IAM Generator', () => {
313
313
  expect(yaml).toContain('CredentialsSecretArn:');
314
314
  });
315
315
  });
316
+
317
+ describe("scoping to the app's own resources", () => {
318
+ const yaml = require('js-yaml');
319
+ const policyResources = (template, policy) =>
320
+ template.Resources[
321
+ policy
322
+ ].Properties.PolicyDocument.Statement.flatMap((statement) =>
323
+ [].concat(statement.Resource)
324
+ ).map((r) => (typeof r === 'string' ? r : r['Fn::Sub']));
325
+
326
+ // `frigg deploy` names everything after the service (Definition.name):
327
+ // stack my-app-prod, functions my-app-prod-auth, role
328
+ // my-app-prod-us-east-1-lambdaRole, queues my-app-internal-error-queue-prod
329
+ // and my-app-prod-DbMigrationQueue, layer my-app-prisma-prod, and
330
+ // CloudFormation-named topics, alarms and buckets prefixed my-app-prod.
331
+ const generate = (appDefinition) => {
332
+ const summary = getFeatureSummary(appDefinition);
333
+ return yaml.load(
334
+ generateIAMCloudFormation({
335
+ appName: summary.appName,
336
+ serviceName: summary.serviceName,
337
+ features: summary.features,
338
+ })
339
+ );
340
+ };
341
+
342
+ it('reports the service name osls deploys under', () => {
343
+ expect(getFeatureSummary({ name: 'my-app' }).serviceName).toBe(
344
+ 'my-app'
345
+ );
346
+ expect(getFeatureSummary({}).serviceName).toBe('create-frigg-app');
347
+ });
348
+
349
+ it('lets an app whose name does not contain "frigg" deploy its stack and resources', () => {
350
+ const resources = policyResources(
351
+ generate({ name: 'my-app' }),
352
+ 'FriggCoreDeploymentPolicy'
353
+ );
354
+
355
+ for (const expected of [
356
+ 'arn:aws:cloudformation:*:${AWS::AccountId}:stack/*my-app*/*',
357
+ 'arn:aws:lambda:*:${AWS::AccountId}:function:*my-app*',
358
+ 'arn:aws:iam::${AWS::AccountId}:role/*my-app*',
359
+ 'arn:aws:sqs:*:${AWS::AccountId}:*my-app*',
360
+ 'arn:aws:sns:*:${AWS::AccountId}:*my-app*',
361
+ 'arn:aws:logs:*:${AWS::AccountId}:log-group:/aws/lambda/*my-app*',
362
+ 'arn:aws:logs:*:${AWS::AccountId}:log-group:/aws/lambda/*my-app*:*',
363
+ 'arn:aws:cloudwatch:*:${AWS::AccountId}:alarm:*my-app*',
364
+ 'arn:aws:lambda:*:${AWS::AccountId}:layer:*my-app*',
365
+ 'arn:aws:lambda:*:${AWS::AccountId}:layer:*my-app*:*',
366
+ 'arn:aws:s3:::*my-app*',
367
+ 'arn:aws:s3:::*my-app*/*',
368
+ ]) {
369
+ expect(resources).toContain(expected);
370
+ }
371
+ // Existing grants for frigg-named resources are kept.
372
+ expect(resources).toContain(
373
+ 'arn:aws:lambda:*:${AWS::AccountId}:function:*frigg*'
374
+ );
375
+ });
376
+
377
+ it('matches S3 bucket names in lower case', () => {
378
+ const resources = policyResources(
379
+ generate({ name: 'MyApp' }),
380
+ 'FriggCoreDeploymentPolicy'
381
+ );
382
+ expect(resources).toContain('arn:aws:s3:::*myapp*');
383
+ });
384
+
385
+ it('scopes the SSM parameter grant to the app too', () => {
386
+ const template = generate({
387
+ name: 'my-app',
388
+ ssm: { enable: true },
389
+ });
390
+ const resources = policyResources(template, 'FriggSSMPolicy');
391
+ expect(resources).toContain(
392
+ 'arn:aws:ssm:*:${AWS::AccountId}:parameter/*my-app*'
393
+ );
394
+ });
395
+
396
+ it('does not duplicate grants for an app named frigg', () => {
397
+ const resources = policyResources(
398
+ generate({ name: 'frigg' }),
399
+ 'FriggCoreDeploymentPolicy'
400
+ );
401
+ expect(
402
+ resources.filter(
403
+ (r) =>
404
+ r ===
405
+ 'arn:aws:lambda:*:${AWS::AccountId}:function:*frigg*'
406
+ )
407
+ ).toHaveLength(1);
408
+ });
409
+ });
316
410
  });
@@ -164,7 +164,7 @@ describe('CloudFormationDiscovery', () => {
164
164
  expect(result.routeTableId).toBe('rtb-123');
165
165
  expect(result.vpcEndpointSecurityGroupId).toBe('sg-vpce-123');
166
166
  expect(result.s3VpcEndpointId).toBe('vpce-s3-123');
167
- expect(result.dynamoDbVpcEndpointId).toBe('vpce-ddb-123');
167
+ expect(result.dynamodbVpcEndpointId).toBe('vpce-ddb-123');
168
168
  expect(result.kmsVpcEndpointId).toBe('vpce-kms-123');
169
169
  expect(result.secretsManagerVpcEndpointId).toBe('vpce-sm-123');
170
170
  });
@@ -190,6 +190,9 @@ describe('CloudFormationDiscovery', () => {
190
190
 
191
191
  expect(result).toEqual({
192
192
  fromCloudFormationStack: true,
193
+ // _extractFromResources() initialises the structured endpoint map whenever
194
+ // the stack has resources (37a354e8)
195
+ vpcEndpoints: {},
193
196
  stackName: 'test-stack',
194
197
  auroraClusterId: 'test-cluster',
195
198
  existingLogicalIds: ['FriggAuroraCluster'],
@@ -257,6 +260,9 @@ describe('CloudFormationDiscovery', () => {
257
260
 
258
261
  expect(result).toEqual({
259
262
  fromCloudFormationStack: true,
263
+ // _extractFromResources() initialises the structured endpoint map whenever
264
+ // the stack has resources (37a354e8)
265
+ vpcEndpoints: {},
260
266
  stackName: 'test-stack',
261
267
  migrationStatusBucket: 'test-migration-bucket',
262
268
  existingLogicalIds: ['FriggMigrationStatusBucket'],
@@ -285,6 +291,9 @@ describe('CloudFormationDiscovery', () => {
285
291
 
286
292
  expect(result).toEqual({
287
293
  fromCloudFormationStack: true,
294
+ // _extractFromResources() initialises the structured endpoint map whenever
295
+ // the stack has resources (37a354e8)
296
+ vpcEndpoints: {},
288
297
  stackName: 'test-stack',
289
298
  migrationQueueUrl:
290
299
  'https://sqs.us-east-1.amazonaws.com/123456789/test-queue',
@@ -313,6 +322,9 @@ describe('CloudFormationDiscovery', () => {
313
322
 
314
323
  expect(result).toEqual({
315
324
  fromCloudFormationStack: true,
325
+ // _extractFromResources() initialises the structured endpoint map whenever
326
+ // the stack has resources (37a354e8)
327
+ vpcEndpoints: {},
316
328
  stackName: 'test-stack',
317
329
  natGatewayId: 'nat-0123456789',
318
330
  existingLogicalIds: ['FriggNatGateway'],
@@ -340,6 +352,9 @@ describe('CloudFormationDiscovery', () => {
340
352
 
341
353
  expect(result).toEqual({
342
354
  fromCloudFormationStack: true,
355
+ // _extractFromResources() initialises the structured endpoint map whenever
356
+ // the stack has resources (37a354e8)
357
+ vpcEndpoints: {},
343
358
  stackName: 'test-stack',
344
359
  defaultVpcId: 'vpc-037ec55fe87aec1e7',
345
360
  existingLogicalIds: ['FriggVPC'],
@@ -378,6 +393,9 @@ describe('CloudFormationDiscovery', () => {
378
393
 
379
394
  expect(result).toEqual({
380
395
  fromCloudFormationStack: true,
396
+ // _extractFromResources() initialises the structured endpoint map whenever
397
+ // the stack has resources (37a354e8)
398
+ vpcEndpoints: {},
381
399
  stackName: 'test-stack',
382
400
  defaultVpcId: 'vpc-123', // VpcBuilder expects 'defaultVpcId'
383
401
  defaultKmsKeyId: 'arn:aws:kms:us-east-1:123456789:key/abc',
@@ -406,6 +424,9 @@ describe('CloudFormationDiscovery', () => {
406
424
 
407
425
  expect(result).toEqual({
408
426
  fromCloudFormationStack: true,
427
+ // _extractFromResources() initialises the structured endpoint map whenever
428
+ // the stack has resources (37a354e8)
429
+ vpcEndpoints: {},
409
430
  stackName: 'test-stack',
410
431
  });
411
432
  });
@@ -439,6 +460,11 @@ describe('CloudFormationDiscovery', () => {
439
460
  SecurityGroups: [{ VpcId: 'vpc-123' }],
440
461
  });
441
462
 
463
+ // Mock the VPC's default security group lookup (added in 37a354e8)
464
+ mockEC2Client.send.mockResolvedValueOnce({
465
+ SecurityGroups: [{ GroupId: 'sg-default-123' }],
466
+ });
467
+
442
468
  // Mock subnet query
443
469
  mockEC2Client.send.mockResolvedValueOnce({
444
470
  Subnets: [
@@ -469,9 +495,11 @@ describe('CloudFormationDiscovery', () => {
469
495
 
470
496
  const result = await cfDiscovery.discoverFromStack('test-stack');
471
497
 
498
+ expect(result.defaultVpcId).toBe('vpc-123');
499
+ expect(result.defaultSecurityGroupId).toBe('sg-default-123');
472
500
  expect(result.privateSubnetId1).toBe('subnet-private-1');
473
501
  expect(result.privateSubnetId2).toBe('subnet-private-2');
474
- expect(mockEC2Client.send).toHaveBeenCalledTimes(2);
502
+ expect(mockEC2Client.send).toHaveBeenCalledTimes(3);
475
503
  });
476
504
 
477
505
  it('should handle EC2 subnet query errors gracefully', async () => {
@@ -739,7 +767,7 @@ describe('CloudFormationDiscovery', () => {
739
767
  expect(result.vpcEndpoints.s3).toBe('vpce-0352ceac2124c14be');
740
768
  expect(result.vpcEndpoints.dynamodb).toBe('vpce-0b06c4f631199ea68');
741
769
  expect(result.s3VpcEndpointId).toBe('vpce-0352ceac2124c14be');
742
- expect(result.dynamoDbVpcEndpointId).toBe('vpce-0b06c4f631199ea68');
770
+ expect(result.dynamodbVpcEndpointId).toBe('vpce-0b06c4f631199ea68');
743
771
 
744
772
  // Verify NO VPC/KMS resources (they're external)
745
773
  expect(result.defaultVpcId).toBeUndefined();
@@ -776,7 +804,7 @@ describe('CloudFormationDiscovery', () => {
776
804
  expect(result.vpcEndpoints.s3).toBe('vpce-legacy-s3');
777
805
  expect(result.vpcEndpoints.dynamodb).toBe('vpce-legacy-ddb');
778
806
  expect(result.s3VpcEndpointId).toBe('vpce-legacy-s3');
779
- expect(result.dynamoDbVpcEndpointId).toBe('vpce-legacy-ddb');
807
+ expect(result.dynamodbVpcEndpointId).toBe('vpce-legacy-ddb');
780
808
  });
781
809
 
782
810
  it('should extract FriggLambdaSecurityGroup from stack', async () => {
@@ -807,7 +835,9 @@ describe('CloudFormationDiscovery', () => {
807
835
 
808
836
  // Lambda security group should be extracted
809
837
  expect(result.lambdaSecurityGroupId).toBe('sg-01002240c6a446202');
810
- expect(result.defaultSecurityGroupId).toBe('sg-01002240c6a446202');
838
+ // The Lambda SG must not masquerade as the VPC's default SG
839
+ // (defaultSecurityGroupId is only ever the VPC default; see 37a354e8).
840
+ expect(result.defaultSecurityGroupId).toBeUndefined();
811
841
  expect(result.existingLogicalIds).toContain(
812
842
  'FriggLambdaSecurityGroup'
813
843
  );
@@ -899,7 +929,7 @@ describe('CloudFormationDiscovery', () => {
899
929
 
900
930
  describe('existingLogicalIds tracking', () => {
901
931
  it('should track OLD VPC endpoint logical IDs (VPCEndpointS3 pattern) for backwards compatibility', async () => {
902
- // CRITICAL: Frontify production uses OLD naming convention
932
+ // CRITICAL: Older production stacks use the OLD naming convention
903
933
  const mockStack = {
904
934
  StackName: 'create-frigg-app-production',
905
935
  Outputs: [],