Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(security): fail loudly on redirects in the SSRF opt-out and pin allowlisted hosts
Yudhi Armyndharisfb6eb1610200
diff --git a/.env.example b/.env.exampleindex 3183430f9..675260f8b 100644--- a/.env.example+++ b/.env.example@@ -389,6 +389,10 @@ WEBHOOK_RETRY_DELAY=5000 # Delay between retries in ms# refused (at registration AND delivery) and redirects are not followed.# (Server-side media-by-URL fetches are ALWAYS SSRF-guarded, regardless of this flag.)WEBHOOK_SSRF_PROTECT=true+# Redirect handling when SSRF protection is DISABLED (WEBHOOK_SSRF_PROTECT=false): fail loudly on+# 3xx ('error', the default) or follow them ('true'). Disabling the guard is not opting into+# chasing redirects to arbitrary hosts — set this only if a receiver legitimately redirects.+WEBHOOK_SSRF_REDIRECTS=false# Expose the FULL sender `contact` field set (id, number, shortName, business flags, isBlocked,# labels, …) on the message.received webhook + websocket payload. OFF by default — the payload keepsdiff --git a/src/common/security/ssrf-guard.spec.ts b/src/common/security/ssrf-guard.spec.tsindex 9f54d4e69..a0ebf2a21 100644--- a/src/common/security/ssrf-guard.spec.ts+++ b/src/common/security/ssrf-guard.spec.ts@@ -128,6 +128,7 @@ describe('assertSafeFetchUrl — SSRF_ALLOWED_HOSTS escape-hatch', () => {it('allows an internal host that is explicitly allowlisted (case-insensitive)', async () => {process.env.SSRF_ALLOWED_HOSTS = 'Localhost, minio';+ (dnsPromises.lookup as jest.Mock).mockResolvedValue([{ address: '127.0.0.1', family: 4 }]);await expect(assertSafeFetchUrl('http://localhost:9000/bucket/x.png')).resolves.toBeUndefined();await expect(assertSafeFetchUrl('http://minio:9000/x.png')).resolves.toBeUndefined();});@@ -200,9 +201,15 @@ describe('resolveSafeFetchTarget', () => {await expect(resolveSafeFetchTarget('https://8.8.8.8/hook')).resolves.toBeNull();});- it('returns null for an allowlisted host (trusted, no pin needed)', async () => {+ it('pins an allowlisted host to its resolved addresses (exemption from the BLOCK check, not from pinning)', async () => {+ // The rebinding window: validation resolves the name, then fetch re-resolves — and a rebind+ // flips the second answer. Allowlisted hosts now return their resolved addresses so the+ // connection is pinned to exactly what was vetted, like every other DNS name.process.env.SSRF_ALLOWED_HOSTS = 'minio';- await expect(resolveSafeFetchTarget('http://minio:9000/x.png')).resolves.toBeNull();+ (dnsPromises.lookup as jest.Mock).mockResolvedValueOnce([{ address: '10.0.0.9', family: 4 }]);+ await expect(resolveSafeFetchTarget('http://minio:9000/x.png')).resolves.toEqual([+ { address: '10.0.0.9', family: 4 },+ ]);});it('throws for a blocked literal address', async () => {@@ -291,10 +298,24 @@ describe('withSafeFetch (guarded + pinned fetch)', () => {expect(result).toBe('ok');const [, init] = (undiciFetch as jest.Mock).mock.calls[0] as [string, { redirect: string; dispatcher: unknown }];- expect(init.redirect).toBe('follow');+ // disabling SSRF protection is not opting into redirect-chasing — fail loudly instead.+ expect(init.redirect).toBe('error');expect(init.dispatcher).toBeUndefined();});+ it('an unguarded fetch follows redirects ONLY with WEBHOOK_SSRF_REDIRECTS=true', async () => {+ (undiciFetch as jest.Mock).mockResolvedValue({ status: 200, type: 'basic' });+ const use = jest.fn(() => 'ok');+ process.env.WEBHOOK_SSRF_REDIRECTS = 'true';+ try {+ await withSafeFetch('http://10.0.0.5/hook', {}, use, { guard: false });+ const [, init] = (undiciFetch as jest.Mock).mock.calls[0] as [string, { redirect: string }];+ expect(init.redirect).toBe('follow');+ } finally {+ delete process.env.WEBHOOK_SSRF_REDIRECTS;+ }+ });+it('follows redirects hop-by-hop, re-validating each target and delivering the final 200 (download path)', async () => {// GitHub Releases 302 to a CDN; the download path must follow (not refuse) redirects — but by// fetching each hop with `redirect: 'manual'` and re-running resolveSafeFetchTarget on thediff --git a/src/common/security/ssrf-guard.ts b/src/common/security/ssrf-guard.tsindex 8ddd19389..5e0e25593 100644--- a/src/common/security/ssrf-guard.ts+++ b/src/common/security/ssrf-guard.ts@@ -332,7 +332,10 @@ export async function resolveSafeFetchTarget(const host = url.hostname.replace(/^\[|\]$/g, ''); // strip IPv6 bracketsif (getAllowedHosts().has(host.toLowerCase())) {- return null; // explicitly allowlisted internal target+ // Allowlisted = exempt from the BLOCK check, not from pinning: the operator opted into THIS+ // host, so freeze the connection to the addresses it resolves to right now. Returning null+ // here left a rebinding window where a name could flip to a different address after validation.+ return lookupWithDeadline(host, signal);}if (isIPv4(host) || isIPv6(host)) {@@ -470,7 +473,11 @@ export async function withSafeFetch<T>(): Promise<T> {const guard = opts.guard ?? true;if (!guard) {- return useAndSettleBody(await undiciFetch(rawUrl, { ...init, redirect: 'follow' }), use);+ // Redirect-following is a separate decision from SSRF protection: an operator who disabled the+ // guard (closed network) did not opt into chasing 3xx chains to arbitrary hosts. Fail loudly+ // unless WEBHOOK_SSRF_REDIRECTS=true says otherwise.+ const follow = process.env.WEBHOOK_SSRF_REDIRECTS === 'true';+ return useAndSettleBody(await undiciFetch(rawUrl, { ...init, redirect: follow ? 'follow' : 'error' }), use);}if (opts.followRedirects) {diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex f73a5afd8..50281c637 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -39,6 +39,18 @@ import { LabelNotFoundError } from '../../common/errors/label-not-found.error';import { SsrfBlockedError } from '../../common/security/ssrf-guard';import { fetch as undiciFetch } from 'undici';+// Allowlisted hosts are PINNED to their DNS answer (ssrf-guard pins allowlisted hosts to their DNS answers), so the specs that exercise+// the SSRF_ALLOWED_HOSTS escape-hatch need a deterministic resolver. Default answers are PUBLIC+// addresses — the non-allowlisted paths keep behaving exactly as they did with the real resolver.+jest.mock('dns/promises', () => {+ const actual = jest.requireActual<typeof import('dns/promises')>('dns/promises');+ return {+ __esModule: true,+ ...actual,+ lookup: jest.fn(() => Promise.resolve([{ address: '93.184.216.34', family: 4 }])),+ };+});+// loadRemoteMedia now fetches bytes through the SSRF-pinned path (undici fetch), then builds the// MessageMedia locally — so mock undici fetch, not MessageMedia.fromUrl.jest.mock('undici', () => {diff --git a/src/modules/webhook/dto/webhook-secret-entropy.spec.ts b/src/modules/webhook/dto/webhook-secret-entropy.spec.tsindex 88e4f4cfb..f977fe4d5 100644--- a/src/modules/webhook/dto/webhook-secret-entropy.spec.ts+++ b/src/modules/webhook/dto/webhook-secret-entropy.spec.ts@@ -2,7 +2,7 @@ import { validate } from 'class-validator';import { CreateWebhookDto } from './webhook.dto';/**- * the HMAC secret signs every delivery this webhook fires. A short secret is recoverable+ * The HMAC secret signs every delivery this webhook fires. A short secret is recoverable* from one observed signature, which turns the signature from an integrity check into a forging* tool — 16 characters is the floor, not a recommendation.*/