Skip to content

The open alternative to Salesforce, designed for AI.

Make connection provider scope immutable and derive account scope from it (#28637)

nitinea1a68e3047d
diff --git a/packages/twenty-agent-skills/references/develop-app/logic.md b/packages/twenty-agent-skills/references/develop-app/logic.md
index b3c367de188..bc4b9762dba 100644
--- a/packages/twenty-agent-skills/references/develop-app/logic.md
+++ b/packages/twenty-agent-skills/references/develop-app/logic.md
@@ -100,7 +100,7 @@ For third-party connections:
- Document required OAuth or API setup in the app README or listing.
- Verify failure states for expired or missing credentials.
- When the provider can say which account a token belongs to (team, organization, user), declare `identifyAccountLogicFunction` so a reconnect that authorizes a different account is refused instead of overwriting the connection. Write the handler as one request to the provider's "who am I" endpoint, return the id as a string, and return `{ externalAccountId: null }` when there is no stable id.
-- Set `scope` on `defineConnectionProvider`: `'WORKSPACE'` (default) when the app uses one connection shared with the workspace, `'USER'` when each member connects their own account. One scope per provider; declare two providers when the app needs both. Members cannot add `USER` connections from settings yet (they will from App preferences). Requires `"engines": { "twenty": ">=2.49.0" }`.
+- Set `scope` on `defineConnectionProvider`: `'WORKSPACE'` (default) when the app uses one connection shared with the workspace, `'USER'` when each member connects their own account. One scope per provider; declare two providers when the app needs both. A provider's scope cannot change in a later version: declare a new provider with a new `universalIdentifier` instead, which deletes the old provider's connections on upgrade, and deletes existing `'USER'` connected accounts left on a `'WORKSPACE'` provider. Members cannot add `USER` connections from settings yet (they will from App preferences). Requires `"engines": { "twenty": ">=2.49.0" }`.
## Post-Install Hooks
diff --git a/packages/twenty-docs/developers/extend/apps/logic/connections.mdx b/packages/twenty-docs/developers/extend/apps/logic/connections.mdx
index 6e33fa11d58..b27adf1ef2f 100644
--- a/packages/twenty-docs/developers/extend/apps/logic/connections.mdx
+++ b/packages/twenty-docs/developers/extend/apps/logic/connections.mdx
@@ -370,14 +370,14 @@ Each connection has one of two scopes:
The provider's `scope` decides which one its new connections get:
-- `scope: 'WORKSPACE'` (the default) — the app works with connections shared with the workspace. **Add connection** in the app's settings creates a workspace-shared connection, and a member can turn a personal connection made earlier (before Twenty 2.49.0, or while the provider was `USER`) into a shared one with **Share with workspace**.
+- `scope: 'WORKSPACE'` (the default) — the app works with connections shared with the workspace. **Add connection** in the app's settings creates a workspace-shared connection.
- `scope: 'USER'` — each member connects their own account, creating personal connections. Members will connect from their **App preferences**, which is not available yet: until then a `USER` provider has no **Add connection** button, and the app's settings only list the connections a member can already see.
A provider has exactly one scope. If your app needs both a shared credential and one per member for the same service (a bot token and each member's own account, say), declare two providers.
-Twenty refuses a new connection whose scope does not match the provider's, including when your app changes its scope while a member is on the provider's consent screen. Changing `scope` in a later version does not move or delete existing connections: they keep their scope and can still be disconnected or reconnected.
+A connection always has its provider's scope, and a provider's scope is part of its identity: a later version cannot change the `scope` of an existing provider, and the upgrade is refused if it tries. To move a service from one scope to the other, declare a new provider with a new `universalIdentifier` and drop the old one. Upgrading then deletes the old provider and every connection made with it through the regular disconnect path (`onDisconnectLogicFunction`, token revocation, channel cleanup), and members connect again through the new provider.
-Adding or reconnecting a **Just for me** connection requires `CONNECTED_ACCOUNTS` permission, and adding or reconnecting a **Workspace shared** one requires `APPLICATIONS` permission. Reconnecting a **Workspace shared** connection as **Just for me** requires both.
+Adding or reconnecting a **Just for me** connection requires `CONNECTED_ACCOUNTS` permission, and adding or reconnecting a **Workspace shared** one requires `APPLICATIONS` permission.
Use the right connection for each handler:
diff --git a/packages/twenty-front/src/pages/settings/applications/SettingsApplicationConnectionDetail.tsx b/packages/twenty-front/src/pages/settings/applications/SettingsApplicationConnectionDetail.tsx
index e06e1ac6ede..ab30fca00f6 100644
--- a/packages/twenty-front/src/pages/settings/applications/SettingsApplicationConnectionDetail.tsx
+++ b/packages/twenty-front/src/pages/settings/applications/SettingsApplicationConnectionDetail.tsx
@@ -8,7 +8,7 @@ import { SettingsPath } from 'twenty-shared/types';
import { getSettingsPath } from 'twenty-shared/utils';
import { Section } from 'twenty-ui/components/layout';
import { Status, Tag } from 'twenty-ui/primitives/data-display';
-import { IconRefresh, IconTrash, IconUsers } from 'twenty-ui/icon';
+import { IconRefresh, IconTrash } from 'twenty-ui/icon';
import { Button } from 'twenty-ui/primitives/input';
import { themeCssVariables } from 'twenty-ui/theme';
@@ -135,7 +135,6 @@ export const SettingsApplicationConnectionDetail = () => {
? connection.name
: (connection?.handle ?? t`Connection`);
const deleteModalId = `delete-application-connection-modal-${connectedAccountId}`;
- const shareWithWorkspaceModalId = `share-application-connection-with-workspace-modal-${connectedAccountId}`;
const applicationSettingsPath = getSettingsPath(
SettingsPath.ApplicationDetail,
{ applicationId },
@@ -155,21 +154,6 @@ export const SettingsApplicationConnectionDetail = () => {
triggerAppOAuth({
applicationId,
providerName: provider.name,
- scope: connection.scope === 'WORKSPACE' ? 'WORKSPACE' : 'USER',
- reconnectingConnectedAccountId: connection.id,
- redirectLocation: detailPath,
- });
- };
-
- const handleShareWithWorkspace = () => {
- if (connection === undefined || provider === undefined) {
- return;
- }
-
- triggerAppOAuth({
- applicationId,
- providerName: provider.name,
- scope: 'WORKSPACE',
reconnectingConnectedAccountId: connection.id,
redirectLocation: detailPath,
});
@@ -334,14 +318,6 @@ export const SettingsApplicationConnectionDetail = () => {
color="accent"
>{t`Reconnect`}</Button>
)}
- {connection.scope !== 'WORKSPACE' &&
- provider.scope === 'WORKSPACE' && (
- <Button
- startIcon={<IconUsers />}
- onClick={() => openDialog(shareWithWorkspaceModalId)}
- variant="outline"
- >{t`Share with workspace`}</Button>
- )}
<Button
startIcon={<IconTrash />}
onClick={() => openDialog(deleteModalId)}
@@ -389,19 +365,6 @@ export const SettingsApplicationConnectionDetail = () => {
confirmButtonText={t`Disconnect`}
loading={isDeleting}
/>
- <ConfirmationDialog
- dialogId={shareWithWorkspaceModalId}
- title={t`Share with workspace?`}
- subtitle={
- <Trans>
- Sharing this connection with the workspace requires
- reconnecting it. You will be redirected to authorize it again.
- </Trans>
- }
- onConfirmClick={handleShareWithWorkspace}
- confirmButtonText={t`Reconnect and share`}
- confirmButtonColor="accent"
- />
</>
)}
</SettingsPageContainer>
diff --git a/packages/twenty-front/src/pages/settings/applications/__tests__/SettingsApplicationConnectionDetail.test.tsx b/packages/twenty-front/src/pages/settings/applications/__tests__/SettingsApplicationConnectionDetail.test.tsx
index d7f3c1d00b8..a3e6ff05782 100644
--- a/packages/twenty-front/src/pages/settings/applications/__tests__/SettingsApplicationConnectionDetail.test.tsx
+++ b/packages/twenty-front/src/pages/settings/applications/__tests__/SettingsApplicationConnectionDetail.test.tsx
@@ -148,7 +148,7 @@ describe('SettingsApplicationConnectionDetail', () => {
lastSignedInAt: null,
connectionProviderId: 'provider-1',
name: 'Original name',
- scope: ConnectedAccountScope.USER,
+ scope: ConnectedAccountScope.WORKSPACE,
lastCredentialsRefreshedAt: null,
createdAt: '2026-05-01T00:00:00.000Z',
updatedAt: '2026-05-01T00:00:00.000Z',
@@ -159,66 +159,6 @@ describe('SettingsApplicationConnectionDetail', () => {
});
});
- it('changes scope by reconnecting with the opposite scope', () => {
- renderDetailPage();
-
- fireEvent.click(
- screen.getByRole('button', {
- name: /Share with workspace/,
- }),
- );
-
- expect(mockOpenModal).toHaveBeenCalledWith(
- 'share-application-connection-with-workspace-modal-account-1',
- );
-
- fireEvent.click(
- screen.getByRole('button', {
- name: 'Reconnect and share',
- }),
- );
-
- expect(mockTriggerAppOAuth).toHaveBeenCalledWith({
- applicationId: 'app-1',
- providerName: 'google-calendar',
- scope: 'WORKSPACE',
- reconnectingConnectedAccountId: 'account-1',
- redirectLocation: '/settings/applications/app-1/connections/account-1',
- });
- });
-
- it('does not offer to share a connection of a provider scoped to each member', () => {
- mockedUseFindApplicationConnectionProviders.mockReturnValue({
- connectionProviders: [
- {
- id: 'provider-1',
- applicationId: 'app-1',
- type: 'oauth',
- name: 'google-calendar',
- displayName: 'Google Calendar',
- scope: 'USER',
- logoUrl: null,
- oauth: {
- scopes: ['calendar.readonly'],
- isClientCredentialsConfigured: true,
- },
- },
- ],
- loading: false,
- refetch: jest.fn(),
- });
-
- renderDetailPage();
-
- expect(screen.getByText('Just for me')).toBeVisible();
- expect(
- screen.queryByRole('button', { name: /Share with workspace/ }),
- ).not.toBeInTheDocument();
- expect(
- screen.getAllByRole('button', { name: 'Disconnect' }).length,
- ).toBeGreaterThan(0);
- });
-
it('offers reconnect and disconnect on a failed workspace shared connection', () => {
mockedUseApplicationConnectedAccounts.mockReturnValue({
accounts: [
@@ -252,7 +192,6 @@ describe('SettingsApplicationConnectionDetail', () => {
expect(mockTriggerAppOAuth).toHaveBeenCalledWith({
applicationId: 'app-1',
providerName: 'google-calendar',
- scope: 'WORKSPACE',
reconnectingConnectedAccountId: 'account-1',
redirectLocation: '/settings/applications/app-1/connections/account-1',
});
diff --git a/packages/twenty-front/src/pages/settings/applications/hooks/__tests__/useTriggerAppOAuth.test.tsx b/packages/twenty-front/src/pages/settings/applications/hooks/__tests__/useTriggerAppOAuth.test.tsx
index 61e5bcf91e3..883bbc2ed10 100644
--- a/packages/twenty-front/src/pages/settings/applications/hooks/__tests__/useTriggerAppOAuth.test.tsx
+++ b/packages/twenty-front/src/pages/settings/applications/hooks/__tests__/useTriggerAppOAuth.test.tsx
@@ -26,14 +26,13 @@ describe('useTriggerAppOAuth', () => {
] as unknown as ReturnType<typeof useMutation>);
});
- it('asks the server for the scope and the visibility previous releases read', async () => {
+ it('redirects to the authorize endpoint with the transient token', async () => {
const { result } = renderHook(() => useTriggerAppOAuth());
await act(() =>
result.current.triggerAppOAuth({
applicationId: 'app-1',
providerName: 'linear',
- scope: 'WORKSPACE',
reconnectingConnectedAccountId: 'account-1',
}),
);
@@ -45,8 +44,6 @@ describe('useTriggerAppOAuth', () => {
applicationId: 'app-1',
providerName: 'linear',
transientToken: 'transient',
- scope: 'WORKSPACE',
- visibility: 'workspace',
reconnectingConnectedAccountId: 'account-1',
});
});
diff --git a/packages/twenty-front/src/pages/settings/applications/hooks/useTriggerAppOAuth.ts b/packages/twenty-front/src/pages/settings/applications/hooks/useTriggerAppOAuth.ts
index 7ab71d59a2a..fa1429757bc 100644
--- a/packages/twenty-front/src/pages/settings/applications/hooks/useTriggerAppOAuth.ts
+++ b/packages/twenty-front/src/pages/settings/applications/hooks/useTriggerAppOAuth.ts
@@ -1,6 +1,5 @@
import { useMutation } from '@apollo/client/react';
import { useCallback } from 'react';
-import { LEGACY_CONNECTION_VISIBILITY_BY_SCOPE } from 'twenty-shared/application-runtime';
import { useRedirect } from '@/domain-manager/hooks/useRedirect';
import { REACT_APP_SERVER_BASE_URL } from '~/config';
@@ -17,13 +16,11 @@ export const useTriggerAppOAuth = () => {
async ({
applicationId,
providerName,
- scope,
reconnectingConnectedAccountId,
redirectLocation,
}: {
applicationId: string;
providerName: string;
- scope: 'USER' | 'WORKSPACE';
// Set to update an existing connectedAccount row rather than creating
// a new one (the "Reconnect" action on a failed credential).
reconnectingConnectedAccountId?: string;
@@ -40,9 +37,6 @@ export const useTriggerAppOAuth = () => {
applicationId,
providerName,
transientToken: token,
- scope,
- // Read by previous-release servers mid rollout
- visibility: LEGACY_CONNECTION_VISIBILITY_BY_SCOPE[scope],
});
if (reconnectingConnectedAccountId) {
diff --git a/packages/twenty-front/src/pages/settings/applications/tabs/SettingsApplicationConnectionsSection.tsx b/packages/twenty-front/src/pages/settings/applications/tabs/SettingsApplicationConnectionsSection.tsx
index b5c5c2d7a11..503ad37fd42 100644
--- a/packages/twenty-front/src/pages/settings/applications/tabs/SettingsApplicationConnectionsSection.tsx
+++ b/packages/twenty-front/src/pages/settings/applications/tabs/SettingsApplicationConnectionsSection.tsx
@@ -168,7 +168,6 @@ export const SettingsApplicationConnectionsSection = ({
triggerAppOAuth({
applicationId,
providerName: provider.name,
- scope: 'WORKSPACE',
})
}
variant="outline"
diff --git a/packages/twenty-front/src/pages/settings/applications/tabs/__tests__/SettingsApplicationConnectionsSection.test.tsx b/packages/twenty-front/src/pages/settings/applications/tabs/__tests__/SettingsApplicationConnectionsSection.test.tsx
index a074eb5058d..3c0f3cb3a8f 100644
--- a/packages/twenty-front/src/pages/settings/applications/tabs/__tests__/SettingsApplicationConnectionsSection.test.tsx
+++ b/packages/twenty-front/src/pages/settings/applications/tabs/__tests__/SettingsApplicationConnectionsSection.test.tsx
@@ -112,7 +112,7 @@ describe('SettingsApplicationConnectionsSection', () => {
).not.toBeInTheDocument();
});
- it('adds a workspace shared connection without asking for a scope', async () => {
+ it('adds a workspace shared connection', async () => {
mockedUseFindApplicationConnectionProviders.mockReturnValue({
connectionProviders: [
{
@@ -151,12 +151,10 @@ describe('SettingsApplicationConnectionsSection', () => {
screen.getByRole('button', { name: /Add connection/i }),
);
- expect(screen.queryByText('Just for me')).not.toBeInTheDocument();
expect(mockTriggerAppOAuth).toHaveBeenCalledTimes(1);
expect(mockTriggerAppOAuth).toHaveBeenCalledWith({
applicationId: 'app-1',
providerName: 'google-calendar',
- scope: 'WORKSPACE',
});
});
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-51/2-51-upgrade-version-command.module.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-51/2-51-upgrade-version-command.module.ts
index 0339a89fb30..9bd06b80838 100644
--- a/packages/twenty-server/src/database/commands/upgrade-version-command/2-51/2-51-upgrade-version-command.module.ts
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-51/2-51-upgrade-version-command.module.ts
@@ -2,10 +2,19 @@ import { Module } from '@nestjs/common';
import { WorkspaceIteratorModule } from 'src/database/commands/command-runners/workspace-iterator.module';
import { FileSettledAgentChatThreadsCommand } from 'src/database/commands/upgrade-version-command/2-51/2-51-workspace-command-1792612809770-file-settled-agent-chat-threads.command';
+import { DeleteConnectedAccountsOutsideProviderScopeCommand } from 'src/database/commands/upgrade-version-command/2-51/2-51-workspace-command-1792675225627-delete-connected-accounts-outside-provider-scope.command';
+import { ConnectedAccountMetadataModule } from 'src/engine/metadata-modules/connected-account/connected-account-metadata.module';
import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
@Module({
- imports: [WorkspaceCacheModule, WorkspaceIteratorModule],
- providers: [FileSettledAgentChatThreadsCommand],
+ imports: [
+ WorkspaceCacheModule,
+ WorkspaceIteratorModule,
+ ConnectedAccountMetadataModule,
+ ],
+ providers: [
+ FileSettledAgentChatThreadsCommand,
+ DeleteConnectedAccountsOutsideProviderScopeCommand,
+ ],
})
export class V2_51_UpgradeVersionCommandModule {}
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-51/2-51-workspace-command-1792675225627-delete-connected-accounts-outside-provider-scope.command.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-51/2-51-workspace-command-1792675225627-delete-connected-accounts-outside-provider-scope.command.ts
new file mode 100644
index 00000000000..de3e97c1b50
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-51/2-51-workspace-command-1792675225627-delete-connected-accounts-outside-provider-scope.command.ts
@@ -0,0 +1,57 @@
+import { InjectDataSource } from '@nestjs/typeorm';
+import { Command } from 'nest-commander';
+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 { RegisteredWorkspaceCommand } from 'src/engine/core-modules/upgrade/decorators/registered-workspace-command.decorator';
+import { ConnectedAccountMetadataService } from 'src/engine/metadata-modules/connected-account/connected-account-metadata.service';
+
+@RegisteredWorkspaceCommand('2.51.0', 1792675225627)
+@Command({
+ name: 'upgrade:2-51:delete-connected-accounts-outside-provider-scope',
+ description:
+ 'Delete app connected accounts whose scope differs from their connection provider scope, through the regular disconnect path',
+})
+export class DeleteConnectedAccountsOutsideProviderScopeCommand extends ProvisionedWorkspaceCommandRunner {
+ constructor(
+ protected readonly workspaceIteratorService: WorkspaceIteratorService,
+ private readonly connectedAccountMetadataService: ConnectedAccountMetadataService,
+ @InjectDataSource() private readonly dataSource: DataSource,
+ ) {
+ super(workspaceIteratorService);
+ }
+
+ override async runOnWorkspace({
+ workspaceId,
+ options,
+ }: RunOnWorkspaceArgs): Promise<void> {
+ const connectedAccounts = await this.dataSource.query<{ id: string }[]>(
+ `SELECT "connectedAccount".id
+ FROM core."connectedAccount" "connectedAccount"
+ JOIN core."connectionProvider" "connectionProvider"
+ ON "connectionProvider".id = "connectedAccount"."connectionProviderId"
+ WHERE "connectedAccount"."workspaceId" = $1
+ AND "connectedAccount".scope <> "connectionProvider".scope::text`,
+ [workspaceId],
+ );
+
+ if (options.dryRun) {
+ this.logger.log(
+ `[DRY RUN] Workspace ${workspaceId}: ${connectedAccounts.length} connected account(s) outside their provider scope would be deleted`,
+ );
+
+ return;
+ }
+
+ await this.connectedAccountMetadataService.deleteMany({
+ ids: connectedAccounts.map(({ id }) => id),
+ workspaceId,
+ });
+
+ this.logger.log(
+ `Workspace ${workspaceId}: ${connectedAccounts.length} connected account(s) outside their provider scope deleted`,
+ );
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-manifest-migration.service.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-manifest-migration.service.ts
index 727058b8ea3..5ff6d0cd935 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-manifest-migration.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-manifest-migration.service.ts
@@ -21,6 +21,8 @@ import { ApplicationService } from 'src/engine/core-modules/application/applicat
import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
import { LoggerService } from 'src/engine/core-modules/logger/logger.service';
import { WorkflowVersionCoreSyncService } from 'src/engine/core-modules/workflow/services/workflow-version-core-sync.service';
+import { ConnectedAccountMetadataService } from 'src/engine/metadata-modules/connected-account/connected-account-metadata.service';
+import { findFlatEntityByUniversalIdentifierOrThrow } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-universal-identifier-or-throw.util';
import { getMetadataFlatEntityMapsKey } from 'src/engine/metadata-modules/flat-entity/utils/get-metadata-flat-entity-maps-key.util';
import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
import { TWENTY_STANDARD_APPLICATION } from 'src/engine/workspace-manager/twenty-standard-application/constants/twenty-standard-applications';
@@ -37,6 +39,7 @@ export class ApplicationManifestMigrationService {
private readonly computeManifestFlatEntityMapsService: ComputeApplicationManifestAllUniversalFlatEntityMapsService,
private readonly logger: LoggerService,
private readonly workflowVersionCoreSyncService: WorkflowVersionCoreSyncService,
+ private readonly connectedAccountMetadataService: ConnectedAccountMetadataService,
) {}
async syncPreInstallLogicFunctionFromManifest({
@@ -252,33 +255,53 @@ export class ApplicationManifestMigrationService {
},
});
+ const connectionProviderIdsToDelete = Object.values(
+ allFlatEntityOperationRecordByMetadataName.connectionProvider
+ ?.flatEntityToDelete ?? {},
+ )
+ .filter(isDefined)
+ .map(
+ ({ universalIdentifier }) =>
+ findFlatEntityByUniversalIdentifierOrThrow({
+ flatEntityMaps: fromAllFlatEntityMaps.flatConnectionProviderMaps,
+ universalIdentifier,
+ }).id,
+ );
+
+ const shouldDeleteConnectedAccounts =
+ !dryRun && connectionProviderIdsToDelete.length > 0;
+
+ const validateBuildAndRunMigration = (isDryRun: boolean) =>
+ this.validateBuildAndRunOrThrow({
+ allFlatEntityOperationRecordByMetadataName,
+ workspaceId,
+ isSystemBuild: false,
+ applicationUniversalIdentifier:
+ ownerFlatApplication.universalIdentifier,
+ idByUniversalIdentifierByMetadataName,
+ dryRun: isDryRun,
+ });
+
const validateBuildRunStart = performance.now();
- const validateAndBuildResult =
- await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunWorkspaceMigrationFromRecord(
- {
- allFlatEntityOperationRecordByMetadataName,
- workspaceId,
- isSystemBuild: false,
- applicationUniversalIdentifier:
- ownerFlatApplication.universalIdentifier,
- idByUniversalIdentifierByMetadataName,
- dryRun,
- },
+ let validateAndBuildResult = await validateBuildAndRunMigration(
+ dryRun || shouldDeleteConnectedAccounts,
+ );
+
+ // Deleting runs disconnect hooks and revokes tokens, so the plan is validated before anything is released
+ if (shouldDeleteConnectedAccounts) {
+ await this.connectedAccountMetadataService.deleteManyByConnectionProviderIds(
+ { connectionProviderIds: connectionProviderIdsToDelete, workspaceId },
);
+
+ validateAndBuildResult = await validateBuildAndRunMigration(false);
+ }
const validateBuildRunMs = performance.now() - validateBuildRunStart;
this.logger.perf(
- `[install-perf] syncMetadataFromManifest validateBuildAndRunWorkspaceMigrationFromTo took ${validateBuildRunMs.toFixed(1)}ms (dryRun=${dryRun}, actions=${validateAndBuildResult.status === 'success' ? validateAndBuildResult.workspaceMigration.actions.length : 'n/a-failed'})`,
+ `[install-perf] syncMetadataFromManifest validateBuildAndRunWorkspaceMigrationFromTo took ${validateBuildRunMs.toFixed(1)}ms (dryRun=${dryRun}, actions=${validateAndBuildResult.workspaceMigration.actions.length})`,
ApplicationManifestMigrationService.name,
);
- if (validateAndBuildResult.status === 'fail') {
- throw new WorkspaceMigrationBuilderException(
- validateAndBuildResult,
- 'Validation errors occurred while syncing application manifest metadata',
- );
- }
-
this.logger.log(
`Metadata migration ${dryRun ? 'plan computed (dry run)' : 'completed'} for application ${ownerFlatApplication.universalIdentifier}`,
ApplicationManifestMigrationService.name,
@@ -306,6 +329,26 @@ export class ApplicationManifestMigrationService {
};
}
+ private async validateBuildAndRunOrThrow(
+ args: Parameters<
+ WorkspaceMigrationValidateBuildAndRunService['validateBuildAndRunWorkspaceMigrationFromRecord']
+ >[0],
+ ) {
+ const validateAndBuildResult =
+ await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunWorkspaceMigrationFromRecord(
+ args,
+ );
+
+ if (validateAndBuildResult.status === 'fail') {
+ throw new WorkspaceMigrationBuilderException(
+ validateAndBuildResult,
+ 'Validation errors occurred while syncing application manifest metadata',
+ );
+ }
+
+ return validateAndBuildResult;
+ }
+
private async syncApplicationReferencesFromManifest({
manifest,
workspaceId,
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-manifest.module.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-manifest.module.ts
index 6bac36669aa..ced80c551c6 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-manifest.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-manifest.module.ts
@@ -16,6 +16,7 @@ import { ApplicationRegistrationModule } from 'src/engine/core-modules/applicati
import { ApplicationTranslationModule } from 'src/engine/core-modules/application/application-translation/application-translation.module';
import { SecretEncryptionModule } from 'src/engine/core-modules/secret-encryption/secret-encryption.module';
import { SdkClientModule } from 'src/engine/core-modules/sdk-client/sdk-client.module';
+import { ConnectedAccountMetadataModule } from 'src/engine/metadata-modules/connected-account/connected-account-metadata.module';
import { FrontComponentEntity } from 'src/engine/metadata-modules/front-component/entities/front-component.entity';
import { WorkflowVersionCoreModule } from 'src/engine/core-modules/workflow/workflow-version-core.module';
import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
@@ -31,6 +32,7 @@ import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspac
ApplicationRegistrationLookupModule,
ApplicationRegistrationModule,
ApplicationTranslationModule,
+ ConnectedAccountMetadataModule,
SecretEncryptionModule,
SdkClientModule,
WorkflowVersionCoreModule,
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-exception-code.enum.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-exception-code.enum.ts
index 95a1e4f4496..5c73924bd8f 100644
--- a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-exception-code.enum.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-exception-code.enum.ts
@@ -16,5 +16,4 @@ export enum ConnectionProviderExceptionCode {
IDENTIFY_ACCOUNT_LOGIC_FUNCTION_NOT_FOUND = 'IDENTIFY_ACCOUNT_LOGIC_FUNCTION_NOT_FOUND',
IDENTIFY_ACCOUNT_LOGIC_FUNCTION_FAILED = 'IDENTIFY_ACCOUNT_LOGIC_FUNCTION_FAILED',
RECONNECT_ACCOUNT_MISMATCH = 'RECONNECT_ACCOUNT_MISMATCH',
- CONNECTION_SCOPE_NOT_ALLOWED = 'CONNECTION_SCOPE_NOT_ALLOWED',
}
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-oauth-flow.service.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-oauth-flow.service.ts
index a57ff863e81..b71af434bfe 100644
--- a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-oauth-flow.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-oauth-flow.service.ts
@@ -4,10 +4,6 @@ import { InjectRepository } from '@nestjs/typeorm';
import { IsNull, Repository } from 'typeorm';
import { type IdentifiedAccount } from 'twenty-shared/application';
-import {
- CONNECTION_SCOPE_BY_LEGACY_VISIBILITY,
- LEGACY_CONNECTION_VISIBILITY_BY_SCOPE,
-} from 'twenty-shared/application-runtime';
import { ConnectedAccountProvider } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
@@ -22,16 +18,12 @@ import {
assertOAuthProvider,
type OAuthConnectionProvider,
} from 'src/engine/core-modules/application/connection-provider/utils/assert-oauth-provider.util';
-import { assertConnectionScopeAllowedByProviderOrThrow } from 'src/engine/core-modules/application/connection-provider/utils/assert-connection-scope-allowed-by-provider-or-throw.util';
import { buildAppOAuthCallbackUrl } from 'src/engine/core-modules/application/connection-provider/utils/build-callback-url.util';
import { computePkceChallenge } from 'src/engine/core-modules/application/connection-provider/utils/compute-pkce-challenge.util';
import { exchangeCodeForToken } from 'src/engine/core-modules/application/connection-provider/utils/exchange-code-for-token.util';
import { extractEmailFromIdTokenClaims } from 'src/engine/core-modules/application/connection-provider/utils/extract-email-from-id-token-claims.util';
import { generatePkceVerifier } from 'src/engine/core-modules/application/connection-provider/utils/generate-pkce-verifier.util';
-import {
- type AppOAuthStateJwtPayload,
- type LegacyAppOAuthStateJwtPayload,
-} from 'src/engine/core-modules/auth/types/app-oauth-state-jwt-payload.type';
+import { type AppOAuthStateJwtPayload } from 'src/engine/core-modules/auth/types/app-oauth-state-jwt-payload.type';
import { JwtTokenTypeEnum } from 'src/engine/core-modules/auth/types/jwt-token-type.enum';
import { JwtWrapperService } from 'src/engine/core-modules/jwt/services/jwt-wrapper.service';
import { SecureHttpClientService } from 'src/engine/core-modules/secure-http-client/secure-http-client.service';
@@ -51,7 +43,6 @@ type AuthorizeArgs = {
workspaceId: string;
userId: string;
userWorkspaceId: string;
- scope: ConnectedAccountScope | null;
reconnectingConnectedAccountId: string | null;
redirectLocation: string | null;
};
@@ -93,27 +84,17 @@ export class ConnectionProviderOAuthFlowService {
assertOAuthProvider(connectionProvider);
- const reconnectTarget = await this.findReconnectTargetOrThrow({
+ await this.assertReconnectTargetUsableByCallerOrThrow({
connectionProviderId: connectionProvider.id,
workspaceId,
userWorkspaceId,
reconnectingConnectedAccountId: args.reconnectingConnectedAccountId,
});
- const scope =
- args.scope ?? reconnectTarget?.scope ?? connectionProvider.scope;
-
- assertConnectionScopeAllowedByProviderOrThrow({
- connectionProvider,
- scope,
- reconnectTarget,
- });
-
- await this.validateCallerCanManageRequestedConnection({
+ await this.validateCallerCanManageConnection({
workspaceId,
userWorkspaceId,
- scope,
- reconnectTarget,
+ scope: connectionProvider.scope,
});
const { clientId } =
@@ -131,8 +112,7 @@ export class ConnectionProviderOAuthFlowService {
workspaceId,
userId,
userWorkspaceId,
- scope,
- visibility: LEGACY_CONNECTION_VISIBILITY_BY_SCOPE[scope],
+ scope: connectionProvider.scope,
reconnectingConnectedAccountId: args.reconnectingConnectedAccountId,
redirectLocation: args.redirectLocation,
codeVerifier,
@@ -173,7 +153,7 @@ export class ConnectionProviderOAuthFlowService {
assertOAuthProvider(provider);
- const reconnectTarget = await this.findReconnectTargetOrThrow({
+ await this.assertReconnectTargetUsableByCallerOrThrow({
connectionProviderId: provider.id,
workspaceId: statePayload.workspaceId,
userWorkspaceId: statePayload.userWorkspaceId,
@@ -181,18 +161,10 @@ export class ConnectionProviderOAuthFlowService {
statePayload.reconnectingConnectedAccountId,
});
- // The app may have changed its scope while the member was on the consent screen.
- assertConnectionScopeAllowedByProviderOrThrow({
- connectionProvider: provider,
- scope: statePayload.scope,
- reconnectTarget,
- });
-
- await this.validateCallerCanManageRequestedConnection({
+ await this.validateCallerCanManageConnection({
workspaceId: statePayload.workspaceId,
userWorkspaceId: statePayload.userWorkspaceId,
scope: statePayload.scope,
- reconnectTarget,
});
const { clientId, clientSecret } =
@@ -257,35 +229,23 @@ export class ConnectionProviderOAuthFlowService {
};
}
- private async validateCallerCanManageRequestedConnection({
+ private async validateCallerCanManageConnection({
workspaceId,
userWorkspaceId,
scope,
- reconnectTarget,
}: {
workspaceId: string;
userWorkspaceId: string;
scope: ConnectedAccountScope;
- reconnectTarget: ConnectedAccountEntity | null;
}): Promise<void> {
- if (scope === 'WORKSPACE' || reconnectTarget?.scope === 'WORKSPACE') {
- await this.appConnectionAccessService.validateCallerCanManageConnection({
- isWorkspaceShared: true,
- workspaceId,
- userWorkspaceId,
- });
- }
-
- if (scope === 'USER') {
- await this.appConnectionAccessService.validateCallerCanManageConnection({
- isWorkspaceShared: false,
- workspaceId,
- userWorkspaceId,
- });
- }
+ await this.appConnectionAccessService.validateCallerCanManageConnection({
+ isWorkspaceShared: scope === 'WORKSPACE',
+ workspaceId,
+ userWorkspaceId,
+ });
}
- private async findReconnectTargetOrThrow({
+ private async assertReconnectTargetUsableByCallerOrThrow({
connectionProviderId,
workspaceId,
userWorkspaceId,
@@ -295,9 +255,9 @@ export class ConnectionProviderOAuthFlowService {
workspaceId: string;
userWorkspaceId: string;
reconnectingConnectedAccountId: string | null;
- }): Promise<ConnectedAccountEntity | null> {
+ }): Promise<void> {
if (!isDefined(reconnectingConnectedAccountId)) {
- return null;
+ return;
}
const reconnectTarget = await this.connectedAccountRepository.findOne({
@@ -317,8 +277,6 @@ export class ConnectionProviderOAuthFlowService {
ConnectionProviderExceptionCode.FORBIDDEN,
);
}
-
- return reconnectTarget;
}
private async signState(payload: AppOAuthStateJwtPayload): Promise<string> {
@@ -329,20 +287,15 @@ export class ConnectionProviderOAuthFlowService {
private async verifyState(state: string): Promise<AppOAuthStateJwtPayload> {
try {
- const verified = (await this.jwtWrapperService.verifyJwtToken(state)) as
- | AppOAuthStateJwtPayload
- | LegacyAppOAuthStateJwtPayload;
+ const verified = (await this.jwtWrapperService.verifyJwtToken(
+ state,
+ )) as AppOAuthStateJwtPayload;
if (verified.type !== JwtTokenTypeEnum.APP_OAUTH_STATE) {
throw new Error('Wrong JWT type for OAuth state');
}
- return 'scope' in verified
- ? verified
- : {
- ...verified,
- scope: CONNECTION_SCOPE_BY_LEGACY_VISIBILITY[verified.visibility],
- };
+ return verified;
} catch (error) {
this.logger.warn(
`Rejected OAuth state: ${(error as Error).message ?? 'unknown reason'}`,
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-oauth.controller.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-oauth.controller.ts
index 740dfa89de3..6394feb8b02 100644
--- a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-oauth.controller.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-oauth.controller.ts
@@ -2,8 +2,6 @@ import { Controller, Get, Logger, Query, Res, UseGuards } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { type Response } from 'express';
-import { isConnectionProviderScope } from 'twenty-shared/application';
-import { CONNECTION_SCOPE_BY_LEGACY_VISIBILITY } from 'twenty-shared/application-runtime';
import { ApiPath, SettingsPath } from 'twenty-shared/types';
import { getSettingsPath, isDefined } from 'twenty-shared/utils';
import { Repository } from 'typeorm';
@@ -50,8 +48,6 @@ export class ConnectionProviderOAuthController {
@Query('applicationId') applicationId: string,
@Query('providerName') providerName: string,
@Query('transientToken') transientToken: string,
- @Query('scope') scope: string | undefined,
- @Query('visibility') legacyVisibility: string | undefined,
@Query('reconnectingConnectedAccountId')
reconnectingConnectedAccountId: string | undefined,
@Query('redirectLocation') redirectLocation: string | undefined,
@@ -68,24 +64,6 @@ export class ConnectionProviderOAuthController {
);
}
- if (isDefined(scope) && !isConnectionProviderScope(scope)) {
- throw new ConnectionProviderException(
- `Invalid scope "${scope}" — must be 'USER' or 'WORKSPACE'`,
- ConnectionProviderExceptionCode.INVALID_REQUEST,
- );
- }
-
- if (
- legacyVisibility !== undefined &&
- legacyVisibility !== 'user' &&
- legacyVisibility !== 'workspace'
- ) {
- throw new ConnectionProviderException(
- `Invalid visibility "${legacyVisibility}" — must be 'user' or 'workspace'`,
- ConnectionProviderExceptionCode.INVALID_REQUEST,
- );
- }
-
const { userId, workspaceId } =
await this.transientTokenService.verifyTransientToken(transientToken);
@@ -138,11 +116,6 @@ export class ConnectionProviderOAuthController {
workspaceId,
userId,
userWorkspaceId: userWorkspace.id,
- scope:
- scope ??
- (isDefined(legacyVisibility)
- ? CONNECTION_SCOPE_BY_LEGACY_VISIBILITY[legacyVisibility]
- : null),
reconnectingConnectedAccountId:
reconnectingConnectedAccountId ?? null,
redirectLocation: redirectLocation ?? null,
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider.exception.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider.exception.ts
index 1ed6df52da4..5de4e49f566 100644
--- a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider.exception.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider.exception.ts
@@ -43,8 +43,6 @@ const getConnectionProviderExceptionUserFriendlyMessage = (
return msg`We could not identify the account you authorized. Please try again.`;
case ConnectionProviderExceptionCode.RECONNECT_ACCOUNT_MISMATCH:
return msg`You authorized a different account than the one this connection belongs to.`;
- case ConnectionProviderExceptionCode.CONNECTION_SCOPE_NOT_ALLOWED:
- return msg`This connection provider does not support this kind of connection.`;
default:
assertUnreachable(code);
}
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/filters/connection-provider-rest-api-exception.filter.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/filters/connection-provider-rest-api-exception.filter.ts
index aa3a87af3a7..a66df97b568 100644
--- a/packages/twenty-server/src/engine/core-modules/application/connection-provider/filters/connection-provider-rest-api-exception.filter.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/filters/connection-provider-rest-api-exception.filter.ts
@@ -31,7 +31,6 @@ const connectionProviderExceptionCodeToHttpStatus = (
case ConnectionProviderExceptionCode.INVALID_CONNECTION_PROVIDER_INPUT:
case ConnectionProviderExceptionCode.CONNECTION_PROVIDER_NAME_ALREADY_EXISTS:
case ConnectionProviderExceptionCode.RECONNECT_ACCOUNT_MISMATCH:
- case ConnectionProviderExceptionCode.CONNECTION_SCOPE_NOT_ALLOWED:
return 400;
case ConnectionProviderExceptionCode.CLIENT_CREDENTIALS_NOT_CONFIGURED:
case ConnectionProviderExceptionCode.TOKEN_EXCHANGE_FAILED:
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/__tests__/assert-connection-scope-allowed-by-provider-or-throw.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/__tests__/assert-connection-scope-allowed-by-provider-or-throw.util.spec.ts
deleted file mode 100644
index 7f1ce1a8e2a..00000000000
--- a/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/__tests__/assert-connection-scope-allowed-by-provider-or-throw.util.spec.ts
+++ /dev/null
@@ -1,120 +0,0 @@
-import { i18n } from '@lingui/core';
-
-import { ConnectionProviderExceptionCode } from 'src/engine/core-modules/application/connection-provider/connection-provider-exception-code.enum';
-import { ConnectionProviderException } from 'src/engine/core-modules/application/connection-provider/connection-provider.exception';
-import { assertConnectionScopeAllowedByProviderOrThrow } from 'src/engine/core-modules/application/connection-provider/utils/assert-connection-scope-allowed-by-provider-or-throw.util';
-
-const userProvider = {
- name: 'linear',
- displayName: 'Linear',
- scope: 'USER' as const,
-};
-
-const workspaceProvider = {
- name: 'slack',
- displayName: 'Slack',
- scope: 'WORKSPACE' as const,
-};
-
-const catchException = (assertion: () => void): ConnectionProviderException => {
- try {
- assertion();
- } catch (error) {
- if (error instanceof ConnectionProviderException) {
- return error;
- }
-
- throw error;
- }
-
- throw new Error('Expected a ConnectionProviderException');
-};
-
-describe('assertConnectionScopeAllowedByProviderOrThrow', () => {
- beforeAll(() => {
- i18n.loadAndActivate({ locale: 'en', messages: {} });
- });
-
- it.each([
- ['USER', userProvider],
- ['WORKSPACE', workspaceProvider],
- ] as const)(
- 'accepts a new %s connection on a provider with the same scope',
- (scope, connectionProvider) => {
- expect(() =>
- assertConnectionScopeAllowedByProviderOrThrow({
- connectionProvider,
- scope,
- reconnectTarget: null,
- }),
- ).not.toThrow();
- },
- );
-
- it.each([
- ['USER', workspaceProvider],
- ['WORKSPACE', userProvider],
- ] as const)(
- 'accepts a reconnect that keeps an existing %s scope the provider no longer has',
- (scope, connectionProvider) => {
- expect(() =>
- assertConnectionScopeAllowedByProviderOrThrow({
- connectionProvider,
- scope,
- reconnectTarget: { scope },
- }),
- ).not.toThrow();
- },
- );
-
- it('refuses a reconnect that moves a connection out of the provider scope', () => {
- const exception = catchException(() =>
- assertConnectionScopeAllowedByProviderOrThrow({
- connectionProvider: userProvider,
- scope: 'WORKSPACE',
- reconnectTarget: { scope: 'USER' },
- }),
- );
-
- expect(exception.code).toBe(
- ConnectionProviderExceptionCode.CONNECTION_SCOPE_NOT_ALLOWED,
- );
- });
-
- it('tells the member that a USER provider only supports personal connections', () => {
- const exception = catchException(() =>
- assertConnectionScopeAllowedByProviderOrThrow({
- connectionProvider: userProvider,
- scope: 'WORKSPACE',
- reconnectTarget: null,
- }),
- );
-
- expect(exception.code).toBe(
- ConnectionProviderExceptionCode.CONNECTION_SCOPE_NOT_ALLOWED,
- );
- expect(exception.message).toBe(
- 'Connection provider "linear" has scope USER and does not accept WORKSPACE connections',
- );
- expect(i18n._(exception.userFriendlyMessage)).toBe(
- 'Linear only supports personal connections.',
- );
- });
-
- it('tells the member that a WORKSPACE provider only supports shared connections', () => {
- const exception = catchException(() =>
- assertConnectionScopeAllowedByProviderOrThrow({
- connectionProvider: workspaceProvider,
- scope: 'USER',
- reconnectTarget: null,
- }),
- );
-
- expect(exception.code).toBe(
- ConnectionProviderExceptionCode.CONNECTION_SCOPE_NOT_ALLOWED,
- );
- expect(i18n._(exception.userFriendlyMessage)).toBe(
- 'Slack only supports connections shared with the workspace.',
- );
- });
-});
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/assert-connection-scope-allowed-by-provider-or-throw.util.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/assert-connection-scope-allowed-by-provider-or-throw.util.ts
deleted file mode 100644
index 9abdd7149f0..00000000000
--- a/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/assert-connection-scope-allowed-by-provider-or-throw.util.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-import { msg } from '@lingui/core/macro';
-import { isDefined } from 'twenty-shared/utils';
-
-import { ConnectionProviderExceptionCode } from 'src/engine/core-modules/application/connection-provider/connection-provider-exception-code.enum';
-import { type ConnectionProviderEntity } from 'src/engine/core-modules/application/connection-provider/connection-provider.entity';
-import { ConnectionProviderException } from 'src/engine/core-modules/application/connection-provider/connection-provider.exception';
-import {
- type ConnectedAccountEntity,
- type ConnectedAccountScope,
-} from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
-
-export const assertConnectionScopeAllowedByProviderOrThrow = ({
- connectionProvider,
- scope,
- reconnectTarget,
-}: {
- connectionProvider: Pick<
- ConnectionProviderEntity,
- 'name' | 'displayName' | 'scope'
- >;
- scope: ConnectedAccountScope;
- reconnectTarget: Pick<ConnectedAccountEntity, 'scope'> | null;
-}): void => {
- const isKeepingExistingScope =
- isDefined(reconnectTarget) && reconnectTarget.scope === scope;
-
- if (isKeepingExistingScope || connectionProvider.scope === scope) {
- return;
- }
-
- const providerDisplayName = connectionProvider.displayName;
-
- throw new ConnectionProviderException(
- `Connection provider "${connectionProvider.name}" has scope ${connectionProvider.scope} and does not accept ${scope} connections`,
- ConnectionProviderExceptionCode.CONNECTION_SCOPE_NOT_ALLOWED,
- {
- userFriendlyMessage:
- connectionProvider.scope === 'USER'
- ? msg`${providerDisplayName} only supports personal connections.`
- : msg`${providerDisplayName} only supports connections shared with the workspace.`,
- },
- );
-};
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/connection-provider-graphql-api-exception-handler.util.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/connection-provider-graphql-api-exception-handler.util.ts
index 34d47fb1c74..ddc5be95088 100644
--- a/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/connection-provider-graphql-api-exception-handler.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/connection-provider-graphql-api-exception-handler.util.ts
@@ -26,7 +26,6 @@ export const connectionProviderGraphqlApiExceptionHandler = (error: Error) => {
case ConnectionProviderExceptionCode.INVALID_CONNECTION_PROVIDER_INPUT:
case ConnectionProviderExceptionCode.CONNECTION_PROVIDER_NAME_ALREADY_EXISTS:
case ConnectionProviderExceptionCode.RECONNECT_ACCOUNT_MISMATCH:
- case ConnectionProviderExceptionCode.CONNECTION_SCOPE_NOT_ALLOWED:
throw new UserInputError(error);
case ConnectionProviderExceptionCode.CLIENT_CREDENTIALS_NOT_CONFIGURED:
case ConnectionProviderExceptionCode.TOKEN_EXCHANGE_FAILED:
diff --git a/packages/twenty-server/src/engine/core-modules/auth/types/app-oauth-state-jwt-payload.type.ts b/packages/twenty-server/src/engine/core-modules/auth/types/app-oauth-state-jwt-payload.type.ts
index ab260e0f963..403199b595a 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/types/app-oauth-state-jwt-payload.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/types/app-oauth-state-jwt-payload.type.ts
@@ -9,16 +9,9 @@ export type AppOAuthStateJwtPayload = CommonPropertiesJwtPayload & {
userId: string;
userWorkspaceId: string;
scope: ConnectedAccountScope;
- // Read by previous-release servers that complete the callback mid rollout
- visibility: 'user' | 'workspace';
// If set, the callback updates this existing connectedAccount row instead
// of creating a new one (used by the UI's "Reconnect" action).
reconnectingConnectedAccountId: string | null;
redirectLocation: string | null;
codeVerifier: string | null;
};
-
-export type LegacyAppOAuthStateJwtPayload = Omit<
- AppOAuthStateJwtPayload,
- 'scope'
->;
diff --git a/packages/twenty-server/src/engine/metadata-modules/connected-account/connected-account-metadata.service.ts b/packages/twenty-server/src/engine/metadata-modules/connected-account/connected-account-metadata.service.ts
index cbe09112302..0c98ccc8be8 100644
--- a/packages/twenty-server/src/engine/metadata-modules/connected-account/connected-account-metadata.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/connected-account/connected-account-metadata.service.ts
@@ -566,6 +566,24 @@ export class ConnectedAccountMetadataService {
return this.repository.findOneOrFail({ where: { id, workspaceId } });
}
+ async deleteManyByConnectionProviderIds({
+ connectionProviderIds,
+ workspaceId,
+ }: {
+ connectionProviderIds: string[];
+ workspaceId: string;
+ }): Promise<void> {
+ const connectedAccounts = await this.repository.find({
+ where: { connectionProviderId: In(connectionProviderIds), workspaceId },
+ select: { id: true },
+ });
+
+ await this.deleteMany({
+ ids: connectedAccounts.map(({ id }) => id),
+ workspaceId,
+ });
+ }
+
async delete({
id,
workspaceId,
@@ -577,27 +595,55 @@ export class ConnectedAccountMetadataService {
where: { id, workspaceId },
});
+ await this.deleteMany({ ids: [id], workspaceId });
+
+ return connectedAccount;
+ }
+
+ async deleteMany({
+ ids,
+ workspaceId,
+ }: {
+ ids: string[];
+ workspaceId: string;
+ }): Promise<void> {
+ if (ids.length === 0) {
+ return;
+ }
+
+ const connectedAccounts = await this.repository.find({
+ where: { id: In(ids), workspaceId },
+ });
+
+ if (connectedAccounts.length === 0) {
+ return;
+ }
+
+ const connectedAccountIds = connectedAccounts.map(({ id }) => id);
+
const [messageChannels, calendarChannels] = await Promise.all([
this.messageChannelRepository.find({
- where: { connectedAccountId: id, workspaceId },
+ where: { connectedAccountId: In(connectedAccountIds), workspaceId },
select: { id: true },
}),
this.calendarChannelRepository.find({
- where: { connectedAccountId: id, workspaceId },
+ where: { connectedAccountId: In(connectedAccountIds), workspaceId },
select: { id: true },
}),
]);
this.logger.log(
- `WorkspaceId: ${workspaceId} Deleting connected account ${id} with ${messageChannels.length} message channel(s) and ${calendarChannels.length} calendar channel(s)`,
+ `WorkspaceId: ${workspaceId} Deleting ${connectedAccounts.length} connected account(s) with ${messageChannels.length} message channel(s) and ${calendarChannels.length} calendar channel(s)`,
);
- if (isDefined(connectedAccount.connectionProviderId)) {
- await this.connectionProviderLifecycleHookService.runOnDisconnect({
- connectionProviderId: connectedAccount.connectionProviderId,
- workspaceId,
- connectedAccountId: id,
- });
+ for (const { id, connectionProviderId } of connectedAccounts) {
+ if (isDefined(connectionProviderId)) {
+ await this.connectionProviderLifecycleHookService.runOnDisconnect({
+ connectionProviderId,
+ workspaceId,
+ connectedAccountId: id,
+ });
+ }
}
await this.stopWebhookSubscriptions({
@@ -606,17 +652,16 @@ export class ConnectedAccountMetadataService {
workspaceId,
});
- // The hook may have refreshed the tokens through getConnection, and an
- // overlapping delete may already have removed the row.
- const latestConnectedAccount = await this.repository.findOne({
- where: { id, workspaceId },
+ // Hooks may have refreshed tokens through getConnection and an overlapping delete may have removed rows
+ const latestConnectedAccounts = await this.repository.find({
+ where: { id: In(connectedAccountIds), workspaceId },
});
- if (isDefined(latestConnectedAccount)) {
+ for (const latestConnectedAccount of latestConnectedAccounts) {
await this.appOAuthRevokeService.revokeIfApp(latestConnectedAccount);
}
- await this.repository.delete({ id, workspaceId });
+ await this.repository.delete({ id: In(connectedAccountIds), workspaceId });
this.workspaceEventEmitter.emitCustomBatchEvent<MessageChannelDeletedEvent>(
MESSAGE_CHANNEL_DELETED_EVENT,
@@ -636,16 +681,12 @@ export class ConnectedAccountMetadataService {
this.workspaceEventEmitter.emitCustomBatchEvent<ConnectedAccountDeletedEvent>(
CONNECTED_ACCOUNT_DELETED_EVENT,
- [
- {
- connectedAccountId: id,
- userWorkspaceId: connectedAccount.userWorkspaceId,
- },
- ],
+ connectedAccounts.map(({ id, userWorkspaceId }) => ({
+ connectedAccountId: id,
+ userWorkspaceId,
+ })),
workspaceId,
);
-
- return connectedAccount;
}
private async stopWebhookSubscriptions({
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/flat-connection-provider-validator.service.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/flat-connection-provider-validator.service.ts
index e213de225dd..4cc431855d5 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/flat-connection-provider-validator.service.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/flat-connection-provider-validator.service.ts
@@ -174,11 +174,16 @@ export class FlatConnectionProviderValidatorService {
return validationResult;
}
- validationResult.errors.push(
- ...validateConnectionProviderScope(
- flatEntityUpdate.scope ?? fromFlatConnectionProvider.scope,
- ),
- );
+ if (
+ isDefined(flatEntityUpdate.scope) &&
+ flatEntityUpdate.scope !== fromFlatConnectionProvider.scope
+ ) {
+ validationResult.errors.push({
+ code: ConnectionProviderExceptionCode.INVALID_CONNECTION_PROVIDER_INPUT,
+ message: t`Connection provider scope cannot be changed after creation: declare a new connection provider with a new universalIdentifier`,
+ userFriendlyMessage: msg`Connection provider scope cannot be changed`,
+ });
+ }
return validationResult;
}
diff --git a/packages/twenty-server/test/integration/metadata/suites/connection-provider/app-connection-connected-accounts-permission.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/connection-provider/app-connection-connected-accounts-permission.integration-spec.ts
index 6cd6f6a260f..8a8ad7c8dc2 100644
--- a/packages/twenty-server/test/integration/metadata/suites/connection-provider/app-connection-connected-accounts-permission.integration-spec.ts
+++ b/packages/twenty-server/test/integration/metadata/suites/connection-provider/app-connection-connected-accounts-permission.integration-spec.ts
@@ -210,7 +210,6 @@ describe('app connection connected accounts permission', () => {
userId: USER_DATA_SEED_IDS.PHIL,
userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.PHIL,
scope: 'USER',
- visibility: 'user',
reconnectingConnectedAccountId: null,
redirectLocation: null,
codeVerifier: null,
diff --git a/packages/twenty-server/test/integration/metadata/suites/connection-provider/app-connection-management-guards.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/connection-provider/app-connection-management-guards.integration-spec.ts
index ad22189f650..b96a37e178b 100644
--- a/packages/twenty-server/test/integration/metadata/suites/connection-provider/app-connection-management-guards.integration-spec.ts
+++ b/packages/twenty-server/test/integration/metadata/suites/connection-provider/app-connection-management-guards.integration-spec.ts
@@ -34,7 +34,6 @@ const SHARED_BY_TIM_ID = uuidv4();
const PRIVATE_OF_TIM_ID = uuidv4();
const PRIVATE_OF_JONY_ID = uuidv4();
const PRIVATE_OF_PHIL_ID = uuidv4();
-const SHARED_ON_PERSONAL_PROVIDER_ID = uuidv4();
describe('app connection management guards (e2e)', () => {
let applicationDbId: string;
@@ -108,12 +107,10 @@ describe('app connection management guards (e2e)', () => {
const startAuthorizeAndGetErrorMessage = async ({
reconnectingConnectedAccountId,
- scope,
as = 'admin',
providerName = 'slack',
}: {
reconnectingConnectedAccountId?: string;
- scope?: 'USER' | 'WORKSPACE';
as?: keyof typeof transientTokenGenerators;
providerName?: string;
}): Promise<string> => {
@@ -126,7 +123,6 @@ describe('app connection management guards (e2e)', () => {
...(isDefined(reconnectingConnectedAccountId)
? { reconnectingConnectedAccountId }
: {}),
- ...(isDefined(scope) ? { scope } : {}),
});
expect(response.status).toBe(302);
@@ -207,21 +203,18 @@ describe('app connection management guards (e2e)', () => {
id: PRIVATE_OF_TIM_ID,
scope: 'USER',
userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.TIM,
+ connectionProviderId: personalProviderDbId,
});
await insertAppConnection({
id: PRIVATE_OF_JONY_ID,
scope: 'USER',
userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.JONY,
+ connectionProviderId: personalProviderDbId,
});
await insertAppConnection({
id: PRIVATE_OF_PHIL_ID,
scope: 'USER',
userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.PHIL,
- });
- await insertAppConnection({
- id: SHARED_ON_PERSONAL_PROVIDER_ID,
- scope: 'WORKSPACE',
- userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.TIM,
connectionProviderId: personalProviderDbId,
});
}, 180000);
@@ -241,6 +234,7 @@ describe('app connection management guards (e2e)', () => {
it('refuses to reconnect a private connection owned by another member', async () => {
const errorMessage = await startAuthorizeAndGetErrorMessage({
reconnectingConnectedAccountId: PRIVATE_OF_TIM_ID,
+ providerName: 'slack-personal',
});
expect(errorMessage).toContain(
@@ -268,17 +262,6 @@ describe('app connection management guards (e2e)', () => {
it('refuses a member without the Workspace Apps permission to create a workspace-shared connection', async () => {
const errorMessage = await startAuthorizeAndGetErrorMessage({
- scope: 'WORKSPACE',
- as: 'member',
- });
-
- expect(errorMessage).toContain('does not have permission');
- });
-
- it('refuses a member without the Workspace Apps permission to share their own private connection', async () => {
- const errorMessage = await startAuthorizeAndGetErrorMessage({
- reconnectingConnectedAccountId: PRIVATE_OF_JONY_ID,
- scope: 'WORKSPACE',
as: 'member',
});
@@ -289,6 +272,7 @@ describe('app connection management guards (e2e)', () => {
const errorMessage = await startAuthorizeAndGetErrorMessage({
reconnectingConnectedAccountId: PRIVATE_OF_JONY_ID,
as: 'member',
+ providerName: 'slack-personal',
});
expect(errorMessage).not.toContain('Cannot reconnect connectedAccount');
@@ -299,16 +283,6 @@ describe('app connection management guards (e2e)', () => {
const errorMessage = await startAuthorizeAndGetErrorMessage({
reconnectingConnectedAccountId: PRIVATE_OF_PHIL_ID,
as: 'guest',
- });
-
- expect(errorMessage).toContain('does not have permission');
- });
-
- it('refuses a member without the Applications permission to turn a workspace-shared connection into a private one', async () => {
- const errorMessage = await startAuthorizeAndGetErrorMessage({
- reconnectingConnectedAccountId: SHARED_ON_PERSONAL_PROVIDER_ID,
- scope: 'USER',
- as: 'member',
providerName: 'slack-personal',
});
@@ -369,10 +343,9 @@ describe('app connection management guards (e2e)', () => {
});
}, 60000);
- it('lets the member reconnect a workspace-shared connection as shared', async () => {
+ it('lets the member reconnect a workspace-shared connection', async () => {
const errorMessage = await startAuthorizeAndGetErrorMessage({
reconnectingConnectedAccountId: SHARED_BY_TIM_ID,
- scope: 'WORKSPACE',
as: 'member',
});
@@ -380,10 +353,9 @@ describe('app connection management guards (e2e)', () => {
expect(errorMessage).not.toContain('does not have permission');
});
- it('refuses the member to turn a workspace-shared connection into a private one', async () => {
+ it('refuses the member to reconnect their own private connection', async () => {
const errorMessage = await startAuthorizeAndGetErrorMessage({
- reconnectingConnectedAccountId: SHARED_ON_PERSONAL_PROVIDER_ID,
- scope: 'USER',
+ reconnectingConnectedAccountId: PRIVATE_OF_JONY_ID,
as: 'member',
providerName: 'slack-personal',
});
diff --git a/packages/twenty-server/test/integration/metadata/suites/connection-provider/app-connection-oauth-callback.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/connection-provider/app-connection-oauth-callback.integration-spec.ts
index ec5a1692335..61a636f3351 100644
--- a/packages/twenty-server/test/integration/metadata/suites/connection-provider/app-connection-oauth-callback.integration-spec.ts
+++ b/packages/twenty-server/test/integration/metadata/suites/connection-provider/app-connection-oauth-callback.integration-spec.ts
@@ -23,17 +23,11 @@ import { v4 } from 'uuid';
import { z } from 'zod';
import { type ConnectionProviderEntity } from 'src/engine/core-modules/application/connection-provider/connection-provider.entity';
-import { type LegacyAppOAuthStateJwtPayload } from 'src/engine/core-modules/auth/types/app-oauth-state-jwt-payload.type';
-import { type JwtPayload } from 'src/engine/core-modules/auth/types/jwt-payload.type';
-import { JwtTokenTypeEnum } from 'src/engine/core-modules/auth/types/jwt-token-type.enum';
-import { type JwtWrapperService } from 'src/engine/core-modules/jwt/services/jwt-wrapper.service';
import { plaintextStringSchema } from 'src/engine/core-modules/secret-encryption/branded-strings/plaintext-string.type';
import { type SecretEncryptionService } from 'src/engine/core-modules/secret-encryption/secret-encryption.service';
import { type ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
import { type ConnectedAccountTokenEncryptionService } from 'src/engine/metadata-modules/connected-account/services/connected-account-token-encryption.service';
import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
-import { USER_WORKSPACE_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-user-workspaces.util';
-import { USER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-users.util';
const APPLICATION_IDENTIFIER = v4();
const PROVIDER_IDENTIFIER = v4();
@@ -115,7 +109,6 @@ describe('app connection OAuth callback', () => {
providerName: provider.name,
transientToken:
transient.data.generateTransientToken.transientToken.token,
- scope: 'WORKSPACE',
reconnectingConnectedAccountId,
});
@@ -404,33 +397,6 @@ export const handler = ({ connectedAccountId }) => {
expect(readExecutions(onConnectExecutionsPath)).toEqual([]);
});
- it('completes the callback for a state signed before visibility was renamed to scope', async () => {
- const legacyStatePayload: LegacyAppOAuthStateJwtPayload = {
- sub: provider.id,
- type: JwtTokenTypeEnum.APP_OAUTH_STATE,
- workspaceId: SEED_APPLE_WORKSPACE_ID,
- connectionProviderId: provider.id,
- userId: USER_DATA_SEED_IDS.JANE,
- userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.JANE,
- visibility: 'workspace',
- reconnectingConnectedAccountId: null,
- redirectLocation: null,
- codeVerifier: null,
- };
- const legacyState = await getAppProviderByClassName<JwtWrapperService>(
- 'JwtWrapperService',
- ).signAsyncOrThrow(legacyStatePayload as unknown as JwtPayload, {
- expiresIn: 60,
- });
-
- const redirect = await callback(legacyState, 'team-a:first');
-
- expect(redirect.searchParams.get('errorMessage')).toBeNull();
- expect(await readAccounts()).toMatchObject([
- { scope: 'WORKSPACE', externalAccountId: 'team-a' },
- ]);
- });
-
it('rejects tampered state before exchanging a code or executing the app', async () => {
const state = await authorize();
const redirect = await callback(`${state}invalid`, 'team-a:first');
diff --git a/packages/twenty-server/test/integration/metadata/suites/connection-provider/app-connection-provider-scope.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/connection-provider/app-connection-provider-scope.integration-spec.ts
index 4e36d2dd466..766f7d57078 100644
--- a/packages/twenty-server/test/integration/metadata/suites/connection-provider/app-connection-provider-scope.integration-spec.ts
+++ b/packages/twenty-server/test/integration/metadata/suites/connection-provider/app-connection-provider-scope.integration-spec.ts
@@ -9,10 +9,7 @@ import { generateTransientToken } from 'test/integration/utils/generate-transien
import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
import { setupHttpMock } from 'test/integration/utils/http-mock.util';
import { waitForAllJobsToFinish } from 'test/integration/utils/wait-for-all-jobs-to-finish.util';
-import {
- type ConnectionProviderManifest,
- type ConnectionProviderScope,
-} from 'twenty-shared/application';
+import { type ConnectionProviderManifest } from 'twenty-shared/application';
import { ConnectedAccountProvider } from 'twenty-shared/types';
import { assertIsDefinedOrThrow, isDefined } from 'twenty-shared/utils';
import { v4 } from 'uuid';
@@ -20,10 +17,7 @@ import { z } from 'zod';
import { plaintextStringSchema } from 'src/engine/core-modules/secret-encryption/branded-strings/plaintext-string.type';
import { type SecretEncryptionService } from 'src/engine/core-modules/secret-encryption/secret-encryption.service';
-import {
- type ConnectedAccountEntity,
- type ConnectedAccountScope,
-} from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
+import { type ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
import { USER_WORKSPACE_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-user-workspaces.util';
@@ -40,13 +34,13 @@ const buildProvider = ({
}: {
universalIdentifier: string;
name: string;
- scope?: ConnectionProviderScope;
+ scope: 'USER' | 'WORKSPACE';
}): ConnectionProviderManifest => ({
universalIdentifier,
name,
displayName: name,
type: 'oauth',
- ...(isDefined(scope) ? { scope } : {}),
+ scope,
oauth: {
authorizationEndpoint: 'https://scoped-provider.example.com/authorize',
tokenEndpoint: TOKEN_ENDPOINT,
@@ -56,9 +50,7 @@ const buildProvider = ({
},
});
-const syncProviders = async (
- workspaceProviderScope?: ConnectionProviderScope,
-) => {
+const syncProviders = async () => {
const { errors } = await syncApplication({
manifest: buildBaseManifest({
appId: APPLICATION_IDENTIFIER,
@@ -68,7 +60,7 @@ const syncProviders = async (
buildProvider({
universalIdentifier: WORKSPACE_PROVIDER_IDENTIFIER,
name: 'workspace-provider',
- scope: workspaceProviderScope,
+ scope: 'WORKSPACE',
}),
buildProvider({
universalIdentifier: USER_PROVIDER_IDENTIFIER,
@@ -84,9 +76,9 @@ const syncProviders = async (
jest.useRealTimers();
};
-describe('app connections outside the provider scope', () => {
+describe('app connections follow the provider scope', () => {
let applicationId: string;
- let providerIdByName: Record<string, string>;
+ let providerByName: Record<string, { id: string; scope: string }>;
let tokenExchanges: string[];
setupHttpMock(
@@ -114,10 +106,8 @@ describe('app connections outside the provider scope', () => {
const insertConnection = async ({
providerName,
- scope,
}: {
providerName: string;
- scope: ConnectedAccountScope;
}): Promise<string> => {
const id = v4();
@@ -130,11 +120,11 @@ describe('app connections outside the provider scope', () => {
id,
`${providerName}@example.com`,
ConnectedAccountProvider.APP,
- scope,
+ providerByName[providerName].scope,
SEED_APPLE_WORKSPACE_ID,
USER_WORKSPACE_DATA_SEED_IDS.JANE,
applicationId,
- providerIdByName[providerName],
+ providerByName[providerName].id,
],
);
@@ -143,13 +133,9 @@ describe('app connections outside the provider scope', () => {
const authorize = async ({
providerName,
- scope,
- legacyVisibility,
reconnectingConnectedAccountId,
}: {
providerName: string;
- scope?: ConnectedAccountScope;
- legacyVisibility?: 'user' | 'workspace';
reconnectingConnectedAccountId?: string;
}): Promise<{ state: string | null; errorMessage: string | null }> => {
const response = await request(`http://localhost:${APP_PORT}`)
@@ -158,10 +144,6 @@ describe('app connections outside the provider scope', () => {
applicationId,
providerName,
transientToken: await generateTransientToken(),
- ...(isDefined(scope) ? { scope } : {}),
- ...(isDefined(legacyVisibility)
- ? { visibility: legacyVisibility }
- : {}),
...(isDefined(reconnectingConnectedAccountId)
? { reconnectingConnectedAccountId }
: {}),
@@ -202,7 +184,7 @@ describe('app connections outside the provider scope', () => {
await setupApplicationForSync({
applicationUniversalIdentifier: APPLICATION_IDENTIFIER,
name: 'Connection provider scope',
- description: 'Connections outside the provider scope',
+ description: 'Connections follow the provider scope',
sourcePath: 'connection-provider-scope',
});
jest.useRealTimers();
@@ -214,8 +196,8 @@ describe('app connections outside the provider scope', () => {
);
applicationId = providers[0].applicationId;
- providerIdByName = Object.fromEntries(
- providers.map((provider) => [provider.name, provider.id]),
+ providerByName = Object.fromEntries(
+ providers.map((provider) => [provider.name, provider]),
);
const encryption = getAppProviderByClassName<SecretEncryptionService>(
@@ -254,16 +236,7 @@ describe('app connections outside the provider scope', () => {
});
});
- it('refuses a new personal connection on a WORKSPACE provider', async () => {
- const { errorMessage } = await authorize({
- providerName: 'workspace-provider',
- scope: 'USER',
- });
-
- expect(errorMessage).toContain('does not accept USER connections');
- });
-
- it('creates a workspace connection on a WORKSPACE provider when no scope is given', async () => {
+ it('creates a workspace connection on a WORKSPACE provider', async () => {
const errorMessage = await callback(
await authorizeOrThrow({ providerName: 'workspace-provider' }),
'workspace-code',
@@ -273,16 +246,7 @@ describe('app connections outside the provider scope', () => {
expect(await readAccounts()).toMatchObject([{ scope: 'WORKSPACE' }]);
});
- it('refuses a new workspace connection on a USER provider', async () => {
- const { errorMessage } = await authorize({
- providerName: 'user-provider',
- scope: 'WORKSPACE',
- });
-
- expect(errorMessage).toContain('does not accept WORKSPACE connections');
- });
-
- it('creates a personal connection on a USER provider when no scope is given', async () => {
+ it('creates a personal connection on a USER provider', async () => {
const errorMessage = await callback(
await authorizeOrThrow({ providerName: 'user-provider' }),
'user-code',
@@ -297,10 +261,9 @@ describe('app connections outside the provider scope', () => {
]);
});
- it('reconnects an existing connection whose scope no longer matches the provider scope', async () => {
+ it('reconnects an existing connection with the provider scope', async () => {
const connectedAccountId = await insertConnection({
providerName: 'user-provider',
- scope: 'WORKSPACE',
});
const errorMessage = await callback(
@@ -312,102 +275,9 @@ describe('app connections outside the provider scope', () => {
);
expect(errorMessage).toBeNull();
- expect(await readAccounts()).toMatchObject([
- { id: connectedAccountId, scope: 'WORKSPACE' },
- ]);
- expect(tokenExchanges).toEqual(['reconnect-code']);
- });
-
- it('reconnects an existing personal connection on a WORKSPACE provider', async () => {
- const connectedAccountId = await insertConnection({
- providerName: 'workspace-provider',
- scope: 'USER',
- });
-
- const errorMessage = await callback(
- await authorizeOrThrow({
- providerName: 'workspace-provider',
- reconnectingConnectedAccountId: connectedAccountId,
- }),
- 'personal-reconnect-code',
- );
-
- expect(errorMessage).toBeNull();
- expect(await readAccounts()).toMatchObject([
- { id: connectedAccountId, scope: 'USER' },
- ]);
- expect(tokenExchanges).toEqual(['personal-reconnect-code']);
- });
-
- it('refuses to share a personal connection of a USER provider with the workspace', async () => {
- const connectedAccountId = await insertConnection({
- providerName: 'user-provider',
- scope: 'USER',
- });
-
- const { errorMessage } = await authorize({
- providerName: 'user-provider',
- scope: 'WORKSPACE',
- reconnectingConnectedAccountId: connectedAccountId,
- });
-
- expect(errorMessage).toContain('does not accept WORKSPACE connections');
expect(await readAccounts()).toMatchObject([
{ id: connectedAccountId, scope: 'USER' },
]);
+ expect(tokenExchanges).toEqual(['reconnect-code']);
});
-
- it.each([
- {
- providerName: 'workspace-provider',
- legacyVisibility: 'user',
- scope: 'USER',
- },
- {
- providerName: 'user-provider',
- legacyVisibility: 'workspace',
- scope: 'WORKSPACE',
- },
- ] as const)(
- 'maps the legacy visibility=$legacyVisibility param to the $scope scope',
- async ({ providerName, legacyVisibility, scope }) => {
- const { errorMessage } = await authorize({
- providerName,
- legacyVisibility,
- });
-
- expect(errorMessage).toContain(`does not accept ${scope} connections`);
- },
- );
-
- it('creates a connection from the legacy visibility param', async () => {
- const errorMessage = await callback(
- await authorizeOrThrow({
- providerName: 'workspace-provider',
- legacyVisibility: 'workspace',
- }),
- 'legacy-code',
- );
-
- expect(errorMessage).toBeNull();
- expect(await readAccounts()).toMatchObject([{ scope: 'WORKSPACE' }]);
- });
-
- it('refuses at the callback when the app changed the provider scope after authorize', async () => {
- const state = await authorizeOrThrow({
- providerName: 'workspace-provider',
- });
-
- await syncProviders('USER');
-
- try {
- const errorMessage = await callback(state, 'late-code');
-
- expect(errorMessage).toContain('does not accept WORKSPACE connections');
- expect(tokenExchanges).toEqual([]);
- expect(await readAccounts()).toEqual([]);
- } finally {
- await syncProviders();
- }
- }, 60000);
});
diff --git a/packages/twenty-server/test/integration/metadata/suites/connection-provider/connection-provider-scope-manifest-sync.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/connection-provider/connection-provider-scope-manifest-sync.integration-spec.ts
index 7af398689c1..15a4f95cbe7 100644
--- a/packages/twenty-server/test/integration/metadata/suites/connection-provider/connection-provider-scope-manifest-sync.integration-spec.ts
+++ b/packages/twenty-server/test/integration/metadata/suites/connection-provider/connection-provider-scope-manifest-sync.integration-spec.ts
@@ -4,16 +4,24 @@ import { setupApplicationForSync } from 'test/integration/metadata/suites/applic
import { syncApplication } from 'test/integration/metadata/suites/application/utils/sync-application.util';
import { findConnectionProvidersByApplication } from 'test/integration/metadata/suites/connection-provider/utils/find-connection-providers-by-application.util';
import { type ConnectionProviderManifest } from 'twenty-shared/application';
+import { ConnectedAccountProvider } from 'twenty-shared/types';
import { v4 as uuidv4 } from 'uuid';
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+import { USER_WORKSPACE_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-user-workspaces.util';
+
const TEST_APP_ID = uuidv4();
const TEST_ROLE_ID = uuidv4();
const TEST_PROVIDER_ID = uuidv4();
-const buildProvider = (
- scope?: ConnectionProviderManifest['scope'],
-): ConnectionProviderManifest => ({
- universalIdentifier: TEST_PROVIDER_ID,
+const buildProvider = ({
+ scope,
+ universalIdentifier = TEST_PROVIDER_ID,
+}: {
+ scope?: ConnectionProviderManifest['scope'];
+ universalIdentifier?: string;
+} = {}): ConnectionProviderManifest => ({
+ universalIdentifier,
name: 'linear',
displayName: 'Linear',
type: 'oauth',
@@ -45,6 +53,39 @@ const findProviderScopes = async () =>
(provider) => provider.scope,
);
+const insertConnectedAccount = async (): Promise<string> => {
+ const [provider] = await findConnectionProvidersByApplication(TEST_APP_ID);
+ const id = uuidv4();
+
+ await globalThis.testDataSource.query(
+ `INSERT INTO core."connectedAccount"
+ (id, handle, provider, scope, "workspaceId", "userWorkspaceId",
+ "applicationId", "connectionProviderId")
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,
+ [
+ id,
+ ConnectedAccountProvider.APP,
+ provider.scope,
+ SEED_APPLE_WORKSPACE_ID,
+ USER_WORKSPACE_DATA_SEED_IDS.JANE,
+ provider.applicationId,
+ provider.id,
+ ],
+ );
+
+ return id;
+};
+
+const countConnectedAccounts = async (id: string): Promise<number> => {
+ const [{ count }] = await globalThis.testDataSource.query(
+ 'SELECT count(*)::int AS count FROM core."connectedAccount" WHERE id = $1',
+ [id],
+ );
+
+ return count;
+};
+
describe('connection provider scope manifest sync', () => {
beforeEach(async () => {
await setupApplicationForSync({
@@ -68,41 +109,45 @@ describe('connection provider scope manifest sync', () => {
}, 60000);
it('stores the declared scope', async () => {
- await syncProvider(buildProvider('USER'));
+ await syncProvider(buildProvider({ scope: 'USER' }));
expect(await findProviderScopes()).toEqual(['USER']);
}, 60000);
- it('applies a scope change on a later sync', async () => {
- await syncProvider(buildProvider('WORKSPACE'));
- await syncProvider(buildProvider('USER'));
+ it('refuses a scope change on a later sync and keeps the stored one', async () => {
+ await syncProvider(buildProvider({ scope: 'WORKSPACE' }));
- expect(await findProviderScopes()).toEqual(['USER']);
- }, 60000);
-
- it('rejects an unknown scope on create', async () => {
- const { errors } = await syncProvider(
- buildProvider('WORKSPACE_MEMBER' as never),
- { expectToFail: true },
- );
+ const { errors } = await syncProvider(buildProvider({ scope: 'USER' }), {
+ expectToFail: true,
+ });
expect(JSON.stringify(errors)).toContain(
- 'Connection provider scope \\"WORKSPACE_MEMBER\\" is invalid',
+ 'Connection provider scope cannot be changed after creation',
);
- expect(await findProviderScopes()).toEqual([]);
+ expect(await findProviderScopes()).toEqual(['WORKSPACE']);
}, 60000);
- it('rejects an unknown scope on update and keeps the stored one', async () => {
- await syncProvider(buildProvider('USER'));
+ it('deletes the connections of a provider replaced by one with a new identifier', async () => {
+ await syncProvider(buildProvider({ scope: 'WORKSPACE' }));
+ const connectedAccountId = await insertConnectedAccount();
+
+ await syncProvider(
+ buildProvider({ scope: 'USER', universalIdentifier: uuidv4() }),
+ );
+ expect(await findProviderScopes()).toEqual(['USER']);
+ expect(await countConnectedAccounts(connectedAccountId)).toBe(0);
+ }, 60000);
+
+ it('rejects an unknown scope on create', async () => {
const { errors } = await syncProvider(
- buildProvider('WORKSPACE_MEMBER' as never),
+ buildProvider({ scope: 'WORKSPACE_MEMBER' as never }),
{ expectToFail: true },
);
expect(JSON.stringify(errors)).toContain(
'Connection provider scope \\"WORKSPACE_MEMBER\\" is invalid',
);
- expect(await findProviderScopes()).toEqual(['USER']);
+ expect(await findProviderScopes()).toEqual([]);
}, 60000);
});
diff --git a/packages/twenty-server/test/integration/upgrade/suites/2-51-workspace-command-1792675225627-delete-connected-accounts-outside-provider-scope.integration-spec.ts b/packages/twenty-server/test/integration/upgrade/suites/2-51-workspace-command-1792675225627-delete-connected-accounts-outside-provider-scope.integration-spec.ts
new file mode 100644
index 00000000000..39b0355923d
--- /dev/null
+++ b/packages/twenty-server/test/integration/upgrade/suites/2-51-workspace-command-1792675225627-delete-connected-accounts-outside-provider-scope.integration-spec.ts
@@ -0,0 +1,183 @@
+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 { findConnectionProvidersByApplication } from 'test/integration/metadata/suites/connection-provider/utils/find-connection-providers-by-application.util';
+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
+import { ConnectedAccountProvider } from 'twenty-shared/types';
+import { v4 } from 'uuid';
+
+import { type DeleteConnectedAccountsOutsideProviderScopeCommand } from 'src/database/commands/upgrade-version-command/2-51/2-51-workspace-command-1792675225627-delete-connected-accounts-outside-provider-scope.command';
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+import { USER_WORKSPACE_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-user-workspaces.util';
+
+const APPLICATION_IDENTIFIER = v4();
+const PROVIDER_IDENTIFIER = v4();
+
+const RUN_ON_WORKSPACE_ARGS = {
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ options: {},
+ index: 0,
+ total: 1,
+};
+
+describe('2-51 workspace command - delete connected accounts outside provider scope (integration)', () => {
+ let command: DeleteConnectedAccountsOutsideProviderScopeCommand;
+ let applicationId: string;
+ let connectionProviderId: string;
+
+ const insertConnectedAccount = async ({
+ provider,
+ scope,
+ isAppConnection,
+ }: {
+ provider: ConnectedAccountProvider;
+ scope: 'USER' | 'WORKSPACE';
+ isAppConnection: boolean;
+ }): Promise<string> => {
+ const id = v4();
+
+ await globalThis.testDataSource.query(
+ `INSERT INTO core."connectedAccount"
+ (id, handle, provider, scope, "workspaceId", "userWorkspaceId",
+ "applicationId", "connectionProviderId")
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,
+ [
+ id,
+ `${id}@provider-scope.test`,
+ provider,
+ scope,
+ SEED_APPLE_WORKSPACE_ID,
+ USER_WORKSPACE_DATA_SEED_IDS.JANE,
+ isAppConnection ? applicationId : null,
+ isAppConnection ? connectionProviderId : null,
+ ],
+ );
+
+ return id;
+ };
+
+ const findRemainingIds = async (ids: string[]): Promise<string[]> => {
+ const rows = await globalThis.testDataSource.query<{ id: string }[]>(
+ 'SELECT id FROM core."connectedAccount" WHERE id = ANY($1)',
+ [ids],
+ );
+
+ return rows.map(({ id }) => id).sort();
+ };
+
+ beforeAll(async () => {
+ command =
+ getAppProviderByClassName<DeleteConnectedAccountsOutsideProviderScopeCommand>(
+ 'DeleteConnectedAccountsOutsideProviderScopeCommand',
+ );
+
+ await setupApplicationForSync({
+ applicationUniversalIdentifier: APPLICATION_IDENTIFIER,
+ name: 'Provider scope cleanup',
+ description: 'Connected accounts outside their provider scope',
+ sourcePath: 'provider-scope-cleanup',
+ });
+
+ const { errors } = await syncApplication({
+ manifest: buildBaseManifest({
+ appId: APPLICATION_IDENTIFIER,
+ roleId: v4(),
+ overrides: {
+ connectionProviders: [
+ {
+ universalIdentifier: PROVIDER_IDENTIFIER,
+ name: 'workspace-provider',
+ displayName: 'Workspace provider',
+ type: 'oauth',
+ scope: 'WORKSPACE',
+ oauth: {
+ authorizationEndpoint:
+ 'https://provider-scope.example.com/authorize',
+ tokenEndpoint: 'https://provider-scope.example.com/token',
+ scopes: ['read'],
+ clientIdVariable: 'CLIENT_ID',
+ clientSecretVariable: 'CLIENT_SECRET',
+ },
+ },
+ ],
+ },
+ }),
+ });
+
+ expect(errors).toBeUndefined();
+ jest.useRealTimers();
+
+ const [provider] = await findConnectionProvidersByApplication(
+ APPLICATION_IDENTIFIER,
+ );
+
+ applicationId = provider.applicationId;
+ connectionProviderId = provider.id;
+ }, 120000);
+
+ afterEach(async () => {
+ await globalThis.testDataSource.query(
+ 'DELETE FROM core."connectedAccount" WHERE handle LIKE $1',
+ ['%@provider-scope.test'],
+ );
+ });
+
+ afterAll(async () => {
+ await cleanupApplicationAndAppRegistration({
+ applicationUniversalIdentifier: APPLICATION_IDENTIFIER,
+ });
+ });
+
+ it('deletes only app connections whose scope differs from their provider scope', async () => {
+ const googleAccountId = await insertConnectedAccount({
+ provider: ConnectedAccountProvider.GOOGLE,
+ scope: 'USER',
+ isAppConnection: false,
+ });
+ const microsoftAccountId = await insertConnectedAccount({
+ provider: ConnectedAccountProvider.MICROSOFT,
+ scope: 'USER',
+ isAppConnection: false,
+ });
+ const sharedAppAccountId = await insertConnectedAccount({
+ provider: ConnectedAccountProvider.APP,
+ scope: 'WORKSPACE',
+ isAppConnection: true,
+ });
+ const personalAppAccountId = await insertConnectedAccount({
+ provider: ConnectedAccountProvider.APP,
+ scope: 'USER',
+ isAppConnection: true,
+ });
+ const allIds = [
+ googleAccountId,
+ microsoftAccountId,
+ sharedAppAccountId,
+ personalAppAccountId,
+ ];
+
+ await command.runOnWorkspace(RUN_ON_WORKSPACE_ARGS);
+
+ expect(await findRemainingIds(allIds)).toEqual(
+ [googleAccountId, microsoftAccountId, sharedAppAccountId].sort(),
+ );
+ });
+
+ it('deletes nothing on a dry run', async () => {
+ const personalAppAccountId = await insertConnectedAccount({
+ provider: ConnectedAccountProvider.APP,
+ scope: 'USER',
+ isAppConnection: true,
+ });
+
+ await command.runOnWorkspace({
+ ...RUN_ON_WORKSPACE_ARGS,
+ options: { dryRun: true },
+ });
+
+ expect(await findRemainingIds([personalAppAccountId])).toEqual([
+ personalAppAccountId,
+ ]);
+ });
+});