The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Refuse application tokens on core workflow writes (#28058)
Thomas Trompette86190d3511c6
diff --git a/packages/twenty-server/src/engine/api/graphql/workspace-graphql-schema-sdl/utils/__tests__/append-core-workflow-app-operations-to-sdl.util.spec.ts b/packages/twenty-server/src/engine/api/graphql/workspace-graphql-schema-sdl/utils/__tests__/append-core-workflow-app-operations-to-sdl.util.spec.tsindex bcc04c98cbd..f80b2c7858a 100644--- a/packages/twenty-server/src/engine/api/graphql/workspace-graphql-schema-sdl/utils/__tests__/append-core-workflow-app-operations-to-sdl.util.spec.ts+++ b/packages/twenty-server/src/engine/api/graphql/workspace-graphql-schema-sdl/utils/__tests__/append-core-workflow-app-operations-to-sdl.util.spec.ts@@ -16,10 +16,7 @@ import {} from 'graphql';import { appendCoreWorkflowAppOperationsToSdl } from 'src/engine/api/graphql/workspace-graphql-schema-sdl/utils/append-core-workflow-app-operations-to-sdl.util';-import {- CORE_WORKFLOW_APP_MUTATION_NAMES,- CORE_WORKFLOW_APP_QUERY_NAMES,-} from 'src/engine/api/graphql/workspace-graphql-schema-sdl/utils/build-core-workflow-app-operations-sdl.util';+import { CORE_WORKFLOW_APP_QUERY_NAMES } from 'src/engine/api/graphql/workspace-graphql-schema-sdl/utils/build-core-workflow-app-operations-sdl.util';import { CoreWorkflowVersionMutationResolver } from 'src/engine/core-modules/workflow/resolvers/core-workflow-version-mutation.resolver';import { CoreWorkflowResolver } from 'src/engine/core-modules/workflow/resolvers/core-workflow.resolver';@@ -86,10 +83,7 @@ describe('appendCoreWorkflowAppOperationsToSdl', () => {);});- it.each([- ...CORE_WORKFLOW_APP_QUERY_NAMES,- ...CORE_WORKFLOW_APP_MUTATION_NAMES,- ])(+ it.each(CORE_WORKFLOW_APP_QUERY_NAMES)('exposes %s with the signature the core schema declares',(operationName) => {const coreField = describeField(coreSchema, operationName);@@ -99,6 +93,12 @@ describe('appendCoreWorkflowAppOperationsToSdl', () => {},);+ it('exposes no core workflow mutation', () => {+ expect(+ Object.keys(mergedSchema.getMutationType()?.getFields() ?? {}),+ ).toEqual(['createCompany']);+ });+it('carries every referenced type over unchanged', () => {const coreTypeNames = Object.values(coreSchema.getTypeMap()).filter(diff --git a/packages/twenty-server/src/engine/api/graphql/workspace-graphql-schema-sdl/utils/build-core-workflow-app-operations-sdl.util.ts b/packages/twenty-server/src/engine/api/graphql/workspace-graphql-schema-sdl/utils/build-core-workflow-app-operations-sdl.util.tsindex dfe62f5e2fa..98de552a84e 100644--- a/packages/twenty-server/src/engine/api/graphql/workspace-graphql-schema-sdl/utils/build-core-workflow-app-operations-sdl.util.ts+++ b/packages/twenty-server/src/engine/api/graphql/workspace-graphql-schema-sdl/utils/build-core-workflow-app-operations-sdl.util.ts@@ -14,7 +14,6 @@ import {} from 'graphql';import { isDefined } from 'twenty-shared/utils';-import { CoreWorkflowVersionMutationResolver } from 'src/engine/core-modules/workflow/resolvers/core-workflow-version-mutation.resolver';import { CoreWorkflowResolver } from 'src/engine/core-modules/workflow/resolvers/core-workflow.resolver';export const CORE_WORKFLOW_APP_QUERY_NAMES = [@@ -22,14 +21,6 @@ export const CORE_WORKFLOW_APP_QUERY_NAMES = ['coreWorkflowVersionsByCoreWorkflowId',];-export const CORE_WORKFLOW_APP_MUTATION_NAMES = [- 'createCoreWorkflow',- 'updateCoreWorkflowVersionTrigger',- 'createCoreWorkflowVersionStep',- 'updateCoreWorkflowVersionStep',- 'activateCoreWorkflowVersion',-];-type RootTypeConfig = ReturnType<GraphQLObjectType['toConfig']>;const pickRootType = ({@@ -67,28 +58,21 @@ const buildSlice = async (): Promise<string> => {try {const coreSchema = await applicationContext.get(GraphQLSchemaFactory)- .create([CoreWorkflowResolver, CoreWorkflowVersionMutationResolver]);+ .create([CoreWorkflowResolver]);const queryTypeConfig = coreSchema.getQueryType()?.toConfig();- const mutationTypeConfig = coreSchema.getMutationType()?.toConfig();- if (!isDefined(queryTypeConfig) || !isDefined(mutationTypeConfig)) {- throw new Error(- 'Core workflow resolvers produced no Query or Mutation type',- );+ if (!isDefined(queryTypeConfig)) {+ throw new Error('Core workflow resolvers produced no Query type');}const query = pickRootType({rootTypeConfig: queryTypeConfig,operationNames: CORE_WORKFLOW_APP_QUERY_NAMES,});- const mutation = pickRootType({- rootTypeConfig: mutationTypeConfig,- operationNames: CORE_WORKFLOW_APP_MUTATION_NAMES,- });const reachableTypes = Object.values(- new GraphQLSchema({ query, mutation }).getTypeMap(),+ new GraphQLSchema({ query }).getTypeMap(),);const interfaceImplementations = reachableTypes.filter(isInterfaceType)@@ -96,7 +80,7 @@ const buildSlice = async (): Promise<string> => {return printSchema(lexicographicSortSchema(- new GraphQLSchema({ query, mutation, types: interfaceImplementations }),+ new GraphQLSchema({ query, types: interfaceImplementations }),),);} finally {diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/providers/workflow-tool.provider.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/providers/workflow-tool.provider.tsindex ca413e26255..87fa94b4346 100644--- a/packages/twenty-server/src/engine/core-modules/tool-provider/providers/workflow-tool.provider.ts+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/providers/workflow-tool.provider.ts@@ -2,7 +2,9 @@ import { Inject, Injectable, Optional } from '@nestjs/common';import { type ToolSet } from 'ai';import { PermissionFlagType } from 'twenty-shared/constants';+import { isDefined } from 'twenty-shared/utils';+import { getScopedCallingApplication } from 'src/engine/core-modules/application/utils/get-scoped-calling-application.util';import { type GenerateDescriptorOptions } from 'src/engine/core-modules/tool-provider/interfaces/generate-descriptor-options.type';import { type ToolProvider } from 'src/engine/core-modules/tool-provider/interfaces/tool-provider.interface';import { type ToolProviderContext } from 'src/engine/core-modules/tool-provider/interfaces/tool-provider-context.type';@@ -33,7 +35,10 @@ export class WorkflowToolProvider implements ToolProvider {) {}async isAvailable(context: ToolProviderContext): Promise<boolean> {- if (!this.workflowToolService) {+ if (+ !this.workflowToolService ||+ isDefined(getScopedCallingApplication(context.application))+ ) {return false;}diff --git a/packages/twenty-server/src/engine/core-modules/workflow/resolvers/core-workflow-run.resolver.ts b/packages/twenty-server/src/engine/core-modules/workflow/resolvers/core-workflow-run.resolver.tsnew file mode 100644index 00000000000..94adbd3788b--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/workflow/resolvers/core-workflow-run.resolver.ts@@ -0,0 +1,123 @@+import { UseFilters, UseGuards, UsePipes } from '@nestjs/common';+import { Args, Mutation } from '@nestjs/graphql';++import { PermissionFlagType } from 'twenty-shared/constants';++import { CoreResolver } from 'src/engine/api/graphql/graphql-config/decorators/core-resolver.decorator';+import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';+import { type AuthContextUser } from 'src/engine/core-modules/auth/types/auth-context.type';+import { PreventNestToAutoLogGraphqlErrorsFilter } from 'src/engine/core-modules/graphql/filters/prevent-nest-to-auto-log-graphql-errors.filter';+import { ResolverValidationPipe } from 'src/engine/core-modules/graphql/pipes/resolver-validation.pipe';+import { RunCoreWorkflowVersionInput } from 'src/engine/core-modules/workflow/dtos/run-core-workflow-version.input';+import { RunWorkflowVersionDTO } from 'src/engine/core-modules/workflow/dtos/run-workflow-version.dto';+import { WorkflowQueryValidationGraphqlApiExceptionFilter } from 'src/engine/core-modules/workflow/filters/workflow-query-validation-graphql-api-exception.filter';+import { WorkflowTriggerGraphqlApiExceptionFilter } from 'src/engine/core-modules/workflow/filters/workflow-trigger-graphql-api-exception.filter';+import { WorkflowVersionEdgeGraphqlApiExceptionFilter } from 'src/engine/core-modules/workflow/filters/workflow-version-edge-graphql-api-exception.filter';+import { WorkflowVersionStepGraphqlApiExceptionFilter } from 'src/engine/core-modules/workflow/filters/workflow-version-step-graphql-api-exception.filter';+import { WorkflowVersionValidationGraphqlApiExceptionFilter } from 'src/engine/core-modules/workflow/filters/workflow-version-validation-graphql-api-exception.filter';+import { CoreWorkflowAccessService } from 'src/engine/core-modules/workflow/services/core-workflow-access.service';+import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';+import { AuthApplication } from 'src/engine/decorators/auth/auth-application.decorator';+import { AuthUserWorkspaceId } from 'src/engine/decorators/auth/auth-user-workspace-id.decorator';+import { AuthUser } from 'src/engine/decorators/auth/auth-user.decorator';+import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';+import { AuthPrincipalGuard } from 'src/engine/guards/auth-principal.guard';+import { SettingsPermissionGuard } from 'src/engine/guards/settings-permission.guard';+import { PermissionsGraphqlApiExceptionFilter } from 'src/engine/metadata-modules/permissions/utils/permissions-graphql-api-exception.filter';+import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';+import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';+import { CoreWorkflowRunnerService } from 'src/modules/workflow/workflow-runner/services/core-workflow-runner.service';+import { buildWorkflowRunTriggerContext } from 'src/modules/workflow/workflow-trigger/utils/build-workflow-run-trigger-context.util';+import { type WorkspaceMemberWorkspaceEntity } from 'src/modules/workspace-member/standard-objects/workspace-member.workspace-entity';++@CoreResolver()+@UsePipes(ResolverValidationPipe)+@UseGuards(+ AuthPrincipalGuard({+ userSession: {+ standard: true,+ impersonated: true,+ playground: true,+ workspaceAgnostic: false,+ },+ apiKey: false,+ oauthClient: { withUser: true, withoutUser: false },+ application: { withUser: true, withoutUser: false },+ }),+ SettingsPermissionGuard(PermissionFlagType.WORKFLOWS),+)+@UseFilters(+ PermissionsGraphqlApiExceptionFilter,+ PreventNestToAutoLogGraphqlErrorsFilter,+ WorkflowQueryValidationGraphqlApiExceptionFilter,+ WorkflowTriggerGraphqlApiExceptionFilter,+ WorkflowVersionEdgeGraphqlApiExceptionFilter,+ WorkflowVersionStepGraphqlApiExceptionFilter,+ WorkflowVersionValidationGraphqlApiExceptionFilter,+)+export class CoreWorkflowRunResolver {+ constructor(+ private readonly coreWorkflowRunnerService: CoreWorkflowRunnerService,+ private readonly coreWorkflowAccessService: CoreWorkflowAccessService,+ private readonly workspaceOrmManager: WorkspaceOrmManager,+ ) {}++ @Mutation(() => RunWorkflowVersionDTO)+ async runCoreWorkflowVersion(+ @AuthUser() user: AuthContextUser,+ @AuthWorkspace() { id: workspaceId }: WorkspaceEntity,+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,+ @AuthApplication({ allowUndefined: true })+ callerApplication: FlatApplication | undefined,+ @Args('input')+ {+ coreWorkflowVersionId,+ workflowRunId,+ payload,+ }: RunCoreWorkflowVersionInput,+ ): Promise<RunWorkflowVersionDTO> {+ const workspaceMember =+ await this.workspaceOrmManager.executeInWorkspaceContext(async () => {+ const workspaceMemberRepository =+ this.workspaceOrmManager.getRepository<WorkspaceMemberWorkspaceEntity>(+ 'workspaceMember',+ { shouldBypassPermissionChecks: true },+ );++ return workspaceMemberRepository.findOneOrFail({+ where: { userId: user.id },+ });+ }, buildSystemAuthContext(workspaceId));++ await this.coreWorkflowAccessService.assertCoreWorkflowVersionsAreAccessibleOrThrow(+ {+ workspaceId,+ userWorkspaceId,+ coreWorkflowVersionIds: [coreWorkflowVersionId],+ },+ );++ await this.coreWorkflowAccessService.assertCoreWorkflowVersionsAreStartableByApplicationOrThrow(+ {+ workspaceId,+ callerApplicationId: callerApplication?.id,+ coreWorkflowVersionIds: [coreWorkflowVersionId],+ },+ );++ const { payload: triggerPayload, createdBy } =+ buildWorkflowRunTriggerContext({+ workspaceMember,+ payload,+ });++ return this.coreWorkflowRunnerService.run({+ workspaceId,+ coreWorkflowVersionId,+ workflowRunId: workflowRunId ?? undefined,+ payload: triggerPayload,+ source: createdBy,+ });+ }+}diff --git a/packages/twenty-server/src/engine/core-modules/workflow/resolvers/core-workflow-version-mutation.resolver.ts b/packages/twenty-server/src/engine/core-modules/workflow/resolvers/core-workflow-version-mutation.resolver.tsindex 29e57fc7e1f..bc549ab5f8b 100644--- a/packages/twenty-server/src/engine/core-modules/workflow/resolvers/core-workflow-version-mutation.resolver.ts+++ b/packages/twenty-server/src/engine/core-modules/workflow/resolvers/core-workflow-version-mutation.resolver.ts@@ -5,8 +5,6 @@ import { PermissionFlagType } from 'twenty-shared/constants';import { CoreResolver } from 'src/engine/api/graphql/graphql-config/decorators/core-resolver.decorator';import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';-import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';-import { type AuthContextUser } from 'src/engine/core-modules/auth/types/auth-context.type';import { PreventNestToAutoLogGraphqlErrorsFilter } from 'src/engine/core-modules/graphql/filters/prevent-nest-to-auto-log-graphql-errors.filter';import { ResolverValidationPipe } from 'src/engine/core-modules/graphql/pipes/resolver-validation.pipe';import { CoreWorkflowVersionDTO } from 'src/engine/core-modules/workflow/dtos/core-workflow-version.dto';@@ -16,8 +14,6 @@ import { CreateDraftFromCoreWorkflowVersionInput } from 'src/engine/core-modulesimport { DeleteCoreWorkflowVersionEdgeInput } from 'src/engine/core-modules/workflow/dtos/delete-core-workflow-version-edge.input';import { DeleteCoreWorkflowVersionStepInput } from 'src/engine/core-modules/workflow/dtos/delete-core-workflow-version-step.input';import { DuplicateCoreWorkflowVersionStepInput } from 'src/engine/core-modules/workflow/dtos/duplicate-core-workflow-version-step.input';-import { RunCoreWorkflowVersionInput } from 'src/engine/core-modules/workflow/dtos/run-core-workflow-version.input';-import { RunWorkflowVersionDTO } from 'src/engine/core-modules/workflow/dtos/run-workflow-version.dto';import { UpdateCoreWorkflowVersionPositionsInput } from 'src/engine/core-modules/workflow/dtos/update-core-workflow-version-positions.input';import { UpdateCoreWorkflowVersionStepInput } from 'src/engine/core-modules/workflow/dtos/update-core-workflow-version-step.input';import { UpdateCoreWorkflowVersionTriggerInput } from 'src/engine/core-modules/workflow/dtos/update-core-workflow-version-trigger.input';@@ -32,19 +28,11 @@ import { WorkflowVersionValidationGraphqlApiExceptionFilter } from 'src/engine/cimport { CoreWorkflowLifecycleWorkspaceService } from 'src/engine/core-modules/workflow/services/core-workflow-lifecycle.workspace-service';import { CoreWorkflowVersionMutationWorkspaceService } from 'src/engine/core-modules/workflow/services/core-workflow-version-mutation.workspace-service';import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';-import { AuthApplication } from 'src/engine/decorators/auth/auth-application.decorator';-import { AuthUser } from 'src/engine/decorators/auth/auth-user.decorator';-import { CoreWorkflowAccessService } from 'src/engine/core-modules/workflow/services/core-workflow-access.service';import { AuthUserWorkspaceId } from 'src/engine/decorators/auth/auth-user-workspace-id.decorator';import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';import { SettingsPermissionGuard } from 'src/engine/guards/settings-permission.guard';import { AuthPrincipalGuard } from 'src/engine/guards/auth-principal.guard';import { PermissionsGraphqlApiExceptionFilter } from 'src/engine/metadata-modules/permissions/utils/permissions-graphql-api-exception.filter';-import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';-import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';-import { buildWorkflowRunTriggerContext } from 'src/modules/workflow/workflow-trigger/utils/build-workflow-run-trigger-context.util';-import { type WorkspaceMemberWorkspaceEntity } from 'src/modules/workspace-member/standard-objects/workspace-member.workspace-entity';-import { CoreWorkflowRunnerService } from 'src/modules/workflow/workflow-runner/services/core-workflow-runner.service';@CoreResolver()@UsePipes(ResolverValidationPipe)@@ -58,7 +46,7 @@ import { CoreWorkflowRunnerService } from 'src/modules/workflow/workflow-runner/},apiKey: false,oauthClient: true,- application: true,+ application: false,}),SettingsPermissionGuard(PermissionFlagType.WORKFLOWS),)@@ -75,9 +63,6 @@ export class CoreWorkflowVersionMutationResolver {constructor(private readonly coreWorkflowVersionMutationWorkspaceService: CoreWorkflowVersionMutationWorkspaceService,private readonly coreWorkflowLifecycleWorkspaceService: CoreWorkflowLifecycleWorkspaceService,- private readonly coreWorkflowRunnerService: CoreWorkflowRunnerService,- private readonly coreWorkflowAccessService: CoreWorkflowAccessService,- private readonly workspaceOrmManager: WorkspaceOrmManager,) {}@Mutation(() => Boolean)@@ -116,78 +101,6 @@ export class CoreWorkflowVersionMutationResolver {);}- @Mutation(() => RunWorkflowVersionDTO)- @UseGuards(- AuthPrincipalGuard({- userSession: {- standard: true,- impersonated: true,- playground: true,- workspaceAgnostic: false,- },- apiKey: false,- oauthClient: { withUser: true, withoutUser: false },- application: { withUser: true, withoutUser: false },- }),- )- async runCoreWorkflowVersion(- @AuthUser() user: AuthContextUser,- @AuthWorkspace() { id: workspaceId }: WorkspaceEntity,- @AuthUserWorkspaceId({ allowUndefined: true })- userWorkspaceId: string | undefined,- @AuthApplication({ allowUndefined: true })- callerApplication: FlatApplication | undefined,- @Args('input')- {- coreWorkflowVersionId,- workflowRunId,- payload,- }: RunCoreWorkflowVersionInput,- ): Promise<RunWorkflowVersionDTO> {- const workspaceMember =- await this.workspaceOrmManager.executeInWorkspaceContext(async () => {- const workspaceMemberRepository =- this.workspaceOrmManager.getRepository<WorkspaceMemberWorkspaceEntity>(- 'workspaceMember',- { shouldBypassPermissionChecks: true },- );-- return workspaceMemberRepository.findOneOrFail({- where: { userId: user.id },- });- }, buildSystemAuthContext(workspaceId));-- await this.coreWorkflowAccessService.assertCoreWorkflowVersionsAreAccessibleOrThrow(- {- workspaceId,- userWorkspaceId,- coreWorkflowVersionIds: [coreWorkflowVersionId],- },- );-- await this.coreWorkflowAccessService.assertCoreWorkflowVersionsAreStartableByApplicationOrThrow(- {- workspaceId,- callerApplicationId: callerApplication?.id,- coreWorkflowVersionIds: [coreWorkflowVersionId],- },- );-- const { payload: triggerPayload, createdBy } =- buildWorkflowRunTriggerContext({- workspaceMember,- payload,- });-- return this.coreWorkflowRunnerService.run({- workspaceId,- coreWorkflowVersionId,- workflowRunId: workflowRunId ?? undefined,- payload: triggerPayload,- source: createdBy,- });- }-@Mutation(() => CoreWorkflowVersionDTO)async createDraftFromCoreWorkflowVersion(@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,diff --git a/packages/twenty-server/src/engine/core-modules/workflow/resolvers/core-workflow.resolver.ts b/packages/twenty-server/src/engine/core-modules/workflow/resolvers/core-workflow.resolver.tsindex e35faa3a261..1408213200e 100644--- a/packages/twenty-server/src/engine/core-modules/workflow/resolvers/core-workflow.resolver.ts+++ b/packages/twenty-server/src/engine/core-modules/workflow/resolvers/core-workflow.resolver.ts@@ -94,6 +94,19 @@ export class CoreWorkflowResolver {}@Mutation(() => CoreWorkflowDTO, { nullable: true })+ @UseGuards(+ AuthPrincipalGuard({+ userSession: {+ standard: true,+ impersonated: true,+ playground: true,+ workspaceAgnostic: false,+ },+ apiKey: false,+ oauthClient: true,+ application: false,+ }),+ )async updateCoreWorkflow(@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,@AuthUserWorkspaceId({ allowUndefined: true })@@ -114,6 +127,19 @@ export class CoreWorkflowResolver {}@Mutation(() => CoreWorkflowDTO, { nullable: true })+ @UseGuards(+ AuthPrincipalGuard({+ userSession: {+ standard: true,+ impersonated: true,+ playground: true,+ workspaceAgnostic: false,+ },+ apiKey: false,+ oauthClient: true,+ application: false,+ }),+ )async updateCoreWorkflowVisibility(@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,@AuthUserWorkspaceId() userWorkspaceId: string,@@ -127,6 +153,19 @@ export class CoreWorkflowResolver {}@Mutation(() => CoreWorkflowDTO)+ @UseGuards(+ AuthPrincipalGuard({+ userSession: {+ standard: true,+ impersonated: true,+ playground: true,+ workspaceAgnostic: false,+ },+ apiKey: false,+ oauthClient: true,+ application: false,+ }),+ )async duplicateCoreWorkflow(@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,@AuthWorkspaceMember() workspaceMember:@@ -153,6 +192,19 @@ export class CoreWorkflowResolver {}@Mutation(() => CoreWorkflowDTO)+ @UseGuards(+ AuthPrincipalGuard({+ userSession: {+ standard: true,+ impersonated: true,+ playground: true,+ workspaceAgnostic: false,+ },+ apiKey: false,+ oauthClient: true,+ application: false,+ }),+ )async createCoreWorkflow(@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,@AuthWorkspaceMember() workspaceMember:@@ -174,6 +226,19 @@ export class CoreWorkflowResolver {}@Mutation(() => [DeletedCoreWorkflowDTO])+ @UseGuards(+ AuthPrincipalGuard({+ userSession: {+ standard: true,+ impersonated: true,+ playground: true,+ workspaceAgnostic: false,+ },+ apiKey: false,+ oauthClient: true,+ application: false,+ }),+ )async deleteCoreWorkflows(@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,@AuthUserWorkspaceId({ allowUndefined: true })@@ -188,6 +253,19 @@ export class CoreWorkflowResolver {}@Mutation(() => CoreWorkflowDTO, { nullable: true })+ @UseGuards(+ AuthPrincipalGuard({+ userSession: {+ standard: true,+ impersonated: true,+ playground: true,+ workspaceAgnostic: false,+ },+ apiKey: false,+ oauthClient: true,+ application: false,+ }),+ )async discardCoreWorkflowDraft(@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,@AuthUserWorkspaceId({ allowUndefined: true })diff --git a/packages/twenty-server/src/engine/core-modules/workflow/workflow-api.module.ts b/packages/twenty-server/src/engine/core-modules/workflow/workflow-api.module.tsindex 209ef02afe9..db4745faa45 100644--- a/packages/twenty-server/src/engine/core-modules/workflow/workflow-api.module.ts+++ b/packages/twenty-server/src/engine/core-modules/workflow/workflow-api.module.ts@@ -6,6 +6,7 @@ import { TypeOrmModule } from '@nestjs/typeorm';import { ToolModule } from 'src/engine/core-modules/tool/tool.module';import { WorkflowTriggerController } from 'src/engine/core-modules/workflow/controllers/workflow-trigger.controller';import { CoreWorkflowResolver } from 'src/engine/core-modules/workflow/resolvers/core-workflow.resolver';+import { CoreWorkflowRunResolver } from 'src/engine/core-modules/workflow/resolvers/core-workflow-run.resolver';import { CoreWorkflowVersionMutationResolver } from 'src/engine/core-modules/workflow/resolvers/core-workflow-version-mutation.resolver';import { WorkflowBuilderResolver } from 'src/engine/core-modules/workflow/resolvers/workflow-builder.resolver';import { WorkflowTriggerResolver } from 'src/engine/core-modules/workflow/resolvers/workflow-trigger.resolver';@@ -49,6 +50,7 @@ import { WorkflowTriggerModule } from 'src/modules/workflow/workflow-trigger/worWorkflowVersionStepResolver,CoreWorkflowResolver,CoreWorkflowVersionMutationResolver,+ CoreWorkflowRunResolver,provideWorkspaceScopedRepository(WorkflowVersionEntity),],})diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.tsindex edf8a1854f4..eceb64ce9d2 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.ts@@ -11,7 +11,10 @@ import {type StepResult,type ToolSet,} from 'ai';-import { type RunAgentMessage } from 'twenty-shared/application';+import {+ type RunAgentMessage,+ TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER,+} from 'twenty-shared/application';import {ASK_QUESTION_TOOL_NAME,type AgentResponseFormat,@@ -27,6 +30,8 @@ import {} from 'twenty-shared/utils';import { type Repository } from 'typeorm';+import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';+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 { TOOL_EXECUTION_DURATION_MS_BUCKET_BOUNDARIES } from 'src/engine/core-modules/metrics/constants/tool-execution-duration-ms-bucket-boundaries.constant';@@ -108,6 +113,7 @@ type RegistryToolContext = Pick<ToolContext,| 'workspaceId'| 'authContext'+ | 'application'| 'actorContext'| 'userId'| 'userWorkspaceId'@@ -160,6 +166,40 @@ export class AgentAsyncExecutorService {return {};}+ private resolveCallingApplication(+ authContext?: WorkspaceAuthContext,+ ): FlatApplication | undefined {+ if (!isDefined(authContext)) {+ return undefined;+ }++ const application = this.getAuthContextApplication(authContext);++ if (+ application?.id === authContext.workspace.workspaceCustomApplicationId ||+ application?.universalIdentifier ===+ TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER+ ) {+ return undefined;+ }++ return application;+ }++ private getAuthContextApplication(+ authContext: WorkspaceAuthContext,+ ): FlatApplication | undefined {+ if (isApplicationAuthContext(authContext)) {+ return authContext.application;+ }++ if (isUserAuthContext(authContext)) {+ return authContext.application ?? authContext.viaApplication;+ }++ return undefined;+ }+// preloading the few granted object schemas saves the model a learn_tools round tripprivate async buildPreloadedRegistryTools({toolContext,@@ -231,13 +271,19 @@ export class AgentAsyncExecutorService {agentRunRoleIds,}),};- const { workspaceId, userId, userWorkspaceId, rolePermissionConfig } =- toolContext;+ const {+ workspaceId,+ userId,+ userWorkspaceId,+ rolePermissionConfig,+ application,+ } = toolContext;const fullCatalog = await this.toolRegistry.buildToolIndex(workspaceId, {userId,userWorkspaceId,rolePermissionConfig,+ application,});const allowedCategories = new Set(@@ -407,6 +453,7 @@ export class AgentAsyncExecutorService {workspaceId: agent.workspaceId,agentId: agent.id,authContext,+ application: this.resolveCallingApplication(authContext),actorContext,...this.resolveUserIdentity(authContext),};diff --git a/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap b/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snapindex d1c1923bc8f..949cd9153ab 100644--- a/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap+++ b/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap@@ -247,24 +247,24 @@ exports[`endpoint permission declarations should match the AuthPrincipalGuard an"CoreWorkflowResolver.coreWorkflowVersionsByCoreWorkflowId {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}","CoreWorkflowResolver.coreWorkflows {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}","CoreWorkflowResolver.coreWorkflowsWithCurrentVersions {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",- "CoreWorkflowResolver.createCoreWorkflow {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",- "CoreWorkflowResolver.deleteCoreWorkflows {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",- "CoreWorkflowResolver.discardCoreWorkflowDraft {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",- "CoreWorkflowResolver.duplicateCoreWorkflow {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",- "CoreWorkflowResolver.updateCoreWorkflow {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",- "CoreWorkflowResolver.updateCoreWorkflowVisibility {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",- "CoreWorkflowVersionMutationResolver.activateCoreWorkflowVersion {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",- "CoreWorkflowVersionMutationResolver.createCoreWorkflowVersionEdge {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",- "CoreWorkflowVersionMutationResolver.createCoreWorkflowVersionStep {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",- "CoreWorkflowVersionMutationResolver.createDraftFromCoreWorkflowVersion {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",- "CoreWorkflowVersionMutationResolver.deactivateCoreWorkflowVersion {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",- "CoreWorkflowVersionMutationResolver.deleteCoreWorkflowVersionEdge {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",- "CoreWorkflowVersionMutationResolver.deleteCoreWorkflowVersionStep {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",- "CoreWorkflowVersionMutationResolver.duplicateCoreWorkflowVersionStep {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",- "CoreWorkflowVersionMutationResolver.runCoreWorkflowVersion {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}},{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",- "CoreWorkflowVersionMutationResolver.updateCoreWorkflowVersionPositions {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",- "CoreWorkflowVersionMutationResolver.updateCoreWorkflowVersionStep {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",- "CoreWorkflowVersionMutationResolver.updateCoreWorkflowVersionTrigger {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",+ "CoreWorkflowResolver.createCoreWorkflow {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}},{"apiKey":false,"application":{"withAgent":false,"withUser":false,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",+ "CoreWorkflowResolver.deleteCoreWorkflows {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}},{"apiKey":false,"application":{"withAgent":false,"withUser":false,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",+ "CoreWorkflowResolver.discardCoreWorkflowDraft {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}},{"apiKey":false,"application":{"withAgent":false,"withUser":false,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",+ "CoreWorkflowResolver.duplicateCoreWorkflow {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}},{"apiKey":false,"application":{"withAgent":false,"withUser":false,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",+ "CoreWorkflowResolver.updateCoreWorkflow {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}},{"apiKey":false,"application":{"withAgent":false,"withUser":false,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",+ "CoreWorkflowResolver.updateCoreWorkflowVisibility {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}},{"apiKey":false,"application":{"withAgent":false,"withUser":false,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",+ "CoreWorkflowRunResolver.runCoreWorkflowVersion {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",+ "CoreWorkflowVersionMutationResolver.activateCoreWorkflowVersion {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":false,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",+ "CoreWorkflowVersionMutationResolver.createCoreWorkflowVersionEdge {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":false,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",+ "CoreWorkflowVersionMutationResolver.createCoreWorkflowVersionStep {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":false,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",+ "CoreWorkflowVersionMutationResolver.createDraftFromCoreWorkflowVersion {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":false,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",+ "CoreWorkflowVersionMutationResolver.deactivateCoreWorkflowVersion {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":false,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",+ "CoreWorkflowVersionMutationResolver.deleteCoreWorkflowVersionEdge {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":false,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",+ "CoreWorkflowVersionMutationResolver.deleteCoreWorkflowVersionStep {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":false,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",+ "CoreWorkflowVersionMutationResolver.duplicateCoreWorkflowVersionStep {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":false,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",+ "CoreWorkflowVersionMutationResolver.updateCoreWorkflowVersionPositions {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":false,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",+ "CoreWorkflowVersionMutationResolver.updateCoreWorkflowVersionStep {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":false,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",+ "CoreWorkflowVersionMutationResolver.updateCoreWorkflowVersionTrigger {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":false,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}","CreateCalendarEventResolver.createCalendarEvent {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}","DashboardController.duplicate {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}","DashboardResolver.duplicateDashboard {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-application-auth.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-application-auth.integration-spec.tsindex 6e2ece53f42..85417b935da 100644--- a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-application-auth.integration-spec.ts+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-application-auth.integration-spec.ts@@ -2,11 +2,13 @@ import crypto from 'crypto';import bcrypt from 'bcrypt';import request from 'supertest';+import { callMcpTool } from 'test/integration/graphql/suites/application-role-intersection/utils/call-mcp-tool.util';import { buildBaseManifest } from 'test/integration/metadata/suites/application/utils/build-base-manifest.util';import { cleanupApplicationAndAppRegistration } from 'test/integration/metadata/suites/application/utils/cleanup-application-and-app-registration.util';import { setupApplicationForSync } from 'test/integration/metadata/suites/application/utils/setup-application-for-sync.util';import { syncApplication } from 'test/integration/metadata/suites/application/utils/sync-application.util';import { generateAppleAdminApplicationTokenPair } from 'test/integration/utils/generate-apple-admin-application-token-pair.util';+import { ToolCategory } from 'twenty-shared/ai';import { SystemPermissionFlag } from 'twenty-shared/constants';import {@@ -154,6 +156,12 @@ const UPDATE_CORE_TRIGGER = `}`;+const ACTIVATE_CORE_WORKFLOW_VERSION = `+ mutation ActivateCoreWorkflowVersion($coreWorkflowVersionId: UUID!) {+ activateCoreWorkflowVersion(coreWorkflowVersionId: $coreWorkflowVersionId)+ }+`;+const MANUAL_TRIGGER = {name: 'Manual Trigger',type: 'MANUAL',@@ -179,12 +187,12 @@ const APP_SCHEMA_INTROSPECTION = `}`;-const CORE_WORKFLOW_SEEDING_QUERY_FIELDS = [+const CORE_WORKFLOW_APP_QUERY_FIELDS = ['coreWorkflows','coreWorkflowVersionsByCoreWorkflowId',];-const CORE_WORKFLOW_SEEDING_MUTATION_FIELDS = [+const CORE_WORKFLOW_WRITE_FIELDS = ['createCoreWorkflow','createCoreWorkflowVersionStep','updateCoreWorkflowVersionStep',@@ -192,6 +200,28 @@ const CORE_WORKFLOW_SEEDING_MUTATION_FIELDS = ['activateCoreWorkflowVersion',];+const getMcpToolCatalog = async (+ token: string,+): Promise<Record<string, { name: string }[]>> => {+ const result = await callMcpTool({ toolName: 'get_tool_catalog', token });++ expect(result.isError).toBe(false);++ return JSON.parse(result.content[0].text).catalog;+};++const createCoreWorkflowAsMember = async (name: string) => {+ const createResponse = await graphqlAs(+ APPLE_JANE_ADMIN_ACCESS_TOKEN,+ CREATE_CORE_WORKFLOW,+ { input: { name } },+ );++ expect(createResponse.body.errors).toBeUndefined();++ return createResponse.body.data.createCoreWorkflow.id as string;+};+describe('core workflow API with application credentials (integration)', () => {let authorizedApplication: InstalledTestApplication;let deniedApplication: InstalledTestApplication;@@ -213,7 +243,7 @@ describe('core workflow API with application credentials (integration)', () => {afterAll(async () => {if (coreWorkflowIdsToDelete.length > 0) {await graphqlAs(- authorizedApplication.accessToken,+ APPLE_JANE_ADMIN_ACCESS_TOKEN,`mutation DeleteCoreWorkflows($input: DeleteCoreWorkflowsInput!) {deleteCoreWorkflows(input: $input) {@@ -235,61 +265,52 @@ describe('core workflow API with application credentials (integration)', () => {});});- it('should let an application without a human user create and configure a workflow', async () => {- const createResponse = await graphqlAs(+ it('should refuse an application without a human user creating a workflow', async () => {+ const response = await graphqlAs(authorizedApplication.accessToken,CREATE_CORE_WORKFLOW,- { input: { name: `App seeded workflow ${crypto.randomUUID()}` } },+ { input: { name: `App created workflow ${crypto.randomUUID()}` } },);- expect(createResponse.body.errors).toBeUndefined();+ expect(response.body.errors?.[0]?.extensions?.code).toBe('FORBIDDEN');+ expect(response.body.data?.createCoreWorkflow).toBeFalsy();+ });- const coreWorkflowId = createResponse.body.data.createCoreWorkflow.id;+ it('should refuse an application configuring and activating a workflow a member created', async () => {+ const coreWorkflowId = await createCoreWorkflowAsMember(+ `Member created workflow ${crypto.randomUUID()}`,+ );coreWorkflowIdsToDelete.push(coreWorkflowId);const versionsResponse = await graphqlAs(- authorizedApplication.accessToken,+ APPLE_JANE_ADMIN_ACCESS_TOKEN,CORE_WORKFLOW_VERSIONS,{ coreWorkflowId },);- expect(versionsResponse.body.errors).toBeUndefined();-- const versions =+ const [{ id: coreWorkflowVersionId }] =versionsResponse.body.data.coreWorkflowVersionsByCoreWorkflowId;- expect(versions).toHaveLength(1);- expect(versions[0].status).toBe('DRAFT');-const triggerResponse = await graphqlAs(authorizedApplication.accessToken,UPDATE_CORE_TRIGGER,- {- input: {- coreWorkflowVersionId: versions[0].id,- trigger: MANUAL_TRIGGER,- },- },+ { input: { coreWorkflowVersionId, trigger: MANUAL_TRIGGER } },);- expect(triggerResponse.body.errors).toBeUndefined();- });+ expect(triggerResponse.body.errors?.[0]?.extensions?.code).toBe(+ 'FORBIDDEN',+ );- it('should attribute the created workflow to the application rather than to a workspace member', async () => {- const createResponse = await graphqlAs(+ const activateResponse = await graphqlAs(authorizedApplication.accessToken,- CREATE_CORE_WORKFLOW,- { input: { name: `App attributed workflow ${crypto.randomUUID()}` } },+ ACTIVATE_CORE_WORKFLOW_VERSION,+ { coreWorkflowVersionId },);- expect(createResponse.body.errors).toBeUndefined();-- const { id: coreWorkflowId } = createResponse.body.data.createCoreWorkflow;-- coreWorkflowIdsToDelete.push(coreWorkflowId);-- expect(await findCoreWorkflowCreator(coreWorkflowId)).toBeNull();+ expect(activateResponse.body.errors?.[0]?.extensions?.code).toBe(+ 'FORBIDDEN',+ );});it('should attribute the workflow to the workspace member when a user creates it', async () => {@@ -308,27 +329,20 @@ describe('core workflow API with application credentials (integration)', () => {expect(await findCoreWorkflowCreator(coreWorkflowId)).not.toBeNull();});- it('should keep the application role when a user acts through the application', async () => {+ it('should refuse a user acting through an application creating a workflow', async () => {const { applicationAccessToken } =await generateAppleAdminApplicationTokenPair({applicationId: authorizedApplication.applicationId,});- const delegatedToken = applicationAccessToken.token;-- const createResponse = await graphqlAs(- delegatedToken,+ const response = await graphqlAs(+ applicationAccessToken.token,CREATE_CORE_WORKFLOW,{ input: { name: `Delegated workflow ${crypto.randomUUID()}` } },);- expect(createResponse.body.errors).toBeUndefined();-- const { id: coreWorkflowId } = createResponse.body.data.createCoreWorkflow;-- coreWorkflowIdsToDelete.push(coreWorkflowId);-- expect(await findCoreWorkflowCreator(coreWorkflowId)).not.toBeNull();+ expect(response.body.errors?.[0]?.extensions?.code).toBe('FORBIDDEN');+ expect(response.body.data?.createCoreWorkflow).toBeFalsy();});it('should refuse an API key, which is neither a user nor an application', async () => {@@ -360,12 +374,14 @@ describe('core workflow API with application credentials (integration)', () => {it('should deny an application whose role does not grant the workflows permission', async () => {const response = await graphqlAs(deniedApplication.accessToken,- CREATE_CORE_WORKFLOW,- { input: { name: `Denied workflow ${crypto.randomUUID()}` } },+ CORE_WORKFLOW_VERSIONS,+ { coreWorkflowId: crypto.randomUUID() },);expect(response.body.errors?.[0]?.extensions?.code).toBe('FORBIDDEN');- expect(response.body.data?.createCoreWorkflow).toBeFalsy();+ expect(+ response.body.data?.coreWorkflowVersionsByCoreWorkflowId,+ ).toBeFalsy();});it('should not expose a core workflow that belongs to another workspace', async () => {@@ -417,7 +433,7 @@ describe('core workflow API with application credentials (integration)', () => {expect(response.body.data?.createCoreWorkflow).toBeFalsy();});- it('should expose the core workflow operations the app SDK client seeds with', async () => {+ it('should expose the core workflow reads but no workflow write to the app SDK client', async () => {const response = await graphqlAs(authorizedApplication.accessToken,APP_SCHEMA_INTROSPECTION,@@ -432,43 +448,41 @@ describe('core workflow API with application credentials (integration)', () => {response.body.data?.__schema?.mutationType?.fields ?? []).map((field: { name: string }) => field.name);- for (const fieldName of CORE_WORKFLOW_SEEDING_QUERY_FIELDS) {+ for (const fieldName of CORE_WORKFLOW_APP_QUERY_FIELDS) {expect(queryFieldNames).toContain(fieldName);}- for (const fieldName of CORE_WORKFLOW_SEEDING_MUTATION_FIELDS) {- expect(mutationFieldNames).toContain(fieldName);+ for (const fieldName of CORE_WORKFLOW_WRITE_FIELDS) {+ expect(mutationFieldNames).not.toContain(fieldName);}});- it('should let the application read back a workflow it just created', async () => {- const workflowName = `Seeded enrichment workflow ${crypto.randomUUID()}`;-- const createResponse = await graphqlAs(+ it('should not offer workflow tools to an application over MCP', async () => {+ const applicationCatalog = await getMcpToolCatalog(authorizedApplication.accessToken,- CREATE_CORE_WORKFLOW,- { input: { name: workflowName } },+ );+ const memberCatalog = await getMcpToolCatalog(+ APPLE_JANE_ADMIN_ACCESS_TOKEN,);- expect(createResponse.body.errors).toBeUndefined();-- const createdCoreWorkflowId =- createResponse.body.data?.createCoreWorkflow?.id;+ expect(applicationCatalog[ToolCategory.WORKFLOW]).toBeUndefined();+ expect(memberCatalog[ToolCategory.WORKFLOW]?.length).toBeGreaterThan(0);+ });- expect(createdCoreWorkflowId).toBeDefined();+ it('should let the application read a workflow a member created', async () => {+ const workflowName = `Member workflow read by app ${crypto.randomUUID()}`;+ const coreWorkflowId = await createCoreWorkflowAsMember(workflowName);- coreWorkflowIdsToDelete.push(createdCoreWorkflowId);+ coreWorkflowIdsToDelete.push(coreWorkflowId);const readResponse = await graphqlAs(authorizedApplication.accessToken,CORE_WORKFLOW_BY_ID,- { coreWorkflowId: createdCoreWorkflowId },+ { coreWorkflowId },);expect(readResponse.body.errors).toBeUndefined();- expect(readResponse.body.data?.coreWorkflowById?.id).toBe(- createdCoreWorkflowId,- );+ expect(readResponse.body.data?.coreWorkflowById?.id).toBe(coreWorkflowId);expect(readResponse.body.data?.coreWorkflowById?.name).toBe(workflowName);});});