The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Keep notes and tasks attached to nothing readable by every member (#27002)
Félix Malfait38c59474d0a4
diff --git a/packages/twenty-server/src/engine/core-modules/record-share/constants/open-when-detached-object-universal-identifiers.constant.ts b/packages/twenty-server/src/engine/core-modules/record-share/constants/open-when-detached-object-universal-identifiers.constant.tsnew file mode 100644index 00000000000..b4ea4310f29--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/record-share/constants/open-when-detached-object-universal-identifiers.constant.ts@@ -0,0 +1,11 @@+/* @license Enterprise */++import { STANDARD_OBJECTS } from 'twenty-shared/metadata';++// Notes and tasks were readable by every member before they inherited from+// their targets, so one attached to nothing stays that way instead of falling+// back to its creator only+export const OPEN_WHEN_DETACHED_OBJECT_UNIVERSAL_IDENTIFIERS: string[] = [+ STANDARD_OBJECTS.note.universalIdentifier,+ STANDARD_OBJECTS.task.universalIdentifier,+];diff --git a/packages/twenty-server/src/engine/core-modules/record-share/services/record-access-policy.service.ts b/packages/twenty-server/src/engine/core-modules/record-share/services/record-access-policy.service.tsindex 43f449828ab..ee29e2a553f 100644--- a/packages/twenty-server/src/engine/core-modules/record-share/services/record-access-policy.service.ts+++ b/packages/twenty-server/src/engine/core-modules/record-share/services/record-access-policy.service.ts@@ -6,7 +6,7 @@ import { type ObjectRecordEvent } from 'twenty-shared/database-events';import { type ObjectRecord } from 'twenty-shared/types';import { assertUnreachable, isDefined } from 'twenty-shared/utils';import { isNonEmptyString } from '@sniptt/guards';-import { In } from 'typeorm';+import { In, MoreThanOrEqual } from 'typeorm';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';@@ -27,8 +27,10 @@ import { type InheritedReadabilityColumnParent } from 'src/engine/core-modules/rimport { type RowAccessPolicySubject } from 'src/engine/twenty-orm/types/row-access-policy.type';import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';import { isObjectOperationPermitted } from 'src/engine/twenty-orm/utils/is-object-operation-permitted.util';+import { isChildRecordBoundAtDeletion } from 'src/engine/twenty-orm/utils/is-child-record-bound-at-deletion.util';import { isRecordMatchingRLSRowLevelPermissionPredicate } from 'src/engine/twenty-orm/utils/is-record-matching-rls-row-level-permission-predicate.util';import { resolveInheritedReadabilityParents } from 'src/engine/core-modules/record-share/utils/resolve-inherited-readability-parents.util';+import { isOpenWhenDetachedObject } from 'src/engine/core-modules/record-share/utils/is-open-when-detached-object.util';import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';import { type WorkspaceEventBatch } from 'src/engine/workspace-event-emitter/types/workspace-event-batch.type';@@ -53,6 +55,11 @@ type SnapshotEvaluationInContext = SnapshotEvaluation & {type FetchRecordShares = () => Promise<RecordShare[]>;+type SnapshotIdsThroughParent = {+ readableSnapshotIds: Set<string>;+ attachedSnapshotIds: Set<string>;+};+@Injectable()export class RecordAccessPolicyService {constructor(@@ -239,9 +246,10 @@ export class RecordAccessPolicyService {flatObjectMetadataMaps: maps.flatObjectMetadataMaps,});const readableSnapshotIds = new Set<string>();+ const attachedSnapshotIds = new Set<string>();for (const parent of parents) {- const readableIds =+ const snapshotIdsThroughParent =parent.kind === 'column'? await this.resolveSnapshotIdsReadableThroughColumnParent({...evaluation,@@ -254,9 +262,21 @@ export class RecordAccessPolicyService {parent,});- for (const readableId of readableIds) {+ for (const readableId of snapshotIdsThroughParent.readableSnapshotIds) {readableSnapshotIds.add(readableId);}++ for (const attachedId of snapshotIdsThroughParent.attachedSnapshotIds) {+ attachedSnapshotIds.add(attachedId);+ }+ }++ if (isOpenWhenDetachedObject(objectMetadata)) {+ for (const snapshot of evaluation.snapshots) {+ if (!attachedSnapshotIds.has(snapshot.id)) {+ readableSnapshotIds.add(snapshot.id);+ }+ }}return readableSnapshotIds;@@ -269,7 +289,7 @@ export class RecordAccessPolicyService {parent,}: SnapshotEvaluationInContext & {parent: InheritedReadabilityColumnParent;- }): Promise<Set<string>> {+ }): Promise<SnapshotIdsThroughParent> {const parentIdBySnapshotId = new Map(snapshots.flatMap((snapshot) => {const parentId = snapshot[parent.joinColumnName];@@ -284,15 +304,19 @@ export class RecordAccessPolicyService {depth: depth + 1,});- return new Set(- [...parentIdBySnapshotId]- .filter(([, parentId]) => readableParentIds.has(parentId))- .map(([snapshotId]) => snapshotId),- );+ return {+ readableSnapshotIds: new Set(+ [...parentIdBySnapshotId]+ .filter(([, parentId]) => readableParentIds.has(parentId))+ .map(([snapshotId]) => snapshotId),+ ),+ attachedSnapshotIds: new Set(parentIdBySnapshotId.keys()),+ };}private async resolveSnapshotIdsReadableThroughChildren({workspaceId,+ objectMetadata,snapshots,subject,depth,@@ -300,7 +324,7 @@ export class RecordAccessPolicyService {parent,}: SnapshotEvaluationInContext & {parent: InheritedReadabilityChildrenParent;- }): Promise<Set<string>> {+ }): Promise<SnapshotIdsThroughParent> {const childNameSingular = parent.childFlatObjectMetadata.nameSingular;const capturedChildSnapshotsBySnapshotId = new Map(snapshots.flatMap((snapshot) => {@@ -329,12 +353,20 @@ export class RecordAccessPolicyService {.map((snapshot) => snapshot.id);const readableSnapshotIds = new Set<string>();+ const attachedSnapshotIds = new Set(+ [...capturedChildSnapshotsBySnapshotId]+ .filter(+ ([, capturedChildSnapshots]) => capturedChildSnapshots.length > 0,+ )+ .map(([snapshotId]) => snapshotId),+ );if (liveSnapshotIds.length > 0) {- const childRows = await this.workspaceOrmManager- .getRepository(childNameSingular, {- shouldBypassPermissionChecks: true,- })+ const childRepository = this.workspaceOrmManager.getRepository(+ childNameSingular,+ { shouldBypassPermissionChecks: true },+ );+ const childRows = await childRepository.createQueryBuilder().select(['id', parent.childJoinColumnName]).where({ [parent.childJoinColumnName]: In(liveSnapshotIds) })@@ -347,8 +379,60 @@ export class RecordAccessPolicyService {});for (const childRow of childRows) {+ const snapshotId = String(childRow[parent.childJoinColumnName]);++ attachedSnapshotIds.add(snapshotId);+if (readableChildIds.has(String(childRow.id))) {- readableSnapshotIds.add(String(childRow[parent.childJoinColumnName]));+ readableSnapshotIds.add(snapshotId);+ }+ }++ const trashedSnapshots = snapshots.filter(+ (snapshot) =>+ !capturedChildSnapshotsBySnapshotId.has(snapshot.id) &&+ isDefined(snapshot.deletedAt),+ );++ if (+ isOpenWhenDetachedObject(objectMetadata) &&+ trashedSnapshots.length > 0+ ) {+ const snapshotById = new Map(+ trashedSnapshots.map((snapshot) => [snapshot.id, snapshot]),+ );+ const earliestDeletedAt = new Date(+ Math.min(+ ...trashedSnapshots.map((snapshot) =>+ new Date(String(snapshot.deletedAt)).getTime(),+ ),+ ),+ );+ // A row trashed along with the record still attaches it, as in the+ // query gate; rows trashed before any of these records cannot+ const trashedChildRows = await childRepository+ .createQueryBuilder()+ .select(['id', parent.childJoinColumnName, 'deletedAt'])+ .where({+ [parent.childJoinColumnName]: In([...snapshotById.keys()]),+ deletedAt: MoreThanOrEqual(earliestDeletedAt),+ })+ .withDeleted()+ .getMany<ObjectRecord>({ noFormatting: true });++ for (const childRow of trashedChildRows) {+ const snapshotId = String(childRow[parent.childJoinColumnName]);+ const snapshot = snapshotById.get(snapshotId);++ if (+ isDefined(snapshot) &&+ isChildRecordBoundAtDeletion({+ childRecord: childRow,+ record: snapshot,+ })+ ) {+ attachedSnapshotIds.add(snapshotId);+ }}}}@@ -375,7 +459,7 @@ export class RecordAccessPolicyService {}}- return readableSnapshotIds;+ return { readableSnapshotIds, attachedSnapshotIds };}private async resolveReadableSnapshotIds(diff --git a/packages/twenty-server/src/engine/core-modules/record-share/utils/__tests__/build-inherited-readability-condition.util.spec.ts b/packages/twenty-server/src/engine/core-modules/record-share/utils/__tests__/build-inherited-readability-condition.util.spec.tsindex 2ebcededaa8..44e4caf4504 100644--- a/packages/twenty-server/src/engine/core-modules/record-share/utils/__tests__/build-inherited-readability-condition.util.spec.ts+++ b/packages/twenty-server/src/engine/core-modules/record-share/utils/__tests__/build-inherited-readability-condition.util.spec.ts@@ -18,7 +18,10 @@ const OWN_RECORD_SHARE_EXISTS =const countOccurrences = (haystack: string, needle: string): number =>haystack.split(needle).length - 1;-const build = (parents: InheritedReadabilityParentCondition[]) =>+const build = (+ parents: InheritedReadabilityParentCondition[],+ { isOpenWhenDetached }: { isOpenWhenDetached?: boolean } = {},+) =>buildInheritedReadabilityCondition({tableAlias: 'attachment',objectMetadataId: ATTACHMENT_OBJECT_METADATA_ID,@@ -26,6 +29,7 @@ const build = (parents: InheritedReadabilityParentCondition[]) =>recordShareTableExpression: RECORD_SHARE_TABLE_EXPRESSION,principalIds: PRINCIPAL_IDS,accessLevels: ACCESS_LEVELS,+ isOpenWhenDetached,});const noteParent = (@@ -147,4 +151,30 @@ describe('buildInheritedReadabilityCondition', () => {expect(sql).not.toContain('secret');expect(parameters.nested).toBe('value');});++ it('should not accept a detached record unless its object is open when detached', () => {+ const { sql } = build([personParent({ kind: 'denied' })]);++ expect(sql).not.toContain('"attachment"."targetPersonId" IS NULL');+ });++ it('should accept a record attached through no link at all, a denied parent included, when its object is open when detached', () => {+ const { sql } = build(+ [+ personParent({ kind: 'denied' }),+ {+ kind: 'children',+ childTableAlias: 'attachment_noteTarget',+ childTableExpression: '"workspace_abc"."noteTarget"',+ childJoinColumnName: 'noteId',+ policy: { kind: 'denied' },+ },+ ],+ { isOpenWhenDetached: true },+ );++ expect(sql).toContain(+ ' OR ("attachment"."targetPersonId" IS NULL AND NOT EXISTS (SELECT 1 FROM "workspace_abc"."noteTarget" AS "attachment_noteTarget" WHERE "attachment_noteTarget"."noteId" = "attachment"."id" AND ("attachment_noteTarget"."deletedAt" IS NULL OR ("attachment"."deletedAt" IS NOT NULL AND "attachment_noteTarget"."deletedAt" >= "attachment"."deletedAt")))))',+ );+ });});diff --git a/packages/twenty-server/src/engine/core-modules/record-share/utils/build-inherited-readability-condition.util.ts b/packages/twenty-server/src/engine/core-modules/record-share/utils/build-inherited-readability-condition.util.tsindex 0760914b00f..e59f1bbb9de 100644--- a/packages/twenty-server/src/engine/core-modules/record-share/utils/build-inherited-readability-condition.util.ts+++ b/packages/twenty-server/src/engine/core-modules/record-share/utils/build-inherited-readability-condition.util.ts@@ -35,6 +35,25 @@ const buildChildLinkBoundCondition = ({}): string =>`(${quotedChildTableAlias}."deletedAt" IS NULL OR (${quotedTableAlias}."deletedAt" IS NOT NULL AND ${quotedChildTableAlias}."deletedAt" >= ${quotedTableAlias}."deletedAt"))`;+const buildDetachedCondition = ({+ quotedTableAlias,+ parents,+}: {+ quotedTableAlias: string;+ parents: InheritedReadabilityParentCondition[];+}): string =>+ `(${parents+ .map((parent) => {+ if (parent.kind === 'column') {+ return `${quotedTableAlias}.${escapeIdentifier(parent.joinColumnName)} IS NULL`;+ }++ const quotedChildTableAlias = escapeIdentifier(parent.childTableAlias);++ return `NOT EXISTS (SELECT 1 FROM ${parent.childTableExpression} AS ${quotedChildTableAlias} WHERE ${quotedChildTableAlias}.${escapeIdentifier(parent.childJoinColumnName)} = ${quotedTableAlias}."id" AND ${buildChildLinkBoundCondition({ quotedTableAlias, quotedChildTableAlias })})`;+ })+ .join(' AND ')})`;+export const buildInheritedReadabilityCondition = ({tableAlias,objectMetadataId,@@ -42,6 +61,7 @@ export const buildInheritedReadabilityCondition = ({recordShareTableExpression,principalIds,accessLevels,+ isOpenWhenDetached = false,}: {tableAlias: string;objectMetadataId: string;@@ -49,6 +69,7 @@ export const buildInheritedReadabilityCondition = ({recordShareTableExpression: string;principalIds: string[];accessLevels: RecordShareAccessLevel[];+ isOpenWhenDetached?: boolean;}): SqlCondition => {const parameters: ObjectLiteral = {};const quotedTableAlias = escapeIdentifier(tableAlias);@@ -106,8 +127,14 @@ export const buildInheritedReadabilityCondition = ({];});+ // Every link counts towards being attached, a denied parent's included+ const detachedConditions =+ isOpenWhenDetached && parents.length > 0+ ? [buildDetachedCondition({ quotedTableAlias, parents })]+ : [];+return {- sql: `(${[ownRecordShareCondition.sql, ...parentConditions].join(' OR ')})`,+ sql: `(${[ownRecordShareCondition.sql, ...parentConditions, ...detachedConditions].join(' OR ')})`,parameters,};};diff --git a/packages/twenty-server/src/engine/core-modules/record-share/utils/build-record-share-gate.util.ts b/packages/twenty-server/src/engine/core-modules/record-share/utils/build-record-share-gate.util.tsindex e969a9005e0..6292a5449a2 100644--- a/packages/twenty-server/src/engine/core-modules/record-share/utils/build-record-share-gate.util.ts+++ b/packages/twenty-server/src/engine/core-modules/record-share/utils/build-record-share-gate.util.ts@@ -11,6 +11,7 @@ import {type InheritedReadabilityParentCondition,} from 'src/engine/core-modules/record-share/utils/build-inherited-readability-condition.util';import { buildRecordShareCondition } from 'src/engine/core-modules/record-share/utils/build-record-share-condition.util';+import { isOpenWhenDetachedObject } from 'src/engine/core-modules/record-share/utils/is-open-when-detached-object.util';import { resolveInheritedReadabilityParents } from 'src/engine/core-modules/record-share/utils/resolve-inherited-readability-parents.util';import { resolveRequiredRecordShareAccessLevels } from 'src/engine/core-modules/record-share/utils/resolve-required-record-share-access-levels.util';import {@@ -129,8 +130,12 @@ const buildInheritedReadabilityGate = ({return { kind: 'open' };}+ const isOpenWhenDetached = isOpenWhenDetachedObject(flatObjectMetadata);+if (parents.length === 0) {- return buildOwnRecordShareGate(context, target);+ return isOpenWhenDetached+ ? { kind: 'open' }+ : buildOwnRecordShareGate(context, target);}const principals = resolveRecordSharePrincipals(context, target);@@ -155,6 +160,7 @@ const buildInheritedReadabilityGate = ({recordShareTableExpression:context.environment.recordShareTableExpression,...principals,+ isOpenWhenDetached,}),};};diff --git a/packages/twenty-server/src/engine/core-modules/record-share/utils/is-open-when-detached-object.util.ts b/packages/twenty-server/src/engine/core-modules/record-share/utils/is-open-when-detached-object.util.tsnew file mode 100644index 00000000000..3b3fb647ec9--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/record-share/utils/is-open-when-detached-object.util.ts@@ -0,0 +1,11 @@+/* @license Enterprise */++import { OPEN_WHEN_DETACHED_OBJECT_UNIVERSAL_IDENTIFIERS } from 'src/engine/core-modules/record-share/constants/open-when-detached-object-universal-identifiers.constant';+import { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';++export const isOpenWhenDetachedObject = (+ flatObjectMetadata: Pick<FlatObjectMetadata, 'universalIdentifier'>,+): boolean =>+ OPEN_WHEN_DETACHED_OBJECT_UNIVERSAL_IDENTIFIERS.includes(+ flatObjectMetadata.universalIdentifier,+ );diff --git a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/inherited-through-children-readability-object-records-permissions.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/inherited-through-children-readability-object-records-permissions.integration-spec.tsindex 5685749090f..b6a406492b3 100644--- a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/inherited-through-children-readability-object-records-permissions.integration-spec.ts+++ b/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/inherited-through-children-readability-object-records-permissions.integration-spec.ts@@ -51,6 +51,9 @@ const BOTH_PERSON_NOTE_TARGET_ID = randomUUID();const BOTH_COMPANY_NOTE_TARGET_ID = randomUUID();const MEMBER_NOTE_TARGET_ID = randomUUID();const COMPANY_NOTE_ATTACHMENT_ID = randomUUID();+const TASK_ON_PERSON_ID = randomUUID();+const TASK_ALONE_ID = randomUUID();+const PERSON_TASK_TARGET_ID = randomUUID();const PERSON_NOTE_ATTACHMENT_ID = randomUUID();const NOTE_IDS = [@@ -68,6 +71,7 @@ const NOTE_TARGET_IDS = [MEMBER_NOTE_TARGET_ID,];const ATTACHMENT_IDS = [COMPANY_NOTE_ATTACHMENT_ID, PERSON_NOTE_ATTACHMENT_ID];+const TASK_IDS = [TASK_ON_PERSON_ID, TASK_ALONE_ID];const collectIds = (edges: { node: { id: string } }[]): string[] =>edges.map((edge) => edge.node.id).sort();@@ -95,6 +99,13 @@ const findNoteTargetsOperation = findManyOperationFactory({filter: { id: { in: NOTE_TARGET_IDS } },});+const findTasksOperation = findManyOperationFactory({+ objectMetadataSingularName: 'task',+ objectMetadataPluralName: 'tasks',+ gqlFields: 'id',+ filter: { id: { in: TASK_IDS } },+});+const findAttachmentsOperation = findManyOperationFactory({objectMetadataSingularName: 'attachment',objectMetadataPluralName: 'attachments',@@ -163,6 +174,7 @@ describe('inheritedThroughChildrenReadabilityObjectRecordsPermissions', () => {let recordShareStorageService: RecordShareStorageService;let personObjectMetadataId: string;let noteObjectMetadataId: string;+ let taskObjectMetadataId: string;const sourceId = randomUUID();@@ -186,6 +198,11 @@ describe('inheritedThroughChildrenReadabilityObjectRecordsPermissions', () => {where: { workspaceId: SEED_APPLE_WORKSPACE_ID, nameSingular: 'note' },})).id;+ taskObjectMetadataId = (+ await objectMetadataRepository.findOneOrFail({+ where: { workspaceId: SEED_APPLE_WORKSPACE_ID, nameSingular: 'task' },+ })+ ).id;const createRecords = [{@@ -244,6 +261,22 @@ describe('inheritedThroughChildrenReadabilityObjectRecordsPermissions', () => {targetCompanyId: COMPANY_ID,},},+ {+ objectMetadataSingularName: 'task',+ data: { id: TASK_ON_PERSON_ID, title: 'On the private person' },+ },+ {+ objectMetadataSingularName: 'task',+ data: { id: TASK_ALONE_ID, title: 'Attached to nothing' },+ },+ {+ objectMetadataSingularName: 'taskTarget',+ data: {+ id: PERSON_TASK_TARGET_ID,+ taskId: TASK_ON_PERSON_ID,+ targetPersonId: PERSON_ID,+ },+ },{objectMetadataSingularName: 'attachment',data: {@@ -291,6 +324,11 @@ describe('inheritedThroughChildrenReadabilityObjectRecordsPermissions', () => {objectMetadataId: noteObjectMetadataId,recordIds: NOTE_IDS,});+ await recordShareStorageService.deleteByRecordIds({+ workspaceId: SEED_APPLE_WORKSPACE_ID,+ objectMetadataId: taskObjectMetadataId,+ recordIds: TASK_IDS,+ });await setObjectReadability(personObjectMetadataId,MetadataReadability.OPEN,@@ -310,6 +348,16 @@ describe('inheritedThroughChildrenReadabilityObjectRecordsPermissions', () => {objectMetadataPluralName: 'notes',ids: NOTE_IDS,});+ await destroyRecords({+ objectMetadataSingularName: 'taskTarget',+ objectMetadataPluralName: 'taskTargets',+ ids: [PERSON_TASK_TARGET_ID],+ });+ await destroyRecords({+ objectMetadataSingularName: 'task',+ objectMetadataPluralName: 'tasks',+ ids: TASK_IDS,+ });await destroyRecords({objectMetadataSingularName: 'person',objectMetadataPluralName: 'people',@@ -323,7 +371,7 @@ describe('inheritedThroughChildrenReadabilityObjectRecordsPermissions', () => {});describe('without a share row on the person', () => {- it('should show the notes attached to the open company, their company targets and their attachments only', async () => {+ it('should show the notes attached to the open company or to nothing, their company targets and their attachments only', async () => {const notesResponse =await makeGraphqlApiRequestWithMemberRole(findNotesOperation);const noteTargetsResponse = await makeGraphqlApiRequestWithMemberRole(@@ -335,7 +383,7 @@ describe('inheritedThroughChildrenReadabilityObjectRecordsPermissions', () => {expect(notesResponse.body.errors).toBeUndefined();expect(collectIds(notesResponse.body.data.notes.edges)).toEqual(- [NOTE_ON_COMPANY_ID, NOTE_ON_BOTH_ID].sort(),+ [NOTE_ON_COMPANY_ID, NOTE_ON_BOTH_ID, NOTE_ALONE_ID].sort(),);const noteOnBoth = notesResponse.body.data.notes.edges.find(@@ -355,10 +403,63 @@ describe('inheritedThroughChildrenReadabilityObjectRecordsPermissions', () => {).toEqual([COMPANY_NOTE_ATTACHMENT_ID]);});- it('should let the member rename the note on the open company and refuse the one on the private person', async () => {+ it('should show the task attached to nothing and hide the one on the private person, to the query and the event gate alike', async () => {+ const memberRole = await findOneRoleByLabel({ label: 'Member' });+ const { rolesPermissions, flatObjectMetadataMaps } =+ await getAppProviderByClassName<WorkspaceCacheService>(+ 'WorkspaceCacheService',+ ).getOrRecompute(SEED_APPLE_WORKSPACE_ID, [+ 'rolesPermissions',+ 'flatObjectMetadataMaps',+ ]);+ const taskObjectMetadata = findFlatEntityByIdInFlatEntityMaps({+ flatEntityId: taskObjectMetadataId,+ flatEntityMaps: flatObjectMetadataMaps,+ });++ expect(taskObjectMetadata).toBeDefined();++ const recordIdsAdmittedByEventGate =+ await getAppProviderByClassName<RecordAccessPolicyService>(+ 'RecordAccessPolicyService',+ )+ .buildEventRecordAccessGate({+ name: 'task.created',+ workspaceId: SEED_APPLE_WORKSPACE_ID,+ objectMetadata: taskObjectMetadata!,+ events: TASK_IDS.map((id) => ({+ recordId: id,+ properties: { after: { id } },+ })),+ })+ .resolveAdmittedRecordIds({+ isSystemContext: false,+ objectsPermissions: rolesPermissions[memberRole.id],+ principalIds: [+ EVERYONE_PRINCIPAL_ID,+ WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,+ memberRole.id,+ ],+ isOwningApplication: () => false,+ resolveRowLevelPermissionRecordFilter: () => null,+ });+ const tasksResponse =+ await makeGraphqlApiRequestWithMemberRole(findTasksOperation);++ expect(tasksResponse.body.errors).toBeUndefined();+ expect(collectIds(tasksResponse.body.data.tasks.edges)).toEqual([+ TASK_ALONE_ID,+ ]);+ expect([...recordIdsAdmittedByEventGate]).toEqual([TASK_ALONE_ID]);+ });++ it('should let the member rename the notes on the open company or on nothing and refuse the one on the private person', async () => {const companyNoteResponse = await makeGraphqlApiRequestWithMemberRole(renameNoteOperation(NOTE_ON_COMPANY_ID, 'Renamed on the open company'),);+ const aloneNoteResponse = await makeGraphqlApiRequestWithMemberRole(+ renameNoteOperation(NOTE_ALONE_ID, 'Renamed on nothing'),+ );const personNoteResponse = await makeGraphqlApiRequestWithMemberRole(renameNoteOperation(NOTE_ON_PERSON_ID, 'Renamed on the private person'),);@@ -368,6 +469,11 @@ describe('inheritedThroughChildrenReadabilityObjectRecordsPermissions', () => {id: NOTE_ON_COMPANY_ID,title: 'Renamed on the open company',});+ expect(aloneNoteResponse.body.errors).toBeUndefined();+ expect(aloneNoteResponse.body.data.updateNote).toEqual({+ id: NOTE_ALONE_ID,+ title: 'Renamed on nothing',+ });expect(personNoteResponse.body.data?.updateNote ?? null).toBeNull();expect(personNoteResponse.body.errors).toBeDefined();});@@ -407,6 +513,62 @@ describe('inheritedThroughChildrenReadabilityObjectRecordsPermissions', () => {await setRecordSharingEnabled(true);});++ it('should not show a deleted note in the trash through a target detached before its deletion', async () => {+ const noteOnBothFilter = { id: { eq: NOTE_ON_BOTH_ID } };++ const detachResponse = await makeGraphqlApiRequest(+ detachNoteOnBothFromCompanyOperation,+ );+ const deleteResponse = await makeGraphqlApiRequest(+ deleteManyOperationFactory({+ objectMetadataSingularName: 'note',+ objectMetadataPluralName: 'notes',+ gqlFields: 'id',+ filter: noteOnBothFilter,+ }),+ );+ const trashedNotesResponse = await makeGraphqlApiRequestWithMemberRole(+ findManyOperationFactory({+ objectMetadataSingularName: 'note',+ objectMetadataPluralName: 'notes',+ gqlFields: 'id',+ filter: {+ ...noteOnBothFilter,+ not: { deletedAt: { is: 'NULL' } },+ },+ }),+ );+ const restoreNoteResponse = await makeGraphqlApiRequest(+ restoreManyOperationFactory({+ objectMetadataSingularName: 'note',+ objectMetadataPluralName: 'notes',+ gqlFields: 'id',+ filter: noteOnBothFilter,+ }),+ );+ const restoreTargetsResponse = await makeGraphqlApiRequest(+ restoreManyOperationFactory({+ objectMetadataSingularName: 'noteTarget',+ objectMetadataPluralName: 'noteTargets',+ gqlFields: 'id',+ filter: {+ id: {+ in: [BOTH_PERSON_NOTE_TARGET_ID, BOTH_COMPANY_NOTE_TARGET_ID],+ },+ },+ }),+ );++ expect(detachResponse.body.errors).toBeUndefined();+ expect(deleteResponse.body.data.deleteNotes).toEqual([+ { id: NOTE_ON_BOTH_ID },+ ]);+ expect(trashedNotesResponse.body.errors).toBeUndefined();+ expect(trashedNotesResponse.body.data.notes.edges).toEqual([]);+ expect(restoreNoteResponse.body.errors).toBeUndefined();+ expect(restoreTargetsResponse.body.errors).toBeUndefined();+ });});describe('with a READ share row on the person', () => {@@ -427,7 +589,7 @@ describe('inheritedThroughChildrenReadabilityObjectRecordsPermissions', () => {});});- it('should show every attached note, target and attachment and keep the unattached note hidden', async () => {+ it('should show every note, target and attachment', async () => {const notesResponse =await makeGraphqlApiRequestWithMemberRole(findNotesOperation);const noteTargetsResponse = await makeGraphqlApiRequestWithMemberRole(@@ -439,7 +601,12 @@ describe('inheritedThroughChildrenReadabilityObjectRecordsPermissions', () => {expect(notesResponse.body.errors).toBeUndefined();expect(collectIds(notesResponse.body.data.notes.edges)).toEqual(- [NOTE_ON_PERSON_ID, NOTE_ON_COMPANY_ID, NOTE_ON_BOTH_ID].sort(),+ [+ NOTE_ON_PERSON_ID,+ NOTE_ON_COMPANY_ID,+ NOTE_ON_BOTH_ID,+ NOTE_ALONE_ID,+ ].sort(),);expect(noteTargetsResponse.body.errors).toBeUndefined();expect(@@ -482,10 +649,12 @@ describe('inheritedThroughChildrenReadabilityObjectRecordsPermissions', () => {name: 'note.created',workspaceId: SEED_APPLE_WORKSPACE_ID,objectMetadata: noteObjectMetadata!,- events: NOTE_IDS.map((id) => ({- recordId: id,- properties: { after: { id } },- })),+ events: NOTE_IDS.filter((id) => id !== MEMBER_NOTE_ID).map(+ (id) => ({+ recordId: id,+ properties: { after: { id } },+ }),+ ),}).resolveAdmittedRecordIds({isSystemContext: false,@@ -540,7 +709,7 @@ describe('inheritedThroughChildrenReadabilityObjectRecordsPermissions', () => {expect(notesResponse.body.errors).toBeUndefined();expect(collectIds(notesResponse.body.data.notes.edges)).toEqual(- [NOTE_ON_COMPANY_ID, NOTE_ON_BOTH_ID].sort(),+ [NOTE_ON_COMPANY_ID, NOTE_ON_BOTH_ID, NOTE_ALONE_ID].sort(),);expect(noteTargetsResponse.body.errors).toBeUndefined();expect(@@ -624,6 +793,7 @@ describe('inheritedThroughChildrenReadabilityObjectRecordsPermissions', () => {NOTE_ON_PERSON_ID,NOTE_ON_COMPANY_ID,NOTE_ON_BOTH_ID,+ NOTE_ALONE_ID,MEMBER_NOTE_ID,].sort(),);@@ -669,13 +839,14 @@ describe('inheritedThroughChildrenReadabilityObjectRecordsPermissions', () => {deleteManyOperationFactory({objectMetadataSingularName: 'note',objectMetadataPluralName: 'notes',- gqlFields: 'id',+ gqlFields: 'id deletedAt',filter: noteOnPersonFilter,}),);+ const { deletedAt } = deleteResponse.body.data.deleteNotes[0];const deletedNoteEventProperties = {before: { id: NOTE_ON_PERSON_ID },- after: { id: NOTE_ON_PERSON_ID },+ after: { id: NOTE_ON_PERSON_ID, deletedAt },updatedFields: ['deletedAt'],diff: {},};@@ -710,7 +881,7 @@ describe('inheritedThroughChildrenReadabilityObjectRecordsPermissions', () => {expect(deleteResponse.body.errors).toBeUndefined();expect(deleteResponse.body.data.deleteNotes).toEqual([- { id: NOTE_ON_PERSON_ID },+ { id: NOTE_ON_PERSON_ID, deletedAt: expect.any(String) },]);expect(restoreResponse.body.errors).toBeUndefined();expect(restoreResponse.body.data.restoreNotes).toEqual([@@ -720,7 +891,7 @@ describe('inheritedThroughChildrenReadabilityObjectRecordsPermissions', () => {expect([...readableThroughCapturedLinks]).toEqual([NOTE_ON_PERSON_ID]);});- it('should not show a deleted note in the trash through a target detached before its deletion', async () => {+ it('should show a deleted note in the trash when its only target was detached before its deletion', async () => {const noteOnCompanyFilter = { id: { eq: NOTE_ON_COMPANY_ID } };const companyNoteTargetFilter = { id: { eq: COMPANY_NOTE_TARGET_ID } };@@ -786,7 +957,9 @@ describe('inheritedThroughChildrenReadabilityObjectRecordsPermissions', () => {{ id: NOTE_ON_COMPANY_ID },]);expect(trashedNotesResponse.body.errors).toBeUndefined();- expect(trashedNotesResponse.body.data.notes.edges).toEqual([]);+ expect(collectIds(trashedNotesResponse.body.data.notes.edges)).toEqual([+ NOTE_ON_COMPANY_ID,+ ]);expect(restoreNoteResponse.body.errors).toBeUndefined();expect(restoreTargetResponse.body.errors).toBeUndefined();});