Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(ssrf): settle unread body when a redirect is refused (#887)
Yudhi Armyndharisb5d8947fe8bd
diff --git a/src/common/security/ssrf-guard.spec.ts b/src/common/security/ssrf-guard.spec.tsindex 41f2a5f65..443036859 100644--- a/src/common/security/ssrf-guard.spec.ts+++ b/src/common/security/ssrf-guard.spec.ts@@ -368,6 +368,26 @@ describe('withSafeFetch (guarded + pinned fetch)', () => {).rejects.toThrow('HTTP 500');expect(cancel).toHaveBeenCalledTimes(1);});++ it('cancels an unread body when the response is a refused redirect (#887)', async () => {+ // assertNoRedirect throws before `use` runs; the settle must still happen so a refused 3xx+ // cannot reach dispatcher.destroy() with an unread body either.+ const cancel = jest.fn().mockResolvedValue(undefined);+ (dnsPromises.lookup as jest.Mock).mockResolvedValueOnce([{ address: '93.184.216.34', family: 4 }]);+ (undiciFetch as jest.Mock).mockResolvedValue({+ status: 302,+ type: 'basic',+ bodyUsed: false,+ body: { cancel },+ });+ const use = jest.fn();++ await expect(withSafeFetch('https://example.com/hook', {}, use, { guard: true })).rejects.toThrow(+ SsrfBlockedError,+ );+ expect(use).not.toHaveBeenCalled();+ expect(cancel).toHaveBeenCalledTimes(1);+ });});describe('validatingLookup (per-hop redirect guard)', () => {diff --git a/src/common/security/ssrf-guard.ts b/src/common/security/ssrf-guard.tsindex 5e9b1cb18..8e9f08f16 100644--- a/src/common/security/ssrf-guard.ts+++ b/src/common/security/ssrf-guard.ts@@ -448,8 +448,14 @@ export async function withSafeFetch<T>(const dispatcher = target ? new Agent({ connect: { lookup: pinnedLookup(target) } }) : undefined;try {const response = await undiciFetch(rawUrl, { ...init, redirect: 'manual', dispatcher });- assertNoRedirect(response, rawUrl);- return await useAndSettleBody(response, use);+ try {+ assertNoRedirect(response, rawUrl);+ return await use(response);+ } finally {+ // Settle even when assertNoRedirect throws: a refused 3xx still carries an unread body,+ // and tearing the dispatcher down with it open is the same crash path as #887.+ await settleUnreadResponseBody(response);+ }} finally {if (dispatcher) await dispatcher.destroy().catch(() => undefined);}