n8n/packages/cli/test/integration/owner.api.test.ts
Iván Ovejero 1e2d6daaa3
🚨 Optimize UM tests (#3066)
*  Declutter test logs

* 🐛 Fix random passwords length

* 🐛 Fix password hashing in test user creation

* 🐛 Hash leftover password

*  Improve error message for `compare`

*  Restore `randomInvalidPassword` contant

*  Mock Telemetry module to prevent `--forceExit`

* 🔥 Remove unused imports

* 🔥 Remove unused import

*  Add util for configuring test SMTP

*  Isolate user creation

* 🔥 De-duplicate `createFullUser`

*  Centralize hashing

* 🔥 Remove superfluous arg

* 🔥 Remove outdated comment

*  Prioritize shared tables during trucation

* 🧪 Add login tests

*  Use token helper

* ✏️ Improve naming

*  Make `createMemberShell` consistent

* 🔥 Remove unneeded helper

* 🔥 De-duplicate `beforeEach`

* ✏️ Improve naming

* 🚚 Move `categorize` to utils

* ✏️ Update comment

* 🧪 Simplify test

* 📘 Improve `User.password` type

*  Silence logger

*  Simplify condition

*  Unhash password in payload

* 🐛 Fix comparison against unhashed password

*  Increase timeout for fake SMTP service

* 🔥 Remove unneeded import

*  Use `isNull()`

* 🧪 Use `Promise.all()` in creds tests

* 🧪 Use `Promise.all()` in me tests

* 🧪 Use `Promise.all()` in owner tests

* 🧪 Use `Promise.all()` in password tests

* 🧪 Use `Promise.all()` in users tests

*  Re-set cookie if UM disabled

* 🔥 Remove repeated line

*  Refactor out shared owner data

* 🔥 Remove unneeded import

* 🔥 Remove repeated lines

*  Organize imports

*  Reuse helper

* 🚚 Rename tests to match routers

* 🚚 Rename `createFullUser()` to `createUser()`

*  Consolidate user shell creation

*  Make hashing async

*  Add email to user shell

*  Optimize array building

* 🛠 refactor user shell factory

* 🐛 Fix MySQL tests

*  Silence logger in other DBs

Co-authored-by: Ben Hesseldieck <b.hesseldieck@gmail.com>
2022-04-08 18:37:07 +02:00

166 lines
4.3 KiB
TypeScript

import express = require('express');
import validator from 'validator';
import * as utils from './shared/utils';
import * as testDb from './shared/testDb';
import { Db } from '../../src';
import config = require('../../config');
import {
randomEmail,
randomName,
randomValidPassword,
randomInvalidPassword,
} from './shared/random';
import type { Role } from '../../src/databases/entities/Role';
jest.mock('../../src/telemetry');
let app: express.Application;
let testDbName = '';
let globalOwnerRole: Role;
beforeAll(async () => {
app = utils.initTestServer({ endpointGroups: ['owner'], applyAuth: true });
const initResult = await testDb.init();
testDbName = initResult.testDbName;
globalOwnerRole = await testDb.getGlobalOwnerRole();
utils.initTestLogger();
utils.initTestTelemetry();
});
beforeEach(async () => {
await testDb.truncate(['User'], testDbName);
});
afterAll(async () => {
await testDb.terminate(testDbName);
});
test('POST /owner should create owner and enable isInstanceOwnerSetUp', async () => {
const ownerShell = await testDb.createUserShell(globalOwnerRole);
const authOwnerAgent = utils.createAgent(app, { auth: true, user: ownerShell });
const newOwnerData = {
email: randomEmail(),
firstName: randomName(),
lastName: randomName(),
password: randomValidPassword(),
};
const response = await authOwnerAgent.post('/owner').send(newOwnerData);
expect(response.statusCode).toBe(200);
const {
id,
email,
firstName,
lastName,
personalizationAnswers,
globalRole,
password,
resetPasswordToken,
isPending,
} = response.body.data;
expect(validator.isUUID(id)).toBe(true);
expect(email).toBe(newOwnerData.email);
expect(firstName).toBe(newOwnerData.firstName);
expect(lastName).toBe(newOwnerData.lastName);
expect(personalizationAnswers).toBeNull();
expect(password).toBeUndefined();
expect(isPending).toBe(false);
expect(resetPasswordToken).toBeUndefined();
expect(globalRole.name).toBe('owner');
expect(globalRole.scope).toBe('global');
const storedOwner = await Db.collections.User!.findOneOrFail(id);
expect(storedOwner.password).not.toBe(newOwnerData.password);
expect(storedOwner.email).toBe(newOwnerData.email);
expect(storedOwner.firstName).toBe(newOwnerData.firstName);
expect(storedOwner.lastName).toBe(newOwnerData.lastName);
const isInstanceOwnerSetUpConfig = config.get('userManagement.isInstanceOwnerSetUp');
expect(isInstanceOwnerSetUpConfig).toBe(true);
const isInstanceOwnerSetUpSetting = await utils.isInstanceOwnerSetUp();
expect(isInstanceOwnerSetUpSetting).toBe(true);
});
test('POST /owner should fail with invalid inputs', async () => {
const ownerShell = await testDb.createUserShell(globalOwnerRole);
const authOwnerAgent = utils.createAgent(app, { auth: true, user: ownerShell });
await Promise.all(
INVALID_POST_OWNER_PAYLOADS.map(async (invalidPayload) => {
const response = await authOwnerAgent.post('/owner').send(invalidPayload);
expect(response.statusCode).toBe(400);
}),
);
});
test('POST /owner/skip-setup should persist skipping setup to the DB', async () => {
const ownerShell = await testDb.createUserShell(globalOwnerRole);
const authOwnerAgent = utils.createAgent(app, { auth: true, user: ownerShell });
const response = await authOwnerAgent.post('/owner/skip-setup').send();
expect(response.statusCode).toBe(200);
const skipConfig = config.get('userManagement.skipInstanceOwnerSetup');
expect(skipConfig).toBe(true);
const { value } = await Db.collections.Settings!.findOneOrFail({
key: 'userManagement.skipInstanceOwnerSetup',
});
expect(value).toBe('true');
});
const INVALID_POST_OWNER_PAYLOADS = [
{
email: '',
firstName: randomName(),
lastName: randomName(),
password: randomValidPassword(),
},
{
email: randomEmail(),
firstName: '',
lastName: randomName(),
password: randomValidPassword(),
},
{
email: randomEmail(),
firstName: randomName(),
lastName: '',
password: randomValidPassword(),
},
{
email: randomEmail(),
firstName: randomName(),
lastName: randomName(),
password: randomInvalidPassword(),
},
{
firstName: randomName(),
lastName: randomName(),
},
{
firstName: randomName(),
},
{
lastName: randomName(),
},
{
email: randomEmail(),
firstName: 'John <script',
lastName: randomName(),
},
{
email: randomEmail(),
firstName: 'John <a',
lastName: randomName(),
},
];