Skip to content

The open alternative to Salesforce, designed for AI.

Record sharing 4/14: let a create state who may read the record with shareWith (#25428)

martmull019f142b6fce
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 8e87e5a492a..a9ecbee548e 100644
--- a/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx
+++ b/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx
@@ -803,8 +803,28 @@ const { createCompany } = await client.mutation({
name: true,
},
});
+
+// Only on an object whose readability is PRIVATE: choose who can read the created record
+const { createContract } = await client.mutation({
+ createContract: {
+ __args: {
+ data: {
+ name: 'Acme Corp renewal',
+ },
+ shareWith: [
+ {
+ roleId: '7f0c1b6e-2d4a-4c8e-9b3f-5a6d7e8f9a0b',
+ accessLevel: 'READ_WRITE',
+ },
+ ],
+ },
+ id: true,
+ },
+});
```
+`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 on a workspace where record sharing is enabled (`IS_RECORD_SHARING_ENABLED`) such callers, like a system caller, must pass `shareWith` or the create is rejected — while the flag is off a create without `shareWith` grants `FULL` access to everyone instead, so the record stays as open as it is today. Rows written while the flag is off are kept and take effect the moment the flag is turned on. 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.
<Note>
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 514a92c5fd4..e3b8340159b 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,11 @@ import { Injectable } from '@nestjs/common';
import { msg } from '@lingui/core/macro';
import { QUERY_MAX_RECORDS } from 'twenty-shared/constants';
-import { ObjectRecord } from 'twenty-shared/types';
+import {
+ FeatureFlagKey,
+ MetadataReadability,
+ ObjectRecord,
+} from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
import {
Brackets,
@@ -46,6 +50,8 @@ import { buildFieldMapsFromFlatObjectMetadata } from 'src/engine/metadata-module
import { type FlatIndexMetadata } from 'src/engine/metadata-modules/flat-index-metadata/types/flat-index-metadata.type';
import { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';
import { assertMutationNotOnRemoteObject } from 'src/engine/metadata-modules/object-metadata/utils/assert-mutation-not-on-remote-object.util';
+import { ShareWithService } from 'src/engine/record-share/services/share-with.service';
+import { type ShareWithInput } from 'src/engine/record-share/types/share-with-input.type';
import { WorkspaceRepository } from 'src/engine/twenty-orm/repository/workspace-repository';
import { RolePermissionConfig } from 'src/engine/twenty-orm/types/role-permission-config';
import { containsNestedRelationCreate } from 'src/engine/twenty-orm/utils/contains-nested-relation-create.util';
@@ -60,7 +66,10 @@ export class CommonCreateManyQueryRunnerService extends CommonBaseQueryRunnerSer
> {
protected readonly operationName = CommonQueryNames.CREATE_MANY;
- constructor(private readonly recordPositionService: RecordPositionService) {
+ constructor(
+ private readonly recordPositionService: RecordPositionService,
+ private readonly shareWithService: ShareWithService,
+ ) {
super();
}
@@ -68,15 +77,28 @@ export class CommonCreateManyQueryRunnerService extends CommonBaseQueryRunnerSer
args: CommonExtendedInput<CreateManyQueryArgs>,
queryRunnerContext: CommonExtendedQueryRunnerContext,
): Promise<ObjectRecord[]> {
+ const isPrivateObject =
+ queryRunnerContext.flatObjectMetadata.readability ===
+ MetadataReadability.PRIVATE;
+
+ if (isPrivateObject) {
+ await this.shareWithService.validateShareWithOrThrow({
+ authContext: queryRunnerContext.authContext,
+ isRecordSharingEnabled: this.isRecordSharingEnabled(queryRunnerContext),
+ shareWith: args.shareWith,
+ });
+ }
+
if (
!isDefined(queryRunnerContext.transactionScope) &&
- containsNestedRelationCreate(
- args.data,
- getNestedRelationFieldNames({
- flatObjectMetadata: queryRunnerContext.flatObjectMetadata,
- flatFieldMetadataMaps: queryRunnerContext.flatFieldMetadataMaps,
- }),
- )
+ (isPrivateObject ||
+ containsNestedRelationCreate(
+ args.data,
+ getNestedRelationFieldNames({
+ flatObjectMetadata: queryRunnerContext.flatObjectMetadata,
+ flatFieldMetadataMaps: queryRunnerContext.flatFieldMetadataMaps,
+ }),
+ ))
) {
return this.workspaceOrmManager.runInWorkspaceTransaction(
(transactionScope) =>
@@ -135,7 +157,13 @@ export class CommonCreateManyQueryRunnerService extends CommonBaseQueryRunnerSer
flatObjectMetadata,
flatObjectMetadataMaps,
flatFieldMetadataMaps,
- repository,
+ repository:
+ isPrivateObject && isDefined(queryRunnerContext.transactionScope)
+ ? queryRunnerContext.transactionScope.getRepository(
+ flatObjectMetadata.nameSingular,
+ { shouldBypassPermissionChecks: true },
+ )
+ : repository,
selectedFieldsResult: args.selectedFieldsResult,
});
@@ -268,14 +296,23 @@ export class CommonCreateManyQueryRunnerService extends CommonBaseQueryRunnerSer
const writeRepository = this.getWriteRepository(queryRunnerContext);
- return writeRepository.runInsert({
+ const insertResult = await writeRepository.runInsert({
records: await this.resolveNestedRelationsForCreate({
records: args.data,
+ shareWith: args.shareWith,
queryRunnerContext,
writeRepository,
}),
columnsToReturn: selectedColumns,
});
+
+ await this.insertRecordShares({
+ insertResult,
+ shareWith: args.shareWith,
+ queryRunnerContext,
+ });
+
+ return insertResult;
}
return this.performUpsertOperation({
@@ -359,6 +396,7 @@ export class CommonCreateManyQueryRunnerService extends CommonBaseQueryRunnerSer
flatFieldMetadataMaps,
result,
columnsToReturn,
+ shareWith: args.shareWith,
queryRunnerContext,
});
}
@@ -367,6 +405,7 @@ export class CommonCreateManyQueryRunnerService extends CommonBaseQueryRunnerSer
recordsToInsert: recordsToInsertWithPosition,
result,
columnsToReturn,
+ shareWith: args.shareWith,
queryRunnerContext,
});
@@ -469,6 +508,7 @@ export class CommonCreateManyQueryRunnerService extends CommonBaseQueryRunnerSer
flatFieldMetadataMaps,
result,
columnsToReturn,
+ shareWith,
queryRunnerContext,
}: {
partialRecordsToUpdate: PartialObjectRecordWithId[];
@@ -476,6 +516,7 @@ export class CommonCreateManyQueryRunnerService extends CommonBaseQueryRunnerSer
flatFieldMetadataMaps: FlatEntityMaps<OrmFlatFieldMetadata>;
result: InsertResult;
columnsToReturn: string[];
+ shareWith?: ShareWithInput[];
queryRunnerContext: CommonExtendedQueryRunnerContext;
}): Promise<void> {
const updateInputs = partialRecordsToUpdate
@@ -494,6 +535,7 @@ export class CommonCreateManyQueryRunnerService extends CommonBaseQueryRunnerSer
const writeRepository = this.getWriteRepository(queryRunnerContext);
const resolvedData = await this.resolveNestedRelationsForCreate({
records: updateInputs.map((input) => input.data),
+ shareWith,
queryRunnerContext,
writeRepository,
});
@@ -518,11 +560,13 @@ export class CommonCreateManyQueryRunnerService extends CommonBaseQueryRunnerSer
recordsToInsert,
result,
columnsToReturn,
+ shareWith,
queryRunnerContext,
}: {
recordsToInsert: Partial<ObjectRecord>[];
result: InsertResult;
columnsToReturn: string[];
+ shareWith?: ShareWithInput[];
queryRunnerContext: CommonExtendedQueryRunnerContext;
}): Promise<void> {
if (recordsToInsert.length === 0) {
@@ -534,23 +578,69 @@ export class CommonCreateManyQueryRunnerService extends CommonBaseQueryRunnerSer
const insertResult = await writeRepository.runInsert({
records: await this.resolveNestedRelationsForCreate({
records: recordsToInsert,
+ shareWith,
queryRunnerContext,
writeRepository,
}),
columnsToReturn,
});
+ await this.insertRecordShares({
+ insertResult,
+ shareWith,
+ queryRunnerContext,
+ });
+
result.identifiers.push(...insertResult.identifiers);
result.generatedMaps.push(...insertResult.generatedMaps);
result.raw.push(...insertResult.raw);
}
+ private async insertRecordShares({
+ insertResult,
+ shareWith,
+ queryRunnerContext,
+ }: {
+ insertResult: InsertResult;
+ shareWith?: ShareWithInput[];
+ queryRunnerContext: CommonExtendedQueryRunnerContext;
+ }): Promise<void> {
+ const { authContext, flatObjectMetadata, repository, transactionScope } =
+ queryRunnerContext;
+
+ if (flatObjectMetadata.readability !== MetadataReadability.PRIVATE) {
+ return;
+ }
+
+ await this.shareWithService.insertRecordSharesForCreatedRecords({
+ authContext,
+ objectMetadataId: flatObjectMetadata.id,
+ recordIds: insertResult.generatedMaps.map((record) => record.id),
+ apiKeyRoleMap: repository.internalContext.apiKeyRoleMap,
+ isRecordSharingEnabled: this.isRecordSharingEnabled(queryRunnerContext),
+ shareWith,
+ transactionScope,
+ });
+ }
+
+ private isRecordSharingEnabled(
+ queryRunnerContext: CommonExtendedQueryRunnerContext,
+ ): boolean {
+ return (
+ queryRunnerContext.featureFlagsMap[
+ FeatureFlagKey.IS_RECORD_SHARING_ENABLED
+ ] ?? false
+ );
+ }
+
private resolveNestedRelationsForCreate({
records,
+ shareWith,
queryRunnerContext,
writeRepository,
}: {
records: Partial<ObjectRecord>[];
+ shareWith?: ShareWithInput[];
queryRunnerContext: CommonExtendedQueryRunnerContext;
writeRepository: WorkspaceRepository;
}): Promise<Partial<ObjectRecord>[]> {
@@ -591,6 +681,7 @@ export class CommonCreateManyQueryRunnerService extends CommonBaseQueryRunnerSer
const { results } = await this.execute(
{
data: targetRecords,
+ shareWith,
selectedFields: { id: true },
},
{
diff --git a/packages/twenty-server/src/engine/api/common/core-common-api.module.ts b/packages/twenty-server/src/engine/api/common/core-common-api.module.ts
index f684c8de448..c1f2eb937a0 100644
--- a/packages/twenty-server/src/engine/api/common/core-common-api.module.ts
+++ b/packages/twenty-server/src/engine/api/common/core-common-api.module.ts
@@ -26,6 +26,7 @@ import { UserRoleModule } from 'src/engine/metadata-modules/user-role/user-role.
import { ViewFilterGroupModule } from 'src/engine/metadata-modules/view-filter-group/view-filter-group.module';
import { ViewFilterModule } from 'src/engine/metadata-modules/view-filter/view-filter.module';
import { ViewModule } from 'src/engine/metadata-modules/view/view.module';
+import { RecordShareModule } from 'src/engine/record-share/record-share.module';
import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
@Module({
@@ -45,6 +46,7 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache
UsageModule,
MetricsModule,
RecordPositionModule,
+ RecordShareModule,
RecordTransformerModule,
FeatureFlagModule,
WorkspaceCacheModule,
diff --git a/packages/twenty-server/src/engine/api/common/types/common-query-args.type.ts b/packages/twenty-server/src/engine/api/common/types/common-query-args.type.ts
index ddb5c451efb..77c24514cc9 100644
--- a/packages/twenty-server/src/engine/api/common/types/common-query-args.type.ts
+++ b/packages/twenty-server/src/engine/api/common/types/common-query-args.type.ts
@@ -13,6 +13,7 @@ import {
type CommonSelectedFields,
type CommonSelectedFieldsResult,
} from 'src/engine/api/common/types/common-selected-fields-result.type';
+import { type ShareWithInput } from 'src/engine/record-share/types/share-with-input.type';
export enum CommonQueryNames {
FIND_ONE = 'findOne',
@@ -56,11 +57,13 @@ export interface FindManyQueryArgs {
export interface CreateManyQueryArgs {
data: Partial<ObjectRecord>[];
upsert?: boolean;
+ shareWith?: ShareWithInput[];
}
export interface CreateOneQueryArgs {
data: Partial<ObjectRecord>;
upsert?: boolean;
+ shareWith?: ShareWithInput[];
}
export interface GroupByQueryArgs {
filter?: ObjectRecordFilter;
diff --git a/packages/twenty-server/src/engine/api/graphql/direct-execution/utils/assert-create-many-args.util.ts b/packages/twenty-server/src/engine/api/graphql/direct-execution/utils/assert-create-many-args.util.ts
index 280d0838d5c..217eb977d46 100644
--- a/packages/twenty-server/src/engine/api/graphql/direct-execution/utils/assert-create-many-args.util.ts
+++ b/packages/twenty-server/src/engine/api/graphql/direct-execution/utils/assert-create-many-args.util.ts
@@ -7,6 +7,7 @@ import {
GraphqlDirectExecutionExceptionCode,
} from 'src/engine/api/graphql/direct-execution/errors/graphql-direct-execution.exception';
import { STANDARD_ERROR_MESSAGE } from 'src/engine/api/common/common-query-runners/errors/standard-error-message.constant';
+import { assertShareWithArg } from 'src/engine/api/graphql/direct-execution/utils/assert-share-with-arg.util';
import { type CreateManyResolverArgs } from 'src/engine/api/graphql/workspace-resolver-builder/interfaces/workspace-resolvers-builder.interface';
export function assertCreateManyArgs(
@@ -21,7 +22,7 @@ export function assertCreateManyArgs(
}
const argKeys = Object.keys(args);
- const allowedKeys = new Set(['data', 'upsert']);
+ const allowedKeys = new Set(['data', 'upsert', 'shareWith']);
for (const key of argKeys) {
if (!allowedKeys.has(key)) {
@@ -48,4 +49,8 @@ export function assertCreateManyArgs(
{ userFriendlyMessage: STANDARD_ERROR_MESSAGE },
);
}
+
+ if ('shareWith' in args) {
+ assertShareWithArg(args.shareWith);
+ }
}
diff --git a/packages/twenty-server/src/engine/api/graphql/direct-execution/utils/assert-create-one-args.util.ts b/packages/twenty-server/src/engine/api/graphql/direct-execution/utils/assert-create-one-args.util.ts
index d5e2e9f3361..a3eda770b71 100644
--- a/packages/twenty-server/src/engine/api/graphql/direct-execution/utils/assert-create-one-args.util.ts
+++ b/packages/twenty-server/src/engine/api/graphql/direct-execution/utils/assert-create-one-args.util.ts
@@ -7,6 +7,7 @@ import {
GraphqlDirectExecutionExceptionCode,
} from 'src/engine/api/graphql/direct-execution/errors/graphql-direct-execution.exception';
import { STANDARD_ERROR_MESSAGE } from 'src/engine/api/common/common-query-runners/errors/standard-error-message.constant';
+import { assertShareWithArg } from 'src/engine/api/graphql/direct-execution/utils/assert-share-with-arg.util';
import { type CreateOneResolverArgs } from 'src/engine/api/graphql/workspace-resolver-builder/interfaces/workspace-resolvers-builder.interface';
export function assertCreateOneArgs(
@@ -22,7 +23,7 @@ export function assertCreateOneArgs(
const argKeys = Object.keys(args);
- const allowedKeys = new Set(['data', 'upsert']);
+ const allowedKeys = new Set(['data', 'upsert', 'shareWith']);
for (const key of argKeys) {
if (!allowedKeys.has(key)) {
@@ -49,4 +50,8 @@ export function assertCreateOneArgs(
{ userFriendlyMessage: STANDARD_ERROR_MESSAGE },
);
}
+
+ if ('shareWith' in args) {
+ assertShareWithArg(args.shareWith);
+ }
}
diff --git a/packages/twenty-server/src/engine/api/graphql/direct-execution/utils/assert-share-with-arg.util.ts b/packages/twenty-server/src/engine/api/graphql/direct-execution/utils/assert-share-with-arg.util.ts
new file mode 100644
index 00000000000..1518379c342
--- /dev/null
+++ b/packages/twenty-server/src/engine/api/graphql/direct-execution/utils/assert-share-with-arg.util.ts
@@ -0,0 +1,46 @@
+import { isBoolean, isEnum, isObject, isString } from 'class-validator';
+
+import { RecordShareAccessLevel } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+
+import { STANDARD_ERROR_MESSAGE } from 'src/engine/api/common/common-query-runners/errors/standard-error-message.constant';
+import { type ShareWithInput } from 'src/engine/record-share/types/share-with-input.type';
+import {
+ GraphqlDirectExecutionException,
+ GraphqlDirectExecutionExceptionCode,
+} from 'src/engine/api/graphql/direct-execution/errors/graphql-direct-execution.exception';
+
+const ALLOWED_SHARE_WITH_ENTRY_KEYS = new Set([
+ 'workspaceMemberId',
+ 'roleId',
+ 'everyone',
+ 'accessLevel',
+]);
+
+const isOptionalString = (value: unknown): boolean =>
+ !isDefined(value) || isString(value);
+
+const isShareWithEntry = (entry: unknown): boolean =>
+ isObject(entry) &&
+ Object.keys(entry).every((key) => ALLOWED_SHARE_WITH_ENTRY_KEYS.has(key)) &&
+ isOptionalString(Reflect.get(entry, 'workspaceMemberId')) &&
+ isOptionalString(Reflect.get(entry, 'roleId')) &&
+ (!isDefined(Reflect.get(entry, 'everyone')) ||
+ isBoolean(Reflect.get(entry, 'everyone'))) &&
+ isEnum(Reflect.get(entry, 'accessLevel'), RecordShareAccessLevel);
+
+export function assertShareWithArg(
+ shareWith: unknown,
+): asserts shareWith is ShareWithInput[] | undefined {
+ if (!isDefined(shareWith)) {
+ return;
+ }
+
+ if (!Array.isArray(shareWith) || !shareWith.every(isShareWithEntry)) {
+ throw new GraphqlDirectExecutionException(
+ 'Invalid argument: "shareWith" must be an array of objects with an accessLevel and one of workspaceMemberId, roleId or everyone',
+ GraphqlDirectExecutionExceptionCode.INVALID_QUERY_INPUT,
+ { userFriendlyMessage: STANDARD_ERROR_MESSAGE },
+ );
+ }
+}
diff --git a/packages/twenty-server/src/engine/api/graphql/workspace-query-runner/utils/workspace-query-runner-graphql-api-exception-handler.util.ts b/packages/twenty-server/src/engine/api/graphql/workspace-query-runner/utils/workspace-query-runner-graphql-api-exception-handler.util.ts
index 622bb45031d..dc5240856b2 100644
--- a/packages/twenty-server/src/engine/api/graphql/workspace-query-runner/utils/workspace-query-runner-graphql-api-exception-handler.util.ts
+++ b/packages/twenty-server/src/engine/api/graphql/workspace-query-runner/utils/workspace-query-runner-graphql-api-exception-handler.util.ts
@@ -20,6 +20,8 @@ import { UsageLimitException } from 'src/engine/core-modules/usage-limit/excepti
import { usageLimitToGraphqlApiExceptionHandler } from 'src/engine/core-modules/usage-limit/utils/usage-limit-to-graphql-api-exception-handler.util';
import { PermissionsException } from 'src/engine/metadata-modules/permissions/permissions.exception';
import { permissionGraphqlApiExceptionHandler } from 'src/engine/metadata-modules/permissions/utils/permission-graphql-api-exception-handler.util';
+import { RecordShareException } from 'src/engine/record-share/record-share.exception';
+import { recordShareGraphqlApiExceptionHandler } from 'src/engine/record-share/utils/record-share-graphql-api-exception-handler.util';
import { TwentyOrmException } from 'src/engine/twenty-orm/exceptions/twenty-orm.exception';
import { twentyOrmGraphqlApiExceptionHandler } from 'src/engine/twenty-orm/utils/twenty-orm-graphql-api-exception-handler.util';
import { WorkflowQueryValidationException } from 'src/modules/workflow/common/exceptions/workflow-query-validation.exception';
@@ -45,6 +47,8 @@ export const workspaceQueryRunnerGraphqlApiExceptionHandler = (
return twentyOrmGraphqlApiExceptionHandler(error);
case error instanceof CommonQueryRunnerException:
return commonQueryRunnerToGraphqlApiExceptionHandler(error);
+ case error instanceof RecordShareException:
+ return recordShareGraphqlApiExceptionHandler(error);
case error instanceof AuthException:
return authGraphqlApiExceptionHandler(error);
case error instanceof ApiKeyException:
diff --git a/packages/twenty-server/src/engine/api/graphql/workspace-resolver-builder/interfaces/workspace-resolvers-builder.interface.ts b/packages/twenty-server/src/engine/api/graphql/workspace-resolver-builder/interfaces/workspace-resolvers-builder.interface.ts
index 3413c122a97..a06c5c44794 100644
--- a/packages/twenty-server/src/engine/api/graphql/workspace-resolver-builder/interfaces/workspace-resolvers-builder.interface.ts
+++ b/packages/twenty-server/src/engine/api/graphql/workspace-resolver-builder/interfaces/workspace-resolvers-builder.interface.ts
@@ -10,6 +10,7 @@ import {
type ObjectRecordOrderBy,
} from 'src/engine/api/graphql/workspace-query-builder/interfaces/object-record.interface';
+import { type ShareWithInput } from 'src/engine/record-share/types/share-with-input.type';
import { RESOLVER_METHOD_NAMES } from 'src/engine/api/graphql/workspace-resolver-builder/constants/resolver-method-names';
import { type workspaceResolverBuilderMethodNames } from 'src/engine/api/graphql/workspace-resolver-builder/factories/factories';
@@ -49,6 +50,7 @@ export interface CreateOneResolverArgs<
> {
data: Data;
upsert?: boolean;
+ shareWith?: ShareWithInput[];
}
export interface CreateManyResolverArgs<
@@ -56,6 +58,7 @@ export interface CreateManyResolverArgs<
> {
data: Data[];
upsert?: boolean;
+ shareWith?: ShareWithInput[];
}
export interface GroupByResolverArgs<Filter = ObjectRecordFilter> {
diff --git a/packages/twenty-server/src/engine/api/graphql/workspace-schema-builder/graphql-types/enum/index.ts b/packages/twenty-server/src/engine/api/graphql/workspace-schema-builder/graphql-types/enum/index.ts
index 31526754de0..bc7ac4ffb1a 100644
--- a/packages/twenty-server/src/engine/api/graphql/workspace-schema-builder/graphql-types/enum/index.ts
+++ b/packages/twenty-server/src/engine/api/graphql/workspace-schema-builder/graphql-types/enum/index.ts
@@ -1 +1,2 @@
export * from './order-by-direction.enum-type';
+export * from './record-share-access-level.enum-type';
diff --git a/packages/twenty-server/src/engine/api/graphql/workspace-schema-builder/graphql-types/enum/record-share-access-level.enum-type.ts b/packages/twenty-server/src/engine/api/graphql/workspace-schema-builder/graphql-types/enum/record-share-access-level.enum-type.ts
new file mode 100644
index 00000000000..841e13c4353
--- /dev/null
+++ b/packages/twenty-server/src/engine/api/graphql/workspace-schema-builder/graphql-types/enum/record-share-access-level.enum-type.ts
@@ -0,0 +1,20 @@
+import { GraphQLEnumType } from 'graphql';
+
+export const RecordShareAccessLevelType = new GraphQLEnumType({
+ name: 'RecordShareAccessLevel',
+ description: 'This enum is used to specify the access granted on a record',
+ values: {
+ READ: {
+ value: 'READ',
+ description: 'Read the record',
+ },
+ READ_WRITE: {
+ value: 'READ_WRITE',
+ description: 'Read and update the record',
+ },
+ FULL: {
+ value: 'FULL',
+ description: 'Read, update, delete, restore and destroy the record',
+ },
+ },
+});
diff --git a/packages/twenty-server/src/engine/api/graphql/workspace-schema-builder/graphql-types/input/share-with.input-type.ts b/packages/twenty-server/src/engine/api/graphql/workspace-schema-builder/graphql-types/input/share-with.input-type.ts
new file mode 100644
index 00000000000..94a269bc35d
--- /dev/null
+++ b/packages/twenty-server/src/engine/api/graphql/workspace-schema-builder/graphql-types/input/share-with.input-type.ts
@@ -0,0 +1,20 @@
+import {
+ GraphQLBoolean,
+ GraphQLInputObjectType,
+ GraphQLNonNull,
+} from 'graphql';
+
+import { RecordShareAccessLevelType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/enum/record-share-access-level.enum-type';
+import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
+
+export const ShareWithInputType = new GraphQLInputObjectType({
+ name: 'ShareWithInput',
+ description:
+ 'Grants access on the created record to exactly one of a workspace member, a role or everyone',
+ fields: {
+ workspaceMemberId: { type: UUIDScalarType },
+ roleId: { type: UUIDScalarType },
+ everyone: { type: GraphQLBoolean },
+ accessLevel: { type: new GraphQLNonNull(RecordShareAccessLevelType) },
+ },
+});
diff --git a/packages/twenty-server/src/engine/api/graphql/workspace-schema-builder/interfaces/param-metadata.interface.ts b/packages/twenty-server/src/engine/api/graphql/workspace-schema-builder/interfaces/param-metadata.interface.ts
index 531112adad7..e878f3cc35b 100644
--- a/packages/twenty-server/src/engine/api/graphql/workspace-schema-builder/interfaces/param-metadata.interface.ts
+++ b/packages/twenty-server/src/engine/api/graphql/workspace-schema-builder/interfaces/param-metadata.interface.ts
@@ -1,4 +1,8 @@
-import { type GraphQLScalarType } from 'graphql';
+import {
+ type GraphQLInputObjectType,
+ type GraphQLNonNull,
+ type GraphQLScalarType,
+} from 'graphql';
import {
type FieldMetadataType,
type FieldMetadataDefaultValue,
@@ -8,7 +12,10 @@ import { type GqlInputTypeDefinitionKind } from 'src/engine/api/graphql/workspac
export interface ArgMetadata {
kind?: GqlInputTypeDefinitionKind;
- type?: GraphQLScalarType;
+ type?:
+ | GraphQLScalarType
+ | GraphQLInputObjectType
+ | GraphQLNonNull<GraphQLInputObjectType>;
isNullable?: boolean;
isArray?: boolean;
defaultValue?: FieldMetadataDefaultValue<FieldMetadataType>;
diff --git a/packages/twenty-server/src/engine/api/graphql/workspace-schema-builder/utils/__tests__/get-resolver-args.spec.ts b/packages/twenty-server/src/engine/api/graphql/workspace-schema-builder/utils/__tests__/get-resolver-args.spec.ts
index 803c438d7ec..8999a333e61 100644
--- a/packages/twenty-server/src/engine/api/graphql/workspace-schema-builder/utils/__tests__/get-resolver-args.spec.ts
+++ b/packages/twenty-server/src/engine/api/graphql/workspace-schema-builder/utils/__tests__/get-resolver-args.spec.ts
@@ -1,8 +1,14 @@
-import { GraphQLBoolean, GraphQLInt, GraphQLString } from 'graphql';
+import {
+ GraphQLBoolean,
+ GraphQLInt,
+ GraphQLNonNull,
+ GraphQLString,
+} from 'graphql';
import { type WorkspaceResolverBuilderMethodNames } from 'src/engine/api/graphql/workspace-resolver-builder/interfaces/workspace-resolvers-builder.interface';
import { GqlInputTypeDefinitionKind } from 'src/engine/api/graphql/workspace-schema-builder/enums/gql-input-type-definition-kind.enum';
+import { ShareWithInputType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/input/share-with.input-type';
import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
import { getResolverArgs } from 'src/engine/api/graphql/workspace-schema-builder/utils/get-resolver-args.util';
@@ -35,6 +41,11 @@ describe('getResolverArgs', () => {
isNullable: true,
type: GraphQLBoolean,
},
+ shareWith: {
+ type: new GraphQLNonNull(ShareWithInputType),
+ isNullable: true,
+ isArray: true,
+ },
},
createOne: {
data: { kind: GqlInputTypeDefinitionKind.Create, isNullable: false },
@@ -43,6 +54,11 @@ describe('getResolverArgs', () => {
isNullable: true,
type: GraphQLBoolean,
},
+ shareWith: {
+ type: new GraphQLNonNull(ShareWithInputType),
+ isNullable: true,
+ isArray: true,
+ },
},
updateOne: {
id: { type: UUIDScalarType, isNullable: false },
diff --git a/packages/twenty-server/src/engine/api/graphql/workspace-schema-builder/utils/get-resolver-args.util.ts b/packages/twenty-server/src/engine/api/graphql/workspace-schema-builder/utils/get-resolver-args.util.ts
index 606e72c18c4..2d1e23cf0db 100644
--- a/packages/twenty-server/src/engine/api/graphql/workspace-schema-builder/utils/get-resolver-args.util.ts
+++ b/packages/twenty-server/src/engine/api/graphql/workspace-schema-builder/utils/get-resolver-args.util.ts
@@ -1,9 +1,15 @@
-import { GraphQLBoolean, GraphQLInt, GraphQLString } from 'graphql';
+import {
+ GraphQLBoolean,
+ GraphQLInt,
+ GraphQLNonNull,
+ GraphQLString,
+} from 'graphql';
import { type WorkspaceResolverBuilderMethodNames } from 'src/engine/api/graphql/workspace-resolver-builder/interfaces/workspace-resolvers-builder.interface';
import { type ArgMetadata } from 'src/engine/api/graphql/workspace-schema-builder/interfaces/param-metadata.interface';
import { GqlInputTypeDefinitionKind } from 'src/engine/api/graphql/workspace-schema-builder/enums/gql-input-type-definition-kind.enum';
+import { ShareWithInputType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/input/share-with.input-type';
import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
export const getResolverArgs = (
@@ -62,6 +68,11 @@ export const getResolverArgs = (
isNullable: true,
isArray: false,
},
+ shareWith: {
+ type: new GraphQLNonNull(ShareWithInputType),
+ isNullable: true,
+ isArray: true,
+ },
};
case 'createOne':
return {
@@ -74,6 +85,11 @@ export const getResolverArgs = (
isNullable: true,
isArray: false,
},
+ shareWith: {
+ type: new GraphQLNonNull(ShareWithInputType),
+ isNullable: true,
+ isArray: true,
+ },
};
case 'updateOne':
return {
diff --git a/packages/twenty-server/src/engine/api/rest/utils/workspace-query-runner-rest-api-exception-handler.util.ts b/packages/twenty-server/src/engine/api/rest/utils/workspace-query-runner-rest-api-exception-handler.util.ts
index c1ba010f466..94989a96598 100644
--- a/packages/twenty-server/src/engine/api/rest/utils/workspace-query-runner-rest-api-exception-handler.util.ts
+++ b/packages/twenty-server/src/engine/api/rest/utils/workspace-query-runner-rest-api-exception-handler.util.ts
@@ -6,6 +6,8 @@ import { CommonQueryRunnerException } from 'src/engine/api/common/common-query-r
import { commonQueryRunnerToRestApiExceptionHandler } from 'src/engine/api/common/common-query-runners/utils/common-query-runner-to-rest-api-exception-handler.util';
import { RestInputRequestParserException } from 'src/engine/api/rest/input-request-parsers/rest-input-request-parser.exception';
import { ThrottlerException } from 'src/engine/core-modules/throttler/throttler.exception';
+import { RecordShareException } from 'src/engine/record-share/record-share.exception';
+import { recordShareRestApiExceptionHandler } from 'src/engine/record-share/utils/record-share-rest-api-exception-handler.util';
import { throttlerToRestApiExceptionHandler } from 'src/engine/core-modules/throttler/utils/throttler-to-rest-api-exception-handler.util';
import { UsageLimitException } from 'src/engine/core-modules/usage-limit/exceptions/usage-limit.exception';
import { usageLimitToRestApiExceptionHandler } from 'src/engine/core-modules/usage-limit/utils/usage-limit-to-rest-api-exception-handler.util';
@@ -22,6 +24,8 @@ export const workspaceQueryRunnerRestApiExceptionHandler = (
switch (true) {
case error instanceof CommonQueryRunnerException:
return commonQueryRunnerToRestApiExceptionHandler(error);
+ case error instanceof RecordShareException:
+ return recordShareRestApiExceptionHandler(error);
case error instanceof RestInputRequestParserException:
throw new BadRequestException(error.message);
case error instanceof UsageLimitException:
diff --git a/packages/twenty-server/src/engine/core-modules/record-crud/services/create-many-records.service.ts b/packages/twenty-server/src/engine/core-modules/record-crud/services/create-many-records.service.ts
index 9c4bba5f85b..03f0436c608 100644
--- a/packages/twenty-server/src/engine/core-modules/record-crud/services/create-many-records.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/record-crud/services/create-many-records.service.ts
@@ -24,8 +24,13 @@ export class CreateManyRecordsService {
) {}
async execute(params: CreateManyRecordsParams): Promise<ToolOutput> {
- const { objectName, objectRecords, authContext, rolePermissionConfig } =
- params;
+ const {
+ objectName,
+ objectRecords,
+ authContext,
+ rolePermissionConfig,
+ shareWith,
+ } = params;
try {
const {
@@ -64,6 +69,7 @@ export class CreateManyRecordsService {
await this.commonCreateManyRunner.execute(
{
data: cleanedRecords,
+ shareWith,
selectedFields,
},
queryRunnerContext,
diff --git a/packages/twenty-server/src/engine/core-modules/record-crud/services/create-record.service.ts b/packages/twenty-server/src/engine/core-modules/record-crud/services/create-record.service.ts
index aefb3f23e9a..c503e6844e6 100644
--- a/packages/twenty-server/src/engine/core-modules/record-crud/services/create-record.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/record-crud/services/create-record.service.ts
@@ -24,8 +24,13 @@ export class CreateRecordService {
) {}
async execute(params: CreateRecordParams): Promise<ToolOutput> {
- const { objectName, objectRecord, authContext, rolePermissionConfig } =
- params;
+ const {
+ objectName,
+ objectRecord,
+ authContext,
+ rolePermissionConfig,
+ shareWith,
+ } = params;
try {
const {
@@ -66,6 +71,7 @@ export class CreateRecordService {
await this.commonCreateOneRunner.execute(
{
data: dataWithActor,
+ shareWith,
selectedFields,
},
queryRunnerContext,
diff --git a/packages/twenty-server/src/engine/core-modules/record-crud/types/create-many-records-params.type.ts b/packages/twenty-server/src/engine/core-modules/record-crud/types/create-many-records-params.type.ts
index c3e3cf627a4..4f695c05d57 100644
--- a/packages/twenty-server/src/engine/core-modules/record-crud/types/create-many-records-params.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/record-crud/types/create-many-records-params.type.ts
@@ -1,5 +1,6 @@
import { type ActorMetadata } from 'twenty-shared/types';
+import { type ShareWithInput } from 'src/engine/record-share/types/share-with-input.type';
import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
import { type ObjectRecordProperties } from 'src/engine/core-modules/record-crud/types/object-record-properties.type';
import { type RolePermissionConfig } from 'src/engine/twenty-orm/types/role-permission-config';
@@ -11,4 +12,5 @@ export type CreateManyRecordsParams = {
rolePermissionConfig?: RolePermissionConfig;
createdBy?: ActorMetadata;
slimResponse?: boolean;
+ shareWith?: ShareWithInput[];
};
diff --git a/packages/twenty-server/src/engine/core-modules/record-crud/types/record-crud-input.type.ts b/packages/twenty-server/src/engine/core-modules/record-crud/types/record-crud-input.type.ts
index 496ec7a3e48..73678a0f190 100644
--- a/packages/twenty-server/src/engine/core-modules/record-crud/types/record-crud-input.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/record-crud/types/record-crud-input.type.ts
@@ -1,3 +1,4 @@
+import { type ShareWithInput } from 'src/engine/record-share/types/share-with-input.type';
import { type ObjectRecordOrderBy } from 'src/engine/api/graphql/workspace-query-builder/interfaces/object-record.interface';
import { type ObjectRecordProperties } from './object-record-properties.type';
@@ -6,6 +7,7 @@ export type CreateRecordInput = {
objectName: string;
objectRecord: ObjectRecordProperties;
upsert?: boolean;
+ shareWith?: ShareWithInput[];
};
export type UpdateRecordInput = {
diff --git a/packages/twenty-server/src/engine/record-share/record-share.exception.ts b/packages/twenty-server/src/engine/record-share/record-share.exception.ts
index 710d52e5e00..ae05adad3ae 100644
--- a/packages/twenty-server/src/engine/record-share/record-share.exception.ts
+++ b/packages/twenty-server/src/engine/record-share/record-share.exception.ts
@@ -1,12 +1,21 @@
+import { type MessageDescriptor } from '@lingui/core';
+
import { STANDARD_ERROR_MESSAGE } from 'src/engine/api/common/common-query-runners/errors/standard-error-message.constant';
import { CustomException } from 'src/utils/custom-exception';
export enum RecordShareExceptionCode {
+ INVALID_SHARE_WITH = 'INVALID_SHARE_WITH',
TRANSACTION_SCOPE_WORKSPACE_MISMATCH = 'TRANSACTION_SCOPE_WORKSPACE_MISMATCH',
}
export class RecordShareException extends CustomException<RecordShareExceptionCode> {
- constructor(message: string, code: RecordShareExceptionCode) {
- super(message, code, { userFriendlyMessage: STANDARD_ERROR_MESSAGE });
+ constructor(
+ message: string,
+ code: RecordShareExceptionCode,
+ { userFriendlyMessage }: { userFriendlyMessage?: MessageDescriptor } = {},
+ ) {
+ super(message, code, {
+ userFriendlyMessage: userFriendlyMessage ?? STANDARD_ERROR_MESSAGE,
+ });
}
}
diff --git a/packages/twenty-server/src/engine/record-share/record-share.module.ts b/packages/twenty-server/src/engine/record-share/record-share.module.ts
index 253406f701e..c52ac93a0c0 100644
--- a/packages/twenty-server/src/engine/record-share/record-share.module.ts
+++ b/packages/twenty-server/src/engine/record-share/record-share.module.ts
@@ -1,11 +1,13 @@
import { Module } from '@nestjs/common';
import { RecordShareService } from 'src/engine/record-share/services/record-share.service';
+import { ShareWithService } from 'src/engine/record-share/services/share-with.service';
import { TwentyOrmModule } from 'src/engine/twenty-orm/twenty-orm.module';
+import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
@Module({
- imports: [TwentyOrmModule],
- providers: [RecordShareService],
- exports: [RecordShareService],
+ imports: [TwentyOrmModule, WorkspaceCacheModule],
+ providers: [RecordShareService, ShareWithService],
+ exports: [RecordShareService, ShareWithService],
})
export class RecordShareModule {}
diff --git a/packages/twenty-server/src/engine/record-share/services/record-share.service.ts b/packages/twenty-server/src/engine/record-share/services/record-share.service.ts
index f94932f73b8..8bd09a73215 100644
--- a/packages/twenty-server/src/engine/record-share/services/record-share.service.ts
+++ b/packages/twenty-server/src/engine/record-share/services/record-share.service.ts
@@ -1,6 +1,7 @@
import { Injectable } from '@nestjs/common';
import { isDefined } from 'twenty-shared/utils';
+import { In } from 'typeorm';
import {
RecordShareException,
@@ -39,6 +40,26 @@ export class RecordShareService {
);
}
+ async deleteByRecordIds({
+ workspaceId,
+ objectMetadataId,
+ recordIds,
+ transactionScope,
+ }: {
+ workspaceId: string;
+ objectMetadataId: string;
+ recordIds: string[];
+ transactionScope?: WorkspaceTransactionScope;
+ }): Promise<void> {
+ if (recordIds.length === 0) {
+ return;
+ }
+
+ await this.withRepository({ workspaceId, transactionScope }, (repository) =>
+ repository.delete({ objectMetadataId, recordId: In(recordIds) }),
+ );
+ }
+
async deleteBySourceId({
workspaceId,
sourceId,
diff --git a/packages/twenty-server/src/engine/record-share/services/share-with.service.ts b/packages/twenty-server/src/engine/record-share/services/share-with.service.ts
new file mode 100644
index 00000000000..db22ff4e22d
--- /dev/null
+++ b/packages/twenty-server/src/engine/record-share/services/share-with.service.ts
@@ -0,0 +1,93 @@
+import { Injectable } from '@nestjs/common';
+
+import { isNonEmptyArray } from 'twenty-shared/utils';
+
+import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
+import { RecordShareService } from 'src/engine/record-share/services/record-share.service';
+import { type ShareWithInput } from 'src/engine/record-share/types/share-with-input.type';
+import { buildRecordShareInputsForCreatedRecords } from 'src/engine/record-share/utils/build-record-share-inputs-for-created-records.util';
+import { validateShareWithArgOrThrow } from 'src/engine/record-share/utils/validate-share-with-arg-or-throw.util';
+import { validateShareWithPrincipalsOrThrow } from 'src/engine/record-share/utils/validate-share-with-principals-or-throw.util';
+import { type WorkspaceTransactionScope } from 'src/engine/twenty-orm/types/workspace-transaction-scope.type';
+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+
+@Injectable()
+export class ShareWithService {
+ constructor(
+ private readonly recordShareService: RecordShareService,
+ private readonly workspaceCacheService: WorkspaceCacheService,
+ ) {}
+
+ async validateShareWithOrThrow({
+ authContext,
+ isRecordSharingEnabled,
+ shareWith,
+ }: {
+ authContext: WorkspaceAuthContext;
+ isRecordSharingEnabled: boolean;
+ shareWith?: ShareWithInput[] | null;
+ }): Promise<void> {
+ validateShareWithArgOrThrow({
+ authContext,
+ isRecordSharingEnabled,
+ shareWith,
+ });
+
+ if (!isNonEmptyArray(shareWith)) {
+ return;
+ }
+
+ const { flatWorkspaceMemberMaps, flatRoleMaps } =
+ await this.workspaceCacheService.getOrRecompute(
+ authContext.workspace.id,
+ ['flatWorkspaceMemberMaps', 'flatRoleMaps'],
+ );
+
+ validateShareWithPrincipalsOrThrow({
+ shareWith,
+ flatWorkspaceMemberMaps,
+ flatRoleMaps,
+ });
+ }
+
+ async insertRecordSharesForCreatedRecords({
+ authContext,
+ objectMetadataId,
+ recordIds,
+ apiKeyRoleMap,
+ isRecordSharingEnabled,
+ shareWith,
+ transactionScope,
+ }: {
+ authContext: WorkspaceAuthContext;
+ objectMetadataId: string;
+ recordIds: string[];
+ apiKeyRoleMap: Record<string, string>;
+ isRecordSharingEnabled: boolean;
+ shareWith?: ShareWithInput[] | null;
+ transactionScope?: WorkspaceTransactionScope;
+ }): Promise<void> {
+ const workspaceId = authContext.workspace.id;
+
+ // A hard-destroyed record leaves its rows behind, and a client may reuse its id
+ await this.recordShareService.deleteByRecordIds({
+ workspaceId,
+ objectMetadataId,
+ recordIds,
+ transactionScope,
+ });
+
+ await this.recordShareService.insertMany({
+ workspaceId,
+ recordShares: buildRecordShareInputsForCreatedRecords({
+ recordIds,
+ objectMetadataId,
+ authContext,
+ apiKeyRoleMap,
+ isRecordSharingEnabled,
+ shareWith,
+ }),
+ transactionScope,
+ });
+ }
+}
diff --git a/packages/twenty-server/src/engine/record-share/types/share-with-input.type.ts b/packages/twenty-server/src/engine/record-share/types/share-with-input.type.ts
new file mode 100644
index 00000000000..850b841565a
--- /dev/null
+++ b/packages/twenty-server/src/engine/record-share/types/share-with-input.type.ts
@@ -0,0 +1,8 @@
+import { type RecordShareAccessLevel } from 'twenty-shared/types';
+
+export type ShareWithInput = {
+ workspaceMemberId?: string;
+ roleId?: string;
+ everyone?: boolean;
+ accessLevel: RecordShareAccessLevel;
+};
diff --git a/packages/twenty-server/src/engine/record-share/utils/__tests__/build-record-share-inputs-for-created-records.util.spec.ts b/packages/twenty-server/src/engine/record-share/utils/__tests__/build-record-share-inputs-for-created-records.util.spec.ts
new file mode 100644
index 00000000000..6a7dea58a5d
--- /dev/null
+++ b/packages/twenty-server/src/engine/record-share/utils/__tests__/build-record-share-inputs-for-created-records.util.spec.ts
@@ -0,0 +1,366 @@
+import { EVERYONE_PRINCIPAL_ID } from 'twenty-shared/constants';
+import {
+ RecordShareAccessLevel,
+ RecordSharePrincipalType,
+ RecordShareRowCause,
+} from 'twenty-shared/types';
+
+import { buildRecordShareInputsForCreatedRecords } from 'src/engine/record-share/utils/build-record-share-inputs-for-created-records.util';
+import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
+
+const OBJECT_METADATA_ID = 'object-metadata-1';
+const WORKSPACE_MEMBER_ID = '20202020-0000-4000-8000-000000000001';
+const OTHER_WORKSPACE_MEMBER_ID = '20202020-0000-4000-8000-000000000002';
+const ROLE_ID = '20202020-0000-4000-8000-000000000003';
+const API_KEY_ROLE_ID = '20202020-0000-4000-8000-000000000004';
+const APPLICATION_ROLE_ID = '20202020-0000-4000-8000-000000000005';
+const API_KEY_ID = 'api-key-1';
+const APPLICATION_ID = 'application-1';
+
+const userAuthContext = {
+ type: 'user',
+ workspace: { id: 'workspace-1' },
+ workspaceMemberId: WORKSPACE_MEMBER_ID,
+} as unknown as WorkspaceAuthContext;
+
+const apiKeyAuthContext = {
+ type: 'apiKey',
+ workspace: { id: 'workspace-1' },
+ apiKey: { id: API_KEY_ID },
+} as unknown as WorkspaceAuthContext;
+
+const applicationAuthContext = {
+ type: 'application',
+ workspace: { id: 'workspace-1' },
+ application: { id: APPLICATION_ID, defaultRoleId: APPLICATION_ROLE_ID },
+} as unknown as WorkspaceAuthContext;
+
+const systemAuthContext = {
+ type: 'system',
+ workspace: { id: 'workspace-1' },
+} as unknown as WorkspaceAuthContext;
+
+const apiKeyRoleMap = { [API_KEY_ID]: API_KEY_ROLE_ID };
+
+const everyoneFullRowFor = (recordId: string) => ({
+ recordId,
+ objectMetadataId: OBJECT_METADATA_ID,
+ principalId: EVERYONE_PRINCIPAL_ID,
+ principalType: RecordSharePrincipalType.EVERYONE,
+ accessLevel: RecordShareAccessLevel.FULL,
+ rowCause: RecordShareRowCause.APPLICATION,
+ sourceId: OBJECT_METADATA_ID,
+});
+
+describe('buildRecordShareInputsForCreatedRecords', () => {
+ describe('with record sharing enabled', () => {
+ const isRecordSharingEnabled = true;
+
+ it('should give a user a FULL owner row per record', () => {
+ expect(
+ buildRecordShareInputsForCreatedRecords({
+ recordIds: ['record-1', 'record-2'],
+ objectMetadataId: OBJECT_METADATA_ID,
+ authContext: userAuthContext,
+ apiKeyRoleMap,
+ isRecordSharingEnabled,
+ }),
+ ).toEqual([
+ {
+ recordId: 'record-1',
+ objectMetadataId: OBJECT_METADATA_ID,
+ principalId: WORKSPACE_MEMBER_ID,
+ principalType: RecordSharePrincipalType.WORKSPACE_MEMBER,
+ accessLevel: RecordShareAccessLevel.FULL,
+ rowCause: RecordShareRowCause.OWNER,
+ sourceId: 'record-1',
+ },
+ {
+ recordId: 'record-2',
+ objectMetadataId: OBJECT_METADATA_ID,
+ principalId: WORKSPACE_MEMBER_ID,
+ principalType: RecordSharePrincipalType.WORKSPACE_MEMBER,
+ accessLevel: RecordShareAccessLevel.FULL,
+ rowCause: RecordShareRowCause.OWNER,
+ sourceId: 'record-2',
+ },
+ ]);
+ });
+
+ it('should add a MANUAL row sourced from the creating member for each shareWith entry', () => {
+ expect(
+ buildRecordShareInputsForCreatedRecords({
+ recordIds: ['record-1'],
+ objectMetadataId: OBJECT_METADATA_ID,
+ authContext: userAuthContext,
+ apiKeyRoleMap,
+ isRecordSharingEnabled,
+ shareWith: [
+ { roleId: ROLE_ID, accessLevel: RecordShareAccessLevel.READ },
+ {
+ workspaceMemberId: OTHER_WORKSPACE_MEMBER_ID,
+ accessLevel: RecordShareAccessLevel.READ_WRITE,
+ },
+ ],
+ }),
+ ).toEqual([
+ expect.objectContaining({ rowCause: RecordShareRowCause.OWNER }),
+ {
+ recordId: 'record-1',
+ objectMetadataId: OBJECT_METADATA_ID,
+ principalId: ROLE_ID,
+ principalType: RecordSharePrincipalType.ROLE,
+ accessLevel: RecordShareAccessLevel.READ,
+ rowCause: RecordShareRowCause.MANUAL,
+ sourceId: WORKSPACE_MEMBER_ID,
+ },
+ {
+ recordId: 'record-1',
+ objectMetadataId: OBJECT_METADATA_ID,
+ principalId: OTHER_WORKSPACE_MEMBER_ID,
+ principalType: RecordSharePrincipalType.WORKSPACE_MEMBER,
+ accessLevel: RecordShareAccessLevel.READ_WRITE,
+ rowCause: RecordShareRowCause.MANUAL,
+ sourceId: WORKSPACE_MEMBER_ID,
+ },
+ ]);
+ });
+
+ it('should give an api key a FULL row for its role next to MANUAL rows sourced from the record', () => {
+ expect(
+ buildRecordShareInputsForCreatedRecords({
+ recordIds: ['record-1'],
+ objectMetadataId: OBJECT_METADATA_ID,
+ authContext: apiKeyAuthContext,
+ apiKeyRoleMap,
+ isRecordSharingEnabled,
+ shareWith: [
+ { everyone: true, accessLevel: RecordShareAccessLevel.READ },
+ ],
+ }),
+ ).toEqual([
+ {
+ recordId: 'record-1',
+ objectMetadataId: OBJECT_METADATA_ID,
+ principalId: API_KEY_ROLE_ID,
+ principalType: RecordSharePrincipalType.ROLE,
+ accessLevel: RecordShareAccessLevel.FULL,
+ rowCause: RecordShareRowCause.MANUAL,
+ sourceId: 'record-1',
+ },
+ {
+ recordId: 'record-1',
+ objectMetadataId: OBJECT_METADATA_ID,
+ principalId: EVERYONE_PRINCIPAL_ID,
+ principalType: RecordSharePrincipalType.EVERYONE,
+ accessLevel: RecordShareAccessLevel.READ,
+ rowCause: RecordShareRowCause.MANUAL,
+ sourceId: 'record-1',
+ },
+ ]);
+ });
+
+ it('should write only the shareWith rows for an api key without a role', () => {
+ expect(
+ buildRecordShareInputsForCreatedRecords({
+ recordIds: ['record-1'],
+ objectMetadataId: OBJECT_METADATA_ID,
+ authContext: apiKeyAuthContext,
+ apiKeyRoleMap: {},
+ isRecordSharingEnabled,
+ shareWith: [
+ { everyone: true, accessLevel: RecordShareAccessLevel.READ },
+ ],
+ }),
+ ).toEqual([
+ expect.objectContaining({
+ principalId: EVERYONE_PRINCIPAL_ID,
+ accessLevel: RecordShareAccessLevel.READ,
+ }),
+ ]);
+ });
+
+ it('should give an application a FULL row for its default role next to APPLICATION rows sourced from the application', () => {
+ expect(
+ buildRecordShareInputsForCreatedRecords({
+ recordIds: ['record-1'],
+ objectMetadataId: OBJECT_METADATA_ID,
+ authContext: applicationAuthContext,
+ apiKeyRoleMap,
+ isRecordSharingEnabled,
+ shareWith: [
+ { roleId: ROLE_ID, accessLevel: RecordShareAccessLevel.FULL },
+ ],
+ }),
+ ).toEqual([
+ {
+ recordId: 'record-1',
+ objectMetadataId: OBJECT_METADATA_ID,
+ principalId: APPLICATION_ROLE_ID,
+ principalType: RecordSharePrincipalType.ROLE,
+ accessLevel: RecordShareAccessLevel.FULL,
+ rowCause: RecordShareRowCause.APPLICATION,
+ sourceId: APPLICATION_ID,
+ },
+ {
+ recordId: 'record-1',
+ objectMetadataId: OBJECT_METADATA_ID,
+ principalId: ROLE_ID,
+ principalType: RecordSharePrincipalType.ROLE,
+ accessLevel: RecordShareAccessLevel.FULL,
+ rowCause: RecordShareRowCause.APPLICATION,
+ sourceId: APPLICATION_ID,
+ },
+ ]);
+ });
+
+ it('should keep the creator role at FULL when shareWith names it at a lower level', () => {
+ expect(
+ buildRecordShareInputsForCreatedRecords({
+ recordIds: ['record-1'],
+ objectMetadataId: OBJECT_METADATA_ID,
+ authContext: applicationAuthContext,
+ apiKeyRoleMap,
+ isRecordSharingEnabled,
+ shareWith: [
+ {
+ roleId: APPLICATION_ROLE_ID,
+ accessLevel: RecordShareAccessLevel.READ,
+ },
+ ],
+ }),
+ ).toEqual([
+ {
+ recordId: 'record-1',
+ objectMetadataId: OBJECT_METADATA_ID,
+ principalId: APPLICATION_ROLE_ID,
+ principalType: RecordSharePrincipalType.ROLE,
+ accessLevel: RecordShareAccessLevel.FULL,
+ rowCause: RecordShareRowCause.APPLICATION,
+ sourceId: APPLICATION_ID,
+ },
+ ]);
+ });
+
+ it('should write no creator row for an application without a default role', () => {
+ expect(
+ buildRecordShareInputsForCreatedRecords({
+ recordIds: ['record-1'],
+ objectMetadataId: OBJECT_METADATA_ID,
+ authContext: {
+ ...applicationAuthContext,
+ application: { id: APPLICATION_ID, defaultRoleId: null },
+ } as unknown as WorkspaceAuthContext,
+ apiKeyRoleMap,
+ isRecordSharingEnabled,
+ shareWith: [
+ { roleId: ROLE_ID, accessLevel: RecordShareAccessLevel.FULL },
+ ],
+ }),
+ ).toEqual([expect.objectContaining({ principalId: ROLE_ID })]);
+ });
+
+ it('should write only the shareWith rows for a system caller', () => {
+ expect(
+ buildRecordShareInputsForCreatedRecords({
+ recordIds: ['record-1'],
+ objectMetadataId: OBJECT_METADATA_ID,
+ authContext: systemAuthContext,
+ apiKeyRoleMap,
+ isRecordSharingEnabled,
+ shareWith: [
+ { everyone: true, accessLevel: RecordShareAccessLevel.READ },
+ ],
+ }),
+ ).toEqual([
+ {
+ recordId: 'record-1',
+ objectMetadataId: OBJECT_METADATA_ID,
+ principalId: EVERYONE_PRINCIPAL_ID,
+ principalType: RecordSharePrincipalType.EVERYONE,
+ accessLevel: RecordShareAccessLevel.READ,
+ rowCause: RecordShareRowCause.MANUAL,
+ sourceId: 'record-1',
+ },
+ ]);
+ });
+ });
+
+ describe('with record sharing disabled', () => {
+ const isRecordSharingEnabled = false;
+
+ it('should give a user the FULL owner row and an EVERYONE FULL row, so the record stays open once the flag turns on', () => {
+ expect(
+ buildRecordShareInputsForCreatedRecords({
+ recordIds: ['record-1'],
+ objectMetadataId: OBJECT_METADATA_ID,
+ authContext: userAuthContext,
+ apiKeyRoleMap,
+ isRecordSharingEnabled,
+ shareWith: null,
+ }),
+ ).toEqual([
+ expect.objectContaining({
+ principalId: WORKSPACE_MEMBER_ID,
+ rowCause: RecordShareRowCause.OWNER,
+ }),
+ everyoneFullRowFor('record-1'),
+ ]);
+ });
+
+ it('should write one EVERYONE FULL row per record for an api key without shareWith', () => {
+ expect(
+ buildRecordShareInputsForCreatedRecords({
+ recordIds: ['record-1', 'record-2'],
+ objectMetadataId: OBJECT_METADATA_ID,
+ authContext: apiKeyAuthContext,
+ apiKeyRoleMap,
+ isRecordSharingEnabled,
+ }),
+ ).toEqual([
+ everyoneFullRowFor('record-1'),
+ everyoneFullRowFor('record-2'),
+ ]);
+ });
+
+ it('should write one EVERYONE FULL row for a system caller with an empty shareWith', () => {
+ expect(
+ buildRecordShareInputsForCreatedRecords({
+ recordIds: ['record-1'],
+ objectMetadataId: OBJECT_METADATA_ID,
+ authContext: systemAuthContext,
+ apiKeyRoleMap,
+ isRecordSharingEnabled,
+ shareWith: [],
+ }),
+ ).toEqual([everyoneFullRowFor('record-1')]);
+ });
+
+ it('should honour an explicit shareWith from an api key', () => {
+ expect(
+ buildRecordShareInputsForCreatedRecords({
+ recordIds: ['record-1'],
+ objectMetadataId: OBJECT_METADATA_ID,
+ authContext: apiKeyAuthContext,
+ apiKeyRoleMap,
+ isRecordSharingEnabled,
+ shareWith: [
+ {
+ workspaceMemberId: OTHER_WORKSPACE_MEMBER_ID,
+ accessLevel: RecordShareAccessLevel.READ,
+ },
+ ],
+ }),
+ ).toEqual([
+ expect.objectContaining({
+ principalId: API_KEY_ROLE_ID,
+ accessLevel: RecordShareAccessLevel.FULL,
+ }),
+ expect.objectContaining({
+ principalId: OTHER_WORKSPACE_MEMBER_ID,
+ accessLevel: RecordShareAccessLevel.READ,
+ }),
+ ]);
+ });
+ });
+});
diff --git a/packages/twenty-server/src/engine/record-share/utils/__tests__/validate-share-with-arg-or-throw.util.spec.ts b/packages/twenty-server/src/engine/record-share/utils/__tests__/validate-share-with-arg-or-throw.util.spec.ts
new file mode 100644
index 00000000000..e95f651f298
--- /dev/null
+++ b/packages/twenty-server/src/engine/record-share/utils/__tests__/validate-share-with-arg-or-throw.util.spec.ts
@@ -0,0 +1,194 @@
+import { RecordShareAccessLevel } from 'twenty-shared/types';
+
+import { validateShareWithArgOrThrow } from 'src/engine/record-share/utils/validate-share-with-arg-or-throw.util';
+import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
+
+const userAuthContext = {
+ type: 'user',
+ workspace: { id: 'workspace-1' },
+ workspaceMemberId: 'workspace-member-1',
+} as unknown as WorkspaceAuthContext;
+
+const apiKeyAuthContext = {
+ type: 'apiKey',
+ workspace: { id: 'workspace-1' },
+ apiKey: { id: 'api-key-1' },
+} as unknown as WorkspaceAuthContext;
+
+const systemAuthContext = {
+ type: 'system',
+ workspace: { id: 'workspace-1' },
+} as unknown as WorkspaceAuthContext;
+
+const OTHER_WORKSPACE_MEMBER_ID = '20202020-0000-4000-8000-000000000002';
+const ROLE_ID = '20202020-0000-4000-8000-000000000003';
+const SHARE_WITH_REQUIRED_MESSAGE =
+ 'Creating a record of a private object requires the shareWith argument';
+
+describe('validateShareWithArgOrThrow', () => {
+ describe('with record sharing enabled', () => {
+ const isRecordSharingEnabled = true;
+
+ it('should accept a user without shareWith', () => {
+ expect(() =>
+ validateShareWithArgOrThrow({
+ authContext: userAuthContext,
+ isRecordSharingEnabled,
+ }),
+ ).not.toThrow();
+ });
+
+ it('should reject an api key without shareWith', () => {
+ expect(() =>
+ validateShareWithArgOrThrow({
+ authContext: apiKeyAuthContext,
+ isRecordSharingEnabled,
+ }),
+ ).toThrow(SHARE_WITH_REQUIRED_MESSAGE);
+ });
+
+ it('should reject an api key with an empty shareWith', () => {
+ expect(() =>
+ validateShareWithArgOrThrow({
+ authContext: apiKeyAuthContext,
+ isRecordSharingEnabled,
+ shareWith: [],
+ }),
+ ).toThrow(SHARE_WITH_REQUIRED_MESSAGE);
+ });
+
+ it('should reject a system caller without shareWith', () => {
+ expect(() =>
+ validateShareWithArgOrThrow({
+ authContext: systemAuthContext,
+ isRecordSharingEnabled,
+ }),
+ ).toThrow(SHARE_WITH_REQUIRED_MESSAGE);
+ });
+
+ it('should accept an api key with one valid entry', () => {
+ expect(() =>
+ validateShareWithArgOrThrow({
+ authContext: apiKeyAuthContext,
+ isRecordSharingEnabled,
+ shareWith: [
+ { everyone: true, accessLevel: RecordShareAccessLevel.READ },
+ ],
+ }),
+ ).not.toThrow();
+ });
+ });
+
+ describe('with record sharing disabled', () => {
+ const isRecordSharingEnabled = false;
+
+ it('should accept an api key without shareWith', () => {
+ expect(() =>
+ validateShareWithArgOrThrow({
+ authContext: apiKeyAuthContext,
+ isRecordSharingEnabled,
+ }),
+ ).not.toThrow();
+ });
+
+ it('should accept a system caller with an empty shareWith', () => {
+ expect(() =>
+ validateShareWithArgOrThrow({
+ authContext: systemAuthContext,
+ isRecordSharingEnabled,
+ shareWith: [],
+ }),
+ ).not.toThrow();
+ });
+
+ it('should still reject a malformed entry', () => {
+ expect(() =>
+ validateShareWithArgOrThrow({
+ authContext: apiKeyAuthContext,
+ isRecordSharingEnabled,
+ shareWith: [
+ { everyone: false, accessLevel: RecordShareAccessLevel.READ },
+ ],
+ }),
+ ).toThrow(
+ 'Each shareWith entry must target exactly one of workspaceMemberId, roleId or everyone',
+ );
+ });
+ });
+
+ it('should treat a null shareWith as omitted for a user', () => {
+ expect(() =>
+ validateShareWithArgOrThrow({
+ authContext: userAuthContext,
+ isRecordSharingEnabled: true,
+ shareWith: null,
+ }),
+ ).not.toThrow();
+ });
+
+ it('should reject the same principal named twice', () => {
+ expect(() =>
+ validateShareWithArgOrThrow({
+ authContext: userAuthContext,
+ isRecordSharingEnabled: true,
+ shareWith: [
+ {
+ workspaceMemberId: OTHER_WORKSPACE_MEMBER_ID,
+ accessLevel: RecordShareAccessLevel.READ,
+ },
+ {
+ workspaceMemberId: OTHER_WORKSPACE_MEMBER_ID,
+ accessLevel: RecordShareAccessLevel.FULL,
+ },
+ ],
+ }),
+ ).toThrow('shareWith names the same principal more than once');
+ });
+
+ it('should reject an entry targeting no principal', () => {
+ expect(() =>
+ validateShareWithArgOrThrow({
+ authContext: userAuthContext,
+ isRecordSharingEnabled: true,
+ shareWith: [
+ { everyone: false, accessLevel: RecordShareAccessLevel.READ },
+ ],
+ }),
+ ).toThrow(
+ 'Each shareWith entry must target exactly one of workspaceMemberId, roleId or everyone',
+ );
+ });
+
+ it('should reject a workspaceMemberId that is not a uuid', () => {
+ expect(() =>
+ validateShareWithArgOrThrow({
+ authContext: userAuthContext,
+ isRecordSharingEnabled: true,
+ shareWith: [
+ {
+ workspaceMemberId: 'not-a-uuid',
+ accessLevel: RecordShareAccessLevel.READ,
+ },
+ ],
+ }),
+ ).toThrow('shareWith principal "not-a-uuid" is not a valid UUID');
+ });
+
+ it('should reject an entry targeting two principals even for a user', () => {
+ expect(() =>
+ validateShareWithArgOrThrow({
+ authContext: userAuthContext,
+ isRecordSharingEnabled: true,
+ shareWith: [
+ {
+ workspaceMemberId: OTHER_WORKSPACE_MEMBER_ID,
+ roleId: ROLE_ID,
+ accessLevel: RecordShareAccessLevel.READ,
+ },
+ ],
+ }),
+ ).toThrow(
+ 'Each shareWith entry must target exactly one of workspaceMemberId, roleId or everyone',
+ );
+ });
+});
diff --git a/packages/twenty-server/src/engine/record-share/utils/__tests__/validate-share-with-principals-or-throw.util.spec.ts b/packages/twenty-server/src/engine/record-share/utils/__tests__/validate-share-with-principals-or-throw.util.spec.ts
new file mode 100644
index 00000000000..1b651a9f69a
--- /dev/null
+++ b/packages/twenty-server/src/engine/record-share/utils/__tests__/validate-share-with-principals-or-throw.util.spec.ts
@@ -0,0 +1,86 @@
+import { RecordShareAccessLevel } from 'twenty-shared/types';
+
+import { validateShareWithPrincipalsOrThrow } from 'src/engine/record-share/utils/validate-share-with-principals-or-throw.util';
+import { type FlatWorkspaceMemberMaps } from 'src/engine/core-modules/user/types/flat-workspace-member-maps.type';
+import { type FlatRoleMaps } from 'src/engine/metadata-modules/flat-role/types/flat-role-maps.type';
+
+const WORKSPACE_MEMBER_ID = '20202020-0000-4000-8000-000000000001';
+const ROLE_ID = '20202020-0000-4000-8000-000000000002';
+const DELETED_WORKSPACE_MEMBER_ID = '20202020-0000-4000-8000-000000000003';
+const UNKNOWN_ID = '20202020-0000-4000-8000-000000000009';
+
+const flatWorkspaceMemberMaps = {
+ byId: {
+ [WORKSPACE_MEMBER_ID]: { id: WORKSPACE_MEMBER_ID },
+ [DELETED_WORKSPACE_MEMBER_ID]: {
+ id: DELETED_WORKSPACE_MEMBER_ID,
+ deletedAt: '2026-09-01T00:00:00.000Z',
+ },
+ },
+ idByUserId: {},
+} as unknown as FlatWorkspaceMemberMaps;
+
+const flatRoleMaps = {
+ universalIdentifierById: { [ROLE_ID]: 'role-universal-identifier' },
+} as unknown as FlatRoleMaps;
+
+describe('validateShareWithPrincipalsOrThrow', () => {
+ it('should accept a member, a role and everyone that belong to the workspace', () => {
+ expect(() =>
+ validateShareWithPrincipalsOrThrow({
+ shareWith: [
+ {
+ workspaceMemberId: WORKSPACE_MEMBER_ID,
+ accessLevel: RecordShareAccessLevel.READ,
+ },
+ { roleId: ROLE_ID, accessLevel: RecordShareAccessLevel.READ_WRITE },
+ { everyone: true, accessLevel: RecordShareAccessLevel.READ },
+ ],
+ flatWorkspaceMemberMaps,
+ flatRoleMaps,
+ }),
+ ).not.toThrow();
+ });
+
+ it('should reject a workspace member of another workspace', () => {
+ expect(() =>
+ validateShareWithPrincipalsOrThrow({
+ shareWith: [
+ {
+ workspaceMemberId: UNKNOWN_ID,
+ accessLevel: RecordShareAccessLevel.READ,
+ },
+ ],
+ flatWorkspaceMemberMaps,
+ flatRoleMaps,
+ }),
+ ).toThrow('workspace member that does not belong to this workspace');
+ });
+
+ it('should reject a soft-deleted workspace member', () => {
+ expect(() =>
+ validateShareWithPrincipalsOrThrow({
+ shareWith: [
+ {
+ workspaceMemberId: DELETED_WORKSPACE_MEMBER_ID,
+ accessLevel: RecordShareAccessLevel.READ,
+ },
+ ],
+ flatWorkspaceMemberMaps,
+ flatRoleMaps,
+ }),
+ ).toThrow('workspace member that does not belong to this workspace');
+ });
+
+ it('should reject a role of another workspace', () => {
+ expect(() =>
+ validateShareWithPrincipalsOrThrow({
+ shareWith: [
+ { roleId: UNKNOWN_ID, accessLevel: RecordShareAccessLevel.READ },
+ ],
+ flatWorkspaceMemberMaps,
+ flatRoleMaps,
+ }),
+ ).toThrow('role that does not belong to this workspace');
+ });
+});
diff --git a/packages/twenty-server/src/engine/record-share/utils/build-record-share-inputs-for-created-records.util.ts b/packages/twenty-server/src/engine/record-share/utils/build-record-share-inputs-for-created-records.util.ts
new file mode 100644
index 00000000000..2dd6407cbb7
--- /dev/null
+++ b/packages/twenty-server/src/engine/record-share/utils/build-record-share-inputs-for-created-records.util.ts
@@ -0,0 +1,169 @@
+import { EVERYONE_PRINCIPAL_ID } from 'twenty-shared/constants';
+import {
+ RecordShareAccessLevel,
+ RecordSharePrincipalType,
+ RecordShareRowCause,
+} from 'twenty-shared/types';
+import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';
+
+import { isApiKeyAuthContext } from 'src/engine/core-modules/auth/guards/is-api-key-auth-context.guard';
+import { isApplicationAuthContext } from 'src/engine/core-modules/auth/guards/is-application-auth-context.guard';
+import { isUserAuthContext } from 'src/engine/core-modules/auth/guards/is-user-auth-context.guard';
+import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
+import { type RecordShareInput } from 'src/engine/record-share/types/record-share-input.type';
+import { type ShareWithInput } from 'src/engine/record-share/types/share-with-input.type';
+import { resolveShareWithPrincipalOrThrow } from 'src/engine/record-share/utils/resolve-share-with-principal-or-throw.util';
+
+type RecordShareInputForRecord = Omit<
+ RecordShareInput,
+ 'recordId' | 'objectMetadataId'
+>;
+
+const resolveShareWithRowOrigin = ({
+ authContext,
+ recordId,
+}: {
+ authContext: WorkspaceAuthContext;
+ recordId: string;
+}): Pick<RecordShareInput, 'rowCause' | 'sourceId'> => {
+ if (isUserAuthContext(authContext)) {
+ return {
+ rowCause: RecordShareRowCause.MANUAL,
+ sourceId: authContext.workspaceMemberId,
+ };
+ }
+
+ if (isApplicationAuthContext(authContext)) {
+ return {
+ rowCause: RecordShareRowCause.APPLICATION,
+ sourceId: authContext.application.id,
+ };
+ }
+
+ return { rowCause: RecordShareRowCause.MANUAL, sourceId: recordId };
+};
+
+const resolveCreatorRoleId = ({
+ authContext,
+ apiKeyRoleMap,
+}: {
+ authContext: WorkspaceAuthContext;
+ apiKeyRoleMap: Record<string, string>;
+}): string | null | undefined => {
+ if (isApplicationAuthContext(authContext)) {
+ return authContext.application.defaultRoleId;
+ }
+
+ if (isApiKeyAuthContext(authContext)) {
+ return apiKeyRoleMap[authContext.apiKey.id];
+ }
+
+ return undefined;
+};
+
+const buildCreatorRows = ({
+ authContext,
+ apiKeyRoleMap,
+ recordId,
+ shareWithPrincipals,
+}: {
+ authContext: WorkspaceAuthContext;
+ apiKeyRoleMap: Record<string, string>;
+ recordId: string;
+ shareWithPrincipals: Pick<RecordShareInput, 'principalId'>[];
+}): RecordShareInputForRecord[] => {
+ if (isUserAuthContext(authContext)) {
+ return [
+ {
+ principalId: authContext.workspaceMemberId,
+ principalType: RecordSharePrincipalType.WORKSPACE_MEMBER,
+ accessLevel: RecordShareAccessLevel.FULL,
+ rowCause: RecordShareRowCause.OWNER,
+ sourceId: recordId,
+ },
+ ];
+ }
+
+ const creatorRoleId = resolveCreatorRoleId({ authContext, apiKeyRoleMap });
+
+ if (
+ !isDefined(creatorRoleId) ||
+ shareWithPrincipals.some(
+ (shareWithPrincipal) => shareWithPrincipal.principalId === creatorRoleId,
+ )
+ ) {
+ return [];
+ }
+
+ return [
+ {
+ principalId: creatorRoleId,
+ principalType: RecordSharePrincipalType.ROLE,
+ accessLevel: RecordShareAccessLevel.FULL,
+ ...resolveShareWithRowOrigin({ authContext, recordId }),
+ },
+ ];
+};
+
+export const buildRecordShareInputsForCreatedRecords = ({
+ recordIds,
+ objectMetadataId,
+ authContext,
+ apiKeyRoleMap,
+ isRecordSharingEnabled,
+ shareWith,
+}: {
+ recordIds: string[];
+ objectMetadataId: string;
+ authContext: WorkspaceAuthContext;
+ apiKeyRoleMap: Record<string, string>;
+ isRecordSharingEnabled: boolean;
+ shareWith?: ShareWithInput[] | null;
+}): RecordShareInput[] => {
+ const shareWithEntries = shareWith ?? [];
+ // A record created while the flag is off is readable by everyone today and
+ // must stay so once the flag turns on, whoever created it
+ const everyoneFullRows =
+ !isRecordSharingEnabled && !isNonEmptyArray(shareWithEntries)
+ ? recordIds.map((recordId) => ({
+ recordId,
+ objectMetadataId,
+ principalId: EVERYONE_PRINCIPAL_ID,
+ principalType: RecordSharePrincipalType.EVERYONE,
+ accessLevel: RecordShareAccessLevel.FULL,
+ rowCause: RecordShareRowCause.APPLICATION,
+ sourceId: objectMetadataId,
+ }))
+ : [];
+
+ if (!isUserAuthContext(authContext) && isNonEmptyArray(everyoneFullRows)) {
+ return everyoneFullRows;
+ }
+
+ const creatorRoleId = resolveCreatorRoleId({ authContext, apiKeyRoleMap });
+ const shareWithPrincipals = shareWithEntries
+ .map(resolveShareWithPrincipalOrThrow)
+ .map((shareWithPrincipal) =>
+ shareWithPrincipal.principalId === creatorRoleId
+ ? { ...shareWithPrincipal, accessLevel: RecordShareAccessLevel.FULL }
+ : shareWithPrincipal,
+ );
+
+ return [
+ ...recordIds.flatMap((recordId) => [
+ ...buildCreatorRows({
+ authContext,
+ apiKeyRoleMap,
+ recordId,
+ shareWithPrincipals,
+ }).map((creatorRow) => ({ recordId, objectMetadataId, ...creatorRow })),
+ ...shareWithPrincipals.map((shareWithPrincipal) => ({
+ recordId,
+ objectMetadataId,
+ ...shareWithPrincipal,
+ ...resolveShareWithRowOrigin({ authContext, recordId }),
+ })),
+ ]),
+ ...everyoneFullRows,
+ ];
+};
diff --git a/packages/twenty-server/src/engine/record-share/utils/record-share-graphql-api-exception-handler.util.ts b/packages/twenty-server/src/engine/record-share/utils/record-share-graphql-api-exception-handler.util.ts
new file mode 100644
index 00000000000..79da7fb5953
--- /dev/null
+++ b/packages/twenty-server/src/engine/record-share/utils/record-share-graphql-api-exception-handler.util.ts
@@ -0,0 +1,24 @@
+import { assertUnreachable } from 'twenty-shared/utils';
+
+import {
+ InternalServerError,
+ UserInputError,
+} from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
+import {
+ type RecordShareException,
+ RecordShareExceptionCode,
+} from 'src/engine/record-share/record-share.exception';
+
+export const recordShareGraphqlApiExceptionHandler = (
+ error: RecordShareException,
+) => {
+ switch (error.code) {
+ case RecordShareExceptionCode.INVALID_SHARE_WITH:
+ throw new UserInputError(error);
+ case RecordShareExceptionCode.TRANSACTION_SCOPE_WORKSPACE_MISMATCH:
+ throw new InternalServerError(error);
+ default: {
+ return assertUnreachable(error.code);
+ }
+ }
+};
diff --git a/packages/twenty-server/src/engine/record-share/utils/record-share-rest-api-exception-handler.util.ts b/packages/twenty-server/src/engine/record-share/utils/record-share-rest-api-exception-handler.util.ts
new file mode 100644
index 00000000000..35e1cfb2f9a
--- /dev/null
+++ b/packages/twenty-server/src/engine/record-share/utils/record-share-rest-api-exception-handler.util.ts
@@ -0,0 +1,25 @@
+import {
+ BadRequestException,
+ InternalServerErrorException,
+} from '@nestjs/common';
+
+import { assertUnreachable } from 'twenty-shared/utils';
+
+import {
+ type RecordShareException,
+ RecordShareExceptionCode,
+} from 'src/engine/record-share/record-share.exception';
+
+export const recordShareRestApiExceptionHandler = (
+ error: RecordShareException,
+): never => {
+ switch (error.code) {
+ case RecordShareExceptionCode.INVALID_SHARE_WITH:
+ throw new BadRequestException(error.message);
+ case RecordShareExceptionCode.TRANSACTION_SCOPE_WORKSPACE_MISMATCH:
+ throw new InternalServerErrorException(error.message);
+ default: {
+ return assertUnreachable(error.code);
+ }
+ }
+};
diff --git a/packages/twenty-server/src/engine/record-share/utils/resolve-share-with-principal-or-throw.util.ts b/packages/twenty-server/src/engine/record-share/utils/resolve-share-with-principal-or-throw.util.ts
new file mode 100644
index 00000000000..5b169612b02
--- /dev/null
+++ b/packages/twenty-server/src/engine/record-share/utils/resolve-share-with-principal-or-throw.util.ts
@@ -0,0 +1,68 @@
+import { msg } from '@lingui/core/macro';
+import { EVERYONE_PRINCIPAL_ID } from 'twenty-shared/constants';
+import { RecordSharePrincipalType } from 'twenty-shared/types';
+import { isDefined, isValidUuid } from 'twenty-shared/utils';
+
+import {
+ RecordShareException,
+ RecordShareExceptionCode,
+} from 'src/engine/record-share/record-share.exception';
+import { type RecordShareInput } from 'src/engine/record-share/types/record-share-input.type';
+import { type ShareWithInput } from 'src/engine/record-share/types/share-with-input.type';
+
+const buildSingleTargetException = () =>
+ new RecordShareException(
+ 'Each shareWith entry must target exactly one of workspaceMemberId, roleId or everyone',
+ RecordShareExceptionCode.INVALID_SHARE_WITH,
+ {
+ userFriendlyMessage: msg`Each shareWith entry must target exactly one of workspaceMemberId, roleId or everyone`,
+ },
+ );
+
+export const resolveShareWithPrincipalOrThrow = (
+ shareWithEntry: ShareWithInput | null,
+): Pick<RecordShareInput, 'principalId' | 'principalType' | 'accessLevel'> => {
+ if (!isDefined(shareWithEntry)) {
+ throw buildSingleTargetException();
+ }
+
+ const principals = [
+ isDefined(shareWithEntry.workspaceMemberId)
+ ? {
+ principalId: shareWithEntry.workspaceMemberId,
+ principalType: RecordSharePrincipalType.WORKSPACE_MEMBER,
+ }
+ : undefined,
+ isDefined(shareWithEntry.roleId)
+ ? {
+ principalId: shareWithEntry.roleId,
+ principalType: RecordSharePrincipalType.ROLE,
+ }
+ : undefined,
+ shareWithEntry.everyone
+ ? {
+ principalId: EVERYONE_PRINCIPAL_ID,
+ principalType: RecordSharePrincipalType.EVERYONE,
+ }
+ : undefined,
+ ].filter(isDefined);
+
+ if (principals.length !== 1) {
+ throw buildSingleTargetException();
+ }
+
+ const [principal] = principals;
+
+ if (
+ principal.principalType !== RecordSharePrincipalType.EVERYONE &&
+ !isValidUuid(principal.principalId)
+ ) {
+ throw new RecordShareException(
+ `shareWith principal "${principal.principalId}" is not a valid UUID`,
+ RecordShareExceptionCode.INVALID_SHARE_WITH,
+ { userFriendlyMessage: msg`Invalid UUID format.` },
+ );
+ }
+
+ return { ...principal, accessLevel: shareWithEntry.accessLevel };
+};
diff --git a/packages/twenty-server/src/engine/record-share/utils/validate-share-with-arg-or-throw.util.ts b/packages/twenty-server/src/engine/record-share/utils/validate-share-with-arg-or-throw.util.ts
new file mode 100644
index 00000000000..ffbac1a688a
--- /dev/null
+++ b/packages/twenty-server/src/engine/record-share/utils/validate-share-with-arg-or-throw.util.ts
@@ -0,0 +1,50 @@
+import { msg } from '@lingui/core/macro';
+import { isNonEmptyArray } from 'twenty-shared/utils';
+
+import { isUserAuthContext } from 'src/engine/core-modules/auth/guards/is-user-auth-context.guard';
+import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
+import {
+ RecordShareException,
+ RecordShareExceptionCode,
+} from 'src/engine/record-share/record-share.exception';
+import { type ShareWithInput } from 'src/engine/record-share/types/share-with-input.type';
+import { resolveShareWithPrincipalOrThrow } from 'src/engine/record-share/utils/resolve-share-with-principal-or-throw.util';
+
+export const validateShareWithArgOrThrow = ({
+ authContext,
+ isRecordSharingEnabled,
+ shareWith,
+}: {
+ authContext: WorkspaceAuthContext;
+ isRecordSharingEnabled: boolean;
+ shareWith?: ShareWithInput[] | null;
+}): void => {
+ if (
+ isRecordSharingEnabled &&
+ !isUserAuthContext(authContext) &&
+ !isNonEmptyArray(shareWith)
+ ) {
+ throw new RecordShareException(
+ 'Creating a record of a private object requires the shareWith argument',
+ RecordShareExceptionCode.INVALID_SHARE_WITH,
+ {
+ userFriendlyMessage: msg`Creating a record of a private object requires the shareWith argument`,
+ },
+ );
+ }
+
+ const principalIds = (shareWith ?? []).map(
+ (shareWithEntry) =>
+ resolveShareWithPrincipalOrThrow(shareWithEntry).principalId,
+ );
+
+ if (new Set(principalIds).size !== principalIds.length) {
+ throw new RecordShareException(
+ 'shareWith names the same principal more than once',
+ RecordShareExceptionCode.INVALID_SHARE_WITH,
+ {
+ userFriendlyMessage: msg`shareWith names the same principal more than once`,
+ },
+ );
+ }
+};
diff --git a/packages/twenty-server/src/engine/record-share/utils/validate-share-with-principals-or-throw.util.ts b/packages/twenty-server/src/engine/record-share/utils/validate-share-with-principals-or-throw.util.ts
new file mode 100644
index 00000000000..385b1c00ba5
--- /dev/null
+++ b/packages/twenty-server/src/engine/record-share/utils/validate-share-with-principals-or-throw.util.ts
@@ -0,0 +1,56 @@
+import { msg } from '@lingui/core/macro';
+import { RecordSharePrincipalType } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+
+import { type FlatWorkspaceMemberMaps } from 'src/engine/core-modules/user/types/flat-workspace-member-maps.type';
+import { type FlatRoleMaps } from 'src/engine/metadata-modules/flat-role/types/flat-role-maps.type';
+import {
+ RecordShareException,
+ RecordShareExceptionCode,
+} from 'src/engine/record-share/record-share.exception';
+import { type ShareWithInput } from 'src/engine/record-share/types/share-with-input.type';
+import { resolveShareWithPrincipalOrThrow } from 'src/engine/record-share/utils/resolve-share-with-principal-or-throw.util';
+
+export const validateShareWithPrincipalsOrThrow = ({
+ shareWith,
+ flatWorkspaceMemberMaps,
+ flatRoleMaps,
+}: {
+ shareWith: ShareWithInput[];
+ flatWorkspaceMemberMaps: FlatWorkspaceMemberMaps;
+ flatRoleMaps: FlatRoleMaps;
+}): void => {
+ for (const shareWithEntry of shareWith) {
+ const { principalId, principalType } =
+ resolveShareWithPrincipalOrThrow(shareWithEntry);
+
+ const flatWorkspaceMember = flatWorkspaceMemberMaps.byId[principalId];
+
+ if (
+ principalType === RecordSharePrincipalType.WORKSPACE_MEMBER &&
+ (!isDefined(flatWorkspaceMember) ||
+ isDefined(flatWorkspaceMember.deletedAt))
+ ) {
+ throw new RecordShareException(
+ `shareWith names a workspace member that does not belong to this workspace: ${principalId}`,
+ RecordShareExceptionCode.INVALID_SHARE_WITH,
+ {
+ userFriendlyMessage: msg`shareWith names a workspace member that does not belong to this workspace`,
+ },
+ );
+ }
+
+ if (
+ principalType === RecordSharePrincipalType.ROLE &&
+ !isDefined(flatRoleMaps.universalIdentifierById[principalId])
+ ) {
+ throw new RecordShareException(
+ `shareWith names a role that does not belong to this workspace: ${principalId}`,
+ RecordShareExceptionCode.INVALID_SHARE_WITH,
+ {
+ userFriendlyMessage: msg`shareWith names a role that does not belong to this workspace`,
+ },
+ );
+ }
+ }
+};
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/record-crud/types/workflow-record-crud-action-input.type.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/record-crud/types/workflow-record-crud-action-input.type.ts
index 9ac9abc3702..e308c983c83 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/record-crud/types/workflow-record-crud-action-input.type.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/record-crud/types/workflow-record-crud-action-input.type.ts
@@ -1,4 +1,10 @@
-export type { CreateRecordInput as WorkflowCreateRecordActionInput } from 'src/engine/core-modules/record-crud/types/record-crud-input.type';
+import { type CreateRecordInput } from 'src/engine/core-modules/record-crud/types/record-crud-input.type';
+
+// The action passes the input on field by field and does not forward shareWith yet
+export type WorkflowCreateRecordActionInput = Omit<
+ CreateRecordInput,
+ 'shareWith'
+>;
export type { UpdateRecordInput as WorkflowUpdateRecordActionInput } from 'src/engine/core-modules/record-crud/types/record-crud-input.type';
export type { DeleteRecordInput as WorkflowDeleteRecordActionInput } from 'src/engine/core-modules/record-crud/types/record-crud-input.type';
export type { FindRecordsInput as WorkflowFindRecordsActionInput } from 'src/engine/core-modules/record-crud/types/record-crud-input.type';
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
new file mode 100644
index 00000000000..97a568a9065
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/create-share-with-object-records-permissions.integration-spec.ts
@@ -0,0 +1,745 @@
+import { randomUUID } from 'node:crypto';
+
+import gql from 'graphql-tag';
+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 { makeGraphqlAPIRequestWithApiKey } from 'test/integration/graphql/utils/make-graphql-api-request-with-api-key.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 { createOneFieldMetadata } from 'test/integration/metadata/suites/field-metadata/utils/create-one-field-metadata.util';
+import { deleteOneFieldMetadata } from 'test/integration/metadata/suites/field-metadata/utils/delete-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 { 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 { 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';
+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
+import { getCoreRepository } from 'test/integration/utils/get-core-repository.util';
+import { EVERYONE_PRINCIPAL_ID } from 'twenty-shared/constants';
+import {
+ FeatureFlagKey,
+ FieldMetadataType,
+ MetadataReadability,
+ RecordShareAccessLevel,
+ RecordSharePrincipalType,
+ RecordShareRowCause,
+} from 'twenty-shared/types';
+
+import { type ShareWithInput } from 'src/engine/record-share/types/share-with-input.type';
+import { RelationType } from 'src/engine/metadata-modules/field-metadata/interfaces/relation-type.interface';
+import { ObjectMetadataEntity } from 'src/engine/metadata-modules/object-metadata/object-metadata.entity';
+import { type RecordShareService } from 'src/engine/record-share/services/record-share.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 OBJECT_SINGULAR = 'shareWithTestObject';
+const OBJECT_PLURAL = 'shareWithTestObjects';
+const SHARE_WITH_REQUIRED_MESSAGE =
+ 'Creating a record of a private object requires the shareWith argument';
+const SHARE_WITH_SINGLE_TARGET_MESSAGE =
+ 'Each shareWith entry must target exactly one of workspaceMemberId, roleId or everyone';
+
+const createOneOperation = ({
+ data,
+ shareWith,
+}: {
+ data: { id: string; name: string };
+ shareWith?: ShareWithInput[] | null;
+}) => ({
+ query: gql`
+ mutation CreateOneShareWithTestObject(
+ $data: ShareWithTestObjectCreateInput!
+ $shareWith: [ShareWithInput!]
+ ) {
+ createShareWithTestObject(data: $data, shareWith: $shareWith) {
+ id
+ }
+ }
+ `,
+ variables: { data, shareWith },
+});
+
+const createManyOperation = ({
+ data,
+ shareWith,
+}: {
+ data: { id: string; name: string }[];
+ shareWith?: ShareWithInput[];
+}) => ({
+ query: gql`
+ mutation CreateManyShareWithTestObjects(
+ $data: [ShareWithTestObjectCreateInput!]!
+ $shareWith: [ShareWithInput!]
+ ) {
+ createShareWithTestObjects(data: $data, shareWith: $shareWith) {
+ id
+ }
+ }
+ `,
+ variables: { data, shareWith },
+});
+
+const createOnePersonWithNestedRecordOperation = ({
+ personId,
+ nestedRecord,
+ shareWith,
+}: {
+ personId: string;
+ nestedRecord: { id: string; name: string };
+ shareWith?: ShareWithInput[];
+}) => ({
+ query: gql`
+ mutation CreateOnePersonWithNestedShareWithTestObject(
+ $data: PersonCreateInput!
+ $shareWith: [ShareWithInput!]
+ ) {
+ createPerson(data: $data, shareWith: $shareWith) {
+ id
+ shareWithTestObject {
+ id
+ }
+ }
+ }
+ `,
+ variables: {
+ data: {
+ id: personId,
+ [OBJECT_SINGULAR]: { create: nestedRecord },
+ },
+ shareWith,
+ },
+});
+
+const findManyOperation = (recordId: string) =>
+ findManyOperationFactory({
+ objectMetadataSingularName: OBJECT_SINGULAR,
+ objectMetadataPluralName: OBJECT_PLURAL,
+ gqlFields: 'id',
+ filter: { id: { eq: recordId } },
+ });
+
+const ownerRowFor = (recordId: string, workspaceMemberId: string) => ({
+ recordId,
+ principalId: workspaceMemberId,
+ principalType: RecordSharePrincipalType.WORKSPACE_MEMBER,
+ accessLevel: RecordShareAccessLevel.FULL,
+ rowCause: RecordShareRowCause.OWNER,
+ sourceId: recordId,
+});
+
+const apiKeyRoleRowFor = (recordId: string, roleId: string) => ({
+ recordId,
+ principalId: roleId,
+ principalType: RecordSharePrincipalType.ROLE,
+ accessLevel: RecordShareAccessLevel.FULL,
+ rowCause: RecordShareRowCause.MANUAL,
+ sourceId: recordId,
+});
+
+const setRecordSharingEnabled = (value: boolean) =>
+ updateFeatureFlag({
+ featureFlag: FeatureFlagKey.IS_RECORD_SHARING_ENABLED,
+ value,
+ expectToFail: false,
+ });
+
+describe('createShareWithObjectRecordsPermissions', () => {
+ let recordShareService: RecordShareService;
+ let objectMetadataId: string;
+ let personRelationFieldMetadataId: string;
+ let memberRoleId: string;
+ let adminRoleId: string;
+
+ const createdRecordIds: string[] = [];
+ const createdPersonIds: string[] = [];
+
+ const findRecordShares = (recordId: string) =>
+ recordShareService.findByRecord({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ objectMetadataId,
+ recordId,
+ });
+
+ const trackRecordId = (): string => {
+ const recordId = randomUUID();
+
+ createdRecordIds.push(recordId);
+
+ return recordId;
+ };
+
+ beforeAll(async () => {
+ recordShareService =
+ getAppProviderByClassName<RecordShareService>('RecordShareService');
+
+ const { data } = await createOneObjectMetadata({
+ input: {
+ nameSingular: OBJECT_SINGULAR,
+ namePlural: OBJECT_PLURAL,
+ labelSingular: 'Share With Test Object',
+ labelPlural: 'Share With Test Objects',
+ icon: 'IconLock',
+ isLabelSyncedWithName: false,
+ },
+ });
+
+ objectMetadataId = data.createOneObject.id;
+
+ await createOneFieldMetadata({
+ input: {
+ name: 'name',
+ label: 'Name',
+ type: FieldMetadataType.TEXT,
+ objectMetadataId,
+ isLabelSyncedWithName: false,
+ },
+ });
+
+ const personObjectMetadata = await getCoreRepository<ObjectMetadataEntity>(
+ ObjectMetadataEntity,
+ ).findOneOrFail({
+ where: { workspaceId: SEED_APPLE_WORKSPACE_ID, nameSingular: 'person' },
+ });
+
+ const { data: personRelationFieldData } = await createOneFieldMetadata({
+ input: {
+ name: OBJECT_SINGULAR,
+ label: 'Share With Test Object',
+ type: FieldMetadataType.RELATION,
+ objectMetadataId: personObjectMetadata.id,
+ isLabelSyncedWithName: false,
+ relationCreationPayload: {
+ targetObjectMetadataId: objectMetadataId,
+ targetFieldLabel: 'People',
+ targetFieldIcon: 'IconUser',
+ type: RelationType.MANY_TO_ONE,
+ },
+ },
+ });
+
+ personRelationFieldMetadataId = personRelationFieldData.createOneField.id;
+
+ memberRoleId = (await findOneRoleByLabel({ label: 'Member' })).id;
+ adminRoleId = (await findOneRoleByLabel({ label: 'Admin' })).id;
+ });
+
+ afterAll(async () => {
+ await setRecordSharingEnabled(false);
+
+ const recordShareIds = (
+ await Promise.all(createdRecordIds.map(findRecordShares))
+ )
+ .flat()
+ .map((recordShare) => recordShare.id);
+
+ await deleteRecordsByIds('recordShare', recordShareIds);
+ await setObjectReadability(objectMetadataId, MetadataReadability.OPEN);
+ await makeGraphqlAPIRequest(
+ destroyManyOperationFactory({
+ objectMetadataSingularName: 'person',
+ objectMetadataPluralName: 'people',
+ gqlFields: 'id',
+ filter: { id: { in: createdPersonIds } },
+ }),
+ );
+ await deleteOneFieldMetadata({
+ input: { idToDelete: personRelationFieldMetadataId },
+ expectToFail: false,
+ });
+ await updateOneObjectMetadata({
+ expectToFail: false,
+ input: {
+ idToUpdate: objectMetadataId,
+ updatePayload: { isActive: false },
+ },
+ });
+ await deleteOneObjectMetadata({
+ input: { idToDelete: objectMetadataId },
+ });
+ });
+
+ describe('PRIVATE readability with record sharing enabled', () => {
+ beforeAll(async () => {
+ await setObjectReadability(objectMetadataId, MetadataReadability.PRIVATE);
+ await setRecordSharingEnabled(true);
+ });
+
+ it('should give the creating member a FULL owner row when no shareWith is passed', async () => {
+ const recordId = trackRecordId();
+
+ const response = await makeGraphqlAPIRequest(
+ createOneOperation({ data: { id: recordId, name: 'owner only' } }),
+ );
+
+ expect(response.body.errors).toBeUndefined();
+ expect(response.body.data.createShareWithTestObject.id).toBe(recordId);
+
+ expect(await findRecordShares(recordId)).toEqual([
+ expect.objectContaining(
+ ownerRowFor(recordId, WORKSPACE_MEMBER_DATA_SEED_IDS.JANE),
+ ),
+ ]);
+ });
+
+ it('should drop the rows of a destroyed record whose id is reused', async () => {
+ const recordId = trackRecordId();
+
+ const firstResponse = await makeGraphqlAPIRequest(
+ createOneOperation({
+ data: { id: recordId, name: 'first record with this id' },
+ shareWith: [
+ { roleId: memberRoleId, accessLevel: RecordShareAccessLevel.READ },
+ ],
+ }),
+ );
+
+ expect(firstResponse.body.errors).toBeUndefined();
+ expect(await findRecordShares(recordId)).toHaveLength(2);
+
+ const destroyResponse = await makeGraphqlAPIRequest(
+ destroyManyOperationFactory({
+ objectMetadataSingularName: OBJECT_SINGULAR,
+ objectMetadataPluralName: OBJECT_PLURAL,
+ gqlFields: 'id',
+ filter: { id: { eq: recordId } },
+ }),
+ );
+
+ expect(destroyResponse.body.errors).toBeUndefined();
+ expect(await findRecordShares(recordId)).toHaveLength(2);
+
+ const secondResponse = await makeGraphqlAPIRequest(
+ createOneOperation({
+ data: { id: recordId, name: 'second record with this id' },
+ }),
+ );
+
+ expect(secondResponse.body.errors).toBeUndefined();
+ expect(await findRecordShares(recordId)).toEqual([
+ expect.objectContaining(
+ ownerRowFor(recordId, WORKSPACE_MEMBER_DATA_SEED_IDS.JANE),
+ ),
+ ]);
+ });
+
+ it('should treat a null shareWith as omitted for a member', async () => {
+ const recordId = trackRecordId();
+
+ const response = await makeGraphqlAPIRequest(
+ createOneOperation({
+ data: { id: recordId, name: 'null shareWith' },
+ shareWith: null,
+ }),
+ );
+
+ expect(response.body.errors).toBeUndefined();
+ expect(await findRecordShares(recordId)).toEqual([
+ expect.objectContaining(
+ ownerRowFor(recordId, WORKSPACE_MEMBER_DATA_SEED_IDS.JANE),
+ ),
+ ]);
+ });
+
+ it('should refuse a shareWith naming the same principal twice', async () => {
+ const recordId = trackRecordId();
+
+ const response = await makeGraphqlAPIRequest(
+ createOneOperation({
+ data: { id: recordId, name: 'duplicate principal' },
+ shareWith: [
+ { roleId: memberRoleId, accessLevel: RecordShareAccessLevel.READ },
+ { roleId: memberRoleId, accessLevel: RecordShareAccessLevel.FULL },
+ ],
+ }),
+ );
+
+ expect(JSON.stringify(response.body.errors)).toContain(
+ 'shareWith names the same principal more than once',
+ );
+ expect(await findRecordShares(recordId)).toEqual([]);
+ });
+
+ it('should add a MANUAL role row next to the owner row', async () => {
+ const recordId = trackRecordId();
+
+ const response = await makeGraphqlAPIRequest(
+ createOneOperation({
+ data: { id: recordId, name: 'shared with member role' },
+ shareWith: [
+ { roleId: memberRoleId, accessLevel: RecordShareAccessLevel.READ },
+ ],
+ }),
+ );
+
+ expect(response.body.errors).toBeUndefined();
+
+ expect(await findRecordShares(recordId)).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining(
+ ownerRowFor(recordId, WORKSPACE_MEMBER_DATA_SEED_IDS.JANE),
+ ),
+ expect.objectContaining({
+ recordId,
+ principalId: memberRoleId,
+ principalType: RecordSharePrincipalType.ROLE,
+ accessLevel: RecordShareAccessLevel.READ,
+ rowCause: RecordShareRowCause.MANUAL,
+ sourceId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
+ }),
+ ]),
+ );
+ expect(await findRecordShares(recordId)).toHaveLength(2);
+ });
+
+ it('should reject an api key create without shareWith', async () => {
+ const recordId = trackRecordId();
+
+ const response = await makeGraphqlAPIRequestWithApiKey(
+ createOneOperation({ data: { id: recordId, name: 'api key' } }),
+ );
+
+ expect(response.body.data).toStrictEqual({
+ createShareWithTestObject: null,
+ });
+ expect(response.body.errors[0].message).toBe(SHARE_WITH_REQUIRED_MESSAGE);
+ expect(await findRecordShares(recordId)).toEqual([]);
+ });
+
+ it('should write an EVERYONE row next to the api key role row for an api key create sharing with everyone', async () => {
+ const recordId = trackRecordId();
+
+ const response = await makeGraphqlAPIRequestWithApiKey(
+ createOneOperation({
+ data: { id: recordId, name: 'api key shared with everyone' },
+ shareWith: [
+ { everyone: true, accessLevel: RecordShareAccessLevel.READ },
+ ],
+ }),
+ );
+
+ expect(response.body.errors).toBeUndefined();
+ expect(response.body.data.createShareWithTestObject.id).toBe(recordId);
+
+ expect(await findRecordShares(recordId)).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining(apiKeyRoleRowFor(recordId, adminRoleId)),
+ expect.objectContaining({
+ recordId,
+ principalId: EVERYONE_PRINCIPAL_ID,
+ principalType: RecordSharePrincipalType.EVERYONE,
+ accessLevel: RecordShareAccessLevel.READ,
+ rowCause: RecordShareRowCause.MANUAL,
+ sourceId: recordId,
+ }),
+ ]),
+ );
+ expect(await findRecordShares(recordId)).toHaveLength(2);
+ });
+
+ it('should keep the api key role at FULL when shareWith names it at a lower level', async () => {
+ const recordId = trackRecordId();
+
+ const response = await makeGraphqlAPIRequestWithApiKey(
+ createOneOperation({
+ data: { id: recordId, name: 'api key shared with its own role' },
+ shareWith: [
+ { roleId: adminRoleId, accessLevel: RecordShareAccessLevel.READ },
+ ],
+ }),
+ );
+
+ expect(response.body.errors).toBeUndefined();
+
+ expect(await findRecordShares(recordId)).toEqual([
+ expect.objectContaining({
+ recordId,
+ principalId: adminRoleId,
+ principalType: RecordSharePrincipalType.ROLE,
+ accessLevel: RecordShareAccessLevel.FULL,
+ rowCause: RecordShareRowCause.MANUAL,
+ sourceId: recordId,
+ }),
+ ]);
+ });
+
+ it('should let an api key that shared a record with a member only read and update it', async () => {
+ const recordId = trackRecordId();
+
+ const response = await makeGraphqlAPIRequestWithApiKey(
+ createOneOperation({
+ data: { id: recordId, name: 'api key shared with jony only' },
+ shareWith: [
+ {
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
+ accessLevel: RecordShareAccessLevel.FULL,
+ },
+ ],
+ }),
+ );
+
+ expect(response.body.errors).toBeUndefined();
+ expect(response.body.data.createShareWithTestObject.id).toBe(recordId);
+
+ expect(await findRecordShares(recordId)).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining(apiKeyRoleRowFor(recordId, adminRoleId)),
+ expect.objectContaining({
+ recordId,
+ principalId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
+ principalType: RecordSharePrincipalType.WORKSPACE_MEMBER,
+ accessLevel: RecordShareAccessLevel.FULL,
+ rowCause: RecordShareRowCause.MANUAL,
+ sourceId: recordId,
+ }),
+ ]),
+ );
+ expect(await findRecordShares(recordId)).toHaveLength(2);
+
+ const apiKeyReadResponse = await makeGraphqlAPIRequestWithApiKey(
+ findManyOperation(recordId),
+ );
+
+ expect(apiKeyReadResponse.body.errors).toBeUndefined();
+ expect(
+ apiKeyReadResponse.body.data[OBJECT_PLURAL].edges.map(
+ (edge: { node: { id: string } }) => edge.node.id,
+ ),
+ ).toEqual([recordId]);
+
+ const apiKeyUpdateResponse = await makeGraphqlAPIRequestWithApiKey(
+ updateOneOperationFactory({
+ objectMetadataSingularName: OBJECT_SINGULAR,
+ gqlFields: 'id name',
+ recordId,
+ data: { name: 'renamed by api key' },
+ }),
+ );
+
+ expect(apiKeyUpdateResponse.body.errors).toBeUndefined();
+ expect(apiKeyUpdateResponse.body.data.updateShareWithTestObject).toEqual({
+ id: recordId,
+ name: 'renamed by api key',
+ });
+
+ const jonyReadResponse = await makeGraphqlAPIRequestWithMemberRole(
+ findManyOperation(recordId),
+ );
+
+ expect(jonyReadResponse.body.errors).toBeUndefined();
+ expect(
+ jonyReadResponse.body.data[OBJECT_PLURAL].edges.map(
+ (edge: { node: { id: string } }) => edge.node.id,
+ ),
+ ).toEqual([recordId]);
+ });
+
+ it('should give the creating member the owner row on a nested create', async () => {
+ const personId = randomUUID();
+ const nestedRecordId = trackRecordId();
+
+ createdPersonIds.push(personId);
+
+ const response = await makeGraphqlAPIRequest(
+ createOnePersonWithNestedRecordOperation({
+ personId,
+ nestedRecord: { id: nestedRecordId, name: 'nested by member' },
+ }),
+ );
+
+ expect(response.body.errors).toBeUndefined();
+ expect(response.body.data.createPerson[OBJECT_SINGULAR].id).toBe(
+ nestedRecordId,
+ );
+
+ expect(await findRecordShares(nestedRecordId)).toEqual([
+ expect.objectContaining(
+ ownerRowFor(nestedRecordId, WORKSPACE_MEMBER_DATA_SEED_IDS.JANE),
+ ),
+ ]);
+ });
+
+ it('should forward shareWith to a nested create by an api key', async () => {
+ const personId = randomUUID();
+ const nestedRecordId = trackRecordId();
+
+ createdPersonIds.push(personId);
+
+ const response = await makeGraphqlAPIRequestWithApiKey(
+ createOnePersonWithNestedRecordOperation({
+ personId,
+ nestedRecord: { id: nestedRecordId, name: 'nested by api key' },
+ shareWith: [
+ { everyone: true, accessLevel: RecordShareAccessLevel.READ },
+ ],
+ }),
+ );
+
+ expect(response.body.errors).toBeUndefined();
+ expect(response.body.data.createPerson[OBJECT_SINGULAR].id).toBe(
+ nestedRecordId,
+ );
+
+ expect(await findRecordShares(nestedRecordId)).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining(
+ apiKeyRoleRowFor(nestedRecordId, adminRoleId),
+ ),
+ expect.objectContaining({
+ recordId: nestedRecordId,
+ principalId: EVERYONE_PRINCIPAL_ID,
+ principalType: RecordSharePrincipalType.EVERYONE,
+ accessLevel: RecordShareAccessLevel.READ,
+ rowCause: RecordShareRowCause.MANUAL,
+ sourceId: nestedRecordId,
+ }),
+ ]),
+ );
+ expect(await findRecordShares(nestedRecordId)).toHaveLength(2);
+ });
+
+ it('should write the owner row and the shared row for every record of a createMany', async () => {
+ const recordIds = [trackRecordId(), trackRecordId(), trackRecordId()];
+
+ const response = await makeGraphqlAPIRequest(
+ createManyOperation({
+ data: recordIds.map((id, index) => ({ id, name: `batch ${index}` })),
+ shareWith: [
+ {
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
+ accessLevel: RecordShareAccessLevel.READ_WRITE,
+ },
+ ],
+ }),
+ );
+
+ expect(response.body.errors).toBeUndefined();
+ expect(response.body.data.createShareWithTestObjects).toHaveLength(3);
+
+ for (const recordId of recordIds) {
+ expect(await findRecordShares(recordId)).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining(
+ ownerRowFor(recordId, WORKSPACE_MEMBER_DATA_SEED_IDS.JANE),
+ ),
+ expect.objectContaining({
+ recordId,
+ principalId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
+ principalType: RecordSharePrincipalType.WORKSPACE_MEMBER,
+ accessLevel: RecordShareAccessLevel.READ_WRITE,
+ rowCause: RecordShareRowCause.MANUAL,
+ sourceId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
+ }),
+ ]),
+ );
+ expect(await findRecordShares(recordId)).toHaveLength(2);
+ }
+ });
+
+ it('should reject an entry targeting two principals', async () => {
+ const recordId = trackRecordId();
+
+ const response = await makeGraphqlAPIRequest(
+ createOneOperation({
+ data: { id: recordId, name: 'two targets' },
+ shareWith: [
+ {
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
+ roleId: memberRoleId,
+ accessLevel: RecordShareAccessLevel.READ,
+ },
+ ],
+ }),
+ );
+
+ expect(response.body.data).toStrictEqual({
+ createShareWithTestObject: null,
+ });
+ expect(response.body.errors[0].message).toBe(
+ SHARE_WITH_SINGLE_TARGET_MESSAGE,
+ );
+ expect(await findRecordShares(recordId)).toEqual([]);
+ });
+ });
+
+ describe('PRIVATE readability with record sharing disabled', () => {
+ beforeAll(async () => {
+ await setObjectReadability(objectMetadataId, MetadataReadability.PRIVATE);
+ await setRecordSharingEnabled(false);
+ });
+
+ it('should accept an api key create without shareWith and grant everyone FULL access', async () => {
+ const recordId = trackRecordId();
+
+ const response = await makeGraphqlAPIRequestWithApiKey(
+ createOneOperation({
+ data: { id: recordId, name: 'api key without shareWith' },
+ }),
+ );
+
+ expect(response.body.errors).toBeUndefined();
+ expect(response.body.data.createShareWithTestObject.id).toBe(recordId);
+
+ expect(await findRecordShares(recordId)).toEqual([
+ expect.objectContaining({
+ recordId,
+ principalId: EVERYONE_PRINCIPAL_ID,
+ principalType: RecordSharePrincipalType.EVERYONE,
+ accessLevel: RecordShareAccessLevel.FULL,
+ rowCause: RecordShareRowCause.APPLICATION,
+ sourceId: objectMetadataId,
+ }),
+ ]);
+ });
+
+ it('should give the creating member the owner row and everyone FULL access, so the record stays open once the flag turns on', async () => {
+ const recordId = trackRecordId();
+
+ const response = await makeGraphqlAPIRequest(
+ createOneOperation({
+ data: { id: recordId, name: 'member with flag off' },
+ }),
+ );
+
+ expect(response.body.errors).toBeUndefined();
+
+ expect(await findRecordShares(recordId)).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining(
+ ownerRowFor(recordId, WORKSPACE_MEMBER_DATA_SEED_IDS.JANE),
+ ),
+ expect.objectContaining({
+ recordId,
+ principalId: EVERYONE_PRINCIPAL_ID,
+ accessLevel: RecordShareAccessLevel.FULL,
+ }),
+ ]),
+ );
+ expect(await findRecordShares(recordId)).toHaveLength(2);
+ });
+ });
+
+ describe('OPEN readability', () => {
+ beforeAll(async () => {
+ await setObjectReadability(objectMetadataId, MetadataReadability.OPEN);
+ });
+
+ it('should ignore shareWith and write no row', async () => {
+ const recordId = trackRecordId();
+
+ const response = await makeGraphqlAPIRequest(
+ createOneOperation({
+ data: { id: recordId, name: 'open object' },
+ shareWith: [
+ { everyone: true, accessLevel: RecordShareAccessLevel.FULL },
+ ],
+ }),
+ );
+
+ expect(response.body.errors).toBeUndefined();
+ expect(await findRecordShares(recordId)).toEqual([]);
+ });
+ });
+});
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 c2c5bd93dc0..9559c868198 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
@@ -16,6 +16,7 @@ import { createOneFieldMetadata } from 'test/integration/metadata/suites/field-m
import { deleteOneFieldMetadata } from 'test/integration/metadata/suites/field-metadata/utils/delete-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 { 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';
@@ -99,26 +100,6 @@ const totalCountOperation = {
variables: { filter: ALL_RECORDS_FILTER },
};
-const setObjectReadability = async (
- objectMetadataId: string,
- readability: MetadataReadability,
-) => {
- await getCoreRepository<ObjectMetadataEntity>(ObjectMetadataEntity).update(
- objectMetadataId,
- { readability },
- );
-
- const { errors } = await updateOneObjectMetadata({
- expectToFail: false,
- input: {
- idToUpdate: objectMetadataId,
- updatePayload: { description: `readability set to ${readability}` },
- },
- });
-
- expect(errors).toBeUndefined();
-};
-
const setRecordSharingEnabled = (value: boolean) =>
updateFeatureFlag({
featureFlag: FeatureFlagKey.IS_RECORD_SHARING_ENABLED,
diff --git a/packages/twenty-server/test/integration/metadata/suites/object-metadata/utils/set-object-readability.util.ts b/packages/twenty-server/test/integration/metadata/suites/object-metadata/utils/set-object-readability.util.ts
new file mode 100644
index 00000000000..b6bc49daedb
--- /dev/null
+++ b/packages/twenty-server/test/integration/metadata/suites/object-metadata/utils/set-object-readability.util.ts
@@ -0,0 +1,23 @@
+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
+import { getCoreRepository } from 'test/integration/utils/get-core-repository.util';
+import { type MetadataReadability } from 'twenty-shared/types';
+
+import { ObjectMetadataEntity } from 'src/engine/metadata-modules/object-metadata/object-metadata.entity';
+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';
+
+// Written straight to the table and pushed into the caches: the metadata API
+// refuses most levels, and an update through it would leave an override behind
+export const setObjectReadability = async (
+ objectMetadataId: string,
+ readability: MetadataReadability,
+) => {
+ await getCoreRepository<ObjectMetadataEntity>(ObjectMetadataEntity).update(
+ objectMetadataId,
+ { readability },
+ );
+
+ await getAppProviderByClassName<WorkspaceCacheService>(
+ 'WorkspaceCacheService',
+ ).invalidateAndRecompute(SEED_APPLE_WORKSPACE_ID, ['flatObjectMetadataMaps']);
+};