Skip to content

The open alternative to Salesforce, designed for AI.

Stop using writability, sharing reach and non-private readability in favor of disabled object permission actions (#29034)

Charles Bochet426939269267
diff --git a/packages/twenty-agent-skills/references/develop-app/data-model.md b/packages/twenty-agent-skills/references/develop-app/data-model.md
index d7c11504d22..e0b3a332daa 100644
--- a/packages/twenty-agent-skills/references/develop-app/data-model.md
+++ b/packages/twenty-agent-skills/references/develop-app/data-model.md
@@ -120,8 +120,7 @@ When adding permissions:
- Grant the smallest useful scope.
- Keep sensitive objects and fields out of broad roles.
- Check whether the app introduces side effects through logic functions before granting write access.
-- To keep some permissions from being granted on an object, set `disabledObjectPermissionActions` on `defineObject()`, for example `['canDestroyObjectRecords']`. Allowed values are the object permission flags: `'canReadObjectRecords'`, `'canUpdateObjectRecords'`, `'canSoftDeleteObjectRecords'` and `'canDestroyObjectRecords'`. It only blocks granting them on that object; roles granting an action on all objects are unaffected.
-- For sensitive objects, set `sharingReach: ObjectSharingReach.ROLE_ACCESS` on `defineObject()` (imported from `twenty-sdk/define`) so records can only be shared with people whose role already reaches them. The default, `ObjectSharingReach.WORKSPACE`, lets a record be shared with anyone in the workspace. It only matters while record sharing is enabled, and objects with `APPLICATION` or `SYSTEM` readability are never shared.
+- To keep some permissions from being granted on an object, set `disabledObjectPermissionActions` on `defineObject()`, for example `['canDestroyObjectRecords']`. Allowed values are the object permission flags: `'canReadObjectRecords'`, `'canUpdateObjectRecords'`, `'canSoftDeleteObjectRecords'` and `'canDestroyObjectRecords'`. Users, API keys and agents never get these actions on that object, whatever their role grants; the app's own logic functions keep them. List the update, soft-delete and destroy flags to make an object only the app can write.
## Verification
diff --git a/packages/twenty-docs/developers/extend/apps/data/extending-objects.mdx b/packages/twenty-docs/developers/extend/apps/data/extending-objects.mdx
index 4673c1b27bb..5160dba85c2 100644
--- a/packages/twenty-docs/developers/extend/apps/data/extending-objects.mdx
+++ b/packages/twenty-docs/developers/extend/apps/data/extending-objects.mdx
@@ -44,7 +44,6 @@ export default defineField({
- `defineField()` is the only way to add fields to objects you didn't create with `defineObject()`.
- `SELECT` and `MULTI_SELECT` follow the same [option validation and color rules](/developers/extend/apps/data/objects#select-options) as inline fields. An omitted or null color defaults to `gray`; unsupported colors are rejected.
- File location is up to you. The convention is `src/fields/<name>.field.ts`, but the CLI detects fields anywhere in `src/`.
-- `writability` can also be set per field: `MetadataWritability.APPLICATION` restricts writes to your app's own logic functions, `MetadataWritability.SYSTEM` is reserved for platform-managed data. A field's writability can only be stricter than its object's level, and reads are unaffected. See [Objects](/developers/extend/apps/data/objects) for the full semantics.
- `isSearchable: true` can be set on `defineField()` with the same constraints as inline fields (searchable target object, text-compatible field type), so records of the target object become findable through your field's values in full-text search.
- `isAuditLogged: false` can be set on `defineField()` to keep the field's changes out of the target record's timeline, which matters most for fields your app rewrites on a schedule.
- To add a tab to a standard page layout (e.g. the Task or Company detail page), use [`definePageLayoutTab`](/developers/extend/apps/layout/page-layouts#definepagelayouttab) with `STANDARD_PAGE_LAYOUT_UNIVERSAL_IDENTIFIERS` from `twenty-sdk/define`.
diff --git a/packages/twenty-docs/developers/extend/apps/data/objects.mdx b/packages/twenty-docs/developers/extend/apps/data/objects.mdx
index 4a6417e8d3e..d52f7ef9b2a 100644
--- a/packages/twenty-docs/developers/extend/apps/data/objects.mdx
+++ b/packages/twenty-docs/developers/extend/apps/data/objects.mdx
@@ -103,17 +103,7 @@ export default defineObject({
- Each field requires a `name`, `type`, `label`, and its own stable `universalIdentifier`.
- The `fields` array is optional — you can define objects without custom fields.
- `openRecordIn` sets where records of this object open when clicked: `ObjectOpenRecordIn.USER_CHOICE` (the default, following each workspace member's own preference from Settings → Experience), `ObjectOpenRecordIn.SIDE_PANEL`, or `ObjectOpenRecordIn.RECORD_PAGE`. Pin it to `RECORD_PAGE` for records that need a full page to be usable, the way workflows and dashboards do, or to `SIDE_PANEL` for records that only make sense as a quick panel, the way calendar events do.
-- `writability` controls who may write records of the object at all, before role permissions apply: `MetadataWritability.OPEN` (the default — workspace roles decide), `MetadataWritability.APPLICATION` (only your app's own logic functions can create, update, or delete records; use this for configuration-like objects whose records grant behavior, so workspace members with broad record access cannot edit them through the API), or `MetadataWritability.SYSTEM` (reserved for platform-managed data). Reads are unaffected — this is enforced server-side, unlike `isUIEditable`, which only hides UI affordances. It also exists per field, where it can only be stricter than the object's level.
-- `readability` declares who may read records of the object: `MetadataReadability.OPEN` (the default — workspace roles decide), `MetadataReadability.PRIVATE` (only principals the record was shared with), `MetadataReadability.INHERITED` (whoever reads the parent record), `MetadataReadability.APPLICATION` (only your app's own logic functions) or `MetadataReadability.SYSTEM` (platform-managed data). All readability policies are always enforced.
-- `readabilityParentFieldUniversalIdentifiers` goes with `MetadataReadability.INHERITED`: the universal identifiers of the relation fields that lead to the parent records.
- - A many-to-one field names the record the row points to. Declaring one field of a morph relation covers every target of that relation.
- - A one-to-many field names a child object whose rows point back at the record, such as the join rows of a many-to-many relation. The record is then readable when at least one of those rows leads to a readable record: a note follows the people, companies and opportunities its note targets attach it to.
- - Several parents combine as a union: one readable parent is enough.
- - A parent grants access under its complete policy, the one a query of the parent applies: the reader's permission on the parent object, the row-level restrictions of their role and the parent's own readability. A record never shows through a parent its reader could not query. Subscriptions, webhooks, workflows and logic functions decide what an event of an `INHERITED` record reaches by that same policy.
- - The share rows on the record itself grant access exactly as on a `PRIVATE` record. Its creator gets one when the record is created while record sharing is enabled, so whoever created a record keeps seeing it, and a record whose parent fields are all empty is visible to those it was shared with directly.
- - An `INHERITED` object that names no usable parent field behaves like a `PRIVATE` one.
-- `sharingReach` sets how far a record of the object can be shared by name: `ObjectSharingReach.WORKSPACE` (the default, a record can be shared with anyone in the workspace, even someone whose role cannot access the object or whose row-level filter hides the record; they get that record only, to view or edit) or `ObjectSharingReach.ROLE_ACCESS` (shares never go beyond role and row-level permissions). Pick `ROLE_ACCESS` for sensitive objects where no access must mean no access. Roles that can update all settings see every record of an `OPEN` object whatever its sharing restrictions; their object permissions and row-level filters still apply. It only applies while record sharing is enabled in the workspace, and only to objects whose records can be shared: `MetadataReadability.OPEN`, `PRIVATE` and `INHERITED` objects that are not system objects. `APPLICATION` and `SYSTEM` objects are never shared.
-- `disabledObjectPermissionActions` lists object permissions that cannot be granted on the object: any of `'canReadObjectRecords'`, `'canUpdateObjectRecords'`, `'canSoftDeleteObjectRecords'` and `'canDestroyObjectRecords'`, the same flags a role sets per object. Saving an object permission that grants one of them on this object fails, for example `disabledObjectPermissionActions: ['canDestroyObjectRecords']` keeps any role from being given destroy on it specifically. It does not change what roles granting an action on all objects can do.
+- `disabledObjectPermissionActions` lists object permissions that cannot be granted on the object: any of `'canReadObjectRecords'`, `'canUpdateObjectRecords'`, `'canSoftDeleteObjectRecords'` and `'canDestroyObjectRecords'`, the same flags a role sets per object. Users, API keys and agents never get these actions on the object, whatever their role grants, and saving an object permission that grants one of them fails. Your app's own logic functions keep them. For example, `['canUpdateObjectRecords', 'canSoftDeleteObjectRecords', 'canDestroyObjectRecords']` makes an object only your app can write, for configuration-like records that grant behavior.
- `color` sets the accent color of the object in the UI. Omit it and Twenty picks one for the object.
- `imageIdentifierFieldMetadataUniversalIdentifier` names the field whose value is shown as the record avatar. Omit it to let Twenty pick the default.
- `isLabelSyncedWithName`, on an object or on a field, keeps the API name in sync with the label when the label is edited in Settings. It defaults to `false`, so a renamed label leaves the name untouched.
diff --git a/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx b/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx
index b9e56e930e9..0ee1fafc1a4 100644
--- a/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx
+++ b/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx
@@ -1040,7 +1040,7 @@ const { createCompany } = await client.mutation({
},
});
-// Only on an object whose readability is PRIVATE: choose who can read the created record
+// Only on an object whose records are private: choose who can read the created record
const { createContract } = await client.mutation({
createContract: {
__args: {
@@ -1059,7 +1059,7 @@ const { createContract } = await client.mutation({
});
```
-`shareWith` only matters on an object whose readability is `PRIVATE`; every object is `OPEN` by default, and on an `OPEN` object the argument is ignored. On a `PRIVATE` object it lists who gets access to the created record: each entry targets exactly one of `workspaceMemberId`, `roleId` or `everyone: true` with an `accessLevel` of `READ`, `READ_WRITE` or `FULL`. A workspace member creating a record always receives a `FULL` owner grant, so the argument is optional for them; a logic function acting as its application or an API key also receives a `FULL` grant for its role, and such callers, like a system caller, must pass `shareWith` or the create is rejected. Every entry must name a member or a role of the workspace. A logic function or API key shares through its role, so every holder of that role gets the same access to the records it creates; give a key whose records must stay private to it a role of its own.
+`shareWith` only matters on an object whose records are private; elsewhere the argument is ignored. On such an object it lists who gets access to the created record: each entry targets exactly one of `workspaceMemberId`, `roleId` or `everyone: true` with an `accessLevel` of `READ`, `READ_WRITE` or `FULL`. A workspace member creating a record always receives a `FULL` owner grant, so the argument is optional for them; a logic function acting as its application or an API key also receives a `FULL` grant for its role, and such callers, like a system caller, must pass `shareWith` or the create is rejected. Every entry must name a member or a role of the workspace. A logic function or API key shares through its role, so every holder of that role gets the same access to the records it creates; give a key whose records must stay private to it a role of its own.
The client uses a selection-set syntax: pass `true` to include a field, use `__args` for arguments, and nest objects for relations. You get full autocompletion and type checking based on your workspace schema.
diff --git a/packages/twenty-front/src/modules/command-menu-item/hooks/useCurrentCommandMenuContextApi.ts b/packages/twenty-front/src/modules/command-menu-item/hooks/useCurrentCommandMenuContextApi.ts
index 7178b6c501a..93f00750e7d 100644
--- a/packages/twenty-front/src/modules/command-menu-item/hooks/useCurrentCommandMenuContextApi.ts
+++ b/packages/twenty-front/src/modules/command-menu-item/hooks/useCurrentCommandMenuContextApi.ts
@@ -16,7 +16,6 @@ import { useNavigationMenuItemsData } from '@/navigation-menu-item/display/hooks
import { useObjectMetadataItems } from '@/object-metadata/hooks/useObjectMetadataItems';
import { useObjectPermissionsForObject } from '@/object-record/hooks/useObjectPermissionsForObject';
import { isLayoutCustomizationModeEnabledState } from '@/layout-customization/states/isLayoutCustomizationModeEnabledState';
-import { restrictObjectPermissionsToMetadataWritability } from '@/object-record/read-only/utils/restrictObjectPermissionsToMetadataWritability';
import { hasAnySoftDeleteFilterOnViewComponentSelector } from '@/object-record/record-filter/states/hasAnySoftDeleteFilterOnView';
import { recordPermissionsByRecordIdFamilySelector } from '@/object-record/record-sharing/states/recordPermissionsByRecordIdFamilySelector';
import { type ObjectRecord } from '@/object-record/types/ObjectRecord';
@@ -145,10 +144,7 @@ export const useCurrentCommandMenuContextApi = (): CommandMenuContextApi => {
objectMetadataItem?.id ?? '',
);
const objectPermissions = isDefined(objectMetadataItem)
- ? restrictObjectPermissionsToMetadataWritability({
- objectPermissions: currentObjectPermissions,
- writability: objectMetadataItem.writability,
- })
+ ? currentObjectPermissions
: EMPTY_COMMAND_MENU_CONTEXT_API.objectPermissions;
const contextStoreCurrentViewId = useAtomComponentStateValue(
diff --git a/packages/twenty-front/src/modules/command-menu-item/utils/__tests__/buildGlobalRecordCreationCommandMenuItems.test.ts b/packages/twenty-front/src/modules/command-menu-item/utils/__tests__/buildGlobalRecordCreationCommandMenuItems.test.ts
index 785e7d2e39b..94f3ee38a13 100644
--- a/packages/twenty-front/src/modules/command-menu-item/utils/__tests__/buildGlobalRecordCreationCommandMenuItems.test.ts
+++ b/packages/twenty-front/src/modules/command-menu-item/utils/__tests__/buildGlobalRecordCreationCommandMenuItems.test.ts
@@ -1,10 +1,7 @@
// oxlint-disable twenty/folder-structure -- Utility specs intentionally live beside their implementation.
import { buildGlobalRecordCreationCommandMenuItems } from '@/command-menu-item/utils/buildGlobalRecordCreationCommandMenuItems';
import { getObjectPermissionsForObject } from '@/object-metadata/utils/getObjectPermissionsForObject';
-import {
- EngineComponentKey,
- MetadataWritability,
-} from '~/generated-metadata/graphql';
+import { EngineComponentKey } from '~/generated-metadata/graphql';
import { mockedCommandMenuItems } from '~/testing/mock-data/generated/metadata/command-menu-items/mock-command-menu-items-data';
const createRecordCommand = mockedCommandMenuItems.find(
@@ -19,19 +16,8 @@ const objects = [
{ id: 'remote', labelSingular: 'remote', isRemote: true },
{ id: 'readonly', labelSingular: 'readonly', isUIEditable: false },
{ id: 'internal', labelSingular: 'internal', isUICreatable: false },
- {
- id: 'system',
- labelSingular: 'system',
- writability: MetadataWritability.SYSTEM,
- },
- {
- id: 'application',
- labelSingular: 'application',
- writability: MetadataWritability.APPLICATION,
- },
].map((objectMetadataItem) => ({
icon: null,
- writability: MetadataWritability.OPEN,
isUICreatable: true,
isUIEditable: true,
isRemote: false,
diff --git a/packages/twenty-front/src/modules/command-menu-item/utils/buildGlobalRecordCreationCommandMenuItems.ts b/packages/twenty-front/src/modules/command-menu-item/utils/buildGlobalRecordCreationCommandMenuItems.ts
index a0948ecd7fc..7f323418e36 100644
--- a/packages/twenty-front/src/modules/command-menu-item/utils/buildGlobalRecordCreationCommandMenuItems.ts
+++ b/packages/twenty-front/src/modules/command-menu-item/utils/buildGlobalRecordCreationCommandMenuItems.ts
@@ -15,7 +15,6 @@ type BuildGlobalRecordCreationCommandMenuItemsParams = {
| 'isUICreatable'
| 'isUIEditable'
| 'isRemote'
- | 'writability'
>[];
objectPermissionsByObjectMetadataId: Record<
string,
diff --git a/packages/twenty-front/src/modules/object-record/read-only/utils/__tests__/isObjectMetadataReadOnly.test.ts b/packages/twenty-front/src/modules/object-record/read-only/utils/__tests__/isObjectMetadataReadOnly.test.ts
index 1a93cfdbb21..8630148e99f 100644
--- a/packages/twenty-front/src/modules/object-record/read-only/utils/__tests__/isObjectMetadataReadOnly.test.ts
+++ b/packages/twenty-front/src/modules/object-record/read-only/utils/__tests__/isObjectMetadataReadOnly.test.ts
@@ -1,5 +1,4 @@
import { isObjectMetadataReadOnly } from '@/object-record/read-only/utils/isObjectMetadataReadOnly';
-import { MetadataWritability } from '~/generated-metadata/graphql';
describe('isObjectMetadataReadOnly', () => {
it('should return false if object can be updated and is not UI read only and is not remote', () => {
@@ -10,7 +9,6 @@ describe('isObjectMetadataReadOnly', () => {
objectMetadataItem: {
isUIEditable: true,
isRemote: false,
- writability: MetadataWritability.OPEN,
},
});
@@ -25,7 +23,6 @@ describe('isObjectMetadataReadOnly', () => {
objectMetadataItem: {
isUIEditable: true,
isRemote: false,
- writability: MetadataWritability.OPEN,
},
});
@@ -40,7 +37,6 @@ describe('isObjectMetadataReadOnly', () => {
objectMetadataItem: {
isUIEditable: false,
isRemote: false,
- writability: MetadataWritability.OPEN,
},
});
@@ -55,7 +51,6 @@ describe('isObjectMetadataReadOnly', () => {
objectMetadataItem: {
isUIEditable: true,
isRemote: true,
- writability: MetadataWritability.OPEN,
},
});
@@ -67,25 +62,9 @@ describe('isObjectMetadataReadOnly', () => {
objectMetadataItem: {
isUIEditable: true,
isRemote: false,
- writability: MetadataWritability.OPEN,
},
});
expect(result).toBe(false);
});
-
- it('should return true if object metadata writability is not OPEN', () => {
- const result = isObjectMetadataReadOnly({
- objectPermissions: {
- canUpdateObjectRecords: true,
- },
- objectMetadataItem: {
- isUIEditable: true,
- isRemote: false,
- writability: MetadataWritability.SYSTEM,
- },
- });
-
- expect(result).toBe(true);
- });
});
diff --git a/packages/twenty-front/src/modules/object-record/read-only/utils/__tests__/isObjectReadOnly.test.ts b/packages/twenty-front/src/modules/object-record/read-only/utils/__tests__/isObjectReadOnly.test.ts
index e56184868e4..871e0829c05 100644
--- a/packages/twenty-front/src/modules/object-record/read-only/utils/__tests__/isObjectReadOnly.test.ts
+++ b/packages/twenty-front/src/modules/object-record/read-only/utils/__tests__/isObjectReadOnly.test.ts
@@ -1,10 +1,8 @@
import { isObjectReadOnly } from '@/object-record/read-only/utils/isObjectReadOnly';
-import { MetadataWritability } from '~/generated-metadata/graphql';
const editableObjectMetadataItem = {
isUIEditable: true,
isRemote: false,
- writability: MetadataWritability.OPEN,
};
describe('isObjectReadOnly', () => {
diff --git a/packages/twenty-front/src/modules/object-record/read-only/utils/__tests__/isRecordFieldReadOnly.test.ts b/packages/twenty-front/src/modules/object-record/read-only/utils/__tests__/isRecordFieldReadOnly.test.ts
index f4cee1f13a3..06e58178bfa 100644
--- a/packages/twenty-front/src/modules/object-record/read-only/utils/__tests__/isRecordFieldReadOnly.test.ts
+++ b/packages/twenty-front/src/modules/object-record/read-only/utils/__tests__/isRecordFieldReadOnly.test.ts
@@ -2,11 +2,7 @@ import { type ObjectPermissionsWithObjectMetadataId } from '@/object-metadata/ty
import { isRecordFieldReadOnly } from '@/object-record/read-only/utils/isRecordFieldReadOnly';
import { type FieldDefinition } from '@/object-record/record-field/ui/types/FieldDefinition';
import { type FieldRelationMetadata } from '@/object-record/record-field/ui/types/FieldMetadata';
-import {
- FieldMetadataType,
- MetadataWritability,
- RelationType,
-} from '~/generated-metadata/graphql';
+import { FieldMetadataType, RelationType } from '~/generated-metadata/graphql';
const OBJECT_METADATA_ID = 'object-metadata-id';
const TARGET_OBJECT_METADATA_ID = 'target-object-metadata-id';
@@ -33,7 +29,6 @@ const baseParams = {
fieldMetadataItem: {
id: FIELD_METADATA_ID,
isUIEditable: true,
- writability: MetadataWritability.OPEN,
},
objectPermissionsByObjectMetadataId: {
[OBJECT_METADATA_ID]: buildObjectPermissions(),
@@ -115,42 +110,6 @@ describe('isRecordFieldReadOnly', () => {
expect(isRecordFieldReadOnly(baseParams)).toBe(false);
});
- it('should return true when the field writability is SYSTEM', () => {
- expect(
- isRecordFieldReadOnly({
- ...baseParams,
- fieldMetadataItem: {
- ...baseParams.fieldMetadataItem,
- writability: MetadataWritability.SYSTEM,
- },
- }),
- ).toBe(true);
- });
-
- it('should return true when the field writability is APPLICATION', () => {
- expect(
- isRecordFieldReadOnly({
- ...baseParams,
- fieldMetadataItem: {
- ...baseParams.fieldMetadataItem,
- writability: MetadataWritability.APPLICATION,
- },
- }),
- ).toBe(true);
- });
-
- it('should treat a missing field writability as OPEN', () => {
- expect(
- isRecordFieldReadOnly({
- ...baseParams,
- fieldMetadataItem: {
- ...baseParams.fieldMetadataItem,
- writability: undefined,
- },
- }),
- ).toBe(false);
- });
-
it('should return true for a one-to-many relation whose target object cannot be updated', () => {
expect(
isRecordFieldReadOnly({
diff --git a/packages/twenty-front/src/modules/object-record/read-only/utils/__tests__/isRecordReadonly.test.ts b/packages/twenty-front/src/modules/object-record/read-only/utils/__tests__/isRecordReadonly.test.ts
index bbd82f74d12..8b108a8ef13 100644
--- a/packages/twenty-front/src/modules/object-record/read-only/utils/__tests__/isRecordReadonly.test.ts
+++ b/packages/twenty-front/src/modules/object-record/read-only/utils/__tests__/isRecordReadonly.test.ts
@@ -1,5 +1,4 @@
import { isRecordReadOnly } from '@/object-record/read-only/utils/isRecordReadOnly';
-import { MetadataWritability } from '~/generated-metadata/graphql';
describe('isRecordReadOnly', () => {
it('should return false if record is not deleted, has update permissions and object metadata is not read only', () => {
@@ -11,7 +10,6 @@ describe('isRecordReadOnly', () => {
objectMetadataItem: {
isUIEditable: true,
isRemote: false,
- writability: MetadataWritability.OPEN,
},
});
@@ -27,7 +25,6 @@ describe('isRecordReadOnly', () => {
objectMetadataItem: {
isUIEditable: true,
isRemote: false,
- writability: MetadataWritability.OPEN,
},
});
@@ -43,7 +40,6 @@ describe('isRecordReadOnly', () => {
objectMetadataItem: {
isUIEditable: true,
isRemote: false,
- writability: MetadataWritability.OPEN,
},
});
@@ -59,7 +55,6 @@ describe('isRecordReadOnly', () => {
objectMetadataItem: {
isUIEditable: false,
isRemote: false,
- writability: MetadataWritability.OPEN,
},
});
@@ -75,7 +70,6 @@ describe('isRecordReadOnly', () => {
objectMetadataItem: {
isUIEditable: true,
isRemote: true,
- writability: MetadataWritability.OPEN,
},
});
diff --git a/packages/twenty-front/src/modules/object-record/read-only/utils/__tests__/restrictObjectPermissionsToMetadataWritability.test.ts b/packages/twenty-front/src/modules/object-record/read-only/utils/__tests__/restrictObjectPermissionsToMetadataWritability.test.ts
deleted file mode 100644
index 4838a5ddd6e..00000000000
--- a/packages/twenty-front/src/modules/object-record/read-only/utils/__tests__/restrictObjectPermissionsToMetadataWritability.test.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import { restrictObjectPermissionsToMetadataWritability } from '@/object-record/read-only/utils/restrictObjectPermissionsToMetadataWritability';
-import { type ObjectPermissions } from 'twenty-shared/types';
-import { MetadataWritability } from '~/generated-metadata/graphql';
-
-const FULL_OBJECT_PERMISSIONS: ObjectPermissions = {
- canReadObjectRecords: true,
- canUpdateObjectRecords: true,
- canSoftDeleteObjectRecords: true,
- canDestroyObjectRecords: true,
- restrictedFields: {},
- rowLevelPermissionPredicates: [],
- rowLevelPermissionPredicateGroups: [],
-};
-
-describe('restrictObjectPermissionsToMetadataWritability', () => {
- it.each([MetadataWritability.OPEN, null, undefined])(
- 'should keep permissions when writability is %s',
- (writability) => {
- expect(
- restrictObjectPermissionsToMetadataWritability({
- objectPermissions: FULL_OBJECT_PERMISSIONS,
- writability,
- }),
- ).toBe(FULL_OBJECT_PERMISSIONS);
- },
- );
-
- it.each([MetadataWritability.APPLICATION, MetadataWritability.SYSTEM])(
- 'should revoke write permissions when writability is %s',
- (writability) => {
- expect(
- restrictObjectPermissionsToMetadataWritability({
- objectPermissions: FULL_OBJECT_PERMISSIONS,
- writability,
- }),
- ).toEqual({
- ...FULL_OBJECT_PERMISSIONS,
- canUpdateObjectRecords: false,
- canSoftDeleteObjectRecords: false,
- canDestroyObjectRecords: false,
- });
- },
- );
-});
diff --git a/packages/twenty-front/src/modules/object-record/read-only/utils/internal/isMetadataWritabilityRestricted.ts b/packages/twenty-front/src/modules/object-record/read-only/utils/internal/isMetadataWritabilityRestricted.ts
deleted file mode 100644
index b9023c360a9..00000000000
--- a/packages/twenty-front/src/modules/object-record/read-only/utils/internal/isMetadataWritabilityRestricted.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import { isDefined } from 'twenty-shared/utils';
-import { MetadataWritability } from '~/generated-metadata/graphql';
-
-// Only OPEN accepts user-session writes: APPLICATION is reserved to the owning app, SYSTEM to the platform.
-// Missing writability predates the flag and means OPEN.
-export const isMetadataWritabilityRestricted = (
- writability: MetadataWritability | null | undefined,
-): boolean =>
- isDefined(writability) && writability !== MetadataWritability.OPEN;
diff --git a/packages/twenty-front/src/modules/object-record/read-only/utils/isObjectMetadataReadOnly.ts b/packages/twenty-front/src/modules/object-record/read-only/utils/isObjectMetadataReadOnly.ts
index 5a71ac87a70..ea4c69a1076 100644
--- a/packages/twenty-front/src/modules/object-record/read-only/utils/isObjectMetadataReadOnly.ts
+++ b/packages/twenty-front/src/modules/object-record/read-only/utils/isObjectMetadataReadOnly.ts
@@ -1,5 +1,4 @@
import { type EnrichedObjectMetadataItem } from '@/object-metadata/types/EnrichedObjectMetadataItem';
-import { isMetadataWritabilityRestricted } from '@/object-record/read-only/utils/internal/isMetadataWritabilityRestricted';
import { type ObjectPermissions } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
@@ -7,7 +6,7 @@ type IsObjectMetadataReadOnlyParams = {
objectPermissions?: Pick<ObjectPermissions, 'canUpdateObjectRecords'>;
objectMetadataItem?: Pick<
EnrichedObjectMetadataItem,
- 'isUIEditable' | 'isRemote' | 'writability'
+ 'isUIEditable' | 'isRemote'
>;
};
@@ -19,8 +18,6 @@ export const isObjectMetadataReadOnly = ({
(isDefined(objectPermissions) &&
!objectPermissions.canUpdateObjectRecords) ||
(isDefined(objectMetadataItem) &&
- (!objectMetadataItem.isUIEditable ||
- objectMetadataItem.isRemote ||
- isMetadataWritabilityRestricted(objectMetadataItem.writability)))
+ (!objectMetadataItem.isUIEditable || objectMetadataItem.isRemote))
);
};
diff --git a/packages/twenty-front/src/modules/object-record/read-only/utils/isObjectReadOnly.ts b/packages/twenty-front/src/modules/object-record/read-only/utils/isObjectReadOnly.ts
index e8f926922d4..a41c1367bd5 100644
--- a/packages/twenty-front/src/modules/object-record/read-only/utils/isObjectReadOnly.ts
+++ b/packages/twenty-front/src/modules/object-record/read-only/utils/isObjectReadOnly.ts
@@ -7,7 +7,7 @@ type IsObjectReadOnlyParams = {
objectPermissions: Pick<ObjectPermissions, 'canUpdateObjectRecords'>;
objectMetadataItem: Pick<
EnrichedObjectMetadataItem,
- 'isUIEditable' | 'isRemote' | 'writability'
+ 'isUIEditable' | 'isRemote'
>;
};
diff --git a/packages/twenty-front/src/modules/object-record/read-only/utils/isRecordFieldReadOnly.ts b/packages/twenty-front/src/modules/object-record/read-only/utils/isRecordFieldReadOnly.ts
index 61004d67bcf..d434206cfa5 100644
--- a/packages/twenty-front/src/modules/object-record/read-only/utils/isRecordFieldReadOnly.ts
+++ b/packages/twenty-front/src/modules/object-record/read-only/utils/isRecordFieldReadOnly.ts
@@ -2,7 +2,6 @@ import { type FieldMetadataItem } from '@/object-metadata/types/FieldMetadataIte
import { type ObjectPermissionsByObjectMetadataId } from '@/object-metadata/types/ObjectPermissionsByObjectMetadataId';
import { getFieldPermissions } from '@/object-metadata/utils/getFieldPermissions';
import { getObjectPermissionsForObject } from '@/object-metadata/utils/getObjectPermissionsForObject';
-import { isMetadataWritabilityRestricted } from '@/object-record/read-only/utils/internal/isMetadataWritabilityRestricted';
import { isOneToManyRelationFieldReadOnlyDueToTargetUpdatePermission } from '@/object-record/read-only/utils/isOneToManyRelationFieldReadOnlyDueToTargetUpdatePermission';
import { type FieldDefinition } from '@/object-record/record-field/ui/types/FieldDefinition';
import { type FieldMetadata } from '@/object-record/record-field/ui/types/FieldMetadata';
@@ -11,10 +10,7 @@ import { isDefined } from 'twenty-shared/utils';
type IsRecordFieldReadOnlyParams = {
isRecordReadOnly: boolean;
objectMetadataId: string;
- fieldMetadataItem: Pick<
- FieldMetadataItem,
- 'id' | 'isUIEditable' | 'writability'
- >;
+ fieldMetadataItem: Pick<FieldMetadataItem, 'id' | 'isUIEditable'>;
objectPermissionsByObjectMetadataId: ObjectPermissionsByObjectMetadataId;
fieldDefinition?: FieldDefinition<FieldMetadata>;
};
@@ -26,11 +22,7 @@ export const isRecordFieldReadOnly = ({
objectPermissionsByObjectMetadataId,
fieldDefinition,
}: IsRecordFieldReadOnlyParams) => {
- if (
- isRecordReadOnly ||
- !(fieldMetadataItem.isUIEditable ?? true) ||
- isMetadataWritabilityRestricted(fieldMetadataItem.writability)
- ) {
+ if (isRecordReadOnly || !(fieldMetadataItem.isUIEditable ?? true)) {
return true;
}
diff --git a/packages/twenty-front/src/modules/object-record/read-only/utils/isRecordReadOnly.ts b/packages/twenty-front/src/modules/object-record/read-only/utils/isRecordReadOnly.ts
index 0c54db9bce0..3633f09a1ea 100644
--- a/packages/twenty-front/src/modules/object-record/read-only/utils/isRecordReadOnly.ts
+++ b/packages/twenty-front/src/modules/object-record/read-only/utils/isRecordReadOnly.ts
@@ -6,7 +6,7 @@ export type IsObjectReadOnlyParams = {
objectPermissions: Pick<ObjectPermissions, 'canUpdateObjectRecords'>;
objectMetadataItem: Pick<
EnrichedObjectMetadataItem,
- 'isUIEditable' | 'isRemote' | 'writability'
+ 'isUIEditable' | 'isRemote'
>;
isRecordDeleted: boolean;
};
diff --git a/packages/twenty-front/src/modules/object-record/read-only/utils/restrictObjectPermissionsToMetadataWritability.ts b/packages/twenty-front/src/modules/object-record/read-only/utils/restrictObjectPermissionsToMetadataWritability.ts
deleted file mode 100644
index 92ce12300b8..00000000000
--- a/packages/twenty-front/src/modules/object-record/read-only/utils/restrictObjectPermissionsToMetadataWritability.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import { isMetadataWritabilityRestricted } from '@/object-record/read-only/utils/internal/isMetadataWritabilityRestricted';
-import { type ObjectPermissions } from 'twenty-shared/types';
-import { type MetadataWritability } from '~/generated-metadata/graphql';
-
-type RestrictObjectPermissionsToMetadataWritabilityParams<
- TObjectPermissions extends ObjectPermissions,
-> = {
- objectPermissions: TObjectPermissions;
- writability: MetadataWritability | null | undefined;
-};
-
-export const restrictObjectPermissionsToMetadataWritability = <
- TObjectPermissions extends ObjectPermissions,
->({
- objectPermissions,
- writability,
-}: RestrictObjectPermissionsToMetadataWritabilityParams<TObjectPermissions>): TObjectPermissions => {
- if (!isMetadataWritabilityRestricted(writability)) {
- return objectPermissions;
- }
-
- return {
- ...objectPermissions,
- canUpdateObjectRecords: false,
- canSoftDeleteObjectRecords: false,
- canDestroyObjectRecords: false,
- };
-};
diff --git a/packages/twenty-front/src/modules/object-record/record-sharing/hooks/__tests__/useCanReadObjectRecordsOrSharedRecords.test.ts b/packages/twenty-front/src/modules/object-record/record-sharing/hooks/__tests__/useCanReadObjectRecordsOrSharedRecords.test.ts
index e4e81f6914e..5b49439111e 100644
--- a/packages/twenty-front/src/modules/object-record/record-sharing/hooks/__tests__/useCanReadObjectRecordsOrSharedRecords.test.ts
+++ b/packages/twenty-front/src/modules/object-record/record-sharing/hooks/__tests__/useCanReadObjectRecordsOrSharedRecords.test.ts
@@ -1,10 +1,7 @@
+import { type EnrichedObjectMetadataItem } from '@/object-metadata/types/EnrichedObjectMetadataItem';
import { renderHook } from '@testing-library/react';
import { useCanReadObjectRecordsOrSharedRecords } from '@/object-record/record-sharing/hooks/useCanReadObjectRecordsOrSharedRecords';
-import {
- MetadataReadability,
- ObjectSharingReach,
-} from '~/generated-metadata/graphql';
const mockIsRecordLevelSharingEnabled = jest.fn();
const mockCanReadObjectRecords = jest.fn();
@@ -19,18 +16,14 @@ jest.mock('@/object-record/hooks/useObjectPermissionsForObject', () => ({
}));
const renderCanRead = (
- objectMetadataItem: Partial<{
- isSystem: boolean;
- readability: MetadataReadability;
- sharingReach: ObjectSharingReach;
- }> = {},
+ objectMetadataItem: Partial<
+ Pick<EnrichedObjectMetadataItem, 'isSystem'>
+ > = {},
) =>
renderHook(() =>
useCanReadObjectRecordsOrSharedRecords({
id: 'object-id',
isSystem: false,
- readability: MetadataReadability.OPEN,
- sharingReach: ObjectSharingReach.WORKSPACE,
...objectMetadataItem,
}),
).result.current;
@@ -48,16 +41,10 @@ describe('useCanReadObjectRecordsOrSharedRecords', () => {
expect(renderCanRead()).toBe(true);
});
- it('allows reading shared records when the object can be shared with anyone', () => {
+ it('allows reading shared records when the object can be shared', () => {
expect(renderCanRead()).toBe(true);
});
- it('denies when sharing stays within role access', () => {
- expect(
- renderCanRead({ sharingReach: ObjectSharingReach.ROLE_ACCESS }),
- ).toBe(false);
- });
-
it.each([true, false])(
'denies on system objects with record sharing enabled: %s',
(isRecordLevelSharingEnabled) => {
@@ -69,13 +56,6 @@ describe('useCanReadObjectRecordsOrSharedRecords', () => {
},
);
- it.each([MetadataReadability.APPLICATION, MetadataReadability.SYSTEM])(
- 'denies on %s objects, whose records are never shared',
- (readability) => {
- expect(renderCanRead({ readability })).toBe(false);
- },
- );
-
it('denies when record sharing is disabled', () => {
mockIsRecordLevelSharingEnabled.mockReturnValue(false);
diff --git a/packages/twenty-front/src/modules/object-record/record-sharing/hooks/useCanReadObjectRecordsOrSharedRecords.ts b/packages/twenty-front/src/modules/object-record/record-sharing/hooks/useCanReadObjectRecordsOrSharedRecords.ts
index 8cd48ef241b..99641ee7c8f 100644
--- a/packages/twenty-front/src/modules/object-record/record-sharing/hooks/useCanReadObjectRecordsOrSharedRecords.ts
+++ b/packages/twenty-front/src/modules/object-record/record-sharing/hooks/useCanReadObjectRecordsOrSharedRecords.ts
@@ -2,19 +2,13 @@ import { type EnrichedObjectMetadataItem } from '@/object-metadata/types/Enriche
import { useObjectPermissionsForObject } from '@/object-record/hooks/useObjectPermissionsForObject';
import { useIsFeatureEnabled } from '@/workspace/hooks/useIsFeatureEnabled';
import { isShareableObjectMetadataItem } from '@/object-record/record-sharing/utils/isShareableObjectMetadataItem';
-import {
- FeatureFlagKey,
- ObjectSharingReach,
-} from '~/generated-metadata/graphql';
+import { FeatureFlagKey } from '~/generated-metadata/graphql';
// A record shared by name reaches people whose role cannot read its object,
// so a direct link must still be fetched; the server returns nothing when
// the record was not shared with them
export const useCanReadObjectRecordsOrSharedRecords = (
- objectMetadataItem: Pick<
- EnrichedObjectMetadataItem,
- 'id' | 'isSystem' | 'readability' | 'sharingReach'
- >,
+ objectMetadataItem: Pick<EnrichedObjectMetadataItem, 'id' | 'isSystem'>,
): boolean => {
const objectPermissions = useObjectPermissionsForObject(
objectMetadataItem.id,
@@ -26,7 +20,6 @@ export const useCanReadObjectRecordsOrSharedRecords = (
return (
objectPermissions.canReadObjectRecords ||
(isRecordLevelSharingEnabled &&
- isShareableObjectMetadataItem(objectMetadataItem) &&
- objectMetadataItem.sharingReach === ObjectSharingReach.WORKSPACE)
+ isShareableObjectMetadataItem(objectMetadataItem))
);
};
diff --git a/packages/twenty-front/src/modules/object-record/record-sharing/utils/__tests__/getRecordShareRoleAccessNote.test.ts b/packages/twenty-front/src/modules/object-record/record-sharing/utils/__tests__/getRecordShareRoleAccessNote.test.ts
index 2bb808b6622..00fe54b1ea2 100644
--- a/packages/twenty-front/src/modules/object-record/record-sharing/utils/__tests__/getRecordShareRoleAccessNote.test.ts
+++ b/packages/twenty-front/src/modules/object-record/record-sharing/utils/__tests__/getRecordShareRoleAccessNote.test.ts
@@ -1,94 +1,29 @@
import { getRecordShareRoleAccessNote } from '@/object-record/record-sharing/utils/getRecordShareRoleAccessNote';
-import {
- ObjectSharingReach,
- RecordShareAccessLevel,
-} from '~/generated-metadata/graphql';
const OBJECT_LABEL_PLURAL = 'Opportunities';
-const getNote = ({
- accessLevel = RecordShareAccessLevel.READ_WRITE,
- principalRole,
- sharingReach,
-}: {
- accessLevel?: RecordShareAccessLevel;
- principalRole:
- | { canRead: boolean | null; canUpdate: boolean | null }
- | undefined;
- sharingReach: ObjectSharingReach;
-}) =>
+const getNote = (principalRole: { canRead: boolean | null } | undefined) =>
getRecordShareRoleAccessNote({
- accessLevel,
principalRole,
- sharingReach,
objectLabelPlural: OBJECT_LABEL_PLURAL,
});
describe('getRecordShareRoleAccessNote', () => {
it('should say nothing when the role of the recipient is unknown', () => {
- expect(
- getNote({
- principalRole: undefined,
- sharingReach: ObjectSharingReach.WORKSPACE,
- }),
- ).toBeUndefined();
+ expect(getNote(undefined)).toBeUndefined();
});
it('should say nothing when the access of the role is unknown', () => {
- expect(
- getNote({
- principalRole: { canRead: null, canUpdate: null },
- sharingReach: ObjectSharingReach.ROLE_ACCESS,
- }),
- ).toBeUndefined();
+ expect(getNote({ canRead: null })).toBeUndefined();
});
it('should tell that a grant reaches beyond the role of its recipient', () => {
- expect(
- getNote({
- principalRole: { canRead: false, canUpdate: false },
- sharingReach: ObjectSharingReach.WORKSPACE,
- }),
- ).toBe("Gets this record only: their role can't access Opportunities");
+ expect(getNote({ canRead: false })).toBe(
+ "Gets this record only: their role can't access Opportunities",
+ );
});
- it('should not warn about editing when the grant reaches beyond the role', () => {
- expect(
- getNote({
- principalRole: { canRead: true, canUpdate: false },
- sharingReach: ObjectSharingReach.WORKSPACE,
- }),
- ).toBeUndefined();
- });
-
- it('should warn that a grant does nothing when sharing stays within roles', () => {
- expect(
- getNote({
- principalRole: { canRead: false, canUpdate: false },
- sharingReach: ObjectSharingReach.ROLE_ACCESS,
- }),
- ).toBe("Won't see it: their role can't access Opportunities");
- });
-
- it('should warn that an edit grant only lets them view within roles', () => {
- expect(
- getNote({
- principalRole: { canRead: true, canUpdate: false },
- sharingReach: ObjectSharingReach.ROLE_ACCESS,
- }),
- ).toBe("Can only view: their role can't edit Opportunities");
- expect(
- getNote({
- accessLevel: RecordShareAccessLevel.READ,
- principalRole: { canRead: true, canUpdate: false },
- sharingReach: ObjectSharingReach.ROLE_ACCESS,
- }),
- ).toBeUndefined();
- expect(
- getNote({
- principalRole: { canRead: true, canUpdate: true },
- sharingReach: ObjectSharingReach.ROLE_ACCESS,
- }),
- ).toBeUndefined();
+ it('should say nothing when the role can already access the object', () => {
+ expect(getNote({ canRead: true })).toBeUndefined();
});
});
diff --git a/packages/twenty-front/src/modules/object-record/record-sharing/utils/getRecordShareRoleAccessNote.ts b/packages/twenty-front/src/modules/object-record/record-sharing/utils/getRecordShareRoleAccessNote.ts
index de34cf7e74a..0cd3973a622 100644
--- a/packages/twenty-front/src/modules/object-record/record-sharing/utils/getRecordShareRoleAccessNote.ts
+++ b/packages/twenty-front/src/modules/object-record/record-sharing/utils/getRecordShareRoleAccessNote.ts
@@ -1,42 +1,23 @@
import { t } from '@lingui/core/macro';
import { isDefined } from 'twenty-shared/utils';
-import {
- ObjectSharingReach,
- RecordShareAccessLevel,
- type RecordSharingRoleDto,
-} from '~/generated-metadata/graphql';
+import { type RecordSharingRoleDto } from '~/generated-metadata/graphql';
// Owners see what each grant actually gives, not only the level they picked
export const getRecordShareRoleAccessNote = ({
- accessLevel,
principalRole,
- sharingReach,
objectLabelPlural,
}: {
- accessLevel: RecordShareAccessLevel;
- principalRole:
- | Pick<RecordSharingRoleDto, 'canRead' | 'canUpdate'>
- | undefined;
- sharingReach: ObjectSharingReach;
+ principalRole: Pick<RecordSharingRoleDto, 'canRead'> | undefined;
objectLabelPlural: string;
}): string | undefined => {
- if (!isDefined(principalRole) || !isDefined(principalRole.canRead)) {
+ if (
+ !isDefined(principalRole) ||
+ !isDefined(principalRole.canRead) ||
+ principalRole.canRead
+ ) {
return undefined;
}
- if (sharingReach === ObjectSharingReach.WORKSPACE) {
- return principalRole.canRead
- ? undefined
- : t`Gets this record only: their role can't access ${objectLabelPlural}`;
- }
-
- if (!principalRole.canRead) {
- return t`Won't see it: their role can't access ${objectLabelPlural}`;
- }
-
- return accessLevel !== RecordShareAccessLevel.READ &&
- principalRole.canUpdate === false
- ? t`Can only view: their role can't edit ${objectLabelPlural}`
- : undefined;
+ return t`Gets this record only: their role can't access ${objectLabelPlural}`;
};
diff --git a/packages/twenty-front/src/modules/object-record/record-sharing/utils/isShareableObjectMetadataItem.ts b/packages/twenty-front/src/modules/object-record/record-sharing/utils/isShareableObjectMetadataItem.ts
index 93e2918efda..48483e2cba2 100644
--- a/packages/twenty-front/src/modules/object-record/record-sharing/utils/isShareableObjectMetadataItem.ts
+++ b/packages/twenty-front/src/modules/object-record/record-sharing/utils/isShareableObjectMetadataItem.ts
@@ -1,18 +1,6 @@
import { type EnrichedObjectMetadataItem } from '@/object-metadata/types/EnrichedObjectMetadataItem';
-import { MetadataReadability } from '~/generated-metadata/graphql';
-const SHAREABLE_READABILITIES = [
- MetadataReadability.OPEN,
- MetadataReadability.PRIVATE,
- MetadataReadability.INHERITED,
-];
-
-// Mirrors the server: application and system data is never shared by record
+// Mirrors the server: system data is never shared by record
export const isShareableObjectMetadataItem = (
- objectMetadataItem: Pick<
- EnrichedObjectMetadataItem,
- 'isSystem' | 'readability'
- >,
-): boolean =>
- !objectMetadataItem.isSystem &&
- SHAREABLE_READABILITIES.includes(objectMetadataItem.readability);
+ objectMetadataItem: Pick<EnrichedObjectMetadataItem, 'isSystem'>,
+): boolean => !objectMetadataItem.isSystem;
diff --git a/packages/twenty-front/src/modules/object-record/utils/__tests__/canCreateRecordsForObjectMetadataItem.test.ts b/packages/twenty-front/src/modules/object-record/utils/__tests__/canCreateRecordsForObjectMetadataItem.test.ts
index 476f3b6aaea..84ae71d814d 100644
--- a/packages/twenty-front/src/modules/object-record/utils/__tests__/canCreateRecordsForObjectMetadataItem.test.ts
+++ b/packages/twenty-front/src/modules/object-record/utils/__tests__/canCreateRecordsForObjectMetadataItem.test.ts
@@ -1,9 +1,7 @@
import { canCreateRecordsForObjectMetadataItem } from '@/object-record/utils/canCreateRecordsForObjectMetadataItem';
-import { MetadataWritability } from '~/generated-metadata/graphql';
const creatableObjectMetadataItem = {
isUICreatable: true,
- writability: MetadataWritability.OPEN,
isUIEditable: true,
isRemote: false,
};
@@ -15,7 +13,7 @@ const objectPermissionsAllowingUpdate = {
};
describe('canCreateRecordsForObjectMetadataItem', () => {
- it('should return true for a creatable, editable, OPEN, non-remote object with update permission', () => {
+ it('should return true for a creatable, editable, non-remote object with update permission', () => {
const result = canCreateRecordsForObjectMetadataItem({
objectPermissions: objectPermissionsAllowingUpdate,
objectMetadataItem: creatableObjectMetadataItem,
@@ -36,18 +34,6 @@ describe('canCreateRecordsForObjectMetadataItem', () => {
expect(result).toBe(false);
});
- it('should return false when the object writability is not OPEN', () => {
- const result = canCreateRecordsForObjectMetadataItem({
- objectPermissions: objectPermissionsAllowingUpdate,
- objectMetadataItem: {
- ...creatableObjectMetadataItem,
- writability: MetadataWritability.SYSTEM,
- },
- });
-
- expect(result).toBe(false);
- });
-
it('should return false when the object is not UI editable', () => {
const result = canCreateRecordsForObjectMetadataItem({
objectPermissions: objectPermissionsAllowingUpdate,
diff --git a/packages/twenty-front/src/modules/object-record/utils/canCreateRecordsForObjectMetadataItem.ts b/packages/twenty-front/src/modules/object-record/utils/canCreateRecordsForObjectMetadataItem.ts
index 90a70f5affa..6378de27068 100644
--- a/packages/twenty-front/src/modules/object-record/utils/canCreateRecordsForObjectMetadataItem.ts
+++ b/packages/twenty-front/src/modules/object-record/utils/canCreateRecordsForObjectMetadataItem.ts
@@ -6,11 +6,10 @@ type CanCreateRecordsForObjectMetadataItemParams = {
objectPermissions?: Pick<ObjectPermissions, 'canUpdateObjectRecords'>;
objectMetadataItem: Pick<
EnrichedObjectMetadataItem,
- 'isUICreatable' | 'isUIEditable' | 'isRemote' | 'writability'
+ 'isUICreatable' | 'isUIEditable' | 'isRemote'
>;
};
-// isSystem only controls Data Model visibility; isUICreatable and OPEN writability govern creation.
// No CREATE permission exists yet, so canUpdateObjectRecords is the proxy (inline creation edits a blank record).
export const canCreateRecordsForObjectMetadataItem = ({
objectPermissions,
diff --git a/packages/twenty-front/src/modules/settings/data-model/object-details/components/tabs/ObjectSettings.tsx b/packages/twenty-front/src/modules/settings/data-model/object-details/components/tabs/ObjectSettings.tsx
index 8e88122691d..1855e6fad2d 100644
--- a/packages/twenty-front/src/modules/settings/data-model/object-details/components/tabs/ObjectSettings.tsx
+++ b/packages/twenty-front/src/modules/settings/data-model/object-details/components/tabs/ObjectSettings.tsx
@@ -4,12 +4,10 @@ import { useGetIsMetadataItemCustom } from '@/object-metadata/hooks/useGetIsMeta
import { useUpdateOneObjectMetadataItem } from '@/object-metadata/hooks/useUpdateOneObjectMetadataItem';
import { type EnrichedObjectMetadataItem } from '@/object-metadata/types/EnrichedObjectMetadataItem';
import { getObjectColorWithFallback } from '@/object-metadata/utils/getObjectColorWithFallback';
-import { isShareableObjectMetadataItem } from '@/object-record/record-sharing/utils/isShareableObjectMetadataItem';
import { isObjectMetadataReadOnly } from '@/object-record/read-only/utils/isObjectMetadataReadOnly';
import { SettingsCard } from '@/settings/components/SettingsCard';
import { SettingsEnterpriseFeatureGateCard } from '@/settings/components/SettingsEnterpriseFeatureGateCard';
import { SettingsUpdateDataModelObjectAboutForm } from '@/settings/data-model/object-details/components/SettingsUpdateDataModelObjectAboutForm';
-import { ObjectSharingReachPicker } from '@/settings/data-model/object-details/components/tabs/ObjectSharingReachPicker';
import { SettingsObjectValidationRulesSection } from '@/settings/data-model/object-details/components/tabs/SettingsObjectValidationRulesSection';
import { SettingsDataModelObjectSettingsFormCard } from '@/settings/data-model/objects/forms/components/SettingsDataModelObjectSettingsFormCard';
import { OrganizationAdornment } from '@/settings/enterprise/components/OrganizationAdornment';
@@ -105,9 +103,6 @@ export const ObjectSettings = ({
FeatureFlagKey.IS_RECORD_CREATION_FORM_ENABLED,
);
const hasValidationRulesEntitlement = useHasValidationRulesEntitlement();
- const isRecordLevelSharingEnabled = useIsFeatureEnabled(
- FeatureFlagKey.IS_RECORD_LEVEL_SHARING_ENABLED,
- );
const handleDisable = async () => {
const result = await updateOneObjectMetadataItem({
@@ -185,19 +180,6 @@ export const ObjectSettings = ({
)}
</Section.Root>
)}
- {isRecordLevelSharingEnabled &&
- isShareableObjectMetadataItem(objectMetadataItem) && (
- <Section.Root>
- <Section.Header
- title={t`Record sharing`}
- description={t`Who a record of ${objectLabel} can be shared with. Roles still decide what people see by default.`}
- />
- <ObjectSharingReachPicker
- objectMetadataItem={objectMetadataItem}
- isReadOnly={isReadOnly}
- />
- </Section.Root>
- )}
<Section.Root>
<Section.Header
title={t`Advanced`}
diff --git a/packages/twenty-front/src/modules/settings/data-model/object-details/components/tabs/ObjectSharingReachPicker.tsx b/packages/twenty-front/src/modules/settings/data-model/object-details/components/tabs/ObjectSharingReachPicker.tsx
deleted file mode 100644
index cccb44a47c5..00000000000
--- a/packages/twenty-front/src/modules/settings/data-model/object-details/components/tabs/ObjectSharingReachPicker.tsx
+++ /dev/null
@@ -1,51 +0,0 @@
-import { msg } from '@lingui/core/macro';
-import { IconLock, IconUsers } from 'twenty-ui/icon';
-
-import { useUpdateOneObjectMetadataItem } from '@/object-metadata/hooks/useUpdateOneObjectMetadataItem';
-import { type EnrichedObjectMetadataItem } from '@/object-metadata/types/EnrichedObjectMetadataItem';
-import { SettingsRadioSettingsCard } from '@/settings/components/SettingsRadioSettingsCard';
-import { ObjectSharingReach } from '~/generated-metadata/graphql';
-
-type ObjectSharingReachPickerProps = {
- objectMetadataItem: EnrichedObjectMetadataItem;
- isReadOnly: boolean;
-};
-
-const OBJECT_SHARING_REACH_OPTIONS = [
- {
- value: ObjectSharingReach.WORKSPACE,
- title: msg`Anyone in the workspace`,
- description: msg`A record can be shared with anyone, even people whose role cannot access this object. They get that record only, to view or edit.`,
- cardMedia: <IconUsers />,
- },
- {
- value: ObjectSharingReach.ROLE_ACCESS,
- title: msg`Only people who can already access these records`,
- description: msg`Sharing never goes beyond roles and their row filters. Use it for sensitive objects.`,
- cardMedia: <IconLock />,
- },
-];
-
-export const ObjectSharingReachPicker = ({
- objectMetadataItem,
- isReadOnly,
-}: ObjectSharingReachPickerProps) => {
- const { updateOneObjectMetadataItem } = useUpdateOneObjectMetadataItem();
-
- const handleChange = (sharingReach: ObjectSharingReach) => {
- void updateOneObjectMetadataItem({
- idToUpdate: objectMetadataItem.id,
- updatePayload: { sharingReach },
- });
- };
-
- return (
- <SettingsRadioSettingsCard
- name="object-sharing-reach"
- onChange={handleChange}
- options={OBJECT_SHARING_REACH_OPTIONS}
- value={objectMetadataItem.sharingReach}
- disabled={isReadOnly}
- />
- );
-};
diff --git a/packages/twenty-front/src/modules/side-panel/pages/share-record/components/SidePanelShareRecordContent.tsx b/packages/twenty-front/src/modules/side-panel/pages/share-record/components/SidePanelShareRecordContent.tsx
index 71cf0a362a8..0937bb29739 100644
--- a/packages/twenty-front/src/modules/side-panel/pages/share-record/components/SidePanelShareRecordContent.tsx
+++ b/packages/twenty-front/src/modules/side-panel/pages/share-record/components/SidePanelShareRecordContent.tsx
@@ -22,10 +22,7 @@ import { SidePanelShareRecordSkeleton } from '@/side-panel/pages/share-record/co
import { useSidePanelShareRecordInvitation } from '@/side-panel/pages/share-record/hooks/useSidePanelShareRecordInvitation';
import { useSidePanelShareRecordSearch } from '@/side-panel/pages/share-record/hooks/useSidePanelShareRecordSearch';
import { SidePanelFooter } from '@/ui/layout/side-panel/components/SidePanelFooter';
-import {
- ObjectSharingReach,
- RecordSharingMode,
-} from '~/generated-metadata/graphql';
+import { RecordSharingMode } from '~/generated-metadata/graphql';
import { useCopyToClipboard } from '~/hooks/useCopyToClipboard';
const StyledContainer = styled.div`
@@ -57,14 +54,12 @@ const StyledSeparator = styled.div`
type SidePanelShareRecordContentProps = {
recordUrl: string;
objectLabelPlural: string;
- sharingReach: ObjectSharingReach;
sharingState: ReturnType<typeof useRecordSharing>;
};
export const SidePanelShareRecordContent = ({
recordUrl,
objectLabelPlural,
- sharingReach,
sharingState,
}: SidePanelShareRecordContentProps) => {
const { t } = useLingui();
@@ -202,7 +197,6 @@ export const SidePanelShareRecordContent = ({
member={member}
roles={sharing.roles}
objectLabelPlural={objectLabelPlural}
- sharingReach={sharingReach}
isSaving={invitation.isSubmitting}
setShare={setShare}
removeShare={removeShare}
@@ -235,17 +229,11 @@ export const SidePanelShareRecordContent = ({
{sharing.hasManagedGeneralAccess && (
<StyledDescription>{t`Workspace access is also managed by an application.`}</StyledDescription>
)}
- {sharing.sharingMode === RecordSharingMode.INHERITED && (
- <StyledDescription>{t`Access is also inherited from related records.`}</StyledDescription>
+ {!sharing.hasManagedGeneralAccess && (
+ <StyledDescription>
+ {t`People you add get this record even if their role can't access ${objectLabelPlural}. Field permissions still apply.`}
+ </StyledDescription>
)}
- {!sharing.hasManagedGeneralAccess &&
- sharing.sharingMode !== RecordSharingMode.INHERITED && (
- <StyledDescription>
- {sharingReach === ObjectSharingReach.WORKSPACE
- ? t`People you add get this record even if their role can't access ${objectLabelPlural}. Field permissions still apply.`
- : t`Role and field permissions still apply.`}
- </StyledDescription>
- )}
</>
) : (
<StyledDescription>
diff --git a/packages/twenty-front/src/modules/side-panel/pages/share-record/components/SidePanelShareRecordPage.tsx b/packages/twenty-front/src/modules/side-panel/pages/share-record/components/SidePanelShareRecordPage.tsx
index 27c832a843e..cb31f3842f3 100644
--- a/packages/twenty-front/src/modules/side-panel/pages/share-record/components/SidePanelShareRecordPage.tsx
+++ b/packages/twenty-front/src/modules/side-panel/pages/share-record/components/SidePanelShareRecordPage.tsx
@@ -29,7 +29,6 @@ const SidePanelShareRecordPageContent = ({
<RecordSharingRefreshEffect refetch={sharingState.refetch} />
<SidePanelShareRecordContent
objectLabelPlural={objectMetadataItem.labelPlural}
- sharingReach={objectMetadataItem.sharingReach}
recordUrl={
new URL(
getLinkToShowPage(objectMetadataItem.nameSingular, {
diff --git a/packages/twenty-front/src/modules/side-panel/pages/share-record/components/SidePanelShareRecordRecipient.tsx b/packages/twenty-front/src/modules/side-panel/pages/share-record/components/SidePanelShareRecordRecipient.tsx
index 456f5b4b86e..4ffd9f6775b 100644
--- a/packages/twenty-front/src/modules/side-panel/pages/share-record/components/SidePanelShareRecordRecipient.tsx
+++ b/packages/twenty-front/src/modules/side-panel/pages/share-record/components/SidePanelShareRecordRecipient.tsx
@@ -15,7 +15,6 @@ import { SidePanelShareRecordDropdownItem } from '@/side-panel/pages/share-recor
import { ListItemIconContainer } from '@/ui/navigation/list-item/components/ListItemIconContainer';
import { getWorkspaceMemberNameOrEmail } from '@/workspace-member/utils/getWorkspaceMemberNameOrEmail';
import {
- type ObjectSharingReach,
RecordSharePrincipalType,
RecordShareRowCause,
type RecordSharingFieldsFragment,
@@ -35,7 +34,6 @@ type SidePanelShareRecordRecipientProps = {
member: PartialWorkspaceMember | undefined;
roles: RecordSharingFieldsFragment['roles'];
objectLabelPlural: string;
- sharingReach: ObjectSharingReach;
isSaving: boolean;
setShare: ReturnType<typeof useRecordSharing>['setShare'];
removeShare: ReturnType<typeof useRecordSharing>['removeShare'];
@@ -47,7 +45,6 @@ export const SidePanelShareRecordRecipient = ({
member,
roles,
objectLabelPlural,
- sharingReach,
isSaving,
setShare,
removeShare,
@@ -71,9 +68,7 @@ export const SidePanelShareRecordRecipient = ({
</ListItemIconContainer>
) : undefined;
const roleAccessNote = getRecordShareRoleAccessNote({
- accessLevel: share.accessLevel,
principalRole: roles.find(({ id }) => id === principalRoleId),
- sharingReach,
objectLabelPlural,
});
const isEditable = share.rowCause === RecordShareRowCause.MANUAL;
diff --git a/packages/twenty-front/src/modules/side-panel/pages/share-record/components/__stories__/SidePanelShareRecordContent.stories.tsx b/packages/twenty-front/src/modules/side-panel/pages/share-record/components/__stories__/SidePanelShareRecordContent.stories.tsx
index c9d61836cf6..e71dc795a13 100644
--- a/packages/twenty-front/src/modules/side-panel/pages/share-record/components/__stories__/SidePanelShareRecordContent.stories.tsx
+++ b/packages/twenty-front/src/modules/side-panel/pages/share-record/components/__stories__/SidePanelShareRecordContent.stories.tsx
@@ -11,7 +11,6 @@ import { currentWorkspaceMembersState } from '@/auth/states/currentWorkspaceMemb
import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';
import { SidePanelShareRecordContent } from '@/side-panel/pages/share-record/components/SidePanelShareRecordContent';
import {
- ObjectSharingReach,
RecordShareAccessLevel,
RecordSharePrincipalType,
RecordShareRowCause,
@@ -139,7 +138,6 @@ const meta: Meta<typeof SidePanelShareRecordContent> = {
args: {
recordUrl: 'https://example.com/chat/shared-chat',
objectLabelPlural: 'Chats',
- sharingReach: ObjectSharingReach.WORKSPACE,
sharingState: {
sharing: SHARING,
loading: false,
@@ -354,7 +352,6 @@ export const ChangeAccessWithoutMovingRecipients: Story = {
<SidePanelShareRecordContent
recordUrl={args.recordUrl}
objectLabelPlural={args.objectLabelPlural}
- sharingReach={args.sharingReach}
sharingState={{
...args.sharingState,
sharing,
diff --git a/packages/twenty-front/src/modules/side-panel/pages/share-record/components/__tests__/SidePanelShareRecordContent.test.tsx b/packages/twenty-front/src/modules/side-panel/pages/share-record/components/__tests__/SidePanelShareRecordContent.test.tsx
index 54dda02d7a8..81fd6643fb6 100644
--- a/packages/twenty-front/src/modules/side-panel/pages/share-record/components/__tests__/SidePanelShareRecordContent.test.tsx
+++ b/packages/twenty-front/src/modules/side-panel/pages/share-record/components/__tests__/SidePanelShareRecordContent.test.tsx
@@ -5,7 +5,6 @@ import { Provider as JotaiProvider } from 'jotai';
import { type ReactNode } from 'react';
import { MemoryRouter } from 'react-router-dom';
import {
- ObjectSharingReach,
RecordShareAccessLevel,
RecordSharePrincipalType,
RecordShareRowCause,
@@ -70,12 +69,10 @@ const Wrapper = ({ children }: { children: ReactNode }) => (
const renderSharing = ({
sharingOverrides = {},
- sharingReach = ObjectSharingReach.WORKSPACE,
isLoading = false,
error,
}: {
sharingOverrides?: Partial<RecordSharingFieldsFragment>;
- sharingReach?: ObjectSharingReach;
isLoading?: boolean;
error?: Error;
} = {}) =>
@@ -83,7 +80,6 @@ const renderSharing = ({
<SidePanelShareRecordContent
recordUrl="https://example.com/record"
objectLabelPlural="Companies"
- sharingReach={sharingReach}
sharingState={{
sharing: { ...sharing, ...sharingOverrides },
setGeneralAccess,
@@ -185,31 +181,17 @@ describe('Share record side panel', () => {
expect(screen.queryByRole('button', { name: /Remove/ })).toBeNull();
});
- it('explains inherited access instead of promising a manual revocation removes it', async () => {
- renderSharing({
- sharingOverrides: { sharingMode: RecordSharingMode.INHERITED },
- });
+ it('tells managers what adding people grants', async () => {
+ renderSharing();
await waitFor(() =>
expect(
- screen.getByText(/Access is also inherited from related records/),
+ screen.getByText(
+ "People you add get this record even if their role can't access Companies. Field permissions still apply.",
+ ),
).toBeVisible(),
);
});
- it.each([
- [
- ObjectSharingReach.WORKSPACE,
- "People you add get this record even if their role can't access Companies. Field permissions still apply.",
- ],
- [ObjectSharingReach.ROLE_ACCESS, 'Role and field permissions still apply.'],
- ])(
- 'tells managers what adding people grants when sharing reach is %s',
- async (sharingReach, notice) => {
- renderSharing({ sharingReach });
- await waitFor(() => expect(screen.getByText(notice)).toBeVisible());
- },
- );
-
it('tells viewers of a record open by default who can change its access', async () => {
renderSharing({
sharingOverrides: {
@@ -247,33 +229,26 @@ describe('Share record side panel', () => {
expect(screen.queryByText(/Only the creator of this record/)).toBeNull();
});
- it.each([
- [
- ObjectSharingReach.WORKSPACE,
- "Gets this record only: their role can't access Companies",
- ],
- [
- ObjectSharingReach.ROLE_ACCESS,
- "Won't see it: their role can't access Companies",
- ],
- ])(
- 'explains what a grant does for a role without access when sharing reach is %s',
- async (sharingReach, note) => {
- renderSharing({
- sharingReach,
- sharingOverrides: {
- roles: [
- {
- id: 'member-role',
- label: 'Member',
- canRead: false,
- canUpdate: false,
- },
- ],
- shares: [buildShare({ principalRoleId: 'member-role' })],
- },
- });
- await waitFor(() => expect(screen.getByText(note)).toBeVisible());
- },
- );
+ it('explains what a grant does for a role without access', async () => {
+ renderSharing({
+ sharingOverrides: {
+ roles: [
+ {
+ id: 'member-role',
+ label: 'Member',
+ canRead: false,
+ canUpdate: false,
+ },
+ ],
+ shares: [buildShare({ principalRoleId: 'member-role' })],
+ },
+ });
+ await waitFor(() =>
+ expect(
+ screen.getByText(
+ "Gets this record only: their role can't access Companies",
+ ),
+ ).toBeVisible(),
+ );
+ });
});
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-43/utils/__tests__/is-legacy-record-access-open.util.spec.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-43/utils/__tests__/is-legacy-record-access-open.util.spec.ts
index 5c0332a06cc..46d1eee8d23 100644
--- a/packages/twenty-server/src/database/commands/upgrade-version-command/2-43/utils/__tests__/is-legacy-record-access-open.util.spec.ts
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-43/utils/__tests__/is-legacy-record-access-open.util.spec.ts
@@ -1,7 +1,6 @@
import { STANDARD_OBJECTS } from 'twenty-shared/metadata';
import { MetadataReadability } from 'twenty-shared/types';
import { isLegacyRecordAccessOpen } from 'src/database/commands/upgrade-version-command/2-43/utils/is-legacy-record-access-open.util';
-import { resolveRecordShareGateKind } from 'src/engine/core-modules/record-share/utils/resolve-record-share-gate-kind.util';
it.each([
[MetadataReadability.SYSTEM, false, false, true],
@@ -23,18 +22,6 @@ it.each([
wasRecordSharingEnabled: flag && entitlement,
});
expect(legacyOpen).toBe(expected);
- expect(
- resolveRecordShareGateKind({
- readability: MetadataReadability.PRIVATE,
- isOwningApplication: false,
- }),
- ).toBe('private');
- expect(
- resolveRecordShareGateKind({
- readability: MetadataReadability.SYSTEM,
- isOwningApplication: false,
- }),
- ).toBe('deny');
},
);
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-45/utils/__tests__/build-chat-share-record-availability-updates.util.spec.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-45/utils/__tests__/build-chat-share-record-availability-updates.util.spec.ts
index 62a232c5476..b3e9a8851df 100644
--- a/packages/twenty-server/src/database/commands/upgrade-version-command/2-45/utils/__tests__/build-chat-share-record-availability-updates.util.spec.ts
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-45/utils/__tests__/build-chat-share-record-availability-updates.util.spec.ts
@@ -105,20 +105,11 @@ describe('buildChatShareRecordAvailabilityUpdates', () => {
expect(isAvailable(shareAnyRecordExpression, {}, company)).toBe(false);
});
- it.each(['APPLICATION', 'SYSTEM'])(
- 'keeps the unpinned item off %s objects and off chats',
- (readability) => {
- expect(
- isAvailable(shareAnyRecordExpression, recordSharing, {
- ...company,
- readability,
- }),
- ).toBe(false);
- expect(isAvailable(shareAnyRecordExpression, recordSharing, chat)).toBe(
- false,
- );
- },
- );
+ it('keeps the unpinned item off chats', () => {
+ expect(isAvailable(shareAnyRecordExpression, recordSharing, chat)).toBe(
+ false,
+ );
+ });
it.each<Record<string, boolean>>([
{ IS_AI_CHAT_SHARING_DROPDOWN_ENABLED: true },
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-53/2-53-upgrade-version-command.module.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-53/2-53-upgrade-version-command.module.ts
index e3b91439b17..391141898c2 100644
--- a/packages/twenty-server/src/database/commands/upgrade-version-command/2-53/2-53-upgrade-version-command.module.ts
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-53/2-53-upgrade-version-command.module.ts
@@ -2,6 +2,7 @@ import { Module } from '@nestjs/common';
import { WorkspaceIteratorModule } from 'src/database/commands/command-runners/workspace-iterator.module';
import { AddChatAssistantParticipationCommand } from 'src/database/commands/upgrade-version-command/2-53/2-53-workspace-command-1793111719062-add-chat-assistant-participation.command';
+import { MoveApplicationAndSystemAccessToDisabledActionsCommand } from 'src/database/commands/upgrade-version-command/2-53/2-53-workspace-command-1793176233512-move-application-and-system-access-to-disabled-actions.command';
import { ApplicationModule } from 'src/engine/core-modules/application/application.module';
import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
import { WorkspaceMigrationModule } from 'src/engine/workspace-manager/workspace-migration/workspace-migration.module';
@@ -13,6 +14,9 @@ import { WorkspaceMigrationModule } from 'src/engine/workspace-manager/workspace
WorkspaceIteratorModule,
WorkspaceMigrationModule,
],
- providers: [AddChatAssistantParticipationCommand],
+ providers: [
+ AddChatAssistantParticipationCommand,
+ MoveApplicationAndSystemAccessToDisabledActionsCommand,
+ ],
})
export class V2_53_UpgradeVersionCommandModule {}
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-53/2-53-workspace-command-1793176233512-move-application-and-system-access-to-disabled-actions.command.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-53/2-53-workspace-command-1793176233512-move-application-and-system-access-to-disabled-actions.command.ts
new file mode 100644
index 00000000000..5be6e02046e
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-53/2-53-workspace-command-1793176233512-move-application-and-system-access-to-disabled-actions.command.ts
@@ -0,0 +1,118 @@
+import { InjectDataSource } from '@nestjs/typeorm';
+
+import { Command } from 'nest-commander';
+import { DataSource } from 'typeorm';
+
+import { ProvisionedWorkspaceCommandRunner } from 'src/database/commands/command-runners/provisioned-workspace.command-runner';
+import { WorkspaceIteratorService } from 'src/database/commands/command-runners/workspace-iterator.service';
+import { type RunOnWorkspaceArgs } from 'src/database/commands/command-runners/workspace.command-runner';
+import { RegisteredWorkspaceCommand } from 'src/engine/core-modules/upgrade/decorators/registered-workspace-command.decorator';
+import { getMetadataFlatEntityMapsKey } from 'src/engine/metadata-modules/flat-entity/utils/get-metadata-flat-entity-maps-key.util';
+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+
+const WRITE_ACTIONS = [
+ 'canUpdateObjectRecords',
+ 'canSoftDeleteObjectRecords',
+ 'canDestroyObjectRecords',
+];
+
+const READ_ACTIONS = ['canReadObjectRecords'];
+
+// APPLICATION falls back to OPEN; SYSTEM keeps its stored value, which the runtime no longer reads
+const ACCESS_MOVES = [
+ {
+ column: 'writability',
+ value: 'APPLICATION',
+ shouldOpenAfterMove: true,
+ disabledActions: WRITE_ACTIONS,
+ },
+ {
+ column: 'readability',
+ value: 'APPLICATION',
+ shouldOpenAfterMove: true,
+ disabledActions: READ_ACTIONS,
+ },
+ {
+ column: 'writability',
+ value: 'SYSTEM',
+ shouldOpenAfterMove: false,
+ disabledActions: WRITE_ACTIONS,
+ },
+ {
+ column: 'readability',
+ value: 'SYSTEM',
+ shouldOpenAfterMove: false,
+ disabledActions: READ_ACTIONS,
+ },
+] as const;
+
+@RegisteredWorkspaceCommand('2.53.0', 1793176233512)
+@Command({
+ name: 'upgrade:2-53:move-application-and-system-access-to-disabled-actions',
+ description:
+ 'Express APPLICATION and SYSTEM object readability and writability as disabled object permission actions',
+})
+export class MoveApplicationAndSystemAccessToDisabledActionsCommand extends ProvisionedWorkspaceCommandRunner {
+ constructor(
+ protected readonly workspaceIteratorService: WorkspaceIteratorService,
+ private readonly workspaceCacheService: WorkspaceCacheService,
+ @InjectDataSource()
+ private readonly coreDataSource: DataSource,
+ ) {
+ super(workspaceIteratorService);
+ }
+
+ override async runOnWorkspace({
+ workspaceId,
+ options,
+ }: RunOnWorkspaceArgs): Promise<void> {
+ if (options.dryRun) {
+ const [{ count }] = await this.coreDataSource.query(
+ `SELECT COUNT(*)::int AS "count" FROM "core"."objectMetadata"
+ WHERE "workspaceId" = $1
+ AND ("writability" IN ('APPLICATION', 'SYSTEM') OR "readability" IN ('APPLICATION', 'SYSTEM'))`,
+ [workspaceId],
+ );
+
+ this.logger.log(
+ `[DRY RUN] Workspace ${workspaceId}: would review ${count} object(s) with APPLICATION or SYSTEM access`,
+ );
+
+ return;
+ }
+
+ let movedObjectCount = 0;
+
+ for (const { column, value, shouldOpenAfterMove, disabledActions } of ACCESS_MOVES) {
+ const [movedObjects] = await this.coreDataSource.query(
+ `UPDATE "core"."objectMetadata"
+ SET ${shouldOpenAfterMove ? `"${column}" = 'OPEN',` : ''}
+ "disabledObjectPermissionActions" = (
+ SELECT jsonb_agg(DISTINCT "action" ORDER BY "action")
+ FROM jsonb_array_elements_text(
+ COALESCE("disabledObjectPermissionActions", '[]'::jsonb) || $3::jsonb
+ ) AS "action"
+ )
+ WHERE "workspaceId" = $1
+ AND "${column}" = $2
+ ${shouldOpenAfterMove ? '' : `AND NOT COALESCE("disabledObjectPermissionActions", '[]'::jsonb) @> $3::jsonb`}
+ RETURNING "id"`,
+ [workspaceId, value, JSON.stringify(disabledActions)],
+ );
+
+ movedObjectCount += movedObjects.length;
+ }
+
+ if (movedObjectCount === 0) {
+ return;
+ }
+
+ await this.workspaceCacheService.invalidateAndRecompute(workspaceId, [
+ getMetadataFlatEntityMapsKey('objectMetadata'),
+ ]);
+
+ this.logger.log(
+ `Workspace ${workspaceId}: moved APPLICATION or SYSTEM access of ${movedObjectCount} object update(s) to disabled actions`,
+ );
+ }
+}
diff --git a/packages/twenty-server/src/engine/api/common/common-nested-relations-processor/process-nested-relations.helper.ts b/packages/twenty-server/src/engine/api/common/common-nested-relations-processor/process-nested-relations.helper.ts
index 26b74bb793d..4a86f6535b7 100644
--- a/packages/twenty-server/src/engine/api/common/common-nested-relations-processor/process-nested-relations.helper.ts
+++ b/packages/twenty-server/src/engine/api/common/common-nested-relations-processor/process-nested-relations.helper.ts
@@ -210,7 +210,7 @@ export class ProcessNestedRelationsHelper {
const targetObjectNameSingular = targetObjectMetadata.nameSingular;
// A joined relation to such records reads as empty, so a nested one does too instead of failing the parent
- if (targetObjectRepository.isReadDeniedByReadability()) {
+ if (targetObjectRepository.isReadDisabled()) {
this.assignRelationResults({
parentRecords: parentObjectRecords,
parentObjectRecordsAggregatedValues,
diff --git a/packages/twenty-server/src/engine/api/common/common-query-runners/common-create-many-query-runner/common-create-many-query-runner.service.ts b/packages/twenty-server/src/engine/api/common/common-query-runners/common-create-many-query-runner/common-create-many-query-runner.service.ts
index a8d568aa90b..5a5ddca4f33 100644
--- a/packages/twenty-server/src/engine/api/common/common-query-runners/common-create-many-query-runner/common-create-many-query-runner.service.ts
+++ b/packages/twenty-server/src/engine/api/common/common-query-runners/common-create-many-query-runner/common-create-many-query-runner.service.ts
@@ -2,7 +2,7 @@ import { Injectable } from '@nestjs/common';
import { msg } from '@lingui/core/macro';
import { QUERY_MAX_RECORDS } from 'twenty-shared/constants';
-import { MetadataReadability, ObjectRecord } from 'twenty-shared/types';
+import { ObjectRecord } from 'twenty-shared/types';
import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';
import {
Brackets,
@@ -77,15 +77,9 @@ export class CommonCreateManyQueryRunnerService extends CommonBaseQueryRunnerSer
args: CommonExtendedInput<CreateManyQueryArgs>,
queryRunnerContext: CommonExtendedQueryRunnerContext,
): Promise<ObjectRecord[]> {
- const isPrivateObject =
- queryRunnerContext.flatObjectMetadata.readability ===
- MetadataReadability.PRIVATE;
const { sharingMode } = resolveObjectSharing(queryRunnerContext);
- const isGatedThroughRecordShares =
- sharingMode === RecordSharingMode.PRIVATE ||
- sharingMode === RecordSharingMode.INHERITED;
+ const isPrivateObject = sharingMode === RecordSharingMode.PRIVATE;
- // An inherited record is reachable through its parent, so shareWith is optional there
if (isPrivateObject || isNonEmptyArray(args.shareWith)) {
await this.shareWithService.validateShareWithOrThrow({
authContext: queryRunnerContext.authContext,
@@ -164,8 +158,7 @@ export class CommonCreateManyQueryRunnerService extends CommonBaseQueryRunnerSer
flatObjectMetadataMaps,
flatFieldMetadataMaps,
repository:
- isGatedThroughRecordShares &&
- isDefined(queryRunnerContext.transactionScope)
+ isPrivateObject && isDefined(queryRunnerContext.transactionScope)
? queryRunnerContext.transactionScope.getRepository(
flatObjectMetadata.nameSingular,
{ shouldBypassPermissionChecks: true },
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-trigger/triggers/database-event/utils/__tests__/transform-event-batch-to-event-payloads.spec.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-trigger/triggers/database-event/utils/__tests__/transform-event-batch-to-event-payloads.spec.ts
index 4b739d30043..3130cc88264 100644
--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-trigger/triggers/database-event/utils/__tests__/transform-event-batch-to-event-payloads.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-trigger/triggers/database-event/utils/__tests__/transform-event-batch-to-event-payloads.spec.ts
@@ -1,7 +1,4 @@
-import type {
- ObjectRecordDeleteEvent,
- ObjectRecordEvent,
-} from 'twenty-shared/database-events';
+import type { ObjectRecordEvent } from 'twenty-shared/database-events';
import { MAX_EVENTS_PER_TRIGGER_JOB } from 'src/engine/core-modules/logic-function/logic-function-trigger/triggers/database-event/constants/max-events-per-trigger-job.constant';
import { transformEventBatchToEventPayloads } from 'src/engine/core-modules/logic-function/logic-function-trigger/triggers/database-event/utils/transform-event-batch-to-event-payloads';
@@ -819,33 +816,3 @@ describe('transformEventBatchToEventPayloads', () => {
});
});
});
-
-describe('transformEventBatchToEventPayloads with a deletion capture', () => {
- it('should not hand the child records captured with a deletion to the function', () => {
- const [jobData] = transformEventBatchToEventPayloads({
- workspaceEventBatch: createMockWorkspaceEventBatch({
- name: 'company.deleted',
- events: [
- createMockEvent({
- properties: {
- before: { id: 'record-1' },
- after: { id: 'record-1', deletedAt: '2026-09-15T00:00:00Z' },
- updatedFields: ['deletedAt'],
- diff: {},
- inheritedReadabilityChildRecords: { noteTarget: [] },
- } as ObjectRecordDeleteEvent['properties'],
- }),
- ],
- }),
- logicFunctions: [
- createMockLogicFunction({
- databaseEventTriggerSettings: { eventName: 'company.deleted' },
- }),
- ],
- });
-
- expect(
- (jobData.payload as { properties: object }).properties,
- ).not.toHaveProperty('inheritedReadabilityChildRecords');
- });
-});
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-trigger/triggers/database-event/utils/transform-event-batch-to-event-payloads.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-trigger/triggers/database-event/utils/transform-event-batch-to-event-payloads.ts
index 3e90b4a09ed..de0eeafb8f0 100644
--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-trigger/triggers/database-event/utils/transform-event-batch-to-event-payloads.ts
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-trigger/triggers/database-event/utils/transform-event-batch-to-event-payloads.ts
@@ -7,7 +7,6 @@ import type { ObjectRecordEvent } from 'twenty-shared/database-events';
import { type LogicFunctionTriggerJobData } from 'src/engine/core-modules/logic-function/logic-function-trigger/jobs/logic-function-trigger.job';
import { MAX_EVENTS_PER_TRIGGER_JOB } from 'src/engine/core-modules/logic-function/logic-function-trigger/triggers/database-event/constants/max-events-per-trigger-job.constant';
import { type LogicFunctionEntity } from 'src/engine/metadata-modules/logic-function/logic-function.entity';
-import { omitInheritedReadabilityChildRecords } from 'src/engine/core-modules/record-share/utils/omit-inherited-readability-child-records.util';
import type { WorkspaceEventBatch } from 'src/engine/workspace-event-emitter/types/workspace-event-batch.type';
import { filterEventsByUpdatedFields } from 'src/engine/workspace-event-emitter/utils/filter-events-by-updated-fields.util';
@@ -40,7 +39,7 @@ export const transformEventBatchToEventPayloads = ({
workspaceId: logicFunction.workspaceId,
payload: {
...batchEventInfo,
- ...omitInheritedReadabilityChildRecords(event),
+ ...event,
},
...buildAuthContext(event),
});
@@ -62,7 +61,7 @@ export const transformEventBatchToEventPayloads = ({
workspaceId: logicFunction.workspaceId,
payload: {
...batchEventInfo,
- events: eventsChunk.map(omitInheritedReadabilityChildRecords),
+ events: eventsChunk,
},
...buildAuthContext(eventsChunk[0]),
});
diff --git a/packages/twenty-server/src/engine/core-modules/record-share/constants/max-inherited-readability-depth.constant.ts b/packages/twenty-server/src/engine/core-modules/record-share/constants/max-inherited-readability-depth.constant.ts
deleted file mode 100644
index f96c075ea9c..00000000000
--- a/packages/twenty-server/src/engine/core-modules/record-share/constants/max-inherited-readability-depth.constant.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-/* @license Enterprise */
-
-export const MAX_INHERITED_READABILITY_DEPTH = 3;
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.ts
deleted file mode 100644
index 6db4373c215..00000000000
--- a/packages/twenty-server/src/engine/core-modules/record-share/constants/open-when-detached-object-universal-identifiers.constant.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-/* @license Enterprise */
-
-import { STANDARD_OBJECTS } from 'twenty-shared/metadata';
-
-// Notes and tasks were open to every member before inheriting from targets, so detached ones stay open.
-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.ts
index b0abab2a9bc..e72fe282d4f 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
@@ -2,51 +2,21 @@
import { Injectable } from '@nestjs/common';
-import { isNonEmptyString } from '@sniptt/guards';
import groupBy from 'lodash.groupby';
import { type ObjectRecordEvent } from 'twenty-shared/database-events';
-import { type ObjectRecord } from 'twenty-shared/types';
-import { isDefined } from 'twenty-shared/utils';
-import { In, MoreThanOrEqual } from 'typeorm';
import { RecordShareStorageService } from 'src/engine/core-modules/record-share/services/record-share-storage.service';
import { type EventRecordAccessGate } from 'src/engine/core-modules/record-share/types/event-record-access-gate.type';
import { type RecordShare } from 'src/engine/core-modules/record-share/types/record-share.type';
-import {
- evaluateRowAccessPolicy,
- type RowAccessEvaluationContext,
-} from 'src/engine/core-modules/record-share/utils/evaluate-row-access-policy.util';
-import {
- type EventRecordSnapshot,
- resolveEventRecordSnapshots,
-} from 'src/engine/core-modules/record-share/utils/resolve-event-record-snapshots.util';
-import { type InheritedReadabilityParentExpression } from 'src/engine/twenty-orm/types/row-access-policy.type';
+import { evaluateRowAccessPolicy } from 'src/engine/core-modules/record-share/utils/evaluate-row-access-policy.util';
+import { resolveEventRecordSnapshots } from 'src/engine/core-modules/record-share/utils/resolve-event-record-snapshots.util';
import { buildRowAccessPolicy } from 'src/engine/twenty-orm/utils/build-row-access-policy.util';
-import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
-import { isChildRecordBoundAtDeletion } from 'src/engine/twenty-orm/utils/is-child-record-bound-at-deletion.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';
-type ColumnParentExpression = Extract<
- InheritedReadabilityParentExpression,
- { kind: 'column' }
->;
-
-type ChildrenParentExpression = Extract<
- InheritedReadabilityParentExpression,
- { kind: 'children' }
->;
-
-type SnapshotIdsThroughParent = {
- readableSnapshotIds: Set<string>;
- attachedSnapshotIds: Set<string>;
-};
-
@Injectable()
export class RecordAccessPolicyService {
constructor(
- private readonly workspaceOrmManager: WorkspaceOrmManager,
private readonly workspaceCacheService: WorkspaceCacheService,
private readonly recordShareStorageService: RecordShareStorageService,
) {}
@@ -126,50 +96,6 @@ export class RecordAccessPolicyService {
'flatFieldMetadataMapsOrm',
'featureFlagsMap',
]);
- const context: RowAccessEvaluationContext<EventRecordSnapshot> = {
- flatFieldMetadataMaps: flatFieldMetadataMapsOrm,
- shouldIgnoreSoftDeleteDefaultFilter: true,
- fetchRecordShares,
- // Parents and children are only reached through their tables
- resolveRecordIdsReadableThroughParents: ({ expression, records }) =>
- this.workspaceOrmManager.executeInWorkspaceContext(async () => {
- const readableSnapshotIds = new Set<string>();
- const attachedSnapshotIds = new Set<string>();
-
- for (const parent of expression.parents) {
- const throughParent =
- parent.kind === 'column'
- ? await this.resolveSnapshotIdsReadableThroughColumnParent({
- parent,
- snapshots: records,
- })
- : await this.resolveSnapshotIdsReadableThroughChildren({
- parent,
- snapshots: records,
- isOpenWhenDetached: expression.isOpenWhenDetached,
- context,
- });
-
- throughParent.readableSnapshotIds.forEach((id) =>
- readableSnapshotIds.add(id),
- );
- throughParent.attachedSnapshotIds.forEach((id) =>
- attachedSnapshotIds.add(id),
- );
- }
-
- if (expression.isOpenWhenDetached) {
- for (const record of records) {
- if (!attachedSnapshotIds.has(record.id)) {
- readableSnapshotIds.add(record.id);
- }
- }
- }
-
- return readableSnapshotIds;
- }, buildSystemAuthContext(workspaceId)),
- };
-
return evaluateRowAccessPolicy({
policy: buildRowAccessPolicy({
subject,
@@ -181,188 +107,15 @@ export class RecordAccessPolicyService {
tableAlias: objectMetadata.nameSingular,
flatObjectMetadata: objectMetadata,
operationType: 'select',
- depth: 0,
}),
records: resolveEventRecordSnapshots(events),
- context,
+ context: {
+ flatFieldMetadataMaps: flatFieldMetadataMapsOrm,
+ shouldIgnoreSoftDeleteDefaultFilter: true,
+ fetchRecordShares,
+ },
});
},
};
}
-
- private async resolveSnapshotIdsReadableThroughColumnParent({
- parent,
- snapshots,
- }: {
- parent: ColumnParentExpression;
- snapshots: EventRecordSnapshot[];
- }): Promise<SnapshotIdsThroughParent> {
- const parentIdBySnapshotId = new Map(
- snapshots.flatMap((snapshot) => {
- const parentId = snapshot[parent.joinColumnName];
-
- return isNonEmptyString(parentId) ? [[snapshot.id, parentId]] : [];
- }),
- );
- const readableParentIds = await this.workspaceOrmManager
- .getRepository(parent.parentFlatObjectMetadata.nameSingular, {
- shouldBypassPermissionChecks: true,
- })
- .findRecordIdsAdmittedByRowAccessPolicy({
- recordIds: [...new Set(parentIdBySnapshotId.values())],
- policy: parent.policy,
- tableAlias: parent.parentTableAlias,
- });
-
- return {
- readableSnapshotIds: new Set(
- [...parentIdBySnapshotId]
- .filter(([, parentId]) => readableParentIds.has(parentId))
- .map(([snapshotId]) => snapshotId),
- ),
- attachedSnapshotIds: new Set(parentIdBySnapshotId.keys()),
- };
- }
-
- private async resolveSnapshotIdsReadableThroughChildren({
- parent,
- snapshots,
- isOpenWhenDetached,
- context,
- }: {
- parent: ChildrenParentExpression;
- snapshots: EventRecordSnapshot[];
- isOpenWhenDetached: boolean;
- context: RowAccessEvaluationContext<EventRecordSnapshot>;
- }): Promise<SnapshotIdsThroughParent> {
- const childNameSingular = parent.childFlatObjectMetadata.nameSingular;
- const capturedChildSnapshotsBySnapshotId = new Map(
- snapshots.flatMap((snapshot) => {
- const capturedChildRecords =
- snapshot.inheritedReadabilityChildRecords?.[childNameSingular];
-
- return isDefined(capturedChildRecords)
- ? [
- [
- snapshot.id,
- capturedChildRecords.map(
- (childRecord): EventRecordSnapshot => ({
- ...childRecord,
- id: String(childRecord.id),
- }),
- ),
- ] as const,
- ]
- : [];
- }),
- );
- const liveSnapshotIds = snapshots
- .filter(
- (snapshot) => !capturedChildSnapshotsBySnapshotId.has(snapshot.id),
- )
- .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 childRepository = this.workspaceOrmManager.getRepository(
- childNameSingular,
- { shouldBypassPermissionChecks: true },
- );
- const childRows = await childRepository
- .createQueryBuilder()
- .select(['id', parent.childJoinColumnName])
- .where({ [parent.childJoinColumnName]: In(liveSnapshotIds) })
- .getMany<ObjectRecord>({ noFormatting: true });
- const readableChildIds =
- await childRepository.findRecordIdsAdmittedByRowAccessPolicy({
- recordIds: childRows.map((childRow) => String(childRow.id)),
- policy: parent.policy,
- tableAlias: parent.childTableAlias,
- });
-
- for (const childRow of childRows) {
- const snapshotId = String(childRow[parent.childJoinColumnName]);
-
- attachedSnapshotIds.add(snapshotId);
-
- if (readableChildIds.has(String(childRow.id))) {
- readableSnapshotIds.add(snapshotId);
- }
- }
-
- const trashedSnapshots = snapshots.filter(
- (snapshot) =>
- !capturedChildSnapshotsBySnapshotId.has(snapshot.id) &&
- isDefined(snapshot.deletedAt),
- );
-
- if (isOpenWhenDetached && 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);
- }
- }
- }
- }
-
- const readableCapturedChildIds = await evaluateRowAccessPolicy({
- policy: parent.policy,
- records: [...capturedChildSnapshotsBySnapshotId.values()].flat(),
- context,
- });
-
- for (const [
- snapshotId,
- capturedChildSnapshots,
- ] of capturedChildSnapshotsBySnapshotId) {
- if (
- capturedChildSnapshots.some((childSnapshot) =>
- readableCapturedChildIds.has(childSnapshot.id),
- )
- ) {
- readableSnapshotIds.add(snapshotId);
- }
- }
-
- return { readableSnapshotIds, attachedSnapshotIds };
- }
}
diff --git a/packages/twenty-server/src/engine/core-modules/record-share/services/record-share-ownership-transfer.service.ts b/packages/twenty-server/src/engine/core-modules/record-share/services/record-share-ownership-transfer.service.ts
index 7bf8b9e856f..88e0d5eeebe 100644
--- a/packages/twenty-server/src/engine/core-modules/record-share/services/record-share-ownership-transfer.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/record-share/services/record-share-ownership-transfer.service.ts
@@ -51,8 +51,7 @@ export class RecordShareOwnershipTransferService {
});
}
- // Only records that access to all records already reaches change hands:
- // private objects such as chats and workflow runs stay with their creator
+ // Private objects such as chats and workflow runs stay with their creator
private async findTransferableObjectMetadataIds(
workspaceId: string,
): Promise<string[]> {
diff --git a/packages/twenty-server/src/engine/core-modules/record-share/types/inherited-readability-child-records.type.ts b/packages/twenty-server/src/engine/core-modules/record-share/types/inherited-readability-child-records.type.ts
deleted file mode 100644
index b828e155d90..00000000000
--- a/packages/twenty-server/src/engine/core-modules/record-share/types/inherited-readability-child-records.type.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-/* @license Enterprise */
-
-export type InheritedReadabilityChildRecords = Record<
- string,
- Record<string, unknown>[]
->;
-
-export type InheritedReadabilityChildRecordsCarrier = {
- inheritedReadabilityChildRecords?: InheritedReadabilityChildRecords;
-};
diff --git a/packages/twenty-server/src/engine/core-modules/record-share/types/inherited-readability-parent-link.type.ts b/packages/twenty-server/src/engine/core-modules/record-share/types/inherited-readability-parent-link.type.ts
deleted file mode 100644
index 20846a7bfd5..00000000000
--- a/packages/twenty-server/src/engine/core-modules/record-share/types/inherited-readability-parent-link.type.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-/* @license Enterprise */
-
-import { type InheritedReadabilityColumnParent } from 'src/engine/core-modules/record-share/types/inherited-readability-column-parent.type';
-
-export type InheritedReadabilityParentLink = Pick<
- InheritedReadabilityColumnParent,
- 'joinColumnName' | 'parentFlatObjectMetadata'
->;
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.ts
deleted file mode 100644
index c335d405e66..00000000000
--- a/packages/twenty-server/src/engine/core-modules/record-share/utils/__tests__/build-inherited-readability-condition.util.spec.ts
+++ /dev/null
@@ -1,180 +0,0 @@
-/* @license Enterprise */
-
-import { RecordShareAccessLevel } from 'twenty-shared/types';
-
-import {
- buildInheritedReadabilityCondition,
- type InheritedReadabilityParentCondition,
-} from 'src/engine/core-modules/record-share/utils/build-inherited-readability-condition.util';
-
-const RECORD_SHARE_TABLE_EXPRESSION = '"workspace_abc"."recordShare"';
-const ATTACHMENT_OBJECT_METADATA_ID = 'attachment-object-metadata-id';
-const PRINCIPAL_IDS = ['principal-1', 'principal-2'];
-const ACCESS_LEVELS = [RecordShareAccessLevel.READ];
-
-const OWN_RECORD_SHARE_EXISTS =
- '(EXISTS (SELECT 1 FROM "workspace_abc"."recordShare" AS "attachment_recordShare" WHERE "attachment_recordShare"."recordId" = "attachment"."id"';
-
-const countOccurrences = (haystack: string, needle: string): number =>
- haystack.split(needle).length - 1;
-
-const build = (
- parents: InheritedReadabilityParentCondition[],
- { isOpenWhenDetached = false }: { isOpenWhenDetached?: boolean } = {},
-) =>
- buildInheritedReadabilityCondition({
- tableAlias: 'attachment',
- objectMetadataId: ATTACHMENT_OBJECT_METADATA_ID,
- parents,
- recordShareTableExpression: RECORD_SHARE_TABLE_EXPRESSION,
- principalIds: PRINCIPAL_IDS,
- accessLevels: ACCESS_LEVELS,
- isOpenWhenDetached,
- });
-
-const noteParent = (
- policy: InheritedReadabilityParentCondition['policy'],
-): InheritedReadabilityParentCondition => ({
- kind: 'column',
- joinColumnName: 'targetNoteId',
- parentTableAlias: 'attachment_targetNoteId',
- parentTableExpression: '"workspace_abc"."note"',
- policy,
-});
-
-const personParent = (
- policy: InheritedReadabilityParentCondition['policy'],
-): InheritedReadabilityParentCondition => ({
- kind: 'column',
- joinColumnName: 'targetPersonId',
- parentTableAlias: 'attachment_targetPersonId',
- parentTableExpression: '"workspace_abc"."person"',
- policy,
-});
-
-describe('buildInheritedReadabilityCondition', () => {
- it('should accept a share row on the record itself or an OPEN parent present', () => {
- const { sql, parameters } = build([
- personParent({ kind: 'open' }),
- {
- kind: 'column',
- joinColumnName: 'targetCompanyId',
- parentTableAlias: 'attachment_targetCompanyId',
- parentTableExpression: '"workspace_abc"."company"',
- policy: { kind: 'open' },
- },
- ]);
-
- expect(sql.startsWith(OWN_RECORD_SHARE_EXISTS)).toBe(true);
- expect(sql).toContain(
- ' OR "attachment"."targetPersonId" IS NOT NULL OR "attachment"."targetCompanyId" IS NOT NULL)',
- );
- expect(countOccurrences(sql, 'EXISTS')).toBe(1);
- expect(
- Object.entries(parameters)
- .filter(([name]) => name.startsWith('recordShareObjectMetadataId_'))
- .map(([, value]) => value),
- ).toEqual([ATTACHMENT_OBJECT_METADATA_ID]);
- });
-
- it('should correlate a gated parent through the parent row under its policy', () => {
- const { sql, parameters } = build([
- personParent({ kind: 'open' }),
- noteParent({
- kind: 'gated',
- condition: {
- sql: '"attachment_targetNoteId"."companyId" IS NOT NULL',
- parameters: { nested: 'value' },
- },
- }),
- ]);
-
- expect(sql).toContain(
- ' OR "attachment"."targetPersonId" IS NOT NULL OR ("attachment"."targetNoteId" IS NOT NULL AND EXISTS (SELECT 1 FROM "workspace_abc"."note" AS "attachment_targetNoteId" WHERE "attachment_targetNoteId"."id" = "attachment"."targetNoteId" AND "attachment_targetNoteId"."companyId" IS NOT NULL)))',
- );
- expect(countOccurrences(sql, 'EXISTS')).toBe(2);
- expect(sql).not.toContain('"attachment"."targetPersonId" IS NOT NULL AND');
- expect(parameters.nested).toBe('value');
- });
-
- it('should only keep rows shared directly when every parent is denied', () => {
- const { sql } = build([noteParent({ kind: 'denied' })]);
-
- expect(sql.startsWith(OWN_RECORD_SHARE_EXISTS)).toBe(true);
- expect(sql).not.toContain('IS NOT NULL');
- expect(countOccurrences(sql, 'EXISTS')).toBe(1);
- });
-
- it('should accept a live child row, or one trashed with the record, of an OPEN child object', () => {
- const { sql } = build([
- {
- kind: 'children',
- childTableAlias: 'attachment_noteTarget',
- childTableExpression: '"workspace_abc"."noteTarget"',
- childJoinColumnName: 'noteId',
- policy: { kind: 'open' },
- },
- ]);
-
- expect(sql).toContain(
- ' OR 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"))))',
- );
- });
-
- it('should require a readable child row of a gated child object and skip a denied one', () => {
- const { sql, parameters } = build([
- {
- kind: 'children',
- childTableAlias: 'attachment_noteTarget',
- childTableExpression: '"workspace_abc"."noteTarget"',
- childJoinColumnName: 'noteId',
- policy: {
- kind: 'gated',
- condition: {
- sql: '"attachment_noteTarget"."targetPersonId" IS NOT NULL',
- parameters: { nested: 'value' },
- },
- },
- },
- {
- kind: 'children',
- childTableAlias: 'attachment_secret',
- childTableExpression: '"workspace_abc"."secret"',
- childJoinColumnName: 'attachmentId',
- policy: { kind: 'denied' },
- },
- ]);
-
- expect(sql).toContain(
- ' OR 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")) AND "attachment_noteTarget"."targetPersonId" IS NOT NULL))',
- );
- 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/__tests__/evaluate-row-access-policy.util.spec.ts b/packages/twenty-server/src/engine/core-modules/record-share/utils/__tests__/evaluate-row-access-policy.util.spec.ts
index bef301516bf..4871b5e1528 100644
--- a/packages/twenty-server/src/engine/core-modules/record-share/utils/__tests__/evaluate-row-access-policy.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/record-share/utils/__tests__/evaluate-row-access-policy.util.spec.ts
@@ -83,8 +83,8 @@ const recordShares: RecordShareGrant[] = [
];
const buildContext = (
- overrides: Partial<RowAccessEvaluationContext<RowAccessRecord>> = {},
-): RowAccessEvaluationContext<RowAccessRecord> => ({
+ overrides: Partial<RowAccessEvaluationContext> = {},
+): RowAccessEvaluationContext => ({
flatFieldMetadataMaps,
shouldIgnoreSoftDeleteDefaultFilter: false,
fetchRecordShares: jest.fn(async ({ recordIds }) =>
@@ -92,9 +92,6 @@ const buildContext = (
recordIds.includes(recordShare.recordId),
),
),
- resolveRecordIdsReadableThroughParents: jest.fn(
- async () => new Set<string>(),
- ),
...overrides,
});
@@ -187,29 +184,4 @@ describe('evaluateRowAccessPolicy', () => {
recordIds: ['active-private', 'archived-shared'],
});
});
-
- it('asks parents only about records not shared directly', async () => {
- const context = buildContext({
- resolveRecordIdsReadableThroughParents: jest.fn(
- async () => new Set(['active-private']),
- ),
- });
-
- expect(
- await evaluate(
- {
- kind: 'inheritedReadability',
- parents: [],
- isOpenWhenDetached: false,
- ...shareTarget,
- },
- context,
- ),
- ).toEqual(new Set(['active-shared', 'archived-shared', 'active-private']));
- expect(context.resolveRecordIdsReadableThroughParents).toHaveBeenCalledWith(
- expect.objectContaining({
- records: [expect.objectContaining({ id: 'active-private' })],
- }),
- );
- });
});
diff --git a/packages/twenty-server/src/engine/core-modules/record-share/utils/__tests__/resolve-inherited-readability-child-links.util.spec.ts b/packages/twenty-server/src/engine/core-modules/record-share/utils/__tests__/resolve-inherited-readability-child-links.util.spec.ts
deleted file mode 100644
index ba83e59c05a..00000000000
--- a/packages/twenty-server/src/engine/core-modules/record-share/utils/__tests__/resolve-inherited-readability-child-links.util.spec.ts
+++ /dev/null
@@ -1,126 +0,0 @@
-/* @license Enterprise */
-
-import { FieldMetadataType, MetadataReadability } from 'twenty-shared/types';
-
-import { RelationType } from 'src/engine/metadata-modules/field-metadata/interfaces/relation-type.interface';
-
-import { type FlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-maps.type';
-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';
-import { resolveInheritedReadabilityChildLinks } from 'src/engine/core-modules/record-share/utils/resolve-inherited-readability-child-links.util';
-
-const ATTACHMENT_OBJECT_ID = 'attachment-object-id';
-const NOTE_OBJECT_ID = 'note-object-id';
-const NOTE_ATTACHMENTS_FIELD_ID = 'note-attachments-field-id';
-const TARGET_NOTE_FIELD_ID = 'target-note-field-id';
-
-const targetNoteField = getFlatFieldMetadataMock({
- id: TARGET_NOTE_FIELD_ID,
- name: 'targetNote',
- type: FieldMetadataType.MORPH_RELATION,
- universalIdentifier: `${TARGET_NOTE_FIELD_ID}-universal-identifier`,
- objectMetadataId: ATTACHMENT_OBJECT_ID,
- relationTargetObjectMetadataId: NOTE_OBJECT_ID,
- relationTargetFieldMetadataId: NOTE_ATTACHMENTS_FIELD_ID,
- morphId: 'target-morph-id',
- settings: {
- relationType: RelationType.MANY_TO_ONE,
- joinColumnName: 'targetNoteId',
- },
-} as Parameters<typeof getFlatFieldMetadataMock>[0]);
-
-const noteAttachmentsField = getFlatFieldMetadataMock({
- id: NOTE_ATTACHMENTS_FIELD_ID,
- name: 'attachments',
- type: FieldMetadataType.RELATION,
- universalIdentifier: `${NOTE_ATTACHMENTS_FIELD_ID}-universal-identifier`,
- objectMetadataId: NOTE_OBJECT_ID,
- relationTargetObjectMetadataId: ATTACHMENT_OBJECT_ID,
- relationTargetFieldMetadataId: TARGET_NOTE_FIELD_ID,
- settings: { relationType: RelationType.ONE_TO_MANY },
-} as Parameters<typeof getFlatFieldMetadataMock>[0]);
-
-const buildFlatEntityMaps = <T extends FlatFieldMetadata | FlatObjectMetadata>(
- flatEntities: T[],
-): FlatEntityMaps<T> => ({
- byUniversalIdentifier: Object.fromEntries(
- flatEntities.map((flatEntity) => [
- flatEntity.universalIdentifier,
- flatEntity,
- ]),
- ),
- universalIdentifierById: Object.fromEntries(
- flatEntities.map((flatEntity) => [
- flatEntity.id,
- flatEntity.universalIdentifier,
- ]),
- ),
- universalIdentifiersByApplicationId: {},
-});
-
-const attachmentFlatObjectMetadata = getFlatObjectMetadataMock({
- id: ATTACHMENT_OBJECT_ID,
- universalIdentifier: 'attachment-object-universal-identifier',
- nameSingular: 'attachment',
- fieldIds: [targetNoteField.id],
-});
-
-const buildNoteObject = ({
- readability,
- readabilityParentFieldUniversalIdentifiers,
-}: {
- readability: MetadataReadability;
- readabilityParentFieldUniversalIdentifiers: string[] | null;
-}) =>
- getFlatObjectMetadataMock({
- id: NOTE_OBJECT_ID,
- universalIdentifier: 'note-object-universal-identifier',
- nameSingular: 'note',
- fieldIds: [noteAttachmentsField.id],
- readability,
- readabilityParentFieldUniversalIdentifiers,
- });
-
-const resolveForAttachment = (noteFlatObjectMetadata: FlatObjectMetadata) =>
- resolveInheritedReadabilityChildLinks({
- flatObjectMetadata: attachmentFlatObjectMetadata,
- flatFieldMetadataMaps: buildFlatEntityMaps([
- targetNoteField,
- noteAttachmentsField,
- ]),
- flatObjectMetadataMaps: buildFlatEntityMaps([
- attachmentFlatObjectMetadata,
- noteFlatObjectMetadata,
- ]),
- }).map(({ joinColumnName, parentFlatObjectMetadata }) => ({
- joinColumnName,
- parentNameSingular: parentFlatObjectMetadata.nameSingular,
- }));
-
-describe('resolveInheritedReadabilityChildLinks', () => {
- it('should link a row to the records that inherit through it', () => {
- expect(
- resolveForAttachment(
- buildNoteObject({
- readability: MetadataReadability.INHERITED,
- readabilityParentFieldUniversalIdentifiers: [
- noteAttachmentsField.universalIdentifier,
- ],
- }),
- ),
- ).toEqual([{ joinColumnName: 'targetNoteId', parentNameSingular: 'note' }]);
- });
-
- it('should link nothing when the pointed record does not inherit through the row', () => {
- expect(
- resolveForAttachment(
- buildNoteObject({
- readability: MetadataReadability.OPEN,
- readabilityParentFieldUniversalIdentifiers: null,
- }),
- ),
- ).toEqual([]);
- });
-});
diff --git a/packages/twenty-server/src/engine/core-modules/record-share/utils/__tests__/resolve-inherited-readability-parents.util.spec.ts b/packages/twenty-server/src/engine/core-modules/record-share/utils/__tests__/resolve-inherited-readability-parents.util.spec.ts
deleted file mode 100644
index f060964c11b..00000000000
--- a/packages/twenty-server/src/engine/core-modules/record-share/utils/__tests__/resolve-inherited-readability-parents.util.spec.ts
+++ /dev/null
@@ -1,287 +0,0 @@
-/* @license Enterprise */
-
-import { FieldMetadataType, MetadataReadability } from 'twenty-shared/types';
-
-import { RelationType } from 'src/engine/metadata-modules/field-metadata/interfaces/relation-type.interface';
-
-import { type FlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-maps.type';
-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';
-import { resolveInheritedReadabilityParents } from 'src/engine/core-modules/record-share/utils/resolve-inherited-readability-parents.util';
-
-const ATTACHMENT_OBJECT_ID = 'attachment-object-id';
-const NOTE_OBJECT_ID = 'note-object-id';
-const PERSON_OBJECT_ID = 'person-object-id';
-const WORKSPACE_MEMBER_OBJECT_ID = 'workspace-member-object-id';
-const TARGET_MORPH_ID = 'target-morph-id';
-const OTHER_MORPH_ID = 'other-morph-id';
-const NOTE_ATTACHMENTS_FIELD_ID = 'note-attachments-field-id';
-const TARGET_NOTE_FIELD_ID = 'target-note-field-id';
-
-const buildManyToOneField = ({
- id,
- name,
- type,
- objectMetadataId,
- relationTargetObjectMetadataId,
- relationTargetFieldMetadataId,
- morphId,
-}: {
- id: string;
- name: string;
- type: FieldMetadataType.RELATION | FieldMetadataType.MORPH_RELATION;
- objectMetadataId: string;
- relationTargetObjectMetadataId: string;
- relationTargetFieldMetadataId?: string;
- morphId?: string;
-}) =>
- getFlatFieldMetadataMock({
- id,
- name,
- type,
- universalIdentifier: `${id}-universal-identifier`,
- objectMetadataId,
- relationTargetObjectMetadataId,
- relationTargetFieldMetadataId: relationTargetFieldMetadataId ?? null,
- morphId: morphId ?? null,
- settings: {
- relationType: RelationType.MANY_TO_ONE,
- joinColumnName: `${name}Id`,
- },
- } as Parameters<typeof getFlatFieldMetadataMock>[0]);
-
-const targetNoteField = buildManyToOneField({
- id: TARGET_NOTE_FIELD_ID,
- name: 'targetNote',
- type: FieldMetadataType.MORPH_RELATION,
- objectMetadataId: ATTACHMENT_OBJECT_ID,
- relationTargetObjectMetadataId: NOTE_OBJECT_ID,
- relationTargetFieldMetadataId: NOTE_ATTACHMENTS_FIELD_ID,
- morphId: TARGET_MORPH_ID,
-});
-
-const targetPersonField = buildManyToOneField({
- id: 'target-person-field-id',
- name: 'targetPerson',
- type: FieldMetadataType.MORPH_RELATION,
- objectMetadataId: ATTACHMENT_OBJECT_ID,
- relationTargetObjectMetadataId: PERSON_OBJECT_ID,
- morphId: TARGET_MORPH_ID,
-});
-
-const otherMorphField = buildManyToOneField({
- id: 'other-morph-field-id',
- name: 'otherPerson',
- type: FieldMetadataType.MORPH_RELATION,
- objectMetadataId: ATTACHMENT_OBJECT_ID,
- relationTargetObjectMetadataId: PERSON_OBJECT_ID,
- morphId: OTHER_MORPH_ID,
-});
-
-const authorField = buildManyToOneField({
- id: 'author-field-id',
- name: 'author',
- type: FieldMetadataType.RELATION,
- objectMetadataId: ATTACHMENT_OBJECT_ID,
- relationTargetObjectMetadataId: WORKSPACE_MEMBER_OBJECT_ID,
-});
-
-const noteAttachmentsField = getFlatFieldMetadataMock({
- id: NOTE_ATTACHMENTS_FIELD_ID,
- name: 'attachments',
- type: FieldMetadataType.RELATION,
- universalIdentifier: `${NOTE_ATTACHMENTS_FIELD_ID}-universal-identifier`,
- objectMetadataId: NOTE_OBJECT_ID,
- relationTargetObjectMetadataId: ATTACHMENT_OBJECT_ID,
- relationTargetFieldMetadataId: TARGET_NOTE_FIELD_ID,
- settings: { relationType: RelationType.ONE_TO_MANY },
-} as Parameters<typeof getFlatFieldMetadataMock>[0]);
-
-const nameField = getFlatFieldMetadataMock({
- id: 'name-field-id',
- name: 'name',
- type: FieldMetadataType.TEXT,
- universalIdentifier: 'name-field-id-universal-identifier',
- objectMetadataId: ATTACHMENT_OBJECT_ID,
-});
-
-const allFields = [
- targetNoteField,
- targetPersonField,
- otherMorphField,
- authorField,
- noteAttachmentsField,
- nameField,
-];
-
-const attachmentFields = allFields.filter(
- (field) => field.objectMetadataId === ATTACHMENT_OBJECT_ID,
-);
-
-const buildFlatEntityMaps = <T extends FlatFieldMetadata | FlatObjectMetadata>(
- flatEntities: T[],
-): FlatEntityMaps<T> => ({
- byUniversalIdentifier: Object.fromEntries(
- flatEntities.map((flatEntity) => [
- flatEntity.universalIdentifier,
- flatEntity,
- ]),
- ),
- universalIdentifierById: Object.fromEntries(
- flatEntities.map((flatEntity) => [
- flatEntity.id,
- flatEntity.universalIdentifier,
- ]),
- ),
- universalIdentifiersByApplicationId: {},
-});
-
-const buildAttachmentObject = (
- readabilityParentFieldUniversalIdentifiers: string[] | null,
-) =>
- getFlatObjectMetadataMock({
- id: ATTACHMENT_OBJECT_ID,
- universalIdentifier: 'attachment-object-universal-identifier',
- nameSingular: 'attachment',
- fieldIds: attachmentFields.map((field) => field.id),
- readabilityParentFieldUniversalIdentifiers,
- });
-
-const buildNoteObject = ({
- readability,
- readabilityParentFieldUniversalIdentifiers,
-}: {
- readability: MetadataReadability;
- readabilityParentFieldUniversalIdentifiers: string[] | null;
-}) =>
- getFlatObjectMetadataMock({
- id: NOTE_OBJECT_ID,
- universalIdentifier: 'note-object-universal-identifier',
- nameSingular: 'note',
- fieldIds: [noteAttachmentsField.id],
- readability,
- readabilityParentFieldUniversalIdentifiers,
- });
-
-const buildObjectMetadataMaps = ({
- noteFlatObjectMetadata = buildNoteObject({
- readability: MetadataReadability.OPEN,
- readabilityParentFieldUniversalIdentifiers: null,
- }),
-}: { noteFlatObjectMetadata?: FlatObjectMetadata } = {}) =>
- buildFlatEntityMaps([
- buildAttachmentObject(null),
- noteFlatObjectMetadata,
- getFlatObjectMetadataMock({
- id: PERSON_OBJECT_ID,
- universalIdentifier: 'person-object-universal-identifier',
- nameSingular: 'person',
- }),
- getFlatObjectMetadataMock({
- id: WORKSPACE_MEMBER_OBJECT_ID,
- universalIdentifier: 'workspace-member-object-universal-identifier',
- nameSingular: 'workspaceMember',
- }),
- ]);
-
-const describeParent = (
- parent: ReturnType<typeof resolveInheritedReadabilityParents>[number],
-) =>
- parent.kind === 'column'
- ? {
- kind: parent.kind,
- joinColumnName: parent.joinColumnName,
- parentNameSingular: parent.parentFlatObjectMetadata.nameSingular,
- }
- : {
- kind: parent.kind,
- childJoinColumnName: parent.childJoinColumnName,
- childNameSingular: parent.childFlatObjectMetadata.nameSingular,
- };
-
-const resolveForAttachment = (
- readabilityParentFieldUniversalIdentifiers: string[],
-) =>
- resolveInheritedReadabilityParents({
- flatObjectMetadata: buildAttachmentObject(
- readabilityParentFieldUniversalIdentifiers,
- ),
- flatFieldMetadataMaps: buildFlatEntityMaps(allFields),
- flatObjectMetadataMaps: buildObjectMetadataMaps(),
- }).map(describeParent);
-
-describe('resolveInheritedReadabilityParents', () => {
- it('should resolve a declared plain relation field to its join column and parent', () => {
- expect(resolveForAttachment([authorField.universalIdentifier])).toEqual([
- {
- kind: 'column',
- joinColumnName: 'authorId',
- parentNameSingular: 'workspaceMember',
- },
- ]);
- });
-
- it('should expand a declared morph relation field to every field sharing its morph id', () => {
- expect(resolveForAttachment([targetNoteField.universalIdentifier])).toEqual(
- [
- {
- kind: 'column',
- joinColumnName: 'targetNoteId',
- parentNameSingular: 'note',
- },
- {
- kind: 'column',
- joinColumnName: 'targetPersonId',
- parentNameSingular: 'person',
- },
- ],
- );
- });
-
- it('should resolve a declared one-to-many field to the child object and its join column', () => {
- const noteFlatObjectMetadata = buildNoteObject({
- readability: MetadataReadability.INHERITED,
- readabilityParentFieldUniversalIdentifiers: [
- noteAttachmentsField.universalIdentifier,
- ],
- });
-
- expect(
- resolveInheritedReadabilityParents({
- flatObjectMetadata: noteFlatObjectMetadata,
- flatFieldMetadataMaps: buildFlatEntityMaps(allFields),
- flatObjectMetadataMaps: buildObjectMetadataMaps({
- noteFlatObjectMetadata,
- }),
- }).map(describeParent),
- ).toEqual([
- {
- kind: 'children',
- childJoinColumnName: 'targetNoteId',
- childNameSingular: 'attachment',
- },
- ]);
- });
-
- it('should ignore declared fields that are not relations of the object', () => {
- expect(
- resolveForAttachment([
- nameField.universalIdentifier,
- noteAttachmentsField.universalIdentifier,
- 'unknown-universal-identifier',
- ]),
- ).toEqual([]);
- });
-
- it('should resolve nothing when no parent field is declared', () => {
- expect(
- resolveInheritedReadabilityParents({
- flatObjectMetadata: buildAttachmentObject(null),
- flatFieldMetadataMaps: buildFlatEntityMaps(allFields),
- flatObjectMetadataMaps: buildObjectMetadataMaps(),
- }),
- ).toEqual([]);
- });
-});
diff --git a/packages/twenty-server/src/engine/core-modules/record-share/utils/__tests__/resolve-object-sharing.util.spec.ts b/packages/twenty-server/src/engine/core-modules/record-share/utils/__tests__/resolve-object-sharing.util.spec.ts
index e39dc3b571f..e0f25dc87e8 100644
--- a/packages/twenty-server/src/engine/core-modules/record-share/utils/__tests__/resolve-object-sharing.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/record-share/utils/__tests__/resolve-object-sharing.util.spec.ts
@@ -1,92 +1,118 @@
/* @license Enterprise */
-import {
- FeatureFlagKey,
- MetadataReadability,
- ObjectSharingReach,
-} from 'twenty-shared/types';
+import { FeatureFlagKey, MetadataReadability } from 'twenty-shared/types';
import { RecordSharingMode } from 'src/engine/core-modules/record-share/enums/record-sharing-mode.enum';
import { resolveObjectSharing } from 'src/engine/core-modules/record-share/utils/resolve-object-sharing.util';
-const OPEN_OBJECT = {
+const OBJECT = {
readability: MetadataReadability.OPEN,
isSystem: false,
- sharingReach: ObjectSharingReach.WORKSPACE,
+ disabledObjectPermissionActions: null,
};
const RECORD_SHARING = {
[FeatureFlagKey.IS_RECORD_LEVEL_SHARING_ENABLED]: true,
};
describe('resolveObjectSharing', () => {
+ it('should open records by default and let grants view or edit beyond the role', () => {
+ expect(
+ resolveObjectSharing({
+ flatObjectMetadata: OBJECT,
+ featureFlagsMap: RECORD_SHARING,
+ }),
+ ).toEqual({
+ sharingMode: RecordSharingMode.OPEN_BY_DEFAULT,
+ canShareBeyondRole: true,
+ operationTypesGrantedBeyondRole: ['select', 'update'],
+ });
+ });
+
it.each([
- [MetadataReadability.PRIVATE, false, false, RecordSharingMode.PRIVATE],
- [MetadataReadability.PRIVATE, true, false, RecordSharingMode.PRIVATE],
- [MetadataReadability.INHERITED, false, false, RecordSharingMode.INHERITED],
- [MetadataReadability.OPEN, false, true, RecordSharingMode.OPEN_BY_DEFAULT],
- [MetadataReadability.OPEN, false, false, RecordSharingMode.ROLE_ONLY],
- [MetadataReadability.OPEN, true, true, RecordSharingMode.ROLE_ONLY],
- [MetadataReadability.SYSTEM, false, true, RecordSharingMode.ROLE_ONLY],
- [MetadataReadability.APPLICATION, false, true, RecordSharingMode.ROLE_ONLY],
+ { isSystem: false, featureFlagsMap: {} },
+ { isSystem: true, featureFlagsMap: RECORD_SHARING },
])(
- 'should resolve a %s object (system: %s) with record sharing %s to %s',
- (readability, isSystem, isRecordSharingEnabled, sharingMode) => {
+ 'should keep records role-only for %o',
+ ({ isSystem, featureFlagsMap }) => {
expect(
resolveObjectSharing({
- flatObjectMetadata: { ...OPEN_OBJECT, readability, isSystem },
- featureFlagsMap: isRecordSharingEnabled ? RECORD_SHARING : {},
- }).sharingMode,
- ).toBe(sharingMode);
+ flatObjectMetadata: { ...OBJECT, isSystem },
+ featureFlagsMap,
+ }),
+ ).toEqual({
+ sharingMode: RecordSharingMode.ROLE_ONLY,
+ canShareBeyondRole: false,
+ operationTypesGrantedBeyondRole: [],
+ });
},
);
- it('should keep an open object role-only for a workspace without flag rows', () => {
+ it('should not grant beyond the role an operation the object disables', () => {
expect(
resolveObjectSharing({
- flatObjectMetadata: OPEN_OBJECT,
- featureFlagsMap: {},
+ flatObjectMetadata: {
+ ...OBJECT,
+ disabledObjectPermissionActions: ['canUpdateObjectRecords'],
+ },
+ featureFlagsMap: RECORD_SHARING,
+ }).operationTypesGrantedBeyondRole,
+ ).toEqual(['select']);
+ });
+
+ it('should not share beyond the role when the object disables every operation a share could grant', () => {
+ expect(
+ resolveObjectSharing({
+ flatObjectMetadata: {
+ ...OBJECT,
+ disabledObjectPermissionActions: [
+ 'canReadObjectRecords',
+ 'canUpdateObjectRecords',
+ ],
+ },
+ featureFlagsMap: RECORD_SHARING,
}),
- ).toEqual({
- sharingMode: RecordSharingMode.ROLE_ONLY,
+ ).toMatchObject({
canShareBeyondRole: false,
operationTypesGrantedBeyondRole: [],
});
});
it.each([
- MetadataReadability.OPEN,
- MetadataReadability.PRIVATE,
- MetadataReadability.INHERITED,
+ { isSystem: false, featureFlagsMap: {} },
+ { isSystem: true, featureFlagsMap: RECORD_SHARING },
])(
- 'should let a grant on a %s object view or edit beyond the role',
- (readability) => {
+ 'should keep private records private for %o',
+ ({ isSystem, featureFlagsMap }) => {
expect(
resolveObjectSharing({
- flatObjectMetadata: { ...OPEN_OBJECT, readability },
- featureFlagsMap: RECORD_SHARING,
+ flatObjectMetadata: {
+ ...OBJECT,
+ readability: MetadataReadability.PRIVATE,
+ isSystem,
+ },
+ featureFlagsMap,
}),
- ).toMatchObject({
- canShareBeyondRole: true,
- operationTypesGrantedBeyondRole: ['select', 'update'],
+ ).toEqual({
+ sharingMode: RecordSharingMode.PRIVATE,
+ canShareBeyondRole: false,
+ operationTypesGrantedBeyondRole: [],
});
},
);
- it.each([
- { sharingReach: ObjectSharingReach.ROLE_ACCESS },
- { readability: MetadataReadability.SYSTEM },
- { readability: MetadataReadability.APPLICATION },
- { isSystem: true },
- { readability: MetadataReadability.PRIVATE, isSystem: true },
- ])('should keep grants within the role on %o', (object) => {
+ it('should let a grant on a private object view or edit beyond the role', () => {
expect(
resolveObjectSharing({
- flatObjectMetadata: { ...OPEN_OBJECT, ...object },
+ flatObjectMetadata: {
+ ...OBJECT,
+ readability: MetadataReadability.PRIVATE,
+ },
featureFlagsMap: RECORD_SHARING,
}),
- ).toMatchObject({
- canShareBeyondRole: false,
- operationTypesGrantedBeyondRole: [],
+ ).toEqual({
+ sharingMode: RecordSharingMode.PRIVATE,
+ canShareBeyondRole: true,
+ operationTypesGrantedBeyondRole: ['select', 'update'],
});
});
});
diff --git a/packages/twenty-server/src/engine/core-modules/record-share/utils/__tests__/resolve-record-general-access-level.util.spec.ts b/packages/twenty-server/src/engine/core-modules/record-share/utils/__tests__/resolve-record-general-access-level.util.spec.ts
index d6b61e067cf..2e924e39dc5 100644
--- a/packages/twenty-server/src/engine/core-modules/record-share/utils/__tests__/resolve-record-general-access-level.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/record-share/utils/__tests__/resolve-record-general-access-level.util.spec.ts
@@ -29,7 +29,6 @@ describe('resolveRecordGeneralAccessLevel', () => {
it.each([
[RecordSharingMode.OPEN_BY_DEFAULT, RecordShareAccessLevel.READ_WRITE],
[RecordSharingMode.PRIVATE, RecordShareAccessLevel.NONE],
- [RecordSharingMode.INHERITED, RecordShareAccessLevel.NONE],
[RecordSharingMode.ROLE_ONLY, null],
])(
'should fall back to the default of a %s object',
@@ -61,7 +60,7 @@ describe('resolveRecordGeneralAccessLevel', () => {
it('should ignore everyone grants managed by a rule', () => {
expect(
resolveRecordGeneralAccessLevel({
- sharingMode: RecordSharingMode.PRIVATE,
+ sharingMode: RecordSharingMode.OPEN_BY_DEFAULT,
recordShares: [
buildEveryoneShare(
RecordShareAccessLevel.FULL,
@@ -69,7 +68,7 @@ describe('resolveRecordGeneralAccessLevel', () => {
),
],
}),
- ).toBe(RecordShareAccessLevel.NONE);
+ ).toBe(RecordShareAccessLevel.READ_WRITE);
});
it('should report no general access when records are not shared', () => {
diff --git a/packages/twenty-server/src/engine/core-modules/record-share/utils/__tests__/resolve-record-share-gate-kind.util.spec.ts b/packages/twenty-server/src/engine/core-modules/record-share/utils/__tests__/resolve-record-share-gate-kind.util.spec.ts
deleted file mode 100644
index f6fb0a6e267..00000000000
--- a/packages/twenty-server/src/engine/core-modules/record-share/utils/__tests__/resolve-record-share-gate-kind.util.spec.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-/* @license Enterprise */
-
-import { MetadataReadability } from 'twenty-shared/types';
-
-import { resolveRecordShareGateKind } from 'src/engine/core-modules/record-share/utils/resolve-record-share-gate-kind.util';
-
-describe('resolveRecordShareGateKind', () => {
- it.each([
- {
- readability: MetadataReadability.OPEN,
- isOwningApplication: false,
- expected: 'open',
- },
- {
- readability: MetadataReadability.OPEN,
- isOwningApplication: true,
- expected: 'open',
- },
- {
- readability: MetadataReadability.INHERITED,
- isOwningApplication: false,
- expected: 'inherited',
- },
- {
- readability: MetadataReadability.INHERITED,
- isOwningApplication: true,
- expected: 'open',
- },
- {
- readability: MetadataReadability.SYSTEM,
- isOwningApplication: false,
- expected: 'deny',
- },
- {
- readability: MetadataReadability.SYSTEM,
- isOwningApplication: true,
- expected: 'deny',
- },
- {
- readability: MetadataReadability.APPLICATION,
- isOwningApplication: false,
- expected: 'deny',
- },
- {
- readability: MetadataReadability.APPLICATION,
- isOwningApplication: true,
- expected: 'open',
- },
- {
- readability: MetadataReadability.PRIVATE,
- isOwningApplication: false,
- expected: 'private',
- },
- {
- readability: MetadataReadability.PRIVATE,
- isOwningApplication: true,
- expected: 'open',
- },
- ])(
- 'should resolve $expected for $readability readability when isOwningApplication is $isOwningApplication',
- ({ readability, isOwningApplication, expected }) => {
- expect(
- resolveRecordShareGateKind({ readability, isOwningApplication }),
- ).toBe(expected);
- },
- );
-});
diff --git a/packages/twenty-server/src/engine/core-modules/record-share/utils/__tests__/resolve-share-with-to-write.util.spec.ts b/packages/twenty-server/src/engine/core-modules/record-share/utils/__tests__/resolve-share-with-to-write.util.spec.ts
index 526460e6aa6..f028763a310 100644
--- a/packages/twenty-server/src/engine/core-modules/record-share/utils/__tests__/resolve-share-with-to-write.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/record-share/utils/__tests__/resolve-share-with-to-write.util.spec.ts
@@ -19,33 +19,29 @@ const EVERYONE_AT_DEFAULT = {
};
describe('resolveShareWithToWrite', () => {
- it.each([RecordSharingMode.PRIVATE, RecordSharingMode.INHERITED])(
- 'should write every entry, and the creator rows, on a %s object',
- (sharingMode) => {
- expect(
- resolveShareWithToWrite({
- sharingMode,
- shareWith: [ROLE_GRANT, EVERYONE_GRANT],
- }),
- ).toEqual([ROLE_GRANT, EVERYONE_GRANT]);
- expect(resolveShareWithToWrite({ sharingMode })).toEqual([]);
- },
- );
+ it('should write every entry, and the creator rows, on a private object', () => {
+ expect(
+ resolveShareWithToWrite({
+ sharingMode: RecordSharingMode.PRIVATE,
+ shareWith: [ROLE_GRANT, EVERYONE_GRANT],
+ }),
+ ).toEqual([ROLE_GRANT, EVERYONE_GRANT]);
+ expect(
+ resolveShareWithToWrite({ sharingMode: RecordSharingMode.PRIVATE }),
+ ).toEqual([]);
+ });
- it.each([RecordSharingMode.PRIVATE, RecordSharingMode.INHERITED])(
- 'should leave no everyone row when everyone keeps the default of a %s object',
- (sharingMode) => {
- expect(
- resolveShareWithToWrite({
- sharingMode,
- shareWith: [
- ROLE_GRANT,
- { everyone: true, accessLevel: RecordShareAccessLevel.NONE },
- ],
- }),
- ).toEqual([ROLE_GRANT]);
- },
- );
+ it('should leave no everyone row when everyone keeps the default of a private object', () => {
+ expect(
+ resolveShareWithToWrite({
+ sharingMode: RecordSharingMode.PRIVATE,
+ shareWith: [
+ ROLE_GRANT,
+ { everyone: true, accessLevel: RecordShareAccessLevel.NONE },
+ ],
+ }),
+ ).toEqual([ROLE_GRANT]);
+ });
it('should write named grants and a general access other than the default on a record open by default', () => {
expect(
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.ts
deleted file mode 100644
index 6b489a5d630..00000000000
--- a/packages/twenty-server/src/engine/core-modules/record-share/utils/build-inherited-readability-condition.util.ts
+++ /dev/null
@@ -1,139 +0,0 @@
-/* @license Enterprise */
-
-import { type RecordShareAccessLevel } from 'twenty-shared/types';
-import { type ObjectLiteral } from 'typeorm';
-
-import {
- type CompiledRowAccessPolicy,
- type SqlCondition,
-} from 'src/engine/twenty-orm/types/row-access-policy.type';
-import { buildRecordShareCondition } from 'src/engine/core-modules/record-share/utils/build-record-share-condition.util';
-import { escapeIdentifier } from 'src/engine/workspace-manager/workspace-migration/utils/remove-sql-injection.util';
-
-export type InheritedReadabilityParentCondition =
- | {
- kind: 'column';
- joinColumnName: string;
- parentTableAlias: string;
- parentTableExpression: string;
- policy: CompiledRowAccessPolicy;
- }
- | {
- kind: 'children';
- childTableAlias: string;
- childTableExpression: string;
- childJoinColumnName: string;
- policy: CompiledRowAccessPolicy;
- };
-
-const buildChildLinkBoundCondition = ({
- quotedTableAlias,
- quotedChildTableAlias,
-}: {
- quotedTableAlias: string;
- quotedChildTableAlias: string;
-}): 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,
- parents,
- recordShareTableExpression,
- principalIds,
- accessLevels,
- isOpenWhenDetached,
-}: {
- tableAlias: string;
- objectMetadataId: string;
- parents: InheritedReadabilityParentCondition[];
- recordShareTableExpression: string;
- principalIds: string[];
- accessLevels: RecordShareAccessLevel[];
- isOpenWhenDetached: boolean;
-}): SqlCondition => {
- const parameters: ObjectLiteral = {};
- const quotedTableAlias = escapeIdentifier(tableAlias);
-
- // The record's own share rows, its creator's included, grant access on their own, as on a PRIVATE record.
- const ownRecordShareCondition = buildRecordShareCondition({
- tableAlias,
- recordShareTableExpression,
- objectMetadataId,
- principalIds,
- accessLevels,
- });
-
- Object.assign(parameters, ownRecordShareCondition.parameters);
-
- const parentConditions = parents.flatMap((parent) => {
- if (parent.policy.kind === 'denied') {
- return [];
- }
-
- if (parent.kind === 'children') {
- const quotedChildTableAlias = escapeIdentifier(parent.childTableAlias);
- const childRowConditions = [
- `${quotedChildTableAlias}.${escapeIdentifier(parent.childJoinColumnName)} = ${quotedTableAlias}."id"`,
- buildChildLinkBoundCondition({
- quotedTableAlias,
- quotedChildTableAlias,
- }),
- ];
-
- if (parent.policy.kind === 'gated') {
- Object.assign(parameters, parent.policy.condition.parameters);
- childRowConditions.push(parent.policy.condition.sql);
- }
-
- return [
- `EXISTS (SELECT 1 FROM ${parent.childTableExpression} AS ${quotedChildTableAlias} WHERE ${childRowConditions.join(' AND ')})`,
- ];
- }
-
- const quotedJoinColumn = `${quotedTableAlias}.${escapeIdentifier(parent.joinColumnName)}`;
- const notNullCondition = `${quotedJoinColumn} IS NOT NULL`;
-
- if (parent.policy.kind === 'open') {
- return [notNullCondition];
- }
-
- const quotedParentTableAlias = escapeIdentifier(parent.parentTableAlias);
-
- Object.assign(parameters, parent.policy.condition.parameters);
-
- return [
- `(${notNullCondition} AND EXISTS (SELECT 1 FROM ${parent.parentTableExpression} AS ${quotedParentTableAlias} WHERE ${quotedParentTableAlias}."id" = ${quotedJoinColumn} AND ${parent.policy.condition.sql}))`,
- ];
- });
-
- // 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, ...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.ts
index 710fcb36869..1ce5ad866e3 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
@@ -1,238 +1,62 @@
/* @license Enterprise */
-import { resolveRecordShareGateKind } from 'src/engine/core-modules/record-share/utils/resolve-record-share-gate-kind.util';
-import { type RecordShareAccessLevel } from 'twenty-shared/types';
-import { assertUnreachable, isDefined } from 'twenty-shared/utils';
+import { isDefined } from 'twenty-shared/utils';
-import { MAX_INHERITED_READABILITY_DEPTH } from 'src/engine/core-modules/record-share/constants/max-inherited-readability-depth.constant';
import { RecordSharingMode } from 'src/engine/core-modules/record-share/enums/record-sharing-mode.enum';
-import { type InheritedReadabilityParent } from 'src/engine/core-modules/record-share/types/inherited-readability-parent.type';
-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 { resolveObjectSharing } from 'src/engine/core-modules/record-share/utils/resolve-object-sharing.util';
import { resolveRequiredRecordShareAccessLevels } from 'src/engine/core-modules/record-share/utils/resolve-required-record-share-access-levels.util';
import {
- type InheritedReadabilityParentExpression,
type RowAccessPolicy,
type RowAccessPolicyContext,
type RowAccessPolicyTarget,
} from 'src/engine/twenty-orm/types/row-access-policy.type';
-import { buildPostgresSafeAlias } from 'src/engine/twenty-orm/sql/utils/build-postgres-safe-alias.util';
-
-type BuildParentPolicy = (target: RowAccessPolicyTarget) => RowAccessPolicy;
-
-type RecordShareGateArgs = {
- context: RowAccessPolicyContext;
- target: RowAccessPolicyTarget;
- buildParentPolicy: BuildParentPolicy;
-};
export const buildRecordShareGate = ({
- context,
- target,
- buildParentPolicy,
-}: RecordShareGateArgs): RowAccessPolicy => {
- const isOwningApplication = context.subject.isOwningApplication(
- target.flatObjectMetadata,
- );
-
- const gateKind = resolveRecordShareGateKind({
- readability: target.flatObjectMetadata.readability,
- isOwningApplication,
- });
+ subject,
+ environment,
+ tableAlias,
+ flatObjectMetadata,
+ operationType,
+}: RowAccessPolicyContext &
+ Pick<
+ RowAccessPolicyTarget,
+ 'tableAlias' | 'flatObjectMetadata' | 'operationType'
+ >): RowAccessPolicy => {
const { sharingMode } = resolveObjectSharing({
- flatObjectMetadata: target.flatObjectMetadata,
- featureFlagsMap: context.environment.featureFlagsMap,
- });
-
- switch (gateKind) {
- case 'open':
- return sharingMode === RecordSharingMode.OPEN_BY_DEFAULT &&
- !context.subject.canAccessAllRecords
- ? buildRecordShareExceptionGate(context, target)
- : { kind: 'open' };
- case 'deny':
- return { kind: 'denied' };
- case 'inherited':
- return buildInheritedReadabilityGate({
- context,
- target,
- buildParentPolicy,
- });
- case 'private':
- return buildOwnRecordShareGate(context, target);
- default:
- return assertUnreachable(gateKind);
- }
-};
-
-const resolveRecordSharePrincipals = (
- { subject }: RowAccessPolicyContext,
- { operationType }: RowAccessPolicyTarget,
-):
- | { principalIds: string[]; accessLevels: RecordShareAccessLevel[] }
- | undefined => {
- if (!isDefined(subject.principalIds)) {
- return undefined;
- }
-
- const accessLevels = resolveRequiredRecordShareAccessLevels(operationType);
-
- if (accessLevels.length === 0) {
- return undefined;
- }
-
- return { principalIds: subject.principalIds, accessLevels };
-};
-
-const buildOwnRecordShareGate = (
- context: RowAccessPolicyContext,
- target: RowAccessPolicyTarget,
-): RowAccessPolicy => {
- const principals = resolveRecordSharePrincipals(context, target);
-
- if (!isDefined(principals)) {
- return { kind: 'open' };
- }
-
- return {
- kind: 'gated',
- expression: {
- kind: 'recordShared',
- tableAlias: target.tableAlias,
- objectMetadataId: target.flatObjectMetadata.id,
- ...principals,
- },
- };
-};
-
-const buildRecordShareExceptionGate = (
- context: RowAccessPolicyContext,
- target: RowAccessPolicyTarget,
-): RowAccessPolicy => {
- const principals = resolveRecordSharePrincipals(context, target);
-
- if (!isDefined(principals)) {
- return { kind: 'open' };
- }
-
- return {
- kind: 'gated',
- expression: {
- kind: 'recordNotRestricted',
- tableAlias: target.tableAlias,
- objectMetadataId: target.flatObjectMetadata.id,
- ...principals,
- },
- };
-};
-
-const buildInheritedReadabilityGate = ({
- context,
- target,
- buildParentPolicy,
-}: RecordShareGateArgs): RowAccessPolicy => {
- const { tableAlias, flatObjectMetadata, depth, joinParentRelationShape } =
- target;
-
- if (depth > MAX_INHERITED_READABILITY_DEPTH) {
- return { kind: 'denied' };
- }
-
- const parents = resolveInheritedReadabilityParents({
flatObjectMetadata,
- flatFieldMetadataMaps: context.environment.flatFieldMetadataMaps,
- flatObjectMetadataMaps: context.environment.flatObjectMetadataMaps,
+ featureFlagsMap: environment.featureFlagsMap,
});
+ const isPrivate =
+ sharingMode === RecordSharingMode.PRIVATE &&
+ !subject.isOwningApplication(flatObjectMetadata);
+
if (
- isDefined(joinParentRelationShape) &&
- parents.some(
- (parent) =>
- parent.kind === 'column' &&
- parent.fieldMetadataId ===
- joinParentRelationShape.targetFieldMetadataId,
- )
+ !isPrivate &&
+ (sharingMode !== RecordSharingMode.OPEN_BY_DEFAULT ||
+ subject.canAccessAllRecords)
) {
return { kind: 'open' };
}
- const isOpenWhenDetached = isOpenWhenDetachedObject(flatObjectMetadata);
-
- if (parents.length === 0) {
- return isOpenWhenDetached
- ? { kind: 'open' }
- : buildOwnRecordShareGate(context, target);
+ if (!isDefined(subject.principalIds)) {
+ return { kind: 'open' };
}
- const principals = resolveRecordSharePrincipals(context, target);
+ const accessLevels = resolveRequiredRecordShareAccessLevels(operationType);
- if (!isDefined(principals)) {
+ if (accessLevels.length === 0) {
return { kind: 'open' };
}
- const parentExpressions = parents.map((parent) =>
- buildInheritedReadabilityParentExpression({
- context,
- target,
- parent,
- buildParentPolicy,
- }),
- );
-
return {
kind: 'gated',
expression: {
- kind: 'inheritedReadability',
+ kind: isPrivate ? 'recordShared' : 'recordNotRestricted',
tableAlias,
objectMetadataId: flatObjectMetadata.id,
- ...principals,
- isOpenWhenDetached,
- parents: parentExpressions,
+ principalIds: subject.principalIds,
+ accessLevels,
},
};
};
-
-const buildInheritedReadabilityParentExpression = ({
- target: { tableAlias, operationType, depth },
- parent,
- buildParentPolicy,
-}: RecordShareGateArgs & {
- parent: InheritedReadabilityParent;
-}): InheritedReadabilityParentExpression => {
- if (parent.kind === 'column') {
- const parentTableAlias = buildPostgresSafeAlias(
- `${tableAlias}_${parent.joinColumnName}`,
- );
-
- return {
- kind: 'column',
- joinColumnName: parent.joinColumnName,
- parentTableAlias,
- parentFlatObjectMetadata: parent.parentFlatObjectMetadata,
- policy: buildParentPolicy({
- tableAlias: parentTableAlias,
- flatObjectMetadata: parent.parentFlatObjectMetadata,
- operationType,
- depth: depth + 1,
- }),
- };
- }
-
- const childTableAlias = buildPostgresSafeAlias(
- `${tableAlias}_${parent.childFlatObjectMetadata.nameSingular}`,
- );
-
- return {
- kind: 'children',
- childTableAlias,
- childJoinColumnName: parent.childJoinColumnName,
- childFlatObjectMetadata: parent.childFlatObjectMetadata,
- policy: buildParentPolicy({
- tableAlias: childTableAlias,
- flatObjectMetadata: parent.childFlatObjectMetadata,
- operationType,
- depth: depth + 1,
- }),
- };
-};
diff --git a/packages/twenty-server/src/engine/core-modules/record-share/utils/evaluate-row-access-policy.util.ts b/packages/twenty-server/src/engine/core-modules/record-share/utils/evaluate-row-access-policy.util.ts
index a2c9893217d..467e6839e7d 100644
--- a/packages/twenty-server/src/engine/core-modules/record-share/utils/evaluate-row-access-policy.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/record-share/utils/evaluate-row-access-policy.util.ts
@@ -15,23 +15,13 @@ import { isRecordMatchingRLSRowLevelPermissionPredicate } from 'src/engine/twent
export type RowAccessRecord = { id: string } & Record<string, unknown>;
-type InheritedReadabilityExpression = Extract<
- RowAccessExpression,
- { kind: 'inheritedReadability' }
->;
-
-export type RowAccessEvaluationContext<TRecord extends RowAccessRecord> = {
+export type RowAccessEvaluationContext = {
flatFieldMetadataMaps: FlatEntityMaps<OrmFlatFieldMetadata>;
shouldIgnoreSoftDeleteDefaultFilter: boolean;
fetchRecordShares: (args: {
objectMetadataId: string;
recordIds: string[];
}) => Promise<RecordShareGrant[]>;
- // Parents live in other tables, so whoever holds the records resolves them
- resolveRecordIdsReadableThroughParents: (args: {
- expression: InheritedReadabilityExpression;
- records: TRecord[];
- }) => Promise<Set<string>>;
};
// The in-memory counterpart of compileRowAccessPolicy: both read the same
@@ -43,7 +33,7 @@ export const evaluateRowAccessPolicy = async <TRecord extends RowAccessRecord>({
}: {
policy: RowAccessPolicy;
records: TRecord[];
- context: RowAccessEvaluationContext<TRecord>;
+ context: RowAccessEvaluationContext;
}): Promise<Set<string>> => {
switch (policy.kind) {
case 'open':
@@ -68,7 +58,7 @@ const evaluateRowAccessExpression = async <TRecord extends RowAccessRecord>({
}: {
expression: RowAccessExpression;
records: TRecord[];
- context: RowAccessEvaluationContext<TRecord>;
+ context: RowAccessEvaluationContext;
}): Promise<Set<string>> => {
if (records.length === 0) {
return new Set();
@@ -162,26 +152,6 @@ const evaluateRowAccessExpression = async <TRecord extends RowAccessRecord>({
return new Set(admittedRecordIds);
}
- case 'inheritedReadability': {
- const sharedRecordIds = await evaluateRowAccessExpression({
- expression: {
- kind: 'recordShared',
- tableAlias: expression.tableAlias,
- objectMetadataId: expression.objectMetadataId,
- principalIds: expression.principalIds,
- accessLevels: expression.accessLevels,
- },
- records,
- context,
- });
- const readableThroughParentIds =
- await context.resolveRecordIdsReadableThroughParents({
- expression,
- records: records.filter((record) => !sharedRecordIds.has(record.id)),
- });
-
- return new Set([...sharedRecordIds, ...readableThroughParentIds]);
- }
default:
return assertUnreachable(expression);
}
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.ts
deleted file mode 100644
index 3b3fb647ec9..00000000000
--- a/packages/twenty-server/src/engine/core-modules/record-share/utils/is-open-when-detached-object.util.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-/* @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/src/engine/core-modules/record-share/utils/is-record-share-exception-object.util.ts b/packages/twenty-server/src/engine/core-modules/record-share/utils/is-record-share-exception-object.util.ts
index 94d57b604e4..9ff4e6486ae 100644
--- a/packages/twenty-server/src/engine/core-modules/record-share/utils/is-record-share-exception-object.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/record-share/utils/is-record-share-exception-object.util.ts
@@ -9,5 +9,5 @@ import { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object
export const isRecordShareExceptionObject = (
flatObjectMetadata: Pick<FlatObjectMetadata, 'readability' | 'isSystem'>,
): boolean =>
- flatObjectMetadata.readability === MetadataReadability.OPEN &&
+ flatObjectMetadata.readability !== MetadataReadability.PRIVATE &&
!flatObjectMetadata.isSystem;
diff --git a/packages/twenty-server/src/engine/core-modules/record-share/utils/omit-inherited-readability-child-records.util.ts b/packages/twenty-server/src/engine/core-modules/record-share/utils/omit-inherited-readability-child-records.util.ts
deleted file mode 100644
index 8086bf7f60b..00000000000
--- a/packages/twenty-server/src/engine/core-modules/record-share/utils/omit-inherited-readability-child-records.util.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-/* @license Enterprise */
-
-import { type ObjectRecordEvent } from 'twenty-shared/database-events';
-import { isDefined } from 'twenty-shared/utils';
-
-import { type InheritedReadabilityChildRecordsCarrier } from 'src/engine/core-modules/record-share/types/inherited-readability-child-records.type';
-
-export const omitInheritedReadabilityChildRecords = <
- TEvent extends ObjectRecordEvent,
->(
- event: TEvent,
-): TEvent => {
- const { inheritedReadabilityChildRecords, ...properties } =
- event.properties as TEvent['properties'] &
- InheritedReadabilityChildRecordsCarrier;
-
- return isDefined(inheritedReadabilityChildRecords)
- ? ({ ...event, properties } as TEvent)
- : event;
-};
diff --git a/packages/twenty-server/src/engine/core-modules/record-share/utils/resolve-event-record-snapshots.util.ts b/packages/twenty-server/src/engine/core-modules/record-share/utils/resolve-event-record-snapshots.util.ts
index 339c494c272..c5246acef86 100644
--- a/packages/twenty-server/src/engine/core-modules/record-share/utils/resolve-event-record-snapshots.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/record-share/utils/resolve-event-record-snapshots.util.ts
@@ -5,27 +5,16 @@ import {
type ObjectRecordEvent,
} from 'twenty-shared/database-events';
-import {
- type InheritedReadabilityChildRecords,
- type InheritedReadabilityChildRecordsCarrier,
-} from 'src/engine/core-modules/record-share/types/inherited-readability-child-records.type';
-
-export type EventRecordSnapshot = {
- id: string;
- inheritedReadabilityChildRecords?: InheritedReadabilityChildRecords;
-} & Record<string, unknown>;
+import { type RowAccessRecord } from 'src/engine/core-modules/record-share/utils/evaluate-row-access-policy.util';
export const resolveEventRecordSnapshots = (
events: ObjectRecordEvent[],
-): EventRecordSnapshot[] =>
+): RowAccessRecord[] =>
events.map((event) => {
- const properties = event.properties as ObjectRecordBaseEvent['properties'] &
- InheritedReadabilityChildRecordsCarrier;
+ const properties = event.properties as ObjectRecordBaseEvent['properties'];
return {
...(properties.after ?? properties.before ?? {}),
id: event.recordId,
- inheritedReadabilityChildRecords:
- properties.inheritedReadabilityChildRecords,
};
});
diff --git a/packages/twenty-server/src/engine/core-modules/record-share/utils/resolve-inherited-readability-child-links.util.ts b/packages/twenty-server/src/engine/core-modules/record-share/utils/resolve-inherited-readability-child-links.util.ts
deleted file mode 100644
index 0771feae269..00000000000
--- a/packages/twenty-server/src/engine/core-modules/record-share/utils/resolve-inherited-readability-child-links.util.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-/* @license Enterprise */
-
-import { MetadataReadability } from 'twenty-shared/types';
-import { isDefined } from 'twenty-shared/utils';
-
-import { computeMorphOrRelationFieldJoinColumnName } from 'src/engine/metadata-modules/field-metadata/utils/compute-morph-or-relation-field-join-column-name.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 { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';
-import { type InheritedReadabilityParentLink } from 'src/engine/core-modules/record-share/types/inherited-readability-parent-link.type';
-import { getRelationFlatFieldMetadatasOfObject } from 'src/engine/twenty-orm/utils/get-relation-flat-field-metadatas-of-object.util';
-import { isManyToOneFlatFieldMetadata } from 'src/engine/twenty-orm/utils/is-many-to-one-flat-field-metadata.util';
-
-// The records of other objects that inherit their readability through the rows
-// of this object: writing such a row grants access to the record it points at
-export const resolveInheritedReadabilityChildLinks = ({
- flatObjectMetadata,
- flatFieldMetadataMaps,
- flatObjectMetadataMaps,
-}: {
- flatObjectMetadata: FlatObjectMetadata;
- flatFieldMetadataMaps: FlatEntityMaps<OrmFlatFieldMetadata>;
- flatObjectMetadataMaps: FlatEntityMaps<FlatObjectMetadata>;
-}): InheritedReadabilityParentLink[] =>
- getRelationFlatFieldMetadatasOfObject({
- flatObjectMetadata,
- flatFieldMetadataMaps,
- })
- .filter(isManyToOneFlatFieldMetadata)
- .flatMap((flatFieldMetadata) => {
- const parentFlatObjectMetadata = findFlatEntityByIdInFlatEntityMaps({
- flatEntityMaps: flatObjectMetadataMaps,
- flatEntityId: flatFieldMetadata.relationTargetObjectMetadataId,
- });
- const parentFlatFieldMetadata = findFlatEntityByIdInFlatEntityMaps({
- flatEntityMaps: flatFieldMetadataMaps,
- flatEntityId: flatFieldMetadata.relationTargetFieldMetadataId,
- });
-
- if (
- !isDefined(parentFlatObjectMetadata) ||
- !isDefined(parentFlatFieldMetadata) ||
- parentFlatObjectMetadata.readability !==
- MetadataReadability.INHERITED ||
- !(
- parentFlatObjectMetadata.readabilityParentFieldUniversalIdentifiers ??
- []
- ).includes(parentFlatFieldMetadata.universalIdentifier)
- ) {
- return [];
- }
-
- return [
- {
- joinColumnName: computeMorphOrRelationFieldJoinColumnName({
- name: flatFieldMetadata.name,
- }),
- parentFlatObjectMetadata,
- },
- ];
- });
diff --git a/packages/twenty-server/src/engine/core-modules/record-share/utils/resolve-object-sharing.util.ts b/packages/twenty-server/src/engine/core-modules/record-share/utils/resolve-object-sharing.util.ts
index 46e113907e6..99cfa72fc90 100644
--- a/packages/twenty-server/src/engine/core-modules/record-share/utils/resolve-object-sharing.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/record-share/utils/resolve-object-sharing.util.ts
@@ -1,22 +1,24 @@
/* @license Enterprise */
-import {
- FeatureFlagKey,
- MetadataReadability,
- ObjectSharingReach,
-} from 'twenty-shared/types';
+import { type ObjectPermissionAction } from 'twenty-shared/application';
+import { FeatureFlagKey, MetadataReadability } from 'twenty-shared/types';
+
+import { isNonEmptyArray } from 'twenty-shared/utils';
-import { RecordSharingMode } from 'src/engine/core-modules/record-share/enums/record-sharing-mode.enum';
import { isRecordShareExceptionObject } from 'src/engine/core-modules/record-share/utils/is-record-share-exception-object.util';
+import { RecordSharingMode } from 'src/engine/core-modules/record-share/enums/record-sharing-mode.enum';
import { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';
import { type OperationType } from 'src/engine/twenty-orm/repository/permissions.utils';
// A record shared by name reaches people whose role cannot otherwise access
// its object, but only to view or edit it: deleting it, creating siblings or
// managing its access stay with the roles that can access the object
-const OPERATION_TYPES_GRANTABLE_BEYOND_ROLE: OperationType[] = [
- 'select',
- 'update',
+const OPERATIONS_GRANTABLE_BEYOND_ROLE: {
+ operationType: OperationType;
+ objectPermissionAction: ObjectPermissionAction;
+}[] = [
+ { operationType: 'select', objectPermissionAction: 'canReadObjectRecords' },
+ { operationType: 'update', objectPermissionAction: 'canUpdateObjectRecords' },
];
export type ObjectSharing = {
@@ -25,53 +27,47 @@ export type ObjectSharing = {
operationTypesGrantedBeyondRole: OperationType[];
};
-const resolveSharingMode = ({
- flatObjectMetadata,
- isRecordSharingEnabled,
-}: {
- flatObjectMetadata: Pick<FlatObjectMetadata, 'readability' | 'isSystem'>;
- isRecordSharingEnabled: boolean;
-}): RecordSharingMode => {
- switch (flatObjectMetadata.readability) {
- case MetadataReadability.PRIVATE:
- return RecordSharingMode.PRIVATE;
- case MetadataReadability.INHERITED:
- return RecordSharingMode.INHERITED;
- default:
- return isRecordSharingEnabled &&
- isRecordShareExceptionObject(flatObjectMetadata)
- ? RecordSharingMode.OPEN_BY_DEFAULT
- : RecordSharingMode.ROLE_ONLY;
- }
-};
-
export const resolveObjectSharing = ({
flatObjectMetadata,
featureFlagsMap,
}: {
flatObjectMetadata: Pick<
FlatObjectMetadata,
- 'readability' | 'isSystem' | 'sharingReach'
+ 'readability' | 'isSystem' | 'disabledObjectPermissionActions'
>;
featureFlagsMap: Partial<Record<FeatureFlagKey, boolean>>;
}): ObjectSharing => {
const isRecordSharingEnabled =
featureFlagsMap[FeatureFlagKey.IS_RECORD_LEVEL_SHARING_ENABLED] ?? false;
- const sharingMode = resolveSharingMode({
- flatObjectMetadata,
- isRecordSharingEnabled,
- });
- const canShareBeyondRole =
- isRecordSharingEnabled &&
- sharingMode !== RecordSharingMode.ROLE_ONLY &&
- !flatObjectMetadata.isSystem &&
- flatObjectMetadata.sharingReach === ObjectSharingReach.WORKSPACE;
+
+ // Private records are only reached through their shares, whatever the flag
+ const sharingMode =
+ flatObjectMetadata.readability === MetadataReadability.PRIVATE
+ ? RecordSharingMode.PRIVATE
+ : isRecordSharingEnabled &&
+ isRecordShareExceptionObject(flatObjectMetadata)
+ ? RecordSharingMode.OPEN_BY_DEFAULT
+ : RecordSharingMode.ROLE_ONLY;
+
+ if (!isRecordSharingEnabled || flatObjectMetadata.isSystem) {
+ return {
+ sharingMode,
+ canShareBeyondRole: false,
+ operationTypesGrantedBeyondRole: [],
+ };
+ }
+
+ const operationTypesGrantedBeyondRole =
+ OPERATIONS_GRANTABLE_BEYOND_ROLE.filter(
+ ({ objectPermissionAction }) =>
+ !flatObjectMetadata.disabledObjectPermissionActions?.includes(
+ objectPermissionAction,
+ ),
+ ).map(({ operationType }) => operationType);
return {
sharingMode,
- canShareBeyondRole,
- operationTypesGrantedBeyondRole: canShareBeyondRole
- ? OPERATION_TYPES_GRANTABLE_BEYOND_ROLE
- : [],
+ canShareBeyondRole: isNonEmptyArray(operationTypesGrantedBeyondRole),
+ operationTypesGrantedBeyondRole,
};
};
diff --git a/packages/twenty-server/src/engine/core-modules/record-share/utils/resolve-record-share-gate-kind.util.ts b/packages/twenty-server/src/engine/core-modules/record-share/utils/resolve-record-share-gate-kind.util.ts
deleted file mode 100644
index 3d29186a9c1..00000000000
--- a/packages/twenty-server/src/engine/core-modules/record-share/utils/resolve-record-share-gate-kind.util.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-/* @license Enterprise */
-
-import { MetadataReadability } from 'twenty-shared/types';
-import { assertUnreachable } from 'twenty-shared/utils';
-
-export type RecordShareGateKind = 'open' | 'deny' | 'private' | 'inherited';
-
-export const resolveRecordShareGateKind = ({
- readability,
- isOwningApplication,
-}: {
- readability: MetadataReadability;
- isOwningApplication: boolean;
-}): RecordShareGateKind => {
- switch (readability) {
- case MetadataReadability.OPEN:
- return 'open';
- case MetadataReadability.SYSTEM:
- return 'deny';
- case MetadataReadability.APPLICATION:
- return isOwningApplication ? 'open' : 'deny';
- case MetadataReadability.PRIVATE:
- return isOwningApplication ? 'open' : 'private';
- case MetadataReadability.INHERITED:
- return isOwningApplication ? 'open' : 'inherited';
- default:
- assertUnreachable(readability);
- }
-};
diff --git a/packages/twenty-server/src/engine/core-modules/record-share/utils/resolve-share-with-to-write.util.ts b/packages/twenty-server/src/engine/core-modules/record-share/utils/resolve-share-with-to-write.util.ts
index 8aa8a7999bc..d16ae59d05f 100644
--- a/packages/twenty-server/src/engine/core-modules/record-share/utils/resolve-share-with-to-write.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/record-share/utils/resolve-share-with-to-write.util.ts
@@ -17,7 +17,10 @@ export const resolveShareWithToWrite = ({
sharingMode: RecordSharingMode;
shareWith?: ShareWithInput[] | null;
}): ShareWithInput[] | null => {
- if (sharingMode === RecordSharingMode.ROLE_ONLY) {
+ if (
+ sharingMode === RecordSharingMode.ROLE_ONLY ||
+ sharingMode === RecordSharingMode.INHERITED
+ ) {
return null;
}
@@ -33,7 +36,6 @@ export const resolveShareWithToWrite = ({
case RecordSharingMode.OPEN_BY_DEFAULT:
return isNonEmptyArray(shareWithToWrite) ? shareWithToWrite : null;
case RecordSharingMode.PRIVATE:
- case RecordSharingMode.INHERITED:
return shareWithToWrite;
default:
return assertUnreachable(sharingMode);
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-trigger/jobs/call-agent-database-event-triggers.job.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-trigger/jobs/call-agent-database-event-triggers.job.ts
index 801011e6f5e..7f0d57bb085 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-trigger/jobs/call-agent-database-event-triggers.job.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-trigger/jobs/call-agent-database-event-triggers.job.ts
@@ -13,7 +13,6 @@ import { MessageQueueService } from 'src/engine/core-modules/message-queue/servi
import { RecordAccessPolicyService } from 'src/engine/core-modules/record-share/services/record-access-policy.service';
import { buildRoleRowAccessPolicySubject } from 'src/engine/core-modules/record-share/utils/build-role-row-access-policy-subject.util';
import { isUpdateOfHiddenFieldsOnly } from 'src/engine/core-modules/record-share/utils/is-update-of-hidden-fields-only.util';
-import { omitInheritedReadabilityChildRecords } from 'src/engine/core-modules/record-share/utils/omit-inherited-readability-child-records.util';
import { omitRestrictedFieldsFromEvent } from 'src/engine/metadata-modules/permissions/utils/omit-restricted-fields-from-event.util';
import { AGENT_TRIGGER_RUN_LIMITS } from 'src/engine/metadata-modules/ai/ai-agent-trigger/constants/agent-trigger-run-limits.const';
import { RunAgentTriggerJob } from 'src/engine/metadata-modules/ai/ai-agent-trigger/jobs/run-agent-trigger.job';
@@ -114,15 +113,13 @@ export class CallAgentDatabaseEventTriggersJob {
}),
)
.map((event) =>
- omitInheritedReadabilityChildRecords(
- omitRestrictedFieldsFromEvent({
- event,
- objectMetadata,
- objectsPermissions: agentObjectsPermissions,
- flatObjectMetadataMaps,
- flatFieldMetadataMaps,
- }),
- ),
+ omitRestrictedFieldsFromEvent({
+ event,
+ objectMetadata,
+ objectsPermissions: agentObjectsPermissions,
+ flatObjectMetadataMaps,
+ flatFieldMetadataMaps,
+ }),
)
.filter((event) => !isUpdateOfHiddenFieldsOnly(event));
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/utils/__tests__/get-database-crud-tool-flat-objects.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/utils/__tests__/get-database-crud-tool-flat-objects.util.spec.ts
index 33b2795ade2..50ded342875 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/utils/__tests__/get-database-crud-tool-flat-objects.util.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/utils/__tests__/get-database-crud-tool-flat-objects.util.spec.ts
@@ -1,62 +1,24 @@
import { STANDARD_OBJECTS } from 'twenty-shared/metadata';
-import { MetadataReadability } from 'twenty-shared/types';
import { getDatabaseCrudToolFlatObjects } from 'src/engine/metadata-modules/ai/ai-agent/utils/get-database-crud-tool-flat-objects.util';
-const createObject = (
- universalIdentifier: string,
- readability = MetadataReadability.OPEN,
-) => ({
+const createObject = (universalIdentifier: string) => ({
universalIdentifier,
applicationUniversalIdentifier: 'test-application',
isActive: true,
- readability,
});
describe('getDatabaseCrudToolFlatObjects', () => {
- it('excludes internal history and record sharing objects from generic tools', () => {
+ it('keeps active objects available for subsequent permission checks', () => {
const company = createObject(STANDARD_OBJECTS.company.universalIdentifier);
- const systemObjects = [
- STANDARD_OBJECTS.agentChatThread,
- STANDARD_OBJECTS.agentMessage,
- STANDARD_OBJECTS.agentMessagePart,
- STANDARD_OBJECTS.agentTurn,
- STANDARD_OBJECTS.recordShare,
- ].map(({ universalIdentifier }) =>
- createObject(universalIdentifier, MetadataReadability.SYSTEM),
- );
+ const systemObject = { ...createObject('test-object'), isSystem: true };
- expect(
- getDatabaseCrudToolFlatObjects(
- Object.fromEntries(
- [company, ...systemObjects].map((objectMetadata) => [
- objectMetadata.universalIdentifier,
- objectMetadata,
- ]),
- ),
- ),
- ).toEqual([company]);
+ expect(getDatabaseCrudToolFlatObjects({ company, systemObject })).toEqual([
+ company,
+ systemObject,
+ ]);
});
- it.each([
- MetadataReadability.OPEN,
- MetadataReadability.APPLICATION,
- MetadataReadability.PRIVATE,
- MetadataReadability.INHERITED,
- ])(
- 'keeps %s objects available for subsequent permission checks',
- (readability) => {
- const objectMetadata = {
- ...createObject('test-object', readability),
- isSystem: true,
- };
-
- expect(getDatabaseCrudToolFlatObjects({ objectMetadata })).toEqual([
- objectMetadata,
- ]);
- },
- );
-
it('continues excluding missing, inactive and workflow objects', () => {
const inactive = { ...createObject('inactive'), isActive: false };
const workflow = createObject(
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/utils/get-database-crud-tool-flat-objects.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/utils/get-database-crud-tool-flat-objects.util.ts
index ccaec45068f..482573d0825 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/utils/get-database-crud-tool-flat-objects.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/utils/get-database-crud-tool-flat-objects.util.ts
@@ -1,4 +1,3 @@
-import { MetadataReadability } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
import { isWorkflowRelatedObject } from 'src/engine/metadata-modules/ai/ai-agent/utils/is-workflow-related-object.util';
@@ -9,7 +8,6 @@ import {
type FlatObjectWithActivityAndIdentifier = OverridableFlatEntity & {
isActive: boolean;
- readability: MetadataReadability;
universalIdentifier: string;
};
@@ -22,12 +20,10 @@ export const getDatabaseCrudToolFlatObjects = <
.filter(isDefined)
.filter(
(objectMetadata) =>
- objectMetadata.readability !== MetadataReadability.SYSTEM &&
resolveEffectiveFlatEntityProperty({
metadataName: 'objectMetadata',
flatEntity: objectMetadata,
property: 'isActive',
- }) &&
- !isWorkflowRelatedObject(objectMetadata),
+ }) && !isWorkflowRelatedObject(objectMetadata),
);
};
diff --git a/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/types/orm-flat-field-metadata.type.ts b/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/types/orm-flat-field-metadata.type.ts
index 4e56ea947cb..1ff6e060f70 100644
--- a/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/types/orm-flat-field-metadata.type.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/types/orm-flat-field-metadata.type.ts
@@ -16,7 +16,6 @@ export const ORM_FLAT_FIELD_METADATA_KEYS = [
'settings',
'isNullable',
'isUnique',
- 'writability',
'relationTargetFieldMetadataId',
'relationTargetObjectMetadataId',
'morphId',
diff --git a/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/validators/utils/__tests__/validate-ts-vector-flat-field-metadata.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/validators/utils/__tests__/validate-ts-vector-flat-field-metadata.util.spec.ts
index 0852e45f55c..8c39096d570 100644
--- a/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/validators/utils/__tests__/validate-ts-vector-flat-field-metadata.util.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/validators/utils/__tests__/validate-ts-vector-flat-field-metadata.util.spec.ts
@@ -1,67 +1,41 @@
-import { FieldMetadataType, MetadataWritability } from 'twenty-shared/types';
+import { FieldMetadataType } from 'twenty-shared/types';
import { validateTsVectorFlatFieldMetadata } from 'src/engine/metadata-modules/flat-field-metadata/validators/utils/validate-ts-vector-flat-field-metadata.util';
-import { type UniversalFlatEntityUpdate } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-entity-update.type';
import { type UniversalFlatFieldMetadata } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-field-metadata.type';
-const createFlatEntityToValidate = (
+const callValidator = (
overrides: Partial<
UniversalFlatFieldMetadata<FieldMetadataType.TS_VECTOR>
> = {},
-): UniversalFlatFieldMetadata<FieldMetadataType.TS_VECTOR> =>
- ({
- type: FieldMetadataType.TS_VECTOR,
- name: 'searchVector',
- isSystem: true,
- writability: MetadataWritability.SYSTEM,
- ...overrides,
- }) as UniversalFlatFieldMetadata<FieldMetadataType.TS_VECTOR>;
-
-const callValidator = (
- flatEntityToValidate: UniversalFlatFieldMetadata<FieldMetadataType.TS_VECTOR>,
- update?: UniversalFlatEntityUpdate<'fieldMetadata'>,
) =>
validateTsVectorFlatFieldMetadata({
- flatEntityToValidate,
- update,
+ flatEntityToValidate: {
+ type: FieldMetadataType.TS_VECTOR,
+ name: 'searchVector',
+ isSystem: true,
+ ...overrides,
+ },
} as Parameters<typeof validateTsVectorFlatFieldMetadata>[0]);
describe('validateTsVectorFlatFieldMetadata', () => {
- it('should return no errors for a SYSTEM writability search vector', () => {
- const errors = callValidator(createFlatEntityToValidate());
-
- expect(errors).toEqual([]);
+ it('should return no errors for a system search vector', () => {
+ expect(callValidator()).toEqual([]);
});
- it('should reject a create with non-SYSTEM writability', () => {
- const errors = callValidator(
- createFlatEntityToValidate({ writability: MetadataWritability.OPEN }),
- );
-
- expect(errors).toHaveLength(1);
- expect(errors[0].message).toBe(
- 'Field type TS_VECTOR must have SYSTEM writability',
- );
+ it('should reject a search vector with another name', () => {
+ expect(callValidator({ name: 'otherVector' })).toEqual([
+ expect.objectContaining({
+ message:
+ 'Field type TS_VECTOR must be named "searchVector", got "otherVector"',
+ }),
+ ]);
});
- it('should reject an update that sets non-SYSTEM writability', () => {
- const errors = callValidator(
- createFlatEntityToValidate({ writability: MetadataWritability.OPEN }),
- { writability: MetadataWritability.OPEN },
- );
-
- expect(errors).toHaveLength(1);
- expect(errors[0].message).toBe(
- 'Field type TS_VECTOR must have SYSTEM writability',
- );
- });
-
- it('should accept an update leaving writability untouched on a not-yet-migrated OPEN search vector', () => {
- const errors = callValidator(
- createFlatEntityToValidate({ writability: MetadataWritability.OPEN }),
- { isActive: false },
- );
-
- expect(errors).toEqual([]);
+ it('should reject a search vector that is not a system field', () => {
+ expect(callValidator({ isSystem: false })).toEqual([
+ expect.objectContaining({
+ message: 'Field type TS_VECTOR must be a system field',
+ }),
+ ]);
});
});
diff --git a/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/validators/utils/validate-ts-vector-flat-field-metadata.util.ts b/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/validators/utils/validate-ts-vector-flat-field-metadata.util.ts
index 7072699ecc4..cd8e14a6235 100644
--- a/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/validators/utils/validate-ts-vector-flat-field-metadata.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/validators/utils/validate-ts-vector-flat-field-metadata.util.ts
@@ -1,9 +1,5 @@
import { msg } from '@lingui/core/macro';
-import {
- MetadataWritability,
- type FieldMetadataType,
-} from 'twenty-shared/types';
-import { isDefined } from 'twenty-shared/utils';
+import { type FieldMetadataType } from 'twenty-shared/types';
import { FieldMetadataExceptionCode } from 'src/engine/metadata-modules/field-metadata/field-metadata.exception';
import { type FlatFieldMetadataTypeValidationArgs } from 'src/engine/metadata-modules/flat-field-metadata/types/flat-field-metadata-type-validator.type';
@@ -11,7 +7,6 @@ import { type FlatFieldMetadataValidationError } from 'src/engine/metadata-modul
export const validateTsVectorFlatFieldMetadata = ({
flatEntityToValidate,
- update,
}: FlatFieldMetadataTypeValidationArgs<FieldMetadataType.TS_VECTOR>): FlatFieldMetadataValidationError[] => {
const errors: FlatFieldMetadataValidationError[] = [];
@@ -33,20 +28,5 @@ export const validateTsVectorFlatFieldMetadata = ({
});
}
- const isUpdateLeavingWritabilityUntouched =
- isDefined(update) && !('writability' in update);
-
- if (
- !isUpdateLeavingWritabilityUntouched &&
- flatEntityToValidate.writability !== MetadataWritability.SYSTEM
- ) {
- errors.push({
- code: FieldMetadataExceptionCode.INVALID_FIELD_INPUT,
- message: 'Field type TS_VECTOR must have SYSTEM writability',
- value: flatEntityToValidate.writability,
- userFriendlyMessage: msg`Field type TS_VECTOR must have SYSTEM writability`,
- });
- }
-
return errors;
};
diff --git a/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/object-metadata/services/object-navigation-command-on-create-side-effect-handler.service.ts b/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/object-metadata/services/object-navigation-command-on-create-side-effect-handler.service.ts
index ece106f1f7e..1534f99e4a2 100644
--- a/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/object-metadata/services/object-navigation-command-on-create-side-effect-handler.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/object-metadata/services/object-navigation-command-on-create-side-effect-handler.service.ts
@@ -1,6 +1,5 @@
import { Injectable } from '@nestjs/common';
-import { MetadataReadability } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
import { buildObjectNavigationUniversalFlatCommandMenuItem } from 'src/engine/metadata-modules/flat-command-menu-item/utils/build-object-navigation-universal-flat-command-menu-item.util';
@@ -19,7 +18,7 @@ export class ObjectNavigationCommandOnCreateSideEffectHandlerService extends Met
metadataName: 'objectMetadata',
name: 'objectNavigationCommandOnCreate',
description:
- 'When an object is created, provision its singleton "Go to" navigation command menu item (engineComponentKey NAVIGATION, a null payload and the target in navigationTargetObjectMetadataId), isSystemSideEffect so the engine owns its lifecycle, and isActive mirrors the object so an object created inactive gets a disabled command rather than none. Label, shortLabel and icon are interpolation templates resolved from the object at render time, the availability expression gates on the object read permission plus a feature flag for gated standard objects, and hotKeys derive from the object shortcut. The identifier is name-free and keyed on (application, object), so an object rename keeps the same command. Position is derived from the synced maximum plus the object index in the creation batch, so batch object creation never double-books a position. Noops when the object create carries no workspace id (the manifest sync path mints entity ids after side-effect expansion), and for SYSTEM-readable objects, whose records the API never serves. twenty-standard is not concerned: it synchronizes through the from/to migration path, which never runs the side-effect engine, and seeds one navigation command per active, non-SYSTEM-readable object itself.',
+ 'When an object is created, provision its singleton "Go to" navigation command menu item (engineComponentKey NAVIGATION, a null payload and the target in navigationTargetObjectMetadataId), isSystemSideEffect so the engine owns its lifecycle, and isActive mirrors the object so an object created inactive gets a disabled command rather than none. Label, shortLabel and icon are interpolation templates resolved from the object at render time, the availability expression gates on the object read permission plus a feature flag for gated standard objects, and hotKeys derive from the object shortcut. The identifier is name-free and keyed on (application, object), so an object rename keeps the same command. Position is derived from the synced maximum plus the object index in the creation batch, so batch object creation never double-books a position. Noops when the object create carries no workspace id (the manifest sync path mints entity ids after side-effect expansion), and for objects whose read action is disabled, since their records are never served. twenty-standard is not concerned: it synchronizes through the from/to migration path, which never runs the side-effect engine, and seeds one navigation command per active, readable object itself.',
},
) {
buildSideEffects({
@@ -32,7 +31,9 @@ export class ObjectNavigationCommandOnCreateSideEffectHandlerService extends Met
if (
!isDefined(sourceFlatObjectMetadata.id) ||
- sourceFlatObjectMetadata.readability === MetadataReadability.SYSTEM
+ sourceFlatObjectMetadata.disabledObjectPermissionActions?.includes(
+ 'canReadObjectRecords',
+ )
) {
return { status: 'noop' };
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/webhook/jobs/__tests__/call-webhook-jobs.job.spec.ts b/packages/twenty-server/src/engine/metadata-modules/webhook/jobs/__tests__/call-webhook-jobs.job.spec.ts
index 58cb1f1aa02..efe0fdd9a51 100644
--- a/packages/twenty-server/src/engine/metadata-modules/webhook/jobs/__tests__/call-webhook-jobs.job.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/webhook/jobs/__tests__/call-webhook-jobs.job.spec.ts
@@ -1,5 +1,4 @@
import { Test } from '@nestjs/testing';
-import { MetadataReadability } from 'twenty-shared/types';
import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
import { getQueueToken } from 'src/engine/core-modules/message-queue/utils/get-queue-token.util';
import { RecordAccessPolicyService } from 'src/engine/core-modules/record-share/services/record-access-policy.service';
@@ -11,12 +10,9 @@ import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager
import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
describe('webhook mandatory visibility', () => {
- it('drops missing metadata and SYSTEM batches', async () => {
+ it('drops batches whose object metadata is missing', async () => {
const add = jest.fn();
- const objectMetadata = {
- ...COMPANY_FLAT_OBJECT_MOCK,
- readability: MetadataReadability.SYSTEM,
- };
+ const objectMetadata = COMPANY_FLAT_OBJECT_MOCK;
const maps = {
byUniversalIdentifier: {},
universalIdentifierById: {},
@@ -47,18 +43,9 @@ describe('webhook mandatory visibility', () => {
},
],
}).compile();
- for (const flatObjectMetadataMaps of [
- maps,
- {
- ...maps,
- byUniversalIdentifier: {
- [objectMetadata.universalIdentifier]: objectMetadata,
- },
- universalIdentifierById: {
- [objectMetadata.id]: objectMetadata.universalIdentifier,
- },
- },
- ]) {
+ {
+ const flatObjectMetadataMaps = maps;
+
getOrRecompute.mockResolvedValue({
flatObjectMetadataMaps,
flatFieldMetadataMapsOrm: maps,
diff --git a/packages/twenty-server/src/engine/metadata-modules/webhook/jobs/call-webhook-jobs.job.ts b/packages/twenty-server/src/engine/metadata-modules/webhook/jobs/call-webhook-jobs.job.ts
index aae1871afd0..6339d460a61 100644
--- a/packages/twenty-server/src/engine/metadata-modules/webhook/jobs/call-webhook-jobs.job.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/webhook/jobs/call-webhook-jobs.job.ts
@@ -60,7 +60,6 @@ export class CallWebhookJobsJob {
flatEntityMaps: flatObjectMetadataMaps,
});
- // Without the readability the batch cannot be gated, so nothing may leave
if (!isDefined(flatObjectMetadata)) {
this.logger.warn(
`Object metadata ${workspaceEventBatch.objectMetadata.id} not found for workspace ${workspaceEventBatch.workspaceId}, dropping the webhook batch`,
diff --git a/packages/twenty-server/src/engine/subscriptions/object-record-event/__tests__/object-record-event-publisher.spec.ts b/packages/twenty-server/src/engine/subscriptions/object-record-event/__tests__/object-record-event-publisher.spec.ts
index 655a67f2087..7dd5296b3cd 100644
--- a/packages/twenty-server/src/engine/subscriptions/object-record-event/__tests__/object-record-event-publisher.spec.ts
+++ b/packages/twenty-server/src/engine/subscriptions/object-record-event/__tests__/object-record-event-publisher.spec.ts
@@ -541,9 +541,9 @@ describe('ObjectRecordEventPublisher', () => {
});
it('should not evaluate the record share gate for a stream whose queries target another object', async () => {
- const inheritedObjectMetadata: FlatObjectMetadata = {
+ const privateObjectMetadata: FlatObjectMetadata = {
...companyObjectMetadata,
- readability: MetadataReadability.INHERITED,
+ readability: MetadataReadability.PRIVATE,
};
mockEventStreamService.getStreamsData.mockResolvedValue(
new Map([
@@ -562,7 +562,7 @@ describe('ObjectRecordEventPublisher', () => {
await service.publish({
name: 'company.created',
workspaceId,
- objectMetadata: inheritedObjectMetadata,
+ objectMetadata: privateObjectMetadata,
events: [createMockEvent()],
} as WorkspaceEventBatch<never>);
@@ -574,49 +574,6 @@ describe('ObjectRecordEventPublisher', () => {
).not.toHaveBeenCalled();
});
- it('should not forward the child records captured with a deletion to the stream', async () => {
- await service.publish({
- name: 'company.deleted',
- workspaceId,
- objectMetadata: companyObjectMetadata,
- events: [
- createMockEvent({
- properties: {
- before: { id: 'record-1', name: 'Test Company' },
- after: {
- id: 'record-1',
- name: 'Test Company',
- deletedAt: '2026-09-15T00:00:00.000Z',
- },
- updatedFields: ['deletedAt'],
- diff: {},
- inheritedReadabilityChildRecords: {
- noteTarget: [{ id: 'note-target-1', noteId: 'record-1' }],
- },
- },
- }),
- ],
- } as WorkspaceEventBatch<never>);
-
- const publishCall = (
- mockSubscriptionService.publishToEventStream as jest.Mock
- ).mock.calls[0][0];
-
- expect(
- publishCall.payload.objectRecordEventsWithQueryIds[0].objectRecordEvent
- .properties,
- ).toEqual({
- before: { id: 'record-1', name: 'Test Company' },
- after: {
- id: 'record-1',
- name: 'Test Company',
- deletedAt: '2026-09-15T00:00:00.000Z',
- },
- updatedFields: ['deletedAt'],
- diff: {},
- });
- });
-
it('only publishes shared private records after metadata activation', async () => {
const privateObjectMetadata: FlatObjectMetadata = {
...companyObjectMetadata,
diff --git a/packages/twenty-server/src/engine/subscriptions/object-record-event/object-record-event-publisher.ts b/packages/twenty-server/src/engine/subscriptions/object-record-event/object-record-event-publisher.ts
index 6afce4fe598..0b8d9e71077 100644
--- a/packages/twenty-server/src/engine/subscriptions/object-record-event/object-record-event-publisher.ts
+++ b/packages/twenty-server/src/engine/subscriptions/object-record-event/object-record-event-publisher.ts
@@ -33,7 +33,6 @@ import { type FlatRowLevelPermissionPredicateGroupMaps } from 'src/engine/metada
import { type FlatRowLevelPermissionPredicateMaps } from 'src/engine/metadata-modules/row-level-permission-predicate/types/flat-row-level-permission-predicate-maps.type';
import { RecordAccessPolicyService } from 'src/engine/core-modules/record-share/services/record-access-policy.service';
import { type EventRecordAccessGate } from 'src/engine/core-modules/record-share/types/event-record-access-gate.type';
-import { omitInheritedReadabilityChildRecords } from 'src/engine/core-modules/record-share/utils/omit-inherited-readability-child-records.util';
import { omitRestrictedFieldsFromEvent } from 'src/engine/metadata-modules/permissions/utils/omit-restricted-fields-from-event.util';
import { EventStreamService } from 'src/engine/subscriptions/event-stream.service';
import { SubscriptionService } from 'src/engine/subscriptions/subscription.service';
@@ -233,7 +232,7 @@ export class ObjectRecordEventPublisher {
const eventWithObjectName: ObjectRecordSubscriptionEvent = {
action,
objectNameSingular,
- ...omitInheritedReadabilityChildRecords(event),
+ ...event,
};
const filteredEvent = omitRestrictedFieldsFromEvent({
diff --git a/packages/twenty-server/src/engine/twenty-orm/query-builder/workspace-select-query-builder.ts b/packages/twenty-server/src/engine/twenty-orm/query-builder/workspace-select-query-builder.ts
index 09cfddf116a..26c3bc432a6 100644
--- a/packages/twenty-server/src/engine/twenty-orm/query-builder/workspace-select-query-builder.ts
+++ b/packages/twenty-server/src/engine/twenty-orm/query-builder/workspace-select-query-builder.ts
@@ -51,10 +51,7 @@ import {
type SelectStatementState,
type WhereClause,
} from 'src/engine/twenty-orm/sql/utils/build-select-statement.util';
-import {
- type WorkspaceRelationShape,
- type WorkspaceTableShape,
-} from 'src/engine/twenty-orm/table-shape/types/workspace-table-shape.type';
+import { type WorkspaceTableShape } from 'src/engine/twenty-orm/table-shape/types/workspace-table-shape.type';
import { escapeIdentifier } from 'src/engine/workspace-manager/workspace-migration/utils/remove-sql-injection.util';
let objectWhereParameterSequence = 0;
@@ -719,23 +716,6 @@ export class WorkspaceSelectQueryBuilder implements WhereExpressionLike {
);
}
- getJoinParentRelationShape(
- alias: string,
- ): WorkspaceRelationShape | undefined {
- const clause =
- this.joinClauses.find((joinClause) => joinClause.alias === alias) ??
- this.existsFilterClauses.find(
- (existsFilterClause) => existsFilterClause.alias === alias,
- );
-
- if (!isDefined(clause)) {
- return undefined;
- }
-
- return this.getTableShapeForAlias(clause.parentAlias)
- ?.relationShapeByFieldName[clause.relationFieldName];
- }
-
markRowLevelPermissionApplied(alias: string): boolean {
if (this.aliasesWithRowLevelPermissionApplied.has(alias)) {
return false;
diff --git a/packages/twenty-server/src/engine/twenty-orm/repository/__tests__/validate-writability-or-throw.util.spec.ts b/packages/twenty-server/src/engine/twenty-orm/repository/__tests__/validate-writability-or-throw.util.spec.ts
deleted file mode 100644
index 96c3e9c9911..00000000000
--- a/packages/twenty-server/src/engine/twenty-orm/repository/__tests__/validate-writability-or-throw.util.spec.ts
+++ /dev/null
@@ -1,264 +0,0 @@
-import { MetadataWritability } from 'twenty-shared/types';
-
-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 FlatFieldMetadata } from 'src/engine/metadata-modules/flat-field-metadata/types/flat-field-metadata.type';
-import { type OperationType } from 'src/engine/twenty-orm/repository/permissions.utils';
-import { validateWritabilityOrThrow } from 'src/engine/twenty-orm/repository/validate-writability-or-throw.util';
-
-const OWNING_APPLICATION_ID = 'app-1';
-
-const buildObjectMetadata = (writability: MetadataWritability) => ({
- nameSingular: 'slackUserLink',
- applicationId: OWNING_APPLICATION_ID,
- writability,
-});
-
-const buildFieldMetadataMaps = (
- writability: MetadataWritability,
-): FlatEntityMaps<FlatFieldMetadata> => ({
- universalIdentifierById: { 'field-1': 'field-universal-1' },
- universalIdentifiersByApplicationId: {},
- byUniversalIdentifier: {
- 'field-universal-1': {
- id: 'field-1',
- name: 'status',
- applicationId: OWNING_APPLICATION_ID,
- writability,
- } as FlatFieldMetadata,
- },
-});
-
-const applicationContext = {
- type: 'application',
- workspace: { id: 'workspace-1' },
- application: { id: OWNING_APPLICATION_ID },
-} as WorkspaceAuthContext;
-
-const otherApplicationContext = {
- type: 'application',
- workspace: { id: 'workspace-1' },
- application: { id: 'app-2' },
-} as WorkspaceAuthContext;
-
-const systemContext = {
- type: 'system',
- workspace: { id: 'workspace-1' },
-} as WorkspaceAuthContext;
-
-const apiKeyContext = {
- type: 'apiKey',
- workspace: { id: 'workspace-1' },
- apiKey: { id: 'api-key-1' },
-} as WorkspaceAuthContext;
-
-const userContextCarryingApplication = {
- type: 'user',
- workspace: { id: 'workspace-1' },
- userWorkspaceId: 'user-workspace-1',
- user: { id: 'user-1' },
- workspaceMemberId: 'workspace-member-1',
- workspaceMember: { id: 'workspace-member-1' },
- application: { id: OWNING_APPLICATION_ID },
-} as WorkspaceAuthContext;
-
-const plainUserContext = {
- type: 'user',
- workspace: { id: 'workspace-1' },
- userWorkspaceId: 'user-workspace-1',
- user: { id: 'user-1' },
- workspaceMemberId: 'workspace-member-1',
- workspaceMember: { id: 'workspace-member-1' },
-} as WorkspaceAuthContext;
-
-const otherApplicationUserContext = {
- type: 'user',
- workspace: { id: 'workspace-1' },
- userWorkspaceId: 'user-workspace-1',
- user: { id: 'user-1' },
- workspaceMemberId: 'workspace-member-1',
- workspaceMember: { id: 'workspace-member-1' },
- application: { id: 'app-2' },
-} as WorkspaceAuthContext;
-
-const validate = ({
- objectWritability = MetadataWritability.OPEN,
- fieldWritability = MetadataWritability.OPEN,
- operationType = 'update',
- updatedColumns = ['status'],
- authContext,
-}: {
- objectWritability?: MetadataWritability;
- fieldWritability?: MetadataWritability;
- operationType?: OperationType;
- updatedColumns?: string[];
- authContext: WorkspaceAuthContext | undefined;
-}) =>
- validateWritabilityOrThrow({
- operationType,
- objectMetadata: buildObjectMetadata(objectWritability),
- updatedColumns,
- columnNameToFieldMetadataIdMap: { status: 'field-1' },
- flatFieldMetadataMaps: buildFieldMetadataMaps(fieldWritability),
- authContext,
- });
-
-describe('validateWritabilityOrThrow', () => {
- it('should allow writes on OPEN metadata regardless of context', () => {
- expect(() => validate({ authContext: undefined })).not.toThrow();
- });
-
- it('should never restrict selects', () => {
- expect(() =>
- validate({
- objectWritability: MetadataWritability.SYSTEM,
- operationType: 'select',
- authContext: undefined,
- }),
- ).not.toThrow();
- });
-
- it('should let the owning application write an APPLICATION object', () => {
- expect(() =>
- validate({
- objectWritability: MetadataWritability.APPLICATION,
- authContext: applicationContext,
- }),
- ).not.toThrow();
- });
-
- it('should refuse another application on an APPLICATION object', () => {
- expect(() =>
- validate({
- objectWritability: MetadataWritability.APPLICATION,
- authContext: otherApplicationContext,
- }),
- ).toThrow(/not writable/);
- });
-
- it('should let the owning application write while serving a person', () => {
- expect(() =>
- validate({
- objectWritability: MetadataWritability.APPLICATION,
- authContext: userContextCarryingApplication,
- }),
- ).not.toThrow();
- });
-
- it('should refuse a plain session on an APPLICATION object', () => {
- expect(() =>
- validate({
- objectWritability: MetadataWritability.APPLICATION,
- authContext: plainUserContext,
- }),
- ).toThrow();
- });
-
- it('should refuse another application serving a person on an APPLICATION object', () => {
- expect(() =>
- validate({
- objectWritability: MetadataWritability.APPLICATION,
- authContext: otherApplicationUserContext,
- }),
- ).toThrow(/not writable/);
- });
-
- it('should refuse an api key context on an APPLICATION object', () => {
- expect(() =>
- validate({
- objectWritability: MetadataWritability.APPLICATION,
- authContext: apiKeyContext,
- }),
- ).toThrow(/not writable/);
- });
-
- it('should refuse a missing context on an APPLICATION object', () => {
- expect(() =>
- validate({
- objectWritability: MetadataWritability.APPLICATION,
- authContext: undefined,
- }),
- ).toThrow(/not writable/);
- });
-
- it('should refuse every token-bound caller on a SYSTEM object', () => {
- for (const authContext of [
- applicationContext,
- userContextCarryingApplication,
- plainUserContext,
- apiKeyContext,
- undefined,
- ]) {
- expect(() =>
- validate({
- objectWritability: MetadataWritability.SYSTEM,
- authContext,
- }),
- ).toThrow(/not writable/);
- }
- });
-
- it('should let a system context write a SYSTEM object', () => {
- expect(() =>
- validate({
- objectWritability: MetadataWritability.SYSTEM,
- authContext: systemContext,
- }),
- ).not.toThrow();
- });
-
- it('should let a system context write an APPLICATION object', () => {
- expect(() =>
- validate({
- objectWritability: MetadataWritability.APPLICATION,
- authContext: systemContext,
- }),
- ).not.toThrow();
- });
-
- it('should let a system context write a SYSTEM field', () => {
- expect(() =>
- validate({
- fieldWritability: MetadataWritability.SYSTEM,
- authContext: systemContext,
- }),
- ).not.toThrow();
- });
-
- it('should enforce field writability even when the object is OPEN', () => {
- expect(() =>
- validate({
- fieldWritability: MetadataWritability.APPLICATION,
- authContext: plainUserContext,
- }),
- ).toThrow(/field "status".*not writable/);
- });
-
- it('should let the owning application write an APPLICATION field', () => {
- expect(() =>
- validate({
- fieldWritability: MetadataWritability.APPLICATION,
- authContext: applicationContext,
- }),
- ).not.toThrow();
- });
-
- it('should refuse every caller on a SYSTEM field', () => {
- expect(() =>
- validate({
- fieldWritability: MetadataWritability.SYSTEM,
- authContext: applicationContext,
- }),
- ).toThrow(/field "status".*not writable/);
- });
-
- it('should ignore field writability for columns that are not written', () => {
- expect(() =>
- validate({
- fieldWritability: MetadataWritability.SYSTEM,
- updatedColumns: [],
- authContext: undefined,
- }),
- ).not.toThrow();
- });
-});
diff --git a/packages/twenty-server/src/engine/twenty-orm/repository/permissions.utils.ts b/packages/twenty-server/src/engine/twenty-orm/repository/permissions.utils.ts
index 6112bec895e..dc3dc88fb6c 100644
--- a/packages/twenty-server/src/engine/twenty-orm/repository/permissions.utils.ts
+++ b/packages/twenty-server/src/engine/twenty-orm/repository/permissions.utils.ts
@@ -17,8 +17,6 @@ import {
PermissionsExceptionCode,
PermissionsExceptionMessage,
} from 'src/engine/metadata-modules/permissions/permissions.exception';
-import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
-import { validateWritabilityOrThrow } from 'src/engine/twenty-orm/repository/validate-writability-or-throw.util';
import { isObjectOperationPermitted } from 'src/engine/twenty-orm/utils/is-object-operation-permitted.util';
import { resolveObjectSharing } from 'src/engine/core-modules/record-share/utils/resolve-object-sharing.util';
import { getColumnNameToFieldMetadataIdMap } from 'src/engine/twenty-orm/utils/get-column-name-to-field-metadata-id.util';
@@ -40,7 +38,6 @@ type ValidateOperationIsPermittedOrThrowArgs = {
objectIdByNameSingular: Record<string, string>;
selectedColumns: string[];
updatedColumns: string[];
- authContext?: WorkspaceAuthContext;
featureFlagsMap?: Partial<Record<FeatureFlagKey, boolean>>;
};
@@ -53,7 +50,6 @@ export const validateOperationIsPermittedOrThrow = ({
objectIdByNameSingular,
selectedColumns,
updatedColumns,
- authContext,
featureFlagsMap = {},
}: ValidateOperationIsPermittedOrThrowArgs) => {
const objectMetadataIdForEntity = objectIdByNameSingular[entityName];
@@ -82,15 +78,6 @@ export const validateOperationIsPermittedOrThrow = ({
flatFieldMetadataMaps,
);
- validateWritabilityOrThrow({
- operationType,
- objectMetadata,
- updatedColumns,
- columnNameToFieldMetadataIdMap,
- flatFieldMetadataMaps,
- authContext,
- });
-
const permissionsForEntity = objectsPermissions[objectMetadataIdForEntity];
// Records shared by name stay reachable without the object permission; the
diff --git a/packages/twenty-server/src/engine/twenty-orm/repository/validate-writability-or-throw.util.ts b/packages/twenty-server/src/engine/twenty-orm/repository/validate-writability-or-throw.util.ts
deleted file mode 100644
index c14e9323911..00000000000
--- a/packages/twenty-server/src/engine/twenty-orm/repository/validate-writability-or-throw.util.ts
+++ /dev/null
@@ -1,102 +0,0 @@
-import { isMetadataWritePermitted } from 'src/engine/twenty-orm/utils/is-metadata-write-permitted.util';
-import { MetadataWritability } from 'twenty-shared/types';
-import { isDefined } from 'twenty-shared/utils';
-
-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 { 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 { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';
-import {
- PermissionsException,
- PermissionsExceptionCode,
- PermissionsExceptionMessage,
-} from 'src/engine/metadata-modules/permissions/permissions.exception';
-import { type OperationType } from 'src/engine/twenty-orm/repository/permissions.utils';
-import { isOwningApplicationAuthContext } from 'src/engine/twenty-orm/utils/is-owning-application-auth-context.util';
-
-const isWritePermittedByWritability = ({
- writability,
- owningApplicationId,
- authContext,
-}: {
- writability: MetadataWritability | undefined;
- owningApplicationId: string | undefined;
- authContext: WorkspaceAuthContext | undefined;
-}): boolean => {
- return isMetadataWritePermitted({
- writability,
- isSystemContext: authContext?.type === 'system',
- isOwningApplication:
- isDefined(authContext) &&
- isOwningApplicationAuthContext({ authContext, owningApplicationId }),
- });
-};
-
-type ValidateWritabilityOrThrowArgs = {
- operationType: OperationType;
- objectMetadata: Pick<
- FlatObjectMetadata,
- 'writability' | 'applicationId' | 'nameSingular'
- >;
- updatedColumns: string[];
- columnNameToFieldMetadataIdMap: Record<string, string>;
- flatFieldMetadataMaps: FlatEntityMaps<OrmFlatFieldMetadata>;
- authContext: WorkspaceAuthContext | undefined;
-};
-
-export const validateWritabilityOrThrow = ({
- operationType,
- objectMetadata,
- updatedColumns,
- columnNameToFieldMetadataIdMap,
- flatFieldMetadataMaps,
- authContext,
-}: ValidateWritabilityOrThrowArgs): void => {
- if (operationType === 'select') {
- return;
- }
-
- if (
- !isWritePermittedByWritability({
- writability: objectMetadata.writability,
- owningApplicationId: objectMetadata.applicationId,
- authContext,
- })
- ) {
- throw new PermissionsException(
- `${PermissionsExceptionMessage.PERMISSION_DENIED}: records of "${objectMetadata.nameSingular}" are not writable through the API`,
- PermissionsExceptionCode.PERMISSION_DENIED,
- );
- }
-
- for (const column of updatedColumns) {
- const fieldMetadataId = columnNameToFieldMetadataIdMap[column];
-
- if (!isDefined(fieldMetadataId)) {
- continue;
- }
-
- const fieldMetadata = findFlatEntityByIdInFlatEntityMaps({
- flatEntityId: fieldMetadataId,
- flatEntityMaps: flatFieldMetadataMaps,
- });
-
- if (!isDefined(fieldMetadata)) {
- continue;
- }
-
- if (
- !isWritePermittedByWritability({
- writability: fieldMetadata.writability,
- owningApplicationId: fieldMetadata.applicationId,
- authContext,
- })
- ) {
- throw new PermissionsException(
- `${PermissionsExceptionMessage.PERMISSION_DENIED}: field "${fieldMetadata.name}" on "${objectMetadata.nameSingular}" is not writable through the API`,
- PermissionsExceptionCode.PERMISSION_DENIED,
- );
- }
- }
-};
diff --git a/packages/twenty-server/src/engine/twenty-orm/repository/workspace-repository.ts b/packages/twenty-server/src/engine/twenty-orm/repository/workspace-repository.ts
index ffae572e671..fb85e9397fe 100644
--- a/packages/twenty-server/src/engine/twenty-orm/repository/workspace-repository.ts
+++ b/packages/twenty-server/src/engine/twenty-orm/repository/workspace-repository.ts
@@ -2,7 +2,6 @@ import { msg } from '@lingui/core/macro';
import { isNonEmptyString } from '@sniptt/guards';
import { QUERY_MAX_RECORDS } from 'twenty-shared/constants';
import {
- MetadataReadability,
type ObjectRecord,
type ObjectsPermissions,
} from 'twenty-shared/types';
@@ -31,11 +30,6 @@ import {
} from 'src/engine/twenty-orm/repository/permissions.utils';
import { type WorkspaceInternalContext } from 'src/engine/twenty-orm/interfaces/workspace-internal-context.interface';
import { canRolesAccessAllRecords } from 'src/engine/core-modules/record-share/utils/can-roles-access-all-records.util';
-import { type InheritedReadabilityChildRecords } from 'src/engine/core-modules/record-share/types/inherited-readability-child-records.type';
-import { type InheritedReadabilityChildrenParent } from 'src/engine/core-modules/record-share/types/inherited-readability-children-parent.type';
-import { type InheritedReadabilityColumnParent } from 'src/engine/core-modules/record-share/types/inherited-readability-column-parent.type';
-import { type InheritedReadabilityParent } from 'src/engine/core-modules/record-share/types/inherited-readability-parent.type';
-import { type InheritedReadabilityParentLink } from 'src/engine/core-modules/record-share/types/inherited-readability-parent-link.type';
import {
type RowAccessExpression,
type RowAccessPolicy,
@@ -45,7 +39,6 @@ import {
type SqlCondition,
} from 'src/engine/twenty-orm/types/row-access-policy.type';
import { compileRowAccessExpression } from 'src/engine/twenty-orm/utils/compile-row-access-policy.util';
-import { resolveRecordShareGateKind } from 'src/engine/core-modules/record-share/utils/resolve-record-share-gate-kind.util';
import { buildRowAccessPolicy } from 'src/engine/twenty-orm/utils/build-row-access-policy.util';
import { type RecordShareGrant } from 'src/engine/core-modules/record-share/types/record-share-grant.type';
import {
@@ -55,6 +48,7 @@ import {
} from 'src/engine/core-modules/record-share/utils/evaluate-row-access-policy.util';
import { isRowAccessExpressionReadingRoleFilter } from 'src/engine/twenty-orm/utils/is-row-access-expression-reading-role-filter.util';
import { resolveObjectSharing } from 'src/engine/core-modules/record-share/utils/resolve-object-sharing.util';
+import { isObjectOperationDisabled } from 'src/engine/twenty-orm/utils/is-object-operation-disabled.util';
import { isObjectOperationPermitted } from 'src/engine/twenty-orm/utils/is-object-operation-permitted.util';
import { formatData } from 'src/engine/twenty-orm/utils/format-data.util';
import { formatResult } from 'src/engine/twenty-orm/utils/format-result.util';
@@ -63,11 +57,8 @@ import {
getUpdateEventRecords,
mergeRecordsWithUpdateValues,
} from 'src/engine/twenty-orm/utils/merge-records-with-update-values.util';
-import { isChildRecordBoundAtDeletion } from 'src/engine/twenty-orm/utils/is-child-record-bound-at-deletion.util';
import { isOwningApplicationAuthContext } from 'src/engine/twenty-orm/utils/is-owning-application-auth-context.util';
import { resolvePrincipalIdsFromAuthContext } from 'src/engine/twenty-orm/utils/resolve-principal-ids-from-auth-context.util';
-import { resolveInheritedReadabilityChildLinks } from 'src/engine/core-modules/record-share/utils/resolve-inherited-readability-child-links.util';
-import { resolveInheritedReadabilityParents } from 'src/engine/core-modules/record-share/utils/resolve-inherited-readability-parents.util';
import { type RolePermissionConfig } from 'src/engine/twenty-orm/types/role-permission-config.type';
import { getRoleIdsFromRolePermissionConfig } from 'src/engine/twenty-orm/utils/get-role-ids-from-role-permission-config.util';
import { resolveRowLevelPermissionRecordFilter } from 'src/engine/twenty-orm/utils/resolve-row-level-permission-record-filter.util';
@@ -1076,11 +1067,6 @@ export class WorkspaceRepository<TEntity extends ObjectLiteral = ObjectRecord> {
shouldBypassPermissionChecks: this.options.shouldBypassPermissionChecks,
});
- await this.validateInheritedParentsAreWritableOrThrow({
- writtenRecords: formattedRecords,
- affectedRecords: formattedRecords,
- });
-
await this.assertRecordStockAvailable(recordsToInsert.length);
const sql = buildInsertStatement({
@@ -1206,16 +1192,6 @@ export class WorkspaceRepository<TEntity extends ObjectLiteral = ObjectRecord> {
this.formatWriteData(data),
);
- await this.validateInheritedParentsAreWritableOrThrow({
- writtenRecords,
- affectedRecords: writtenRecords.flatMap((writtenRecord, index) =>
- rawBeforeByInputIndex[index].flatMap((rawBefore) => [
- rawBefore,
- { ...rawBefore, ...writtenRecord },
- ]),
- ),
- });
-
const setColumnsByInputIndex = writtenRecords.map(
({ id: _id, ...setColumns }) => setColumns,
);
@@ -1483,108 +1459,6 @@ export class WorkspaceRepository<TEntity extends ObjectLiteral = ObjectRecord> {
.withDeleted();
}
- // Re-parenting or creating under a parent is a write on that parent, so the destination must grant READ_WRITE
- // Inheriting records are checked before and after any write, since creating, changing, deleting or restoring the row changes what they expose
- private async validateInheritedParentsAreWritableOrThrow({
- writtenRecords,
- affectedRecords,
- }: {
- writtenRecords: Record<string, unknown>[];
- affectedRecords: Record<string, unknown>[];
- }): Promise<void> {
- if (!this.shouldValidateInheritedParents()) {
- return;
- }
-
- for (const parent of this.resolveOwnParentLinks()) {
- await this.validateParentRecordsAreWritableOrThrow({
- parent,
- records: writtenRecords,
- });
- }
-
- for (const parent of this.resolveInheritingRecordLinks()) {
- await this.validateParentRecordsAreWritableOrThrow({
- parent,
- records: affectedRecords,
- });
- }
- }
-
- private shouldValidateInheritedParents(): boolean {
- return !this.options.shouldBypassPermissionChecks;
- }
-
- private async validateParentRecordsAreWritableOrThrow({
- parent,
- records,
- }: {
- parent: InheritedReadabilityParentLink;
- records: Record<string, unknown>[];
- }): Promise<void> {
- const parentIds = [
- ...new Set(
- records
- .map((record) => record[parent.joinColumnName])
- .filter(isNonEmptyString),
- ),
- ];
-
- if (parentIds.length === 0) {
- return;
- }
-
- const parentRepository = this.options.getRepositoryForObjectMetadataId(
- parent.parentFlatObjectMetadata.id,
- );
- const queryBuilder = parentRepository
- .createQueryBuilder()
- .where({ id: In(parentIds) })
- .withDeleted();
-
- parentRepository.applyWriteRowLevelPermissions(queryBuilder, 'update');
- queryBuilder.select(['id']);
-
- const writableParentRows = await queryBuilder.getMany<ObjectRecord>({
- noFormatting: true,
- });
-
- if (writableParentRows.length !== parentIds.length) {
- throw new PermissionsException(
- `${PermissionsExceptionMessage.PERMISSION_DENIED}: the "${parent.parentFlatObjectMetadata.nameSingular}" record a "${this.options.flatObjectMetadata.nameSingular}" is attached to is not writable`,
- PermissionsExceptionCode.PERMISSION_DENIED,
- );
- }
- }
-
- private resolveOwnParentLinks(): InheritedReadabilityParentLink[] {
- const { flatObjectMetadata } = this.options;
-
- if (
- flatObjectMetadata.readability !== MetadataReadability.INHERITED ||
- isOwningApplicationAuthContext({
- authContext: this.options.authContext,
- owningApplicationId: flatObjectMetadata.applicationId,
- })
- ) {
- return [];
- }
-
- return this.resolveInheritedReadabilityParents(flatObjectMetadata).filter(
- (parent): parent is InheritedReadabilityColumnParent =>
- parent.kind === 'column',
- );
- }
-
- private resolveInheritingRecordLinks(): InheritedReadabilityParentLink[] {
- return resolveInheritedReadabilityChildLinks({
- flatObjectMetadata: this.options.flatObjectMetadata,
- flatFieldMetadataMaps: this.options.internalContext.flatFieldMetadataMaps,
- flatObjectMetadataMaps:
- this.options.internalContext.flatObjectMetadataMaps,
- });
- }
-
private async resolveWritableRecordIds({
ids,
operationType,
@@ -1737,21 +1611,6 @@ export class WorkspaceRepository<TEntity extends ObjectLiteral = ObjectRecord> {
);
}
- await this.validateInheritedParentsAreWritableOrThrow({
- writtenRecords: isDefined(setColumns) ? [setColumns] : [],
- affectedRecords: isDefined(setColumns)
- ? recordsBefore.flatMap((record) => [
- record,
- { ...record, ...setColumns },
- ])
- : recordsBefore,
- });
-
- const inheritedReadabilityChildRecordsByRecordId =
- kind === 'delete' || kind === 'soft-delete'
- ? await this.fetchInheritedReadabilityChildRecords(recordsBefore)
- : undefined;
-
const mutationResult = await this.morphAndExecute({
selectQueryBuilder,
kind,
@@ -1797,83 +1656,11 @@ export class WorkspaceRepository<TEntity extends ObjectLiteral = ObjectRecord> {
kind,
recordsBefore,
recordsAfter,
- inheritedReadabilityChildRecordsByRecordId,
});
return mutationResult.generatedMaps;
}
- private async fetchInheritedReadabilityChildRecords(
- records: ObjectRecord[],
- ): Promise<Map<string, InheritedReadabilityChildRecords> | undefined> {
- const { flatObjectMetadata } = this.options;
-
- if (
- records.length === 0 ||
- flatObjectMetadata.readability !== MetadataReadability.INHERITED
- ) {
- return undefined;
- }
-
- const childrenParents = this.resolveInheritedReadabilityParents(
- flatObjectMetadata,
- ).filter(
- (parent): parent is InheritedReadabilityChildrenParent =>
- parent.kind === 'children',
- );
-
- if (childrenParents.length === 0) {
- return undefined;
- }
-
- const recordById = new Map(
- records.map((record) => [String(record.id), record]),
- );
- const recordIds = [...recordById.keys()];
- const childRecordsByRecordId = new Map(
- recordIds.map((recordId): [string, InheritedReadabilityChildRecords] => [
- recordId,
- Object.fromEntries(
- childrenParents.map((parent) => [
- parent.childFlatObjectMetadata.nameSingular,
- [],
- ]),
- ),
- ]),
- );
-
- for (const parent of childrenParents) {
- const childRepository = this.options.getRepositoryForObjectMetadataId(
- parent.childFlatObjectMetadata.id,
- );
- const childRecords = await childRepository
- .buildBypassingEventSelectQueryBuilder(
- parent.childFlatObjectMetadata.nameSingular,
- )
- .where({ [parent.childJoinColumnName]: In(recordIds) })
- .withDeleted()
- .getMany<ObjectRecord>();
-
- for (const childRecord of childRecords) {
- const recordId = String(childRecord[parent.childJoinColumnName]);
- const record = recordById.get(recordId);
-
- if (
- !isDefined(record) ||
- !isChildRecordBoundAtDeletion({ childRecord, record })
- ) {
- continue;
- }
-
- childRecordsByRecordId
- .get(recordId)
- ?.[parent.childFlatObjectMetadata.nameSingular].push(childRecord);
- }
- }
-
- return childRecordsByRecordId;
- }
-
private async morphAndExecute({
selectQueryBuilder,
kind,
@@ -1919,6 +1706,14 @@ export class WorkspaceRepository<TEntity extends ObjectLiteral = ObjectRecord> {
return;
}
+ // Inserts skip the row access policy, so disabled actions are checked here
+ if (this.isOperationDisabled(operationType)) {
+ throw new PermissionsException(
+ `${PermissionsExceptionMessage.PERMISSION_DENIED}: records of "${this.options.flatObjectMetadata.nameSingular}" are not writable through the API`,
+ PermissionsExceptionCode.PERMISSION_DENIED,
+ );
+ }
+
validateOperationIsPermittedOrThrow({
entityName: this.options.tableShape.nameSingular,
operationType,
@@ -1930,7 +1725,6 @@ export class WorkspaceRepository<TEntity extends ObjectLiteral = ObjectRecord> {
this.options.internalContext.objectIdByNameSingular,
selectedColumns: columnsToReturn,
updatedColumns,
- authContext: this.options.authContext,
featureFlagsMap: this.options.internalContext.featureFlagsMap,
});
}
@@ -1999,7 +1793,7 @@ export class WorkspaceRepository<TEntity extends ObjectLiteral = ObjectRecord> {
private buildWriteRowAccessEvaluationContext(
recordIds: string[],
- ): RowAccessEvaluationContext<RowAccessRecord> {
+ ): RowAccessEvaluationContext {
const recordShareGrantsByObjectMetadataId = new Map<
string,
Promise<RecordShareGrant[]>
@@ -2027,11 +1821,6 @@ export class WorkspaceRepository<TEntity extends ObjectLiteral = ObjectRecord> {
requestedRecordIdSet.has(recordShareGrant.recordId),
);
},
- // Writes check parents before and after through
- // validateInheritedParentsAreWritableOrThrow, so this branch only has to
- // leave the rest of the policy to decide
- resolveRecordIdsReadableThroughParents: async ({ records }) =>
- new Set(records.map((record) => record.id)),
};
}
@@ -2056,15 +1845,10 @@ export class WorkspaceRepository<TEntity extends ObjectLiteral = ObjectRecord> {
kind,
recordsBefore,
recordsAfter,
- inheritedReadabilityChildRecordsByRecordId,
}: {
kind: MutationKind;
recordsBefore: ObjectRecord[];
recordsAfter?: ObjectRecord[];
- inheritedReadabilityChildRecordsByRecordId?: Map<
- string,
- InheritedReadabilityChildRecords
- >;
}): void {
if (this.options.shouldSkipEventEmission) {
return;
@@ -2087,7 +1871,6 @@ export class WorkspaceRepository<TEntity extends ObjectLiteral = ObjectRecord> {
recordsBefore: formattedBefore,
recordsAfter: formattedAfter,
authContext: this.options.authContext,
- inheritedReadabilityChildRecordsByRecordId,
});
if (isDefined(event)) {
@@ -2192,7 +1975,6 @@ export class WorkspaceRepository<TEntity extends ObjectLiteral = ObjectRecord> {
isMainAlias: alias === queryBuilder.alias,
flatObjectMetadata,
operationType,
- joinParentRelationShape: queryBuilder.getJoinParentRelationShape(alias),
});
switch (policy.kind) {
@@ -2225,13 +2007,11 @@ export class WorkspaceRepository<TEntity extends ObjectLiteral = ObjectRecord> {
isMainAlias,
flatObjectMetadata,
operationType,
- joinParentRelationShape,
}: {
alias: string;
isMainAlias: boolean;
flatObjectMetadata: FlatObjectMetadata;
operationType: OperationType;
- joinParentRelationShape?: WorkspaceRelationShape;
}): RowAccessPolicy {
if (
isMainAlias &&
@@ -2253,8 +2033,6 @@ export class WorkspaceRepository<TEntity extends ObjectLiteral = ObjectRecord> {
tableAlias: alias,
flatObjectMetadata,
operationType,
- depth: 0,
- joinParentRelationShape,
});
}
@@ -2443,14 +2221,33 @@ export class WorkspaceRepository<TEntity extends ObjectLiteral = ObjectRecord> {
});
}
+ isReadDisabled(): boolean {
+ return this.isOperationDisabled('select');
+ }
+
+ private isOperationDisabled(operationType: OperationType): boolean {
+ if (this.options.shouldBypassPermissionChecks) {
+ return false;
+ }
+
+ const subject = this.resolveRowAccessPolicySubject();
+
+ return (
+ !subject.isSystemContext &&
+ isObjectOperationDisabled({
+ objectMetadata: this.options.flatObjectMetadata,
+ operationType,
+ }) &&
+ !subject.isOwningApplication(this.options.flatObjectMetadata)
+ );
+ }
+
buildRowAccessPolicy({
subject,
operationType,
- depth = 0,
}: {
subject: RowAccessPolicySubject;
operationType: OperationType;
- depth?: number;
}): RowAccessPolicy {
return buildRowAccessPolicy({
subject,
@@ -2458,24 +2255,9 @@ export class WorkspaceRepository<TEntity extends ObjectLiteral = ObjectRecord> {
tableAlias: this.options.tableShape.nameSingular,
flatObjectMetadata: this.options.flatObjectMetadata,
operationType,
- depth,
});
}
- isReadDeniedByReadability(): boolean {
- const subject = this.resolveRowAccessPolicySubject();
-
- return (
- !subject.isSystemContext &&
- resolveRecordShareGateKind({
- readability: this.options.flatObjectMetadata.readability,
- isOwningApplication: subject.isOwningApplication(
- this.options.flatObjectMetadata,
- ),
- }) === 'deny'
- );
- }
-
private resolveRowAccessPolicySubject(): RowAccessPolicySubject {
const roleMaps = {
authContext: this.options.authContext,
@@ -2518,23 +2300,10 @@ export class WorkspaceRepository<TEntity extends ObjectLiteral = ObjectRecord> {
recordShareTableExpression: this.getTableExpression(
this.options.internalContext.objectIdByNameSingular.recordShare,
),
- resolveTableExpression: (objectMetadataId) =>
- this.getTableExpression(objectMetadataId),
featureFlagsMap: this.options.internalContext.featureFlagsMap,
};
}
- private resolveInheritedReadabilityParents(
- flatObjectMetadata: FlatObjectMetadata,
- ): InheritedReadabilityParent[] {
- return resolveInheritedReadabilityParents({
- flatObjectMetadata,
- flatFieldMetadataMaps: this.options.internalContext.flatFieldMetadataMaps,
- flatObjectMetadataMaps:
- this.options.internalContext.flatObjectMetadataMaps,
- });
- }
-
private getTableExpression(objectMetadataId: string): string {
const tableShape =
this.options.tableShapeByObjectMetadataId(objectMetadataId);
diff --git a/packages/twenty-server/src/engine/twenty-orm/types/row-access-policy.type.ts b/packages/twenty-server/src/engine/twenty-orm/types/row-access-policy.type.ts
index 625dde0ec69..ce1a1f0b4d5 100644
--- a/packages/twenty-server/src/engine/twenty-orm/types/row-access-policy.type.ts
+++ b/packages/twenty-server/src/engine/twenty-orm/types/row-access-policy.type.ts
@@ -11,7 +11,6 @@ import { type FlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/typ
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';
import { type OperationType } from 'src/engine/twenty-orm/repository/permissions.utils';
-import { type WorkspaceRelationShape } from 'src/engine/twenty-orm/table-shape/types/workspace-table-shape.type';
export type SqlCondition = { sql: string; parameters: ObjectLiteral };
@@ -33,12 +32,7 @@ export type RowAccessExpression =
// Compiled as a grant list read once, so it can be ORed with an indexed filter
isUncorrelated?: boolean;
} & RecordShareExpressionTarget)
- | ({ kind: 'recordNotRestricted' } & RecordShareExpressionTarget)
- | ({
- kind: 'inheritedReadability';
- parents: InheritedReadabilityParentExpression[];
- isOpenWhenDetached: boolean;
- } & RecordShareExpressionTarget);
+ | ({ kind: 'recordNotRestricted' } & RecordShareExpressionTarget);
export type RecordShareExpressionTarget = {
tableAlias: string;
@@ -47,22 +41,6 @@ export type RecordShareExpressionTarget = {
accessLevels: RecordShareAccessLevel[];
};
-export type InheritedReadabilityParentExpression =
- | {
- kind: 'column';
- joinColumnName: string;
- parentTableAlias: string;
- parentFlatObjectMetadata: FlatObjectMetadata;
- policy: RowAccessPolicy;
- }
- | {
- kind: 'children';
- childTableAlias: string;
- childJoinColumnName: string;
- childFlatObjectMetadata: FlatObjectMetadata;
- policy: RowAccessPolicy;
- };
-
export type RowAccessPolicy =
| { kind: 'open' }
| { kind: 'denied' }
@@ -92,7 +70,6 @@ export type RowAccessPolicyEnvironment = {
export type RowAccessCompilationEnvironment = {
recordShareTableExpression: string;
- resolveTableExpression: (objectMetadataId: string) => string;
};
export type RowAccessPolicyContext = {
@@ -104,6 +81,4 @@ export type RowAccessPolicyTarget = {
tableAlias: string;
flatObjectMetadata: FlatObjectMetadata;
operationType: OperationType;
- depth: number;
- joinParentRelationShape?: WorkspaceRelationShape;
};
diff --git a/packages/twenty-server/src/engine/twenty-orm/utils/__tests__/build-row-access-policy.util.spec.ts b/packages/twenty-server/src/engine/twenty-orm/utils/__tests__/build-row-access-policy.util.spec.ts
index 125d8e83613..85f315ae187 100644
--- a/packages/twenty-server/src/engine/twenty-orm/utils/__tests__/build-row-access-policy.util.spec.ts
+++ b/packages/twenty-server/src/engine/twenty-orm/utils/__tests__/build-row-access-policy.util.spec.ts
@@ -2,8 +2,6 @@ import { EVERYONE_PRINCIPAL_ID } from 'twenty-shared/constants';
import {
FeatureFlagKey,
MetadataReadability,
- MetadataWritability,
- ObjectSharingReach,
RecordShareAccessLevel,
} from 'twenty-shared/types';
@@ -17,11 +15,7 @@ import {
import { buildRowAccessPolicy } from 'src/engine/twenty-orm/utils/build-row-access-policy.util';
import { compileRowAccessPolicy } from 'src/engine/twenty-orm/utils/compile-row-access-policy.util';
import { renderRowLevelPermissionFilterToSql } from 'src/engine/twenty-orm/utils/render-row-level-permission-filter-to-sql.util';
-import { resolveInheritedReadabilityParents } from 'src/engine/core-modules/record-share/utils/resolve-inherited-readability-parents.util';
-jest.mock(
- 'src/engine/core-modules/record-share/utils/resolve-inherited-readability-parents.util',
-);
jest.mock(
'src/engine/twenty-orm/utils/render-row-level-permission-filter-to-sql.util',
);
@@ -29,13 +23,7 @@ jest.mock(
const APPLICATION_ID = 'application-id';
const NOTE_FILTER = { title: { eq: 'restricted' } };
-const buildObject = ({
- id,
- readability,
-}: {
- id: string;
- readability: MetadataReadability;
-}): FlatObjectMetadata =>
+const buildObject = ({ id }: { id: string }): FlatObjectMetadata =>
getFlatObjectMetadataMock({
id,
nameSingular: id,
@@ -43,27 +31,19 @@ const buildObject = ({
universalIdentifier: `${id}-universal-identifier`,
applicationId: APPLICATION_ID,
isSystem: false,
- readability,
- readabilityParentFieldUniversalIdentifiers: null,
} as Parameters<typeof getFlatObjectMetadataMock>[0]);
-const attachment = buildObject({
- id: 'attachment',
- readability: MetadataReadability.INHERITED,
-});
-const note = buildObject({ id: 'note', readability: MetadataReadability.OPEN });
-const person = buildObject({
- id: 'person',
+const note = buildObject({ id: 'note' });
+const person: FlatObjectMetadata = {
+ ...buildObject({ id: 'person' }),
readability: MetadataReadability.PRIVATE,
-});
+};
const environment: RowAccessPolicyEnvironment &
RowAccessCompilationEnvironment = {
flatFieldMetadataMaps: { byId: {} } as never,
flatObjectMetadataMaps: { byId: {} } as never,
recordShareTableExpression: '"workspace"."recordShare"',
- resolveTableExpression: (objectMetadataId) =>
- `"workspace"."${objectMetadataId}"`,
featureFlagsMap: {},
};
const sharingEnvironment = {
@@ -100,7 +80,6 @@ const build = (
tableAlias: flatObjectMetadata.nameSingular,
flatObjectMetadata,
operationType: 'select',
- depth: 0,
});
const gatedSql = (
@@ -116,20 +95,6 @@ const gatedSql = (
describe('buildRowAccessPolicy', () => {
beforeEach(() => {
- (resolveInheritedReadabilityParents as jest.Mock).mockReturnValue([
- {
- kind: 'column',
- fieldMetadataId: 'target-note-field-id',
- joinColumnName: 'targetNoteId',
- parentFlatObjectMetadata: note,
- },
- {
- kind: 'column',
- fieldMetadataId: 'target-person-field-id',
- joinColumnName: 'targetPersonId',
- parentFlatObjectMetadata: person,
- },
- ]);
(renderRowLevelPermissionFilterToSql as jest.Mock).mockImplementation(
({ tableAlias }: { tableAlias: string }) => ({
sql: `"${tableAlias}"."title" = :restricted`,
@@ -138,56 +103,47 @@ describe('buildRowAccessPolicy', () => {
);
});
- it.each(Object.values(MetadataReadability))(
- 'allows trusted system reads and writes for %s metadata',
- (readability) => {
- for (const operationType of ['select', 'update', 'delete'] as const) {
- expect(
- buildCompiledRowAccessPolicy({
- subject: {
- ...readEverything,
- isSystemContext: true,
- principalIds: undefined,
- },
- environment,
- tableAlias: 'internal',
- flatObjectMetadata: {
- ...note,
- readability,
- writability: MetadataWritability.SYSTEM,
- },
- operationType,
- depth: 0,
- }),
- ).toEqual({ kind: 'open' });
- }
- },
- );
-
- it('keeps APPLICATION records restricted to their owning application', () => {
- const object = { ...note, readability: MetadataReadability.APPLICATION };
+ it('allows trusted system reads and writes', () => {
+ for (const operationType of ['select', 'update', 'delete'] as const) {
+ expect(
+ buildCompiledRowAccessPolicy({
+ subject: {
+ ...readEverything,
+ isSystemContext: true,
+ principalIds: undefined,
+ },
+ environment,
+ tableAlias: 'internal',
+ flatObjectMetadata: note,
+ operationType,
+ }),
+ ).toEqual({ kind: 'open' });
+ }
+ });
+
+ it('keeps records of an object that disables reading to its owning application', () => {
+ const object = {
+ ...note,
+ disabledObjectPermissionActions: ['canReadObjectRecords' as const],
+ };
expect(build(readEverything, object)).toEqual({ kind: 'denied' });
expect(
build({ ...readEverything, isOwningApplication: () => true }, object),
).toEqual({ kind: 'open' });
});
- it('opens an OPEN object to a subject without predicate', () => {
+ it('opens an object to a subject without predicate', () => {
expect(build(readEverything, note)).toEqual({ kind: 'open' });
});
- it('gates an OPEN object on its restrictions once record sharing is enabled', () => {
- const company = buildObject({
- id: 'company',
- readability: MetadataReadability.OPEN,
- });
+ it('gates an object on its restrictions once record sharing is enabled', () => {
+ const company = buildObject({ id: 'company' });
const policy = buildCompiledRowAccessPolicy({
subject: readEverything,
environment: sharingEnvironment,
tableAlias: 'company',
flatObjectMetadata: company,
operationType: 'select',
- depth: 0,
});
expect(policy.kind).toBe('gated');
@@ -197,7 +153,7 @@ describe('buildRowAccessPolicy', () => {
);
});
- it('lifts the restrictions of an OPEN object for a subject with access to all records', () => {
+ it('lifts the restrictions of an object for a subject with access to all records', () => {
expect(
buildCompiledRowAccessPolicy({
subject: { ...readEverything, canAccessAllRecords: true },
@@ -205,7 +161,6 @@ describe('buildRowAccessPolicy', () => {
tableAlias: 'note',
flatObjectMetadata: note,
operationType: 'select',
- depth: 0,
}),
).toEqual({ kind: 'open' });
});
@@ -216,7 +171,7 @@ describe('buildRowAccessPolicy', () => {
).toContain('recordShare');
});
- it('keeps an OPEN system object open when record sharing is enabled', () => {
+ it('keeps a system object open when record sharing is enabled', () => {
expect(
buildCompiledRowAccessPolicy({
subject: readEverything,
@@ -224,12 +179,11 @@ describe('buildRowAccessPolicy', () => {
tableAlias: 'note',
flatObjectMetadata: { ...note, isSystem: true },
operationType: 'select',
- depth: 0,
}),
).toEqual({ kind: 'open' });
});
- it('leaves an OPEN object open to inserts when record sharing is enabled', () => {
+ it('leaves an object open to inserts when record sharing is enabled', () => {
expect(
buildCompiledRowAccessPolicy({
subject: readEverything,
@@ -237,16 +191,12 @@ describe('buildRowAccessPolicy', () => {
tableAlias: 'note',
flatObjectMetadata: note,
operationType: 'insert',
- depth: 0,
}),
).toEqual({ kind: 'open' });
});
describe('with a record shared beyond the role', () => {
- const company = buildObject({
- id: 'company',
- readability: MetadataReadability.OPEN,
- });
+ const company = buildObject({ id: 'company' });
const buildForCompany = (
subject: RowAccessPolicySubject,
operationType: 'select' | 'update' | 'delete' = 'select',
@@ -257,7 +207,6 @@ describe('buildRowAccessPolicy', () => {
tableAlias: 'company',
flatObjectMetadata: company,
operationType,
- depth: 0,
});
const withoutObjectPermission: RowAccessPolicySubject = {
...readEverything,
@@ -330,22 +279,6 @@ describe('buildRowAccessPolicy', () => {
/^\(\(\("company"."title" = :restricted\) AND \(NOT EXISTS .*\)\) OR \("company"."id" = ANY\(ARRAY\(SELECT "company_recordShare"."recordId"/,
);
});
-
- it('keeps the role limits when the object restricts sharing to the role', () => {
- expect(
- buildCompiledRowAccessPolicy({
- subject: withoutObjectPermission,
- environment: sharingEnvironment,
- tableAlias: 'company',
- flatObjectMetadata: {
- ...company,
- sharingReach: ObjectSharingReach.ROLE_ACCESS,
- },
- operationType: 'select',
- depth: 0,
- }),
- ).toEqual({ kind: 'denied' });
- });
});
it('denies an object the subject has no permission on', () => {
@@ -354,7 +287,7 @@ describe('buildRowAccessPolicy', () => {
});
});
- it('gates an OPEN object on the role predicate alone', () => {
+ it('gates an object on the role predicate alone', () => {
const sql = gatedSql(
{
...readEverything,
@@ -375,74 +308,11 @@ describe('buildRowAccessPolicy', () => {
).toEqual({ kind: 'open' });
});
- it('follows an INHERITED object to its parents under the parents policies', () => {
- const sql = gatedSql(
- {
- ...readEverything,
- resolveRowLevelPermissionRecordFilter: (objectMetadata) =>
- objectMetadata.id === note.id ? NOTE_FILTER : null,
- },
- attachment,
- );
-
- expect(sql).toContain(
- '"attachment"."targetNoteId" IS NOT NULL AND EXISTS (SELECT 1 FROM "workspace"."note" AS "attachment_targetNoteId" WHERE "attachment_targetNoteId"."id" = "attachment"."targetNoteId" AND ("attachment_targetNoteId"."title" = :restricted))',
- );
- expect(sql).toContain(
- '"attachment"."targetPersonId" IS NOT NULL AND EXISTS (SELECT 1 FROM "workspace"."person" AS "attachment_targetPersonId" WHERE "attachment_targetPersonId"."id" = "attachment"."targetPersonId" AND (EXISTS (SELECT 1 FROM "workspace"."recordShare" AS "attachment_targetPersonId_recordShare"',
- );
- });
-
- it('drops a parent the subject may not read and keeps the others', () => {
- const sql = gatedSql(
- {
- ...readEverything,
- objectsPermissions: {
- [attachment.id]: { canReadObjectRecords: true },
- [note.id]: { canReadObjectRecords: true },
- [person.id]: { canReadObjectRecords: false },
- } as never,
- },
- attachment,
- );
-
- expect(sql).toContain('"attachment"."targetNoteId" IS NOT NULL');
- expect(sql).not.toContain('targetPersonId');
- });
-
- it('keeps an INHERITED object open for its owning application', () => {
+ it('keeps a PRIVATE object open for its owning application', () => {
expect(
- build({ ...readEverything, isOwningApplication: () => true }, attachment),
+ build({ ...readEverything, isOwningApplication: () => true }, person),
).toEqual({ kind: 'open' });
});
- it.each([MetadataWritability.SYSTEM, MetadataWritability.APPLICATION])(
- 'does not inherit write access through a %s parent',
- (writability) => {
- jest.mocked(resolveInheritedReadabilityParents).mockReturnValue([
- {
- kind: 'column',
- fieldMetadataId: 'target-note-field-id',
- joinColumnName: 'targetNoteId',
- parentFlatObjectMetadata: {
- ...note,
- writability,
- },
- },
- ]);
- const policy = buildCompiledRowAccessPolicy({
- subject: readEverything,
- environment,
- tableAlias: 'attachment',
- flatObjectMetadata: attachment,
- operationType: 'update',
- depth: 0,
- });
- expect(policy.kind).toBe('gated');
- if (policy.kind !== 'gated') throw new Error('Expected a grant gate');
- expect(policy.condition.sql).not.toContain('targetNoteId');
- expect(policy.condition.sql).toContain('recordShare');
- },
- );
it('keeps private records gated regardless of the sharing UI flag', () => {
const policy = buildCompiledRowAccessPolicy({
@@ -451,7 +321,6 @@ describe('buildRowAccessPolicy', () => {
tableAlias: 'person',
flatObjectMetadata: person,
operationType: 'select',
- depth: 0,
});
expect(policy.kind).toBe('gated');
if (policy.kind !== 'gated') throw new Error('Expected a grant gate');
diff --git a/packages/twenty-server/src/engine/twenty-orm/utils/__tests__/format-twenty-orm-event-to-database-batch-event.util.spec.ts b/packages/twenty-server/src/engine/twenty-orm/utils/__tests__/format-twenty-orm-event-to-database-batch-event.util.spec.ts
index 15aafcc2e7d..8f75c608b68 100644
--- a/packages/twenty-server/src/engine/twenty-orm/utils/__tests__/format-twenty-orm-event-to-database-batch-event.util.spec.ts
+++ b/packages/twenty-server/src/engine/twenty-orm/utils/__tests__/format-twenty-orm-event-to-database-batch-event.util.spec.ts
@@ -1,8 +1,4 @@
-import {
- type ObjectRecordDeleteEvent,
- type ObjectRecordDestroyEvent,
- type ObjectRecordUpdateEvent,
-} from 'twenty-shared/database-events';
+import { type ObjectRecordUpdateEvent } from 'twenty-shared/database-events';
import { FieldMetadataType, RelationType } from 'twenty-shared/types';
import { DatabaseEventAction } from 'src/engine/api/graphql/graphql-query-runner/enums/database-event-action';
@@ -14,7 +10,6 @@ import {
TwentyOrmExceptionCode,
} from 'src/engine/twenty-orm/exceptions/twenty-orm.exception';
import { formatTwentyOrmEventToDatabaseBatchEvent } from 'src/engine/twenty-orm/utils/format-twenty-orm-event-to-database-batch-event.util';
-import { type InheritedReadabilityChildRecordsCarrier } from 'src/engine/core-modules/record-share/types/inherited-readability-child-records.type';
describe('formatTwentyOrmEventToDatabaseBatchEvent', () => {
const workspaceId = 'workspace-id';
@@ -247,91 +242,4 @@ describe('formatTwentyOrmEventToDatabaseBatchEvent', () => {
},
);
});
-
- describe('DELETED and DESTROYED actions', () => {
- const deletedAtField = createMockField({
- id: 'deleted-at-id',
- type: FieldMetadataType.DATE_TIME,
- name: 'deletedAt',
- label: 'Deleted at',
- });
- const flatFieldMetadataMapsWithDeletedAt: FlatEntityMaps<FlatFieldMetadata> =
- {
- byUniversalIdentifier: {
- 'name-id': nameField,
- 'deleted-at-id': deletedAtField,
- },
- universalIdentifierById: {
- 'name-id': 'name-id',
- 'deleted-at-id': 'deleted-at-id',
- },
- universalIdentifiersByApplicationId: {},
- };
- const flatObjectMetadataWithDeletedAt = {
- ...flatObjectMetadata,
- fieldIds: ['name-id', 'deleted-at-id'],
- } as FlatObjectMetadata;
- const inheritedReadabilityChildRecordsByRecordId = new Map([
- [
- 'record-1',
- { noteTarget: [{ id: 'note-target-1', noteId: 'record-1' }] },
- ],
- ]);
-
- it('should carry the child records captured for a record on its deleted event only', () => {
- const result = formatTwentyOrmEventToDatabaseBatchEvent({
- action: DatabaseEventAction.DELETED,
- objectMetadataItem: flatObjectMetadataWithDeletedAt,
- flatFieldMetadataMaps: flatFieldMetadataMapsWithDeletedAt,
- workspaceId: mockWorkspaceId,
- authContext: mockAuthContext,
- recordsBefore: [
- { id: 'record-1', name: 'John', deletedAt: null },
- { id: 'record-2', name: 'Jane', deletedAt: null },
- ],
- recordsAfter: [
- { id: 'record-1', name: 'John', deletedAt: '2026-09-15T00:00:00Z' },
- { id: 'record-2', name: 'Jane', deletedAt: '2026-09-15T00:00:00Z' },
- ],
- inheritedReadabilityChildRecordsByRecordId,
- });
- const [deleteEvent1, deleteEvent2] =
- result?.events as ObjectRecordDeleteEvent[];
-
- expect(
- (deleteEvent1.properties as InheritedReadabilityChildRecordsCarrier)
- .inheritedReadabilityChildRecords,
- ).toEqual({
- noteTarget: [{ id: 'note-target-1', noteId: 'record-1' }],
- });
- expect(deleteEvent2.properties).not.toHaveProperty(
- 'inheritedReadabilityChildRecords',
- );
- });
-
- it('should carry the child records captured for a record on its destroyed event only', () => {
- const result = formatTwentyOrmEventToDatabaseBatchEvent({
- action: DatabaseEventAction.DESTROYED,
- objectMetadataItem: flatObjectMetadata,
- flatFieldMetadataMaps,
- workspaceId: mockWorkspaceId,
- authContext: mockAuthContext,
- recordsBefore: [
- { id: 'record-1', name: 'John' },
- { id: 'record-2', name: 'Jane' },
- ],
- inheritedReadabilityChildRecordsByRecordId,
- });
- const [destroyEvent1, destroyEvent2] =
- result?.events as ObjectRecordDestroyEvent[];
-
- expect(
- (destroyEvent1.properties as InheritedReadabilityChildRecordsCarrier)
- .inheritedReadabilityChildRecords,
- ).toEqual({ noteTarget: [{ id: 'note-target-1', noteId: 'record-1' }] });
- expect(destroyEvent2.properties).not.toHaveProperty(
- 'inheritedReadabilityChildRecords',
- );
- });
- });
});
diff --git a/packages/twenty-server/src/engine/twenty-orm/utils/__tests__/is-child-record-bound-at-deletion.util.spec.ts b/packages/twenty-server/src/engine/twenty-orm/utils/__tests__/is-child-record-bound-at-deletion.util.spec.ts
deleted file mode 100644
index 591ad09f0be..00000000000
--- a/packages/twenty-server/src/engine/twenty-orm/utils/__tests__/is-child-record-bound-at-deletion.util.spec.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import { isChildRecordBoundAtDeletion } from 'src/engine/twenty-orm/utils/is-child-record-bound-at-deletion.util';
-
-describe('isChildRecordBoundAtDeletion', () => {
- it('should bind a live child record whatever the record state', () => {
- expect(
- isChildRecordBoundAtDeletion({
- childRecord: { deletedAt: null },
- record: { deletedAt: null },
- }),
- ).toBe(true);
- expect(
- isChildRecordBoundAtDeletion({
- childRecord: { deletedAt: null },
- record: { deletedAt: '2026-09-15T08:00:00.000Z' },
- }),
- ).toBe(true);
- });
-
- it('should not bind a child record detached before a live record is deleted', () => {
- expect(
- isChildRecordBoundAtDeletion({
- childRecord: { deletedAt: '2026-09-15T07:00:00.000Z' },
- record: { deletedAt: null },
- }),
- ).toBe(false);
- });
-
- it('should bind a child record deleted with or after a trashed record', () => {
- expect(
- isChildRecordBoundAtDeletion({
- childRecord: { deletedAt: new Date('2026-09-15T08:00:00.000Z') },
- record: { deletedAt: '2026-09-15T08:00:00.000Z' },
- }),
- ).toBe(true);
- expect(
- isChildRecordBoundAtDeletion({
- childRecord: { deletedAt: '2026-09-15T08:00:01.000Z' },
- record: { deletedAt: new Date('2026-09-15T08:00:00.000Z') },
- }),
- ).toBe(true);
- });
-
- it('should not bind a child record detached before a trashed record was deleted', () => {
- expect(
- isChildRecordBoundAtDeletion({
- childRecord: { deletedAt: '2026-09-15T07:59:59.000Z' },
- record: { deletedAt: '2026-09-15T08:00:00.000Z' },
- }),
- ).toBe(false);
- });
-});
diff --git a/packages/twenty-server/src/engine/twenty-orm/utils/__tests__/is-row-access-expression-reading-role-filter.util.spec.ts b/packages/twenty-server/src/engine/twenty-orm/utils/__tests__/is-row-access-expression-reading-role-filter.util.spec.ts
index 36268579ffe..4fde64e47b2 100644
--- a/packages/twenty-server/src/engine/twenty-orm/utils/__tests__/is-row-access-expression-reading-role-filter.util.spec.ts
+++ b/packages/twenty-server/src/engine/twenty-orm/utils/__tests__/is-row-access-expression-reading-role-filter.util.spec.ts
@@ -39,12 +39,6 @@ describe('isRowAccessExpressionReadingRoleFilter', () => {
operands: [
recordShared,
{ ...recordShared, kind: 'recordNotRestricted' },
- {
- ...recordShared,
- kind: 'inheritedReadability',
- parents: [],
- isOpenWhenDetached: false,
- },
],
}),
).toBe(false);
diff --git a/packages/twenty-server/src/engine/twenty-orm/utils/build-row-access-policy.util.ts b/packages/twenty-server/src/engine/twenty-orm/utils/build-row-access-policy.util.ts
index 95061dad2ba..c2daf72b393 100644
--- a/packages/twenty-server/src/engine/twenty-orm/utils/build-row-access-policy.util.ts
+++ b/packages/twenty-server/src/engine/twenty-orm/utils/build-row-access-policy.util.ts
@@ -1,4 +1,3 @@
-import { isMetadataWritePermitted } from 'src/engine/twenty-orm/utils/is-metadata-write-permitted.util';
import { isDefined } from 'twenty-shared/utils';
import { buildNamedRecordGrantExpression } from 'src/engine/core-modules/record-share/utils/build-named-record-grant-expression.util';
@@ -10,6 +9,7 @@ import {
type RowAccessPolicyContext,
type RowAccessPolicyTarget,
} from 'src/engine/twenty-orm/types/row-access-policy.type';
+import { isObjectOperationDisabled } from 'src/engine/twenty-orm/utils/is-object-operation-disabled.util';
import { isObjectOperationPermitted } from 'src/engine/twenty-orm/utils/is-object-operation-permitted.util';
import { renderRowLevelPermissionFilterToSql } from 'src/engine/twenty-orm/utils/render-row-level-permission-filter-to-sql.util';
@@ -23,16 +23,13 @@ export const buildRowAccessPolicy = ({
}
const context = { subject, environment };
- // Inherited writes also need the parent's writability, or a child could become writable through a SYSTEM parent
+
if (
- target.operationType !== 'select' &&
- !isMetadataWritePermitted({
- writability: target.flatObjectMetadata.writability,
- isSystemContext: false,
- isOwningApplication: subject.isOwningApplication(
- target.flatObjectMetadata,
- ),
- })
+ isObjectOperationDisabled({
+ objectMetadata: target.flatObjectMetadata,
+ operationType: target.operationType,
+ }) &&
+ !subject.isOwningApplication(target.flatObjectMetadata)
) {
return { kind: 'denied' };
}
@@ -57,16 +54,7 @@ export const buildRowAccessPolicy = ({
: { kind: 'denied' };
}
- const recordShareGate = buildRecordShareGate({
- context,
- target,
- buildParentPolicy: (parentTarget) =>
- buildRowAccessPolicy({ ...context, ...parentTarget }),
- });
-
- if (recordShareGate.kind === 'denied') {
- return { kind: 'denied' };
- }
+ const recordShareGate = buildRecordShareGate({ ...context, ...target });
const roleFilter = buildRoleFilterExpression(context, target);
const operands = [
diff --git a/packages/twenty-server/src/engine/twenty-orm/utils/compile-row-access-policy.util.ts b/packages/twenty-server/src/engine/twenty-orm/utils/compile-row-access-policy.util.ts
index 7d95fbb72c7..2777ae87685 100644
--- a/packages/twenty-server/src/engine/twenty-orm/utils/compile-row-access-policy.util.ts
+++ b/packages/twenty-server/src/engine/twenty-orm/utils/compile-row-access-policy.util.ts
@@ -1,6 +1,5 @@
import { assertUnreachable } from 'twenty-shared/utils';
-import { buildInheritedReadabilityCondition } 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 { buildRecordShareExceptionCondition } from 'src/engine/core-modules/record-share/utils/build-record-share-exception-condition.util';
import {
@@ -57,42 +56,6 @@ export const compileRowAccessExpression = ({
...expression,
recordShareTableExpression: environment.recordShareTableExpression,
});
- case 'inheritedReadability':
- return buildInheritedReadabilityCondition({
- tableAlias: expression.tableAlias,
- objectMetadataId: expression.objectMetadataId,
- principalIds: expression.principalIds,
- accessLevels: expression.accessLevels,
- isOpenWhenDetached: expression.isOpenWhenDetached,
- recordShareTableExpression: environment.recordShareTableExpression,
- parents: expression.parents.map((parent) =>
- parent.kind === 'column'
- ? {
- kind: 'column',
- joinColumnName: parent.joinColumnName,
- parentTableAlias: parent.parentTableAlias,
- parentTableExpression: environment.resolveTableExpression(
- parent.parentFlatObjectMetadata.id,
- ),
- policy: compileRowAccessPolicy({
- policy: parent.policy,
- environment,
- }),
- }
- : {
- kind: 'children',
- childTableAlias: parent.childTableAlias,
- childJoinColumnName: parent.childJoinColumnName,
- childTableExpression: environment.resolveTableExpression(
- parent.childFlatObjectMetadata.id,
- ),
- policy: compileRowAccessPolicy({
- policy: parent.policy,
- environment,
- }),
- },
- ),
- });
default:
return assertUnreachable(expression);
}
diff --git a/packages/twenty-server/src/engine/twenty-orm/utils/format-twenty-orm-event-to-database-batch-event.util.ts b/packages/twenty-server/src/engine/twenty-orm/utils/format-twenty-orm-event-to-database-batch-event.util.ts
index 7a75287b6b6..54c1f86368e 100644
--- a/packages/twenty-server/src/engine/twenty-orm/utils/format-twenty-orm-event-to-database-batch-event.util.ts
+++ b/packages/twenty-server/src/engine/twenty-orm/utils/format-twenty-orm-event-to-database-batch-event.util.ts
@@ -28,7 +28,6 @@ import {
TwentyOrmException,
TwentyOrmExceptionCode,
} from 'src/engine/twenty-orm/exceptions/twenty-orm.exception';
-import { type InheritedReadabilityChildRecords } from 'src/engine/core-modules/record-share/types/inherited-readability-child-records.type';
import { type DatabaseBatchEventInput } from 'src/engine/workspace-event-emitter/workspace-event-emitter';
export const formatTwentyOrmEventToDatabaseBatchEvent = <
@@ -41,7 +40,6 @@ export const formatTwentyOrmEventToDatabaseBatchEvent = <
authContext,
recordsAfter,
recordsBefore,
- inheritedReadabilityChildRecordsByRecordId,
}: {
action: DatabaseEventAction;
objectMetadataItem: FlatObjectMetadata;
@@ -50,22 +48,9 @@ export const formatTwentyOrmEventToDatabaseBatchEvent = <
authContext?: RawAuthContext;
recordsAfter?: T[];
recordsBefore?: T[];
- inheritedReadabilityChildRecordsByRecordId?: Map<
- string,
- InheritedReadabilityChildRecords
- >;
}): DatabaseBatchEventInput<T, DatabaseEventAction> | undefined => {
const objectMetadataNameSingular = objectMetadataItem.nameSingular;
- const buildInheritedReadabilityChildRecordsProperty = (recordId: string) => {
- const inheritedReadabilityChildRecords =
- inheritedReadabilityChildRecordsByRecordId?.get(recordId);
-
- return isDefined(inheritedReadabilityChildRecords)
- ? { inheritedReadabilityChildRecords }
- : {};
- };
-
let events: (
| ObjectRecordDeleteEvent<T>
| ObjectRecordRestoreEvent<T>
@@ -166,9 +151,6 @@ export const formatTwentyOrmEventToDatabaseBatchEvent = <
after: recordAfter,
updatedFields,
diff,
- ...(action === DatabaseEventAction.DELETED
- ? buildInheritedReadabilityChildRecordsProperty(recordAfter.id)
- : {}),
},
} satisfies
| ObjectRecordUpdateEvent<T>
@@ -216,7 +198,6 @@ export const formatTwentyOrmEventToDatabaseBatchEvent = <
event.recordId = recordBefore.id;
event.properties = {
before: recordBefore,
- ...buildInheritedReadabilityChildRecordsProperty(recordBefore.id),
};
return event;
diff --git a/packages/twenty-server/src/engine/twenty-orm/utils/is-child-record-bound-at-deletion.util.ts b/packages/twenty-server/src/engine/twenty-orm/utils/is-child-record-bound-at-deletion.util.ts
deleted file mode 100644
index 8423e8630bc..00000000000
--- a/packages/twenty-server/src/engine/twenty-orm/utils/is-child-record-bound-at-deletion.util.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import { isDefined } from 'twenty-shared/utils';
-
-const toTime = (value: unknown): number | undefined =>
- isDefined(value) && (typeof value === 'string' || value instanceof Date)
- ? new Date(value).getTime()
- : undefined;
-
-export const isChildRecordBoundAtDeletion = ({
- childRecord,
- record,
-}: {
- childRecord: Record<string, unknown>;
- record: Record<string, unknown>;
-}): boolean => {
- const childDeletedAt = toTime(childRecord.deletedAt);
-
- if (!isDefined(childDeletedAt)) {
- return true;
- }
-
- const recordDeletedAt = toTime(record.deletedAt);
-
- return isDefined(recordDeletedAt) && childDeletedAt >= recordDeletedAt;
-};
diff --git a/packages/twenty-server/src/engine/twenty-orm/utils/is-metadata-write-permitted.util.ts b/packages/twenty-server/src/engine/twenty-orm/utils/is-metadata-write-permitted.util.ts
deleted file mode 100644
index ace8b8e5470..00000000000
--- a/packages/twenty-server/src/engine/twenty-orm/utils/is-metadata-write-permitted.util.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { MetadataWritability } from 'twenty-shared/types';
-import { isDefined } from 'twenty-shared/utils';
-
-export const isMetadataWritePermitted = ({
- writability,
- isSystemContext,
- isOwningApplication,
-}: {
- writability: MetadataWritability | undefined;
- isSystemContext: boolean;
- isOwningApplication: boolean;
-}): boolean =>
- !isDefined(writability) ||
- writability === MetadataWritability.OPEN ||
- isSystemContext ||
- (writability === MetadataWritability.APPLICATION && isOwningApplication);
diff --git a/packages/twenty-server/src/engine/twenty-orm/utils/is-object-operation-disabled.util.ts b/packages/twenty-server/src/engine/twenty-orm/utils/is-object-operation-disabled.util.ts
new file mode 100644
index 00000000000..039a5ac9e2f
--- /dev/null
+++ b/packages/twenty-server/src/engine/twenty-orm/utils/is-object-operation-disabled.util.ts
@@ -0,0 +1,35 @@
+import { type ObjectPermissionAction } from 'twenty-shared/application';
+import { assertUnreachable } from 'twenty-shared/utils';
+
+import { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';
+import { type OperationType } from 'src/engine/twenty-orm/repository/permissions.utils';
+
+const getObjectPermissionAction = (
+ operationType: OperationType,
+): ObjectPermissionAction => {
+ switch (operationType) {
+ case 'select':
+ return 'canReadObjectRecords';
+ case 'insert':
+ case 'update':
+ return 'canUpdateObjectRecords';
+ case 'delete':
+ return 'canDestroyObjectRecords';
+ case 'restore':
+ case 'soft-delete':
+ return 'canSoftDeleteObjectRecords';
+ default:
+ return assertUnreachable(operationType);
+ }
+};
+
+export const isObjectOperationDisabled = ({
+ objectMetadata,
+ operationType,
+}: {
+ objectMetadata: Pick<FlatObjectMetadata, 'disabledObjectPermissionActions'>;
+ operationType: OperationType;
+}): boolean =>
+ objectMetadata.disabledObjectPermissionActions?.includes(
+ getObjectPermissionAction(operationType),
+ ) ?? false;
diff --git a/packages/twenty-server/src/engine/twenty-orm/utils/is-row-access-expression-reading-role-filter.util.ts b/packages/twenty-server/src/engine/twenty-orm/utils/is-row-access-expression-reading-role-filter.util.ts
index 03d522dfccc..5dac6ef3112 100644
--- a/packages/twenty-server/src/engine/twenty-orm/utils/is-row-access-expression-reading-role-filter.util.ts
+++ b/packages/twenty-server/src/engine/twenty-orm/utils/is-row-access-expression-reading-role-filter.util.ts
@@ -4,8 +4,6 @@ import { assertUnreachable } from 'twenty-shared/utils';
import { type RowAccessExpression } from 'src/engine/twenty-orm/types/row-access-policy.type';
-// Parent policies are left out: writes check parents on their own through
-// validateInheritedParentsAreWritableOrThrow
export const isRowAccessExpressionReadingRoleFilter = (
expression: RowAccessExpression,
): boolean => {
@@ -17,7 +15,6 @@ export const isRowAccessExpressionReadingRoleFilter = (
return true;
case 'recordShared':
case 'recordNotRestricted':
- case 'inheritedReadability':
return false;
default:
return assertUnreachable(expression);
diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/constants/standard-command-menu-item.constant.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/constants/standard-command-menu-item.constant.ts
index 04a80b1f18d..37ea2724850 100644
--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/constants/standard-command-menu-item.constant.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/constants/standard-command-menu-item.constant.ts
@@ -1118,7 +1118,7 @@ export const STANDARD_COMMAND_MENU_ITEMS = {
),
availabilityType: CommandMenuItemAvailabilityType.RECORD_SELECTION,
conditionalAvailabilityExpression:
- 'numberOfSelectedRecords == 1 and featureFlags.IS_RECORD_LEVEL_SHARING_ENABLED and not objectMetadataItem.isSystem and objectMetadataItem.readability != "APPLICATION" and objectMetadataItem.readability != "SYSTEM" and noneDefined(selectedRecords, "deletedAt")',
+ 'numberOfSelectedRecords == 1 and featureFlags.IS_RECORD_LEVEL_SHARING_ENABLED and not objectMetadataItem.isSystem and noneDefined(selectedRecords, "deletedAt")',
availabilityObjectMetadataUniversalIdentifier: null,
frontComponentUniversalIdentifier: null,
engineComponentKey: EngineComponentKey.SHARE_RECORD,
diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/constants/standard-disabled-object-permission-actions.constant.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/constants/standard-disabled-object-permission-actions.constant.ts
new file mode 100644
index 00000000000..9ec2b820514
--- /dev/null
+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/constants/standard-disabled-object-permission-actions.constant.ts
@@ -0,0 +1,17 @@
+import { type ObjectPermissionAction } from 'twenty-shared/application';
+
+// sorted to match the order the 2.53 upgrade command stores them in
+export const PLATFORM_MANAGED_DISABLED_OBJECT_PERMISSION_ACTIONS: ObjectPermissionAction[] =
+ [
+ 'canDestroyObjectRecords',
+ 'canReadObjectRecords',
+ 'canSoftDeleteObjectRecords',
+ 'canUpdateObjectRecords',
+ ];
+
+export const PLATFORM_WRITTEN_DISABLED_OBJECT_PERMISSION_ACTIONS: ObjectPermissionAction[] =
+ [
+ 'canDestroyObjectRecords',
+ 'canSoftDeleteObjectRecords',
+ 'canUpdateObjectRecords',
+ ];
diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/standard-object-readability.spec.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/standard-object-readability.spec.ts
index 03407ad38a2..e5fae466260 100644
--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/standard-object-readability.spec.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/standard-object-readability.spec.ts
@@ -1,30 +1,14 @@
-import {
- STANDARD_OBJECT_FIELDS,
- STANDARD_OBJECTS,
-} from 'twenty-shared/metadata';
-import { MetadataReadability, MetadataWritability } from 'twenty-shared/types';
+import { STANDARD_OBJECTS } from 'twenty-shared/metadata';
+import { MetadataReadability } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
import { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';
-import { resolveInheritedReadabilityParents } from 'src/engine/core-modules/record-share/utils/resolve-inherited-readability-parents.util';
import { computeTwentyStandardApplicationAllFlatEntityMaps } from 'src/engine/workspace-manager/twenty-standard-application/utils/twenty-standard-application-all-flat-entity-maps.constant';
const WORKSPACE_ID = '20202020-1111-4111-8111-111111111111';
const TWENTY_STANDARD_APPLICATION_ID = '20202020-2222-4222-8222-222222222222';
const NOW = '2024-01-01T00:00:00.000Z';
-const INHERITED_STANDARD_OBJECT_PARENT_FIELDS = {
- attachment: STANDARD_OBJECT_FIELDS.attachment.targetNote,
- timelineActivity: STANDARD_OBJECT_FIELDS.timelineActivity.targetPerson,
- note: STANDARD_OBJECT_FIELDS.note.noteTargets,
- noteTarget: STANDARD_OBJECT_FIELDS.noteTarget.targetPerson,
- task: STANDARD_OBJECT_FIELDS.task.taskTargets,
- taskTarget: STANDARD_OBJECT_FIELDS.taskTarget.targetPerson,
- messageThreadTarget: STANDARD_OBJECT_FIELDS.messageThreadTarget.messageThread,
- calendarEventTarget: STANDARD_OBJECT_FIELDS.calendarEventTarget.calendarEvent,
- agentChatThreadTarget: STANDARD_OBJECT_FIELDS.agentChatThreadTarget.thread,
-} as const;
-
describe('Standard object readability', () => {
const { allFlatEntityMaps } =
computeTwentyStandardApplicationAllFlatEntityMaps({
@@ -33,62 +17,19 @@ describe('Standard object readability', () => {
twentyStandardApplicationId: TWENTY_STANDARD_APPLICATION_ID,
});
- const standardFlatObjectMetadatas = Object.values(
- allFlatEntityMaps.flatObjectMetadataMaps.byUniversalIdentifier,
- ).filter(isDefined);
-
const findStandardFlatObjectMetadata = (
objectName: keyof typeof STANDARD_OBJECTS,
): FlatObjectMetadata | undefined =>
- standardFlatObjectMetadatas.find(
- (flatObjectMetadata) =>
- flatObjectMetadata.universalIdentifier ===
- STANDARD_OBJECTS[objectName].universalIdentifier,
- );
-
- const resolveParents = (objectName: keyof typeof STANDARD_OBJECTS) => {
- const flatObjectMetadata = findStandardFlatObjectMetadata(objectName);
-
- expect(flatObjectMetadata).toBeDefined();
-
- return resolveInheritedReadabilityParents({
- flatObjectMetadata: flatObjectMetadata!,
- flatFieldMetadataMaps: allFlatEntityMaps.flatFieldMetadataMaps,
- flatObjectMetadataMaps: allFlatEntityMaps.flatObjectMetadataMaps,
- });
- };
-
- const inheritedObjectNames = Object.keys(
- INHERITED_STANDARD_OBJECT_PARENT_FIELDS,
- ) as (keyof typeof INHERITED_STANDARD_OBJECT_PARENT_FIELDS)[];
-
- const nonOpenObjectUniversalIdentifiers: string[] = [
- STANDARD_OBJECTS.agentMessage.universalIdentifier,
- STANDARD_OBJECTS.agentMessagePart.universalIdentifier,
- STANDARD_OBJECTS.agentMessageReaction.universalIdentifier,
- STANDARD_OBJECTS.agentTurn.universalIdentifier,
- STANDARD_OBJECTS.agentChatThread.universalIdentifier,
- STANDARD_OBJECTS.agentChatThreadParticipant.universalIdentifier,
-
- STANDARD_OBJECTS.campaignDelivery.universalIdentifier,
- STANDARD_OBJECTS.messageSuppression.universalIdentifier,
-
- STANDARD_OBJECTS.recordShare.universalIdentifier,
- STANDARD_OBJECTS.workflowRun.universalIdentifier,
- STANDARD_OBJECTS.shortLink.universalIdentifier,
- ...inheritedObjectNames.map(
- (objectName) => STANDARD_OBJECTS[objectName].universalIdentifier,
- ),
- ];
-
- const otherStandardFlatObjectMetadatas = standardFlatObjectMetadatas.filter(
- (flatObjectMetadata) =>
- !nonOpenObjectUniversalIdentifiers.includes(
- flatObjectMetadata.universalIdentifier,
- ),
- );
+ Object.values(
+ allFlatEntityMaps.flatObjectMetadataMaps.byUniversalIdentifier,
+ )
+ .filter(isDefined)
+ .find(
+ (flatObjectMetadata) =>
+ flatObjectMetadata.universalIdentifier ===
+ STANDARD_OBJECTS[objectName].universalIdentifier,
+ );
- // workflowRun grants follow the core workflow's visibility, which does not live on the workspace workflow record
it('declares workflowRun PRIVATE and leaves workflow and workflowVersion OPEN', () => {
expect(findStandardFlatObjectMetadata('workflowRun')).toMatchObject({
readability: MetadataReadability.PRIVATE,
@@ -101,162 +42,12 @@ describe('Standard object readability', () => {
});
});
- it.each(['recordShare', 'shortLink'] as const)(
- 'declares %s SYSTEM for readability and writability',
+ it.each(['agentChatThread', 'agentChatThreadParticipant'] as const)(
+ 'declares %s PRIVATE, read through its own grants',
(objectName) => {
expect(findStandardFlatObjectMetadata(objectName)).toMatchObject({
- readability: MetadataReadability.SYSTEM,
- writability: MetadataWritability.SYSTEM,
+ readability: MetadataReadability.PRIVATE,
});
},
);
-
- it('declares agentChatThread PRIVATE, read through its own grants', () => {
- expect(findStandardFlatObjectMetadata('agentChatThread')).toMatchObject({
- readability: MetadataReadability.PRIVATE,
- readabilityParentFieldUniversalIdentifiers: null,
- });
- });
-
- it('declares agentChatThreadParticipant PRIVATE, written only by the chat resolvers', () => {
- expect(
- findStandardFlatObjectMetadata('agentChatThreadParticipant'),
- ).toMatchObject({
- readability: MetadataReadability.PRIVATE,
- writability: MetadataWritability.SYSTEM,
- });
- });
-
- // Inheriting from the record would reveal which private conversations are filed under it
- it('resolves its thread as the only parent of an agentChatThreadTarget', () => {
- expect(
- resolveParents('agentChatThreadTarget').map((parent) =>
- parent.kind === 'column'
- ? {
- joinColumnName: parent.joinColumnName,
- parentNameSingular: parent.parentFlatObjectMetadata.nameSingular,
- }
- : parent.kind,
- ),
- ).toEqual([
- { joinColumnName: 'threadId', parentNameSingular: 'agentChatThread' },
- ]);
- });
-
- it.each(inheritedObjectNames)(
- 'declares %s INHERITED from its parent field',
- (objectName) => {
- expect(findStandardFlatObjectMetadata(objectName)).toMatchObject({
- readability: MetadataReadability.INHERITED,
- readabilityParentFieldUniversalIdentifiers: [
- INHERITED_STANDARD_OBJECT_PARENT_FIELDS[objectName]
- .universalIdentifier,
- ],
- });
- },
- );
-
- it('resolves every attachment target as a parent of attachment', () => {
- const parentJoinColumnNames = resolveParents('attachment')
- .map((parent) => (parent.kind === 'column' ? parent.joinColumnName : ''))
- .sort();
-
- expect(parentJoinColumnNames).toEqual(
- [
- 'targetAgentChatThreadId',
- 'targetCompanyId',
- 'targetDashboardId',
- 'targetNoteId',
- 'targetOpportunityId',
- 'targetPersonId',
- 'targetTaskId',
- 'targetWorkflowId',
- ].sort(),
- );
- });
-
- it('resolves the agent chat thread as the parent of a chat attachment', () => {
- expect(
- resolveParents('attachment').map((parent) =>
- parent.kind === 'column'
- ? {
- joinColumnName: parent.joinColumnName,
- parentNameSingular: parent.parentFlatObjectMetadata.nameSingular,
- parentReadability: parent.parentFlatObjectMetadata.readability,
- }
- : parent.kind,
- ),
- ).toContainEqual({
- joinColumnName: 'targetAgentChatThreadId',
- parentNameSingular: 'agentChatThread',
- parentReadability: MetadataReadability.PRIVATE,
- });
- });
-
- it('resolves every target of a noteTarget as its parent, not the note', () => {
- const parents = resolveParents('noteTarget').map((parent) =>
- parent.kind === 'column'
- ? {
- joinColumnName: parent.joinColumnName,
- parentNameSingular: parent.parentFlatObjectMetadata.nameSingular,
- }
- : parent.kind,
- );
-
- expect(parents).toEqual(
- expect.arrayContaining([
- { joinColumnName: 'targetPersonId', parentNameSingular: 'person' },
- { joinColumnName: 'targetCompanyId', parentNameSingular: 'company' },
- {
- joinColumnName: 'targetOpportunityId',
- parentNameSingular: 'opportunity',
- },
- ]),
- );
- expect(parents).not.toContainEqual({
- joinColumnName: 'noteId',
- parentNameSingular: 'note',
- });
- });
-
- it('resolves its note targets as the parents of a note, through the noteId column', () => {
- expect(
- resolveParents('note').map((parent) =>
- parent.kind === 'children'
- ? {
- childNameSingular: parent.childFlatObjectMetadata.nameSingular,
- childJoinColumnName: parent.childJoinColumnName,
- }
- : parent.kind,
- ),
- ).toEqual([
- { childNameSingular: 'noteTarget', childJoinColumnName: 'noteId' },
- ]);
- });
-
- it('resolves its task targets as the parents of a task, through the taskId column', () => {
- expect(
- resolveParents('task').map((parent) =>
- parent.kind === 'children'
- ? {
- childNameSingular: parent.childFlatObjectMetadata.nameSingular,
- childJoinColumnName: parent.childJoinColumnName,
- }
- : parent.kind,
- ),
- ).toEqual([
- { childNameSingular: 'taskTarget', childJoinColumnName: 'taskId' },
- ]);
- });
-
- it('leaves every other standard object OPEN for readability', () => {
- const readabilities = new Set(
- otherStandardFlatObjectMetadatas.map(
- (flatObjectMetadata) => flatObjectMetadata.readability,
- ),
- );
-
- expect(otherStandardFlatObjectMetadatas.length).toBeGreaterThan(0);
- expect([...readabilities]).toEqual([MetadataReadability.OPEN]);
- });
});
diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/command-menu-item/build-standard-flat-command-menu-item-maps.util.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/command-menu-item/build-standard-flat-command-menu-item-maps.util.ts
index 1d1957983f8..6bb471e0add 100644
--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/command-menu-item/build-standard-flat-command-menu-item-maps.util.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/command-menu-item/build-standard-flat-command-menu-item-maps.util.ts
@@ -1,5 +1,4 @@
import { TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER } from 'twenty-shared/application';
-import { MetadataReadability } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
import { v4 } from 'uuid';
@@ -58,7 +57,9 @@ export const buildStandardFlatCommandMenuItemMaps = ({
.filter(
(flatObject) =>
flatObject.isActive &&
- flatObject.readability !== MetadataReadability.SYSTEM,
+ !flatObject.disabledObjectPermissionActions?.includes(
+ 'canReadObjectRecords',
+ ),
)
.sort(seedCompareObjectMetadataForNavigationPosition);
diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/object-metadata/create-standard-flat-object-metadata.util.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/object-metadata/create-standard-flat-object-metadata.util.ts
index 735379c6bfe..b482d3675ee 100644
--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/object-metadata/create-standard-flat-object-metadata.util.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/object-metadata/create-standard-flat-object-metadata.util.ts
@@ -13,6 +13,10 @@ import {
type CreateStandardObjectArgs,
createStandardObjectFlatMetadata,
} from 'src/engine/workspace-manager/twenty-standard-application/utils/object-metadata/create-standard-object-flat-metadata.util';
+import {
+ PLATFORM_MANAGED_DISABLED_OBJECT_PERMISSION_ACTIONS,
+ PLATFORM_WRITTEN_DISABLED_OBJECT_PERMISSION_ACTIONS,
+} from 'src/engine/workspace-manager/twenty-standard-application/constants/standard-disabled-object-permission-actions.constant';
export const STANDARD_FLAT_OBJECT_METADATA_BUILDERS_BY_OBJECT_NAME = {
agentChatThread: (
@@ -136,6 +140,8 @@ export const STANDARD_FLAT_OBJECT_METADATA_BUILDERS_BY_OBJECT_NAME = {
isUICreatable: false,
readability: MetadataReadability.SYSTEM,
writability: MetadataWritability.SYSTEM,
+ disabledObjectPermissionActions:
+ PLATFORM_MANAGED_DISABLED_OBJECT_PERMISSION_ACTIONS,
labelIdentifierFieldMetadataName: 'id',
},
}),
@@ -178,6 +184,8 @@ export const STANDARD_FLAT_OBJECT_METADATA_BUILDERS_BY_OBJECT_NAME = {
isUICreatable: false,
readability: MetadataReadability.SYSTEM,
writability: MetadataWritability.SYSTEM,
+ disabledObjectPermissionActions:
+ PLATFORM_MANAGED_DISABLED_OBJECT_PERMISSION_ACTIONS,
labelIdentifierFieldMetadataName: 'id',
},
}),
@@ -221,6 +229,8 @@ export const STANDARD_FLAT_OBJECT_METADATA_BUILDERS_BY_OBJECT_NAME = {
isUICreatable: false,
readability: MetadataReadability.SYSTEM,
writability: MetadataWritability.SYSTEM,
+ disabledObjectPermissionActions:
+ PLATFORM_MANAGED_DISABLED_OBJECT_PERMISSION_ACTIONS,
labelIdentifierFieldMetadataName: 'id',
},
}),
@@ -266,6 +276,8 @@ export const STANDARD_FLAT_OBJECT_METADATA_BUILDERS_BY_OBJECT_NAME = {
// member can read the message's thread
readability: MetadataReadability.SYSTEM,
writability: MetadataWritability.SYSTEM,
+ disabledObjectPermissionActions:
+ PLATFORM_MANAGED_DISABLED_OBJECT_PERMISSION_ACTIONS,
labelIdentifierFieldMetadataName: 'id',
},
}),
@@ -311,6 +323,8 @@ export const STANDARD_FLAT_OBJECT_METADATA_BUILDERS_BY_OBJECT_NAME = {
// owner grant and written only through the chat resolvers
readability: MetadataReadability.PRIVATE,
writability: MetadataWritability.SYSTEM,
+ disabledObjectPermissionActions:
+ PLATFORM_WRITTEN_DISABLED_OBJECT_PERMISSION_ACTIONS,
labelIdentifierFieldMetadataName: 'id',
},
}),
@@ -354,6 +368,8 @@ export const STANDARD_FLAT_OBJECT_METADATA_BUILDERS_BY_OBJECT_NAME = {
isUICreatable: false,
readability: MetadataReadability.SYSTEM,
writability: MetadataWritability.SYSTEM,
+ disabledObjectPermissionActions:
+ PLATFORM_MANAGED_DISABLED_OBJECT_PERMISSION_ACTIONS,
labelIdentifierFieldMetadataName: 'id',
},
}),
@@ -397,6 +413,8 @@ export const STANDARD_FLAT_OBJECT_METADATA_BUILDERS_BY_OBJECT_NAME = {
isUICreatable: false,
readability: MetadataReadability.SYSTEM,
writability: MetadataWritability.SYSTEM,
+ disabledObjectPermissionActions:
+ PLATFORM_MANAGED_DISABLED_OBJECT_PERMISSION_ACTIONS,
labelIdentifierFieldMetadataName: 'id',
},
}),
@@ -522,6 +540,8 @@ export const STANDARD_FLAT_OBJECT_METADATA_BUILDERS_BY_OBJECT_NAME = {
isAuditLogged: false,
isUICreatable: false,
writability: MetadataWritability.SYSTEM,
+ disabledObjectPermissionActions:
+ PLATFORM_WRITTEN_DISABLED_OBJECT_PERMISSION_ACTIONS,
labelIdentifierFieldMetadataName: 'id',
},
workspaceId,
@@ -958,6 +978,8 @@ export const STANDARD_FLAT_OBJECT_METADATA_BUILDERS_BY_OBJECT_NAME = {
isAuditLogged: false,
isUICreatable: false,
writability: MetadataWritability.SYSTEM,
+ disabledObjectPermissionActions:
+ PLATFORM_WRITTEN_DISABLED_OBJECT_PERMISSION_ACTIONS,
labelIdentifierFieldMetadataName: 'id',
},
workspaceId,
@@ -1007,6 +1029,8 @@ export const STANDARD_FLAT_OBJECT_METADATA_BUILDERS_BY_OBJECT_NAME = {
isAuditLogged: false,
isUICreatable: false,
writability: MetadataWritability.SYSTEM,
+ disabledObjectPermissionActions:
+ PLATFORM_WRITTEN_DISABLED_OBJECT_PERMISSION_ACTIONS,
labelIdentifierFieldMetadataName: 'id',
},
workspaceId,
@@ -1390,6 +1414,8 @@ export const STANDARD_FLAT_OBJECT_METADATA_BUILDERS_BY_OBJECT_NAME = {
isUICreatable: false,
writability: MetadataWritability.SYSTEM,
readability: MetadataReadability.SYSTEM,
+ disabledObjectPermissionActions:
+ PLATFORM_MANAGED_DISABLED_OBJECT_PERMISSION_ACTIONS,
labelIdentifierFieldMetadataName: 'id',
},
workspaceId,
@@ -1437,6 +1463,8 @@ export const STANDARD_FLAT_OBJECT_METADATA_BUILDERS_BY_OBJECT_NAME = {
isUICreatable: false,
writability: MetadataWritability.SYSTEM,
readability: MetadataReadability.SYSTEM,
+ disabledObjectPermissionActions:
+ PLATFORM_MANAGED_DISABLED_OBJECT_PERMISSION_ACTIONS,
labelIdentifierFieldMetadataName: 'resolvedDestinationUrl',
},
workspaceId,
@@ -1646,6 +1674,8 @@ export const STANDARD_FLAT_OBJECT_METADATA_BUILDERS_BY_OBJECT_NAME = {
isSystem: true,
isUICreatable: false,
writability: MetadataWritability.SYSTEM,
+ disabledObjectPermissionActions:
+ PLATFORM_WRITTEN_DISABLED_OBJECT_PERMISSION_ACTIONS,
labelIdentifierFieldMetadataName: 'id',
},
workspaceId,
diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/object-metadata/create-standard-object-flat-metadata.util.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/object-metadata/create-standard-object-flat-metadata.util.ts
index db03fae4b76..9ffb8533647 100644
--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/object-metadata/create-standard-object-flat-metadata.util.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/object-metadata/create-standard-object-flat-metadata.util.ts
@@ -5,7 +5,10 @@ import {
ObjectOpenRecordIn,
ObjectSharingReach,
} from 'twenty-shared/types';
-import { TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER } from 'twenty-shared/application';
+import {
+ type ObjectPermissionAction,
+ TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER,
+} from 'twenty-shared/application';
import { isDefined } from 'twenty-shared/utils';
import { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';
@@ -29,6 +32,7 @@ export type CreateStandardObjectContext<O extends AllStandardObjectName> = {
writability?: MetadataWritability;
readability?: MetadataReadability;
readabilityParentFieldMetadataNames?: AllStandardObjectFieldName<O>[];
+ disabledObjectPermissionActions?: ObjectPermissionAction[];
openRecordIn?: ObjectOpenRecordIn;
shortcut?: string | null;
duplicateCriteria?: string[][] | null;
@@ -77,6 +81,7 @@ export const createStandardObjectFlatMetadata = <
writability = MetadataWritability.OPEN,
readability = MetadataReadability.OPEN,
readabilityParentFieldMetadataNames,
+ disabledObjectPermissionActions,
openRecordIn = ObjectOpenRecordIn.USER_CHOICE,
shortcut = null,
duplicateCriteria = null,
@@ -135,7 +140,7 @@ export const createStandardObjectFlatMetadata = <
writability,
readability,
readabilityParentFieldUniversalIdentifiers,
- disabledObjectPermissionActions: null,
+ disabledObjectPermissionActions: disabledObjectPermissionActions ?? null,
sharingReach: ObjectSharingReach.WORKSPACE,
openRecordIn,
isLabelSyncedWithName: false,
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/flat-object-permission-validator.service.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/flat-object-permission-validator.service.ts
index 57d5fe73f88..196d523395c 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/flat-object-permission-validator.service.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/flat-object-permission-validator.service.ts
@@ -98,6 +98,7 @@ export class FlatObjectPermissionValidatorService {
...validateObjectPermissionGrantsNoDisabledAction({
flatObjectPermission: flatObjectPermissionToValidate,
flatObjectMetadata: referencedObjectMetadata,
+ flatRole: referencedRole,
}),
);
@@ -217,6 +218,7 @@ export class FlatObjectPermissionValidatorService {
updatedFlatObjectPermission.objectMetadataUniversalIdentifier,
flatEntityMaps: flatObjectMetadataMaps,
}),
+ flatRole: referencedRole,
}),
);
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/utils/__tests__/validate-object-permission-grants-no-disabled-action.util.spec.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/utils/__tests__/validate-object-permission-grants-no-disabled-action.util.spec.ts
index 4dd35f79d13..cab11510c3b 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/utils/__tests__/validate-object-permission-grants-no-disabled-action.util.spec.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/utils/__tests__/validate-object-permission-grants-no-disabled-action.util.spec.ts
@@ -20,11 +20,18 @@ const buildObjectPermission = (
...overrides,
});
+const OWNING_APPLICATION_UNIVERSAL_IDENTIFIER = 'stripe-universal-identifier';
+
const invoice = getFlatObjectMetadataMock({
universalIdentifier: OBJECT_UNIVERSAL_IDENTIFIER,
+ applicationUniversalIdentifier: OWNING_APPLICATION_UNIVERSAL_IDENTIFIER,
disabledObjectPermissionActions: ['canDestroyObjectRecords'],
});
+const workspaceRole = {
+ applicationUniversalIdentifier: 'workspace-custom-universal-identifier',
+};
+
describe('validateObjectPermissionGrantsNoDisabledAction', () => {
it('should reject granting an action the object disables', () => {
expect(
@@ -33,6 +40,7 @@ describe('validateObjectPermissionGrantsNoDisabledAction', () => {
canDestroyObjectRecords: true,
}),
flatObjectMetadata: invoice,
+ flatRole: workspaceRole,
}),
).toEqual([expect.objectContaining({ value: 'canDestroyObjectRecords' })]);
});
@@ -45,8 +53,24 @@ describe('validateObjectPermissionGrantsNoDisabledAction', () => {
canDestroyObjectRecords,
}),
flatObjectMetadata: invoice,
+ flatRole: workspaceRole,
}),
).toEqual([]);
}
});
+
+ it('should let the owning application grant a disabled action to its own role', () => {
+ expect(
+ validateObjectPermissionGrantsNoDisabledAction({
+ flatObjectPermission: buildObjectPermission({
+ canDestroyObjectRecords: true,
+ }),
+ flatObjectMetadata: invoice,
+ flatRole: {
+ applicationUniversalIdentifier:
+ OWNING_APPLICATION_UNIVERSAL_IDENTIFIER,
+ },
+ }),
+ ).toEqual([]);
+ });
});
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/utils/validate-object-permission-grants-no-disabled-action.util.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/utils/validate-object-permission-grants-no-disabled-action.util.ts
index 1f5781a2cf6..a372d86fe95 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/utils/validate-object-permission-grants-no-disabled-action.util.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/utils/validate-object-permission-grants-no-disabled-action.util.ts
@@ -1,24 +1,45 @@
import { msg, t } from '@lingui/core/macro';
import { type ObjectPermissionAction } from 'twenty-shared/application';
+import { isDefined } from 'twenty-shared/utils';
import { PermissionsExceptionCode } from 'src/engine/metadata-modules/permissions/permissions.exception';
import { type UniversalFlatObjectMetadata } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-object-metadata.type';
import { type UniversalFlatObjectPermission } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-object-permission.type';
+import { type UniversalFlatRole } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-role.type';
import { type FlatEntityValidationError } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/builders/types/failed-flat-entity-validation.type';
export const validateObjectPermissionGrantsNoDisabledAction = ({
flatObjectPermission,
flatObjectMetadata,
+ flatRole,
}: {
flatObjectPermission: Pick<
UniversalFlatObjectPermission,
ObjectPermissionAction | 'objectMetadataUniversalIdentifier'
>;
flatObjectMetadata:
- | Pick<UniversalFlatObjectMetadata, 'disabledObjectPermissionActions'>
+ | Pick<
+ UniversalFlatObjectMetadata,
+ 'disabledObjectPermissionActions' | 'applicationUniversalIdentifier'
+ >
| undefined;
-}): FlatEntityValidationError[] =>
- (flatObjectMetadata?.disabledObjectPermissionActions ?? [])
+ flatRole:
+ | Pick<UniversalFlatRole, 'applicationUniversalIdentifier'>
+ | undefined;
+}): FlatEntityValidationError[] => {
+ if (!isDefined(flatObjectMetadata)) {
+ return [];
+ }
+
+ // the owning application keeps disabled actions on its own objects, so its roles may grant them
+ if (
+ flatRole?.applicationUniversalIdentifier ===
+ flatObjectMetadata.applicationUniversalIdentifier
+ ) {
+ return [];
+ }
+
+ return (flatObjectMetadata.disabledObjectPermissionActions ?? [])
.filter((action) => flatObjectPermission[action])
.map((action) => ({
code: PermissionsExceptionCode.INVALID_SETTING,
@@ -26,3 +47,4 @@ export const validateObjectPermissionGrantsNoDisabledAction = ({
userFriendlyMessage: msg`This permission is disabled on the object and cannot be granted`,
value: action,
}));
+};
diff --git a/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/listeners/__tests__/workflow-database-event-trigger.listener.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/listeners/__tests__/workflow-database-event-trigger.listener.spec.ts
index f2d27ae7dbd..04697745c8a 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/listeners/__tests__/workflow-database-event-trigger.listener.spec.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/listeners/__tests__/workflow-database-event-trigger.listener.spec.ts
@@ -601,45 +601,6 @@ describe('WorkflowDatabaseEventTriggerListener', () => {
);
});
- it('should not hand the child records captured with a deletion to the workflow', async () => {
- const capturedEvent = {
- ...mockPayload.events[0],
- properties: {
- before: { field1: 'old', field2: 'old' },
- inheritedReadabilityChildRecords: {
- noteTarget: [{ id: 'note-target-1', noteId: 'record-1' }],
- },
- },
- };
-
- setTriggerMap([
- {
- type: AutomatedTriggerType.DATABASE_EVENT,
- workflowId,
- settings: {
- eventName: 'deleteEvent',
- },
- },
- ]);
-
- await listener.handleObjectRecordDeleteEvent({
- ...mockPayload,
- name: 'deleteEvent',
- events: [capturedEvent],
- });
-
- expect(messageQueueService.add).toHaveBeenCalledWith(
- WorkflowTriggerJob.name,
- expect.objectContaining({
- payload: {
- ...capturedEvent,
- properties: { before: { field1: 'old', field2: 'old' } },
- },
- }),
- { retryLimit: 3 },
- );
- });
-
it('should handle destroy events correctly', async () => {
const destroyPayload: WorkspaceEventBatch<any> = {
...mockPayload,
@@ -769,59 +730,6 @@ describe('WorkflowDatabaseEventTriggerListener', () => {
);
});
- it('should not trigger workflow for a system object and no resolved role', async () => {
- const systemPayload: WorkspaceEventBatch<ObjectRecordUpdateEvent> = {
- ...mockPayload,
- objectMetadata: createMockFlatObjectMetadata({
- readability: MetadataReadability.SYSTEM,
- }),
- };
-
- workspaceCacheService.getOrRecompute.mockImplementation(((
- _workspaceId: string,
- keys: string[],
- ) =>
- Promise.resolve(
- !keys.includes('workflowAutomatedTriggerMaps')
- ? {
- flatObjectMetadataMaps: { byUniversalIdentifier: {} },
- featureFlagsMap: {},
- flatApplicationMaps: {
- byId: {},
- idByUniversalIdentifier: {},
- },
- flatRoleMaps: { byUniversalIdentifier: {} },
- rolesPermissions: {},
- roleIdsWithAllRecordsAccess: [],
- flatRowLevelPermissionPredicateMaps:
- createEmptyFlatEntityMaps(),
- flatRowLevelPermissionPredicateGroupMaps:
- createEmptyFlatEntityMaps(),
- flatFieldMetadataMaps: createEmptyFlatEntityMaps(),
- }
- : {
- flatApplicationMaps: { byId: {}, idByUniversalIdentifier: {} },
- workflowAutomatedTriggerMaps: {
- byWorkflowId: {
- [workflowId]: {
- type: AutomatedTriggerType.DATABASE_EVENT,
- coreWorkflowVersionId: `core-version-${workflowId}`,
- workspaceWorkflowVersionId: `workspace-version-${workflowId}`,
- workflowId,
- applicationId: WORKSPACE_CUSTOM_APPLICATION_ID,
- settings: { eventName: databaseEventName },
- },
- },
- },
- },
- )) as never);
-
- await listener.handleObjectRecordUpdateEvent(systemPayload);
-
- expect(recordShareStorageService.findByRecordIds).not.toHaveBeenCalled();
- expect(messageQueueService.add).not.toHaveBeenCalled();
- });
-
it('should handle multiple events in a batch', async () => {
const batchPayload: WorkspaceEventBatch<any> = {
...mockPayload,
diff --git a/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/listeners/workflow-database-event-trigger.listener.ts b/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/listeners/workflow-database-event-trigger.listener.ts
index 1b1944d6c34..5c1310d57dd 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/listeners/workflow-database-event-trigger.listener.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/listeners/workflow-database-event-trigger.listener.ts
@@ -26,7 +26,6 @@ import { type FlatFieldMetadata } from 'src/engine/metadata-modules/flat-field-m
import { buildFieldMapsFromFlatObjectMetadata } from 'src/engine/metadata-modules/flat-field-metadata/utils/build-field-maps-from-flat-object-metadata.util';
import { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';
import { RecordAccessPolicyService } from 'src/engine/core-modules/record-share/services/record-access-policy.service';
-import { omitInheritedReadabilityChildRecords } from 'src/engine/core-modules/record-share/utils/omit-inherited-readability-child-records.util';
import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
import { ApplicationService } from 'src/engine/core-modules/application/application.service';
@@ -428,7 +427,7 @@ export class WorkflowDatabaseEventTriggerListener {
workflowId:
eventListener.legacyWorkflowId ?? eventListener.workflowId,
...buildCoreDispatchIds(eventListener),
- payload: omitInheritedReadabilityChildRecords(eventPayload),
+ payload: eventPayload,
},
{ retryLimit: 3 },
);
diff --git a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/chat-thread-sharing.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/chat-thread-sharing.integration-spec.ts
index df5e73c89f6..2a8d2010288 100644
--- a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/chat-thread-sharing.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/chat-thread-sharing.integration-spec.ts
@@ -894,12 +894,6 @@ describe('Conversations through the record API', () => {
'Renamed through the record API',
);
- const legacyArchive = await updateThreadRecord(threadId, {
- archivedAt: new Date().toISOString(),
- });
- expect(legacyArchive.body.errors[0].extensions.code).toBe('FORBIDDEN');
- expect((await readStoredThread(threadId))?.archivedAt).toBeNull();
-
const outsiderSoftDelete = await softDeleteThreadRecord(
threadId,
APPLE_JONY_MEMBER_ACCESS_TOKEN,
diff --git a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/create-share-with-object-records-permissions.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/create-share-with-object-records-permissions.integration-spec.ts
index 0191f85a913..ccb03245214 100644
--- a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/create-share-with-object-records-permissions.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/create-share-with-object-records-permissions.integration-spec.ts
@@ -15,7 +15,6 @@ import { createOneObjectMetadata } from 'test/integration/metadata/suites/object
import { deleteOneObjectMetadata } from 'test/integration/metadata/suites/object-metadata/utils/delete-one-object-metadata.util';
import { setObjectReadability } from 'test/integration/metadata/suites/object-metadata/utils/set-object-readability.util';
import { updateOneObjectMetadata } from 'test/integration/metadata/suites/object-metadata/utils/update-one-object-metadata.util';
-import { upsertObjectPermissions } from 'test/integration/metadata/suites/object-permission/utils/upsert-object-permissions.util';
import { findOneRoleByLabel } from 'test/integration/metadata/suites/role/utils/find-one-role-by-label.util';
import { updateFeatureFlag } from 'test/integration/metadata/suites/utils/update-feature-flag.util';
import { deleteRecordsByIds } from 'test/integration/utils/delete-records-by-ids';
@@ -26,7 +25,6 @@ import {
FeatureFlagKey,
FieldMetadataType,
MetadataReadability,
- ObjectSharingReach,
RecordShareAccessLevel,
RecordSharePrincipalType,
RecordShareRowCause,
@@ -660,7 +658,7 @@ describe('createShareWithObjectRecordsPermissions', () => {
});
});
- describe.each([MetadataReadability.SYSTEM, MetadataReadability.PRIVATE])(
+ describe.each([MetadataReadability.PRIVATE])(
'PRIVATE creates with conversation readability %s',
(conversationReadability) => {
let conversationObjectMetadata: ObjectMetadataEntity;
@@ -805,32 +803,6 @@ describe('createShareWithObjectRecordsPermissions', () => {
expectToFail: false,
});
- const setSharingReach = (sharingReach: ObjectSharingReach) =>
- updateOneObjectMetadata({
- expectToFail: false,
- input: {
- idToUpdate: objectMetadataId,
- updatePayload: { sharingReach },
- },
- });
-
- const setMemberObjectAccess = (canAccessObject: boolean) =>
- upsertObjectPermissions({
- expectToFail: false,
- input: {
- roleId: memberRoleId,
- objectPermissions: [
- {
- objectMetadataId,
- canReadObjectRecords: canAccessObject,
- canUpdateObjectRecords: canAccessObject,
- canSoftDeleteObjectRecords: canAccessObject,
- canDestroyObjectRecords: canAccessObject,
- },
- ],
- },
- });
-
beforeAll(async () => {
await setObjectReadability(objectMetadataId, MetadataReadability.OPEN);
await setRecordSharingEnabled(true);
@@ -971,39 +943,5 @@ describe('createShareWithObjectRecordsPermissions', () => {
);
expect(await findRecordShares(recordId)).toEqual([]);
});
-
- it('should refuse a grant the role of its recipient cannot use when sharing stays within roles', async () => {
- const recordId = trackRecordId();
-
- try {
- await setSharingReach(ObjectSharingReach.ROLE_ACCESS);
- await setMemberObjectAccess(false);
-
- const response = await makeGraphqlApiRequest(
- createOneOperation({
- data: { id: recordId, name: 'beyond the role' },
- shareWith: [
- {
- workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
- accessLevel: RecordShareAccessLevel.READ,
- },
- ],
- }),
- );
-
- expect(response.body.errors?.[0]?.extensions?.code).toBe(
- 'BAD_USER_INPUT',
- );
- expect(await findRecordShares(recordId)).toEqual([]);
- expect(
- (await makeGraphqlApiRequest(findManyOperation(recordId))).body.data[
- OBJECT_PLURAL
- ].edges,
- ).toEqual([]);
- } finally {
- await setMemberObjectAccess(true);
- await setSharingReach(ObjectSharingReach.WORKSPACE);
- }
- });
});
});
diff --git a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/disabled-object-permission-actions-object-records-permissions.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/disabled-object-permission-actions-object-records-permissions.integration-spec.ts
new file mode 100644
index 00000000000..98314bfefbc
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/disabled-object-permission-actions-object-records-permissions.integration-spec.ts
@@ -0,0 +1,54 @@
+import { randomUUID } from 'node:crypto';
+
+import { createOneOperationFactory } from 'test/integration/graphql/utils/create-one-operation-factory.util';
+import { makeGraphqlApiRequestWithApiKey } from 'test/integration/graphql/utils/make-graphql-api-request-with-api-key.util';
+import { makeGraphqlApiRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';
+import { getCoreRepository } from 'test/integration/utils/get-core-repository.util';
+import {
+ RecordShareAccessLevel,
+ RecordSharePrincipalType,
+ RecordShareRowCause,
+} from 'twenty-shared/types';
+
+import { ErrorCode } from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
+import { ObjectMetadataEntity } from 'src/engine/metadata-modules/object-metadata/object-metadata.entity';
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+import { PERSON_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/person-data-seeds.constant';
+
+describe('disabled object permission actions', () => {
+ let createRecordShareOperation: ReturnType<typeof createOneOperationFactory>;
+
+ beforeAll(async () => {
+ const personObjectMetadata = await getCoreRepository<ObjectMetadataEntity>(
+ ObjectMetadataEntity,
+ ).findOneOrFail({
+ where: { workspaceId: SEED_APPLE_WORKSPACE_ID, nameSingular: 'person' },
+ });
+
+ createRecordShareOperation = createOneOperationFactory({
+ objectMetadataSingularName: 'recordShare',
+ gqlFields: 'id',
+ data: {
+ recordId: PERSON_DATA_SEED_IDS.ID_1,
+ objectMetadataId: personObjectMetadata.id,
+ principalId: randomUUID(),
+ principalType: RecordSharePrincipalType.WORKSPACE_MEMBER,
+ accessLevel: RecordShareAccessLevel.READ,
+ rowCause: RecordShareRowCause.MANUAL,
+ sourceId: randomUUID(),
+ },
+ });
+ });
+
+ it.each([
+ ['an admin API key', makeGraphqlApiRequestWithApiKey],
+ ['an admin user', makeGraphqlApiRequest],
+ ])('denies %s creating a record share', async (_, makeRequest) => {
+ const response = await makeRequest(createRecordShareOperation);
+
+ expect(response.body.data?.createRecordShare ?? null).toBeNull();
+ expect(response.body.errors?.[0]?.extensions?.code).toBe(
+ ErrorCode.FORBIDDEN,
+ );
+ });
+});
diff --git a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/inherited-readability-object-records-permissions.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/inherited-readability-object-records-permissions.integration-spec.ts
deleted file mode 100644
index fc07afc6f87..00000000000
--- a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/inherited-readability-object-records-permissions.integration-spec.ts
+++ /dev/null
@@ -1,607 +0,0 @@
-/* @license Enterprise */
-
-import { randomUUID } from 'node:crypto';
-
-import { createOneOperationFactory } from 'test/integration/graphql/utils/create-one-operation-factory.util';
-import { deleteOneOperationFactory } from 'test/integration/graphql/utils/delete-one-operation-factory.util';
-import { destroyManyOperationFactory } from 'test/integration/graphql/utils/destroy-many-operation-factory.util';
-import { findManyOperationFactory } from 'test/integration/graphql/utils/find-many-operation-factory.util';
-import { makeGraphqlApiRequestWithMemberRole } from 'test/integration/graphql/utils/make-graphql-api-request-with-member-role.util';
-import { makeGraphqlApiRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';
-import { updateOneOperationFactory } from 'test/integration/graphql/utils/update-one-operation-factory.util';
-import { setObjectReadability } from 'test/integration/metadata/suites/object-metadata/utils/set-object-readability.util';
-import { findOneRoleByLabel } from 'test/integration/metadata/suites/role/utils/find-one-role-by-label.util';
-import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
-import { getCoreRepository } from 'test/integration/utils/get-core-repository.util';
-import {
- MetadataReadability,
- RecordShareAccessLevel,
- RecordSharePrincipalType,
- RecordShareRowCause,
-} from 'twenty-shared/types';
-
-import { ObjectMetadataEntity } from 'src/engine/metadata-modules/object-metadata/object-metadata.entity';
-import { type RecordShareStorageService } from 'src/engine/core-modules/record-share/services/record-share-storage.service';
-import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
-import { WORKSPACE_MEMBER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/workspace-member-data-seeds.constant';
-
-const NOTE_ID = randomUUID();
-const PERSON_ID = randomUUID();
-const NOTE_ATTACHMENT_ID = randomUUID();
-const PERSON_ATTACHMENT_ID = randomUUID();
-const ORPHAN_ATTACHMENT_ID = randomUUID();
-const MEMBER_ATTACHMENT_ID = randomUUID();
-const UNATTACHED_MEMBER_ATTACHMENT_ID = randomUUID();
-const NOTE_TARGET_ID = randomUUID();
-
-const ATTACHMENT_IDS = [
- NOTE_ATTACHMENT_ID,
- PERSON_ATTACHMENT_ID,
- ORPHAN_ATTACHMENT_ID,
- MEMBER_ATTACHMENT_ID,
- UNATTACHED_MEMBER_ATTACHMENT_ID,
-];
-
-const collectIds = (edges: { node: { id: string } }[]): string[] =>
- edges.map((edge) => edge.node.id).sort();
-
-const findAttachmentsOperation = findManyOperationFactory({
- objectMetadataSingularName: 'attachment',
- objectMetadataPluralName: 'attachments',
- gqlFields: 'id',
- filter: { id: { in: ATTACHMENT_IDS } },
-});
-
-const findAttachmentsOrderedByNoteOperation = findManyOperationFactory({
- objectMetadataSingularName: 'attachment',
- objectMetadataPluralName: 'attachments',
- gqlFields: 'id',
- filter: { id: { in: ATTACHMENT_IDS } },
- orderBy: [{ targetNote: { title: 'AscNullsLast' } }],
-});
-
-const findNoteTargetsOperation = findManyOperationFactory({
- objectMetadataSingularName: 'noteTarget',
- objectMetadataPluralName: 'noteTargets',
- gqlFields: 'id',
- filter: { id: { eq: NOTE_TARGET_ID } },
-});
-
-const findNoteWithChildrenOperation = findManyOperationFactory({
- objectMetadataSingularName: 'note',
- objectMetadataPluralName: 'notes',
- gqlFields: `
- id
- attachments {
- edges {
- node {
- id
- }
- }
- }
- noteTargets {
- edges {
- node {
- id
- }
- }
- }
- `,
- filter: { id: { eq: NOTE_ID } },
-});
-
-const destroyRecords = ({
- objectMetadataSingularName,
- objectMetadataPluralName,
- ids,
-}: {
- objectMetadataSingularName: string;
- objectMetadataPluralName: string;
- ids: string[];
-}) =>
- makeGraphqlApiRequest(
- destroyManyOperationFactory({
- objectMetadataSingularName,
- objectMetadataPluralName,
- gqlFields: 'id',
- filter: { id: { in: ids } },
- }),
- );
-
-describe('inheritedReadabilityObjectRecordsPermissions', () => {
- let recordShareStorageService: RecordShareStorageService;
- let noteObjectMetadataId: string;
- let personObjectMetadataId: string;
- let attachmentObjectMetadataId: string;
-
- const sourceId = randomUUID();
-
- beforeAll(async () => {
- recordShareStorageService =
- getAppProviderByClassName<RecordShareStorageService>(
- 'RecordShareStorageService',
- );
-
- const noteObjectMetadata = await getCoreRepository<ObjectMetadataEntity>(
- ObjectMetadataEntity,
- ).findOneOrFail({
- where: { workspaceId: SEED_APPLE_WORKSPACE_ID, nameSingular: 'note' },
- });
-
- noteObjectMetadataId = noteObjectMetadata.id;
-
- const attachmentObjectMetadata =
- await getCoreRepository<ObjectMetadataEntity>(
- ObjectMetadataEntity,
- ).findOneOrFail({
- where: {
- workspaceId: SEED_APPLE_WORKSPACE_ID,
- nameSingular: 'attachment',
- },
- });
-
- attachmentObjectMetadataId = attachmentObjectMetadata.id;
-
- const personObjectMetadata = await getCoreRepository<ObjectMetadataEntity>(
- ObjectMetadataEntity,
- ).findOneOrFail({
- where: { workspaceId: SEED_APPLE_WORKSPACE_ID, nameSingular: 'person' },
- });
-
- personObjectMetadataId = personObjectMetadata.id;
-
- const createRecords = [
- {
- objectMetadataSingularName: 'note',
- data: { id: NOTE_ID, title: 'Inherited readability note' },
- },
- {
- objectMetadataSingularName: 'person',
- data: { id: PERSON_ID, name: { firstName: 'Inherited' } },
- },
- {
- objectMetadataSingularName: 'attachment',
- data: {
- id: NOTE_ATTACHMENT_ID,
- name: 'note-attachment.pdf',
- targetNoteId: NOTE_ID,
- },
- },
- {
- objectMetadataSingularName: 'attachment',
- data: {
- id: PERSON_ATTACHMENT_ID,
- name: 'person-attachment.pdf',
- targetPersonId: PERSON_ID,
- },
- },
- {
- objectMetadataSingularName: 'attachment',
- data: { id: ORPHAN_ATTACHMENT_ID, name: 'orphan-attachment.pdf' },
- },
- {
- objectMetadataSingularName: 'noteTarget',
- data: {
- id: NOTE_TARGET_ID,
- noteId: NOTE_ID,
- targetPersonId: PERSON_ID,
- },
- },
- ];
-
- for (const { objectMetadataSingularName, data } of createRecords) {
- const response = await makeGraphqlApiRequest(
- createOneOperationFactory({
- objectMetadataSingularName,
- gqlFields: 'id',
- data,
- }),
- );
-
- expect(response.body.errors).toBeUndefined();
- }
-
- await setObjectReadability(
- noteObjectMetadataId,
- MetadataReadability.PRIVATE,
- );
- });
-
- afterAll(async () => {
- await recordShareStorageService.deleteBySourceId({
- workspaceId: SEED_APPLE_WORKSPACE_ID,
- sourceId,
- });
- await recordShareStorageService.deleteByRecordIds({
- workspaceId: SEED_APPLE_WORKSPACE_ID,
- objectMetadataId: attachmentObjectMetadataId,
- recordIds: ATTACHMENT_IDS,
- });
- await setObjectReadability(
- noteObjectMetadataId,
- MetadataReadability.INHERITED,
- );
- await destroyRecords({
- objectMetadataSingularName: 'attachment',
- objectMetadataPluralName: 'attachments',
- ids: ATTACHMENT_IDS,
- });
- await destroyRecords({
- objectMetadataSingularName: 'noteTarget',
- objectMetadataPluralName: 'noteTargets',
- ids: [NOTE_TARGET_ID],
- });
- await destroyRecords({
- objectMetadataSingularName: 'note',
- objectMetadataPluralName: 'notes',
- ids: [NOTE_ID],
- });
- await destroyRecords({
- objectMetadataSingularName: 'person',
- objectMetadataPluralName: 'people',
- ids: [PERSON_ID],
- });
- });
-
- describe('without a share row on the note', () => {
- it('should hide the attachment hanging off the note and keep the note target that points at the open person', async () => {
- const attachmentsResponse = await makeGraphqlApiRequestWithMemberRole(
- findAttachmentsOperation,
- );
- const noteTargetsResponse = await makeGraphqlApiRequestWithMemberRole(
- findNoteTargetsOperation,
- );
-
- expect(attachmentsResponse.body.errors).toBeUndefined();
- expect(
- collectIds(attachmentsResponse.body.data.attachments.edges),
- ).toEqual([PERSON_ATTACHMENT_ID]);
- expect(noteTargetsResponse.body.errors).toBeUndefined();
- expect(
- collectIds(noteTargetsResponse.body.data.noteTargets.edges),
- ).toEqual([NOTE_TARGET_ID]);
- });
-
- it('should keep the attachment hidden when ordering through its note', async () => {
- const response = await makeGraphqlApiRequestWithMemberRole(
- findAttachmentsOrderedByNoteOperation,
- );
-
- expect(response.body.errors).toBeUndefined();
- expect(collectIds(response.body.data.attachments.edges)).toEqual([
- PERSON_ATTACHMENT_ID,
- ]);
- });
-
- it('should hide the note itself and with it its nested children', async () => {
- const response = await makeGraphqlApiRequestWithMemberRole(
- findNoteWithChildrenOperation,
- );
-
- expect(response.body.errors).toBeUndefined();
- expect(response.body.data.notes.edges).toHaveLength(0);
- });
- });
-
- describe('with a READ share row on the note', () => {
- beforeAll(async () => {
- await recordShareStorageService.insertMany({
- workspaceId: SEED_APPLE_WORKSPACE_ID,
- recordShares: [
- {
- recordId: NOTE_ID,
- objectMetadataId: noteObjectMetadataId,
- principalId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
- principalType: RecordSharePrincipalType.WORKSPACE_MEMBER,
- accessLevel: RecordShareAccessLevel.READ,
- rowCause: RecordShareRowCause.MANUAL,
- sourceId,
- },
- ],
- });
- });
-
- it('should show the attachment and the note target hanging off the note and keep the orphan hidden', async () => {
- const attachmentsResponse = await makeGraphqlApiRequestWithMemberRole(
- findAttachmentsOperation,
- );
- const orderedAttachmentsResponse =
- await makeGraphqlApiRequestWithMemberRole(
- findAttachmentsOrderedByNoteOperation,
- );
- const noteTargetsResponse = await makeGraphqlApiRequestWithMemberRole(
- findNoteTargetsOperation,
- );
-
- expect(attachmentsResponse.body.errors).toBeUndefined();
- expect(
- collectIds(attachmentsResponse.body.data.attachments.edges),
- ).toEqual([NOTE_ATTACHMENT_ID, PERSON_ATTACHMENT_ID].sort());
- expect(orderedAttachmentsResponse.body.errors).toBeUndefined();
- expect(
- collectIds(orderedAttachmentsResponse.body.data.attachments.edges),
- ).toEqual([NOTE_ATTACHMENT_ID, PERSON_ATTACHMENT_ID].sort());
- expect(noteTargetsResponse.body.errors).toBeUndefined();
- expect(
- collectIds(noteTargetsResponse.body.data.noteTargets.edges),
- ).toEqual([NOTE_TARGET_ID]);
- });
-
- it('should show the note with its nested attachment and note target', async () => {
- const response = await makeGraphqlApiRequestWithMemberRole(
- findNoteWithChildrenOperation,
- );
-
- expect(response.body.errors).toBeUndefined();
- expect(response.body.data.notes.edges).toHaveLength(1);
-
- const note = response.body.data.notes.edges[0].node;
-
- expect(note.id).toBe(NOTE_ID);
- expect(collectIds(note.attachments.edges)).toEqual([NOTE_ATTACHMENT_ID]);
- expect(collectIds(note.noteTargets.edges)).toEqual([NOTE_TARGET_ID]);
- });
-
- it('should show the orphan attachment once it is shared with the member itself', async () => {
- await recordShareStorageService.insertMany({
- workspaceId: SEED_APPLE_WORKSPACE_ID,
- recordShares: [
- {
- recordId: ORPHAN_ATTACHMENT_ID,
- objectMetadataId: attachmentObjectMetadataId,
- principalId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
- principalType: RecordSharePrincipalType.WORKSPACE_MEMBER,
- accessLevel: RecordShareAccessLevel.READ,
- rowCause: RecordShareRowCause.MANUAL,
- sourceId,
- },
- ],
- });
-
- const response = await makeGraphqlApiRequestWithMemberRole(
- findAttachmentsOperation,
- );
-
- expect(response.body.errors).toBeUndefined();
- expect(collectIds(response.body.data.attachments.edges)).toEqual(
- [NOTE_ATTACHMENT_ID, PERSON_ATTACHMENT_ID, ORPHAN_ATTACHMENT_ID].sort(),
- );
- });
-
- it('should refuse to update or delete the attachment with READ access on the note', async () => {
- const updateResponse = await makeGraphqlApiRequestWithMemberRole(
- updateOneOperationFactory({
- objectMetadataSingularName: 'attachment',
- gqlFields: 'id name',
- recordId: NOTE_ATTACHMENT_ID,
- data: { name: 'renamed-by-member.pdf' },
- }),
- );
- const deleteResponse = await makeGraphqlApiRequestWithMemberRole(
- deleteOneOperationFactory({
- objectMetadataSingularName: 'attachment',
- gqlFields: 'id',
- recordId: NOTE_ATTACHMENT_ID,
- }),
- );
-
- expect(updateResponse.body.data?.updateAttachment ?? null).toBeNull();
- expect(updateResponse.body.errors).toBeDefined();
- expect(deleteResponse.body.data?.deleteAttachment ?? null).toBeNull();
- expect(deleteResponse.body.errors).toBeDefined();
- });
-
- it('should refuse to attach a new or an existing attachment to the note with READ access on it', async () => {
- const createResponse = await makeGraphqlApiRequestWithMemberRole(
- createOneOperationFactory({
- objectMetadataSingularName: 'attachment',
- gqlFields: 'id',
- data: {
- id: MEMBER_ATTACHMENT_ID,
- name: 'member-attachment.pdf',
- targetNoteId: NOTE_ID,
- },
- }),
- );
- const moveResponse = await makeGraphqlApiRequestWithMemberRole(
- updateOneOperationFactory({
- objectMetadataSingularName: 'attachment',
- gqlFields: 'id',
- recordId: PERSON_ATTACHMENT_ID,
- data: { targetPersonId: null, targetNoteId: NOTE_ID },
- }),
- );
-
- expect(createResponse.body.data?.createAttachment ?? null).toBeNull();
- expect(createResponse.body.errors[0].message).toContain('not writable');
- expect(moveResponse.body.data?.updateAttachment ?? null).toBeNull();
- expect(moveResponse.body.errors[0].message).toContain('not writable');
- });
- });
-
- describe('with a READ_WRITE share row on the note for the member role', () => {
- beforeAll(async () => {
- const memberRole = await findOneRoleByLabel({ label: 'Member' });
-
- await recordShareStorageService.insertMany({
- workspaceId: SEED_APPLE_WORKSPACE_ID,
- recordShares: [
- {
- recordId: NOTE_ID,
- objectMetadataId: noteObjectMetadataId,
- principalId: memberRole.id,
- principalType: RecordSharePrincipalType.ROLE,
- accessLevel: RecordShareAccessLevel.READ_WRITE,
- rowCause: RecordShareRowCause.MANUAL,
- sourceId,
- },
- ],
- });
- });
-
- it('should update the attachment hanging off the note', async () => {
- const response = await makeGraphqlApiRequestWithMemberRole(
- updateOneOperationFactory({
- objectMetadataSingularName: 'attachment',
- gqlFields: 'id name',
- recordId: NOTE_ATTACHMENT_ID,
- data: { name: 'renamed-by-member.pdf' },
- }),
- );
-
- expect(response.body.errors).toBeUndefined();
- expect(response.body.data.updateAttachment).toEqual({
- id: NOTE_ATTACHMENT_ID,
- name: 'renamed-by-member.pdf',
- });
- });
-
- it('should attach a new and an existing attachment to the note', async () => {
- const createResponse = await makeGraphqlApiRequestWithMemberRole(
- createOneOperationFactory({
- objectMetadataSingularName: 'attachment',
- gqlFields: 'id',
- data: {
- id: MEMBER_ATTACHMENT_ID,
- name: 'member-attachment.pdf',
- targetNoteId: NOTE_ID,
- },
- }),
- );
- const moveResponse = await makeGraphqlApiRequestWithMemberRole(
- updateOneOperationFactory({
- objectMetadataSingularName: 'attachment',
- gqlFields: 'id',
- recordId: PERSON_ATTACHMENT_ID,
- data: { targetPersonId: null, targetNoteId: NOTE_ID },
- }),
- );
-
- expect(createResponse.body.errors).toBeUndefined();
- expect(createResponse.body.data.createAttachment.id).toBe(
- MEMBER_ATTACHMENT_ID,
- );
- expect(moveResponse.body.errors).toBeUndefined();
- expect(moveResponse.body.data.updateAttachment.id).toBe(
- PERSON_ATTACHMENT_ID,
- );
- });
-
- it('should let the member read back an attachment created without any parent', async () => {
- const createResponse = await makeGraphqlApiRequestWithMemberRole(
- createOneOperationFactory({
- objectMetadataSingularName: 'attachment',
- gqlFields: 'id',
- data: {
- id: UNATTACHED_MEMBER_ATTACHMENT_ID,
- name: 'unattached-member-attachment.pdf',
- },
- }),
- );
- const findResponse = await makeGraphqlApiRequestWithMemberRole(
- findManyOperationFactory({
- objectMetadataSingularName: 'attachment',
- objectMetadataPluralName: 'attachments',
- gqlFields: 'id',
- filter: { id: { eq: UNATTACHED_MEMBER_ATTACHMENT_ID } },
- }),
- );
-
- expect(createResponse.body.errors).toBeUndefined();
- expect(findResponse.body.errors).toBeUndefined();
- expect(collectIds(findResponse.body.data.attachments.edges)).toEqual([
- UNATTACHED_MEMBER_ATTACHMENT_ID,
- ]);
- });
- });
-
- describe('once every share row on the note is gone', () => {
- beforeAll(async () => {
- await recordShareStorageService.deleteBySourceId({
- workspaceId: SEED_APPLE_WORKSPACE_ID,
- sourceId,
- });
- });
-
- it('should keep showing the member the attachments they created and hide the others', async () => {
- const response = await makeGraphqlApiRequestWithMemberRole(
- findAttachmentsOperation,
- );
-
- expect(response.body.errors).toBeUndefined();
- expect(collectIds(response.body.data.attachments.edges)).toEqual(
- [MEMBER_ATTACHMENT_ID, UNATTACHED_MEMBER_ATTACHMENT_ID].sort(),
- );
- });
-
- it('should let the member update the attachment they created under the note', async () => {
- const response = await makeGraphqlApiRequestWithMemberRole(
- updateOneOperationFactory({
- objectMetadataSingularName: 'attachment',
- gqlFields: 'id name',
- recordId: MEMBER_ATTACHMENT_ID,
- data: { name: 'renamed-by-owner.pdf' },
- }),
- );
-
- expect(response.body.errors).toBeUndefined();
- expect(response.body.data.updateAttachment).toEqual({
- id: MEMBER_ATTACHMENT_ID,
- name: 'renamed-by-owner.pdf',
- });
- });
- });
-
- describe('INHERITED readability without any parent field', () => {
- beforeAll(async () => {
- await setObjectReadability(
- personObjectMetadataId,
- MetadataReadability.INHERITED,
- );
- });
-
- afterAll(async () => {
- await setObjectReadability(
- personObjectMetadataId,
- MetadataReadability.OPEN,
- );
- });
-
- it('should gate reads through share rows on the record itself', async () => {
- const findPersonOperation = findManyOperationFactory({
- objectMetadataSingularName: 'person',
- objectMetadataPluralName: 'people',
- gqlFields: 'id',
- filter: { id: { eq: PERSON_ID } },
- });
-
- const unsharedResponse =
- await makeGraphqlApiRequestWithMemberRole(findPersonOperation);
-
- await recordShareStorageService.insertMany({
- workspaceId: SEED_APPLE_WORKSPACE_ID,
- recordShares: [
- {
- recordId: PERSON_ID,
- objectMetadataId: personObjectMetadataId,
- principalId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
- principalType: RecordSharePrincipalType.WORKSPACE_MEMBER,
- accessLevel: RecordShareAccessLevel.READ,
- rowCause: RecordShareRowCause.MANUAL,
- sourceId,
- },
- ],
- });
-
- const sharedResponse =
- await makeGraphqlApiRequestWithMemberRole(findPersonOperation);
-
- expect(unsharedResponse.body.errors).toBeUndefined();
- expect(unsharedResponse.body.data.people.edges).toHaveLength(0);
- expect(sharedResponse.body.errors).toBeUndefined();
- expect(collectIds(sharedResponse.body.data.people.edges)).toEqual([
- PERSON_ID,
- ]);
- });
- });
-});
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.ts
deleted file mode 100644
index d57e1f1c7f5..00000000000
--- a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/inherited-through-children-readability-object-records-permissions.integration-spec.ts
+++ /dev/null
@@ -1,947 +0,0 @@
-/* @license Enterprise */
-
-import { randomUUID } from 'node:crypto';
-
-import { EVERYONE_PRINCIPAL_ID } from 'twenty-shared/constants';
-import {
- type ObjectRecordDeleteEvent,
- type ObjectRecordEvent,
-} from 'twenty-shared/database-events';
-
-import { createOneOperationFactory } from 'test/integration/graphql/utils/create-one-operation-factory.util';
-import { deleteManyOperationFactory } from 'test/integration/graphql/utils/delete-many-operation-factory.util';
-import { destroyManyOperationFactory } from 'test/integration/graphql/utils/destroy-many-operation-factory.util';
-import { findManyOperationFactory } from 'test/integration/graphql/utils/find-many-operation-factory.util';
-import { makeGraphqlApiRequestWithMemberRole } from 'test/integration/graphql/utils/make-graphql-api-request-with-member-role.util';
-import { makeGraphqlApiRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';
-import { restoreManyOperationFactory } from 'test/integration/graphql/utils/restore-many-operation-factory.util';
-import { updateOneOperationFactory } from 'test/integration/graphql/utils/update-one-operation-factory.util';
-import { setObjectReadability } from 'test/integration/metadata/suites/object-metadata/utils/set-object-readability.util';
-import { upsertObjectPermissions } from 'test/integration/metadata/suites/object-permission/utils/upsert-object-permissions.util';
-import { findOneRoleByLabel } from 'test/integration/metadata/suites/role/utils/find-one-role-by-label.util';
-import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
-import { getCoreRepository } from 'test/integration/utils/get-core-repository.util';
-import {
- MetadataReadability,
- RecordShareAccessLevel,
- RecordSharePrincipalType,
- RecordShareRowCause,
-} from 'twenty-shared/types';
-
-import { findFlatEntityByIdInFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-id-in-flat-entity-maps.util';
-import { ObjectMetadataEntity } from 'src/engine/metadata-modules/object-metadata/object-metadata.entity';
-import { type RecordAccessPolicyService } from 'src/engine/core-modules/record-share/services/record-access-policy.service';
-import { type RecordShareStorageService } from 'src/engine/core-modules/record-share/services/record-share-storage.service';
-import { type WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
-import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
-import { WORKSPACE_MEMBER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/workspace-member-data-seeds.constant';
-
-const PERSON_ID = randomUUID();
-const COMPANY_ID = randomUUID();
-const NOTE_ON_PERSON_ID = randomUUID();
-const NOTE_ON_COMPANY_ID = randomUUID();
-const NOTE_ON_BOTH_ID = randomUUID();
-const NOTE_ALONE_ID = randomUUID();
-const MEMBER_NOTE_ID = randomUUID();
-const PERSON_NOTE_TARGET_ID = randomUUID();
-const COMPANY_NOTE_TARGET_ID = randomUUID();
-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 = [
- NOTE_ON_PERSON_ID,
- NOTE_ON_COMPANY_ID,
- NOTE_ON_BOTH_ID,
- NOTE_ALONE_ID,
- MEMBER_NOTE_ID,
-];
-const NOTE_TARGET_IDS = [
- PERSON_NOTE_TARGET_ID,
- COMPANY_NOTE_TARGET_ID,
- BOTH_PERSON_NOTE_TARGET_ID,
- BOTH_COMPANY_NOTE_TARGET_ID,
- 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();
-
-const findNotesOperation = findManyOperationFactory({
- objectMetadataSingularName: 'note',
- objectMetadataPluralName: 'notes',
- gqlFields: `
- id
- noteTargets {
- edges {
- node {
- id
- }
- }
- }
- `,
- filter: { id: { in: NOTE_IDS } },
-});
-
-const findNoteTargetsOperation = findManyOperationFactory({
- objectMetadataSingularName: 'noteTarget',
- objectMetadataPluralName: 'noteTargets',
- gqlFields: 'id',
- 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',
- gqlFields: 'id',
- filter: { id: { in: ATTACHMENT_IDS } },
-});
-
-const renameNoteOperation = (noteId: string, title: string) =>
- updateOneOperationFactory({
- objectMetadataSingularName: 'note',
- gqlFields: 'id title',
- recordId: noteId,
- data: { title },
- });
-
-const attachNoteToCompanyOperation = createOneOperationFactory({
- objectMetadataSingularName: 'noteTarget',
- gqlFields: 'id',
- data: {
- id: MEMBER_NOTE_TARGET_ID,
- noteId: NOTE_ON_PERSON_ID,
- targetCompanyId: COMPANY_ID,
- },
-});
-
-const detachNoteOnBothFromCompanyOperation = deleteManyOperationFactory({
- objectMetadataSingularName: 'noteTarget',
- objectMetadataPluralName: 'noteTargets',
- gqlFields: 'id',
- filter: { id: { eq: BOTH_COMPANY_NOTE_TARGET_ID } },
-});
-
-const reattachNoteOnBothToCompanyOperation = restoreManyOperationFactory({
- objectMetadataSingularName: 'noteTarget',
- objectMetadataPluralName: 'noteTargets',
- gqlFields: 'id',
- filter: { id: { eq: BOTH_COMPANY_NOTE_TARGET_ID } },
-});
-
-const destroyRecords = ({
- objectMetadataSingularName,
- objectMetadataPluralName,
- ids,
-}: {
- objectMetadataSingularName: string;
- objectMetadataPluralName: string;
- ids: string[];
-}) =>
- makeGraphqlApiRequest(
- destroyManyOperationFactory({
- objectMetadataSingularName,
- objectMetadataPluralName,
- gqlFields: 'id',
- filter: { id: { in: ids } },
- }),
- );
-
-describe('inheritedThroughChildrenReadabilityObjectRecordsPermissions', () => {
- let recordShareStorageService: RecordShareStorageService;
- let personObjectMetadataId: string;
- let noteObjectMetadataId: string;
- let taskObjectMetadataId: string;
-
- const sourceId = randomUUID();
-
- beforeAll(async () => {
- recordShareStorageService =
- getAppProviderByClassName<RecordShareStorageService>(
- 'RecordShareStorageService',
- );
-
- const objectMetadataRepository =
- getCoreRepository<ObjectMetadataEntity>(ObjectMetadataEntity);
-
- personObjectMetadataId = (
- await objectMetadataRepository.findOneOrFail({
- where: { workspaceId: SEED_APPLE_WORKSPACE_ID, nameSingular: 'person' },
- })
- ).id;
- noteObjectMetadataId = (
- await objectMetadataRepository.findOneOrFail({
- where: { workspaceId: SEED_APPLE_WORKSPACE_ID, nameSingular: 'note' },
- })
- ).id;
- taskObjectMetadataId = (
- await objectMetadataRepository.findOneOrFail({
- where: { workspaceId: SEED_APPLE_WORKSPACE_ID, nameSingular: 'task' },
- })
- ).id;
-
- const createRecords = [
- {
- objectMetadataSingularName: 'person',
- data: { id: PERSON_ID, name: { firstName: 'Private' } },
- },
- {
- objectMetadataSingularName: 'company',
- data: { id: COMPANY_ID, name: 'Open company' },
- },
- {
- objectMetadataSingularName: 'note',
- data: { id: NOTE_ON_PERSON_ID, title: 'On the private person' },
- },
- {
- objectMetadataSingularName: 'note',
- data: { id: NOTE_ON_COMPANY_ID, title: 'On the open company' },
- },
- {
- objectMetadataSingularName: 'note',
- data: { id: NOTE_ON_BOTH_ID, title: 'On both' },
- },
- {
- objectMetadataSingularName: 'note',
- data: { id: NOTE_ALONE_ID, title: 'Attached to nothing' },
- },
- {
- objectMetadataSingularName: 'noteTarget',
- data: {
- id: PERSON_NOTE_TARGET_ID,
- noteId: NOTE_ON_PERSON_ID,
- targetPersonId: PERSON_ID,
- },
- },
- {
- objectMetadataSingularName: 'noteTarget',
- data: {
- id: COMPANY_NOTE_TARGET_ID,
- noteId: NOTE_ON_COMPANY_ID,
- targetCompanyId: COMPANY_ID,
- },
- },
- {
- objectMetadataSingularName: 'noteTarget',
- data: {
- id: BOTH_PERSON_NOTE_TARGET_ID,
- noteId: NOTE_ON_BOTH_ID,
- targetPersonId: PERSON_ID,
- },
- },
- {
- objectMetadataSingularName: 'noteTarget',
- data: {
- id: BOTH_COMPANY_NOTE_TARGET_ID,
- noteId: NOTE_ON_BOTH_ID,
- 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: {
- id: COMPANY_NOTE_ATTACHMENT_ID,
- name: 'company-note-attachment.pdf',
- targetNoteId: NOTE_ON_COMPANY_ID,
- },
- },
- {
- objectMetadataSingularName: 'attachment',
- data: {
- id: PERSON_NOTE_ATTACHMENT_ID,
- name: 'person-note-attachment.pdf',
- targetNoteId: NOTE_ON_PERSON_ID,
- },
- },
- ];
-
- for (const { objectMetadataSingularName, data } of createRecords) {
- const response = await makeGraphqlApiRequest(
- createOneOperationFactory({
- objectMetadataSingularName,
- gqlFields: 'id',
- data,
- }),
- );
-
- expect(response.body.errors).toBeUndefined();
- }
-
- await setObjectReadability(
- personObjectMetadataId,
- MetadataReadability.PRIVATE,
- );
- });
-
- afterAll(async () => {
- await recordShareStorageService.deleteBySourceId({
- workspaceId: SEED_APPLE_WORKSPACE_ID,
- sourceId,
- });
- await recordShareStorageService.deleteByRecordIds({
- workspaceId: SEED_APPLE_WORKSPACE_ID,
- objectMetadataId: noteObjectMetadataId,
- recordIds: NOTE_IDS,
- });
- await recordShareStorageService.deleteByRecordIds({
- workspaceId: SEED_APPLE_WORKSPACE_ID,
- objectMetadataId: taskObjectMetadataId,
- recordIds: TASK_IDS,
- });
- await setObjectReadability(
- personObjectMetadataId,
- MetadataReadability.OPEN,
- );
- await destroyRecords({
- objectMetadataSingularName: 'attachment',
- objectMetadataPluralName: 'attachments',
- ids: ATTACHMENT_IDS,
- });
- await destroyRecords({
- objectMetadataSingularName: 'noteTarget',
- objectMetadataPluralName: 'noteTargets',
- ids: NOTE_TARGET_IDS,
- });
- await destroyRecords({
- objectMetadataSingularName: 'note',
- 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',
- ids: [PERSON_ID],
- });
- await destroyRecords({
- objectMetadataSingularName: 'company',
- objectMetadataPluralName: 'companies',
- ids: [COMPANY_ID],
- });
- });
-
- describe('without a share row on the person', () => {
- 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(
- findNoteTargetsOperation,
- );
- const attachmentsResponse = await makeGraphqlApiRequestWithMemberRole(
- findAttachmentsOperation,
- );
-
- expect(notesResponse.body.errors).toBeUndefined();
- expect(collectIds(notesResponse.body.data.notes.edges)).toEqual(
- [NOTE_ON_COMPANY_ID, NOTE_ON_BOTH_ID, NOTE_ALONE_ID].sort(),
- );
-
- const noteOnBoth = notesResponse.body.data.notes.edges.find(
- (edge: { node: { id: string } }) => edge.node.id === NOTE_ON_BOTH_ID,
- ).node;
-
- expect(collectIds(noteOnBoth.noteTargets.edges)).toEqual([
- BOTH_COMPANY_NOTE_TARGET_ID,
- ]);
- expect(noteTargetsResponse.body.errors).toBeUndefined();
- expect(
- collectIds(noteTargetsResponse.body.data.noteTargets.edges),
- ).toEqual([COMPANY_NOTE_TARGET_ID, BOTH_COMPANY_NOTE_TARGET_ID].sort());
- expect(attachmentsResponse.body.errors).toBeUndefined();
- expect(
- collectIds(attachmentsResponse.body.data.attachments.edges),
- ).toEqual([COMPANY_NOTE_ATTACHMENT_ID]);
- });
-
- 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,
- ],
- canAccessAllRecords: false,
- 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'),
- );
-
- expect(companyNoteResponse.body.errors).toBeUndefined();
- expect(companyNoteResponse.body.data.updateNote).toEqual({
- 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();
- });
-
- it('should refuse to attach the note on the private person to the open company', async () => {
- const response = await makeGraphqlApiRequestWithMemberRole(
- attachNoteToCompanyOperation,
- );
-
- expect(response.body.data?.createNoteTarget ?? null).toBeNull();
- expect(response.body.errors).toBeDefined();
- expect(response.body.errors[0].message).toContain('not writable');
- });
-
- it('should refuse to restore a detached target of a note the member cannot write', async () => {
- const detachResponse = await makeGraphqlApiRequest(
- detachNoteOnBothFromCompanyOperation,
- );
-
- expect(detachResponse.body.errors).toBeUndefined();
-
- const restoreResponse = await makeGraphqlApiRequestWithMemberRole(
- reattachNoteOnBothToCompanyOperation,
- );
-
- expect(restoreResponse.body.data?.restoreNoteTargets ?? null).toBeNull();
- expect(restoreResponse.body.errors).toBeDefined();
- expect(restoreResponse.body.errors[0].message).toContain('not writable');
-
- const reattachResponse = await makeGraphqlApiRequest(
- reattachNoteOnBothToCompanyOperation,
- );
-
- expect(reattachResponse.body.errors).toBeUndefined();
- });
-
- 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', () => {
- beforeAll(async () => {
- await recordShareStorageService.insertMany({
- workspaceId: SEED_APPLE_WORKSPACE_ID,
- recordShares: [
- {
- recordId: PERSON_ID,
- objectMetadataId: personObjectMetadataId,
- principalId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
- principalType: RecordSharePrincipalType.WORKSPACE_MEMBER,
- accessLevel: RecordShareAccessLevel.READ,
- rowCause: RecordShareRowCause.MANUAL,
- sourceId,
- },
- ],
- });
- });
-
- it('should show every note, target and attachment', async () => {
- const notesResponse =
- await makeGraphqlApiRequestWithMemberRole(findNotesOperation);
- const noteTargetsResponse = await makeGraphqlApiRequestWithMemberRole(
- findNoteTargetsOperation,
- );
- const attachmentsResponse = await makeGraphqlApiRequestWithMemberRole(
- findAttachmentsOperation,
- );
-
- 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,
- NOTE_ALONE_ID,
- ].sort(),
- );
- expect(noteTargetsResponse.body.errors).toBeUndefined();
- expect(
- collectIds(noteTargetsResponse.body.data.noteTargets.edges),
- ).toEqual(
- [
- PERSON_NOTE_TARGET_ID,
- COMPANY_NOTE_TARGET_ID,
- BOTH_PERSON_NOTE_TARGET_ID,
- BOTH_COMPANY_NOTE_TARGET_ID,
- ].sort(),
- );
- expect(attachmentsResponse.body.errors).toBeUndefined();
- expect(
- collectIds(attachmentsResponse.body.data.attachments.edges),
- ).toEqual(ATTACHMENT_IDS.sort());
- });
-
- it('should let the event gate see the same notes as the query gate', async () => {
- const memberRole = await findOneRoleByLabel({ label: 'Member' });
- const { rolesPermissions, flatObjectMetadataMaps } =
- await getAppProviderByClassName<WorkspaceCacheService>(
- 'WorkspaceCacheService',
- ).getOrRecompute(SEED_APPLE_WORKSPACE_ID, [
- 'rolesPermissions',
- 'flatObjectMetadataMaps',
- ]);
- const noteObjectMetadata = findFlatEntityByIdInFlatEntityMaps({
- flatEntityId: noteObjectMetadataId,
- flatEntityMaps: flatObjectMetadataMaps,
- });
-
- expect(noteObjectMetadata).toBeDefined();
-
- const recordIdsAdmittedByEventGate =
- await getAppProviderByClassName<RecordAccessPolicyService>(
- 'RecordAccessPolicyService',
- )
- .buildEventRecordAccessGate({
- name: 'note.created',
- workspaceId: SEED_APPLE_WORKSPACE_ID,
- objectMetadata: noteObjectMetadata!,
- events: NOTE_IDS.filter((id) => id !== MEMBER_NOTE_ID).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,
- ],
- canAccessAllRecords: false,
- isOwningApplication: () => false,
- resolveRowLevelPermissionRecordFilter: () => null,
- });
- const notesResponse =
- await makeGraphqlApiRequestWithMemberRole(findNotesOperation);
-
- expect([...recordIdsAdmittedByEventGate].sort()).toEqual(
- collectIds(notesResponse.body.data.notes.edges),
- );
- });
-
- it('should hide what is reached through the person from a role that cannot read people', async () => {
- const memberRole = await findOneRoleByLabel({ label: 'Member' });
- const setMemberCanReadPeople = (canReadObjectRecords: boolean) =>
- upsertObjectPermissions({
- expectToFail: false,
- input: {
- roleId: memberRole.id,
- objectPermissions: [
- {
- objectMetadataId: personObjectMetadataId,
- canReadObjectRecords,
- canUpdateObjectRecords: canReadObjectRecords,
- canSoftDeleteObjectRecords: canReadObjectRecords,
- canDestroyObjectRecords: canReadObjectRecords,
- },
- ],
- },
- });
-
- await setMemberCanReadPeople(false);
-
- const notesResponse =
- await makeGraphqlApiRequestWithMemberRole(findNotesOperation);
- const noteTargetsResponse = await makeGraphqlApiRequestWithMemberRole(
- findNoteTargetsOperation,
- );
- const attachmentsResponse = await makeGraphqlApiRequestWithMemberRole(
- findAttachmentsOperation,
- );
-
- await setMemberCanReadPeople(true);
-
- expect(notesResponse.body.errors).toBeUndefined();
- expect(collectIds(notesResponse.body.data.notes.edges)).toEqual(
- [NOTE_ON_COMPANY_ID, NOTE_ON_BOTH_ID, NOTE_ALONE_ID].sort(),
- );
- expect(noteTargetsResponse.body.errors).toBeUndefined();
- expect(
- collectIds(noteTargetsResponse.body.data.noteTargets.edges),
- ).toEqual([COMPANY_NOTE_TARGET_ID, BOTH_COMPANY_NOTE_TARGET_ID].sort());
- expect(attachmentsResponse.body.errors).toBeUndefined();
- expect(
- collectIds(attachmentsResponse.body.data.attachments.edges),
- ).toEqual([COMPANY_NOTE_ATTACHMENT_ID]);
- });
-
- it('should still refuse to rename the note on the private person or attach it elsewhere', async () => {
- const renameResponse = await makeGraphqlApiRequestWithMemberRole(
- renameNoteOperation(NOTE_ON_PERSON_ID, 'Renamed with READ'),
- );
- const attachResponse = await makeGraphqlApiRequestWithMemberRole(
- attachNoteToCompanyOperation,
- );
-
- expect(renameResponse.body.data?.updateNote ?? null).toBeNull();
- expect(renameResponse.body.errors).toBeDefined();
- expect(attachResponse.body.data?.createNoteTarget ?? null).toBeNull();
- expect(attachResponse.body.errors).toBeDefined();
- });
- });
-
- describe('with a READ_WRITE share row on the person for the member role', () => {
- beforeAll(async () => {
- const memberRole = await findOneRoleByLabel({ label: 'Member' });
-
- await recordShareStorageService.insertMany({
- workspaceId: SEED_APPLE_WORKSPACE_ID,
- recordShares: [
- {
- recordId: PERSON_ID,
- objectMetadataId: personObjectMetadataId,
- principalId: memberRole.id,
- principalType: RecordSharePrincipalType.ROLE,
- accessLevel: RecordShareAccessLevel.READ_WRITE,
- rowCause: RecordShareRowCause.MANUAL,
- sourceId,
- },
- ],
- });
- });
-
- it('should let the member rename the note on the private person and attach it to the open company', async () => {
- const renameResponse = await makeGraphqlApiRequestWithMemberRole(
- renameNoteOperation(NOTE_ON_PERSON_ID, 'Renamed with READ_WRITE'),
- );
- const attachResponse = await makeGraphqlApiRequestWithMemberRole(
- attachNoteToCompanyOperation,
- );
-
- expect(renameResponse.body.errors).toBeUndefined();
- expect(renameResponse.body.data.updateNote).toEqual({
- id: NOTE_ON_PERSON_ID,
- title: 'Renamed with READ_WRITE',
- });
- expect(attachResponse.body.errors).toBeUndefined();
- expect(attachResponse.body.data.createNoteTarget.id).toBe(
- MEMBER_NOTE_TARGET_ID,
- );
- });
-
- it('should let the member read back a note they created before attaching it anywhere', async () => {
- const createResponse = await makeGraphqlApiRequestWithMemberRole(
- createOneOperationFactory({
- objectMetadataSingularName: 'note',
- gqlFields: 'id',
- data: { id: MEMBER_NOTE_ID, title: 'Created by the member' },
- }),
- );
- const notesResponse =
- await makeGraphqlApiRequestWithMemberRole(findNotesOperation);
-
- expect(createResponse.body.errors).toBeUndefined();
- 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,
- NOTE_ALONE_ID,
- MEMBER_NOTE_ID,
- ].sort(),
- );
- });
-
- it('should keep a deleted note readable through the links captured with its deletion', async () => {
- const memberRole = await findOneRoleByLabel({ label: 'Member' });
- const { rolesPermissions, flatObjectMetadataMaps } =
- await getAppProviderByClassName<WorkspaceCacheService>(
- 'WorkspaceCacheService',
- ).getOrRecompute(SEED_APPLE_WORKSPACE_ID, [
- 'rolesPermissions',
- 'flatObjectMetadataMaps',
- ]);
- const noteObjectMetadata = findFlatEntityByIdInFlatEntityMaps({
- flatEntityId: noteObjectMetadataId,
- flatEntityMaps: flatObjectMetadataMaps,
- });
- const resolveReadableNoteIds = (events: ObjectRecordEvent[]) =>
- getAppProviderByClassName<RecordAccessPolicyService>(
- 'RecordAccessPolicyService',
- )
- .buildEventRecordAccessGate({
- name: 'note.deleted',
- workspaceId: SEED_APPLE_WORKSPACE_ID,
- objectMetadata: noteObjectMetadata!,
- events,
- })
- .resolveAdmittedRecordIds({
- isSystemContext: false,
- objectsPermissions: rolesPermissions[memberRole.id],
- principalIds: [
- EVERYONE_PRINCIPAL_ID,
- WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
- memberRole.id,
- ],
- canAccessAllRecords: false,
- isOwningApplication: () => false,
- resolveRowLevelPermissionRecordFilter: () => null,
- });
- const noteOnPersonFilter = { id: { eq: NOTE_ON_PERSON_ID } };
-
- const deleteResponse = await makeGraphqlApiRequest(
- deleteManyOperationFactory({
- objectMetadataSingularName: 'note',
- objectMetadataPluralName: 'notes',
- 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, deletedAt },
- updatedFields: ['deletedAt'],
- diff: {},
- };
- const readableThroughLiveLinks = await resolveReadableNoteIds([
- { recordId: NOTE_ON_PERSON_ID, properties: deletedNoteEventProperties },
- ]);
- const readableThroughCapturedLinks = await resolveReadableNoteIds([
- {
- recordId: NOTE_ON_PERSON_ID,
- properties: {
- ...deletedNoteEventProperties,
- inheritedReadabilityChildRecords: {
- noteTarget: [
- {
- id: PERSON_NOTE_TARGET_ID,
- noteId: NOTE_ON_PERSON_ID,
- targetPersonId: PERSON_ID,
- },
- ],
- },
- } as ObjectRecordDeleteEvent['properties'],
- },
- ]);
- const restoreResponse = await makeGraphqlApiRequest(
- restoreManyOperationFactory({
- objectMetadataSingularName: 'note',
- objectMetadataPluralName: 'notes',
- gqlFields: 'id',
- filter: noteOnPersonFilter,
- }),
- );
-
- expect(deleteResponse.body.errors).toBeUndefined();
- expect(deleteResponse.body.data.deleteNotes).toEqual([
- { id: NOTE_ON_PERSON_ID, deletedAt: expect.any(String) },
- ]);
- expect(restoreResponse.body.errors).toBeUndefined();
- expect(restoreResponse.body.data.restoreNotes).toEqual([
- { id: NOTE_ON_PERSON_ID },
- ]);
- expect([...readableThroughLiveLinks]).toEqual([]);
- expect([...readableThroughCapturedLinks]).toEqual([NOTE_ON_PERSON_ID]);
- });
-
- 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 } };
-
- const detachResponse = await makeGraphqlApiRequest(
- deleteManyOperationFactory({
- objectMetadataSingularName: 'noteTarget',
- objectMetadataPluralName: 'noteTargets',
- gqlFields: 'id',
- filter: companyNoteTargetFilter,
- }),
- );
-
- const deleteResponse = await makeGraphqlApiRequest(
- deleteManyOperationFactory({
- objectMetadataSingularName: 'note',
- objectMetadataPluralName: 'notes',
- gqlFields: 'id',
- filter: noteOnCompanyFilter,
- }),
- );
-
- const trashedNotesResponse = await makeGraphqlApiRequestWithMemberRole(
- findManyOperationFactory({
- objectMetadataSingularName: 'note',
- objectMetadataPluralName: 'notes',
- gqlFields: 'id',
- filter: {
- ...noteOnCompanyFilter,
- not: { deletedAt: { is: 'NULL' } },
- },
- }),
- );
-
- const restoreNoteResponse = await makeGraphqlApiRequest(
- restoreManyOperationFactory({
- objectMetadataSingularName: 'note',
- objectMetadataPluralName: 'notes',
- gqlFields: 'id',
- filter: noteOnCompanyFilter,
- }),
- );
- const restoreTargetResponse = await makeGraphqlApiRequest(
- restoreManyOperationFactory({
- objectMetadataSingularName: 'noteTarget',
- objectMetadataPluralName: 'noteTargets',
- gqlFields: 'id',
- filter: companyNoteTargetFilter,
- }),
- );
-
- expect(detachResponse.body.data.deleteNoteTargets).toEqual([
- { id: COMPANY_NOTE_TARGET_ID },
- ]);
- expect(deleteResponse.body.data.deleteNotes).toEqual([
- { id: NOTE_ON_COMPANY_ID },
- ]);
- expect(trashedNotesResponse.body.errors).toBeUndefined();
- expect(collectIds(trashedNotesResponse.body.data.notes.edges)).toEqual([
- NOTE_ON_COMPANY_ID,
- ]);
- expect(restoreNoteResponse.body.errors).toBeUndefined();
- expect(restoreTargetResponse.body.errors).toBeUndefined();
- });
- });
-});
diff --git a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/readability-object-records-permissions.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/readability-object-records-permissions.integration-spec.ts
index d45400c2557..abb0b58d359 100644
--- a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/readability-object-records-permissions.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/readability-object-records-permissions.integration-spec.ts
@@ -544,17 +544,4 @@ describe('readabilityObjectRecordsPermissions', () => {
);
});
});
-
- describe('SYSTEM readability', () => {
- beforeAll(async () => {
- await setObjectReadability(objectMetadataId, MetadataReadability.SYSTEM);
- });
-
- it('should refuse reads even for an admin', async () => {
- const response = await makeGraphqlApiRequest(findManyOperation);
-
- expect(response.body.errors).toBeDefined();
- expect(response.body.errors[0].message).toContain('not readable');
- });
- });
});
diff --git a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/record-level-sharing-restricted-record-surfaces.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/record-level-sharing-restricted-record-surfaces.integration-spec.ts
index 5be9295311e..9f0eb8730ba 100644
--- a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/record-level-sharing-restricted-record-surfaces.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/record-level-sharing-restricted-record-surfaces.integration-spec.ts
@@ -37,8 +37,6 @@ const RESTRICTED_COMPANY_ID = randomUUID();
const OPEN_COMPANY_ID = randomUUID();
const COMPANY_IDS = [RESTRICTED_COMPANY_ID, OPEN_COMPANY_ID];
const PERSON_ID = randomUUID();
-const NOTE_ID = randomUUID();
-const NOTE_TARGET_ID = randomUUID();
const SET_SHARE = parse(
`mutation SetShare($target: RecordTargetInput!, $principal: RecordSharePrincipalInput!, $accessLevel: RecordShareAccessLevel!) { setRecordShare(target: $target, principal: $principal, accessLevel: $accessLevel) { generalAccessLevel } }`,
@@ -141,12 +139,6 @@ describe('A restricted record on an object open by default', () => {
name: { firstName: 'Works at', lastName: 'Restricted' },
companyId: RESTRICTED_COMPANY_ID,
});
- await createRecord('note', { id: NOTE_ID, title: 'On the restricted' });
- await createRecord('noteTarget', {
- id: NOTE_TARGET_ID,
- noteId: NOTE_ID,
- targetCompanyId: RESTRICTED_COMPANY_ID,
- });
const restricted = await changeSharing(SET_GENERAL_ACCESS, {
accessLevel: RecordShareAccessLevel.NONE,
@@ -171,8 +163,6 @@ describe('A restricted record on an object open by default', () => {
});
for (const [singular, plural, ids] of [
- ['noteTarget', 'noteTargets', [NOTE_TARGET_ID]],
- ['note', 'notes', [NOTE_ID]],
['person', 'people', [PERSON_ID]],
['company', 'companies', COMPANY_IDS],
] as const) {
@@ -295,27 +285,6 @@ describe('A restricted record on an object open by default', () => {
).toEqual([OPEN_COMPANY_ID]);
});
- it('should hide the note attached to it only', async () => {
- const findNoteIds = async (token: string) => {
- const response = await makeGraphqlApiRequest(
- findManyOperationFactory({
- objectMetadataSingularName: 'note',
- objectMetadataPluralName: 'notes',
- gqlFields: 'id',
- filter: { id: { eq: NOTE_ID } },
- }),
- token,
- );
-
- expect(response.body.errors).toBeUndefined();
-
- return collectIds(response.body.data.notes.edges);
- };
-
- expect(await findNoteIds(APPLE_JONY_MEMBER_ACCESS_TOKEN)).toEqual([]);
- expect(await findNoteIds(APPLE_JANE_ADMIN_ACCESS_TOKEN)).toEqual([NOTE_ID]);
- });
-
it('should leave it out of the events delivered to others', async () => {
const memberRole = await findOneRoleByLabel({ label: 'Member' });
const { rolesPermissions, flatObjectMetadataMaps } =
@@ -444,18 +413,6 @@ describe('A restricted record on an object open by default', () => {
id: RESTRICTED_COMPANY_ID,
});
- const notes = await makeGraphqlApiRequest(
- findManyOperationFactory({
- objectMetadataSingularName: 'note',
- objectMetadataPluralName: 'notes',
- gqlFields: 'id',
- filter: { id: { eq: NOTE_ID } },
- }),
- APPLE_JONY_MEMBER_ACCESS_TOKEN,
- );
-
- expect(collectIds(notes.body.data.notes.edges)).toEqual([NOTE_ID]);
-
await changeSharing(REMOVE_SHARE, {
principal: { workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY },
});
diff --git a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/record-share-object.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/record-share-object.integration-spec.ts
index 56c906b9108..e2ae8860942 100644
--- a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/record-share-object.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/record-share-object.integration-spec.ts
@@ -12,9 +12,6 @@ import { type AgentChatThreadService } from 'src/engine/metadata-modules/ai/ai-c
import { USER_WORKSPACE_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-user-workspaces.util';
import { randomUUID } from 'node:crypto';
-import { createOneOperationFactory } from 'test/integration/graphql/utils/create-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 { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
import { getCoreRepository } from 'test/integration/utils/get-core-repository.util';
import {
@@ -232,32 +229,6 @@ describe('recordShare object', () => {
}
});
- it('refuses reads through the GraphQL API even for an admin', async () => {
- const response = await makeGraphqlApiRequest(
- findManyOperationFactory({
- objectMetadataSingularName: 'recordShare',
- objectMetadataPluralName: 'recordShares',
- gqlFields: 'id',
- }),
- );
-
- expect(response.body.errors).toBeDefined();
- expect(response.body.errors[0].message).toContain('not readable');
- });
-
- it('refuses creation through the GraphQL API even for an admin', async () => {
- const response = await makeGraphqlApiRequest(
- createOneOperationFactory({
- objectMetadataSingularName: 'recordShare',
- gqlFields: 'id',
- data: recordShareInput,
- }),
- );
-
- expect(response.body.errors).toBeDefined();
- expect(response.body.errors[0].message).toContain('not writable');
- });
-
it('inserts, reads back, deduplicates and removes shares through the service', async () => {
await recordShareStorageService.insertMany({
workspaceId: SEED_APPLE_WORKSPACE_ID,
diff --git a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/record-sharing-api.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/record-sharing-api.integration-spec.ts
index f4af709876e..764543c6fa4 100644
--- a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/record-sharing-api.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/record-sharing-api.integration-spec.ts
@@ -1,7 +1,5 @@
import { deleteOneOperationFactory } from 'test/integration/graphql/utils/delete-one-operation-factory.util';
import { restoreOneOperationFactory } from 'test/integration/graphql/utils/restore-one-operation-factory.util';
-import { getCoreRepository } from 'test/integration/utils/get-core-repository.util';
-import { ObjectMetadataEntity } from 'src/engine/metadata-modules/object-metadata/object-metadata.entity';
import { preserveLegacyRecordAccess } from 'src/database/commands/upgrade-version-command/2-43/utils/preserve-legacy-record-access.util';
import { STANDARD_OBJECTS } from 'twenty-shared/metadata';
import { EVERYONE_PRINCIPAL_ID } from 'twenty-shared/constants';
@@ -13,7 +11,6 @@ import { parse } from 'graphql';
import {
FieldMetadataType,
MetadataReadability,
- MetadataWritability,
RecordShareAccessLevel,
RecordSharePrincipalType,
RecordShareRowCause,
@@ -563,36 +560,6 @@ describe('Generic sharing API on an ordinary private object', () => {
).toBeDefined();
});
- it('keeps object writability above FULL grants', async () => {
- const setWritability = async (writability: MetadataWritability) => {
- await getCoreRepository<ObjectMetadataEntity>(
- ObjectMetadataEntity,
- ).update(objectMetadataId, { writability });
- await getAppProviderByClassName<WorkspaceCacheService>(
- 'WorkspaceCacheService',
- ).invalidateAndRecompute(workspaceId, ['flatObjectMetadataMaps']);
- };
- await grant(RecordShareAccessLevel.FULL);
- await setWritability(MetadataWritability.SYSTEM);
- try {
- expect(
- (await settings()).body.data.recordSharing.permissions.canUpdate,
- ).toBe(false);
- expect(
- (await setGeneralAccess(RecordShareAccessLevel.READ)).body.errors,
- ).toBeDefined();
- expect(
- (
- await unshare({
- workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
- })
- ).body.errors,
- ).toBeDefined();
- } finally {
- await setWritability(MetadataWritability.OPEN);
- }
- });
-
it('keeps object role permissions above even FULL record grants', async () => {
await grant(RecordShareAccessLevel.FULL);
await setRoleUpdate(false);
diff --git a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/record-sharing-beyond-role.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/record-sharing-beyond-role.integration-spec.ts
index 2c0db0dc223..5a50905b800 100644
--- a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/record-sharing-beyond-role.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/record-sharing-beyond-role.integration-spec.ts
@@ -6,7 +6,6 @@ import { type ObjectRecordEvent } from 'twenty-shared/database-events';
import { isDefined } from 'twenty-shared/utils';
import {
FeatureFlagKey,
- ObjectSharingReach,
RecordShareAccessLevel,
RowLevelPermissionPredicateOperand,
} from 'twenty-shared/types';
@@ -114,12 +113,6 @@ describe('Records shared beyond the role that can access their object', () => {
},
});
- const setSharingReach = (sharingReach: ObjectSharingReach) =>
- updateOneObjectMetadata({
- expectToFail: false,
- input: { idToUpdate: objectMetadataId, updatePayload: { sharingReach } },
- });
-
const findIdsAsJony = async () => {
const response = await makeGraphqlApiRequest(
findManyOperationFactory({
@@ -197,7 +190,6 @@ describe('Records shared beyond the role that can access their object', () => {
recordIds: [SHARED_RECORD_ID, OTHER_RECORD_ID],
});
await setMemberObjectAccess(false);
- await setSharingReach(ObjectSharingReach.WORKSPACE);
});
afterAll(async () => {
@@ -329,83 +321,6 @@ describe('Records shared beyond the role that can access their object', () => {
);
});
- it('should refuse to share with someone the object cannot reach', async () => {
- await setSharingReach(ObjectSharingReach.ROLE_ACCESS);
-
- const response = await setShare({ principal: JONY });
-
- expect(response.body.errors?.[0]?.extensions?.subCode).toBe(
- 'INVALID_SHARE_WITH',
- );
-
- expect(
- (await setShare({ principal: { roleId: memberRoleId } })).body.errors?.[0]
- ?.extensions?.subCode,
- ).toBe('INVALID_SHARE_WITH');
-
- await setMemberObjectAccess(true);
-
- expect((await setShare({ principal: JONY })).body.errors).toBeUndefined();
- expect(
- (await setShare({ principal: { roleId: memberRoleId } })).body.errors,
- ).toBeUndefined();
- });
-
- it('should refuse a share the row filter of the recipient would hide, but let the role filter each member on read', async () => {
- await setMemberObjectAccess(true);
- await setSharingReach(ObjectSharingReach.ROLE_ACCESS);
- await upsertRowLevelPermissionPredicates({
- expectToFail: false,
- input: {
- roleId: memberRoleId,
- objectMetadataId,
- predicates: [
- {
- fieldMetadataId: nameFieldMetadataId,
- operand: RowLevelPermissionPredicateOperand.CONTAINS,
- value: 'Visible',
- },
- ],
- predicateGroups: [],
- },
- });
-
- try {
- const response = await setShare({ principal: JONY });
-
- expect(response.body.errors?.[0]?.extensions?.subCode).toBe(
- 'INVALID_SHARE_WITH',
- );
- expect(
- await shares.findByRecordIds({
- workspaceId,
- objectMetadataId,
- recordIds: [SHARED_RECORD_ID],
- }),
- ).toEqual([]);
- expect(
- (await setShare({ principal: { roleId: memberRoleId } })).body.errors,
- ).toBeUndefined();
- } finally {
- await upsertRowLevelPermissionPredicates({
- expectToFail: false,
- input: {
- roleId: memberRoleId,
- objectMetadataId,
- predicates: [],
- predicateGroups: [],
- },
- });
- }
- });
-
- it('should stay within the role when the object limits sharing to it', async () => {
- await setShare({ principal: JONY });
- await setSharingReach(ObjectSharingReach.ROLE_ACCESS);
-
- expect((await findIdsAsJony()).errors).toBeDefined();
- });
-
it('should let a named grant reach a record the row filter of the role hides', async () => {
await setMemberObjectAccess(true);
await upsertRowLevelPermissionPredicates({
@@ -438,10 +353,6 @@ describe('Records shared beyond the role that can access their object', () => {
expect(
(await renameAsJony('Edited under a row filter')).body.errors,
).toBeUndefined();
-
- await setSharingReach(ObjectSharingReach.ROLE_ACCESS);
-
- expect((await findIdsAsJony()).ids).toEqual([OTHER_RECORD_ID]);
} finally {
await upsertRowLevelPermissionPredicates({
expectToFail: false,
@@ -506,10 +417,6 @@ describe('Records shared beyond the role that can access their object', () => {
expect((await findIdsAsJony()).ids).toEqual([SHARED_RECORD_ID]);
expect([...(await resolveAdmittedRecordIds())]).toEqual([SHARED_RECORD_ID]);
-
- await setSharingReach(ObjectSharingReach.ROLE_ACCESS);
-
- expect([...(await resolveAdmittedRecordIds())]).toEqual([]);
});
it('should keep grants within the role while the flag is off', async () => {
@@ -522,43 +429,4 @@ describe('Records shared beyond the role that can access their object', () => {
await setRecordSharingEnabled(true);
}
});
-
- it('should let admins change the reach of a standard object', async () => {
- const { data } = await makeMetadataApiRequest({
- query: parse(
- `query { objects(paging: { first: 1000 }) { edges { node { id nameSingular sharingReach } } } }`,
- ),
- }).then((response) => response.body);
- const company = data.objects.edges
- .map(({ node }: { node: { nameSingular: string } }) => node)
- .find(
- ({ nameSingular }: { nameSingular: string }) =>
- nameSingular === 'company',
- );
-
- expect(company.sharingReach).toBe(ObjectSharingReach.WORKSPACE);
-
- try {
- const { data: updated } = await updateOneObjectMetadata({
- expectToFail: false,
- input: {
- idToUpdate: company.id,
- updatePayload: { sharingReach: ObjectSharingReach.ROLE_ACCESS },
- },
- gqlFields: 'sharingReach',
- });
-
- expect(updated.updateOneObject.sharingReach).toBe(
- ObjectSharingReach.ROLE_ACCESS,
- );
- } finally {
- await updateOneObjectMetadata({
- expectToFail: false,
- input: {
- idToUpdate: company.id,
- updatePayload: { sharingReach: ObjectSharingReach.WORKSPACE },
- },
- });
- }
- });
});
diff --git a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/writability-object-records-permissions.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/writability-object-records-permissions.integration-spec.ts
deleted file mode 100644
index 21aac2a4a8f..00000000000
--- a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/writability-object-records-permissions.integration-spec.ts
+++ /dev/null
@@ -1,246 +0,0 @@
-import { randomUUID } from 'node:crypto';
-
-import { createOneOperationFactory } from 'test/integration/graphql/utils/create-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 { updateOneOperationFactory } from 'test/integration/graphql/utils/update-one-operation-factory.util';
-import { createOneFieldMetadata } from 'test/integration/metadata/suites/field-metadata/utils/create-one-field-metadata.util';
-import { updateOneFieldMetadata } from 'test/integration/metadata/suites/field-metadata/utils/update-one-field-metadata.util';
-import { createOneObjectMetadata } from 'test/integration/metadata/suites/object-metadata/utils/create-one-object-metadata.util';
-import { deleteOneObjectMetadata } from 'test/integration/metadata/suites/object-metadata/utils/delete-one-object-metadata.util';
-import { updateOneObjectMetadata } from 'test/integration/metadata/suites/object-metadata/utils/update-one-object-metadata.util';
-import { getCoreRepository } from 'test/integration/utils/get-core-repository.util';
-import { FieldMetadataType, MetadataWritability } from 'twenty-shared/types';
-
-import { FieldMetadataEntity } from 'src/engine/metadata-modules/field-metadata/field-metadata.entity';
-import { ObjectMetadataEntity } from 'src/engine/metadata-modules/object-metadata/object-metadata.entity';
-
-const OBJECT_SINGULAR = 'writabilityTestObject';
-const OBJECT_PLURAL = 'writabilityTestObjects';
-const UPDATE_RESPONSE_KEY = 'updateWritabilityTestObject';
-const RECORD_GQL_FIELDS = `
- id
- guardedField
- freeField
-`;
-
-const setObjectWritability = async (
- objectMetadataId: string,
- writability: MetadataWritability,
-) => {
- await getCoreRepository<ObjectMetadataEntity>(ObjectMetadataEntity).update(
- objectMetadataId,
- { writability },
- );
-
- const { errors } = await updateOneObjectMetadata({
- expectToFail: false,
- input: {
- idToUpdate: objectMetadataId,
- updatePayload: { description: `writability set to ${writability}` },
- },
- });
-
- expect(errors).toBeUndefined();
-};
-
-const setFieldWritability = async (
- fieldMetadataId: string,
- writability: MetadataWritability,
-) => {
- await getCoreRepository<FieldMetadataEntity>(FieldMetadataEntity).update(
- fieldMetadataId,
- { writability },
- );
-
- const { errors } = await updateOneFieldMetadata({
- expectToFail: false,
- input: {
- idToUpdate: fieldMetadataId,
- updatePayload: { description: `writability set to ${writability}` },
- },
- });
-
- expect(errors).toBeUndefined();
-};
-
-describe('writabilityObjectRecordsPermissions', () => {
- let objectMetadataId: string;
- let guardedFieldMetadataId: string;
- let recordId: string;
-
- beforeAll(async () => {
- const { data } = await createOneObjectMetadata({
- input: {
- nameSingular: OBJECT_SINGULAR,
- namePlural: OBJECT_PLURAL,
- labelSingular: 'Writability Test Object',
- labelPlural: 'Writability Test Objects',
- icon: 'IconLock',
- isLabelSyncedWithName: false,
- },
- });
-
- objectMetadataId = data.createOneObject.id;
-
- const { data: guardedFieldData } = await createOneFieldMetadata({
- input: {
- name: 'guardedField',
- label: 'Guarded Field',
- type: FieldMetadataType.TEXT,
- objectMetadataId,
- isLabelSyncedWithName: false,
- },
- });
-
- guardedFieldMetadataId = guardedFieldData.createOneField.id;
-
- await createOneFieldMetadata({
- input: {
- name: 'freeField',
- label: 'Free Field',
- type: FieldMetadataType.TEXT,
- objectMetadataId,
- isLabelSyncedWithName: false,
- },
- });
-
- recordId = randomUUID();
-
- const response = await makeGraphqlApiRequest(
- createOneOperationFactory({
- objectMetadataSingularName: OBJECT_SINGULAR,
- gqlFields: RECORD_GQL_FIELDS,
- data: { id: recordId },
- }),
- );
-
- expect(response.body.errors).toBeUndefined();
- });
-
- afterAll(async () => {
- await setObjectWritability(objectMetadataId, MetadataWritability.OPEN);
- await updateOneObjectMetadata({
- expectToFail: false,
- input: {
- idToUpdate: objectMetadataId,
- updatePayload: { isActive: false },
- },
- });
- await deleteOneObjectMetadata({
- input: { idToDelete: objectMetadataId },
- });
- });
-
- describe('SYSTEM object writability', () => {
- beforeAll(async () => {
- await setObjectWritability(objectMetadataId, MetadataWritability.SYSTEM);
- });
-
- afterAll(async () => {
- await setObjectWritability(objectMetadataId, MetadataWritability.OPEN);
- });
-
- it('should refuse record creation even for an admin', async () => {
- const response = await makeGraphqlApiRequest(
- createOneOperationFactory({
- objectMetadataSingularName: OBJECT_SINGULAR,
- gqlFields: RECORD_GQL_FIELDS,
- data: { id: randomUUID() },
- }),
- );
-
- expect(response.body.errors).toBeDefined();
- expect(response.body.errors[0].message).toContain('not writable');
- });
-
- it('should refuse record update even for an admin', async () => {
- const response = await makeGraphqlApiRequest(
- updateOneOperationFactory({
- objectMetadataSingularName: OBJECT_SINGULAR,
- gqlFields: RECORD_GQL_FIELDS,
- recordId,
- data: { guardedField: 'blocked' },
- }),
- );
-
- expect(response.body.errors).toBeDefined();
- expect(response.body.errors[0].message).toContain('not writable');
- });
-
- it('should keep records readable', async () => {
- const response = await makeGraphqlApiRequest(
- findManyOperationFactory({
- objectMetadataSingularName: OBJECT_SINGULAR,
- objectMetadataPluralName: OBJECT_PLURAL,
- gqlFields: RECORD_GQL_FIELDS,
- }),
- );
-
- expect(response.body.errors).toBeUndefined();
- expect(response.body.data[OBJECT_PLURAL].edges.length).toBeGreaterThan(0);
- });
- });
-
- describe('SYSTEM field writability on an OPEN object', () => {
- beforeAll(async () => {
- await setFieldWritability(
- guardedFieldMetadataId,
- MetadataWritability.SYSTEM,
- );
- });
-
- afterAll(async () => {
- await setFieldWritability(
- guardedFieldMetadataId,
- MetadataWritability.OPEN,
- );
- });
-
- it('should refuse writes to the protected field', async () => {
- const response = await makeGraphqlApiRequest(
- updateOneOperationFactory({
- objectMetadataSingularName: OBJECT_SINGULAR,
- gqlFields: RECORD_GQL_FIELDS,
- recordId,
- data: { guardedField: 'blocked' },
- }),
- );
-
- expect(response.body.errors).toBeDefined();
- expect(response.body.errors[0].message).toContain('not writable');
- });
-
- it('should allow writes to other fields of the same object', async () => {
- const response = await makeGraphqlApiRequest(
- updateOneOperationFactory({
- objectMetadataSingularName: OBJECT_SINGULAR,
- gqlFields: RECORD_GQL_FIELDS,
- recordId,
- data: { freeField: 'allowed' },
- }),
- );
-
- expect(response.body.errors).toBeUndefined();
- expect(response.body.data[UPDATE_RESPONSE_KEY].freeField).toBe('allowed');
- });
- });
-
- describe('OPEN writability', () => {
- it('should keep record writes working as before', async () => {
- const response = await makeGraphqlApiRequest(
- updateOneOperationFactory({
- objectMetadataSingularName: OBJECT_SINGULAR,
- gqlFields: RECORD_GQL_FIELDS,
- recordId,
- data: { guardedField: 'open again' },
- }),
- );
-
- expect(response.body.errors).toBeUndefined();
- expect(response.body.data[UPDATE_RESPONSE_KEY].guardedField).toBe(
- 'open again',
- );
- });
- });
-});
diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/pick-record-round-robin-workflow.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/pick-record-round-robin-workflow.integration-spec.ts
index 7fedc24d6ca..5c0144a1a17 100644
--- a/packages/twenty-server/test/integration/graphql/suites/workflow/pick-record-round-robin-workflow.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/pick-record-round-robin-workflow.integration-spec.ts
@@ -1,4 +1,8 @@
-import request from 'supertest';
+import { randomUUID } from 'crypto';
+
+import { createManyOperationFactory } from 'test/integration/graphql/utils/create-many-operation-factory.util';
+import { destroyManyOperationFactory } from 'test/integration/graphql/utils/destroy-many-operation-factory.util';
+import { makeGraphqlApiRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';
import {
activateCoreWorkflowVersion,
createCoreWorkflow,
@@ -13,8 +17,6 @@ import {
waitForWorkflowCompletion,
} from 'test/integration/graphql/suites/workflow/utils/workflow-run-test.util';
-const client = request(`http://localhost:${APP_PORT}`);
-
describe('Pick Record Workflow - round robin (e2e)', () => {
let coreWorkflowId: string | null = null;
let coreWorkflowVersionId: string | null = null;
@@ -47,29 +49,20 @@ describe('Pick Record Workflow - round robin (e2e)', () => {
pickRecordStepId = pickRecordStep.id;
- const companiesResponse = await client
- .post('/graphql')
- .set('Authorization', `Bearer ${APPLE_JANE_ADMIN_ACCESS_TOKEN}`)
- .send({
- query: `
- query Companies {
- companies(first: 3) {
- edges {
- node {
- id
- }
- }
- }
- }
- `,
- });
-
- const candidateRecordIds = companiesResponse.body.data.companies.edges.map(
- (edge: { node: { id: string } }) => edge.node.id,
+ const candidateRecordIds = [randomUUID(), randomUUID(), randomUUID()];
+
+ await makeGraphqlApiRequest(
+ createManyOperationFactory({
+ objectMetadataSingularName: 'company',
+ objectMetadataPluralName: 'companies',
+ gqlFields: 'id',
+ data: candidateRecordIds.map((id, index) => ({
+ id,
+ name: `Round robin candidate ${index + 1}`,
+ })),
+ }),
);
- expect(candidateRecordIds.length).toBe(3);
-
// The executor sorts the resolved pool deterministically by id before
// applying the round-robin cursor, so the expected cycle order is the
// pool sorted the same way.
@@ -99,6 +92,15 @@ describe('Pick Record Workflow - round robin (e2e)', () => {
if (coreWorkflowId) {
await deleteCoreWorkflows({ coreWorkflowIds: [coreWorkflowId] });
}
+
+ await makeGraphqlApiRequest(
+ destroyManyOperationFactory({
+ objectMetadataSingularName: 'company',
+ objectMetadataPluralName: 'companies',
+ gqlFields: 'id',
+ filter: { id: { in: orderedCandidateRecordIds } },
+ }),
+ );
});
it('cycles through the pool in order on consecutive runs', async () => {
diff --git a/packages/twenty-server/test/integration/metadata/suites/application/__snapshots__/failing-sync-application-search-vector-identifier-hijack.integration-spec.ts.snap b/packages/twenty-server/test/integration/metadata/suites/application/__snapshots__/failing-sync-application-search-vector-identifier-hijack.integration-spec.ts.snap
index 6bf709276d5..d2985bb4d6a 100644
--- a/packages/twenty-server/test/integration/metadata/suites/application/__snapshots__/failing-sync-application-search-vector-identifier-hijack.integration-spec.ts.snap
+++ b/packages/twenty-server/test/integration/metadata/suites/application/__snapshots__/failing-sync-application-search-vector-identifier-hijack.integration-spec.ts.snap
@@ -13,12 +13,6 @@ exports[`Sync application should reject hijacking the searchVector system field
"message": "System fields only allow updating: universalSettings, isActive. Forbidden properties: description, icon, isUIEditable, writability",
"userFriendlyMessage": "System fields cannot be updated",
},
- {
- "code": "INVALID_FIELD_INPUT",
- "message": "Field type TS_VECTOR must have SYSTEM writability",
- "userFriendlyMessage": "Field type TS_VECTOR must have SYSTEM writability",
- "value": "OPEN",
- },
{
"code": "NON_UPDATABLE_PROPERTY_DIVERGENCE",
"message": "fieldMetadata property "isSystemSideEffect" cannot be updated",
@@ -147,12 +141,6 @@ exports[`Sync application should reject hijacking the searchVector system field
"userFriendlyMessage": "Field type TS_VECTOR must be named "searchVector"",
"value": "stolenSearchVector",
},
- {
- "code": "INVALID_FIELD_INPUT",
- "message": "Field type TS_VECTOR must have SYSTEM writability",
- "userFriendlyMessage": "Field type TS_VECTOR must have SYSTEM writability",
- "value": "OPEN",
- },
{
"code": "NON_UPDATABLE_PROPERTY_DIVERGENCE",
"message": "fieldMetadata property "isSystemSideEffect" cannot be updated",
diff --git a/packages/twenty-server/test/integration/metadata/suites/object-permission/successful-object-permission-upsert.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/object-permission/successful-object-permission-upsert.integration-spec.ts
index 94811be9515..33b59a2a58f 100644
--- a/packages/twenty-server/test/integration/metadata/suites/object-permission/successful-object-permission-upsert.integration-spec.ts
+++ b/packages/twenty-server/test/integration/metadata/suites/object-permission/successful-object-permission-upsert.integration-spec.ts
@@ -6,7 +6,7 @@ import { createOneRole } from 'test/integration/metadata/suites/role/utils/creat
import { deleteOneRole } from 'test/integration/metadata/suites/role/utils/delete-one-role.util';
import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';
import { jestExpectToBeDefined } from 'test/utils/jest-expect-to-be-defined.util.test';
-import { isDefined } from 'twenty-shared/utils';
+import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';
describe('Object permission upsert should succeed', () => {
let createdRoleId: string;
@@ -58,6 +58,7 @@ describe('Object permission upsert should succeed', () => {
node {
id
isSystem
+ disabledObjectPermissionActions
}
}
}
@@ -66,8 +67,15 @@ describe('Object permission upsert should succeed', () => {
});
const edges = objectMetadataResponse.body.data?.objects?.edges ?? [];
const systemObjectNode = edges.find(
- (edge: { node: { isSystem: boolean | string } }) =>
- edge.node.isSystem === true || String(edge.node.isSystem) === 'true',
+ (edge: {
+ node: {
+ isSystem: boolean | string;
+ disabledObjectPermissionActions: string[] | null;
+ };
+ }) =>
+ (edge.node.isSystem === true ||
+ String(edge.node.isSystem) === 'true') &&
+ !isNonEmptyArray(edge.node.disabledObjectPermissionActions),
)?.node;
jestExpectToBeDefined(systemObjectNode);
diff --git a/packages/twenty-server/test/integration/upgrade/suites/2-53-workspace-command-1793176233512-move-application-and-system-access-to-disabled-actions.integration-spec.ts b/packages/twenty-server/test/integration/upgrade/suites/2-53-workspace-command-1793176233512-move-application-and-system-access-to-disabled-actions.integration-spec.ts
new file mode 100644
index 00000000000..784e68f3a17
--- /dev/null
+++ b/packages/twenty-server/test/integration/upgrade/suites/2-53-workspace-command-1793176233512-move-application-and-system-access-to-disabled-actions.integration-spec.ts
@@ -0,0 +1,244 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
+
+import { type MoveApplicationAndSystemAccessToDisabledActionsCommand } from 'src/database/commands/upgrade-version-command/2-53/2-53-workspace-command-1793176233512-move-application-and-system-access-to-disabled-actions.command';
+import { type WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+
+const RUN_ON_WORKSPACE_ARGS = {
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ options: {},
+ index: 0,
+ total: 1,
+};
+
+const APPLICATION_WRITABLE_OBJECT = 'rocket';
+const APPLICATION_READABLE_OBJECT = 'pet';
+const SYSTEM_OBJECT = 'shortLink';
+const SYSTEM_WRITABLE_OBJECT = 'workflowAutomatedTrigger';
+
+const ALL_ACTIONS = [
+ 'canDestroyObjectRecords',
+ 'canReadObjectRecords',
+ 'canSoftDeleteObjectRecords',
+ 'canUpdateObjectRecords',
+];
+const WRITE_ACTIONS = [
+ 'canDestroyObjectRecords',
+ 'canSoftDeleteObjectRecords',
+ 'canUpdateObjectRecords',
+];
+
+type ObjectAccessRow = {
+ writability: string;
+ readability: string;
+ disabledObjectPermissionActions: string[] | null;
+};
+
+describe('2-53 workspace command - move application and system access to disabled actions (integration)', () => {
+ let command: MoveApplicationAndSystemAccessToDisabledActionsCommand;
+ let workspaceCacheService: WorkspaceCacheService;
+
+ const setObjectAccess = async ({
+ nameSingular,
+ access,
+ }: {
+ nameSingular: string;
+ access: ObjectAccessRow;
+ }) => {
+ await global.testDataSource.query(
+ `UPDATE core."objectMetadata"
+ SET "writability" = $3, "readability" = $4, "disabledObjectPermissionActions" = $5
+ WHERE "workspaceId" = $1 AND "nameSingular" = $2`,
+ [
+ SEED_APPLE_WORKSPACE_ID,
+ nameSingular,
+ access.writability,
+ access.readability,
+ isDefined(access.disabledObjectPermissionActions)
+ ? JSON.stringify(access.disabledObjectPermissionActions)
+ : null,
+ ],
+ );
+ await workspaceCacheService.invalidateAndRecompute(
+ SEED_APPLE_WORKSPACE_ID,
+ ['flatObjectMetadataMaps'],
+ );
+ };
+
+ const findObjectAccess = async (
+ nameSingular: string,
+ ): Promise<ObjectAccessRow> => {
+ const [row] = await global.testDataSource.query(
+ `SELECT "writability", "readability", "disabledObjectPermissionActions"
+ FROM core."objectMetadata" WHERE "workspaceId" = $1 AND "nameSingular" = $2`,
+ [SEED_APPLE_WORKSPACE_ID, nameSingular],
+ );
+
+ return row;
+ };
+
+ const findCachedObjectAccess = async (nameSingular: string) => {
+ const { flatObjectMetadataMaps } =
+ await workspaceCacheService.getOrRecompute(SEED_APPLE_WORKSPACE_ID, [
+ 'flatObjectMetadataMaps',
+ ]);
+ const flatObjectMetadata = Object.values(
+ flatObjectMetadataMaps.byUniversalIdentifier,
+ ).find((objectMetadata) => objectMetadata?.nameSingular === nameSingular);
+
+ return {
+ writability: flatObjectMetadata?.writability,
+ readability: flatObjectMetadata?.readability,
+ disabledObjectPermissionActions:
+ flatObjectMetadata?.disabledObjectPermissionActions,
+ };
+ };
+
+ beforeAll(async () => {
+ command =
+ getAppProviderByClassName<MoveApplicationAndSystemAccessToDisabledActionsCommand>(
+ 'MoveApplicationAndSystemAccessToDisabledActionsCommand',
+ );
+ workspaceCacheService = getAppProviderByClassName<WorkspaceCacheService>(
+ 'WorkspaceCacheService',
+ );
+
+ await setObjectAccess({
+ nameSingular: APPLICATION_WRITABLE_OBJECT,
+ access: {
+ writability: 'APPLICATION',
+ readability: 'OPEN',
+ disabledObjectPermissionActions: ['canDestroyObjectRecords'],
+ },
+ });
+ await setObjectAccess({
+ nameSingular: APPLICATION_READABLE_OBJECT,
+ access: {
+ writability: 'OPEN',
+ readability: 'APPLICATION',
+ disabledObjectPermissionActions: null,
+ },
+ });
+ await setObjectAccess({
+ nameSingular: SYSTEM_OBJECT,
+ access: {
+ writability: 'SYSTEM',
+ readability: 'SYSTEM',
+ disabledObjectPermissionActions: null,
+ },
+ });
+ await setObjectAccess({
+ nameSingular: SYSTEM_WRITABLE_OBJECT,
+ access: {
+ writability: 'SYSTEM',
+ readability: 'OPEN',
+ disabledObjectPermissionActions: null,
+ },
+ });
+ });
+
+ afterAll(async () => {
+ for (const nameSingular of [
+ APPLICATION_WRITABLE_OBJECT,
+ APPLICATION_READABLE_OBJECT,
+ ]) {
+ await setObjectAccess({
+ nameSingular,
+ access: {
+ writability: 'OPEN',
+ readability: 'OPEN',
+ disabledObjectPermissionActions: null,
+ },
+ });
+ }
+ await setObjectAccess({
+ nameSingular: SYSTEM_OBJECT,
+ access: {
+ writability: 'SYSTEM',
+ readability: 'SYSTEM',
+ disabledObjectPermissionActions: ALL_ACTIONS,
+ },
+ });
+ await setObjectAccess({
+ nameSingular: SYSTEM_WRITABLE_OBJECT,
+ access: {
+ writability: 'SYSTEM',
+ readability: 'OPEN',
+ disabledObjectPermissionActions: WRITE_ACTIONS,
+ },
+ });
+ });
+
+ it('changes nothing on a dry run', async () => {
+ await command.runOnWorkspace({
+ ...RUN_ON_WORKSPACE_ARGS,
+ options: { dryRun: true },
+ });
+
+ expect(await findObjectAccess(APPLICATION_WRITABLE_OBJECT)).toEqual({
+ writability: 'APPLICATION',
+ readability: 'OPEN',
+ disabledObjectPermissionActions: ['canDestroyObjectRecords'],
+ });
+ });
+
+ it('moves APPLICATION writability and readability to disabled actions and refreshes the cache', async () => {
+ await command.runOnWorkspace(RUN_ON_WORKSPACE_ARGS);
+
+ const expectedWritableAccess = {
+ writability: 'OPEN',
+ readability: 'OPEN',
+ disabledObjectPermissionActions: [
+ 'canDestroyObjectRecords',
+ 'canSoftDeleteObjectRecords',
+ 'canUpdateObjectRecords',
+ ],
+ };
+ const expectedReadableAccess = {
+ writability: 'OPEN',
+ readability: 'OPEN',
+ disabledObjectPermissionActions: ['canReadObjectRecords'],
+ };
+
+ expect(await findObjectAccess(APPLICATION_WRITABLE_OBJECT)).toEqual(
+ expectedWritableAccess,
+ );
+ expect(await findObjectAccess(APPLICATION_READABLE_OBJECT)).toEqual(
+ expectedReadableAccess,
+ );
+ expect(await findCachedObjectAccess(APPLICATION_WRITABLE_OBJECT)).toEqual(
+ expectedWritableAccess,
+ );
+ expect(await findCachedObjectAccess(APPLICATION_READABLE_OBJECT)).toEqual(
+ expectedReadableAccess,
+ );
+ });
+
+ it('disables the actions SYSTEM access forbade and keeps the stored values', async () => {
+ expect(await findObjectAccess(SYSTEM_OBJECT)).toEqual({
+ writability: 'SYSTEM',
+ readability: 'SYSTEM',
+ disabledObjectPermissionActions: ALL_ACTIONS,
+ });
+ expect(await findObjectAccess(SYSTEM_WRITABLE_OBJECT)).toEqual({
+ writability: 'SYSTEM',
+ readability: 'OPEN',
+ disabledObjectPermissionActions: WRITE_ACTIONS,
+ });
+ });
+
+ it('changes nothing when it runs again', async () => {
+ await command.runOnWorkspace(RUN_ON_WORKSPACE_ARGS);
+
+ expect(
+ (await findObjectAccess(APPLICATION_WRITABLE_OBJECT))
+ .disabledObjectPermissionActions,
+ ).toEqual([
+ 'canDestroyObjectRecords',
+ 'canSoftDeleteObjectRecords',
+ 'canUpdateObjectRecords',
+ ]);
+ });
+});