@friggframework/devtools 2.0.0--canary.731.ffe61d3.0 → 2.0.0--canary.658.130b4ec.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 (102) hide show
  1. package/frigg-cli/README.md +31 -115
  2. package/frigg-cli/__tests__/unit/commands/build.test.js +0 -3
  3. package/frigg-cli/__tests__/unit/commands/deploy.test.js +24 -33
  4. package/frigg-cli/__tests__/unit/commands/doctor.test.js +6 -10
  5. package/frigg-cli/__tests__/unit/commands/generate-iam.test.js +0 -18
  6. package/frigg-cli/__tests__/unit/commands/install.test.js +341 -601
  7. package/frigg-cli/__tests__/unit/commands/ui.test.js +30 -31
  8. package/frigg-cli/__tests__/unit/dependencies.test.js +2 -6
  9. package/frigg-cli/build-command/index.js +0 -6
  10. package/frigg-cli/deploy-command/index.js +0 -6
  11. package/frigg-cli/generate-command/index.js +0 -1
  12. package/frigg-cli/generate-iam-command.js +0 -1
  13. package/frigg-cli/index.js +5 -22
  14. package/frigg-cli/index.test.js +158 -0
  15. package/frigg-cli/init-command/backend-first-handler.js +551 -395
  16. package/frigg-cli/init-command/index.js +35 -82
  17. package/frigg-cli/install-command/commit-changes.js +8 -40
  18. package/frigg-cli/install-command/environment-variables.js +0 -15
  19. package/frigg-cli/install-command/index.js +21 -96
  20. package/frigg-cli/install-command/install-package.js +4 -77
  21. package/frigg-cli/install-command/integration-file.js +11 -20
  22. package/frigg-cli/install-command/template.js +75 -102
  23. package/frigg-cli/install-command/validate-package.js +4 -36
  24. package/frigg-cli/package.json +1 -1
  25. package/frigg-cli/start-command/index.js +0 -4
  26. package/frigg-cli/start-command/start-command.test.js +0 -3
  27. package/frigg-cli/test/init-command.test.js +2 -9
  28. package/infrastructure/README.md +5 -32
  29. package/infrastructure/__tests__/postgres-config.test.js +836 -245
  30. package/infrastructure/__tests__/scoped-environment.test.js +0 -3
  31. package/infrastructure/__tests__/ssm-preload-node-options.test.js +0 -3
  32. package/infrastructure/__tests__/template-generation.test.js +8 -39
  33. package/infrastructure/create-frigg-infrastructure.js +1 -4
  34. package/infrastructure/docs/POSTGRES-CONFIGURATION.md +98 -80
  35. package/infrastructure/domains/admin-scripts/admin-script-builder.js +2 -8
  36. package/infrastructure/domains/admin-scripts/admin-script-builder.test.js +6 -52
  37. package/infrastructure/domains/database/aurora-builder.js +2 -13
  38. package/infrastructure/domains/database/aurora-builder.test.js +0 -22
  39. package/infrastructure/domains/database/migration-builder.js +2 -21
  40. package/infrastructure/domains/database/migration-builder.test.js +6 -61
  41. package/infrastructure/domains/health/application/use-cases/__tests__/mismatch-analyzer-method-name.test.js +8 -12
  42. package/infrastructure/domains/health/application/use-cases/__tests__/repair-via-import-use-case.test.js +7 -19
  43. package/infrastructure/domains/health/application/use-cases/run-health-check-use-case.test.js +8 -12
  44. package/infrastructure/domains/health/domain/services/__tests__/import-progress-monitor.test.js +18 -17
  45. package/infrastructure/domains/health/domain/services/__tests__/update-progress-monitor.test.js +2 -12
  46. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-relationship-analysis.test.js +1 -8
  47. package/infrastructure/domains/health/infrastructure/adapters/aws-property-reconciler.test.js +2 -4
  48. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-detector.test.js +0 -10
  49. package/infrastructure/domains/integration/integration-builder.js +0 -2
  50. package/infrastructure/domains/integration/integration-builder.test.js +6 -22
  51. package/infrastructure/domains/networking/vpc-builder.js +8 -18
  52. package/infrastructure/domains/networking/vpc-builder.test.js +12 -26
  53. package/infrastructure/domains/security/iam-generator.js +5 -112
  54. package/infrastructure/domains/security/iam-generator.test.js +0 -94
  55. package/infrastructure/domains/shared/cloudformation-discovery.test.js +6 -36
  56. package/infrastructure/domains/shared/environment-builder.js +5 -31
  57. package/infrastructure/domains/shared/environment-builder.test.js +7 -93
  58. package/infrastructure/domains/shared/utilities/base-definition-factory.js +3 -39
  59. package/infrastructure/domains/shared/utilities/base-definition-factory.test.js +5 -85
  60. package/infrastructure/domains/shared/utilities/nested-node-modules.js +5 -6
  61. package/infrastructure/domains/shared/utilities/nested-node-modules.test.js +26 -20
  62. package/infrastructure/domains/shared/utilities/prisma-layer-manager.js +12 -92
  63. package/infrastructure/domains/shared/utilities/prisma-layer-manager.test.js +6 -158
  64. package/infrastructure/infrastructure-composer.js +1 -12
  65. package/infrastructure/infrastructure-composer.test.js +794 -339
  66. package/infrastructure/integration.test.js +381 -0
  67. package/infrastructure/scripts/build-prisma-layer.js +50 -136
  68. package/infrastructure/scripts/build-prisma-layer.test.js +7 -128
  69. package/infrastructure/scripts/build-time-discovery.test.js +3 -18
  70. package/package.json +10 -12
  71. package/frigg-cli/__tests__/unit/commands/init.test.js +0 -688
  72. package/frigg-cli/__tests__/unit/commands/validate-wiring.test.js +0 -92
  73. package/frigg-cli/init-command/deployment-modes.js +0 -7
  74. package/frigg-cli/init-command/safe-path.js +0 -58
  75. package/frigg-cli/init-command/scaffold-dependencies.js +0 -202
  76. package/frigg-cli/install-command/app-definition.js +0 -174
  77. package/frigg-cli/install-command/resolve-module.js +0 -69
  78. package/frigg-cli/templates/backend/README.md +0 -267
  79. package/frigg-cli/templates/backend/env.example +0 -20
  80. package/frigg-cli/templates/backend/gitignore +0 -10
  81. package/frigg-cli/templates/backend/index.js +0 -114
  82. package/frigg-cli/templates/backend/infrastructure.js +0 -20
  83. package/frigg-cli/validate-command/__tests__/init-validation.test.js +0 -63
  84. package/frigg-cli/validate-command/__tests__/integrations-checks.test.js +0 -133
  85. package/frigg-cli/validate-command/__tests__/validate-app-definition.test.js +0 -443
  86. package/frigg-cli/validate-command/__tests__/validate-command.test.js +0 -262
  87. package/frigg-cli/validate-command/checks/config.js +0 -504
  88. package/frigg-cli/validate-command/checks/integrations.js +0 -274
  89. package/frigg-cli/validate-command/format-report.js +0 -58
  90. package/frigg-cli/validate-command/index.js +0 -107
  91. package/frigg-cli/validate-command/load-app-definition.js +0 -105
  92. package/frigg-cli/validate-command/schema-issues.js +0 -154
  93. package/frigg-cli/validate-command/validate-app-definition.js +0 -60
  94. package/infrastructure/__tests__/helpers/bundled-prisma-engine-excludes.js +0 -39
  95. package/infrastructure/__tests__/management-api-gateway-routes.test.js +0 -284
  96. package/infrastructure/__tests__/scaffold-default-infrastructure.test.js +0 -151
  97. package/infrastructure/app-definition-schema-contract.test.js +0 -634
  98. package/infrastructure/create-frigg-infrastructure.test.js +0 -51
  99. package/infrastructure/domains/database/migration-engines.js +0 -93
  100. package/infrastructure/domains/database/migration-engines.test.js +0 -142
  101. package/infrastructure/domains/shared/lambda-architectures.js +0 -113
  102. package/infrastructure/domains/shared/lambda-architectures.test.js +0 -164
