Skip to content

The open alternative to Salesforce, designed for AI.

Return auth errors instead of 500 on auth-required route triggers (#27318)

Paul Rastoinf1c1bb52c859
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-trigger/triggers/route/exceptions/__tests__/route-trigger-rest-api-exception-filter.spec.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-trigger/triggers/route/exceptions/__tests__/route-trigger-rest-api-exception-filter.spec.ts
index ef6c3cad3d9..59d2a00afa5 100644
--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-trigger/triggers/route/exceptions/__tests__/route-trigger-rest-api-exception-filter.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-trigger/triggers/route/exceptions/__tests__/route-trigger-rest-api-exception-filter.spec.ts
@@ -2,6 +2,10 @@ import { type ArgumentsHost } from '@nestjs/common';
import { type Response } from 'express';
+import {
+ AuthException,
+ AuthExceptionCode,
+} from 'src/engine/core-modules/auth/auth.exception';
import { type HttpExceptionHandlerService } from 'src/engine/core-modules/exception-handler/http-exception-handler.service';
import { RouteTriggerRestApiExceptionFilter } from 'src/engine/core-modules/logic-function/logic-function-trigger/triggers/route/exceptions/route-trigger-rest-api-exception-filter';
import {
@@ -76,6 +80,28 @@ describe('RouteTriggerRestApiExceptionFilter', () => {
);
});
+ it('maps an invalid token to 401', () => {
+ const exception = new AuthException(
+ 'Invalid token',
+ AuthExceptionCode.UNAUTHENTICATED,
+ );
+
+ filter.catch(exception, host);
+
+ expect(handleError).toHaveBeenCalledWith(exception, response, 401);
+ });
+
+ it('maps a token refused for this workspace to 403', () => {
+ const exception = new AuthException(
+ 'User is not a member of the workspace',
+ AuthExceptionCode.FORBIDDEN_EXCEPTION,
+ );
+
+ filter.catch(exception, host);
+
+ expect(handleError).toHaveBeenCalledWith(exception, response, 403);
+ });
+
it('maps a disabled function to 403', () => {
const exception = new RouteTriggerException(
'disabled',
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-trigger/triggers/route/exceptions/route-trigger-rest-api-exception-filter.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-trigger/triggers/route/exceptions/route-trigger-rest-api-exception-filter.ts
index cc0e5bfb607..5c19d8da30d 100644
--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-trigger/triggers/route/exceptions/route-trigger-rest-api-exception-filter.ts
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-trigger/triggers/route/exceptions/route-trigger-rest-api-exception-filter.ts
@@ -6,6 +6,7 @@ import {
import type { Response } from 'express';
+import { AuthException } from 'src/engine/core-modules/auth/auth.exception';
import {
RouteTriggerException,
RouteTriggerExceptionCode,
@@ -13,16 +14,24 @@ import {
import type { CustomException } from 'src/utils/custom-exception';
import { HttpExceptionHandlerService } from 'src/engine/core-modules/exception-handler/http-exception-handler.service';
-@Catch(RouteTriggerException)
+@Catch(RouteTriggerException, AuthException)
export class RouteTriggerRestApiExceptionFilter implements ExceptionFilter {
constructor(
private readonly httpExceptionHandlerService: HttpExceptionHandlerService,
) {}
- catch(exception: RouteTriggerException, host: ArgumentsHost) {
+ catch(exception: RouteTriggerException | AuthException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
+ if (exception instanceof AuthException) {
+ return this.httpExceptionHandlerService.handleError(
+ exception,
+ response,
+ exception.statusCode ?? 500,
+ );
+ }
+
switch (exception.code) {
case RouteTriggerExceptionCode.WORKSPACE_NOT_FOUND:
case RouteTriggerExceptionCode.ROUTE_NOT_FOUND:
diff --git a/packages/twenty-server/test/integration/route-trigger/suites/route-trigger-authentication.integration-spec.ts b/packages/twenty-server/test/integration/route-trigger/suites/route-trigger-authentication.integration-spec.ts
new file mode 100644
index 00000000000..11263377f67
--- /dev/null
+++ b/packages/twenty-server/test/integration/route-trigger/suites/route-trigger-authentication.integration-spec.ts
@@ -0,0 +1,119 @@
+import { HTTPMethod } from 'twenty-shared/types';
+import request from 'supertest';
+import { findManyApplications } from 'test/integration/graphql/utils/find-many-applications.util';
+import { buildBaseManifest } from 'test/integration/metadata/suites/application/utils/build-base-manifest.util';
+import { cleanupApplicationAndAppRegistration } from 'test/integration/metadata/suites/application/utils/cleanup-application-and-app-registration.util';
+import { generateAppleAdminApplicationTokenPair } from 'test/integration/utils/generate-apple-admin-application-token-pair.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 { uploadApplicationFile } from 'test/integration/metadata/suites/application/utils/upload-application-file.util';
+import { type LogicFunctionManifest } from 'twenty-shared/application';
+
+const APP_UNIVERSAL_IDENTIFIER = '4e1b6a52-7c1f-4b0e-9a55-27255a1c0001';
+const ROLE_UNIVERSAL_IDENTIFIER = '4e1b6a52-7c1f-4b0e-9a55-27255a1c0002';
+const ROUTE_FUNCTION_UNIVERSAL_IDENTIFIER =
+ '4e1b6a52-7c1f-4b0e-9a55-27255a1c0003';
+
+const ROUTE_BUILT_HANDLER_CODE =
+ 'export const main = async () => ({ executed: true });\n';
+
+const authRequiredRouteManifest: LogicFunctionManifest = {
+ universalIdentifier: ROUTE_FUNCTION_UNIVERSAL_IDENTIFIER,
+ name: 'auth-required-route',
+ handlerName: 'main',
+ sourceHandlerPath: 'src/auth-required-route.ts',
+ builtHandlerPath: 'dist/auth-required-route.mjs',
+ builtHandlerChecksum: 'checksum-auth-required-route',
+ httpRouteTriggerSettings: {
+ path: '/auth-required-route',
+ httpMethod: HTTPMethod.GET,
+ isAuthRequired: true,
+ },
+};
+
+describe('RouteTrigger authentication (integration)', () => {
+ const baseUrl = `http://localhost:${APP_PORT}`;
+ const workspaceHost = `apple.localhost:${APP_PORT}`;
+ let applicationAccessToken: string;
+
+ beforeAll(async () => {
+ await setupApplicationForSync({
+ applicationUniversalIdentifier: APP_UNIVERSAL_IDENTIFIER,
+ name: 'Route Trigger Authentication Test App',
+ description: 'App for testing authentication on route triggers',
+ sourcePath: 'route-trigger-authentication-test-app',
+ });
+
+ jest.useRealTimers();
+ await uploadApplicationFile({
+ applicationUniversalIdentifier: APP_UNIVERSAL_IDENTIFIER,
+ fileFolder: 'BuiltLogicFunction',
+ filePath: 'dist/auth-required-route.mjs',
+ fileBuffer: Buffer.from(ROUTE_BUILT_HANDLER_CODE),
+ filename: 'auth-required-route.mjs',
+ contentType: 'application/javascript',
+ expectToFail: false,
+ });
+ jest.useFakeTimers();
+
+ await syncApplication({
+ manifest: buildBaseManifest({
+ appId: APP_UNIVERSAL_IDENTIFIER,
+ roleId: ROLE_UNIVERSAL_IDENTIFIER,
+ overrides: { logicFunctions: [authRequiredRouteManifest] },
+ }),
+ expectToFail: false,
+ });
+
+ const { data } = await findManyApplications({ expectToFail: false });
+ const application = data.findManyApplications.find(
+ ({ universalIdentifier }) =>
+ universalIdentifier === APP_UNIVERSAL_IDENTIFIER,
+ );
+
+ expect(application).toBeDefined();
+
+ const tokenPair = await generateAppleAdminApplicationTokenPair({
+ applicationId: application!.id,
+ });
+
+ applicationAccessToken = tokenPair.applicationAccessToken.token;
+
+ jest.useRealTimers();
+ }, 60000);
+
+ afterAll(async () => {
+ await cleanupApplicationAndAppRegistration({
+ applicationUniversalIdentifier: APP_UNIVERSAL_IDENTIFIER,
+ });
+ }, 60000);
+
+ it('serves an auth-required route when the token is valid', async () => {
+ const response = await request(baseUrl)
+ .get('/s/auth-required-route')
+ .set('Host', workspaceHost)
+ .set('Authorization', `Bearer ${applicationAccessToken}`);
+
+ expect(response.status).toBe(200);
+ expect(response.body).toEqual({ executed: true });
+ }, 60000);
+
+ it('rejects an auth-required route with 403 when no credentials are sent', async () => {
+ const response = await request(baseUrl)
+ .get('/s/auth-required-route')
+ .set('Host', workspaceHost);
+
+ expect(response.status).toBe(403);
+ expect(response.body.code).toBe('FORBIDDEN_EXCEPTION');
+ }, 60000);
+
+ it('rejects an auth-required route with 401 when the token is invalid', async () => {
+ const response = await request(baseUrl)
+ .get('/s/auth-required-route')
+ .set('Host', workspaceHost)
+ .set('Authorization', 'Bearer not-a-jwt');
+
+ expect(response.status).toBe(401);
+ expect(response.body.code).toBe('UNAUTHENTICATED');
+ }, 60000);
+});