Skip to content

The open alternative to Salesforce, designed for AI.

Return 403 for REST permission denials and rework the CRUD permission specs (#29537)

Charles Bocheteea1200176bf
diff --git a/packages/twenty-server/src/engine/api/rest/core/controllers/rest-api-core.controller.ts b/packages/twenty-server/src/engine/api/rest/core/controllers/rest-api-core.controller.ts
index c9b0ecc6885..453e8b46787 100644
--- a/packages/twenty-server/src/engine/api/rest/core/controllers/rest-api-core.controller.ts
+++ b/packages/twenty-server/src/engine/api/rest/core/controllers/rest-api-core.controller.ts
@@ -22,6 +22,7 @@ import { CustomPermissionGuard } from 'src/engine/guards/custom-permission.guard
import { JwtAuthGuard } from 'src/engine/guards/jwt-auth.guard';
import { AuthPrincipalGuard } from 'src/engine/guards/auth-principal.guard';
import { AuthRestApiExceptionFilter } from 'src/engine/core-modules/auth/filters/auth-rest-api-exception.filter';
+import { PermissionsRestApiExceptionFilter } from 'src/engine/permissions/utils/permissions-rest-api-exception.filter';
@Controller(ApiPath.Rest)
@UseGuards(
@@ -39,7 +40,11 @@ import { AuthRestApiExceptionFilter } from 'src/engine/core-modules/auth/filters
}),
CustomPermissionGuard,
)
-@UseFilters(RestApiExceptionFilter, AuthRestApiExceptionFilter)
+@UseFilters(
+ RestApiExceptionFilter,
+ AuthRestApiExceptionFilter,
+ PermissionsRestApiExceptionFilter,
+)
export class RestApiCoreController {
private readonly logger = new Logger(RestApiCoreController.name);
constructor(private readonly restApiCoreService: RestApiCoreService) {}
diff --git a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/destroy-many-object-records-permissions.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/object-generated/people-destroy-many.integration-spec.ts
similarity index 54%
rename from packages/twenty-server/test/integration/graphql/suites/object-records-permissions/destroy-many-object-records-permissions.integration-spec.ts
rename to packages/twenty-server/test/integration/graphql/suites/object-generated/people-destroy-many.integration-spec.ts
index 40615c35e97..d7871f878b2 100644
--- a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/destroy-many-object-records-permissions.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/object-generated/people-destroy-many.integration-spec.ts
@@ -3,43 +3,18 @@ import { randomUUID } from 'node:crypto';
import { PERSON_GQL_FIELDS } from 'test/integration/constants/person-gql-fields.constants';
import { createManyOperationFactory } from 'test/integration/graphql/utils/create-many-operation-factory.util';
import { destroyManyOperationFactory } from 'test/integration/graphql/utils/destroy-many-operation-factory.util';
-import { makeGraphqlApiRequestWithGuestRole } from 'test/integration/graphql/utils/make-graphql-api-request-with-guest-role.util';
import { makeGraphqlApiRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';
import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
import { DatabaseEventAction } from 'src/engine/api/graphql/graphql-query-runner/enums/database-event-action';
-import { ErrorCode } from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
-import { PermissionsExceptionMessage } from 'src/engine/permissions/permissions.exception';
import { type WorkspaceEventEmitter } from 'src/engine/workspace-event-emitter/workspace-event-emitter';
-describe('destroyManyObjectRecordsPermissions', () => {
+describe('destroyPeople', () => {
afterEach(() => {
jest.restoreAllMocks();
});
- it('should throw a permission error when user does not have permission (guest role)', async () => {
- const graphqlOperation = destroyManyOperationFactory({
- objectMetadataSingularName: 'person',
- objectMetadataPluralName: 'people',
- gqlFields: PERSON_GQL_FIELDS,
- filter: {
- id: {
- in: [randomUUID(), randomUUID()],
- },
- },
- });
-
- const response = await makeGraphqlApiRequestWithGuestRole(graphqlOperation);
-
- expect(response.body.data).toStrictEqual({ destroyPeople: null });
- expect(response.body.errors).toBeDefined();
- expect(response.body.errors[0].message).toBe(
- PermissionsExceptionMessage.PERMISSION_DENIED,
- );
- expect(response.body.errors[0].extensions.code).toBe(ErrorCode.FORBIDDEN);
- });
-
- it('should destroy multiple object records when user has permission (admin role)', async () => {
+ it('should emit a DESTROYED event for the destroyed records and none when repeated', async () => {
const workspaceEventEmitter =
getAppProviderByClassName<WorkspaceEventEmitter>('WorkspaceEventEmitter');
const emitEventSpy = jest.spyOn(
@@ -50,41 +25,28 @@ describe('destroyManyObjectRecordsPermissions', () => {
const personId1 = randomUUID();
const personId2 = randomUUID();
- const createGraphqlOperation = createManyOperationFactory({
- objectMetadataSingularName: 'person',
- objectMetadataPluralName: 'people',
- gqlFields: PERSON_GQL_FIELDS,
- data: [
- {
- id: personId1,
- },
- {
- id: personId2,
- },
- ],
- });
-
- const createResponse = await makeGraphqlApiRequest(createGraphqlOperation);
+ const createResponse = await makeGraphqlApiRequest(
+ createManyOperationFactory({
+ objectMetadataSingularName: 'person',
+ objectMetadataPluralName: 'people',
+ gqlFields: PERSON_GQL_FIELDS,
+ data: [{ id: personId1 }, { id: personId2 }],
+ }),
+ );
expect(createResponse.body.errors).toBeUndefined();
emitEventSpy.mockClear();
- const graphqlOperation = destroyManyOperationFactory({
+ const destroyPeopleOperation = destroyManyOperationFactory({
objectMetadataSingularName: 'person',
objectMetadataPluralName: 'people',
gqlFields: PERSON_GQL_FIELDS,
- filter: {
- id: {
- in: [personId1, personId2],
- },
- },
+ filter: { id: { in: [personId1, personId2] } },
});
- const response = await makeGraphqlApiRequest(graphqlOperation);
+ const response = await makeGraphqlApiRequest(destroyPeopleOperation);
expect(response.body.errors).toBeUndefined();
- expect(response.body.data).toBeDefined();
- expect(response.body.data.destroyPeople).toBeDefined();
expect(response.body.data.destroyPeople).toHaveLength(2);
expect(response.body.data.destroyPeople).toEqual(
expect.arrayContaining([
@@ -105,7 +67,7 @@ describe('destroyManyObjectRecordsPermissions', () => {
emitEventSpy.mockClear();
- const repeatResponse = await makeGraphqlApiRequest(graphqlOperation);
+ const repeatResponse = await makeGraphqlApiRequest(destroyPeopleOperation);
expect(repeatResponse.body.errors).toBeUndefined();
expect(repeatResponse.body.data.destroyPeople).toEqual([]);
diff --git a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/create-many-object-records-permissions.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/create-many-object-records-permissions.integration-spec.ts
deleted file mode 100644
index b4319c63a51..00000000000
--- a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/create-many-object-records-permissions.integration-spec.ts
+++ /dev/null
@@ -1,111 +0,0 @@
-import { randomUUID } from 'node:crypto';
-
-import { PERSON_GQL_FIELDS } from 'test/integration/constants/person-gql-fields.constants';
-import { createManyOperationFactory } from 'test/integration/graphql/utils/create-many-operation-factory.util';
-import { makeGraphqlApiRequestWithApiKey } from 'test/integration/graphql/utils/make-graphql-api-request-with-api-key.util';
-import { makeGraphqlApiRequestWithGuestRole } from 'test/integration/graphql/utils/make-graphql-api-request-with-guest-role.util';
-import { makeGraphqlApiRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';
-import { deleteRecordsByIds } from 'test/integration/utils/delete-records-by-ids';
-
-import { ErrorCode } from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
-import { PermissionsExceptionMessage } from 'src/engine/permissions/permissions.exception';
-
-describe('createManyObjectRecordsPermissions', () => {
- let createdPersonIds: string[] = [];
-
- afterEach(async () => {
- if (createdPersonIds.length > 0) {
- await deleteRecordsByIds('person', createdPersonIds);
- createdPersonIds = [];
- }
- });
-
- it('should throw a permission error when user does not have permission (guest role)', async () => {
- const graphqlOperation = createManyOperationFactory({
- objectMetadataSingularName: 'person',
- objectMetadataPluralName: 'people',
- gqlFields: PERSON_GQL_FIELDS,
- data: [
- {
- id: randomUUID(),
- },
- {
- id: randomUUID(),
- },
- ],
- });
-
- const response = await makeGraphqlApiRequestWithGuestRole(graphqlOperation);
-
- expect(response.body.data).toStrictEqual({ createPeople: null });
- expect(response.body.errors).toBeDefined();
- expect(response.body.errors[0].message).toBe(
- PermissionsExceptionMessage.PERMISSION_DENIED,
- );
- expect(response.body.errors[0].extensions.code).toBe(ErrorCode.FORBIDDEN);
- });
-
- it('should create multiple object records when user has permission (admin role)', async () => {
- const personId1 = randomUUID();
- const personId2 = randomUUID();
-
- const graphqlOperation = createManyOperationFactory({
- objectMetadataSingularName: 'person',
- objectMetadataPluralName: 'people',
- gqlFields: PERSON_GQL_FIELDS,
- data: [
- {
- id: personId1,
- },
- {
- id: personId2,
- },
- ],
- });
-
- const response = await makeGraphqlApiRequest(graphqlOperation);
-
- createdPersonIds.push(personId1, personId2);
-
- expect(response.body.data).toBeDefined();
- expect(response.body.data.createPeople).toBeDefined();
- expect(response.body.data.createPeople).toHaveLength(2);
- expect([
- response.body.data.createPeople[0].id,
- response.body.data.createPeople[1].id,
- ]).toContain(personId1);
- expect([
- response.body.data.createPeople[0].id,
- response.body.data.createPeople[1].id,
- ]).toContain(personId2);
- });
-
- it('should create multiple object records when executed by api key', async () => {
- const personId1 = randomUUID();
- const personId2 = randomUUID();
-
- const graphqlOperation = createManyOperationFactory({
- objectMetadataSingularName: 'person',
- objectMetadataPluralName: 'people',
- gqlFields: PERSON_GQL_FIELDS,
- data: [
- {
- id: personId1,
- },
- {
- id: personId2,
- },
- ],
- });
-
- const response = await makeGraphqlApiRequestWithApiKey(graphqlOperation);
-
- createdPersonIds.push(personId1, personId2);
-
- expect(response.body.data).toBeDefined();
- expect(response.body.data.createPeople).toBeDefined();
- expect(response.body.data.createPeople).toHaveLength(2);
- expect(response.body.data.createPeople[0].id).toBe(personId1);
- expect(response.body.data.createPeople[1].id).toBe(personId2);
- });
-});
diff --git a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/create-one-object-records-permissions.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/create-one-object-records-permissions.integration-spec.ts
deleted file mode 100644
index 794f3b0d4c6..00000000000
--- a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/create-one-object-records-permissions.integration-spec.ts
+++ /dev/null
@@ -1,79 +0,0 @@
-import { randomUUID } from 'node:crypto';
-
-import { PERSON_GQL_FIELDS } from 'test/integration/constants/person-gql-fields.constants';
-import { createOneOperationFactory } from 'test/integration/graphql/utils/create-one-operation-factory.util';
-import { makeGraphqlApiRequestWithApiKey } from 'test/integration/graphql/utils/make-graphql-api-request-with-api-key.util';
-import { makeGraphqlApiRequestWithGuestRole } from 'test/integration/graphql/utils/make-graphql-api-request-with-guest-role.util';
-import { makeGraphqlApiRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';
-import { deleteRecordsByIds } from 'test/integration/utils/delete-records-by-ids';
-
-import { ErrorCode } from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
-import { PermissionsExceptionMessage } from 'src/engine/permissions/permissions.exception';
-
-describe('createOneObjectRecordsPermissions', () => {
- let createdPersonIds: string[] = [];
-
- afterEach(async () => {
- if (createdPersonIds.length > 0) {
- await deleteRecordsByIds('person', createdPersonIds);
- createdPersonIds = [];
- }
- });
-
- it('should throw a permission error when user does not have permission (guest role)', async () => {
- const graphqlOperation = createOneOperationFactory({
- objectMetadataSingularName: 'person',
- gqlFields: PERSON_GQL_FIELDS,
- data: {
- id: randomUUID(),
- },
- });
-
- const response = await makeGraphqlApiRequestWithGuestRole(graphqlOperation);
-
- expect(response.body.data).toStrictEqual({ createPerson: null });
- expect(response.body.errors).toBeDefined();
- expect(response.body.errors[0].message).toBe(
- PermissionsExceptionMessage.PERMISSION_DENIED,
- );
- expect(response.body.errors[0].extensions.code).toBe(ErrorCode.FORBIDDEN);
- });
-
- it('should create an object record when user has permission (admin role)', async () => {
- const personId = randomUUID();
- const graphqlOperation = createOneOperationFactory({
- objectMetadataSingularName: 'person',
- gqlFields: PERSON_GQL_FIELDS,
- data: {
- id: personId,
- },
- });
-
- const response = await makeGraphqlApiRequest(graphqlOperation);
-
- createdPersonIds.push(personId);
-
- expect(response.body.data).toBeDefined();
- expect(response.body.data.createPerson).toBeDefined();
- expect(response.body.data.createPerson.id).toBe(personId);
- });
-
- it('should create an object record when executed by api key', async () => {
- const personId = randomUUID();
- const graphqlOperation = createOneOperationFactory({
- objectMetadataSingularName: 'person',
- gqlFields: PERSON_GQL_FIELDS,
- data: {
- id: personId,
- },
- });
-
- const response = await makeGraphqlApiRequestWithApiKey(graphqlOperation);
-
- createdPersonIds.push(personId);
-
- expect(response.body.data).toBeDefined();
- expect(response.body.data.createPerson).toBeDefined();
- expect(response.body.data.createPerson.id).toBe(personId);
- });
-});
diff --git a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/delete-many-object-records-permissions.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/delete-many-object-records-permissions.integration-spec.ts
deleted file mode 100644
index b16d764b8e4..00000000000
--- a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/delete-many-object-records-permissions.integration-spec.ts
+++ /dev/null
@@ -1,137 +0,0 @@
-import { randomUUID } from 'node:crypto';
-
-import { PERSON_GQL_FIELDS } from 'test/integration/constants/person-gql-fields.constants';
-import { createManyOperationFactory } from 'test/integration/graphql/utils/create-many-operation-factory.util';
-import { deleteManyOperationFactory } from 'test/integration/graphql/utils/delete-many-operation-factory.util';
-import { makeGraphqlApiRequestWithApiKey } from 'test/integration/graphql/utils/make-graphql-api-request-with-api-key.util';
-import { makeGraphqlApiRequestWithGuestRole } from 'test/integration/graphql/utils/make-graphql-api-request-with-guest-role.util';
-import { makeGraphqlApiRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';
-import { deleteRecordsByIds } from 'test/integration/utils/delete-records-by-ids';
-
-import { ErrorCode } from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
-import { PermissionsExceptionMessage } from 'src/engine/permissions/permissions.exception';
-
-describe('deleteManyObjectRecordsPermissions', () => {
- let createdPersonIds: string[] = [];
-
- afterEach(async () => {
- if (createdPersonIds.length > 0) {
- await deleteRecordsByIds('person', createdPersonIds);
- createdPersonIds = [];
- }
- });
-
- it('should throw a permission error when user does not have permission (guest role)', async () => {
- const graphqlOperation = deleteManyOperationFactory({
- objectMetadataSingularName: 'person',
- objectMetadataPluralName: 'people',
- gqlFields: PERSON_GQL_FIELDS,
- filter: {
- id: {
- in: [randomUUID(), randomUUID()],
- },
- },
- });
-
- const response = await makeGraphqlApiRequestWithGuestRole(graphqlOperation);
-
- expect(response.body.data).toStrictEqual({ deletePeople: null });
- expect(response.body.errors).toBeDefined();
- expect(response.body.errors[0].message).toBe(
- PermissionsExceptionMessage.PERMISSION_DENIED,
- );
- expect(response.body.errors[0].extensions.code).toBe(ErrorCode.FORBIDDEN);
- });
-
- it('should delete multiple object records when user has permission (admin role)', async () => {
- const personId1 = randomUUID();
- const personId2 = randomUUID();
-
- const createGraphqlOperation = createManyOperationFactory({
- objectMetadataSingularName: 'person',
- objectMetadataPluralName: 'people',
- gqlFields: PERSON_GQL_FIELDS,
- data: [
- {
- id: personId1,
- },
- {
- id: personId2,
- },
- ],
- });
-
- await makeGraphqlApiRequest(createGraphqlOperation);
- createdPersonIds.push(personId1, personId2);
-
- const deleteGraphqlOperation = deleteManyOperationFactory({
- objectMetadataSingularName: 'person',
- objectMetadataPluralName: 'people',
- gqlFields: PERSON_GQL_FIELDS,
- filter: {
- id: {
- in: [personId1, personId2],
- },
- },
- });
-
- const response = await makeGraphqlApiRequest(deleteGraphqlOperation);
-
- expect(response.body.data).toBeDefined();
- expect(response.body.data.deletePeople).toBeDefined();
- expect(response.body.data.deletePeople).toHaveLength(2);
- expect(response.body.data.deletePeople).toEqual(
- expect.arrayContaining([
- expect.objectContaining({ id: personId1 }),
- expect.objectContaining({ id: personId2 }),
- ]),
- );
- });
-
- it('should delete multiple object records when executed by api key', async () => {
- const personId1 = randomUUID();
- const personId2 = randomUUID();
-
- const createGraphqlOperation = createManyOperationFactory({
- objectMetadataSingularName: 'person',
- objectMetadataPluralName: 'people',
- gqlFields: PERSON_GQL_FIELDS,
- data: [
- {
- id: personId1,
- },
- {
- id: personId2,
- },
- ],
- });
-
- await makeGraphqlApiRequest(createGraphqlOperation);
- createdPersonIds.push(personId1, personId2);
-
- const deleteGraphqlOperation = deleteManyOperationFactory({
- objectMetadataSingularName: 'person',
- objectMetadataPluralName: 'people',
- gqlFields: PERSON_GQL_FIELDS,
- filter: {
- id: {
- in: [personId1, personId2],
- },
- },
- });
-
- const response = await makeGraphqlApiRequestWithApiKey(
- deleteGraphqlOperation,
- );
-
- expect(response.body.data).toBeDefined();
- expect(response.body.data.deletePeople).toBeDefined();
- expect(response.body.data.deletePeople).toHaveLength(2);
- expect(response.body.data.deletePeople).toEqual(
- expect.arrayContaining([
- expect.objectContaining({ id: personId1 }),
- expect.objectContaining({ id: personId2 }),
- ]),
- );
- });
-});
diff --git a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/delete-one-object-records-permissions.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/delete-one-object-records-permissions.integration-spec.ts
deleted file mode 100644
index c82f7edfa4b..00000000000
--- a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/delete-one-object-records-permissions.integration-spec.ts
+++ /dev/null
@@ -1,111 +0,0 @@
-import { randomUUID } from 'node:crypto';
-
-import { PERSON_GQL_FIELDS } from 'test/integration/constants/person-gql-fields.constants';
-import { createOneOperationFactory } from 'test/integration/graphql/utils/create-one-operation-factory.util';
-import { deleteOneOperationFactory } from 'test/integration/graphql/utils/delete-one-operation-factory.util';
-import { makeGraphqlApiRequestWithApiKey } from 'test/integration/graphql/utils/make-graphql-api-request-with-api-key.util';
-import { makeGraphqlApiRequestWithGuestRole } from 'test/integration/graphql/utils/make-graphql-api-request-with-guest-role.util';
-import { makeGraphqlApiRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';
-
-import { ErrorCode } from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
-import { PermissionsExceptionMessage } from 'src/engine/permissions/permissions.exception';
-
-describe('deleteOneObjectRecordsPermissions', () => {
- describe('permissions V2 enabled', () => {
- const personId = randomUUID();
-
- beforeAll(async () => {
- const createOnePersonRecordOperation = createOneOperationFactory({
- objectMetadataSingularName: 'person',
- gqlFields: PERSON_GQL_FIELDS,
- data: {
- id: personId,
- },
- });
-
- await makeGraphqlApiRequest(createOnePersonRecordOperation);
- });
-
- it('should throw a permission error when user does not have permission (guest role)', async () => {
- const personId = randomUUID();
- const createGraphqlOperation = createOneOperationFactory({
- objectMetadataSingularName: 'person',
- gqlFields: PERSON_GQL_FIELDS,
- data: {
- id: personId,
- },
- });
-
- await makeGraphqlApiRequest(createGraphqlOperation);
-
- const deleteGraphqlOperation = deleteOneOperationFactory({
- objectMetadataSingularName: 'person',
- gqlFields: PERSON_GQL_FIELDS,
- recordId: personId,
- });
-
- const response = await makeGraphqlApiRequestWithGuestRole(
- deleteGraphqlOperation,
- );
-
- expect(response.body.data).toStrictEqual({ deletePerson: null });
- expect(response.body.errors).toBeDefined();
- expect(response.body.errors[0].message).toBe(
- PermissionsExceptionMessage.PERMISSION_DENIED,
- );
- expect(response.body.errors[0].extensions.code).toBe(ErrorCode.FORBIDDEN);
- });
-
- it('should delete an object record when user has permission (admin role)', async () => {
- const personId = randomUUID();
- const createGraphqlOperation = createOneOperationFactory({
- objectMetadataSingularName: 'person',
- gqlFields: PERSON_GQL_FIELDS,
- data: {
- id: personId,
- },
- });
-
- await makeGraphqlApiRequest(createGraphqlOperation);
-
- const deleteGraphqlOperation = deleteOneOperationFactory({
- objectMetadataSingularName: 'person',
- gqlFields: PERSON_GQL_FIELDS,
- recordId: personId,
- });
-
- const response = await makeGraphqlApiRequest(deleteGraphqlOperation);
-
- expect(response.body.data).toBeDefined();
- expect(response.body.data.deletePerson).toBeDefined();
- expect(response.body.data.deletePerson.id).toBe(personId);
- });
-
- it('should delete an object record when executed by api key', async () => {
- const personId = randomUUID();
- const createGraphqlOperation = createOneOperationFactory({
- objectMetadataSingularName: 'person',
- gqlFields: PERSON_GQL_FIELDS,
- data: {
- id: personId,
- },
- });
-
- await makeGraphqlApiRequest(createGraphqlOperation);
-
- const deleteGraphqlOperation = deleteOneOperationFactory({
- objectMetadataSingularName: 'person',
- gqlFields: PERSON_GQL_FIELDS,
- recordId: personId,
- });
-
- const response = await makeGraphqlApiRequestWithApiKey(
- deleteGraphqlOperation,
- );
-
- expect(response.body.data).toBeDefined();
- expect(response.body.data.deletePerson).toBeDefined();
- expect(response.body.data.deletePerson.id).toBe(personId);
- });
- });
-});
diff --git a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/destroy-one-object-records-permissions.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/destroy-one-object-records-permissions.integration-spec.ts
deleted file mode 100644
index 02e89fffb82..00000000000
--- a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/destroy-one-object-records-permissions.integration-spec.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import { randomUUID } from 'node:crypto';
-
-import { PERSON_GQL_FIELDS } from 'test/integration/constants/person-gql-fields.constants';
-import { createOneOperationFactory } from 'test/integration/graphql/utils/create-one-operation-factory.util';
-import { destroyOneOperationFactory } from 'test/integration/graphql/utils/destroy-one-operation-factory.util';
-import { makeGraphqlApiRequestWithGuestRole } from 'test/integration/graphql/utils/make-graphql-api-request-with-guest-role.util';
-import { makeGraphqlApiRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';
-
-import { ErrorCode } from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
-import { PermissionsExceptionMessage } from 'src/engine/permissions/permissions.exception';
-
-describe('destroyOneObjectRecordsPermissions', () => {
- const personId = randomUUID();
-
- beforeAll(async () => {
- const createGraphqlOperation = createOneOperationFactory({
- objectMetadataSingularName: 'person',
- gqlFields: PERSON_GQL_FIELDS,
- data: {
- id: personId,
- },
- });
-
- await makeGraphqlApiRequest(createGraphqlOperation);
- });
-
- it('should throw a permission error when user does not have permission (guest role)', async () => {
- const personId = randomUUID();
- const graphqlOperation = destroyOneOperationFactory({
- objectMetadataSingularName: 'person',
- gqlFields: PERSON_GQL_FIELDS,
- recordId: personId,
- });
-
- const response = await makeGraphqlApiRequestWithGuestRole(graphqlOperation);
-
- expect(response.body.data).toStrictEqual({ destroyPerson: null });
- expect(response.body.errors).toBeDefined();
- expect(response.body.errors[0].message).toBe(
- PermissionsExceptionMessage.PERMISSION_DENIED,
- );
- expect(response.body.errors[0].extensions.code).toBe(ErrorCode.FORBIDDEN);
- });
-
- it('should destroy an object record when user has permission (admin role)', async () => {
- const graphqlOperation = destroyOneOperationFactory({
- objectMetadataSingularName: 'person',
- gqlFields: PERSON_GQL_FIELDS,
- recordId: personId,
- });
-
- const response = await makeGraphqlApiRequest(graphqlOperation);
-
- expect(response.body.data).toBeDefined();
- expect(response.body.data.destroyPerson).toBeDefined();
- expect(response.body.data.destroyPerson.id).toBe(personId);
- });
-});
diff --git a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/restore-many-object-records-permissions.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/restore-many-object-records-permissions.integration-spec.ts
deleted file mode 100644
index df2a40785bb..00000000000
--- a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/restore-many-object-records-permissions.integration-spec.ts
+++ /dev/null
@@ -1,91 +0,0 @@
-import { randomUUID } from 'node:crypto';
-
-import { PERSON_GQL_FIELDS } from 'test/integration/constants/person-gql-fields.constants';
-import { createManyOperationFactory } from 'test/integration/graphql/utils/create-many-operation-factory.util';
-import { deleteManyOperationFactory } from 'test/integration/graphql/utils/delete-many-operation-factory.util';
-import { makeGraphqlApiRequestWithGuestRole } from 'test/integration/graphql/utils/make-graphql-api-request-with-guest-role.util';
-import { makeGraphqlApiRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';
-import { restoreManyOperationFactory } from 'test/integration/graphql/utils/restore-many-operation-factory.util';
-
-import { ErrorCode } from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
-import { PermissionsExceptionMessage } from 'src/engine/permissions/permissions.exception';
-
-describe('restoreManyObjectRecordsPermissions', () => {
- const personId1 = randomUUID();
- const personId2 = randomUUID();
-
- beforeAll(async () => {
- const createGraphqlOperation = createManyOperationFactory({
- objectMetadataSingularName: 'person',
- objectMetadataPluralName: 'people',
- gqlFields: PERSON_GQL_FIELDS,
- data: [
- {
- id: personId1,
- },
- {
- id: personId2,
- },
- ],
- });
-
- await makeGraphqlApiRequest(createGraphqlOperation);
-
- const deleteGraphqlOperation = deleteManyOperationFactory({
- objectMetadataSingularName: 'person',
- objectMetadataPluralName: 'people',
- gqlFields: PERSON_GQL_FIELDS,
- filter: {
- id: {
- in: [personId1, personId2],
- },
- },
- });
-
- await makeGraphqlApiRequest(deleteGraphqlOperation);
- });
-
- it('should throw a permission error when user does not have permission (guest role)', async () => {
- const graphqlOperation = restoreManyOperationFactory({
- objectMetadataSingularName: 'person',
- objectMetadataPluralName: 'people',
- gqlFields: PERSON_GQL_FIELDS,
- filter: {
- id: {
- in: [personId1, personId2],
- },
- },
- });
-
- const response = await makeGraphqlApiRequestWithGuestRole(graphqlOperation);
-
- expect(response.body.data).toStrictEqual({ restorePeople: null });
- expect(response.body.errors).toBeDefined();
- expect(response.body.errors[0].message).toBe(
- PermissionsExceptionMessage.PERMISSION_DENIED,
- );
- expect(response.body.errors[0].extensions.code).toBe(ErrorCode.FORBIDDEN);
- });
-
- it('should restore multiple object records when user has permission (admin role)', async () => {
- const graphqlOperation = restoreManyOperationFactory({
- objectMetadataSingularName: 'person',
- objectMetadataPluralName: 'people',
- gqlFields: PERSON_GQL_FIELDS,
- filter: {
- id: {
- in: [personId1, personId2],
- },
- },
- });
-
- const response = await makeGraphqlApiRequest(graphqlOperation);
-
- expect(response.body.data).toBeDefined();
- expect(response.body.data.restorePeople).toBeDefined();
- expect(response.body.data.restorePeople).toHaveLength(2);
- expect(
- response.body.data.restorePeople.map((person: any) => person.id),
- ).toEqual(expect.arrayContaining([personId1, personId2]));
- });
-});
diff --git a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/restore-one-object-records-permissions.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/restore-one-object-records-permissions.integration-spec.ts
deleted file mode 100644
index c97b7bf6622..00000000000
--- a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/restore-one-object-records-permissions.integration-spec.ts
+++ /dev/null
@@ -1,66 +0,0 @@
-import { randomUUID } from 'node:crypto';
-
-import { PERSON_GQL_FIELDS } from 'test/integration/constants/person-gql-fields.constants';
-import { createOneOperationFactory } from 'test/integration/graphql/utils/create-one-operation-factory.util';
-import { deleteOneOperationFactory } from 'test/integration/graphql/utils/delete-one-operation-factory.util';
-import { makeGraphqlApiRequestWithGuestRole } from 'test/integration/graphql/utils/make-graphql-api-request-with-guest-role.util';
-import { makeGraphqlApiRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';
-import { restoreOneOperationFactory } from 'test/integration/graphql/utils/restore-one-operation-factory.util';
-
-import { ErrorCode } from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
-import { PermissionsExceptionMessage } from 'src/engine/permissions/permissions.exception';
-
-describe('restoreOneObjectRecordsPermissions', () => {
- const personId = randomUUID();
-
- beforeAll(async () => {
- const createGraphqlOperation = createOneOperationFactory({
- objectMetadataSingularName: 'person',
- gqlFields: PERSON_GQL_FIELDS,
- data: {
- id: personId,
- },
- });
-
- await makeGraphqlApiRequest(createGraphqlOperation);
-
- const deleteGraphqlOperation = deleteOneOperationFactory({
- objectMetadataSingularName: 'person',
- gqlFields: PERSON_GQL_FIELDS,
- recordId: personId,
- });
-
- await makeGraphqlApiRequest(deleteGraphqlOperation);
- });
-
- it('should throw a permission error when user does not have permission (guest role)', async () => {
- const graphqlOperation = restoreOneOperationFactory({
- objectMetadataSingularName: 'person',
- gqlFields: PERSON_GQL_FIELDS,
- recordId: personId,
- });
-
- const response = await makeGraphqlApiRequestWithGuestRole(graphqlOperation);
-
- expect(response.body.data).toStrictEqual({ restorePerson: null });
- expect(response.body.errors).toBeDefined();
- expect(response.body.errors[0].message).toBe(
- PermissionsExceptionMessage.PERMISSION_DENIED,
- );
- expect(response.body.errors[0].extensions.code).toBe(ErrorCode.FORBIDDEN);
- });
-
- it('should restore an object record when user has permission (admin role)', async () => {
- const graphqlOperation = restoreOneOperationFactory({
- objectMetadataSingularName: 'person',
- gqlFields: PERSON_GQL_FIELDS,
- recordId: personId,
- });
-
- const response = await makeGraphqlApiRequest(graphqlOperation);
-
- expect(response.body.data).toBeDefined();
- expect(response.body.data.restorePerson).toBeDefined();
- expect(response.body.data.restorePerson.id).toBe(personId);
- });
-});
diff --git a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/update-many-object-records-permissions.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/update-many-object-records-permissions.integration-spec.ts
deleted file mode 100644
index 3dc72a7bed5..00000000000
--- a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/update-many-object-records-permissions.integration-spec.ts
+++ /dev/null
@@ -1,170 +0,0 @@
-import { randomUUID } from 'node:crypto';
-
-import { PERSON_GQL_FIELDS } from 'test/integration/constants/person-gql-fields.constants';
-import { createManyOperationFactory } from 'test/integration/graphql/utils/create-many-operation-factory.util';
-import { makeGraphqlApiRequestWithApiKey } from 'test/integration/graphql/utils/make-graphql-api-request-with-api-key.util';
-import { makeGraphqlApiRequestWithGuestRole } from 'test/integration/graphql/utils/make-graphql-api-request-with-guest-role.util';
-import { makeGraphqlApiRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';
-import { updateManyOperationFactory } from 'test/integration/graphql/utils/update-many-operation-factory.util';
-import { deleteRecordsByIds } from 'test/integration/utils/delete-records-by-ids';
-
-import { ErrorCode } from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
-import { PermissionsExceptionMessage } from 'src/engine/permissions/permissions.exception';
-
-type RecordWithId = { id: string; [key: string]: unknown };
-
-// updateMany returns its RETURNING rows in an unspecified order, so key them by
-// id rather than asserting positionally.
-const keyRecordsById = (
- records: RecordWithId[],
-): Record<string, RecordWithId> =>
- Object.fromEntries(records.map((record) => [record.id, record]));
-
-describe('updateManyObjectRecordsPermissions', () => {
- let createdPersonIds: string[] = [];
-
- afterEach(async () => {
- if (createdPersonIds.length > 0) {
- await deleteRecordsByIds('person', createdPersonIds);
- createdPersonIds = [];
- }
- });
-
- it('should throw a permission error when user does not have permission (guest role)', async () => {
- const personId1 = randomUUID();
- const personId2 = randomUUID();
- const createGraphqlOperation = createManyOperationFactory({
- objectMetadataSingularName: 'person',
- objectMetadataPluralName: 'people',
- gqlFields: PERSON_GQL_FIELDS,
- data: [
- {
- id: personId1,
- },
- {
- id: personId2,
- },
- ],
- });
-
- await makeGraphqlApiRequest(createGraphqlOperation);
- createdPersonIds.push(personId1, personId2);
-
- const updateGraphqlOperation = updateManyOperationFactory({
- objectMetadataSingularName: 'person',
- objectMetadataPluralName: 'people',
- gqlFields: PERSON_GQL_FIELDS,
- filter: {
- id: {
- in: [personId1, personId2],
- },
- },
- data: {
- jobTitle: 'Senior Developer',
- },
- });
-
- const response = await makeGraphqlApiRequestWithGuestRole(
- updateGraphqlOperation,
- );
-
- expect(response.body.data).toStrictEqual({ updatePeople: null });
- expect(response.body.errors).toBeDefined();
- expect(response.body.errors[0].message).toBe(
- PermissionsExceptionMessage.PERMISSION_DENIED,
- );
- expect(response.body.errors[0].extensions.code).toBe(ErrorCode.FORBIDDEN);
- });
-
- it('should update multiple object records when user has permission (admin role)', async () => {
- const personId1 = randomUUID();
- const personId2 = randomUUID();
- const createGraphqlOperation = createManyOperationFactory({
- objectMetadataSingularName: 'person',
- objectMetadataPluralName: 'people',
- gqlFields: PERSON_GQL_FIELDS,
- data: [
- {
- id: personId1,
- },
- {
- id: personId2,
- },
- ],
- });
-
- await makeGraphqlApiRequest(createGraphqlOperation);
- createdPersonIds.push(personId1, personId2);
-
- const updateGraphqlOperation = updateManyOperationFactory({
- objectMetadataSingularName: 'person',
- objectMetadataPluralName: 'people',
- gqlFields: PERSON_GQL_FIELDS,
- filter: {
- id: {
- in: [personId1, personId2],
- },
- },
- data: {
- jobTitle: 'Tech Lead',
- },
- });
-
- const response = await makeGraphqlApiRequest(updateGraphqlOperation);
-
- expect(response.body.data).toBeDefined();
- expect(response.body.data.updatePeople).toBeDefined();
- expect(response.body.data.updatePeople).toHaveLength(2);
- const updatedPeopleById = keyRecordsById(response.body.data.updatePeople);
-
- expect(updatedPeopleById[personId1]?.jobTitle).toBe('Tech Lead');
- expect(updatedPeopleById[personId2]?.jobTitle).toBe('Tech Lead');
- });
-
- it('should update multiple object records when executed by api key', async () => {
- const personId1 = randomUUID();
- const personId2 = randomUUID();
- const createGraphqlOperation = createManyOperationFactory({
- objectMetadataSingularName: 'person',
- objectMetadataPluralName: 'people',
- gqlFields: PERSON_GQL_FIELDS,
- data: [
- {
- id: personId1,
- },
- {
- id: personId2,
- },
- ],
- });
-
- await makeGraphqlApiRequest(createGraphqlOperation);
- createdPersonIds.push(personId1, personId2);
-
- const updateGraphqlOperation = updateManyOperationFactory({
- objectMetadataSingularName: 'person',
- objectMetadataPluralName: 'people',
- gqlFields: PERSON_GQL_FIELDS,
- filter: {
- id: {
- in: [personId1, personId2],
- },
- },
- data: {
- jobTitle: 'Product Manager',
- },
- });
-
- const response = await makeGraphqlApiRequestWithApiKey(
- updateGraphqlOperation,
- );
-
- expect(response.body.data).toBeDefined();
- expect(response.body.data.updatePeople).toBeDefined();
- expect(response.body.data.updatePeople).toHaveLength(2);
- const updatedPeopleById = keyRecordsById(response.body.data.updatePeople);
-
- expect(updatedPeopleById[personId1]?.jobTitle).toBe('Product Manager');
- expect(updatedPeopleById[personId2]?.jobTitle).toBe('Product Manager');
- });
-});
diff --git a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/update-one-object-records-permissions.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/update-one-object-records-permissions.integration-spec.ts
deleted file mode 100644
index d818c60108e..00000000000
--- a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/update-one-object-records-permissions.integration-spec.ts
+++ /dev/null
@@ -1,147 +0,0 @@
-import { randomUUID } from 'node:crypto';
-
-import { PERSON_GQL_FIELDS } from 'test/integration/constants/person-gql-fields.constants';
-import { createOneOperationFactory } from 'test/integration/graphql/utils/create-one-operation-factory.util';
-import { findOneOperationFactory } from 'test/integration/graphql/utils/find-one-operation-factory.util';
-import { makeGraphqlApiRequestWithApiKey } from 'test/integration/graphql/utils/make-graphql-api-request-with-api-key.util';
-import { makeGraphqlApiRequestWithGuestRole } from 'test/integration/graphql/utils/make-graphql-api-request-with-guest-role.util';
-import { makeGraphqlApiRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';
-import { updateOneOperationFactory } from 'test/integration/graphql/utils/update-one-operation-factory.util';
-
-import { ErrorCode } from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
-import { PermissionsExceptionMessage } from 'src/engine/permissions/permissions.exception';
-
-describe('updateOneObjectRecordsPermissions', () => {
- const personId = randomUUID();
- let messageId: string;
- let originalMessageText: string;
-
- beforeAll(async () => {
- const createPersonOperation = createOneOperationFactory({
- objectMetadataSingularName: 'person',
- gqlFields: PERSON_GQL_FIELDS,
- data: {
- id: personId,
- jobTitle: 'Software Engineer',
- },
- });
-
- await makeGraphqlApiRequest(createPersonOperation);
-
- const findAllMessagesOperation = findOneOperationFactory({
- objectMetadataSingularName: 'message',
- gqlFields: `
- id
- text
- `,
- filter: {
- subject: {
- eq: 'Meeting Request',
- },
- },
- });
-
- const findAllMessagesResponse = await makeGraphqlApiRequest(
- findAllMessagesOperation,
- );
-
- messageId = findAllMessagesResponse.body.data.message.id;
- originalMessageText = findAllMessagesResponse.body.data.message.text;
- });
-
- afterAll(async () => {
- const updateMessageOperation = updateOneOperationFactory({
- objectMetadataSingularName: 'message',
- gqlFields: 'id',
- recordId: messageId,
- data: {
- text: originalMessageText,
- },
- });
-
- await makeGraphqlApiRequest(updateMessageOperation);
- });
-
- it('should throw a permission error when user does not have permission (guest role)', async () => {
- const graphqlOperation = updateOneOperationFactory({
- objectMetadataSingularName: 'person',
- gqlFields: PERSON_GQL_FIELDS,
- recordId: personId,
- data: {
- jobTitle: 'Senior Software Engineer',
- },
- });
-
- const response = await makeGraphqlApiRequestWithGuestRole(graphqlOperation);
-
- expect(response.body.data).toStrictEqual({ updatePerson: null });
- expect(response.body.errors).toBeDefined();
- expect(response.body.errors[0].message).toBe(
- PermissionsExceptionMessage.PERMISSION_DENIED,
- );
- expect(response.body.errors[0].extensions.code).toBe(ErrorCode.FORBIDDEN);
- });
-
- it('should allow to update a system object record even without update permission (guest role)', async () => {
- const graphqlOperation = updateOneOperationFactory({
- objectMetadataSingularName: 'message',
- gqlFields: `
- id
- text
- `,
- recordId: messageId,
- data: {
- text: "Hello, I'm fine, thank you!",
- },
- });
-
- const response = await makeGraphqlApiRequestWithGuestRole(graphqlOperation);
-
- expect(response.body.data).toBeDefined();
- expect(response.body.data.updateMessage).toBeDefined();
- expect(response.body.data.updateMessage.id).toBe(messageId);
- expect(response.body.data.updateMessage.text).toBe(
- "Hello, I'm fine, thank you!",
- );
- });
-
- it('should update an object record when user has permission (admin role)', async () => {
- const graphqlOperation = updateOneOperationFactory({
- objectMetadataSingularName: 'person',
- gqlFields: PERSON_GQL_FIELDS,
- recordId: personId,
- data: {
- jobTitle: 'Senior Software Engineer',
- },
- });
-
- const response = await makeGraphqlApiRequest(graphqlOperation);
-
- expect(response.body.data).toBeDefined();
- expect(response.body.data.updatePerson).toBeDefined();
- expect(response.body.data.updatePerson.id).toBe(personId);
- expect(response.body.data.updatePerson.jobTitle).toBe(
- 'Senior Software Engineer',
- );
- });
-
- it('should update an object record when executed by api key', async () => {
- const graphqlOperation = updateOneOperationFactory({
- objectMetadataSingularName: 'person',
- gqlFields: PERSON_GQL_FIELDS,
- recordId: personId,
- data: {
- jobTitle: 'Senior Software Engineer',
- },
- });
-
- const response = await makeGraphqlApiRequestWithApiKey(graphqlOperation);
-
- expect(response.body.data).toBeDefined();
- expect(response.body.data.updatePerson).toBeDefined();
- expect(response.body.data.updatePerson.id).toBe(personId);
- expect(response.body.data.updatePerson.jobTitle).toBe(
- 'Senior Software Engineer',
- );
- });
-});
diff --git a/packages/twenty-server/test/integration/graphql/utils/create-api-key-operation-factory.util.ts b/packages/twenty-server/test/integration/graphql/utils/create-api-key-operation-factory.util.ts
new file mode 100644
index 00000000000..0b70e02eb82
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/utils/create-api-key-operation-factory.util.ts
@@ -0,0 +1,20 @@
+import gql from 'graphql-tag';
+
+export const createApiKeyOperationFactory = ({
+ name,
+ expiresAt,
+ roleId,
+}: {
+ name: string;
+ expiresAt: string;
+ roleId: string;
+}) => ({
+ query: gql`
+ mutation CreateApiKey($input: CreateApiKeyInput!) {
+ createApiKey(input: $input) {
+ id
+ }
+ }
+ `,
+ variables: { input: { name, expiresAt, roleId } },
+});
diff --git a/packages/twenty-server/test/integration/graphql/utils/create-api-key.util.ts b/packages/twenty-server/test/integration/graphql/utils/create-api-key.util.ts
new file mode 100644
index 00000000000..2c11408e2ee
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/utils/create-api-key.util.ts
@@ -0,0 +1,18 @@
+import { createApiKeyOperationFactory } from 'test/integration/graphql/utils/create-api-key-operation-factory.util';
+import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';
+
+export const createApiKey = async ({
+ name,
+ expiresAt,
+ roleId,
+ accessToken,
+}: {
+ name: string;
+ expiresAt: string;
+ roleId: string;
+ accessToken: string;
+}) =>
+ makeMetadataApiRequest(
+ createApiKeyOperationFactory({ name, expiresAt, roleId }),
+ accessToken,
+ );
diff --git a/packages/twenty-server/test/integration/graphql/utils/revoke-api-key-operation-factory.util.ts b/packages/twenty-server/test/integration/graphql/utils/revoke-api-key-operation-factory.util.ts
new file mode 100644
index 00000000000..9e364c8256c
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/utils/revoke-api-key-operation-factory.util.ts
@@ -0,0 +1,16 @@
+import gql from 'graphql-tag';
+
+export const revokeApiKeyOperationFactory = ({
+ apiKeyId,
+}: {
+ apiKeyId: string;
+}) => ({
+ query: gql`
+ mutation RevokeApiKey($input: RevokeApiKeyInput!) {
+ revokeApiKey(input: $input) {
+ id
+ }
+ }
+ `,
+ variables: { input: { id: apiKeyId } },
+});
diff --git a/packages/twenty-server/test/integration/graphql/utils/revoke-api-key.util.ts b/packages/twenty-server/test/integration/graphql/utils/revoke-api-key.util.ts
new file mode 100644
index 00000000000..58b548e399d
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/utils/revoke-api-key.util.ts
@@ -0,0 +1,14 @@
+import { revokeApiKeyOperationFactory } from 'test/integration/graphql/utils/revoke-api-key-operation-factory.util';
+import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';
+
+export const revokeApiKey = async ({
+ apiKeyId,
+ accessToken,
+}: {
+ apiKeyId: string;
+ accessToken: string;
+}) =>
+ makeMetadataApiRequest(
+ revokeApiKeyOperationFactory({ apiKeyId }),
+ accessToken,
+ );
diff --git a/packages/twenty-server/test/integration/metadata/suites/application/failing-application-preferences.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/application/failing-application-preferences.integration-spec.ts
index b44d88823f4..d04f036c217 100644
--- a/packages/twenty-server/test/integration/metadata/suites/application/failing-application-preferences.integration-spec.ts
+++ b/packages/twenty-server/test/integration/metadata/suites/application/failing-application-preferences.integration-spec.ts
@@ -2,7 +2,7 @@ import { randomUUID } from 'crypto';
import IORedis from 'ioredis';
import { expectOneNotInternalServerErrorSnapshot } from 'test/integration/graphql/utils/expect-one-not-internal-server-error-snapshot.util';
-import { expectPermissionDenied } from 'test/integration/metadata/suites/application/utils/expect-permission-denied.util';
+import { expectPermissionDenied } from 'test/integration/permissions/utils/expect-permission-denied.util';
import { cleanupApplicationAndAppRegistration } from 'test/integration/metadata/suites/application/utils/cleanup-application-and-app-registration.util';
import { myApplicationPreferences } from 'test/integration/metadata/suites/application/utils/my-application-preferences.util';
import { runMyApplicationHealthCheckQueryFactory } from 'test/integration/metadata/suites/application/utils/run-my-application-health-check-query-factory.util';
diff --git a/packages/twenty-server/test/integration/metadata/suites/application/failing-user-application-variable-values.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/application/failing-user-application-variable-values.integration-spec.ts
index b3922fcd166..f13b530363c 100644
--- a/packages/twenty-server/test/integration/metadata/suites/application/failing-user-application-variable-values.integration-spec.ts
+++ b/packages/twenty-server/test/integration/metadata/suites/application/failing-user-application-variable-values.integration-spec.ts
@@ -1,5 +1,5 @@
import { expectOneNotInternalServerErrorSnapshot } from 'test/integration/graphql/utils/expect-one-not-internal-server-error-snapshot.util';
-import { expectPermissionDenied } from 'test/integration/metadata/suites/application/utils/expect-permission-denied.util';
+import { expectPermissionDenied } from 'test/integration/permissions/utils/expect-permission-denied.util';
import { myUserApplicationVariables } from 'test/integration/metadata/suites/application/utils/my-user-application-variables.util';
import { cleanupApplicationAndAppRegistration } from 'test/integration/metadata/suites/application/utils/cleanup-application-and-app-registration.util';
import {
diff --git a/packages/twenty-server/test/integration/permissions/object-records/object-record-grants.integration-spec.ts b/packages/twenty-server/test/integration/permissions/object-records/object-record-grants.integration-spec.ts
new file mode 100644
index 00000000000..047fa77f64f
--- /dev/null
+++ b/packages/twenty-server/test/integration/permissions/object-records/object-record-grants.integration-spec.ts
@@ -0,0 +1,503 @@
+import { randomUUID } from 'node:crypto';
+
+import { type Response } from 'supertest';
+import {
+ type ApiKeyWithObjectRecordGrants,
+ createApiKeyWithObjectRecordGrants,
+ type ObjectRecordGrants,
+} from 'test/integration/permissions/utils/create-api-key-with-object-record-grants.util';
+import { deleteApiKeysWithObjectRecordGrants } from 'test/integration/permissions/utils/delete-api-keys-with-object-record-grants.util';
+import { expectPermissionDeniedResponse } from 'test/integration/permissions/utils/expect-permission-denied-response.util';
+import { expectPermissionGrantedResponse } from 'test/integration/permissions/utils/expect-permission-granted-response.util';
+import { createPersonRecords } from 'test/integration/utils/create-person-records.util';
+import { destroyPersonRecordsByFirstName } from 'test/integration/utils/destroy-person-records-by-first-name.util';
+import { findPersonRecordStates } from 'test/integration/utils/find-person-record-states.util';
+import { PERSON_RECORD_FIXTURE } from 'test/integration/utils/person-record-fixture.constant';
+import {
+ personRequestsByApi,
+ type RecordApi,
+} from 'test/integration/utils/person-requests-by-api.util';
+
+type GrantApiKeys = {
+ withGrant: ApiKeyWithObjectRecordGrants;
+ withoutGrant: ApiKeyWithObjectRecordGrants;
+};
+
+const UPDATED_JOB_TITLE = 'Updated job title';
+
+const ACTIVE = { status: 'active', jobTitle: PERSON_RECORD_FIXTURE.jobTitle };
+const SOFT_DELETED = {
+ status: 'softDeleted',
+ jobTitle: PERSON_RECORD_FIXTURE.jobTitle,
+};
+const ABSENT = { status: 'absent' };
+
+const createGrantApiKeys = async ({
+ withGrant,
+ withoutGrant,
+}: {
+ withGrant: ObjectRecordGrants;
+ withoutGrant: ObjectRecordGrants;
+}): Promise<GrantApiKeys> => {
+ const [withGrantApiKey, withoutGrantApiKey] = await Promise.all([
+ createApiKeyWithObjectRecordGrants(withGrant),
+ createApiKeyWithObjectRecordGrants(withoutGrant),
+ ]);
+
+ return { withGrant: withGrantApiKey, withoutGrant: withoutGrantApiKey };
+};
+
+const getReturnedPersonIds = ({
+ api,
+ response,
+}: {
+ api: RecordApi;
+ response: Response;
+}): string[] => {
+ if (api === 'graphql') {
+ return response.body.data.people.edges.map(
+ (edge: { node: { id: string } }) => edge.node.id,
+ );
+ }
+
+ return response.body.data.people.map((person: { id: string }) => person.id);
+};
+
+describe('object record grants', () => {
+ let readApiKeys: GrantApiKeys;
+ let updateApiKeys: GrantApiKeys;
+ let softDeleteApiKeys: GrantApiKeys;
+ let destroyApiKeys: GrantApiKeys;
+
+ beforeAll(async () => {
+ [readApiKeys, updateApiKeys, softDeleteApiKeys, destroyApiKeys] =
+ await Promise.all([
+ createGrantApiKeys({
+ withGrant: {
+ canReadAllObjectRecords: true,
+ },
+ withoutGrant: {},
+ }),
+ createGrantApiKeys({
+ withGrant: {
+ canReadAllObjectRecords: true,
+ canUpdateAllObjectRecords: true,
+ },
+ withoutGrant: {
+ canReadAllObjectRecords: true,
+ canSoftDeleteAllObjectRecords: true,
+ canDestroyAllObjectRecords: true,
+ },
+ }),
+ createGrantApiKeys({
+ withGrant: {
+ canReadAllObjectRecords: true,
+ canSoftDeleteAllObjectRecords: true,
+ },
+ withoutGrant: {
+ canReadAllObjectRecords: true,
+ canUpdateAllObjectRecords: true,
+ canDestroyAllObjectRecords: true,
+ },
+ }),
+ createGrantApiKeys({
+ withGrant: {
+ canReadAllObjectRecords: true,
+ canDestroyAllObjectRecords: true,
+ },
+ withoutGrant: {
+ canReadAllObjectRecords: true,
+ canUpdateAllObjectRecords: true,
+ canSoftDeleteAllObjectRecords: true,
+ },
+ }),
+ ]);
+ });
+
+ afterAll(async () => {
+ await Promise.all([
+ deleteApiKeysWithObjectRecordGrants(
+ [readApiKeys, updateApiKeys, softDeleteApiKeys, destroyApiKeys].flatMap(
+ ({ withGrant, withoutGrant }) => [withGrant, withoutGrant],
+ ),
+ ),
+ destroyPersonRecordsByFirstName(PERSON_RECORD_FIXTURE.firstName),
+ ]);
+ });
+
+ describe('read grant', () => {
+ describe.each(['graphql', 'rest'] as const)('%s', (api) => {
+ it('denies findMany without the grant', async () => {
+ const ids = await createPersonRecords({ count: 2 });
+
+ const response = await personRequestsByApi.findMany({
+ api,
+ token: readApiKeys.withoutGrant.token,
+ ids,
+ });
+
+ expectPermissionDeniedResponse({ api, response });
+ });
+
+ it('allows findMany with the grant', async () => {
+ const ids = await createPersonRecords({ count: 2 });
+
+ const response = await personRequestsByApi.findMany({
+ api,
+ token: readApiKeys.withGrant.token,
+ ids,
+ });
+
+ expectPermissionGrantedResponse({ api, response });
+ expect(getReturnedPersonIds({ api, response }).sort()).toEqual(
+ ids.sort(),
+ );
+ });
+
+ it('denies findOne without the grant', async () => {
+ const [id] = await createPersonRecords({ count: 1 });
+
+ const response = await personRequestsByApi.findOne({
+ api,
+ token: readApiKeys.withoutGrant.token,
+ id,
+ });
+
+ expectPermissionDeniedResponse({ api, response });
+ });
+
+ it('allows findOne with the grant', async () => {
+ const [id] = await createPersonRecords({ count: 1 });
+
+ const response = await personRequestsByApi.findOne({
+ api,
+ token: readApiKeys.withGrant.token,
+ id,
+ });
+
+ expectPermissionGrantedResponse({ api, response });
+ expect(response.body.data.person.id).toBe(id);
+ });
+ });
+ });
+
+ describe('update grant', () => {
+ describe.each(['graphql', 'rest'] as const)('%s', (api) => {
+ it('denies createOne without the grant', async () => {
+ const [id] = [randomUUID()];
+
+ const response = await personRequestsByApi.createOne({
+ api,
+ token: updateApiKeys.withoutGrant.token,
+ data: { id, name: { firstName: PERSON_RECORD_FIXTURE.firstName } },
+ });
+
+ expectPermissionDeniedResponse({ api, response });
+ expect(await findPersonRecordStates([id])).toEqual([
+ { status: 'absent' },
+ ]);
+ });
+
+ it('allows createOne with the grant', async () => {
+ const [id] = [randomUUID()];
+
+ const response = await personRequestsByApi.createOne({
+ api,
+ token: updateApiKeys.withGrant.token,
+ data: { id, name: { firstName: PERSON_RECORD_FIXTURE.firstName } },
+ });
+
+ expectPermissionGrantedResponse({ api, response });
+ expect(await findPersonRecordStates([id])).toEqual([
+ { status: 'active', jobTitle: '' },
+ ]);
+ });
+
+ it('denies createMany without the grant', async () => {
+ const ids = [randomUUID(), randomUUID()];
+
+ const response = await personRequestsByApi.createMany({
+ api,
+ token: updateApiKeys.withoutGrant.token,
+ data: ids.map((id) => ({
+ id,
+ name: { firstName: PERSON_RECORD_FIXTURE.firstName },
+ })),
+ });
+
+ expectPermissionDeniedResponse({ api, response });
+ expect(await findPersonRecordStates(ids)).toEqual([
+ { status: 'absent' },
+ { status: 'absent' },
+ ]);
+ });
+
+ it('allows createMany with the grant', async () => {
+ const ids = [randomUUID(), randomUUID()];
+
+ const response = await personRequestsByApi.createMany({
+ api,
+ token: updateApiKeys.withGrant.token,
+ data: ids.map((id) => ({
+ id,
+ name: { firstName: PERSON_RECORD_FIXTURE.firstName },
+ })),
+ });
+
+ expectPermissionGrantedResponse({ api, response });
+ expect(await findPersonRecordStates(ids)).toEqual([
+ { status: 'active', jobTitle: '' },
+ { status: 'active', jobTitle: '' },
+ ]);
+ });
+
+ it('denies updateOne without the grant', async () => {
+ const [id] = await createPersonRecords({ count: 1 });
+
+ const response = await personRequestsByApi.updateOne({
+ api,
+ token: updateApiKeys.withoutGrant.token,
+ id,
+ data: { jobTitle: UPDATED_JOB_TITLE },
+ });
+
+ expectPermissionDeniedResponse({ api, response });
+ expect(await findPersonRecordStates([id])).toEqual([
+ { status: 'active', jobTitle: PERSON_RECORD_FIXTURE.jobTitle },
+ ]);
+ });
+
+ it('allows updateOne with the grant', async () => {
+ const [id] = await createPersonRecords({ count: 1 });
+
+ const response = await personRequestsByApi.updateOne({
+ api,
+ token: updateApiKeys.withGrant.token,
+ id,
+ data: { jobTitle: UPDATED_JOB_TITLE },
+ });
+
+ expectPermissionGrantedResponse({ api, response });
+ expect(await findPersonRecordStates([id])).toEqual([
+ { status: 'active', jobTitle: UPDATED_JOB_TITLE },
+ ]);
+ });
+
+ it('denies updateMany without the grant', async () => {
+ const ids = await createPersonRecords({ count: 2 });
+
+ const response = await personRequestsByApi.updateMany({
+ api,
+ token: updateApiKeys.withoutGrant.token,
+ ids,
+ data: { jobTitle: UPDATED_JOB_TITLE },
+ });
+
+ expectPermissionDeniedResponse({ api, response });
+ expect(await findPersonRecordStates(ids)).toEqual([
+ { status: 'active', jobTitle: PERSON_RECORD_FIXTURE.jobTitle },
+ { status: 'active', jobTitle: PERSON_RECORD_FIXTURE.jobTitle },
+ ]);
+ });
+
+ it('allows updateMany with the grant', async () => {
+ const ids = await createPersonRecords({ count: 2 });
+
+ const response = await personRequestsByApi.updateMany({
+ api,
+ token: updateApiKeys.withGrant.token,
+ ids,
+ data: { jobTitle: UPDATED_JOB_TITLE },
+ });
+
+ expectPermissionGrantedResponse({ api, response });
+ expect(await findPersonRecordStates(ids)).toEqual([
+ { status: 'active', jobTitle: UPDATED_JOB_TITLE },
+ { status: 'active', jobTitle: UPDATED_JOB_TITLE },
+ ]);
+ });
+ });
+ });
+
+ describe('soft-delete grant', () => {
+ describe.each(['graphql', 'rest'] as const)('%s', (api) => {
+ it('denies deleteOne without the grant', async () => {
+ const [id] = await createPersonRecords({ count: 1 });
+
+ const response = await personRequestsByApi.deleteOne({
+ api,
+ token: softDeleteApiKeys.withoutGrant.token,
+ id,
+ });
+
+ expectPermissionDeniedResponse({ api, response });
+ expect(await findPersonRecordStates([id])).toEqual([ACTIVE]);
+ });
+
+ it('allows deleteOne with the grant', async () => {
+ const [id] = await createPersonRecords({ count: 1 });
+
+ const response = await personRequestsByApi.deleteOne({
+ api,
+ token: softDeleteApiKeys.withGrant.token,
+ id,
+ });
+
+ expectPermissionGrantedResponse({ api, response });
+ expect(await findPersonRecordStates([id])).toEqual([SOFT_DELETED]);
+ });
+
+ it('denies deleteMany without the grant', async () => {
+ const ids = await createPersonRecords({ count: 2 });
+
+ const response = await personRequestsByApi.deleteMany({
+ api,
+ token: softDeleteApiKeys.withoutGrant.token,
+ ids,
+ });
+
+ expectPermissionDeniedResponse({ api, response });
+ expect(await findPersonRecordStates(ids)).toEqual([ACTIVE, ACTIVE]);
+ });
+
+ it('allows deleteMany with the grant', async () => {
+ const ids = await createPersonRecords({ count: 2 });
+
+ const response = await personRequestsByApi.deleteMany({
+ api,
+ token: softDeleteApiKeys.withGrant.token,
+ ids,
+ });
+
+ expectPermissionGrantedResponse({ api, response });
+ expect(await findPersonRecordStates(ids)).toEqual([
+ SOFT_DELETED,
+ SOFT_DELETED,
+ ]);
+ });
+
+ it('denies restoreOne without the grant', async () => {
+ const [id] = await createPersonRecords({
+ count: 1,
+ isSoftDeleted: true,
+ });
+
+ const response = await personRequestsByApi.restoreOne({
+ api,
+ token: softDeleteApiKeys.withoutGrant.token,
+ id,
+ });
+
+ expectPermissionDeniedResponse({ api, response });
+ expect(await findPersonRecordStates([id])).toEqual([SOFT_DELETED]);
+ });
+
+ it('allows restoreOne with the grant', async () => {
+ const [id] = await createPersonRecords({
+ count: 1,
+ isSoftDeleted: true,
+ });
+
+ const response = await personRequestsByApi.restoreOne({
+ api,
+ token: softDeleteApiKeys.withGrant.token,
+ id,
+ });
+
+ expectPermissionGrantedResponse({ api, response });
+ expect(await findPersonRecordStates([id])).toEqual([ACTIVE]);
+ });
+
+ it('denies restoreMany without the grant', async () => {
+ const ids = await createPersonRecords({
+ count: 2,
+ isSoftDeleted: true,
+ });
+
+ const response = await personRequestsByApi.restoreMany({
+ api,
+ token: softDeleteApiKeys.withoutGrant.token,
+ ids,
+ });
+
+ expectPermissionDeniedResponse({ api, response });
+ expect(await findPersonRecordStates(ids)).toEqual([
+ SOFT_DELETED,
+ SOFT_DELETED,
+ ]);
+ });
+
+ it('allows restoreMany with the grant', async () => {
+ const ids = await createPersonRecords({
+ count: 2,
+ isSoftDeleted: true,
+ });
+
+ const response = await personRequestsByApi.restoreMany({
+ api,
+ token: softDeleteApiKeys.withGrant.token,
+ ids,
+ });
+
+ expectPermissionGrantedResponse({ api, response });
+ expect(await findPersonRecordStates(ids)).toEqual([ACTIVE, ACTIVE]);
+ });
+ });
+ });
+
+ describe('destroy grant', () => {
+ describe.each(['graphql', 'rest'] as const)('%s', (api) => {
+ it('denies destroyOne without the grant', async () => {
+ const [id] = await createPersonRecords({ count: 1 });
+
+ const response = await personRequestsByApi.destroyOne({
+ api,
+ token: destroyApiKeys.withoutGrant.token,
+ id,
+ });
+
+ expectPermissionDeniedResponse({ api, response });
+ expect(await findPersonRecordStates([id])).toEqual([ACTIVE]);
+ });
+
+ it('allows destroyOne with the grant', async () => {
+ const [id] = await createPersonRecords({ count: 1 });
+
+ const response = await personRequestsByApi.destroyOne({
+ api,
+ token: destroyApiKeys.withGrant.token,
+ id,
+ });
+
+ expectPermissionGrantedResponse({ api, response });
+ expect(await findPersonRecordStates([id])).toEqual([ABSENT]);
+ });
+
+ it('denies destroyMany without the grant', async () => {
+ const ids = await createPersonRecords({ count: 2 });
+
+ const response = await personRequestsByApi.destroyMany({
+ api,
+ token: destroyApiKeys.withoutGrant.token,
+ ids,
+ });
+
+ expectPermissionDeniedResponse({ api, response });
+ expect(await findPersonRecordStates(ids)).toEqual([ACTIVE, ACTIVE]);
+ });
+
+ it('allows destroyMany with the grant', async () => {
+ const ids = await createPersonRecords({ count: 2 });
+
+ const response = await personRequestsByApi.destroyMany({
+ api,
+ token: destroyApiKeys.withGrant.token,
+ ids,
+ });
+
+ expectPermissionGrantedResponse({ api, response });
+ expect(await findPersonRecordStates(ids)).toEqual([ABSENT, ABSENT]);
+ });
+ });
+ });
+});
diff --git a/packages/twenty-server/test/integration/permissions/utils/create-api-key-with-object-record-grants.util.ts b/packages/twenty-server/test/integration/permissions/utils/create-api-key-with-object-record-grants.util.ts
new file mode 100644
index 00000000000..fe1ad1a69d0
--- /dev/null
+++ b/packages/twenty-server/test/integration/permissions/utils/create-api-key-with-object-record-grants.util.ts
@@ -0,0 +1,70 @@
+import { randomUUID } from 'node:crypto';
+
+import { createApiKey } from 'test/integration/graphql/utils/create-api-key.util';
+import { generateApiKeyToken } from 'test/integration/graphql/utils/generate-api-key-token.util';
+import { createOneRole } from 'test/integration/metadata/suites/role/utils/create-one-role.util';
+
+import { type CreateRoleInput } from 'src/engine/metadata-modules/role/dtos/create-role.input';
+
+export type ApiKeyWithObjectRecordGrants = {
+ roleId: string;
+ apiKeyId: string;
+ token: string;
+};
+
+export type ObjectRecordGrants = Pick<
+ CreateRoleInput,
+ | 'canReadAllObjectRecords'
+ | 'canUpdateAllObjectRecords'
+ | 'canSoftDeleteAllObjectRecords'
+ | 'canDestroyAllObjectRecords'
+>;
+
+const API_KEY_EXPIRES_AT = '2099-01-01T00:00:00Z';
+
+export const createApiKeyWithObjectRecordGrants = async (
+ grants: ObjectRecordGrants,
+): Promise<ApiKeyWithObjectRecordGrants> => {
+ const label = `Test API key role ${randomUUID()}`;
+
+ const { data: roleData } = await createOneRole({
+ input: {
+ label,
+ canUpdateAllSettings: false,
+ canAccessAllTools: false,
+ canReadAllObjectRecords: false,
+ canUpdateAllObjectRecords: false,
+ canSoftDeleteAllObjectRecords: false,
+ canDestroyAllObjectRecords: false,
+ canBeAssignedToUsers: false,
+ canBeAssignedToAgents: false,
+ canBeAssignedToApiKeys: true,
+ ...grants,
+ },
+ gqlFields: 'id',
+ expectToFail: false,
+ });
+
+ const roleId = roleData.createOneRole.id;
+
+ const createApiKeyResponse = await createApiKey({
+ name: label,
+ expiresAt: API_KEY_EXPIRES_AT,
+ roleId,
+ accessToken: APPLE_JANE_ADMIN_ACCESS_TOKEN,
+ });
+
+ const apiKeyId: string = createApiKeyResponse.body.data.createApiKey.id;
+
+ const generateTokenResponse = await generateApiKeyToken({
+ apiKeyId,
+ accessToken: APPLE_JANE_ADMIN_ACCESS_TOKEN,
+ expiresAt: API_KEY_EXPIRES_AT,
+ });
+
+ return {
+ roleId,
+ apiKeyId,
+ token: generateTokenResponse.body.data.generateApiKeyToken.token,
+ };
+};
diff --git a/packages/twenty-server/test/integration/permissions/utils/delete-api-keys-with-object-record-grants.util.ts b/packages/twenty-server/test/integration/permissions/utils/delete-api-keys-with-object-record-grants.util.ts
new file mode 100644
index 00000000000..7eaad9b940a
--- /dev/null
+++ b/packages/twenty-server/test/integration/permissions/utils/delete-api-keys-with-object-record-grants.util.ts
@@ -0,0 +1,23 @@
+import { revokeApiKey } from 'test/integration/graphql/utils/revoke-api-key.util';
+import { deleteOneRole } from 'test/integration/metadata/suites/role/utils/delete-one-role.util';
+import { type ApiKeyWithObjectRecordGrants } from 'test/integration/permissions/utils/create-api-key-with-object-record-grants.util';
+
+export const deleteApiKeysWithObjectRecordGrants = async (
+ testApiKeys: ApiKeyWithObjectRecordGrants[],
+) => {
+ await Promise.all(
+ testApiKeys.map(async ({ roleId, apiKeyId }) => {
+ const revokeResponse = await revokeApiKey({
+ apiKeyId,
+ accessToken: APPLE_JANE_ADMIN_ACCESS_TOKEN,
+ });
+
+ expect(revokeResponse.body.errors).toBeUndefined();
+
+ await deleteOneRole({
+ input: { idToDelete: roleId },
+ expectToFail: false,
+ });
+ }),
+ );
+};
diff --git a/packages/twenty-server/test/integration/permissions/utils/expect-permission-denied-response.util.ts b/packages/twenty-server/test/integration/permissions/utils/expect-permission-denied-response.util.ts
new file mode 100644
index 00000000000..b2fd6098c0a
--- /dev/null
+++ b/packages/twenty-server/test/integration/permissions/utils/expect-permission-denied-response.util.ts
@@ -0,0 +1,33 @@
+import { type Response } from 'supertest';
+import { expectPermissionDenied } from 'test/integration/permissions/utils/expect-permission-denied.util';
+import { type RecordApi } from 'test/integration/utils/person-requests-by-api.util';
+
+import {
+ PermissionsExceptionCode,
+ PermissionsExceptionMessage,
+} from 'src/engine/permissions/permissions.exception';
+
+export const expectPermissionDeniedResponse = ({
+ api,
+ response,
+}: {
+ api: RecordApi;
+ response: Response;
+}) => {
+ if (api === 'graphql') {
+ expectPermissionDenied(response.body.errors);
+
+ for (const result of Object.values(response.body.data ?? {})) {
+ expect(result).toBeNull();
+ }
+
+ return;
+ }
+
+ expect(response.status).toBe(403);
+ expect(response.body.data).toBeUndefined();
+ expect(response.body.code).toBe(PermissionsExceptionCode.PERMISSION_DENIED);
+ expect(response.body.messages).toStrictEqual([
+ PermissionsExceptionMessage.PERMISSION_DENIED,
+ ]);
+};
diff --git a/packages/twenty-server/test/integration/metadata/suites/application/utils/expect-permission-denied.util.ts b/packages/twenty-server/test/integration/permissions/utils/expect-permission-denied.util.ts
similarity index 100%
rename from packages/twenty-server/test/integration/metadata/suites/application/utils/expect-permission-denied.util.ts
rename to packages/twenty-server/test/integration/permissions/utils/expect-permission-denied.util.ts
diff --git a/packages/twenty-server/test/integration/permissions/utils/expect-permission-granted-response.util.ts b/packages/twenty-server/test/integration/permissions/utils/expect-permission-granted-response.util.ts
new file mode 100644
index 00000000000..c604c613cb2
--- /dev/null
+++ b/packages/twenty-server/test/integration/permissions/utils/expect-permission-granted-response.util.ts
@@ -0,0 +1,21 @@
+import { type Response } from 'supertest';
+import { type RecordApi } from 'test/integration/utils/person-requests-by-api.util';
+
+export const expectPermissionGrantedResponse = ({
+ api,
+ response,
+}: {
+ api: RecordApi;
+ response: Response;
+}) => {
+ if (api === 'graphql') {
+ expect(response.status).toBe(200);
+ expect(response.body.errors).toBeUndefined();
+ expect(Object.values(response.body.data)).not.toContain(null);
+
+ return;
+ }
+
+ expect([200, 201]).toContain(response.status);
+ expect(response.body.data).toEqual(expect.anything());
+};
diff --git a/packages/twenty-server/test/integration/rest/suites/field-permissions.integration-spec.ts b/packages/twenty-server/test/integration/rest/suites/field-permissions.integration-spec.ts
index 1c613a2bd7b..a30b751dbe3 100644
--- a/packages/twenty-server/test/integration/rest/suites/field-permissions.integration-spec.ts
+++ b/packages/twenty-server/test/integration/rest/suites/field-permissions.integration-spec.ts
@@ -209,7 +209,7 @@ describe('Restricted fields', () => {
},
},
})
- .expect(400)
+ .expect(403)
.expect((res) => {
expect(res.body.messages[0]).toContain(
'Entity performing the request does not have permission',
@@ -273,7 +273,7 @@ describe('Restricted fields', () => {
},
},
})
- .expect(400)
+ .expect(403)
.expect((res) => {
expect(res.body.messages[0]).toContain(
'Entity performing the request does not have permission',
@@ -403,7 +403,7 @@ describe('Restricted fields', () => {
},
],
})
- .expect(400)
+ .expect(403)
.expect((res) => {
expect(res.body.messages[0]).toContain(
'Entity performing the request does not have permission',
diff --git a/packages/twenty-server/test/integration/utils/create-person-records.util.ts b/packages/twenty-server/test/integration/utils/create-person-records.util.ts
new file mode 100644
index 00000000000..11c56705b44
--- /dev/null
+++ b/packages/twenty-server/test/integration/utils/create-person-records.util.ts
@@ -0,0 +1,46 @@
+import { randomUUID } from 'node:crypto';
+
+import { createManyOperationFactory } from 'test/integration/graphql/utils/create-many-operation-factory.util';
+import { deleteManyOperationFactory } from 'test/integration/graphql/utils/delete-many-operation-factory.util';
+import { makeGraphqlApiRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';
+import { PERSON_RECORD_FIXTURE } from 'test/integration/utils/person-record-fixture.constant';
+
+export const createPersonRecords = async ({
+ count,
+ isSoftDeleted = false,
+}: {
+ count: number;
+ isSoftDeleted?: boolean;
+}) => {
+ const ids = Array.from({ length: count }, () => randomUUID());
+
+ const createResponse = await makeGraphqlApiRequest(
+ createManyOperationFactory({
+ objectMetadataSingularName: 'person',
+ objectMetadataPluralName: 'people',
+ gqlFields: 'id',
+ data: ids.map((id) => ({
+ id,
+ name: { firstName: PERSON_RECORD_FIXTURE.firstName },
+ jobTitle: PERSON_RECORD_FIXTURE.jobTitle,
+ })),
+ }),
+ );
+
+ expect(createResponse.body.errors).toBeUndefined();
+
+ if (isSoftDeleted) {
+ const deleteResponse = await makeGraphqlApiRequest(
+ deleteManyOperationFactory({
+ objectMetadataSingularName: 'person',
+ objectMetadataPluralName: 'people',
+ gqlFields: 'id',
+ filter: { id: { in: ids } },
+ }),
+ );
+
+ expect(deleteResponse.body.errors).toBeUndefined();
+ }
+
+ return ids;
+};
diff --git a/packages/twenty-server/test/integration/utils/destroy-person-records-by-first-name.util.ts b/packages/twenty-server/test/integration/utils/destroy-person-records-by-first-name.util.ts
new file mode 100644
index 00000000000..db38afa6262
--- /dev/null
+++ b/packages/twenty-server/test/integration/utils/destroy-person-records-by-first-name.util.ts
@@ -0,0 +1,25 @@
+import { destroyManyOperationFactory } from 'test/integration/graphql/utils/destroy-many-operation-factory.util';
+import { makeGraphqlApiRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';
+
+export const destroyPersonRecordsByFirstName = async (firstName: string) => {
+ const destroyResponse = await makeGraphqlApiRequest(
+ destroyManyOperationFactory({
+ objectMetadataSingularName: 'person',
+ objectMetadataPluralName: 'people',
+ gqlFields: 'id',
+ filter: {
+ and: [
+ { name: { firstName: { eq: firstName } } },
+ {
+ or: [
+ { deletedAt: { is: 'NULL' } },
+ { deletedAt: { is: 'NOT_NULL' } },
+ ],
+ },
+ ],
+ },
+ }),
+ );
+
+ expect(destroyResponse.body.errors).toBeUndefined();
+};
diff --git a/packages/twenty-server/test/integration/utils/find-person-record-states.util.ts b/packages/twenty-server/test/integration/utils/find-person-record-states.util.ts
new file mode 100644
index 00000000000..05853eec9d6
--- /dev/null
+++ b/packages/twenty-server/test/integration/utils/find-person-record-states.util.ts
@@ -0,0 +1,37 @@
+import { findRecordNodesByFilter } from 'test/integration/utils/find-records-by-filter.util';
+import { isDefined } from 'twenty-shared/utils';
+
+export type PersonRecordState = {
+ status: 'active' | 'softDeleted' | 'absent';
+ jobTitle?: string;
+};
+
+export const findPersonRecordStates = async (
+ ids: string[],
+): Promise<PersonRecordState[]> => {
+ const people = await findRecordNodesByFilter<{
+ id: string;
+ jobTitle: string;
+ deletedAt: string | null;
+ }>('person', 'people', 'id jobTitle deletedAt', {
+ and: [
+ { id: { in: ids } },
+ {
+ or: [{ deletedAt: { is: 'NULL' } }, { deletedAt: { is: 'NOT_NULL' } }],
+ },
+ ],
+ });
+
+ return ids.map((id) => {
+ const person = people.find((candidate) => candidate.id === id);
+
+ if (!isDefined(person)) {
+ return { status: 'absent' };
+ }
+
+ return {
+ status: isDefined(person.deletedAt) ? 'softDeleted' : 'active',
+ jobTitle: person.jobTitle,
+ };
+ });
+};
diff --git a/packages/twenty-server/test/integration/utils/person-record-fixture.constant.ts b/packages/twenty-server/test/integration/utils/person-record-fixture.constant.ts
new file mode 100644
index 00000000000..4b1ab931e20
--- /dev/null
+++ b/packages/twenty-server/test/integration/utils/person-record-fixture.constant.ts
@@ -0,0 +1,4 @@
+export const PERSON_RECORD_FIXTURE = {
+ firstName: 'Person record fixture',
+ jobTitle: 'Seeded job title',
+};
diff --git a/packages/twenty-server/test/integration/utils/person-requests-by-api.util.ts b/packages/twenty-server/test/integration/utils/person-requests-by-api.util.ts
new file mode 100644
index 00000000000..5501b47c0ec
--- /dev/null
+++ b/packages/twenty-server/test/integration/utils/person-requests-by-api.util.ts
@@ -0,0 +1,299 @@
+import { createManyOperationFactory } from 'test/integration/graphql/utils/create-many-operation-factory.util';
+import { createOneOperationFactory } from 'test/integration/graphql/utils/create-one-operation-factory.util';
+import { deleteManyOperationFactory } from 'test/integration/graphql/utils/delete-many-operation-factory.util';
+import { deleteOneOperationFactory } from 'test/integration/graphql/utils/delete-one-operation-factory.util';
+import { destroyManyOperationFactory } from 'test/integration/graphql/utils/destroy-many-operation-factory.util';
+import { destroyOneOperationFactory } from 'test/integration/graphql/utils/destroy-one-operation-factory.util';
+import { findManyOperationFactory } from 'test/integration/graphql/utils/find-many-operation-factory.util';
+import { findOneOperationFactory } from 'test/integration/graphql/utils/find-one-operation-factory.util';
+import { makeGraphqlApiRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';
+import { restoreManyOperationFactory } from 'test/integration/graphql/utils/restore-many-operation-factory.util';
+import { restoreOneOperationFactory } from 'test/integration/graphql/utils/restore-one-operation-factory.util';
+import { updateManyOperationFactory } from 'test/integration/graphql/utils/update-many-operation-factory.util';
+import { updateOneOperationFactory } from 'test/integration/graphql/utils/update-one-operation-factory.util';
+import { makeRestApiRequest } from 'test/integration/rest/utils/make-rest-api-request.util';
+
+export type RecordApi = 'graphql' | 'rest';
+
+type PersonData = {
+ id: string;
+ name?: { firstName: string };
+ jobTitle?: string;
+};
+
+type PersonRequestInput = { api: RecordApi; token: string };
+
+const PERSON_SINGULAR_NAME = 'person';
+const PERSON_PLURAL_NAME = 'people';
+const PERSON_FIELDS = 'id jobTitle';
+
+const restIdFilter = (ids: string[]) =>
+ `filter=id[in]:[${ids.map((id) => `"${id}"`).join(',')}]`;
+
+export const personRequestsByApi = {
+ findMany: ({ api, token, ids }: PersonRequestInput & { ids: string[] }) => {
+ if (api === 'graphql') {
+ return makeGraphqlApiRequest(
+ findManyOperationFactory({
+ objectMetadataSingularName: PERSON_SINGULAR_NAME,
+ objectMetadataPluralName: PERSON_PLURAL_NAME,
+ gqlFields: PERSON_FIELDS,
+ filter: { id: { in: ids } },
+ }),
+ token,
+ );
+ }
+
+ return makeRestApiRequest({
+ method: 'get',
+ path: `/${PERSON_PLURAL_NAME}?${restIdFilter(ids)}`,
+ bearer: token,
+ });
+ },
+
+ findOne: ({ api, token, id }: PersonRequestInput & { id: string }) => {
+ if (api === 'graphql') {
+ return makeGraphqlApiRequest(
+ findOneOperationFactory({
+ objectMetadataSingularName: PERSON_SINGULAR_NAME,
+ gqlFields: PERSON_FIELDS,
+ filter: { id: { eq: id } },
+ }),
+ token,
+ );
+ }
+
+ return makeRestApiRequest({
+ method: 'get',
+ path: `/${PERSON_PLURAL_NAME}/${id}`,
+ bearer: token,
+ });
+ },
+
+ createOne: ({
+ api,
+ token,
+ data,
+ }: PersonRequestInput & { data: PersonData }) => {
+ if (api === 'graphql') {
+ return makeGraphqlApiRequest(
+ createOneOperationFactory({
+ objectMetadataSingularName: PERSON_SINGULAR_NAME,
+ gqlFields: PERSON_FIELDS,
+ data,
+ }),
+ token,
+ );
+ }
+
+ return makeRestApiRequest({
+ method: 'post',
+ path: `/${PERSON_PLURAL_NAME}`,
+ body: data,
+ bearer: token,
+ });
+ },
+
+ createMany: ({
+ api,
+ token,
+ data,
+ }: PersonRequestInput & { data: PersonData[] }) => {
+ if (api === 'graphql') {
+ return makeGraphqlApiRequest(
+ createManyOperationFactory({
+ objectMetadataSingularName: PERSON_SINGULAR_NAME,
+ objectMetadataPluralName: PERSON_PLURAL_NAME,
+ gqlFields: PERSON_FIELDS,
+ data,
+ }),
+ token,
+ );
+ }
+
+ return makeRestApiRequest({
+ method: 'post',
+ path: `/batch/${PERSON_PLURAL_NAME}`,
+ body: data,
+ bearer: token,
+ });
+ },
+
+ updateOne: ({
+ api,
+ token,
+ id,
+ data,
+ }: PersonRequestInput & { id: string; data: Omit<PersonData, 'id'> }) => {
+ if (api === 'graphql') {
+ return makeGraphqlApiRequest(
+ updateOneOperationFactory({
+ objectMetadataSingularName: PERSON_SINGULAR_NAME,
+ gqlFields: PERSON_FIELDS,
+ recordId: id,
+ data,
+ }),
+ token,
+ );
+ }
+
+ return makeRestApiRequest({
+ method: 'patch',
+ path: `/${PERSON_PLURAL_NAME}/${id}`,
+ body: data,
+ bearer: token,
+ });
+ },
+
+ updateMany: ({
+ api,
+ token,
+ ids,
+ data,
+ }: PersonRequestInput & { ids: string[]; data: Omit<PersonData, 'id'> }) => {
+ if (api === 'graphql') {
+ return makeGraphqlApiRequest(
+ updateManyOperationFactory({
+ objectMetadataSingularName: PERSON_SINGULAR_NAME,
+ objectMetadataPluralName: PERSON_PLURAL_NAME,
+ gqlFields: PERSON_FIELDS,
+ filter: { id: { in: ids } },
+ data,
+ }),
+ token,
+ );
+ }
+
+ return makeRestApiRequest({
+ method: 'patch',
+ path: `/${PERSON_PLURAL_NAME}?${restIdFilter(ids)}`,
+ body: data,
+ bearer: token,
+ });
+ },
+
+ deleteOne: ({ api, token, id }: PersonRequestInput & { id: string }) => {
+ if (api === 'graphql') {
+ return makeGraphqlApiRequest(
+ deleteOneOperationFactory({
+ objectMetadataSingularName: PERSON_SINGULAR_NAME,
+ gqlFields: PERSON_FIELDS,
+ recordId: id,
+ }),
+ token,
+ );
+ }
+
+ return makeRestApiRequest({
+ method: 'delete',
+ path: `/${PERSON_PLURAL_NAME}/${id}?soft_delete=true`,
+ bearer: token,
+ });
+ },
+
+ deleteMany: ({ api, token, ids }: PersonRequestInput & { ids: string[] }) => {
+ if (api === 'graphql') {
+ return makeGraphqlApiRequest(
+ deleteManyOperationFactory({
+ objectMetadataSingularName: PERSON_SINGULAR_NAME,
+ objectMetadataPluralName: PERSON_PLURAL_NAME,
+ gqlFields: PERSON_FIELDS,
+ filter: { id: { in: ids } },
+ }),
+ token,
+ );
+ }
+
+ return makeRestApiRequest({
+ method: 'delete',
+ path: `/${PERSON_PLURAL_NAME}?${restIdFilter(ids)}&soft_delete=true`,
+ bearer: token,
+ });
+ },
+
+ restoreOne: ({ api, token, id }: PersonRequestInput & { id: string }) => {
+ if (api === 'graphql') {
+ return makeGraphqlApiRequest(
+ restoreOneOperationFactory({
+ objectMetadataSingularName: PERSON_SINGULAR_NAME,
+ gqlFields: PERSON_FIELDS,
+ recordId: id,
+ }),
+ token,
+ );
+ }
+
+ return makeRestApiRequest({
+ method: 'patch',
+ path: `/${PERSON_PLURAL_NAME}/${id}/restore`,
+ bearer: token,
+ });
+ },
+
+ restoreMany: ({
+ api,
+ token,
+ ids,
+ }: PersonRequestInput & { ids: string[] }) => {
+ if (api === 'graphql') {
+ return makeGraphqlApiRequest(
+ restoreManyOperationFactory({
+ objectMetadataSingularName: PERSON_SINGULAR_NAME,
+ objectMetadataPluralName: PERSON_PLURAL_NAME,
+ gqlFields: PERSON_FIELDS,
+ filter: { id: { in: ids } },
+ }),
+ token,
+ );
+ }
+
+ return makeRestApiRequest({
+ method: 'patch',
+ path: `/${PERSON_PLURAL_NAME}/restore?${restIdFilter(ids)}`,
+ bearer: token,
+ });
+ },
+
+ destroyOne: ({ api, token, id }: PersonRequestInput & { id: string }) => {
+ if (api === 'graphql') {
+ return makeGraphqlApiRequest(
+ destroyOneOperationFactory({
+ objectMetadataSingularName: PERSON_SINGULAR_NAME,
+ gqlFields: PERSON_FIELDS,
+ recordId: id,
+ }),
+ token,
+ );
+ }
+
+ return makeRestApiRequest({
+ method: 'delete',
+ path: `/${PERSON_PLURAL_NAME}/${id}`,
+ bearer: token,
+ });
+ },
+
+ destroyMany: ({
+ api,
+ token,
+ ids,
+ }: PersonRequestInput & { ids: string[] }) => {
+ if (api === 'graphql') {
+ return makeGraphqlApiRequest(
+ destroyManyOperationFactory({
+ objectMetadataSingularName: PERSON_SINGULAR_NAME,
+ objectMetadataPluralName: PERSON_PLURAL_NAME,
+ gqlFields: PERSON_FIELDS,
+ filter: { id: { in: ids } },
+ }),
+ token,
+ );
+ }
+
+ return makeRestApiRequest({
+ method: 'delete',
+ path: `/${PERSON_PLURAL_NAME}?${restIdFilter(ids)}`,
+ bearer: token,
+ });
+ },
+};