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:
@@ -1,22 +1,21 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
|
||||
import { McpCoreController } from 'src/engine/api/mcp/controllers/mcp-core.controller';
|
||||
import { McpMetadataController } from 'src/engine/api/mcp/controllers/mcp-metadata.controller';
|
||||
import { MCPMetadataService } from 'src/engine/api/mcp/services/mcp-metadata.service';
|
||||
import { McpProtocolService } from 'src/engine/api/mcp/services/mcp-protocol.service';
|
||||
import { McpToolExecutorService } from 'src/engine/api/mcp/services/mcp-tool-executor.service';
|
||||
import { ApiKeyModule } from 'src/engine/core-modules/api-key/api-key.module';
|
||||
import { TokenModule } from 'src/engine/core-modules/auth/token/token.module';
|
||||
import { FeatureFlagModule } from 'src/engine/core-modules/feature-flag/feature-flag.module';
|
||||
import { MetricsModule } from 'src/engine/core-modules/metrics/metrics.module';
|
||||
import { ToolProviderModule } from 'src/engine/core-modules/tool-provider/tool-provider.module';
|
||||
import { RoleEntity } from 'src/engine/metadata-modules/role/role.entity';
|
||||
import { UserRoleModule } from 'src/engine/metadata-modules/user-role/user-role.module';
|
||||
import { WorkspaceCacheStorageModule } from 'src/engine/workspace-cache-storage/workspace-cache-storage.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
TypeOrmModule.forFeature([RoleEntity]),
|
||||
ApiKeyModule,
|
||||
TokenModule,
|
||||
WorkspaceCacheStorageModule,
|
||||
FeatureFlagModule,
|
||||
|
||||
+13
-12
@@ -1,6 +1,5 @@
|
||||
import { HttpException, HttpStatus } from '@nestjs/common';
|
||||
import { Test, type TestingModule } from '@nestjs/testing';
|
||||
import { getRepositoryToken } from '@nestjs/typeorm';
|
||||
|
||||
import { jsonSchema } from 'ai';
|
||||
|
||||
@@ -9,12 +8,11 @@ import { type JsonRpc } from 'src/engine/api/mcp/dtos/json-rpc';
|
||||
import { McpProtocolService } from 'src/engine/api/mcp/services/mcp-protocol.service';
|
||||
import { McpToolExecutorService } from 'src/engine/api/mcp/services/mcp-tool-executor.service';
|
||||
import { type ApiKeyEntity } from 'src/engine/core-modules/api-key/api-key.entity';
|
||||
import { ApiKeyRoleService } from 'src/engine/core-modules/api-key/services/api-key-role.service';
|
||||
import { FeatureFlagKey } from 'src/engine/core-modules/feature-flag/enums/feature-flag-key.enum';
|
||||
import { FeatureFlagService } from 'src/engine/core-modules/feature-flag/services/feature-flag.service';
|
||||
import { ToolProviderService } from 'src/engine/core-modules/tool-provider/services/tool-provider.service';
|
||||
import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
|
||||
import { ADMIN_ROLE_LABEL } from 'src/engine/metadata-modules/permissions/constants/admin-role-label.constants';
|
||||
import { RoleEntity } from 'src/engine/metadata-modules/role/role.entity';
|
||||
import { UserRoleService } from 'src/engine/metadata-modules/user-role/user-role.service';
|
||||
|
||||
describe('McpProtocolService', () => {
|
||||
@@ -23,6 +21,7 @@ describe('McpProtocolService', () => {
|
||||
let toolProviderService: jest.Mocked<ToolProviderService>;
|
||||
let userRoleService: jest.Mocked<UserRoleService>;
|
||||
let mcpToolExecutorService: jest.Mocked<McpToolExecutorService>;
|
||||
let apiKeyRoleService: jest.Mocked<ApiKeyRoleService>;
|
||||
|
||||
const mockWorkspace = { id: 'workspace-1' } as WorkspaceEntity;
|
||||
const mockUserWorkspaceId = 'user-workspace-1';
|
||||
@@ -51,10 +50,9 @@ describe('McpProtocolService', () => {
|
||||
handleToolsListing: jest.fn(),
|
||||
};
|
||||
|
||||
const mockAdminRole = {
|
||||
id: mockAdminRoleId,
|
||||
label: ADMIN_ROLE_LABEL,
|
||||
} as RoleEntity;
|
||||
const mockApiKeyRoleService = {
|
||||
getRoleIdForApiKeyId: jest.fn().mockResolvedValue(mockAdminRoleId),
|
||||
};
|
||||
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
@@ -76,10 +74,8 @@ describe('McpProtocolService', () => {
|
||||
useValue: mockMcpToolExecutorService,
|
||||
},
|
||||
{
|
||||
provide: getRepositoryToken(RoleEntity),
|
||||
useValue: {
|
||||
find: jest.fn().mockResolvedValue([mockAdminRole]),
|
||||
},
|
||||
provide: ApiKeyRoleService,
|
||||
useValue: mockApiKeyRoleService,
|
||||
},
|
||||
],
|
||||
}).compile();
|
||||
@@ -89,6 +85,7 @@ describe('McpProtocolService', () => {
|
||||
toolProviderService = module.get(ToolProviderService);
|
||||
userRoleService = module.get(UserRoleService);
|
||||
mcpToolExecutorService = module.get(McpToolExecutorService);
|
||||
apiKeyRoleService = module.get(ApiKeyRoleService);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
@@ -171,7 +168,7 @@ describe('McpProtocolService', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('should return admin role ID when apiKey is provided', async () => {
|
||||
it('should return role ID from ApiKeyRoleService when apiKey is provided', async () => {
|
||||
const result = await service.getRoleId(
|
||||
'workspace-1',
|
||||
undefined,
|
||||
@@ -179,6 +176,10 @@ describe('McpProtocolService', () => {
|
||||
);
|
||||
|
||||
expect(result).toBe(mockAdminRoleId);
|
||||
expect(apiKeyRoleService.getRoleIdForApiKeyId).toHaveBeenCalledWith(
|
||||
mockApiKey.id,
|
||||
'workspace-1',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,22 +1,21 @@
|
||||
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
|
||||
import { isDefined } from 'twenty-shared/utils';
|
||||
import { Repository } from 'typeorm';
|
||||
|
||||
import { type WorkspaceAuthContext } from 'src/engine/api/common/interfaces/workspace-auth-context.interface';
|
||||
|
||||
import { type JsonRpc } from 'src/engine/api/mcp/dtos/json-rpc';
|
||||
import { McpToolExecutorService } from 'src/engine/api/mcp/services/mcp-tool-executor.service';
|
||||
import { wrapJsonRpcResponse } from 'src/engine/api/mcp/utils/wrap-jsonrpc-response.util';
|
||||
import { ApiKeyEntity } from 'src/engine/core-modules/api-key/api-key.entity';
|
||||
import { type ApiKeyEntity } from 'src/engine/core-modules/api-key/api-key.entity';
|
||||
import { ApiKeyRoleService } from 'src/engine/core-modules/api-key/services/api-key-role.service';
|
||||
import { FeatureFlagKey } from 'src/engine/core-modules/feature-flag/enums/feature-flag-key.enum';
|
||||
import { FeatureFlagService } from 'src/engine/core-modules/feature-flag/services/feature-flag.service';
|
||||
import { ToolCategory } from 'src/engine/core-modules/tool-provider/enums/tool-category.enum';
|
||||
import { ToolProviderService } from 'src/engine/core-modules/tool-provider/services/tool-provider.service';
|
||||
import { ToolType } from 'src/engine/core-modules/tool/enums/tool-type.enum';
|
||||
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
|
||||
import { RoleEntity } from 'src/engine/metadata-modules/role/role.entity';
|
||||
import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
|
||||
import { UserRoleService } from 'src/engine/metadata-modules/user-role/user-role.service';
|
||||
import { ADMIN_ROLE } from 'src/engine/workspace-manager/workspace-sync-metadata/standard-roles/roles/admin-role';
|
||||
|
||||
@Injectable()
|
||||
export class McpProtocolService {
|
||||
@@ -25,8 +24,7 @@ export class McpProtocolService {
|
||||
private readonly toolProvider: ToolProviderService,
|
||||
private readonly userRoleService: UserRoleService,
|
||||
private readonly mcpToolExecutorService: McpToolExecutorService,
|
||||
@InjectRepository(RoleEntity)
|
||||
private readonly roleRepository: Repository<RoleEntity>,
|
||||
private readonly apiKeyRoleService: ApiKeyRoleService,
|
||||
) {}
|
||||
|
||||
async checkAiEnabled(workspaceId: string): Promise<void> {
|
||||
@@ -64,18 +62,10 @@ export class McpProtocolService {
|
||||
apiKey?: ApiKeyEntity,
|
||||
) {
|
||||
if (isDefined(apiKey)) {
|
||||
const [role] = await this.roleRepository.find({
|
||||
where: {
|
||||
workspaceId,
|
||||
standardId: ADMIN_ROLE.standardId,
|
||||
},
|
||||
});
|
||||
|
||||
if (!isDefined(role)) {
|
||||
throw new HttpException('Admin role not found', HttpStatus.FORBIDDEN);
|
||||
}
|
||||
|
||||
return role.id;
|
||||
return this.apiKeyRoleService.getRoleIdForApiKeyId(
|
||||
apiKey.id,
|
||||
workspaceId,
|
||||
);
|
||||
}
|
||||
|
||||
if (!userWorkspaceId) {
|
||||
@@ -97,6 +87,21 @@ export class McpProtocolService {
|
||||
return roleId;
|
||||
}
|
||||
|
||||
private buildAuthContext(
|
||||
workspace: WorkspaceEntity,
|
||||
userWorkspaceId?: string,
|
||||
apiKey?: ApiKeyEntity,
|
||||
): WorkspaceAuthContext {
|
||||
return {
|
||||
user: null,
|
||||
apiKey: apiKey ?? null,
|
||||
application: null,
|
||||
workspace,
|
||||
workspaceMemberId: undefined,
|
||||
userWorkspaceId: userWorkspaceId ?? undefined,
|
||||
} as WorkspaceAuthContext;
|
||||
}
|
||||
|
||||
async handleMCPCoreQuery(
|
||||
{ id, method, params }: JsonRpc,
|
||||
{
|
||||
@@ -132,10 +137,17 @@ export class McpProtocolService {
|
||||
apiKey,
|
||||
);
|
||||
|
||||
const authContext = this.buildAuthContext(
|
||||
workspace,
|
||||
userWorkspaceId,
|
||||
apiKey,
|
||||
);
|
||||
|
||||
const toolSet = await this.toolProvider.getTools({
|
||||
workspaceId: workspace.id,
|
||||
categories: [ToolCategory.DATABASE_CRUD, ToolCategory.ACTION],
|
||||
rolePermissionConfig: { unionOf: [roleId] },
|
||||
authContext,
|
||||
wrapWithErrorContext: false,
|
||||
// Exclude code_interpreter from MCP to prevent recursive execution attacks
|
||||
// (code running in the sandbox could call code_interpreter via MCP)
|
||||
|
||||
Reference in New Issue
Block a user