@@ -1,60 +0,0 @@
1
- /**
2
- * Validate an app definition: the JSON Schema (keys, types, enums) plus the
3
- * semantic checks the schema cannot express (ADR-051). Pure: no I/O.
4
- */
5
-
6
- const {
7
- validateAppDefinition,
8
- applyAppDefinitionDefaults,
9
- getSchema,
10
- } = require('@friggframework/schemas');
11
- const { schemaErrorsToIssues } = require('./schema-issues');
12
- const { checkIntegrations } = require('./checks/integrations');
13
- const { checkConfig } = require('./checks/config');
14
-
15
- /**
16
- * @param {object} params
17
- * @param {object} params.definition the `Definition` exported by index.js
18
- * @param {string} [params.stage] the stage being built or deployed
19
- * @param {object} [params.env] environment variables (default process.env)
20
- * @returns {{ errors: object[], warnings: object[] }}
21
- */
22
- function validateDefinition({ definition, stage, env = process.env }) {
23
- const schemaResult = validateAppDefinition(definition);
24
- // Integration entries are classes: checkIntegrations reports them more
25
- // precisely than the schema's view of them can.
26
- const issues = schemaErrorsToIssues(
27
- schemaResult.errors,
28
- getSchema('app-definition')
29
- ).filter((issue) => !issue.pointer.startsWith('/integrations/'));
30
-
31
- let semantic = [];
32
- if (definition && typeof definition === 'object') {
33
- semantic = [
34
- ...checkIntegrations(definition),
35
- ...checkConfig({
36
- definition: applyAppDefinitionDefaults(definition),
37
- raw: definition,
38
- stage,
39
- env,
40
- }),
41
- ];
42
- }
43
-
44
- // One issue per pointer and code; the schema's wins.
45
- const seen = new Set(issues.map((i) => `${i.code}:${i.pointer}`));
46
- for (const issue of semantic) {
47
- const key = `${issue.code}:${issue.pointer}`;
48
- if (!seen.has(key)) {
49
- seen.add(key);
50
- issues.push(issue);
51
- }
52
- }
53
-
54
- return {
55
- errors: issues.filter((i) => i.severity === 'error'),
56
- warnings: issues.filter((i) => i.severity !== 'error'),
57
- };
58
- }
59
-
60
- module.exports = { validateDefinition };
@@ -1,39 +0,0 @@
1
- /**
2
- * Shared cases for every builder whose functions bundle Prisma when the
3
- * Prisma layer is off.
4
- * @param {(usePrismaLayer: boolean, architecture?: string) => Promise<Object[]>|Object[]} functionsOf
5
- * Builds the app and returns its function definitions
6
- */
7
- function itBundlesOnlyTheTargetPrismaEngine(functionsOf) {
8
- it.each([
9
- [undefined, 'rhel-openssl-3.0.x', 'linux-arm64-openssl-3.0.x'],
10
- ['x86_64', 'rhel-openssl-3.0.x', 'linux-arm64-openssl-3.0.x'],
11
- ['arm64', 'linux-arm64-openssl-3.0.x', 'rhel-openssl-3.0.x'],
12
- ])(
13
- 'with the layer off and architecture %s, the bundled Prisma keeps only the %s engine',
14
- async (architecture, target, otherTarget) => {
15
- for (const fn of await functionsOf(false, architecture)) {
16
- expect(fn.package.exclude).toEqual(
17
- expect.arrayContaining([
18
- '**/libquery_engine-debian*',
19
- `**/libquery_engine-${otherTarget}*`,
20
- ])
21
- );
22
- expect(fn.package.exclude).not.toContain(`**/libquery_engine-${target}*`);
23
- }
24
- }
25
- );
26
-
27
- it('with the layer on, adds no engine patterns, since the layer carries the engines', async () => {
28
- for (const fn of await functionsOf(true, 'arm64')) {
29
- expect(fn.package.exclude).not.toEqual(
30
- expect.arrayContaining(['**/libquery_engine-rhel-openssl-3.0.x*'])
31
- );
32
- expect(fn.package.exclude).not.toEqual(
33
- expect.arrayContaining(['**/libquery_engine-debian*'])
34
- );
35
- }
36
- });
37
- }
38
-
39
- module.exports = { itBundlesOnlyTheTargetPrismaEngine };
@@ -1,284 +0,0 @@
1
- /**
2
- * Management API ↔ API Gateway route coverage
3
- *
4
- * The Management API is an Express app (core's createIntegrationRouter)
5
- * served by the `auth` Lambda. API Gateway HTTP APIs have no implicit
6
- * catch-all: a request whose path matches no declared route gets a gateway
7
- * 404 and never reaches Express. So every route the integration router
8
- * registers must be covered by an httpApi event on the `auth` function, and
9
- * no more-specific route on another function may shadow it.
10
- *
11
- * The Express routes are read from the live router (not a hard-coded list),
12
- * so a route added to core later fails this test until the gateway routes
13
- * are updated alongside it.
14
- */
15
-
16
- // Avoid AWS calls: hand the builders a fixed discovery result.
17
- jest.mock('../domains/shared/resource-discovery', () => {
18
- const actual = jest.requireActual('../domains/shared/resource-discovery');
19
- return {
20
- ...actual,
21
- gatherDiscoveredResources: jest.fn().mockResolvedValue({
22
- defaultVpcId: 'vpc-123456',
23
- vpcCidr: '172.31.0.0/16',
24
- defaultSecurityGroupId: 'sg-123456',
25
- privateSubnetId1: 'subnet-123456',
26
- privateSubnetId2: 'subnet-789012',
27
- publicSubnetId1: 'subnet-public-1',
28
- publicSubnetId2: 'subnet-public-2',
29
- defaultRouteTableId: 'rtb-123456',
30
- defaultKmsKeyId:
31
- 'arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012',
32
- existingNatGatewayId: 'nat-default123',
33
- auroraClusterEndpoint:
34
- 'test-cluster.cluster-abc123.us-east-1.rds.amazonaws.com',
35
- auroraPort: 5432,
36
- auroraEngine: 'aurora-postgresql',
37
- }),
38
- };
39
- });
40
- jest.mock('../domains/database/migration-engines', () => ({
41
- ensureMigrationEngines: jest.fn().mockResolvedValue(undefined),
42
- }));
43
-
44
- // createIntegrationRouter loads the app definition from the consuming
45
- // backend; give it an empty one so the router can be built in isolation.
46
- jest.mock('@friggframework/core/handlers/app-definition-loader', () => ({
47
- loadAppDefinition: () => ({ integrations: [], userConfig: {} }),
48
- }));
49
-
50
- const { composeServerlessDefinition } = require('../infrastructure-composer');
51
-
52
- // Routes the auth Lambda's handler (core/handlers/routers/auth.js) adds on
53
- // top of createIntegrationRouter().
54
- const AUTH_HANDLER_EXTRA_ROUTES = [
55
- { method: 'GET', path: '/api/integrations/redirect/:appId' },
56
- ];
57
-
58
- function getIntegrationRouterRoutes() {
59
- const { createIntegrationRouter } = require('@friggframework/core');
60
- // The repository factories pick an adapter from DB_TYPE (or the backend's
61
- // app definition, which doesn't exist here). Nothing connects.
62
- const previousDbType = process.env.DB_TYPE;
63
- process.env.DB_TYPE = 'postgresql';
64
- let app;
65
- try {
66
- app = createIntegrationRouter();
67
- } finally {
68
- if (previousDbType === undefined) delete process.env.DB_TYPE;
69
- else process.env.DB_TYPE = previousDbType;
70
- }
71
- const stack = (app._router || app.router).stack;
72
- const routes = [];
73
- for (const layer of stack) {
74
- if (!layer.route) continue;
75
- for (const method of Object.keys(layer.route.methods)) {
76
- routes.push({
77
- method: method === '_all' ? 'ANY' : method.toUpperCase(),
78
- path: layer.route.path,
79
- });
80
- }
81
- }
82
- return routes;
83
- }
84
-
85
- function getGatewayRoutes(definition) {
86
- const routes = [];
87
- for (const [functionName, fn] of Object.entries(definition.functions)) {
88
- for (const event of fn.events || []) {
89
- if (!event.httpApi) continue;
90
- routes.push({
91
- functionName,
92
- method: String(event.httpApi.method).toUpperCase(),
93
- path: event.httpApi.path,
94
- });
95
- }
96
- }
97
- return routes;
98
- }
99
-
100
- const segmentsOf = (p) => p.split('/').filter(Boolean);
101
-
102
- // Turn an Express path into a concrete request path, e.g.
103
- // /api/entities/:entityId/options -> /api/entities/sample-entityId/options
104
- const toConcretePath = (expressPath) =>
105
- expressPath.replace(/:([A-Za-z0-9_]+)/g, 'sample-$1');
106
-
107
- /**
108
- * HTTP API path matching: literal segments match exactly, {param} matches
109
- * one segment, a trailing {proxy+} greedily matches one or more segments.
110
- * Returns null on no match, otherwise a specificity descriptor.
111
- */
112
- function matchGatewayPath(gatewayPath, requestPath) {
113
- const g = segmentsOf(gatewayPath);
114
- const r = segmentsOf(requestPath);
115
- let literals = 0;
116
- for (let i = 0; i < g.length; i++) {
117
- const seg = g[i];
118
- if (/^\{[^}]+\+\}$/.test(seg)) {
119
- if (i !== g.length - 1 || r.length <= i) return null;
120
- return { greedy: true, literals, prefixLength: i };
121
- }
122
- if (i >= r.length) return null;
123
- if (/^\{[^}]+\}$/.test(seg)) continue;
124
- if (seg !== r[i]) return null;
125
- literals++;
126
- }
127
- if (g.length !== r.length) return null;
128
- return { greedy: false, literals, prefixLength: g.length };
129
- }
130
-
131
- /**
132
- * Select the route API Gateway would invoke: a non-greedy match beats a
133
- * greedy one, then more literal segments, then the longer greedy prefix,
134
- * then an explicit method beats ANY.
135
- */
136
- function selectGatewayRoute(gatewayRoutes, method, requestPath) {
137
- const candidates = gatewayRoutes
138
- .filter(
139
- (r) => r.method === 'ANY' || method === 'ANY' || r.method === method
140
- )
141
- .map((r) => ({
142
- route: r,
143
- match: matchGatewayPath(r.path, requestPath),
144
- }))
145
- .filter((c) => c.match);
146
- candidates.sort(
147
- (a, b) =>
148
- Number(a.match.greedy) - Number(b.match.greedy) ||
149
- b.match.literals - a.match.literals ||
150
- b.match.prefixLength - a.match.prefixLength ||
151
- Number(a.route.method === 'ANY') - Number(b.route.method === 'ANY')
152
- );
153
- return candidates.length ? candidates[0].route : null;
154
- }
155
-
156
- describe('Management API routes are reachable through API Gateway', () => {
157
- let gatewayRoutes;
158
- let managementRoutes;
159
- const originalArgv = process.argv;
160
-
161
- beforeAll(async () => {
162
- process.argv = ['node', 'test'];
163
- process.env.AWS_REGION = 'us-east-1';
164
- // The builders narrate their progress; keep the test output quiet.
165
- const logSpy = jest.spyOn(console, 'log').mockImplementation(() => {});
166
- const warnSpy = jest
167
- .spyOn(console, 'warn')
168
- .mockImplementation(() => {});
169
- try {
170
- const definition = await composeServerlessDefinition({
171
- name: 'route-coverage-app',
172
- provider: 'aws',
173
- usePrismaLambdaLayer: false,
174
- database: { postgres: { enable: true } },
175
- websockets: { enable: true },
176
- adminScripts: [
177
- class ExampleScript {
178
- static Definition = { name: 'example-script' };
179
- },
180
- ],
181
- admin: { includeBuiltinReports: true },
182
- integrations: [
183
- {
184
- Definition: {
185
- name: 'acme',
186
- webhooks: true,
187
- extensions: {
188
- inbound: {
189
- extension: {
190
- routes: [
191
- { path: '/events', method: 'POST' },
192
- ],
193
- },
194
- },
195
- },
196
- },
197
- },
198
- // Integration names share the /api/ namespace with the
199
- // Management API; make sure they don't shadow it.
200
- { Definition: { name: 'entities' } },
201
- ],
202
- });
203
- gatewayRoutes = getGatewayRoutes(definition);
204
- } finally {
205
- logSpy.mockRestore();
206
- warnSpy.mockRestore();
207
- }
208
- managementRoutes = [
209
- ...getIntegrationRouterRoutes(),
210
- ...AUTH_HANDLER_EXTRA_ROUTES,
211
- ];
212
- });
213
-
214
- afterAll(() => {
215
- process.argv = originalArgv;
216
- delete process.env.AWS_REGION;
217
- });
218
-
219
- it('reads the Management API routes from the core integration router', () => {
220
- const paths = managementRoutes.map((r) => r.path);
221
- expect(paths).toEqual(
222
- expect.arrayContaining([
223
- '/api/integrations',
224
- '/api/authorize',
225
- '/api/entity',
226
- '/api/entity/options/:credentialId',
227
- '/api/entities/:entityId',
228
- ])
229
- );
230
- });
231
-
232
- it('routes every Management API route to the auth function', () => {
233
- const unreachable = managementRoutes
234
- .map(({ method, path: expressPath }) => {
235
- const requestPath = toConcretePath(expressPath);
236
- const selected = selectGatewayRoute(
237
- gatewayRoutes,
238
- method,
239
- requestPath
240
- );
241
- return {
242
- route: `${method} ${expressPath}`,
243
- reachedBy: selected
244
- ? `${selected.method} ${selected.path} -> ${selected.functionName}`
245
- : 'no API Gateway route',
246
- ok: selected && selected.functionName === 'auth',
247
- };
248
- })
249
- .filter((r) => !r.ok)
250
- .map(({ route, reachedBy }) => `${route} (${reachedBy})`);
251
-
252
- expect(unreachable).toEqual([]);
253
- });
254
-
255
- it.each([
256
- ['GET', '/api/v2/reports', 'reportRouter'],
257
- ['POST', '/api/v2/reports/daily/run', 'reportRouter'],
258
- ['GET', '/admin/scripts/example-script', 'adminScriptRouter'],
259
- ['POST', '/api/acme-integration/webhooks', 'acmeWebhook'],
260
- ['POST', '/api/acme-integration/inbound/events', 'acme__inbound'],
261
- ['GET', '/api/acme-integration/custom', 'acme'],
262
- ['GET', '/api/entities-integration/custom', 'entities'],
263
- ['POST', '/user/login', 'user'],
264
- ['GET', '/health/ready', 'health'],
265
- ])('leaves %s %s on %s', (method, requestPath, functionName) => {
266
- const selected = selectGatewayRoute(gatewayRoutes, method, requestPath);
267
- expect(selected && selected.functionName).toBe(functionName);
268
- });
269
-
270
- it('declares no method + path pair on more than one function', () => {
271
- const seen = new Map();
272
- const duplicates = [];
273
- for (const r of gatewayRoutes) {
274
- const key = `${r.method} ${r.path}`;
275
- if (seen.has(key) && seen.get(key) !== r.functionName) {
276
- duplicates.push(
277
- `${key}: ${seen.get(key)} and ${r.functionName}`
278
- );
279
- }
280
- seen.set(key, r.functionName);
281
- }
282
- expect(duplicates).toEqual([]);
283
- });
284
- });
@@ -1,151 +0,0 @@
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
- });
149
- jest.mock('../domains/database/migration-engines', () => ({
150
- ensureMigrationEngines: jest.fn().mockResolvedValue(undefined),
151
- }));