@friggframework/devtools 2.0.0--canary.686.df38e8e.0 → 2.0.0--canary.711.f8b6445.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/frigg-cli/README.md +77 -30
  2. package/frigg-cli/__tests__/unit/commands/generate-iam.test.js +18 -0
  3. package/frigg-cli/__tests__/unit/commands/init.test.js +688 -0
  4. package/frigg-cli/__tests__/unit/commands/install.test.js +594 -341
  5. package/frigg-cli/build-command/index.js +1 -32
  6. package/frigg-cli/deploy-command/index.js +2 -50
  7. package/frigg-cli/doctor-command/index.js +0 -7
  8. package/frigg-cli/generate-command/index.js +1 -0
  9. package/frigg-cli/generate-iam-command.js +1 -7
  10. package/frigg-cli/index.js +9 -4
  11. package/frigg-cli/init-command/backend-first-handler.js +397 -554
  12. package/frigg-cli/init-command/deployment-modes.js +7 -0
  13. package/frigg-cli/init-command/index.js +82 -35
  14. package/frigg-cli/init-command/safe-path.js +58 -0
  15. package/frigg-cli/init-command/scaffold-dependencies.js +202 -0
  16. package/frigg-cli/install-command/app-definition.js +174 -0
  17. package/frigg-cli/install-command/commit-changes.js +40 -8
  18. package/frigg-cli/install-command/environment-variables.js +15 -0
  19. package/frigg-cli/install-command/index.js +96 -21
  20. package/frigg-cli/install-command/install-package.js +77 -4
  21. package/frigg-cli/install-command/integration-file.js +20 -11
  22. package/frigg-cli/install-command/resolve-module.js +69 -0
  23. package/frigg-cli/install-command/template.js +102 -75
  24. package/frigg-cli/install-command/validate-package.js +36 -4
  25. package/frigg-cli/package.json +1 -1
  26. package/frigg-cli/repair-command/index.js +0 -7
  27. package/frigg-cli/start-command/index.js +0 -58
  28. package/frigg-cli/templates/backend/README.md +267 -0
  29. package/frigg-cli/templates/backend/env.example +20 -0
  30. package/frigg-cli/templates/backend/gitignore +10 -0
  31. package/frigg-cli/templates/backend/index.js +114 -0
  32. package/frigg-cli/templates/backend/infrastructure.js +20 -0
  33. package/frigg-cli/test/init-command.test.js +9 -2
  34. package/infrastructure/README.md +2 -4
  35. package/infrastructure/__tests__/scaffold-default-infrastructure.test.js +148 -0
  36. package/infrastructure/__tests__/template-generation.test.js +0 -7
  37. package/infrastructure/create-frigg-infrastructure.js +0 -14
  38. package/infrastructure/docs/POSTGRES-CONFIGURATION.md +21 -1
  39. package/infrastructure/domains/admin-scripts/admin-script-builder.js +6 -2
  40. package/infrastructure/domains/admin-scripts/admin-script-builder.test.js +30 -0
  41. package/infrastructure/domains/database/aurora-builder.js +13 -2
  42. package/infrastructure/domains/database/aurora-builder.test.js +22 -0
  43. package/infrastructure/domains/parameters/offload-utils.js +0 -1
  44. package/infrastructure/domains/security/iam-generator.js +112 -5
  45. package/infrastructure/domains/security/iam-generator.test.js +94 -0
  46. package/infrastructure/domains/shared/environment-builder.js +1 -12
  47. package/infrastructure/domains/shared/environment-builder.test.js +0 -20
  48. package/infrastructure/domains/shared/types/app-definition.js +1 -15
  49. package/infrastructure/domains/shared/utilities/base-definition-factory.js +17 -30
  50. package/infrastructure/domains/shared/utilities/base-definition-factory.test.js +22 -85
  51. package/infrastructure/infrastructure-composer.test.js +0 -7
  52. package/infrastructure/scripts/build-prisma-layer.js +5 -32
  53. package/infrastructure/scripts/build-prisma-layer.test.js +0 -35
  54. package/package.json +10 -8
  55. package/frigg-cli/__tests__/unit/commands/provider-dispatch.test.js +0 -140
  56. package/frigg-cli/utils/provider-helper.js +0 -80
  57. package/infrastructure/__tests__/create-frigg-infrastructure-provider.test.js +0 -64
  58. package/infrastructure/__tests__/management-api-gateway-routes.test.js +0 -335
  59. package/infrastructure/provider-build.js +0 -119
  60. package/test/npm-install-guard.js +0 -104
  61. package/test/npm-install-guard.test.js +0 -53
