The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Block private-network SSO issuers and replace the safe-mode toggle with an internal host allowlist (#25756)
Félix Malfait38b55f8890b0
diff --git a/packages/twenty-apps/internal/twenty-partners/src/workflows/README.md b/packages/twenty-apps/internal/twenty-partners/src/workflows/README.mdindex b0fa092db81..5dfc63ee3f0 100644--- a/packages/twenty-apps/internal/twenty-partners/src/workflows/README.md+++ b/packages/twenty-apps/internal/twenty-partners/src/workflows/README.md@@ -55,9 +55,9 @@ Prod prerequisites: a connected mailbox (Settings → Accounts) and the app instRun smtp4dev:`docker run --rm -d --name smtp4dev -p 8090:80 -p 2525:25 -p 1143:143 rnwood/smtp4dev`.-Set `OUTBOUND_HTTP_SAFE_MODE_ENABLED` to false (Settings → Admin Panel → Config-Variables) — safe mode blocks private hosts for IMAP/SMTP on purpose. Connect an-IMAP/SMTP account with host `host.docker.internal` (SMTP 2525, IMAP 1143, no TLS, any+Add `host.docker.internal` to `OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS` (Settings → Admin+Panel → Config Variables) — private hosts are blocked for IMAP/SMTP on purpose. Connect+an IMAP/SMTP account with host `host.docker.internal` (SMTP 2525, IMAP 1143, no TLS, anycredentials). Mails land at http://localhost:8090. `EMAIL_DRIVER` env vars are thesystem mailer, not this — leave them alone.diff --git a/packages/twenty-docs/developers/self-host/capabilities/setup.mdx b/packages/twenty-docs/developers/self-host/capabilities/setup.mdxindex 14c4c5291c7..2f4f54e40bf 100644--- a/packages/twenty-docs/developers/self-host/capabilities/setup.mdx+++ b/packages/twenty-docs/developers/self-host/capabilities/setup.mdx@@ -263,6 +263,18 @@ yarn command:prod cron:calendar:ongoing-staleyarn command:prod cron:workflow:automated-cron-trigger```+## Outbound Connections to Internal Hosts++By default, Twenty refuses outbound connections to private/internal IP addresses (SSRF protection). This covers HTTP workflow actions, webhooks, SSO identity providers and IMAP/SMTP/CalDAV connections. If your identity provider, mail or calendar server runs on a private network, list its hostname or IP literal:++```bash+OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS=keycloak,mail.internal,192.168.1.10+```++Entries are matched on the hostname only, without wildcards: for an OIDC issuer such as `http://keycloak:8080/realms/twenty`, list `keycloak`. Every other private address stays blocked, and even an allowed host can never reach the cloud metadata address range. Set the variable to `*` to disable the protection entirely, which is only appropriate on trusted, isolated networks.++`OUTBOUND_HTTP_SAFE_MODE_ENABLED` is deprecated. While it is set to `false`, the protection stays fully off and `OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS` is ignored, so remove it when you migrate to the list.+## Email Configuration1. Go to **Settings → Admin Panel → Configuration Variables**diff --git a/packages/twenty-docs/user-guide/calendar-emails/overview.mdx b/packages/twenty-docs/user-guide/calendar-emails/overview.mdxindex 92c41128ec1..483e1e1f1ab 100644--- a/packages/twenty-docs/user-guide/calendar-emails/overview.mdx+++ b/packages/twenty-docs/user-guide/calendar-emails/overview.mdx@@ -31,13 +31,13 @@ For other email and calendar providers:4. Test the connection<Note>-**Self-hosting on an air-gapped or internal network**: By default, Twenty refuses outbound connections to private/internal IP addresses (SSRF protection). If your mail or calendar server runs on a local/private IP (e.g. an on-premise server on a LAN), connections to it will be blocked. To allow them, set the following environment variable on the server:+**Self-hosting on an internal network**: By default, Twenty refuses outbound connections to private/internal IP addresses (SSRF protection). If your mail, calendar or identity provider server runs on a local/private IP (e.g. an on-premise server on a LAN), connections to it will be blocked. To allow them, list the hostnames or IP literals in the following environment variable on the server:```-OUTBOUND_HTTP_SAFE_MODE_ENABLED=false+OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS=mail.internal,keycloak,192.168.1.10```-This disables safe mode for **all** outbound requests (HTTP workflow actions, webhooks, and IMAP/SMTP/CalDAV connections), so only set it on trusted, isolated networks where the SSRF protection is not needed.+Entries are matched on the hostname only (`keycloak`, not `http://keycloak:8080/realms/…`), without wildcards. Every other outbound request (HTTP workflow actions, webhooks, SSO and IMAP/SMTP/CalDAV connections) stays protected, and even an allowed host can never reach the cloud metadata address range. Set it to `*` to disable the protection entirely, which is only appropriate on trusted, isolated networks. If you previously set `OUTBOUND_HTTP_SAFE_MODE_ENABLED=false`, remove it: while it is set, the protection stays fully off and the list is ignored.</Note>### Multiple Mailboxesdiff --git a/packages/twenty-server/src/engine/core-modules/auth/guards/oidc-auth.guard.ts b/packages/twenty-server/src/engine/core-modules/auth/guards/oidc-auth.guard.tsindex 61e9b32ddab..b599192c9ca 100644--- a/packages/twenty-server/src/engine/core-modules/auth/guards/oidc-auth.guard.ts+++ b/packages/twenty-server/src/engine/core-modules/auth/guards/oidc-auth.guard.ts@@ -3,8 +3,6 @@import { type ExecutionContext, Injectable } from '@nestjs/common';import { AuthGuard } from '@nestjs/passport';-import { Issuer } from 'openid-client';-import {AuthException,AuthExceptionCode,@@ -79,7 +77,9 @@ export class OidcAuthGuard extends AuthGuard('openidconnect') {AuthExceptionCode.INVALID_DATA,);}- const issuer = await Issuer.discover(identityProvider.issuer);+ const issuer = await this.ssoService.discoverOidcIssuer(+ identityProvider.issuer,+ );new OidcAuthStrategy(this.ssoService.getOidcClient(identityProvider, issuer),diff --git a/packages/twenty-server/src/engine/core-modules/auth/guards/oidc-auth.spec.ts b/packages/twenty-server/src/engine/core-modules/auth/guards/oidc-auth.spec.tsindex 4de52e95436..16a2466341d 100644--- a/packages/twenty-server/src/engine/core-modules/auth/guards/oidc-auth.spec.ts+++ b/packages/twenty-server/src/engine/core-modules/auth/guards/oidc-auth.spec.ts@@ -30,9 +30,6 @@ jestjest.mock('openid-client', () => ({Strategy: jest.fn(),- Issuer: {- discover: jest.fn().mockResolvedValue({} as Issuer),- },}));describe('OIDCAuthGuard', () => {@@ -49,6 +46,7 @@ describe('OIDCAuthGuard', () => {provide: SsoService,useValue: {findSsoIdentityProviderById: jest.fn(),+ discoverOidcIssuer: jest.fn().mockResolvedValue({} as Issuer),getOidcClient: jest.fn(),},},@@ -101,6 +99,9 @@ describe('OIDCAuthGuard', () => {expect(ssoService.findSsoIdentityProviderById).toHaveBeenCalledWith('test-id',);+ expect(ssoService.discoverOidcIssuer).toHaveBeenCalledWith(+ 'https://issuer.example.com',+ );});it('should throw error when identity provider is not found', async () => {diff --git a/packages/twenty-server/src/engine/core-modules/secure-http-client/__tests__/secure-http-client.service.spec.ts b/packages/twenty-server/src/engine/core-modules/secure-http-client/__tests__/secure-http-client.service.spec.tsnew file mode 100644index 00000000000..b8035a76d9d--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/secure-http-client/__tests__/secure-http-client.service.spec.ts@@ -0,0 +1,136 @@+import { EventEmitter } from 'events';+import * as http from 'http';+import * as https from 'https';+import { type Duplex } from 'stream';++import { Logger } from '@nestjs/common';++import { SecureHttpClientService } from 'src/engine/core-modules/secure-http-client/secure-http-client.service';+import { type TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';++describe('SecureHttpClientService', () => {+ const buildService = (config: {+ OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS: string[];+ OUTBOUND_HTTP_SAFE_MODE_ENABLED?: boolean;+ }) =>+ new SecureHttpClientService({+ get: (key: keyof typeof config) => config[key],+ } as unknown as TwentyConfigService);++ describe('getSsrfSafeAgent', () => {+ it('returns an agent matching the URL protocol', () => {+ const service = buildService({+ OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS: [],+ });++ expect(+ service.getSsrfSafeAgent(new URL('https://idp.example.com')),+ ).toBeInstanceOf(https.Agent);+ expect(+ service.getSsrfSafeAgent(new URL('http://idp.example.com')),+ ).toBeInstanceOf(http.Agent);+ });++ it('returns an agent that blocks a private address', () => {+ const service = buildService({+ OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS: [],+ });++ const agent = service.getSsrfSafeAgent(+ new URL('http://169.254.169.254/latest/meta-data/'),+ ) as http.Agent;++ expect(() =>+ agent.createConnection(+ { host: '169.254.169.254' } as http.ClientRequestArgs,+ jest.fn(),+ ),+ ).toThrow(+ 'Request to internal IP address 169.254.169.254 is not allowed.',+ );+ });++ it('returns undefined when all internal hosts are allowed', () => {+ const service = buildService({+ OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS: ['*'],+ });++ expect(+ service.getSsrfSafeAgent(new URL('http://keycloak:8080')),+ ).toBeUndefined();+ });++ it('honours the deprecated OUTBOUND_HTTP_SAFE_MODE_ENABLED=false and warns once', () => {+ const warnSpy = jest+ .spyOn(Logger.prototype, 'warn')+ .mockImplementation(() => undefined);+ const service = buildService({+ OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS: ['keycloak'],+ OUTBOUND_HTTP_SAFE_MODE_ENABLED: false,+ });++ expect(+ service.getSsrfSafeAgent(new URL('http://keycloak:8080')),+ ).toBeUndefined();+ expect(+ service.getSsrfSafeAgent(new URL('http://10.0.0.1')),+ ).toBeUndefined();+ expect(warnSpy).toHaveBeenCalledTimes(1);++ warnSpy.mockRestore();+ });++ it('accepts a full URL or host:port entry and matches on the hostname', () => {+ const socket = new EventEmitter();+ const createConnectionSpy = jest+ .spyOn(http.Agent.prototype, 'createConnection')+ .mockReturnValue(socket as unknown as Duplex);+ const service = buildService({+ OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS: [+ 'http://Keycloak:8080/realms/twenty',+ '[::1]:993',+ ],+ });++ const agent = service.getSsrfSafeAgent(+ new URL('http://keycloak:8080'),+ ) as http.Agent;++ agent.createConnection(+ { host: '::1' } as http.ClientRequestArgs,+ jest.fn(),+ );+ agent.createConnection(+ { host: 'keycloak' } as http.ClientRequestArgs,+ jest.fn(),+ );+ socket.emit('lookup', null, '172.18.0.5', 4, 'keycloak');++ expect(createConnectionSpy).toHaveBeenCalledTimes(2);++ createConnectionSpy.mockRestore();+ });+ });++ describe('getValidatedHost', () => {+ it('lets an allowed private IP through, ignoring surrounding whitespace', async () => {+ const service = buildService({+ OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS: [' 192.168.1.10 '],+ });++ await expect(service.getValidatedHost('192.168.1.10')).resolves.toBe(+ '192.168.1.10',+ );+ });++ it('still blocks a private IP that is not allowed', async () => {+ const service = buildService({+ OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS: ['192.168.1.10'],+ });++ await expect(service.getValidatedHost('10.0.0.1')).rejects.toThrow(+ 'Connection to internal IP address 10.0.0.1 is not allowed.',+ );+ });+ });+});diff --git a/packages/twenty-server/src/engine/core-modules/secure-http-client/constants/allow-all-internal-hosts.constant.ts b/packages/twenty-server/src/engine/core-modules/secure-http-client/constants/allow-all-internal-hosts.constant.tsnew file mode 100644index 00000000000..b661e9ed6cf--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/secure-http-client/constants/allow-all-internal-hosts.constant.ts@@ -0,0 +1 @@+export const ALLOW_ALL_INTERNAL_HOSTS = '*';diff --git a/packages/twenty-server/src/engine/core-modules/secure-http-client/secure-http-client.service.ts b/packages/twenty-server/src/engine/core-modules/secure-http-client/secure-http-client.service.tsindex 5ce63de2b03..c4686f51637 100644--- a/packages/twenty-server/src/engine/core-modules/secure-http-client/secure-http-client.service.ts+++ b/packages/twenty-server/src/engine/core-modules/secure-http-client/secure-http-client.service.ts@@ -1,12 +1,17 @@+import * as http from 'http';+import { Injectable, Logger } from '@nestjs/common';import axios, { type AxiosInstance, type CreateAxiosDefaults } from 'axios';import axiosRetry from 'axios-retry';+import { isNonEmptyString } from '@sniptt/guards';import { isDefined } from 'twenty-shared/utils';import { buildAxiosFetch } from '@lifeomic/axios-fetch';import { createSsrfSafeAgent } from 'src/engine/core-modules/secure-http-client/utils/create-ssrf-safe-agent.util';+import { ALLOW_ALL_INTERNAL_HOSTS } from 'src/engine/core-modules/secure-http-client/constants/allow-all-internal-hosts.constant';+import { normalizeAllowedInternalHost } from 'src/engine/core-modules/secure-http-client/utils/normalize-allowed-internal-host.util';import { resolveAndValidateHostname } from 'src/engine/core-modules/secure-http-client/utils/resolve-and-validate-hostname.util';import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';@@ -23,6 +28,7 @@ type SecureHttpClientConfig = CreateAxiosDefaults & {@Injectable()export class SecureHttpClientService {private readonly logger = new Logger(SecureHttpClientService.name);+ private hasWarnedAboutDeprecatedSafeModeFlag = false;constructor(private readonly twentyConfigService: TwentyConfigService) {}@@ -37,15 +43,14 @@ export class SecureHttpClientService {): AxiosInstance {const { retries, shouldResetTimeout, ...axiosConfig } = config ?? {};- const isSafeModeEnabled = this.twentyConfigService.get(- 'OUTBOUND_HTTP_SAFE_MODE_ENABLED',- );+ const allowedInternalHosts = this.getAllowedInternalHosts();+ const isSafeModeEnabled = this.isSafeModeEnabled(allowedInternalHosts);const client = isSafeModeEnabled? axios.create({...axiosConfig,- httpAgent: createSsrfSafeAgent('http'),- httpsAgent: createSsrfSafeAgent('https'),+ httpAgent: createSsrfSafeAgent('http', allowedInternalHosts),+ httpsAgent: createSsrfSafeAgent('https', allowedInternalHosts),maxRedirects: Math.min(axiosConfig.maxRedirects ?? MAX_REDIRECTS,MAX_REDIRECTS,@@ -104,22 +109,61 @@ export class SecureHttpClientService {}createSsrfSafeFetch(): typeof globalThis.fetch {- if (!this.isSafeModeEnabled()) {+ if (!this.isSafeModeEnabled(this.getAllowedInternalHosts())) {return globalThis.fetch;}return buildAxiosFetch(this.getHttpClient()) as typeof globalThis.fetch;}+ // For libraries that own their HTTP stack and only accept an agent+ // (openid-client). Undefined means no restriction.+ getSsrfSafeAgent(url: URL): http.Agent | undefined {+ const allowedInternalHosts = this.getAllowedInternalHosts();++ if (!this.isSafeModeEnabled(allowedInternalHosts)) {+ return undefined;+ }++ return createSsrfSafeAgent(+ url.protocol === 'https:' ? 'https' : 'http',+ allowedInternalHosts,+ );+ }+async getValidatedHost(hostnameOrUrl: string): Promise<string> {- if (!this.isSafeModeEnabled()) {+ const allowedInternalHosts = this.getAllowedInternalHosts();++ if (!this.isSafeModeEnabled(allowedInternalHosts)) {return hostnameOrUrl;}- return resolveAndValidateHostname(hostnameOrUrl);+ return resolveAndValidateHostname(hostnameOrUrl, allowedInternalHosts);+ }++ private getAllowedInternalHosts(): string[] {+ // OUTBOUND_HTTP_SAFE_MODE_ENABLED is deprecated but still honoured so+ // self-hosted setups that turned it off keep working after upgrading.+ if (+ this.twentyConfigService.get('OUTBOUND_HTTP_SAFE_MODE_ENABLED') === false+ ) {+ if (!this.hasWarnedAboutDeprecatedSafeModeFlag) {+ this.hasWarnedAboutDeprecatedSafeModeFlag = true;+ this.logger.warn(+ 'OUTBOUND_HTTP_SAFE_MODE_ENABLED=false is deprecated and overrides OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS: every private address is reachable. Remove it and list the internal hosts you need instead.',+ );+ }++ return [ALLOW_ALL_INTERNAL_HOSTS];+ }++ return this.twentyConfigService+ .get('OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS')+ .map(normalizeAllowedInternalHost)+ .filter(isNonEmptyString);}- private isSafeModeEnabled(): boolean {- return this.twentyConfigService.get('OUTBOUND_HTTP_SAFE_MODE_ENABLED');+ private isSafeModeEnabled(allowedInternalHosts: string[]): boolean {+ return !allowedInternalHosts.includes(ALLOW_ALL_INTERNAL_HOSTS);}}diff --git a/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/__tests__/create-ssrf-safe-agent.util.spec.ts b/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/__tests__/create-ssrf-safe-agent.util.spec.tsindex 4063914c676..6823fa25242 100644--- a/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/__tests__/create-ssrf-safe-agent.util.spec.ts+++ b/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/__tests__/create-ssrf-safe-agent.util.spec.ts@@ -215,6 +215,84 @@ describe('createSsrfSafeAgent', () => {});});+ describe('allowed internal hosts', () => {+ it('should allow an allowed private IP literal', () => {+ const agent = createSsrfSafeAgent('http', ['192.168.1.10']);++ agent.createConnection(+ { host: '192.168.1.10' } as http.ClientRequestArgs,+ jest.fn(),+ );++ expect(createConnectionSpy).toHaveBeenCalled();+ });++ it('should let an allowed hostname resolve to a private address', () => {+ const agent = createSsrfSafeAgent('http', ['keycloak']);++ agent.createConnection(+ { host: 'Keycloak' } as http.ClientRequestArgs,+ jest.fn(),+ );++ mockSocket.emit('lookup', null, '172.18.0.5', 4, 'Keycloak');++ expect(mockSocket.destroy).not.toHaveBeenCalled();+ });++ it('should still block an allowed hostname that resolves to the metadata service', () => {+ const agent = createSsrfSafeAgent('http', ['keycloak']);++ agent.createConnection(+ { host: 'keycloak' } as http.ClientRequestArgs,+ jest.fn(),+ );++ mockSocket.emit('lookup', null, '169.254.169.254', 4, 'keycloak');++ expect(mockSocket.destroy).toHaveBeenCalledWith(+ expect.objectContaining({+ message: expect.stringContaining('169.254.169.254'),+ }),+ );+ });++ it('should still block a link-local IP literal even when allowed', () => {+ const agent = createSsrfSafeAgent('http', ['169.254.169.254']);++ expect(() => {+ agent.createConnection(+ { host: '169.254.169.254' } as http.ClientRequestArgs,+ jest.fn(),+ );+ }).toThrow(+ 'Request to internal IP address 169.254.169.254 is not allowed.',+ );+ });++ it('should still block private IPs for hosts that are not allowed', () => {+ const agent = createSsrfSafeAgent('http', ['keycloak']);++ expect(() => {+ agent.createConnection(+ { host: '10.0.0.1' } as http.ClientRequestArgs,+ jest.fn(),+ );+ }).toThrow('Request to internal IP address 10.0.0.1 is not allowed.');+ });++ it('should allow private hosts when the wildcard is set', () => {+ const agent = createSsrfSafeAgent('http', ['*']);++ agent.createConnection(+ { host: '10.0.0.1' } as http.ClientRequestArgs,+ jest.fn(),+ );++ expect(createConnectionSpy).toHaveBeenCalled();+ });+ });+describe('HTTPS agent', () => {it('should block private IPs for HTTPS connections', () => {const agent = createSsrfSafeAgent('https');diff --git a/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/__tests__/is-private-ip.util.spec.ts b/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/__tests__/is-private-ip.util.spec.tsindex 9a421a5f85b..04421e7a872 100644--- a/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/__tests__/is-private-ip.util.spec.ts+++ b/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/__tests__/is-private-ip.util.spec.ts@@ -1,3 +1,4 @@+import { isLinkLocalIp } from 'src/engine/core-modules/secure-http-client/utils/is-link-local-ip.util';import { isPrivateIp } from 'src/engine/core-modules/secure-http-client/utils/is-private-ip.util';describe('isPrivateIp', () => {@@ -257,3 +258,17 @@ describe('isPrivateIp', () => {});});});++describe('isLinkLocalIp', () => {+ it('should detect the cloud metadata address', () => {+ expect(isLinkLocalIp('169.254.169.254')).toBe(true);+ expect(isLinkLocalIp('::ffff:a9fe:a9fe')).toBe(true);+ expect(isLinkLocalIp('fe80::1')).toBe(true);+ });++ it('should not flag other private or loopback addresses', () => {+ expect(isLinkLocalIp('10.0.0.1')).toBe(false);+ expect(isLinkLocalIp('192.168.1.10')).toBe(false);+ expect(isLinkLocalIp('127.0.0.1')).toBe(false);+ });+});diff --git a/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/__tests__/resolve-and-validate-hostname.util.spec.ts b/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/__tests__/resolve-and-validate-hostname.util.spec.tsindex 3095f824532..e825876a1ca 100644--- a/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/__tests__/resolve-and-validate-hostname.util.spec.ts+++ b/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/__tests__/resolve-and-validate-hostname.util.spec.ts@@ -11,7 +11,7 @@ describe('resolveAndValidateHostname', () => {it('should resolve a plain hostname and pass it to DNS lookup', async () => {mockDnsLookup.mockResolvedValue({ address: '93.184.216.34', family: 4 });- await resolveAndValidateHostname('imap.fastmail.com', mockDnsLookup);+ await resolveAndValidateHostname('imap.fastmail.com', [], mockDnsLookup);expect(mockDnsLookup).toHaveBeenCalledWith('imap.fastmail.com');});@@ -21,6 +21,7 @@ describe('resolveAndValidateHostname', () => {await resolveAndValidateHostname('https://caldav.example.com:8443/dav/principals',+ [],mockDnsLookup,);@@ -31,7 +32,7 @@ describe('resolveAndValidateHostname', () => {mockDnsLookup.mockResolvedValue({ address: '10.0.0.1', family: 4 });await expect(- resolveAndValidateHostname('evil.example.com', mockDnsLookup),+ resolveAndValidateHostname('evil.example.com', [], mockDnsLookup),).rejects.toThrow('Connection to internal IP address 10.0.0.1 is not allowed.',);@@ -42,19 +43,49 @@ describe('resolveAndValidateHostname', () => {const result = await resolveAndValidateHostname('mail.example.com',+ [],mockDnsLookup,);expect(result).toBe('93.184.216.34');});+ it('should let an allowed internal host resolve to a private address', async () => {+ mockDnsLookup.mockResolvedValue({ address: '172.18.0.5', family: 4 });++ const result = await resolveAndValidateHostname(+ 'Mail.Internal',+ ['mail.internal'],+ mockDnsLookup,+ );++ expect(result).toBe('172.18.0.5');+ });++ it('should still block an allowed internal host that resolves to the metadata service', async () => {+ mockDnsLookup.mockResolvedValue({+ address: '169.254.169.254',+ family: 4,+ });++ await expect(+ resolveAndValidateHostname(+ 'https://caldav.internal/dav',+ ['caldav.internal'],+ mockDnsLookup,+ ),+ ).rejects.toThrow(+ 'Connection to internal IP address 169.254.169.254 is not allowed.',+ );+ });+it('should propagate DNS resolution failures', async () => {mockDnsLookup.mockRejectedValue(new Error('getaddrinfo ENOTFOUND bogus.invalid'),);await expect(- resolveAndValidateHostname('bogus.invalid', mockDnsLookup),+ resolveAndValidateHostname('bogus.invalid', [], mockDnsLookup),).rejects.toThrow('getaddrinfo ENOTFOUND bogus.invalid');});});diff --git a/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/create-ssrf-safe-agent.util.ts b/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/create-ssrf-safe-agent.util.tsindex 60ac2985145..364272b55b9 100644--- a/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/create-ssrf-safe-agent.util.ts+++ b/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/create-ssrf-safe-agent.util.ts@@ -3,28 +3,36 @@ import * as https from 'https';import { type Socket } from 'net';import { type Duplex } from 'stream';-import { isPrivateIp } from 'src/engine/core-modules/secure-http-client/utils/is-private-ip.util';+import { getIsBlockedIp } from 'src/engine/core-modules/secure-http-client/utils/get-is-blocked-ip.util';-// Checks whether a hostname is a private IP literal.+type IsBlockedIp = ReturnType<typeof getIsBlockedIp>;++// Checks whether a hostname is a blocked IP literal.// Returns false for domain names — those are validated after DNS// resolution in the socket 'lookup' event handler.-const isHostnamePrivateIp = (hostname: string): boolean => {+const isHostnameBlockedIp = (+ hostname: string,+ isBlockedIp: IsBlockedIp,+): boolean => {try {- return isPrivateIp(hostname);+ return isBlockedIp(hostname);} catch {return false;}};-const validateHost = (host?: string) => {- if (host && isHostnamePrivateIp(host)) {+const validateHost = (host: string | undefined, isBlockedIp: IsBlockedIp) => {+ if (host && isHostnameBlockedIp(host, isBlockedIp)) {throw new Error(`Request to internal IP address ${host} is not allowed.`);}};-// Validates a resolved IP and destroys the socket if it's private.+// Validates a resolved IP and destroys the socket if it's blocked.// Fails closed: if the IP cannot be parsed, the socket is destroyed.-const attachLookupValidation = (duplex: Duplex): Socket => {+const attachLookupValidation = (+ duplex: Duplex,+ isBlockedIp: IsBlockedIp,+): Socket => {// createConnection returns a net.Socket at runtime; the Duplex// return type in @types/node is overly broad.const socket = duplex as Socket;@@ -35,7 +43,7 @@ const attachLookupValidation = (duplex: Duplex): Socket => {}try {- if (isPrivateIp(address)) {+ if (isBlockedIp(address)) {socket.destroy(new Error(`Request to internal IP address ${address} is not allowed.`,@@ -59,29 +67,56 @@ const attachLookupValidation = (duplex: Duplex): Socket => {// which means every connection is checked — including those created// by automatic redirect following.class SsrfSafeHttpAgent extends http.Agent {+ constructor(private readonly allowedInternalHosts: string[]) {+ super();+ }+createConnection(options: http.ClientRequestArgs,callback?: (err: Error, stream: Duplex) => void,): Duplex {- validateHost(options.host ?? undefined);+ const isBlockedIp = getIsBlockedIp(+ options.host ?? undefined,+ this.allowedInternalHosts,+ );++ validateHost(options.host ?? undefined, isBlockedIp);- return attachLookupValidation(super.createConnection(options, callback));+ return attachLookupValidation(+ super.createConnection(options, callback),+ isBlockedIp,+ );}}class SsrfSafeHttpsAgent extends https.Agent {+ constructor(private readonly allowedInternalHosts: string[]) {+ super();+ }+createConnection(options: http.ClientRequestArgs,callback?: (err: Error, stream: Duplex) => void,): Duplex {- validateHost(options.host ?? undefined);+ const isBlockedIp = getIsBlockedIp(+ options.host ?? undefined,+ this.allowedInternalHosts,+ );++ validateHost(options.host ?? undefined, isBlockedIp);- return attachLookupValidation(super.createConnection(options, callback));+ return attachLookupValidation(+ super.createConnection(options, callback),+ isBlockedIp,+ );}}-export const createSsrfSafeAgent = (protocol: 'http' | 'https'): http.Agent => {+export const createSsrfSafeAgent = (+ protocol: 'http' | 'https',+ allowedInternalHosts: string[] = [],+): http.Agent => {return protocol === 'https'- ? new SsrfSafeHttpsAgent()- : new SsrfSafeHttpAgent();+ ? new SsrfSafeHttpsAgent(allowedInternalHosts)+ : new SsrfSafeHttpAgent(allowedInternalHosts);};diff --git a/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/get-is-blocked-ip.util.ts b/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/get-is-blocked-ip.util.tsnew file mode 100644index 00000000000..55f7ff6e052--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/get-is-blocked-ip.util.ts@@ -0,0 +1,13 @@+import { isAllowedInternalHost } from 'src/engine/core-modules/secure-http-client/utils/is-allowed-internal-host.util';+import { isLinkLocalIp } from 'src/engine/core-modules/secure-http-client/utils/is-link-local-ip.util';+import { isPrivateIp } from 'src/engine/core-modules/secure-http-client/utils/is-private-ip.util';++// An allowlisted host may reach private networks but never the link-local+// range, so a DNS change cannot turn it into a path to the metadata service.+export const getIsBlockedIp = (+ host: string | undefined,+ allowedInternalHosts: string[],+): ((address: string) => boolean) =>+ host && isAllowedInternalHost(host, allowedInternalHosts)+ ? isLinkLocalIp+ : isPrivateIp;diff --git a/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/is-allowed-internal-host.util.ts b/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/is-allowed-internal-host.util.tsnew file mode 100644index 00000000000..82c8c1f33fb--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/is-allowed-internal-host.util.ts@@ -0,0 +1,8 @@+import { ALLOW_ALL_INTERNAL_HOSTS } from 'src/engine/core-modules/secure-http-client/constants/allow-all-internal-hosts.constant';++export const isAllowedInternalHost = (+ host: string,+ allowedInternalHosts: string[],+): boolean =>+ allowedInternalHosts.includes(ALLOW_ALL_INTERNAL_HOSTS) ||+ allowedInternalHosts.includes(host.toLowerCase());diff --git a/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/is-link-local-ip.util.ts b/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/is-link-local-ip.util.tsnew file mode 100644index 00000000000..608fa5b546b--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/is-link-local-ip.util.ts@@ -0,0 +1,13 @@+import { BlockList } from 'net';++import { matchesIpRanges } from 'src/engine/core-modules/secure-http-client/utils/matches-ip-ranges.util';++// Cloud metadata services (169.254.169.254, ECS/EKS task credentials) live in+// the link-local range, so it is never opened by the internal host allowlist.+const LINK_LOCAL_RANGES = new BlockList();++LINK_LOCAL_RANGES.addSubnet('169.254.0.0', 16);+LINK_LOCAL_RANGES.addSubnet('fe80::', 10, 'ipv6');++export const isLinkLocalIp = (addr: string): boolean =>+ matchesIpRanges(LINK_LOCAL_RANGES, addr);diff --git a/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/is-private-ip.util.ts b/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/is-private-ip.util.tsindex 11410d094d9..1ed5909c868 100644--- a/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/is-private-ip.util.ts+++ b/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/is-private-ip.util.ts@@ -1,5 +1,7 @@import { BlockList } from 'net';+import { matchesIpRanges } from 'src/engine/core-modules/secure-http-client/utils/matches-ip-ranges.util';+const PRIVATE_RANGES = new BlockList();PRIVATE_RANGES.addSubnet('0.0.0.0', 8);@@ -22,107 +24,5 @@ PRIVATE_RANGES.addSubnet('::', 128, 'ipv6');PRIVATE_RANGES.addSubnet('fc00::', 7, 'ipv6');PRIVATE_RANGES.addSubnet('fe80::', 10, 'ipv6');-const fromLong = (ipl: number): string => {- return `${ipl >>> 24}.${(ipl >> 16) & 255}.${(ipl >> 8) & 255}.${ipl & 255}`;-};--// Parses IPv4 in any encoding (dotted decimal, octal, hex, bare integer)-// into a 32-bit unsigned integer. Returns -1 for invalid input.-const normalizeToLong = (addr: string): number => {- const parts = addr.split('.').map((part) => {- if (part.startsWith('0x') || part.startsWith('0X')) {- return parseInt(part, 16);- } else if (part.startsWith('0') && part !== '0' && /^[0-7]+$/.test(part)) {- return parseInt(part, 8);- } else if (/^[1-9]\d*$/.test(part) || part === '0') {- return parseInt(part, 10);- } else {- return NaN;- }- });-- if (parts.some(isNaN)) return -1;-- let val = 0;- const n = parts.length;-- switch (n) {- case 1:- val = parts[0];- break;- case 2:- if (parts[0] > 0xff || parts[1] > 0xffffff) return -1;- val = (parts[0] << 24) | (parts[1] & 0xffffff);- break;- case 3:- if (parts[0] > 0xff || parts[1] > 0xff || parts[2] > 0xffff) return -1;- val = (parts[0] << 24) | (parts[1] << 16) | (parts[2] & 0xffff);- break;- case 4:- if (parts.some((part) => part > 0xff)) return -1;- val = (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3];- break;- default:- return -1;- }-- return val >>> 0;-};--// Extracts the embedded IPv4 from an IPv4-mapped IPv6 address in hex-// notation (e.g. ::ffff:a9fe:a9fe → 169.254.169.254). Returns null-// if the address is not in this form.-const HEX_MAPPED_RE = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i;--const extractIpv4FromHexMappedIpv6 = (addr: string): string | null => {- const match = addr.match(HEX_MAPPED_RE);-- if (!match) {- return null;- }-- const hi = parseInt(match[1], 16);- const lo = parseInt(match[2], 16);-- return `${(hi >> 8) & 0xff}.${hi & 0xff}.${(lo >> 8) & 0xff}.${lo & 0xff}`;-};--// Extracts the embedded IPv4 from an IPv4-mapped IPv6 address in-// dotted-decimal notation (e.g. ::ffff:127.0.0.1 → 127.0.0.1).-const DOTTED_MAPPED_RE = /^::ffff:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/i;--const extractIpv4FromDottedMappedIpv6 = (addr: string): string | null => {- const match = addr.match(DOTTED_MAPPED_RE);-- return match ? match[1] : null;-};--export const isPrivateIp = (addr: string): boolean => {- // IPv4-mapped IPv6 in hex form — the form Node.js URL parser produces.- const hexMappedIpv4 = extractIpv4FromHexMappedIpv6(addr);-- if (hexMappedIpv4 !== null) {- return PRIVATE_RANGES.check(hexMappedIpv4);- }-- // IPv4-mapped IPv6 in dotted-decimal form (::ffff:D.D.D.D)- const dottedMappedIpv4 = extractIpv4FromDottedMappedIpv6(addr);-- if (dottedMappedIpv4 !== null) {- return PRIVATE_RANGES.check(dottedMappedIpv4);- }-- // Pure IPv6 (any address containing a colon that isn't IPv4-mapped)- if (addr.includes(':')) {- return PRIVATE_RANGES.check(addr, 'ipv6');- }-- // IPv4 in any encoding (standard, octal, hex, bare integer)- const ipl = normalizeToLong(addr);-- if (ipl < 0) {- throw new Error('invalid ipv4 address');- }-- return PRIVATE_RANGES.check(fromLong(ipl));-};+export const isPrivateIp = (addr: string): boolean =>+ matchesIpRanges(PRIVATE_RANGES, addr);diff --git a/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/matches-ip-ranges.util.ts b/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/matches-ip-ranges.util.tsnew file mode 100644index 00000000000..4e46f8b40bc--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/matches-ip-ranges.util.ts@@ -0,0 +1,106 @@+import { type BlockList } from 'net';++const fromLong = (ipl: number): string => {+ return `${ipl >>> 24}.${(ipl >> 16) & 255}.${(ipl >> 8) & 255}.${ipl & 255}`;+};++// Parses IPv4 in any encoding (dotted decimal, octal, hex, bare integer)+// into a 32-bit unsigned integer. Returns -1 for invalid input.+const normalizeToLong = (addr: string): number => {+ const parts = addr.split('.').map((part) => {+ if (part.startsWith('0x') || part.startsWith('0X')) {+ return parseInt(part, 16);+ } else if (part.startsWith('0') && part !== '0' && /^[0-7]+$/.test(part)) {+ return parseInt(part, 8);+ } else if (/^[1-9]\d*$/.test(part) || part === '0') {+ return parseInt(part, 10);+ } else {+ return NaN;+ }+ });++ if (parts.some(isNaN)) return -1;++ let val = 0;+ const n = parts.length;++ switch (n) {+ case 1:+ val = parts[0];+ break;+ case 2:+ if (parts[0] > 0xff || parts[1] > 0xffffff) return -1;+ val = (parts[0] << 24) | (parts[1] & 0xffffff);+ break;+ case 3:+ if (parts[0] > 0xff || parts[1] > 0xff || parts[2] > 0xffff) return -1;+ val = (parts[0] << 24) | (parts[1] << 16) | (parts[2] & 0xffff);+ break;+ case 4:+ if (parts.some((part) => part > 0xff)) return -1;+ val = (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3];+ break;+ default:+ return -1;+ }++ return val >>> 0;+};++// Extracts the embedded IPv4 from an IPv4-mapped IPv6 address in hex+// notation (e.g. ::ffff:a9fe:a9fe → 169.254.169.254). Returns null+// if the address is not in this form.+const HEX_MAPPED_RE = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i;++const extractIpv4FromHexMappedIpv6 = (addr: string): string | null => {+ const match = addr.match(HEX_MAPPED_RE);++ if (!match) {+ return null;+ }++ const hi = parseInt(match[1], 16);+ const lo = parseInt(match[2], 16);++ return `${(hi >> 8) & 0xff}.${hi & 0xff}.${(lo >> 8) & 0xff}.${lo & 0xff}`;+};++// Extracts the embedded IPv4 from an IPv4-mapped IPv6 address in+// dotted-decimal notation (e.g. ::ffff:127.0.0.1 → 127.0.0.1).+const DOTTED_MAPPED_RE = /^::ffff:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/i;++const extractIpv4FromDottedMappedIpv6 = (addr: string): string | null => {+ const match = addr.match(DOTTED_MAPPED_RE);++ return match ? match[1] : null;+};++export const matchesIpRanges = (ranges: BlockList, addr: string): boolean => {+ // IPv4-mapped IPv6 in hex form — the form Node.js URL parser produces.+ const hexMappedIpv4 = extractIpv4FromHexMappedIpv6(addr);++ if (hexMappedIpv4 !== null) {+ return ranges.check(hexMappedIpv4);+ }++ // IPv4-mapped IPv6 in dotted-decimal form (::ffff:D.D.D.D)+ const dottedMappedIpv4 = extractIpv4FromDottedMappedIpv6(addr);++ if (dottedMappedIpv4 !== null) {+ return ranges.check(dottedMappedIpv4);+ }++ // Pure IPv6 (any address containing a colon that isn't IPv4-mapped)+ if (addr.includes(':')) {+ return ranges.check(addr, 'ipv6');+ }++ // IPv4 in any encoding (standard, octal, hex, bare integer)+ const ipl = normalizeToLong(addr);++ if (ipl < 0) {+ throw new Error('invalid ipv4 address');+ }++ return ranges.check(fromLong(ipl));+};diff --git a/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/normalize-allowed-internal-host.util.ts b/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/normalize-allowed-internal-host.util.tsnew file mode 100644index 00000000000..9eb40bf067e--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/normalize-allowed-internal-host.util.ts@@ -0,0 +1,13 @@+// Operators paste whatever they have at hand (a bare host, host:port or the+// full issuer URL); connections are matched on the hostname alone.+export const normalizeAllowedInternalHost = (entry: string): string => {+ const trimmed = entry.trim();++ try {+ return new URL(+ trimmed.includes('://') ? trimmed : `http://${trimmed}`,+ ).hostname.replace(/^\[|\]$/g, '');+ } catch {+ return trimmed.toLowerCase();+ }+};diff --git a/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/resolve-and-validate-hostname.util.ts b/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/resolve-and-validate-hostname.util.tsindex e5527bebf01..7c1b43c976a 100644--- a/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/resolve-and-validate-hostname.util.ts+++ b/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/resolve-and-validate-hostname.util.ts@@ -1,9 +1,10 @@import * as dns from 'dns/promises';-import { isPrivateIp } from 'src/engine/core-modules/secure-http-client/utils/is-private-ip.util';+import { getIsBlockedIp } from 'src/engine/core-modules/secure-http-client/utils/get-is-blocked-ip.util';export const resolveAndValidateHostname = async (hostnameOrUrl: string,+ allowedInternalHosts: string[] = [],dnsLookup: typeof dns.lookup = dns.lookup,): Promise<string> => {let hostname: string;@@ -16,9 +17,11 @@ export const resolveAndValidateHostname = async (hostname = hostnameOrUrl;}+ const isBlockedIp = getIsBlockedIp(hostname, allowedInternalHosts);+const { address: resolvedIp } = await dnsLookup(hostname);- if (isPrivateIp(resolvedIp)) {+ if (isBlockedIp(resolvedIp)) {throw new Error(`Connection to internal IP address ${resolvedIp} is not allowed.`,);diff --git a/packages/twenty-server/src/engine/core-modules/sso/services/__tests__/sso.service.spec.ts b/packages/twenty-server/src/engine/core-modules/sso/services/__tests__/sso.service.spec.tsnew file mode 100644index 00000000000..ae8abd69d66--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/sso/services/__tests__/sso.service.spec.ts@@ -0,0 +1,93 @@+/* @license Enterprise */++import * as http from 'http';++import { custom, Issuer } from 'openid-client';++import { type BillingService } from 'src/engine/core-modules/billing/services/billing.service';+import { type ExceptionHandlerService } from 'src/engine/core-modules/exception-handler/exception-handler.service';+import { SecureHttpClientService } from 'src/engine/core-modules/secure-http-client/secure-http-client.service';+import { SsoService } from 'src/engine/core-modules/sso/services/sso.service';+import { type TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';+import {+ IdentityProviderType,+ type WorkspaceSsoIdentityProviderEntity,+} from 'src/engine/core-modules/sso/workspace-sso-identity-provider.entity';++const METADATA_SERVICE_URL = new URL(+ 'http://169.254.169.254/latest/meta-data/',+);++const expectAgentToBlockMetadataService = (options: {+ agent?: http.Agent | boolean;+}) => {+ expect(options.agent).toBeInstanceOf(http.Agent);+ expect(() =>+ (options.agent as http.Agent).createConnection(+ { host: METADATA_SERVICE_URL.hostname } as http.ClientRequestArgs,+ jest.fn(),+ ),+ ).toThrow('Request to internal IP address 169.254.169.254 is not allowed.');+};++describe('SsoService', () => {+ const originalIssuerHttpOptions = Issuer[custom.http_options];++ const buildSsoService = (allowedInternalHosts: string[] = []) => {+ const twentyConfigService = {+ get: (key: string) =>+ key === 'OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS'+ ? allowedInternalHosts+ : 'https://app.example.com',+ } as unknown as TwentyConfigService;++ return new SsoService(+ {} as never,+ twentyConfigService,+ {} as BillingService,+ {} as ExceptionHandlerService,+ new SecureHttpClientService(twentyConfigService),+ );+ };++ const oidcIdentityProvider = {+ type: IdentityProviderType.OIDC,+ id: 'idp-id',+ clientID: 'client-id',+ clientSecret: 'client-secret',+ } as WorkspaceSsoIdentityProviderEntity;++ afterEach(() => {+ Issuer[custom.http_options] = originalIssuerHttpOptions;+ });++ it('blocks issuer discovery against the metadata service', () => {+ buildSsoService();++ expectAgentToBlockMetadataService(+ Issuer[custom.http_options](METADATA_SERVICE_URL, {}),+ );+ });++ it('blocks JWKS, token and userinfo endpoints that a discovery document points at the metadata service', () => {+ const ssoService = buildSsoService();+ const issuer = new Issuer({ issuer: 'https://idp.example.com' });++ const client = ssoService.getOidcClient(oidcIdentityProvider, issuer);++ expectAgentToBlockMetadataService(+ issuer[custom.http_options](METADATA_SERVICE_URL, {}),+ );+ expectAgentToBlockMetadataService(+ client[custom.http_options](METADATA_SERVICE_URL, {}),+ );+ });++ it('does not restrict requests when every internal host is allowed', () => {+ buildSsoService(['*']);++ expect(Issuer[custom.http_options](METADATA_SERVICE_URL, {})).toEqual({+ agent: undefined,+ });+ });+});diff --git a/packages/twenty-server/src/engine/core-modules/sso/services/sso.service.ts b/packages/twenty-server/src/engine/core-modules/sso/services/sso.service.tsindex 9556850474d..9fb8d241d30 100644--- a/packages/twenty-server/src/engine/core-modules/sso/services/sso.service.ts+++ b/packages/twenty-server/src/engine/core-modules/sso/services/sso.service.ts@@ -3,7 +3,8 @@import { Injectable } from '@nestjs/common';import { InjectRepository } from '@nestjs/typeorm';-import { Issuer } from 'openid-client';+import { msg } from '@lingui/core/macro';+import { custom, Issuer } from 'openid-client';import { Repository } from 'typeorm';import {@@ -14,6 +15,7 @@ import {import { BillingEntitlementKey } from 'src/engine/core-modules/billing/enums/billing-entitlement-key.enum';import { BillingService } from 'src/engine/core-modules/billing/services/billing.service';import { ExceptionHandlerService } from 'src/engine/core-modules/exception-handler/exception-handler.service';+import { SecureHttpClientService } from 'src/engine/core-modules/secure-http-client/secure-http-client.service';import {SsoException,SsoExceptionCode,@@ -28,13 +30,26 @@ import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twent@Injectable()export class SsoService {private readonly featureLookUpKey = BillingEntitlementKey.SSO;++ // openid-client resolves this hook on whichever object issues the request:+ // the Issuer class for discovery, the issuer instance for JWKS and the+ // client instance for token and userinfo calls, so it is set on all three.+ // It deep-merges what the hook returns with its own per-request options+ // (method, headers, body), so only the agent needs to be returned.+ private readonly oidcHttpOptions = (url: URL) => ({+ agent: this.secureHttpClientService.getSsrfSafeAgent(url),+ });+constructor(@InjectRepository(WorkspaceSsoIdentityProviderEntity)private readonly workspaceSsoIdentityProviderRepository: Repository<WorkspaceSsoIdentityProviderEntity>,private readonly twentyConfigService: TwentyConfigService,private readonly billingService: BillingService,private readonly exceptionHandlerService: ExceptionHandlerService,- ) {}+ private readonly secureHttpClientService: SecureHttpClientService,+ ) {+ Issuer[custom.http_options] = this.oidcHttpOptions;+ }private async isSsoEnabled(workspaceId: string) {const isSsoBillingEnabled = await this.billingService.hasEntitlement(@@ -50,13 +65,18 @@ export class SsoService {}}- private async getIssuerForOidc(issuerUrl: string) {+ async discoverOidcIssuer(issuerUrl: string) {try {return await Issuer.discover(issuerUrl);- } catch {+ } catch (error) {+ // Surfaced so a blocked private-network issuer is diagnosable at setup;+ // at login the failure would only show as a redirect.+ const reason = error instanceof Error ? error.message : String(error);+throw new SsoException(- 'Invalid issuer',+ `Invalid issuer: ${reason}`,SsoExceptionCode.INVALID_ISSUER_URL,+ { userFriendlyMessage: msg`Invalid issuer URL: ${reason}` },);}}@@ -71,7 +91,7 @@ export class SsoService {try {await this.isSsoEnabled(workspaceId);- const issuer = await this.getIssuerForOidc(data.issuer);+ const issuer = await this.discoverOidcIssuer(data.issuer);const identityProvider =await this.workspaceSsoIdentityProviderRepository.save({@@ -194,12 +214,18 @@ export class SsoService {);}- return new issuer.Client({+ issuer[custom.http_options] = this.oidcHttpOptions;++ const client = new issuer.Client({client_id: identityProvider.clientID,client_secret: identityProvider.clientSecret,redirect_uris: [this.buildCallbackUrl(identityProvider)],response_types: [OidcResponseType.CODE],});++ client[custom.http_options] = this.oidcHttpOptions;++ return client;}async getAuthorizationUrlForSSO(diff --git a/packages/twenty-server/src/engine/core-modules/sso/sso.module.ts b/packages/twenty-server/src/engine/core-modules/sso/sso.module.tsindex 3999e34119e..0c208de2140 100644--- a/packages/twenty-server/src/engine/core-modules/sso/sso.module.ts+++ b/packages/twenty-server/src/engine/core-modules/sso/sso.module.ts@@ -7,6 +7,7 @@ import { BillingModule } from 'src/engine/core-modules/billing/billing.module';import { EnterpriseModule } from 'src/engine/core-modules/enterprise/enterprise.module';import { FeatureFlagModule } from 'src/engine/core-modules/feature-flag/feature-flag.module';import { GuardRedirectModule } from 'src/engine/core-modules/guard-redirect/guard-redirect.module';+import { SecureHttpClientModule } from 'src/engine/core-modules/secure-http-client/secure-http-client.module';import { SsoService } from 'src/engine/core-modules/sso/services/sso.service';import { SsoResolver } from 'src/engine/core-modules/sso/sso.resolver';import { WorkspaceSsoIdentityProviderEntity } from 'src/engine/core-modules/sso/workspace-sso-identity-provider.entity';@@ -19,6 +20,7 @@ import { PermissionsModule } from 'src/engine/metadata-modules/permissions/permiGuardRedirectModule,PermissionsModule,FeatureFlagModule,+ SecureHttpClientModule,],exports: [SsoService],providers: [SsoService, SsoResolver],diff --git a/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts b/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.tsindex c5bd8bb13bb..f483d0feb74 100644--- a/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts+++ b/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts@@ -96,7 +96,16 @@ export class ConfigVariables {@ConfigVariablesMetadata({group: ConfigVariablesGroup.ADVANCED_SETTINGS,description:- 'Enable safe mode for outbound requests (prevents private IPs and other security risks). Applies to HTTP workflow actions, webhooks, and IMAP/SMTP/CalDAV connections.',+ 'Hostnames or IP literals on a private network that outbound connections may reach, e.g. an on-premise mail server or identity provider (keycloak, mail.internal, 192.168.1.10). Exact hostname match, no patterns; a full URL is reduced to its hostname. Every other private address is blocked (SSRF protection) for HTTP workflow actions, webhooks, SSO and IMAP/SMTP/CalDAV connections. Set to * to allow all.',+ type: ConfigVariableType.ARRAY,+ })+ @IsOptional()+ OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS: string[] = [];++ @ConfigVariablesMetadata({+ group: ConfigVariablesGroup.ADVANCED_SETTINGS,+ description:+ 'Deprecated: set OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS to * instead. While this is false every private address is reachable and OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS is ignored.',type: ConfigVariableType.BOOLEAN,})@IsOptional()diff --git a/packages/twenty-server/test/integration/caldav/suites/caldav-events-import-without-etags.integration-spec.ts b/packages/twenty-server/test/integration/caldav/suites/caldav-events-import-without-etags.integration-spec.tsindex a9305eaea3c..5c07e28446b 100644--- a/packages/twenty-server/test/integration/caldav/suites/caldav-events-import-without-etags.integration-spec.ts+++ b/packages/twenty-server/test/integration/caldav/suites/caldav-events-import-without-etags.integration-spec.ts@@ -67,7 +67,7 @@ describe('CalDAV calendar events import without entity tags (integration)', () =beforeAll(async () => {await updateConfigVariable({- input: { key: 'OUTBOUND_HTTP_SAFE_MODE_ENABLED', value: false },+ input: { key: 'OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS', value: ['*'] },});radicale = await startRadicaleContainer({@@ -122,7 +122,7 @@ describe('CalDAV calendar events import without entity tags (integration)', () =afterAll(async () => {await updateConfigVariable({- input: { key: 'OUTBOUND_HTTP_SAFE_MODE_ENABLED', value: true },+ input: { key: 'OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS', value: [] },}).catch(() => undefined);if (isNonEmptyString(connectedAccountId)) {diff --git a/packages/twenty-server/test/integration/caldav/suites/caldav-events-import.integration-spec.ts b/packages/twenty-server/test/integration/caldav/suites/caldav-events-import.integration-spec.tsindex 51675be6697..75dbbb77728 100644--- a/packages/twenty-server/test/integration/caldav/suites/caldav-events-import.integration-spec.ts+++ b/packages/twenty-server/test/integration/caldav/suites/caldav-events-import.integration-spec.ts@@ -86,7 +86,7 @@ describe('CalDAV calendar events import (integration)', () => {// The CalDAV driver wraps its fetch in the SSRF guard, which rejects the// container's private address before the request is made.await updateConfigVariable({- input: { key: 'OUTBOUND_HTTP_SAFE_MODE_ENABLED', value: false },+ input: { key: 'OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS', value: ['*'] },});radicale = await startRadicaleContainer({@@ -136,7 +136,7 @@ describe('CalDAV calendar events import (integration)', () => {afterAll(async () => {await updateConfigVariable({- input: { key: 'OUTBOUND_HTTP_SAFE_MODE_ENABLED', value: true },+ input: { key: 'OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS', value: [] },}).catch(() => undefined);if (isNonEmptyString(connectedAccountId)) {diff --git a/packages/twenty-server/test/integration/caldav/suites/caldav-omitted-component-set.integration-spec.ts b/packages/twenty-server/test/integration/caldav/suites/caldav-omitted-component-set.integration-spec.tsindex b659b5ee476..0920b7cf9bc 100644--- a/packages/twenty-server/test/integration/caldav/suites/caldav-omitted-component-set.integration-spec.ts+++ b/packages/twenty-server/test/integration/caldav/suites/caldav-omitted-component-set.integration-spec.ts@@ -52,7 +52,7 @@ describe('CalDAV server omitting supported-calendar-component-set (integration)'beforeAll(async () => {await updateConfigVariable({- input: { key: 'OUTBOUND_HTTP_SAFE_MODE_ENABLED', value: false },+ input: { key: 'OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS', value: ['*'] },});radicale = await startRadicaleContainer({@@ -106,7 +106,7 @@ describe('CalDAV server omitting supported-calendar-component-set (integration)'afterAll(async () => {await updateConfigVariable({- input: { key: 'OUTBOUND_HTTP_SAFE_MODE_ENABLED', value: true },+ input: { key: 'OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS', value: [] },}).catch(() => undefined);if (isNonEmptyString(connectedAccountId)) {diff --git a/packages/twenty-server/test/integration/imap/suites/imap-folder-discovery.integration-spec.ts b/packages/twenty-server/test/integration/imap/suites/imap-folder-discovery.integration-spec.tsindex 28a0b993783..5041c83fc27 100644--- a/packages/twenty-server/test/integration/imap/suites/imap-folder-discovery.integration-spec.ts+++ b/packages/twenty-server/test/integration/imap/suites/imap-folder-discovery.integration-spec.ts@@ -27,7 +27,7 @@ describe('IMAP folder discovery (integration)', () => {afterAll(async () => {await updateConfigVariable({- input: { key: 'OUTBOUND_HTTP_SAFE_MODE_ENABLED', value: true },+ input: { key: 'OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS', value: [] },}).catch(() => undefined);if (isNonEmptyString(connectedAccountId)) {diff --git a/packages/twenty-server/test/integration/imap/suites/imap-folder-import-actions.integration-spec.ts b/packages/twenty-server/test/integration/imap/suites/imap-folder-import-actions.integration-spec.tsindex 5ef0d79ab7d..c95c91aed7a 100644--- a/packages/twenty-server/test/integration/imap/suites/imap-folder-import-actions.integration-spec.ts+++ b/packages/twenty-server/test/integration/imap/suites/imap-folder-import-actions.integration-spec.ts@@ -79,7 +79,7 @@ describe('IMAP folder actions (integration)', () => {jest.restoreAllMocks();await updateConfigVariable({- input: { key: 'OUTBOUND_HTTP_SAFE_MODE_ENABLED', value: true },+ input: { key: 'OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS', value: [] },}).catch(() => undefined);if (isNonEmptyString(connectedAccountId)) {diff --git a/packages/twenty-server/test/integration/imap/suites/imap-messages-import.integration-spec.ts b/packages/twenty-server/test/integration/imap/suites/imap-messages-import.integration-spec.tsindex 03ce26a77fd..6056439db70 100644--- a/packages/twenty-server/test/integration/imap/suites/imap-messages-import.integration-spec.ts+++ b/packages/twenty-server/test/integration/imap/suites/imap-messages-import.integration-spec.ts@@ -58,7 +58,7 @@ describe('IMAP messages import (integration)', () => {afterAll(async () => {await updateConfigVariable({- input: { key: 'OUTBOUND_HTTP_SAFE_MODE_ENABLED', value: true },+ input: { key: 'OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS', value: [] },}).catch(() => undefined);if (isNonEmptyString(connectedAccountId)) {diff --git a/packages/twenty-server/test/integration/imap/suites/imap-smtp-outbound.integration-spec.ts b/packages/twenty-server/test/integration/imap/suites/imap-smtp-outbound.integration-spec.tsindex 19416c25577..6d3273feaae 100644--- a/packages/twenty-server/test/integration/imap/suites/imap-smtp-outbound.integration-spec.ts+++ b/packages/twenty-server/test/integration/imap/suites/imap-smtp-outbound.integration-spec.ts@@ -23,15 +23,18 @@ describe('IMAP/SMTP outbound messaging (integration)', () => {let messageChannelId: string;beforeAll(async () => {- await updateConfigVariable({- input: { key: 'OUTBOUND_HTTP_SAFE_MODE_ENABLED', value: false },- });-greenmail = await startGreenmailContainer({username: HANDLE,password: PASSWORD,});+ await updateConfigVariable({+ input: {+ key: 'OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS',+ value: [greenmail.host],+ },+ });+const { data } = await saveImapSmtpCaldavAccount({input: {handle: HANDLE,@@ -67,7 +70,7 @@ describe('IMAP/SMTP outbound messaging (integration)', () => {afterAll(async () => {await updateConfigVariable({- input: { key: 'OUTBOUND_HTTP_SAFE_MODE_ENABLED', value: true },+ input: { key: 'OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS', value: [] },}).catch(() => undefined);if (connectedAccountId) {diff --git a/packages/twenty-server/test/integration/metadata/suites/developers/webhooks.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/developers/webhooks.integration-spec.tsindex b6ccfa7fb6c..cca67c7fcba 100644--- a/packages/twenty-server/test/integration/metadata/suites/developers/webhooks.integration-spec.ts+++ b/packages/twenty-server/test/integration/metadata/suites/developers/webhooks.integration-spec.ts@@ -272,7 +272,7 @@ describe('webhooksResolver (e2e)', () => {}});- it('should deliver webhook successfully when safe mode is disabled', async () => {+ it('should deliver webhook successfully when internal hosts are allowed', async () => {jest.useRealTimers();const receiver = await createWebhookReceiver(WEBHOOK_RECEIVER_PORT);@@ -281,8 +281,8 @@ describe('webhooksResolver (e2e)', () => {const createConfigResponse = await makeAdminPanelAPIRequest({query: CREATE_CONFIG_VARIABLE_MUTATION,variables: {- key: 'OUTBOUND_HTTP_SAFE_MODE_ENABLED',- value: false,+ key: 'OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS',+ value: ['*'],},});@@ -293,12 +293,12 @@ describe('webhooksResolver (e2e)', () => {const verifyConfig = await makeAdminPanelAPIRequest({query: GET_CONFIG_VARIABLE_QUERY,- variables: { key: 'OUTBOUND_HTTP_SAFE_MODE_ENABLED' },+ variables: { key: 'OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS' },});- expect(verifyConfig.body.data.getDatabaseConfigVariable.value).toBe(- false,- );+ expect(verifyConfig.body.data.getDatabaseConfigVariable.value).toEqual([+ '*',+ ]);expect(verifyConfig.body.data.getDatabaseConfigVariable.source).toBe('DATABASE',);@@ -346,7 +346,7 @@ describe('webhooksResolver (e2e)', () => {await receiver.close();await makeAdminPanelAPIRequest({query: DELETE_CONFIG_VARIABLE_MUTATION,- variables: { key: 'OUTBOUND_HTTP_SAFE_MODE_ENABLED' },+ variables: { key: 'OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS' },}).catch(() => {});jest.useFakeTimers();}diff --git a/packages/twenty-server/test/integration/usage-limit/webhook-rate-limit.integration-spec.ts b/packages/twenty-server/test/integration/usage-limit/webhook-rate-limit.integration-spec.tsindex a90dcd01b6b..95f60939a2f 100644--- a/packages/twenty-server/test/integration/usage-limit/webhook-rate-limit.integration-spec.ts+++ b/packages/twenty-server/test/integration/usage-limit/webhook-rate-limit.integration-spec.ts@@ -97,7 +97,7 @@ describe('Webhook rate limiting', () => {await makeAdminPanelAPIRequest({query: CREATE_CONFIG_VARIABLE_MUTATION,- variables: { key: 'OUTBOUND_HTTP_SAFE_MODE_ENABLED', value: false },+ variables: { key: 'OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS', value: ['*'] },});await featureFlagRepository.delete({@@ -161,7 +161,7 @@ describe('Webhook rate limiting', () => {});await makeAdminPanelAPIRequest({query: DELETE_CONFIG_VARIABLE_MUTATION,- variables: { key: 'OUTBOUND_HTTP_SAFE_MODE_ENABLED' },+ variables: { key: 'OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS' },}).catch(() => {});await invalidateWorkspaceCaches();diff --git a/packages/twenty-server/test/integration/utils/connect-dovecot-imap-account.util.ts b/packages/twenty-server/test/integration/utils/connect-dovecot-imap-account.util.tsindex a3dd19b9d26..52cd9ad24f5 100644--- a/packages/twenty-server/test/integration/utils/connect-dovecot-imap-account.util.ts+++ b/packages/twenty-server/test/integration/utils/connect-dovecot-imap-account.util.ts@@ -25,7 +25,7 @@ export const connectDovecotImapAccount = async ({password: string;}): Promise<DovecotImapAccount> => {await updateConfigVariable({- input: { key: 'OUTBOUND_HTTP_SAFE_MODE_ENABLED', value: false },+ input: { key: 'OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS', value: ['*'] },});const dovecot = await startDovecotContainer({ password });diff --git a/packages/twenty-server/test/integration/workflow-actions/create-calendar-event/drivers/caldav.integration-spec.ts b/packages/twenty-server/test/integration/workflow-actions/create-calendar-event/drivers/caldav.integration-spec.tsindex e362f0cfefd..d2796e692bb 100644--- a/packages/twenty-server/test/integration/workflow-actions/create-calendar-event/drivers/caldav.integration-spec.ts+++ b/packages/twenty-server/test/integration/workflow-actions/create-calendar-event/drivers/caldav.integration-spec.ts@@ -30,7 +30,7 @@ describe('CREATE_CALENDAR_EVENT workflow action on CalDAV (integration)', () =>// The CalDAV driver wraps its fetch in the SSRF guard, which rejects the// container's private address before the request is made.await updateConfigVariable({- input: { key: 'OUTBOUND_HTTP_SAFE_MODE_ENABLED', value: false },+ input: { key: 'OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS', value: ['*'] },});radicale = await startRadicaleContainer({@@ -74,7 +74,7 @@ describe('CREATE_CALENDAR_EVENT workflow action on CalDAV (integration)', () =>afterAll(async () => {await updateConfigVariable({- input: { key: 'OUTBOUND_HTTP_SAFE_MODE_ENABLED', value: true },+ input: { key: 'OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS', value: [] },}).catch(() => undefined);if (isNonEmptyString(connectedAccountId)) {diff --git a/packages/twenty-server/test/integration/workflow-actions/draft-email/drivers/imap-smtp.integration-spec.ts b/packages/twenty-server/test/integration/workflow-actions/draft-email/drivers/imap-smtp.integration-spec.tsindex d573200ebab..08df14f1f85 100644--- a/packages/twenty-server/test/integration/workflow-actions/draft-email/drivers/imap-smtp.integration-spec.ts+++ b/packages/twenty-server/test/integration/workflow-actions/draft-email/drivers/imap-smtp.integration-spec.ts@@ -62,7 +62,7 @@ describe('DRAFT_EMAIL workflow action on IMAP (integration)', () => {beforeAll(async () => {await updateConfigVariable({- input: { key: 'OUTBOUND_HTTP_SAFE_MODE_ENABLED', value: false },+ input: { key: 'OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS', value: ['*'] },});greenmail = await startGreenmailContainer({@@ -105,7 +105,7 @@ describe('DRAFT_EMAIL workflow action on IMAP (integration)', () => {afterAll(async () => {await updateConfigVariable({- input: { key: 'OUTBOUND_HTTP_SAFE_MODE_ENABLED', value: true },+ input: { key: 'OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS', value: [] },}).catch(() => undefined);if (isNonEmptyString(connectedAccountId)) {diff --git a/packages/twenty-server/test/integration/workflow-actions/send-email/drivers/imap-smtp.integration-spec.ts b/packages/twenty-server/test/integration/workflow-actions/send-email/drivers/imap-smtp.integration-spec.tsindex c5533819b0e..f899e323704 100644--- a/packages/twenty-server/test/integration/workflow-actions/send-email/drivers/imap-smtp.integration-spec.ts+++ b/packages/twenty-server/test/integration/workflow-actions/send-email/drivers/imap-smtp.integration-spec.ts@@ -27,7 +27,7 @@ describe('SEND_EMAIL workflow action on SMTP (integration)', () => {beforeAll(async () => {await updateConfigVariable({- input: { key: 'OUTBOUND_HTTP_SAFE_MODE_ENABLED', value: false },+ input: { key: 'OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS', value: ['*'] },});greenmail = await startGreenmailContainer({@@ -70,7 +70,7 @@ describe('SEND_EMAIL workflow action on SMTP (integration)', () => {afterAll(async () => {await updateConfigVariable({- input: { key: 'OUTBOUND_HTTP_SAFE_MODE_ENABLED', value: true },+ input: { key: 'OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS', value: [] },}).catch(() => undefined);if (isNonEmptyString(connectedAccountId)) {