Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(auth): fence bulk send and message forwarding by allowedChats

Lasitha Thilakarathnafe169482f130
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 56637279e..fd5a1da29 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- Message forwarding (`POST .../messages/forward`) and bulk message sending (`POST .../messages/bulk`) enforce the API key `allowedChats` allowlist: forward verifies both `fromChatId` and `toChatId`, while bulk send verifies every recipient in `messages[].chatId`, rejecting any unauthorized chat with `403` ([#1634](https://github.com/rmyndharis/OpenWA/issues/1634)).
- API keys carry an optional `allowedChats` allowlist next to `allowedSessions`: a curated set of chats (groups and/or contacts) a key may read and send to, `null`/empty meaning unrestricted and independent of the session scope. The `ApiKeyGuard` fences the chat in the path (`:chatId` / `:groupId` / `:contactId`) and, for sends, the `chatId` in the request body, rejecting an out-of-scope chat with `403`; a contact entry matches its resolved `@lid` form (and vice versa) through the lid mapping table, and an unmapped `@lid` stays outside the fence. A structural coverage spec pins the surface so a later endpoint cannot bypass it silently.
- Baileys inbound button, template quick-reply, list-row and native-flow replies arrive as `type: "text"` with a structured `button { id, text? }` on `message.received` (whatsapp-web.js still has no interactive reply fields). The REST chat-history route is whatsapp-web.js only and does not carry these fields. Thanks @gabrielmmoraes1999.
- Baileys inbound business prompts that offer clickable buttons (or list rows) also carry `buttons: [{ id, text }, …]` on `message.received` (URL/call CTAs are omitted — they cannot be clicked), so choices like Sim/Não are no longer flattened away into `body` only. Thanks @gabrielmmoraes1999.
diff --git a/src/modules/auth/chat-scope-coverage.spec.ts b/src/modules/auth/chat-scope-coverage.spec.ts
index 133e4554b..cb3ae8e62 100644
--- a/src/modules/auth/chat-scope-coverage.spec.ts
+++ b/src/modules/auth/chat-scope-coverage.spec.ts
@@ -29,14 +29,12 @@ const GUARD_CHAT_PARAMS = ['chatId', 'groupId', 'contactId'];
*/
const ALLOWLIST = new Map<string, string>([
['message.controller.ts :: getMessages', 'GET /messages without chatId: require chatId or filter the page'],
- ['message.controller.ts :: sendBulk', 'bulk send: each items[].chatId must be checked'],
- ['message.controller.ts :: forward', 'forward target travels as `to`, not chatId'],
]);
/**
- * Request DTOs that carry a chat id, mapped to how the id is named. `chatId` is fenced centrally by
- * the ApiKeyGuard's body rule; any other chat-targeting property (e.g. forward's `to`) is not, so a
- * `@Body()` of that shape is an offender until a handler checks it or it is allowlisted.
+ * Request DTOs that carry a chat id, mapped to how the id is named. `chatId`, forward chats, and
+ * bulk messages are fenced centrally by the ApiKeyGuard's body rule; any other chat-targeting
+ * property is not, so a `@Body()` of that shape is an offender until a handler checks it or it is allowlisted.
*/
function chatBearingDtoClasses(dir: string): Map<string, 'chatId' | 'other'> {
const out = new Map<string, 'chatId' | 'other'>();
@@ -53,8 +51,14 @@ function chatBearingDtoClasses(dir: string): Map<string, 'chatId' | 'other'> {
for (const chunk of source.split(/export\s+class\s+/).slice(1)) {
const name = /^([A-Za-z0-9_]+)/.exec(chunk)?.[1];
if (!name) continue;
- if (/\bchatId[!?]?\s*:/.test(chunk)) out.set(name, 'chatId');
- else if (/\b(?:to|recipient)[!?]?\s*:/.test(chunk)) out.set(name, 'other');
+ if (
+ /\b(?:chatId|toChatId|fromChatId)[!?]?\s*:/.test(chunk) ||
+ /\bmessages[!?]?\s*:\s*BulkMessageItemDto\[\]/.test(chunk)
+ ) {
+ out.set(name, 'chatId');
+ } else if (/\b(?:to|recipient)[!?]?\s*:/.test(chunk)) {
+ out.set(name, 'other');
+ }
}
}
};
@@ -101,12 +105,15 @@ function listControllerFiles(dir: string): string[] {
}
describe('chat-scoped keys cannot reach chats outside their allowedChats', () => {
- it('the guard fences both the path chat params and body.chatId', () => {
+ it('the guard fences both the path chat params, body.chatId, forward chats, and bulk send messages', () => {
const guard = readFileSync(join(__dirname, 'guards', 'api-key.guard.ts'), 'utf8');
for (const param of GUARD_CHAT_PARAMS) {
expect(guard).toContain(`request.params['${param}']`);
}
expect(guard).toMatch(/bodyChatId/);
+ expect(guard).toMatch(/fromChatId/);
+ expect(guard).toMatch(/toChatId/);
+ expect(guard).toMatch(/bodyMessages/);
});
it('flags a handler that reads @Query(chatId) without ChatScopeService', () => {
diff --git a/src/modules/auth/guards/api-key.guard.spec.ts b/src/modules/auth/guards/api-key.guard.spec.ts
index 1e77fe5bb..9ba87c4bc 100644
--- a/src/modules/auth/guards/api-key.guard.spec.ts
+++ b/src/modules/auth/guards/api-key.guard.spec.ts
@@ -33,12 +33,14 @@ function createMockContext(
headers: Record<string, string> = {},
params: Record<string, string> = {},
socketIp = '127.0.0.1',
+ body?: unknown,
): ExecutionContext {
const request = {
headers,
params,
ip: socketIp,
socket: { remoteAddress: socketIp },
+ body,
};
return {
@@ -410,4 +412,149 @@ describe('ApiKeyGuard', () => {
expect(authService.validateApiKey).toHaveBeenCalledWith('key', '203.0.113.50', undefined);
});
+
+ describe('chat scope enforcement', () => {
+ const ALLOWED_GROUP = '[email protected]';
+ const FORBIDDEN_GROUP = '[email protected]';
+ const ALLOWED_CONTACT = '[email protected]';
+ const FORBIDDEN_CONTACT = '[email protected]';
+
+ it('rejects a route param chat outside allowedChats with 403', async () => {
+ reflector.getAllAndOverride.mockReturnValueOnce(false).mockReturnValueOnce(undefined);
+ const apiKey = createMockApiKey({ allowedChats: [ALLOWED_GROUP] });
+ (authService.validateApiKey as jest.Mock).mockResolvedValue(apiKey);
+
+ const context = createMockContext({ 'x-api-key': 'key' }, { chatId: FORBIDDEN_GROUP });
+ await expect(guard.canActivate(context)).rejects.toThrow(
+ new ForbiddenException('API key not authorized for this chat'),
+ );
+ });
+
+ it('admits a route param chat inside allowedChats', async () => {
+ reflector.getAllAndOverride.mockReturnValueOnce(false).mockReturnValueOnce(undefined);
+ const apiKey = createMockApiKey({ allowedChats: [ALLOWED_GROUP] });
+ (authService.validateApiKey as jest.Mock).mockResolvedValue(apiKey);
+
+ const context = createMockContext({ 'x-api-key': 'key' }, { chatId: ALLOWED_GROUP });
+ expect(await guard.canActivate(context)).toBe(true);
+ });
+
+ it('rejects a single-send body.chatId outside allowedChats with 403', async () => {
+ reflector.getAllAndOverride.mockReturnValueOnce(false).mockReturnValueOnce(undefined);
+ const apiKey = createMockApiKey({ allowedChats: [ALLOWED_GROUP] });
+ (authService.validateApiKey as jest.Mock).mockResolvedValue(apiKey);
+
+ const context = createMockContext({ 'x-api-key': 'key' }, {}, '127.0.0.1', {
+ chatId: FORBIDDEN_GROUP,
+ text: 'hi',
+ });
+ await expect(guard.canActivate(context)).rejects.toThrow(
+ new ForbiddenException('API key not authorized for this chat'),
+ );
+ });
+
+ it('admits a single-send body.chatId inside allowedChats', async () => {
+ reflector.getAllAndOverride.mockReturnValueOnce(false).mockReturnValueOnce(undefined);
+ const apiKey = createMockApiKey({ allowedChats: [ALLOWED_GROUP] });
+ (authService.validateApiKey as jest.Mock).mockResolvedValue(apiKey);
+
+ const context = createMockContext({ 'x-api-key': 'key' }, {}, '127.0.0.1', {
+ chatId: ALLOWED_GROUP,
+ text: 'hi',
+ });
+ expect(await guard.canActivate(context)).toBe(true);
+ });
+
+ it('rejects message forward when fromChatId is outside allowedChats with 403', async () => {
+ reflector.getAllAndOverride.mockReturnValueOnce(false).mockReturnValueOnce(undefined);
+ const apiKey = createMockApiKey({ allowedChats: [ALLOWED_GROUP, ALLOWED_CONTACT] });
+ (authService.validateApiKey as jest.Mock).mockResolvedValue(apiKey);
+
+ const context = createMockContext({ 'x-api-key': 'key' }, {}, '127.0.0.1', {
+ fromChatId: FORBIDDEN_GROUP,
+ toChatId: ALLOWED_CONTACT,
+ messageId: 'm1',
+ });
+ await expect(guard.canActivate(context)).rejects.toThrow(
+ new ForbiddenException('API key not authorized for this chat'),
+ );
+ });
+
+ it('rejects message forward when toChatId is outside allowedChats with 403', async () => {
+ reflector.getAllAndOverride.mockReturnValueOnce(false).mockReturnValueOnce(undefined);
+ const apiKey = createMockApiKey({ allowedChats: [ALLOWED_GROUP, ALLOWED_CONTACT] });
+ (authService.validateApiKey as jest.Mock).mockResolvedValue(apiKey);
+
+ const context = createMockContext({ 'x-api-key': 'key' }, {}, '127.0.0.1', {
+ fromChatId: ALLOWED_GROUP,
+ toChatId: FORBIDDEN_CONTACT,
+ messageId: 'm1',
+ });
+ await expect(guard.canActivate(context)).rejects.toThrow(
+ new ForbiddenException('API key not authorized for this chat'),
+ );
+ });
+
+ it('admits message forward when both fromChatId and toChatId are inside allowedChats', async () => {
+ reflector.getAllAndOverride.mockReturnValueOnce(false).mockReturnValueOnce(undefined);
+ const apiKey = createMockApiKey({ allowedChats: [ALLOWED_GROUP, ALLOWED_CONTACT] });
+ (authService.validateApiKey as jest.Mock).mockResolvedValue(apiKey);
+
+ const context = createMockContext({ 'x-api-key': 'key' }, {}, '127.0.0.1', {
+ fromChatId: ALLOWED_GROUP,
+ toChatId: ALLOWED_CONTACT,
+ messageId: 'm1',
+ });
+ expect(await guard.canActivate(context)).toBe(true);
+ });
+
+ it('rejects bulk send when any message recipient is outside allowedChats with 403', async () => {
+ reflector.getAllAndOverride.mockReturnValueOnce(false).mockReturnValueOnce(undefined);
+ const apiKey = createMockApiKey({ allowedChats: [ALLOWED_GROUP] });
+ (authService.validateApiKey as jest.Mock).mockResolvedValue(apiKey);
+
+ const context = createMockContext({ 'x-api-key': 'key' }, {}, '127.0.0.1', {
+ messages: [
+ { chatId: ALLOWED_GROUP, type: 'text', content: { text: 'one' } },
+ { chatId: FORBIDDEN_CONTACT, type: 'text', content: { text: 'two' } },
+ ],
+ });
+ await expect(guard.canActivate(context)).rejects.toThrow(
+ new ForbiddenException('API key not authorized for this chat'),
+ );
+ });
+
+ it('admits bulk send when every message recipient is inside allowedChats', async () => {
+ reflector.getAllAndOverride.mockReturnValueOnce(false).mockReturnValueOnce(undefined);
+ const apiKey = createMockApiKey({ allowedChats: [ALLOWED_GROUP, ALLOWED_CONTACT] });
+ (authService.validateApiKey as jest.Mock).mockResolvedValue(apiKey);
+
+ const context = createMockContext({ 'x-api-key': 'key' }, {}, '127.0.0.1', {
+ messages: [
+ { chatId: ALLOWED_GROUP, type: 'text', content: { text: 'one' } },
+ { chatId: ALLOWED_CONTACT, type: 'text', content: { text: 'two' } },
+ ],
+ });
+ expect(await guard.canActivate(context)).toBe(true);
+ });
+
+ it('admits forward and bulk send for an unrestricted key (allowedChats null)', async () => {
+ reflector.getAllAndOverride.mockReturnValueOnce(false).mockReturnValueOnce(undefined);
+ const apiKey = createMockApiKey({ allowedChats: null });
+ (authService.validateApiKey as jest.Mock).mockResolvedValue(apiKey);
+
+ const forwardContext = createMockContext({ 'x-api-key': 'key' }, {}, '127.0.0.1', {
+ fromChatId: FORBIDDEN_GROUP,
+ toChatId: FORBIDDEN_CONTACT,
+ messageId: 'm1',
+ });
+ expect(await guard.canActivate(forwardContext)).toBe(true);
+
+ reflector.getAllAndOverride.mockReturnValueOnce(false).mockReturnValueOnce(undefined);
+ const bulkContext = createMockContext({ 'x-api-key': 'key' }, {}, '127.0.0.1', {
+ messages: [{ chatId: FORBIDDEN_CONTACT, type: 'text', content: { text: 'unrestricted' } }],
+ });
+ expect(await guard.canActivate(bulkContext)).toBe(true);
+ });
+ });
});
diff --git a/src/modules/auth/guards/api-key.guard.ts b/src/modules/auth/guards/api-key.guard.ts
index 63d6f961a..4f0236447 100644
--- a/src/modules/auth/guards/api-key.guard.ts
+++ b/src/modules/auth/guards/api-key.guard.ts
@@ -107,13 +107,38 @@ export class ApiKeyGuard implements CanActivate {
}
// Body fence. Sends carry their target chat in the body, not the path (`POST /messages` and the
- // other write routes). Every send DTO names it `chatId`, so one check here fences the whole send
- // surface instead of one per handler — and a handler cannot forget it. Remaining body shapes
- // (bulk `items[].chatId`, forward `to`) are enumerated by the structural coverage spec.
+ // other write routes). Single sends name it `chatId`, bulk send names `messages[].chatId`, and
+ // forward names `fromChatId` and `toChatId`. Fenced centrally here so the whole send surface is
+ // protected and a handler cannot forget it.
const body: unknown = request.body;
- const bodyChatId = body !== null && typeof body === 'object' ? (body as { chatId?: unknown }).chatId : undefined;
- if (typeof bodyChatId === 'string' && bodyChatId && !this.chatScope.allows(apiKey, bodyChatId)) {
- throw new ForbiddenException('API key not authorized for this chat');
+ if (body !== null && typeof body === 'object') {
+ const b = body as Record<string, unknown>;
+
+ const bodyChatId = b.chatId;
+ if (typeof bodyChatId === 'string' && bodyChatId && !this.chatScope.allows(apiKey, bodyChatId)) {
+ throw new ForbiddenException('API key not authorized for this chat');
+ }
+
+ const fromChatId = b.fromChatId;
+ if (typeof fromChatId === 'string' && fromChatId && !this.chatScope.allows(apiKey, fromChatId)) {
+ throw new ForbiddenException('API key not authorized for this chat');
+ }
+
+ const toChatId = b.toChatId;
+ if (typeof toChatId === 'string' && toChatId && !this.chatScope.allows(apiKey, toChatId)) {
+ throw new ForbiddenException('API key not authorized for this chat');
+ }
+
+ const bodyMessages = b.messages;
+ if (Array.isArray(bodyMessages)) {
+ for (const item of bodyMessages) {
+ const itemChatId =
+ item !== null && typeof item === 'object' ? (item as { chatId?: unknown }).chatId : undefined;
+ if (typeof itemChatId === 'string' && itemChatId && !this.chatScope.allows(apiKey, itemChatId)) {
+ throw new ForbiddenException('API key not authorized for this chat');
+ }
+ }
+ }
}
// Routes marked @RequireUnscopedKey carry no session dimension, so the allowedSessions check