feat: also send credentials when returning workflow via API (#4458) (no-changelog)

This commit is contained in:
Omar Ajoue 2022-10-31 11:08:25 -03:00 committed by GitHub
parent ec5ef0c50d
commit 7563d450f9
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 184 additions and 10 deletions

View file

@ -1,7 +1,7 @@
/* eslint-disable import/no-cycle */
/* eslint-disable no-param-reassign */
import { DeleteResult, EntityManager, In, Not } from 'typeorm';
import { Db } from '..';
import { DeleteResult, EntityManager, FindManyOptions, In, Not } from 'typeorm';
import { Db, ICredentialsDb } from '..';
import { RoleService } from '../role/role.service';
import { CredentialsService } from './credentials.service';

View file

@ -7,7 +7,7 @@ import {
INodeCredentialTestResult,
LoggerProxy,
} from 'n8n-workflow';
import { FindOneOptions, In } from 'typeorm';
import { FindManyOptions, FindOneOptions, In } from 'typeorm';
import {
createCredentialsFromCredentialsEntity,
@ -71,6 +71,10 @@ export class CredentialsService {
});
}
static async getMany(filter: FindManyOptions<ICredentialsDb>): Promise<ICredentialsDb[]> {
return Db.collections.Credentials.find(filter);
}
/**
* Retrieve the sharing that matches a user and a credential.
*/

View file

@ -89,9 +89,11 @@ EEWorkflowController.get(
if (!userSharing && req.user.globalRole.name !== 'owner') {
throw new ResponseHelper.ResponseError(`Forbidden.`, undefined, 403);
}
// @TODO: also return the credentials used by the workflow
return EEWorkflows.addOwnerAndSharings(workflow);
return EEWorkflows.addCredentialsToWorkflow(
EEWorkflows.addOwnerAndSharings(workflow),
req.user,
);
}),
);

View file

