@friggframework/devtools 2.0.0--canary.702.d5e6de1.0 → 2.0.0--canary.666.abcf913.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.
- package/README.md +0 -1
- package/frigg-cli/README.md +80 -41
- package/frigg-cli/__tests__/unit/commands/deploy.test.js +30 -24
- package/frigg-cli/__tests__/unit/commands/doctor.test.js +10 -6
- package/frigg-cli/__tests__/unit/commands/generate-iam.test.js +18 -0
- package/frigg-cli/__tests__/unit/commands/init.test.js +688 -0
- package/frigg-cli/__tests__/unit/commands/install.test.js +601 -341
- package/frigg-cli/__tests__/unit/commands/ui.test.js +31 -30
- package/frigg-cli/__tests__/unit/dependencies.test.js +6 -2
- package/frigg-cli/generate-command/index.js +1 -0
- package/frigg-cli/generate-iam-command.js +1 -0
- package/frigg-cli/index.js +12 -13
- package/frigg-cli/init-command/backend-first-handler.js +377 -512
- package/frigg-cli/init-command/deployment-modes.js +7 -0
- package/frigg-cli/init-command/index.js +82 -35
- package/frigg-cli/init-command/safe-path.js +58 -0
- package/frigg-cli/init-command/scaffold-dependencies.js +202 -0
- package/frigg-cli/install-command/app-definition.js +174 -0
- package/frigg-cli/install-command/commit-changes.js +40 -8
- package/frigg-cli/install-command/environment-variables.js +15 -0
- package/frigg-cli/install-command/index.js +96 -21
- package/frigg-cli/install-command/install-package.js +77 -4
- package/frigg-cli/install-command/integration-file.js +20 -11
- package/frigg-cli/install-command/resolve-module.js +69 -0
- package/frigg-cli/install-command/template.js +102 -75
- package/frigg-cli/install-command/validate-package.js +36 -4
- package/frigg-cli/package.json +1 -1
- package/frigg-cli/templates/backend/README.md +267 -0
- package/frigg-cli/templates/backend/env.example +20 -0
- package/frigg-cli/templates/backend/gitignore +10 -0
- package/frigg-cli/templates/backend/index.js +114 -0
- package/frigg-cli/templates/backend/infrastructure.js +20 -0
- package/frigg-cli/test/init-command.test.js +9 -2
- package/frigg-cli/validate-command/__tests__/validate-app-definition.test.js +123 -6
- package/frigg-cli/validate-command/__tests__/validate-command.test.js +21 -0
- package/frigg-cli/validate-command/checks/config.js +50 -14
- package/frigg-cli/validate-command/format-report.js +2 -4
- package/frigg-cli/validate-command/index.js +4 -48
- package/frigg-cli/validate-command/load-app-definition.js +17 -5
- package/infrastructure/__tests__/management-api-gateway-routes.test.js +281 -0
- package/infrastructure/__tests__/postgres-config.test.js +241 -835
- package/infrastructure/__tests__/scaffold-default-infrastructure.test.js +148 -0
- package/infrastructure/__tests__/template-generation.test.js +36 -8
- package/infrastructure/app-definition-schema-contract.test.js +22 -0
- package/infrastructure/docs/POSTGRES-CONFIGURATION.md +21 -1
- package/infrastructure/domains/database/aurora-builder.js +13 -2
- package/infrastructure/domains/database/aurora-builder.test.js +22 -0
- package/infrastructure/domains/health/application/use-cases/__tests__/mismatch-analyzer-method-name.test.js +12 -8
- package/infrastructure/domains/health/application/use-cases/__tests__/repair-via-import-use-case.test.js +19 -7
- package/infrastructure/domains/health/application/use-cases/run-health-check-use-case.test.js +12 -8
- package/infrastructure/domains/health/domain/services/__tests__/import-progress-monitor.test.js +17 -18
- package/infrastructure/domains/health/domain/services/__tests__/update-progress-monitor.test.js +12 -2
- package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-relationship-analysis.test.js +8 -1
- package/infrastructure/domains/health/infrastructure/adapters/aws-property-reconciler.test.js +4 -2
- package/infrastructure/domains/health/infrastructure/adapters/aws-resource-detector.test.js +10 -0
- package/infrastructure/domains/networking/vpc-builder.js +18 -8
- package/infrastructure/domains/networking/vpc-builder.test.js +26 -12
- package/infrastructure/domains/security/iam-generator.js +112 -5
- package/infrastructure/domains/security/iam-generator.test.js +94 -0
- package/infrastructure/domains/shared/cloudformation-discovery.test.js +36 -6
- package/infrastructure/domains/shared/utilities/base-definition-factory.js +26 -2
- package/infrastructure/domains/shared/utilities/base-definition-factory.test.js +34 -1
- package/infrastructure/infrastructure-composer.test.js +268 -794
- package/infrastructure/scripts/build-prisma-layer.test.js +28 -7
- package/infrastructure/scripts/build-time-discovery.test.js +18 -3
- package/package.json +10 -8
- package/frigg-cli/index.test.js +0 -158
- package/frigg-cli/validate-command/__tests__/validate-module-command.test.js +0 -119
- package/frigg-cli/validate-command/fixtures/bad-module/index.js +0 -18
- package/frigg-cli/validate-command/fixtures/fathom-module/definition.js +0 -76
- package/frigg-cli/validate-command/fixtures/fathom-module/index.js +0 -6
- package/frigg-cli/validate-command/load-module-definition.js +0 -64
- package/frigg-cli/validate-command/validate-module-definition.js +0 -46
- package/infrastructure/integration.test.js +0 -381
|
@@ -206,10 +206,14 @@ function checkManagement({ raw }) {
|
|
|
206
206
|
)
|
|
207
207
|
);
|
|
208
208
|
}
|
|
209
|
+
// 'external' is honoured in every mode (the Aurora builder checks it
|
|
210
|
+
// first). Under managementMode 'managed' or 'existing' the builder ignores
|
|
211
|
+
// 'use-existing' and still provisions or attaches a private cluster.
|
|
212
|
+
const postgresManagementIgnored = mode === 'managed' || mode === 'existing';
|
|
209
213
|
const provisionsAurora =
|
|
210
214
|
postgres.enable === true &&
|
|
211
|
-
postgres.management !== '
|
|
212
|
-
postgres.management !== '
|
|
215
|
+
postgres.management !== 'external' &&
|
|
216
|
+
(postgresManagementIgnored || postgres.management !== 'use-existing');
|
|
213
217
|
if (
|
|
214
218
|
provisionsAurora &&
|
|
215
219
|
vpc.enable !== true &&
|
|
@@ -221,7 +225,9 @@ function checkManagement({ raw }) {
|
|
|
221
225
|
'unreachable-database',
|
|
222
226
|
'/vpc/enable',
|
|
223
227
|
'Frigg provisions or discovers a private Aurora cluster, but the Lambda functions run outside a VPC and cannot reach it.',
|
|
224
|
-
|
|
228
|
+
postgresManagementIgnored
|
|
229
|
+
? `Set vpc.enable: true, or use database.postgres.management: 'external' with a reachable DATABASE_URL (managementMode '${mode}' ignores 'use-existing').`
|
|
230
|
+
: "Set vpc.enable: true, or use database.postgres.management: 'use-existing' with a reachable endpoint (or 'external' with DATABASE_URL)."
|
|
225
231
|
)
|
|
226
232
|
);
|
|
227
233
|
}
|
|
@@ -314,12 +320,13 @@ function checkEncryption({ raw, stage, env }) {
|
|
|
314
320
|
'no-field-encryption',
|
|
315
321
|
'/encryption/fieldLevelEncryptionMethod',
|
|
316
322
|
`No field-level encryption method: stage '${stage}' stores credentials and tokens unencrypted.`,
|
|
317
|
-
"Set encryption.fieldLevelEncryptionMethod to 'kms' (Frigg creates the key) or 'aes'."
|
|
323
|
+
"Set encryption.fieldLevelEncryptionMethod to 'kms' (Frigg creates the key) or 'aes', or to 'none' to store them unencrypted on purpose."
|
|
318
324
|
)
|
|
319
325
|
);
|
|
320
326
|
}
|
|
321
327
|
if (
|
|
322
328
|
method !== undefined &&
|
|
329
|
+
method !== 'none' &&
|
|
323
330
|
stage &&
|
|
324
331
|
ENCRYPTION_BYPASS_STAGES.includes(stage)
|
|
325
332
|
) {
|
|
@@ -338,6 +345,43 @@ function checkEncryption({ raw, stage, env }) {
|
|
|
338
345
|
return issues;
|
|
339
346
|
}
|
|
340
347
|
|
|
348
|
+
/**
|
|
349
|
+
* authModes.adopterJwt verifies tokens with user.jwtConfig.secret. The
|
|
350
|
+
* documented pattern is `secret: process.env.JWT_SECRET`, and build and
|
|
351
|
+
* deploy validate before `.env` is loaded, so an empty value only means the
|
|
352
|
+
* variable is unset in this shell; the Lambda may still receive it. A key
|
|
353
|
+
* missing from the definition is an error: nothing can supply it at runtime.
|
|
354
|
+
*/
|
|
355
|
+
function checkJwtSecret(jwtConfig) {
|
|
356
|
+
const declared =
|
|
357
|
+
jwtConfig !== null &&
|
|
358
|
+
typeof jwtConfig === 'object' &&
|
|
359
|
+
Object.prototype.hasOwnProperty.call(jwtConfig, 'secret');
|
|
360
|
+
if (!declared) {
|
|
361
|
+
return [
|
|
362
|
+
issue(
|
|
363
|
+
'error',
|
|
364
|
+
'missing-key',
|
|
365
|
+
'/user/jwtConfig/secret',
|
|
366
|
+
'authModes.adopterJwt needs user.jwtConfig.secret to verify tokens.',
|
|
367
|
+
'Set user.jwtConfig: { secret: process.env.JWT_SECRET }.'
|
|
368
|
+
),
|
|
369
|
+
];
|
|
370
|
+
}
|
|
371
|
+
if (!jwtConfig.secret) {
|
|
372
|
+
return [
|
|
373
|
+
issue(
|
|
374
|
+
'warning',
|
|
375
|
+
'missing-env-value',
|
|
376
|
+
'/user/jwtConfig/secret',
|
|
377
|
+
'user.jwtConfig.secret is empty here (its environment variable is not set in this shell). It must be set at runtime, or every adopter JWT is rejected.',
|
|
378
|
+
'Make sure the variable (e.g. JWT_SECRET) reaches the deployed Lambdas: list it in `environment` and set it where you deploy.'
|
|
379
|
+
),
|
|
380
|
+
];
|
|
381
|
+
}
|
|
382
|
+
return [];
|
|
383
|
+
}
|
|
384
|
+
|
|
341
385
|
function checkUser({ definition, raw }) {
|
|
342
386
|
const issues = [];
|
|
343
387
|
const user = definition.user || {};
|
|
@@ -387,16 +431,8 @@ function checkUser({ definition, raw }) {
|
|
|
387
431
|
)
|
|
388
432
|
);
|
|
389
433
|
}
|
|
390
|
-
if (authModes.adopterJwt === true
|
|
391
|
-
issues.push(
|
|
392
|
-
issue(
|
|
393
|
-
'error',
|
|
394
|
-
'missing-key',
|
|
395
|
-
'/user/jwtConfig/secret',
|
|
396
|
-
'authModes.adopterJwt needs user.jwtConfig.secret to verify tokens.',
|
|
397
|
-
'Set user.jwtConfig: { secret: process.env.JWT_SECRET }.'
|
|
398
|
-
)
|
|
399
|
-
);
|
|
434
|
+
if (authModes.adopterJwt === true) {
|
|
435
|
+
issues.push(...checkJwtSecret(raw.user?.jwtConfig));
|
|
400
436
|
}
|
|
401
437
|
if (
|
|
402
438
|
raw.user?.authModes?.sharedSecret === true &&
|
|
@@ -21,17 +21,15 @@ function formatIssue(issue) {
|
|
|
21
21
|
*/
|
|
22
22
|
function formatReport(report) {
|
|
23
23
|
const { errors, warnings, source, stage } = report;
|
|
24
|
-
const noun =
|
|
25
|
-
report.kind === 'module' ? 'module definition' : 'app definition';
|
|
26
24
|
const lines = [];
|
|
27
|
-
const header = `Validating ${source ||
|
|
25
|
+
const header = `Validating ${source || 'the app definition'}${
|
|
28
26
|
stage ? ` (stage: ${stage})` : ''
|
|
29
27
|
}`;
|
|
30
28
|
lines.push(chalk.bold(header));
|
|
31
29
|
for (const issue of errors) lines.push(formatIssue(issue));
|
|
32
30
|
for (const issue of warnings) lines.push(formatIssue(issue));
|
|
33
31
|
if (errors.length === 0 && warnings.length === 0) {
|
|
34
|
-
lines.push(chalk.green(
|
|
32
|
+
lines.push(chalk.green(' ✓ The app definition is valid.'));
|
|
35
33
|
} else {
|
|
36
34
|
const summary = `${errors.length} error(s), ${warnings.length} warning(s)`;
|
|
37
35
|
lines.push(
|
|
@@ -1,16 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* `frigg validate` and the validation step that `frigg build`, `frigg deploy`,
|
|
3
3
|
* `frigg start` and `frigg init` run first (ADR-051).
|
|
4
|
-
*
|
|
5
|
-
* Module mode (`frigg validate --module` / `frigg validate module`) validates
|
|
6
|
-
* an API module Definition in the current directory; app mode is unchanged.
|
|
7
4
|
*/
|
|
8
5
|
|
|
9
6
|
const chalk = require('chalk');
|
|
10
7
|
const { loadAppDefinition } = require('./load-app-definition');
|
|
11
|
-
const { loadModuleDefinition } = require('./load-module-definition');
|
|
12
8
|
const { validateDefinition } = require('./validate-app-definition');
|
|
13
|
-
const { validateModuleDefinition } = require('./validate-module-definition');
|
|
14
9
|
const { formatReport, toJsonReport } = require('./format-report');
|
|
15
10
|
|
|
16
11
|
/**
|
|
@@ -36,33 +31,10 @@ function runValidation({ cwd = process.cwd(), stage, env = process.env } = {}) {
|
|
|
36
31
|
}
|
|
37
32
|
|
|
38
33
|
/**
|
|
39
|
-
*
|
|
40
|
-
*
|
|
41
|
-
* @param {object} [params]
|
|
42
|
-
* @param {string} [params.cwd]
|
|
43
|
-
* @returns {{ errors: object[], warnings: object[], source: string }}
|
|
34
|
+
* `frigg validate [--json] [--stage <stage>]`. Exits non-zero on errors.
|
|
44
35
|
*/
|
|
45
|
-
function
|
|
46
|
-
const
|
|
47
|
-
if (!loaded.ok) {
|
|
48
|
-
return { errors: [loaded.issue], warnings: [], source: cwd };
|
|
49
|
-
}
|
|
50
|
-
const { errors, warnings } = validateModuleDefinition({
|
|
51
|
-
definition: loaded.definition,
|
|
52
|
-
});
|
|
53
|
-
return { errors, warnings, source: loaded.indexPath, kind: 'module' };
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
function isModuleMode(options = {}) {
|
|
57
|
-
return Boolean(options.module) || options.target === 'module';
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
/**
|
|
61
|
-
* Print a validation report and set exitCode on errors.
|
|
62
|
-
* @param {object} report
|
|
63
|
-
* @param {object} options
|
|
64
|
-
*/
|
|
65
|
-
function printReport(report, options = {}) {
|
|
36
|
+
async function validateCommand(options = {}) {
|
|
37
|
+
const report = runValidation({ stage: options.stage });
|
|
66
38
|
if (options.json) {
|
|
67
39
|
console.log(JSON.stringify(toJsonReport(report), null, 2));
|
|
68
40
|
} else {
|
|
@@ -73,17 +45,6 @@ function printReport(report, options = {}) {
|
|
|
73
45
|
if (report.errors.length > 0) {
|
|
74
46
|
process.exitCode = 1;
|
|
75
47
|
}
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
/**
|
|
79
|
-
* `frigg validate [--module] [module] [--json] [--stage <stage>]`.
|
|
80
|
-
* Exits non-zero on errors. Module mode does not change app-mode behavior.
|
|
81
|
-
*/
|
|
82
|
-
async function validateCommand(options = {}) {
|
|
83
|
-
const report = isModuleMode(options)
|
|
84
|
-
? runModuleValidation({})
|
|
85
|
-
: runValidation({ stage: options.stage });
|
|
86
|
-
printReport(report, options);
|
|
87
48
|
return report;
|
|
88
49
|
}
|
|
89
50
|
|
|
@@ -143,9 +104,4 @@ function preflightValidation({ command, options = {}, failOnErrors }) {
|
|
|
143
104
|
return true;
|
|
144
105
|
}
|
|
145
106
|
|
|
146
|
-
module.exports = {
|
|
147
|
-
validateCommand,
|
|
148
|
-
runValidation,
|
|
149
|
-
runModuleValidation,
|
|
150
|
-
preflightValidation,
|
|
151
|
-
};
|
|
107
|
+
module.exports = { validateCommand, runValidation, preflightValidation };
|
|
@@ -4,7 +4,10 @@ const path = require('path');
|
|
|
4
4
|
/**
|
|
5
5
|
* Find the backend directory the way `frigg build` and core's
|
|
6
6
|
* findNearestBackendPackageJson do: the current directory when it holds
|
|
7
|
-
* package.json and index.js, else the nearest ancestor's `backend
|
|
7
|
+
* package.json and index.js, else the nearest ancestor's `backend/` that
|
|
8
|
+
* holds a package.json. Like core, the search stops at that nearest
|
|
9
|
+
* `backend/` even when it has no index.js (loadAppDefinition reports it), so
|
|
10
|
+
* validation never passes on a farther app that build would not load.
|
|
8
11
|
*
|
|
9
12
|
* @param {string} cwd
|
|
10
13
|
* @returns {string|null}
|
|
@@ -19,10 +22,7 @@ function resolveBackendDir(cwd = process.cwd()) {
|
|
|
19
22
|
let dir = cwd;
|
|
20
23
|
while (dir !== path.parse(dir).root) {
|
|
21
24
|
const candidate = path.join(dir, 'backend');
|
|
22
|
-
if (
|
|
23
|
-
fs.existsSync(path.join(candidate, 'package.json')) &&
|
|
24
|
-
fs.existsSync(path.join(candidate, 'index.js'))
|
|
25
|
-
) {
|
|
25
|
+
if (fs.existsSync(path.join(candidate, 'package.json'))) {
|
|
26
26
|
return candidate;
|
|
27
27
|
}
|
|
28
28
|
dir = path.dirname(dir);
|
|
@@ -56,6 +56,18 @@ function loadAppDefinition({ cwd = process.cwd() } = {}) {
|
|
|
56
56
|
}
|
|
57
57
|
|
|
58
58
|
const indexPath = path.join(backendDir, 'index.js');
|
|
59
|
+
if (!fs.existsSync(indexPath)) {
|
|
60
|
+
return {
|
|
61
|
+
ok: false,
|
|
62
|
+
issue: {
|
|
63
|
+
severity: 'error',
|
|
64
|
+
code: 'index-not-found',
|
|
65
|
+
pointer: '',
|
|
66
|
+
message: `${backendDir} has a package.json but no index.js. Build and deploy use this directory (the nearest backend/), so they would fail too.`,
|
|
67
|
+
hint: 'Add index.js exporting { Definition }, or run the command in the backend directory you meant.',
|
|
68
|
+
},
|
|
69
|
+
};
|
|
70
|
+
}
|
|
59
71
|
let backend;
|
|
60
72
|
try {
|
|
61
73
|
backend = require(indexPath);
|
|
@@ -0,0 +1,281 @@
|
|
|
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
|
+
|
|
41
|
+
// createIntegrationRouter loads the app definition from the consuming
|
|
42
|
+
// backend; give it an empty one so the router can be built in isolation.
|
|
43
|
+
jest.mock('@friggframework/core/handlers/app-definition-loader', () => ({
|
|
44
|
+
loadAppDefinition: () => ({ integrations: [], userConfig: {} }),
|
|
45
|
+
}));
|
|
46
|
+
|
|
47
|
+
const { composeServerlessDefinition } = require('../infrastructure-composer');
|
|
48
|
+
|
|
49
|
+
// Routes the auth Lambda's handler (core/handlers/routers/auth.js) adds on
|
|
50
|
+
// top of createIntegrationRouter().
|
|
51
|
+
const AUTH_HANDLER_EXTRA_ROUTES = [
|
|
52
|
+
{ method: 'GET', path: '/api/integrations/redirect/:appId' },
|
|
53
|
+
];
|
|
54
|
+
|
|
55
|
+
function getIntegrationRouterRoutes() {
|
|
56
|
+
const { createIntegrationRouter } = require('@friggframework/core');
|
|
57
|
+
// The repository factories pick an adapter from DB_TYPE (or the backend's
|
|
58
|
+
// app definition, which doesn't exist here). Nothing connects.
|
|
59
|
+
const previousDbType = process.env.DB_TYPE;
|
|
60
|
+
process.env.DB_TYPE = 'postgresql';
|
|
61
|
+
let app;
|
|
62
|
+
try {
|
|
63
|
+
app = createIntegrationRouter();
|
|
64
|
+
} finally {
|
|
65
|
+
if (previousDbType === undefined) delete process.env.DB_TYPE;
|
|
66
|
+
else process.env.DB_TYPE = previousDbType;
|
|
67
|
+
}
|
|
68
|
+
const stack = (app._router || app.router).stack;
|
|
69
|
+
const routes = [];
|
|
70
|
+
for (const layer of stack) {
|
|
71
|
+
if (!layer.route) continue;
|
|
72
|
+
for (const method of Object.keys(layer.route.methods)) {
|
|
73
|
+
routes.push({
|
|
74
|
+
method: method === '_all' ? 'ANY' : method.toUpperCase(),
|
|
75
|
+
path: layer.route.path,
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return routes;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function getGatewayRoutes(definition) {
|
|
83
|
+
const routes = [];
|
|
84
|
+
for (const [functionName, fn] of Object.entries(definition.functions)) {
|
|
85
|
+
for (const event of fn.events || []) {
|
|
86
|
+
if (!event.httpApi) continue;
|
|
87
|
+
routes.push({
|
|
88
|
+
functionName,
|
|
89
|
+
method: String(event.httpApi.method).toUpperCase(),
|
|
90
|
+
path: event.httpApi.path,
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return routes;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const segmentsOf = (p) => p.split('/').filter(Boolean);
|
|
98
|
+
|
|
99
|
+
// Turn an Express path into a concrete request path, e.g.
|
|
100
|
+
// /api/entities/:entityId/options -> /api/entities/sample-entityId/options
|
|
101
|
+
const toConcretePath = (expressPath) =>
|
|
102
|
+
expressPath.replace(/:([A-Za-z0-9_]+)/g, 'sample-$1');
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* HTTP API path matching: literal segments match exactly, {param} matches
|
|
106
|
+
* one segment, a trailing {proxy+} greedily matches one or more segments.
|
|
107
|
+
* Returns null on no match, otherwise a specificity descriptor.
|
|
108
|
+
*/
|
|
109
|
+
function matchGatewayPath(gatewayPath, requestPath) {
|
|
110
|
+
const g = segmentsOf(gatewayPath);
|
|
111
|
+
const r = segmentsOf(requestPath);
|
|
112
|
+
let literals = 0;
|
|
113
|
+
for (let i = 0; i < g.length; i++) {
|
|
114
|
+
const seg = g[i];
|
|
115
|
+
if (/^\{[^}]+\+\}$/.test(seg)) {
|
|
116
|
+
if (i !== g.length - 1 || r.length <= i) return null;
|
|
117
|
+
return { greedy: true, literals, prefixLength: i };
|
|
118
|
+
}
|
|
119
|
+
if (i >= r.length) return null;
|
|
120
|
+
if (/^\{[^}]+\}$/.test(seg)) continue;
|
|
121
|
+
if (seg !== r[i]) return null;
|
|
122
|
+
literals++;
|
|
123
|
+
}
|
|
124
|
+
if (g.length !== r.length) return null;
|
|
125
|
+
return { greedy: false, literals, prefixLength: g.length };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Select the route API Gateway would invoke: a non-greedy match beats a
|
|
130
|
+
* greedy one, then more literal segments, then the longer greedy prefix,
|
|
131
|
+
* then an explicit method beats ANY.
|
|
132
|
+
*/
|
|
133
|
+
function selectGatewayRoute(gatewayRoutes, method, requestPath) {
|
|
134
|
+
const candidates = gatewayRoutes
|
|
135
|
+
.filter(
|
|
136
|
+
(r) => r.method === 'ANY' || method === 'ANY' || r.method === method
|
|
137
|
+
)
|
|
138
|
+
.map((r) => ({
|
|
139
|
+
route: r,
|
|
140
|
+
match: matchGatewayPath(r.path, requestPath),
|
|
141
|
+
}))
|
|
142
|
+
.filter((c) => c.match);
|
|
143
|
+
candidates.sort(
|
|
144
|
+
(a, b) =>
|
|
145
|
+
Number(a.match.greedy) - Number(b.match.greedy) ||
|
|
146
|
+
b.match.literals - a.match.literals ||
|
|
147
|
+
b.match.prefixLength - a.match.prefixLength ||
|
|
148
|
+
Number(a.route.method === 'ANY') - Number(b.route.method === 'ANY')
|
|
149
|
+
);
|
|
150
|
+
return candidates.length ? candidates[0].route : null;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
describe('Management API routes are reachable through API Gateway', () => {
|
|
154
|
+
let gatewayRoutes;
|
|
155
|
+
let managementRoutes;
|
|
156
|
+
const originalArgv = process.argv;
|
|
157
|
+
|
|
158
|
+
beforeAll(async () => {
|
|
159
|
+
process.argv = ['node', 'test'];
|
|
160
|
+
process.env.AWS_REGION = 'us-east-1';
|
|
161
|
+
// The builders narrate their progress; keep the test output quiet.
|
|
162
|
+
const logSpy = jest.spyOn(console, 'log').mockImplementation(() => {});
|
|
163
|
+
const warnSpy = jest
|
|
164
|
+
.spyOn(console, 'warn')
|
|
165
|
+
.mockImplementation(() => {});
|
|
166
|
+
try {
|
|
167
|
+
const definition = await composeServerlessDefinition({
|
|
168
|
+
name: 'route-coverage-app',
|
|
169
|
+
provider: 'aws',
|
|
170
|
+
usePrismaLambdaLayer: false,
|
|
171
|
+
database: { postgres: { enable: true } },
|
|
172
|
+
websockets: { enable: true },
|
|
173
|
+
adminScripts: [
|
|
174
|
+
class ExampleScript {
|
|
175
|
+
static Definition = { name: 'example-script' };
|
|
176
|
+
},
|
|
177
|
+
],
|
|
178
|
+
admin: { includeBuiltinReports: true },
|
|
179
|
+
integrations: [
|
|
180
|
+
{
|
|
181
|
+
Definition: {
|
|
182
|
+
name: 'acme',
|
|
183
|
+
webhooks: true,
|
|
184
|
+
extensions: {
|
|
185
|
+
inbound: {
|
|
186
|
+
extension: {
|
|
187
|
+
routes: [
|
|
188
|
+
{ path: '/events', method: 'POST' },
|
|
189
|
+
],
|
|
190
|
+
},
|
|
191
|
+
},
|
|
192
|
+
},
|
|
193
|
+
},
|
|
194
|
+
},
|
|
195
|
+
// Integration names share the /api/ namespace with the
|
|
196
|
+
// Management API; make sure they don't shadow it.
|
|
197
|
+
{ Definition: { name: 'entities' } },
|
|
198
|
+
],
|
|
199
|
+
});
|
|
200
|
+
gatewayRoutes = getGatewayRoutes(definition);
|
|
201
|
+
} finally {
|
|
202
|
+
logSpy.mockRestore();
|
|
203
|
+
warnSpy.mockRestore();
|
|
204
|
+
}
|
|
205
|
+
managementRoutes = [
|
|
206
|
+
...getIntegrationRouterRoutes(),
|
|
207
|
+
...AUTH_HANDLER_EXTRA_ROUTES,
|
|
208
|
+
];
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
afterAll(() => {
|
|
212
|
+
process.argv = originalArgv;
|
|
213
|
+
delete process.env.AWS_REGION;
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
it('reads the Management API routes from the core integration router', () => {
|
|
217
|
+
const paths = managementRoutes.map((r) => r.path);
|
|
218
|
+
expect(paths).toEqual(
|
|
219
|
+
expect.arrayContaining([
|
|
220
|
+
'/api/integrations',
|
|
221
|
+
'/api/authorize',
|
|
222
|
+
'/api/entity',
|
|
223
|
+
'/api/entity/options/:credentialId',
|
|
224
|
+
'/api/entities/:entityId',
|
|
225
|
+
])
|
|
226
|
+
);
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
it('routes every Management API route to the auth function', () => {
|
|
230
|
+
const unreachable = managementRoutes
|
|
231
|
+
.map(({ method, path: expressPath }) => {
|
|
232
|
+
const requestPath = toConcretePath(expressPath);
|
|
233
|
+
const selected = selectGatewayRoute(
|
|
234
|
+
gatewayRoutes,
|
|
235
|
+
method,
|
|
236
|
+
requestPath
|
|
237
|
+
);
|
|
238
|
+
return {
|
|
239
|
+
route: `${method} ${expressPath}`,
|
|
240
|
+
reachedBy: selected
|
|
241
|
+
? `${selected.method} ${selected.path} -> ${selected.functionName}`
|
|
242
|
+
: 'no API Gateway route',
|
|
243
|
+
ok: selected && selected.functionName === 'auth',
|
|
244
|
+
};
|
|
245
|
+
})
|
|
246
|
+
.filter((r) => !r.ok)
|
|
247
|
+
.map(({ route, reachedBy }) => `${route} (${reachedBy})`);
|
|
248
|
+
|
|
249
|
+
expect(unreachable).toEqual([]);
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
it.each([
|
|
253
|
+
['GET', '/api/v2/reports', 'reportRouter'],
|
|
254
|
+
['POST', '/api/v2/reports/daily/run', 'reportRouter'],
|
|
255
|
+
['GET', '/admin/scripts/example-script', 'adminScriptRouter'],
|
|
256
|
+
['POST', '/api/acme-integration/webhooks', 'acmeWebhook'],
|
|
257
|
+
['POST', '/api/acme-integration/inbound/events', 'acme__inbound'],
|
|
258
|
+
['GET', '/api/acme-integration/custom', 'acme'],
|
|
259
|
+
['GET', '/api/entities-integration/custom', 'entities'],
|
|
260
|
+
['POST', '/user/login', 'user'],
|
|
261
|
+
['GET', '/health/ready', 'health'],
|
|
262
|
+
])('leaves %s %s on %s', (method, requestPath, functionName) => {
|
|
263
|
+
const selected = selectGatewayRoute(gatewayRoutes, method, requestPath);
|
|
264
|
+
expect(selected && selected.functionName).toBe(functionName);
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
it('declares no method + path pair on more than one function', () => {
|
|
268
|
+
const seen = new Map();
|
|
269
|
+
const duplicates = [];
|
|
270
|
+
for (const r of gatewayRoutes) {
|
|
271
|
+
const key = `${r.method} ${r.path}`;
|
|
272
|
+
if (seen.has(key) && seen.get(key) !== r.functionName) {
|
|
273
|
+
duplicates.push(
|
|
274
|
+
`${key}: ${seen.get(key)} and ${r.functionName}`
|
|
275
|
+
);
|
|
276
|
+
}
|
|
277
|
+
seen.set(key, r.functionName);
|
|
278
|
+
}
|
|
279
|
+
expect(duplicates).toEqual([]);
|
|
280
|
+
});
|
|
281
|
+
});
|