Skip to content

Commit

Permalink
🚨 Optimize UM tests (#3066)
Browse files Browse the repository at this point in the history
* ⚡ 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>
  • Loading branch information
ivov and BHesseldieck authored Apr 8, 2022
1 parent e78bf15 commit 1e2d6da
Show file tree
Hide file tree
Showing 19 changed files with 837 additions and 680 deletions.
4 changes: 2 additions & 2 deletions packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@
"start:windows": "cd bin && n8n",
"test": "npm run test:sqlite",
"test:sqlite": "export N8N_LOG_LEVEL='silent'; export DB_TYPE=sqlite; jest",
"test:postgres": "export DB_TYPE=postgresdb && jest",
"test:mysql": "export DB_TYPE=mysqldb && jest",
"test:postgres": "export N8N_LOG_LEVEL='silent'; export DB_TYPE=postgresdb && jest",
"test:mysql": "export N8N_LOG_LEVEL='silent'; export DB_TYPE=mysqldb && jest",
"watch": "tsc --watch",
"typeorm": "ts-node ../../node_modules/typeorm/cli.js"
},
Expand Down
14 changes: 6 additions & 8 deletions packages/cli/src/UserManagement/UserManagementHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import { Workflow } from 'n8n-workflow';
import { In, IsNull, Not } from 'typeorm';
import express = require('express');
import { compare } from 'bcryptjs';
import { compare, genSaltSync, hash } from 'bcryptjs';

import { PublicUser } from './Interfaces';
import { Db, ResponseHelper } from '..';
Expand Down Expand Up @@ -63,11 +63,6 @@ export function getInstanceBaseUrl(): string {
return n8nBaseUrl.endsWith('/') ? n8nBaseUrl.slice(0, n8nBaseUrl.length - 1) : n8nBaseUrl;
}

export async function isInstanceOwnerSetup(): Promise<boolean> {
const users = await Db.collections.User!.find({ email: Not(IsNull()) });
return users.length !== 0;
}

