n8n/packages/cli/test/integration/passwordReset.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

286 lines
8.3 KiB
TypeScript

import express = require('express');
import { v4 as uuid } from 'uuid';
import * as utils from './shared/utils';
import { Db } from '../../src';
import config = require('../../config');
import { compare } from 'bcryptjs';
import {
randomEmail,
randomInvalidPassword,
randomName,
randomValidPassword,
} from './shared/random';
import * as testDb from './shared/testDb';
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: ['passwordReset'], applyAuth: true });
const initResult = await testDb.init();
testDbName = initResult.testDbName;
globalOwnerRole = await testDb.getGlobalOwnerRole();
utils.initTestTelemetry();
utils.initTestLogger();
});
beforeEach(async () => {
await testDb.truncate(['User'], testDbName);
jest.mock('../../config');
config.set('userManagement.isInstanceOwnerSetUp', true);
config.set('userManagement.emails.mode', '');
jest.setTimeout(30000); // fake SMTP service might be slow
});
afterAll(async () => {
await testDb.terminate(testDbName);
});
test('POST /forgot-password should send password reset email', async () => {
const owner = await testDb.createUser({ globalRole: globalOwnerRole });
const authlessAgent = utils.createAgent(app);
await utils.configureSmtp();
const response = await authlessAgent.post('/forgot-password').send({ email: owner.email });
expect(response.statusCode).toBe(200);
expect(response.body).toEqual({});
const storedOwner = await Db.collections.User!.findOneOrFail({ email: owner.email });
expect(storedOwner.resetPasswordToken).toBeDefined();
expect(storedOwner.resetPasswordTokenExpiration).toBeGreaterThan(Math.ceil(Date.now() / 1000));
});
test('POST /forgot-password should fail if emailing is not set up', async () => {
const owner = await testDb.createUser({ globalRole: globalOwnerRole });
const authlessAgent = utils.createAgent(app);
const response = await authlessAgent.post('/forgot-password').send({ email: owner.email });
expect(response.statusCode).toBe(500);
const storedOwner = await Db.collections.User!.findOneOrFail({ email: owner.email });
expect(storedOwner.resetPasswordToken).toBeNull();
});
test('POST /forgot-password should fail with invalid inputs', async () => {
const owner = await testDb.createUser({ globalRole: globalOwnerRole });
const authlessAgent = utils.createAgent(app);
config.set('userManagement.emails.mode', 'smtp');
const invalidPayloads = [
randomEmail(),
[randomEmail()],
{},
[{ name: randomName() }],
[{ email: randomName() }],
];
await Promise.all(
invalidPayloads.map(async (invalidPayload) => {
const response = await authlessAgent.post('/forgot-password').send(invalidPayload);
expect(response.statusCode).toBe(400);
const storedOwner = await Db.collections.User!.findOneOrFail({ email: owner.email });
expect(storedOwner.resetPasswordToken).toBeNull();
}),
);
});
test('POST /forgot-password should fail if user is not found', async () => {
const authlessAgent = utils.createAgent(app);
config.set('userManagement.emails.mode', 'smtp');
const response = await authlessAgent.post('/forgot-password').send({ email: randomEmail() });
expect(response.statusCode).toBe(200); // expect 200 to remain vague
});
test('GET /resolve-password-token should succeed with valid inputs', async () => {
const owner = await testDb.createUser({ globalRole: globalOwnerRole });
const authlessAgent = utils.createAgent(app);
const resetPasswordToken = uuid();
const resetPasswordTokenExpiration = Math.floor(Date.now() / 1000) + 100;
await Db.collections.User!.update(owner.id, {
resetPasswordToken,
resetPasswordTokenExpiration,
});
const response = await authlessAgent
.get('/resolve-password-token')
.query({ userId: owner.id, token: resetPasswordToken });
expect(response.statusCode).toBe(200);
});
test('GET /resolve-password-token should fail with invalid inputs', async () => {
const owner = await testDb.createUser({ globalRole: globalOwnerRole });
const authlessAgent = utils.createAgent(app);
config.set('userManagement.emails.mode', 'smtp');
const first = await authlessAgent.get('/resolve-password-token').query({ token: uuid() });
const second = await authlessAgent.get('/resolve-password-token').query({ userId: owner.id });
for (const response of [first, second]) {
expect(response.statusCode).toBe(400);
}
});
test('GET /resolve-password-token should fail if user is not found', async () => {
const owner = await testDb.createUser({ globalRole: globalOwnerRole });
const authlessAgent = utils.createAgent(app);
config.set('userManagement.emails.mode', 'smtp');
const response = await authlessAgent
.get('/resolve-password-token')
.query({ userId: owner.id, token: uuid() });
expect(response.statusCode).toBe(404);
});
test('GET /resolve-password-token should fail if token is expired', async () => {
const owner = await testDb.createUser({ globalRole: globalOwnerRole });
const authlessAgent = utils.createAgent(app);
const resetPasswordToken = uuid();
const resetPasswordTokenExpiration = Math.floor(Date.now() / 1000) - 1;
await Db.collections.User!.update(owner.id, {
resetPasswordToken,
resetPasswordTokenExpiration,
});
config.set('userManagement.emails.mode', 'smtp');
const response = await authlessAgent
.get('/resolve-password-token')
.query({ userId: owner.id, token: resetPasswordToken });
expect(response.statusCode).toBe(404);
});
test('POST /change-password should succeed with valid inputs', async () => {
const owner = await testDb.createUser({ globalRole: globalOwnerRole });
const authlessAgent = utils.createAgent(app);
const resetPasswordToken = uuid();
const resetPasswordTokenExpiration = Math.floor(Date.now() / 1000) + 100;
await Db.collections.User!.update(owner.id, {
resetPasswordToken,
resetPasswordTokenExpiration,
});
const passwordToStore = randomValidPassword();
const response = await authlessAgent.post('/change-password').send({
token: resetPasswordToken,
userId: owner.id,
password: passwordToStore,
});
expect(response.statusCode).toBe(200);
const authToken = utils.getAuthToken(response);
expect(authToken).toBeDefined();
const { password: storedPassword } = await Db.collections.User!.findOneOrFail(owner.id);
const comparisonResult = await compare(passwordToStore, storedPassword);
expect(comparisonResult).toBe(true);
expect(storedPassword).not.toBe(passwordToStore);
});
test('POST /change-password should fail with invalid inputs', async () => {
const owner = await testDb.createUser({ globalRole: globalOwnerRole });
const authlessAgent = utils.createAgent(app);
const resetPasswordToken = uuid();
const resetPasswordTokenExpiration = Math.floor(Date.now() / 1000) + 100;
await Db.collections.User!.update(owner.id, {
resetPasswordToken,
resetPasswordTokenExpiration,
});
const invalidPayloads = [
{ token: uuid() },
{ id: owner.id },
{ password: randomValidPassword() },
{ token: uuid(), id: owner.id },
{ token: uuid(), password: randomValidPassword() },
{ id: owner.id, password: randomValidPassword() },
{
id: owner.id,
password: randomInvalidPassword(),
token: resetPasswordToken,
},
{
id: owner.id,
password: randomValidPassword(),
token: uuid(),
},
];
await Promise.all(
invalidPayloads.map(async (invalidPayload) => {
const response = await authlessAgent.post('/change-password').query(invalidPayload);
expect(response.statusCode).toBe(400);
const { password: storedPassword } = await Db.collections.User!.findOneOrFail();
expect(owner.password).toBe(storedPassword);
}),
);
});
test('POST /change-password should fail when token has expired', async () => {
const owner = await testDb.createUser({ globalRole: globalOwnerRole });
const authlessAgent = utils.createAgent(app);
const resetPasswordToken = uuid();
const resetPasswordTokenExpiration = Math.floor(Date.now() / 1000) - 1;
await Db.collections.User!.update(owner.id, {
resetPasswordToken,
resetPasswordTokenExpiration,
});
const passwordToStore = randomValidPassword();
const response = await authlessAgent.post('/change-password').send({
token: resetPasswordToken,
userId: owner.id,
password: passwordToStore,
});
expect(response.statusCode).toBe(404);
});