feat(core): Use WebCrypto to generate all random numbers and strings (#9786)

This commit is contained in:
कारतोफ्फेलस्क्रिप्ट™
2024-06-19 13:33:57 +02:00
committed by GitHub
parent cfc4db00e3
commit 65c5609ab5
49 changed files with 254 additions and 214 deletions

View File

@@ -3,6 +3,8 @@ import type { Entry as LdapUser } from 'ldapts';
import { Filter } from 'ldapts/filters/Filter';
import { Container } from 'typedi';
import { validate } from 'jsonschema';
import { randomString } from 'n8n-workflow';
import * as Db from '@/Db';
import config from '@/config';
import { User } from '@db/entities/User';
@@ -38,13 +40,6 @@ export const getLdapLoginLabel = (): string => config.getEnv(LDAP_LOGIN_LABEL);
*/
export const isLdapLoginEnabled = (): boolean => config.getEnv(LDAP_LOGIN_ENABLED);
/**
* Return a random password to be assigned to the LDAP users
*/
export const randomPassword = (): string => {
return Math.random().toString(36).slice(-8);
};
/**
* Validate the structure of the LDAP configuration schema
*/
@@ -161,7 +156,7 @@ export const mapLdapUserToDbUser = (
Object.assign(user, data);
if (toCreate) {
user.role = 'global:member';
user.password = randomPassword();
user.password = randomString(8);
user.disabled = false;
} else {
user.disabled = true;
@@ -278,7 +273,7 @@ export const createLdapAuthIdentity = async (user: User, ldapId: string) => {
export const createLdapUserOnLocalDb = async (data: Partial<User>, ldapId: string) => {
const { user } = await Container.get(UserRepository).createUserWithProject({
password: randomPassword(),
password: randomString(8),
role: 'global:member',
...data,
});

View File

@@ -8,7 +8,7 @@ import { createReadStream, createWriteStream, existsSync } from 'fs';
import { pipeline } from 'stream/promises';
import replaceStream from 'replacestream';
import glob from 'fast-glob';
import { jsonParse } from 'n8n-workflow';
import { jsonParse, randomString } from 'n8n-workflow';
import config from '@/config';
import { ActiveExecutions } from '@/ActiveExecutions';
@@ -265,12 +265,7 @@ export class Start extends BaseCommand {
if (tunnelSubdomain === '') {
// When no tunnel subdomain did exist yet create a new random one
const availableCharacters = 'abcdefghijklmnopqrstuvwxyz0123456789';
tunnelSubdomain = Array.from({ length: 24 })
.map(() =>
availableCharacters.charAt(Math.floor(Math.random() * availableCharacters.length)),
)
.join('');
tunnelSubdomain = randomString(24).toLowerCase();
this.instanceSettings.update({ tunnelSubdomain });
}

View File

@@ -1,7 +1,8 @@
import { customAlphabet } from 'nanoid';
import { ALPHABET } from 'n8n-workflow';
import type { N8nInstanceType } from '@/Interfaces';
const nanoid = customAlphabet('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', 16);
const nanoid = customAlphabet(ALPHABET, 16);
export function generateNanoId() {
return nanoid();

View File

@@ -1,18 +1,18 @@
import Container from 'typedi';
import { stringify } from 'flatted';
import { NodeConnectionType, randomInt } from 'n8n-workflow';
import { mockInstance } from '@test/mocking';
import { randomInteger } from '@test-integration/random';
import { createWorkflow } from '@test-integration/db/workflows';
import { createExecution } from '@test-integration/db/executions';
import * as testDb from '@test-integration/testDb';
import { NodeConnectionType } from 'n8n-workflow';
import { mock } from 'jest-mock-extended';
import { OrchestrationService } from '@/services/orchestration.service';
import config from '@/config';
import { ExecutionRecoveryService } from '@/executions/execution-recovery.service';
import { ExecutionRepository } from '@/databases/repositories/execution.repository';
import type { WorkflowEntity } from '@/databases/entities/WorkflowEntity';
import { InternalHooks } from '@/InternalHooks';
import { Push } from '@/push';
import { ARTIFICIAL_TASK_DATA } from '@/constants';
@@ -20,9 +20,7 @@ import { NodeCrashedError } from '@/errors/node-crashed.error';
import { WorkflowCrashedError } from '@/errors/workflow-crashed.error';
import { EventMessageNode } from '@/eventbus/EventMessageClasses/EventMessageNode';
import { EventMessageWorkflow } from '@/eventbus/EventMessageClasses/EventMessageWorkflow';
import type { EventMessageTypes as EventMessage } from '@/eventbus/EventMessageClasses';
import type { WorkflowEntity } from '@/databases/entities/WorkflowEntity';
import type { Logger } from '@/Logger';
/**
@@ -301,7 +299,7 @@ describe('ExecutionRecoveryService', () => {
/**
* Arrange
*/
const inexistentExecutionId = randomInteger(100).toString();
const inexistentExecutionId = randomInt(100).toString();
const noMessages: EventMessage[] = [];
/**
@@ -373,7 +371,7 @@ describe('ExecutionRecoveryService', () => {
/**
* Arrange
*/
const inexistentExecutionId = randomInteger(100).toString();
const inexistentExecutionId = randomInt(100).toString();
const messages = setupMessages(inexistentExecutionId, 'Some workflow');
/**

View File

@@ -1,12 +1,19 @@
import { Container } from 'typedi';
import type { FlowResult } from 'samlify/types/src/flow';
import { randomString } from 'n8n-workflow';
import config from '@/config';
import { AuthIdentity } from '@db/entities/AuthIdentity';
import type { User } from '@db/entities/User';
import { UserRepository } from '@db/repositories/user.repository';
import { AuthIdentityRepository } from '@db/repositories/authIdentity.repository';
import { InternalServerError } from '@/errors/response-errors/internal-server.error';
import { AuthError } from '@/errors/response-errors/auth.error';
import { License } from '@/License';
import { PasswordUtility } from '@/services/password.utility';
import type { SamlPreferences } from './types/samlPreferences';
import type { SamlUserAttributes } from './types/samlUserAttributes';
import type { FlowResult } from 'samlify/types/src/flow';
import type { SamlAttributeMapping } from './types/samlAttributeMapping';
import { SAML_LOGIN_ENABLED, SAML_LOGIN_LABEL } from './constants';
import {
@@ -17,10 +24,6 @@ import {
} from '../ssoHelpers';
import { getServiceProviderConfigTestReturnUrl } from './serviceProvider.ee';
import type { SamlConfiguration } from './types/requests';
import { UserRepository } from '@db/repositories/user.repository';
import { AuthIdentityRepository } from '@db/repositories/authIdentity.repository';
import { InternalServerError } from '@/errors/response-errors/internal-server.error';
import { AuthError } from '@/errors/response-errors/auth.error';
/**
* Check whether the SAML feature is licensed and enabled in the instance
@@ -73,39 +76,18 @@ export const isSamlPreferences = (candidate: unknown): candidate is SamlPreferen
);
};
export function generatePassword(): string {
const length = 18;
const charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
const charsetNoNumbers = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
const randomNumber = Math.floor(Math.random() * 10);
const randomUpper = charset.charAt(Math.floor(Math.random() * charsetNoNumbers.length));
const randomNumberPosition = Math.floor(Math.random() * length);
const randomUpperPosition = Math.floor(Math.random() * length);
let password = '';
for (let i = 0, n = charset.length; i < length; ++i) {
password += charset.charAt(Math.floor(Math.random() * n));
}
password =
password.substring(0, randomNumberPosition) +
randomNumber.toString() +
password.substring(randomNumberPosition);
password =
password.substring(0, randomUpperPosition) +
randomUpper +
password.substring(randomUpperPosition);
return password;
}
export async function createUserFromSamlAttributes(attributes: SamlUserAttributes): Promise<User> {
return await Container.get(UserRepository).manager.transaction(async (trx) => {
const { user } = await Container.get(UserRepository).createUserWithProject(
const randomPassword = randomString(18);
const userRepository = Container.get(UserRepository);
return await userRepository.manager.transaction(async (trx) => {
const { user } = await userRepository.createUserWithProject(
{
email: attributes.email.toLowerCase(),
firstName: attributes.firstName,
lastName: attributes.lastName,
role: 'global:member',
// generates a password that is not used or known to the user
password: await Container.get(PasswordUtility).hash(generatePassword()),
password: await Container.get(PasswordUtility).hash(randomPassword),
},
trx,
);

View File

@@ -1,7 +1,6 @@
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import { CliWorkflowOperationError, SubworkflowOperationError } from 'n8n-workflow';
import type { INode } from 'n8n-workflow';
import { STARTING_NODES } from './constants';
import { STARTING_NODES } from '@/constants';
/**
* Returns if the given id is a valid workflow id