n8n/packages/cli/test/integration/me.api.test.ts
Michael Auerswald b67f803cbe
feat: Add global event bus (#4860)
* fix branch

* fix deserialize, add filewriter

* add catchAll eventGroup/Name

* adding simple Redis sender and receiver to eventbus

* remove native node threads

* improve eventbus

* refactor and simplify

* more refactoring and syslog client

* more refactor, improved endpoints and eventbus

* remove local broker and receivers from mvp

* destination de/serialization

* create MessageEventBusDestinationEntity

* db migrations, load destinations at startup

* add delete destination endpoint

* pnpm merge and circular import fix

* delete destination fix

* trigger log file shuffle after size reached

* add environment variables for eventbus

* reworking event messages

* serialize to thread fix

* some refactor and lint fixing

* add emit to eventbus

* cleanup and fix sending unsent

* quicksave frontend trial

* initial EventTree vue component

* basic log streaming settings in vue

* http request code merge

* create destination settings modals

* fix eventmessage options types

* credentials are loaded

* fix and clean up frontend code

* move request code to axios

* update lock file

* merge fix

* fix redis build

* move destination interfaces into workflow pkg

* revive sentry as destination

* migration fixes and frontend cleanup

* N8N-5777 / N8N-5789 N8N-5788

* N8N-5784

* N8N-5782 removed event levels

* N8N-5790 sentry destination cleanup

* N8N-5786 and refactoring

* N8N-5809 and refactor/cleanup

* UI fixes and anonymize renaming

* N8N-5837

* N8N-5834

* fix no-items UI issues

* remove card / settings label in modal

* N8N-5842 fix

* disable webhook auth for now and update ui

* change sidebar to tabs

* remove payload option

* extend audit events with more user data

* N8N-5853 and UI revert to sidebar

* remove redis destination

* N8N-5864 / N8N-5868 / N8N-5867 / N8N-5865

* ui and licensing fixes

* add node events and info bubbles to frontend

* ui wording changes

* frontend tests

* N8N-5896 and ee rename

* improves backend tests

* merge fix

* fix backend test

* make linter happy

* remove unnecessary cfg / limit  actions to owners

* fix multiple sentry DSN and anon bug

* eslint fix

* more tests and fixes

* merge fix

* fix workflow audit events

* remove 'n8n.workflow.execution.error' event

* merge fix

* lint fix

* lint fix

* review fixes

* fix merge

* prettier fixes

* merge

* review changes

* use loggerproxy

* remove catch from internal hook promises

* fix tests

* lint fix

* include review PR changes

* review changes

* delete duplicate lines from a bad merge

* decouple log-streaming UI options from public API

* logstreaming -> log-streaming for consistency

* do not make unnecessary api calls when log streaming is disabled

* prevent sentryClient.close() from being called if init failed

* fix the e2e test for log-streaming

* review changes

* cleanup

* use `private` for one last private property

* do not use node prefix package names.. just yet

* remove unused import

* fix the tests

because there is a folder called `events`, tsc-alias is messing up all imports for native events module.
https://github.com/justkey007/tsc-alias/issues/152

Co-authored-by: कारतोफ्फेलस्क्रिप्ट™ <aditya@netroy.in>
2023-01-04 09:47:48 +01:00

633 lines
17 KiB
TypeScript

import express from 'express';
import { IsNull } from 'typeorm';
import validator from 'validator';
import config from '@/config';
import * as Db from '@/Db';
import type { Role } from '@db/entities/Role';
import { SUCCESS_RESPONSE_BODY } from './shared/constants';
import {
randomApiKey,
randomEmail,
randomName,
randomString,
randomValidPassword,
} from './shared/random';
import * as testDb from './shared/testDb';
import type { AuthAgent } from './shared/types';
import * as utils from './shared/utils';
let app: express.Application;
let testDbName = '';
let globalOwnerRole: Role;
let globalMemberRole: Role;
let authAgent: AuthAgent;
beforeAll(async () => {
app = await utils.initTestServer({ endpointGroups: ['me'], applyAuth: true });
const initResult = await testDb.init();
testDbName = initResult.testDbName;
globalOwnerRole = await testDb.getGlobalOwnerRole();
globalMemberRole = await testDb.getGlobalMemberRole();
authAgent = utils.createAuthAgent(app);
utils.initTestLogger();
utils.initTestTelemetry();
});
afterAll(async () => {
await testDb.terminate(testDbName);
});
describe('Owner shell', () => {
beforeEach(async () => {
await testDb.truncate(['User'], testDbName);
});
test('GET /me should return sanitized owner shell', async () => {
const ownerShell = await testDb.createUserShell(globalOwnerRole);
const response = await authAgent(ownerShell).get('/me');
expect(response.statusCode).toBe(200);
const {
id,
email,
firstName,
lastName,
personalizationAnswers,
globalRole,
password,
resetPasswordToken,
isPending,
apiKey,
} = response.body.data;
expect(validator.isUUID(id)).toBe(true);
expect(email).toBeNull();
expect(firstName).toBeNull();
expect(lastName).toBeNull();
expect(personalizationAnswers).toBeNull();
expect(password).toBeUndefined();
expect(resetPasswordToken).toBeUndefined();
expect(isPending).toBe(true);
expect(globalRole.name).toBe('owner');
expect(globalRole.scope).toBe('global');
expect(apiKey).toBeUndefined();
});
test('PATCH /me should succeed with valid inputs', async () => {
const ownerShell = await testDb.createUserShell(globalOwnerRole);
const authOwnerShellAgent = authAgent(ownerShell);
for (const validPayload of VALID_PATCH_ME_PAYLOADS) {
const response = await authOwnerShellAgent.patch('/me').send(validPayload);
expect(response.statusCode).toBe(200);
const {
id,
email,
firstName,
lastName,
personalizationAnswers,
globalRole,
password,
resetPasswordToken,
isPending,
apiKey,
} = response.body.data;
expect(validator.isUUID(id)).toBe(true);
expect(email).toBe(validPayload.email.toLowerCase());
expect(firstName).toBe(validPayload.firstName);
expect(lastName).toBe(validPayload.lastName);
expect(personalizationAnswers).toBeNull();
expect(password).toBeUndefined();
expect(resetPasswordToken).toBeUndefined();
expect(isPending).toBe(false);
expect(globalRole.name).toBe('owner');
expect(globalRole.scope).toBe('global');
expect(apiKey).toBeUndefined();
const storedOwnerShell = await Db.collections.User.findOneOrFail(id);
expect(storedOwnerShell.email).toBe(validPayload.email.toLowerCase());
expect(storedOwnerShell.firstName).toBe(validPayload.firstName);
expect(storedOwnerShell.lastName).toBe(validPayload.lastName);
}
});
test('PATCH /me should fail with invalid inputs', async () => {
const ownerShell = await testDb.createUserShell(globalOwnerRole);
const authOwnerShellAgent = authAgent(ownerShell);
for (const invalidPayload of INVALID_PATCH_ME_PAYLOADS) {
const response = await authOwnerShellAgent.patch('/me').send(invalidPayload);
expect(response.statusCode).toBe(400);
const storedOwnerShell = await Db.collections.User.findOneOrFail();
expect(storedOwnerShell.email).toBeNull();
expect(storedOwnerShell.firstName).toBeNull();
expect(storedOwnerShell.lastName).toBeNull();
}
});
test('PATCH /me/password should fail for shell', async () => {
const ownerShell = await testDb.createUserShell(globalOwnerRole);
const authOwnerShellAgent = authAgent(ownerShell);
const validPasswordPayload = {
currentPassword: randomValidPassword(),
newPassword: randomValidPassword(),
};
const validPayloads = [validPasswordPayload, ...INVALID_PASSWORD_PAYLOADS];
await Promise.all(
validPayloads.map(async (payload) => {
const response = await authOwnerShellAgent.patch('/me/password').send(payload);
expect([400, 500].includes(response.statusCode)).toBe(true);
const storedMember = await Db.collections.User.findOneOrFail();
if (payload.newPassword) {
expect(storedMember.password).not.toBe(payload.newPassword);
}
if (payload.currentPassword) {
expect(storedMember.password).not.toBe(payload.currentPassword);
}
}),
);
const storedOwnerShell = await Db.collections.User.findOneOrFail();
expect(storedOwnerShell.password).toBeNull();
});
test('POST /me/survey should succeed with valid inputs', async () => {
const ownerShell = await testDb.createUserShell(globalOwnerRole);
const authOwnerShellAgent = authAgent(ownerShell);
const validPayloads = [SURVEY, {}];
for (const validPayload of validPayloads) {
const response = await authOwnerShellAgent.post('/me/survey').send(validPayload);
expect(response.statusCode).toBe(200);
expect(response.body).toEqual(SUCCESS_RESPONSE_BODY);
const storedShellOwner = await Db.collections.User.findOneOrFail({
where: { email: IsNull() },
});
expect(storedShellOwner.personalizationAnswers).toEqual(validPayload);
}
});
test('POST /me/api-key should create an api key', async () => {
const ownerShell = await testDb.createUserShell(globalOwnerRole);
const response = await authAgent(ownerShell).post('/me/api-key');
expect(response.statusCode).toBe(200);
expect(response.body.data.apiKey).toBeDefined();
expect(response.body.data.apiKey).not.toBeNull();
const storedShellOwner = await Db.collections.User.findOneOrFail({
where: { email: IsNull() },
});
expect(storedShellOwner.apiKey).toEqual(response.body.data.apiKey);
});
test('GET /me/api-key should fetch the api key', async () => {
let ownerShell = await testDb.createUserShell(globalOwnerRole);
ownerShell = await testDb.addApiKey(ownerShell);
const response = await authAgent(ownerShell).get('/me/api-key');
expect(response.statusCode).toBe(200);
expect(response.body.data.apiKey).toEqual(ownerShell.apiKey);
});
test('DELETE /me/api-key should fetch the api key', async () => {
let ownerShell = await testDb.createUserShell(globalOwnerRole);
ownerShell = await testDb.addApiKey(ownerShell);
const response = await authAgent(ownerShell).delete('/me/api-key');
expect(response.statusCode).toBe(200);
const storedShellOwner = await Db.collections.User.findOneOrFail({
where: { email: IsNull() },
});
expect(storedShellOwner.apiKey).toBeNull();
});
});
describe('Member', () => {
beforeEach(async () => {
config.set('userManagement.isInstanceOwnerSetUp', true);
await Db.collections.Settings.update(
{ key: 'userManagement.isInstanceOwnerSetUp' },
{ value: JSON.stringify(true) },
);
});
afterEach(async () => {
await testDb.truncate(['User'], testDbName);
});
test('GET /me should return sanitized member', async () => {
const member = await testDb.createUser({ globalRole: globalMemberRole });
const response = await authAgent(member).get('/me');
expect(response.statusCode).toBe(200);
const {
id,
email,
firstName,
lastName,
personalizationAnswers,
globalRole,
password,
resetPasswordToken,
isPending,
apiKey,
} = response.body.data;
expect(validator.isUUID(id)).toBe(true);
expect(email).toBe(member.email);
expect(firstName).toBe(member.firstName);
expect(lastName).toBe(member.lastName);
expect(personalizationAnswers).toBeNull();
expect(password).toBeUndefined();
expect(resetPasswordToken).toBeUndefined();
expect(isPending).toBe(false);
expect(globalRole.name).toBe('member');
expect(globalRole.scope).toBe('global');
expect(apiKey).toBeUndefined();
});
test('PATCH /me should succeed with valid inputs', async () => {
const member = await testDb.createUser({ globalRole: globalMemberRole });
const authMemberAgent = authAgent(member);
for (const validPayload of VALID_PATCH_ME_PAYLOADS) {
const response = await authMemberAgent.patch('/me').send(validPayload);
expect(response.statusCode).toBe(200);
const {
id,
email,
firstName,
lastName,
personalizationAnswers,
globalRole,
password,
resetPasswordToken,
isPending,
apiKey,
} = response.body.data;
expect(validator.isUUID(id)).toBe(true);
expect(email).toBe(validPayload.email.toLowerCase());
expect(firstName).toBe(validPayload.firstName);
expect(lastName).toBe(validPayload.lastName);
expect(personalizationAnswers).toBeNull();
expect(password).toBeUndefined();
expect(resetPasswordToken).toBeUndefined();
expect(isPending).toBe(false);
expect(globalRole.name).toBe('member');
expect(globalRole.scope).toBe('global');
expect(apiKey).toBeUndefined();
const storedMember = await Db.collections.User.findOneOrFail(id);
expect(storedMember.email).toBe(validPayload.email.toLowerCase());
expect(storedMember.firstName).toBe(validPayload.firstName);
expect(storedMember.lastName).toBe(validPayload.lastName);
}
});
test('PATCH /me should fail with invalid inputs', async () => {
const member = await testDb.createUser({ globalRole: globalMemberRole });
const authMemberAgent = authAgent(member);
for (const invalidPayload of INVALID_PATCH_ME_PAYLOADS) {
const response = await authMemberAgent.patch('/me').send(invalidPayload);
expect(response.statusCode).toBe(400);
const storedMember = await Db.collections.User.findOneOrFail();
expect(storedMember.email).toBe(member.email);
expect(storedMember.firstName).toBe(member.firstName);
expect(storedMember.lastName).toBe(member.lastName);
}
});
test('PATCH /me/password should succeed with valid inputs', async () => {
const memberPassword = randomValidPassword();
const member = await testDb.createUser({
password: memberPassword,
globalRole: globalMemberRole,
});
const validPayload = {
currentPassword: memberPassword,
newPassword: randomValidPassword(),
};
const response = await authAgent(member).patch('/me/password').send(validPayload);
expect(response.statusCode).toBe(200);
expect(response.body).toEqual(SUCCESS_RESPONSE_BODY);
const storedMember = await Db.collections.User.findOneOrFail();
expect(storedMember.password).not.toBe(member.password);
expect(storedMember.password).not.toBe(validPayload.newPassword);
});
test('PATCH /me/password should fail with invalid inputs', async () => {
const member = await testDb.createUser({ globalRole: globalMemberRole });
const authMemberAgent = authAgent(member);
for (const payload of INVALID_PASSWORD_PAYLOADS) {
const response = await authMemberAgent.patch('/me/password').send(payload);
expect([400, 500].includes(response.statusCode)).toBe(true);
const storedMember = await Db.collections.User.findOneOrFail();
if (payload.newPassword) {
expect(storedMember.password).not.toBe(payload.newPassword);
}
if (payload.currentPassword) {
expect(storedMember.password).not.toBe(payload.currentPassword);
}
}
});
test('POST /me/survey should succeed with valid inputs', async () => {
const member = await testDb.createUser({ globalRole: globalMemberRole });
const authMemberAgent = authAgent(member);
const validPayloads = [SURVEY, {}];
for (const validPayload of validPayloads) {
const response = await authMemberAgent.post('/me/survey').send(validPayload);
expect(response.statusCode).toBe(200);
expect(response.body).toEqual(SUCCESS_RESPONSE_BODY);
const { personalizationAnswers: storedAnswers } = await Db.collections.User.findOneOrFail();
expect(storedAnswers).toEqual(validPayload);
}
});
test('POST /me/api-key should create an api key', async () => {
const member = await testDb.createUser({
globalRole: globalMemberRole,
apiKey: randomApiKey(),
});
const response = await authAgent(member).post('/me/api-key');
expect(response.statusCode).toBe(200);
expect(response.body.data.apiKey).toBeDefined();
expect(response.body.data.apiKey).not.toBeNull();
const storedMember = await Db.collections.User.findOneOrFail(member.id);
expect(storedMember.apiKey).toEqual(response.body.data.apiKey);
});
test('GET /me/api-key should fetch the api key', async () => {
const member = await testDb.createUser({
globalRole: globalMemberRole,
apiKey: randomApiKey(),
});
const response = await authAgent(member).get('/me/api-key');
expect(response.statusCode).toBe(200);
expect(response.body.data.apiKey).toEqual(member.apiKey);
});
test('DELETE /me/api-key should fetch the api key', async () => {
const member = await testDb.createUser({
globalRole: globalMemberRole,
apiKey: randomApiKey(),
});
const response = await authAgent(member).delete('/me/api-key');
expect(response.statusCode).toBe(200);
const storedMember = await Db.collections.User.findOneOrFail(member.id);
expect(storedMember.apiKey).toBeNull();
});
});
describe('Owner', () => {
beforeEach(async () => {
config.set('userManagement.isInstanceOwnerSetUp', true);
});
afterEach(async () => {
await testDb.truncate(['User'], testDbName);
});
test('GET /me should return sanitized owner', async () => {
const owner = await testDb.createUser({ globalRole: globalOwnerRole });
const response = await authAgent(owner).get('/me');
expect(response.statusCode).toBe(200);
const {
id,
email,
firstName,
lastName,
personalizationAnswers,
globalRole,
password,
resetPasswordToken,
isPending,
apiKey,
} = response.body.data;
expect(validator.isUUID(id)).toBe(true);
expect(email).toBe(owner.email);
expect(firstName).toBe(owner.firstName);
expect(lastName).toBe(owner.lastName);
expect(personalizationAnswers).toBeNull();
expect(password).toBeUndefined();
expect(resetPasswordToken).toBeUndefined();
expect(isPending).toBe(false);
expect(globalRole.name).toBe('owner');
expect(globalRole.scope).toBe('global');
expect(apiKey).toBeUndefined();
});
test('PATCH /me should succeed with valid inputs', async () => {
const owner = await testDb.createUser({ globalRole: globalOwnerRole });
const authOwnerAgent = authAgent(owner);
for (const validPayload of VALID_PATCH_ME_PAYLOADS) {
const response = await authOwnerAgent.patch('/me').send(validPayload);
expect(response.statusCode).toBe(200);
const {
id,
email,
firstName,
lastName,
personalizationAnswers,
globalRole,
password,
resetPasswordToken,
isPending,
apiKey,
} = response.body.data;
expect(validator.isUUID(id)).toBe(true);
expect(email).toBe(validPayload.email.toLowerCase());
expect(firstName).toBe(validPayload.firstName);
expect(lastName).toBe(validPayload.lastName);
expect(personalizationAnswers).toBeNull();
expect(password).toBeUndefined();
expect(resetPasswordToken).toBeUndefined();
expect(isPending).toBe(false);
expect(globalRole.name).toBe('owner');
expect(globalRole.scope).toBe('global');
expect(apiKey).toBeUndefined();
const storedOwner = await Db.collections.User.findOneOrFail(id);
expect(storedOwner.email).toBe(validPayload.email.toLowerCase());
expect(storedOwner.firstName).toBe(validPayload.firstName);
expect(storedOwner.lastName).toBe(validPayload.lastName);
}
});
});
const SURVEY = [
'codingSkill',
'companyIndustry',
'companySize',
'otherCompanyIndustry',
'otherWorkArea',
'workArea',
].reduce<Record<string, string>>((acc, cur) => {
return (acc[cur] = randomString(2, 10)), acc;
}, {});
const VALID_PATCH_ME_PAYLOADS = [
{
email: randomEmail(),
firstName: randomName(),
lastName: randomName(),
password: randomValidPassword(),
},
{
email: randomEmail().toUpperCase(),
firstName: randomName(),
lastName: randomName(),
password: randomValidPassword(),
},
];
const INVALID_PATCH_ME_PAYLOADS = [
{
email: 'invalid',
firstName: randomName(),
lastName: randomName(),
},
{
email: randomEmail(),
firstName: '',
lastName: randomName(),
},
{
email: randomEmail(),
firstName: randomName(),
lastName: '',
},
{
email: randomEmail(),
firstName: 123,
lastName: randomName(),
},
{
firstName: randomName(),
lastName: randomName(),
},
{
firstName: randomName(),
},
{
lastName: randomName(),
},
{
email: randomEmail(),
firstName: 'John <script',
lastName: randomName(),
},
{
email: randomEmail(),
firstName: 'John <a',
lastName: randomName(),
},
];
const INVALID_PASSWORD_PAYLOADS = [
{
currentPassword: null,
newPassword: randomValidPassword(),
},
{
currentPassword: '',
newPassword: randomValidPassword(),
},
{
currentPassword: {},
newPassword: randomValidPassword(),
},
{
currentPassword: [],
newPassword: randomValidPassword(),
},
{
currentPassword: randomValidPassword(),
},
{
newPassword: randomValidPassword(),
},
{
currentPassword: randomValidPassword(),
newPassword: null,
},
{
currentPassword: randomValidPassword(),
newPassword: '',
},
{
currentPassword: randomValidPassword(),
newPassword: {},
},
{
currentPassword: randomValidPassword(),
newPassword: [],
},
];