The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Restrict application-only endpoints to application callers (#27279)
Paul Rastoin855397543bf3
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-job/application-job.resolver.ts b/packages/twenty-server/src/engine/core-modules/application/application-job/application-job.resolver.tsindex 8a6236521ab..0fcc03fce79 100644--- a/packages/twenty-server/src/engine/core-modules/application/application-job/application-job.resolver.ts+++ b/packages/twenty-server/src/engine/core-modules/application/application-job/application-job.resolver.ts@@ -28,14 +28,9 @@ import { AuthPrincipalGuard } from 'src/engine/guards/auth-principal.guard';@UseGuards(AuthPrincipalGuard({- userSession: {- standard: true,- impersonated: true,- playground: true,- workspaceAgnostic: false,- },- apiKey: true,- oauthClient: true,+ userSession: false,+ apiKey: false,+ oauthClient: false,application: true,}),NoPermissionGuard,diff --git a/packages/twenty-server/src/engine/core-modules/application/application-key-value/application-key-value.resolver.ts b/packages/twenty-server/src/engine/core-modules/application/application-key-value/application-key-value.resolver.tsindex 7e8dabfce2a..9b2b0eebecd 100644--- a/packages/twenty-server/src/engine/core-modules/application/application-key-value/application-key-value.resolver.ts+++ b/packages/twenty-server/src/engine/core-modules/application/application-key-value/application-key-value.resolver.ts@@ -19,14 +19,9 @@ import { AuthGraphqlApiExceptionFilter } from 'src/engine/core-modules/auth/filt@UseGuards(AuthPrincipalGuard({- userSession: {- standard: true,- impersonated: true,- playground: true,- workspaceAgnostic: false,- },- apiKey: true,- oauthClient: true,+ userSession: false,+ apiKey: false,+ oauthClient: false,application: true,}),NoPermissionGuard,diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/application-connections.controller.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/application-connections.controller.tsindex ab1fee37ce0..57fbeb6717b 100644--- a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/application-connections.controller.ts+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/application-connections.controller.ts@@ -33,14 +33,9 @@ import { AuthPrincipalGuard } from 'src/engine/guards/auth-principal.guard';@UseGuards(JwtAuthGuard,AuthPrincipalGuard({- userSession: {- standard: true,- impersonated: true,- playground: true,- workspaceAgnostic: false,- },- apiKey: true,- oauthClient: true,+ userSession: false,+ apiKey: false,+ oauthClient: false,application: true,}),NoPermissionGuard,diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/application-connections.resolver.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/application-connections.resolver.tsindex 3bebe69508f..e78caf63b57 100644--- a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/application-connections.resolver.ts+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/application-connections.resolver.ts@@ -25,14 +25,9 @@ import { AuthGraphqlApiExceptionFilter } from 'src/engine/core-modules/auth/filt@UseGuards(AuthPrincipalGuard({- userSession: {- standard: true,- impersonated: true,- playground: true,- workspaceAgnostic: false,- },- apiKey: true,- oauthClient: true,+ userSession: false,+ apiKey: false,+ oauthClient: false,application: true,}),NoPermissionGuard,diff --git a/packages/twenty-server/src/engine/core-modules/billing/app-billing/app-billing.controller.ts b/packages/twenty-server/src/engine/core-modules/billing/app-billing/app-billing.controller.tsindex 0faae6903c0..6ace649a236 100644--- a/packages/twenty-server/src/engine/core-modules/billing/app-billing/app-billing.controller.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/app-billing/app-billing.controller.ts@@ -50,14 +50,9 @@ const CREDIT_UNAVAILABLE_REASON_BY_SERVER_REASON: Record<@UseGuards(JwtAuthGuard,AuthPrincipalGuard({- userSession: {- standard: true,- impersonated: true,- playground: true,- workspaceAgnostic: false,- },- apiKey: true,- oauthClient: true,+ userSession: false,+ apiKey: false,+ oauthClient: false,application: true,}),NoPermissionGuard,diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/resolvers/application-message-channels.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/resolvers/application-message-channels.resolver.tsindex 9a9bd6806b0..483c9b868db 100644--- a/packages/twenty-server/src/engine/metadata-modules/message-channel/resolvers/application-message-channels.resolver.ts+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/resolvers/application-message-channels.resolver.ts@@ -26,14 +26,9 @@ import { AuthGraphqlApiExceptionFilter } from 'src/engine/core-modules/auth/filt@UseGuards(AuthPrincipalGuard({- userSession: {- standard: true,- impersonated: true,- playground: true,- workspaceAgnostic: false,- },- apiKey: true,- oauthClient: true,+ userSession: false,+ apiKey: false,+ oauthClient: false,application: true,}),NoPermissionGuard,diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/resolvers/application-message-ingestion.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/resolvers/application-message-ingestion.resolver.tsindex c07d760220a..18a09f3f6e2 100644--- a/packages/twenty-server/src/engine/metadata-modules/message-channel/resolvers/application-message-ingestion.resolver.ts+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/resolvers/application-message-ingestion.resolver.ts@@ -23,14 +23,9 @@ import { AuthGraphqlApiExceptionFilter } from 'src/engine/core-modules/auth/filt@UseGuards(AuthPrincipalGuard({- userSession: {- standard: true,- impersonated: true,- playground: true,- workspaceAgnostic: false,- },- apiKey: true,- oauthClient: true,+ userSession: false,+ apiKey: false,+ oauthClient: false,application: true,}),NoPermissionGuard,diff --git a/packages/twenty-server/test/integration/billing/suites/app-billing-controller.integration-spec.ts b/packages/twenty-server/test/integration/billing/suites/app-billing-controller.integration-spec.tsnew file mode 100644index 00000000000..88b26646c5d--- /dev/null+++ b/packages/twenty-server/test/integration/billing/suites/app-billing-controller.integration-spec.ts@@ -0,0 +1,81 @@+import { findManyApplications } from 'test/integration/graphql/utils/find-many-applications.util';+import {+ APPLICATION_ONLY_REST_REQUEST_FACTORIES,+ makeApplicationOnlyRestRequest,+} from 'test/integration/metadata/suites/application/utils/application-only-endpoint-request-factories.util';+import { generateAppleAdminApplicationTokenPair } from 'test/integration/utils/generate-apple-admin-application-token-pair.util';+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';+import { CREDIT_UNAVAILABLE_REASONS } from 'twenty-shared/application';+import { isDefined } from 'twenty-shared/utils';++import { type AppBillingService } from 'src/engine/core-modules/billing/app-billing/app-billing.service';+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';+import { TWENTY_STANDARD_APPLICATION } from 'src/engine/workspace-manager/twenty-standard-application/constants/twenty-standard-applications';++describe('AppBillingController (integration)', () => {+ let applicationId: string;+ let applicationToken: string;++ beforeAll(async () => {+ const { data } = await findManyApplications({ expectToFail: false });++ const standardApplication = data.findManyApplications.find(+ (application) =>+ application.universalIdentifier ===+ TWENTY_STANDARD_APPLICATION.universalIdentifier,+ );++ if (!isDefined(standardApplication)) {+ throw new Error('The standard application is not installed');+ }++ applicationId = standardApplication.id;++ const tokenPair = await generateAppleAdminApplicationTokenPair({+ applicationId,+ });++ applicationToken = tokenPair.applicationAccessToken.token;+ });++ it('tells the calling application whether credits are available', async () => {+ const response = await makeApplicationOnlyRestRequest(+ APPLICATION_ONLY_REST_REQUEST_FACTORIES['GET /app/billing/credits'](),+ applicationToken,+ );++ expect(response.status).toBe(200);+ expect([+ { hasAvailableCredits: true },+ ...CREDIT_UNAVAILABLE_REASONS.map((reason) => ({+ hasAvailableCredits: false,+ reason,+ })),+ ]).toContainEqual(response.body);+ });++ it('records a charge for the calling application', async () => {+ const emitChargeEventSpy = jest.spyOn(+ getAppProviderByClassName<AppBillingService>('AppBillingService'),+ 'emitChargeEvent',+ );++ try {+ const response = await makeApplicationOnlyRestRequest(+ APPLICATION_ONLY_REST_REQUEST_FACTORIES['POST /app/billing/charge'](),+ applicationToken,+ );++ expect(response.status).toBe(204);+ expect(emitChargeEventSpy).toHaveBeenCalledTimes(1);+ expect(emitChargeEventSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ workspaceId: SEED_APPLE_WORKSPACE_ID,+ applicationId,+ }),+ );+ } finally {+ emitChargeEventSpy.mockRestore();+ }+ });+});diff --git a/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap b/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snapindex ba77a855e16..50cb1131745 100644--- a/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap+++ b/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap@@ -102,17 +102,17 @@ exports[`endpoint permission declarations should match the AuthPrincipalGuard an"ApiKeyResolver.getApiKeyRoles {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":true,"oauthClient":true,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}","ApiKeyResolver.revokeApiKey {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":true,"oauthClient":true,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}},{"apiKey":false,"application":false,"oauthClient":false,"userSession":{"impersonated":true,"playground":false,"standard":true,"workspaceAgnostic":false}}]}","ApiKeyResolver.updateApiKey {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":true,"oauthClient":true,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}},{"apiKey":false,"application":false,"oauthClient":false,"userSession":{"impersonated":true,"playground":false,"standard":true,"workspaceAgnostic":false}}]}",- "AppBillingController.charge {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":true,"oauthClient":true,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",- "AppBillingController.credits {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":true,"oauthClient":true,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",+ "AppBillingController.charge {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":true,"oauthClient":false,"userSession":false}]}",+ "AppBillingController.credits {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":true,"oauthClient":false,"userSession":false}]}","ApplicationAuthorizationResolver.currentUserApplicationAuthorizations {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":false,"oauthClient":false,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}","ApplicationAuthorizationResolver.revokeApplicationAuthorization {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":false,"oauthClient":false,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}","ApplicationCapabilityResolver.grantApplicationCapabilities {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":false,"oauthClient":false,"userSession":{"impersonated":true,"playground":false,"standard":true,"workspaceAgnostic":false}}]}","ApplicationConnectionProviderResolver.applicationConnectionProviders {"applicationTarget":{"argName":"applicationId","kind":"applicationId","requireApplicationRegistrationOwnership":false,"source":"graphqlArg"},"authPrincipalGuards":[{"apiKey":true,"application":true,"oauthClient":true,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",- "ApplicationConnectionsController.get {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":true,"oauthClient":true,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",- "ApplicationConnectionsController.list {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":true,"oauthClient":true,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",- "ApplicationConnectionsResolver.appConnection {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":true,"oauthClient":true,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",- "ApplicationConnectionsResolver.appConnections {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":true,"oauthClient":true,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",- "ApplicationConnectionsResolver.reportAppConnectionAuthFailure {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":true,"oauthClient":true,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",+ "ApplicationConnectionsController.get {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":true,"oauthClient":false,"userSession":false}]}",+ "ApplicationConnectionsController.list {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":true,"oauthClient":false,"userSession":false}]}",+ "ApplicationConnectionsResolver.appConnection {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":true,"oauthClient":false,"userSession":false}]}",+ "ApplicationConnectionsResolver.appConnections {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":true,"oauthClient":false,"userSession":false}]}",+ "ApplicationConnectionsResolver.reportAppConnectionAuthFailure {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":true,"oauthClient":false,"userSession":false}]}","ApplicationDevelopmentResolver.completeApplicationFileUploads {"applicationTarget":{"idKey":"applicationUniversalIdentifier","kind":"applicationUniversalIdentifier","requireApplicationRegistrationOwnership":true,"source":"graphqlArgs"},"authPrincipalGuards":[{"apiKey":true,"application":false,"oauthClient":true,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}","ApplicationDevelopmentResolver.createApplicationFileUploads {"applicationTarget":{"idKey":"applicationUniversalIdentifier","kind":"applicationUniversalIdentifier","requireApplicationRegistrationOwnership":true,"source":"graphqlArgs"},"authPrincipalGuards":[{"apiKey":true,"application":false,"oauthClient":true,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}","ApplicationDevelopmentResolver.createDevelopmentApplication {"applicationTarget":{"idKey":"universalIdentifier","kind":"applicationUniversalIdentifier","requireApplicationRegistrationOwnership":true,"source":"graphqlArgs"},"authPrincipalGuards":[{"apiKey":true,"application":false,"oauthClient":true,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",@@ -130,17 +130,17 @@ exports[`endpoint permission declarations should match the AuthPrincipalGuard an"ApplicationInstallResolver.triggerUninstallApplicationJob {"applicationTarget":{"argName":"input","idKey":"universalIdentifier","kind":"applicationUniversalIdentifier","requireApplicationRegistrationOwnership":false,"source":"graphqlArg"},"authPrincipalGuards":[{"apiKey":true,"application":true,"oauthClient":true,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}},{"apiKey":true,"application":false,"oauthClient":true,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}","ApplicationInstallResolver.uninstallApplication {"applicationTarget":{"idKey":"universalIdentifier","kind":"applicationUniversalIdentifier","requireApplicationRegistrationOwnership":false,"source":"graphqlArgs"},"authPrincipalGuards":[{"apiKey":true,"application":true,"oauthClient":true,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}},{"apiKey":true,"application":false,"oauthClient":true,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}","ApplicationInstallResolver.updateApplication {"applicationTarget":{"argName":"id","kind":"applicationId","requireApplicationRegistrationOwnership":false,"source":"graphqlArg"},"authPrincipalGuards":[{"apiKey":true,"application":true,"oauthClient":true,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}},{"apiKey":true,"application":false,"oauthClient":true,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",- "ApplicationJobResolver.enqueueJob {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":true,"oauthClient":true,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",- "ApplicationJobResolver.enqueueJobs {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":true,"oauthClient":true,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",- "ApplicationJobResolver.getJobs {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":true,"oauthClient":true,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",- "ApplicationKeyValueResolver.appKeyValue {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":true,"oauthClient":true,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",- "ApplicationKeyValueResolver.deleteAppKeyValue {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":true,"oauthClient":true,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",- "ApplicationKeyValueResolver.setAppKeyValue {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":true,"oauthClient":true,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",- "ApplicationMessageChannelsResolver.appMessageChannels {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":true,"oauthClient":true,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",- "ApplicationMessageChannelsResolver.createAppMessageChannel {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":true,"oauthClient":true,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",- "ApplicationMessageChannelsResolver.deleteAppMessageChannel {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":true,"oauthClient":true,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",- "ApplicationMessageChannelsResolver.updateAppMessageChannel {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":true,"oauthClient":true,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",- "ApplicationMessageIngestionResolver.ingestAppMessages {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":true,"oauthClient":true,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",+ "ApplicationJobResolver.enqueueJob {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":true,"oauthClient":false,"userSession":false}]}",+ "ApplicationJobResolver.enqueueJobs {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":true,"oauthClient":false,"userSession":false}]}",+ "ApplicationJobResolver.getJobs {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":true,"oauthClient":false,"userSession":false}]}",+ "ApplicationKeyValueResolver.appKeyValue {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":true,"oauthClient":false,"userSession":false}]}",+ "ApplicationKeyValueResolver.deleteAppKeyValue {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":true,"oauthClient":false,"userSession":false}]}",+ "ApplicationKeyValueResolver.setAppKeyValue {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":true,"oauthClient":false,"userSession":false}]}",+ "ApplicationMessageChannelsResolver.appMessageChannels {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":true,"oauthClient":false,"userSession":false}]}",+ "ApplicationMessageChannelsResolver.createAppMessageChannel {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":true,"oauthClient":false,"userSession":false}]}",+ "ApplicationMessageChannelsResolver.deleteAppMessageChannel {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":true,"oauthClient":false,"userSession":false}]}",+ "ApplicationMessageChannelsResolver.updateAppMessageChannel {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":true,"oauthClient":false,"userSession":false}]}",+ "ApplicationMessageIngestionResolver.ingestAppMessages {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":true,"oauthClient":false,"userSession":false}]}","ApplicationOAuthResolver.renewApplicationToken {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":true,"oauthClient":true,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}},{"apiKey":false,"application":false,"oauthClient":false,"userSession":{"impersonated":true,"playground":false,"standard":true,"workspaceAgnostic":false}}]}","ApplicationRegistrationClaimController.githubCallback {"applicationTarget":null,"authPrincipalGuards":[]}","ApplicationRegistrationResolver.applicationRegistrationTarballUrl {"applicationTarget":{"argName":"id","kind":"applicationRegistrationId","requireApplicationRegistrationOwnership":true,"source":"graphqlArg"},"authPrincipalGuards":[{"apiKey":true,"application":true,"oauthClient":true,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",diff --git a/packages/twenty-server/test/integration/metadata/suites/application/__snapshots__/failing-application-only-endpoint-access.integration-spec.ts.snap b/packages/twenty-server/test/integration/metadata/suites/application/__snapshots__/failing-application-only-endpoint-access.integration-spec.ts.snapnew file mode 100644index 00000000000..1a6277e15e6--- /dev/null+++ b/packages/twenty-server/test/integration/metadata/suites/application/__snapshots__/failing-application-only-endpoint-access.integration-spec.ts.snap@@ -0,0 +1,553 @@+// Jest Snapshot v1, https://goo.gl/fbAQLP++exports[`Application-only endpoints with a non-application caller should fail with a member session should refuse GET /app/billing/credits and leave state unchanged 1`] = `+{+ "body": {+ "error": "Forbidden",+ "message": "This endpoint is not available to this caller",+ "statusCode": 403,+ },+ "status": 403,+}+`;++exports[`Application-only endpoints with a non-application caller should fail with a member session should refuse POST /app/billing/charge and leave state unchanged 1`] = `+{+ "body": {+ "error": "Forbidden",+ "message": "This endpoint is not available to this caller",+ "statusCode": 403,+ },+ "status": 403,+}+`;++exports[`Application-only endpoints with a non-application caller should fail with a member session should refuse POST /apps/connections/get and leave state unchanged 1`] = `+{+ "body": {+ "error": "Forbidden",+ "message": "This endpoint is not available to this caller",+ "statusCode": 403,+ },+ "status": 403,+}+`;++exports[`Application-only endpoints with a non-application caller should fail with a member session should refuse POST /apps/connections/list and leave state unchanged 1`] = `+{+ "body": {+ "error": "Forbidden",+ "message": "This endpoint is not available to this caller",+ "statusCode": 403,+ },+ "status": 403,+}+`;++exports[`Application-only endpoints with a non-application caller should fail with a member session should refuse appConnection and leave state unchanged 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint is not available to this caller",+}+`;++exports[`Application-only endpoints with a non-application caller should fail with a member session should refuse appConnections and leave state unchanged 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint is not available to this caller",+}+`;++exports[`Application-only endpoints with a non-application caller should fail with a member session should refuse appKeyValue and leave state unchanged 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint is not available to this caller",+}+`;++exports[`Application-only endpoints with a non-application caller should fail with a member session should refuse appMessageChannels and leave state unchanged 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint is not available to this caller",+}+`;++exports[`Application-only endpoints with a non-application caller should fail with a member session should refuse createAppMessageChannel and leave state unchanged 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint is not available to this caller",+}+`;++exports[`Application-only endpoints with a non-application caller should fail with a member session should refuse deleteAppKeyValue and leave state unchanged 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint is not available to this caller",+}+`;++exports[`Application-only endpoints with a non-application caller should fail with a member session should refuse deleteAppMessageChannel and leave state unchanged 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint is not available to this caller",+}+`;++exports[`Application-only endpoints with a non-application caller should fail with a member session should refuse enqueueJob and leave state unchanged 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint is not available to this caller",+}+`;++exports[`Application-only endpoints with a non-application caller should fail with a member session should refuse enqueueJobs and leave state unchanged 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint is not available to this caller",+}+`;++exports[`Application-only endpoints with a non-application caller should fail with a member session should refuse getJobs and leave state unchanged 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint is not available to this caller",+}+`;++exports[`Application-only endpoints with a non-application caller should fail with a member session should refuse ingestAppMessages and leave state unchanged 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint is not available to this caller",+}+`;++exports[`Application-only endpoints with a non-application caller should fail with a member session should refuse reportAppConnectionAuthFailure and leave state unchanged 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint is not available to this caller",+}+`;++exports[`Application-only endpoints with a non-application caller should fail with a member session should refuse setAppKeyValue and leave state unchanged 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint is not available to this caller",+}+`;++exports[`Application-only endpoints with a non-application caller should fail with a member session should refuse updateAppMessageChannel and leave state unchanged 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint is not available to this caller",+}+`;++exports[`Application-only endpoints with a non-application caller should fail with an API key should refuse GET /app/billing/credits and leave state unchanged 1`] = `+{+ "body": {+ "error": "Forbidden",+ "message": "This endpoint is not available to this caller",+ "statusCode": 403,+ },+ "status": 403,+}+`;++exports[`Application-only endpoints with a non-application caller should fail with an API key should refuse POST /app/billing/charge and leave state unchanged 1`] = `+{+ "body": {+ "error": "Forbidden",+ "message": "This endpoint is not available to this caller",+ "statusCode": 403,+ },+ "status": 403,+}+`;++exports[`Application-only endpoints with a non-application caller should fail with an API key should refuse POST /apps/connections/get and leave state unchanged 1`] = `+{+ "body": {+ "error": "Forbidden",+ "message": "This endpoint is not available to this caller",+ "statusCode": 403,+ },+ "status": 403,+}+`;++exports[`Application-only endpoints with a non-application caller should fail with an API key should refuse POST /apps/connections/list and leave state unchanged 1`] = `+{+ "body": {+ "error": "Forbidden",+ "message": "This endpoint is not available to this caller",+ "statusCode": 403,+ },+ "status": 403,+}+`;++exports[`Application-only endpoints with a non-application caller should fail with an API key should refuse appConnection and leave state unchanged 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint is not available to this caller",+}+`;++exports[`Application-only endpoints with a non-application caller should fail with an API key should refuse appConnections and leave state unchanged 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint is not available to this caller",+}+`;++exports[`Application-only endpoints with a non-application caller should fail with an API key should refuse appKeyValue and leave state unchanged 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint is not available to this caller",+}+`;++exports[`Application-only endpoints with a non-application caller should fail with an API key should refuse appMessageChannels and leave state unchanged 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint is not available to this caller",+}+`;++exports[`Application-only endpoints with a non-application caller should fail with an API key should refuse createAppMessageChannel and leave state unchanged 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint is not available to this caller",+}+`;++exports[`Application-only endpoints with a non-application caller should fail with an API key should refuse deleteAppKeyValue and leave state unchanged 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint is not available to this caller",+}+`;++exports[`Application-only endpoints with a non-application caller should fail with an API key should refuse deleteAppMessageChannel and leave state unchanged 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint is not available to this caller",+}+`;++exports[`Application-only endpoints with a non-application caller should fail with an API key should refuse enqueueJob and leave state unchanged 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint is not available to this caller",+}+`;++exports[`Application-only endpoints with a non-application caller should fail with an API key should refuse enqueueJobs and leave state unchanged 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint is not available to this caller",+}+`;++exports[`Application-only endpoints with a non-application caller should fail with an API key should refuse getJobs and leave state unchanged 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint is not available to this caller",+}+`;++exports[`Application-only endpoints with a non-application caller should fail with an API key should refuse ingestAppMessages and leave state unchanged 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint is not available to this caller",+}+`;++exports[`Application-only endpoints with a non-application caller should fail with an API key should refuse reportAppConnectionAuthFailure and leave state unchanged 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint is not available to this caller",+}+`;++exports[`Application-only endpoints with a non-application caller should fail with an API key should refuse setAppKeyValue and leave state unchanged 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint is not available to this caller",+}+`;++exports[`Application-only endpoints with a non-application caller should fail with an API key should refuse updateAppMessageChannel and leave state unchanged 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint is not available to this caller",+}+`;++exports[`Application-only endpoints with a non-application caller should fail with an OAuth-only client token should refuse GET /app/billing/credits and leave state unchanged 1`] = `+{+ "body": {+ "error": "Forbidden",+ "message": "This endpoint is not available to this caller",+ "statusCode": 403,+ },+ "status": 403,+}+`;++exports[`Application-only endpoints with a non-application caller should fail with an OAuth-only client token should refuse POST /app/billing/charge and leave state unchanged 1`] = `+{+ "body": {+ "error": "Forbidden",+ "message": "This endpoint is not available to this caller",+ "statusCode": 403,+ },+ "status": 403,+}+`;++exports[`Application-only endpoints with a non-application caller should fail with an OAuth-only client token should refuse POST /apps/connections/get and leave state unchanged 1`] = `+{+ "body": {+ "error": "Forbidden",+ "message": "This endpoint is not available to this caller",+ "statusCode": 403,+ },+ "status": 403,+}+`;++exports[`Application-only endpoints with a non-application caller should fail with an OAuth-only client token should refuse POST /apps/connections/list and leave state unchanged 1`] = `+{+ "body": {+ "error": "Forbidden",+ "message": "This endpoint is not available to this caller",+ "statusCode": 403,+ },+ "status": 403,+}+`;++exports[`Application-only endpoints with a non-application caller should fail with an OAuth-only client token should refuse appConnection and leave state unchanged 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint is not available to this caller",+}+`;++exports[`Application-only endpoints with a non-application caller should fail with an OAuth-only client token should refuse appConnections and leave state unchanged 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint is not available to this caller",+}+`;++exports[`Application-only endpoints with a non-application caller should fail with an OAuth-only client token should refuse appKeyValue and leave state unchanged 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint is not available to this caller",+}+`;++exports[`Application-only endpoints with a non-application caller should fail with an OAuth-only client token should refuse appMessageChannels and leave state unchanged 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint is not available to this caller",+}+`;++exports[`Application-only endpoints with a non-application caller should fail with an OAuth-only client token should refuse createAppMessageChannel and leave state unchanged 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint is not available to this caller",+}+`;++exports[`Application-only endpoints with a non-application caller should fail with an OAuth-only client token should refuse deleteAppKeyValue and leave state unchanged 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint is not available to this caller",+}+`;++exports[`Application-only endpoints with a non-application caller should fail with an OAuth-only client token should refuse deleteAppMessageChannel and leave state unchanged 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint is not available to this caller",+}+`;++exports[`Application-only endpoints with a non-application caller should fail with an OAuth-only client token should refuse enqueueJob and leave state unchanged 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint is not available to this caller",+}+`;++exports[`Application-only endpoints with a non-application caller should fail with an OAuth-only client token should refuse enqueueJobs and leave state unchanged 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint is not available to this caller",+}+`;++exports[`Application-only endpoints with a non-application caller should fail with an OAuth-only client token should refuse getJobs and leave state unchanged 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint is not available to this caller",+}+`;++exports[`Application-only endpoints with a non-application caller should fail with an OAuth-only client token should refuse ingestAppMessages and leave state unchanged 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint is not available to this caller",+}+`;++exports[`Application-only endpoints with a non-application caller should fail with an OAuth-only client token should refuse reportAppConnectionAuthFailure and leave state unchanged 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint is not available to this caller",+}+`;++exports[`Application-only endpoints with a non-application caller should fail with an OAuth-only client token should refuse setAppKeyValue and leave state unchanged 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint is not available to this caller",+}+`;++exports[`Application-only endpoints with a non-application caller should fail with an OAuth-only client token should refuse updateAppMessageChannel and leave state unchanged 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint is not available to this caller",+}+`;diff --git a/packages/twenty-server/test/integration/metadata/suites/application/app-key-value.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/application/app-key-value.integration-spec.tsindex c0e2b531e56..8b5654db49a 100644--- a/packages/twenty-server/test/integration/metadata/suites/application/app-key-value.integration-spec.ts+++ b/packages/twenty-server/test/integration/metadata/suites/application/app-key-value.integration-spec.ts@@ -4,6 +4,7 @@ import { generateAppleAdminApplicationTokenPair } from 'test/integration/utils/gimport { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';import { v4 as uuidv4 } from 'uuid';+import { AUTH_PRINCIPAL_REFUSED_MESSAGE } from 'src/engine/guards/constants/auth-principal-refused-message.constant';import { TWENTY_STANDARD_APPLICATION } from 'src/engine/workspace-manager/twenty-standard-application/constants/twenty-standard-applications';import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';@@ -70,7 +71,10 @@ describe('application key-value store (e2e)', () => {});expect(response.body.errors).toBeDefined();- expect(response.body.errors[0].message).toContain('APPLICATION_ACCESS');+ expect(response.body.errors[0].extensions.code).toBe('FORBIDDEN');+ expect(response.body.errors[0].message).toBe(+ AUTH_PRINCIPAL_REFUSED_MESSAGE,+ );});it('sets, reads, overwrites and deletes a WORKSPACE entry', async () => {diff --git a/packages/twenty-server/test/integration/metadata/suites/application/enqueue-job.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/application/enqueue-job.integration-spec.tsindex 0a24fe03c6a..21129996fff 100644--- a/packages/twenty-server/test/integration/metadata/suites/application/enqueue-job.integration-spec.ts+++ b/packages/twenty-server/test/integration/metadata/suites/application/enqueue-job.integration-spec.ts@@ -24,6 +24,7 @@ import { isDefined } from 'twenty-shared/utils';import { v4 as uuidv4 } from 'uuid';import { WORKSPACE_CUSTOM_APPLICATION_NAME } from 'src/engine/core-modules/application/constants/workspace-custom-application.constant';+import { AUTH_PRINCIPAL_REFUSED_MESSAGE } from 'src/engine/guards/constants/auth-principal-refused-message.constant';import { TWENTY_STANDARD_APPLICATION } from 'src/engine/workspace-manager/twenty-standard-application/constants/twenty-standard-applications';const MARKER_DIRECTORY = join(tmpdir(), `enqueue-job-${uuidv4()}`);@@ -319,7 +320,10 @@ describe('enqueueJob (e2e)', () => {});expect(response.body.errors).toBeDefined();- expect(response.body.errors[0].message).toContain('APPLICATION_ACCESS');+ expect(response.body.errors[0].extensions.code).toBe('FORBIDDEN');+ expect(response.body.errors[0].message).toBe(+ AUTH_PRINCIPAL_REFUSED_MESSAGE,+ );});it('enqueues a logic function owned by the calling application and the worker runs it', async () => {diff --git a/packages/twenty-server/test/integration/metadata/suites/application/failing-application-only-endpoint-access.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/application/failing-application-only-endpoint-access.integration-spec.tsnew file mode 100644index 00000000000..ae1c1653191--- /dev/null+++ b/packages/twenty-server/test/integration/metadata/suites/application/failing-application-only-endpoint-access.integration-spec.ts@@ -0,0 +1,261 @@+import { expectOneNotInternalServerErrorSnapshot } from 'test/integration/graphql/utils/expect-one-not-internal-server-error-snapshot.util';+import {+ APPLICATION_ONLY_GRAPHQL_OPERATION_FACTORIES,+ APPLICATION_ONLY_REST_REQUEST_FACTORIES,+ type ApplicationOnlyEndpointTarget,+ makeApplicationOnlyRestRequest,+} from 'test/integration/metadata/suites/application/utils/application-only-endpoint-request-factories.util';+import { loginAsTwentyCli } from 'test/integration/metadata/suites/application/utils/login-as-twenty-cli.util';+import { uninstallApplication } from 'test/integration/metadata/suites/application/utils/uninstall-application.util';+import {+ type ApplicationWithAppConnection,+ cleanupApplicationWithAppConnection,+ setupApplicationWithAppConnection,+} from 'test/integration/metadata/suites/connection-provider/utils/setup-application-with-app-connection.util';+import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';+import { expectOneNotInternalServerErrorHttpResponseSnapshot } from 'test/integration/utils/expect-one-not-internal-server-error-http-response-snapshot.util';+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';+import {+ type EachTestingContext,+ eachTestingContextFilter,+} from 'twenty-shared/testing';+import { isDefined } from 'twenty-shared/utils';+import { v4 as uuidv4 } from 'uuid';++import { type AppBillingService } from 'src/engine/core-modules/billing/app-billing/app-billing.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 { TWENTY_CLI_APPLICATION_REGISTRATION } from 'src/engine/workspace-manager/twenty-standard-application/constants/twenty-cli-application-registration.constant';++type GlobalTestContext = {+ application: ApplicationWithAppConnection;+ target: ApplicationOnlyEndpointTarget;+ oauthClientToken: string;+ emitChargeEventSpy: jest.SpyInstance;+};++type CallerTestContext = {+ token: (globalContext: GlobalTestContext) => string;+};++type GraphqlOperationName =+ keyof typeof APPLICATION_ONLY_GRAPHQL_OPERATION_FACTORIES;++type RestRequestName = keyof typeof APPLICATION_ONLY_REST_REQUEST_FACTORIES;++type StateReader = (globalContext: GlobalTestContext) => Promise<unknown>;++const WORKSPACE_SCHEMA = getWorkspaceSchemaName(SEED_APPLE_WORKSPACE_ID);++const KEY_VALUE_KEY = `application-only-probe-${uuidv4()}`;++const callerTestCases: EachTestingContext<CallerTestContext>[] = [+ {+ title: 'with a member session',+ context: { token: () => APPLE_JONY_MEMBER_ACCESS_TOKEN },+ },+ {+ title: 'with an API key',+ context: { token: () => API_KEY_ACCESS_TOKEN },+ },+ {+ title: 'with an OAuth-only client token',+ context: { token: (globalContext) => globalContext.oauthClientToken },+ },+];++const readConnectionAuthFailure: StateReader = ({ application }) =>+ globalThis.testDataSource.query(+ `SELECT "authFailedAt", "authFailedReason" FROM core."connectedAccount"+ WHERE id = $1`,+ [application.connectedAccountId],+ );++const readKeyValuePairs: StateReader = ({ target }) =>+ globalThis.testDataSource.query(+ `SELECT "applicationId", value FROM core."keyValuePair"+ WHERE key = $1 ORDER BY "applicationId"`,+ [target.keyValueKey],+ );++const readJobs: StateReader = async ({ application, target }) => {+ const response = await makeMetadataApiRequest(+ APPLICATION_ONLY_GRAPHQL_OPERATION_FACTORIES.getJobs(target),+ application.applicationToken,+ );++ return response.body.data.getJobs;+};++const readMessageChannels: StateReader = ({ application }) =>+ globalThis.testDataSource.query(+ `SELECT id, "displayName", visibility, "isSyncEnabled"+ FROM core."messageChannel"+ WHERE "connectedAccountId" = $1 ORDER BY id`,+ [application.connectedAccountId],+ );++const readIngestedMessages: StateReader = ({ target }) =>+ globalThis.testDataSource.query(+ `SELECT "messageId"+ FROM "${WORKSPACE_SCHEMA}"."messageChannelMessageAssociation"+ WHERE "messageChannelId" = $1`,+ [target.messageChannelId],+ );++const readNothing: StateReader = async () => null;++const GRAPHQL_STATE_READERS: Partial<+ Record<GraphqlOperationName, StateReader>+> = {+ reportAppConnectionAuthFailure: readConnectionAuthFailure,+ setAppKeyValue: readKeyValuePairs,+ deleteAppKeyValue: readKeyValuePairs,+ enqueueJob: readJobs,+ enqueueJobs: readJobs,+ createAppMessageChannel: readMessageChannels,+ updateAppMessageChannel: readMessageChannels,+ deleteAppMessageChannel: readMessageChannels,+ ingestAppMessages: readIngestedMessages,+};++const REST_STATE_READERS: Partial<Record<RestRequestName, StateReader>> = {+ 'POST /app/billing/charge': async ({ emitChargeEventSpy }) =>+ emitChargeEventSpy.mock.calls.length,+};++const graphqlOperationNames = Object.keys(+ APPLICATION_ONLY_GRAPHQL_OPERATION_FACTORIES,+) as GraphqlOperationName[];++const restRequestNames = Object.keys(+ APPLICATION_ONLY_REST_REQUEST_FACTORIES,+) as RestRequestName[];++describe('Application-only endpoints with a non-application caller should fail', () => {+ let globalTestContext: GlobalTestContext;+ let applicationToCleanUp: ApplicationWithAppConnection | undefined;+ let isTwentyCliInstalled = false;++ beforeAll(async () => {+ const application = await setupApplicationWithAppConnection({+ name: 'Application Only Probe',+ });++ applicationToCleanUp = application;++ const setKeyValueResponse = await makeMetadataApiRequest(+ APPLICATION_ONLY_GRAPHQL_OPERATION_FACTORIES.setAppKeyValue({+ keyValueKey: KEY_VALUE_KEY,+ }),+ application.applicationToken,+ );++ expect(setKeyValueResponse.body.errors).toBeUndefined();++ const createMessageChannelResponse = await makeMetadataApiRequest(+ APPLICATION_ONLY_GRAPHQL_OPERATION_FACTORIES.createAppMessageChannel({+ connectedAccountId: application.connectedAccountId,+ }),+ application.applicationToken,+ );++ expect(createMessageChannelResponse.body.errors).toBeUndefined();++ const oauthClientToken = await loginAsTwentyCli();++ isTwentyCliInstalled = true;++ globalTestContext = {+ application,+ target: {+ connectedAccountId: application.connectedAccountId,+ messageChannelId:+ createMessageChannelResponse.body.data.createAppMessageChannel.id,+ keyValueKey: KEY_VALUE_KEY,+ logicFunctionUniversalIdentifier:+ application.logicFunctionUniversalIdentifier,+ singleJobId: `application-only-probe.${uuidv4()}`,+ batchJobId: `application-only-probe.${uuidv4()}`,+ },+ oauthClientToken,+ emitChargeEventSpy: jest.spyOn(+ getAppProviderByClassName<AppBillingService>('AppBillingService'),+ 'emitChargeEvent',+ ),+ };+ }, 120000);++ afterAll(async () => {+ if (isDefined(globalTestContext)) {+ globalTestContext.emitChargeEventSpy.mockRestore();+ }++ await globalThis.testDataSource.query(+ `DELETE FROM core."keyValuePair" WHERE key = $1`,+ [KEY_VALUE_KEY],+ );++ if (isDefined(applicationToCleanUp)) {+ await cleanupApplicationWithAppConnection(applicationToCleanUp);+ }++ if (isTwentyCliInstalled) {+ await uninstallApplication({+ universalIdentifier:+ TWENTY_CLI_APPLICATION_REGISTRATION.universalIdentifier,+ expectToFail: false,+ });+ }+ });++ describe.each(eachTestingContextFilter(callerTestCases))(+ '$title',+ ({ context }) => {+ it.each(graphqlOperationNames)(+ 'should refuse %s and leave state unchanged',+ async (operationName) => {+ const readState = GRAPHQL_STATE_READERS[operationName] ?? readNothing;+ const stateBeforeAttempt = await readState(globalTestContext);++ const response = await makeMetadataApiRequest(+ APPLICATION_ONLY_GRAPHQL_OPERATION_FACTORIES[operationName](+ globalTestContext.target,+ ),+ context.token(globalTestContext),+ );++ expect(await readState(globalTestContext)).toEqual(+ stateBeforeAttempt,+ );+ expectOneNotInternalServerErrorSnapshot({+ errors: response.body.errors,+ });+ },+ );++ it.each(restRequestNames)(+ 'should refuse %s and leave state unchanged',+ async (requestName) => {+ const readState = REST_STATE_READERS[requestName] ?? readNothing;+ const stateBeforeAttempt = await readState(globalTestContext);++ const response = await makeApplicationOnlyRestRequest(+ APPLICATION_ONLY_REST_REQUEST_FACTORIES[requestName](+ globalTestContext.target,+ ),+ context.token(globalTestContext),+ );++ expect(await readState(globalTestContext)).toEqual(+ stateBeforeAttempt,+ );+ expectOneNotInternalServerErrorHttpResponseSnapshot({+ status: response.status,+ body: response.body,+ });+ },+ );+ },+ );+});diff --git a/packages/twenty-server/test/integration/metadata/suites/application/successful-oauth-only-client-access.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/application/successful-oauth-only-client-access.integration-spec.tsindex 6608e36088c..9ddaf3f71b0 100644--- a/packages/twenty-server/test/integration/metadata/suites/application/successful-oauth-only-client-access.integration-spec.ts+++ b/packages/twenty-server/test/integration/metadata/suites/application/successful-oauth-only-client-access.integration-spec.ts@@ -1,6 +1,4 @@import crypto from 'crypto';-import gql from 'graphql-tag';-import request from 'supertest';import { getMcpToolCatalog } from 'test/integration/graphql/suites/application-role-intersection/utils/get-mcp-tool-catalog.util';import { findApplicationRegistrationByUniversalIdentifier } from 'test/integration/metadata/suites/application-registration/utils/find-application-registration-by-universal-identifier.util';import { buildBaseManifest } from 'test/integration/metadata/suites/application/utils/build-base-manifest.util';@@ -11,6 +9,7 @@ import { createAppTarballUpload } from 'test/integration/metadata/suites/applicaimport { createApplicationFileUploads } from 'test/integration/metadata/suites/application/utils/create-application-file-uploads.util';import { exportApplication } from 'test/integration/metadata/suites/application/utils/export-application.util';import { installApplication } from 'test/integration/metadata/suites/application/utils/install-application.util';+import { loginAsTwentyCli } from 'test/integration/metadata/suites/application/utils/login-as-twenty-cli.util';import { putApplicationFileUploadTarget } from 'test/integration/metadata/suites/application/utils/put-application-file-upload-target.util';import {type ApplicationWithResources,@@ -20,7 +19,6 @@ import { syncApplication } from 'test/integration/metadata/suites/application/utimport { uninstallApplication } from 'test/integration/metadata/suites/application/utils/uninstall-application.util';import { executeLogicFunction } from 'test/integration/metadata/suites/logic-function/utils/execute-logic-function.util';import { findManyLogicFunctions } from 'test/integration/metadata/suites/logic-function/utils/find-many-logic-functions.util';-import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';import { ToolCategory } from 'twenty-shared/ai';@@ -28,63 +26,6 @@ import { type LogicFunctionExecutorService } from 'src/engine/core-modules/logicimport { LogicFunctionExecutionStatus } from 'src/engine/metadata-modules/logic-function/dtos/logic-function-execution-result.dto';import { TWENTY_CLI_APPLICATION_REGISTRATION } from 'src/engine/workspace-manager/twenty-standard-application/constants/twenty-cli-application-registration.constant';-const CLI_CALLBACK_URL = 'http://127.0.0.1:53682/callback';--// Same browser flow as `twenty remote add`: authorize the CLI client with PKCE-// as the workspace admin, then exchange the code for the CLI access token.-const loginAsTwentyCli = async (): Promise<string> => {- const baseUrl = `http://localhost:${APP_PORT}`;-- const discovery = await request(baseUrl)- .get('/.well-known/oauth-authorization-server')- .expect(200);-- const clientId: string = discovery.body.cli_client_id;- const codeVerifier = crypto.randomBytes(32).toString('base64url');- const codeChallenge = crypto- .createHash('sha256')- .update(codeVerifier)- .digest('base64url');-- const authorizeResponse = await makeMetadataApiRequest({- query: gql`- mutation AuthorizeApp(- $clientId: String!- $codeChallenge: String- $redirectUrl: String!- ) {- authorizeApp(- clientId: $clientId- codeChallenge: $codeChallenge- redirectUrl: $redirectUrl- ) {- redirectUrl- }- }- `,- variables: { clientId, codeChallenge, redirectUrl: CLI_CALLBACK_URL },- });-- expect(authorizeResponse.body.errors).toBeUndefined();-- const code = new URL(- authorizeResponse.body.data.authorizeApp.redirectUrl,- ).searchParams.get('code');-- const tokenResponse = await request(baseUrl)- .post('/oauth/token')- .send({- grant_type: 'authorization_code',- code,- code_verifier: codeVerifier,- redirect_uri: CLI_CALLBACK_URL,- client_id: clientId,- })- .expect(200);-- return tokenResponse.body.access_token;-};-describe('OAuth-only client access to installed applications should succeed', () => {let installedApplication: ApplicationWithResources;let cliToken: string;diff --git a/packages/twenty-server/test/integration/metadata/suites/application/utils/application-only-endpoint-request-factories.util.ts b/packages/twenty-server/test/integration/metadata/suites/application/utils/application-only-endpoint-request-factories.util.tsnew file mode 100644index 00000000000..51eb17bd29f--- /dev/null+++ b/packages/twenty-server/test/integration/metadata/suites/application/utils/application-only-endpoint-request-factories.util.ts@@ -0,0 +1,271 @@+import gql from 'graphql-tag';+import request from 'supertest';+import {+ MessageChannelVisibility,+ MessageParticipantRole,+} from 'twenty-shared/types';++export type ApplicationOnlyEndpointTarget = {+ connectedAccountId: string;+ messageChannelId: string;+ keyValueKey: string;+ logicFunctionUniversalIdentifier: string;+ singleJobId: string;+ batchJobId: string;+};++export const APPLICATION_ONLY_GRAPHQL_OPERATION_FACTORIES = {+ appConnections: () => ({+ query: gql`+ query AppConnections {+ appConnections {+ id+ }+ }+ `,+ }),+ appConnection: ({+ connectedAccountId,+ }: Pick<ApplicationOnlyEndpointTarget, 'connectedAccountId'>) => ({+ query: gql`+ query AppConnection($id: ID!) {+ appConnection(id: $id) {+ id+ }+ }+ `,+ variables: { id: connectedAccountId },+ }),+ reportAppConnectionAuthFailure: ({+ connectedAccountId,+ }: Pick<ApplicationOnlyEndpointTarget, 'connectedAccountId'>) => ({+ query: gql`+ mutation ReportAppConnectionAuthFailure(+ $input: ReportAppConnectionAuthFailureInput!+ ) {+ reportAppConnectionAuthFailure(input: $input)+ }+ `,+ variables: {+ input: { id: connectedAccountId, reason: 'application-only-probe' },+ },+ }),+ appKeyValue: ({+ keyValueKey,+ }: Pick<ApplicationOnlyEndpointTarget, 'keyValueKey'>) => ({+ query: gql`+ query AppKeyValue($key: String!) {+ appKeyValue(key: $key) {+ key+ }+ }+ `,+ variables: { key: keyValueKey },+ }),+ setAppKeyValue: ({+ keyValueKey,+ }: Pick<ApplicationOnlyEndpointTarget, 'keyValueKey'>) => ({+ query: gql`+ mutation SetAppKeyValue($input: SetAppKeyValueInput!) {+ setAppKeyValue(input: $input) {+ key+ }+ }+ `,+ variables: {+ input: { key: keyValueKey, value: 'application-only-probe' },+ },+ }),+ deleteAppKeyValue: ({+ keyValueKey,+ }: Pick<ApplicationOnlyEndpointTarget, 'keyValueKey'>) => ({+ query: gql`+ mutation DeleteAppKeyValue($key: String!) {+ deleteAppKeyValue(key: $key)+ }+ `,+ variables: { key: keyValueKey },+ }),+ enqueueJob: ({+ logicFunctionUniversalIdentifier,+ singleJobId,+ }: Pick<+ ApplicationOnlyEndpointTarget,+ 'logicFunctionUniversalIdentifier' | 'singleJobId'+ >) => ({+ query: gql`+ mutation EnqueueJob($input: EnqueueJobInput!) {+ enqueueJob(input: $input) {+ jobId+ }+ }+ `,+ variables: {+ input: { logicFunctionUniversalIdentifier, jobId: singleJobId },+ },+ }),+ enqueueJobs: ({+ logicFunctionUniversalIdentifier,+ batchJobId,+ }: Pick<+ ApplicationOnlyEndpointTarget,+ 'logicFunctionUniversalIdentifier' | 'batchJobId'+ >) => ({+ query: gql`+ mutation EnqueueJobs($input: EnqueueJobsInput!) {+ enqueueJobs(input: $input) {+ jobIds+ }+ }+ `,+ variables: {+ input: {+ logicFunctionUniversalIdentifier,+ jobs: [{ jobId: batchJobId, payload: {} }],+ },+ },+ }),+ getJobs: ({+ singleJobId,+ batchJobId,+ }: Pick<ApplicationOnlyEndpointTarget, 'singleJobId' | 'batchJobId'>) => ({+ query: gql`+ query GetJobs($jobIds: [String!]!) {+ getJobs(jobIds: $jobIds) {+ jobId+ }+ }+ `,+ variables: { jobIds: [singleJobId, batchJobId] },+ }),+ appMessageChannels: () => ({+ query: gql`+ query AppMessageChannels {+ appMessageChannels {+ id+ }+ }+ `,+ }),+ createAppMessageChannel: ({+ connectedAccountId,+ }: Pick<ApplicationOnlyEndpointTarget, 'connectedAccountId'>) => ({+ query: gql`+ mutation CreateAppMessageChannel($input: CreateAppMessageChannelInput!) {+ createAppMessageChannel(input: $input) {+ id+ }+ }+ `,+ variables: {+ input: {+ connectedAccountId,+ handle: '[email protected]',+ visibility: MessageChannelVisibility.SHARE_EVERYTHING,+ },+ },+ }),+ updateAppMessageChannel: ({+ messageChannelId,+ }: Pick<ApplicationOnlyEndpointTarget, 'messageChannelId'>) => ({+ query: gql`+ mutation UpdateAppMessageChannel($input: UpdateAppMessageChannelInput!) {+ updateAppMessageChannel(input: $input) {+ id+ }+ }+ `,+ variables: {+ input: { id: messageChannelId, displayName: 'application-only-probe' },+ },+ }),+ deleteAppMessageChannel: ({+ messageChannelId,+ }: Pick<ApplicationOnlyEndpointTarget, 'messageChannelId'>) => ({+ query: gql`+ mutation DeleteAppMessageChannel($id: UUID!) {+ deleteAppMessageChannel(id: $id) {+ id+ }+ }+ `,+ variables: { id: messageChannelId },+ }),+ ingestAppMessages: ({+ messageChannelId,+ }: Pick<ApplicationOnlyEndpointTarget, 'messageChannelId'>) => ({+ query: gql`+ mutation IngestAppMessages($input: IngestAppMessagesInput!) {+ ingestAppMessages(input: $input) {+ messages {+ messageId+ }+ }+ }+ `,+ variables: {+ input: {+ messageChannelId,+ messages: [+ {+ externalId: 'application-only-probe',+ threadExternalId: 'application-only-probe',+ text: 'application-only-probe',+ receivedAt: '2026-01-01T10:00:00.000Z',+ participants: [+ {+ role: MessageParticipantRole.FROM,+ handle: '[email protected]',+ },+ ],+ },+ ],+ },+ },+ }),+};++type ApplicationOnlyRestRequest = {+ method: 'get' | 'post';+ path: string;+ body?: Record<string, unknown>;+};++export const APPLICATION_ONLY_REST_REQUEST_FACTORIES = {+ 'POST /apps/connections/list': (): ApplicationOnlyRestRequest => ({+ method: 'post',+ path: '/apps/connections/list',+ body: {},+ }),+ 'POST /apps/connections/get': ({+ connectedAccountId,+ }: Pick<+ ApplicationOnlyEndpointTarget,+ 'connectedAccountId'+ >): ApplicationOnlyRestRequest => ({+ method: 'post',+ path: '/apps/connections/get',+ body: { id: connectedAccountId },+ }),+ 'GET /app/billing/credits': (): ApplicationOnlyRestRequest => ({+ method: 'get',+ path: '/app/billing/credits',+ }),+ 'POST /app/billing/charge': (): ApplicationOnlyRestRequest => ({+ method: 'post',+ path: '/app/billing/charge',+ body: { creditsUsedMicro: 0, quantity: 1, operationType: 'AI_CHAT_TOKEN' },+ }),+};++export const makeApplicationOnlyRestRequest = (+ { method, path, body }: ApplicationOnlyRestRequest,+ token: string,+) => {+ const client = request(`http://localhost:${APP_PORT}`);+ const authorization = `Bearer ${token}`;++ return method === 'get'+ ? client.get(path).set('Authorization', authorization)+ : client.post(path).set('Authorization', authorization).send(body);+};diff --git a/packages/twenty-server/test/integration/metadata/suites/application/utils/login-as-twenty-cli.util.ts b/packages/twenty-server/test/integration/metadata/suites/application/utils/login-as-twenty-cli.util.tsnew file mode 100644index 00000000000..61cde6b17e4--- /dev/null+++ b/packages/twenty-server/test/integration/metadata/suites/application/utils/login-as-twenty-cli.util.ts@@ -0,0 +1,61 @@+import crypto from 'crypto';+import gql from 'graphql-tag';+import request from 'supertest';+import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';++const CLI_CALLBACK_URL = 'http://127.0.0.1:53682/callback';++// Same browser flow as `twenty remote add`: authorize the CLI client with PKCE+// as the workspace admin, then exchange the code for the CLI access token.+export const loginAsTwentyCli = async (): Promise<string> => {+ const baseUrl = `http://localhost:${APP_PORT}`;++ const discovery = await request(baseUrl)+ .get('/.well-known/oauth-authorization-server')+ .expect(200);++ const clientId: string = discovery.body.cli_client_id;+ const codeVerifier = crypto.randomBytes(32).toString('base64url');+ const codeChallenge = crypto+ .createHash('sha256')+ .update(codeVerifier)+ .digest('base64url');++ const authorizeResponse = await makeMetadataApiRequest({+ query: gql`+ mutation AuthorizeApp(+ $clientId: String!+ $codeChallenge: String+ $redirectUrl: String!+ ) {+ authorizeApp(+ clientId: $clientId+ codeChallenge: $codeChallenge+ redirectUrl: $redirectUrl+ ) {+ redirectUrl+ }+ }+ `,+ variables: { clientId, codeChallenge, redirectUrl: CLI_CALLBACK_URL },+ });++ expect(authorizeResponse.body.errors).toBeUndefined();++ const code = new URL(+ authorizeResponse.body.data.authorizeApp.redirectUrl,+ ).searchParams.get('code');++ const tokenResponse = await request(baseUrl)+ .post('/oauth/token')+ .send({+ grant_type: 'authorization_code',+ code,+ code_verifier: codeVerifier,+ redirect_uri: CLI_CALLBACK_URL,+ client_id: clientId,+ })+ .expect(200);++ return tokenResponse.body.access_token;+};diff --git a/packages/twenty-server/test/integration/metadata/suites/connection-provider/app-connections.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/connection-provider/app-connections.integration-spec.tsnew file mode 100644index 00000000000..59e4ff4084a--- /dev/null+++ b/packages/twenty-server/test/integration/metadata/suites/connection-provider/app-connections.integration-spec.ts@@ -0,0 +1,117 @@+import { gql } from 'graphql-tag';+import {+ APPLICATION_ONLY_REST_REQUEST_FACTORIES,+ makeApplicationOnlyRestRequest,+} from 'test/integration/metadata/suites/application/utils/application-only-endpoint-request-factories.util';+import {+ type ApplicationWithAppConnection,+ cleanupApplicationWithAppConnection,+ setupApplicationWithAppConnection,+} from 'test/integration/metadata/suites/connection-provider/utils/setup-application-with-app-connection.util';+import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';+import { isDefined } from 'twenty-shared/utils';++import { USER_WORKSPACE_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-user-workspaces.util';++const APP_CONNECTION_FIELDS = gql`+ fragment AppConnectionFields on AppConnection {+ id+ providerName+ handle+ visibility+ userWorkspaceId+ accessToken+ }+`;++const LIST_APP_CONNECTIONS_QUERY = gql`+ ${APP_CONNECTION_FIELDS}+ query AppConnections {+ appConnections {+ ...AppConnectionFields+ }+ }+`;++const GET_APP_CONNECTION_QUERY = gql`+ ${APP_CONNECTION_FIELDS}+ query AppConnection($id: ID!) {+ appConnection(id: $id) {+ ...AppConnectionFields+ }+ }+`;++describe('app connections API (e2e)', () => {+ let application: ApplicationWithAppConnection;++ const expectedConnection = () => ({+ id: application.connectedAccountId,+ providerName: application.connectionProviderName,+ handle: application.connectedAccountHandle,+ visibility: 'workspace',+ userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.JANE,+ accessToken: application.connectedAccountAccessToken,+ });++ beforeAll(async () => {+ application = await setupApplicationWithAppConnection({+ name: 'App Connections',+ });+ }, 120000);++ afterAll(async () => {+ if (isDefined(application)) {+ await cleanupApplicationWithAppConnection(application);+ }+ }, 120000);++ it('lists the connections of the calling application', async () => {+ const response = await makeMetadataApiRequest(+ { query: LIST_APP_CONNECTIONS_QUERY },+ application.applicationToken,+ );++ expect(response.body.errors).toBeUndefined();+ expect(response.body.data.appConnections).toEqual([expectedConnection()]);+ });++ it('returns one connection of the calling application', async () => {+ const response = await makeMetadataApiRequest(+ {+ query: GET_APP_CONNECTION_QUERY,+ variables: { id: application.connectedAccountId },+ },+ application.applicationToken,+ );++ expect(response.body.errors).toBeUndefined();+ expect(response.body.data.appConnection).toEqual(expectedConnection());+ });++ it('lists the connections of the calling application over the deprecated REST endpoint', async () => {+ const response = await makeApplicationOnlyRestRequest(+ APPLICATION_ONLY_REST_REQUEST_FACTORIES['POST /apps/connections/list'](),+ application.applicationToken,+ );++ expect(response.status).toBe(200);+ expect(response.body).toEqual([+ expect.objectContaining(expectedConnection()),+ ]);+ });++ it('returns one connection of the calling application over the deprecated REST endpoint', async () => {+ const response = await makeApplicationOnlyRestRequest(+ APPLICATION_ONLY_REST_REQUEST_FACTORIES['POST /apps/connections/get'](+ application,+ ),+ application.applicationToken,+ );++ expect(response.status).toBe(200);+ expect(response.body).toEqual(+ expect.objectContaining(expectedConnection()),+ );+ });+});diff --git a/packages/twenty-server/test/integration/metadata/suites/connection-provider/utils/setup-application-with-app-connection.util.ts b/packages/twenty-server/test/integration/metadata/suites/connection-provider/utils/setup-application-with-app-connection.util.tsnew file mode 100644index 00000000000..4723ab12e6e--- /dev/null+++ b/packages/twenty-server/test/integration/metadata/suites/connection-provider/utils/setup-application-with-app-connection.util.ts@@ -0,0 +1,159 @@+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 { generateAppleAdminApplicationTokenPair } from 'test/integration/utils/generate-apple-admin-application-token-pair.util';+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';+import { ConnectedAccountProvider } from 'twenty-shared/types';+import { v4 as uuidv4 } from 'uuid';++import { type PlaintextString } from 'src/engine/core-modules/secret-encryption/branded-strings/plaintext-string.type';+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';++export type ApplicationWithAppConnection = {+ applicationUniversalIdentifier: string;+ applicationId: string;+ applicationToken: string;+ connectionProviderName: string;+ connectedAccountId: string;+ connectedAccountHandle: string;+ connectedAccountAccessToken: string;+ logicFunctionUniversalIdentifier: string;+};++const CONNECTION_PROVIDER_NAME = 'slack';++export const setupApplicationWithAppConnection = async ({+ name,+}: {+ name: string;+}): Promise<ApplicationWithAppConnection> => {+ const applicationUniversalIdentifier = uuidv4();+ const roleUniversalIdentifier = uuidv4();+ const logicFunctionUniversalIdentifier = uuidv4();+ const sourcePath = `test-${name.toLowerCase().replace(/\s+/g, '-')}`;++ await setupApplicationForSync({+ applicationUniversalIdentifier,+ name,+ description: `App for testing ${name}`,+ sourcePath,+ });++ await syncApplication({+ manifest: buildBaseManifest({+ appId: applicationUniversalIdentifier,+ roleId: roleUniversalIdentifier,+ overrides: {+ roles: [+ {+ universalIdentifier: roleUniversalIdentifier,+ label: `Test Role ${sourcePath}`,+ description: 'A test role',+ },+ ],+ logicFunctions: [+ {+ universalIdentifier: logicFunctionUniversalIdentifier,+ name: `${sourcePath}-handler`,+ handlerName: 'handler',+ sourceHandlerPath: 'src/handler.ts',+ builtHandlerPath: 'dist/handler.mjs',+ builtHandlerChecksum: 'handler-checksum',+ },+ ],+ connectionProviders: [+ {+ universalIdentifier: uuidv4(),+ name: CONNECTION_PROVIDER_NAME,+ displayName: 'Slack',+ type: 'oauth',+ oauth: {+ authorizationEndpoint: 'https://slack.com/oauth/v2/authorize',+ tokenEndpoint: 'https://slack.com/api/oauth.v2.access',+ scopes: ['chat:write'],+ clientIdVariable: 'SLACK_CLIENT_ID',+ clientSecretVariable: 'SLACK_CLIENT_SECRET',+ },+ },+ ],+ },+ }),+ expectToFail: false,+ });++ jest.useRealTimers();++ const [connectionProvider] = await findConnectionProvidersByApplication(+ applicationUniversalIdentifier,+ );++ const connectedAccountId = uuidv4();+ const connectedAccountHandle = `${sourcePath}@slack.test`;+ const connectedAccountAccessToken = `xoxb-${uuidv4()}`;++ const encryptedAccessToken =+ getAppProviderByClassName<ConnectedAccountTokenEncryptionService>(+ 'ConnectedAccountTokenEncryptionService',+ ).encrypt({+ plaintext: connectedAccountAccessToken as PlaintextString,+ workspaceId: SEED_APPLE_WORKSPACE_ID,+ });++ // Without a refresh token, an APP connection's access token is served as is.+ await globalThis.testDataSource.query(+ `INSERT INTO core."connectedAccount"+ (id, handle, provider, visibility, "workspaceId", "userWorkspaceId",+ "applicationId", "connectionProviderId", "accessToken")+ VALUES ($1, $2, $3, 'workspace', $4, $5, $6, $7, $8)`,+ [+ connectedAccountId,+ connectedAccountHandle,+ ConnectedAccountProvider.APP,+ SEED_APPLE_WORKSPACE_ID,+ USER_WORKSPACE_DATA_SEED_IDS.JANE,+ connectionProvider.applicationId,+ connectionProvider.id,+ encryptedAccessToken,+ ],+ );++ const applicationTokenPair = await generateAppleAdminApplicationTokenPair({+ applicationId: connectionProvider.applicationId,+ });++ return {+ applicationUniversalIdentifier,+ applicationId: connectionProvider.applicationId,+ applicationToken: applicationTokenPair.applicationAccessToken.token,+ connectionProviderName: CONNECTION_PROVIDER_NAME,+ connectedAccountId,+ connectedAccountHandle,+ connectedAccountAccessToken,+ logicFunctionUniversalIdentifier,+ };+};++export const cleanupApplicationWithAppConnection = async ({+ applicationUniversalIdentifier,+ applicationId,+}: Pick<+ ApplicationWithAppConnection,+ 'applicationUniversalIdentifier' | 'applicationId'+>) => {+ await globalThis.testDataSource.query(+ `DELETE FROM core."messageChannel" WHERE "connectedAccountId" IN (+ SELECT id FROM core."connectedAccount" WHERE "applicationId" = $1)`,+ [applicationId],+ );+ await globalThis.testDataSource.query(+ `DELETE FROM core."connectedAccount" WHERE "applicationId" = $1`,+ [applicationId],+ );+ await cleanupApplicationAndAppRegistration({+ applicationUniversalIdentifier,+ });+};