// TODO: Enforce at model level
export function validatePassword(password?: string): string {
if (!password) {
Expand Down Expand Up @@ -223,9 +218,12 @@ export function isAuthenticatedRequest(request: express.Request): request is Aut
// hashing
// ----------------------------------

export async function compareHash(str: string, hash: string): Promise<boolean | undefined> {
export const hashPassword = async (validPassword: string): Promise<string> =>
hash(validPassword, genSaltSync(10));

export async function compareHash(plaintext: string, hashed: string): Promise<boolean | undefined> {
try {
return await compare(str, hash);
return await compare(plaintext, hashed);
} catch (error) {
if (error instanceof Error && error.message.includes('Invalid salt version')) {
error.message +=
Expand Down
10 changes: 8 additions & 2 deletions packages/cli/src/UserManagement/routes/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@ import { Db, ResponseHelper } from '../..';
import { AUTH_COOKIE_NAME } from '../../constants';
import { issueCookie, resolveJwt } from '../auth/jwt';
import { N8nApp, PublicUser } from '../Interfaces';
import { compareHash, isInstanceOwnerSetup, sanitizeUser } from '../UserManagementHelper';
import { compareHash, sanitizeUser } from '../UserManagementHelper';
import { User } from '../../databases/entities/User';
import type { LoginRequest } from '../../requests';
import config = require('../../../config');

export function authenticationMethods(this: N8nApp): void {
/**
Expand Down Expand Up @@ -71,13 +72,18 @@ export function authenticationMethods(this: N8nApp): void {
// If logged in, return user
try {
user = await resolveJwt(cookieContents);

if (!config.get('userManagement.isInstanceOwnerSetUp')) {
res.cookie(AUTH_COOKIE_NAME, cookieContents);
}

return sanitizeUser(user);
} catch (error) {
res.clearCookie(AUTH_COOKIE_NAME);
}
}

if (await isInstanceOwnerSetup()) {
if (config.get('userManagement.isInstanceOwnerSetUp')) {
const error = new Error('Not logged in');
// @ts-ignore
error.httpStatusCode = 401;
Expand Down
7 changes: 3 additions & 4 deletions packages/cli/src/UserManagement/routes/me.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
/* eslint-disable @typescript-eslint/no-non-null-assertion */
/* eslint-disable import/no-cycle */

import { compare, genSaltSync, hashSync } from 'bcryptjs';
import express = require('express');
import validator from 'validator';
import { LoggerProxy as Logger } from 'n8n-workflow';

import { Db, InternalHooksManager, ResponseHelper } from '../..';
import { issueCookie } from '../auth/jwt';
import { N8nApp, PublicUser } from '../Interfaces';
import { validatePassword, sanitizeUser } from '../UserManagementHelper';
import { validatePassword, sanitizeUser, compareHash, hashPassword } from '../UserManagementHelper';
import type { AuthenticatedRequest, MeRequest } from '../../requests';
import { validateEntity } from '../../GenericHelpers';
import { User } from '../../databases/entities/User';
Expand Down Expand Up @@ -87,7 +86,7 @@ export function meNamespace(this: N8nApp): void {
throw new ResponseHelper.ResponseError('Requesting user not set up.');
}

const isCurrentPwCorrect = await compare(currentPassword, req.user.password);
const isCurrentPwCorrect = await compareHash(currentPassword, req.user.password);
if (!isCurrentPwCorrect) {
throw new ResponseHelper.ResponseError(
'Provided current password is incorrect.',
Expand All @@ -98,7 +97,7 @@ export function meNamespace(this: N8nApp): void {

const validPassword = validatePassword(newPassword);

req.user.password = hashSync(validPassword, genSaltSync(10));
req.user.password = await hashPassword(validPassword);

const user = await Db.collections.User!.save(req.user);
Logger.info('Password updated successfully', { userId: user.id });
Expand Down
5 changes: 2 additions & 3 deletions packages/cli/src/UserManagement/routes/owner.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
/* eslint-disable import/no-cycle */
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import { hashSync, genSaltSync } from 'bcryptjs';
import * as express from 'express';
import validator from 'validator';
import { LoggerProxy as Logger } from 'n8n-workflow';
Expand All @@ -11,7 +10,7 @@ import { validateEntity } from '../../GenericHelpers';
import { AuthenticatedRequest, OwnerRequest } from '../../requests';
import { issueCookie } from '../auth/jwt';
import { N8nApp } from '../Interfaces';
import { sanitizeUser, validatePassword } from '../UserManagementHelper';
import { hashPassword, sanitizeUser, validatePassword } from '../UserManagementHelper';

export function ownerNamespace(this: N8nApp): void {
/**
Expand Down Expand Up @@ -74,7 +73,7 @@ export function ownerNamespace(this: N8nApp): void {
email,
firstName,
lastName,
password: hashSync(validPassword, genSaltSync(10)),
password: await hashPassword(validPassword),
});

await validateEntity(owner);
Expand Down
5 changes: 2 additions & 3 deletions packages/cli/src/UserManagement/routes/passwordReset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,13 @@
import express = require('express');
import { v4 as uuid } from 'uuid';
import { URL } from 'url';
import { genSaltSync, hashSync } from 'bcryptjs';
import validator from 'validator';
import { IsNull, MoreThanOrEqual, Not } from 'typeorm';
import { LoggerProxy as Logger } from 'n8n-workflow';

import { Db, InternalHooksManager, ResponseHelper } from '../..';
import { N8nApp } from '../Interfaces';
import { getInstanceBaseUrl, validatePassword } from '../UserManagementHelper';
import { getInstanceBaseUrl, hashPassword, validatePassword } from '../UserManagementHelper';
import * as UserManagementMailer from '../email';
import type { PasswordResetRequest } from '../../requests';
import { issueCookie } from '../auth/jwt';
Expand Down Expand Up @@ -206,7 +205,7 @@ export function passwordResetNamespace(this: N8nApp): void {
}

await Db.collections.User!.update(userId, {
password: hashSync(validPassword, genSaltSync(10)),
password: await hashPassword(validPassword),
resetPasswordToken: null,
resetPasswordTokenExpiration: null,
});
Expand Down
4 changes: 2 additions & 2 deletions packages/cli/src/UserManagement/routes/users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import { Response } from 'express';
import { In } from 'typeorm';
import { genSaltSync, hashSync } from 'bcryptjs';
import validator from 'validator';
import { LoggerProxy as Logger } from 'n8n-workflow';

Expand All @@ -12,6 +11,7 @@ import { N8nApp, PublicUser } from '../Interfaces';
import { UserRequest } from '../../requests';
import {
getInstanceBaseUrl,
hashPassword,
isEmailSetUp,
sanitizeUser,
validatePassword,
Expand Down Expand Up @@ -349,7 +349,7 @@ export function usersNamespace(this: N8nApp): void {

invitee.firstName = firstName;
invitee.lastName = lastName;
invitee.password = hashSync(validPassword, genSaltSync(10));
invitee.password = await hashPassword(validPassword);

const updatedUser = await Db.collections.User!.save(invitee);

Expand Down
4 changes: 2 additions & 2 deletions packages/cli/src/databases/entities/User.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export class User {
@PrimaryGeneratedColumn('uuid')
id: string;

@Column({ length: 254 })
@Column({ length: 254, nullable: true })
@Index({ unique: true })
@IsEmail()
email: string;
Expand All @@ -81,7 +81,7 @@ export class User {

@Column({ nullable: true })
@IsString({ message: 'Password must be of type string.' })
password?: string;
password: string;

@Column({ type: String, nullable: true })
resetPasswordToken?: string | null;
Expand Down
Loading

0 comments on commit 1e2d6da

Please sign in to comment.