🚨 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>
This commit is contained in:
@@ -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 '..';
|
||||
@@ -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) {
|
||||
@@ -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 +=
|
||||
|
||||
@@ -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 {
|
||||
/**
|
||||
@@ -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;
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
/* 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';
|
||||
@@ -9,7 +8,7 @@ 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';
|
||||
@@ -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.',
|
||||
@@ -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 });
|
||||
|
||||
@@ -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';
|
||||
@@ -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 {
|
||||
/**
|
||||
@@ -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);
|
||||
|
||||
@@ -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';
|
||||
@@ -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,
|
||||
});
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -12,6 +11,7 @@ import { N8nApp, PublicUser } from '../Interfaces';
|
||||
import { UserRequest } from '../../requests';
|
||||
import {
|
||||
getInstanceBaseUrl,
|
||||
hashPassword,
|
||||
isEmailSetUp,
|
||||
sanitizeUser,
|
||||
validatePassword,
|
||||
@@ -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);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user