Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(webhook): scope by-id ops and GET /webhooks to the session (close cross-session IDOR) (#323)
Yudhi Armyndharis1b0ba93ae53b
diff --git a/src/modules/webhook/webhook-session-scope.spec.ts b/src/modules/webhook/webhook-session-scope.spec.tsnew file mode 100644index 000000000..012c90b1a--- /dev/null+++ b/src/modules/webhook/webhook-session-scope.spec.ts@@ -0,0 +1,82 @@+// F-05 — webhook by-id operations (findOne/update/delete/test) must be scoped to the URL+// :sessionId, and GET /webhooks must be scoped to the key's allowedSessions. Without it, an+// OPERATOR key for one session can read/edit/delete/redirect/fire another session's webhook,+// and enumerate every session's webhook URLs. These run against a real in-memory DB so the+// scoping is exercised end-to-end, not asserted on a mock's WHERE clause.+import { DataSource } from 'typeorm';+import { NotFoundException } from '@nestjs/common';+import { WebhookService } from './webhook.service';+import { Webhook } from './entities/webhook.entity';+import { Session, SessionStatus } from '../session/entities/session.entity';++describe('WebhookService session-scoped access (F-05)', () => {+ let ds: DataSource;+ let service: WebhookService;+ let whA: Webhook;+ let whB: Webhook;++ beforeEach(async () => {+ ds = new DataSource({+ type: 'sqlite',+ database: ':memory:',+ entities: [Session, Webhook],+ synchronize: true,+ });+ await ds.initialize();+ const repo = ds.getRepository(Webhook);+ const cfg = { get: () => false }; // queue.enabled = false+ service = new WebhookService(repo, cfg as never, {} as never, undefined);++ const sessions = ds.getRepository(Session);+ for (const id of ['sessA', 'sessB']) {+ await sessions.save(sessions.create({ id, name: id, status: SessionStatus.READY, config: {} }));+ }+ whA = await repo.save(+ repo.create({+ sessionId: 'sessA',+ url: 'https://a.example/hook',+ events: ['message.received'],+ headers: {},+ retryCount: 3,+ }),+ );+ whB = await repo.save(+ repo.create({+ sessionId: 'sessB',+ url: 'https://b.example/hook',+ events: ['message.received'],+ headers: {},+ retryCount: 3,+ }),+ );+ });++ afterEach(async () => {+ await ds.destroy();+ });++ it('findOne returns a webhook only for its owning session', async () => {+ expect((await service.findOne('sessA', whA.id)).id).toBe(whA.id);+ await expect(service.findOne('sessA', whB.id)).rejects.toThrow(NotFoundException);+ });++ it('update refuses (404) a webhook owned by another session and does not mutate it', async () => {+ await expect(service.update('sessA', whB.id, { url: 'https://evil.example/x' })).rejects.toThrow(NotFoundException);+ expect((await ds.getRepository(Webhook).findOneByOrFail({ id: whB.id })).url).toBe('https://b.example/hook');+ });++ it('delete refuses (404) a webhook owned by another session and does not remove it', async () => {+ await expect(service.delete('sessA', whB.id)).rejects.toThrow(NotFoundException);+ expect(await ds.getRepository(Webhook).countBy({ id: whB.id })).toBe(1);+ });++ it('test refuses (404) to fire a webhook owned by another session', async () => {+ await expect(service.test('sessA', whB.id)).rejects.toThrow(NotFoundException);+ });++ it('findAll scopes to allowedSessions when set, returns all when unrestricted', async () => {+ expect((await service.findAll(['sessA'])).map(w => w.id)).toEqual([whA.id]);+ expect((await service.findAll(null)).map(w => w.id).sort()).toEqual([whA.id, whB.id].sort());+ expect((await service.findAll([])).length).toBe(2); // empty allowlist = unrestricted (matches the guard)+ });+});diff --git a/src/modules/webhook/webhook.controller.ts b/src/modules/webhook/webhook.controller.tsindex e4b240e57..3d37faf0b 100644--- a/src/modules/webhook/webhook.controller.ts+++ b/src/modules/webhook/webhook.controller.ts@@ -47,8 +47,8 @@ export class WebhookController {type: WebhookResponseDto,})@ApiResponse({ status: 404, description: 'Webhook not found' })- async findOne(@Param('id') id: string): Promise<WebhookResponseDto> {- return WebhookResponseDto.fromEntity(await this.webhookService.findOne(id));+ async findOne(@Param('sessionId') sessionId: string, @Param('id') id: string): Promise<WebhookResponseDto> {+ return WebhookResponseDto.fromEntity(await this.webhookService.findOne(sessionId, id));}@Put(':id')@@ -62,8 +62,12 @@ export class WebhookController {type: WebhookResponseDto,})@ApiResponse({ status: 404, description: 'Webhook not found' })- async update(@Param('id') id: string, @Body() dto: UpdateWebhookDto): Promise<WebhookResponseDto> {- return WebhookResponseDto.fromEntity(await this.webhookService.update(id, dto));+ async update(+ @Param('sessionId') sessionId: string,+ @Param('id') id: string,+ @Body() dto: UpdateWebhookDto,+ ): Promise<WebhookResponseDto> {+ return WebhookResponseDto.fromEntity(await this.webhookService.update(sessionId, id, dto));}@Post(':id/test')@@ -88,7 +92,7 @@ export class WebhookController {@ApiParam({ name: 'id', description: 'Webhook ID' })@ApiResponse({ status: 204, description: 'Webhook deleted' })@ApiResponse({ status: 404, description: 'Webhook not found' })- async delete(@Param('id') id: string): Promise<void> {- return this.webhookService.delete(id);+ async delete(@Param('sessionId') sessionId: string, @Param('id') id: string): Promise<void> {+ return this.webhookService.delete(sessionId, id);}}diff --git a/src/modules/webhook/webhook.service.spec.ts b/src/modules/webhook/webhook.service.spec.tsindex b89ddf9f2..9f47d197d 100644--- a/src/modules/webhook/webhook.service.spec.ts+++ b/src/modules/webhook/webhook.service.spec.ts@@ -189,14 +189,14 @@ describe('WebhookService', () => {const webhook = createMockWebhook();(repository.findOne as jest.Mock).mockResolvedValue(webhook);- const result = await service.findOne('wh-uuid-1');+ const result = await service.findOne('sess-1', 'wh-uuid-1');expect(result.id).toBe('wh-uuid-1');});it('should throw NotFoundException if not found', async () => {(repository.findOne as jest.Mock).mockResolvedValue(null);- await expect(service.findOne('nonexistent')).rejects.toThrow(NotFoundException);+ await expect(service.findOne('sess-1', 'nonexistent')).rejects.toThrow(NotFoundException);});});@@ -208,7 +208,7 @@ describe('WebhookService', () => {(repository.findOne as jest.Mock).mockResolvedValue(webhook);(repository.save as jest.Mock).mockImplementation(w => Promise.resolve(w));- const result = await service.update('wh-uuid-1', { url: 'https://new-url.com/hook' });+ const result = await service.update('sess-1', 'wh-uuid-1', { url: 'https://new-url.com/hook' });expect(result.url).toBe('https://new-url.com/hook');expect(result.events).toEqual(['message.received']); // unchanged@@ -223,7 +223,7 @@ describe('WebhookService', () => {(repository.findOne as jest.Mock).mockResolvedValue(webhook);(repository.remove as jest.Mock).mockResolvedValue(webhook);- await service.delete('wh-uuid-1');+ await service.delete('sess-1', 'wh-uuid-1');expect(repository.remove).toHaveBeenCalledWith(webhook);});diff --git a/src/modules/webhook/webhook.service.ts b/src/modules/webhook/webhook.service.tsindex 8eef241c2..1af4ebdd9 100644--- a/src/modules/webhook/webhook.service.ts+++ b/src/modules/webhook/webhook.service.ts@@ -1,6 +1,6 @@import { Injectable, NotFoundException, Optional, BadRequestException } from '@nestjs/common';import { InjectRepository } from '@nestjs/typeorm';-import { Repository } from 'typeorm';+import { FindManyOptions, In, Repository } from 'typeorm';import { ConfigService } from '@nestjs/config';import { InjectQueue } from '@nestjs/bullmq';import { Queue } from 'bullmq';@@ -93,22 +93,28 @@ export class WebhookService {});}- async findAll(): Promise<Webhook[]> {- return this.webhookRepository.find({- order: { createdAt: 'DESC' },- });+ async findAll(allowedSessions?: string[] | null): Promise<Webhook[]> {+ // A session-restricted key only sees its own sessions' webhooks; an unrestricted key+ // (null/empty allowlist, e.g. ADMIN) sees all — mirroring the ApiKeyGuard allowedSessions model.+ const options: FindManyOptions<Webhook> = { order: { createdAt: 'DESC' } };+ if (allowedSessions && allowedSessions.length > 0) {+ options.where = { sessionId: In(allowedSessions) };+ }+ return this.webhookRepository.find(options);}- async findOne(id: string): Promise<Webhook> {- const webhook = await this.webhookRepository.findOne({ where: { id } });+ async findOne(sessionId: string, id: string): Promise<Webhook> {+ // Scope by the URL's sessionId so one session cannot read/act on another's webhook by id.+ // A wrong-session id resolves to not-found (no cross-session existence oracle).+ const webhook = await this.webhookRepository.findOne({ where: { id, sessionId } });if (!webhook) {throw new NotFoundException(`Webhook with id '${id}' not found`);}return webhook;}- async update(id: string, dto: UpdateWebhookDto): Promise<Webhook> {- const webhook = await this.findOne(id);+ async update(sessionId: string, id: string, dto: UpdateWebhookDto): Promise<Webhook> {+ const webhook = await this.findOne(sessionId, id);if (dto.url !== undefined) {await this.validateWebhookUrl(dto.url);@@ -125,13 +131,13 @@ export class WebhookService {return this.webhookRepository.save(webhook);}- async delete(id: string): Promise<void> {- const webhook = await this.findOne(id);+ async delete(sessionId: string, id: string): Promise<void> {+ const webhook = await this.findOne(sessionId, id);await this.webhookRepository.remove(webhook);}async test(sessionId: string, webhookId: string): Promise<{ success: boolean; statusCode?: number; error?: string }> {- const webhook = await this.findOne(webhookId);+ const webhook = await this.findOne(sessionId, webhookId);const testPayload: WebhookPayload = {event: 'test',diff --git a/src/modules/webhook/webhooks-list.controller.ts b/src/modules/webhook/webhooks-list.controller.tsindex e86055b14..709d91256 100644--- a/src/modules/webhook/webhooks-list.controller.ts+++ b/src/modules/webhook/webhooks-list.controller.ts@@ -2,8 +2,8 @@ import { Controller, Get } from '@nestjs/common';import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';import { WebhookService } from './webhook.service';import { WebhookResponseDto } from './dto';-import { RequireRole } from '../auth/decorators/auth.decorators';-import { ApiKeyRole } from '../auth/entities/api-key.entity';+import { RequireRole, CurrentApiKey } from '../auth/decorators/auth.decorators';+import { ApiKey, ApiKeyRole } from '../auth/entities/api-key.entity';@ApiTags('webhooks')@Controller('webhooks')@@ -12,13 +12,15 @@ export class WebhooksListController {@Get()@RequireRole(ApiKeyRole.OPERATOR)- @ApiOperation({ summary: 'List all webhooks across all sessions' })+ @ApiOperation({ summary: 'List webhooks visible to the calling key (scoped to its allowed sessions)' })@ApiResponse({status: 200,- description: 'List of all webhooks',+ description: 'List of webhooks',type: [WebhookResponseDto],})- async findAll(): Promise<WebhookResponseDto[]> {- return WebhookResponseDto.fromEntities(await this.webhookService.findAll());+ async findAll(@CurrentApiKey() apiKey?: ApiKey): Promise<WebhookResponseDto[]> {+ // Scope to the key's allowedSessions so a session-restricted key cannot enumerate every+ // session's webhook URLs. A null/empty allowlist (e.g. ADMIN) still sees all.+ return WebhookResponseDto.fromEntities(await this.webhookService.findAll(apiKey?.allowedSessions));}}