Skip to content

The open alternative to Salesforce, designed for AI.

Replace the field permission specs with one spec on both APIs (#29606)

Charles Bochet034f8c136406
diff --git a/packages/twenty-server/test/integration/ai/suites/mcp-role-tools.integration-spec.ts b/packages/twenty-server/test/integration/ai/suites/mcp-role-tools.integration-spec.ts
index 840b91655c8..543f0a9a7b8 100644
--- a/packages/twenty-server/test/integration/ai/suites/mcp-role-tools.integration-spec.ts
+++ b/packages/twenty-server/test/integration/ai/suites/mcp-role-tools.integration-spec.ts
@@ -1,6 +1,6 @@
import { executeToolThroughMcp } from 'test/integration/ai/utils/execute-tool-through-mcp.util';
import { callMcpTool } from 'test/integration/graphql/suites/application-role-intersection/utils/call-mcp-tool.util';
-import { findObjectMetadataIdByName } from 'test/integration/graphql/suites/application-role-intersection/utils/find-object-metadata-id-by-name.util';
+import { findObjectMetadataIdByName } from 'test/integration/utils/find-object-metadata-id-by-name.util';
import { getMcpToolCatalog } from 'test/integration/graphql/suites/application-role-intersection/utils/get-mcp-tool-catalog.util';
import { jestExpectToBeDefined } from 'test/utils/jest-expect-to-be-defined.util.test';
import { ToolCategory } from 'twenty-shared/ai';
diff --git a/packages/twenty-server/test/integration/graphql/suites/application-role-intersection/failing-delegated-application-role-intersection.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/application-role-intersection/failing-delegated-application-role-intersection.integration-spec.ts
index c2d17a6d4df..dfd7be669c0 100644
--- a/packages/twenty-server/test/integration/graphql/suites/application-role-intersection/failing-delegated-application-role-intersection.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/application-role-intersection/failing-delegated-application-role-intersection.integration-spec.ts
@@ -7,7 +7,7 @@ import {
} from 'test/integration/graphql/suites/application-role-intersection/utils/create-workspace-blocklist-entry.util';
import { deleteBlocklistEntryThroughMcp } from 'test/integration/graphql/suites/application-role-intersection/utils/delete-blocklist-entry-through-mcp.util';
import { deleteUserFromWorkspace } from 'test/integration/graphql/suites/user-session/utils/delete-user-from-workspace.util';
-import { findObjectMetadataIdByName } from 'test/integration/graphql/suites/application-role-intersection/utils/find-object-metadata-id-by-name.util';
+import { findObjectMetadataIdByName } from 'test/integration/utils/find-object-metadata-id-by-name.util';
import {
cleanupDelegatedApplications,
type DelegatedApplications,
diff --git a/packages/twenty-server/test/integration/graphql/suites/application-role-intersection/successful-delegated-application-role-intersection.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/application-role-intersection/successful-delegated-application-role-intersection.integration-spec.ts
index 06e594ff0aa..792c0a2bfc5 100644
--- a/packages/twenty-server/test/integration/graphql/suites/application-role-intersection/successful-delegated-application-role-intersection.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/application-role-intersection/successful-delegated-application-role-intersection.integration-spec.ts
@@ -7,7 +7,7 @@ import {
} from 'test/integration/graphql/suites/application-role-intersection/utils/create-workspace-blocklist-entry.util';
import { deleteBlocklistEntryThroughMcp } from 'test/integration/graphql/suites/application-role-intersection/utils/delete-blocklist-entry-through-mcp.util';
import { deleteUserFromWorkspace } from 'test/integration/graphql/suites/user-session/utils/delete-user-from-workspace.util';
-import { findObjectMetadataIdByName } from 'test/integration/graphql/suites/application-role-intersection/utils/find-object-metadata-id-by-name.util';
+import { findObjectMetadataIdByName } from 'test/integration/utils/find-object-metadata-id-by-name.util';
import { workspaceBlocklistEntryExists } from 'test/integration/graphql/suites/application-role-intersection/utils/read-target-state.util';
import {
cleanupDelegatedApplications,
diff --git a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/fields-permissions/read-permissions.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/fields-permissions/read-permissions.integration-spec.ts
deleted file mode 100644
index 3c8c18f0428..00000000000
--- a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/fields-permissions/read-permissions.integration-spec.ts
+++ /dev/null
@@ -1,627 +0,0 @@
-import { randomUUID } from 'crypto';
-
-import gql from 'graphql-tag';
-import request from 'supertest';
-import { createCustomRoleWithObjectPermissions } from 'test/integration/graphql/utils/create-custom-role-with-object-permissions.util';
-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 { deleteRole } from 'test/integration/graphql/utils/delete-one-role.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 { groupByOperationFactory } from 'test/integration/graphql/utils/group-by-operation-factory.util';
-import { makeGraphqlApiRequestWithMemberRole } from 'test/integration/graphql/utils/make-graphql-api-request-with-member-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 { updateOneOperationFactory } from 'test/integration/graphql/utils/update-one-operation-factory.util';
-import { updateWorkspaceMemberRole } from 'test/integration/graphql/utils/update-workspace-member-role.util';
-import { upsertFieldPermissions } from 'test/integration/graphql/utils/upsert-field-permissions.util';
-import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';
-
-import { ErrorCode } from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
-import { PermissionsExceptionMessage } from 'src/engine/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}`);
-
-const COMPANY_GQL_FIELDS_WITH_PEOPLE_JOB_TITLE = `
- id
- name
- people {
- edges {
- node {
- id
- name {
- firstName
- lastName
- }
- jobTitle
- }
- }
- }
-`;
-
-const COMPANY_GQL_FIELDS_WITH_POSITION = `
- id
- name
- position
- people {
- edges {
- node {
- id
- name {
- firstName
- lastName
- }
- }
- }
- }
-`;
-
-const COMPANY_GQL_FIELDS_WITHOUT_POSITION_AND_WITHOUT_PEOPLE_JOB_TITLE = `
- id
- name
- people {
- edges {
- node {
- id
- name {
- firstName
- lastName
- }
- }
- }
- }
-`;
-
-const COMPANY_GQL_FIELDS_WITH_PEOPLE_JOB_TITLE_AGGREGATE = `
- id
- name
- people {
- percentageEmptyJobTitle
- }
-`;
-
-const expectNoGraphQLErrors = (response: any) => {
- expect(response.body.errors).toBeUndefined();
- expect(response.body.data).toBeDefined();
-};
-
-const expectPermissionDeniedError = (response: any) => {
- expect(response.body.errors).toBeDefined();
- expect(response.body.errors.length).toBeGreaterThan(0);
- expect(response.body.errors[0].message).toContain(
- PermissionsExceptionMessage.PERMISSION_DENIED,
- );
- expect(response.body.errors[0].extensions.code).toBe(ErrorCode.FORBIDDEN);
-};
-
-describe('Field permissions restrictions', () => {
- let companyId: string;
- let personId: string;
- let customRoleId: string;
- let companyObjectId: string;
- let personObjectId: string;
- let restrictedCompanyFieldId: string;
- let restrictedPersonFieldId: string;
- let originalMemberRoleId: string;
-
- const restrictAccessToCompanyEmployee = async (
- roleId: string,
- companyObjectId: string,
- restrictedCompanyFieldId: string,
- ) => {
- await upsertFieldPermissions({
- roleId,
- fieldPermissions: [
- {
- objectMetadataId: companyObjectId,
- fieldMetadataId: restrictedCompanyFieldId,
- canUpdateFieldValue: false,
- },
- ],
- });
- };
-
- const restrictAccessToPersonCity = async (
- roleId: string,
- personObjectId: string,
- restrictedPersonFieldId: string,
- ) => {
- await upsertFieldPermissions({
- roleId,
- fieldPermissions: [
- {
- objectMetadataId: personObjectId,
- fieldMetadataId: restrictedPersonFieldId,
- canUpdateFieldValue: false,
- },
- ],
- });
- };
-
- beforeAll(async () => {
- const getRolesQuery = {
- query: `
- query GetRoles {
- getRoles {
- id
- label
- }
- }
- `,
- };
- const rolesResponse = await client
- .post('/metadata')
- .set('Authorization', `Bearer ${APPLE_JANE_ADMIN_ACCESS_TOKEN}`)
- .send(getRolesQuery);
-
- originalMemberRoleId = rolesResponse.body.data.getRoles.find(
- (role: any) => role.label === 'Member',
- ).id;
-
- companyId = randomUUID();
- personId = randomUUID();
- const createCompanyOp = createOneOperationFactory({
- objectMetadataSingularName: 'company',
- gqlFields: 'id name',
- data: { id: companyId, name: 'TestCompany' },
- });
-
- await makeGraphqlApiRequest(createCompanyOp);
- const createPersonOperation = createOneOperationFactory({
- objectMetadataSingularName: 'person',
- gqlFields: 'id jobTitle',
- data: { id: personId, jobTitle: 'Paris', companyId },
- });
-
- await makeGraphqlApiRequest(createPersonOperation);
-
- const getObjectMetadataOp = {
- query: gql`
- query {
- objects(paging: { first: 1000 }) {
- edges {
- node {
- id
- nameSingular
- }
- }
- }
- }
- `,
- };
- const objectMetadataResponse =
- await makeMetadataApiRequest(getObjectMetadataOp);
- const objects = objectMetadataResponse.body.data.objects.edges;
-
- companyObjectId = objects.find(
- (obj: any) => obj.node.nameSingular === 'company',
- ).node.id;
- personObjectId = objects.find(
- (obj: any) => obj.node.nameSingular === 'person',
- ).node.id;
-
- const getFieldMetadataOp = {
- query: gql`
- query {
- fields(paging: { first: 1000 }) {
- edges {
- node {
- id
- name
- object {
- nameSingular
- }
- }
- }
- }
- }
- `,
- };
- const fieldMetadataResponse =
- await makeMetadataApiRequest(getFieldMetadataOp);
- const fields = fieldMetadataResponse.body.data.fields.edges;
-
- restrictedCompanyFieldId = fields.find(
- (field: any) =>
- field.node.name === 'position' &&
- field.node.object.nameSingular === 'company',
- ).node.id;
- restrictedPersonFieldId = fields.find(
- (field: any) =>
- field.node.name === 'jobTitle' &&
- field.node.object.nameSingular === 'person',
- ).node.id;
- });
-
- afterAll(async () => {
- const restoreMemberRoleQuery = {
- query: `
- mutation UpdateWorkspaceMemberRole {
- updateWorkspaceMemberRole(
- workspaceMemberId: "${WORKSPACE_MEMBER_DATA_SEED_IDS.JONY}"
- roleId: "${originalMemberRoleId}"
- ) { id }
- }
- `,
- };
-
- await client
- .post('/metadata')
- .set('Authorization', `Bearer ${APPLE_JANE_ADMIN_ACCESS_TOKEN}`)
- .send(restoreMemberRoleQuery);
- });
-
- beforeEach(async () => {
- const { roleId } = await createCustomRoleWithObjectPermissions({
- label: 'CompanyPeopleRole',
- canReadCompany: true,
- canReadPerson: true,
- });
-
- customRoleId = roleId;
- await updateWorkspaceMemberRole({
- client,
- roleId: customRoleId,
- workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
- });
- });
-
- afterEach(async () => {
- if (customRoleId) {
- await deleteRole(client, customRoleId);
- customRoleId = '';
- }
- });
-
- describe('should allow restricted fields to be read', () => {
- beforeEach(async () => {
- await restrictAccessToCompanyEmployee(
- customRoleId,
- companyObjectId,
- restrictedCompanyFieldId,
- );
- });
-
- it('1. findMany', async () => {
- const graphqlOperation = findManyOperationFactory({
- objectMetadataSingularName: 'company',
- objectMetadataPluralName: 'companies',
- gqlFields: COMPANY_GQL_FIELDS_WITH_POSITION,
- });
- const response =
- await makeGraphqlApiRequestWithMemberRole(graphqlOperation);
-
- expectNoGraphQLErrors(response);
- expect(response.body.data.companies.edges[0].node.position).toBeDefined();
- });
-
- it('2. findOne', async () => {
- const graphqlOperation = findOneOperationFactory({
- objectMetadataSingularName: 'company',
- gqlFields: COMPANY_GQL_FIELDS_WITH_POSITION,
- filter: { id: { eq: companyId } },
- });
- const response =
- await makeGraphqlApiRequestWithMemberRole(graphqlOperation);
-
- expectNoGraphQLErrors(response);
- expect(response.body.data.company.position).toBeDefined();
- });
-
- it('3. updateMany', async () => {
- const graphqlOperation = updateManyOperationFactory({
- objectMetadataSingularName: 'company',
- objectMetadataPluralName: 'companies',
- gqlFields: COMPANY_GQL_FIELDS_WITH_POSITION,
- filter: { id: { eq: companyId } },
- data: { name: 'TestUpdate' },
- });
-
- const response =
- await makeGraphqlApiRequestWithMemberRole(graphqlOperation);
-
- expectPermissionDeniedError(response);
- });
-
- it('4. updateOne', async () => {
- const graphqlOperation = updateOneOperationFactory({
- objectMetadataSingularName: 'company',
- gqlFields: COMPANY_GQL_FIELDS_WITH_POSITION,
- recordId: companyId,
- data: { name: 'TestUpdate' },
- });
-
- const response =
- await makeGraphqlApiRequestWithMemberRole(graphqlOperation);
-
- expectPermissionDeniedError(response);
- });
-
- it('5. createMany', async () => {
- const graphqlOperation = createManyOperationFactory({
- objectMetadataSingularName: 'company',
- objectMetadataPluralName: 'companies',
- gqlFields: COMPANY_GQL_FIELDS_WITH_POSITION,
- data: [
- { id: randomUUID(), name: 'TestCompany' },
- { id: randomUUID(), name: 'TestCompany2' },
- ],
- });
-
- const response =
- await makeGraphqlApiRequestWithMemberRole(graphqlOperation);
-
- expectPermissionDeniedError(response);
- });
-
- it('5. createOne', async () => {
- const graphqlOperation = createOneOperationFactory({
- objectMetadataSingularName: 'company',
- gqlFields: COMPANY_GQL_FIELDS_WITH_POSITION,
- data: { id: randomUUID(), name: 'TestCompany3' },
- });
-
- const response =
- await makeGraphqlApiRequestWithMemberRole(graphqlOperation);
-
- expectPermissionDeniedError(response);
- });
-
- it('6. deleteMany', async () => {
- const graphqlOperation = deleteManyOperationFactory({
- objectMetadataSingularName: 'company',
- objectMetadataPluralName: 'companies',
- gqlFields: COMPANY_GQL_FIELDS_WITH_POSITION,
- filter: { id: { eq: companyId } },
- });
-
- const response =
- await makeGraphqlApiRequestWithMemberRole(graphqlOperation);
-
- expectPermissionDeniedError(response);
- });
-
- it('7. deleteOne', async () => {
- const graphqlOperation = deleteOneOperationFactory({
- objectMetadataSingularName: 'company',
- gqlFields: COMPANY_GQL_FIELDS_WITH_POSITION,
- recordId: companyId,
- });
-
- const response =
- await makeGraphqlApiRequestWithMemberRole(graphqlOperation);
-
- expectPermissionDeniedError(response);
- });
- });
-
- it('2. should allow a restricted field of a related object to be read', async () => {
- await restrictAccessToPersonCity(
- customRoleId,
- personObjectId,
- restrictedPersonFieldId,
- );
- const graphqlOperation = findManyOperationFactory({
- objectMetadataSingularName: 'company',
- objectMetadataPluralName: 'companies',
- gqlFields: COMPANY_GQL_FIELDS_WITH_PEOPLE_JOB_TITLE,
- filter: { id: { eq: companyId } },
- });
- const response =
- await makeGraphqlApiRequestWithMemberRole(graphqlOperation);
-
- expectNoGraphQLErrors(response);
- expect(
- response.body.data.companies.edges[0].node.people.edges[0].node.jobTitle,
- ).toBeDefined();
- });
-
- it('3. should succeed if restricted fields exist but are not requested', async () => {
- await restrictAccessToCompanyEmployee(
- customRoleId,
- companyObjectId,
- restrictedCompanyFieldId,
- );
- await restrictAccessToPersonCity(
- customRoleId,
- personObjectId,
- restrictedPersonFieldId,
- );
-
- const graphqlOperation = findManyOperationFactory({
- objectMetadataSingularName: 'company',
- objectMetadataPluralName: 'companies',
- gqlFields:
- COMPANY_GQL_FIELDS_WITHOUT_POSITION_AND_WITHOUT_PEOPLE_JOB_TITLE,
- });
- const response =
- await makeGraphqlApiRequestWithMemberRole(graphqlOperation);
-
- expect(response.body.errors).toBeUndefined();
- expect(response.body.data).toBeDefined();
- expect(response.body.data.companies.edges[0].node.id).toBeDefined();
- });
-
- it('should reject filters on fields without read permission', async () => {
- await upsertFieldPermissions({
- roleId: customRoleId,
- fieldPermissions: [
- {
- objectMetadataId: personObjectId,
- fieldMetadataId: restrictedPersonFieldId,
- canReadFieldValue: false,
- canUpdateFieldValue: null,
- },
- ],
- });
-
- const graphqlOperation = {
- query: gql`
- query People($filter: PersonFilterInput) {
- people(filter: $filter, first: 0) {
- totalCount
- }
- }
- `,
- variables: {
- filter: { jobTitle: { like: 'Par%' } },
- },
- };
-
- const response =
- await makeGraphqlApiRequestWithMemberRole(graphqlOperation);
-
- expectPermissionDeniedError(response);
- });
-
- it('should reject ordering a group by on a relation record by a target field without read permission', async () => {
- await upsertFieldPermissions({
- roleId: customRoleId,
- fieldPermissions: [
- {
- objectMetadataId: companyObjectId,
- fieldMetadataId: restrictedCompanyFieldId,
- canReadFieldValue: false,
- canUpdateFieldValue: null,
- },
- ],
- });
-
- const graphqlOperation = groupByOperationFactory({
- objectMetadataSingularName: 'person',
- objectMetadataPluralName: 'people',
- groupBy: [{ companyId: true }],
- orderBy: [{ company: { position: 'AscNullsLast' } }],
- });
-
- const response =
- await makeGraphqlApiRequestWithMemberRole(graphqlOperation);
-
- expectPermissionDeniedError(response);
- });
-
- it('should allow ordering a group by on a relation record by a readable target field', async () => {
- await upsertFieldPermissions({
- roleId: customRoleId,
- fieldPermissions: [
- {
- objectMetadataId: companyObjectId,
- fieldMetadataId: restrictedCompanyFieldId,
- canReadFieldValue: false,
- canUpdateFieldValue: null,
- },
- ],
- });
-
- const graphqlOperation = groupByOperationFactory({
- objectMetadataSingularName: 'person',
- objectMetadataPluralName: 'people',
- groupBy: [{ companyId: true }],
- orderBy: [{ company: { name: 'AscNullsLast' } }],
- });
-
- const response =
- await makeGraphqlApiRequestWithMemberRole(graphqlOperation);
-
- expectNoGraphQLErrors(response);
- });
-
- it('should return record field values in a group by records selection when the field is readable', async () => {
- const graphqlOperation = groupByOperationFactory({
- objectMetadataSingularName: 'person',
- objectMetadataPluralName: 'people',
- groupBy: [{ companyId: true }],
- filter: { id: { eq: personId } },
- gqlFields: 'edges { node { id jobTitle } }',
- });
-
- const response =
- await makeGraphqlApiRequestWithMemberRole(graphqlOperation);
-
- expectNoGraphQLErrors(response);
-
- const jobTitles = response.body.data.peopleGroupBy
- .flatMap(
- (group: { edges: { node: { jobTitle: string } }[] }) => group.edges,
- )
- .map((edge: { node: { jobTitle: string } }) => edge.node.jobTitle);
-
- expect(jobTitles).toContain('Paris');
- });
-
- it('should reject reading a record field without read permission in a group by records selection', async () => {
- await upsertFieldPermissions({
- roleId: customRoleId,
- fieldPermissions: [
- {
- objectMetadataId: personObjectId,
- fieldMetadataId: restrictedPersonFieldId,
- canReadFieldValue: false,
- canUpdateFieldValue: null,
- },
- ],
- });
-
- const graphqlOperation = groupByOperationFactory({
- objectMetadataSingularName: 'person',
- objectMetadataPluralName: 'people',
- groupBy: [{ companyId: true }],
- gqlFields: 'edges { node { id jobTitle } }',
- });
-
- const response =
- await makeGraphqlApiRequestWithMemberRole(graphqlOperation);
-
- expectPermissionDeniedError(response);
- });
-
- describe('Aggregate operations', () => {
- it('1. should allow aggregate over a restricted field', async () => {
- await restrictAccessToCompanyEmployee(
- customRoleId,
- companyObjectId,
- restrictedCompanyFieldId,
- );
-
- const graphqlOperation = {
- query: gql`
- query Companies {
- companies {
- countEmptyPosition
- }
- }
- `,
- };
- const response =
- await makeGraphqlApiRequestWithMemberRole(graphqlOperation);
-
- expectNoGraphQLErrors(response);
- expect(response.body.data.companies.countEmptyPosition).toBeDefined();
- });
-
- it('2. should allow aggregate over a restricted field on a related object', async () => {
- await restrictAccessToPersonCity(
- customRoleId,
- personObjectId,
- restrictedPersonFieldId,
- );
-
- const graphqlOperation = findManyOperationFactory({
- objectMetadataSingularName: 'company',
- objectMetadataPluralName: 'companies',
- gqlFields: COMPANY_GQL_FIELDS_WITH_PEOPLE_JOB_TITLE_AGGREGATE,
- });
- const response =
- await makeGraphqlApiRequestWithMemberRole(graphqlOperation);
-
- expectNoGraphQLErrors(response);
- expect(
- response.body.data.companies.edges[0].node.people
- .percentageEmptyJobTitle,
- ).toBeDefined();
- });
- });
-});
diff --git a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/fields-permissions/update-permissions.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/fields-permissions/update-permissions.integration-spec.ts
deleted file mode 100644
index 5c4b97a43c2..00000000000
--- a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/fields-permissions/update-permissions.integration-spec.ts
+++ /dev/null
@@ -1,391 +0,0 @@
-import { randomUUID } from 'crypto';
-
-import gql from 'graphql-tag';
-import request from 'supertest';
-import { createCustomRoleWithObjectPermissions } from 'test/integration/graphql/utils/create-custom-role-with-object-permissions.util';
-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 { deleteRole } from 'test/integration/graphql/utils/delete-one-role.util';
-import { makeGraphqlApiRequestWithMemberRole } from 'test/integration/graphql/utils/make-graphql-api-request-with-member-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 { updateOneOperationFactory } from 'test/integration/graphql/utils/update-one-operation-factory.util';
-import { updateWorkspaceMemberRole } from 'test/integration/graphql/utils/update-workspace-member-role.util';
-import { upsertFieldPermissions } from 'test/integration/graphql/utils/upsert-field-permissions.util';
-import { upsertRowLevelPermissionPredicates } from 'test/integration/metadata/suites/row-level-permission-predicate/utils/upsert-row-level-permission-predicates.util';
-import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';
-import { RowLevelPermissionPredicateOperand } from 'twenty-shared/types';
-
-import { ErrorCode } from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
-import { PermissionsExceptionMessage } from 'src/engine/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}`);
-
-const COMPANY_GQL_FIELDS_WITH_EMPLOYEES = `
- id
- name
- employees
-`;
-
-const COMPANY_GQL_FIELDS_WITHOUT_EMPLOYEES = `
- id
- name
-`;
-const expectPermissionDeniedError = (response: any) => {
- expect(response.body.errors).toBeDefined();
- expect(response.body.errors.length).toBeGreaterThan(0);
- expect(response.body.errors[0].message).toContain(
- PermissionsExceptionMessage.PERMISSION_DENIED,
- );
- expect(response.body.errors[0].extensions.code).toBe(ErrorCode.FORBIDDEN);
-};
-
-const expectEmployeesIsAccessible = ({
- response,
- operationName,
- expectedEmployees,
-}: {
- response: any;
- operationName: 'createCompanies' | 'createCompany';
- expectedEmployees: number;
-}) => {
- expect(response.body.errors).toBeUndefined();
- expect(response.body.data).toBeDefined();
-
- const result =
- operationName === 'createCompany'
- ? response.body.data[operationName]
- : response.body.data[operationName]?.[0];
-
- expect(result).toBeDefined();
- expect(result.employees).toBe(expectedEmployees);
-};
-
-describe('Field update permissions restrictions', () => {
- let companyId: string;
- let personId: string;
- let customRoleId: string;
- let companyObjectId: string;
- let restrictedCompanyFieldId: string;
- let originalMemberRoleId: string;
-
- const restrictUpdateAccessToCompanyEmployee = async (
- roleId: string,
- companyObjectId: string,
- restrictedCompanyFieldId: string,
- ) => {
- await upsertFieldPermissions({
- roleId,
- fieldPermissions: [
- {
- objectMetadataId: companyObjectId,
- fieldMetadataId: restrictedCompanyFieldId,
- canUpdateFieldValue: false,
- },
- ],
- });
- };
-
- const restrictReadAccessToCompanyEmployee = async (
- roleId: string,
- companyObjectId: string,
- restrictedCompanyFieldId: string,
- ) => {
- await upsertFieldPermissions({
- roleId,
- fieldPermissions: [
- {
- objectMetadataId: companyObjectId,
- fieldMetadataId: restrictedCompanyFieldId,
- canReadFieldValue: false,
- },
- ],
- });
- };
-
- beforeAll(async () => {
- const getRolesQuery = {
- query: `
- query GetRoles {
- getRoles {
- id
- label
- }
- }
- `,
- };
- const rolesResponse = await client
- .post('/metadata')
- .set('Authorization', `Bearer ${APPLE_JANE_ADMIN_ACCESS_TOKEN}`)
- .send(getRolesQuery);
-
- originalMemberRoleId = rolesResponse.body.data.getRoles.find(
- (role: any) => role.label === 'Member',
- ).id;
-
- companyId = randomUUID();
- personId = randomUUID();
- const createCompanyOp = createOneOperationFactory({
- objectMetadataSingularName: 'company',
- gqlFields: 'id name employees',
- data: { id: companyId, name: 'TestCompany', employees: 10 },
- });
-
- await makeGraphqlApiRequest(createCompanyOp);
- const createPersonOperation = createOneOperationFactory({
- objectMetadataSingularName: 'person',
- gqlFields: 'id jobTitle',
- data: { id: personId, jobTitle: 'Paris', companyId },
- });
-
- await makeGraphqlApiRequest(createPersonOperation);
-
- const getObjectMetadataOp = {
- query: gql`
- query {
- objects(paging: { first: 1000 }) {
- edges {
- node {
- id
- nameSingular
- }
- }
- }
- }
- `,
- };
- const objectMetadataResponse =
- await makeMetadataApiRequest(getObjectMetadataOp);
- const objects = objectMetadataResponse.body.data.objects.edges;
-
- companyObjectId = objects.find(
- (obj: any) => obj.node.nameSingular === 'company',
- ).node.id;
-
- const getFieldMetadataOp = {
- query: gql`
- query {
- fields(paging: { first: 1000 }) {
- edges {
- node {
- id
- name
- object {
- nameSingular
- }
- }
- }
- }
- }
- `,
- };
- const fieldMetadataResponse =
- await makeMetadataApiRequest(getFieldMetadataOp);
- const fields = fieldMetadataResponse.body.data.fields.edges;
-
- restrictedCompanyFieldId = fields.find(
- (field: any) =>
- field.node.name === 'employees' &&
- field.node.object.nameSingular === 'company',
- ).node.id;
- });
-
- afterAll(async () => {
- const restoreMemberRoleQuery = {
- query: `
- mutation UpdateWorkspaceMemberRole {
- updateWorkspaceMemberRole(
- workspaceMemberId: "${WORKSPACE_MEMBER_DATA_SEED_IDS.JONY}"
- roleId: "${originalMemberRoleId}"
- ) { id }
- }
- `,
- };
-
- await client
- .post('/metadata')
- .set('Authorization', `Bearer ${APPLE_JANE_ADMIN_ACCESS_TOKEN}`)
- .send(restoreMemberRoleQuery);
- });
-
- beforeEach(async () => {
- const { roleId } = await createCustomRoleWithObjectPermissions({
- label: 'CompanyPeopleRole',
- canReadCompany: true,
- canReadPerson: true,
- hasAllObjectRecordsReadPermission: true,
- canUpdateCompany: true,
- canUpdatePerson: true,
- canUpdateOpportunities: true,
- });
-
- customRoleId = roleId;
- await updateWorkspaceMemberRole({
- client,
- roleId: customRoleId,
- workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
- });
- });
-
- afterEach(async () => {
- if (customRoleId) {
- await deleteRole(client, customRoleId);
- customRoleId = '';
- }
- });
-
- describe('should allow employees field when creating if field is in RLS predicate', () => {
- beforeEach(async () => {
- await restrictUpdateAccessToCompanyEmployee(
- customRoleId,
- companyObjectId,
- restrictedCompanyFieldId,
- );
-
- await upsertRowLevelPermissionPredicates({
- input: {
- roleId: customRoleId,
- objectMetadataId: companyObjectId,
- predicates: [
- {
- fieldMetadataId: restrictedCompanyFieldId,
- operand: RowLevelPermissionPredicateOperand.IS_NOT_EMPTY,
- },
- ],
- predicateGroups: [],
- },
- });
- });
-
- afterEach(async () => {
- await upsertRowLevelPermissionPredicates({
- input: {
- roleId: customRoleId,
- objectMetadataId: companyObjectId,
- predicates: [],
- predicateGroups: [],
- },
- });
- });
-
- it('1. createMany with restricted field in RLS predicate', async () => {
- const graphqlOperation = createManyOperationFactory({
- objectMetadataSingularName: 'company',
- objectMetadataPluralName: 'companies',
- gqlFields: COMPANY_GQL_FIELDS_WITH_EMPLOYEES,
- data: [
- { id: randomUUID(), name: 'NewCompany1', employees: 15 },
- { id: randomUUID(), name: 'NewCompany2', employees: 20 },
- ],
- });
-
- const response =
- await makeGraphqlApiRequestWithMemberRole(graphqlOperation);
-
- expectEmployeesIsAccessible({
- response,
- operationName: 'createCompanies',
- expectedEmployees: 15,
- });
- });
-
- it('2. createOne with restricted field in RLS predicate', async () => {
- const graphqlOperation = createOneOperationFactory({
- objectMetadataSingularName: 'company',
- gqlFields: COMPANY_GQL_FIELDS_WITH_EMPLOYEES,
- data: { id: randomUUID(), name: 'NewCompany3', employees: 25 },
- });
-
- const response =
- await makeGraphqlApiRequestWithMemberRole(graphqlOperation);
-
- expectEmployeesIsAccessible({
- response,
- operationName: 'createCompany',
- expectedEmployees: 25,
- });
- });
- });
- describe('should block read-restricted field in update operation responses', () => {
- beforeEach(async () => {
- await restrictReadAccessToCompanyEmployee(
- customRoleId,
- companyObjectId,
- restrictedCompanyFieldId,
- );
- });
-
- it('1. updateMany requesting restricted field in response', async () => {
- const graphqlOperation = updateManyOperationFactory({
- objectMetadataSingularName: 'company',
- objectMetadataPluralName: 'companies',
- gqlFields: COMPANY_GQL_FIELDS_WITH_EMPLOYEES,
- data: { name: 'UpdatedCompany' },
- filter: { id: { eq: companyId } },
- });
-
- const response =
- await makeGraphqlApiRequestWithMemberRole(graphqlOperation);
-
- expectPermissionDeniedError(response);
- });
-
- it('2. updateOne requesting restricted field in response', async () => {
- const graphqlOperation = updateOneOperationFactory({
- objectMetadataSingularName: 'company',
- gqlFields: COMPANY_GQL_FIELDS_WITH_EMPLOYEES,
- recordId: companyId,
- data: { name: 'UpdatedCompany' },
- });
-
- const response =
- await makeGraphqlApiRequestWithMemberRole(graphqlOperation);
-
- expectPermissionDeniedError(response);
- });
- });
-
- describe('should succeed if not requesting restricted fields in update operations', () => {
- beforeEach(async () => {
- await restrictUpdateAccessToCompanyEmployee(
- customRoleId,
- companyObjectId,
- restrictedCompanyFieldId,
- );
- });
-
- it('1. updateMany not requesting restricted field in response', async () => {
- const graphqlOperation = updateManyOperationFactory({
- objectMetadataSingularName: 'company',
- objectMetadataPluralName: 'companies',
- gqlFields: COMPANY_GQL_FIELDS_WITHOUT_EMPLOYEES,
- data: { name: 'UpdatedCompany' },
- filter: { id: { eq: companyId } },
- });
-
- const response =
- await makeGraphqlApiRequestWithMemberRole(graphqlOperation);
-
- expect(response.body.errors).toBeUndefined();
- expect(response.body.data).toBeDefined();
- expect(response.body.data.updateCompanies[0].name).toBe('UpdatedCompany');
- });
-
- it('2. updateOne not requesting restricted field in response', async () => {
- const graphqlOperation = updateOneOperationFactory({
- objectMetadataSingularName: 'company',
- gqlFields: COMPANY_GQL_FIELDS_WITHOUT_EMPLOYEES,
- recordId: companyId,
- data: { name: 'UpdatedCompany2' },
- });
-
- const response =
- await makeGraphqlApiRequestWithMemberRole(graphqlOperation);
-
- expect(response.body.errors).toBeUndefined();
- expect(response.body.data).toBeDefined();
- expect(response.body.data.updateCompany.name).toBe('UpdatedCompany2');
- });
- });
-});
diff --git a/packages/twenty-server/test/integration/graphql/suites/user-session/failing-code-interpreter-token-beyond-agent-role.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/user-session/failing-code-interpreter-token-beyond-agent-role.integration-spec.ts
index 1406e428595..40b40ea9795 100644
--- a/packages/twenty-server/test/integration/graphql/suites/user-session/failing-code-interpreter-token-beyond-agent-role.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/user-session/failing-code-interpreter-token-beyond-agent-role.integration-spec.ts
@@ -1,6 +1,6 @@
import gql from 'graphql-tag';
import { callMcpTool } from 'test/integration/graphql/suites/application-role-intersection/utils/call-mcp-tool.util';
-import { findObjectMetadataIdByName } from 'test/integration/graphql/suites/application-role-intersection/utils/find-object-metadata-id-by-name.util';
+import { findObjectMetadataIdByName } from 'test/integration/utils/find-object-metadata-id-by-name.util';
import { captureAgentRunExecution } from 'test/integration/graphql/suites/user-session/utils/capture-agent-run-execution.util';
import { captureCodeInterpreterSandboxToken } from 'test/integration/graphql/suites/user-session/utils/capture-code-interpreter-sandbox-token.util';
import { listMcpTools } from 'test/integration/graphql/suites/user-session/utils/list-mcp-tools.util';
diff --git a/packages/twenty-server/test/integration/permissions/fields/field-permissions.integration-spec.ts b/packages/twenty-server/test/integration/permissions/fields/field-permissions.integration-spec.ts
new file mode 100644
index 00000000000..a2a2d2b6dd2
--- /dev/null
+++ b/packages/twenty-server/test/integration/permissions/fields/field-permissions.integration-spec.ts
@@ -0,0 +1,609 @@
+import { randomUUID } from 'node:crypto';
+
+import gql from 'graphql-tag';
+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 { findManyOperationFactory } from 'test/integration/graphql/utils/find-many-operation-factory.util';
+import { groupByOperationFactory } from 'test/integration/graphql/utils/group-by-operation-factory.util';
+import { makeGraphqlApiRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';
+import { type ApiKeyWithObjectRecordGrants } from 'test/integration/permissions/utils/create-api-key-with-object-record-grants.util';
+import { createApiKeyWithFieldPermission } from 'test/integration/permissions/utils/create-api-key-with-field-permission.util';
+import { deleteApiKeysWithObjectRecordGrants } from 'test/integration/permissions/utils/delete-api-keys-with-object-record-grants.util';
+import { expectPermissionDenied } from 'test/integration/permissions/utils/expect-permission-denied.util';
+import { expectFieldPermissionDeniedResponse } from 'test/integration/permissions/utils/expect-field-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 { findRecordNodesByFilter } from 'test/integration/utils/find-records-by-filter.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 } from 'test/integration/utils/person-requests-by-api.util';
+
+const UPDATED_JOB_TITLE = 'Updated job title';
+const RESTRICTED_INTRO = 'Restricted intro';
+const LINKED_PERSON_INTRO = 'Linked person intro';
+
+const ACTIVE = { status: 'active', jobTitle: PERSON_RECORD_FIXTURE.jobTitle };
+const ACTIVE_UPDATED = { status: 'active', jobTitle: UPDATED_JOB_TITLE };
+const ABSENT = { status: 'absent' };
+
+const PERSON_FIELDS_WITH_INTRO = 'id jobTitle intro';
+
+const findSavedIntros = async (ids: string[]) => {
+ const people = await findRecordNodesByFilter<{ id: string; intro: string }>(
+ 'person',
+ 'people',
+ 'id intro',
+ { id: { in: ids } },
+ );
+
+ return ids.map((id) => people.find((person) => person.id === id)?.intro);
+};
+
+describe('field permissions on person.intro', () => {
+ let readRestricted: ApiKeyWithObjectRecordGrants;
+ let updateRestricted: ApiKeyWithObjectRecordGrants;
+ let updateRestrictedInPredicate: ApiKeyWithObjectRecordGrants;
+ const companyId = randomUUID();
+
+ beforeAll(async () => {
+ const createCompanyResponse = await makeGraphqlApiRequest(
+ createOneOperationFactory({
+ objectMetadataSingularName: 'company',
+ gqlFields: 'id',
+ data: { id: companyId, name: PERSON_RECORD_FIXTURE.firstName },
+ }),
+ );
+
+ expect(createCompanyResponse.body.errors).toBeUndefined();
+
+ const createPersonResponse = await personRequestsByApi.createOne({
+ api: 'graphql',
+ token: APPLE_JANE_ADMIN_ACCESS_TOKEN,
+ data: {
+ id: randomUUID(),
+ name: { firstName: PERSON_RECORD_FIXTURE.firstName },
+ jobTitle: PERSON_RECORD_FIXTURE.jobTitle,
+ intro: LINKED_PERSON_INTRO,
+ companyId,
+ },
+ });
+
+ expect(createPersonResponse.body.errors).toBeUndefined();
+
+ [readRestricted, updateRestricted, updateRestrictedInPredicate] =
+ await Promise.all([
+ createApiKeyWithFieldPermission({
+ objectNameSingular: 'person',
+ fieldName: 'intro',
+ canReadFieldValue: false,
+ }),
+ createApiKeyWithFieldPermission({
+ objectNameSingular: 'person',
+ fieldName: 'intro',
+ canUpdateFieldValue: false,
+ }),
+ createApiKeyWithFieldPermission({
+ objectNameSingular: 'person',
+ fieldName: 'intro',
+ canUpdateFieldValue: false,
+ isFieldInRowLevelPredicate: true,
+ }),
+ ]);
+ });
+
+ afterAll(async () => {
+ await Promise.all([
+ deleteApiKeysWithObjectRecordGrants([
+ readRestricted,
+ updateRestricted,
+ updateRestrictedInPredicate,
+ ]),
+ destroyPersonRecordsByFirstName(PERSON_RECORD_FIXTURE.firstName),
+ makeGraphqlApiRequest(
+ destroyOneOperationFactory({
+ objectMetadataSingularName: 'company',
+ gqlFields: 'id',
+ recordId: companyId,
+ }),
+ ),
+ ]);
+ });
+
+ describe('read-restricted field over GraphQL', () => {
+ it('denies findMany selecting it', async () => {
+ const ids = await createPersonRecords({ count: 1 });
+
+ const response = await personRequestsByApi.findMany({
+ api: 'graphql',
+ token: readRestricted.token,
+ ids,
+ gqlFields: PERSON_FIELDS_WITH_INTRO,
+ });
+
+ expectFieldPermissionDeniedResponse({
+ api: 'graphql',
+ response,
+ access: 'read',
+ objectNameSingular: 'person',
+ fieldName: 'intro',
+ });
+ });
+
+ it('allows findMany not selecting it', async () => {
+ const ids = await createPersonRecords({ count: 1 });
+
+ const response = await personRequestsByApi.findMany({
+ api: 'graphql',
+ token: readRestricted.token,
+ ids,
+ });
+
+ expectPermissionGrantedResponse({ api: 'graphql', response });
+ expect(response.body.data.people.edges[0].node.id).toBe(ids[0]);
+ });
+
+ it('denies findOne selecting it', async () => {
+ const [id] = await createPersonRecords({ count: 1 });
+
+ const response = await personRequestsByApi.findOne({
+ api: 'graphql',
+ token: readRestricted.token,
+ id,
+ gqlFields: PERSON_FIELDS_WITH_INTRO,
+ });
+
+ expectFieldPermissionDeniedResponse({
+ api: 'graphql',
+ response,
+ access: 'read',
+ objectNameSingular: 'person',
+ fieldName: 'intro',
+ });
+ });
+
+ it('denies updateOne selecting it, and does not write', async () => {
+ const [id] = await createPersonRecords({ count: 1 });
+
+ const response = await personRequestsByApi.updateOne({
+ api: 'graphql',
+ token: readRestricted.token,
+ id,
+ data: { jobTitle: UPDATED_JOB_TITLE },
+ gqlFields: PERSON_FIELDS_WITH_INTRO,
+ });
+
+ expectFieldPermissionDeniedResponse({
+ api: 'graphql',
+ response,
+ access: 'read',
+ objectNameSingular: 'person',
+ fieldName: 'intro',
+ });
+ expect(await findPersonRecordStates([id])).toEqual([ACTIVE]);
+ });
+
+ it('allows updateOne not selecting it', async () => {
+ const [id] = await createPersonRecords({ count: 1 });
+
+ const response = await personRequestsByApi.updateOne({
+ api: 'graphql',
+ token: readRestricted.token,
+ id,
+ data: { jobTitle: UPDATED_JOB_TITLE },
+ });
+
+ expectPermissionGrantedResponse({ api: 'graphql', response });
+ expect(await findPersonRecordStates([id])).toEqual([ACTIVE_UPDATED]);
+ });
+
+ it('denies updateMany selecting it, and does not write', async () => {
+ const ids = await createPersonRecords({ count: 2 });
+
+ const response = await personRequestsByApi.updateMany({
+ api: 'graphql',
+ token: readRestricted.token,
+ ids,
+ data: { jobTitle: UPDATED_JOB_TITLE },
+ gqlFields: PERSON_FIELDS_WITH_INTRO,
+ });
+
+ expectFieldPermissionDeniedResponse({
+ api: 'graphql',
+ response,
+ access: 'read',
+ objectNameSingular: 'person',
+ fieldName: 'intro',
+ });
+ expect(await findPersonRecordStates(ids)).toEqual([ACTIVE, ACTIVE]);
+ });
+
+ it('allows updateMany not selecting it', async () => {
+ const ids = await createPersonRecords({ count: 2 });
+
+ const response = await personRequestsByApi.updateMany({
+ api: 'graphql',
+ token: readRestricted.token,
+ ids,
+ data: { jobTitle: UPDATED_JOB_TITLE },
+ });
+
+ expectPermissionGrantedResponse({ api: 'graphql', response });
+ expect(await findPersonRecordStates(ids)).toEqual([
+ ACTIVE_UPDATED,
+ ACTIVE_UPDATED,
+ ]);
+ });
+
+ it('denies filtering on it', async () => {
+ const response = await makeGraphqlApiRequest(
+ findManyOperationFactory({
+ objectMetadataSingularName: 'person',
+ objectMetadataPluralName: 'people',
+ gqlFields: 'id',
+ filter: { intro: { like: 'Par%' } },
+ }),
+ readRestricted.token,
+ );
+
+ expectPermissionDenied(response.body.errors);
+ });
+
+ it('denies reading it through a relation', async () => {
+ const response = await makeGraphqlApiRequest(
+ findManyOperationFactory({
+ objectMetadataSingularName: 'company',
+ objectMetadataPluralName: 'companies',
+ gqlFields: 'id people { edges { node { id intro } } }',
+ filter: { id: { eq: companyId } },
+ }),
+ readRestricted.token,
+ );
+
+ expectFieldPermissionDeniedResponse({
+ api: 'graphql',
+ response,
+ access: 'read',
+ objectNameSingular: 'person',
+ fieldName: 'intro',
+ });
+ });
+
+ it('denies selecting it in group by records', async () => {
+ const response = await makeGraphqlApiRequest(
+ groupByOperationFactory({
+ objectMetadataSingularName: 'person',
+ objectMetadataPluralName: 'people',
+ groupBy: [{ companyId: true }],
+ gqlFields: 'edges { node { id intro } }',
+ }),
+ readRestricted.token,
+ );
+
+ expectFieldPermissionDeniedResponse({
+ api: 'graphql',
+ response,
+ access: 'read',
+ objectNameSingular: 'person',
+ fieldName: 'intro',
+ });
+ });
+
+ it('denies ordering a group by by it through a relation', async () => {
+ const response = await makeGraphqlApiRequest(
+ groupByOperationFactory({
+ objectMetadataSingularName: 'opportunity',
+ objectMetadataPluralName: 'opportunities',
+ groupBy: [{ pointOfContactId: true }],
+ orderBy: [{ pointOfContact: { intro: 'AscNullsLast' } }],
+ }),
+ readRestricted.token,
+ );
+
+ expectFieldPermissionDeniedResponse({
+ api: 'graphql',
+ response,
+ access: 'read',
+ objectNameSingular: 'person',
+ fieldName: 'intro',
+ });
+ });
+
+ it('allows ordering a group by by a readable field through the same relation', async () => {
+ const response = await makeGraphqlApiRequest(
+ groupByOperationFactory({
+ objectMetadataSingularName: 'opportunity',
+ objectMetadataPluralName: 'opportunities',
+ groupBy: [{ pointOfContactId: true }],
+ orderBy: [{ pointOfContact: { jobTitle: 'AscNullsLast' } }],
+ }),
+ readRestricted.token,
+ );
+
+ expectPermissionGrantedResponse({ api: 'graphql', response });
+ });
+
+ it('denies aggregating over it', async () => {
+ const response = await makeGraphqlApiRequest(
+ {
+ query: gql`
+ query People {
+ people {
+ countEmptyIntro
+ }
+ }
+ `,
+ },
+ readRestricted.token,
+ );
+
+ expectFieldPermissionDeniedResponse({
+ api: 'graphql',
+ response,
+ access: 'read',
+ objectNameSingular: 'person',
+ fieldName: 'intro',
+ });
+ });
+
+ it('denies aggregating over it through a relation', async () => {
+ const response = await makeGraphqlApiRequest(
+ findManyOperationFactory({
+ objectMetadataSingularName: 'company',
+ objectMetadataPluralName: 'companies',
+ gqlFields: 'id people { percentageEmptyIntro }',
+ filter: { id: { eq: companyId } },
+ }),
+ readRestricted.token,
+ );
+
+ expectFieldPermissionDeniedResponse({
+ api: 'graphql',
+ response,
+ access: 'read',
+ objectNameSingular: 'person',
+ fieldName: 'intro',
+ });
+ });
+ });
+
+ describe('read-restricted field over REST', () => {
+ it('omits it from findOne', async () => {
+ const [id] = await createPersonRecords({ count: 1 });
+
+ const response = await personRequestsByApi.findOne({
+ api: 'rest',
+ token: readRestricted.token,
+ id,
+ });
+
+ expectPermissionGrantedResponse({ api: 'rest', response });
+ expect(response.body.data.person.id).toBe(id);
+ expect(response.body.data.person.intro).toBeUndefined();
+ });
+
+ it('omits it from findMany', async () => {
+ const ids = await createPersonRecords({ count: 1 });
+
+ const response = await personRequestsByApi.findMany({
+ api: 'rest',
+ token: readRestricted.token,
+ ids,
+ });
+
+ expectPermissionGrantedResponse({ api: 'rest', response });
+ expect(response.body.data.people[0].id).toBe(ids[0]);
+ expect(response.body.data.people[0].intro).toBeUndefined();
+ });
+
+ it('omits it from the updateOne response and writes', async () => {
+ const [id] = await createPersonRecords({ count: 1 });
+
+ const response = await personRequestsByApi.updateOne({
+ api: 'rest',
+ token: readRestricted.token,
+ id,
+ data: { jobTitle: UPDATED_JOB_TITLE },
+ });
+
+ expectPermissionGrantedResponse({ api: 'rest', response });
+ expect(response.body.data.updatePerson.intro).toBeUndefined();
+ expect(await findPersonRecordStates([id])).toEqual([ACTIVE_UPDATED]);
+ });
+ });
+
+ describe('update-restricted field in GraphQL selections', () => {
+ it('allows a write whose selection includes it', async () => {
+ const [id] = await createPersonRecords({ count: 1 });
+
+ const response = await personRequestsByApi.updateOne({
+ api: 'graphql',
+ token: updateRestricted.token,
+ id,
+ data: { jobTitle: UPDATED_JOB_TITLE },
+ gqlFields: PERSON_FIELDS_WITH_INTRO,
+ });
+
+ expectPermissionGrantedResponse({ api: 'graphql', response });
+ expect(await findPersonRecordStates([id])).toEqual([ACTIVE_UPDATED]);
+ });
+
+ it('allows reading it through a relation', async () => {
+ const response = await makeGraphqlApiRequest(
+ findManyOperationFactory({
+ objectMetadataSingularName: 'company',
+ objectMetadataPluralName: 'companies',
+ gqlFields: 'id people { edges { node { id intro } } }',
+ filter: { id: { eq: companyId } },
+ }),
+ updateRestricted.token,
+ );
+
+ expectPermissionGrantedResponse({ api: 'graphql', response });
+ expect(
+ response.body.data.companies.edges[0].node.people.edges.map(
+ ({ node }: { node: { intro: string } }) => node.intro,
+ ),
+ ).toEqual([LINKED_PERSON_INTRO]);
+ });
+ });
+
+ describe.each(['graphql', 'rest'] as const)(
+ 'update-restricted field over %s',
+ (api) => {
+ it('allows reading it', async () => {
+ const [id] = await createPersonRecords({ count: 1 });
+
+ const response = await personRequestsByApi.findOne({
+ api,
+ token: updateRestricted.token,
+ id,
+ gqlFields: PERSON_FIELDS_WITH_INTRO,
+ });
+
+ expectPermissionGrantedResponse({ api, response });
+ expect(response.body.data.person).toHaveProperty('intro');
+ });
+
+ it('denies updateOne writing it, and does not write', async () => {
+ const [id] = await createPersonRecords({ count: 1 });
+
+ const response = await personRequestsByApi.updateOne({
+ api,
+ token: updateRestricted.token,
+ id,
+ data: { intro: RESTRICTED_INTRO, jobTitle: UPDATED_JOB_TITLE },
+ });
+
+ expectFieldPermissionDeniedResponse({
+ api,
+ response,
+ access: 'write',
+ objectNameSingular: 'person',
+ fieldName: 'intro',
+ });
+ expect(await findPersonRecordStates([id])).toEqual([ACTIVE]);
+ expect(await findSavedIntros([id])).toEqual(['']);
+ });
+
+ it('allows updateOne writing another field', async () => {
+ const [id] = await createPersonRecords({ count: 1 });
+
+ const response = await personRequestsByApi.updateOne({
+ api,
+ token: updateRestricted.token,
+ id,
+ data: { jobTitle: UPDATED_JOB_TITLE },
+ });
+
+ expectPermissionGrantedResponse({ api, response });
+ expect(await findPersonRecordStates([id])).toEqual([ACTIVE_UPDATED]);
+ });
+
+ it('denies createOne writing it', async () => {
+ const id = randomUUID();
+
+ const response = await personRequestsByApi.createOne({
+ api,
+ token: updateRestricted.token,
+ data: {
+ id,
+ name: { firstName: PERSON_RECORD_FIXTURE.firstName },
+ intro: RESTRICTED_INTRO,
+ },
+ });
+
+ expectFieldPermissionDeniedResponse({
+ api,
+ response,
+ access: 'write',
+ objectNameSingular: 'person',
+ fieldName: 'intro',
+ });
+ expect(await findPersonRecordStates([id])).toEqual([ABSENT]);
+ });
+
+ it('denies createMany writing it', async () => {
+ const ids = [randomUUID(), randomUUID()];
+
+ const response = await personRequestsByApi.createMany({
+ api,
+ token: updateRestricted.token,
+ data: ids.map((id) => ({
+ id,
+ name: { firstName: PERSON_RECORD_FIXTURE.firstName },
+ intro: RESTRICTED_INTRO,
+ })),
+ });
+
+ expectFieldPermissionDeniedResponse({
+ api,
+ response,
+ access: 'write',
+ objectNameSingular: 'person',
+ fieldName: 'intro',
+ });
+ expect(await findPersonRecordStates(ids)).toEqual([ABSENT, ABSENT]);
+ });
+
+ it('allows createOne not writing it', async () => {
+ const id = randomUUID();
+
+ const response = await personRequestsByApi.createOne({
+ api,
+ token: updateRestricted.token,
+ data: {
+ id,
+ name: { firstName: PERSON_RECORD_FIXTURE.firstName },
+ jobTitle: PERSON_RECORD_FIXTURE.jobTitle,
+ },
+ });
+
+ expectPermissionGrantedResponse({ api, response });
+ expect(await findPersonRecordStates([id])).toEqual([ACTIVE]);
+ });
+
+ it('allows createOne writing it when it is in a row-level predicate', async () => {
+ const id = randomUUID();
+
+ const response = await personRequestsByApi.createOne({
+ api,
+ token: updateRestrictedInPredicate.token,
+ data: {
+ id,
+ name: { firstName: PERSON_RECORD_FIXTURE.firstName },
+ jobTitle: PERSON_RECORD_FIXTURE.jobTitle,
+ intro: RESTRICTED_INTRO,
+ },
+ });
+
+ expectPermissionGrantedResponse({ api, response });
+ expect(await findPersonRecordStates([id])).toEqual([ACTIVE]);
+ expect(await findSavedIntros([id])).toEqual(
+ [id].map(() => RESTRICTED_INTRO),
+ );
+ });
+
+ it('allows createMany writing it when it is in a row-level predicate', async () => {
+ const ids = [randomUUID(), randomUUID()];
+
+ const response = await personRequestsByApi.createMany({
+ api,
+ token: updateRestrictedInPredicate.token,
+ data: ids.map((id) => ({
+ id,
+ name: { firstName: PERSON_RECORD_FIXTURE.firstName },
+ jobTitle: PERSON_RECORD_FIXTURE.jobTitle,
+ intro: RESTRICTED_INTRO,
+ })),
+ });
+
+ expectPermissionGrantedResponse({ api, response });
+ expect(await findPersonRecordStates(ids)).toEqual([ACTIVE, ACTIVE]);
+ expect(await findSavedIntros(ids)).toEqual(
+ ids.map(() => RESTRICTED_INTRO),
+ );
+ });
+ },
+ );
+});
diff --git a/packages/twenty-server/test/integration/permissions/utils/create-api-key-with-field-permission.util.ts b/packages/twenty-server/test/integration/permissions/utils/create-api-key-with-field-permission.util.ts
new file mode 100644
index 00000000000..d671d986e81
--- /dev/null
+++ b/packages/twenty-server/test/integration/permissions/utils/create-api-key-with-field-permission.util.ts
@@ -0,0 +1,70 @@
+import { findObjectMetadataIdByName } from 'test/integration/utils/find-object-metadata-id-by-name.util';
+import { upsertFieldPermissions } from 'test/integration/metadata/suites/field-permission/utils/upsert-field-permissions.util';
+import { upsertRowLevelPermissionPredicates } from 'test/integration/metadata/suites/row-level-permission-predicate/utils/upsert-row-level-permission-predicates.util';
+import {
+ type ApiKeyWithObjectRecordGrants,
+ createApiKeyWithObjectRecordGrants,
+} from 'test/integration/permissions/utils/create-api-key-with-object-record-grants.util';
+import { findFieldMetadataIdByName } from 'test/integration/utils/find-field-metadata-id-by-name.util';
+
+import { RowLevelPermissionPredicateOperand } from 'twenty-shared/types';
+
+export const createApiKeyWithFieldPermission = async ({
+ objectNameSingular,
+ fieldName,
+ canReadFieldValue = null,
+ canUpdateFieldValue = null,
+ isFieldInRowLevelPredicate = false,
+}: {
+ objectNameSingular: string;
+ fieldName: string;
+ canReadFieldValue?: false | null;
+ canUpdateFieldValue?: false | null;
+ isFieldInRowLevelPredicate?: boolean;
+}): Promise<ApiKeyWithObjectRecordGrants> => {
+ const objectMetadataId = await findObjectMetadataIdByName(objectNameSingular);
+
+ const [apiKey, fieldMetadataId] = await Promise.all([
+ createApiKeyWithObjectRecordGrants({
+ canReadAllObjectRecords: true,
+ canUpdateAllObjectRecords: true,
+ canSoftDeleteAllObjectRecords: true,
+ canDestroyAllObjectRecords: true,
+ }),
+ findFieldMetadataIdByName({ objectMetadataId, fieldName }),
+ ]);
+
+ await upsertFieldPermissions({
+ input: {
+ roleId: apiKey.roleId,
+ fieldPermissions: [
+ {
+ objectMetadataId,
+ fieldMetadataId,
+ canReadFieldValue,
+ canUpdateFieldValue,
+ },
+ ],
+ },
+ expectToFail: false,
+ });
+
+ if (isFieldInRowLevelPredicate) {
+ await upsertRowLevelPermissionPredicates({
+ input: {
+ roleId: apiKey.roleId,
+ objectMetadataId,
+ predicates: [
+ {
+ fieldMetadataId,
+ operand: RowLevelPermissionPredicateOperand.IS_NOT_EMPTY,
+ },
+ ],
+ predicateGroups: [],
+ },
+ expectToFail: false,
+ });
+ }
+
+ return apiKey;
+};
diff --git a/packages/twenty-server/test/integration/permissions/utils/expect-field-permission-denied-response.util.ts b/packages/twenty-server/test/integration/permissions/utils/expect-field-permission-denied-response.util.ts
new file mode 100644
index 00000000000..decad1520b2
--- /dev/null
+++ b/packages/twenty-server/test/integration/permissions/utils/expect-field-permission-denied-response.util.ts
@@ -0,0 +1,40 @@
+import { type Response } from 'supertest';
+import { type RecordApi } from 'test/integration/utils/person-requests-by-api.util';
+
+import { ErrorCode } from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
+import {
+ PermissionsExceptionCode,
+ PermissionsExceptionMessage,
+} from 'src/engine/permissions/permissions.exception';
+
+export const expectFieldPermissionDeniedResponse = ({
+ api,
+ response,
+ access,
+ objectNameSingular,
+ fieldName,
+}: {
+ api: RecordApi;
+ response: Response;
+ access: 'read' | 'write';
+ objectNameSingular: string;
+ fieldName: string;
+}) => {
+ const message = `${PermissionsExceptionMessage.PERMISSION_DENIED}: no permission to ${access} field "${fieldName}" on "${objectNameSingular}"`;
+
+ if (api === 'graphql') {
+ expect(response.body.errors).toHaveLength(1);
+ expect(response.body.errors[0].message).toBe(message);
+ expect(response.body.errors[0].extensions.code).toBe(ErrorCode.FORBIDDEN);
+
+ for (const result of Object.values(response.body.data ?? {})) {
+ expect(result).toBeNull();
+ }
+
+ return;
+ }
+
+ expect(response.status).toBe(403);
+ expect(response.body.code).toBe(PermissionsExceptionCode.PERMISSION_DENIED);
+ expect(response.body.messages).toStrictEqual([message]);
+};
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
deleted file mode 100644
index a30b751dbe3..00000000000
--- a/packages/twenty-server/test/integration/rest/suites/field-permissions.integration-spec.ts
+++ /dev/null
@@ -1,517 +0,0 @@
-import gql from 'graphql-tag';
-import { TEST_COMPANY_1_ID } from 'test/integration/constants/test-company-ids.constants';
-import { TEST_PERSON_1_ID } from 'test/integration/constants/test-person-ids.constants';
-import { TEST_PRIMARY_LINK_URL } from 'test/integration/constants/test-primary-link-url.constant';
-import { upsertFieldPermissions } from 'test/integration/graphql/utils/upsert-field-permissions.util';
-import { upsertRowLevelPermissionPredicates } from 'test/integration/metadata/suites/row-level-permission-predicate/utils/upsert-row-level-permission-predicates.util';
-import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';
-import { makeRestApiRequest } from 'test/integration/rest/utils/make-rest-api-request.util';
-import { generateRecordName } from 'test/integration/utils/generate-record-name';
-import { RowLevelPermissionPredicateOperand } from 'twenty-shared/types';
-
-describe('Restricted fields', () => {
- let personJobTitle: string;
- let memberRoleId: string;
- let personObjectId: string;
- let emailsFieldId: string;
- let phonesFieldId: string;
-
- beforeAll(async () => {
- personJobTitle = generateRecordName(TEST_PERSON_1_ID);
-
- await makeRestApiRequest({
- method: 'post',
- path: '/companies',
- body: {
- id: TEST_COMPANY_1_ID,
- domainName: {
- primaryLinkUrl: TEST_PRIMARY_LINK_URL,
- },
- },
- });
-
- await makeRestApiRequest({
- method: 'post',
- path: '/people',
- body: {
- id: TEST_PERSON_1_ID,
- jobTitle: personJobTitle,
- emails: {
- primaryEmail: '[email protected]',
- },
- phones: {
- primaryPhoneNumber: '4155552671',
- primaryPhoneCountryCode: 'US',
- primaryPhoneCallingCode: '+1',
- },
- },
- });
-
- const getObjectMetadataOperation = {
- query: gql`
- query {
- objects(paging: { first: 1000 }) {
- edges {
- node {
- id
- nameSingular
- }
- }
- }
- }
- `,
- };
-
- const objectMetadataResponse = await makeMetadataApiRequest(
- getObjectMetadataOperation,
- );
- const objects = objectMetadataResponse.body.data.objects.edges;
-
- personObjectId = objects.find(
- (obj: any) => obj.node.nameSingular === 'person',
- )?.node.id;
-
- const getFieldMetadataOperation = {
- query: gql`
- query {
- fields(paging: { first: 1000 }) {
- edges {
- node {
- id
- name
- object {
- nameSingular
- }
- }
- }
- }
- }
- `,
- };
-
- const fieldMetadataResponse = await makeMetadataApiRequest(
- getFieldMetadataOperation,
- );
- const fields = fieldMetadataResponse.body.data.fields.edges;
-
- emailsFieldId = fields.find(
- (field: any) =>
- field.node.name === 'emails' &&
- field.node.object.nameSingular === 'person',
- ).node.id;
-
- phonesFieldId = fields.find(
- (field: any) =>
- field.node.name === 'phones' &&
- field.node.object.nameSingular === 'person',
- ).node.id;
-
- const getRolesOperation = {
- query: gql`
- query {
- getRoles {
- id
- label
- }
- }
- `,
- };
-
- const rolesResponse = await makeMetadataApiRequest(getRolesOperation);
-
- memberRoleId = rolesResponse.body.data.getRoles.find(
- (role: any) => role.label === 'Member',
- )?.id;
-
- await upsertFieldPermissions({
- roleId: memberRoleId,
- fieldPermissions: [
- {
- objectMetadataId: personObjectId,
- fieldMetadataId: emailsFieldId,
- canReadFieldValue: false,
- canUpdateFieldValue: null,
- },
- ],
- });
- });
-
- it('should hide fields when user has restricted read permissions - findOne', async () => {
- await makeRestApiRequest({
- method: 'get',
- path: `/people/${TEST_PERSON_1_ID}`,
- bearer: APPLE_JONY_MEMBER_ACCESS_TOKEN,
- })
- .expect(200)
- .expect((res) => {
- const person = res.body.data.person;
-
- expect(person).toBeDefined();
- expect(person.id).toBeDefined();
- expect(person.emails).toBeUndefined();
- });
- });
-
- describe('updateOne', () => {
- it('should hide fields in the response when user has restricted read permissions', async () => {
- await upsertFieldPermissions({
- roleId: memberRoleId,
- fieldPermissions: [
- {
- objectMetadataId: personObjectId,
- fieldMetadataId: phonesFieldId,
- canReadFieldValue: false,
- canUpdateFieldValue: null,
- },
- ],
- });
-
- await makeRestApiRequest({
- method: 'patch',
- path: `/people/${TEST_PERSON_1_ID}`,
- bearer: APPLE_JONY_MEMBER_ACCESS_TOKEN,
- body: {
- name: {
- firstName: 'John',
- },
- },
- })
- .expect(200)
- .expect((res) => {
- const updatedPerson = res.body.data.updatePerson;
-
- expect(updatedPerson.name.firstName).toBe('John');
- expect(updatedPerson.phones).toBeUndefined();
- });
- });
- it('should block update when user tries to update non-updatable field', async () => {
- await upsertFieldPermissions({
- roleId: memberRoleId,
- fieldPermissions: [
- {
- objectMetadataId: personObjectId,
- fieldMetadataId: phonesFieldId,
- canReadFieldValue: null,
- canUpdateFieldValue: false,
- },
- ],
- });
-
- await makeRestApiRequest({
- method: 'patch',
- path: `/people/${TEST_PERSON_1_ID}`,
- bearer: APPLE_JONY_MEMBER_ACCESS_TOKEN,
- body: {
- phones: {
- primaryPhoneNumber: '987654321',
- primaryPhoneCountryCode: 'FR',
- primaryPhoneCallingCode: '+33',
- },
- },
- })
- .expect(403)
- .expect((res) => {
- expect(res.body.messages[0]).toContain(
- 'Entity performing the request does not have permission',
- );
- });
- });
-
- it('should allow update when user has no restricted update permissions', async () => {
- await upsertFieldPermissions({
- roleId: memberRoleId,
- fieldPermissions: [
- {
- objectMetadataId: personObjectId,
- fieldMetadataId: phonesFieldId,
- canReadFieldValue: null,
- canUpdateFieldValue: null,
- },
- ],
- });
-
- await makeRestApiRequest({
- method: 'patch',
- path: `/people/${TEST_PERSON_1_ID}`,
- bearer: APPLE_JONY_MEMBER_ACCESS_TOKEN,
- body: {
- jobTitle: 'Updated City',
- },
- })
- .expect(200)
- .expect((res) => {
- const updatedPerson = res.body.data.updatePerson;
-
- expect(updatedPerson.jobTitle).toBe('Updated City');
- });
- });
- });
-
- describe('createOne', () => {
- it('should block create when restricted field is not in any RLS predicate', async () => {
- await upsertFieldPermissions({
- roleId: memberRoleId,
- fieldPermissions: [
- {
- objectMetadataId: personObjectId,
- fieldMetadataId: phonesFieldId,
- canReadFieldValue: null,
- canUpdateFieldValue: false,
- },
- ],
- });
-
- await makeRestApiRequest({
- method: 'post',
- path: `/people`,
- bearer: APPLE_JONY_MEMBER_ACCESS_TOKEN,
- body: {
- phones: {
- primaryPhoneNumber: '2025550123',
- primaryPhoneCountryCode: 'US',
- primaryPhoneCallingCode: '+1',
- },
- },
- })
- .expect(403)
- .expect((res) => {
- expect(res.body.messages[0]).toContain(
- 'Entity performing the request does not have permission',
- );
- });
- });
-
- it('should allow create when restricted field is referenced in an RLS predicate', async () => {
- await upsertFieldPermissions({
- roleId: memberRoleId,
- fieldPermissions: [
- {
- objectMetadataId: personObjectId,
- fieldMetadataId: phonesFieldId,
- canReadFieldValue: null,
- canUpdateFieldValue: false,
- },
- ],
- });
-
- await upsertRowLevelPermissionPredicates({
- input: {
- roleId: memberRoleId,
- objectMetadataId: personObjectId,
- predicates: [
- {
- fieldMetadataId: phonesFieldId,
- operand: RowLevelPermissionPredicateOperand.IS_NOT_EMPTY,
- },
- ],
- predicateGroups: [],
- },
- });
-
- await makeRestApiRequest({
- method: 'post',
- path: `/people`,
- bearer: APPLE_JONY_MEMBER_ACCESS_TOKEN,
- body: {
- phones: {
- primaryPhoneNumber: '2025550123',
- primaryPhoneCountryCode: 'US',
- primaryPhoneCallingCode: '+1',
- },
- },
- })
- .expect(201)
- .expect((res) => {
- const createdPerson = res.body.data.createPerson;
-
- expect(createdPerson).toBeDefined();
- expect(createdPerson.phones.primaryPhoneNumber).toBe('2025550123');
- });
-
- await upsertRowLevelPermissionPredicates({
- input: {
- roleId: memberRoleId,
- objectMetadataId: personObjectId,
- predicates: [],
- predicateGroups: [],
- },
- });
- });
-
- it('should allow create when user has no restricted update permissions', async () => {
- await upsertFieldPermissions({
- roleId: memberRoleId,
- fieldPermissions: [
- {
- objectMetadataId: personObjectId,
- fieldMetadataId: phonesFieldId,
- canReadFieldValue: null,
- canUpdateFieldValue: null,
- },
- {
- objectMetadataId: personObjectId,
- fieldMetadataId: emailsFieldId,
- canReadFieldValue: false,
- canUpdateFieldValue: null,
- },
- ],
- });
-
- await makeRestApiRequest({
- method: 'post',
- path: `/people`,
- bearer: APPLE_JONY_MEMBER_ACCESS_TOKEN,
- body: {
- jobTitle: 'New City',
- },
- })
- .expect(201)
- .expect((res) => {
- const createdPerson = res.body.data.createPerson;
-
- expect(createdPerson.jobTitle).toBe('New City');
- expect(createdPerson.emails).toBeUndefined();
- });
- });
- });
-
- describe('createMany', () => {
- it('should block createMany when restricted field is not in any RLS predicate', async () => {
- await upsertFieldPermissions({
- roleId: memberRoleId,
- fieldPermissions: [
- {
- objectMetadataId: personObjectId,
- fieldMetadataId: phonesFieldId,
- canReadFieldValue: null,
- canUpdateFieldValue: false,
- },
- ],
- });
-
- await makeRestApiRequest({
- method: 'post',
- path: `/batch/people`,
- bearer: APPLE_JONY_MEMBER_ACCESS_TOKEN,
- body: [
- {
- phones: {
- primaryPhoneNumber: '2025550123',
- primaryPhoneCountryCode: 'US',
- primaryPhoneCallingCode: '+1',
- },
- },
- ],
- })
- .expect(403)
- .expect((res) => {
- expect(res.body.messages[0]).toContain(
- 'Entity performing the request does not have permission',
- );
- });
- });
-
- it('should allow createMany when restricted field is referenced in an RLS predicate', async () => {
- await upsertFieldPermissions({
- roleId: memberRoleId,
- fieldPermissions: [
- {
- objectMetadataId: personObjectId,
- fieldMetadataId: phonesFieldId,
- canReadFieldValue: null,
- canUpdateFieldValue: false,
- },
- ],
- });
-
- await upsertRowLevelPermissionPredicates({
- input: {
- roleId: memberRoleId,
- objectMetadataId: personObjectId,
- predicates: [
- {
- fieldMetadataId: phonesFieldId,
- operand: RowLevelPermissionPredicateOperand.IS_NOT_EMPTY,
- },
- ],
- predicateGroups: [],
- },
- });
-
- await makeRestApiRequest({
- method: 'post',
- path: `/batch/people`,
- bearer: APPLE_JONY_MEMBER_ACCESS_TOKEN,
- body: [
- {
- phones: {
- primaryPhoneNumber: '2025550123',
- primaryPhoneCountryCode: 'US',
- primaryPhoneCallingCode: '+1',
- },
- },
- ],
- })
- .expect(201)
- .expect((res) => {
- const createdPeople = res.body.data.createPeople;
-
- expect(createdPeople).toHaveLength(1);
- expect(createdPeople[0].phones.primaryPhoneNumber).toBe('2025550123');
- });
-
- await upsertRowLevelPermissionPredicates({
- input: {
- roleId: memberRoleId,
- objectMetadataId: personObjectId,
- predicates: [],
- predicateGroups: [],
- },
- });
- });
-
- it('should allow createMany when user has no restricted update permissions', async () => {
- await upsertFieldPermissions({
- roleId: memberRoleId,
- fieldPermissions: [
- {
- objectMetadataId: personObjectId,
- fieldMetadataId: phonesFieldId,
- canReadFieldValue: null,
- canUpdateFieldValue: null,
- },
- {
- objectMetadataId: personObjectId,
- fieldMetadataId: emailsFieldId,
- canReadFieldValue: false,
- canUpdateFieldValue: null,
- },
- ],
- });
-
- await makeRestApiRequest({
- method: 'post',
- path: `/batch/people`,
- bearer: APPLE_JONY_MEMBER_ACCESS_TOKEN,
- body: [
- {
- jobTitle: 'Batch City 1',
- },
- {
- jobTitle: 'Batch City 2',
- },
- ],
- })
- .expect(201)
- .expect((res) => {
- const createdPeople = res.body.data.createPeople;
-
- expect(createdPeople).toHaveLength(2);
- expect(createdPeople[0].jobTitle).toBe('Batch City 1');
- expect(createdPeople[0].emails).toBeUndefined();
- expect(createdPeople[1].jobTitle).toBe('Batch City 2');
- expect(createdPeople[1].emails).toBeUndefined();
- });
- });
- });
-});
diff --git a/packages/twenty-server/test/integration/utils/find-field-metadata-id-by-name.util.ts b/packages/twenty-server/test/integration/utils/find-field-metadata-id-by-name.util.ts
new file mode 100644
index 00000000000..05265965b32
--- /dev/null
+++ b/packages/twenty-server/test/integration/utils/find-field-metadata-id-by-name.util.ts
@@ -0,0 +1,32 @@
+import { findManyFieldsMetadata } from 'test/integration/metadata/suites/field-metadata/utils/find-many-fields-metadata.util';
+import { isDefined } from 'twenty-shared/utils';
+
+export const findFieldMetadataIdByName = async ({
+ objectMetadataId,
+ fieldName,
+}: {
+ objectMetadataId: string;
+ fieldName: string;
+}): Promise<string> => {
+ const { fields } = await findManyFieldsMetadata({
+ input: {
+ filter: { objectMetadataId: { eq: objectMetadataId } },
+ paging: { first: 1000 },
+ },
+ gqlFields: `
+ id
+ name
+ `,
+ expectToFail: false,
+ });
+
+ const fieldMetadataId = fields?.find(
+ ({ node }: { node: { name: string } }) => node.name === fieldName,
+ )?.node.id;
+
+ if (!isDefined(fieldMetadataId)) {
+ throw new Error(`The ${fieldName} field metadata is missing from the seed`);
+ }
+
+ return fieldMetadataId;
+};
diff --git a/packages/twenty-server/test/integration/graphql/suites/application-role-intersection/utils/find-object-metadata-id-by-name.util.ts b/packages/twenty-server/test/integration/utils/find-object-metadata-id-by-name.util.ts
similarity index 100%
rename from packages/twenty-server/test/integration/graphql/suites/application-role-intersection/utils/find-object-metadata-id-by-name.util.ts
rename to packages/twenty-server/test/integration/utils/find-object-metadata-id-by-name.util.ts
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
index 5501b47c0ec..5b7d7d5db08 100644
--- 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
@@ -17,12 +17,16 @@ export type RecordApi = 'graphql' | 'rest';
type PersonData = {
id: string;
+ companyId?: string;
name?: { firstName: string };
jobTitle?: string;
+ intro?: string;
};
type PersonRequestInput = { api: RecordApi; token: string };
+type GraphqlSelectionInput = { gqlFields?: string };
+
const PERSON_SINGULAR_NAME = 'person';
const PERSON_PLURAL_NAME = 'people';
const PERSON_FIELDS = 'id jobTitle';
@@ -31,13 +35,18 @@ const restIdFilter = (ids: string[]) =>
`filter=id[in]:[${ids.map((id) => `"${id}"`).join(',')}]`;
export const personRequestsByApi = {
- findMany: ({ api, token, ids }: PersonRequestInput & { ids: string[] }) => {
+ findMany: ({
+ api,
+ token,
+ ids,
+ gqlFields = PERSON_FIELDS,
+ }: PersonRequestInput & GraphqlSelectionInput & { ids: string[] }) => {
if (api === 'graphql') {
return makeGraphqlApiRequest(
findManyOperationFactory({
objectMetadataSingularName: PERSON_SINGULAR_NAME,
objectMetadataPluralName: PERSON_PLURAL_NAME,
- gqlFields: PERSON_FIELDS,
+ gqlFields,
filter: { id: { in: ids } },
}),
token,
@@ -51,12 +60,17 @@ export const personRequestsByApi = {
});
},
- findOne: ({ api, token, id }: PersonRequestInput & { id: string }) => {
+ findOne: ({
+ api,
+ token,
+ id,
+ gqlFields = PERSON_FIELDS,
+ }: PersonRequestInput & GraphqlSelectionInput & { id: string }) => {
if (api === 'graphql') {
return makeGraphqlApiRequest(
findOneOperationFactory({
objectMetadataSingularName: PERSON_SINGULAR_NAME,
- gqlFields: PERSON_FIELDS,
+ gqlFields,
filter: { id: { eq: id } },
}),
token,
@@ -124,12 +138,14 @@ export const personRequestsByApi = {
token,
id,
data,
- }: PersonRequestInput & { id: string; data: Omit<PersonData, 'id'> }) => {
+ gqlFields = PERSON_FIELDS,
+ }: PersonRequestInput &
+ GraphqlSelectionInput & { id: string; data: Omit<PersonData, 'id'> }) => {
if (api === 'graphql') {
return makeGraphqlApiRequest(
updateOneOperationFactory({
objectMetadataSingularName: PERSON_SINGULAR_NAME,
- gqlFields: PERSON_FIELDS,
+ gqlFields,
recordId: id,
data,
}),
@@ -150,13 +166,18 @@ export const personRequestsByApi = {
token,
ids,
data,
- }: PersonRequestInput & { ids: string[]; data: Omit<PersonData, 'id'> }) => {
+ gqlFields = PERSON_FIELDS,
+ }: PersonRequestInput &
+ GraphqlSelectionInput & {
+ ids: string[];
+ data: Omit<PersonData, 'id'>;
+ }) => {
if (api === 'graphql') {
return makeGraphqlApiRequest(
updateManyOperationFactory({
objectMetadataSingularName: PERSON_SINGULAR_NAME,
objectMetadataPluralName: PERSON_PLURAL_NAME,
- gqlFields: PERSON_FIELDS,
+ gqlFields,
filter: { id: { in: ids } },
data,
}),