Files
twenty/packages/twenty-server/test/integration/graphql/suites/user.integration-spec.ts
T
Marie 4ce93aee52 Fix user deletion flows (#15614)
**Before**
- any user with workpace_members permission was able to remove a user
from their workspace. This triggered the deletion of workspaceMember +
of userWorkspace, but did not delete the user (even if they had no
workspace left) nor the roleTarget (acts as junction between role and
userWorkspace) which was left with a userWorkspaceId pointing to
nothing. This is because roleTarget points to userWorkspaceId but the
foreign key constraint was not implemented
- any user could delete their own account. This triggered the deletion
of all their workspaceMembers, but not of their userWorkspace nor their
user nor the roleTarget --> we have orphaned userWorkspace, not
technically but product wise - a userWorkspace without a workspaceMember
does not make sense

So the problems are
- we have some roleTargets pointing to non-existing userWorkspaceId
(which caused https://github.com/twentyhq/twenty/issues/14608 )
- we have userWorkspaces that should not exist and that have no
workspaceMember counterpart
- it is not possible for a user to leave a workspace by themselves, they
can only leave all workspaces at once, except if they are being removed
from the workspace by another user

**Now**
- if a user has multiple workspaces, they are given the possibility to
leave one workspace while remaining in the others (we show two buttons:
Leave workspace and Delete account buttons). if a user has just one
workspace, they only see Delete account
- when a user leaves a workspace, we delete their workspaceMember,
userWorkspace and roleTarget. If they don't belong to any other
workspace we also soft-delete their user
- soft-deleted users get hard deleted after 30 days thanks to a cron
- we have two commands to clean the orphans roleTarget and userWorkspace
(TODO: query db to see how many must be run)

**Next**
- once the commands have been run, we can implement and introduce the
foreign key constraint on roleTarget


Fixes https://github.com/twentyhq/twenty/issues/14608
2025-11-06 18:29:12 +00:00

191 lines
5.8 KiB
TypeScript

import request from 'supertest';
import { signUpOperationFactory } from 'test/integration/graphql/utils/sign-up-operation-factory.util';
import { ErrorCode } from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
import { PermissionsExceptionMessage } from 'src/engine/metadata-modules/permissions/permissions.exception';
import { WORKSPACE_MEMBER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/workspace-member-data-seeds.constant';
const client = request(`http://localhost:${APP_PORT}`);
describe('deleteUser', () => {
it('should not allow to delete user if they are the unique admin of a workspace', async () => {
const query = {
query: `
mutation DeleteUser {
deleteUser {
id
}
}
`,
};
await client
.post('/graphql')
.set('Authorization', `Bearer ${APPLE_JANE_ADMIN_ACCESS_TOKEN}`)
.send(query)
.expect((res) => {
expect(res.body.data).toBeNull();
expect(res.body.errors).toBeDefined();
expect(res.body.errors[0].message).toBe(
'Cannot delete account: user is the unique admin of a workspace',
);
expect(res.body.errors[0].extensions.code).toBe(ErrorCode.FORBIDDEN);
});
});
it('should deny deleting another user when caller lacks WORKSPACE_MEMBERS permission', async () => {
const query = {
query: `
mutation DeleteUserFromWorkspace {
deleteUserFromWorkspace(workspaceMemberIdToDelete: "${WORKSPACE_MEMBER_DATA_SEED_IDS.JANE}") {
id
}
}
`,
};
await client
.post('/graphql')
.set('Authorization', `Bearer ${APPLE_JONY_MEMBER_ACCESS_TOKEN}`)
.send(query)
.expect(200)
.expect((res) => {
expect(res.body.data).toBeNull();
expect(res.body.errors).toBeDefined();
expect(res.body.errors[0].message).toBe(
PermissionsExceptionMessage.PERMISSION_DENIED,
);
expect(res.body.errors[0].extensions.code).toBe(ErrorCode.FORBIDDEN);
});
});
it('should soft delete user and remove workspace relations when deleting a user in their only workspace', async () => {
// 1. Arrange
// Enable public invite link to allow sign up without personal token
const enablePublicInviteLinkMutation = {
query: `
mutation updateWorkspace {
updateWorkspace(data: { isPublicInviteLinkEnabled: true }) {
id
isPublicInviteLinkEnabled
}
}
`,
};
await client
.post('/graphql')
.set('Authorization', `Bearer ${APPLE_JANE_ADMIN_ACCESS_TOKEN}`)
.send(enablePublicInviteLinkMutation)
.expect(200)
.expect((res) => {
expect(res.body.errors).toBeUndefined();
expect(res.body.data.updateWorkspace.isPublicInviteLinkEnabled).toBe(
true,
);
});
// Sign up a new user into the current workspace via public invite link
const testEmail = `test_user_${Date.now()}@example.com`;
const signUpMutation = signUpOperationFactory({
email: testEmail,
password: 'Password123!',
});
const signUpResponse = await client.post('/graphql').send(signUpMutation);
expect(signUpResponse.status).toBe(200);
expect(signUpResponse.body.errors).toBeUndefined();
// Query workspace members and find the created user by email to get workspaceMemberId
const newWorkspaceMemberQuery = {
query: `
query WorkspaceMember($workspaceMemberFilter: WorkspaceMemberFilterInput!) {
workspaceMember(filter: $workspaceMemberFilter) {
id
userId
userWorkspaceId
}
}
`,
variables: {
workspaceMemberFilter: {
userEmail: {
eq: testEmail,
},
},
},
} as const;
const newMemberResponse = await client
.post('/graphql')
.set('Authorization', `Bearer ${APPLE_JANE_ADMIN_ACCESS_TOKEN}`)
.send(newWorkspaceMemberQuery);
expect(newMemberResponse.status).toBe(200);
const createdMember = newMemberResponse.body.data.workspaceMember;
expect(createdMember).toBeDefined();
const createdWorkspaceMemberId = createdMember.id;
// 2. Act
const deleteUserFromWorkspaceMutation = {
query: `
mutation DeleteUserFromWorkspace {
deleteUserFromWorkspace(workspaceMemberIdToDelete: "${createdWorkspaceMemberId}") {
id
}
}
`,
};
const deleteResponse = await client
.post('/graphql')
.set('Authorization', `Bearer ${APPLE_JANE_ADMIN_ACCESS_TOKEN}`)
.send(deleteUserFromWorkspaceMutation);
expect(deleteResponse.status).toBe(200);
expect(deleteResponse.body.errors).toBeUndefined();
// 3. Assert
const membersAfterDeletionResponse = await client
.post('/graphql')
.set('Authorization', `Bearer ${APPLE_JANE_ADMIN_ACCESS_TOKEN}`)
.send(newWorkspaceMemberQuery);
const createdMemberAfterDeletion =
membersAfterDeletionResponse.body.data.workspaceMember;
expect(createdMemberAfterDeletion).toBeNull();
const getRolesWithMembersQuery = {
query: `
query GetRoles {
getRoles { id label workspaceMembers { id } }
}
`,
};
const rolesResponse = await client
.post('/graphql')
.set('Authorization', `Bearer ${APPLE_JANE_ADMIN_ACCESS_TOKEN}`)
.send(getRolesWithMembersQuery);
expect(rolesResponse.status).toBe(200);
expect(rolesResponse.body.errors).toBeUndefined();
const roles = rolesResponse.body.data.getRoles as Array<{
id: string;
workspaceMembers: Array<{ id: string }>;
}>;
for (const role of roles) {
expect(
role.workspaceMembers.find((wm) => wm.id === createdWorkspaceMemberId),
).toBeUndefined();
}
});
});