n8n/packages/cli/test/integration/shared/utils/testServer.ts

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

274 lines
8.3 KiB
TypeScript
Raw Normal View History

import { Container } from 'typedi';
import cookieParser from 'cookie-parser';
import express from 'express';
import type superagent from 'superagent';
import request from 'supertest';
import { URL } from 'url';
import config from '@/config';
import { AUTH_COOKIE_NAME } from '@/constants';
import type { User } from '@db/entities/User';
import { issueJWT } from '@/auth/jwt';
import { registerController } from '@/decorators';
import { rawBodyReader, bodyParser, setupAuthMiddlewares } from '@/middlewares';
import { PostHogClient } from '@/posthog';
import { Push } from '@/push';
import { License } from '@/License';
import { Logger } from '@/Logger';
import { InternalHooks } from '@/InternalHooks';
import { mockInstance } from '../../../shared/mocking';
import * as testDb from '../../shared/testDb';
import { AUTHLESS_ENDPOINTS, PUBLIC_API_REST_PATH_SEGMENT, REST_PATH_SEGMENT } from '../constants';
import type { SetupProps, TestServer } from '../types';
import { LicenseMocker } from '../license';
/**
* Plugin to prefix a path segment into a request URL pathname.
*
* Example: http://127.0.0.1:62100/me/password → http://127.0.0.1:62100/rest/me/password
*/
function prefix(pathSegment: string) {
return async function (request: superagent.SuperAgentRequest) {
const url = new URL(request.url);
// enforce consistency at call sites
if (url.pathname[0] !== '/') {
throw new Error('Pathname must start with a forward slash');
}
url.pathname = pathSegment + url.pathname;
request.url = url.toString();
return await request;
};
}
function createAgent(app: express.Application, options?: { auth: boolean; user: User }) {
const agent = request.agent(app);
void agent.use(prefix(REST_PATH_SEGMENT));
if (options?.auth && options?.user) {
const { token } = issueJWT(options.user);
agent.jar.setCookie(`${AUTH_COOKIE_NAME}=${token}`);
}
return agent;
}
function publicApiAgent(
app: express.Application,
{ user, version = 1 }: { user: User; version?: number },
) {
const agent = request.agent(app);
void agent.use(prefix(`${PUBLIC_API_REST_PATH_SEGMENT}/v${version}`));
if (user.apiKey) {
void agent.set({ 'X-N8N-API-KEY': user.apiKey });
}
return agent;
}
export const setupTestServer = ({
endpointGroups,
applyAuth = true,
enabledFeatures,
quotas,
}: SetupProps): TestServer => {
const app = express();
app.use(rawBodyReader);
app.use(cookieParser());
// Mock all telemetry and logging
mockInstance(Logger);
mockInstance(InternalHooks);
mockInstance(PostHogClient);
mockInstance(Push);
refactor(core): Implement soft-deletions for executions (#7092) Based on #7065 | Story: https://linear.app/n8n/issue/PAY-771 n8n on filesystem mode marks binary data to delete on manual execution deletion, on unsaved execution completion, and on every execution pruning cycle. We later prune binary data in a separate cycle via these marker files, based on the configured TTL. In the context of introducing an S3 client to manage binary data, the filesystem mode's mark-and-prune setup is too tightly coupled to the general binary data management client interface. This PR... - Ensures the deletion of an execution causes the deletion of any binary data associated to it. This does away with the need for binary data TTL and simplifies the filesystem mode's mark-and-prune setup. - Refactors all execution deletions (including pruning) to cause soft deletions, hard-deletes soft-deleted executions based on the existing pruning config, and adjusts execution endpoints to filter out soft-deleted executions. This reduces DB load, and keeps binary data around long enough for users to access it when building workflows with unsaved executions. - Moves all execution pruning work from an execution lifecycle hook to `execution.repository.ts`. This keeps related logic in a single place. - Removes all marking logic from the binary data manager. This simplifies the interface that the S3 client will meet. - Adds basic sanity-check tests to pruning logic and execution deletion. Out of scope: - Improving existing pruning logic. - Improving existing execution repository logic. - Adjusting dir structure for filesystem mode. --------- Co-authored-by: कारतोफ्फेलस्क्रिप्ट™ <aditya@netroy.in>
2023-09-20 06:21:42 -07:00
const testServer: TestServer = {
app,
httpServer: app.listen(0),
authAgentFor: (user: User) => createAgent(app, { auth: true, user }),
authlessAgent: createAgent(app),
publicApiAgentFor: (user) => publicApiAgent(app, { user }),
license: new LicenseMocker(),
};
beforeAll(async () => {
await testDb.init();
config.set('userManagement.jwtSecret', 'My JWT secret');
config.set('userManagement.isInstanceOwnerSetUp', true);
testServer.license.mock(Container.get(License));
if (enabledFeatures) {
testServer.license.setDefaults({
features: enabledFeatures,
quotas,
});
}
const enablePublicAPI = endpointGroups?.includes('publicApi');
if (applyAuth && !enablePublicAPI) {
setupAuthMiddlewares(app, AUTHLESS_ENDPOINTS, REST_PATH_SEGMENT);
}
if (!endpointGroups) return;
app.use(bodyParser);
if (enablePublicAPI) {
const { loadPublicApiVersions } = await import('@/PublicApi');
const { apiRouters } = await loadPublicApiVersions(PUBLIC_API_REST_PATH_SEGMENT);
app.use(...apiRouters);
}
if (endpointGroups.length) {
for (const group of endpointGroups) {
switch (group) {
case 'credentials':
const { credentialsController } = await import('@/credentials/credentials.controller');
app.use(`/${REST_PATH_SEGMENT}/credentials`, credentialsController);
break;
case 'workflows':
const { WorkflowsController } = await import('@/workflows/workflows.controller');
registerController(app, WorkflowsController);
break;
case 'executions':
const { ExecutionsController } = await import('@/executions/executions.controller');
registerController(app, ExecutionsController);
break;
case 'variables':
const { VariablesController } = await import(
'@/environments/variables/variables.controller.ee'
);
registerController(app, VariablesController);
break;
case 'license':
const { LicenseController } = await import('@/license/license.controller');
registerController(app, LicenseController);
break;
case 'metrics':
const { MetricsService } = await import('@/services/metrics.service');
await Container.get(MetricsService).configureMetrics(app);
break;
case 'eventBus':
const { EventBusController } = await import('@/eventbus/eventBus.controller');
const { EventBusControllerEE } = await import('@/eventbus/eventBus.controller.ee');
registerController(app, EventBusController);
registerController(app, EventBusControllerEE);
break;
case 'auth':
const { AuthController } = await import('@/controllers/auth.controller');
registerController(app, AuthController);
break;
case 'mfa':
const { MFAController } = await import('@/controllers/mfa.controller');
registerController(app, MFAController);
break;
case 'ldap':
const { LdapService } = await import('@/Ldap/ldap.service');
const { LdapController } = await import('@/Ldap/ldap.controller');
testServer.license.enable('feat:ldap');
await Container.get(LdapService).init();
registerController(app, LdapController);
break;
case 'saml':
const { setSamlLoginEnabled } = await import('@/sso/saml/samlHelpers');
const { SamlController } = await import('@/sso/saml/routes/saml.controller.ee');
await setSamlLoginEnabled(true);
registerController(app, SamlController);
break;
case 'sourceControl':
const { SourceControlController } = await import(
'@/environments/sourceControl/sourceControl.controller.ee'
);
registerController(app, SourceControlController);
break;
case 'community-packages':
const { CommunityPackagesController } = await import(
'@/controllers/communityPackages.controller'
);
registerController(app, CommunityPackagesController);
break;
case 'me':
const { MeController } = await import('@/controllers/me.controller');
registerController(app, MeController);
break;
case 'passwordReset':
const { PasswordResetController } = await import(
'@/controllers/passwordReset.controller'
);
registerController(app, PasswordResetController);
break;
case 'owner':
const { OwnerController } = await import('@/controllers/owner.controller');
registerController(app, OwnerController);
break;
case 'users':
const { UsersController } = await import('@/controllers/users.controller');
registerController(app, UsersController);
break;
case 'invitations':
const { InvitationController } = await import('@/controllers/invitation.controller');
registerController(app, InvitationController);
break;
case 'tags':
const { TagsController } = await import('@/controllers/tags.controller');
registerController(app, TagsController);
break;
case 'externalSecrets':
const { ExternalSecretsController } = await import(
'@/ExternalSecrets/ExternalSecrets.controller.ee'
);
registerController(app, ExternalSecretsController);
break;
case 'workflowHistory':
const { WorkflowHistoryController } = await import(
'@/workflows/workflowHistory/workflowHistory.controller.ee'
);
registerController(app, WorkflowHistoryController);
break;
case 'binaryData':
const { BinaryDataController } = await import('@/controllers/binaryData.controller');
registerController(app, BinaryDataController);
break;
feat(core): Add multi-main setup debug endpoint (no-changelog) (#7991) ## Summary Provide details about your pull request and what it adds, fixes, or changes. Photos and videos are recommended. Adi's idea here to help diagnose: https://n8nio.slack.com/archives/C069KJBJ8HE/p1702300349277609?thread_ts=1702299930.728029&cid=C069KJBJ8HE ... #### How to test the change: 1. ... ## Issues fixed Include links to Github issue or Community forum post or **Linear ticket**: > Important in order to close automatically and provide context to reviewers ... ## Review / Merge checklist - [ ] PR title and summary are descriptive. **Remember, the title automatically goes into the changelog. Use `(no-changelog)` otherwise.** ([conventions](https://github.com/n8n-io/n8n/blob/master/.github/pull_request_title_conventions.md)) - [ ] [Docs updated](https://github.com/n8n-io/n8n-docs) or follow-up ticket created. - [ ] Tests included. > A bug is not considered fixed, unless a test is added to prevent it from happening again. A feature is not complete without tests. > > *(internal)* You can use Slack commands to trigger [e2e tests](https://www.notion.so/n8n/How-to-use-Test-Instances-d65f49dfc51f441ea44367fb6f67eb0a?pvs=4#a39f9e5ba64a48b58a71d81c837e8227) or [deploy test instance](https://www.notion.so/n8n/How-to-use-Test-Instances-d65f49dfc51f441ea44367fb6f67eb0a?pvs=4#f6a177d32bde4b57ae2da0b8e454bfce) or [deploy early access version on Cloud](https://www.notion.so/n8n/Cloudbot-3dbe779836004972b7057bc989526998?pvs=4#fef2d36ab02247e1a0f65a74f6fb534e).
2023-12-12 06:18:32 -08:00
case 'debug':
const { DebugController } = await import('@/controllers/debug.controller');
registerController(app, DebugController);
feat(core): Add multi-main setup debug endpoint (no-changelog) (#7991) ## Summary Provide details about your pull request and what it adds, fixes, or changes. Photos and videos are recommended. Adi's idea here to help diagnose: https://n8nio.slack.com/archives/C069KJBJ8HE/p1702300349277609?thread_ts=1702299930.728029&cid=C069KJBJ8HE ... #### How to test the change: 1. ... ## Issues fixed Include links to Github issue or Community forum post or **Linear ticket**: > Important in order to close automatically and provide context to reviewers ... ## Review / Merge checklist - [ ] PR title and summary are descriptive. **Remember, the title automatically goes into the changelog. Use `(no-changelog)` otherwise.** ([conventions](https://github.com/n8n-io/n8n/blob/master/.github/pull_request_title_conventions.md)) - [ ] [Docs updated](https://github.com/n8n-io/n8n-docs) or follow-up ticket created. - [ ] Tests included. > A bug is not considered fixed, unless a test is added to prevent it from happening again. A feature is not complete without tests. > > *(internal)* You can use Slack commands to trigger [e2e tests](https://www.notion.so/n8n/How-to-use-Test-Instances-d65f49dfc51f441ea44367fb6f67eb0a?pvs=4#a39f9e5ba64a48b58a71d81c837e8227) or [deploy test instance](https://www.notion.so/n8n/How-to-use-Test-Instances-d65f49dfc51f441ea44367fb6f67eb0a?pvs=4#f6a177d32bde4b57ae2da0b8e454bfce) or [deploy early access version on Cloud](https://www.notion.so/n8n/Cloudbot-3dbe779836004972b7057bc989526998?pvs=4#fef2d36ab02247e1a0f65a74f6fb534e).
2023-12-12 06:18:32 -08:00
break;
}
}
}
});
afterAll(async () => {
await testDb.terminate();
testServer.httpServer.close();
});
beforeEach(() => {
testServer.license.reset();
});
return testServer;
};