feat(workflow): use authContext in CRUD services for Common API migration (#16857)
## Summary This PR migrates workflow CRUD operations to properly use the Common API layer's authentication context, addressing the issues from the reverted PR #15875. The original PR was reverted because the Common API required passing either a User or an API Key for authentication, which was problematic for workflows. Since then, the "Application" concept was introduced in the Common API layer, allowing for token injection in serverless functions. This PR leverages the "Twenty Standard Application" concept for non-manual workflow triggers, providing a clean authentication path without the issues of user impersonation. ## Changes ### Core Infrastructure - **RecordCrudExecutionContext**: Replace `workspaceId` with full `authContext` - **WorkflowExecutionContext**: Add `authContext` field to carry authentication info - **ToolGeneratorContext/ToolSpecification**: Add optional `authContext` support for tool generation ### Authentication Flow - **WorkflowExecutionContextService**: Build appropriate auth context based on trigger type: - **Manual triggers**: Use user's workspace auth context with their role permissions - **Non-manual triggers**: Use Twenty Standard Application auth context (bypasses permission checks or uses default serverless function role) - **ApplicationService**: Add `findTwentyStandardApplicationOrThrow` method to retrieve the system application - **UserWorkspaceService**: Make relations configurable in `getUserWorkspaceForUserOrThrow` to load only what's needed ### CRUD Services Migration All 5 record CRUD services now receive `authContext` instead of `workspaceId`: - `CreateRecordService` - `UpdateRecordService` - `DeleteRecordService` - `FindRecordsService` - `UpsertRecordService` ### Workflow Actions All record CRUD workflow actions pass `executionContext.authContext` to the services: - `CreateRecordWorkflowAction` - `UpdateRecordWorkflowAction` - `DeleteRecordWorkflowAction` - `FindRecordsWorkflowAction` - `UpsertRecordWorkflowAction` ### AI Agent Integration - AI agent workflow action passes auth context to agent executor - Tool provider and MCP protocol service support auth context propagation ## Benefits - ✅ Proper authentication for workflow CRUD operations via Common API - ✅ Non-manual triggers use system application context (no user impersonation issues) - ✅ Manual triggers preserve user permissions correctly - ✅ Foundation for better permission handling in automated workflows - ✅ Cleaner separation between user-initiated and system-initiated operations ## Related - Reverted PR: #15875
This commit is contained in:
@@ -2,7 +2,7 @@ import { Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
|
||||
import { isDefined } from 'twenty-shared/utils';
|
||||
import { type QueryRunner, Repository } from 'typeorm';
|
||||
import { type QueryRunner, type Repository } from 'typeorm';
|
||||
import { v4 } from 'uuid';
|
||||
|
||||
import { ApplicationEntity } from 'src/engine/core-modules/application/application.entity';
|
||||
@@ -146,6 +146,32 @@ export class ApplicationService {
|
||||
});
|
||||
}
|
||||
|
||||
async findTwentyStandardApplicationOrThrow(workspaceId: string): Promise<{
|
||||
application: ApplicationEntity;
|
||||
workspace: WorkspaceEntity;
|
||||
}> {
|
||||
const workspace = await this.workspaceRepository.findOne({
|
||||
where: { id: workspaceId },
|
||||
});
|
||||
|
||||
if (!isDefined(workspace)) {
|
||||
throw new ApplicationException(
|
||||
`Could not find workspace ${workspaceId}`,
|
||||
ApplicationExceptionCode.APPLICATION_NOT_FOUND,
|
||||
);
|
||||
}
|
||||
|
||||
const { twentyStandardFlatApplication } =
|
||||
await this.findWorkspaceTwentyStandardAndCustomApplicationOrThrow({
|
||||
workspace,
|
||||
});
|
||||
|
||||
return {
|
||||
application: twentyStandardFlatApplication as ApplicationEntity,
|
||||
workspace,
|
||||
};
|
||||
}
|
||||
|
||||
async createTwentyStandardApplication(
|
||||
{
|
||||
workspaceId,
|
||||
|
||||
+2
-11
@@ -17,7 +17,6 @@ import { type ToolOutput } from 'src/engine/core-modules/tool/types/tool-output.
|
||||
import { findFlatEntityByIdInFlatEntityMapsOrThrow } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-id-in-flat-entity-maps-or-throw.util';
|
||||
import { buildFieldMapsFromFlatObjectMetadata } from 'src/engine/metadata-modules/flat-field-metadata/utils/build-field-maps-from-flat-object-metadata.util';
|
||||
import { GlobalWorkspaceOrmManager } from 'src/engine/twenty-orm/global-workspace-datasource/global-workspace-orm.manager';
|
||||
import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
|
||||
|
||||
@Injectable()
|
||||
export class CreateRecordService {
|
||||
@@ -30,18 +29,10 @@ export class CreateRecordService {
|
||||
) {}
|
||||
|
||||
async execute(params: CreateRecordParams): Promise<ToolOutput> {
|
||||
const { objectName, objectRecord, workspaceId, rolePermissionConfig } =
|
||||
const { objectName, objectRecord, authContext, rolePermissionConfig } =
|
||||
params;
|
||||
|
||||
if (!workspaceId) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'Failed to create record: Workspace ID is required',
|
||||
error: 'Workspace ID not found',
|
||||
};
|
||||
}
|
||||
|
||||
const authContext = buildSystemAuthContext(workspaceId);
|
||||
const workspaceId = authContext.workspace.id;
|
||||
|
||||
try {
|
||||
return await this.globalWorkspaceOrmManager.executeInWorkspaceContext(
|
||||
|
||||
+2
-11
@@ -11,7 +11,6 @@ import { type DeleteRecordParams } from 'src/engine/core-modules/record-crud/typ
|
||||
import { type ToolOutput } from 'src/engine/core-modules/tool/types/tool-output.type';
|
||||
import { findFlatEntityByIdInFlatEntityMapsOrThrow } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-id-in-flat-entity-maps-or-throw.util';
|
||||
import { GlobalWorkspaceOrmManager } from 'src/engine/twenty-orm/global-workspace-datasource/global-workspace-orm.manager';
|
||||
import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
|
||||
|
||||
@Injectable()
|
||||
export class DeleteRecordService {
|
||||
@@ -25,18 +24,12 @@ export class DeleteRecordService {
|
||||
const {
|
||||
objectName,
|
||||
objectRecordId,
|
||||
workspaceId,
|
||||
authContext,
|
||||
rolePermissionConfig,
|
||||
soft = true,
|
||||
} = params;
|
||||
|
||||
if (!workspaceId) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'Failed to delete record: Workspace ID is required',
|
||||
error: 'Workspace ID not found',
|
||||
};
|
||||
}
|
||||
const workspaceId = authContext.workspace.id;
|
||||
|
||||
if (!isDefined(objectRecordId) || !isValidUuid(objectRecordId)) {
|
||||
return {
|
||||
@@ -46,8 +39,6 @@ export class DeleteRecordService {
|
||||
};
|
||||
}
|
||||
|
||||
const authContext = buildSystemAuthContext(workspaceId);
|
||||
|
||||
try {
|
||||
return await this.globalWorkspaceOrmManager.executeInWorkspaceContext(
|
||||
authContext,
|
||||
|
||||
+3
-12
@@ -18,7 +18,7 @@ import {
|
||||
RecordCrudExceptionCode,
|
||||
} from 'src/engine/core-modules/record-crud/exceptions/record-crud.exception';
|
||||
import { type FindRecordsParams } from 'src/engine/core-modules/record-crud/types/find-records-params.type';
|
||||
import { FindRecordsResult } from 'src/engine/core-modules/record-crud/types/find-records-result.type';
|
||||
import { type FindRecordsResult } from 'src/engine/core-modules/record-crud/types/find-records-result.type';
|
||||
import { getRecordDisplayName } from 'src/engine/core-modules/record-crud/utils/get-record-display-name.util';
|
||||
import { type ToolOutput } from 'src/engine/core-modules/tool/types/tool-output.type';
|
||||
import { type FlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-maps.type';
|
||||
@@ -28,7 +28,6 @@ import { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object
|
||||
import { GlobalWorkspaceOrmManager } from 'src/engine/twenty-orm/global-workspace-datasource/global-workspace-orm.manager';
|
||||
import { type WorkspaceSelectQueryBuilder } from 'src/engine/twenty-orm/repository/workspace-select-query-builder';
|
||||
import { type WorkspaceRepository } from 'src/engine/twenty-orm/repository/workspace.repository';
|
||||
import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
|
||||
|
||||
@Injectable()
|
||||
export class FindRecordsService {
|
||||
@@ -47,19 +46,11 @@ export class FindRecordsService {
|
||||
orderBy,
|
||||
limit,
|
||||
offset = 0,
|
||||
workspaceId,
|
||||
authContext,
|
||||
rolePermissionConfig,
|
||||
} = params;
|
||||
|
||||
if (!workspaceId) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'Failed to find records: Workspace ID is required',
|
||||
error: 'Workspace ID not found',
|
||||
};
|
||||
}
|
||||
|
||||
const authContext = buildSystemAuthContext(workspaceId);
|
||||
const workspaceId = authContext.workspace.id;
|
||||
|
||||
try {
|
||||
return await this.globalWorkspaceOrmManager.executeInWorkspaceContext(
|
||||
|
||||
+2
-11
@@ -15,7 +15,6 @@ import { RecordInputTransformerService } from 'src/engine/core-modules/record-tr
|
||||
import { type ToolOutput } from 'src/engine/core-modules/tool/types/tool-output.type';
|
||||
import { findFlatEntityByIdInFlatEntityMapsOrThrow } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-id-in-flat-entity-maps-or-throw.util';
|
||||
import { GlobalWorkspaceOrmManager } from 'src/engine/twenty-orm/global-workspace-datasource/global-workspace-orm.manager';
|
||||
import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
|
||||
|
||||
@Injectable()
|
||||
export class UpdateRecordService {
|
||||
@@ -32,18 +31,12 @@ export class UpdateRecordService {
|
||||
objectRecordId,
|
||||
objectRecord,
|
||||
fieldsToUpdate,
|
||||
workspaceId,
|
||||
authContext,
|
||||
rolePermissionConfig,
|
||||
// updatedBy,
|
||||
} = params;
|
||||
|
||||
if (!workspaceId) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'Failed to update record: Workspace ID is required',
|
||||
error: 'Workspace ID not found',
|
||||
};
|
||||
}
|
||||
const workspaceId = authContext.workspace.id;
|
||||
|
||||
if (!isDefined(objectRecordId) || !isValidUuid(objectRecordId)) {
|
||||
return {
|
||||
@@ -53,8 +46,6 @@ export class UpdateRecordService {
|
||||
};
|
||||
}
|
||||
|
||||
const authContext = buildSystemAuthContext(workspaceId);
|
||||
|
||||
try {
|
||||
return await this.globalWorkspaceOrmManager.executeInWorkspaceContext(
|
||||
authContext,
|
||||
|
||||
+3
-12
@@ -7,7 +7,7 @@ import {
|
||||
RecordCrudException,
|
||||
RecordCrudExceptionCode,
|
||||
} from 'src/engine/core-modules/record-crud/exceptions/record-crud.exception';
|
||||
import { UpsertRecordParams } from 'src/engine/core-modules/record-crud/types/upsert-record-params.type';
|
||||
import { type UpsertRecordParams } from 'src/engine/core-modules/record-crud/types/upsert-record-params.type';
|
||||
import { getSelectedColumnsFromRestrictedFields } from 'src/engine/core-modules/record-crud/utils/get-selected-columns-from-restricted-fields.util';
|
||||
import { RecordInputTransformerService } from 'src/engine/core-modules/record-transformer/services/record-input-transformer.service';
|
||||
import { type ToolOutput } from 'src/engine/core-modules/tool/types/tool-output.type';
|
||||
@@ -17,7 +17,6 @@ import { isCompositeFieldMetadataType } from 'src/engine/metadata-modules/field-
|
||||
import { findFlatEntityByIdInFlatEntityMapsOrThrow } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-id-in-flat-entity-maps-or-throw.util';
|
||||
import { buildFieldMapsFromFlatObjectMetadata } from 'src/engine/metadata-modules/flat-field-metadata/utils/build-field-maps-from-flat-object-metadata.util';
|
||||
import { GlobalWorkspaceOrmManager } from 'src/engine/twenty-orm/global-workspace-datasource/global-workspace-orm.manager';
|
||||
import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
|
||||
|
||||
@Injectable()
|
||||
export class UpsertRecordService {
|
||||
@@ -29,18 +28,10 @@ export class UpsertRecordService {
|
||||
) {}
|
||||
|
||||
async execute(params: UpsertRecordParams): Promise<ToolOutput> {
|
||||
const { objectName, objectRecord, workspaceId, rolePermissionConfig } =
|
||||
const { objectName, objectRecord, authContext, rolePermissionConfig } =
|
||||
params;
|
||||
|
||||
if (!workspaceId) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'Failed to upsert record: Workspace ID is required',
|
||||
error: 'Workspace ID not found',
|
||||
};
|
||||
}
|
||||
|
||||
const authContext = buildSystemAuthContext(workspaceId);
|
||||
const workspaceId = authContext.workspace.id;
|
||||
|
||||
try {
|
||||
return await this.globalWorkspaceOrmManager.executeInWorkspaceContext(
|
||||
|
||||
+13
-5
@@ -36,6 +36,14 @@ export const createDirectRecordToolsFactory = (deps: DirectRecordToolsDeps) => {
|
||||
): ToolSet => {
|
||||
const tools: ToolSet = {};
|
||||
|
||||
// Skip generating tools if no auth context is provided
|
||||
if (!context.authContext) {
|
||||
return tools;
|
||||
}
|
||||
|
||||
// Capture authContext in a constant for use in async callbacks
|
||||
const authContext = context.authContext;
|
||||
|
||||
if (canRead) {
|
||||
tools[`find_${objectMetadata.namePlural}`] = {
|
||||
description: `Search for ${objectMetadata.labelPlural} records using flexible filtering criteria. Supports exact matches, pattern matching, ranges, and null checks. Use limit/offset for pagination and orderBy for sorting. To find by ID, use filter: { id: { eq: "record-id" } }. Returns an array of matching records with their full data.`,
|
||||
@@ -52,7 +60,7 @@ export const createDirectRecordToolsFactory = (deps: DirectRecordToolsDeps) => {
|
||||
orderBy,
|
||||
limit,
|
||||
offset,
|
||||
workspaceId: context.workspaceId,
|
||||
authContext,
|
||||
rolePermissionConfig: context.rolePermissionConfig,
|
||||
});
|
||||
},
|
||||
@@ -66,7 +74,7 @@ export const createDirectRecordToolsFactory = (deps: DirectRecordToolsDeps) => {
|
||||
objectName: objectMetadata.nameSingular,
|
||||
filter: { id: { eq: parameters.input.id } },
|
||||
limit: 1,
|
||||
workspaceId: context.workspaceId,
|
||||
authContext,
|
||||
rolePermissionConfig: context.rolePermissionConfig,
|
||||
});
|
||||
},
|
||||
@@ -84,7 +92,7 @@ export const createDirectRecordToolsFactory = (deps: DirectRecordToolsDeps) => {
|
||||
return deps.createRecordService.execute({
|
||||
objectName: objectMetadata.nameSingular,
|
||||
objectRecord: parameters.input,
|
||||
workspaceId: context.workspaceId,
|
||||
authContext,
|
||||
rolePermissionConfig: context.rolePermissionConfig,
|
||||
createdBy: context.actorContext,
|
||||
});
|
||||
@@ -112,7 +120,7 @@ export const createDirectRecordToolsFactory = (deps: DirectRecordToolsDeps) => {
|
||||
objectName: objectMetadata.nameSingular,
|
||||
objectRecordId: id,
|
||||
objectRecord,
|
||||
workspaceId: context.workspaceId,
|
||||
authContext,
|
||||
rolePermissionConfig: context.rolePermissionConfig,
|
||||
});
|
||||
},
|
||||
@@ -127,7 +135,7 @@ export const createDirectRecordToolsFactory = (deps: DirectRecordToolsDeps) => {
|
||||
return deps.deleteRecordService.execute({
|
||||
objectName: objectMetadata.nameSingular,
|
||||
objectRecordId: parameters.input.id,
|
||||
workspaceId: context.workspaceId,
|
||||
authContext,
|
||||
rolePermissionConfig: context.rolePermissionConfig,
|
||||
soft: true,
|
||||
});
|
||||
|
||||
+3
-1
@@ -1,6 +1,8 @@
|
||||
import { type WorkspaceAuthContext } from 'src/engine/api/common/interfaces/workspace-auth-context.interface';
|
||||
|
||||
import { type RolePermissionConfig } from 'src/engine/twenty-orm/types/role-permission-config';
|
||||
|
||||
export type RecordCrudExecutionContext = {
|
||||
workspaceId: string;
|
||||
authContext: WorkspaceAuthContext;
|
||||
rolePermissionConfig?: RolePermissionConfig;
|
||||
};
|
||||
|
||||
+3
@@ -4,6 +4,8 @@ import {
|
||||
type RestrictedFieldsPermissions,
|
||||
} from 'twenty-shared/types';
|
||||
|
||||
import { type WorkspaceAuthContext } from 'src/engine/api/common/interfaces/workspace-auth-context.interface';
|
||||
|
||||
import { type ObjectMetadataForToolSchema } from 'src/engine/core-modules/record-crud/types/object-metadata-for-tool-schema.type';
|
||||
import { type RolePermissionConfig } from 'src/engine/twenty-orm/types/role-permission-config';
|
||||
|
||||
@@ -20,6 +22,7 @@ export type ObjectWithPermission = {
|
||||
// Context passed to tool factories
|
||||
export type ToolGeneratorContext = {
|
||||
workspaceId: string;
|
||||
authContext?: WorkspaceAuthContext;
|
||||
rolePermissionConfig: RolePermissionConfig;
|
||||
actorContext?: ActorMetadata;
|
||||
};
|
||||
|
||||
+2
-1
@@ -139,7 +139,7 @@ export class ToolProviderService {
|
||||
}
|
||||
|
||||
private async getDatabaseTools(spec: ToolSpecification): Promise<ToolSet> {
|
||||
if (!spec.rolePermissionConfig) {
|
||||
if (!spec.rolePermissionConfig || !spec.authContext) {
|
||||
return {};
|
||||
}
|
||||
|
||||
@@ -153,6 +153,7 @@ export class ToolProviderService {
|
||||
return this.perObjectToolGenerator.generate(
|
||||
{
|
||||
workspaceId: spec.workspaceId,
|
||||
authContext: spec.authContext,
|
||||
rolePermissionConfig: spec.rolePermissionConfig,
|
||||
actorContext: spec.actorContext,
|
||||
},
|
||||
|
||||
+3
@@ -1,5 +1,7 @@
|
||||
import { type ActorMetadata } from 'twenty-shared/types';
|
||||
|
||||
import { type WorkspaceAuthContext } from 'src/engine/api/common/interfaces/workspace-auth-context.interface';
|
||||
|
||||
import { type ToolCategory } from 'src/engine/core-modules/tool-provider/enums/tool-category.enum';
|
||||
import { type ToolType } from 'src/engine/core-modules/tool/enums/tool-type.enum';
|
||||
import { type FlatAgentWithRoleId } from 'src/engine/metadata-modules/flat-agent/types/flat-agent.type';
|
||||
@@ -9,6 +11,7 @@ export type ToolSpecification = {
|
||||
workspaceId: string;
|
||||
categories: ToolCategory[];
|
||||
rolePermissionConfig?: RolePermissionConfig;
|
||||
authContext?: WorkspaceAuthContext;
|
||||
actorContext?: ActorMetadata;
|
||||
agent?: FlatAgentWithRoleId | null;
|
||||
wrapWithErrorContext?: boolean;
|
||||
|
||||
+6
-4
@@ -3,7 +3,7 @@ import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { TypeOrmQueryService } from '@ptc-org/nestjs-query-typeorm';
|
||||
import { type APP_LOCALES, SOURCE_LOCALE } from 'twenty-shared/translations';
|
||||
import { assertIsDefinedOrThrow, isDefined } from 'twenty-shared/utils';
|
||||
import { type QueryRunner, IsNull, Not, Repository } from 'typeorm';
|
||||
import { type QueryRunner, IsNull, Not, type Repository } from 'typeorm';
|
||||
|
||||
import { FileStorageExceptionCode } from 'src/engine/core-modules/file-storage/interfaces/file-storage-exception';
|
||||
import { FileFolder } from 'src/engine/core-modules/file/interfaces/file-folder.interface';
|
||||
@@ -24,7 +24,7 @@ import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user
|
||||
import { UserEntity } from 'src/engine/core-modules/user/user.entity';
|
||||
import { WorkspaceInvitationService } from 'src/engine/core-modules/workspace-invitation/services/workspace-invitation.service';
|
||||
import { AuthProviderEnum } from 'src/engine/core-modules/workspace/types/workspace.type';
|
||||
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
|
||||
import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
|
||||
import { workspaceValidator } from 'src/engine/core-modules/workspace/workspace.validate';
|
||||
import {
|
||||
PermissionsException,
|
||||
@@ -35,7 +35,7 @@ import { RoleTargetEntity } from 'src/engine/metadata-modules/role-target/role-t
|
||||
import { UserRoleService } from 'src/engine/metadata-modules/user-role/user-role.service';
|
||||
import { GlobalWorkspaceOrmManager } from 'src/engine/twenty-orm/global-workspace-datasource/global-workspace-orm.manager';
|
||||
import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
|
||||
import { WorkspaceMemberWorkspaceEntity } from 'src/modules/workspace-member/standard-objects/workspace-member.workspace-entity';
|
||||
import { type WorkspaceMemberWorkspaceEntity } from 'src/modules/workspace-member/standard-objects/workspace-member.workspace-entity';
|
||||
import { assert } from 'src/utils/assert';
|
||||
import { getDomainNameByEmail } from 'src/utils/get-domain-name-by-email';
|
||||
|
||||
@@ -325,16 +325,18 @@ export class UserWorkspaceService extends TypeOrmQueryService<UserWorkspaceEntit
|
||||
async getUserWorkspaceForUserOrThrow({
|
||||
userId,
|
||||
workspaceId,
|
||||
relations = ['twoFactorAuthenticationMethods'],
|
||||
}: {
|
||||
userId: string;
|
||||
workspaceId: string;
|
||||
relations?: string[];
|
||||
}): Promise<UserWorkspaceEntity> {
|
||||
const userWorkspace = await this.userWorkspaceRepository.findOne({
|
||||
where: {
|
||||
userId,
|
||||
workspaceId,
|
||||
},
|
||||
relations: ['twoFactorAuthenticationMethods'],
|
||||
relations,
|
||||
});
|
||||
|
||||
if (!isDefined(userWorkspace)) {
|
||||
|
||||
Reference in New Issue
Block a user