n8n/packages/cli/test/integration/workflows/workflows.controller.ee.test.ts

3076 lines
99 KiB
TypeScript

import {
createTeamProject,
getPersonalProject,
linkUserToProject,
createWorkflow,
createActiveWorkflow,
createWorkflowWithHistory,
createWorkflowHistory,
getWorkflowSharing,
shareWorkflowWithProjects,
shareWorkflowWithUsers,
randomCredentialPayload,
testDb,
mockInstance,
} from '@n8n/backend-test-utils';
import type {
CredentialsEntity,
Project,
User,
WorkflowEntity,
WorkflowWithSharingsMetaDataAndCredentials,
} from '@n8n/db';
import {
ProjectRepository,
WorkflowHistoryRepository,
SharedWorkflowRepository,
WorkflowRepository,
WorkflowPublishedVersionRepository,
CredentialsRepository,
GLOBAL_MEMBER_ROLE,
} from '@n8n/db';
import { Container } from '@n8n/di';
import type { ProjectRole } from '@n8n/permissions';
import { PERSONAL_SPACE_SHARING_SETTING } from '@n8n/permissions';
import {
UnexpectedError,
WorkflowActivationError,
calculateWorkflowChecksum,
type INode,
} from 'n8n-workflow';
import { ExecuteWorkflow } from 'n8n-nodes-base/nodes/ExecuteWorkflow/ExecuteWorkflow/ExecuteWorkflow.node';
import { v4 as uuid } from 'uuid';
import { ActiveWorkflowManager } from '@/active-workflow-manager';
import config from '@/config';
import { SecuritySettingsService } from '@/services/security-settings.service';
import { UserManagementMailer } from '@/user-management/email';
import { createFolder } from '@test-integration/db/folders';
import { createCustomRoleWithScopeSlugs } from '@test-integration/db/roles';
import {
affixRoleToSaveCredential,
getCredentialSharings,
shareCredentialWithProjects,
shareCredentialWithUsers,
} from '../shared/db/credentials';
import { createTag } from '../shared/db/tags';
import { createAdmin, createOwner, createUser, createUserShell } from '../shared/db/users';
import type { SaveCredentialFunction, SuperAgentTest } from '../shared/types';
import * as utils from '../shared/utils/';
import { makeWorkflow } from '../shared/utils/';
let owner: User;
let admin: User;
let ownerPersonalProject: Project;
let member: User;
let memberPersonalProject: Project;
let anotherMember: User;
let anotherMemberPersonalProject: Project;
let authOwnerAgent: SuperAgentTest;
let authMemberAgent: SuperAgentTest;
let authAnotherMemberAgent: SuperAgentTest;
let saveCredential: SaveCredentialFunction;
let projectRepository: ProjectRepository;
let workflowRepository: WorkflowRepository;
const activeWorkflowManager = mockInstance(ActiveWorkflowManager);
const testServer = utils.setupTestServer({
endpointGroups: ['workflows'],
enabledFeatures: ['feat:sharing', 'feat:advancedPermissions'],
});
const license = testServer.license;
const mailer = mockInstance(UserManagementMailer);
beforeAll(async () => {
projectRepository = Container.get(ProjectRepository);
workflowRepository = Container.get(WorkflowRepository);
owner = await createOwner();
admin = await createAdmin();
ownerPersonalProject = await projectRepository.getPersonalProjectForUserOrFail(owner.id);
member = await createUser({ role: { slug: 'global:member' } });
memberPersonalProject = await projectRepository.getPersonalProjectForUserOrFail(member.id);
anotherMember = await createUser({ role: { slug: 'global:member' } });
anotherMemberPersonalProject = await projectRepository.getPersonalProjectForUserOrFail(
anotherMember.id,
);
authOwnerAgent = testServer.authAgentFor(owner);
authMemberAgent = testServer.authAgentFor(member);
authAnotherMemberAgent = testServer.authAgentFor(anotherMember);
saveCredential = affixRoleToSaveCredential('credential:owner');
// Use the real node description to test parameter defaults and visibility.
await utils.initNodeTypes({
...utils.buildDefaultNodes(),
'n8n-nodes-base.executeWorkflow': { type: new ExecuteWorkflow(), sourcePath: '' },
});
});
beforeEach(async () => {
activeWorkflowManager.add.mockReset();
activeWorkflowManager.remove.mockReset();
await testDb.truncate([
'WorkflowEntity',
'SharedWorkflow',
'WorkflowHistory',
'WorkflowPublishHistory',
'TagEntity',
]);
});
afterEach(() => {
vi.clearAllMocks();
});
describe('router should switch based on flag', () => {
let savedWorkflowId: string;
beforeEach(async () => {
const createWorkflowResponse = await authOwnerAgent.post('/workflows').send(makeWorkflow());
savedWorkflowId = createWorkflowResponse.body.data.id;
});
test('when sharing is disabled', async () => {
license.disable('feat:sharing');
await authOwnerAgent
.put(`/workflows/${savedWorkflowId}/share`)
.send({ shareWithIds: [memberPersonalProject.id] })
.expect(403);
});
test('when sharing is enabled', async () => {
license.enable('feat:sharing');
await authOwnerAgent
.put(`/workflows/${savedWorkflowId}/share`)
.send({ shareWithIds: [memberPersonalProject.id] })
.expect(200);
});
});
describe('PUT /workflows/:workflowId/share', () => {
test('should save sharing with new users', async () => {
const workflow = await createWorkflow({}, owner);
const response = await authOwnerAgent
.put(`/workflows/${workflow.id}/share`)
.send({ shareWithIds: [memberPersonalProject.id] });
expect(response.statusCode).toBe(200);
const sharedWorkflows = await getWorkflowSharing(workflow);
expect(sharedWorkflows).toHaveLength(2);
expect(mailer.notifyWorkflowShared).toHaveBeenCalledTimes(1);
expect(mailer.notifyWorkflowShared).toHaveBeenCalledWith(
expect.objectContaining({
newShareeIds: [member.id],
sharer: expect.objectContaining({ id: owner.id }),
workflow: expect.objectContaining({ id: workflow.id }),
}),
);
});
test('should succeed when sharing with invalid user-id', async () => {
const workflow = await createWorkflow({}, owner);
const response = await authOwnerAgent
.put(`/workflows/${workflow.id}/share`)
.send({ shareWithIds: [uuid()] });
expect(response.statusCode).toBe(200);
const sharedWorkflows = await getWorkflowSharing(workflow);
expect(sharedWorkflows).toHaveLength(1);
});
test('should allow sharing with pending users', async () => {
const workflow = await createWorkflow({}, owner);
const memberShell = await createUserShell(GLOBAL_MEMBER_ROLE);
const memberShellPersonalProject = await projectRepository.getPersonalProjectForUserOrFail(
memberShell.id,
);
const response = await authOwnerAgent
.put(`/workflows/${workflow.id}/share`)
.send({ shareWithIds: [memberShellPersonalProject.id] });
expect(response.statusCode).toBe(200);
const sharedWorkflows = await getWorkflowSharing(workflow);
expect(sharedWorkflows).toHaveLength(2);
expect(mailer.notifyWorkflowShared).toHaveBeenCalledTimes(1);
});
test('should allow sharing with multiple users', async () => {
const workflow = await createWorkflow({}, owner);
const response = await authOwnerAgent
.put(`/workflows/${workflow.id}/share`)
.send({ shareWithIds: [memberPersonalProject.id, anotherMemberPersonalProject.id] });
expect(response.statusCode).toBe(200);
const sharedWorkflows = await getWorkflowSharing(workflow);
expect(sharedWorkflows).toHaveLength(3);
expect(mailer.notifyWorkflowShared).toHaveBeenCalledTimes(1);
});
test('should override sharing', async () => {
const workflow = await createWorkflow({}, owner);
const response = await authOwnerAgent
.put(`/workflows/${workflow.id}/share`)
.send({ shareWithIds: [memberPersonalProject.id, anotherMemberPersonalProject.id] });
expect(response.statusCode).toBe(200);
const sharedWorkflows = await getWorkflowSharing(workflow);
expect(sharedWorkflows).toHaveLength(3);
const secondResponse = await authOwnerAgent
.put(`/workflows/${workflow.id}/share`)
.send({ shareWithIds: [memberPersonalProject.id] });
expect(secondResponse.statusCode).toBe(200);
const secondSharedWorkflows = await getWorkflowSharing(workflow);
expect(secondSharedWorkflows).toHaveLength(2);
expect(mailer.notifyWorkflowShared).toHaveBeenCalledTimes(2);
});
test('should allow sharing by the owner of the workflow', async () => {
const workflow = await createWorkflow({}, member);
const response = await authMemberAgent
.put(`/workflows/${workflow.id}/share`)
.send({ shareWithIds: [anotherMemberPersonalProject.id] });
expect(response.statusCode).toBe(200);
const sharedWorkflows = await getWorkflowSharing(workflow);
expect(sharedWorkflows).toHaveLength(2);
expect(mailer.notifyWorkflowShared).toHaveBeenCalledTimes(1);
});
test('should allow sharing by the instance owner', async () => {
const workflow = await createWorkflow({}, member);
const response = await authOwnerAgent
.put(`/workflows/${workflow.id}/share`)
.send({ shareWithIds: [anotherMemberPersonalProject.id] });
expect(response.statusCode).toBe(200);
const sharedWorkflows = await getWorkflowSharing(workflow);
expect(sharedWorkflows).toHaveLength(2);
expect(mailer.notifyWorkflowShared).toHaveBeenCalledTimes(1);
});
test('should not allow sharing by another shared member', async () => {
const workflow = await createWorkflow({}, member);
await shareWorkflowWithUsers(workflow, [anotherMember]);
const response = await authAnotherMemberAgent
.put(`/workflows/${workflow.id}/share`)
.send({ shareWithIds: [anotherMemberPersonalProject.id, ownerPersonalProject.id] });
expect(response.statusCode).toBe(403);
const sharedWorkflows = await getWorkflowSharing(workflow);
expect(sharedWorkflows).toHaveLength(2);
expect(mailer.notifyWorkflowShared).toHaveBeenCalledTimes(0);
});
test('should not allow sharing with self by another non-shared member', async () => {
const workflow = await createWorkflow({}, member);
const response = await authAnotherMemberAgent
.put(`/workflows/${workflow.id}/share`)
.send({ shareWithIds: [anotherMemberPersonalProject.id] });
expect(response.statusCode).toBe(403);
const sharedWorkflows = await getWorkflowSharing(workflow);
expect(sharedWorkflows).toHaveLength(1);
expect(mailer.notifyWorkflowShared).toHaveBeenCalledTimes(0);
});
test('should not allow sharing by another non-shared member', async () => {
const workflow = await createWorkflow({}, member);
const tempUser = await createUser({ role: { slug: 'global:member' } });
const tempUserPersonalProject = await projectRepository.getPersonalProjectForUserOrFail(
tempUser.id,
);
const response = await authAnotherMemberAgent
.put(`/workflows/${workflow.id}/share`)
.send({ shareWithIds: [tempUserPersonalProject.id] });
expect(response.statusCode).toBe(403);
const sharedWorkflows = await getWorkflowSharing(workflow);
expect(sharedWorkflows).toHaveLength(1);
expect(mailer.notifyWorkflowShared).toHaveBeenCalledTimes(0);
});
test('should not call internal hooks listener for email sent if emailing is disabled', async () => {
config.set('userManagement.emails.mode', '');
const workflow = await createWorkflow({}, owner);
const response = await authOwnerAgent
.put(`/workflows/${workflow.id}/share`)
.send({ shareWithIds: [memberPersonalProject.id] });
expect(response.statusCode).toBe(200);
config.set('userManagement.emails.mode', 'smtp');
});
test('should ignore sharing with owner project', async () => {
// ARRANGE
const project = ownerPersonalProject;
const workflow = await createWorkflow({ name: 'My workflow' }, project);
await authOwnerAgent
.put(`/workflows/${workflow.id}/share`)
.send({ shareWithIds: [project.id] })
.expect(200);
const sharedWorkflows = await Container.get(SharedWorkflowRepository).findBy({
workflowId: workflow.id,
});
expect(sharedWorkflows).toHaveLength(1);
expect(sharedWorkflows).toEqual([
expect.objectContaining({ projectId: project.id, role: 'workflow:owner' }),
]);
});
test('should ignore sharing with project that already has it shared', async () => {
// ARRANGE
const project = ownerPersonalProject;
const workflow = await createWorkflow({ name: 'My workflow' }, project);
const project2 = memberPersonalProject;
await shareWorkflowWithProjects(workflow, [{ project: project2 }]);
await authOwnerAgent
.put(`/workflows/${workflow.id}/share`)
.send({ shareWithIds: [project2.id] })
.expect(200);
const sharedWorkflows = await Container.get(SharedWorkflowRepository).findBy({
workflowId: workflow.id,
});
expect(sharedWorkflows).toHaveLength(2);
expect(sharedWorkflows).toEqual(
expect.arrayContaining([
expect.objectContaining({ projectId: project.id, role: 'workflow:owner' }),
expect.objectContaining({ projectId: project2.id, role: 'workflow:editor' }),
]),
);
});
});
describe('PUT /workflows/:workflowId/share - split share/unshare scopes', () => {
test('should allow owner to add new shares (share operation)', async () => {
const workflow = await createWorkflow({}, member);
const response = await authMemberAgent
.put(`/workflows/${workflow.id}/share`)
.send({ shareWithIds: [anotherMemberPersonalProject.id] });
expect(response.statusCode).toBe(200);
const sharedWorkflows = await getWorkflowSharing(workflow);
expect(sharedWorkflows).toHaveLength(2);
});
test('should allow owner to remove existing shares (unshare operation)', async () => {
const workflow = await createWorkflow({}, member);
await shareWorkflowWithUsers(workflow, [anotherMember]);
// Verify initial state: owner + 1 shared
const initialSharing = await getWorkflowSharing(workflow);
expect(initialSharing).toHaveLength(2);
// Send empty shareWithIds to remove all shares
const response = await authMemberAgent
.put(`/workflows/${workflow.id}/share`)
.send({ shareWithIds: [] });
expect(response.statusCode).toBe(200);
const sharedWorkflows = await getWorkflowSharing(workflow);
expect(sharedWorkflows).toHaveLength(1);
});
test('should allow both share and unshare in a single request', async () => {
const workflow = await createWorkflow({}, owner);
await shareWorkflowWithUsers(workflow, [member]);
// Replace member with anotherMember (unshare member, share anotherMember)
const response = await authOwnerAgent
.put(`/workflows/${workflow.id}/share`)
.send({ shareWithIds: [anotherMemberPersonalProject.id] });
expect(response.statusCode).toBe(200);
const sharedWorkflows = await getWorkflowSharing(workflow);
expect(sharedWorkflows).toHaveLength(2);
const projectIds = sharedWorkflows.map((sw) => sw.projectId);
expect(projectIds).toContain(anotherMemberPersonalProject.id);
expect(projectIds).not.toContain(memberPersonalProject.id);
});
describe('personal space sharing disabled', () => {
let securitySettingsService: SecuritySettingsService;
beforeEach(async () => {
securitySettingsService = Container.get(SecuritySettingsService);
});
test('should forbid adding new shares when personal space sharing is disabled', async () => {
await securitySettingsService.setPersonalSpaceSetting(PERSONAL_SPACE_SHARING_SETTING, false);
const workflow = await createWorkflow({}, member);
const response = await authMemberAgent
.put(`/workflows/${workflow.id}/share`)
.send({ shareWithIds: [anotherMemberPersonalProject.id] });
expect(response.statusCode).toBe(403);
const sharedWorkflows = await getWorkflowSharing(workflow);
expect(sharedWorkflows).toHaveLength(1);
// Re-enable for cleanup
await securitySettingsService.setPersonalSpaceSetting(PERSONAL_SPACE_SHARING_SETTING, true);
});
test('should allow removing existing shares when personal space sharing is disabled', async () => {
const workflow = await createWorkflow({}, member);
await shareWorkflowWithUsers(workflow, [anotherMember]);
// Verify initial state
const initialSharing = await getWorkflowSharing(workflow);
expect(initialSharing).toHaveLength(2);
// Disable personal space sharing
await securitySettingsService.setPersonalSpaceSetting(PERSONAL_SPACE_SHARING_SETTING, false);
// Unshare should still work
const response = await authMemberAgent
.put(`/workflows/${workflow.id}/share`)
.send({ shareWithIds: [] });
expect(response.statusCode).toBe(200);
const sharedWorkflows = await getWorkflowSharing(workflow);
expect(sharedWorkflows).toHaveLength(1);
// Re-enable for cleanup
await securitySettingsService.setPersonalSpaceSetting(PERSONAL_SPACE_SHARING_SETTING, true);
});
test('should forbid mixed share+unshare when user lacks share scope', async () => {
const workflow = await createWorkflow({}, member);
await shareWorkflowWithUsers(workflow, [anotherMember]);
// Disable sharing
await securitySettingsService.setPersonalSpaceSetting(PERSONAL_SPACE_SHARING_SETTING, false);
const tempUser = await createUser({ role: { slug: 'global:member' } });
const tempUserPersonalProject = await projectRepository.getPersonalProjectForUserOrFail(
tempUser.id,
);
// Try to unshare anotherMember AND share tempUser - should fail because of share
const response = await authMemberAgent
.put(`/workflows/${workflow.id}/share`)
.send({ shareWithIds: [tempUserPersonalProject.id] });
expect(response.statusCode).toBe(403);
// State should be unchanged
const sharedWorkflows = await getWorkflowSharing(workflow);
expect(sharedWorkflows).toHaveLength(2);
// Re-enable for cleanup
await securitySettingsService.setPersonalSpaceSetting(PERSONAL_SPACE_SHARING_SETTING, true);
});
});
});
describe('GET /workflows/new', () => {
[true, false].forEach((sharingEnabled) => {
test(`should return an auto-incremented name, even when sharing is ${
sharingEnabled ? 'enabled' : 'disabled'
}`, async () => {
license.enable('feat:sharing');
await createWorkflow({ name: 'My workflow' }, owner);
await createWorkflow({ name: 'My workflow 7' }, owner);
const response = await authOwnerAgent.get('/workflows/new').query({
projectId: ownerPersonalProject.id,
});
expect(response.statusCode).toBe(200);
expect(response.body.data.name).toEqual('My workflow 8');
});
});
test('should return 403 when user does not have workflow:create permission in the project', async () => {
const teamProject = await createTeamProject();
await linkUserToProject(member, teamProject, 'project:viewer');
const response = await authMemberAgent
.get('/workflows/new')
.query({
projectId: teamProject.id,
})
.expect(403);
expect(response.body).toMatchObject({
message: "You don't have the permissions to create a workflow in this project.",
});
});
test('should return 403 when user is not part of the project', async () => {
const teamProject = await createTeamProject();
await linkUserToProject(anotherMember, teamProject, 'project:admin');
const response = await authMemberAgent
.get('/workflows/new')
.query({
projectId: teamProject.id,
})
.expect(403);
expect(response.body).toMatchObject({
message: "You don't have the permissions to create a workflow in this project.",
});
});
test('should allow user with workflow:create permission in personal project', async () => {
await createWorkflow({ name: 'My workflow' }, member);
const response = await authMemberAgent
.get('/workflows/new')
.query({
projectId: memberPersonalProject.id,
})
.expect(200);
expect(response.body.data.name).toEqual('My workflow 2');
});
test('should allow user with workflow:create permission in team project', async () => {
const teamProject = await createTeamProject();
await linkUserToProject(member, teamProject, 'project:editor');
const response = await authMemberAgent
.get('/workflows/new')
.query({
projectId: teamProject.id,
})
.expect(200);
// The naming service generates unique names globally, not per-project
expect(response.body.data.name).toBeDefined();
expect(typeof response.body.data.name).toBe('string');
});
test('should allow project admin to get new workflow name', async () => {
const teamProject = await createTeamProject();
await linkUserToProject(member, teamProject, 'project:admin');
const response = await authMemberAgent
.get('/workflows/new')
.query({
projectId: teamProject.id,
})
.expect(200);
expect(response.body.data.name).toBeDefined();
});
test('should allow instance owner to get new workflow name for any project', async () => {
const teamProject = await createTeamProject();
await linkUserToProject(anotherMember, teamProject, 'project:admin');
const response = await authOwnerAgent
.get('/workflows/new')
.query({
projectId: teamProject.id,
})
.expect(200);
expect(response.body.data.name).toBeDefined();
});
});
describe('GET /workflows/from-url', () => {
test('should return 403 when user does not have workflow:create permission in the project', async () => {
const teamProject = await createTeamProject();
await linkUserToProject(member, teamProject, 'project:viewer');
const response = await authMemberAgent
.get('/workflows/from-url')
.query({
url: 'https://example.com/workflow.json',
projectId: teamProject.id,
})
.expect(403);
expect(response.body).toMatchObject({
message: "You don't have the permissions to create a workflow in this project.",
});
});
test('should return 403 when user is not part of the project', async () => {
const teamProject = await createTeamProject();
await linkUserToProject(anotherMember, teamProject, 'project:admin');
const response = await authMemberAgent
.get('/workflows/from-url')
.query({
url: 'https://example.com/workflow.json',
projectId: teamProject.id,
})
.expect(403);
expect(response.body).toMatchObject({
message: "You don't have the permissions to create a workflow in this project.",
});
});
});
describe('GET /workflows/:workflowId', () => {
test('should fail with invalid id due to route rule', async () => {
const response = await authOwnerAgent.get('/workflows/potatoes');
expect(response.statusCode).toBe(404);
});
test('should return 404 for non existing workflow', async () => {
const response = await authOwnerAgent.get('/workflows/9001');
expect(response.statusCode).toBe(404);
});
test('project viewers can view workflows', async () => {
const teamProject = await createTeamProject();
await linkUserToProject(member, teamProject, 'project:viewer');
const workflow = await createWorkflow({}, teamProject);
const response = await authMemberAgent.get(`/workflows/${workflow.id}`).expect(200);
const responseWorkflow: WorkflowWithSharingsMetaDataAndCredentials = response.body.data;
expect(responseWorkflow.homeProject).toMatchObject({
id: teamProject.id,
name: teamProject.name,
type: 'team',
});
expect(responseWorkflow.sharedWithProjects).toHaveLength(0);
});
test('should return a workflow with owner', async () => {
const workflow = await createWorkflow({}, owner);
const response = await authOwnerAgent.get(`/workflows/${workflow.id}`).expect(200);
const responseWorkflow: WorkflowWithSharingsMetaDataAndCredentials = response.body.data;
expect(responseWorkflow.homeProject).toMatchObject({
id: ownerPersonalProject.id,
name: owner.createPersonalProjectName(),
type: 'personal',
});
expect(responseWorkflow.sharedWithProjects).toHaveLength(0);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((responseWorkflow as any).shared).toBeUndefined();
});
test('should return tags', async () => {
const tag = await createTag({ name: 'A' });
const workflow = await createWorkflow({ tags: [tag] }, owner);
const response = await authOwnerAgent.get(`/workflows/${workflow.id}`).expect(200);
expect(response.body.data).toMatchObject({
tags: [expect.objectContaining({ id: tag.id, name: tag.name })],
});
});
test('should return shared workflow with user data', async () => {
const workflow = await createWorkflow({}, owner);
await shareWorkflowWithUsers(workflow, [member]);
const response = await authOwnerAgent.get(`/workflows/${workflow.id}`).expect(200);
const responseWorkflow: WorkflowWithSharingsMetaDataAndCredentials = response.body.data;
expect(responseWorkflow.homeProject).toMatchObject({
id: ownerPersonalProject.id,
name: owner.createPersonalProjectName(),
type: 'personal',
});
expect(responseWorkflow.sharedWithProjects).toHaveLength(1);
expect(responseWorkflow.sharedWithProjects[0]).toMatchObject({
id: memberPersonalProject.id,
name: member.createPersonalProjectName(),
type: 'personal',
});
});
test('should return all sharees', async () => {
const workflow = await createWorkflow({}, owner);
await shareWorkflowWithUsers(workflow, [member, anotherMember]);
const response = await authOwnerAgent.get(`/workflows/${workflow.id}`).expect(200);
const responseWorkflow: WorkflowWithSharingsMetaDataAndCredentials = response.body.data;
expect(responseWorkflow.homeProject).toMatchObject({
id: ownerPersonalProject.id,
name: owner.createPersonalProjectName(),
type: 'personal',
});
expect(responseWorkflow.sharedWithProjects).toHaveLength(2);
});
test('should return workflow with credentials owned by user', async () => {
const savedCredential = await saveCredential(randomCredentialPayload(), { user: owner });
const workflowPayload = makeWorkflow({
withPinData: false,
withCredential: { id: savedCredential.id, name: savedCredential.name },
});
const workflow = await createWorkflow(workflowPayload, owner);
const response = await authOwnerAgent.get(`/workflows/${workflow.id}`).expect(200);
const responseWorkflow: WorkflowWithSharingsMetaDataAndCredentials = response.body.data;
expect(response.statusCode).toBe(200);
expect(responseWorkflow.usedCredentials).toMatchObject([
{
id: savedCredential.id,
name: savedCredential.name,
currentUserCanUse: true,
},
]);
expect(responseWorkflow.sharedWithProjects).toHaveLength(0);
});
test.each([
['owner', () => owner],
['admin', () => admin],
])(
'should return workflow with credentials saying %s can use them even when not shared',
async (_description, getActor) => {
const actor = getActor();
const savedCredential = await saveCredential(randomCredentialPayload(), { user: member });
const workflowPayload = makeWorkflow({
withPinData: false,
withCredential: { id: savedCredential.id, name: savedCredential.name },
});
const workflow = await createWorkflow(workflowPayload, actor);
const response = await testServer
.authAgentFor(actor)
.get(`/workflows/${workflow.id}`)
.expect(200);
const responseWorkflow: WorkflowWithSharingsMetaDataAndCredentials = response.body.data;
expect(responseWorkflow.usedCredentials).toMatchObject([
{
id: savedCredential.id,
name: savedCredential.name,
currentUserCanUse: true,
},
]);
expect(responseWorkflow.sharedWithProjects).toHaveLength(0);
},
);
test('should return workflow with credentials for all users whether or not they can use them', async () => {
const savedCredential = await saveCredential(randomCredentialPayload(), { user: member });
const workflowPayload = makeWorkflow({
withPinData: false,
withCredential: { id: savedCredential.id, name: savedCredential.name },
});
const workflow = await createWorkflow(workflowPayload, member);
await shareWorkflowWithUsers(workflow, [anotherMember]);
const responseMember1 = await authMemberAgent.get(`/workflows/${workflow.id}`).expect(200);
const member1Workflow: WorkflowWithSharingsMetaDataAndCredentials = responseMember1.body.data;
expect(member1Workflow.usedCredentials).toMatchObject([
{
id: savedCredential.id,
name: savedCredential.name,
currentUserCanUse: true, // one user can use it
},
]);
expect(member1Workflow.sharedWithProjects).toHaveLength(1);
const responseMember2 = await authAnotherMemberAgent
.get(`/workflows/${workflow.id}`)
.expect(200);
const member2Workflow: WorkflowWithSharingsMetaDataAndCredentials = responseMember2.body.data;
expect(member2Workflow.usedCredentials).toMatchObject([
{
id: savedCredential.id,
name: savedCredential.name,
currentUserCanUse: false, // the other one can't
},
]);
expect(member2Workflow.sharedWithProjects).toHaveLength(1);
});
test('should return workflow with credentials for all users who can use them', async () => {
const savedCredential = await saveCredential(randomCredentialPayload(), { user: member });
// Both users can use the credential (none is owner)
await shareCredentialWithUsers(savedCredential, [anotherMember]);
const workflowPayload = makeWorkflow({
withPinData: false,
withCredential: { id: savedCredential.id, name: savedCredential.name },
});
const workflow = await createWorkflow(workflowPayload, member);
await shareWorkflowWithUsers(workflow, [anotherMember]);
const responseMember1 = await authMemberAgent.get(`/workflows/${workflow.id}`).expect(200);
const member1Workflow: WorkflowWithSharingsMetaDataAndCredentials = responseMember1.body.data;
expect(member1Workflow.usedCredentials).toMatchObject([
{
id: savedCredential.id,
name: savedCredential.name,
currentUserCanUse: true,
},
]);
expect(member1Workflow.sharedWithProjects).toHaveLength(1);
const responseMember2 = await authAnotherMemberAgent
.get(`/workflows/${workflow.id}`)
.expect(200);
const member2Workflow: WorkflowWithSharingsMetaDataAndCredentials = responseMember2.body.data;
expect(responseMember2.statusCode).toBe(200);
expect(member2Workflow.usedCredentials).toMatchObject([
{
id: savedCredential.id,
name: savedCredential.name,
currentUserCanUse: true,
},
]);
expect(member2Workflow.sharedWithProjects).toHaveLength(1);
});
test('should return workflow credentials home project and shared with projects', async () => {
const savedCredential = await saveCredential(randomCredentialPayload(), { user: member });
// Both users can use the credential (none is owner)
await shareCredentialWithUsers(savedCredential, [anotherMember]);
const workflowPayload = makeWorkflow({
withPinData: false,
withCredential: { id: savedCredential.id, name: savedCredential.name },
});
const workflow = await createWorkflow(workflowPayload, member);
await shareWorkflowWithUsers(workflow, [anotherMember]);
const responseMember1 = await authMemberAgent.get(`/workflows/${workflow.id}`).expect(200);
const member1Workflow: WorkflowWithSharingsMetaDataAndCredentials = responseMember1.body.data;
expect(member1Workflow.usedCredentials).toMatchObject([
{
id: savedCredential.id,
name: savedCredential.name,
currentUserCanUse: true,
homeProject: {
id: memberPersonalProject.id,
},
sharedWithProjects: [{ id: anotherMemberPersonalProject.id }],
},
]);
expect(member1Workflow.sharedWithProjects).toHaveLength(1);
});
describe('with N8N_ENV_FEAT_CRED_SHARING enabled', () => {
beforeEach(() => {
process.env.N8N_ENV_FEAT_CRED_SHARING = 'true';
});
afterEach(() => {
delete process.env.N8N_ENV_FEAT_CRED_SHARING;
});
test('reports currentUserCanUse from the identity-based check', async () => {
const savedCredential = await saveCredential(randomCredentialPayload(), { user: owner });
const workflowPayload = makeWorkflow({
withPinData: false,
withCredential: { id: savedCredential.id, name: savedCredential.name },
});
const workflow = await createWorkflow(workflowPayload, owner);
const response = await authOwnerAgent.get(`/workflows/${workflow.id}`).expect(200);
const responseWorkflow: WorkflowWithSharingsMetaDataAndCredentials = response.body.data;
expect(responseWorkflow.usedCredentials).toMatchObject([
{
id: savedCredential.id,
name: savedCredential.name,
currentUserCanUse: true,
},
]);
});
test('describes a referenced credential the user cannot use, unconditionally', async () => {
const savedCredential = await saveCredential(randomCredentialPayload(), { user: member });
const workflowPayload = makeWorkflow({
withPinData: false,
withCredential: { id: savedCredential.id, name: savedCredential.name },
});
const workflow = await createWorkflow(workflowPayload, member);
await shareWorkflowWithUsers(workflow, [anotherMember]);
const response = await authAnotherMemberAgent.get(`/workflows/${workflow.id}`).expect(200);
const responseWorkflow: WorkflowWithSharingsMetaDataAndCredentials = response.body.data;
// Visible regardless of access: name, type and owner are unconditional.
expect(responseWorkflow.usedCredentials).toMatchObject([
{
id: savedCredential.id,
name: savedCredential.name,
currentUserCanUse: false,
},
]);
});
describe('the Owner in a team-project workflow', () => {
const ownerSees = async (
credentialId: string,
teamProject: Project,
sharedWith: Project[] = [],
) => {
const workflow = await createWorkflow(
makeWorkflow({
withPinData: false,
withCredential: { id: credentialId, name: 'Credential' },
}),
teamProject,
);
if (sharedWith.length > 0) {
await shareWorkflowWithProjects(
workflow,
sharedWith.map((project) => ({ project })),
);
}
const response = await authOwnerAgent.get(`/workflows/${workflow.id}`).expect(200);
const responseWorkflow: WorkflowWithSharingsMetaDataAndCredentials = response.body.data;
return responseWorkflow.usedCredentials?.[0]?.currentUserCanUse;
};
test('cannot use a personal credential that nobody shared with the project', async () => {
const teamProject = await createTeamProject('Marketing', member);
const credential = await saveCredential(randomCredentialPayload(), { user: member });
expect(await ownerSees(credential.id, teamProject)).toBe(false);
});
test('can use a credential shared with another team project the workflow is in', async () => {
const teamProject = await createTeamProject('Marketing', member);
const salesProject = await createTeamProject('Sales', member);
const credential = await saveCredential(randomCredentialPayload(), { user: member });
await shareCredentialWithProjects(credential, [salesProject]);
expect(await ownerSees(credential.id, teamProject, [salesProject])).toBe(true);
});
test('cannot use the personal credential of someone the workflow is shared with', async () => {
const teamProject = await createTeamProject('Marketing', member);
const credential = await saveCredential(randomCredentialPayload(), { user: member });
const memberPersonalProject = await getPersonalProject(member);
expect(await ownerSees(credential.id, teamProject, [memberPersonalProject])).toBe(false);
});
test('can use a credential shared with the project', async () => {
const teamProject = await createTeamProject('Marketing', member);
const credential = await saveCredential(randomCredentialPayload(), { user: member });
await shareCredentialWithProjects(credential, [teamProject]);
expect(await ownerSees(credential.id, teamProject)).toBe(true);
});
test('can use a credential shared with everyone', async () => {
const teamProject = await createTeamProject('Marketing', member);
const credential = await saveCredential(
{ ...randomCredentialPayload(), isGlobal: true },
{ user: member },
);
expect(await ownerSees(credential.id, teamProject)).toBe(true);
});
});
});
});
describe('POST /workflows', () => {
test('project viewers cannot create workflows', async () => {
const teamProject = await createTeamProject();
await linkUserToProject(member, teamProject, 'project:viewer');
const response = await authMemberAgent
.post('/workflows')
.send({ ...makeWorkflow(), projectId: teamProject.id });
expect(response.statusCode).toBe(400);
expect(response.body).toMatchObject({
code: 400,
message: "You don't have the permissions to save the workflow in this project.",
});
});
it('Should create a workflow that uses no credential', async () => {
const workflow = makeWorkflow({ withPinData: false });
const response = await authOwnerAgent.post('/workflows').send(workflow);
expect(response.statusCode).toBe(200);
});
it('Should save a new workflow with credentials', async () => {
const savedCredential = await saveCredential(randomCredentialPayload(), { user: owner });
const workflow = makeWorkflow({
withPinData: false,
withCredential: { id: savedCredential.id, name: savedCredential.name },
});
const response = await authOwnerAgent.post('/workflows').send(workflow);
expect(response.statusCode).toBe(200);
});
it('Should not allow saving a workflow using credential you have no access', async () => {
// Credential belongs to owner, member cannot use it.
const savedCredential = await saveCredential(randomCredentialPayload(), { user: owner });
const workflow = makeWorkflow({
withPinData: false,
withCredential: { id: savedCredential.id, name: savedCredential.name },
});
const response = await authMemberAgent.post('/workflows').send(workflow);
expect(response.statusCode).toBe(400);
expect(response.body.message).toBe(
'The workflow you are trying to save contains credentials that are not shared with you',
);
});
it('Should allow owner to save a workflow using credential owned by others', async () => {
// Credential belongs to owner, member cannot use it.
const savedCredential = await saveCredential(randomCredentialPayload(), { user: member });
const workflow = makeWorkflow({
withPinData: false,
withCredential: { id: savedCredential.id, name: savedCredential.name },
});
const response = await authOwnerAgent.post('/workflows').send(workflow);
expect(response.statusCode).toBe(200);
});
it('Should allow saving a workflow using a credential owned by others and shared with you', async () => {
const savedCredential = await saveCredential(randomCredentialPayload(), { user: member });
await shareCredentialWithUsers(savedCredential, [anotherMember]);
const workflow = makeWorkflow({
withPinData: false,
withCredential: { id: savedCredential.id, name: savedCredential.name },
});
const response = await authAnotherMemberAgent.post('/workflows').send(workflow);
expect(response.statusCode).toBe(200);
});
test('Should always create workflow history version', async () => {
const payload = {
name: 'testing',
nodes: [
{
id: 'uuid-1234',
parameters: {},
name: 'Start',
type: 'n8n-nodes-base.manualTrigger',
typeVersion: 1,
position: [240, 300],
},
],
connections: {},
staticData: null,
settings: {
saveExecutionProgress: true,
saveManualExecutions: true,
saveDataErrorExecution: 'all',
saveDataSuccessExecution: 'all',
executionTimeout: 3600,
timezone: 'America/New_York',
},
active: false,
};
const response = await authOwnerAgent.post('/workflows').send(payload);
expect(response.statusCode).toBe(200);
const {
data: { id },
} = response.body;
expect(id).toBeDefined();
expect(
await Container.get(WorkflowHistoryRepository).count({ where: { workflowId: id } }),
).toBe(1);
const historyVersion = await Container.get(WorkflowHistoryRepository).findOne({
where: {
workflowId: id,
},
});
expect(historyVersion).not.toBeNull();
expect(historyVersion!.connections).toEqual(payload.connections);
expect(historyVersion!.nodes).toEqual(payload.nodes);
});
});
describe('PATCH /workflows/:workflowId', () => {
test('project viewers cannot update workflows', async () => {
const teamProject = await createTeamProject();
await linkUserToProject(member, teamProject, 'project:viewer');
const workflow = await createWorkflow({ name: 'WF Name' }, teamProject);
const response = await authMemberAgent
.patch(`/workflows/${workflow.id}`)
.send({ ...workflow, name: 'New Name' });
expect(response.status).toBe(403);
expect(response.body).toMatchObject({
message: 'User is missing a scope required to perform this action',
});
});
describe('validate credential permissions to user', () => {
it('Should succeed when saving unchanged workflow nodes', async () => {
const savedCredential = await saveCredential(randomCredentialPayload(), { user: owner });
const workflow = {
name: 'test',
active: false,
connections: {},
nodes: [
{
id: 'uuid-1234',
name: 'Start',
parameters: {},
position: [-20, 260],
type: 'n8n-nodes-base.manualTrigger',
typeVersion: 1,
credentials: {
default: {
id: savedCredential.id,
name: savedCredential.name,
},
},
},
],
};
const createResponse = await authOwnerAgent.post('/workflows').send(workflow);
const { id, versionId } = createResponse.body.data;
const response = await authOwnerAgent.patch(`/workflows/${id}`).send({
name: 'new name',
versionId,
});
expect(response.statusCode).toBe(200);
});
it('Should allow owner to add node containing credential not shared with the owner', async () => {
const savedCredential = await saveCredential(randomCredentialPayload(), { user: member });
const workflow = {
name: 'test',
active: false,
connections: {},
nodes: [
{
id: 'uuid-1234',
name: 'Start',
parameters: {},
position: [-20, 260],
type: 'n8n-nodes-base.manualTrigger',
typeVersion: 1,
credentials: {
default: {
id: savedCredential.id,
name: savedCredential.name,
},
},
},
],
};
const createResponse = await authOwnerAgent.post('/workflows').send(workflow);
const { id, versionId } = createResponse.body.data;
const response = await authOwnerAgent.patch(`/workflows/${id}`).send({
versionId,
nodes: [
{
id: 'uuid-1234',
name: 'Start',
parameters: {},
position: [-20, 260],
type: 'n8n-nodes-base.manualTrigger',
typeVersion: 1,
credentials: {
default: {
id: savedCredential.id,
name: savedCredential.name,
},
},
},
],
});
expect(response.statusCode).toBe(200);
});
it.each([
[
'the owner and shared with the member',
'the owner',
async function creteWorkflow() {
const workflow = await createWorkflow({}, owner);
await shareWorkflowWithUsers(workflow, [member]);
return workflow;
},
async function createCredential() {
return await saveCredential(randomCredentialPayload(), { user: owner });
},
],
[
'team 1',
'the member',
async function creteWorkflow() {
const team = await createTeamProject('Team 1', member);
return await createWorkflow({}, team);
},
async function createCredential() {
return await saveCredential(randomCredentialPayload(), { user: member });
},
],
[
'team 1',
'team 2',
async function creteWorkflow() {
const team1 = await createTeamProject('Team 1', member);
return await createWorkflow({}, team1);
},
async function createCredential() {
const team2 = await createTeamProject('Team 2', member);
return await saveCredential(randomCredentialPayload(), { project: team2 });
},
],
[
'the member',
'the owner',
async function creteWorkflow() {
return await createWorkflow({}, member);
},
async function createCredential() {
return await saveCredential(randomCredentialPayload(), { user: owner });
},
],
[
'the member',
'team 2',
async function creteWorkflow() {
return await createWorkflow({}, member);
},
async function createCredential() {
const team2 = await createTeamProject('Team 2', member);
return await saveCredential(randomCredentialPayload(), { project: team2 });
},
],
])(
'Tamper proofing kicks in if the workflow is owned by %s, the credentials is owned by %s, and the member tries to use the credential in the workflow',
async (_workflowText, _credentialText, createWorkflow, createCredential) => {
//
// ARRANGE
//
const workflow = await createWorkflow();
const credential = await createCredential();
//
// ACT
//
const response = await authMemberAgent.patch(`/workflows/${workflow.id}`).send({
versionId: workflow.versionId,
nodes: [
{
id: 'uuid-12345',
name: 'Start',
parameters: {},
position: [-20, 260],
type: 'n8n-nodes-base.manualTrigger',
typeVersion: 1,
credentials: {
default: {
id: credential.id,
name: credential.name,
},
},
},
],
});
//
// ASSERT
//
expect(response.statusCode).toBe(400);
expect(response.body.message).toBe(
"You don't have access to the credentials in the 'Start' node. Ask the owner to share them with you.",
);
},
);
describe('sub-workflow loaded from a URL or file', () => {
const UNINSPECTABLE_SOURCE_MESSAGE =
'The \'Sub\' node loads its sub-workflow from a source that is resolved only when the workflow runs, so its credential access cannot be checked on save. Use the "Database" or "Define Below" source instead.';
const remoteSubworkflowNode = (workflowUrl = 'https://example.com/workflow.json') => ({
id: 'uuid-sub-1',
name: 'Sub',
type: 'n8n-nodes-base.executeWorkflow',
typeVersion: 1.1,
position: [0, 0] as [number, number],
parameters: { source: 'url', workflowUrl },
});
it('rejects a member adding such a node to a shared workflow', async () => {
const workflow = await createWorkflow({}, owner);
await shareWorkflowWithUsers(workflow, [member]);
const response = await authMemberAgent.patch(`/workflows/${workflow.id}`).send({
versionId: workflow.versionId,
nodes: [remoteSubworkflowNode()],
});
expect(response.statusCode).toBe(400);
expect(response.body.message).toBe(UNINSPECTABLE_SOURCE_MESSAGE);
});
it('rejects a member creating a workflow with such a node', async () => {
const response = await authMemberAgent.post('/workflows').send({
name: 'test',
active: false,
connections: {},
nodes: [remoteSubworkflowNode()],
});
expect(response.statusCode).toBe(400);
expect(response.body.message).toBe(UNINSPECTABLE_SOURCE_MESSAGE);
});
it('rejects a member adding the HITL tool variant of such a node', async () => {
const workflow = await createWorkflow({}, owner);
await shareWorkflowWithUsers(workflow, [member]);
const response = await authMemberAgent.patch(`/workflows/${workflow.id}`).send({
versionId: workflow.versionId,
nodes: [{ ...remoteSubworkflowNode(), type: 'n8n-nodes-base.executeWorkflowHitlTool' }],
});
expect(response.statusCode).toBe(400);
expect(response.body.message).toBe(UNINSPECTABLE_SOURCE_MESSAGE);
});
it('rejects a member changing an execution setting of an existing node', async () => {
const workflow = await createWorkflow({ nodes: [remoteSubworkflowNode()] }, owner);
await shareWorkflowWithUsers(workflow, [member]);
const response = await authMemberAgent.patch(`/workflows/${workflow.id}`).send({
versionId: workflow.versionId,
nodes: [{ ...remoteSubworkflowNode(), retryOnFail: true }],
});
expect(response.statusCode).toBe(400);
expect(response.body.message).toBe(UNINSPECTABLE_SOURCE_MESSAGE);
});
it('preserves a renamed URL node when the editor omits default and hidden parameters', async () => {
// The editor omits the default mode and the old database workflow ID.
const stored = {
...remoteSubworkflowNode(),
parameters: {
...remoteSubworkflowNode().parameters,
mode: 'once',
workflowId: { __rl: true, value: 'old-workflow', mode: 'id' },
},
};
const workflow = await createWorkflow({ nodes: [stored] }, owner);
await shareWorkflowWithUsers(workflow, [member]);
const response = await authMemberAgent.patch(`/workflows/${workflow.id}`).send({
versionId: workflow.versionId,
nodes: [{ ...remoteSubworkflowNode(), name: 'Renamed' }],
});
expect(response.statusCode).toBe(200);
const saved = await workflowRepository.findOneByOrFail({ id: workflow.id });
expect(saved.nodes).toEqual([{ ...stored, name: 'Renamed' }]);
});
it('rejects a member changing a stored URL and leaves the node unchanged', async () => {
const workflow = await createWorkflow({ nodes: [remoteSubworkflowNode()] }, owner);
await shareWorkflowWithUsers(workflow, [member]);
const changed = await authMemberAgent.patch(`/workflows/${workflow.id}`).send({
versionId: workflow.versionId,
nodes: [remoteSubworkflowNode('https://example.com/other.json')],
});
expect(changed.statusCode).toBe(400);
expect(changed.body.message).toBe(UNINSPECTABLE_SOURCE_MESSAGE);
const saved = await workflowRepository.findOneByOrFail({ id: workflow.id });
expect(saved.nodes).toEqual([remoteSubworkflowNode()]);
});
it('lets the owner create and change such a node', async () => {
const createResponse = await authOwnerAgent.post('/workflows').send({
name: 'test',
active: false,
connections: {},
nodes: [remoteSubworkflowNode()],
});
expect(createResponse.statusCode).toBe(200);
const { id, versionId } = createResponse.body.data;
const response = await authOwnerAgent.patch(`/workflows/${id}`).send({
versionId,
nodes: [remoteSubworkflowNode('https://example.com/other.json')],
});
expect(response.statusCode).toBe(200);
expect(response.body.data.nodes[0].parameters.workflowUrl).toBe(
'https://example.com/other.json',
);
});
});
const nodeWith = (credential: { id: string; name: string }, url = 'https://v1.test') => ({
id: 'uuid-restore-1',
name: 'Call',
parameters: { url },
position: [0, 0] as [number, number],
type: 'n8n-nodes-base.httpRequest',
typeVersion: 4.2,
credentials: { httpHeaderAuth: { id: credential.id, name: credential.name } },
});
// The type must match the node's credential key, so the server resolves it by id.
const saveHttpHeaderCredential = async (user: User) =>
await saveCredential({ ...randomCredentialPayload(), type: 'httpHeaderAuth' }, { user });
/**
* A member's workflow whose earlier version used the owner's credential. The
* current version no longer has that node, and the member cannot use it.
*/
const setUp = async () => {
const credential = await saveHttpHeaderCredential(owner);
const workflow = await createWorkflow({}, member);
const oldVersionId = uuid();
await createWorkflowHistory(workflow, member, undefined, {
versionId: oldVersionId,
nodes: [nodeWith(credential)],
});
return { credential, workflow, oldVersionId };
};
describe('restoring a history version', () => {
test('restores a version with a credential the user cannot use', async () => {
const { credential, workflow, oldVersionId } = await setUp();
const response = await authMemberAgent.patch(`/workflows/${workflow.id}`).send({
versionId: workflow.versionId,
nodes: [nodeWith(credential)],
restoredFromVersionId: oldVersionId,
});
expect(response.statusCode).toBe(200);
expect(response.body.data.nodes).toEqual([nodeWith(credential)]);
});
test('restores a version after its credential was renamed', async () => {
const { credential, workflow, oldVersionId } = await setUp();
await Container.get(CredentialsRepository).update(credential.id, { name: 'Renamed' });
// The editor sends the nodes as the version stored them, with the old name.
const response = await authMemberAgent.patch(`/workflows/${workflow.id}`).send({
versionId: workflow.versionId,
nodes: [nodeWith(credential)],
restoredFromVersionId: oldVersionId,
});
expect(response.statusCode).toBe(200);
expect(response.body.data.nodes[0].credentials.httpHeaderAuth).toEqual({
id: credential.id,
name: 'Renamed',
});
});
test('blocks a credential that no version stored on the node in an ordinary save', async () => {
const { workflow } = await setUp();
const otherCredential = await saveHttpHeaderCredential(owner);
const response = await authMemberAgent.patch(`/workflows/${workflow.id}`).send({
versionId: workflow.versionId,
nodes: [nodeWith(otherCredential)],
});
expect(response.statusCode).toBe(400);
expect(response.body.message).toBe(
"You don't have access to the credentials in the 'Call' node. Ask the owner to share them with you.",
);
});
test('blocks a node that differs from the restored version', async () => {
const { credential, workflow, oldVersionId } = await setUp();
const response = await authMemberAgent.patch(`/workflows/${workflow.id}`).send({
versionId: workflow.versionId,
nodes: [nodeWith(credential, 'https://changed.test')],
restoredFromVersionId: oldVersionId,
});
expect(response.statusCode).toBe(400);
});
test("refuses a version that is not in this workflow's history", async () => {
const { credential, workflow } = await setUp();
const otherWorkflow = await createWorkflow({}, member);
const otherVersionId = uuid();
await createWorkflowHistory(otherWorkflow, member, undefined, {
versionId: otherVersionId,
nodes: [nodeWith(credential)],
});
const response = await authMemberAgent.patch(`/workflows/${workflow.id}`).send({
versionId: workflow.versionId,
nodes: [nodeWith(credential)],
restoredFromVersionId: otherVersionId,
});
expect(response.statusCode).toBe(400);
expect(response.body.message).toBe(
"The version to restore is not in this workflow's history.",
);
});
});
describe('switching a node back to a credential a history version stored', () => {
/**
* The member switched the node from the owner's credential to their own and
* autosave stored it: the current version has the member's credential, an
* earlier version the owner's.
*/
const setUpSwitched = async () => {
const { credential, workflow } = await setUp();
const ownCredential = await saveHttpHeaderCredential(member);
await Container.get(WorkflowRepository).update(workflow.id, {
nodes: [nodeWith(ownCredential)],
});
return { credential, ownCredential, workflow };
};
test('saves the node switched back, renamed and moved', async () => {
const { credential, workflow } = await setUpSwitched();
const switchedBack = { ...nodeWith(credential), name: 'Renamed', position: [10, 20] };
const response = await authMemberAgent.patch(`/workflows/${workflow.id}`).send({
versionId: workflow.versionId,
nodes: [switchedBack],
});
expect(response.statusCode).toBe(200);
expect(response.body.data.nodes).toEqual([switchedBack]);
});
test('saves the node switched back after its credential was renamed', async () => {
const { credential, workflow } = await setUpSwitched();
await Container.get(CredentialsRepository).update(credential.id, { name: 'Renamed' });
const response = await authMemberAgent.patch(`/workflows/${workflow.id}`).send({
versionId: workflow.versionId,
nodes: [nodeWith({ id: credential.id, name: 'Renamed' })],
});
expect(response.statusCode).toBe(200);
expect(response.body.data.nodes[0].credentials.httpHeaderAuth).toEqual({
id: credential.id,
name: 'Renamed',
});
});
test('saves the node switched back and disabled after its credential was renamed', async () => {
const { credential, workflow } = await setUpSwitched();
await Container.get(CredentialsRepository).update(credential.id, { name: 'Renamed' });
// A disabled node is not normalized, so the old credential name reaches the guard.
const response = await authMemberAgent.patch(`/workflows/${workflow.id}`).send({
versionId: workflow.versionId,
nodes: [{ ...nodeWith(credential), disabled: true }],
});
expect(response.statusCode).toBe(200);
expect(response.body.data.nodes[0].disabled).toBe(true);
expect(response.body.data.nodes[0].credentials.httpHeaderAuth.id).toBe(credential.id);
});
test('blocks the switch back when another parameter changed too', async () => {
const { credential, workflow } = await setUpSwitched();
const response = await authMemberAgent.patch(`/workflows/${workflow.id}`).send({
versionId: workflow.versionId,
nodes: [nodeWith(credential, 'https://changed.test')],
});
expect(response.statusCode).toBe(400);
expect(response.body.message).toBe(
"You don't have access to the credentials in the 'Call' node. Ask the owner to share them with you.",
);
});
test('blocks a credential the user cannot use that no version stored on the node', async () => {
const { workflow } = await setUpSwitched();
const otherCredential = await saveHttpHeaderCredential(owner);
const response = await authMemberAgent.patch(`/workflows/${workflow.id}`).send({
versionId: workflow.versionId,
nodes: [nodeWith(otherCredential)],
});
expect(response.statusCode).toBe(400);
});
});
describe('sub-workflow with an inspectable source', () => {
const databaseSubworkflowNode = (workflowId: string) => ({
id: 'uuid-sub-db',
name: 'Sub',
type: 'n8n-nodes-base.executeWorkflow',
typeVersion: 1.2,
position: [0, 0] as [number, number],
parameters: {
source: 'database',
workflowId: { __rl: true, value: workflowId, mode: 'id' },
},
});
it('lets a member change a stored node that loads its sub-workflow from the database', async () => {
const workflow = await createWorkflow(
{ nodes: [databaseSubworkflowNode('wf-old')] },
owner,
);
await shareWorkflowWithUsers(workflow, [member]);
const response = await authMemberAgent.patch(`/workflows/${workflow.id}`).send({
versionId: workflow.versionId,
nodes: [databaseSubworkflowNode('wf-new')],
});
expect(response.statusCode).toBe(200);
expect(response.body.data.nodes[0].parameters.workflowId.value).toBe('wf-new');
});
it('lets a member create a workflow with a node that defines its sub-workflow inline', async () => {
const response = await authMemberAgent.post('/workflows').send({
name: 'test',
active: false,
connections: {},
nodes: [
{
id: 'uuid-sub-inline',
name: 'Sub',
type: 'n8n-nodes-base.executeWorkflow',
typeVersion: 1.2,
position: [0, 0],
parameters: {
source: 'parameter',
workflowJson: JSON.stringify({ nodes: [], connections: {} }),
},
},
],
});
expect(response.statusCode).toBe(200);
expect(response.body.data.nodes[0].parameters.source).toBe('parameter');
});
});
describe('credentials in an agent node parameter', () => {
// The agent node keeps the model credential and its tool credentials in
// the hidden `inlineAgent` parameter, not in `node.credentials`.
const OWNER_INSTRUCTIONS = 'Answer questions about the docs.';
const EDITOR_INSTRUCTIONS = 'Summarize the input.';
let ownerModelCredential: CredentialsEntity;
let ownerToolCredential: CredentialsEntity;
let memberCredential: CredentialsEntity;
let sharedWorkflow: WorkflowEntity;
const agentNode = (id: string, inlineAgent: unknown) =>
({
id,
name: id,
type: 'n8n-nodes-base.messageAnAgent',
typeVersion: 2,
position: [0, 0],
parameters: { agentSource: 'inline', inlineAgent },
}) as unknown as INode;
const inlineAgent = (credential: string, instructions: string, extra: object = {}) => ({
config: { model: 'gpt-4o-mini', credential, instructions, ...extra },
});
const ownerAgentNode = () =>
agentNode('agent-1', inlineAgent(ownerModelCredential.id, OWNER_INSTRUCTIONS));
const patchAsMember = async (nodes: INode[]) =>
await authMemberAgent
.patch(`/workflows/${sharedWorkflow.id}`)
.send({ versionId: sharedWorkflow.versionId, nodes });
const storedNodes = async () =>
(await workflowRepository.findOneByOrFail({ id: sharedWorkflow.id })).nodes;
beforeAll(async () => {
ownerModelCredential = await saveCredential(randomCredentialPayload(), { user: owner });
ownerToolCredential = await saveCredential(randomCredentialPayload(), { user: owner });
memberCredential = await saveCredential(randomCredentialPayload(), { user: member });
});
beforeEach(async () => {
sharedWorkflow = await createWorkflow({ nodes: [ownerAgentNode()] }, owner);
await shareWorkflowWithUsers(sharedWorkflow, [member]);
});
it('keeps the stored agent node when the editor cannot use its credential', async () => {
const edited = agentNode(
'agent-1',
inlineAgent(ownerModelCredential.id, EDITOR_INSTRUCTIONS),
);
// The node id matches the stored node, so the guard restores it.
const response = await patchAsMember([edited]);
expect(response.statusCode).toBe(200);
expect((await storedNodes())[0].parameters).toEqual(ownerAgentNode().parameters);
});
it('rejects a new agent node whose credential is not shared with the editor', async () => {
const planted = agentNode(
'agent-2',
inlineAgent(ownerModelCredential.id, EDITOR_INSTRUCTIONS),
);
const response = await patchAsMember([ownerAgentNode(), planted]);
expect(response.statusCode).toBe(400);
expect(await storedNodes()).toHaveLength(1);
});
it('rejects a node tool credential that is not shared with the editor', async () => {
const planted = agentNode(
'agent-2',
inlineAgent(memberCredential.id, EDITOR_INSTRUCTIONS, {
tools: [
{
type: 'node',
name: 'fetch',
node: {
nodeType: 'n8n-nodes-base.httpRequest',
nodeParameters: { url: 'https://example.com/hook' },
credentials: {
httpBearerAuth: { id: ownerToolCredential.id, name: 'Owner token' },
},
},
},
],
}),
);
const response = await patchAsMember([ownerAgentNode(), planted]);
expect(response.statusCode).toBe(400);
expect(await storedNodes()).toHaveLength(1);
});
it('reads the credential id from a JSON-encoded parameter', async () => {
const planted = agentNode(
'agent-2',
JSON.stringify(inlineAgent(ownerModelCredential.id, EDITOR_INSTRUCTIONS)),
);
const response = await patchAsMember([ownerAgentNode(), planted]);
expect(response.statusCode).toBe(400);
expect(await storedNodes()).toHaveLength(1);
});
it("saves a new agent node that uses the editor's own credential", async () => {
const own = agentNode('agent-3', inlineAgent(memberCredential.id, EDITOR_INSTRUCTIONS));
const response = await patchAsMember([ownerAgentNode(), own]);
expect(response.statusCode).toBe(200);
expect(await storedNodes()).toHaveLength(2);
});
});
it('Should succeed but prevent modifying node attributes other than position, name and disabled', async () => {
const savedCredential = await saveCredential(randomCredentialPayload(), { user: member });
const originalNodes: INode[] = [
{
id: 'uuid-1234',
name: 'Start',
parameters: {
firstParam: 123,
},
position: [-20, 260],
type: 'n8n-nodes-base.manualTrigger',
typeVersion: 1,
credentials: {
default: {
id: savedCredential.id,
name: savedCredential.name,
},
},
},
];
const changedNodes: INode[] = [
{
id: 'uuid-1234',
name: 'End',
parameters: {
firstParam: 456,
},
position: [-20, 555],
type: 'n8n-nodes-base.no-op',
typeVersion: 1,
credentials: {
default: {
id: '200',
name: 'fake credential',
},
},
disabled: true,
},
];
const expectedNodes: INode[] = [
{
id: 'uuid-1234',
name: 'End',
parameters: {
firstParam: 123,
},
position: [-20, 555],
type: 'n8n-nodes-base.manualTrigger',
typeVersion: 1,
credentials: {
default: {
id: savedCredential.id,
name: savedCredential.name,
},
},
disabled: true,
},
];
const workflow = {
name: 'test',
active: false,
connections: {},
nodes: originalNodes,
};
const createResponse = await authMemberAgent.post('/workflows').send(workflow);
const { id, versionId } = createResponse.body.data;
await authMemberAgent
.put(`/workflows/${id}/share`)
.send({ shareWithIds: [anotherMemberPersonalProject.id] })
.expect(200);
const response = await authAnotherMemberAgent.patch(`/workflows/${id}`).send({
versionId,
nodes: changedNodes,
});
expect(response.statusCode).toBe(200);
expect(response.body.data.nodes).toMatchObject(expectedNodes);
});
});
describe('validate interim updates', () => {
it('should block owner updating workflow nodes on interim update by member', async () => {
// owner creates and shares workflow
const createResponse = await authOwnerAgent.post('/workflows').send(makeWorkflow());
const { id, versionId: ownerVersionId } = createResponse.body.data;
const ownerChecksum = await calculateWorkflowChecksum(createResponse.body.data);
await authOwnerAgent
.put(`/workflows/${id}/share`)
.send({ shareWithIds: [memberPersonalProject.id] });
// member accesses and updates workflow name
const memberGetResponse = await authMemberAgent.get(`/workflows/${id}`);
const { versionId: memberVersionId } = memberGetResponse.body.data;
await authMemberAgent
.patch(`/workflows/${id}`)
.send({ name: 'Update by member', versionId: memberVersionId });
// owner blocked from updating workflow nodes
const updateAttemptResponse = await authOwnerAgent
.patch(`/workflows/${id}`)
.send({ nodes: [], versionId: ownerVersionId, expectedChecksum: ownerChecksum });
expect(updateAttemptResponse.status).toBe(409);
expect(updateAttemptResponse.body.code).toBe(409);
});
it('should block member updating workflow nodes on interim update by owner', async () => {
// owner creates, updates and shares workflow
const createResponse = await authOwnerAgent.post('/workflows').send(makeWorkflow());
const { id, versionId: ownerFirstVersionId } = createResponse.body.data;
const updateResponse = await authOwnerAgent
.patch(`/workflows/${id}`)
.send({ name: 'Update by owner', versionId: ownerFirstVersionId });
const { versionId: ownerSecondVersionId } = updateResponse.body.data;
await authOwnerAgent
.put(`/workflows/${id}/share`)
.send({ shareWithIds: [memberPersonalProject.id] });
// member accesses workflow
const memberGetResponse = await authMemberAgent.get(`/workflows/${id}`);
const { versionId: memberVersionId } = memberGetResponse.body.data;
const memberChecksum = await calculateWorkflowChecksum(memberGetResponse.body.data);
// owner re-updates workflow
await authOwnerAgent
.patch(`/workflows/${id}`)
.send({ name: 'Owner update again', versionId: ownerSecondVersionId });
// member blocked from updating workflow
const updateAttemptResponse = await authMemberAgent
.patch(`/workflows/${id}`)
.send({ nodes: [], versionId: memberVersionId, expectedChecksum: memberChecksum });
expect(updateAttemptResponse.status).toBe(409);
expect(updateAttemptResponse.body.code).toBe(409);
});
it('should block owner activation on interim activation by member', async () => {
// owner creates and shares workflow
const createResponse = await authOwnerAgent.post('/workflows').send(makeWorkflow());
const { id, versionId: ownerVersionId } = createResponse.body.data;
const ownerChecksum = await calculateWorkflowChecksum(createResponse.body.data);
await authOwnerAgent
.put(`/workflows/${id}/share`)
.send({ shareWithIds: [memberPersonalProject.id] });
// member accesses and activates workflow
const memberGetResponse = await authMemberAgent.get(`/workflows/${id}`);
const { versionId: memberVersionId } = memberGetResponse.body.data;
await authMemberAgent
.patch(`/workflows/${id}`)
.send({ active: true, versionId: memberVersionId, name: 'Update by member' });
// owner blocked from activating workflow
const activationAttemptResponse = await authOwnerAgent.patch(`/workflows/${id}`).send({
active: true,
versionId: ownerVersionId,
name: 'Update by owner',
expectedChecksum: ownerChecksum,
});
expect(activationAttemptResponse.status).toBe(409);
expect(activationAttemptResponse.body.code).toBe(409);
});
it('should block member activation on interim activation by owner', async () => {
// owner creates, updates and shares workflow
const createResponse = await authOwnerAgent.post('/workflows').send(makeWorkflow());
const { id, versionId: ownerFirstVersionId } = createResponse.body.data;
const updateResponse = await authOwnerAgent
.patch(`/workflows/${id}`)
.send({ name: 'Update by owner', versionId: ownerFirstVersionId });
const { versionId: ownerSecondVersionId } = updateResponse.body.data;
await authOwnerAgent
.put(`/workflows/${id}/share`)
.send({ shareWithIds: [memberPersonalProject.id] });
// member accesses workflow
const memberGetResponse = await authMemberAgent.get(`/workflows/${id}`);
const { versionId: memberVersionId } = memberGetResponse.body.data;
const memberChecksum = await calculateWorkflowChecksum(memberGetResponse.body.data);
// owner activates workflow
await authOwnerAgent
.patch(`/workflows/${id}`)
.send({ active: true, versionId: ownerSecondVersionId, name: 'Owner update again' });
// member blocked from activating workflow
const updateAttemptResponse = await authMemberAgent.patch(`/workflows/${id}`).send({
active: true,
versionId: memberVersionId,
name: 'Update by member',
expectedChecksum: memberChecksum,
});
expect(updateAttemptResponse.status).toBe(409);
expect(updateAttemptResponse.body.code).toBe(409);
});
it('should block member updating workflow settings on interim update by owner', async () => {
// owner creates and shares workflow
const createResponse = await authOwnerAgent.post('/workflows').send(makeWorkflow());
const { id, versionId: ownerVersionId } = createResponse.body.data;
await authOwnerAgent
.put(`/workflows/${id}/share`)
.send({ shareWithIds: [memberPersonalProject.id] });
// member accesses workflow
const memberGetResponse = await authMemberAgent.get(`/workflows/${id}`);
const { versionId: memberVersionId } = memberGetResponse.body.data;
const memberChecksum = await calculateWorkflowChecksum(memberGetResponse.body.data);
// owner updates workflow name
await authOwnerAgent
.patch(`/workflows/${id}`)
.send({ name: 'Another name', versionId: ownerVersionId });
// member blocked from updating workflow settings
const updateAttemptResponse = await authMemberAgent.patch(`/workflows/${id}`).send({
settings: { saveManualExecutions: true },
versionId: memberVersionId,
expectedChecksum: memberChecksum,
});
expect(updateAttemptResponse.status).toBe(409);
expect(updateAttemptResponse.body.code).toBe(409);
});
it('should block member updating workflow name on interim update by owner', async () => {
// owner creates and shares workflow
const createResponse = await authOwnerAgent.post('/workflows').send(makeWorkflow());
const { id, versionId: ownerVersionId } = createResponse.body.data;
await authOwnerAgent
.put(`/workflows/${id}/share`)
.send({ shareWithIds: [memberPersonalProject.id] });
// member accesses workflow
const memberGetResponse = await authMemberAgent.get(`/workflows/${id}`).expect(200);
const { versionId: memberVersionId } = memberGetResponse.body.data;
const memberChecksum = await calculateWorkflowChecksum(memberGetResponse.body.data);
// owner updates workflow settings
await authOwnerAgent
.patch(`/workflows/${id}`)
.send({ settings: { saveManualExecutions: true }, versionId: ownerVersionId });
// member blocked from updating workflow name
const updateAttemptResponse = await authMemberAgent.patch(`/workflows/${id}`).send({
settings: { saveManualExecutions: true },
versionId: memberVersionId,
expectedChecksum: memberChecksum,
});
expect(updateAttemptResponse.status).toBe(409);
expect(updateAttemptResponse.body.code).toBe(409);
});
});
describe('workflow history', () => {
test('Should always create workflow history version', async () => {
const workflow = await createWorkflowWithHistory({}, owner);
const payload = {
name: 'name updated',
versionId: workflow.versionId,
nodes: [
{
id: 'uuid-1234',
parameters: {},
name: 'Start',
type: 'n8n-nodes-base.manualTrigger',
typeVersion: 1,
position: [240, 300],
},
{
id: 'uuid-5678',
parameters: {},
name: 'Cron',
type: 'n8n-nodes-base.cron',
typeVersion: 1,
position: [400, 300],
},
],
connections: {},
staticData: '{"id":1}',
settings: {
saveExecutionProgress: false,
saveManualExecutions: false,
saveDataErrorExecution: 'all',
saveDataSuccessExecution: 'all',
executionTimeout: 3600,
timezone: 'America/New_York',
},
};
const response = await authOwnerAgent.patch(`/workflows/${workflow.id}`).send(payload);
const {
data: { id, versionId: updatedVersionId },
} = response.body;
expect(response.statusCode).toBe(200);
expect(id).toBe(workflow.id);
expect(
await Container.get(WorkflowHistoryRepository).count({ where: { workflowId: id } }),
).toBe(2);
const historyVersion = await Container.get(WorkflowHistoryRepository).findOne({
where: {
workflowId: id,
versionId: updatedVersionId,
},
});
expect(historyVersion).not.toBeNull();
expect(historyVersion!.connections).toEqual(payload.connections);
expect(historyVersion!.nodes).toEqual(payload.nodes);
});
});
test('should include activeVersion relation in response for active workflows', async () => {
const teamProject = await createTeamProject();
const workflow = await createActiveWorkflow({}, teamProject);
const response = await authOwnerAgent.patch(`/workflows/${workflow.id}`).send({
name: 'Updated Name',
versionId: workflow.versionId,
});
expect(response.statusCode).toBe(200);
expect(response.body.data).toHaveProperty('activeVersion');
expect(response.body.data.activeVersion).toBeDefined();
expect(response.body.data.activeVersion).toMatchObject({
versionId: expect.any(String),
workflowId: workflow.id,
});
});
test('should include activeVersion as null for inactive workflows', async () => {
const teamProject = await createTeamProject();
const workflow = await createWorkflow({}, teamProject);
const response = await authOwnerAgent.patch(`/workflows/${workflow.id}`).send({
name: 'Updated Name',
versionId: workflow.versionId,
});
expect(response.statusCode).toBe(200);
expect(response.body.data).toHaveProperty('activeVersion');
expect(response.body.data.activeVersion).toBeNull();
});
});
describe('PUT /:workflowId/transfer', () => {
test('cannot transfer into the same project', async () => {
const destinationProject = await createTeamProject('Team Project', member);
const workflow = await createWorkflow({}, destinationProject);
await testServer
.authAgentFor(member)
.put(`/workflows/${workflow.id}/transfer`)
.send({ destinationProjectId: destinationProject.id })
.expect(400);
});
test('cannot transfer somebody elses workflow', async () => {
const destinationProject = await createTeamProject('Team Project', member);
const workflow = await createWorkflow({}, anotherMember);
await testServer
.authAgentFor(member)
.put(`/workflows/${workflow.id}/transfer`)
.send({ destinationProjectId: destinationProject.id })
.expect(403);
});
test("cannot transfer if you're not a member of the destination project", async () => {
const destinationProject = await createTeamProject('Team Project', anotherMember);
const workflow = await createWorkflow({}, member);
await testServer
.authAgentFor(member)
.put(`/workflows/${workflow.id}/transfer`)
.send({ destinationProjectId: destinationProject.id })
.expect(404);
});
test.each<ProjectRole>(['project:editor', 'project:viewer'])(
'%ss cannot transfer workflows',
async (projectRole) => {
//
// ARRANGE
//
const sourceProject = await createTeamProject();
await linkUserToProject(member, sourceProject, projectRole);
const workflow = await createWorkflow({}, sourceProject);
const destinationProject = await createTeamProject();
await linkUserToProject(member, destinationProject, 'project:admin');
//
// ACT & ASSERT
//
await testServer
.authAgentFor(member)
.put(`/workflows/${workflow.id}/transfer`)
.send({ destinationProjectId: destinationProject.id })
.expect(403);
},
);
test.each<
[
// user role
'owners' | 'admins',
// source project type
'team' | 'personal',
// destination project type
'team' | 'personal',
// actor
() => User,
// source project
() => Promise<Project> | Project,
// destination project
() => Promise<Project> | Project,
]
>([
// owner
[
'owners',
'team',
'team',
() => owner,
async () => await createTeamProject('Source Project'),
async () => await createTeamProject('Destination Project'),
],
[
'owners',
'team',
'personal',
() => owner,
async () => await createTeamProject('Source Project'),
() => memberPersonalProject,
],
[
'owners',
'personal',
'team',
() => owner,
() => memberPersonalProject,
async () => await createTeamProject('Destination Project'),
],
// admin
[
'admins',
'team',
'team',
() => admin,
async () => await createTeamProject('Source Project'),
async () => await createTeamProject('Destination Project'),
],
[
'admins',
'team',
'personal',
() => admin,
async () => await createTeamProject('Source Project'),
() => memberPersonalProject,
],
[
'admins',
'personal',
'team',
() => admin,
() => memberPersonalProject,
async () => await createTeamProject('Destination Project'),
],
])(
'global %s can transfer workflows from a %s project to a %s project',
async (
_roleName,
_sourceProjectName,
_destinationProjectName,
getActor,
getSourceProject,
getDestinationProject,
) => {
// ARRANGE
const actor = getActor();
const sourceProject = await getSourceProject();
const destinationProject = await getDestinationProject();
const workflow = await createWorkflow({}, sourceProject);
// ACT
const response = await testServer
.authAgentFor(actor)
.put(`/workflows/${workflow.id}/transfer`)
.send({ destinationProjectId: destinationProject.id })
.expect(200);
// ASSERT
expect(response.body).toEqual({});
const allSharings = await getWorkflowSharing(workflow);
expect(allSharings).toHaveLength(1);
expect(allSharings[0]).toMatchObject({
projectId: destinationProject.id,
workflowId: workflow.id,
role: 'workflow:owner',
});
},
);
test('removes and re-adds the workflow from the active workflow manager during the transfer', async () => {
//
// ARRANGE
//
const destinationProject = await createTeamProject('Team Project', member);
const workflow = await createActiveWorkflow({}, member);
//
// ACT
//
const response = await testServer
.authAgentFor(member)
.put(`/workflows/${workflow.id}/transfer`)
.send({ destinationProjectId: destinationProject.id })
.expect(200);
//
// ASSERT
//
expect(response.body).toEqual({});
expect(activeWorkflowManager.remove).toHaveBeenCalledWith(workflow.id);
expect(activeWorkflowManager.add).toHaveBeenCalledWith(workflow.id, 'update', undefined, {
actor: { kind: 'user', user: { id: member.id } },
});
});
test('should move workflow to project root if `destinationParentFolderId` is not provided', async () => {
//
// ARRANGE
//
const destinationProject = await createTeamProject('Team Project', member);
const folder = await createFolder(destinationProject, { name: 'Test Folder' });
const workflow = await createActiveWorkflow({ parentFolder: folder }, member);
//
// ACT
//
const response = await testServer
.authAgentFor(member)
.put(`/workflows/${workflow.id}/transfer`)
.send({ destinationProjectId: destinationProject.id })
.expect(200);
//
// ASSERT
//
expect(response.body).toEqual({});
const workflowFromDB = await workflowRepository.findOneOrFail({
where: { id: workflow.id },
relations: ['parentFolder'],
});
expect(workflowFromDB.parentFolder).toBeNull();
});
test('should move workflow to the parent folder in source project if `destinationParentFolderId` is provided', async () => {
//
// ARRANGE
//
const destinationProject = await createTeamProject('Team Project', member);
const folder = await createFolder(destinationProject, { name: 'Test Folder' });
const workflow = await createActiveWorkflow({ parentFolder: folder }, member);
//
// ACT
//
const response = await testServer
.authAgentFor(member)
.put(`/workflows/${workflow.id}/transfer`)
.send({ destinationProjectId: destinationProject.id, destinationParentFolderId: folder.id })
.expect(200);
//
// ASSERT
//
expect(response.body).toEqual({});
const workflowFromDB = await workflowRepository.findOneOrFail({
where: { id: workflow.id },
relations: ['parentFolder'],
});
expect(workflowFromDB.parentFolder?.id).toBe(folder.id);
});
test('should fail destination parent folder does not exist in project', async () => {
//
// ARRANGE
//
const destinationProject = await createTeamProject('Team Project', member);
const anotherProject = await createTeamProject('Another Project', member);
const folderInDestinationProject = await createFolder(destinationProject, {
name: 'Test Folder',
});
const anotherFolder = await createFolder(destinationProject, {
name: 'Another Test Folder',
});
const workflow = await createWorkflow({ parentFolder: folderInDestinationProject }, member);
//
// ACT
//
await testServer
.authAgentFor(member)
.put(`/workflows/${workflow.id}/transfer`)
.send({
destinationProjectId: anotherProject.id,
destinationParentFolderId: anotherFolder.id,
})
.expect(400);
});
test('deactivates the workflow if it cannot be added to the active workflow manager again and returns the WorkflowActivationError as data', async () => {
//
// ARRANGE
//
const destinationProject = await createTeamProject('Team Project', member);
const workflow = await createActiveWorkflow({}, member);
activeWorkflowManager.add.mockRejectedValue(new WorkflowActivationError('Failed'));
//
// ACT
//
const response = await testServer
.authAgentFor(member)
.put(`/workflows/${workflow.id}/transfer`)
.send({ destinationProjectId: destinationProject.id })
.expect(200);
//
// ASSERT
//
expect(response.body).toMatchObject({
data: {
error: {
message: 'Failed',
name: 'WorkflowActivationError',
},
},
});
expect(activeWorkflowManager.remove).toHaveBeenCalledWith(workflow.id);
expect(activeWorkflowManager.add).toHaveBeenCalledWith(workflow.id, 'update', undefined, {
actor: { kind: 'user', user: { id: member.id } },
});
const workflowFromDB = await workflowRepository.findOneByOrFail({ id: workflow.id });
expect(workflowFromDB.active).toBe(false);
expect(workflowFromDB.activeVersionId).toBeNull();
});
test('owner transfers workflow from project they are not part of, e.g. test global cred sharing scope', async () => {
// ARRANGE
const sourceProject = await createTeamProject('source project', admin);
const destinationProject = await createTeamProject('destination project', member);
const workflow = await createWorkflow({}, sourceProject);
const credential = await saveCredential(randomCredentialPayload(), { project: sourceProject });
// ACT
await testServer
.authAgentFor(owner)
.put(`/workflows/${workflow.id}/transfer`)
.send({
destinationProjectId: destinationProject.id,
shareCredentials: [credential.id],
})
.expect(200);
// ASSERT
const allWorkflowSharings = await getWorkflowSharing(workflow);
expect(allWorkflowSharings).toHaveLength(1);
expect(allWorkflowSharings[0]).toMatchObject({
projectId: destinationProject.id,
workflowId: workflow.id,
role: 'workflow:owner',
});
const allCredentialSharings = await getCredentialSharings(credential);
expect(allCredentialSharings).toHaveLength(2);
expect(allCredentialSharings).toEqual(
expect.arrayContaining([
expect.objectContaining({
projectId: sourceProject.id,
credentialsId: credential.id,
role: 'credential:owner',
}),
expect.objectContaining({
projectId: destinationProject.id,
credentialsId: credential.id,
role: 'credential:user',
}),
]),
);
});
test('admin transfers workflow from project they are not part of, e.g. test global cred sharing scope', async () => {
// ARRANGE
const sourceProject = await createTeamProject('source project', owner);
const destinationProject = await createTeamProject('destination project', owner);
const workflow = await createWorkflow({}, sourceProject);
const credential = await saveCredential(randomCredentialPayload(), { project: sourceProject });
// ACT
await testServer
.authAgentFor(admin)
.put(`/workflows/${workflow.id}/transfer`)
.send({
destinationProjectId: destinationProject.id,
shareCredentials: [credential.id],
})
.expect(200);
// ASSERT
const allWorkflowSharings = await getWorkflowSharing(workflow);
expect(allWorkflowSharings).toHaveLength(1);
expect(allWorkflowSharings[0]).toMatchObject({
projectId: destinationProject.id,
workflowId: workflow.id,
role: 'workflow:owner',
});
const allCredentialSharings = await getCredentialSharings(credential);
expect(allCredentialSharings).toHaveLength(2);
expect(allCredentialSharings).toEqual(
expect.arrayContaining([
expect.objectContaining({
projectId: sourceProject.id,
credentialsId: credential.id,
role: 'credential:owner',
}),
expect.objectContaining({
projectId: destinationProject.id,
credentialsId: credential.id,
role: 'credential:user',
}),
]),
);
});
test('member transfers workflow from personal project to team project and wf contains a credential that they can use but not share', async () => {
// ARRANGE
const sourceProject = memberPersonalProject;
const destinationProject = await createTeamProject('destination project', member);
const workflow = await createWorkflow({}, sourceProject);
const credential = await saveCredential(randomCredentialPayload(), { user: owner });
await shareCredentialWithUsers(credential, [member]);
// ACT
await testServer
.authAgentFor(member)
.put(`/workflows/${workflow.id}/transfer`)
.send({
destinationProjectId: destinationProject.id,
shareCredentials: [credential.id],
})
.expect(200);
// ASSERT
const allWorkflowSharings = await getWorkflowSharing(workflow);
expect(allWorkflowSharings).toHaveLength(1);
expect(allWorkflowSharings[0]).toMatchObject({
projectId: destinationProject.id,
workflowId: workflow.id,
role: 'workflow:owner',
});
const allCredentialSharings = await getCredentialSharings(credential);
expect(allCredentialSharings).toHaveLength(2);
expect(allCredentialSharings).toEqual(
expect.arrayContaining([
expect.objectContaining({
projectId: ownerPersonalProject.id,
credentialsId: credential.id,
role: 'credential:owner',
}),
expect.objectContaining({
projectId: sourceProject.id,
credentialsId: credential.id,
role: 'credential:user',
}),
]),
);
});
test('member transfers workflow from their personal project to another team project in which they have editor role', async () => {
// ARRANGE
const sourceProject = memberPersonalProject;
const destinationProject = await createTeamProject('destination project');
const workflow = await createWorkflow({}, sourceProject);
const credential = await saveCredential(randomCredentialPayload(), { project: sourceProject });
await linkUserToProject(member, destinationProject, 'project:editor');
// ACT
await testServer
.authAgentFor(member)
.put(`/workflows/${workflow.id}/transfer`)
.send({
destinationProjectId: destinationProject.id,
shareCredentials: [credential.id],
})
.expect(200);
// ASSERT
const allWorkflowSharings = await getWorkflowSharing(workflow);
expect(allWorkflowSharings).toHaveLength(1);
expect(allWorkflowSharings[0]).toMatchObject({
projectId: destinationProject.id,
workflowId: workflow.id,
role: 'workflow:owner',
});
const allCredentialSharings = await getCredentialSharings(credential);
expect(allCredentialSharings).toHaveLength(2);
expect(allCredentialSharings).toEqual(
expect.arrayContaining([
expect.objectContaining({
projectId: sourceProject.id,
credentialsId: credential.id,
role: 'credential:owner',
}),
expect.objectContaining({
projectId: destinationProject.id,
credentialsId: credential.id,
role: 'credential:user',
}),
]),
);
});
test('member transfers workflow from a team project as project admin to another team project in which they have editor role', async () => {
// ARRANGE
const sourceProject = await createTeamProject('source project', member);
const destinationProject = await createTeamProject('destination project');
const workflow = await createWorkflow({}, sourceProject);
const credential = await saveCredential(randomCredentialPayload(), { project: sourceProject });
await linkUserToProject(member, destinationProject, 'project:editor');
// ACT
await testServer
.authAgentFor(member)
.put(`/workflows/${workflow.id}/transfer`)
.send({
destinationProjectId: destinationProject.id,
shareCredentials: [credential.id],
})
.expect(200);
// ASSERT
const allWorkflowSharings = await getWorkflowSharing(workflow);
expect(allWorkflowSharings).toHaveLength(1);
expect(allWorkflowSharings[0]).toMatchObject({
projectId: destinationProject.id,
workflowId: workflow.id,
role: 'workflow:owner',
});
const allCredentialSharings = await getCredentialSharings(credential);
expect(allCredentialSharings).toHaveLength(2);
expect(allCredentialSharings).toEqual(
expect.arrayContaining([
expect.objectContaining({
projectId: sourceProject.id,
credentialsId: credential.id,
role: 'credential:owner',
}),
expect.objectContaining({
projectId: destinationProject.id,
credentialsId: credential.id,
role: 'credential:user',
}),
]),
);
});
test('member transfers workflow from a team project as project admin to another team project in which they have editor role but cannot share the credential that is only shared into the source project', async () => {
// ARRANGE
const sourceProject = await createTeamProject('source project', member);
const destinationProject = await createTeamProject('destination project');
const ownerProject = await getPersonalProject(owner);
const workflow = await createWorkflow({}, sourceProject);
const credential = await saveCredential(randomCredentialPayload(), { user: owner });
await linkUserToProject(member, destinationProject, 'project:editor');
await shareCredentialWithProjects(credential, [sourceProject]);
// ACT
await testServer
.authAgentFor(member)
.put(`/workflows/${workflow.id}/transfer`)
.send({
destinationProjectId: destinationProject.id,
shareCredentials: [credential.id],
})
.expect(200);
// ASSERT
const allWorkflowSharings = await getWorkflowSharing(workflow);
expect(allWorkflowSharings).toHaveLength(1);
expect(allWorkflowSharings[0]).toMatchObject({
projectId: destinationProject.id,
workflowId: workflow.id,
role: 'workflow:owner',
});
const allCredentialSharings = await getCredentialSharings(credential);
expect(allCredentialSharings).toHaveLength(2);
expect(allCredentialSharings).toEqual(
expect.arrayContaining([
expect.objectContaining({
projectId: ownerProject.id,
credentialsId: credential.id,
role: 'credential:owner',
}),
expect.objectContaining({
projectId: sourceProject.id,
credentialsId: credential.id,
role: 'credential:user',
}),
]),
);
});
test('member transfers workflow from a team project as project admin to another team project in which they have editor role but cannot share all the credentials', async () => {
// ARRANGE
const sourceProject = await createTeamProject('source project', member);
const workflow = await createWorkflow({}, sourceProject);
const credential = await saveCredential(randomCredentialPayload(), { project: sourceProject });
const ownersCredential = await saveCredential(randomCredentialPayload(), { user: owner });
const destinationProject = await createTeamProject('destination project');
await linkUserToProject(member, destinationProject, 'project:editor');
// ACT
await testServer
.authAgentFor(member)
.put(`/workflows/${workflow.id}/transfer`)
.send({
destinationProjectId: destinationProject.id,
shareCredentials: [credential.id, ownersCredential.id],
})
.expect(200);
// ASSERT
const allWorkflowSharings = await getWorkflowSharing(workflow);
expect(allWorkflowSharings).toHaveLength(1);
expect(allWorkflowSharings[0]).toMatchObject({
projectId: destinationProject.id,
workflowId: workflow.id,
role: 'workflow:owner',
});
const allCredentialSharings = await getCredentialSharings(credential);
expect(allCredentialSharings).toHaveLength(2);
expect(allCredentialSharings).toEqual(
expect.arrayContaining([
expect.objectContaining({
projectId: sourceProject.id,
credentialsId: credential.id,
role: 'credential:owner',
}),
expect.objectContaining({
projectId: destinationProject.id,
credentialsId: credential.id,
role: 'credential:user',
}),
]),
);
const ownerCredentialSharings = await getCredentialSharings(ownersCredential);
expect(ownerCredentialSharings).toHaveLength(1);
expect(ownerCredentialSharings).toEqual([
expect.objectContaining({
projectId: ownerPersonalProject.id,
credentialsId: ownersCredential.id,
role: 'credential:owner',
}),
]);
});
test('returns a 500 if the workflow cannot be activated due to an unknown error', async () => {
//
// ARRANGE
//
const destinationProject = await createTeamProject('Team Project', member);
const workflow = await createActiveWorkflow({}, member);
activeWorkflowManager.add.mockRejectedValue(new UnexpectedError('Oh no!'));
//
// ACT & ASSERT
//
await testServer
.authAgentFor(member)
.put(`/workflows/${workflow.id}/transfer`)
.send({ destinationProjectId: destinationProject.id })
.expect(500);
});
});
describe('POST /workflows/:workflowId/run', () => {
test('project viewers cannot run workflows', async () => {
const teamProject = await createTeamProject();
await linkUserToProject(member, teamProject, 'project:viewer');
const workflow = await createWorkflow({}, teamProject);
const response = await authMemberAgent
.post(`/workflows/${workflow.id}/run`)
.send({ workflowData: workflow });
expect(response.status).toBe(403);
expect(response.body).toMatchObject({
message: 'User is missing a scope required to perform this action',
});
});
test('should always load the workflow from the database, ignoring request workflowData', async () => {
const teamProject = await createTeamProject();
await linkUserToProject(member, teamProject, 'project:editor');
const dbNode: INode = {
id: uuid(),
name: 'Start',
type: 'n8n-nodes-base.start',
parameters: {},
typeVersion: 1,
position: [240, 300],
};
const workflow = await createWorkflow({ nodes: [dbNode], connections: {} }, teamProject);
// Send tampered workflowData with an injected node
const tamperedWorkflowData = {
...workflow,
nodes: [
dbNode,
{
id: uuid(),
name: 'Injected',
type: 'n8n-nodes-base.noOp',
parameters: {},
typeVersion: 1,
position: [500, 300],
},
],
};
const response = await authMemberAgent
.post(`/workflows/${workflow.id}/run`)
.send({ workflowData: tamperedWorkflowData });
// The endpoint should NOT reject (the DB workflow exists and user has execute scope)
// It should use the DB version, not the tampered one
expect(response.status).not.toBe(403);
expect(response.status).not.toBe(404);
});
});
// The editor saves through PATCH /workflows/:id, which never asks for publication, so an editor
// holding workflow:update but not workflow:publish keeps working. Guards the editor against the
// publish-on-save rules the public API needs.
describe('PATCH /workflows/:workflowId as an editor who may not publish', () => {
const publishedWorkflowIds: string[] = [];
afterEach(async () => {
// The published-version row references the workflow, so it has to go before the next truncate.
const publishedVersionRepository = Container.get(WorkflowPublishedVersionRepository);
for (const workflowId of publishedWorkflowIds) {
await publishedVersionRepository.removePublishedVersion(workflowId);
}
publishedWorkflowIds.length = 0;
});
// One role for the whole block: the roles table is not truncated between tests, so creating one
// per test would leave a row behind each time. It outlives the block rather than being deleted,
// because the last test's project relation still references it when a suite teardown would run.
let editorWithoutPublishSlug: string;
beforeAll(async () => {
const role = await createCustomRoleWithScopeSlugs(['workflow:read', 'workflow:update'], {
roleType: 'project',
displayName: 'Editor without publish',
description: 'Can edit workflows but not publish them',
});
editorWithoutPublishSlug = role.slug;
});
const publishedWorkflowMemberCanOnlyEdit = async (label: string) => {
const project = await createTeamProject(`Project ${label}`, owner);
await linkUserToProject(member, project, editorWithoutPublishSlug);
const workflow = await createActiveWorkflow({}, project);
await Container.get(WorkflowPublishedVersionRepository).setPublishedVersion(
workflow.id,
workflow.versionId,
);
publishedWorkflowIds.push(workflow.id);
return workflow;
};
test('saves a content change on a published workflow as a draft', async () => {
const workflow = await publishedWorkflowMemberCanOnlyEdit('content');
const response = await authMemberAgent.patch(`/workflows/${workflow.id}`).send({
versionId: workflow.versionId,
nodes: workflow.nodes.map((node) =>
node.type === 'n8n-nodes-base.cron'
? { ...node, parameters: { triggerTimes: { item: [{ mode: 'everyMinute' }] } } }
: node,
),
connections: workflow.connections,
});
const stored = await Container.get(WorkflowRepository).findOneBy({ id: workflow.id });
expect(response.statusCode).toBe(200);
expect(stored?.versionId).not.toBe(workflow.versionId);
expect(stored?.activeVersionId).toBe(workflow.versionId);
});
test('saves a settings change on a published workflow', async () => {
const workflow = await publishedWorkflowMemberCanOnlyEdit('settings');
const response = await authMemberAgent.patch(`/workflows/${workflow.id}`).send({
versionId: workflow.versionId,
settings: { ...(workflow.settings ?? {}), timezone: 'America/New_York' },
});
const stored = await Container.get(WorkflowRepository).findOneBy({ id: workflow.id });
expect(response.statusCode).toBe(200);
expect(stored?.settings?.timezone).toBe('America/New_York');
expect(stored?.activeVersionId).toBe(workflow.versionId);
});
test('is still refused when it explicitly asks to publish', async () => {
const workflow = await publishedWorkflowMemberCanOnlyEdit('publish');
const response = await authMemberAgent.post(`/workflows/${workflow.id}/activate`).send({});
expect(response.statusCode).toBe(403);
});
});