Skip to content

The open alternative to Salesforce, designed for AI.

Restrict forwarded request headers on logic function route triggers (#26891)

Paul Rastoin811908a919c5
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-trigger/triggers/route/utils/__tests__/build-logic-function-event.util.spec.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-trigger/triggers/route/utils/__tests__/build-logic-function-event.util.spec.ts
index a03dfa2357b..a0f9617580d 100644
--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-trigger/triggers/route/utils/__tests__/build-logic-function-event.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-trigger/triggers/route/utils/__tests__/build-logic-function-event.util.spec.ts
@@ -13,11 +13,11 @@ describe('filterRequestHeaders', () => {
it('should filter headers based on allowed names', () => {
const requestHeaders = {
'content-type': 'application/json',
- authorization: 'Bearer token123',
'x-custom-header': 'custom-value',
+ 'x-other-header': 'other-value',
'user-agent': 'test-agent',
};
- const forwardedRequestHeaders = ['content-type', 'authorization'];
+ const forwardedRequestHeaders = ['content-type', 'x-custom-header'];
const result = filterRequestHeaders({
requestHeaders,
@@ -26,16 +26,16 @@ describe('filterRequestHeaders', () => {
expect(result).toEqual({
'content-type': 'application/json',
- authorization: 'Bearer token123',
+ 'x-custom-header': 'custom-value',
});
});
it('should handle case-insensitive header names', () => {
const requestHeaders = {
'content-type': 'application/json',
- authorization: 'Bearer token123',
+ 'x-custom-header': 'custom-value',
};
- const forwardedRequestHeaders = ['Content-Type', 'AUTHORIZATION'];
+ const forwardedRequestHeaders = ['Content-Type', 'X-CUSTOM-HEADER'];
const result = filterRequestHeaders({
requestHeaders,
@@ -44,7 +44,31 @@ describe('filterRequestHeaders', () => {
expect(result).toEqual({
'content-type': 'application/json',
+ 'x-custom-header': 'custom-value',
+ });
+ });
+
+ it('should never forward credential headers listed in forwardedRequestHeaders', () => {
+ const requestHeaders = {
authorization: 'Bearer token123',
+ cookie: 'session=abc',
+ 'proxy-authorization': 'Basic abc',
+ 'x-custom-header': 'custom-value',
+ };
+ const forwardedRequestHeaders = [
+ 'Authorization',
+ 'COOKIE',
+ 'proxy-authorization',
+ 'x-custom-header',
+ ];
+
+ const result = filterRequestHeaders({
+ requestHeaders,
+ forwardedRequestHeaders,
+ });
+
+ expect(result).toEqual({
+ 'x-custom-header': 'custom-value',
});
});
@@ -108,10 +132,12 @@ describe('filterRequestHeaders', () => {
});
});
- it('should forward every header when forwardAllHeaders is true', () => {
+ it('should forward every non-credential header when forwardAllHeaders is true', () => {
const requestHeaders = {
'content-type': 'application/json',
authorization: 'Bearer token123',
+ cookie: 'session=abc',
+ 'proxy-authorization': 'Basic abc',
'x-custom-header': 'custom-value',
'x-array-header': ['a', 'b'],
'x-missing': undefined,
@@ -125,7 +151,6 @@ describe('filterRequestHeaders', () => {
expect(result).toEqual({
'content-type': 'application/json',
- authorization: 'Bearer token123',
'x-custom-header': 'custom-value',
'x-array-header': 'a, b',
});
@@ -361,7 +386,6 @@ describe('buildLogicFunctionEvent', () => {
expect(result).toEqual({
headers: {
'content-type': 'application/json',
- authorization: 'Bearer token',
},
queryStringParameters: { page: '1' },
pathParameters: { id: '123' },
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-trigger/triggers/route/utils/build-logic-function-event.util.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-trigger/triggers/route/utils/build-logic-function-event.util.ts
index dd8b09378c7..15ab17f3bc7 100644
--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-trigger/triggers/route/utils/build-logic-function-event.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-trigger/triggers/route/utils/build-logic-function-event.util.ts
@@ -4,6 +4,8 @@ import { type LogicFunctionEvent } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
import { isObject, isString } from '@sniptt/guards';
+import { isCredentialRequestHeaderName } from 'src/engine/metadata-modules/logic-function/utils/is-credential-request-header-name.util';
+
const normalizeHeaderValue = (
headerValue: string | string[] | undefined,
): string | undefined =>
@@ -22,7 +24,10 @@ export const filterRequestHeaders = ({
const allHeaders: Record<string, string | undefined> = {};
for (const [headerName, headerValue] of Object.entries(requestHeaders)) {
- if (headerValue === undefined) {
+ if (
+ !isDefined(headerValue) ||
+ isCredentialRequestHeaderName(headerName)
+ ) {
continue;
}
@@ -32,16 +37,16 @@ export const filterRequestHeaders = ({
return allHeaders;
}
- const lowercaseForwardedHeaders = forwardedRequestHeaders.map((h) =>
- h.toLowerCase(),
- );
+ const lowercaseForwardedHeaders = forwardedRequestHeaders
+ .map((headerName) => headerName.toLowerCase())
+ .filter((headerName) => !isCredentialRequestHeaderName(headerName));
const filteredHeaders: Record<string, string | undefined> = {};
for (const headerName of lowercaseForwardedHeaders) {
const headerValue = requestHeaders[headerName];
- if (headerValue !== undefined) {
+ if (isDefined(headerValue)) {
filteredHeaders[headerName] = normalizeHeaderValue(headerValue);
}
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/logic-function/constants/credential-request-header-names.constant.ts b/packages/twenty-server/src/engine/metadata-modules/logic-function/constants/credential-request-header-names.constant.ts
new file mode 100644
index 00000000000..3ab1eaec67c
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/logic-function/constants/credential-request-header-names.constant.ts
@@ -0,0 +1,7 @@
+// App code gets a scoped token from the executor, so the caller's own
+// credentials must never reach it, whatever the manifest forwards.
+export const CREDENTIAL_REQUEST_HEADER_NAMES = new Set([
+ 'authorization',
+ 'cookie',
+ 'proxy-authorization',
+]);
diff --git a/packages/twenty-server/src/engine/metadata-modules/logic-function/utils/is-credential-request-header-name.util.ts b/packages/twenty-server/src/engine/metadata-modules/logic-function/utils/is-credential-request-header-name.util.ts
new file mode 100644
index 00000000000..68558d66b0c
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/logic-function/utils/is-credential-request-header-name.util.ts
@@ -0,0 +1,4 @@
+import { CREDENTIAL_REQUEST_HEADER_NAMES } from 'src/engine/metadata-modules/logic-function/constants/credential-request-header-names.constant';
+
+export const isCredentialRequestHeaderName = (headerName: string): boolean =>
+ CREDENTIAL_REQUEST_HEADER_NAMES.has(headerName.toLowerCase());
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/flat-logic-function-validator.service.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/flat-logic-function-validator.service.ts
index ccf573544e6..e518db0f60b 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/flat-logic-function-validator.service.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/flat-logic-function-validator.service.ts
@@ -15,6 +15,7 @@ import { type FailedFlatEntityValidation } from 'src/engine/workspace-manager/wo
import { getEmptyFlatEntityValidationError } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/builders/utils/get-flat-entity-validation-error.util';
import { type FlatEntityUpdateValidationArgs } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/types/universal-flat-entity-update-validation-args.type';
import { type UniversalFlatEntityValidationArgs } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/types/universal-flat-entity-validation-args.type';
+import { validateLogicFunctionForwardedRequestHeaders } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/utils/validate-logic-function-forwarded-request-headers.util';
@Injectable()
export class FlatLogicFunctionValidatorService {
@@ -93,6 +94,10 @@ export class FlatLogicFunctionValidatorService {
});
}
+ validationResult.errors.push(
+ ...validateLogicFunctionForwardedRequestHeaders(flatEntityUpdate),
+ );
+
const mergedPrebuiltState = {
executionMode:
flatEntityUpdate.executionMode ??
@@ -225,6 +230,12 @@ export class FlatLogicFunctionValidatorService {
});
}
+ validationResult.errors.push(
+ ...validateLogicFunctionForwardedRequestHeaders(
+ flatLogicFunctionToValidate,
+ ),
+ );
+
if (
flatLogicFunctionToValidate.executionMode ===
LogicFunctionExecutionMode.PREBUILT &&
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/utils/__tests__/validate-logic-function-forwarded-request-headers.util.spec.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/utils/__tests__/validate-logic-function-forwarded-request-headers.util.spec.ts
new file mode 100644
index 00000000000..6974b44c9fb
--- /dev/null
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/utils/__tests__/validate-logic-function-forwarded-request-headers.util.spec.ts
@@ -0,0 +1,130 @@
+import { LogicFunctionExceptionCode } from 'src/engine/metadata-modules/logic-function/logic-function.exception';
+import { validateLogicFunctionForwardedRequestHeaders } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/utils/validate-logic-function-forwarded-request-headers.util';
+
+const buildHttpRouteTriggerSettings = (forwardedRequestHeaders: unknown) => ({
+ path: '/route',
+ httpMethod: 'POST' as const,
+ isAuthRequired: false,
+ forwardedRequestHeaders: forwardedRequestHeaders as string[],
+});
+
+const buildServerRouteTriggerSettings = (forwardedRequestHeaders: unknown) => ({
+ forwardedRequestHeaders: forwardedRequestHeaders as string[],
+});
+
+describe('validateLogicFunctionForwardedRequestHeaders', () => {
+ it('should return no error when no route trigger is set', () => {
+ expect(validateLogicFunctionForwardedRequestHeaders({})).toEqual([]);
+ expect(
+ validateLogicFunctionForwardedRequestHeaders({
+ httpRouteTriggerSettings: null,
+ serverRouteTriggerSettings: null,
+ }),
+ ).toEqual([]);
+ });
+
+ it('should return no error when forwardedRequestHeaders is absent', () => {
+ expect(
+ validateLogicFunctionForwardedRequestHeaders({
+ httpRouteTriggerSettings: buildHttpRouteTriggerSettings(undefined),
+ serverRouteTriggerSettings: buildServerRouteTriggerSettings(null),
+ }),
+ ).toEqual([]);
+ });
+
+ it('should return no error for non-credential headers', () => {
+ expect(
+ validateLogicFunctionForwardedRequestHeaders({
+ httpRouteTriggerSettings: buildHttpRouteTriggerSettings([
+ 'x-hub-signature',
+ 'content-type',
+ ]),
+ serverRouteTriggerSettings: buildServerRouteTriggerSettings([
+ 'webhook-signature',
+ ]),
+ }),
+ ).toEqual([]);
+ });
+
+ it('should return an error when an http route forwards a credential header', () => {
+ const errors = validateLogicFunctionForwardedRequestHeaders({
+ httpRouteTriggerSettings: buildHttpRouteTriggerSettings([
+ 'x-custom-header',
+ 'authorization',
+ ]),
+ });
+
+ expect(errors).toHaveLength(1);
+ expect(errors[0].code).toBe(
+ LogicFunctionExceptionCode.INVALID_LOGIC_FUNCTION_INPUT,
+ );
+ expect(errors[0].message).toBe(
+ 'forwardedRequestHeaders cannot include credential headers: authorization',
+ );
+ });
+
+ it('should return an error when a server route forwards a credential header', () => {
+ const errors = validateLogicFunctionForwardedRequestHeaders({
+ serverRouteTriggerSettings: buildServerRouteTriggerSettings(['cookie']),
+ });
+
+ expect(errors).toHaveLength(1);
+ expect(errors[0].message).toBe(
+ 'forwardedRequestHeaders cannot include credential headers: cookie',
+ );
+ });
+
+ it('should match credential headers case-insensitively', () => {
+ const errors = validateLogicFunctionForwardedRequestHeaders({
+ httpRouteTriggerSettings: buildHttpRouteTriggerSettings([
+ 'Cookie',
+ 'PROXY-AUTHORIZATION',
+ ]),
+ });
+
+ expect(errors).toHaveLength(1);
+ expect(errors[0].message).toContain('Cookie, PROXY-AUTHORIZATION');
+ });
+
+ it.each([
+ ['a string', 'authorization'],
+ ['an object', { 0: 'authorization' }],
+ ['an array with a null entry', [null]],
+ ['an array with a nested array', [['authorization']]],
+ ['an array with a number', [42]],
+ ])(
+ 'should return an error without throwing when forwardedRequestHeaders is %s',
+ (_, forwardedRequestHeaders) => {
+ const validate = () =>
+ validateLogicFunctionForwardedRequestHeaders({
+ httpRouteTriggerSettings: buildHttpRouteTriggerSettings(
+ forwardedRequestHeaders,
+ ),
+ });
+
+ expect(validate).not.toThrow();
+
+ const errors = validate();
+
+ expect(errors).toHaveLength(1);
+ expect(errors[0].code).toBe(
+ LogicFunctionExceptionCode.INVALID_LOGIC_FUNCTION_INPUT,
+ );
+ expect(errors[0].message).toBe(
+ 'forwardedRequestHeaders must be an array of strings',
+ );
+ },
+ );
+
+ it('should validate the server route shape too', () => {
+ const errors = validateLogicFunctionForwardedRequestHeaders({
+ serverRouteTriggerSettings:
+ buildServerRouteTriggerSettings('authorization'),
+ });
+
+ expect(errors).toHaveLength(1);
+ expect(errors[0].message).toBe(
+ 'forwardedRequestHeaders must be an array of strings',
+ );
+ });
+});
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/utils/validate-logic-function-forwarded-request-headers.util.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/utils/validate-logic-function-forwarded-request-headers.util.ts
new file mode 100644
index 00000000000..4fbc92e1a66
--- /dev/null
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/utils/validate-logic-function-forwarded-request-headers.util.ts
@@ -0,0 +1,56 @@
+import { msg, t } from '@lingui/core/macro';
+import { isString } from '@sniptt/guards';
+import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';
+
+import { LogicFunctionExceptionCode } from 'src/engine/metadata-modules/logic-function/logic-function.exception';
+import { isCredentialRequestHeaderName } from 'src/engine/metadata-modules/logic-function/utils/is-credential-request-header-name.util';
+import { type UniversalFlatLogicFunction } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-logic-function.type';
+import { type FlatEntityValidationError } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/builders/types/failed-flat-entity-validation.type';
+
+type ValidateLogicFunctionForwardedRequestHeadersArgs = Partial<
+ Pick<
+ UniversalFlatLogicFunction,
+ 'httpRouteTriggerSettings' | 'serverRouteTriggerSettings'
+ >
+>;
+
+const isArrayOfStrings = (value: unknown): value is string[] =>
+ Array.isArray(value) && value.every(isString);
+
+export const validateLogicFunctionForwardedRequestHeaders = ({
+ httpRouteTriggerSettings,
+ serverRouteTriggerSettings,
+}: ValidateLogicFunctionForwardedRequestHeadersArgs): FlatEntityValidationError<LogicFunctionExceptionCode>[] => {
+ const forwardedRequestHeaderLists: unknown[] = [
+ httpRouteTriggerSettings?.forwardedRequestHeaders,
+ serverRouteTriggerSettings?.forwardedRequestHeaders,
+ ].filter(isDefined);
+
+ if (!forwardedRequestHeaderLists.every(isArrayOfStrings)) {
+ return [
+ {
+ code: LogicFunctionExceptionCode.INVALID_LOGIC_FUNCTION_INPUT,
+ message: t`forwardedRequestHeaders must be an array of strings`,
+ userFriendlyMessage: msg`Forwarded request headers must be a list of header names`,
+ },
+ ];
+ }
+
+ const forwardedCredentialHeaderNames = forwardedRequestHeaderLists
+ .flat()
+ .filter(isCredentialRequestHeaderName);
+
+ if (!isNonEmptyArray(forwardedCredentialHeaderNames)) {
+ return [];
+ }
+
+ const headerNames = forwardedCredentialHeaderNames.join(', ');
+
+ return [
+ {
+ code: LogicFunctionExceptionCode.INVALID_LOGIC_FUNCTION_INPUT,
+ message: t`forwardedRequestHeaders cannot include credential headers: ${headerNames}`,
+ userFriendlyMessage: msg`Route triggers cannot forward credential headers`,
+ },
+ ];
+};
diff --git a/packages/twenty-server/test/integration/metadata/suites/logic-function/__snapshots__/failing-logic-function-forwarded-credential-headers.integration-spec.ts.snap b/packages/twenty-server/test/integration/metadata/suites/logic-function/__snapshots__/failing-logic-function-forwarded-credential-headers.integration-spec.ts.snap
new file mode 100644
index 00000000000..76fa4792547
--- /dev/null
+++ b/packages/twenty-server/test/integration/metadata/suites/logic-function/__snapshots__/failing-logic-function-forwarded-credential-headers.integration-spec.ts.snap
@@ -0,0 +1,246 @@
+// Jest Snapshot v1, https://goo.gl/fbAQLP
+
+exports[`Logic function sync should fail when a route trigger forwards credential headers when a created http route forwards headers as a string 1`] = `
+{
+ "extensions": {
+ "code": "METADATA_VALIDATION_FAILED",
+ "errors": {
+ "logicFunction": [
+ {
+ "errors": [
+ {
+ "code": "INVALID_LOGIC_FUNCTION_INPUT",
+ "message": "forwardedRequestHeaders must be an array of strings",
+ "userFriendlyMessage": "Forwarded request headers must be a list of header names",
+ },
+ ],
+ "flatEntityMinimalInformation": {
+ "universalIdentifier": Any<String>,
+ },
+ "metadataName": "logicFunction",
+ "status": "fail",
+ "type": "create",
+ },
+ ],
+ },
+ "message": "Validation failed for 1 logicFunction",
+ "summary": {
+ "logicFunction": 1,
+ "totalErrors": 1,
+ },
+ "userFriendlyMessage": "Forwarded request headers must be a list of header names",
+ },
+ "message": "Validation errors occurred while syncing application manifest metadata",
+ "name": "GraphQLError",
+}
+`;
+
+exports[`Logic function sync should fail when a route trigger forwards credential headers when a created http route forwards headers as an object 1`] = `
+{
+ "extensions": {
+ "code": "METADATA_VALIDATION_FAILED",
+ "errors": {
+ "logicFunction": [
+ {
+ "errors": [
+ {
+ "code": "INVALID_LOGIC_FUNCTION_INPUT",
+ "message": "forwardedRequestHeaders must be an array of strings",
+ "userFriendlyMessage": "Forwarded request headers must be a list of header names",
+ },
+ ],
+ "flatEntityMinimalInformation": {
+ "universalIdentifier": Any<String>,
+ },
+ "metadataName": "logicFunction",
+ "status": "fail",
+ "type": "create",
+ },
+ ],
+ },
+ "message": "Validation failed for 1 logicFunction",
+ "summary": {
+ "logicFunction": 1,
+ "totalErrors": 1,
+ },
+ "userFriendlyMessage": "Forwarded request headers must be a list of header names",
+ },
+ "message": "Validation errors occurred while syncing application manifest metadata",
+ "name": "GraphQLError",
+}
+`;
+
+exports[`Logic function sync should fail when a route trigger forwards credential headers when a created http route forwards the authorization header 1`] = `
+{
+ "extensions": {
+ "code": "METADATA_VALIDATION_FAILED",
+ "errors": {
+ "logicFunction": [
+ {
+ "errors": [
+ {
+ "code": "INVALID_LOGIC_FUNCTION_INPUT",
+ "message": "forwardedRequestHeaders cannot include credential headers: authorization",
+ "userFriendlyMessage": "Route triggers cannot forward credential headers",
+ },
+ ],
+ "flatEntityMinimalInformation": {
+ "universalIdentifier": Any<String>,
+ },
+ "metadataName": "logicFunction",
+ "status": "fail",
+ "type": "create",
+ },
+ ],
+ },
+ "message": "Validation failed for 1 logicFunction",
+ "summary": {
+ "logicFunction": 1,
+ "totalErrors": 1,
+ },
+ "userFriendlyMessage": "Route triggers cannot forward credential headers",
+ },
+ "message": "Validation errors occurred while syncing application manifest metadata",
+ "name": "GraphQLError",
+}
+`;
+
+exports[`Logic function sync should fail when a route trigger forwards credential headers when a created http route forwards the cookie header with a different case 1`] = `
+{
+ "extensions": {
+ "code": "METADATA_VALIDATION_FAILED",
+ "errors": {
+ "logicFunction": [
+ {
+ "errors": [
+ {
+ "code": "INVALID_LOGIC_FUNCTION_INPUT",
+ "message": "forwardedRequestHeaders cannot include credential headers: Cookie",
+ "userFriendlyMessage": "Route triggers cannot forward credential headers",
+ },
+ ],
+ "flatEntityMinimalInformation": {
+ "universalIdentifier": Any<String>,
+ },
+ "metadataName": "logicFunction",
+ "status": "fail",
+ "type": "create",
+ },
+ ],
+ },
+ "message": "Validation failed for 1 logicFunction",
+ "summary": {
+ "logicFunction": 1,
+ "totalErrors": 1,
+ },
+ "userFriendlyMessage": "Route triggers cannot forward credential headers",
+ },
+ "message": "Validation errors occurred while syncing application manifest metadata",
+ "name": "GraphQLError",
+}
+`;
+
+exports[`Logic function sync should fail when a route trigger forwards credential headers when a created server route forwards the proxy-authorization header 1`] = `
+{
+ "extensions": {
+ "code": "METADATA_VALIDATION_FAILED",
+ "errors": {
+ "logicFunction": [
+ {
+ "errors": [
+ {
+ "code": "INVALID_LOGIC_FUNCTION_INPUT",
+ "message": "forwardedRequestHeaders cannot include credential headers: proxy-authorization",
+ "userFriendlyMessage": "Route triggers cannot forward credential headers",
+ },
+ ],
+ "flatEntityMinimalInformation": {
+ "universalIdentifier": Any<String>,
+ },
+ "metadataName": "logicFunction",
+ "status": "fail",
+ "type": "create",
+ },
+ ],
+ },
+ "message": "Validation failed for 1 logicFunction",
+ "summary": {
+ "logicFunction": 1,
+ "totalErrors": 1,
+ },
+ "userFriendlyMessage": "Route triggers cannot forward credential headers",
+ },
+ "message": "Validation errors occurred while syncing application manifest metadata",
+ "name": "GraphQLError",
+}
+`;
+
+exports[`Logic function sync should fail when a route trigger forwards credential headers when an existing http route is updated to forward the authorization header 1`] = `
+{
+ "extensions": {
+ "code": "METADATA_VALIDATION_FAILED",
+ "errors": {
+ "logicFunction": [
+ {
+ "errors": [
+ {
+ "code": "INVALID_LOGIC_FUNCTION_INPUT",
+ "message": "forwardedRequestHeaders cannot include credential headers: authorization",
+ "userFriendlyMessage": "Route triggers cannot forward credential headers",
+ },
+ ],
+ "flatEntityMinimalInformation": {
+ "universalIdentifier": Any<String>,
+ },
+ "metadataName": "logicFunction",
+ "status": "fail",
+ "type": "update",
+ },
+ ],
+ },
+ "message": "Validation failed for 1 logicFunction",
+ "summary": {
+ "logicFunction": 1,
+ "totalErrors": 1,
+ },
+ "userFriendlyMessage": "Route triggers cannot forward credential headers",
+ },
+ "message": "Validation errors occurred while syncing application manifest metadata",
+ "name": "GraphQLError",
+}
+`;
+
+exports[`Logic function sync should fail when a route trigger forwards credential headers when an existing server route is updated with a null header 1`] = `
+{
+ "extensions": {
+ "code": "METADATA_VALIDATION_FAILED",
+ "errors": {
+ "logicFunction": [
+ {
+ "errors": [
+ {
+ "code": "INVALID_LOGIC_FUNCTION_INPUT",
+ "message": "forwardedRequestHeaders must be an array of strings",
+ "userFriendlyMessage": "Forwarded request headers must be a list of header names",
+ },
+ ],
+ "flatEntityMinimalInformation": {
+ "universalIdentifier": Any<String>,
+ },
+ "metadataName": "logicFunction",
+ "status": "fail",
+ "type": "update",
+ },
+ ],
+ },
+ "message": "Validation failed for 1 logicFunction",
+ "summary": {
+ "logicFunction": 1,
+ "totalErrors": 1,
+ },
+ "userFriendlyMessage": "Forwarded request headers must be a list of header names",
+ },
+ "message": "Validation errors occurred while syncing application manifest metadata",
+ "name": "GraphQLError",
+}
+`;
diff --git a/packages/twenty-server/test/integration/metadata/suites/logic-function/failing-logic-function-forwarded-credential-headers.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/logic-function/failing-logic-function-forwarded-credential-headers.integration-spec.ts
new file mode 100644
index 00000000000..b79333cdba8
--- /dev/null
+++ b/packages/twenty-server/test/integration/metadata/suites/logic-function/failing-logic-function-forwarded-credential-headers.integration-spec.ts
@@ -0,0 +1,211 @@
+import { expectOneNotInternalServerErrorSnapshot } from 'test/integration/graphql/utils/expect-one-not-internal-server-error-snapshot.util';
+import { buildBaseManifest } from 'test/integration/metadata/suites/application/utils/build-base-manifest.util';
+import { cleanupApplicationAndAppRegistration } from 'test/integration/metadata/suites/application/utils/cleanup-application-and-app-registration.util';
+import { setupApplicationForSync } from 'test/integration/metadata/suites/application/utils/setup-application-for-sync.util';
+import { syncApplication } from 'test/integration/metadata/suites/application/utils/sync-application.util';
+import { uploadApplicationFile } from 'test/integration/metadata/suites/application/utils/upload-application-file.util';
+import {
+ type LogicFunctionManifest,
+ type Manifest,
+} from 'twenty-shared/application';
+import {
+ type EachTestingContext,
+ eachTestingContextFilter,
+} from 'twenty-shared/testing';
+import { v4 as uuidv4 } from 'uuid';
+
+const TEST_APP_ID = uuidv4();
+const TEST_ROLE_ID = uuidv4();
+const EXISTING_LOGIC_FUNCTION_ID = uuidv4();
+
+const VALID_BUILT_PATH = 'src/logic-functions/handler.mjs';
+
+const buildLogicFunction = (
+ overrides: Partial<LogicFunctionManifest> = {},
+): LogicFunctionManifest => ({
+ universalIdentifier: uuidv4(),
+ name: 'TestLogicFunction',
+ description: 'A test logic function',
+ sourceHandlerPath: 'src/logic-functions/handler.ts',
+ builtHandlerPath: VALID_BUILT_PATH,
+ builtHandlerChecksum: 'valid-checksum',
+ handlerName: 'handler',
+ ...overrides,
+});
+
+const buildHttpRouteTriggerSettings = (forwardedRequestHeaders: string[]) => ({
+ path: '/forwarded-headers',
+ httpMethod: 'POST' as const,
+ isAuthRequired: false,
+ forwardedRequestHeaders,
+});
+
+const buildExistingLogicFunction = (forwardedRequestHeaders: string[]) =>
+ buildLogicFunction({
+ universalIdentifier: EXISTING_LOGIC_FUNCTION_ID,
+ httpRouteTriggerSettings: buildHttpRouteTriggerSettings(
+ forwardedRequestHeaders,
+ ),
+ });
+
+const buildManifest = (logicFunctions: LogicFunctionManifest[]): Manifest =>
+ buildBaseManifest({
+ appId: TEST_APP_ID,
+ roleId: TEST_ROLE_ID,
+ overrides: { logicFunctions },
+ });
+
+type TestContext = {
+ manifest: Manifest;
+};
+
+const FAILING_FORWARDED_CREDENTIAL_HEADERS_TEST_CASES: EachTestingContext<TestContext>[] =
+ [
+ {
+ title: 'when a created http route forwards the authorization header',
+ context: {
+ manifest: buildManifest([
+ buildExistingLogicFunction(['x-custom-header']),
+ buildLogicFunction({
+ httpRouteTriggerSettings: buildHttpRouteTriggerSettings([
+ 'authorization',
+ ]),
+ }),
+ ]),
+ },
+ },
+ {
+ title:
+ 'when a created http route forwards the cookie header with a different case',
+ context: {
+ manifest: buildManifest([
+ buildExistingLogicFunction(['x-custom-header']),
+ buildLogicFunction({
+ httpRouteTriggerSettings: buildHttpRouteTriggerSettings([
+ 'x-custom-header',
+ 'Cookie',
+ ]),
+ }),
+ ]),
+ },
+ },
+ {
+ title:
+ 'when a created server route forwards the proxy-authorization header',
+ context: {
+ manifest: buildManifest([
+ buildExistingLogicFunction(['x-custom-header']),
+ buildLogicFunction({
+ serverRouteTriggerSettings: {
+ forwardedRequestHeaders: ['proxy-authorization'],
+ },
+ }),
+ ]),
+ },
+ },
+ {
+ title:
+ 'when an existing http route is updated to forward the authorization header',
+ context: {
+ manifest: buildManifest([
+ buildExistingLogicFunction(['x-custom-header', 'authorization']),
+ ]),
+ },
+ },
+ {
+ title: 'when a created http route forwards headers as a string',
+ context: {
+ manifest: buildManifest([
+ buildExistingLogicFunction(['x-custom-header']),
+ buildLogicFunction({
+ httpRouteTriggerSettings: buildHttpRouteTriggerSettings(
+ 'authorization' as unknown as string[],
+ ),
+ }),
+ ]),
+ },
+ },
+ {
+ title: 'when a created http route forwards headers as an object',
+ context: {
+ manifest: buildManifest([
+ buildExistingLogicFunction(['x-custom-header']),
+ buildLogicFunction({
+ httpRouteTriggerSettings: buildHttpRouteTriggerSettings({
+ 0: 'authorization',
+ } as unknown as string[]),
+ }),
+ ]),
+ },
+ },
+ {
+ title: 'when an existing server route is updated with a null header',
+ context: {
+ manifest: buildManifest([
+ buildLogicFunction({
+ universalIdentifier: EXISTING_LOGIC_FUNCTION_ID,
+ httpRouteTriggerSettings: buildHttpRouteTriggerSettings([
+ 'x-custom-header',
+ ]),
+ serverRouteTriggerSettings: {
+ forwardedRequestHeaders: [null] as unknown as string[],
+ },
+ }),
+ ]),
+ },
+ },
+ ];
+
+describe('Logic function sync should fail when a route trigger forwards credential headers', () => {
+ beforeAll(async () => {
+ await setupApplicationForSync({
+ applicationUniversalIdentifier: TEST_APP_ID,
+ name: 'Test Forwarded Credential Headers Logic App',
+ description:
+ 'App for testing forwarded request header validation on logic functions',
+ sourcePath: 'test-forwarded-credential-headers-logic',
+ });
+
+ jest.useRealTimers();
+
+ await uploadApplicationFile({
+ applicationUniversalIdentifier: TEST_APP_ID,
+ fileFolder: 'BuiltLogicFunction',
+ filePath: VALID_BUILT_PATH,
+ fileBuffer: Buffer.from('dummy built handler content'),
+ filename: 'handler.mjs',
+ contentType: 'application/javascript',
+ expectToFail: false,
+ });
+
+ jest.useFakeTimers();
+
+ await syncApplication({
+ manifest: buildManifest([
+ buildExistingLogicFunction(['x-custom-header']),
+ ]),
+ expectToFail: false,
+ });
+ }, 60000);
+
+ afterAll(async () => {
+ await cleanupApplicationAndAppRegistration({
+ applicationUniversalIdentifier: TEST_APP_ID,
+ });
+ });
+
+ it.each(
+ eachTestingContextFilter(FAILING_FORWARDED_CREDENTIAL_HEADERS_TEST_CASES),
+ )(
+ '$title',
+ async ({ context }) => {
+ const { errors } = await syncApplication({
+ manifest: context.manifest,
+ expectToFail: true,
+ });
+
+ expectOneNotInternalServerErrorSnapshot({ errors });
+ },
+ 60000,
+ );
+});
diff --git a/packages/twenty-server/test/integration/route-trigger/suites/route-trigger-forwarded-headers.integration-spec.ts b/packages/twenty-server/test/integration/route-trigger/suites/route-trigger-forwarded-headers.integration-spec.ts
new file mode 100644
index 00000000000..1435e4ee4bc
--- /dev/null
+++ b/packages/twenty-server/test/integration/route-trigger/suites/route-trigger-forwarded-headers.integration-spec.ts
@@ -0,0 +1,152 @@
+import request from 'supertest';
+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 { uploadApplicationFile } from 'test/integration/metadata/suites/application/utils/upload-application-file.util';
+import { type LogicFunctionManifest } from 'twenty-shared/application';
+
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+
+const APP_UNIVERSAL_IDENTIFIER = '2a6d62ef-1192-49a7-a256-f1c2368fed90';
+const ROLE_UNIVERSAL_IDENTIFIER = '31f59169-74ca-493f-b25f-0b6285fb4f07';
+const ROUTE_FUNCTION_UNIVERSAL_IDENTIFIER =
+ 'd898f20d-c214-4b30-aed0-f09ebc8d34d7';
+
+const APPLICATION_PUBLIC_DOMAIN = 'forwarded-headers-app.example.com';
+
+const CUSTOM_HEADER_NAME = 'x-custom-header';
+const CUSTOM_HEADER_VALUE = 'custom-value';
+const SESSION_COOKIE = 'twenty_session=raw-session-token';
+
+const ECHO_HEADERS_BUILT_HANDLER_CODE = `export const main = async (event) => event.headers;
+`;
+
+const echoHeadersRouteTriggerSettings = {
+ path: '/echo-headers-route',
+ httpMethod: 'GET' as const,
+ isAuthRequired: true,
+ forwardedRequestHeaders: [CUSTOM_HEADER_NAME],
+};
+
+const echoHeadersRouteFunctionManifest: LogicFunctionManifest = {
+ universalIdentifier: ROUTE_FUNCTION_UNIVERSAL_IDENTIFIER,
+ name: 'echo-headers-route',
+ handlerName: 'main',
+ sourceHandlerPath: 'src/echo-headers-route.ts',
+ builtHandlerPath: 'dist/echo-headers-route.mjs',
+ builtHandlerChecksum: 'checksum-echo-headers-route',
+ httpRouteTriggerSettings: echoHeadersRouteTriggerSettings,
+};
+
+describe('RouteTrigger forwarded request headers (integration)', () => {
+ const baseUrl = `http://localhost:${APP_PORT}`;
+ const bareHost = `localhost:${APP_PORT}`;
+ const applicationPublicDomainHost = `${APPLICATION_PUBLIC_DOMAIN}:${APP_PORT}`;
+
+ beforeAll(async () => {
+ await setupApplicationForSync({
+ applicationUniversalIdentifier: APP_UNIVERSAL_IDENTIFIER,
+ name: 'Route Trigger Forwarded Headers Test App',
+ description: 'App for testing which request headers reach app code',
+ sourcePath: 'route-trigger-forwarded-headers-test-app',
+ });
+
+ jest.useRealTimers();
+ await uploadApplicationFile({
+ applicationUniversalIdentifier: APP_UNIVERSAL_IDENTIFIER,
+ fileFolder: 'BuiltLogicFunction',
+ filePath: 'dist/echo-headers-route.mjs',
+ fileBuffer: Buffer.from(ECHO_HEADERS_BUILT_HANDLER_CODE),
+ filename: 'echo-headers-route.mjs',
+ contentType: 'application/javascript',
+ expectToFail: false,
+ });
+ jest.useFakeTimers();
+
+ await syncApplication({
+ manifest: buildBaseManifest({
+ appId: APP_UNIVERSAL_IDENTIFIER,
+ roleId: ROLE_UNIVERSAL_IDENTIFIER,
+ overrides: { logicFunctions: [echoHeadersRouteFunctionManifest] },
+ }),
+ expectToFail: false,
+ });
+
+ // Sync now rejects credential headers, so this stands in for a route
+ // stored before that validation existed.
+ await globalThis.testDataSource.query(
+ `UPDATE core."logicFunction" SET "httpRouteTriggerSettings" = $1
+ WHERE "universalIdentifier" = $2 AND "workspaceId" = $3`,
+ [
+ JSON.stringify({
+ ...echoHeadersRouteTriggerSettings,
+ forwardedRequestHeaders: [
+ 'authorization',
+ 'cookie',
+ CUSTOM_HEADER_NAME,
+ ],
+ }),
+ ROUTE_FUNCTION_UNIVERSAL_IDENTIFIER,
+ SEED_APPLE_WORKSPACE_ID,
+ ],
+ );
+
+ const [{ id: applicationId }] = await globalThis.testDataSource.query(
+ `SELECT id FROM core."application"
+ WHERE "universalIdentifier" = $1 AND "workspaceId" = $2`,
+ [APP_UNIVERSAL_IDENTIFIER, SEED_APPLE_WORKSPACE_ID],
+ );
+
+ await globalThis.testDataSource.query(
+ `INSERT INTO core."publicDomain"
+ (domain, "isValidated", "applicationId", "workspaceId")
+ VALUES ($1, true, $2, $3)`,
+ [APPLICATION_PUBLIC_DOMAIN, applicationId, SEED_APPLE_WORKSPACE_ID],
+ );
+
+ jest.useRealTimers();
+ }, 60000);
+
+ afterAll(async () => {
+ await globalThis.testDataSource.query(
+ `DELETE FROM core."publicDomain" WHERE domain = $1`,
+ [APPLICATION_PUBLIC_DOMAIN],
+ );
+
+ await cleanupApplicationAndAppRegistration({
+ applicationUniversalIdentifier: APP_UNIVERSAL_IDENTIFIER,
+ });
+ }, 60000);
+
+ it('does not deliver the caller credentials to app code when the manifest forwards them', async () => {
+ const response = await request(baseUrl)
+ .get('/s/echo-headers-route')
+ .set('Host', bareHost)
+ .set('Authorization', `Bearer ${APPLE_JANE_ADMIN_ACCESS_TOKEN}`)
+ .set('Cookie', SESSION_COOKIE)
+ .set(CUSTOM_HEADER_NAME, CUSTOM_HEADER_VALUE);
+
+ expect(response.status).toBe(200);
+ expect(response.body).toEqual({
+ [CUSTOM_HEADER_NAME]: CUSTOM_HEADER_VALUE,
+ });
+ }, 60000);
+
+ it('does not deliver the caller credentials to app code on the application public domain', async () => {
+ const response = await request(baseUrl)
+ .get('/s/echo-headers-route')
+ .set('Host', applicationPublicDomainHost)
+ .set('Authorization', `Bearer ${APPLE_JANE_ADMIN_ACCESS_TOKEN}`)
+ .set('Cookie', SESSION_COOKIE)
+ .set(CUSTOM_HEADER_NAME, CUSTOM_HEADER_VALUE);
+
+ expect(response.status).toBe(200);
+ expect(response.body).not.toHaveProperty('authorization');
+ expect(response.body).not.toHaveProperty('cookie');
+ expect(response.body).toHaveProperty(
+ CUSTOM_HEADER_NAME,
+ CUSTOM_HEADER_VALUE,
+ );
+ }, 60000);
+});