@friggframework/devtools 2.0.0--canary.658.e11f3b0.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.
- package/frigg-cli/README.md +115 -31
- package/frigg-cli/__tests__/unit/commands/build.test.js +3 -0
- package/frigg-cli/__tests__/unit/commands/deploy.test.js +33 -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/commands/validate-wiring.test.js +92 -0
- package/frigg-cli/__tests__/unit/dependencies.test.js +6 -2
- package/frigg-cli/build-command/index.js +6 -0
- package/frigg-cli/deploy-command/index.js +6 -0
- package/frigg-cli/generate-command/index.js +1 -0
- package/frigg-cli/generate-iam-command.js +1 -0
- package/frigg-cli/index.js +22 -5
- package/frigg-cli/init-command/backend-first-handler.js +395 -551
- 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/start-command/index.js +4 -0
- package/frigg-cli/start-command/start-command.test.js +3 -0
- 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__/init-validation.test.js +63 -0
- package/frigg-cli/validate-command/__tests__/integrations-checks.test.js +133 -0
- package/frigg-cli/validate-command/__tests__/validate-app-definition.test.js +443 -0
- package/frigg-cli/validate-command/__tests__/validate-command.test.js +262 -0
- package/frigg-cli/validate-command/checks/config.js +504 -0
- package/frigg-cli/validate-command/checks/integrations.js +274 -0
- package/frigg-cli/validate-command/format-report.js +58 -0
- package/frigg-cli/validate-command/index.js +107 -0
- package/frigg-cli/validate-command/load-app-definition.js +105 -0
- package/frigg-cli/validate-command/schema-issues.js +154 -0
- package/frigg-cli/validate-command/validate-app-definition.js +60 -0
- package/infrastructure/README.md +32 -5
- package/infrastructure/__tests__/helpers/bundled-prisma-engine-excludes.js +39 -0
- package/infrastructure/__tests__/management-api-gateway-routes.test.js +284 -0
- package/infrastructure/__tests__/postgres-config.test.js +245 -836
- package/infrastructure/__tests__/scaffold-default-infrastructure.test.js +151 -0
- package/infrastructure/__tests__/scoped-environment.test.js +3 -0
- package/infrastructure/__tests__/ssm-preload-node-options.test.js +3 -0
- package/infrastructure/__tests__/template-generation.test.js +39 -8
- package/infrastructure/app-definition-schema-contract.test.js +634 -0
- package/infrastructure/create-frigg-infrastructure.js +4 -1
- package/infrastructure/create-frigg-infrastructure.test.js +51 -0
- package/infrastructure/docs/POSTGRES-CONFIGURATION.md +80 -98
- package/infrastructure/domains/admin-scripts/admin-script-builder.js +8 -2
- package/infrastructure/domains/admin-scripts/admin-script-builder.test.js +52 -6
- package/infrastructure/domains/database/aurora-builder.js +13 -2
- package/infrastructure/domains/database/aurora-builder.test.js +22 -0
- package/infrastructure/domains/database/migration-builder.js +21 -2
- package/infrastructure/domains/database/migration-builder.test.js +61 -6
- package/infrastructure/domains/database/migration-engines.js +93 -0
- package/infrastructure/domains/database/migration-engines.test.js +142 -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/integration/integration-builder.js +2 -0
- package/infrastructure/domains/integration/integration-builder.test.js +22 -6
- 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/environment-builder.js +31 -5
- package/infrastructure/domains/shared/environment-builder.test.js +93 -7
- package/infrastructure/domains/shared/lambda-architectures.js +113 -0
- package/infrastructure/domains/shared/lambda-architectures.test.js +164 -0
- package/infrastructure/domains/shared/utilities/base-definition-factory.js +39 -3
- package/infrastructure/domains/shared/utilities/base-definition-factory.test.js +85 -5
- package/infrastructure/domains/shared/utilities/nested-node-modules.js +6 -5
- package/infrastructure/domains/shared/utilities/nested-node-modules.test.js +20 -26
- package/infrastructure/domains/shared/utilities/prisma-layer-manager.js +92 -12
- package/infrastructure/domains/shared/utilities/prisma-layer-manager.test.js +158 -6
- package/infrastructure/infrastructure-composer.js +12 -1
- package/infrastructure/infrastructure-composer.test.js +339 -794
- package/infrastructure/scripts/build-prisma-layer.js +136 -50
- package/infrastructure/scripts/build-prisma-layer.test.js +128 -7
- package/infrastructure/scripts/build-time-discovery.test.js +18 -3
- package/package.json +12 -10
- package/frigg-cli/index.test.js +0 -158
- package/infrastructure/integration.test.js +0 -381
|
@@ -0,0 +1,60 @@
|
|
|
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 };
|
package/infrastructure/README.md
CHANGED
|
@@ -285,23 +285,50 @@ const appDefinition = {
|
|
|
285
285
|
|
|
286
286
|
> ℹ️ When `usePrismaLambdaLayer: false`, Prisma stays inside each bundle and the runtime automatically loads the correct binary. No extra configuration is required.
|
|
287
287
|
|
|
288
|
-
**
|
|
288
|
+
**Nested node_modules in Lambda packages:**
|
|
289
289
|
|
|
290
|
-
|
|
290
|
+
npm nests a package under its dependant only when the root copy cannot satisfy the dependant's range. Function packages ship the dependency tree the way npm resolved it. Nested copies of `@friggframework/*`, `aws-sdk`, `@aws-sdk/*` and, when the Prisma layer is enabled, `@prisma/*` and `.prisma` are excluded: the app's single core, the Lambda runtime and the layer provide them.
|
|
291
291
|
|
|
292
|
-
|
|
292
|
+
An app can exclude every nested `node_modules` to make packages smaller:
|
|
293
293
|
|
|
294
294
|
```javascript
|
|
295
295
|
const appDefinition = {
|
|
296
296
|
name: 'my-app',
|
|
297
297
|
lambda: {
|
|
298
|
-
keepNestedNodeModules:
|
|
298
|
+
keepNestedNodeModules: false,
|
|
299
299
|
},
|
|
300
300
|
integrations: [{ Definition: { name: 'salesforce' } }],
|
|
301
301
|
};
|
|
302
302
|
```
|
|
303
303
|
|
|
304
|
-
|
|
304
|
+
With the opt-out, each nested package resolves whatever version is hoisted to the root, and a package whose root copy is a dev dependency is not shipped at all. The first `require` of such a package fails at Lambda init with `Runtime.ImportModuleError`.
|
|
305
|
+
|
|
306
|
+
**Lambda architecture (arm64 / Graviton):**
|
|
307
|
+
|
|
308
|
+
Every function, the Prisma layer and the migration worker deploy as x86_64 unless the app definition sets `architecture`:
|
|
309
|
+
|
|
310
|
+
```javascript
|
|
311
|
+
const appDefinition = {
|
|
312
|
+
name: 'my-app',
|
|
313
|
+
architecture: 'arm64', // or 'x86_64'; unset keeps today's template
|
|
314
|
+
integrations: [{ Definition: { name: 'hubspot' } }],
|
|
315
|
+
};
|
|
316
|
+
```
|
|
317
|
+
|
|
318
|
+
An explicit value sets `provider.architecture` and the layer's `compatibleArchitectures`, builds the layer with that architecture's Prisma query engine, ships the migration worker with its schema engine and query engine library, and pins the migrate CLI to them through `PRISMA_SCHEMA_ENGINE_BINARY` and `PRISMA_QUERY_ENGINE_LIBRARY`. With `usePrismaLambdaLayer: false`, each function bundles only that engine. An unset key adds no field to the template.
|
|
319
|
+
|
|
320
|
+
Before you flip an app to `arm64`:
|
|
321
|
+
|
|
322
|
+
- It needs a `@friggframework/core` release whose generated Prisma clients include the `linux-arm64-openssl-3.0.x` engine (both schemas list it in `binaryTargets`). With an older core the layer build fails naming the core version.
|
|
323
|
+
- The deploy host must reach Prisma's engine CDN (`binaries.prisma.sh`) at package time: the migration worker's engines for the target are fetched there, and packaging fails if either is missing.
|
|
324
|
+
- This runs on every compose where the migration worker is enabled, and downloads only when the target's engines are missing from the app's `node_modules/@prisma/engines`.
|
|
325
|
+
- Air-gapped or offline deploy hosts set `PRISMA_ENGINES_MIRROR` to an internal mirror of the CDN. Prisma's download honours it (`@prisma/fetch-engine` 6.19.3, `dist/chunk-LONQL55G.js`, where the download URL is built from `PRISMA_BINARIES_MIRROR || PRISMA_ENGINES_MIRROR || "https://binaries.prisma.sh"`).
|
|
326
|
+
- The app must have `prisma` installed in its own `node_modules`, not only in a hoisted parent: the worker ships its engines from there, and packaging fails otherwise. The worker runs the app's own `prisma` CLI and pins `PRISMA_SCHEMA_ENGINE_BINARY` and `PRISMA_QUERY_ENGINE_LIBRARY` to that `@prisma/engines`, so the CLI and its engines always agree. That `prisma` must still be able to run the schema and migrations of `@friggframework/core`.
|
|
327
|
+
- Published core carries one more query engine per generated client (about 15 MB unpacked each).
|
|
328
|
+
- Native addons of the app itself (`sharp`, `bcrypt`, and the like) are built for the deploy host's architecture by `npm ci`, not for the target. Build them for arm64 or replace them.
|
|
329
|
+
- During the stack update, functions run mixed for a short time, so flip in a low-traffic window.
|
|
330
|
+
- The cached layer under `layers/prisma` rebuilds on the flip: its marker records the Prisma binary target, the client set and the core and `@prisma/client` versions, and a mismatch rebuilds.
|
|
331
|
+
- The first compose after upgrading to a Frigg release with this support rebuilds the Prisma layer once, because cache markers written by older releases never match.
|
|
305
332
|
|
|
306
333
|
## Usage Examples
|
|
307
334
|
|
|
@@ -0,0 +1,39 @@
|
|
|
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 };
|
|
@@ -0,0 +1,284 @@
|
|
|
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
|
+
});
|