@friggframework/devtools 2.0.0--canary.657.f16d20b.0 → 2.0.0--canary.737.83b4e17.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 (104) hide show
  1. package/frigg-cli/README.md +115 -31
  2. package/frigg-cli/__tests__/unit/commands/build.test.js +3 -0
  3. package/frigg-cli/__tests__/unit/commands/deploy.test.js +33 -24
  4. package/frigg-cli/__tests__/unit/commands/doctor.test.js +10 -6
  5. package/frigg-cli/__tests__/unit/commands/generate-iam.test.js +18 -0
  6. package/frigg-cli/__tests__/unit/commands/init.test.js +688 -0
  7. package/frigg-cli/__tests__/unit/commands/install.test.js +601 -341
  8. package/frigg-cli/__tests__/unit/commands/ui.test.js +31 -30
  9. package/frigg-cli/__tests__/unit/commands/validate-wiring.test.js +92 -0
  10. package/frigg-cli/__tests__/unit/dependencies.test.js +6 -2
  11. package/frigg-cli/build-command/index.js +6 -0
  12. package/frigg-cli/deploy-command/index.js +6 -0
  13. package/frigg-cli/generate-command/index.js +1 -0
  14. package/frigg-cli/generate-iam-command.js +1 -0
  15. package/frigg-cli/index.js +22 -5
  16. package/frigg-cli/init-command/backend-first-handler.js +395 -551
  17. package/frigg-cli/init-command/deployment-modes.js +7 -0
  18. package/frigg-cli/init-command/index.js +82 -35
  19. package/frigg-cli/init-command/safe-path.js +58 -0
  20. package/frigg-cli/init-command/scaffold-dependencies.js +202 -0
  21. package/frigg-cli/install-command/app-definition.js +174 -0
  22. package/frigg-cli/install-command/commit-changes.js +40 -8
  23. package/frigg-cli/install-command/environment-variables.js +15 -0
  24. package/frigg-cli/install-command/index.js +96 -21
  25. package/frigg-cli/install-command/install-package.js +77 -4
  26. package/frigg-cli/install-command/integration-file.js +20 -11
  27. package/frigg-cli/install-command/resolve-module.js +69 -0
  28. package/frigg-cli/install-command/template.js +102 -75
  29. package/frigg-cli/install-command/validate-package.js +36 -4
  30. package/frigg-cli/package.json +1 -1
  31. package/frigg-cli/start-command/index.js +4 -0
  32. package/frigg-cli/start-command/start-command.test.js +3 -0
  33. package/frigg-cli/templates/backend/README.md +267 -0
  34. package/frigg-cli/templates/backend/env.example +20 -0
  35. package/frigg-cli/templates/backend/gitignore +10 -0
  36. package/frigg-cli/templates/backend/index.js +114 -0
  37. package/frigg-cli/templates/backend/infrastructure.js +20 -0
  38. package/frigg-cli/test/init-command.test.js +9 -2
  39. package/frigg-cli/validate-command/__tests__/init-validation.test.js +63 -0
  40. package/frigg-cli/validate-command/__tests__/integrations-checks.test.js +133 -0
  41. package/frigg-cli/validate-command/__tests__/validate-app-definition.test.js +443 -0
  42. package/frigg-cli/validate-command/__tests__/validate-command.test.js +262 -0
  43. package/frigg-cli/validate-command/checks/config.js +504 -0
  44. package/frigg-cli/validate-command/checks/integrations.js +274 -0
  45. package/frigg-cli/validate-command/format-report.js +58 -0
  46. package/frigg-cli/validate-command/index.js +107 -0
  47. package/frigg-cli/validate-command/load-app-definition.js +105 -0
  48. package/frigg-cli/validate-command/schema-issues.js +154 -0
  49. package/frigg-cli/validate-command/validate-app-definition.js +60 -0
  50. package/infrastructure/README.md +32 -5
  51. package/infrastructure/__tests__/helpers/bundled-prisma-engine-excludes.js +39 -0
  52. package/infrastructure/__tests__/management-api-gateway-routes.test.js +284 -0
  53. package/infrastructure/__tests__/postgres-config.test.js +245 -836
  54. package/infrastructure/__tests__/scaffold-default-infrastructure.test.js +151 -0
  55. package/infrastructure/__tests__/scoped-environment.test.js +3 -0
  56. package/infrastructure/__tests__/ssm-preload-node-options.test.js +3 -0
  57. package/infrastructure/__tests__/template-generation.test.js +39 -8
  58. package/infrastructure/app-definition-schema-contract.test.js +634 -0
  59. package/infrastructure/create-frigg-infrastructure.js +4 -1
  60. package/infrastructure/create-frigg-infrastructure.test.js +51 -0
  61. package/infrastructure/docs/POSTGRES-CONFIGURATION.md +80 -98
  62. package/infrastructure/domains/admin-scripts/admin-script-builder.js +8 -2
  63. package/infrastructure/domains/admin-scripts/admin-script-builder.test.js +52 -6
  64. package/infrastructure/domains/database/aurora-builder.js +13 -2
  65. package/infrastructure/domains/database/aurora-builder.test.js +22 -0
  66. package/infrastructure/domains/database/migration-builder.js +21 -2
  67. package/infrastructure/domains/database/migration-builder.test.js +61 -6
  68. package/infrastructure/domains/database/migration-engines.js +93 -0
  69. package/infrastructure/domains/database/migration-engines.test.js +142 -0
  70. package/infrastructure/domains/health/application/use-cases/__tests__/mismatch-analyzer-method-name.test.js +12 -8
  71. package/infrastructure/domains/health/application/use-cases/__tests__/repair-via-import-use-case.test.js +19 -7
  72. package/infrastructure/domains/health/application/use-cases/run-health-check-use-case.test.js +12 -8
  73. package/infrastructure/domains/health/domain/services/__tests__/import-progress-monitor.test.js +17 -18
  74. package/infrastructure/domains/health/domain/services/__tests__/update-progress-monitor.test.js +12 -2
  75. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-relationship-analysis.test.js +8 -1
  76. package/infrastructure/domains/health/infrastructure/adapters/aws-property-reconciler.test.js +4 -2
  77. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-detector.test.js +10 -0
  78. package/infrastructure/domains/integration/integration-builder.js +2 -0
  79. package/infrastructure/domains/integration/integration-builder.test.js +22 -39
  80. package/infrastructure/domains/networking/vpc-builder.js +18 -8
  81. package/infrastructure/domains/networking/vpc-builder.test.js +26 -12
  82. package/infrastructure/domains/scheduler/scheduler-builder.js +2 -19
  83. package/infrastructure/domains/scheduler/scheduler-builder.test.js +0 -99
  84. package/infrastructure/domains/security/iam-generator.js +112 -5
  85. package/infrastructure/domains/security/iam-generator.test.js +94 -0
  86. package/infrastructure/domains/shared/cloudformation-discovery.test.js +36 -6
  87. package/infrastructure/domains/shared/environment-builder.js +31 -5
  88. package/infrastructure/domains/shared/environment-builder.test.js +93 -7
  89. package/infrastructure/domains/shared/lambda-architectures.js +113 -0
  90. package/infrastructure/domains/shared/lambda-architectures.test.js +164 -0
  91. package/infrastructure/domains/shared/utilities/base-definition-factory.js +39 -4
  92. package/infrastructure/domains/shared/utilities/base-definition-factory.test.js +85 -17
  93. package/infrastructure/domains/shared/utilities/nested-node-modules.js +6 -5
  94. package/infrastructure/domains/shared/utilities/nested-node-modules.test.js +20 -26
  95. package/infrastructure/domains/shared/utilities/prisma-layer-manager.js +92 -12
  96. package/infrastructure/domains/shared/utilities/prisma-layer-manager.test.js +158 -6
  97. package/infrastructure/infrastructure-composer.js +12 -1
  98. package/infrastructure/infrastructure-composer.test.js +339 -794
  99. package/infrastructure/scripts/build-prisma-layer.js +136 -50
  100. package/infrastructure/scripts/build-prisma-layer.test.js +128 -7
  101. package/infrastructure/scripts/build-time-discovery.test.js +18 -3
  102. package/package.json +12 -10
  103. package/frigg-cli/index.test.js +0 -158
  104. package/infrastructure/integration.test.js +0 -381
