Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(auth): bound the allowedChats list of an API key

Yudhi Armyndharis712f29ff88e0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1da042bfc..0bcb115d5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -151,6 +151,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Java SDK (next SDK release after 0.5.1): the request timeout (default 30 s) also bounds the response body; raise it for large media downloads.
- With `OPENWA_DATA_DIR` set, `backup.sh` and `restore.sh` read the default SQLite databases and `./data/...` paths in `./.env` under it; pass a path in the environment to keep it in the working directory.
- A storage import stops at `STORAGE_IMPORT_MAX_TOTAL_BYTES` (default 10 GiB); raise it before importing a larger export.
+- Creating or updating an API key with more than 2000 `allowedChats` entries answers `400`; a stored longer list keeps working until it is edited.
- Baileys answers `400` for an animated sticker with more than 500 frames.
- New Baileys pairings show `Ubuntu` instead of `OpenWA` as the device name in Linked Devices; set `BAILEYS_BROWSER_NAME=OpenWA` to keep the old name. Linked sessions are unaffected.
- `backup.sh` and `restore.sh` exit with status 2 when `./.env` or `.env.generated` sets a key in a form they cannot parse; fix the line or pass the key in the environment.
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 5dccba882..a1ff1fa67 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -47,7 +47,7 @@ API keys carry one of three roles, ordered by privilege:
A key may additionally be scoped to specific sessions (`allowedSessions`) and/or source IPs (`allowedIps`). The scope/IP check runs in the guard **before** any role check, so a request outside that scope is rejected with `403` even if the role would otherwise allow it. `401` is kept for a missing, unknown, revoked or expired key.
-A key may also be restricted to selected chats (`allowedChats`: group `<id>@g.us`, contact `<phone>@c.us` or `<lid>@lid`, or a bare phone number, which is stored as `<phone>@c.us`). An empty or absent list leaves the key unrestricted. A chat-restricted key is **denied by default**: it may call only routes marked as chat-scoped, and every other route (webhooks, automation, status, channels, key management, and any route added later) answers `403 "API key is restricted to selected chats"` after the role check. On a chat-scoped route, every chat id the request names (a `:chatId` / `:groupId` / `:contactId` path param, `?chatId=`, a body `chatId` / `fromChatId` / `toChatId`, and each `messages[].chatId` of a bulk send) must be inside the allowlist, or the request answers `403 "API key not authorized for this chat"`; a contact entry also matches its mapped `@lid` form, and the reverse. The chat, group, contact and label-chat list routes (`GET /api/sessions/:sessionId/chats`, `/groups`, `/contacts` and `/labels/:labelId/chats`) return only the allowed entries, filtered before paging. `GET /api/search` with the built-in provider narrows its hits to the allowed chats before `limit`/`offset`/`total` apply, and an optional `?chatId=` must name an allowed chat. Plugin providers return `403` for these keys before the worker is invoked; set `SEARCH_PROVIDER=builtin-fts` to enable scoped search. `GET /api/sessions/:sessionId/groups/:groupId` and its `GET`/`PUT .../settings` admit a group inside the allowlist and answer `403` for any other. On `GET /api/sessions/:sessionId/messages` such a key must pass `?chatId=`; omitting it answers `403`. A `quotedMessageId` is refused with `403` everywhere except the reply route, which binds the quote to the chat it sends into. The `/events` WebSocket admits chat-restricted keys and delivers only chat events inside their allowlist. MCP tools enforce the same chat fence, filter list results before paging, and refuse tools without chat-scoped authorization. The Bull Board queue dashboard still refuses chat-restricted keys with `403`.
+A key may also be restricted to selected chats (`allowedChats`: group `<id>@g.us`, contact `<phone>@c.us` or `<lid>@lid`, or a bare phone number, which is stored as `<phone>@c.us`), at most 2000 entries. An empty or absent list leaves the key unrestricted. A chat-restricted key is **denied by default**: it may call only routes marked as chat-scoped, and every other route (webhooks, automation, status, channels, key management, and any route added later) answers `403 "API key is restricted to selected chats"` after the role check. On a chat-scoped route, every chat id the request names (a `:chatId` / `:groupId` / `:contactId` path param, `?chatId=`, a body `chatId` / `fromChatId` / `toChatId`, and each `messages[].chatId` of a bulk send) must be inside the allowlist, or the request answers `403 "API key not authorized for this chat"`; a contact entry also matches its mapped `@lid` form, and the reverse. The chat, group, contact and label-chat list routes (`GET /api/sessions/:sessionId/chats`, `/groups`, `/contacts` and `/labels/:labelId/chats`) return only the allowed entries, filtered before paging. `GET /api/search` with the built-in provider narrows its hits to the allowed chats before `limit`/`offset`/`total` apply, and an optional `?chatId=` must name an allowed chat. Plugin providers return `403` for these keys before the worker is invoked; set `SEARCH_PROVIDER=builtin-fts` to enable scoped search. `GET /api/sessions/:sessionId/groups/:groupId` and its `GET`/`PUT .../settings` admit a group inside the allowlist and answer `403` for any other. On `GET /api/sessions/:sessionId/messages` such a key must pass `?chatId=`; omitting it answers `403`. A `quotedMessageId` is refused with `403` everywhere except the reply route, which binds the quote to the chat it sends into. The `/events` WebSocket admits chat-restricted keys and delivers only chat events inside their allowlist. MCP tools enforce the same chat fence, filter list results before paging, and refuse tools without chat-scoped authorization. The Bull Board queue dashboard still refuses chat-restricted keys with `403`.
### API-Key Lifecycle
@@ -5055,7 +5055,7 @@ Same shape as the read DTO **plus** an `apiKey` field carrying the full plaintex
}
```
-**Errors:** `400` validation (bad `name` length, invalid `role` enum, non-IPv4 `allowedIps` entry, bad `expiresAt`, or any non-whitelisted body field) · `401` missing/invalid key · `403` key role below ADMIN, or the key is session-scoped or restricted with `allowedChats`
+**Errors:** `400` validation (bad `name` length, invalid `role` enum, non-IPv4 `allowedIps` entry, more than 2000 `allowedChats` entries, bad `expiresAt`, or any non-whitelisted body field) · `401` missing/invalid key · `403` key role below ADMIN, or the key is session-scoped or restricted with `allowedChats`
#### PUT /api/auth/api-keys/:id
@@ -5107,7 +5107,7 @@ Returns the updated key (no plaintext).
}
```
-**Errors:** `400` validation (incl. `forbidNonWhitelisted` for unknown fields such as `isActive`), or an `expiresAt` that does not parse as a date · `401` missing/invalid key · `403` key role below ADMIN, or the key is session-scoped or restricted with `allowedChats` · `404` not found · `409` change would remove the last usable admin key, or no other usable admin key lasts at least as long
+**Errors:** `400` validation (incl. `forbidNonWhitelisted` for unknown fields such as `isActive`, and more than 2000 `allowedChats` entries), or an `expiresAt` that does not parse as a date · `401` missing/invalid key · `403` key role below ADMIN, or the key is session-scoped or restricted with `allowedChats` · `404` not found · `409` change would remove the last usable admin key, or no other usable admin key lasts at least as long
#### POST /api/auth/api-keys/:id/revoke
diff --git a/src/modules/auth/dto/api-key.dto.spec.ts b/src/modules/auth/dto/api-key.dto.spec.ts
index ed4d20aa9..6c6189668 100644
--- a/src/modules/auth/dto/api-key.dto.spec.ts
+++ b/src/modules/auth/dto/api-key.dto.spec.ts
@@ -2,7 +2,7 @@ import 'reflect-metadata';
import { plainToInstance } from 'class-transformer';
import { validate } from 'class-validator';
import type { Repository } from 'typeorm';
-import { ApiKeyResponseDto, CreateApiKeyDto, UpdateApiKeyDto } from './api-key.dto';
+import { ALLOWED_CHATS_MAX, ApiKeyResponseDto, CreateApiKeyDto, UpdateApiKeyDto } from './api-key.dto';
import { AuthService } from '../auth.service';
import type { ApiKey } from '../entities/api-key.entity';
import type { ApiKeyUsageTracker } from '../api-key-usage-tracker.service';
@@ -38,4 +38,20 @@ describe('API key DTO contract', () => {
it.each([CreateApiKeyDto, UpdateApiKeyDto])('publishes the name length bounds %p validates', dto => {
expect(property(dto.prototype, 'name')).toEqual(expect.objectContaining({ minLength: 3, maxLength: 100 }));
});
+
+ it.each([CreateApiKeyDto, UpdateApiKeyDto])('bounds the allowedChats list of %p', async dto => {
+ // Search binds one SQL parameter per expanded id and a socket holds at most 4096 rooms, two address
+ // forms per phone, so an unbounded list made search answer 500 and every subscribe refuse.
+ const errors = async (count: number) =>
+ (
+ await validate(
+ plainToInstance(dto, {
+ name: 'probe',
+ allowedChats: Array.from({ length: count }, (_, index) => `62811${String(index).padStart(7, '0')}`),
+ }),
+ )
+ ).map(error => error.property);
+ expect(await errors(ALLOWED_CHATS_MAX)).toEqual([]);
+ expect(await errors(ALLOWED_CHATS_MAX + 1)).toEqual(['allowedChats']);
+ });
});
diff --git a/src/modules/auth/dto/api-key.dto.ts b/src/modules/auth/dto/api-key.dto.ts
index 831dad41e..8d1d736d6 100644
--- a/src/modules/auth/dto/api-key.dto.ts
+++ b/src/modules/auth/dto/api-key.dto.ts
@@ -1,4 +1,14 @@
-import { IsString, IsOptional, IsEnum, IsArray, ArrayUnique, IsDateString, MinLength, Validate } from 'class-validator';
+import {
+ IsString,
+ IsOptional,
+ IsEnum,
+ IsArray,
+ ArrayMaxSize,
+ ArrayUnique,
+ IsDateString,
+ MinLength,
+ Validate,
+} from 'class-validator';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { MaxCodePoints } from '../../../common/validation/max-code-points';
import { ApiKeyRole } from '../entities/api-key.entity';
@@ -6,6 +16,13 @@ import { IsIpOrCidrConstraint } from './is-ip-or-cidr.validator';
import { IsSessionIdConstraint } from './is-session-id.validator';
import { IsChatIdConstraint } from './is-chat-id.validator';
+/**
+ * The most chats one key may be restricted to. A chat-restricted WebSocket holds a room per allowed id, two
+ * address forms per phone, within the 4096 a socket may hold, and search binds one SQL parameter per
+ * expanded id; past this bound a key could neither subscribe nor search without an opaque failure.
+ */
+export const ALLOWED_CHATS_MAX = 2000;
+
export class CreateApiKeyDto {
@ApiProperty({
description: 'Friendly name for the API key',
@@ -61,6 +78,7 @@ export class CreateApiKeyDto {
})
@IsOptional()
@IsArray()
+ @ArrayMaxSize(ALLOWED_CHATS_MAX)
@IsString({ each: true })
@ArrayUnique()
@Validate(IsChatIdConstraint, { each: true })
@@ -175,6 +193,7 @@ export class UpdateApiKeyDto {
@ApiPropertyOptional()
@IsOptional()
@IsArray()
+ @ArrayMaxSize(ALLOWED_CHATS_MAX)
@IsString({ each: true })
@ArrayUnique()
@Validate(IsChatIdConstraint, { each: true })