Skip to content

The open alternative to Salesforce, designed for AI.

fix(workflow): make a private workflow's runs private too (#26761)

Félix Malfait2ac7c628b5a1
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-upgrade-version-command.module.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-upgrade-version-command.module.ts
index d3fe3a20bd8..d9071f7df90 100644
--- a/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-upgrade-version-command.module.ts
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-upgrade-version-command.module.ts
@@ -4,11 +4,14 @@ import { WorkspaceIteratorModule } from 'src/database/commands/command-runners/w
import { RenameCallRecordingTabsToTranscriptCommand } from 'src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790583246061-rename-call-recording-tabs-to-transcript.command';
import { VerifyCommonRecordSharingCommand } from 'src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790590808102-verify-common-record-sharing.command';
import { DeleteFieldLessIndexMetadataCommand } from 'src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790595494562-delete-field-less-index-metadata.command';
+import { FollowWorkflowVisibilityOnRunsCommand } from 'src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790595877162-follow-workflow-visibility-on-runs.command';
+import { ApplicationModule } from 'src/engine/core-modules/application/application.module';
import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
import { WorkspaceMigrationModule } from 'src/engine/workspace-manager/workspace-migration/workspace-migration.module';
@Module({
imports: [
+ ApplicationModule,
WorkspaceCacheModule,
WorkspaceIteratorModule,
WorkspaceMigrationModule,
@@ -17,6 +20,7 @@ import { WorkspaceMigrationModule } from 'src/engine/workspace-manager/workspace
RenameCallRecordingTabsToTranscriptCommand,
VerifyCommonRecordSharingCommand,
DeleteFieldLessIndexMetadataCommand,
+ FollowWorkflowVisibilityOnRunsCommand,
],
})
export class V2_44_UpgradeVersionCommandModule {}
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790595877162-follow-workflow-visibility-on-runs.command.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790595877162-follow-workflow-visibility-on-runs.command.ts
new file mode 100644
index 00000000000..168d5f9c709
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790595877162-follow-workflow-visibility-on-runs.command.ts
@@ -0,0 +1,218 @@
+import { InjectDataSource } from '@nestjs/typeorm';
+import { Command } from 'nest-commander';
+import { STANDARD_OBJECTS } from 'twenty-shared/metadata';
+import { MetadataReadability } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+import { DataSource } from 'typeorm';
+
+import { ProvisionedWorkspaceCommandRunner } from 'src/database/commands/command-runners/provisioned-workspace.command-runner';
+import { WorkspaceIteratorService } from 'src/database/commands/command-runners/workspace-iterator.service';
+import { type RunOnWorkspaceArgs } from 'src/database/commands/command-runners/workspace.command-runner';
+import { ApplicationService } from 'src/engine/core-modules/application/application.service';
+import { RegisteredWorkspaceCommand } from 'src/engine/core-modules/upgrade/decorators/registered-workspace-command.decorator';
+import { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';
+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';
+import { WorkspaceMigrationBuilderException } from 'src/engine/workspace-manager/workspace-migration/exceptions/workspace-migration-builder-exception';
+import { WorkspaceMigrationValidateBuildAndRunService } from 'src/engine/workspace-manager/workspace-migration/services/workspace-migration-validate-build-and-run-service';
+import { escapeIdentifier } from 'src/engine/workspace-manager/workspace-migration/utils/remove-sql-injection.util';
+
+// Copied rather than imported: this command must keep granting exactly this
+// set whatever the runtime rule becomes later.
+const EVERYONE_PRINCIPAL_ID = '5047ca8f-514a-4609-8ef4-1bb63f3084c5';
+
+// A private workflow's runs were readable by anyone whose role could read
+// runs. Runs are now private records whose grants mirror their core workflow's
+// visibility. Grants are written before readability changes, so no run is
+// unreadable in between, and a retry rewrites the same derived set.
+@RegisteredWorkspaceCommand('2.44.0', 1790595877162)
+@Command({
+ name: 'upgrade:2-44:follow-workflow-visibility-on-runs',
+ description:
+ "Grant each workflow run its core workflow's visibility, then make runs private",
+})
+export class FollowWorkflowVisibilityOnRunsCommand extends ProvisionedWorkspaceCommandRunner {
+ constructor(
+ protected readonly workspaceIteratorService: WorkspaceIteratorService,
+ private readonly applicationService: ApplicationService,
+ private readonly workspaceCacheService: WorkspaceCacheService,
+ private readonly workspaceMigrationValidateBuildAndRunService: WorkspaceMigrationValidateBuildAndRunService,
+ @InjectDataSource() private readonly dataSource: DataSource,
+ ) {
+ super(workspaceIteratorService);
+ }
+
+ override async runOnWorkspace(args: RunOnWorkspaceArgs): Promise<void> {
+ await this.up(args);
+ }
+
+ async up({ workspaceId, options }: RunOnWorkspaceArgs): Promise<void> {
+ const { flatObjectMetadataMaps } =
+ await this.workspaceCacheService.getOrRecompute(workspaceId, [
+ 'flatObjectMetadataMaps',
+ ]);
+
+ const workflowRunObject =
+ flatObjectMetadataMaps.byUniversalIdentifier[
+ STANDARD_OBJECTS.workflowRun.universalIdentifier
+ ];
+ const recordShareObject =
+ flatObjectMetadataMaps.byUniversalIdentifier[
+ STANDARD_OBJECTS.recordShare.universalIdentifier
+ ];
+
+ if (!isDefined(workflowRunObject) || !isDefined(recordShareObject)) {
+ this.logger.log(
+ `Workflow run or record share objects missing for workspace ${workspaceId}, skipping`,
+ );
+
+ return;
+ }
+
+ if (options.dryRun ?? false) {
+ this.logger.log(
+ `[DRY RUN] Would grant workflow runs their workflow's visibility and make them private for workspace ${workspaceId}`,
+ );
+
+ return;
+ }
+
+ await this.grantWorkflowRunVisibility(workspaceId);
+
+ const { twentyStandardFlatApplication } =
+ await this.applicationService.findWorkspaceTwentyStandardAndCustomApplicationOrThrow(
+ { workspaceId },
+ );
+
+ const flatObjectMetadatasToUpdate: FlatObjectMetadata[] = [
+ {
+ ...workflowRunObject,
+ readability: MetadataReadability.PRIVATE,
+ readabilityParentFieldUniversalIdentifiers: null,
+ },
+ ];
+
+ const result =
+ await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunLegacyWorkspaceMigration(
+ {
+ workspaceId,
+ isSystemBuild: true,
+ applicationUniversalIdentifier:
+ twentyStandardFlatApplication.universalIdentifier,
+ allFlatEntityOperationByMetadataName: {
+ objectMetadata: {
+ flatEntityToCreate: [],
+ flatEntityToDelete: [],
+ flatEntityToUpdate: flatObjectMetadatasToUpdate,
+ },
+ },
+ },
+ );
+
+ if (result.status === 'fail') {
+ throw new WorkspaceMigrationBuilderException(result);
+ }
+ }
+
+ async down({ workspaceId }: RunOnWorkspaceArgs): Promise<void> {
+ const { flatObjectMetadataMaps } =
+ await this.workspaceCacheService.getOrRecompute(workspaceId, [
+ 'flatObjectMetadataMaps',
+ ]);
+ const { twentyStandardFlatApplication } =
+ await this.applicationService.findWorkspaceTwentyStandardAndCustomApplicationOrThrow(
+ { workspaceId },
+ );
+
+ const flatObjectMetadatasToUpdate = [
+ flatObjectMetadataMaps.byUniversalIdentifier[
+ STANDARD_OBJECTS.workflowRun.universalIdentifier
+ ],
+ ]
+ .filter(isDefined)
+ .map((flatObjectMetadata) => ({
+ ...flatObjectMetadata,
+ readability: MetadataReadability.OPEN,
+ readabilityParentFieldUniversalIdentifiers: null,
+ }));
+
+ // The grants stay: they are inert once the objects are open again.
+ const result =
+ await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunLegacyWorkspaceMigration(
+ {
+ workspaceId,
+ isSystemBuild: true,
+ applicationUniversalIdentifier:
+ twentyStandardFlatApplication.universalIdentifier,
+ allFlatEntityOperationByMetadataName: {
+ objectMetadata: {
+ flatEntityToCreate: [],
+ flatEntityToDelete: [],
+ flatEntityToUpdate: flatObjectMetadatasToUpdate,
+ },
+ },
+ },
+ );
+
+ if (result.status === 'fail') {
+ throw new WorkspaceMigrationBuilderException(result);
+ }
+ }
+
+ private async grantWorkflowRunVisibility(
+ workspaceId: string,
+ ): Promise<void> {
+ const schemaName = escapeIdentifier(getWorkspaceSchemaName(workspaceId));
+ const parameters = [
+ workspaceId,
+ STANDARD_OBJECTS.workflowRun.universalIdentifier,
+ ];
+
+ await this.dataSource.transaction(async (manager) => {
+ await manager.query(
+ `DELETE FROM ${schemaName}."recordShare" share
+ USING core."objectMetadata" metadata
+ WHERE metadata.id = share."objectMetadataId"
+ AND metadata."workspaceId" = $1
+ AND metadata."universalIdentifier" = $2
+ AND (
+ share."sourceId" = share."recordId"
+ OR share."rowCause" = 'APPLICATION'
+ OR share."principalType" = 'EVERYONE'
+ )`,
+ parameters,
+ );
+
+ await manager.query(
+ `INSERT INTO ${schemaName}."recordShare"
+ ("objectMetadataId", "recordId", "principalId", "principalType", "accessLevel", "rowCause", "sourceId")
+ SELECT metadata.id, run.id, '${EVERYONE_PRINCIPAL_ID}', 'EVERYONE', 'FULL', 'RULE', run.id
+ FROM ${schemaName}."workflowRun" run
+ JOIN core."objectMetadata" metadata ON metadata."workspaceId" = $1 AND metadata."universalIdentifier" = $2
+ LEFT JOIN core."workflow" core_workflow ON core_workflow.id = run."coreWorkflowId"
+ AND core_workflow."workspaceId" = $1
+ WHERE core_workflow.id IS NULL
+ OR core_workflow."visibility" = 'WORKSPACE'
+ OR core_workflow."createdByUserWorkspaceId" IS NULL
+ ON CONFLICT DO NOTHING`,
+ parameters,
+ );
+
+ await manager.query(
+ `INSERT INTO ${schemaName}."recordShare"
+ ("objectMetadataId", "recordId", "principalId", "principalType", "accessLevel", "rowCause", "sourceId")
+ SELECT metadata.id, run.id, member.id, 'WORKSPACE_MEMBER', 'FULL', 'OWNER', run.id
+ FROM ${schemaName}."workflowRun" run
+ JOIN core."objectMetadata" metadata ON metadata."workspaceId" = $1 AND metadata."universalIdentifier" = $2
+ JOIN core."workflow" core_workflow ON core_workflow.id = run."coreWorkflowId"
+ AND core_workflow."workspaceId" = $1
+ JOIN core."userWorkspace" membership ON membership.id = core_workflow."createdByUserWorkspaceId"
+ AND membership."workspaceId" = $1 AND membership."deletedAt" IS NULL
+ JOIN ${schemaName}."workspaceMember" member ON member."userId" = membership."userId"
+ AND member."deletedAt" IS NULL
+ ON CONFLICT DO NOTHING`,
+ parameters,
+ );
+ });
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/record-share/services/record-share-storage.service.ts b/packages/twenty-server/src/engine/core-modules/record-share/services/record-share-storage.service.ts
index 0e3441e7881..dc34eacfcc7 100644
--- a/packages/twenty-server/src/engine/core-modules/record-share/services/record-share-storage.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/record-share/services/record-share-storage.service.ts
@@ -5,7 +5,7 @@ import { escapeIdentifier } from 'src/engine/workspace-manager/workspace-migrati
import { Injectable } from '@nestjs/common';
import { isDefined } from 'twenty-shared/utils';
-import { In, type EntityManager } from 'typeorm';
+import { In, type EntityManager, type FindOptionsWhere } from 'typeorm';
import { RecordShareRowCause } from 'twenty-shared/types';
import {
@@ -120,6 +120,26 @@ export class RecordShareStorageService {
);
}
+ // Each criterion is ANDed, and a row matching any of them is deleted.
+ async deleteMatching({
+ workspaceId,
+ criteria,
+ transactionScope,
+ }: {
+ workspaceId: string;
+ criteria: FindOptionsWhere<RecordShare>[];
+ transactionScope?: WorkspaceTransactionScope;
+ }): Promise<void> {
+ await this.withRepository(
+ { workspaceId, transactionScope },
+ async (repository) => {
+ for (const criterion of criteria) {
+ await repository.delete(criterion);
+ }
+ },
+ );
+ }
+
async deleteBySourceId({
workspaceId,
sourceId,
diff --git a/packages/twenty-server/src/engine/core-modules/user-workspace/user-workspace.module.ts b/packages/twenty-server/src/engine/core-modules/user-workspace/user-workspace.module.ts
index 87c023a79bb..d395a9c5a21 100644
--- a/packages/twenty-server/src/engine/core-modules/user-workspace/user-workspace.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/user-workspace/user-workspace.module.ts
@@ -1,4 +1,5 @@
import { UserWorkspaceAuthContextService } from 'src/engine/core-modules/user-workspace/services/user-workspace-auth-context.service';
+import { WorkflowRunRecordShareModule } from 'src/engine/core-modules/workflow/workflow-run-record-share.module';
import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
@@ -46,6 +47,7 @@ import { WorkspaceDataSourceModule } from 'src/engine/workspace-datasource/works
EnterpriseModule,
FeatureFlagModule,
CoreEntityCacheModule,
+ WorkflowRunRecordShareModule,
],
exports: [UserWorkspaceService, UserWorkspaceAuthContextService],
providers: [
diff --git a/packages/twenty-server/src/engine/core-modules/user-workspace/user-workspace.service.ts b/packages/twenty-server/src/engine/core-modules/user-workspace/user-workspace.service.ts
index 198244fb3db..95508a128a3 100644
--- a/packages/twenty-server/src/engine/core-modules/user-workspace/user-workspace.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/user-workspace/user-workspace.service.ts
@@ -25,6 +25,7 @@ import { FileUrlService } from 'src/engine/core-modules/file/file-url/file-url.s
import { extractFileIdFromUrl } from 'src/engine/core-modules/file/files-field/utils/extract-file-id-from-url.util';
import { OnboardingService } from 'src/engine/core-modules/onboarding/onboarding.service';
import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
+import { WorkflowRunRecordShareService } from 'src/engine/core-modules/workflow/services/workflow-run-record-share.service';
import { UserEntity } from 'src/engine/core-modules/user/user.entity';
import { WorkspaceInvitationService } from 'src/engine/core-modules/workspace-invitation/services/workspace-invitation.service';
import { WorkspaceDiscoverability } from 'src/engine/core-modules/workspace/types/workspace-discoverability.type';
@@ -69,6 +70,7 @@ export class UserWorkspaceService {
private readonly onboardingService: OnboardingService,
private readonly coreEntityCacheService: CoreEntityCacheService,
private readonly twentyConfigService: TwentyConfigService,
+ private readonly workflowRunRecordShareService: WorkflowRunRecordShareService,
) {}
async findById(id: string): Promise<UserWorkspaceEntity | null> {
@@ -361,8 +363,22 @@ export class UserWorkspaceService {
// Access stays gated by the soft-deleted userWorkspace.
await this.userWorkspaceRepository.softDelete({ id: userWorkspaceId });
} else {
+ // The delete sets the creator of this member's workflows to null, which
+ // makes them workspace-visible in core, so their runs' grants have to
+ // follow or nobody could read those runs.
+ const createdCoreWorkflowIds =
+ await this.workflowRunRecordShareService.findCoreWorkflowIdsCreatedBy({
+ workspaceId,
+ userWorkspaceId,
+ });
+
await this.roleTargetRepository.delete(workspaceId, { userWorkspaceId }); // TODO remove once userWorkspace foreign key is added on roleTarget
await this.userWorkspaceRepository.delete({ id: userWorkspaceId });
+
+ await this.workflowRunRecordShareService.syncRunsOfCoreWorkflows({
+ workspaceId,
+ coreWorkflowIds: createdCoreWorkflowIds,
+ });
}
}
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/core-workflow-services.module.ts b/packages/twenty-server/src/engine/core-modules/workflow/core-workflow-services.module.ts
index 4bb67c3629d..5807ba7fdb8 100644
--- a/packages/twenty-server/src/engine/core-modules/workflow/core-workflow-services.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/workflow/core-workflow-services.module.ts
@@ -8,6 +8,7 @@ import { RecordPositionModule } from 'src/engine/core-modules/record-position/re
import { WorkflowVersionEntity } from 'src/engine/core-modules/workflow/entities/workflow-version.entity';
import { WorkflowEntity } from 'src/engine/core-modules/workflow/entities/workflow.entity';
import { CoreWorkflowAccessModule } from 'src/engine/core-modules/workflow/core-workflow-access.module';
+import { WorkflowRunRecordShareModule } from 'src/engine/core-modules/workflow/workflow-run-record-share.module';
import { CoreWorkflowIdResolutionService } from 'src/engine/core-modules/workflow/services/core-workflow-id-resolution.service';
import { CoreWorkflowLifecycleWorkspaceService } from 'src/engine/core-modules/workflow/services/core-workflow-lifecycle.workspace-service';
import { CoreWorkflowListService } from 'src/engine/core-modules/workflow/services/core-workflow-list.service';
@@ -34,6 +35,7 @@ import { AutomatedTriggerModule } from 'src/modules/workflow/workflow-trigger/au
imports: [
ApplicationModule,
CoreWorkflowAccessModule,
+ WorkflowRunRecordShareModule,
TypeOrmModule.forFeature([WorkspaceEntity, WorkflowVersionEntity]),
AutomatedTriggerModule,
CacheLockModule,
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-mutation.workspace-service.ts b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-mutation.workspace-service.ts
index cab93b341a5..30f9122404c 100644
--- a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-mutation.workspace-service.ts
+++ b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-mutation.workspace-service.ts
@@ -30,6 +30,7 @@ import { CoreWorkflowListService } from 'src/engine/core-modules/workflow/servic
import { CoreWorkflowVersionWriteService } from 'src/engine/core-modules/workflow/services/core-workflow-version-write.service';
import { assertExactlyOneMirrorRowWasWritten } from 'src/engine/core-modules/workflow/utils/assert-exactly-one-mirror-row-was-written.util';
import { CoreWorkflowAccessService } from 'src/engine/core-modules/workflow/services/core-workflow-access.service';
+import { WorkflowRunRecordShareService } from 'src/engine/core-modules/workflow/services/workflow-run-record-share.service';
import { WorkflowCoreSyncService } from 'src/engine/core-modules/workflow/services/workflow-core-sync.service';
import { WorkflowVersionCoreSyncService } from 'src/engine/core-modules/workflow/services/workflow-version-core-sync.service';
import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
@@ -75,6 +76,7 @@ export class CoreWorkflowMutationWorkspaceService {
private readonly workspaceMigrationValidateBuildAndRunService: WorkspaceMigrationValidateBuildAndRunService,
private readonly flatEntityMapsCacheService: WorkspaceManyOrAllFlatEntityMapsCacheService,
private readonly applicationService: ApplicationService,
+ private readonly workflowRunRecordShareService: WorkflowRunRecordShareService,
) {}
private async runCoreWorkflowMigration({
@@ -875,14 +877,20 @@ export class CoreWorkflowMutationWorkspaceService {
// cannot both pass it and have the later write silently take the workflow.
// A workspace-visible workflow is already editable and deletable by every
// member, so claiming one grants no access the claimer did not have.
- const claimResult = await this.coreWorkflowRepository.update(
- workspaceId,
- {
- id: coreWorkflowId,
- createdByUserWorkspaceId: Or(IsNull(), Equal(userWorkspaceId)),
- },
- { visibility, createdByUserWorkspaceId: userWorkspaceId },
- );
+ const claimResult =
+ await this.workflowRunRecordShareService.updateAccessThenSyncRuns({
+ workspaceId,
+ coreWorkflowId,
+ updateAccess: () =>
+ this.coreWorkflowRepository.update(
+ workspaceId,
+ {
+ id: coreWorkflowId,
+ createdByUserWorkspaceId: Or(IsNull(), Equal(userWorkspaceId)),
+ },
+ { visibility, createdByUserWorkspaceId: userWorkspaceId },
+ ),
+ });
if (claimResult.affected === 0) {
const coreWorkflowExists = await this.coreWorkflowRepository.exists(
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/services/workflow-run-record-share.service.ts b/packages/twenty-server/src/engine/core-modules/workflow/services/workflow-run-record-share.service.ts
new file mode 100644
index 00000000000..80776a66079
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/workflow/services/workflow-run-record-share.service.ts
@@ -0,0 +1,338 @@
+import { Injectable } from '@nestjs/common';
+import { InjectRepository } from '@nestjs/typeorm';
+
+import { STANDARD_OBJECTS } from 'twenty-shared/metadata';
+import {
+ RecordSharePrincipalType,
+ RecordShareRowCause,
+ WorkflowVisibility,
+} from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+import { type FindOptionsWhere, In, type Repository } from 'typeorm';
+
+import { CacheLockService } from 'src/engine/core-modules/cache-lock/cache-lock.service';
+import { RecordShareStorageService } from 'src/engine/core-modules/record-share/services/record-share-storage.service';
+import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
+import { WorkflowEntity } from 'src/engine/core-modules/workflow/entities/workflow.entity';
+import { buildWorkflowRunRecordShares } from 'src/engine/core-modules/workflow/utils/build-workflow-run-record-shares.util';
+import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
+import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
+import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
+import { type WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+import { type WorkflowRunWorkspaceEntity } from 'src/modules/workflow/common/standard-objects/workflow-run.workspace-entity';
+
+// Keeps each grant write well under Postgres' bind parameter limit.
+const WORKFLOW_RUN_BATCH_SIZE = 500;
+
+// A whole workflow's runs can take longer than the default lock lifetime.
+const CORE_WORKFLOW_LOCK_OPTIONS = { ttl: 30_000, maxRetries: 300 };
+
+type CoreWorkflowAccess = {
+ isWorkspaceVisible: boolean;
+ creatorWorkspaceMemberId: string | null;
+};
+
+// A run carries its workflow's inputs and outputs, so it is exactly as private
+// as its core workflow. Its grants are derived from that workflow rather than
+// set by hand, which is why the whole derived set is replaced: a visibility
+// change or a new creator must also take away what the old state granted.
+@Injectable()
+export class WorkflowRunRecordShareService {
+ constructor(
+ @InjectWorkspaceScopedRepository(WorkflowEntity)
+ private readonly coreWorkflowRepository: WorkspaceScopedRepository<WorkflowEntity>,
+ @InjectRepository(UserWorkspaceEntity)
+ private readonly userWorkspaceRepository: Repository<UserWorkspaceEntity>,
+ private readonly workspaceOrmManager: WorkspaceOrmManager,
+ private readonly workspaceCacheService: WorkspaceCacheService,
+ private readonly recordShareStorageService: RecordShareStorageService,
+ private readonly cacheLockService: CacheLockService,
+ ) {}
+
+ // Held across both steps so that a run created meanwhile cannot be granted
+ // from the state this change replaces.
+ async updateAccessThenSyncRuns<TResult>({
+ workspaceId,
+ coreWorkflowId,
+ updateAccess,
+ }: {
+ workspaceId: string;
+ coreWorkflowId: string;
+ updateAccess: () => Promise<TResult>;
+ }): Promise<TResult> {
+ return this.withCoreWorkflowLock(
+ { workspaceId, coreWorkflowId },
+ async () => {
+ const result = await updateAccess();
+
+ await this.replaceSharesOfAllRuns({ workspaceId, coreWorkflowId });
+
+ return result;
+ },
+ );
+ }
+
+ async syncRunsOfCoreWorkflows({
+ workspaceId,
+ coreWorkflowIds,
+ }: {
+ workspaceId: string;
+ coreWorkflowIds: string[];
+ }): Promise<void> {
+ for (const coreWorkflowId of new Set(coreWorkflowIds)) {
+ await this.withCoreWorkflowLock({ workspaceId, coreWorkflowId }, () =>
+ this.replaceSharesOfAllRuns({ workspaceId, coreWorkflowId }),
+ );
+ }
+ }
+
+ async syncRuns({
+ workspaceId,
+ workflowRunIds,
+ }: {
+ workspaceId: string;
+ workflowRunIds: string[];
+ }): Promise<void> {
+ const runs = await this.findRuns({
+ workspaceId,
+ where: { id: In(workflowRunIds) },
+ });
+ const runIdsByCoreWorkflowId = new Map<string | null, string[]>();
+
+ for (const run of runs) {
+ runIdsByCoreWorkflowId.set(run.coreWorkflowId, [
+ ...(runIdsByCoreWorkflowId.get(run.coreWorkflowId) ?? []),
+ run.id,
+ ]);
+ }
+
+ for (const [coreWorkflowId, runIds] of runIdsByCoreWorkflowId) {
+ if (!isDefined(coreWorkflowId)) {
+ await this.replaceShares({
+ workspaceId,
+ workflowRunIds: runIds,
+ access: { isWorkspaceVisible: true, creatorWorkspaceMemberId: null },
+ });
+ continue;
+ }
+
+ await this.withCoreWorkflowLock(
+ { workspaceId, coreWorkflowId },
+ async () =>
+ this.replaceShares({
+ workspaceId,
+ workflowRunIds: runIds,
+ access: await this.resolveAccess({ workspaceId, coreWorkflowId }),
+ }),
+ );
+ }
+ }
+
+ async findCoreWorkflowIdsCreatedBy({
+ workspaceId,
+ userWorkspaceId,
+ }: {
+ workspaceId: string;
+ userWorkspaceId: string;
+ }): Promise<string[]> {
+ const coreWorkflows = await this.coreWorkflowRepository.find(workspaceId, {
+ where: { createdByUserWorkspaceId: userWorkspaceId },
+ select: { id: true },
+ withDeleted: true,
+ });
+
+ return coreWorkflows.map(({ id }) => id);
+ }
+
+ private async replaceSharesOfAllRuns({
+ workspaceId,
+ coreWorkflowId,
+ }: {
+ workspaceId: string;
+ coreWorkflowId: string;
+ }): Promise<void> {
+ const runs = await this.findRuns({
+ workspaceId,
+ where: { coreWorkflowId },
+ });
+
+ await this.replaceShares({
+ workspaceId,
+ workflowRunIds: runs.map(({ id }) => id),
+ access: await this.resolveAccess({ workspaceId, coreWorkflowId }),
+ });
+ }
+
+ private async replaceShares({
+ workspaceId,
+ workflowRunIds,
+ access,
+ }: {
+ workspaceId: string;
+ workflowRunIds: string[];
+ access: CoreWorkflowAccess;
+ }): Promise<void> {
+ const { flatObjectMetadataMaps } =
+ await this.workspaceCacheService.getOrRecompute(workspaceId, [
+ 'flatObjectMetadataMaps',
+ ]);
+ const objectMetadataId =
+ flatObjectMetadataMaps.byUniversalIdentifier[
+ STANDARD_OBJECTS.workflowRun.universalIdentifier
+ ]?.id;
+
+ if (!isDefined(objectMetadataId)) {
+ return;
+ }
+
+ for (
+ let offset = 0;
+ offset < workflowRunIds.length;
+ offset += WORKFLOW_RUN_BATCH_SIZE
+ ) {
+ const batch = workflowRunIds.slice(
+ offset,
+ offset + WORKFLOW_RUN_BATCH_SIZE,
+ );
+ const recordScope = { objectMetadataId, recordId: In(batch) };
+
+ await this.workspaceOrmManager.executeInWorkspaceContext(
+ () =>
+ this.workspaceOrmManager.runInWorkspaceTransaction(
+ async (transactionScope) => {
+ await this.recordShareStorageService.deleteMatching({
+ workspaceId,
+ transactionScope,
+ criteria: [
+ // Grants written on the run's own behalf rather than by a
+ // person sharing it: the ones derived here, and the creator
+ // role an application's create writes, which would otherwise
+ // keep everyone holding that role reading a private
+ // workflow's runs.
+ { ...recordScope, sourceId: In(batch) },
+ { ...recordScope, rowCause: RecordShareRowCause.APPLICATION },
+ // Whatever wrote it, a grant to everyone on a run means
+ // workspace-visible, which only the core workflow decides.
+ {
+ ...recordScope,
+ principalType: RecordSharePrincipalType.EVERYONE,
+ },
+ ],
+ });
+ await this.recordShareStorageService.insertMany({
+ workspaceId,
+ transactionScope,
+ recordShares: buildWorkflowRunRecordShares({
+ objectMetadataId,
+ workflowRunIds: batch,
+ ...access,
+ }),
+ });
+ },
+ ),
+ buildSystemAuthContext(workspaceId),
+ );
+ }
+ }
+
+ private async resolveAccess({
+ workspaceId,
+ coreWorkflowId,
+ }: {
+ workspaceId: string;
+ coreWorkflowId: string;
+ }): Promise<CoreWorkflowAccess> {
+ const coreWorkflow = await this.coreWorkflowRepository.findOne(
+ workspaceId,
+ {
+ where: { id: coreWorkflowId },
+ select: { id: true, visibility: true, createdByUserWorkspaceId: true },
+ withDeleted: true,
+ },
+ );
+
+ if (!isDefined(coreWorkflow)) {
+ return { isWorkspaceVisible: true, creatorWorkspaceMemberId: null };
+ }
+
+ return {
+ isWorkspaceVisible:
+ coreWorkflow.visibility === WorkflowVisibility.WORKSPACE ||
+ !isDefined(coreWorkflow.createdByUserWorkspaceId),
+ creatorWorkspaceMemberId: isDefined(coreWorkflow.createdByUserWorkspaceId)
+ ? await this.resolveWorkspaceMemberId({
+ workspaceId,
+ userWorkspaceId: coreWorkflow.createdByUserWorkspaceId,
+ })
+ : null,
+ };
+ }
+
+ private async resolveWorkspaceMemberId({
+ workspaceId,
+ userWorkspaceId,
+ }: {
+ workspaceId: string;
+ userWorkspaceId: string;
+ }): Promise<string | null> {
+ const userWorkspace = await this.userWorkspaceRepository.findOne({
+ where: { id: userWorkspaceId, workspaceId },
+ select: { id: true, userId: true },
+ });
+
+ if (!isDefined(userWorkspace)) {
+ return null;
+ }
+
+ const { flatWorkspaceMemberMaps } =
+ await this.workspaceCacheService.getOrRecompute(workspaceId, [
+ 'flatWorkspaceMemberMaps',
+ ]);
+ const workspaceMemberId =
+ flatWorkspaceMemberMaps.idByUserId[userWorkspace.userId];
+ const workspaceMember = isDefined(workspaceMemberId)
+ ? flatWorkspaceMemberMaps.byId[workspaceMemberId]
+ : undefined;
+
+ return isDefined(workspaceMember) && !isDefined(workspaceMember.deletedAt)
+ ? workspaceMember.id
+ : null;
+ }
+
+ private findRuns({
+ workspaceId,
+ where,
+ }: {
+ workspaceId: string;
+ where: FindOptionsWhere<WorkflowRunWorkspaceEntity>;
+ }): Promise<Pick<WorkflowRunWorkspaceEntity, 'id' | 'coreWorkflowId'>[]> {
+ return this.workspaceOrmManager.executeInWorkspaceContext(
+ () =>
+ this.workspaceOrmManager
+ .getRepository<WorkflowRunWorkspaceEntity>('workflowRun', {
+ shouldBypassPermissionChecks: true,
+ })
+ .find({
+ where,
+ select: { id: true, coreWorkflowId: true },
+ withDeleted: true,
+ }),
+ buildSystemAuthContext(workspaceId),
+ );
+ }
+
+ private withCoreWorkflowLock<TResult>(
+ {
+ workspaceId,
+ coreWorkflowId,
+ }: { workspaceId: string; coreWorkflowId: string },
+ work: () => Promise<TResult>,
+ ): Promise<TResult> {
+ return this.cacheLockService.withLock(
+ work,
+ `workflow-run-record-shares:${workspaceId}:${coreWorkflowId}`,
+ CORE_WORKFLOW_LOCK_OPTIONS,
+ );
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/utils/__tests__/build-workflow-run-record-shares.util.spec.ts b/packages/twenty-server/src/engine/core-modules/workflow/utils/__tests__/build-workflow-run-record-shares.util.spec.ts
new file mode 100644
index 00000000000..67fd0643f93
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/workflow/utils/__tests__/build-workflow-run-record-shares.util.spec.ts
@@ -0,0 +1,82 @@
+import { EVERYONE_PRINCIPAL_ID } from 'twenty-shared/constants';
+import {
+ RecordSharePrincipalType,
+ RecordShareRowCause,
+} from 'twenty-shared/types';
+
+import { buildWorkflowRunRecordShares } from 'src/engine/core-modules/workflow/utils/build-workflow-run-record-shares.util';
+
+const OBJECT_METADATA_ID = 'object-metadata-id';
+const CREATOR_ID = 'creator-workspace-member-id';
+
+const principalsByRun = (
+ shares: ReturnType<typeof buildWorkflowRunRecordShares>,
+) =>
+ shares.map(
+ ({ recordId, principalId, principalType, rowCause, sourceId }) => ({
+ recordId,
+ principalId,
+ principalType,
+ rowCause,
+ sourceId,
+ }),
+ );
+
+describe('buildWorkflowRunRecordShares', () => {
+ it('grants everyone and the creator the runs of a workspace-visible workflow', () => {
+ expect(
+ principalsByRun(
+ buildWorkflowRunRecordShares({
+ objectMetadataId: OBJECT_METADATA_ID,
+ workflowRunIds: ['run-1'],
+ isWorkspaceVisible: true,
+ creatorWorkspaceMemberId: CREATOR_ID,
+ }),
+ ),
+ ).toEqual([
+ {
+ recordId: 'run-1',
+ principalId: EVERYONE_PRINCIPAL_ID,
+ principalType: RecordSharePrincipalType.EVERYONE,
+ rowCause: RecordShareRowCause.RULE,
+ sourceId: 'run-1',
+ },
+ {
+ recordId: 'run-1',
+ principalId: CREATOR_ID,
+ principalType: RecordSharePrincipalType.WORKSPACE_MEMBER,
+ rowCause: RecordShareRowCause.OWNER,
+ sourceId: 'run-1',
+ },
+ ]);
+ });
+
+ it('grants only the creator the runs of a private workflow', () => {
+ expect(
+ principalsByRun(
+ buildWorkflowRunRecordShares({
+ objectMetadataId: OBJECT_METADATA_ID,
+ workflowRunIds: ['run-1', 'run-2'],
+ isWorkspaceVisible: false,
+ creatorWorkspaceMemberId: CREATOR_ID,
+ }),
+ ).map(({ recordId, principalId }) => [recordId, principalId]),
+ ).toEqual([
+ ['run-1', CREATOR_ID],
+ ['run-2', CREATOR_ID],
+ ]);
+ });
+
+ // A private workflow whose creator can no longer be resolved has nobody to
+ // grant, and core shows such a workflow to nobody either.
+ it('grants nothing for a private workflow without a resolvable creator', () => {
+ expect(
+ buildWorkflowRunRecordShares({
+ objectMetadataId: OBJECT_METADATA_ID,
+ workflowRunIds: ['run-1'],
+ isWorkspaceVisible: false,
+ creatorWorkspaceMemberId: null,
+ }),
+ ).toEqual([]);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/utils/build-workflow-run-record-shares.util.ts b/packages/twenty-server/src/engine/core-modules/workflow/utils/build-workflow-run-record-shares.util.ts
new file mode 100644
index 00000000000..84b2e91cac2
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/workflow/utils/build-workflow-run-record-shares.util.ts
@@ -0,0 +1,52 @@
+import { EVERYONE_PRINCIPAL_ID } from 'twenty-shared/constants';
+import {
+ RecordShareAccessLevel,
+ RecordSharePrincipalType,
+ RecordShareRowCause,
+} from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+
+import { type RecordShareInput } from 'src/engine/core-modules/record-share/types/record-share-input.type';
+
+// The rule matches buildCoreWorkflowVisibilitySqlPredicate: everyone reads the
+// runs of a workspace-visible or ownerless workflow, and the creator always
+// reads their own.
+export const buildWorkflowRunRecordShares = ({
+ objectMetadataId,
+ workflowRunIds,
+ isWorkspaceVisible,
+ creatorWorkspaceMemberId,
+}: {
+ objectMetadataId: string;
+ workflowRunIds: string[];
+ isWorkspaceVisible: boolean;
+ creatorWorkspaceMemberId: string | null;
+}): RecordShareInput[] =>
+ workflowRunIds.flatMap((workflowRunId) => [
+ ...(isWorkspaceVisible
+ ? [
+ {
+ objectMetadataId,
+ recordId: workflowRunId,
+ principalId: EVERYONE_PRINCIPAL_ID,
+ principalType: RecordSharePrincipalType.EVERYONE,
+ accessLevel: RecordShareAccessLevel.FULL,
+ rowCause: RecordShareRowCause.RULE,
+ sourceId: workflowRunId,
+ },
+ ]
+ : []),
+ ...(isDefined(creatorWorkspaceMemberId)
+ ? [
+ {
+ objectMetadataId,
+ recordId: workflowRunId,
+ principalId: creatorWorkspaceMemberId,
+ principalType: RecordSharePrincipalType.WORKSPACE_MEMBER,
+ accessLevel: RecordShareAccessLevel.FULL,
+ rowCause: RecordShareRowCause.OWNER,
+ sourceId: workflowRunId,
+ },
+ ]
+ : []),
+ ]);
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/workflow-run-record-share.module.ts b/packages/twenty-server/src/engine/core-modules/workflow/workflow-run-record-share.module.ts
new file mode 100644
index 00000000000..13e31a29936
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/workflow/workflow-run-record-share.module.ts
@@ -0,0 +1,27 @@
+import { Module } from '@nestjs/common';
+import { TypeOrmModule } from '@nestjs/typeorm';
+
+import { CacheLockModule } from 'src/engine/core-modules/cache-lock/cache-lock.module';
+import { RecordShareStorageModule } from 'src/engine/core-modules/record-share/record-share-storage.module';
+import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
+import { WorkflowEntity } from 'src/engine/core-modules/workflow/entities/workflow.entity';
+import { WorkflowRunRecordShareService } from 'src/engine/core-modules/workflow/services/workflow-run-record-share.service';
+import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/provide-workspace-scoped-repository';
+import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
+
+// Run creation, workflow visibility changes and member removal all rewrite run
+// grants, and those modules already depend on each other, so it lives on its own.
+@Module({
+ imports: [
+ TypeOrmModule.forFeature([WorkflowEntity, UserWorkspaceEntity]),
+ CacheLockModule,
+ RecordShareStorageModule,
+ WorkspaceCacheModule,
+ ],
+ providers: [
+ WorkflowRunRecordShareService,
+ provideWorkspaceScopedRepository(WorkflowEntity),
+ ],
+ exports: [WorkflowRunRecordShareService],
+})
+export class WorkflowRunRecordShareModule {}
diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/standard-object-readability.spec.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/standard-object-readability.spec.ts
index d7174855e55..54bcc0b9dba 100644
--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/standard-object-readability.spec.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/standard-object-readability.spec.ts
@@ -73,6 +73,7 @@ describe('Standard object readability', () => {
STANDARD_OBJECTS.messageSuppression.universalIdentifier,
STANDARD_OBJECTS.recordShare.universalIdentifier,
+ STANDARD_OBJECTS.workflowRun.universalIdentifier,
...inheritedObjectNames.map(
(objectName) => STANDARD_OBJECTS[objectName].universalIdentifier,
),
@@ -85,6 +86,20 @@ describe('Standard object readability', () => {
),
);
+ // Its grants follow the core workflow's visibility, since the workspace
+ // workflow record is not where that visibility lives.
+ it('declares workflowRun PRIVATE and leaves workflow and workflowVersion OPEN', () => {
+ expect(findStandardFlatObjectMetadata('workflowRun')).toMatchObject({
+ readability: MetadataReadability.PRIVATE,
+ });
+ expect(findStandardFlatObjectMetadata('workflow')).toMatchObject({
+ readability: MetadataReadability.OPEN,
+ });
+ expect(findStandardFlatObjectMetadata('workflowVersion')).toMatchObject({
+ readability: MetadataReadability.OPEN,
+ });
+ });
+
it('declares recordShare SYSTEM for readability and writability', () => {
expect(findStandardFlatObjectMetadata('recordShare')).toMatchObject({
readability: MetadataReadability.SYSTEM,
diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/object-metadata/create-standard-flat-object-metadata.util.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/object-metadata/create-standard-flat-object-metadata.util.ts
index c25f8962a24..494bfee91d3 100644
--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/object-metadata/create-standard-flat-object-metadata.util.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/object-metadata/create-standard-flat-object-metadata.util.ts
@@ -1596,6 +1596,10 @@ export const STANDARD_FLAT_OBJECT_METADATA_BUILDERS_BY_OBJECT_NAME = {
isSystem: true,
isAuditLogged: false,
isUICreatable: false,
+ // A run carries its workflow's inputs and outputs, so it is exactly as
+ // private as its core workflow; WorkflowRunRecordShareService writes
+ // the grants.
+ readability: MetadataReadability.PRIVATE,
labelIdentifierFieldMetadataName: 'name',
},
workspaceId,
diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.module.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.module.ts
index ccb62398785..1ec53c7afbb 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.module.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.module.ts
@@ -5,6 +5,7 @@ import { CacheLockModule } from 'src/engine/core-modules/cache-lock/cache-lock.m
import { FeatureFlagModule } from 'src/engine/core-modules/feature-flag/feature-flag.module';
import { MetricsModule } from 'src/engine/core-modules/metrics/metrics.module';
import { RecordPositionModule } from 'src/engine/core-modules/record-position/record-position.module';
+import { WorkflowRunRecordShareModule } from 'src/engine/core-modules/workflow/workflow-run-record-share.module';
import { WorkflowCommonModule } from 'src/modules/workflow/common/workflow-common.module';
import { DeleteWorkflowRunsCommand } from 'src/modules/workflow/workflow-runner/workflow-run/command/delete-workflow-runs.command';
import { WorkflowRunStepLogWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run-step-log.workspace-service';
@@ -18,6 +19,7 @@ import { WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runne
MetricsModule,
WorkspaceIteratorModule,
FeatureFlagModule,
+ WorkflowRunRecordShareModule,
],
providers: [
WorkflowRunWorkspaceService,
diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service.ts
index ddbc598c808..37ddcbaa1df 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service.ts
@@ -9,6 +9,7 @@ import { WithLock } from 'src/engine/core-modules/cache-lock/with-lock.decorator
import { MetricsService } from 'src/engine/core-modules/metrics/metrics.service';
import { MetricsKeys } from 'src/engine/core-modules/metrics/types/metrics-keys.type';
import { RecordPositionService } from 'src/engine/core-modules/record-position/services/record-position.service';
+import { WorkflowRunRecordShareService } from 'src/engine/core-modules/workflow/services/workflow-run-record-share.service';
import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
import {
@@ -16,6 +17,7 @@ import {
type WorkflowRunState,
type WorkflowRunWorkspaceEntity,
} from 'src/modules/workflow/common/standard-objects/workflow-run.workspace-entity';
+import { setAllIteratorsStepInfosAsStopped } from 'src/modules/workflow/common/utils/set-all-iterators-step-infos-as-stopped.util';
import { type WorkflowVersionWorkspaceEntity } from 'src/modules/workflow/common/standard-objects/workflow-version.workspace-entity';
import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';
import { type WorkflowTrigger } from 'src/modules/workflow/workflow-trigger/types/workflow-trigger.type';
@@ -30,6 +32,7 @@ export class WorkflowRunWorkspaceService {
private readonly workspaceOrmManager: WorkspaceOrmManager,
private readonly recordPositionService: RecordPositionService,
private readonly metricsService: MetricsService,
+ private readonly workflowRunRecordShareService: WorkflowRunRecordShareService,
) {}
async createCoreWorkflowRun({
@@ -101,6 +104,13 @@ export class WorkflowRunWorkspaceService {
enqueuedAt: status === WorkflowRunStatus.ENQUEUED ? new Date() : null,
});
+ // A run is a private record written by the system, so nobody reads it
+ // until it carries its workflow's grants.
+ await this.workflowRunRecordShareService.syncRuns({
+ workspaceId,
+ workflowRunIds: [id],
+ });
+
return id;
}, authContext);
}
@@ -280,6 +290,100 @@ export class WorkflowRunWorkspaceService {
});
}
+ // Written from the state read under the lock rather than from the caller's
+ // snapshot, or a step-info write that landed in between, such as an accepted
+ // form submission, would be put back as it was.
+ @WithLock('workflowRunId')
+ async markWorkflowRunAsStopping({
+ workflowRunId,
+ workspaceId,
+ }: {
+ workflowRunId: string;
+ workspaceId: string;
+ }): Promise<boolean> {
+ const workflowRunToUpdate = await this.getWorkflowRunOrFail({
+ workflowRunId,
+ workspaceId,
+ });
+
+ if (
+ workflowRunToUpdate.status !== WorkflowRunStatus.RUNNING ||
+ !isDefined(workflowRunToUpdate.state)
+ ) {
+ return false;
+ }
+
+ const { stepInfos, flow } = workflowRunToUpdate.state;
+
+ await this.updateWorkflowRun({
+ workflowRunId,
+ workspaceId,
+ partialUpdate: {
+ status: WorkflowRunStatus.STOPPING,
+ state: {
+ ...workflowRunToUpdate.state,
+ stepInfos: {
+ ...stepInfos,
+ ...setAllIteratorsStepInfosAsStopped({
+ stepInfos,
+ steps: flow.steps,
+ }),
+ },
+ },
+ },
+ });
+
+ return true;
+ }
+
+ // A step waiting on a person must move on exactly once. This shares the lock
+ // every step-info write takes, so of two concurrent callers the second finds
+ // the step no longer PENDING. A stop is refused too: endWorkflowRun turns a
+ // pending step into FAILED, and a stop still waiting on another branch
+ // leaves the run STOPPING with the step PENDING but nothing left to resume.
+ @WithLock('workflowRunId')
+ async updateStepInfoIfPending({
+ stepId,
+ stepInfo,
+ workflowRunId,
+ workspaceId,
+ }: {
+ stepId: string;
+ stepInfo: Partial<WorkflowRunStepInfo>;
+ workflowRunId: string;
+ workspaceId: string;
+ }): Promise<boolean> {
+ const workflowRunToUpdate = await this.getWorkflowRunOrFail({
+ workflowRunId,
+ workspaceId,
+ });
+
+ const currentStepInfo = workflowRunToUpdate.state?.stepInfos?.[stepId];
+
+ if (
+ workflowRunToUpdate.status !== WorkflowRunStatus.RUNNING ||
+ currentStepInfo?.status !== StepStatus.PENDING
+ ) {
+ return false;
+ }
+
+ await this.updateWorkflowRun({
+ workflowRunId,
+ workspaceId,
+ partialUpdate: {
+ state: {
+ ...workflowRunToUpdate.state,
+ stepInfos: {
+ ...workflowRunToUpdate.state?.stepInfos,
+ [stepId]: { ...currentStepInfo, ...stepInfo },
+ },
+ },
+ },
+ });
+
+ return true;
+ }
+
@WithLock('workflowRunId')
async updateWorkflowRunStep({
workflowRunId,
diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/workflow-runner.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/workflow-runner.workspace-service.ts
index 30db8e33e27..205ae641d37 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/workflow-runner.workspace-service.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/workflow-runner.workspace-service.ts
@@ -13,7 +13,6 @@ import {
WorkflowVersionStepExceptionCode,
} from 'src/modules/workflow/common/exceptions/workflow-version-step.exception';
import { WorkflowRunStatus } from 'src/modules/workflow/common/standard-objects/workflow-run.workspace-entity';
-import { setAllIteratorsStepInfosAsStopped } from 'src/modules/workflow/common/utils/set-all-iterators-step-infos-as-stopped.util';
import { workflowHasRunningSteps } from 'src/modules/workflow/common/utils/workflow-has-running-steps.util';
import { WorkflowVersionStepOperationsWorkspaceService } from 'src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step-operations.workspace-service';
import { isWorkflowFormAction } from 'src/modules/workflow/workflow-executor/workflow-actions/form/guards/is-workflow-form-action.guard';
@@ -145,15 +144,26 @@ export class WorkflowRunnerWorkspaceService {
},
);
- await this.workflowRunWorkspaceService.updateWorkflowRunStepInfo({
- stepId,
- stepInfo: {
- status: StepStatus.SUCCESS,
- result: enrichedResponse,
- },
- workspaceId,
- workflowRunId,
- });
+ const hasCompletedStep =
+ await this.workflowRunWorkspaceService.updateStepInfoIfPending({
+ stepId,
+ stepInfo: {
+ status: StepStatus.SUCCESS,
+ result: enrichedResponse,
+ },
+ workspaceId,
+ workflowRunId,
+ });
+
+ if (!hasCompletedStep) {
+ throw new WorkflowVersionStepException(
+ 'Form is no longer awaiting a submission',
+ WorkflowVersionStepExceptionCode.INVALID_REQUEST,
+ {
+ userFriendlyMessage: msg`This form is no longer awaiting a submission`,
+ },
+ );
+ }
await this.resume({
workspaceId,
@@ -198,28 +208,24 @@ export class WorkflowRunnerWorkspaceService {
const steps = workflowRun.state.flow.steps;
if (workflowHasRunningSteps({ stepInfos, steps })) {
- const stoppedIteratorStepInfos = setAllIteratorsStepInfosAsStopped({
- stepInfos,
- steps,
- });
-
- const mergedStepInfos = {
- ...stepInfos,
- ...stoppedIteratorStepInfos,
- };
-
- await this.workflowRunWorkspaceService.updateWorkflowRun({
- workflowRunId,
- workspaceId,
- partialUpdate: {
- status: WorkflowRunStatus.STOPPING,
- state: {
- ...workflowRun.state,
- stepInfos: mergedStepInfos,
- },
- },
- });
- newStatus = WorkflowRunStatus.STOPPING;
+ const isStopping =
+ await this.workflowRunWorkspaceService.markWorkflowRunAsStopping({
+ workflowRunId,
+ workspaceId,
+ });
+
+ if (isStopping) {
+ newStatus = WorkflowRunStatus.STOPPING;
+ } else {
+ // The run changed before the lock was taken, so report what it is now.
+ const currentWorkflowRun =
+ await this.workflowRunWorkspaceService.getWorkflowRunOrFail({
+ workflowRunId,
+ workspaceId,
+ });
+
+ newStatus = currentWorkflowRun.status;
+ }
} else {
await this.workflowRunWorkspaceService.endWorkflowRun({
workflowRunId,
diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-execution.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-execution.integration-spec.ts
index 743043858a0..f3db538b2d0 100644
--- a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-execution.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-execution.integration-spec.ts
@@ -749,6 +749,136 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
},
);
+ const formStep = (nextStepIds: string[]): WorkflowAction => ({
+ ...emptyStep(),
+ type: WorkflowActionType.FORM,
+ nextStepIds,
+ settings: {
+ ...settings,
+ input: [
+ {
+ id: randomUUID(),
+ name: 'answer',
+ label: 'Answer',
+ type: FieldMetadataType.TEXT,
+ },
+ ],
+ },
+ });
+
+ const submitForm = ({
+ runId,
+ stepId,
+ answer,
+ }: {
+ runId: string;
+ stepId: string;
+ answer: string;
+ }) =>
+ workflowGraphqlRequest(
+ 'mutation Submit($input: SubmitFormStepInput!) { submitFormStep(input: $input) }',
+ { input: { workflowRunId: runId, stepId, response: { answer } } },
+ );
+
+ it('refuses a second submission of the same form and keeps the first answer', async () => {
+ const finalStep = emptyStep();
+ const form = formStep([finalStep.id]);
+ const fixture = await createFixture({
+ mirrorless: true,
+ steps: [form, finalStep],
+ });
+ const runId = await runFixture(fixture);
+
+ await waitForStep(runId, form.id, 'PENDING');
+
+ const first = await submitForm({
+ runId,
+ stepId: form.id,
+ answer: 'Approved',
+ });
+
+ expect(first.body.errors).toBeUndefined();
+ await waitForRun(runId, 'COMPLETED');
+
+ const second = await submitForm({
+ runId,
+ stepId: form.id,
+ answer: 'Approved again',
+ });
+
+ expect(second.body.errors?.[0]?.message).toContain(
+ 'no longer awaiting a submission',
+ );
+ expect((await getRun(runId)).state.stepInfos[form.id].result).toEqual({
+ answer: 'Approved',
+ });
+ });
+
+ it('refuses a submission once its run has been stopped', async () => {
+ const finalStep = emptyStep();
+ const form = formStep([finalStep.id]);
+ const fixture = await createFixture({
+ mirrorless: true,
+ steps: [form, finalStep],
+ });
+ const runId = await runFixture(fixture);
+
+ await waitForStep(runId, form.id, 'PENDING');
+
+ await workflowGraphqlRequest(
+ 'mutation Stop($id: UUID!) { stopWorkflowRun(workflowRunId: $id) { id status } }',
+ { id: runId },
+ );
+ await waitForRun(runId, 'STOPPED');
+
+ const response = await submitForm({
+ runId,
+ stepId: form.id,
+ answer: 'Too late',
+ });
+
+ expect(response.body.errors?.[0]?.message).toContain(
+ 'no longer awaiting a submission',
+ );
+
+ const run = await getRun(runId);
+
+ expect(run.status).toBe('STOPPED');
+ expect(run.state.stepInfos[form.id].status).toBe('FAILED');
+ expect(run.state.stepInfos[finalStep.id].status).toBe('NOT_STARTED');
+ });
+
+ // A stop waiting on a step still running on another branch parks the run in
+ // STOPPING with the form still PENDING; nothing would resume an answer.
+ it('refuses a submission while its run is stopping', async () => {
+ const finalStep = emptyStep();
+ const form = formStep([finalStep.id]);
+ const fixture = await createFixture({
+ mirrorless: true,
+ steps: [form, finalStep],
+ });
+ const runId = await runFixture(fixture);
+
+ await waitForStep(runId, form.id, 'PENDING');
+ await global.testDataSource.query(
+ `UPDATE "${schema}"."workflowRun" SET status = 'STOPPING' WHERE id = $1`,
+ [runId],
+ );
+
+ const response = await submitForm({
+ runId,
+ stepId: form.id,
+ answer: 'While stopping',
+ });
+
+ expect(response.body.errors?.[0]?.message).toContain(
+ 'no longer awaiting a submission',
+ );
+ expect((await getRun(runId)).state.stepInfos[form.id].status).toBe(
+ 'PENDING',
+ );
+ });
+
it('stops a pending delay and ignores its later resume job', async () => {
const finalStep = emptyStep();
const delay: WorkflowAction = {
diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-visibility.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-visibility.integration-spec.ts
index e5329cb22ff..457842d2b50 100644
--- a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-visibility.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-visibility.integration-spec.ts
@@ -14,7 +14,10 @@ import { findCommandMenuItems } from 'test/integration/metadata/suites/command-m
import { pollWorkflowGraphqlRequest } from 'test/integration/graphql/suites/workflow/utils/poll-workflow-graphql-request.util';
import { updateWorkflowVersionTrigger } from 'test/integration/graphql/suites/workflow/utils/update-workflow-version-trigger.util';
import { workflowGraphqlRequest } from 'test/integration/graphql/suites/workflow/utils/workflow-graphql-request.util';
+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
+import { type UserWorkspaceService } from 'src/engine/core-modules/user-workspace/user-workspace.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 client = request(`http://localhost:${APP_PORT}`);
@@ -128,6 +131,119 @@ const listCoreWorkflowIds = async (
);
};
+const DESTROY_WORKFLOW_MUTATION = `
+ mutation DestroyWorkflow($id: UUID!) {
+ destroyWorkflow(id: $id) {
+ id
+ }
+ }
+`;
+
+const createActiveManualWorkflow = async (name: string) => {
+ const createResponse = await workflowGraphqlRequest(
+ CREATE_CORE_WORKFLOW_MUTATION,
+ { input: { name } },
+ );
+
+ expect(createResponse.body.errors).toBeUndefined();
+
+ const coreWorkflowId: string = createResponse.body.data.createCoreWorkflow.id;
+ const workspaceWorkflowId: string =
+ createResponse.body.data.createCoreWorkflow.workspaceWorkflowId;
+
+ const versions = await pollWorkflowGraphqlRequest<
+ {
+ coreWorkflowVersions: { workspaceWorkflowVersionId: string | null }[];
+ },
+ { workspaceWorkflowVersionId: string | null }[] | undefined
+ >({
+ query: `
+ query CoreWorkflowVersions($workspaceWorkflowId: UUID!) {
+ coreWorkflowVersions(workspaceWorkflowId: $workspaceWorkflowId) {
+ workspaceWorkflowVersionId
+ }
+ }
+ `,
+ variables: { workspaceWorkflowId },
+ extract: (data) => data?.coreWorkflowVersions,
+ until: (coreWorkflowVersions) =>
+ isDefined(coreWorkflowVersions?.[0]?.workspaceWorkflowVersionId),
+ });
+
+ const workspaceWorkflowVersionId = versions![0].workspaceWorkflowVersionId!;
+
+ await updateWorkflowVersionTrigger({
+ workflowVersionId: workspaceWorkflowVersionId,
+ trigger: {
+ name: 'Manual Trigger',
+ type: 'MANUAL',
+ settings: { outputSchema: {} },
+ nextStepIds: [],
+ position: { x: 0, y: 0 },
+ },
+ });
+
+ const stepResponse = await workflowGraphqlRequest(
+ `
+ mutation CreateWorkflowVersionStep(
+ $input: CreateWorkflowVersionStepInput!
+ ) {
+ createWorkflowVersionStep(input: $input) {
+ stepsDiff
+ }
+ }
+ `,
+ {
+ input: {
+ workflowVersionId: workspaceWorkflowVersionId,
+ stepType: 'FIND_RECORDS',
+ parentStepId: 'trigger',
+ position: { x: 200, y: 0 },
+ },
+ },
+ );
+
+ expect(stepResponse.body.errors).toBeUndefined();
+
+ const activateResponse = await workflowGraphqlRequest(
+ ACTIVATE_VERSION_MUTATION,
+ { workflowVersionId: workspaceWorkflowVersionId },
+ );
+
+ expect(activateResponse.body.errors).toBeUndefined();
+
+ return { coreWorkflowId, workspaceWorkflowId, workspaceWorkflowVersionId };
+};
+
+// The generic record API, which the run pages read, rather than
+// the core workflow API that #26243 already gates.
+const findRecordIds = async (
+ requester: (query: string, variables?: object) => request.Test,
+ objectNamePlural: 'workflowRuns',
+ id: string,
+) => {
+ const response = await requester(
+ `
+ query FindRecords($id: UUID!) {
+ ${objectNamePlural}(filter: { id: { eq: $id } }) {
+ edges {
+ node {
+ id
+ }
+ }
+ }
+ }
+ `,
+ { id },
+ );
+
+ expect(response.body.errors).toBeUndefined();
+
+ return response.body.data[objectNamePlural].edges.map(
+ ({ node }: { node: { id: string } }) => node.id,
+ );
+};
+
describe('core workflow visibility (e2e)', () => {
let workspaceWorkflowId: string;
let coreWorkflowId: string;
@@ -511,77 +627,11 @@ describe('core workflow visibility (e2e)', () => {
};
beforeAll(async () => {
- const createResponse = await workflowGraphqlRequest(
- CREATE_CORE_WORKFLOW_MUTATION,
- { input: { name: 'Manual Trigger Workflow' } },
- );
-
- expect(createResponse.body.errors).toBeUndefined();
- manualCoreWorkflowId = createResponse.body.data.createCoreWorkflow.id;
- manualWorkspaceWorkflowId =
- createResponse.body.data.createCoreWorkflow.workspaceWorkflowId;
-
- const versions = await pollWorkflowGraphqlRequest<
- {
- coreWorkflowVersions: { workspaceWorkflowVersionId: string | null }[];
- },
- { workspaceWorkflowVersionId: string | null }[] | undefined
- >({
- query: `
- query CoreWorkflowVersions($workspaceWorkflowId: UUID!) {
- coreWorkflowVersions(workspaceWorkflowId: $workspaceWorkflowId) {
- workspaceWorkflowVersionId
- }
- }
- `,
- variables: { workspaceWorkflowId: manualWorkspaceWorkflowId },
- extract: (data) => data?.coreWorkflowVersions,
- until: (coreWorkflowVersions) =>
- isDefined(coreWorkflowVersions?.[0]?.workspaceWorkflowVersionId),
- });
-
- manualWorkspaceWorkflowVersionId =
- versions![0].workspaceWorkflowVersionId!;
-
- await updateWorkflowVersionTrigger({
- workflowVersionId: manualWorkspaceWorkflowVersionId,
- trigger: {
- name: 'Manual Trigger',
- type: 'MANUAL',
- settings: { outputSchema: {} },
- nextStepIds: [],
- position: { x: 0, y: 0 },
- },
- });
-
- const stepResponse = await workflowGraphqlRequest(
- `
- mutation CreateWorkflowVersionStep(
- $input: CreateWorkflowVersionStepInput!
- ) {
- createWorkflowVersionStep(input: $input) {
- stepsDiff
- }
- }
- `,
- {
- input: {
- workflowVersionId: manualWorkspaceWorkflowVersionId,
- stepType: 'FIND_RECORDS',
- parentStepId: 'trigger',
- position: { x: 200, y: 0 },
- },
- },
- );
-
- expect(stepResponse.body.errors).toBeUndefined();
-
- const activateResponse = await workflowGraphqlRequest(
- ACTIVATE_VERSION_MUTATION,
- { workflowVersionId: manualWorkspaceWorkflowVersionId },
- );
-
- expect(activateResponse.body.errors).toBeUndefined();
+ ({
+ coreWorkflowId: manualCoreWorkflowId,
+ workspaceWorkflowId: manualWorkspaceWorkflowId,
+ workspaceWorkflowVersionId: manualWorkspaceWorkflowVersionId,
+ } = await createActiveManualWorkflow('Manual Trigger Workflow'));
});
afterAll(async () => {
@@ -628,4 +678,185 @@ describe('core workflow visibility (e2e)', () => {
).toContain(manualWorkspaceWorkflowVersionId);
});
});
+
+ // A run holds the workflow's inputs and step outputs, so it has to be as
+ // private as the workflow even when read through the generic record API.
+ describe('the runs of a workflow', () => {
+ let runsCoreWorkflowId: string;
+ let runsWorkspaceWorkflowId: string;
+ let runsWorkspaceWorkflowVersionId: string;
+ let workflowRunId: string;
+
+ const runWorkflow = async () => {
+ const runResponse = await workflowGraphqlRequest(LEGACY_RUN_MUTATION, {
+ input: { workflowVersionId: runsWorkspaceWorkflowVersionId },
+ });
+
+ expect(runResponse.body.errors).toBeUndefined();
+
+ return runResponse.body.data.runWorkflowVersion.workflowRunId as string;
+ };
+
+ beforeAll(async () => {
+ ({
+ coreWorkflowId: runsCoreWorkflowId,
+ workspaceWorkflowId: runsWorkspaceWorkflowId,
+ workspaceWorkflowVersionId: runsWorkspaceWorkflowVersionId,
+ } = await createActiveManualWorkflow('Workflow With Runs'));
+
+ workflowRunId = await runWorkflow();
+ });
+
+ afterAll(async () => {
+ if (isDefined(runsWorkspaceWorkflowId)) {
+ await setVisibility(runsCoreWorkflowId, WorkflowVisibility.WORKSPACE);
+ await workflowGraphqlRequest(DESTROY_WORKFLOW_MUTATION, {
+ id: runsWorkspaceWorkflowId,
+ });
+ }
+ });
+
+ it('lets another member read them while the workflow is visible to the workspace', async () => {
+ expect(
+ await findRecordIds(asOtherMember, 'workflowRuns', workflowRunId),
+ ).toEqual([workflowRunId]);
+ });
+
+ it('hides them from another member once the workflow is private', async () => {
+ const response = await setVisibility(
+ runsCoreWorkflowId,
+ WorkflowVisibility.PRIVATE,
+ );
+
+ expect(response.body.errors).toBeUndefined();
+ expect(
+ await findRecordIds(asOtherMember, 'workflowRuns', workflowRunId),
+ ).toEqual([]);
+ });
+
+ it('keeps them readable by its creator while private', async () => {
+ expect(
+ await findRecordIds(
+ workflowGraphqlRequest,
+ 'workflowRuns',
+ workflowRunId,
+ ),
+ ).toEqual([workflowRunId]);
+ });
+
+ it('keeps a run started while private to its creator', async () => {
+ const privateRunId = await runWorkflow();
+
+ expect(
+ await findRecordIds(asOtherMember, 'workflowRuns', privateRunId),
+ ).toEqual([]);
+ expect(
+ await findRecordIds(
+ workflowGraphqlRequest,
+ 'workflowRuns',
+ privateRunId,
+ ),
+ ).toEqual([privateRunId]);
+ });
+
+ it('gives them back to another member once the workflow is visible to the workspace again', async () => {
+ const response = await setVisibility(
+ runsCoreWorkflowId,
+ WorkflowVisibility.WORKSPACE,
+ );
+
+ expect(response.body.errors).toBeUndefined();
+ expect(
+ await findRecordIds(asOtherMember, 'workflowRuns', workflowRunId),
+ ).toEqual([workflowRunId]);
+ });
+ });
+
+ // Removing a member deletes their membership, and the database then clears
+ // the creator of every workflow they created.
+ describe('the runs of a private workflow whose creator is removed from the workspace', () => {
+ const removedUserId = randomUUID();
+ const removedUserWorkspaceId = randomUUID();
+ let orphanedWorkflowId: string;
+ let orphanedCoreWorkflowId: string;
+ let orphanedRunId: string;
+
+ beforeAll(async () => {
+ let orphanedWorkflowVersionId: string;
+
+ ({
+ coreWorkflowId: orphanedCoreWorkflowId,
+ workspaceWorkflowId: orphanedWorkflowId,
+ workspaceWorkflowVersionId: orphanedWorkflowVersionId,
+ } = await createActiveManualWorkflow('Workflow Of A Removed Member'));
+
+ expect(
+ (
+ await setVisibility(
+ orphanedCoreWorkflowId,
+ WorkflowVisibility.PRIVATE,
+ )
+ ).body.errors,
+ ).toBeUndefined();
+
+ const runResponse = await workflowGraphqlRequest(LEGACY_RUN_MUTATION, {
+ input: { workflowVersionId: orphanedWorkflowVersionId },
+ });
+
+ expect(runResponse.body.errors).toBeUndefined();
+ orphanedRunId = runResponse.body.data.runWorkflowVersion.workflowRunId;
+
+ await global.testDataSource.query(
+ `INSERT INTO core."user" (id, email) VALUES ($1, $2)`,
+ [removedUserId, `removed-${removedUserId}@apple.dev`],
+ );
+ await global.testDataSource.query(
+ `INSERT INTO core."userWorkspace" (id, "userId", "workspaceId") VALUES ($1, $2, $3)`,
+ [removedUserWorkspaceId, removedUserId, SEED_APPLE_WORKSPACE_ID],
+ );
+ await global.testDataSource.query(
+ `UPDATE core."workflow" SET "createdByUserWorkspaceId" = $2 WHERE id = $1`,
+ [orphanedCoreWorkflowId, removedUserWorkspaceId],
+ );
+ });
+
+ afterAll(async () => {
+ if (isDefined(orphanedWorkflowId)) {
+ await workflowGraphqlRequest(DESTROY_WORKFLOW_MUTATION, {
+ id: orphanedWorkflowId,
+ });
+ }
+ await global.testDataSource.query(
+ `DELETE FROM core."userWorkspace" WHERE id = $1`,
+ [removedUserWorkspaceId],
+ );
+ await global.testDataSource.query(
+ `DELETE FROM core."user" WHERE id = $1`,
+ [removedUserId],
+ );
+ });
+
+ it('become readable to the workspace, as core now shows the workflow', async () => {
+ expect(
+ await findRecordIds(asOtherMember, 'workflowRuns', orphanedRunId),
+ ).toEqual([]);
+
+ await getAppProviderByClassName<UserWorkspaceService>(
+ 'UserWorkspaceService',
+ ).deleteUserWorkspace({
+ userWorkspaceId: removedUserWorkspaceId,
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ });
+
+ const [coreWorkflow] = await global.testDataSource.query(
+ `SELECT "createdByUserWorkspaceId" FROM core."workflow" WHERE id = $1`,
+ [orphanedCoreWorkflowId],
+ );
+
+ expect(coreWorkflow.createdByUserWorkspaceId).toBeNull();
+ expect(
+ await findRecordIds(asOtherMember, 'workflowRuns', orphanedRunId),
+ ).toEqual([orphanedRunId]);
+ });
+ });
});
diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/parallel-branch-leaf-resume-workflow.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/parallel-branch-leaf-resume-workflow.integration-spec.ts
index b7e02b95800..c65789017e8 100644
--- a/packages/twenty-server/test/integration/graphql/suites/workflow/parallel-branch-leaf-resume-workflow.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/parallel-branch-leaf-resume-workflow.integration-spec.ts
@@ -6,6 +6,7 @@ import {
import { FieldMetadataType } from 'twenty-shared/types';
import { v4 } from 'uuid';
+import { type WorkflowRunRecordShareService } from 'src/engine/core-modules/workflow/services/workflow-run-record-share.service';
import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';
import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
import {
@@ -14,6 +15,7 @@ import {
type WorkflowFormAction,
} from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';
import { updateWorkflowVersionTrigger } from 'test/integration/graphql/suites/workflow/utils/update-workflow-version-trigger.util';
+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
const client = request(`http://localhost:${APP_PORT}`);
@@ -295,6 +297,14 @@ describe('Parallel branch leaf resume workflow (e2e)', () => {
JSON.stringify(state),
],
);
+ // Runs are private, and a direct insert skips the grants that creating a
+ // run writes, so the run would be unreadable through the record API.
+ await getAppProviderByClassName<WorkflowRunRecordShareService>(
+ 'WorkflowRunRecordShareService',
+ ).syncRuns({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ workflowRunIds: [createdWorkflowRunId],
+ });
await (
await global.workflowTestServices.runJob()
diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/quick-lead-workflow.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/quick-lead-workflow.integration-spec.ts
index e6aeb306aef..3aeaec70f76 100644
--- a/packages/twenty-server/test/integration/graphql/suites/workflow/quick-lead-workflow.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/quick-lead-workflow.integration-spec.ts
@@ -246,9 +246,12 @@ describe('Quick Lead Workflow (e2e)', () => {
expect(testWorkflowRunId).toBeDefined();
- let workflowRun = await waitForWorkflowRunStatus(
+ await waitForWorkflowRunStatus(testWorkflowRunId as string, 'RUNNING');
+
+ let workflowRun = await waitForWorkflowRunStepStatus(
testWorkflowRunId as string,
- 'RUNNING',
+ FORM_STEP_ID,
+ 'PENDING',
);
expect(workflowRun?.status).toBe('RUNNING');