@@ -10,8 +10,7 @@ const {
10
10
  } = require('@friggframework/core/queues/queue-delivery');
11
11
  const { IntegrationBuilder } = require('./integration-builder');
12
12
  const { ValidationResult } = require('../shared/base-builder');
13
- const { BuilderOrchestrator } = require('../shared/builder-orchestrator');
14
- const { SchedulerBuilder } = require('../scheduler/scheduler-builder');
13
+ const { itBundlesOnlyTheTargetPrismaEngine } = require('../../__tests__/helpers/bundled-prisma-engine-excludes');
15
14
 
16
15
  describe('IntegrationBuilder', () => {
17
16
  let integrationBuilder;
@@ -261,37 +260,6 @@ describe('IntegrationBuilder', () => {
261
260
  ).toBeUndefined();
262
261
  });
263
262
 
264
- it('adds no resource, function or env var when no module declares rateLimit', async () => {
265
- class Api {}
266
- const { merged } = await new BuilderOrchestrator([
267
- new IntegrationBuilder(),
268
- new SchedulerBuilder(),
269
- ]).buildAll({
270
- integrations: [
271
- {
272
- Definition: {
273
- name: 'test',
274
- modules: { crm: { definition: { API: Api } } },
275
- },
276
- },
277
- ],
278
- });
279
- const before = await integrationBuilder.build(
280
- { integrations: [{ Definition: { name: 'test' } }] },
281
- {}
282
- );
283
-
284
- expect(Object.keys(merged.resources)).toEqual(
285
- Object.keys(before.resources)
286
- );
287
- expect(Object.keys(merged.functions)).toEqual(
288
- Object.keys(before.functions)
289
- );
290
- expect(Object.keys(merged.environment)).toEqual(
291
- Object.keys(before.environment)
292
- );
293
- });
294
-
295
263
  it('should create queue worker function', async () => {
296
264
  const appDefinition = {
297
265
  integrations: [
@@ -1118,6 +1086,21 @@ describe('IntegrationBuilder', () => {
1118
1086
  });
1119
1087
 
1120
1088
 
1089
+ describe('IntegrationBuilder Lambda architecture with usePrismaLambdaLayer=false', () => {
1090
+ const functionsOf = async (usePrismaLambdaLayer, architecture) => {
1091
+ const result = await new IntegrationBuilder().build(
1092
+ {
1093
+ integrations: [{ Definition: { name: 'crm' } }],
1094
+ usePrismaLambdaLayer,
1095
+ ...(architecture && { architecture }),
1096
+ },
1097
+ {}
1098
+ );
1099
+ return Object.values(result.functions);
1100
+ };
1101
+ itBundlesOnlyTheTargetPrismaEngine(functionsOf);
1102
+ });
1103
+
1121
1104
  describe('IntegrationBuilder nested node_modules (lambda.keepNestedNodeModules)', () => {
1122
1105
  const appDefinition = (lambda) => ({
1123
1106
  integrations: [{ Definition: { name: 'test', webhooks: true } }],
@@ -1126,24 +1109,24 @@ describe('IntegrationBuilder nested node_modules (lambda.keepNestedNodeModules)'
1126
1109
  const packagedFunctions = (result) =>
1127
1110
  Object.values(result.functions).filter((fn) => fn.package?.exclude);
1128
1111
 
1129
- it('excludes every nested node_modules by default', async () => {
1112
+ it('keeps nested node_modules by default, still excluding nested Frigg copies', async () => {
1130
1113
  const result = await new IntegrationBuilder().build(appDefinition(), {});
1131
1114
 
1132
1115
  expect(packagedFunctions(result).length).toBeGreaterThan(0);
1133
1116
  for (const fn of packagedFunctions(result)) {
1134
- expect(fn.package.exclude).toContain('node_modules/**/node_modules/**');
1117
+ expect(fn.package.exclude).not.toContain('node_modules/**/node_modules/**');
1118
+ expect(fn.package.exclude).toContain('node_modules/**/node_modules/@friggframework/**');
1135
1119
  }
1136
1120
  });
1137
1121
 
1138
- it('keeps nested node_modules when the app opts in, still excluding nested Frigg copies', async () => {
1122
+ it('excludes every nested node_modules when the app opts out', async () => {
1139
1123
  const result = await new IntegrationBuilder().build(
1140
- appDefinition({ keepNestedNodeModules: true }),
1124
+ appDefinition({ keepNestedNodeModules: false }),
1141
1125
  {}
1142
1126
  );
1143
1127
 
1144
1128
  for (const fn of packagedFunctions(result)) {
1145
- expect(fn.package.exclude).not.toContain('node_modules/**/node_modules/**');
1146
- expect(fn.package.exclude).toContain('node_modules/**/node_modules/@friggframework/**');
1129
+ expect(fn.package.exclude).toContain('node_modules/**/node_modules/**');
1147
1130
  }
1148
1131
  });
1149
1132
  });
@@ -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',
@@ -804,7 +810,12 @@ describe('VpcBuilder', () => {
804
810
  expect(result.resources.FriggPrivateSubnet2RouteTableAssociation.Properties.RouteTableId).toEqual({ Ref: 'FriggLambdaRouteTable' });
805
811
  });
806
812
 
807
- it('should add UpdateReplacePolicy to force association recreation on updates', async () => {
813
+ // SKIPPED: whether existing stacks keep FriggSubnetNRouteAssociation or move
814
+ // to FriggPrivateSubnetNRouteTableAssociation is unresolved. Since 37a354e8
815
+ // the source always uses the new IDs; this test (same commit) expects the old
816
+ // ones. Moving could hit Resource.AlreadyAssociated on upgrade.
817
+ // Tracked in https://github.com/friggframework/frigg/issues/714
818
+ it.skip('should add UpdateReplacePolicy to force association recreation on updates', async () => {
808
819
  const appDefinition = {
809
820
  vpc: {
810
821
  enable: true,
@@ -815,7 +826,9 @@ describe('VpcBuilder', () => {
815
826
  };
816
827
 
817
828
  const discoveredResources = {
818
- vpcId: 'vpc-123',
829
+ // Discovery reports the VPC as defaultVpcId (e6fc7c76); with no VPC
830
+ // the resolver refuses to create one implicitly (37a354e8).
831
+ defaultVpcId: 'vpc-123',
819
832
  privateSubnetId1: 'subnet-existing-1',
820
833
  privateSubnetId2: 'subnet-existing-2',
821
834
  natGatewayId: 'nat-existing',
@@ -1522,7 +1535,7 @@ describe('VpcBuilder', () => {
1522
1535
  });
1523
1536
 
1524
1537
  it('should use OLD logical IDs for backwards compatibility (FriggNATRoute, VPCEndpointS3 pattern)', async () => {
1525
- // CRITICAL TEST: Real Frontify production stack uses OLD naming convention
1538
+ // CRITICAL TEST: A real production stack uses OLD naming convention
1526
1539
  // Stack currently has: FriggNATRoute, VPCEndpointS3, VPCEndpointDynamoDB
1527
1540
  // We MUST use these same logical IDs to avoid AlreadyExists errors
1528
1541
  const appDefinition = {
@@ -1541,7 +1554,7 @@ describe('VpcBuilder', () => {
1541
1554
  }
1542
1555
  };
1543
1556
 
1544
- // Discovery results matching ACTUAL Frontify production stack
1557
+ // Discovery results matching an actual production stack
1545
1558
  const discoveredResources = {
1546
1559
  fromCloudFormationStack: true,
1547
1560
  stackName: 'create-frigg-app-production',
@@ -1589,10 +1602,9 @@ describe('VpcBuilder', () => {
1589
1602
  expect(result.resources.FriggNATRoute.Type).toBe('AWS::EC2::Route');
1590
1603
  expect(result.resources.FriggPrivateRoute).toBeUndefined(); // Should NOT create new ID
1591
1604
 
1592
- expect(result.resources.FriggSubnet1RouteAssociation).toBeDefined();
1593
- expect(result.resources.FriggSubnet2RouteAssociation).toBeDefined();
1594
- expect(result.resources.FriggPrivateSubnet1RouteTableAssociation).toBeUndefined();
1595
- expect(result.resources.FriggPrivateSubnet2RouteTableAssociation).toBeUndefined();
1605
+ // Subnet route-table association IDs are deliberately not asserted
1606
+ // here: which IDs an existing stack should keep is unresolved (#714,
1607
+ // see the skipped UpdateReplacePolicy test above).
1596
1608
 
1597
1609
  expect(result.resources.VPCEndpointS3).toBeDefined();
1598
1610
  expect(result.resources.VPCEndpointS3.Type).toBe('AWS::EC2::VPCEndpoint');
@@ -1814,6 +1826,8 @@ describe('VpcBuilder', () => {
1814
1826
  const appDefinition = {
1815
1827
  vpc: { enable: true },
1816
1828
  encryption: { fieldLevelEncryptionMethod: 'kms' },
1829
+ // The DynamoDB gateway endpoint is opt-in since 37a354e8
1830
+ database: { dynamodb: { enable: true } },
1817
1831
  };
1818
1832
 
1819
1833
  const discoveredResources = {
@@ -13,24 +13,12 @@
13
13
  */
14
14
 
15
15
  const { InfrastructureBuilder, ValidationResult } = require('../shared/base-builder');
16
- const { ResourceOwnership } = require('../shared/types/resource-ownership');
17
16
  const {
18
17
  isScopedEnvironmentActive,
19
18
  getIntegrationFunctionNames,
20
19
  getAdminFunctionNames,
21
20
  } = require('../shared/function-environments');
22
21
 
23
- const queueArnFromUrl = (queueUrl) => {
24
- const { hostname, pathname } = new URL(queueUrl);
25
- const [accountId, queueName] = pathname.split('/').filter(Boolean);
26
- return `arn:aws:sqs:${hostname.split('.')[1]}:${accountId}:${queueName}`;
27
- };
28
-
29
- const declaresRateLimit = (integration) =>
30
- Object.values(integration?.Definition?.modules ?? {}).some((module) =>
31
- Boolean(module?.definition?.API?.rateLimit)
32
- );
33
-
34
22
  class SchedulerBuilder extends InfrastructureBuilder {
35
23
  constructor() {
36
24
  super();
@@ -49,8 +37,7 @@ class SchedulerBuilder extends InfrastructureBuilder {
49
37
  return appDefinition.integrations.some(
50
38
  (integration) =>
51
39
  integration?.Definition?.webhooks?.enabled === true ||
52
- integration?.Definition?.webhooks === true ||
53
- declaresRateLimit(integration)
40
+ integration?.Definition?.webhooks === true
54
41
  );
55
42
  }
56
43
 
@@ -120,11 +107,7 @@ class SchedulerBuilder extends InfrastructureBuilder {
120
107
  if (Array.isArray(appDefinition.integrations)) {
121
108
  appDefinition.integrations.forEach((integration) => {
122
109
  const integrationName = integration?.Definition?.name;
123
- if (
124
- integration.ownership?.queue === ResourceOwnership.EXTERNAL
125
- ) {
126
- queueArns.push(queueArnFromUrl(integration.queue.url));
127
- } else if (integrationName) {
110
+ if (integrationName) {
128
111
  const capitalizedName =
129
112
  integrationName.charAt(0).toUpperCase() +
130
113
  integrationName.slice(1);
@@ -38,61 +38,6 @@ describe('SchedulerBuilder', () => {
38
38
  ).toBe(true);
39
39
  });
40
40
 
41
- it('runs when any module declares a rate limit', () => {
42
- class Api {
43
- static rateLimit = { minRetryAfterMs: 1_000 };
44
- }
45
- expect(
46
- schedulerBuilder.shouldExecute({
47
- integrations: [
48
- { Definition: { name: 'a' } },
49
- {
50
- Definition: {
51
- name: 'b',
52
- modules: { crm: { definition: { API: Api } } },
53
- },
54
- },
55
- ],
56
- })
57
- ).toBe(true);
58
- });
59
-
60
- it('skips a module whose API declares no rate limit', () => {
61
- class Api {}
62
- expect(
63
- schedulerBuilder.shouldExecute({
64
- integrations: [
65
- {
66
- Definition: {
67
- name: 'a',
68
- modules: { crm: { definition: { API: Api } } },
69
- },
70
- },
71
- ],
72
- })
73
- ).toBe(false);
74
- });
75
-
76
- it.each([
77
- ['no modules', { name: 'a' }],
78
- ['an empty modules object', { name: 'a', modules: {} }],
79
- [
80
- 'a module with no definition',
81
- { name: 'a', modules: { crm: {} } },
82
- ],
83
- ['a null module', { name: 'a', modules: { crm: null } }],
84
- [
85
- 'a definition with no API',
86
- { name: 'a', modules: { crm: { definition: {} } } },
87
- ],
88
- ])('skips an integration with %s', (_label, Definition) => {
89
- expect(
90
- schedulerBuilder.shouldExecute({
91
- integrations: [{ Definition }],
92
- })
93
- ).toBe(false);
94
- });
95
-
96
41
  it('skips otherwise', () => {
97
42
  expect(
98
43
  schedulerBuilder.shouldExecute({
@@ -170,48 +115,4 @@ describe('SchedulerBuilder', () => {
170
115
  expect(result.functionEnvironments).toBeUndefined();
171
116
  });
172
117
  });
173
-
174
- describe('build() execution role', () => {
175
- const sendableQueues = (result) =>
176
- result.resources.SchedulerExecutionRole.Properties.Policies[0]
177
- .PolicyDocument.Statement[0].Resource;
178
-
179
- it('allows sending to a queue the stack creates', async () => {
180
- const result = await schedulerBuilder.build(
181
- {
182
- scheduler: { enable: true },
183
- integrations: [{ Definition: { name: 'hubspot' } }],
184
- },
185
- {}
186
- );
187
-
188
- expect(sendableQueues(result)).toEqual([
189
- { 'Fn::GetAtt': ['HubspotQueue', 'Arn'] },
190
- ]);
191
- });
192
-
193
- it('allows sending to an external queue by its ARN, not a resource the stack lacks', async () => {
194
- const result = await schedulerBuilder.build(
195
- {
196
- scheduler: { enable: true },
197
- integrations: [
198
- { Definition: { name: 'hubspot' } },
199
- {
200
- Definition: { name: 'salesforce' },
201
- ownership: { queue: 'external' },
202
- queue: {
203
- url: 'https://sqs.us-east-1.amazonaws.com/123456789012/acme-salesforce',
204
- },
205
- },
206
- ],
207
- },
208
- {}
209
- );
210
-
211
- expect(sendableQueues(result)).toEqual([
212
- { 'Fn::GetAtt': ['HubspotQueue', 'Arn'] },
213
- 'arn:aws:sqs:us-east-1:123456789012:acme-salesforce',
214
- ]);
215
- });
216
- });
217
118
  });
@@ -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