Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(webhook): reject registration URLs that embed credentials
Yudhi Armyndharisc048e253c713
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex fa9a92e67..b4b1a9b23 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -4522,7 +4522,7 @@ Create a webhook for the session.`secret` and `headers` are deliberately excluded from the response. `active` defaults to `true`, `lastTriggeredAt` is `null` on create.-**Errors:** `400` validation failure, unknown body field (whitelist), SSRF URL rejection, or the per-session webhook limit (`WEBHOOK_MAX_PER_SESSION`, default 16 — delete an existing webhook before registering another; webhooks already above the cap are grandfathered and keep working) · `401` missing/invalid API key · `403` insufficient role · `404` session not found (message `"Session with id '<id>' not found"`)+**Errors:** `400` validation failure, unknown body field (whitelist), URL rejection (SSRF guard, or embedded credentials in the URL), or the per-session webhook limit (`WEBHOOK_MAX_PER_SESSION`, default 16 — delete an existing webhook before registering another; webhooks already above the cap are grandfathered and keep working) · `401` missing/invalid API key · `403` insufficient role · `404` session not found (message `"Session with id '<id>' not found"`)#### PUT /api/sessions/:sessionId/webhooks/:id@@ -4577,7 +4577,7 @@ Update a webhook. Partial — only fields present in the body are changed.Returns the saved entity; `secret` and `headers` excluded.-**Errors:** `400` validation failure, unknown body field (whitelist), or SSRF URL rejection · `401` missing/invalid API key · `403` insufficient role · `404` webhook not found in this session+**Errors:** `400` validation failure, unknown body field (whitelist), or URL rejection (SSRF guard, or embedded credentials in the URL) · `401` missing/invalid API key · `403` insufficient role · `404` webhook not found in this session#### POST /api/sessions/:sessionId/webhooks/:id/test@@ -6892,4 +6892,4 @@ When the queue is enabled, a non-2xx response, timeout (`WEBHOOK_TIMEOUT`, defau### SSRF guard on registration-Webhook URLs are validated at **registration time**, not just at delivery. When SSRF protection is enabled (the default), creating or updating a webhook with a URL that resolves to a private/internal/loopback address is rejected synchronously with `400 Bad Request` instead of failing silently later at delivery. The `SSRF_ALLOWED_HOSTS` escape-hatch applies equally to registration and delivery. Operator-supplied custom headers that target reserved names (`Content-Type` or any `X-OpenWA-*`) are stripped, so a webhook config cannot forge the signature, event, or idempotency headers.+Webhook URLs are validated at **registration time**, not just at delivery. When SSRF protection is enabled (the default), creating or updating a webhook with a URL that resolves to a private/internal/loopback address is rejected synchronously with `400 Bad Request` instead of failing silently later at delivery. The `SSRF_ALLOWED_HOSTS` escape-hatch applies equally to registration and delivery. Independently of the SSRF flag, a URL embedding credentials (`https://user:pass@host/hook`) is rejected with `400` — such credentials would otherwise be persisted and echoed into delivery logs and dead-letter rows. Operator-supplied custom headers that target reserved names (`Content-Type` or any `X-OpenWA-*`) are stripped, so a webhook config cannot forge the signature, event, or idempotency headers.diff --git a/src/modules/webhook/webhook.service.spec.ts b/src/modules/webhook/webhook.service.spec.tsindex b3c6d5bab..c5b6cc24e 100644--- a/src/modules/webhook/webhook.service.spec.ts+++ b/src/modules/webhook/webhook.service.spec.ts@@ -225,6 +225,39 @@ describe('WebhookService', () => {}});+ // ── URLs must not embed credentials ───────────────────++ it('rejects a webhook URL carrying userinfo at registration', async () => {+ await expect(service.create('sess-1', { url: 'https://user:[email protected]/hook' })).rejects.toMatchObject({+ status: 400,+ });+ await expect(service.create('sess-1', { url: 'https://user:[email protected]/hook' })).rejects.toThrow(+ /must not contain credentials/,+ );+ expect(repository.create).not.toHaveBeenCalled();+ expect(repository.save).not.toHaveBeenCalled();+ });++ it('rejects a username-only userinfo URL as well', async () => {+ await expect(service.create('sess-1', { url: 'https://[email protected]/hook' })).rejects.toThrow(+ /must not contain credentials/,+ );+ });++ it('rejects userinfo URLs even when SSRF protection is explicitly disabled', async () => {+ const origProtect = process.env.WEBHOOK_SSRF_PROTECT;+ process.env.WEBHOOK_SSRF_PROTECT = 'false';+ try {+ await expect(service.create('sess-1', { url: 'https://user:[email protected]/hook' })).rejects.toMatchObject({+ status: 400,+ });+ expect(repository.create).not.toHaveBeenCalled();+ } finally {+ if (origProtect === undefined) delete process.env.WEBHOOK_SSRF_PROTECT;+ else process.env.WEBHOOK_SSRF_PROTECT = origProtect;+ }+ });+// ── per-session fan-out cap ───────────────────────────it('rejects a NEW webhook with 400 once the session is at the per-session cap (default 16)', async () => {@@ -345,6 +378,17 @@ describe('WebhookService', () => {expect(result.url).toBe('https://new-url.com/hook');expect(result.events).toEqual(['message.received']); // unchanged});++ it('rejects a URL carrying userinfo on update and leaves the stored URL unchanged', async () => {+ const webhook = createMockWebhook();+ (repository.findOne as jest.Mock).mockResolvedValue(webhook);++ await expect(+ service.update('sess-1', 'wh-uuid-1', { url: 'https://user:[email protected]/hook' }),+ ).rejects.toMatchObject({ status: 400 });+ expect(webhook.url).toBe('https://example.com/webhook');+ expect(repository.save).not.toHaveBeenCalled();+ });});// ── delete ────────────────────────────────────────────────────────diff --git a/src/modules/webhook/webhook.service.ts b/src/modules/webhook/webhook.service.tsindex b91d41065..b099c3ff5 100644--- a/src/modules/webhook/webhook.service.ts+++ b/src/modules/webhook/webhook.service.ts@@ -234,6 +234,18 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {* SSRF flag + SSRF_ALLOWED_HOSTS escape-hatch as delivery. Maps the guard error to 400.*/private async validateWebhookUrl(url: string): Promise<void> {+ // Credentials embedded in the URL (https://user:pass@host/hook) would be persisted with the row+ // and echoed into delivery logs and dead-letter rows, and are never legitimate for a webhook+ // target — reject outright rather than strip-and-accept. Runs regardless of the SSRF flag.+ let parsed: URL | null = null;+ try {+ parsed = new URL(url);+ } catch {+ // Unparseable: @IsUrl on the DTO (and the SSRF guard when enabled) owns that rejection.+ }+ if (parsed && (parsed.username !== '' || parsed.password !== '')) {+ throw new BadRequestException('Webhook URL must not contain credentials (userinfo)');+ }if (!isSsrfProtectionEnabled()) return;try {await assertSafeFetchUrl(url);diff --git a/test/webhooks.e2e-spec.ts b/test/webhooks.e2e-spec.tsindex a6cdcab26..af440ff3c 100644--- a/test/webhooks.e2e-spec.ts+++ b/test/webhooks.e2e-spec.ts@@ -250,6 +250,18 @@ describe('Webhooks (e2e)', () => {// ── registration validation ───────────────────────────────────────describe('registration validation', () => {+ it('rejects a URL embedding credentials (userinfo) even with SSRF protection off', async () => {+ const session = await nextSession();+ // This suite runs with WEBHOOK_SSRF_PROTECT=false, so a 400 here proves the credential+ // rejection is not tied to the SSRF flag.+ const res = await request(app.getHttpServer())+ .post(`/api/sessions/${session}/webhooks`)+ .set('X-API-Key', apiKey)+ .send({ url: 'https://user:[email protected]/hook' })+ .expect(400);+ expect((res.body as { message: string }).message).toMatch(/must not contain credentials/);+ });+it('rejects an internal URL with 400 when SSRF protection is on', async () => {const session = await nextSession();// Self-contained: turn protection on and clear any ambient SSRF_ALLOWED_HOSTS (a dev .env may