@@ -0,0 +1,148 @@
1
+ /**
2
+ * The app scaffolded by `frigg init` must deploy with no always-on AWS cost.
3
+ *
4
+ * Scaffolds the backend template, loads its Definition and composes it the way
5
+ * `frigg deploy` does (AWS discovery stubbed), then asserts the template has
6
+ * no VPC, NAT gateway, Elastic IP, VPC endpoint or RDS/Aurora resource, that
7
+ * no Lambda is attached to a VPC, and that field-level encryption still gets
8
+ * its KMS key.
9
+ */
10
+
11
+ const os = require('os');
12
+ const path = require('path');
13
+ const fs = require('fs-extra');
14
+
15
+ jest.mock('../domains/shared/resource-discovery', () => ({
16
+ ...jest.requireActual('../domains/shared/resource-discovery'),
17
+ gatherDiscoveredResources: jest.fn(),
18
+ }));
19
+ jest.mock('../domains/shared/utilities/prisma-layer-manager', () => ({
20
+ ensurePrismaLayerExists: jest.fn().mockResolvedValue(undefined),
21
+ }));
22
+
23
+ const {
24
+ gatherDiscoveredResources,
25
+ } = require('../domains/shared/resource-discovery');
26
+ const { composeServerlessDefinition } = require('../infrastructure-composer');
27
+ const BackendFirstHandler = require('../../frigg-cli/init-command/backend-first-handler');
28
+
29
+ const FORBIDDEN_RESOURCE_TYPES = [
30
+ 'AWS::EC2::VPC',
31
+ 'AWS::EC2::NatGateway',
32
+ 'AWS::EC2::EIP',
33
+ 'AWS::EC2::VPCEndpoint',
34
+ 'AWS::RDS::DBCluster',
35
+ 'AWS::RDS::DBInstance',
36
+ 'AWS::RDS::DBSubnetGroup',
37
+ ];
38
+
39
+ // An account that already holds a default VPC, subnets, a NAT gateway and an
40
+ // Aurora cluster: none of it may leak into the scaffolded app's template.
41
+ const BUSY_ACCOUNT_DISCOVERY = {
42
+ defaultVpcId: 'vpc-123456',
43
+ vpcCidr: '172.31.0.0/16',
44
+ defaultSecurityGroupId: 'sg-123456',
45
+ privateSubnetId1: 'subnet-123456',
46
+ privateSubnetId2: 'subnet-789012',
47
+ publicSubnetId1: 'subnet-public-1',
48
+ publicSubnetId2: 'subnet-public-2',
49
+ defaultRouteTableId: 'rtb-123456',
50
+ existingNatGatewayId: 'nat-default123',
51
+ auroraClusterEndpoint: 'c.cluster-abc123.us-east-1.rds.amazonaws.com',
52
+ auroraPort: 5432,
53
+ auroraEngine: 'aurora-postgresql',
54
+ };
55
+
56
+ describe('frigg init default infrastructure', () => {
57
+ let tmpDir;
58
+ let Definition;
59
+ let logSpy;
60
+
61
+ beforeAll(async () => {
62
+ logSpy = jest.spyOn(console, 'log').mockImplementation();
63
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'frigg-default-infra-'));
64
+ const target = path.join(tmpDir, 'demo-app');
65
+ await new BackendFirstHandler(target, {
66
+ yes: true,
67
+ install: false,
68
+ git: false,
69
+ }).initialize();
70
+ ({ Definition } = require(path.join(target, 'index.js')));
71
+ });
72
+
73
+ afterAll(() => {
74
+ fs.removeSync(tmpDir);
75
+ logSpy.mockRestore();
76
+ });
77
+
78
+ beforeEach(() => {
79
+ delete process.env.FRIGG_SKIP_AWS_DISCOVERY;
80
+ process.argv = ['node', 'test'];
81
+ });
82
+
83
+ const compose = async (discovery) => {
84
+ gatherDiscoveredResources.mockResolvedValue(discovery);
85
+ // The composer mutates nested parts of the definition.
86
+ return composeServerlessDefinition(
87
+ JSON.parse(JSON.stringify(Definition))
88
+ );
89
+ };
90
+
91
+ const resourceTypes = (definition) =>
92
+ Object.values(definition.resources.Resources).map((r) => r.Type);
93
+
94
+ it('passes the app-definition schema', () => {
95
+ const { validateAppDefinition } = require('@friggframework/schemas');
96
+ expect(validateAppDefinition(Definition).valid).toBe(true);
97
+ });
98
+
99
+ it.each([
100
+ ['an empty account', {}],
101
+ ['an account with existing VPC/NAT/Aurora', BUSY_ACCOUNT_DISCOVERY],
102
+ ])('composes no always-on resources in %s', async (_label, discovery) => {
103
+ const definition = await compose(discovery);
104
+ const types = resourceTypes(definition);
105
+
106
+ for (const forbidden of FORBIDDEN_RESOURCE_TYPES) {
107
+ expect(types).not.toContain(forbidden);
108
+ }
109
+
110
+ // No Lambda is attached to a VPC.
111
+ expect(definition.provider.vpc).toBeUndefined();
112
+ for (const fn of Object.values(definition.functions)) {
113
+ expect(fn.vpc).toBeUndefined();
114
+ }
115
+ for (const resource of Object.values(definition.resources.Resources)) {
116
+ expect(resource.Properties?.VpcConfig).toBeUndefined();
117
+ }
118
+ });
119
+
120
+ it('keeps field-level encryption on with a per-stage KMS key', async () => {
121
+ const definition = await compose({});
122
+
123
+ expect(definition.resources.Resources.FriggKMSKey.Type).toBe(
124
+ 'AWS::KMS::Key'
125
+ );
126
+ expect(definition.provider.environment.KMS_KEY_ARN).toEqual({
127
+ 'Fn::GetAtt': ['FriggKMSKey', 'Arn'],
128
+ });
129
+ });
130
+
131
+ it('connects to the external database through DATABASE_URL', async () => {
132
+ const definition = await compose({});
133
+
134
+ expect(definition.provider.environment.DATABASE_URL).toBe(
135
+ "${env:DATABASE_URL, ''}"
136
+ );
137
+ expect(definition.provider.environment.DB_TYPE).toBe('postgresql');
138
+ expect(definition.resources.Resources.FriggDBSecret).toBeUndefined();
139
+ });
140
+
141
+ it('expires Lambda logs after 14 days', async () => {
142
+ // Without provider.logRetentionInDays, osls creates log groups that
143
+ // never expire, so CloudWatch storage grows forever.
144
+ const definition = await compose({});
145
+
146
+ expect(definition.provider.logRetentionInDays).toBe(14);
147
+ });
148
+ });
@@ -5,13 +5,6 @@
5
5
  * valid, consistent CloudFormation templates.
