n8n/packages/cli/test/integration/credentials.api.test.ts
Ricardo Espinoza a18081d749
feat: Add n8n Public API (#3064)
*  Inicial setup

*  Add authentication handler

*  Add GET /users route

*  Improvements

* 👕 Fix linting issues

*  Add GET /users/:identifier endpoint

*  Add POST /users endpoint

*  Add DELETE /users/:identifier endpoint

*  Return error using express native functions

* 👕 Fix linting issue

*  Possibility to add custom middleware

*  Refactor POST /users

*  Refactor DELETE /users

*  Improve cleaning function

*  Refactor GET /users and /users/:identifier

*  Add API spec to route

*  Add raw option to response helper

* 🐛 Fix issue adding custom middleware

*  Enable includeRole parameter in GET /users/:identifier

*  Fix linting issues after merge

*  Add missing config variable

*  General improvements

 asasas

*  Add POST /users tests

* Debug public API tests

* Fix both sets of tests

*  Improvements

*  Load api versions dynamically

*  Add endpoints to UM to create/delete an API Key

*  Add index to apiKey column

* 👕 Fix linting issue

*  Clean open api spec

*  Improvements

*  Skip tests

* 🐛 Fix bug with test

*  Fix issue with the open api spec

*  Fix merge issue

*  Move token enpoints from /users to /me

*  Apply feedback to openapi.yml

*  Improvements to api-key endpoints

* 🐛 Fix test to suport API dynamic loading

*  Expose swagger ui in GET /{version}/docs

*  Allow to disable public api via env variable

*  Change handlers structure

* 🚧 WIP create credential, delete credential complete

* 🐛 fix route for creating api key

*  return api key of authenticated user

*  Expose public api activation to the settings

* ⬆️ Update package-lock.json file

*  Add execution resource

*  Fix linting issues

* 🛠 conditional public api endpoints excluding

* ️ create credential complete

*  Added n8n-card component. Added spacing utility classes.

* ♻️ Made use of n8n-card in existing components.

*  Added api key setup view.

*  Added api keys get/create/delete actions.

*  Added public api permissions handling.

* ♻️ Temporarily disabling card tests.

* ♻️ Changed translations. Storing api key only in component.

*  Added utilities storybook entry

* ♻️ Changed default value for generic copy input.

* 🧹 clean up createCredential

*  Add workflow resource to openapi spec

* 🐛 Fix naming with env variable

*  Allow multifile openapi spec

*  Add POST /workflows/:workflowId/activate

* fix up view, fix issues

* remove delete api key modal

* remove unused prop

* clean up store api

* remove getter

* remove unused dispatch

* fix component size to match

* use existing components

* match figma closely

* fix bug when um is disabled in sidebar

* set copy input color

* remove unused import

*  Remove css path

*  Add POST /workflows/:workflowId/desactivate

*  Add POST /workflows

* Revert " Remove css path"

a3d0a71719

* attempt to fix docker image issue

* revert dockerfile test

* disable public api

* disable api differently

* Revert "disable api differently"

b70e29433e

* Revert "disable public api"

886e5164fb

* remove unused box

*  PUT /workflows/:workflowId

*  Refactor workflow endpoints

*  Refactor executions endpoints

*  Fix typo

*  add credentials tests

*  adjust users tests

* update text

* add try it out link

*  Add delete, getAll and get to the workflow resource

* address spacing comments

* ️ apply correct structure

*  Add missing test to user resource and fix some issues

*  Add workflow tests

*  Add missing workflow tests and fix some issues

*  Executions tests

*  finish execution tests

*  Validate credentials data depending on type

* ️ implement review comments

* 👕 fix lint issues

*  Add apiKey to sanatizeUser

*  Fix issues with spec and tests

*  Add new structure

*  Validate credentials type and properties

*  Make all endpoints except /users independent on UM

*  Add instance base path to swagger UI

*  Remove testing endpoints

*  Fix issue with openapi tags

*  Add endpoint GET /credentialTypes/:id/schema

* 🐛 Fix issue adding json middleware to public api

*  Add API playground path to FE

*  Add telemetry and external hooks

* 🐛 Fix issue with user tests

*  Move /credentialTypes under /credentials

*  Add test to GET /credentials/schema/:id

* 🛠 refactor schema naming

*  Add DB migrations
asas

*  add tests for crd apiKey

*  Added API View telemetry events.

*  Remove rsync from the building process as it is missing on alpine base image

*  add missing BE telemetry events

* 🐛 Fix credential tests

*  address outstanding feedback

* 🔨 Remove move:openapi script

* ⬆️ update dependency

* ⬆️ update package-lock.json

* 👕 Fix linting issue

* 🐛 Fix package.json issue

* 🐛 fix migrations and tests

* 🐛 fix typos + naming

* 🚧 WIP fixing tests

*  Add json schema validation

*  Add missing fields to node schema

*  Add limit max upper limit

*  Rename id paths

* 🐛 Fix tests

* Add package-lock.jsonto custom dockerfile

* ⬆️ Update package-lock.json

* 🐛 Fix issue with build

* ✏️ add beta label to api view

* 🔥 Remove user endpoints

*  Add schema examples to GET /credentials/schema/:id

* 🔥 Remove user endpoints tests

* 🐛 Fix tests

* 🎨 adapt points from design review

* 🔥 remove unnecessary text-align

* ️ update UI

* 🐛 Fix issue with executions filter

*  Add tags filter to GET /workflows

*  Add missing error messages

*  add and update public api tests

*  add tests for owner activiating/deactivating non-owned wfs

* 🧪 add tests for filter for tags

* 🧪 add tests for more filter params

* 🐛 fix inclusion of tags

* 🛠 enhance readability

* ️ small refactorings

* 💄 improving readability/naming

*  Set API latest version dinamically

* Add comments to toJsonSchema function

*  Fix issue

*  Make execution data usable

*  Fix validation issue

*  Rename data field and change parameter and options

* 🐛 Fix issue parameter "detailsFieldFormat" not resolving correctly

* Skip executions tests

* skip workflow failing test

* Rename details property to data

*  Add includeData parameter

* 🐛 Fix issue with openapi spec

* 🐛 Fix linting issue

*  Fix execution schema

Co-authored-by: Iván Ovejero <ivov.src@gmail.com>
Co-authored-by: Ben Hesseldieck <b.hesseldieck@gmail.com>
Co-authored-by: Alex Grozav <alex@grozav.com>
Co-authored-by: Mutasem <mutdmour@gmail.com>
Co-authored-by: Jan Oberhauser <jan.oberhauser@gmail.com>
2022-06-08 20:53:12 +02:00

567 lines
21 KiB
TypeScript

import express from 'express';
import { UserSettings } from 'n8n-core';
import { Db } from '../../src';
import { randomName, randomString } from './shared/random';
import * as utils from './shared/utils';
import type { CredentialPayload, SaveCredentialFunction } from './shared/types';
import type { Role } from '../../src/databases/entities/Role';
import type { User } from '../../src/databases/entities/User';
import * as testDb from './shared/testDb';
import { RESPONSE_ERROR_MESSAGES } from '../../src/constants';
import { CredentialsEntity } from '../../src/databases/entities/CredentialsEntity';
jest.mock('../../src/telemetry');
let app: express.Application;
let testDbName = '';
let globalOwnerRole: Role;
let globalMemberRole: Role;
let saveCredential: SaveCredentialFunction;
beforeAll(async () => {
app = await utils.initTestServer({
endpointGroups: ['credentials'],
applyAuth: true,
});
const initResult = await testDb.init();
testDbName = initResult.testDbName;
utils.initConfigFile();
globalOwnerRole = await testDb.getGlobalOwnerRole();
globalMemberRole = await testDb.getGlobalMemberRole();
const credentialOwnerRole = await testDb.getCredentialOwnerRole();
saveCredential = affixRoleToSaveCredential(credentialOwnerRole);
utils.initTestLogger();
utils.initTestTelemetry();
});
beforeEach(async () => {
await testDb.truncate(['User', 'SharedCredentials', 'Credentials'], testDbName);
});
afterAll(async () => {
await testDb.terminate(testDbName);
});
test('POST /credentials should create cred', async () => {
const ownerShell = await testDb.createUserShell(globalOwnerRole);
const authOwnerAgent = utils.createAgent(app, { auth: true, user: ownerShell });
const payload = credentialPayload();
const response = await authOwnerAgent.post('/credentials').send(payload);
expect(response.statusCode).toBe(200);
const { id, name, type, nodesAccess, data: encryptedData } = response.body.data;
expect(name).toBe(payload.name);
expect(type).toBe(payload.type);
expect(nodesAccess[0].nodeType).toBe(payload.nodesAccess[0].nodeType);
expect(encryptedData).not.toBe(payload.data);
const credential = await Db.collections.Credentials.findOneOrFail(id);
expect(credential.name).toBe(payload.name);
expect(credential.type).toBe(payload.type);
expect(credential.nodesAccess[0].nodeType).toBe(payload.nodesAccess[0].nodeType);
expect(credential.data).not.toBe(payload.data);
const sharedCredential = await Db.collections.SharedCredentials.findOneOrFail({
relations: ['user', 'credentials'],
where: { credentials: credential },
});
expect(sharedCredential.user.id).toBe(ownerShell.id);
expect(sharedCredential.credentials.name).toBe(payload.name);
});
test('POST /credentials should fail with invalid inputs', async () => {
const ownerShell = await testDb.createUserShell(globalOwnerRole);
const authOwnerAgent = utils.createAgent(app, { auth: true, user: ownerShell });
await Promise.all(
INVALID_PAYLOADS.map(async (invalidPayload) => {
const response = await authOwnerAgent.post('/credentials').send(invalidPayload);
expect(response.statusCode).toBe(400);
}),
);
});
test('POST /credentials should fail with missing encryption key', async () => {
const mock = jest.spyOn(UserSettings, 'getEncryptionKey');
mock.mockRejectedValue(new Error(RESPONSE_ERROR_MESSAGES.NO_ENCRYPTION_KEY));
const ownerShell = await testDb.createUserShell(globalOwnerRole);
const authOwnerAgent = utils.createAgent(app, { auth: true, user: ownerShell });
const response = await authOwnerAgent.post('/credentials').send(credentialPayload());
expect(response.statusCode).toBe(500);
mock.mockRestore();
});
test('POST /credentials should ignore ID in payload', async () => {
const ownerShell = await testDb.createUserShell(globalOwnerRole);
const authOwnerAgent = utils.createAgent(app, { auth: true, user: ownerShell });
const firstResponse = await authOwnerAgent
.post('/credentials')
.send({ id: '8', ...credentialPayload() });
expect(firstResponse.body.data.id).not.toBe('8');
const secondResponse = await authOwnerAgent
.post('/credentials')
.send({ id: 8, ...credentialPayload() });
expect(secondResponse.body.data.id).not.toBe(8);
});
test('DELETE /credentials/:id should delete owned cred for owner', async () => {
const ownerShell = await testDb.createUserShell(globalOwnerRole);
const authOwnerAgent = utils.createAgent(app, { auth: true, user: ownerShell });
const savedCredential = await saveCredential(credentialPayload(), { user: ownerShell });
const response = await authOwnerAgent.delete(`/credentials/${savedCredential.id}`);
expect(response.statusCode).toBe(200);
expect(response.body).toEqual({ data: true });
const deletedCredential = await Db.collections.Credentials.findOne(savedCredential.id);
expect(deletedCredential).toBeUndefined(); // deleted
const deletedSharedCredential = await Db.collections.SharedCredentials.findOne();
expect(deletedSharedCredential).toBeUndefined(); // deleted
});
test('DELETE /credentials/:id should delete non-owned cred for owner', async () => {
const ownerShell = await testDb.createUserShell(globalOwnerRole);
const authOwnerAgent = utils.createAgent(app, { auth: true, user: ownerShell });
const member = await testDb.createUser({ globalRole: globalMemberRole });
const savedCredential = await saveCredential(credentialPayload(), { user: member });
const response = await authOwnerAgent.delete(`/credentials/${savedCredential.id}`);
expect(response.statusCode).toBe(200);
expect(response.body).toEqual({ data: true });
const deletedCredential = await Db.collections.Credentials.findOne(savedCredential.id);
expect(deletedCredential).toBeUndefined(); // deleted
const deletedSharedCredential = await Db.collections.SharedCredentials.findOne();
expect(deletedSharedCredential).toBeUndefined(); // deleted
});
test('DELETE /credentials/:id should delete owned cred for member', async () => {
const member = await testDb.createUser({ globalRole: globalMemberRole });
const authMemberAgent = utils.createAgent(app, { auth: true, user: member });
const savedCredential = await saveCredential(credentialPayload(), { user: member });
const response = await authMemberAgent.delete(`/credentials/${savedCredential.id}`);
expect(response.statusCode).toBe(200);
expect(response.body).toEqual({ data: true });
const deletedCredential = await Db.collections.Credentials.findOne(savedCredential.id);
expect(deletedCredential).toBeUndefined(); // deleted
const deletedSharedCredential = await Db.collections.SharedCredentials.findOne();
expect(deletedSharedCredential).toBeUndefined(); // deleted
});
test('DELETE /credentials/:id should not delete non-owned cred for member', async () => {
const ownerShell = await testDb.createUserShell(globalOwnerRole);
const member = await testDb.createUser({ globalRole: globalMemberRole });
const authMemberAgent = utils.createAgent(app, { auth: true, user: member });
const savedCredential = await saveCredential(credentialPayload(), { user: ownerShell });
const response = await authMemberAgent.delete(`/credentials/${savedCredential.id}`);
expect(response.statusCode).toBe(404);
const shellCredential = await Db.collections.Credentials.findOne(savedCredential.id);
expect(shellCredential).toBeDefined(); // not deleted
const deletedSharedCredential = await Db.collections.SharedCredentials.findOne();
expect(deletedSharedCredential).toBeDefined(); // not deleted
});
test('DELETE /credentials/:id should fail if cred not found', async () => {
const ownerShell = await testDb.createUserShell(globalOwnerRole);
const authOwnerAgent = utils.createAgent(app, { auth: true, user: ownerShell });
const response = await authOwnerAgent.delete('/credentials/123');
expect(response.statusCode).toBe(404);
});
test('PATCH /credentials/:id should update owned cred for owner', async () => {
const ownerShell = await testDb.createUserShell(globalOwnerRole);
const authOwnerAgent = utils.createAgent(app, { auth: true, user: ownerShell });
const savedCredential = await saveCredential(credentialPayload(), { user: ownerShell });
const patchPayload = credentialPayload();
const response = await authOwnerAgent
.patch(`/credentials/${savedCredential.id}`)
.send(patchPayload);
expect(response.statusCode).toBe(200);
const { id, name, type, nodesAccess, data: encryptedData } = response.body.data;
expect(name).toBe(patchPayload.name);
expect(type).toBe(patchPayload.type);
expect(nodesAccess[0].nodeType).toBe(patchPayload.nodesAccess[0].nodeType);
expect(encryptedData).not.toBe(patchPayload.data);
const credential = await Db.collections.Credentials.findOneOrFail(id);
expect(credential.name).toBe(patchPayload.name);
expect(credential.type).toBe(patchPayload.type);
expect(credential.nodesAccess[0].nodeType).toBe(patchPayload.nodesAccess[0].nodeType);
expect(credential.data).not.toBe(patchPayload.data);
const sharedCredential = await Db.collections.SharedCredentials.findOneOrFail({
relations: ['credentials'],
where: { credentials: credential },
});
expect(sharedCredential.credentials.name).toBe(patchPayload.name); // updated
});
test('PATCH /credentials/:id should update non-owned cred for owner', async () => {
const ownerShell = await testDb.createUserShell(globalOwnerRole);
const authOwnerAgent = utils.createAgent(app, { auth: true, user: ownerShell });
const member = await testDb.createUser({ globalRole: globalMemberRole });
const savedCredential = await saveCredential(credentialPayload(), { user: member });
const patchPayload = credentialPayload();
const response = await authOwnerAgent
.patch(`/credentials/${savedCredential.id}`)
.send(patchPayload);
expect(response.statusCode).toBe(200);
const { id, name, type, nodesAccess, data: encryptedData } = response.body.data;
expect(name).toBe(patchPayload.name);
expect(type).toBe(patchPayload.type);
expect(nodesAccess[0].nodeType).toBe(patchPayload.nodesAccess[0].nodeType);
expect(encryptedData).not.toBe(patchPayload.data);
const credential = await Db.collections.Credentials.findOneOrFail(id);
expect(credential.name).toBe(patchPayload.name);
expect(credential.type).toBe(patchPayload.type);
expect(credential.nodesAccess[0].nodeType).toBe(patchPayload.nodesAccess[0].nodeType);
expect(credential.data).not.toBe(patchPayload.data);
const sharedCredential = await Db.collections.SharedCredentials.findOneOrFail({
relations: ['credentials'],
where: { credentials: credential },
});
expect(sharedCredential.credentials.name).toBe(patchPayload.name); // updated
});
test('PATCH /credentials/:id should update owned cred for member', async () => {
const member = await testDb.createUser({ globalRole: globalMemberRole });
const authMemberAgent = utils.createAgent(app, { auth: true, user: member });
const savedCredential = await saveCredential(credentialPayload(), { user: member });
const patchPayload = credentialPayload();
const response = await authMemberAgent
.patch(`/credentials/${savedCredential.id}`)
.send(patchPayload);
expect(response.statusCode).toBe(200);
const { id, name, type, nodesAccess, data: encryptedData } = response.body.data;
expect(name).toBe(patchPayload.name);
expect(type).toBe(patchPayload.type);
expect(nodesAccess[0].nodeType).toBe(patchPayload.nodesAccess[0].nodeType);
expect(encryptedData).not.toBe(patchPayload.data);
const credential = await Db.collections.Credentials.findOneOrFail(id);
expect(credential.name).toBe(patchPayload.name);
expect(credential.type).toBe(patchPayload.type);
expect(credential.nodesAccess[0].nodeType).toBe(patchPayload.nodesAccess[0].nodeType);
expect(credential.data).not.toBe(patchPayload.data);
const sharedCredential = await Db.collections.SharedCredentials.findOneOrFail({
relations: ['credentials'],
where: { credentials: credential },
});
expect(sharedCredential.credentials.name).toBe(patchPayload.name); // updated
});
test('PATCH /credentials/:id should not update non-owned cred for member', async () => {
const ownerShell = await testDb.createUserShell(globalOwnerRole);
const member = await testDb.createUser({ globalRole: globalMemberRole });
const authMemberAgent = utils.createAgent(app, { auth: true, user: member });
const savedCredential = await saveCredential(credentialPayload(), { user: ownerShell });
const patchPayload = credentialPayload();
const response = await authMemberAgent
.patch(`/credentials/${savedCredential.id}`)
.send(patchPayload);
expect(response.statusCode).toBe(404);
const shellCredential = await Db.collections.Credentials.findOneOrFail(savedCredential.id);
expect(shellCredential.name).not.toBe(patchPayload.name); // not updated
});
test('PATCH /credentials/:id should fail with invalid inputs', async () => {
const ownerShell = await testDb.createUserShell(globalOwnerRole);
const authOwnerAgent = utils.createAgent(app, { auth: true, user: ownerShell });
const savedCredential = await saveCredential(credentialPayload(), { user: ownerShell });
await Promise.all(
INVALID_PAYLOADS.map(async (invalidPayload) => {
const response = await authOwnerAgent
.patch(`/credentials/${savedCredential.id}`)
.send(invalidPayload);
expect(response.statusCode).toBe(400);
}),
);
});
test('PATCH /credentials/:id should fail if cred not found', async () => {
const ownerShell = await testDb.createUserShell(globalOwnerRole);
const authOwnerAgent = utils.createAgent(app, { auth: true, user: ownerShell });
const response = await authOwnerAgent.patch('/credentials/123').send(credentialPayload());
expect(response.statusCode).toBe(404);
});
test('PATCH /credentials/:id should fail with missing encryption key', async () => {
const mock = jest.spyOn(UserSettings, 'getEncryptionKey');
mock.mockRejectedValue(new Error(RESPONSE_ERROR_MESSAGES.NO_ENCRYPTION_KEY));
const ownerShell = await testDb.createUserShell(globalOwnerRole);
const authOwnerAgent = utils.createAgent(app, { auth: true, user: ownerShell });
const response = await authOwnerAgent.post('/credentials').send(credentialPayload());
expect(response.statusCode).toBe(500);
mock.mockRestore();
});
test('GET /credentials should retrieve all creds for owner', async () => {
const ownerShell = await testDb.createUserShell(globalOwnerRole);
const authOwnerAgent = utils.createAgent(app, { auth: true, user: ownerShell });
for (let i = 0; i < 3; i++) {
await saveCredential(credentialPayload(), { user: ownerShell });
}
const member = await testDb.createUser({ globalRole: globalMemberRole });
await saveCredential(credentialPayload(), { user: member });
const response = await authOwnerAgent.get('/credentials');
expect(response.statusCode).toBe(200);
expect(response.body.data.length).toBe(4); // 3 owner + 1 member
await Promise.all(
response.body.data.map(async (credential: CredentialsEntity) => {
const { name, type, nodesAccess, data: encryptedData } = credential;
expect(typeof name).toBe('string');
expect(typeof type).toBe('string');
expect(typeof nodesAccess[0].nodeType).toBe('string');
expect(encryptedData).toBeUndefined();
}),
);
});
test('GET /credentials should retrieve owned creds for member', async () => {
const member = await testDb.createUser({ globalRole: globalMemberRole });
const authMemberAgent = utils.createAgent(app, { auth: true, user: member });
for (let i = 0; i < 3; i++) {
await saveCredential(credentialPayload(), { user: member });
}
const response = await authMemberAgent.get('/credentials');
expect(response.statusCode).toBe(200);
expect(response.body.data.length).toBe(3);
await Promise.all(
response.body.data.map(async (credential: CredentialsEntity) => {
const { name, type, nodesAccess, data: encryptedData } = credential;
expect(typeof name).toBe('string');
expect(typeof type).toBe('string');
expect(typeof nodesAccess[0].nodeType).toBe('string');
expect(encryptedData).toBeUndefined();
}),
);
});
test('GET /credentials should not retrieve non-owned creds for member', async () => {
const ownerShell = await testDb.createUserShell(globalOwnerRole);
const member = await testDb.createUser({ globalRole: globalMemberRole });
const authMemberAgent = utils.createAgent(app, { auth: true, user: member });
for (let i = 0; i < 3; i++) {
await saveCredential(credentialPayload(), { user: ownerShell });
}
const response = await authMemberAgent.get('/credentials');
expect(response.statusCode).toBe(200);
expect(response.body.data.length).toBe(0); // owner's creds not returned
});
test('GET /credentials/:id should retrieve owned cred for owner', async () => {
const ownerShell = await testDb.createUserShell(globalOwnerRole);
const authOwnerAgent = utils.createAgent(app, { auth: true, user: ownerShell });
const savedCredential = await saveCredential(credentialPayload(), { user: ownerShell });
const firstResponse = await authOwnerAgent.get(`/credentials/${savedCredential.id}`);
expect(firstResponse.statusCode).toBe(200);
expect(typeof firstResponse.body.data.name).toBe('string');
expect(typeof firstResponse.body.data.type).toBe('string');
expect(typeof firstResponse.body.data.nodesAccess[0].nodeType).toBe('string');
expect(firstResponse.body.data.data).toBeUndefined();
const secondResponse = await authOwnerAgent
.get(`/credentials/${savedCredential.id}`)
.query({ includeData: true });
expect(secondResponse.statusCode).toBe(200);
expect(typeof secondResponse.body.data.name).toBe('string');
expect(typeof secondResponse.body.data.type).toBe('string');
expect(typeof secondResponse.body.data.nodesAccess[0].nodeType).toBe('string');
expect(secondResponse.body.data.data).toBeDefined();
});
test('GET /credentials/:id should retrieve owned cred for member', async () => {
const member = await testDb.createUser({ globalRole: globalMemberRole });
const authMemberAgent = utils.createAgent(app, { auth: true, user: member });
const savedCredential = await saveCredential(credentialPayload(), { user: member });
const firstResponse = await authMemberAgent.get(`/credentials/${savedCredential.id}`);
expect(firstResponse.statusCode).toBe(200);
expect(typeof firstResponse.body.data.name).toBe('string');
expect(typeof firstResponse.body.data.type).toBe('string');
expect(typeof firstResponse.body.data.nodesAccess[0].nodeType).toBe('string');
expect(firstResponse.body.data.data).toBeUndefined();
const secondResponse = await authMemberAgent
.get(`/credentials/${savedCredential.id}`)
.query({ includeData: true });
expect(secondResponse.statusCode).toBe(200);
expect(typeof secondResponse.body.data.name).toBe('string');
expect(typeof secondResponse.body.data.type).toBe('string');
expect(typeof secondResponse.body.data.nodesAccess[0].nodeType).toBe('string');
expect(secondResponse.body.data.data).toBeDefined();
});
test('GET /credentials/:id should not retrieve non-owned cred for member', async () => {
const ownerShell = await testDb.createUserShell(globalOwnerRole);
const member = await testDb.createUser({ globalRole: globalMemberRole });
const authMemberAgent = utils.createAgent(app, { auth: true, user: member });
const savedCredential = await saveCredential(credentialPayload(), { user: ownerShell });
const response = await authMemberAgent.get(`/credentials/${savedCredential.id}`);
expect(response.statusCode).toBe(404);
expect(response.body.data).toBeUndefined(); // owner's cred not returned
});
test('GET /credentials/:id should fail with missing encryption key', async () => {
const ownerShell = await testDb.createUserShell(globalOwnerRole);
const authOwnerAgent = utils.createAgent(app, { auth: true, user: ownerShell });
const savedCredential = await saveCredential(credentialPayload(), { user: ownerShell });
const mock = jest.spyOn(UserSettings, 'getEncryptionKey');
mock.mockRejectedValue(new Error(RESPONSE_ERROR_MESSAGES.NO_ENCRYPTION_KEY));
const response = await authOwnerAgent
.get(`/credentials/${savedCredential.id}`)
.query({ includeData: true });
expect(response.statusCode).toBe(500);
mock.mockRestore();
});
test('GET /credentials/:id should return 404 if cred not found', async () => {
const ownerShell = await testDb.createUserShell(globalOwnerRole);
const authMemberAgent = utils.createAgent(app, { auth: true, user: ownerShell });
const response = await authMemberAgent.get('/credentials/789');
expect(response.statusCode).toBe(404);
});
const credentialPayload = () => ({
name: randomName(),
type: randomName(),
nodesAccess: [{ nodeType: randomName() }],
data: { accessToken: randomString(6, 16) },
});
const INVALID_PAYLOADS = [
{
type: randomName(),
nodesAccess: [{ nodeType: randomName() }],
data: { accessToken: randomString(6, 16) },
},
{
name: randomName(),
nodesAccess: [{ nodeType: randomName() }],
data: { accessToken: randomString(6, 16) },
},
{
name: randomName(),
type: randomName(),
data: { accessToken: randomString(6, 16) },
},
{
name: randomName(),
type: randomName(),
nodesAccess: [{ nodeType: randomName() }],
},
{},
[],
undefined,
];
function affixRoleToSaveCredential(role: Role) {
return (credentialPayload: CredentialPayload, { user }: { user: User }) =>
testDb.saveCredential(credentialPayload, { user, role });
}