Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(webhook): return 404 when creating a webhook for a missing session
Yudhi Armyndharis2ce6df396d96
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 56061a151..fa9a92e67 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -4469,7 +4469,7 @@ Create a webhook for the session.| Name | Type | Description || --------- | ------ | ------------------------------------------------------------------------------------------------------------------------ |-| sessionId | string | Session the webhook is scoped to; stored as `webhook.sessionId`. No session-existence check is performed at create time. |+| sessionId | string | Session the webhook is scoped to; stored as `webhook.sessionId`. The session must exist — an unknown id is refused with `404` at create time. |**Request body** — `CreateWebhookDto`@@ -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+**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"`)#### PUT /api/sessions/:sessionId/webhooks/:iddiff --git a/openapi.json b/openapi.jsonindex b1afed295..de97fa68a 100644--- a/openapi.json+++ b/openapi.json@@ -1642,6 +1642,9 @@}}}+ },+ "404": {+ "description": "Session not found"}},"summary": "Create a webhook for the session",diff --git a/src/modules/webhook/delivery-failures-scope.spec.ts b/src/modules/webhook/delivery-failures-scope.spec.tsindex e4f086803..c3d0b2167 100644--- a/src/modules/webhook/delivery-failures-scope.spec.ts+++ b/src/modules/webhook/delivery-failures-scope.spec.ts@@ -20,7 +20,7 @@ describe('WebhookService.listDeliveryFailures session scoping', () => {await ds.initialize();const failureRepo = ds.getRepository(WebhookDeliveryFailure);const cfg = { get: () => false };- service = new WebhookService({} as never, failureRepo, cfg as never, {} as never, undefined);+ service = new WebhookService({} as never, failureRepo, {} as never, cfg as never, {} as never, undefined);for (const sessionId of ['sessA', 'sessB']) {await failureRepo.save(failureRepo.create({diff --git a/src/modules/webhook/webhook-session-scope.spec.ts b/src/modules/webhook/webhook-session-scope.spec.tsindex c231e8f4a..495129be7 100644--- a/src/modules/webhook/webhook-session-scope.spec.ts+++ b/src/modules/webhook/webhook-session-scope.spec.ts@@ -25,8 +25,9 @@ describe('WebhookService session-scoped access', () => {await ds.initialize();const repo = ds.getRepository(Webhook);const cfg = { get: () => false }; // queue.enabled = false- // 2nd arg is the delivery-failure repo, unused by the scoped read/update/delete paths under test.- service = new WebhookService(repo, {} as never, cfg as never, {} as never, undefined);+ // 2nd arg is the delivery-failure repo and 3rd the session repo — the scoped read/update/delete+ // paths under test never touch them (only create() checks session existence).+ service = new WebhookService(repo, {} as never, {} as never, cfg as never, {} as never, undefined);const sessions = ds.getRepository(Session);for (const id of ['sessA', 'sessB']) {diff --git a/src/modules/webhook/webhook.controller.ts b/src/modules/webhook/webhook.controller.tsindex a989d83ae..2261e7bf9 100644--- a/src/modules/webhook/webhook.controller.ts+++ b/src/modules/webhook/webhook.controller.ts@@ -19,6 +19,7 @@ export class WebhookController {description: 'Webhook created',type: WebhookResponseDto,})+ @ApiResponse({ status: 404, description: 'Session not found' })async create(@Param('sessionId') sessionId: string, @Body() dto: CreateWebhookDto): Promise<WebhookResponseDto> {return WebhookResponseDto.fromEntity(await this.webhookService.create(sessionId, dto));}diff --git a/src/modules/webhook/webhook.module.ts b/src/modules/webhook/webhook.module.tsindex bc18ad843..5d916621e 100644--- a/src/modules/webhook/webhook.module.ts+++ b/src/modules/webhook/webhook.module.ts@@ -2,6 +2,7 @@ import { Module, DynamicModule, Type } from '@nestjs/common';import { TypeOrmModule } from '@nestjs/typeorm';import { Webhook } from './entities/webhook.entity';import { WebhookDeliveryFailure } from './entities/webhook-delivery-failure.entity';+import { Session } from '../session/entities/session.entity';import { WebhookService } from './webhook.service';import { WebhookController } from './webhook.controller';import { WebhooksListController } from './webhooks-list.controller';@@ -18,7 +19,11 @@ if (process.env.QUEUE_ENABLED === 'true') {}@Module({- imports: [TypeOrmModule.forFeature([Webhook, WebhookDeliveryFailure], 'data'), EngineModule, ...queueModules],+ imports: [+ TypeOrmModule.forFeature([Webhook, WebhookDeliveryFailure, Session], 'data'),+ EngineModule,+ ...queueModules,+ ],controllers: [WebhookController, WebhooksListController],providers: [WebhookService],exports: [WebhookService],diff --git a/src/modules/webhook/webhook.service.spec.ts b/src/modules/webhook/webhook.service.spec.tsindex f28e153c3..b3c6d5bab 100644--- a/src/modules/webhook/webhook.service.spec.ts+++ b/src/modules/webhook/webhook.service.spec.ts@@ -53,6 +53,7 @@ describe('WebhookService', () => {let service: WebhookService;let repository: jest.Mocked<Partial<Repository<Webhook>>>;let failureRepository: jest.Mocked<Partial<Repository<WebhookDeliveryFailure>>>;+ let sessionRepository: jest.Mocked<Partial<Repository<Session>>>;let configService: jest.Mocked<Partial<ConfigService>>;let hookManager: jest.Mocked<Partial<HookManager>>;let webhookQueue: jest.Mocked<Record<string, jest.Mock>>;@@ -75,6 +76,11 @@ describe('WebhookService', () => {delete: jest.fn().mockResolvedValue({ affected: 0 }),};+ sessionRepository = {+ // Default to an existing session; the 404 cases below override this per test.+ exists: jest.fn().mockResolvedValue(true),+ };+configService = {get: jest.fn().mockImplementation(<T>(key: string, def?: T): T | boolean | number => {if (key === 'queue.enabled') return false;@@ -109,6 +115,7 @@ describe('WebhookService', () => {WebhookService,{ provide: getRepositoryToken(Webhook, 'data'), useValue: repository },{ provide: getRepositoryToken(WebhookDeliveryFailure, 'data'), useValue: failureRepository },+ { provide: getRepositoryToken(Session, 'data'), useValue: sessionRepository },{ provide: ConfigService, useValue: configService },{ provide: HookManager, useValue: hookManager },{ provide: LidMappingStoreService, useValue: lidStore },@@ -162,6 +169,31 @@ describe('WebhookService', () => {);});+ // ── session existence ─────────────────────────────────++ it('returns 404 when the session does not exist, without persisting anything', async () => {+ (sessionRepository.exists as jest.Mock).mockResolvedValue(false);++ await expect(service.create('sess-missing', { url: 'https://example.com/webhook' })).rejects.toThrow(+ NotFoundException,+ );+ await expect(service.create('sess-missing', { url: 'https://example.com/webhook' })).rejects.toThrow(+ "Session with id 'sess-missing' not found",+ );+ expect(repository.create).not.toHaveBeenCalled();+ expect(repository.save).not.toHaveBeenCalled();+ expect(repository.count).not.toHaveBeenCalled(); // existence is checked before the fan-out cap+ });++ it('checks session existence against the sessions table and creates when present', async () => {+ const webhook = createMockWebhook();+ (repository.create as jest.Mock).mockReturnValue(webhook);+ (repository.save as jest.Mock).mockResolvedValue(webhook);++ await expect(service.create('sess-1', { url: 'https://example.com/webhook' })).resolves.toBeDefined();+ expect(sessionRepository.exists).toHaveBeenCalledWith({ where: { id: 'sess-1' } });+ });+// ── validate URL at registration, default-on ──────────it('rejects an internal webhook URL at registration with 400 and a generic message (no IP leak)', async () => {@@ -1424,6 +1456,7 @@ describe('WebhookService', () => {WebhookService,{ provide: getRepositoryToken(Webhook, 'data'), useValue: repository },{ provide: getRepositoryToken(WebhookDeliveryFailure, 'data'), useValue: failureRepository },+ { provide: getRepositoryToken(Session, 'data'), useValue: sessionRepository },{ provide: ConfigService, useValue: { get: jest.fn().mockImplementation(configGet) } },{ provide: HookManager, useValue: hookManager },{ provide: getQueueToken(QUEUE_NAMES.WEBHOOK), useValue: webhookQueue },@@ -1515,6 +1548,7 @@ describe('WebhookService', () => {WebhookService,{ provide: getRepositoryToken(Webhook, 'data'), useValue: repository },{ provide: getRepositoryToken(WebhookDeliveryFailure, 'data'), useValue: failureRepository },+ { provide: getRepositoryToken(Session, 'data'), useValue: sessionRepository },{provide: ConfigService,useValue: {@@ -1575,6 +1609,7 @@ describe('WebhookService', () => {WebhookService,{ provide: getRepositoryToken(Webhook, 'data'), useValue: repository },{ provide: getRepositoryToken(WebhookDeliveryFailure, 'data'), useValue: failureRepository },+ { provide: getRepositoryToken(Session, 'data'), useValue: sessionRepository },{provide: ConfigService,useValue: {diff --git a/src/modules/webhook/webhook.service.ts b/src/modules/webhook/webhook.service.tsindex 2561db458..b91d41065 100644--- a/src/modules/webhook/webhook.service.ts+++ b/src/modules/webhook/webhook.service.ts@@ -15,6 +15,7 @@ import * as crypto from 'crypto';import { setTimeout } from 'node:timers/promises';import { Webhook } from './entities/webhook.entity';import { WebhookDeliveryFailure } from './entities/webhook-delivery-failure.entity';+import { Session } from '../session/entities/session.entity';import { recordWebhookDeliveryFailure, statusCodeFromError } from './utils/record-delivery-failure';import { CreateWebhookDto, UpdateWebhookDto } from './dto';import { createLogger } from '../../common/services/logger.service';@@ -115,6 +116,8 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {private readonly webhookRepository: Repository<Webhook>,@InjectRepository(WebhookDeliveryFailure, 'data')private readonly failureRepository: Repository<WebhookDeliveryFailure>,+ @InjectRepository(Session, 'data')+ private readonly sessionRepository: Repository<Session>,private readonly configService: ConfigService,private readonly hookManager: HookManager,@Optional()@@ -245,6 +248,12 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {}async create(sessionId: string, dto: CreateWebhookDto): Promise<Webhook> {+ // The webhooks.sessionId FK makes a missing session surface as a driver error (500) at save time;+ // check first so the caller gets a truthful 404 for a session that does not exist.+ const sessionExists = await this.sessionRepository.exists({ where: { id: sessionId } });+ if (!sessionExists) {+ throw new NotFoundException(`Session with id '${sessionId}' not found`);+ }await this.validateWebhookUrl(dto.url);// Per-session fan-out cap. Soft by design: a concurrent create can race the count check — the// cap bounds amplification, it is not a hard invariant. Webhooks already above the cap are leftdiff --git a/test/webhooks.e2e-spec.ts b/test/webhooks.e2e-spec.tsindex 3929e519c..a6cdcab26 100644--- a/test/webhooks.e2e-spec.ts+++ b/test/webhooks.e2e-spec.ts@@ -148,6 +148,14 @@ describe('Webhooks (e2e)', () => {expect(dto.headers).toBeUndefined();});+ it('returns 404 when creating a webhook for a session that does not exist', async () => {+ await request(app.getHttpServer())+ .post('/api/sessions/no-such-session/webhooks')+ .set('X-API-Key', apiKey)+ .send({ url: receiverUrl, events: ['*'] })+ .expect(404);+ });+it('lists webhooks for a session', async () => {const session = await nextSession();const created = await createWebhook(session);