6
6
  */
7
7
 
8
- // Composing must not build the real Prisma layer: that runs npm install
9
- // under packages/devtools, and two workers doing it at once once pruned the
10
- // repository's root node_modules (test/npm-install-guard.js).
11
- jest.mock('../domains/shared/utilities/prisma-layer-manager', () => ({
12
- ensurePrismaLayerExists: jest.fn(async () => {}),
13
- }));
14
-
15
8
  const { composeServerlessDefinition } = require('../infrastructure-composer');
16
9
 
17
10
  describe('CloudFormation Template Generation', () => {
@@ -35,20 +35,6 @@ async function createFriggInfrastructure() {
35
35
  throw new Error('Could not find index.js');
36
36
  }
37
37
 
38
- // A non-AWS provider (appDefinition.provider, e.g. 'netlify') builds
39
- // through its provider plugin instead of serverless/CloudFormation
40
- // (friggframework/frigg#545). Checked before the cache: the cache holds
41
- // serverless definitions only. Returns an empty serverless definition,
42
- // so an osls invocation has nothing to package.
43
- {
44
- const { isNonAwsProvider, buildWithProvider } = require('./provider-build');
45
- const appDefinition = require(backendFilePath).Definition;
46
- if (isNonAwsProvider(appDefinition)) {
47
- buildWithProvider({ appDefinition, backendDir });
48
- return {};
49
- }
50
- }
51
-
52
38
  const cachePath = getCachePath(backendDir);
53
39
  const lockPath = getLockPath(backendDir);
54
40
 
@@ -11,10 +11,30 @@ Frigg Framework supports automatic provisioning of Amazon Aurora Serverless v2 P
11
11
  - **Aurora Serverless v2**: Cost-efficient auto-scaling database (0.5-1.0 ACU default)
12
12
  - **VPC Integration**: Deployed in same private subnets as Lambda functions
13
13
  - **Secrets Manager**: Automatic credential management and rotation
14
- - **Three Management Modes**: discover, create-new, use-existing
14
+ - **Management Modes**: discover, create-new, use-existing, external (bring your own `DATABASE_URL`)
15
15
  - **Security**: Private subnet deployment with security group isolation
16
16
  - **High Availability**: Multi-AZ deployment with automatic failover
17
17
 
18
+ ### Bring your own PostgreSQL (`management: 'external'`)
19
+
20
+ To connect to a PostgreSQL that Frigg does not manage (any hosted provider, or
21
+ a database you run yourself), set `management: 'external'`. Frigg then creates
22
+ and discovers no database resources (no RDS/Aurora, no Secrets Manager secret)
23
+ and needs no VPC for the database; the app connects through `DATABASE_URL`.
24
+ This check takes precedence over a top-level `managementMode`. The migration
25
+ infrastructure is still composed, so migrations run against `DATABASE_URL`.
26
+
27
+ ```javascript
28
+ const appDefinition = {
29
+ vpc: { enable: false },
30
+ database: { postgres: { enable: true, management: 'external' } },
31
+ environment: { DATABASE_URL: true }, // read from the shell that runs `frigg deploy` (not .env)
32
+ };
33
+ ```
34
+
35
+ Use `sslmode=require` in the URL. This is the default for apps scaffolded by
36
+ `frigg init`.
37
+
18
38
  ---
19
39
 
20
40
  ## Configuration Schema
@@ -141,10 +141,12 @@ class AdminScriptBuilder extends InfrastructureBuilder {
141
141
  }
142
142
 
143
143
  createAdminScriptQueue(result, appDefinition) {
144
+ // Registered under custom so the serverless plugin creates it in LocalStack offline
145
+ result.custom.AdminScriptQueue = '${self:service}-${self:provider.stage}-AdminScriptQueue';
144
146
  result.resources.AdminScriptQueue = {
145
147
  Type: 'AWS::SQS::Queue',
146
148
  Properties: {
147
- QueueName: '${self:service}-${self:provider.stage}-AdminScriptQueue',
149
+ QueueName: '${self:custom.AdminScriptQueue}',
148
150
  MessageRetentionPeriod: 86400, // 1 day
149
151
  VisibilityTimeout: 900, // 15 minutes (Lambda max)
150
152
  RedrivePolicy: {
@@ -264,10 +266,12 @@ class AdminScriptBuilder extends InfrastructureBuilder {
264
266
  }
265
267
 
266
268
  createReportQueue(result, appDefinition) {
269
+ // Registered under custom so the serverless plugin creates it in LocalStack offline
270
+ result.custom.ReportQueue = '${self:service}-${self:provider.stage}-ReportQueue';
267
271
  result.resources.ReportQueue = {
268
272
  Type: 'AWS::SQS::Queue',
269
273
  Properties: {
270
- QueueName: '${self:service}-${self:provider.stage}-ReportQueue',
274
+ QueueName: '${self:custom.ReportQueue}',
271
275
  MessageRetentionPeriod: 86400, // 1 day
272
276
  VisibilityTimeout: 900, // 15 minutes (Lambda max)
273
277
  RedrivePolicy: {
@@ -168,6 +168,21 @@ describe('AdminScriptBuilder', () => {
168
168
  expect(result.resources.AdminScriptQueue.Properties.VisibilityTimeout).toBe(900); // 15 minutes
169
169
  });
170
170
 
171
+ it('registers AdminScriptQueue under custom so frigg start creates it locally', async () => {
172
+ const appDefinition = {
173
+ adminScripts: [{ Definition: { name: 'test-script' } }],
174
+ };
175
+
176
+ const result = await adminScriptBuilder.build(appDefinition, {});
177
+
178
+ expect(result.custom.AdminScriptQueue).toBe(
179
+ '${self:service}-${self:provider.stage}-AdminScriptQueue'
180
+ );
181
+ expect(result.resources.AdminScriptQueue.Properties.QueueName).toBe(
182
+ '${self:custom.AdminScriptQueue}'
183
+ );
184
+ });
185
+
171
186
  it('should configure AdminScriptQueue redrive policy to InternalErrorQueue', async () => {
172
187
  const appDefinition = {
173
188
  adminScripts: [
@@ -621,6 +636,21 @@ describe('AdminScriptBuilder', () => {
621
636
  });
622
637
 
623
638
  describe('reports (ReportQueue + reportExecutor)', () => {
639
+ it('registers ReportQueue under custom so frigg start creates it locally', async () => {
640
+ const appDefinition = {
641
+ reports: [{ Definition: { name: 'my-report', version: '1.0.0' } }],
642
+ };
643
+
644
+ const result = await adminScriptBuilder.build(appDefinition, {});
645
+
646
+ expect(result.custom.ReportQueue).toBe(
647
+ '${self:service}-${self:provider.stage}-ReportQueue'
648
+ );
649
+ expect(result.resources.ReportQueue.Properties.QueueName).toBe(
650
+ '${self:custom.ReportQueue}'
651
+ );
652
+ });
653
+
624
654
  it('creates ReportQueue + reportExecutor and wires REPORT_QUEUE_URL when reports are present', async () => {
625
655
  const appDefinition = {
626
656
  reports: [{ Definition: { name: 'my-report', version: '1.0.0' } }],
@@ -64,7 +64,18 @@ class AuroraBuilder extends InfrastructureBuilder {
64
64
  return false;
65
65
  }
66
66
 
67
- return appDefinition.database?.postgres?.enable === true;
67
+ const postgres = appDefinition.database?.postgres;
68
+
69
+ // management='external': the app brings its own PostgreSQL (any
70
+ // provider) and connects through DATABASE_URL. Frigg creates and
71
+ // discovers no database resources and needs no VPC for it. This
72
+ // check precedes managementMode, which otherwise always manages
73
+ // Aurora. Migrations still run (MigrationBuilder) against DATABASE_URL.
74
+ if (postgres?.management === 'external') {
75
+ return false;
76
+ }
77
+
78
+ return postgres?.enable === true;
68
79
  }
69
80
 
70
81
  getDependencies() {
@@ -82,7 +93,7 @@ class AuroraBuilder extends InfrastructureBuilder {
82
93
  const dbConfig = appDefinition.database.postgres;
83
94
 
84
95
  // Validate management mode
85
- const validModes = ['discover', 'managed', 'use-existing'];
96
+ const validModes = ['discover', 'managed', 'use-existing', 'external'];
86
97
  const management = dbConfig.management || 'discover';
87
98
  if (!validModes.includes(management)) {
88
99
  result.addError(`Invalid database.postgres.management: "${management}"`);
@@ -42,6 +42,28 @@ describe('AuroraBuilder', () => {
42
42
  expect(auroraBuilder.shouldExecute(appDefinition)).toBe(false);
43
43
  });
44
44
 
45
+ it('should return false when Postgres is external (bring your own DATABASE_URL)', () => {
46
+ const appDefinition = {
47
+ database: {
48
+ postgres: { enable: true, management: 'external' },
49
+ },
50
+ };
51
+
52
+ expect(auroraBuilder.shouldExecute(appDefinition)).toBe(false);
53
+ });
54
+
55
+ it('should return false for external Postgres even with managementMode=managed', () => {
56
+ const appDefinition = {
57
+ managementMode: 'managed',
58
+ vpcIsolation: 'isolated',
59
+ database: {
60
+ postgres: { enable: true, management: 'external' },
61
+ },
62
+ };
63
+
64
+ expect(auroraBuilder.shouldExecute(appDefinition)).toBe(false);
65
+ });
66
+
45
67
  it('should return false when database is not defined', () => {
46
68
  const appDefinition = {};
47
69
 
@@ -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
  });
@@ -72,16 +72,6 @@ function addLoggingEnv(appDefinition, envVars) {
72
72
  envVars.FRIGG_LOG_LEVEL = normalized;
73
73
  }
74
74
 
75
- // Field-level encryption fails closed in a deployed stage with no key (core's
76
- // encryption-config.js). `fieldLevelEncryptionMethod: 'none'` is the explicit,
77
- // documented way to run a stage in plaintext; core logs a warning on every
78
- // cold start while it is set.
79
- function addEncryptionEnv(appDefinition, envVars) {
80
- if (appDefinition?.encryption?.fieldLevelEncryptionMethod === 'none') {
81
- envVars.FRIGG_ENCRYPTION_DISABLED = 'true';
82
- }
83
- }
84
-
85
75
  /**
86
76
  * Get environment variables from AppDefinition
87
77
  *
@@ -159,7 +149,6 @@ function getAppEnvironmentVars(appDefinition) {
159
149
  }
160
150
 
161
151
  addLoggingEnv(appDefinition, envVars);
162
- addEncryptionEnv(appDefinition, envVars);
163
152
 
164
153
  if (envKeys.length > 0) {
165
154
  console.log(
@@ -198,7 +187,7 @@ function getAppEnvironmentVars(appDefinition) {
198
187
  function buildEnvironment(appEnvironmentVars, discoveredResources) {
199
188
  const environment = {
200
189
  ...appEnvironmentVars,
201
- STAGE: '${self:provider.stage}', // Read by core: e.g. the local-only encryption bypass
190
+ STAGE: '${self:provider.stage}', // Used by encryption bypass logic
202
191
  FRIGG_STACK: '${self:service}',
203
192
  FRIGG_STAGE: '${self:provider.stage}',
204
193
  FRIGG_REGION: '${self:provider.region}',