From 3d27a1498702206b738cf978d037191306cec42b Mon Sep 17 00:00:00 2001 From: Tomi Turtiainen <10324676+tomi@users.noreply.github.com> Date: Wed, 29 Jan 2025 09:10:04 +0200 Subject: [PATCH] fix(core): Validate credential data before encryption (#12885) --- packages/core/src/__tests__/credentials.test.ts | 12 ++++++++++++ packages/core/src/constants.ts | 1 + packages/core/src/credentials.ts | 6 +++++- 3 files changed, 18 insertions(+), 1 deletion(-) diff --git a/packages/core/src/__tests__/credentials.test.ts b/packages/core/src/__tests__/credentials.test.ts index 199dd363ab..09b7586daf 100644 --- a/packages/core/src/__tests__/credentials.test.ts +++ b/packages/core/src/__tests__/credentials.test.ts @@ -1,6 +1,7 @@ import { Container } from '@n8n/di'; import { mock } from 'jest-mock-extended'; import type { CredentialInformation } from 'n8n-workflow'; +import { AssertionError } from 'node:assert'; import { CREDENTIAL_ERRORS } from '@/constants'; import { Cipher } from '@/encryption/cipher'; @@ -106,4 +107,15 @@ describe('Credentials', () => { expect(decryptedData.password).toBe('testpass'); }); }); + + describe('setData', () => { + test.each<{}>([[123], [null], [undefined]])( + 'should throw an AssertionError when data is %s', + (data) => { + const credentials = new Credentials<{}>(nodeCredentials, credentialType); + + expect(() => credentials.setData(data)).toThrow(AssertionError); + }, + ); + }); }); diff --git a/packages/core/src/constants.ts b/packages/core/src/constants.ts index f6ca2d8b67..bd44e25d10 100644 --- a/packages/core/src/constants.ts +++ b/packages/core/src/constants.ts @@ -20,4 +20,5 @@ export const CREDENTIAL_ERRORS = { DECRYPTION_FAILED: 'Credentials could not be decrypted. The likely reason is that a different "encryptionKey" was used to encrypt the data.', INVALID_JSON: 'Decrypted credentials data is not valid JSON.', + INVALID_DATA: 'Credentials data is not in a valid format.', }; diff --git a/packages/core/src/credentials.ts b/packages/core/src/credentials.ts index ab5d994bcf..f2d10df156 100644 --- a/packages/core/src/credentials.ts +++ b/packages/core/src/credentials.ts @@ -1,11 +1,13 @@ import { Container } from '@n8n/di'; import type { ICredentialDataDecryptedObject, ICredentialsEncrypted } from 'n8n-workflow'; import { ApplicationError, ICredentials, jsonParse } from 'n8n-workflow'; +import * as a from 'node:assert'; import { CREDENTIAL_ERRORS } from '@/constants'; import { Cipher } from '@/encryption/cipher'; +import { isObjectLiteral } from '@/utils'; -class CredentialDataError extends ApplicationError { +export class CredentialDataError extends ApplicationError { constructor({ name, type, id }: Credentials, message: string, cause?: unknown) { super(message, { extra: { name, type, id }, @@ -23,6 +25,8 @@ export class Credentials< * Sets new credential object */ setData(data: T): void { + a.ok(isObjectLiteral(data)); + this.data = this.cipher.encrypt(data); }