@ -6,7 +6,7 @@ import { WorkflowEntity } from '../databases/entities/WorkflowEntity';
import { RoleService } from '../role/role.service';
import { UserService } from '../user/user.service';
import { WorkflowsService } from './workflows.services';
import { WorkflowWithSharings } from './workflows.types';
import type { WorkflowWithSharingsAndCredentials } from './workflows.types';
import { EECredentialsService as EECredentials } from '../credentials/credentials.service.ee';
export class EEWorkflowsService extends WorkflowsService {
@ -74,10 +74,11 @@ export class EEWorkflowsService extends WorkflowsService {
}
static addOwnerAndSharings(
workflow: WorkflowEntity & WorkflowWithSharings,
): WorkflowEntity & WorkflowWithSharings {
workflow: WorkflowWithSharingsAndCredentials,
): WorkflowWithSharingsAndCredentials {
workflow.ownedBy = null;
workflow.sharedWith = [];
workflow.usedCredentials = [];
workflow.shared?.forEach(({ user, role }) => {
const { id, email, firstName, lastName } = user;
@ -90,12 +91,49 @@ export class EEWorkflowsService extends WorkflowsService {
workflow.sharedWith?.push({ id, email, firstName, lastName });
});
// @ts-ignore
delete workflow.shared;
return workflow;
}
static async addCredentialsToWorkflow(
workflow: WorkflowWithSharingsAndCredentials,
currentUser: User,
): Promise<WorkflowWithSharingsAndCredentials> {
workflow.usedCredentials = [];
const userCredentials = await EECredentials.getAll(currentUser);
const credentialIdsUsedByWorkflow = new Set<number>();
workflow.nodes.forEach((node) => {
if (!node.credentials) {
return;
}
Object.keys(node.credentials).forEach((credentialType) => {
const credential = node.credentials?.[credentialType];
if (!credential?.id) {
return;
}
const credentialId = parseInt(credential.id, 10);
credentialIdsUsedByWorkflow.add(credentialId);
});
});
const workflowCredentials = await EECredentials.getMany({
where: {
id: In(Array.from(credentialIdsUsedByWorkflow)),
},
});
const userCredentialIds = userCredentials.map((credential) => credential.id.toString());
workflowCredentials.forEach((credential) => {
const credentialId = credential.id.toString();
workflow.usedCredentials?.push({
id: credential.id.toString(),
name: credential.name,
currentUserHasAccess: userCredentialIds.includes(credentialId),
});
});
return workflow;
}
static validateCredentialPermissionsToUser(
workflow: WorkflowEntity,
allowedCredentials: ICredentialsDb[],

View file

@ -1,7 +1,16 @@
import type { IUser } from 'n8n-workflow';
import { SharedWorkflow } from '../databases/entities/SharedWorkflow';
import { WorkflowEntity } from '../databases/entities/WorkflowEntity';
export interface WorkflowWithSharings extends WorkflowEntity {
export interface WorkflowWithSharingsAndCredentials extends Omit<WorkflowEntity, 'shared'> {
ownedBy?: IUser | null;
sharedWith?: IUser[];
usedCredentials?: CredentialUsedByWorkflow[];
shared?: SharedWorkflow[];
}
export interface CredentialUsedByWorkflow {
id: string;
name: string;
currentUserHasAccess: boolean;
}

View file

@ -213,6 +213,127 @@ describe('GET /workflows/:id', () => {
expect(response.body.data.sharedWith).toHaveLength(2);
});
test('GET should return workflow with credentials owned by user', async () => {
const owner = await testDb.createUser({ globalRole: globalOwnerRole });
const savedCredential = await saveCredential(randomCredentialPayload(), { user: owner });
const workflowPayload = makeWorkflow({
withPinData: false,
withCredential: { id: savedCredential.id.toString(), name: savedCredential.name },
});
const workflow = await createWorkflow(workflowPayload, owner);
const response = await authAgent(owner).get(`/workflows/${workflow.id}`);
expect(response.statusCode).toBe(200);
expect(response.body.data.usedCredentials).toMatchObject([
{
id: savedCredential.id.toString(),
name: savedCredential.name,
currentUserHasAccess: true,
},
]);
expect(response.body.data.sharedWith).toHaveLength(0);
});
test('GET should return workflow with credentials saying owner has access even when not shared', async () => {
const owner = await testDb.createUser({ globalRole: globalOwnerRole });
const member = await testDb.createUser({ globalRole: globalMemberRole });
const savedCredential = await saveCredential(randomCredentialPayload(), { user: member });
const workflowPayload = makeWorkflow({
withPinData: false,
withCredential: { id: savedCredential.id.toString(), name: savedCredential.name },
});
const workflow = await createWorkflow(workflowPayload, owner);
const response = await authAgent(owner).get(`/workflows/${workflow.id}`);
expect(response.statusCode).toBe(200);
expect(response.body.data.usedCredentials).toMatchObject([
{
id: savedCredential.id.toString(),
name: savedCredential.name,
currentUserHasAccess: true, // owner has access to any cred
},
]);
expect(response.body.data.sharedWith).toHaveLength(0);
});
test('GET should return workflow with credentials for all users with or without access', async () => {
const member1 = await testDb.createUser({ globalRole: globalMemberRole });
const member2 = await testDb.createUser({ globalRole: globalMemberRole });
const savedCredential = await saveCredential(randomCredentialPayload(), { user: member1 });
const workflowPayload = makeWorkflow({
withPinData: false,
withCredential: { id: savedCredential.id.toString(), name: savedCredential.name },
});
const workflow = await createWorkflow(workflowPayload, member1);
await testDb.shareWorkflowWithUsers(workflow, [member2]);
const responseMember1 = await authAgent(member1).get(`/workflows/${workflow.id}`);
expect(responseMember1.statusCode).toBe(200);
expect(responseMember1.body.data.usedCredentials).toMatchObject([
{
id: savedCredential.id.toString(),
name: savedCredential.name,
currentUserHasAccess: true, // one user has access
},
]);
expect(responseMember1.body.data.sharedWith).toHaveLength(1);
const responseMember2 = await authAgent(member2).get(`/workflows/${workflow.id}`);
expect(responseMember2.statusCode).toBe(200);
expect(responseMember2.body.data.usedCredentials).toMatchObject([
{
id: savedCredential.id.toString(),
name: savedCredential.name,
currentUserHasAccess: false, // the other one doesn't
},
]);
expect(responseMember2.body.data.sharedWith).toHaveLength(1);
});
test('GET should return workflow with credentials for all users with access', async () => {
const member1 = await testDb.createUser({ globalRole: globalMemberRole });
const member2 = await testDb.createUser({ globalRole: globalMemberRole });
const savedCredential = await saveCredential(randomCredentialPayload(), { user: member1 });
// Both users have access to the credential (none is owner)
await testDb.shareCredentialWithUsers(savedCredential, [member2]);
const workflowPayload = makeWorkflow({
withPinData: false,
withCredential: { id: savedCredential.id.toString(), name: savedCredential.name },
});
const workflow = await createWorkflow(workflowPayload, member1);
await testDb.shareWorkflowWithUsers(workflow, [member2]);
const responseMember1 = await authAgent(member1).get(`/workflows/${workflow.id}`);
expect(responseMember1.statusCode).toBe(200);
expect(responseMember1.body.data.usedCredentials).toMatchObject([
{
id: savedCredential.id.toString(),
name: savedCredential.name,
currentUserHasAccess: true,
},
]);
expect(responseMember1.body.data.sharedWith).toHaveLength(1);
const responseMember2 = await authAgent(member2).get(`/workflows/${workflow.id}`);
expect(responseMember2.statusCode).toBe(200);
expect(responseMember2.body.data.usedCredentials).toMatchObject([
{
id: savedCredential.id.toString(),
name: savedCredential.name,
currentUserHasAccess: true,
},
]);
expect(responseMember2.body.data.sharedWith).toHaveLength(1);
});
});
describe('POST /workflows', () => {