Skip to content

The open alternative to Salesforce, designed for AI.

Mask restricted calendar events and messages in nested relations and groupBy (#28679)

Charles Bochet8fd4b96d2c3d
diff --git a/packages/twenty-server/src/engine/api/common/common-query-runners/common-base-query-runner.service.ts b/packages/twenty-server/src/engine/api/common/common-query-runners/common-base-query-runner.service.ts
index 3f2a5342a5e..263c96becf5 100644
--- a/packages/twenty-server/src/engine/api/common/common-query-runners/common-base-query-runner.service.ts
+++ b/packages/twenty-server/src/engine/api/common/common-query-runners/common-base-query-runner.service.ts
@@ -15,6 +15,7 @@ import { OrderByArgProcessorService } from 'src/engine/api/common/common-args-pr
import { OrderByWithGroupByArgProcessorService } from 'src/engine/api/common/common-args-processors/order-by-with-group-by-arg-processor/order-by-with-group-by-arg-processor.service';
import { QueryRunnerArgsFactory } from 'src/engine/api/common/common-args-processors/query-runner-args.factory';
import { ProcessNestedRelationsHelper } from 'src/engine/api/common/common-nested-relations-processor/process-nested-relations.helper';
+import { CommonRecordVisibilityService } from 'src/engine/api/common/common-record-visibility/common-record-visibility.service';
import {
CommonQueryRunnerException,
CommonQueryRunnerExceptionCode,
@@ -101,6 +102,8 @@ export abstract class CommonBaseQueryRunnerService<
@Inject()
protected readonly commonResultGettersService: CommonResultGettersService;
@Inject()
+ protected readonly commonRecordVisibilityService: CommonRecordVisibilityService;
+ @Inject()
protected readonly usageLimitSpeedService: UsageLimitSpeedService;
@Inject()
protected readonly usageRecorderService: UsageRecorderService;
@@ -205,6 +208,12 @@ export abstract class CommonBaseQueryRunnerService<
authContext: WorkspaceAuthContext,
): Promise<Output>;
+ protected getResultRecords(results: Output): ObjectRecord[] {
+ return (
+ (Array.isArray(results) ? results : [results]) as ObjectRecord[]
+ ).filter(isDefined);
+ }
+
protected computeQueryComplexity(
selectedFieldsResult: CommonSelectedFieldsResult,
_args: CommonExtendedInput<Args>,
@@ -308,6 +317,14 @@ export abstract class CommonBaseQueryRunnerService<
authContext,
);
+ await this.commonRecordVisibilityService.applyVisibilityRestrictions({
+ records: this.getResultRecords(resultWithGetters),
+ flatObjectMetadata,
+ flatObjectMetadataMaps,
+ flatFieldMetadataMaps,
+ authContext,
+ });
+
const executePostQueryHooks = () =>
this.workspaceQueryHookService.executePostQueryHooks(
authContext,
diff --git a/packages/twenty-server/src/engine/api/common/common-query-runners/common-find-duplicates-query-runner.service.ts b/packages/twenty-server/src/engine/api/common/common-query-runners/common-find-duplicates-query-runner.service.ts
index 4c2d82d4098..7ba7cb8adad 100644
--- a/packages/twenty-server/src/engine/api/common/common-query-runners/common-find-duplicates-query-runner.service.ts
+++ b/packages/twenty-server/src/engine/api/common/common-query-runners/common-find-duplicates-query-runner.service.ts
@@ -227,6 +227,12 @@ export class CommonFindDuplicatesQueryRunnerService extends CommonBaseQueryRunne
};
}
+ protected getResultRecords(
+ results: CommonFindDuplicatesOutputItem[],
+ ): ObjectRecord[] {
+ return results.flatMap((duplicates) => duplicates.records);
+ }
+
async processQueryResult(
queryResult: CommonFindDuplicatesOutputItem[],
flatObjectMetadata: FlatObjectMetadata,
diff --git a/packages/twenty-server/src/engine/api/common/common-query-runners/common-find-many-query-runner.service.ts b/packages/twenty-server/src/engine/api/common/common-query-runners/common-find-many-query-runner.service.ts
index 1b6d844de6a..1d95637801b 100644
--- a/packages/twenty-server/src/engine/api/common/common-query-runners/common-find-many-query-runner.service.ts
+++ b/packages/twenty-server/src/engine/api/common/common-query-runners/common-find-many-query-runner.service.ts
@@ -286,6 +286,10 @@ export class CommonFindManyQueryRunnerService extends CommonBaseQueryRunnerServi
};
}
+ protected getResultRecords(results: CommonFindManyOutput): ObjectRecord[] {
+ return results.records;
+ }
+
async processQueryResult(
queryResult: CommonFindManyOutput,
flatObjectMetadata: FlatObjectMetadata,
diff --git a/packages/twenty-server/src/engine/api/common/common-query-runners/common-group-by-query-runner.service.ts b/packages/twenty-server/src/engine/api/common/common-query-runners/common-group-by-query-runner.service.ts
index bbf4fc10b96..487235673a0 100644
--- a/packages/twenty-server/src/engine/api/common/common-query-runners/common-group-by-query-runner.service.ts
+++ b/packages/twenty-server/src/engine/api/common/common-query-runners/common-group-by-query-runner.service.ts
@@ -2,6 +2,7 @@ import { Injectable } from '@nestjs/common';
import {
CompositeFieldSubFieldName,
+ type ObjectRecord,
PartialFieldMetadataItemOption,
RecordFilterGroupLogicalOperator,
type RestrictedFieldsPermissions,
@@ -177,6 +178,12 @@ export class CommonGroupByQueryRunnerService extends CommonBaseQueryRunnerServic
});
}
+ protected getResultRecords(
+ results: CommonGroupByOutputItem[],
+ ): ObjectRecord[] {
+ return results.flatMap((group) => group.records ?? []);
+ }
+
async processQueryResult(
queryResult: CommonGroupByOutputItem[],
_flatObjectMetadata: FlatObjectMetadata,
diff --git a/packages/twenty-server/src/engine/api/common/common-record-visibility/common-record-visibility.module.ts b/packages/twenty-server/src/engine/api/common/common-record-visibility/common-record-visibility.module.ts
new file mode 100644
index 00000000000..c0badb692a1
--- /dev/null
+++ b/packages/twenty-server/src/engine/api/common/common-record-visibility/common-record-visibility.module.ts
@@ -0,0 +1,9 @@
+import { Module } from '@nestjs/common';
+
+import { CommonRecordVisibilityService } from 'src/engine/api/common/common-record-visibility/common-record-visibility.service';
+
+@Module({
+ providers: [CommonRecordVisibilityService],
+ exports: [CommonRecordVisibilityService],
+})
+export class CommonRecordVisibilityModule {}
diff --git a/packages/twenty-server/src/engine/api/common/common-record-visibility/common-record-visibility.service.ts b/packages/twenty-server/src/engine/api/common/common-record-visibility/common-record-visibility.service.ts
new file mode 100644
index 00000000000..52a7db70b8e
--- /dev/null
+++ b/packages/twenty-server/src/engine/api/common/common-record-visibility/common-record-visibility.service.ts
@@ -0,0 +1,68 @@
+import { Injectable } from '@nestjs/common';
+
+import { type ObjectRecord } from 'twenty-shared/types';
+
+import { type RecordVisibilityRestrictionHandler } from 'src/engine/api/common/common-record-visibility/types/record-visibility-restriction-handler.type';
+import { collectRecordsByObjectNameSingular } from 'src/engine/api/common/common-record-visibility/utils/collect-records-by-object-name-singular.util';
+import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
+import { type FlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-maps.type';
+import { type OrmFlatFieldMetadata } from 'src/engine/metadata-modules/flat-field-metadata/types/orm-flat-field-metadata.type';
+import { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';
+
+// Runs on every record of a result, nested relations included, so restricted fields cannot leak through a relation
+// TODO(@charlesBochet): replace with row-level security once it can express channel visibility
+@Injectable()
+export class CommonRecordVisibilityService {
+ private readonly handlersByObjectNameSingular = new Map<
+ string,
+ RecordVisibilityRestrictionHandler
+ >();
+
+ public registerHandler({
+ objectNameSingular,
+ handler,
+ }: {
+ objectNameSingular: string;
+ handler: RecordVisibilityRestrictionHandler;
+ }) {
+ this.handlersByObjectNameSingular.set(objectNameSingular, handler);
+ }
+
+ public async applyVisibilityRestrictions({
+ records,
+ flatObjectMetadata,
+ flatObjectMetadataMaps,
+ flatFieldMetadataMaps,
+ authContext,
+ }: {
+ records: ObjectRecord[];
+ flatObjectMetadata: FlatObjectMetadata;
+ flatObjectMetadataMaps: FlatEntityMaps<FlatObjectMetadata>;
+ flatFieldMetadataMaps: FlatEntityMaps<OrmFlatFieldMetadata>;
+ authContext: WorkspaceAuthContext;
+ }): Promise<void> {
+ if (this.handlersByObjectNameSingular.size === 0 || records.length === 0) {
+ return;
+ }
+
+ const recordsByObjectNameSingular = collectRecordsByObjectNameSingular({
+ records,
+ flatObjectMetadata,
+ flatObjectMetadataMaps,
+ flatFieldMetadataMaps,
+ objectNameSingulars: new Set(this.handlersByObjectNameSingular.keys()),
+ });
+
+ for (const [
+ objectNameSingular,
+ collectedRecords,
+ ] of recordsByObjectNameSingular) {
+ await this.handlersByObjectNameSingular
+ .get(objectNameSingular)
+ ?.applyVisibilityRestrictions({
+ records: collectedRecords,
+ authContext,
+ });
+ }
+ }
+}
diff --git a/packages/twenty-server/src/engine/api/common/common-record-visibility/types/record-visibility-restriction-handler.type.ts b/packages/twenty-server/src/engine/api/common/common-record-visibility/types/record-visibility-restriction-handler.type.ts
new file mode 100644
index 00000000000..10873d01670
--- /dev/null
+++ b/packages/twenty-server/src/engine/api/common/common-record-visibility/types/record-visibility-restriction-handler.type.ts
@@ -0,0 +1,10 @@
+import { type ObjectRecord } from 'twenty-shared/types';
+
+import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
+
+export type RecordVisibilityRestrictionHandler = {
+ applyVisibilityRestrictions: (args: {
+ records: ObjectRecord[];
+ authContext: WorkspaceAuthContext;
+ }) => Promise<void>;
+};
diff --git a/packages/twenty-server/src/engine/api/common/common-record-visibility/utils/__tests__/collect-records-by-object-name-singular.util.spec.ts b/packages/twenty-server/src/engine/api/common/common-record-visibility/utils/__tests__/collect-records-by-object-name-singular.util.spec.ts
new file mode 100644
index 00000000000..964869417e9
--- /dev/null
+++ b/packages/twenty-server/src/engine/api/common/common-record-visibility/utils/__tests__/collect-records-by-object-name-singular.util.spec.ts
@@ -0,0 +1,166 @@
+import {
+ FieldMetadataType,
+ type ObjectRecord,
+ RelationType,
+} from 'twenty-shared/types';
+
+import { collectRecordsByObjectNameSingular } from 'src/engine/api/common/common-record-visibility/utils/collect-records-by-object-name-singular.util';
+import { createEmptyFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/constant/create-empty-flat-entity-maps.constant';
+import { type FlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-maps.type';
+import { addFlatEntityToFlatEntityMapsOrThrow } from 'src/engine/metadata-modules/flat-entity/utils/add-flat-entity-to-flat-entity-maps-or-throw.util';
+import { getFlatFieldMetadataMock } from 'src/engine/metadata-modules/flat-field-metadata/__mocks__/get-flat-field-metadata.mock';
+import { type FlatFieldMetadata } from 'src/engine/metadata-modules/flat-field-metadata/types/flat-field-metadata.type';
+import { getFlatObjectMetadataMock } from 'src/engine/metadata-modules/flat-object-metadata/__mocks__/get-flat-object-metadata.mock';
+import { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';
+
+const buildFlatEntityMaps = <
+ TFlatEntity extends FlatFieldMetadata | FlatObjectMetadata,
+>(
+ flatEntities: TFlatEntity[],
+): FlatEntityMaps<TFlatEntity> =>
+ flatEntities.reduce(
+ (flatEntityMaps, flatEntity) =>
+ addFlatEntityToFlatEntityMapsOrThrow({ flatEntity, flatEntityMaps }),
+ createEmptyFlatEntityMaps() as FlatEntityMaps<TFlatEntity>,
+ );
+
+const participantsField = getFlatFieldMetadataMock({
+ universalIdentifier: 'person-calendar-event-participants',
+ objectMetadataId: 'person',
+ type: FieldMetadataType.RELATION,
+ name: 'calendarEventParticipants',
+ settings: { relationType: RelationType.ONE_TO_MANY },
+ relationTargetObjectMetadataId: 'calendarEventParticipant',
+});
+
+const calendarEventField = getFlatFieldMetadataMock({
+ universalIdentifier: 'calendar-event-participant-calendar-event',
+ objectMetadataId: 'calendarEventParticipant',
+ type: FieldMetadataType.RELATION,
+ name: 'calendarEvent',
+ settings: { relationType: RelationType.MANY_TO_ONE },
+ relationTargetObjectMetadataId: 'calendarEvent',
+});
+
+const person = getFlatObjectMetadataMock({
+ id: 'person',
+ universalIdentifier: 'person',
+ nameSingular: 'person',
+ fieldIds: [participantsField.id],
+});
+
+const calendarEventParticipant = getFlatObjectMetadataMock({
+ id: 'calendarEventParticipant',
+ universalIdentifier: 'calendarEventParticipant',
+ nameSingular: 'calendarEventParticipant',
+ fieldIds: [calendarEventField.id],
+});
+
+const calendarEvent = getFlatObjectMetadataMock({
+ id: 'calendarEvent',
+ universalIdentifier: 'calendarEvent',
+ nameSingular: 'calendarEvent',
+ fieldIds: [],
+});
+
+const collect = ({
+ records,
+ flatObjectMetadata,
+ objectNameSingulars,
+}: {
+ records: ObjectRecord[];
+ flatObjectMetadata: FlatObjectMetadata;
+ objectNameSingulars: string[];
+}) =>
+ collectRecordsByObjectNameSingular({
+ records,
+ flatObjectMetadata,
+ flatObjectMetadataMaps: buildFlatEntityMaps([
+ person,
+ calendarEventParticipant,
+ calendarEvent,
+ ]),
+ flatFieldMetadataMaps: buildFlatEntityMaps([
+ participantsField,
+ calendarEventField,
+ ]),
+ objectNameSingulars: new Set(objectNameSingulars),
+ });
+
+describe('collectRecordsByObjectNameSingular', () => {
+ it('should collect root records of a requested object', () => {
+ const event: ObjectRecord = { id: 'event-1', title: 'Demo' };
+
+ expect(
+ collect({
+ records: [event],
+ flatObjectMetadata: calendarEvent,
+ objectNameSingulars: ['calendarEvent'],
+ }),
+ ).toEqual(new Map([['calendarEvent', [event]]]));
+ });
+
+ it('should collect records nested through one-to-many and many-to-one relations', () => {
+ const firstEvent = { id: 'event-1', title: 'Demo' };
+ const secondEvent = { id: 'event-2', title: 'Sync' };
+
+ const records: ObjectRecord[] = [
+ {
+ id: 'person-1',
+ calendarEventParticipants: [
+ { id: 'participant-1', calendarEvent: firstEvent },
+ { id: 'participant-2', calendarEvent: secondEvent },
+ { id: 'participant-3', calendarEvent: null },
+ ],
+ },
+ ];
+
+ const collectedRecords = collect({
+ records,
+ flatObjectMetadata: person,
+ objectNameSingulars: ['calendarEvent'],
+ });
+
+ expect(collectedRecords.get('calendarEvent')).toEqual([
+ firstEvent,
+ secondEvent,
+ ]);
+ expect(collectedRecords.has('person')).toBe(false);
+ });
+
+ it('should collect a record shared by several parents once', () => {
+ const sharedEvent = { id: 'event-1', title: 'Demo' };
+
+ const records: ObjectRecord[] = [
+ {
+ id: 'person-1',
+ calendarEventParticipants: [
+ { id: 'participant-1', calendarEvent: sharedEvent },
+ { id: 'participant-2', calendarEvent: sharedEvent },
+ ],
+ },
+ ];
+
+ expect(
+ collect({
+ records,
+ flatObjectMetadata: person,
+ objectNameSingulars: ['calendarEvent'],
+ }).get('calendarEvent'),
+ ).toEqual([sharedEvent]);
+ });
+
+ it('should collect nothing when no requested object is in the result', () => {
+ const records: ObjectRecord[] = [
+ { id: 'person-1', calendarEventParticipants: [] },
+ ];
+
+ expect(
+ collect({
+ records,
+ flatObjectMetadata: person,
+ objectNameSingulars: ['message'],
+ }).size,
+ ).toBe(0);
+ });
+});
diff --git a/packages/twenty-server/src/engine/api/common/common-record-visibility/utils/collect-records-by-object-name-singular.util.ts b/packages/twenty-server/src/engine/api/common/common-record-visibility/utils/collect-records-by-object-name-singular.util.ts
new file mode 100644
index 00000000000..31eb00e06ed
--- /dev/null
+++ b/packages/twenty-server/src/engine/api/common/common-record-visibility/utils/collect-records-by-object-name-singular.util.ts
@@ -0,0 +1,112 @@
+import { type ObjectRecord } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+
+import { getFlatFieldsFromFlatObjectMetadata } from 'src/engine/api/graphql/workspace-schema-builder/utils/get-flat-fields-for-flat-object-metadata.util';
+import { type FlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-maps.type';
+import { findFlatEntityByIdInFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-id-in-flat-entity-maps.util';
+import { type OrmFlatFieldMetadata } from 'src/engine/metadata-modules/flat-field-metadata/types/orm-flat-field-metadata.type';
+import { isMorphOrRelationFlatFieldMetadata } from 'src/engine/metadata-modules/flat-field-metadata/utils/is-morph-or-relation-flat-field-metadata.util';
+import { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';
+
+export const collectRecordsByObjectNameSingular = ({
+ records,
+ flatObjectMetadata,
+ flatObjectMetadataMaps,
+ flatFieldMetadataMaps,
+ objectNameSingulars,
+}: {
+ records: ObjectRecord[];
+ flatObjectMetadata: FlatObjectMetadata;
+ flatObjectMetadataMaps: FlatEntityMaps<FlatObjectMetadata>;
+ flatFieldMetadataMaps: FlatEntityMaps<OrmFlatFieldMetadata>;
+ objectNameSingulars: ReadonlySet<string>;
+}): Map<string, ObjectRecord[]> => {
+ const collectedRecordsByObjectNameSingular = new Map<
+ string,
+ Set<ObjectRecord>
+ >();
+ const relationFieldsByObjectMetadataId = new Map<
+ string,
+ OrmFlatFieldMetadata[]
+ >();
+
+ const getRelationFields = (objectMetadata: FlatObjectMetadata) => {
+ const cachedRelationFields = relationFieldsByObjectMetadataId.get(
+ objectMetadata.id,
+ );
+
+ if (isDefined(cachedRelationFields)) {
+ return cachedRelationFields;
+ }
+
+ const relationFields = getFlatFieldsFromFlatObjectMetadata(
+ objectMetadata,
+ flatFieldMetadataMaps,
+ ).filter(isMorphOrRelationFlatFieldMetadata);
+
+ relationFieldsByObjectMetadataId.set(objectMetadata.id, relationFields);
+
+ return relationFields;
+ };
+
+ const visit = ({
+ record,
+ objectMetadata,
+ }: {
+ record: ObjectRecord;
+ objectMetadata: FlatObjectMetadata;
+ }) => {
+ if (objectNameSingulars.has(objectMetadata.nameSingular)) {
+ const collectedRecords =
+ collectedRecordsByObjectNameSingular.get(objectMetadata.nameSingular) ??
+ new Set<ObjectRecord>();
+
+ collectedRecords.add(record);
+ collectedRecordsByObjectNameSingular.set(
+ objectMetadata.nameSingular,
+ collectedRecords,
+ );
+ }
+
+ for (const relationField of getRelationFields(objectMetadata)) {
+ const relationValue = record[relationField.name];
+
+ if (
+ !isDefined(relationValue) ||
+ !isDefined(relationField.relationTargetObjectMetadataId)
+ ) {
+ continue;
+ }
+
+ const targetObjectMetadata = findFlatEntityByIdInFlatEntityMaps({
+ flatEntityId: relationField.relationTargetObjectMetadataId,
+ flatEntityMaps: flatObjectMetadataMaps,
+ });
+
+ if (!isDefined(targetObjectMetadata)) {
+ continue;
+ }
+
+ const relationRecords: ObjectRecord[] = Array.isArray(relationValue)
+ ? relationValue.filter(isDefined)
+ : [relationValue];
+
+ for (const relationRecord of relationRecords) {
+ visit({ record: relationRecord, objectMetadata: targetObjectMetadata });
+ }
+ }
+ };
+
+ for (const record of records) {
+ visit({ record, objectMetadata: flatObjectMetadata });
+ }
+
+ return new Map(
+ [...collectedRecordsByObjectNameSingular].map(
+ ([objectNameSingular, collectedRecords]) => [
+ objectNameSingular,
+ [...collectedRecords],
+ ],
+ ),
+ );
+};
diff --git a/packages/twenty-server/src/engine/api/common/core-common-api.module.ts b/packages/twenty-server/src/engine/api/common/core-common-api.module.ts
index f6e423d1046..18f689944a6 100644
--- a/packages/twenty-server/src/engine/api/common/core-common-api.module.ts
+++ b/packages/twenty-server/src/engine/api/common/core-common-api.module.ts
@@ -2,6 +2,7 @@ import { Module } from '@nestjs/common';
import { CommonArgsProcessors } from 'src/engine/api/common/common-args-processors/common-args-processors';
import { GroupByArgProcessorService } from 'src/engine/api/common/common-args-processors/group-by-arg-processor/group-by-arg-processor.service';
+import { CommonRecordVisibilityModule } from 'src/engine/api/common/common-record-visibility/common-record-visibility.module';
import { ProcessNestedRelationsHelper } from 'src/engine/api/common/common-nested-relations-processor/process-nested-relations.helper';
import { CommonQueryRunners } from 'src/engine/api/common/common-query-runners/common-query-runners';
import { CommonResultGettersService } from 'src/engine/api/common/common-result-getters/common-result-getters.service';
@@ -23,6 +24,7 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache
@Module({
imports: [
WorkspaceQueryHookModule,
+ CommonRecordVisibilityModule,
EventLogEmitterModule,
FileModule,
ViewModule,
diff --git a/packages/twenty-server/src/modules/calendar/common/query-hooks/calendar-event/calendar-event-find-many.post-query.hook.ts b/packages/twenty-server/src/modules/calendar/common/query-hooks/calendar-event/calendar-event-find-many.post-query.hook.ts
deleted file mode 100644
index 47ecd1ebdf9..00000000000
--- a/packages/twenty-server/src/modules/calendar/common/query-hooks/calendar-event/calendar-event-find-many.post-query.hook.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-import { type WorkspacePostQueryHookInstance } from 'src/engine/api/graphql/workspace-query-runner/workspace-query-hook/interfaces/workspace-query-hook.interface';
-
-import { WorkspaceQueryHook } from 'src/engine/api/graphql/workspace-query-runner/workspace-query-hook/decorators/workspace-query-hook.decorator';
-import { WorkspaceQueryHookType } from 'src/engine/api/graphql/workspace-query-runner/workspace-query-hook/types/workspace-query-hook.type';
-import { isUserAuthContext } from 'src/engine/core-modules/auth/guards/is-user-auth-context.guard';
-import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
-import { ForbiddenError } from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
-import { ApplyCalendarEventsVisibilityRestrictionsService } from 'src/modules/calendar/common/query-hooks/calendar-event/services/apply-calendar-events-visibility-restrictions.service';
-import { type CalendarEventWorkspaceEntity } from 'src/modules/calendar/common/standard-objects/calendar-event.workspace-entity';
-import { isApiKeyAuthContext } from 'src/engine/core-modules/auth/guards/is-api-key-auth-context.guard';
-import { isApplicationAuthContext } from 'src/engine/core-modules/auth/guards/is-application-auth-context.guard';
-
-@WorkspaceQueryHook({
- key: `calendarEvent.findMany`,
- type: WorkspaceQueryHookType.POST_HOOK,
-})
-export class CalendarEventFindManyPostQueryHook implements WorkspacePostQueryHookInstance {
- constructor(
- private readonly applyCalendarEventsVisibilityRestrictionsService: ApplyCalendarEventsVisibilityRestrictionsService,
- ) {}
-
- async execute(
- authContext: WorkspaceAuthContext,
- _objectName: string,
- payload: CalendarEventWorkspaceEntity[],
- ): Promise<void> {
- const isUserContext = isUserAuthContext(authContext);
- const userId = isUserContext ? authContext.user.id : undefined;
-
- // TODO: this check should be removed
- if (
- !isUserAuthContext(authContext) &&
- !isApiKeyAuthContext(authContext) &&
- !isApplicationAuthContext(authContext)
- ) {
- throw new ForbiddenError(
- 'Authentication error, auth context should be user, apiKey or application',
- );
- }
-
- const workspace = authContext.workspace;
-
- if (!workspace) {
- throw new ForbiddenError('Workspace is required');
- }
-
- await this.applyCalendarEventsVisibilityRestrictionsService.applyCalendarEventsVisibilityRestrictions(
- payload,
- workspace.id,
- userId,
- );
- }
-}
diff --git a/packages/twenty-server/src/modules/calendar/common/query-hooks/calendar-event/calendar-event-find-one.post-query.hook.ts b/packages/twenty-server/src/modules/calendar/common/query-hooks/calendar-event/calendar-event-find-one.post-query.hook.ts
deleted file mode 100644
index c5d1aaf46c2..00000000000
--- a/packages/twenty-server/src/modules/calendar/common/query-hooks/calendar-event/calendar-event-find-one.post-query.hook.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-import { type WorkspacePostQueryHookInstance } from 'src/engine/api/graphql/workspace-query-runner/workspace-query-hook/interfaces/workspace-query-hook.interface';
-
-import { WorkspaceQueryHook } from 'src/engine/api/graphql/workspace-query-runner/workspace-query-hook/decorators/workspace-query-hook.decorator';
-import { WorkspaceQueryHookType } from 'src/engine/api/graphql/workspace-query-runner/workspace-query-hook/types/workspace-query-hook.type';
-import { isUserAuthContext } from 'src/engine/core-modules/auth/guards/is-user-auth-context.guard';
-import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
-import { ForbiddenError } from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
-import { ApplyCalendarEventsVisibilityRestrictionsService } from 'src/modules/calendar/common/query-hooks/calendar-event/services/apply-calendar-events-visibility-restrictions.service';
-import { type CalendarEventWorkspaceEntity } from 'src/modules/calendar/common/standard-objects/calendar-event.workspace-entity';
-import { isApiKeyAuthContext } from 'src/engine/core-modules/auth/guards/is-api-key-auth-context.guard';
-import { isApplicationAuthContext } from 'src/engine/core-modules/auth/guards/is-application-auth-context.guard';
-
-@WorkspaceQueryHook({
- key: `calendarEvent.findOne`,
- type: WorkspaceQueryHookType.POST_HOOK,
-})
-export class CalendarEventFindOnePostQueryHook implements WorkspacePostQueryHookInstance {
- constructor(
- private readonly applyCalendarEventsVisibilityRestrictionsService: ApplyCalendarEventsVisibilityRestrictionsService,
- ) {}
-
- async execute(
- authContext: WorkspaceAuthContext,
- _objectName: string,
- payload: CalendarEventWorkspaceEntity[],
- ): Promise<void> {
- const isUserContext = isUserAuthContext(authContext);
- const userId = isUserContext ? authContext.user.id : undefined;
-
- // TODO: this check should be removed
- if (
- !isUserAuthContext(authContext) &&
- !isApiKeyAuthContext(authContext) &&
- !isApplicationAuthContext(authContext)
- ) {
- throw new ForbiddenError(
- 'Authentication error, auth context should be user, apiKey or application',
- );
- }
-
- const workspace = authContext.workspace;
-
- if (!workspace) {
- throw new ForbiddenError('Workspace is required');
- }
-
- await this.applyCalendarEventsVisibilityRestrictionsService.applyCalendarEventsVisibilityRestrictions(
- payload,
- workspace.id,
- userId,
- );
- }
-}
diff --git a/packages/twenty-server/src/modules/calendar/common/query-hooks/calendar-event/services/apply-calendar-events-visibility-restrictions.service.ts b/packages/twenty-server/src/modules/calendar/common/query-hooks/calendar-event/services/apply-calendar-events-visibility-restrictions.service.ts
index c4bc3bcefd2..2551321f2ca 100644
--- a/packages/twenty-server/src/modules/calendar/common/query-hooks/calendar-event/services/apply-calendar-events-visibility-restrictions.service.ts
+++ b/packages/twenty-server/src/modules/calendar/common/query-hooks/calendar-event/services/apply-calendar-events-visibility-restrictions.service.ts
@@ -1,134 +1,156 @@
-import { Injectable } from '@nestjs/common';
+import { Injectable, type OnModuleInit } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
-import groupBy from 'lodash.groupby';
import { FIELD_RESTRICTED_ADDITIONAL_PERMISSIONS_REQUIRED } from 'twenty-shared/constants';
-import { CalendarChannelVisibility } from 'twenty-shared/types';
+import {
+ CalendarChannelVisibility,
+ type ObjectRecord,
+} from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
import { In, Repository } from 'typeorm';
-import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
+import { CommonRecordVisibilityService } from 'src/engine/api/common/common-record-visibility/common-record-visibility.service';
+import { type RecordVisibilityRestrictionHandler } from 'src/engine/api/common/common-record-visibility/types/record-visibility-restriction-handler.type';
+import { isUserAuthContext } from 'src/engine/core-modules/auth/guards/is-user-auth-context.guard';
+import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
import { CalendarChannelEntity } from 'src/engine/metadata-modules/calendar-channel/entities/calendar-channel.entity';
-import { ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
import { type CalendarChannelEventAssociationWorkspaceEntity } from 'src/modules/calendar/common/standard-objects/calendar-channel-event-association.workspace-entity';
-import { type CalendarEventWorkspaceEntity } from 'src/modules/calendar/common/standard-objects/calendar-event.workspace-entity';
+
+const RESTRICTED_CALENDAR_EVENT_FIELD_NAMES = ['title', 'description'];
@Injectable()
-export class ApplyCalendarEventsVisibilityRestrictionsService {
+export class ApplyCalendarEventsVisibilityRestrictionsService
+ implements RecordVisibilityRestrictionHandler, OnModuleInit
+{
constructor(
private readonly workspaceOrmManager: WorkspaceOrmManager,
- @InjectRepository(ConnectedAccountEntity)
- private readonly connectedAccountRepository: Repository<ConnectedAccountEntity>,
- @InjectRepository(UserWorkspaceEntity)
- private readonly userWorkspaceRepository: Repository<UserWorkspaceEntity>,
+ private readonly commonRecordVisibilityService: CommonRecordVisibilityService,
@InjectRepository(CalendarChannelEntity)
private readonly calendarChannelRepository: Repository<CalendarChannelEntity>,
) {}
- public async applyCalendarEventsVisibilityRestrictions(
- calendarEvents: CalendarEventWorkspaceEntity[],
- workspaceId: string,
- userId?: string,
- ) {
- const authContext = buildSystemAuthContext(workspaceId);
-
- return this.workspaceOrmManager.executeInWorkspaceContext(
- async () => {
- const calendarChannelEventAssociationRepository =
- this.workspaceOrmManager.getRepository<CalendarChannelEventAssociationWorkspaceEntity>(
- 'calendarChannelEventAssociation',
- { shouldBypassPermissionChecks: true },
- );
-
- const calendarChannelCalendarEventsAssociations =
- await calendarChannelEventAssociationRepository.find({
- where: {
- calendarEventId: In(calendarEvents.map((event) => event.id)),
- },
- });
-
- const calendarChannelIds = [
- ...new Set(
- calendarChannelCalendarEventsAssociations.map(
- (association) => association.calendarChannelId,
- ),
- ),
- ];
-
- const calendarChannelsFromCore =
- calendarChannelIds.length > 0
- ? await this.calendarChannelRepository.find({
- where: {
- id: In(calendarChannelIds),
- workspaceId,
- },
- })
- : [];
-
- const calendarChannelMap = new Map(
- calendarChannelsFromCore.map((channel) => [channel.id, channel]),
- );
-
- for (const calendarEvent of calendarEvents) {
- const associations = calendarChannelCalendarEventsAssociations.filter(
- (association) => association.calendarEventId === calendarEvent.id,
- );
-
- const calendarChannels = associations
- .map((association) =>
- calendarChannelMap.get(association.calendarChannelId),
- )
- .filter(isDefined);
-
- const calendarChannelsGroupByVisibility = groupBy(
- calendarChannels,
- (channel) => channel.visibility,
- );
-
- if (
- calendarChannelsGroupByVisibility[
- CalendarChannelVisibility.SHARE_EVERYTHING
- ]
- ) {
- continue;
- }
-
- if (isDefined(userId)) {
- const userWorkspace = await this.userWorkspaceRepository.findOne({
- where: { userId, workspaceId },
- select: ['id'],
- });
-
- if (userWorkspace) {
- const connectedAccounts =
- await this.connectedAccountRepository.find({
- where: {
- calendarChannels: {
- id: In(calendarChannels.map((channel) => channel.id)),
- },
- userWorkspaceId: userWorkspace.id,
- workspaceId,
- },
- });
-
- if (connectedAccounts.length > 0) {
- continue;
- }
- }
- }
-
- calendarEvent.title =
- FIELD_RESTRICTED_ADDITIONAL_PERMISSIONS_REQUIRED;
- calendarEvent.description =
+ onModuleInit() {
+ this.commonRecordVisibilityService.registerHandler({
+ objectNameSingular: 'calendarEvent',
+ handler: this,
+ });
+ }
+
+ public async applyVisibilityRestrictions({
+ records,
+ authContext,
+ }: {
+ records: ObjectRecord[];
+ authContext: WorkspaceAuthContext;
+ }): Promise<void> {
+ const restrictableCalendarEvents = records.filter((calendarEvent) =>
+ RESTRICTED_CALENDAR_EVENT_FIELD_NAMES.some(
+ (fieldName) => fieldName in calendarEvent,
+ ),
+ );
+
+ if (restrictableCalendarEvents.length === 0) {
+ return;
+ }
+
+ const visibleCalendarEventIds = await this.findVisibleCalendarEventIds({
+ calendarEvents: restrictableCalendarEvents,
+ authContext,
+ });
+
+ for (const calendarEvent of restrictableCalendarEvents) {
+ if (visibleCalendarEventIds.has(calendarEvent.id)) {
+ continue;
+ }
+
+ for (const fieldName of RESTRICTED_CALENDAR_EVENT_FIELD_NAMES) {
+ if (fieldName in calendarEvent) {
+ calendarEvent[fieldName] =
FIELD_RESTRICTED_ADDITIONAL_PERMISSIONS_REQUIRED;
}
+ }
+ }
+ }
- return calendarEvents;
+ private async findVisibleCalendarEventIds({
+ calendarEvents,
+ authContext,
+ }: {
+ calendarEvents: ObjectRecord[];
+ authContext: WorkspaceAuthContext;
+ }): Promise<Set<string>> {
+ const workspaceId = authContext.workspace.id;
+
+ const calendarEventIds = [
+ ...new Set(calendarEvents.map((calendarEvent) => calendarEvent.id)),
+ ].filter(isDefined);
+
+ if (calendarEventIds.length === 0) {
+ return new Set();
+ }
+
+ const calendarChannelEventAssociations =
+ await this.workspaceOrmManager.executeInWorkspaceContext(
+ async () =>
+ this.workspaceOrmManager
+ .getRepository<CalendarChannelEventAssociationWorkspaceEntity>(
+ 'calendarChannelEventAssociation',
+ { shouldBypassPermissionChecks: true },
+ )
+ .find({
+ where: { calendarEventId: In(calendarEventIds) },
+ }),
+ buildSystemAuthContext(workspaceId),
+ { lite: true },
+ );
+
+ const calendarChannelIds = [
+ ...new Set(
+ calendarChannelEventAssociations.map(
+ (association) => association.calendarChannelId,
+ ),
+ ),
+ ];
+
+ if (calendarChannelIds.length === 0) {
+ return new Set();
+ }
+
+ const calendarChannels = await this.calendarChannelRepository.find({
+ where: { id: In(calendarChannelIds), workspaceId },
+ select: {
+ id: true,
+ visibility: true,
+ connectedAccount: { id: true, userWorkspaceId: true },
},
- authContext,
- { lite: true },
+ relations: { connectedAccount: true },
+ });
+
+ const viewerUserWorkspaceId = isUserAuthContext(authContext)
+ ? authContext.userWorkspaceId
+ : undefined;
+
+ const visibleCalendarChannelIds = new Set(
+ calendarChannels
+ .filter(
+ (calendarChannel) =>
+ calendarChannel.visibility ===
+ CalendarChannelVisibility.SHARE_EVERYTHING ||
+ (isDefined(viewerUserWorkspaceId) &&
+ calendarChannel.connectedAccount.userWorkspaceId ===
+ viewerUserWorkspaceId),
+ )
+ .map((calendarChannel) => calendarChannel.id),
+ );
+
+ return new Set(
+ calendarChannelEventAssociations
+ .filter((association) =>
+ visibleCalendarChannelIds.has(association.calendarChannelId),
+ )
+ .map((association) => association.calendarEventId),
);
}
}
diff --git a/packages/twenty-server/src/modules/calendar/common/query-hooks/calendar-query-hook.module.ts b/packages/twenty-server/src/modules/calendar/common/query-hooks/calendar-query-hook.module.ts
index 493d2988a4b..2b9b13c97de 100644
--- a/packages/twenty-server/src/modules/calendar/common/query-hooks/calendar-query-hook.module.ts
+++ b/packages/twenty-server/src/modules/calendar/common/query-hooks/calendar-query-hook.module.ts
@@ -1,27 +1,19 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
-import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
+import { CommonRecordVisibilityModule } from 'src/engine/api/common/common-record-visibility/common-record-visibility.module';
import { CalendarChannelEntity } from 'src/engine/metadata-modules/calendar-channel/entities/calendar-channel.entity';
-import { ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
-import { CalendarEventFindManyPostQueryHook } from 'src/modules/calendar/common/query-hooks/calendar-event/calendar-event-find-many.post-query.hook';
-import { CalendarEventFindOnePostQueryHook } from 'src/modules/calendar/common/query-hooks/calendar-event/calendar-event-find-one.post-query.hook';
import { ApplyCalendarEventsVisibilityRestrictionsService } from 'src/modules/calendar/common/query-hooks/calendar-event/services/apply-calendar-events-visibility-restrictions.service';
import { CalendarEventTargetCreateManyPreQueryHook } from 'src/modules/calendar/common/query-hooks/calendar-event-target/calendar-event-target-create-many.pre-query-hook';
import { CalendarEventTargetCreateOnePreQueryHook } from 'src/modules/calendar/common/query-hooks/calendar-event-target/calendar-event-target-create-one.pre-query-hook';
@Module({
imports: [
- TypeOrmModule.forFeature([
- CalendarChannelEntity,
- ConnectedAccountEntity,
- UserWorkspaceEntity,
- ]),
+ CommonRecordVisibilityModule,
+ TypeOrmModule.forFeature([CalendarChannelEntity]),
],
providers: [
ApplyCalendarEventsVisibilityRestrictionsService,
- CalendarEventFindOnePostQueryHook,
- CalendarEventFindManyPostQueryHook,
CalendarEventTargetCreateOnePreQueryHook,
CalendarEventTargetCreateManyPreQueryHook,
],
diff --git a/packages/twenty-server/src/modules/messaging/common/query-hooks/message/apply-messages-visibility-restrictions.service.ts b/packages/twenty-server/src/modules/messaging/common/query-hooks/message/apply-messages-visibility-restrictions.service.ts
index 7f0c7e9e846..075a0d7bc62 100644
--- a/packages/twenty-server/src/modules/messaging/common/query-hooks/message/apply-messages-visibility-restrictions.service.ts
+++ b/packages/twenty-server/src/modules/messaging/common/query-hooks/message/apply-messages-visibility-restrictions.service.ts
@@ -1,183 +1,197 @@
-import { Injectable } from '@nestjs/common';
+import { Injectable, type OnModuleInit } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
-import groupBy from 'lodash.groupby';
import { FIELD_RESTRICTED_ADDITIONAL_PERMISSIONS_REQUIRED } from 'twenty-shared/constants';
-import { MessageChannelVisibility } from 'twenty-shared/types';
+import {
+ MessageChannelVisibility,
+ type ObjectRecord,
+} from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
import { In, Repository } from 'typeorm';
-import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
-import { ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
+import { CommonRecordVisibilityService } from 'src/engine/api/common/common-record-visibility/common-record-visibility.service';
+import { type RecordVisibilityRestrictionHandler } from 'src/engine/api/common/common-record-visibility/types/record-visibility-restriction-handler.type';
+import { isApplicationAuthContext } from 'src/engine/core-modules/auth/guards/is-application-auth-context.guard';
+import { isUserAuthContext } from 'src/engine/core-modules/auth/guards/is-user-auth-context.guard';
+import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
import { MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';
import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
import { type MessageChannelMessageAssociationWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message-channel-message-association.workspace-entity';
-import { type MessageWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message.workspace-entity';
-import { WorkspaceMemberWorkspaceEntity } from 'src/modules/workspace-member/standard-objects/workspace-member.workspace-entity';
+
+const RESTRICTED_MESSAGE_FIELD_NAMES = ['subject', 'text'];
@Injectable()
-export class ApplyMessagesVisibilityRestrictionsService {
+export class ApplyMessagesVisibilityRestrictionsService
+ implements RecordVisibilityRestrictionHandler, OnModuleInit
+{
constructor(
private readonly workspaceOrmManager: WorkspaceOrmManager,
- @InjectRepository(ConnectedAccountEntity)
- private readonly connectedAccountRepository: Repository<ConnectedAccountEntity>,
- @InjectRepository(UserWorkspaceEntity)
- private readonly userWorkspaceRepository: Repository<UserWorkspaceEntity>,
+ private readonly commonRecordVisibilityService: CommonRecordVisibilityService,
@InjectRepository(MessageChannelEntity)
private readonly messageChannelRepository: Repository<MessageChannelEntity>,
) {}
- public async applyMessagesVisibilityRestrictions(
- messages: MessageWorkspaceEntity[],
- workspaceId: string,
- userId?: string,
- applicationId?: string,
- ) {
- const authContext = buildSystemAuthContext(workspaceId);
-
- return this.workspaceOrmManager.executeInWorkspaceContext(
- async () => {
- const messageChannelMessageAssociationRepository =
- this.workspaceOrmManager.getRepository<MessageChannelMessageAssociationWorkspaceEntity>(
- 'messageChannelMessageAssociation',
- { shouldBypassPermissionChecks: true },
- );
-
- const messageChannelMessagesAssociations =
- await messageChannelMessageAssociationRepository.find({
- where: {
- messageId: In(messages.map((message) => message.id)),
- },
- });
-
- const messageChannelIds = [
- ...new Set(
- messageChannelMessagesAssociations.map((a) => a.messageChannelId),
- ),
- ];
-
- const messageChannelsFromCore =
- messageChannelIds.length > 0
- ? await this.messageChannelRepository.find({
- where: {
- id: In(messageChannelIds),
- workspaceId,
- },
- })
- : [];
-
- const messageChannelMap = new Map(
- messageChannelsFromCore.map((ch) => [ch.id, ch]),
- );
-
- const workspaceMemberRepository =
- this.workspaceOrmManager.getRepository<WorkspaceMemberWorkspaceEntity>(
- 'workspaceMember',
- { shouldBypassPermissionChecks: true },
- );
-
- for (let i = messages.length - 1; i >= 0; i--) {
- const associations = messageChannelMessagesAssociations.filter(
- (association) => association.messageId === messages[i].id,
- );
-
- const messageChannels = associations
- .map((association) =>
- messageChannelMap.get(association.messageChannelId),
+ onModuleInit() {
+ this.commonRecordVisibilityService.registerHandler({
+ objectNameSingular: 'message',
+ handler: this,
+ });
+ }
+
+ public async applyVisibilityRestrictions({
+ records,
+ authContext,
+ }: {
+ records: ObjectRecord[];
+ authContext: WorkspaceAuthContext;
+ }): Promise<void> {
+ const restrictableMessages = records.filter((message) =>
+ RESTRICTED_MESSAGE_FIELD_NAMES.some((fieldName) => fieldName in message),
+ );
+
+ if (restrictableMessages.length === 0) {
+ return;
+ }
+
+ const { fullyVisibleMessageIds, subjectVisibleMessageIds } =
+ await this.findVisibleMessageIds({
+ messages: restrictableMessages,
+ authContext,
+ });
+
+ for (const message of restrictableMessages) {
+ if (fullyVisibleMessageIds.has(message.id)) {
+ continue;
+ }
+
+ if ('text' in message) {
+ message.text = FIELD_RESTRICTED_ADDITIONAL_PERMISSIONS_REQUIRED;
+ }
+
+ if (!subjectVisibleMessageIds.has(message.id) && 'subject' in message) {
+ message.subject = FIELD_RESTRICTED_ADDITIONAL_PERMISSIONS_REQUIRED;
+ }
+ }
+ }
+
+ private async findVisibleMessageIds({
+ messages,
+ authContext,
+ }: {
+ messages: ObjectRecord[];
+ authContext: WorkspaceAuthContext;
+ }): Promise<{
+ fullyVisibleMessageIds: Set<string>;
+ subjectVisibleMessageIds: Set<string>;
+ }> {
+ const workspaceId = authContext.workspace.id;
+ const fullyVisibleMessageIds = new Set<string>();
+ const subjectVisibleMessageIds = new Set<string>();
+
+ const messageIds = [
+ ...new Set(messages.map((message) => message.id)),
+ ].filter(isDefined);
+
+ if (messageIds.length === 0) {
+ return { fullyVisibleMessageIds, subjectVisibleMessageIds };
+ }
+
+ const messageChannelMessageAssociations =
+ await this.workspaceOrmManager.executeInWorkspaceContext(
+ async () =>
+ this.workspaceOrmManager
+ .getRepository<MessageChannelMessageAssociationWorkspaceEntity>(
+ 'messageChannelMessageAssociation',
+ { shouldBypassPermissionChecks: true },
)
- .filter(isDefined);
-
- if (messageChannels.length === 0) {
- messages.splice(i, 1);
- continue;
- }
-
- const messageChannelsGroupByVisibility = groupBy(
- messageChannels,
- (channel) => channel.visibility,
- );
-
- if (
- messageChannelsGroupByVisibility[
- MessageChannelVisibility.SHARE_EVERYTHING
- ]
- ) {
- continue;
- }
-
- if (isDefined(userId)) {
- const workspaceMember =
- await workspaceMemberRepository.findOneByOrFail({
- userId,
- });
-
- const userWorkspace = await this.userWorkspaceRepository.findOne({
- where: { userId: workspaceMember.userId, workspaceId },
- });
-
- if (userWorkspace) {
- const connectedAccounts =
- await this.connectedAccountRepository.find({
- where: {
- userWorkspaceId: userWorkspace.id,
- workspaceId,
- messageChannels: {
- id: In(messageChannels.map((channel) => channel.id)),
- },
- },
- relations: { messageChannels: true },
- });
-
- if (connectedAccounts.length > 0) {
- continue;
- }
- }
- }
-
- // Same bypass as above, via the application owning the connection; email connections carry no
- // applicationId, so this only matches channels the calling application created
- if (isDefined(applicationId)) {
- const connectedAccounts =
- await this.connectedAccountRepository.find({
- where: {
- applicationId,
- workspaceId,
- messageChannels: {
- id: In(messageChannels.map((channel) => channel.id)),
- },
- },
- relations: { messageChannels: true },
- });
-
- if (connectedAccounts.length > 0) {
- continue;
- }
- }
-
- if (
- messageChannelsGroupByVisibility[MessageChannelVisibility.SUBJECT]
- ) {
- messages[i].text = FIELD_RESTRICTED_ADDITIONAL_PERMISSIONS_REQUIRED;
- continue;
- }
-
- if (
- messageChannelsGroupByVisibility[MessageChannelVisibility.METADATA]
- ) {
- messages[i].subject =
- FIELD_RESTRICTED_ADDITIONAL_PERMISSIONS_REQUIRED;
- messages[i].text = FIELD_RESTRICTED_ADDITIONAL_PERMISSIONS_REQUIRED;
- continue;
- }
-
- messages.splice(i, 1);
- }
-
- return messages;
+ .find({
+ where: { messageId: In(messageIds) },
+ }),
+ buildSystemAuthContext(workspaceId),
+ { lite: true },
+ );
+
+ const messageChannelIds = [
+ ...new Set(
+ messageChannelMessageAssociations.map(
+ (association) => association.messageChannelId,
+ ),
+ ),
+ ];
+
+ if (messageChannelIds.length === 0) {
+ return { fullyVisibleMessageIds, subjectVisibleMessageIds };
+ }
+
+ const messageChannels = await this.messageChannelRepository.find({
+ where: { id: In(messageChannelIds), workspaceId },
+ select: {
+ id: true,
+ visibility: true,
+ connectedAccount: {
+ id: true,
+ userWorkspaceId: true,
+ applicationId: true,
+ },
},
- authContext,
- { lite: true },
+ relations: { connectedAccount: true },
+ });
+
+ const messageChannelById = new Map(
+ messageChannels.map((messageChannel) => [
+ messageChannel.id,
+ messageChannel,
+ ]),
);
+
+ for (const association of messageChannelMessageAssociations) {
+ const messageChannel = messageChannelById.get(
+ association.messageChannelId,
+ );
+
+ if (!isDefined(messageChannel)) {
+ continue;
+ }
+
+ if (
+ messageChannel.visibility ===
+ MessageChannelVisibility.SHARE_EVERYTHING ||
+ this.isMessageChannelOwnedByViewer({ messageChannel, authContext })
+ ) {
+ fullyVisibleMessageIds.add(association.messageId);
+ } else if (
+ messageChannel.visibility === MessageChannelVisibility.SUBJECT
+ ) {
+ subjectVisibleMessageIds.add(association.messageId);
+ }
+ }
+
+ return { fullyVisibleMessageIds, subjectVisibleMessageIds };
+ }
+
+ private isMessageChannelOwnedByViewer({
+ messageChannel,
+ authContext,
+ }: {
+ messageChannel: MessageChannelEntity;
+ authContext: WorkspaceAuthContext;
+ }): boolean {
+ if (isUserAuthContext(authContext)) {
+ return (
+ messageChannel.connectedAccount.userWorkspaceId ===
+ authContext.userWorkspaceId
+ );
+ }
+
+ // Email connections carry no applicationId, so an application only sees through channels it created itself
+ if (isApplicationAuthContext(authContext)) {
+ return (
+ messageChannel.connectedAccount.applicationId ===
+ authContext.application.id
+ );
+ }
+
+ return false;
}
}
diff --git a/packages/twenty-server/src/modules/messaging/common/query-hooks/message/message-find-many.post-query.hook.ts b/packages/twenty-server/src/modules/messaging/common/query-hooks/message/message-find-many.post-query.hook.ts
deleted file mode 100644
index 2050fbdd999..00000000000
--- a/packages/twenty-server/src/modules/messaging/common/query-hooks/message/message-find-many.post-query.hook.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-import { type WorkspacePostQueryHookInstance } from 'src/engine/api/graphql/workspace-query-runner/workspace-query-hook/interfaces/workspace-query-hook.interface';
-
-import { WorkspaceQueryHook } from 'src/engine/api/graphql/workspace-query-runner/workspace-query-hook/decorators/workspace-query-hook.decorator';
-import { WorkspaceQueryHookType } from 'src/engine/api/graphql/workspace-query-runner/workspace-query-hook/types/workspace-query-hook.type';
-import { isUserAuthContext } from 'src/engine/core-modules/auth/guards/is-user-auth-context.guard';
-import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
-import { ForbiddenError } from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
-import { ApplyMessagesVisibilityRestrictionsService } from 'src/modules/messaging/common/query-hooks/message/apply-messages-visibility-restrictions.service';
-import { type MessageWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message.workspace-entity';
-import { isApiKeyAuthContext } from 'src/engine/core-modules/auth/guards/is-api-key-auth-context.guard';
-import { isApplicationAuthContext } from 'src/engine/core-modules/auth/guards/is-application-auth-context.guard';
-
-@WorkspaceQueryHook({
- key: `message.findMany`,
- type: WorkspaceQueryHookType.POST_HOOK,
-})
-export class MessageFindManyPostQueryHook implements WorkspacePostQueryHookInstance {
- constructor(
- private readonly applyMessagesVisibilityRestrictionsService: ApplyMessagesVisibilityRestrictionsService,
- ) {}
-
- async execute(
- authContext: WorkspaceAuthContext,
- _objectName: string,
- payload: MessageWorkspaceEntity[],
- ): Promise<void> {
- // TODO: this check should be removed
- if (
- !isUserAuthContext(authContext) &&
- !isApiKeyAuthContext(authContext) &&
- !isApplicationAuthContext(authContext)
- ) {
- throw new ForbiddenError(
- 'Authentication error, auth context should be user, apiKey or application',
- );
- }
-
- const workspace = authContext.workspace;
-
- if (!workspace) {
- throw new ForbiddenError('Workspace is required');
- }
-
- const userId = isUserAuthContext(authContext)
- ? authContext.user.id
- : undefined;
-
- // An application has no user behind it, so it would otherwise get redacted placeholders for its own messages
- const applicationId = isApplicationAuthContext(authContext)
- ? authContext.application.id
- : undefined;
-
- await this.applyMessagesVisibilityRestrictionsService.applyMessagesVisibilityRestrictions(
- payload,
- workspace.id,
- userId,
- applicationId,
- );
- }
-}
diff --git a/packages/twenty-server/src/modules/messaging/common/query-hooks/message/message-find-one.post-query.hook.ts b/packages/twenty-server/src/modules/messaging/common/query-hooks/message/message-find-one.post-query.hook.ts
deleted file mode 100644
index 0cc3f11e573..00000000000
--- a/packages/twenty-server/src/modules/messaging/common/query-hooks/message/message-find-one.post-query.hook.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-import { type WorkspacePostQueryHookInstance } from 'src/engine/api/graphql/workspace-query-runner/workspace-query-hook/interfaces/workspace-query-hook.interface';
-
-import { WorkspaceQueryHook } from 'src/engine/api/graphql/workspace-query-runner/workspace-query-hook/decorators/workspace-query-hook.decorator';
-import { WorkspaceQueryHookType } from 'src/engine/api/graphql/workspace-query-runner/workspace-query-hook/types/workspace-query-hook.type';
-import { isUserAuthContext } from 'src/engine/core-modules/auth/guards/is-user-auth-context.guard';
-import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
-import { ForbiddenError } from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
-import { ApplyMessagesVisibilityRestrictionsService } from 'src/modules/messaging/common/query-hooks/message/apply-messages-visibility-restrictions.service';
-import { type MessageWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message.workspace-entity';
-import { isApiKeyAuthContext } from 'src/engine/core-modules/auth/guards/is-api-key-auth-context.guard';
-import { isApplicationAuthContext } from 'src/engine/core-modules/auth/guards/is-application-auth-context.guard';
-
-@WorkspaceQueryHook({
- key: `message.findOne`,
- type: WorkspaceQueryHookType.POST_HOOK,
-})
-export class MessageFindOnePostQueryHook implements WorkspacePostQueryHookInstance {
- constructor(
- private readonly applyMessagesVisibilityRestrictionsService: ApplyMessagesVisibilityRestrictionsService,
- ) {}
-
- async execute(
- authContext: WorkspaceAuthContext,
- _objectName: string,
- payload: MessageWorkspaceEntity[],
- ): Promise<void> {
- // TODO: this check should be removed
- if (
- !isUserAuthContext(authContext) &&
- !isApiKeyAuthContext(authContext) &&
- !isApplicationAuthContext(authContext)
- ) {
- throw new ForbiddenError(
- 'Authentication error, auth context should be user, apiKey or application',
- );
- }
-
- const workspace = authContext.workspace;
-
- if (!workspace) {
- throw new ForbiddenError('Workspace is required');
- }
-
- const userId = isUserAuthContext(authContext)
- ? authContext.user.id
- : undefined;
-
- // An application has no user behind it, so it would otherwise get redacted placeholders for its own messages
- const applicationId = isApplicationAuthContext(authContext)
- ? authContext.application.id
- : undefined;
-
- await this.applyMessagesVisibilityRestrictionsService.applyMessagesVisibilityRestrictions(
- payload,
- workspace.id,
- userId,
- applicationId,
- );
- }
-}
diff --git a/packages/twenty-server/src/modules/messaging/common/query-hooks/messaging-query-hook.module.ts b/packages/twenty-server/src/modules/messaging/common/query-hooks/messaging-query-hook.module.ts
index 054a6735124..f4c773b36de 100644
--- a/packages/twenty-server/src/modules/messaging/common/query-hooks/messaging-query-hook.module.ts
+++ b/packages/twenty-server/src/modules/messaging/common/query-hooks/messaging-query-hook.module.ts
@@ -1,27 +1,19 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
-import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
-import { ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
+import { CommonRecordVisibilityModule } from 'src/engine/api/common/common-record-visibility/common-record-visibility.module';
import { MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';
import { ApplyMessagesVisibilityRestrictionsService } from 'src/modules/messaging/common/query-hooks/message/apply-messages-visibility-restrictions.service';
-import { MessageFindManyPostQueryHook } from 'src/modules/messaging/common/query-hooks/message/message-find-many.post-query.hook';
-import { MessageFindOnePostQueryHook } from 'src/modules/messaging/common/query-hooks/message/message-find-one.post-query.hook';
import { MessageThreadTargetCreateManyPreQueryHook } from 'src/modules/messaging/common/query-hooks/message-thread-target/message-thread-target-create-many.pre-query-hook';
import { MessageThreadTargetCreateOnePreQueryHook } from 'src/modules/messaging/common/query-hooks/message-thread-target/message-thread-target-create-one.pre-query-hook';
@Module({
imports: [
- TypeOrmModule.forFeature([
- ConnectedAccountEntity,
- MessageChannelEntity,
- UserWorkspaceEntity,
- ]),
+ CommonRecordVisibilityModule,
+ TypeOrmModule.forFeature([MessageChannelEntity]),
],
providers: [
ApplyMessagesVisibilityRestrictionsService,
- MessageFindOnePostQueryHook,
- MessageFindManyPostQueryHook,
MessageThreadTargetCreateOnePreQueryHook,
MessageThreadTargetCreateManyPreQueryHook,
],
diff --git a/packages/twenty-server/test/integration/google/calendar/channel-visibility.integration-spec.ts b/packages/twenty-server/test/integration/google/calendar/channel-visibility.integration-spec.ts
index 2c3a039dd81..731fb3cbcc3 100644
--- a/packages/twenty-server/test/integration/google/calendar/channel-visibility.integration-spec.ts
+++ b/packages/twenty-server/test/integration/google/calendar/channel-visibility.integration-spec.ts
@@ -20,6 +20,7 @@ import { runCalendarChannelEventsImport } from 'test/integration/utils/run-calen
import { runCalendarChannelListFetch } from 'test/integration/utils/run-calendar-channel-list-fetch.util';
const HANDLE = '[email protected]';
+const ATTENDEE_HANDLE = '[email protected]';
const RESTRICTED = FIELD_RESTRICTED_ADDITIONAL_PERMISSIONS_REQUIRED;
@@ -52,6 +53,29 @@ describe('Calendar channel visibility (integration)', () => {
);
};
+ const readEventThroughParticipantAs = async (
+ makeRequest:
+ | typeof makeGraphqlApiRequest
+ | typeof makeGraphqlApiRequestWithMemberRole,
+ ) => {
+ const response = await makeRequest(
+ findManyOperationFactory({
+ objectMetadataSingularName: 'calendarEventParticipant',
+ objectMetadataPluralName: 'calendarEventParticipants',
+ gqlFields: 'calendarEvent { title description }',
+ filter: { handle: { eq: ATTENDEE_HANDLE } },
+ }),
+ );
+
+ expect(response.body.errors).toBeUndefined();
+
+ return response.body.data.calendarEventParticipants.edges.map(
+ (edge: {
+ node: { calendarEvent: { title: string; description: string } };
+ }) => edge.node.calendarEvent,
+ );
+ };
+
const setVisibility = async (visibility: CalendarChannelVisibility) => {
await getCoreRepository<CalendarChannelEntity>(
CalendarChannelEntity,
@@ -68,6 +92,7 @@ describe('Calendar channel visibility (integration)', () => {
googleCalendarEvent({
summary: eventTitle,
description: 'Agenda for the meeting',
+ attendees: [{ email: ATTENDEE_HANDLE }],
}),
]);
@@ -105,4 +130,24 @@ describe('Calendar channel visibility (integration)', () => {
expect(event.title).toBe(eventTitle);
expect(event.description).not.toBe(RESTRICTED);
}, 60000);
+
+ it('masks an event fetched through a relation for another member under metadata visibility', async () => {
+ await setVisibility(CalendarChannelVisibility.METADATA);
+
+ const [event] = await readEventThroughParticipantAs(
+ makeGraphqlApiRequestWithMemberRole,
+ );
+
+ expect(event.title).toBe(RESTRICTED);
+ expect(event.description).toBe(RESTRICTED);
+ }, 60000);
+
+ it('shows an event fetched through a relation to the owner of the connected account', async () => {
+ await setVisibility(CalendarChannelVisibility.METADATA);
+
+ const [event] = await readEventThroughParticipantAs(makeGraphqlApiRequest);
+
+ expect(event.title).toBe(eventTitle);
+ expect(event.description).not.toBe(RESTRICTED);
+ }, 60000);
});
diff --git a/packages/twenty-server/test/integration/google/messaging/channel-visibility.integration-spec.ts b/packages/twenty-server/test/integration/google/messaging/channel-visibility.integration-spec.ts
index b3b2c12ca4d..9726bd9ef99 100644
--- a/packages/twenty-server/test/integration/google/messaging/channel-visibility.integration-spec.ts
+++ b/packages/twenty-server/test/integration/google/messaging/channel-visibility.integration-spec.ts
@@ -18,11 +18,12 @@ import { getCoreRepository } from 'test/integration/utils/get-core-repository.ut
import { runMessageChannelSync } from 'test/integration/utils/run-message-channel-sync.util';
const HANDLE = '[email protected]';
+const SENDER_HANDLE = '[email protected]';
const RESTRICTED = FIELD_RESTRICTED_ADDITIONAL_PERMISSIONS_REQUIRED;
describe('Message channel visibility (integration)', () => {
- const inbox = [gmailMessage()];
+ const inbox = [gmailMessage({ from: SENDER_HANDLE })];
const subject = getGmailMessageSubject(inbox[0]);
setupGoogleMock({ handle: HANDLE, inbox });
@@ -51,6 +52,28 @@ describe('Message channel visibility (integration)', () => {
);
};
+ const readMessageThroughParticipantAs = async (
+ makeRequest:
+ | typeof makeGraphqlApiRequest
+ | typeof makeGraphqlApiRequestWithMemberRole,
+ ) => {
+ const response = await makeRequest(
+ findManyOperationFactory({
+ objectMetadataSingularName: 'messageParticipant',
+ objectMetadataPluralName: 'messageParticipants',
+ gqlFields: 'message { subject text }',
+ filter: { handle: { eq: SENDER_HANDLE } },
+ }),
+ );
+
+ expect(response.body.errors).toBeUndefined();
+
+ return response.body.data.messageParticipants.edges.map(
+ (edge: { node: { message: { subject: string; text: string } } }) =>
+ edge.node.message,
+ );
+ };
+
const setVisibility = async (visibility: MessageChannelVisibility) => {
await getCoreRepository<MessageChannelEntity>(MessageChannelEntity).update(
{ id: channel.channelId },
@@ -106,4 +129,37 @@ describe('Message channel visibility (integration)', () => {
expect(message.subject).toBe(subject);
expect(message.text).not.toBe(RESTRICTED);
}, 60000);
+
+ it('masks a message fetched through a relation for another member under metadata visibility', async () => {
+ await setVisibility(MessageChannelVisibility.METADATA);
+
+ const [message] = await readMessageThroughParticipantAs(
+ makeGraphqlApiRequestWithMemberRole,
+ );
+
+ expect(message.subject).toBe(RESTRICTED);
+ expect(message.text).toBe(RESTRICTED);
+ }, 60000);
+
+ it('masks only the body of a message fetched through a relation under subject visibility', async () => {
+ await setVisibility(MessageChannelVisibility.SUBJECT);
+
+ const [message] = await readMessageThroughParticipantAs(
+ makeGraphqlApiRequestWithMemberRole,
+ );
+
+ expect(message.subject).toBe(subject);
+ expect(message.text).toBe(RESTRICTED);
+ }, 60000);
+
+ it('shows a message fetched through a relation to the owner of the connected account', async () => {
+ await setVisibility(MessageChannelVisibility.METADATA);
+
+ const [message] = await readMessageThroughParticipantAs(
+ makeGraphqlApiRequest,
+ );
+
+ expect(message.subject).toBe(subject);
+ expect(message.text).not.toBe(RESTRICTED);
+ }, 60000);
});
diff --git a/packages/twenty-server/test/integration/graphql/suites/calendar-event-visibility.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/calendar-event-visibility.integration-spec.ts
index d91cdfc56b9..77d2a7db202 100644
--- a/packages/twenty-server/test/integration/graphql/suites/calendar-event-visibility.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/calendar-event-visibility.integration-spec.ts
@@ -3,12 +3,14 @@ import { createOneOperationFactory } from 'test/integration/graphql/utils/create
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 { groupByOperationFactory } from 'test/integration/graphql/utils/group-by-operation-factory.util';
import { makeGraphqlApiRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';
import { FIELD_RESTRICTED_ADDITIONAL_PERMISSIONS_REQUIRED } from 'twenty-shared/constants';
import { CALENDAR_CHANNEL_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/constants/calendar-channel-seed-ids.constant';
const UNASSOCIATED_EVENT_ID = '20202020-ca1e-4000-8000-000000000001';
+const PARTICIPANT_PERSON_ID = '20202020-ca1e-4000-8000-000000000002';
const METADATA_CHANNEL_IDS = [
CALENDAR_CHANNEL_DATA_SEED_IDS.TIM,
@@ -53,6 +55,31 @@ const findSeededEventIdOnChannels = async (calendarChannelIds: string[]) => {
return calendarEventId as string;
};
+type CalendarEventNode = { id: string; title: string; description: string };
+
+const expectMaskedByVisibility = ({
+ calendarEvents,
+ metadataEventId,
+ sharedEventId,
+}: {
+ calendarEvents: CalendarEventNode[];
+ metadataEventId: string;
+ sharedEventId: string;
+}) => {
+ const calendarEventsById = new Map(
+ calendarEvents.map((calendarEvent) => [calendarEvent.id, calendarEvent]),
+ );
+
+ expect(calendarEventsById.get(UNASSOCIATED_EVENT_ID)).toMatchObject(
+ MASKED_FIELDS,
+ );
+ expect(calendarEventsById.get(metadataEventId)).toMatchObject(MASKED_FIELDS);
+ expect(calendarEventsById.get(sharedEventId)?.title).toBeDefined();
+ expect(calendarEventsById.get(sharedEventId)?.title).not.toBe(
+ FIELD_RESTRICTED_ADDITIONAL_PERMISSIONS_REQUIRED,
+ );
+};
+
const findCalendarEvent = async (id: string) => {
const response = await makeGraphqlApiRequest(
findOneOperationFactory({
@@ -70,6 +97,7 @@ const findCalendarEvent = async (id: string) => {
describe('calendarEvent visibility restrictions (e2e)', () => {
let metadataEventId: string;
let sharedEventId: string;
+ const participantIds: string[] = [];
beforeAll(async () => {
const response = await makeGraphqlApiRequest(
@@ -93,9 +121,64 @@ describe('calendarEvent visibility restrictions (e2e)', () => {
sharedEventId = await findSeededEventIdOnChannels(
SHARE_EVERYTHING_CHANNEL_IDS,
);
+
+ const personResponse = await makeGraphqlApiRequest(
+ createOneOperationFactory({
+ objectMetadataSingularName: 'person',
+ gqlFields: 'id',
+ data: {
+ id: PARTICIPANT_PERSON_ID,
+ name: { firstName: 'Visibility', lastName: 'Participant' },
+ },
+ }),
+ );
+
+ expect(personResponse.body.errors).toBeUndefined();
+
+ for (const calendarEventId of [
+ UNASSOCIATED_EVENT_ID,
+ metadataEventId,
+ sharedEventId,
+ ]) {
+ const participantResponse = await makeGraphqlApiRequest(
+ createOneOperationFactory({
+ objectMetadataSingularName: 'calendarEventParticipant',
+ gqlFields: 'id',
+ data: {
+ handle: '[email protected]',
+ calendarEventId,
+ personId: PARTICIPANT_PERSON_ID,
+ },
+ }),
+ );
+
+ expect(participantResponse.body.errors).toBeUndefined();
+
+ participantIds.push(
+ participantResponse.body.data.createCalendarEventParticipant.id,
+ );
+ }
});
afterAll(async () => {
+ for (const participantId of participantIds) {
+ await makeGraphqlApiRequest(
+ destroyOneOperationFactory({
+ objectMetadataSingularName: 'calendarEventParticipant',
+ gqlFields: 'id',
+ recordId: participantId,
+ }),
+ );
+ }
+
+ await makeGraphqlApiRequest(
+ destroyOneOperationFactory({
+ objectMetadataSingularName: 'person',
+ gqlFields: 'id',
+ recordId: PARTICIPANT_PERSON_ID,
+ }),
+ );
+
await makeGraphqlApiRequest(
destroyOneOperationFactory({
objectMetadataSingularName: 'calendarEvent',
@@ -119,21 +202,13 @@ describe('calendarEvent visibility restrictions (e2e)', () => {
expect(response.body.errors).toBeUndefined();
- const calendarEventsById = new Map(
- response.body.data.calendarEvents.edges.map(
- (edge: { node: { id: string } }) => [edge.node.id, edge.node],
+ expectMaskedByVisibility({
+ calendarEvents: response.body.data.calendarEvents.edges.map(
+ (edge: { node: CalendarEventNode }) => edge.node,
),
- );
-
- expect(calendarEventsById.get(UNASSOCIATED_EVENT_ID)).toMatchObject(
- MASKED_FIELDS,
- );
- expect(calendarEventsById.get(metadataEventId)).toMatchObject(
- MASKED_FIELDS,
- );
- expect(
- (calendarEventsById.get(sharedEventId) as { title: string }).title,
- ).not.toBe(FIELD_RESTRICTED_ADDITIONAL_PERMISSIONS_REQUIRED);
+ metadataEventId,
+ sharedEventId,
+ });
});
it('should mask an event without channel associations in findOne', async () => {
@@ -149,4 +224,82 @@ describe('calendarEvent visibility restrictions (e2e)', () => {
FIELD_RESTRICTED_ADDITIONAL_PERMISSIONS_REQUIRED,
);
});
+
+ it('should mask events fetched through a many-to-one relation', async () => {
+ const response = await makeGraphqlApiRequest(
+ findManyOperationFactory({
+ objectMetadataSingularName: 'calendarEventParticipant',
+ objectMetadataPluralName: 'calendarEventParticipants',
+ gqlFields: 'calendarEvent { id title description }',
+ filter: { personId: { eq: PARTICIPANT_PERSON_ID } },
+ }),
+ );
+
+ expect(response.body.errors).toBeUndefined();
+
+ expectMaskedByVisibility({
+ calendarEvents: response.body.data.calendarEventParticipants.edges.map(
+ (edge: { node: { calendarEvent: CalendarEventNode } }) =>
+ edge.node.calendarEvent,
+ ),
+ metadataEventId,
+ sharedEventId,
+ });
+ });
+
+ it('should mask events nested under a one-to-many relation', async () => {
+ const response = await makeGraphqlApiRequest(
+ findOneOperationFactory({
+ objectMetadataSingularName: 'person',
+ filter: { id: { eq: PARTICIPANT_PERSON_ID } },
+ gqlFields: `
+ id
+ calendarEventParticipants {
+ edges {
+ node {
+ calendarEvent { id title description }
+ }
+ }
+ }
+ `,
+ }),
+ );
+
+ expect(response.body.errors).toBeUndefined();
+
+ expectMaskedByVisibility({
+ calendarEvents:
+ response.body.data.person.calendarEventParticipants.edges.map(
+ (edge: { node: { calendarEvent: CalendarEventNode } }) =>
+ edge.node.calendarEvent,
+ ),
+ metadataEventId,
+ sharedEventId,
+ });
+ });
+
+ it('should mask events returned by groupBy', async () => {
+ const response = await makeGraphqlApiRequest(
+ groupByOperationFactory({
+ objectMetadataSingularName: 'calendarEvent',
+ objectMetadataPluralName: 'calendarEvents',
+ groupBy: [{ isFullDay: true }],
+ filter: {
+ id: { in: [UNASSOCIATED_EVENT_ID, metadataEventId, sharedEventId] },
+ },
+ gqlFields: 'edges { node { id title description } }',
+ }),
+ );
+
+ expect(response.body.errors).toBeUndefined();
+
+ expectMaskedByVisibility({
+ calendarEvents: response.body.data.calendarEventsGroupBy.flatMap(
+ (group: { edges: { node: CalendarEventNode }[] }) =>
+ group.edges.map((edge) => edge.node),
+ ),
+ metadataEventId,
+ sharedEventId,
+ });
+ });
});
diff --git a/packages/twenty-server/test/integration/graphql/suites/message-visibility.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/message-visibility.integration-spec.ts
new file mode 100644
index 00000000000..3cbf333fb0e
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/suites/message-visibility.integration-spec.ts
@@ -0,0 +1,99 @@
+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 { makeGraphqlApiRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';
+import { FIELD_RESTRICTED_ADDITIONAL_PERMISSIONS_REQUIRED } from 'twenty-shared/constants';
+
+const UNASSOCIATED_MESSAGE_ID = '20202020-ca1e-4000-8000-000000000101';
+const UNASSOCIATED_MESSAGE_PARTICIPANT_ID =
+ '20202020-ca1e-4000-8000-000000000102';
+
+const MASKED_FIELDS = {
+ subject: FIELD_RESTRICTED_ADDITIONAL_PERMISSIONS_REQUIRED,
+ text: FIELD_RESTRICTED_ADDITIONAL_PERMISSIONS_REQUIRED,
+};
+
+describe('message visibility restrictions (e2e)', () => {
+ beforeAll(async () => {
+ const messageResponse = await makeGraphqlApiRequest(
+ createOneOperationFactory({
+ objectMetadataSingularName: 'message',
+ gqlFields: 'id',
+ data: {
+ id: UNASSOCIATED_MESSAGE_ID,
+ subject: 'Visibility test subject',
+ text: 'Visibility test body',
+ receivedAt: new Date().toISOString(),
+ },
+ }),
+ );
+
+ expect(messageResponse.body.errors).toBeUndefined();
+
+ const participantResponse = await makeGraphqlApiRequest(
+ createOneOperationFactory({
+ objectMetadataSingularName: 'messageParticipant',
+ gqlFields: 'id',
+ data: {
+ id: UNASSOCIATED_MESSAGE_PARTICIPANT_ID,
+ messageId: UNASSOCIATED_MESSAGE_ID,
+ role: 'FROM',
+ handle: '[email protected]',
+ },
+ }),
+ );
+
+ expect(participantResponse.body.errors).toBeUndefined();
+ });
+
+ afterAll(async () => {
+ await makeGraphqlApiRequest(
+ destroyOneOperationFactory({
+ objectMetadataSingularName: 'messageParticipant',
+ gqlFields: 'id',
+ recordId: UNASSOCIATED_MESSAGE_PARTICIPANT_ID,
+ }),
+ );
+
+ await makeGraphqlApiRequest(
+ destroyOneOperationFactory({
+ objectMetadataSingularName: 'message',
+ gqlFields: 'id',
+ recordId: UNASSOCIATED_MESSAGE_ID,
+ }),
+ );
+ });
+
+ it('should return a message without channel associations masked in findMany', async () => {
+ const response = await makeGraphqlApiRequest(
+ findManyOperationFactory({
+ objectMetadataSingularName: 'message',
+ objectMetadataPluralName: 'messages',
+ gqlFields: 'id subject text',
+ filter: { id: { eq: UNASSOCIATED_MESSAGE_ID } },
+ }),
+ );
+
+ expect(response.body.errors).toBeUndefined();
+ expect(response.body.data.messages.edges).toHaveLength(1);
+ expect(response.body.data.messages.edges[0].node).toMatchObject(
+ MASKED_FIELDS,
+ );
+ });
+
+ it('should mask a message without channel associations fetched through a relation', async () => {
+ const response = await makeGraphqlApiRequest(
+ findManyOperationFactory({
+ objectMetadataSingularName: 'messageParticipant',
+ objectMetadataPluralName: 'messageParticipants',
+ gqlFields: 'message { id subject text }',
+ filter: { id: { eq: UNASSOCIATED_MESSAGE_PARTICIPANT_ID } },
+ }),
+ );
+
+ expect(response.body.errors).toBeUndefined();
+ expect(
+ response.body.data.messageParticipants.edges[0].node.message,
+ ).toMatchObject(MASKED_FIELDS);
+ });
+});
diff --git a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/system-object-records-permissions.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/system-object-records-permissions.integration-spec.ts
index a687051a5c7..1997b527459 100644
--- a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/system-object-records-permissions.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/system-object-records-permissions.integration-spec.ts
@@ -313,9 +313,7 @@ describe('systemObjectRecordsPermissions', () => {
);
expect(response.body.errors).toBeUndefined();
- expect(response.body.data.updateMessage.text).toBe(
- 'Updated through the system object default',
- );
+ expect(response.body.data.updateMessage.id).toBe(messageId);
});
it('should deny updating a standard object', async () => {