Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(auth)!: answer 403 when a key's IP or session scope refuses it
Yudhi Armyndharis13c30e0b7973
diff --git a/README.md b/README.mdindex 2f9448174..16a28a919 100644--- a/README.md+++ b/README.md@@ -51,7 +51,7 @@ Built on a **pluggable architecture**, OpenWA lets you select database engines (When you create or edit an **operator** or **viewer** API key in the dashboard, you can tick the WhatsApp sessions that key may use.- **No sessions selected** — the key can access every session, including ones created later.-- **One or more sessions selected** — the key can only list, read, and (for operator) manage those sessions. A request naming any other session returns `401`; session-filtered lists (sessions, audit, webhook delivery failures) return that key's rows rather than an error; and the key-management routes and the queue dashboard, which name no session at all, return `403`.+- **One or more sessions selected** — the key can only list, read, and (for operator) manage those sessions. A request naming any other session returns `403` ("API key not authorized for this session"); session-filtered lists (sessions, audit, webhook delivery failures) return that key's rows rather than an error; and the key-management routes and the queue dashboard, which name no session at all, return `403`.Admin keys stay unscoped in the dashboard so they can keep managing other API keys. The HTTP API still accepts `allowedSessions` on any role if you need that from a client.@@ -60,7 +60,7 @@ Admin keys stay unscoped in the dashboard so they can keep managing other API keA session-scoped key still reaches every chat on the sessions it may use. A key can be narrowed further, to **chats** (a chosen set of groups and individual contacts), with `allowedChats` on `POST /auth/api-keys` or `PUT /auth/api-keys/{id}`. The dashboard does not set or show it yet, and editing a key there leaves its chats unchanged.- **No chats selected** — the key can reach every chat on its sessions.-- **One or more selected** — the key reaches only those chats. Every authenticated REST route not explicitly marked as safe for a chat-scoped key refuses it with `403` (a request naming a session outside `allowedSessions` still answers `401` first), including routes added in later releases: the refusal is the default. Inside its chats an operator key can do what the marked routes allow, which is more than reading and sending: it can also delete or clear a chat, leave or rename a group, and block the contact. It cannot change who belongs to a group: adding, removing, promoting or demoting participants, answering join requests and reading or resetting the invite link all stay closed.+- **One or more selected** — the key reaches only those chats. Every authenticated REST route not explicitly marked as safe for a chat-scoped key refuses it with `403` (a request naming a session outside `allowedSessions` is refused first, with `403 "API key not authorized for this session"`), including routes added in later releases: the refusal is the default. Inside its chats an operator key can do what the marked routes allow, which is more than reading and sending: it can also delete or clear a chat, leave or rename a group, and block the contact. It cannot change who belongs to a group: adding, removing, promoting or demoting participants, answering join requests and reading or resetting the invite link all stay closed.- **The two scopes are independent** — a key may be limited to sessions, to chats, to both, or to neither.This lets you point an **AI agent or third-party integration at a shared account** without handing it every chat. Give the agent a key scoped to the few groups (or DMs) it is meant to handle: it can send and reply there, but it cannot list your other chats, read any other DM, message a contact outside its set, or reach the queue dashboard. It reads its chats' stored messages on either engine through `GET /sessions/{sessionId}/messages?chatId=`, where `chatId` is required for such a key, and live history through `GET /sessions/{sessionId}/messages/{chatId}/history` on whatsapp-web.js only. It receives no pushed events, so it has to poll. It can still read the session's own status (`GET /sessions/{sessionId}`) so an integration can tell whether it is connected.diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.tsindex c8b0d603d..80c5e6c43 100644--- a/dashboard/src/services/api.ts+++ b/dashboard/src/services/api.ts@@ -2,6 +2,7 @@// Centralized API client with TypeScript typesimport { warnIfInsecureHttpUrl } from '../utils/urlSecurity';+import { isKeyUnusable } from '../utils/authLifecycle';// Resolve the API base URL. By default this is the same-origin relative path '/api',// correct when the dashboard and API are served from the same origin (the default@@ -691,24 +692,24 @@ export interface SearchResults {// API Client// =============================================================================-// Shared failure handling for every response shape (json/text/blob). On 401 the stored API key is-// invalid/expired/revoked — clear it and return to login so the user isn't stuck on a dashboard that-// 401s every request; the never-settling promise halts this request's chain so callers neither flash-// a generic error toast nor receive an undefined payload while the page navigates away. Otherwise-// throw an Error carrying the HTTP status and, when the gateway supplied one, its machine code.+// Shared failure handling for every response shape (json/text/blob). When the stored API key is+// unusable (a 401 for an invalid/expired/revoked key, or a 403 because its allowedIps refuse this+// client) clear it and return to login so the user isn't stuck on a dashboard where every request+// fails; the never-settling promise halts this request's chain so callers neither flash a generic+// error toast nor receive an undefined payload while the page navigates away. Otherwise throw an+// Error carrying the HTTP status and, when the gateway supplied one, its machine code.async function handleErrorResponse<T>(response: Response): Promise<T> {- if (response.status === 401) {+ // On a non-JSON body (e.g. a reverse-proxy 502/503/504 HTML page) fall through to `HTTP <status>`+ // rather than statusText: the status code is what the toast connection-lost de-dup matches on,+ // and statusText is empty over HTTP/2 anyway.+ const error = await response.json().catch(() => ({}));+ if (isKeyUnusable(response.status, error.message)) {sessionStorage.removeItem('openwa_api_key');if (typeof window !== 'undefined') {window.location.assign('/');return new Promise<T>(() => {});}}-- // On a non-JSON body (e.g. a reverse-proxy 502/503/504 HTML page) fall through to `HTTP <status>`- // rather than statusText: the status code is what the toast connection-lost de-dup matches on,- // and statusText is empty over HTTP/2 anyway.- const error = await response.json().catch(() => ({}));// Carry the HTTP status on the Error (message unchanged, so the toast de-dup still matches) so// callers can tell apart a permission 403 from a real server 5xx instead of guessing from text.// Carry the machine `code` too: the gateway's stable codes (SESSION_LOGOUT_INCOMPLETE,diff --git a/dashboard/src/utils/authLifecycle.test.ts b/dashboard/src/utils/authLifecycle.test.tsindex f0a072e15..5b131b21b 100644--- a/dashboard/src/utils/authLifecycle.test.ts+++ b/dashboard/src/utils/authLifecycle.test.ts@@ -4,7 +4,7 @@ import assert from 'node:assert/strict';import { createElement } from 'react';import { QueryClient } from '@tanstack/react-query';import type { installJsdomGlobals as installJsdomGlobalsFn } from '../test-helpers/jsdom.ts';-import { clearActorState, isUserRole, resolveStartupValidation } from './authLifecycle.ts';+import { clearActorState, isKeyUnusable, isUserRole, resolveStartupValidation } from './authLifecycle.ts';test('logout cleanup wipes the React Query cache (no cross-actor residue)', () => {const queryClient = new QueryClient();@@ -215,3 +215,19 @@ test('a page reload with a saved key re-validates once at startup and refreshesassert.equal(validateCallCount(), 1);assert.equal(sessionStorage.getItem(ENGINE_KEY), 'baileys');});++test('a 401, or a 403 from allowedIps refusing this client, makes the key unusable', () => {+ assert.equal(isKeyUnusable(401, undefined), true);+ assert.equal(isKeyUnusable(401, 'Invalid API key'), true);+ assert.equal(isKeyUnusable(403, 'IP address not allowed'), true);+ assert.equal(isKeyUnusable(403, 'Client IP could not be determined'), true);+});++test('a role or scope 403 and other failures keep the key', () => {+ assert.equal(isKeyUnusable(403, 'Insufficient permissions'), false);+ assert.equal(isKeyUnusable(403, undefined), false);+ assert.equal(isKeyUnusable(403, ['IP address not allowed']), false);+ assert.equal(isKeyUnusable(400, 'IP address not allowed'), false);+ assert.equal(isKeyUnusable(429, undefined), false);+ assert.equal(isKeyUnusable(500, undefined), false);+});diff --git a/dashboard/src/utils/authLifecycle.ts b/dashboard/src/utils/authLifecycle.tsindex ac2c5898a..bbb3d6ce3 100644--- a/dashboard/src/utils/authLifecycle.ts+++ b/dashboard/src/utils/authLifecycle.ts@@ -22,6 +22,17 @@ export function clearActorState(...caches: ClearableCache[]): void {for (const cache of caches) cache.clear();}+const IP_REFUSALS: ReadonlySet<string> = new Set(['IP address not allowed', 'Client IP could not be determined']);++/**+ * True when a response proves the stored key cannot be used from this client, so the dashboard must+ * log out: a 401, or a 403 because the key's allowedIps refuse this client (the IP can change+ * mid-session). A role or scope 403 leaves the key usable for other requests.+ */+export function isKeyUnusable(status: number, message: unknown): boolean {+ return status === 401 || (status === 403 && typeof message === 'string' && IP_REFUSALS.has(message));+}+export type StartupValidation ={ action: 'role'; role: UserRole; engineType?: string } | { action: 'logout' } | { action: 'keep' };diff --git a/docs/04-security-design.md b/docs/04-security-design.mdindex a04286234..f97f566e3 100644--- a/docs/04-security-design.md+++ b/docs/04-security-design.md@@ -86,7 +86,7 @@ above that level (`AuthService.hasPermission`). A key below it is rejected with| Scope | Field | Effect || --------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ || Source IP | `allowedIps` | Empty/absent = unrestricted; non-empty = fail-closed IP whitelist (see §4.3) |-| Sessions | `allowedSessions` | Empty/absent = every session; non-empty = a request carrying any other session id is rejected with `401` |+| Sessions | `allowedSessions` | Empty/absent = every session; non-empty = a request carrying any other session id is rejected with `403` || Chats | `allowedChats` | Empty/absent = every chat; non-empty = default-deny: only chat-scoped routes, and only for a listed chat, else `403`; `/events`, MCP and Bull Board refuse the key |The key-lifecycle routes (`/api/auth/api-keys`) are additionally fenced with `@RequireUnscopedKey()`:@@ -113,7 +113,7 @@ flowchart TBAUTH -->|Yes| WL{IP Whitelist Enabled?}WL -->|No| ALLOW[Allow Request]WL -->|Yes| CHECK{IP in Whitelist?}- CHECK -->|No| RIP[401 Unauthorized]+ CHECK -->|No| RIP[403 Forbidden]CHECK -->|Yes| ALLOWALLOW --> PROCESS[Process Request]```@@ -149,9 +149,10 @@ sub-resource, no per-entry `active` flag. Enforcement lives in two places:- **Matching** — `AuthService.validateApiKey` compares that IP against the key's `allowedIps` withthe shared `ipMatches` helper, which accepts an exact address or CIDR notation and returns `false`on a malformed entry rather than coercing it into range. With a whitelist configured, an- undeterminable client IP throws `UnauthorizedException` (`401`) straight away, with no log line;+ undeterminable client IP throws `ForbiddenException` (`403`) straight away, with no log line;an IP outside the list writes a `logger.warn` with `action: 'ip_rejected'` first, then throws the- same `401`.+ same `403`. The key itself is valid, so the refusal is a `403` like the role and chat refusals, and+ a client does not read it as a key to discard.### Best Practicesdiff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 225d39451..7895a9f67 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -45,7 +45,7 @@ API keys carry one of three roles, ordered by privilege:`@RequireRole(role)` enforces a **minimum** role using the hierarchy `VIEWER < OPERATOR < ADMIN`: a key satisfies the guard if its own rank is ≥ the required rank (so an `admin` key passes an `OPERATOR`-guarded route). A route with no `@RequireRole` accepts any valid key, including `viewer`. A key whose role is below the requirement gets `403 Forbidden`; a missing or invalid key gets `401 Unauthorized`.-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 `401` (not `403`) even if the role would otherwise allow it.+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. 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 surfaces outside the REST guard refuse a chat-restricted key outright: the `/events` WebSocket at the handshake and on every subscribe, every MCP tool call (`403`), and the Bull Board queue dashboard (`403`).@@ -99,8 +99,8 @@ Validation failures (`statusCode: 400`) return `message` as an **array** of fiel| HTTP Status | Meaning | When || ----------- | --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || `400` | Bad Request | DTO validation failed, unknown body field, or a business precondition not met (e.g. session not active, media over cap) |-| `401` | Unauthorized | Missing/invalid/expired/revoked `X-API-Key` (or `METRICS_TOKEN` for metrics), a blocked source IP, or a key used outside its `allowedSessions` scope |-| `403` | Forbidden | A valid, in-scope key whose **role** is below the route's `@RequireRole` requirement, or a key with `allowedChats` that calls a route that is not chat-scoped, names a chat outside its allowlist, or sends a `quotedMessageId` outside the reply route (see Roles & Authorization) |+| `401` | Unauthorized | Missing/invalid/expired/revoked `X-API-Key` (or `METRICS_TOKEN` for metrics) |+| `403` | Forbidden | A valid key refused by its `allowedIps` (a blocked or undeterminable source IP) or used outside its `allowedSessions` scope, a key whose **role** is below the route's `@RequireRole` requirement, or a key with `allowedChats` that calls a route that is not chat-scoped, names a chat outside its allowlist, or sends a `quotedMessageId` outside the reply route (see Roles & Authorization) || `404` | Not Found | The addressed resource (session, message, webhook, batch, …) does not exist || `409` | Conflict | A uniqueness constraint was violated (e.g. duplicate name); a credential teardown for the same session name is still in flight on `start`/`delete` (retryable; body carries `code: 'SESSION_NAME_TEARDOWN_PENDING'`); or, on routes that reach a WhatsApp engine, the engine exists but is not ready yet (retryable; each route section carries the exact wording); or, on a multi-node deployment, another node currently owns the session's live engine (retryable) || `413` | Payload Too Large | Base64 or downloaded media exceeds the media byte cap (see §6.3) |@@ -277,7 +277,7 @@ Get a single session by ID.}```-**Errors:** `401` missing/invalid key, or key not scoped to this session · `404` session not found+**Errors:** `401` missing/invalid key · `403` key not scoped to this session · `404` session not found#### GET /api/sessions/:sessionId/config@@ -307,7 +307,7 @@ Baileys that covers only the reconnect after a logged-out close: that engine retinternally, with a fixed 1s to 60s backoff and no attempt cap. See §5 (Database Design) for what eachkey does and the moment it is read.-**Errors:** `401` missing/invalid key, or key not scoped to this session · `404` session not found+**Errors:** `401` missing/invalid key · `403` key not scoped to this session · `404` session not found#### PATCH /api/sessions/:sessionId/config@@ -339,7 +339,7 @@ and therefore apply on the next start, leaving a reconnect sequence already in f**Response** `200` — the resulting `SessionConfigResponseDto` (same shape as the GET above).-**Errors:** `400` a supplied value is outside its accepted range · `401` missing/invalid key, or key not scoped to this session · `403` key lacks OPERATOR role · `404` session not found+**Errors:** `400` a supplied value is outside its accepted range · `401` missing/invalid key · `403` key not scoped to this session, or key lacks OPERATOR role · `404` session not found#### GET /api/sessions/:sessionId/proxy@@ -366,7 +366,7 @@ Read a session's masked proxy configuration. Credentials embedded in the storedWhen no proxy is configured, `enabled` is `false` and the other fields are `null`/`false`.-**Errors:** `401` missing/invalid key, or key not scoped to this session · `404` session not found+**Errors:** `401` missing/invalid key · `403` key not scoped to this session · `404` session not found#### PATCH /api/sessions/:sessionId/proxy@@ -392,7 +392,7 @@ Update per-session proxy settings. No restart is required or performed — chang**Response** `200` — the resulting `SessionProxyResponseDto` (same shape as the GET above).-**Errors:** `400` validation (bad `proxyUrl`) · `401` missing/invalid key, or key not scoped to this session · `403` key lacks ADMIN role, or the key is restricted to specific sessions · `404` session not found+**Errors:** `400` validation (bad `proxyUrl`) · `401` missing/invalid key · `403` key not scoped to this session, key lacks ADMIN role, or the key is restricted to specific sessions · `404` session not found#### GET /api/sessions/:sessionId/qr@@ -1254,7 +1254,7 @@ Delete a session.The delete removes, in one transaction, the session's messages, message batches, chat states, received statuses, webhooks, templates, stored Baileys messages, automation rules, webhook outbox rows, webhook delivery-failure records and integration dead-letter rows, then purges its on-disk auth data. It keeps the audit log, the LID mappings, and the integration conversation mappings (so a re-paired session keeps its provider conversations); ingress dedup rows age out on their own after `INGRESS_DEDUP_RETENTION_DAYS` (default 7).-**Errors:** `401` missing/invalid key, or key not scoped to this session · `403` key role below OPERATOR · `404` session not found · `409` credential teardown for the same session name still in flight (retryable; body carries `code: 'SESSION_NAME_TEARDOWN_PENDING'`; on a `409` the row is **not** deleted and no hook/auth-purge runs — retry after cleanup settles)+**Errors:** `401` missing/invalid key · `403` key not scoped to this session, or key role below OPERATOR · `404` session not found · `409` credential teardown for the same session name still in flight (retryable; body carries `code: 'SESSION_NAME_TEARDOWN_PENDING'`; on a `409` the row is **not** deleted and no hook/auth-purge runs — retry after cleanup settles)### 6.4.2 Messages@@ -1526,7 +1526,7 @@ mimetype when it is in a conservative inert set (common image/video/audio types)`application/octet-stream` otherwise — a document, or an `image/svg+xml`, is never served as activecontent on the API origin.-**Errors:** `401` missing/invalid API key, or key not scoped to this session · `404`+**Errors:** `401` missing/invalid API key · `403` key not scoped to this session · `404``No media stored for this message` — the message carries no media, `MEDIA_DOWNLOAD_ENABLED=false`or the media was above `MEDIA_DOWNLOAD_MAX_BYTES` when it was stored (the row holds a size-onlymarker), it was a URL-based API send (the gateway fetches those bytes at send time and never stores@@ -2411,7 +2411,7 @@ On Baileys the list is the saved address book: contacts with a name saved on the]```-**Errors:** `400` session is not started · `401` missing/invalid API key, or key not scoped to this session · `409` conflict or engine not ready (retryable) · `500` engine error, including whatsapp-web.js when entries could not be read and no unblocked contact was, or when no entry had a readable id (a page-wide failure, not an empty address book) · `503` the WhatsApp page died while reading contacts or the command timed out (retry shortly)+**Errors:** `400` session is not started · `401` missing/invalid API key · `403` key not scoped to this session · `409` conflict or engine not ready (retryable) · `500` engine error, including whatsapp-web.js when entries could not be read and no unblocked contact was, or when no entry had a readable id (a page-wide failure, not an empty address book) · `503` the WhatsApp page died while reading contacts or the command timed out (retry shortly)#### GET /api/sessions/:sessionId/contacts/blocked@@ -2553,7 +2553,7 @@ An engine that is not ready is the exception: it describes the session rather th> Route-order caveat: `profile-pictures` is declared **before** `GET /:contactId`, so the literal segment wins — a contact whose id is literally `profile-pictures` cannot be fetched through the single-contact route.-**Errors:** `400` session is not started · `401` missing/invalid API key, or key not scoped to this session · `409` conflict or engine not ready (retryable)+**Errors:** `400` session is not started · `401` missing/invalid API key · `403` key not scoped to this session · `409` conflict or engine not ready (retryable)#### GET /api/sessions/:sessionId/contacts/:contactId/phone@@ -4212,7 +4212,7 @@ Get all contact status updates (stories) visible to the session, read from the sThe controller wraps the store array in `{ statuses }`, ordered newest-first. `type` is one of `text | image | video | voice` (`voice` was added with the send-voice endpoint below; before that anything that was not an image or a video read back as `text`); `caption`, `backgroundColor`, `font` are optional. `mediaUrl` is present only when the status carried media that the store kept (see the media endpoint below) — it is a same-origin path into this API, not an external WhatsApp CDN link. `timestamp` and `expiresAt` serialize to ISO strings (these are `Date` values, not the epoch-number convention used by message timestamps).-**Errors:** `401` missing/invalid API key, or key not scoped to this session+**Errors:** `401` missing/invalid API key · `403` key not scoped to this session#### GET /api/sessions/:sessionId/status/:id@@ -4248,7 +4248,7 @@ Get status updates posted by a specific contact, read from the store (24h TTL, bSame `{ statuses }` wrapper and `Status` shape as the list-all route. An unknown `contactId` returns `{ "statuses": [] }`, not a `404`.-**Errors:** `401` missing/invalid API key, or key not scoped to this session+**Errors:** `401` missing/invalid API key · `403` key not scoped to this session#### GET /api/sessions/:sessionId/status/:statusId/media@@ -4267,7 +4267,7 @@ Stream a stored status's media bytes (the file behind a `mediaUrl` returned abovOnly the essence of the stored mimetype is checked and served: the part before any `;`, trimmed and lowercased, since MIME types are case-insensitive. Parameters are dropped, and a value that is not a single well-formed type (a comma-joined list, for example) is served as `application/octet-stream`.-**Errors:** `401` missing/invalid API key, or key not scoped to this session · `404` `Status media not found or expired` — the status is text-only, its media was omitted (e.g. over the configured size cap), or the 24h TTL has since purged the row+**Errors:** `401` missing/invalid API key · `403` key not scoped to this session · `404` `Status media not found or expired` — the status is text-only, its media was omitted (e.g. over the configured size cap), or the 24h TTL has since purged the rowNote: `:statusId/media` is a two-path-segment route, so it never collides with the single-segment `GET /status/:id` above regardless of declaration order.@@ -4794,7 +4794,7 @@ No content (empty body; explicit `@HttpCode(204)`).### 6.4.9 API Keys-API keys are managed under `/api/auth/api-keys`. All management routes (create/list/get/update/delete/revoke) require an **ADMIN** key **with no session scope**: the controller is fenced with `@RequireUnscopedKey`, so a key whose `allowedSessions` is non-empty is rejected with `403` whatever its role — otherwise a confined admin key could mint an unrestricted one. The guard evaluates the role requirement _before_ that fence, so a scoped VIEWER/OPERATOR key is refused with `Insufficient permissions. Required: admin`; only a scoped ADMIN key reaches the fence and sees `Session-scoped API keys are not permitted on this route`. Both are `403`. A key restricted with `allowedChats` that passes the role check is refused next, before the session fence, with `403 "API key is restricted to selected chats"`: no management route is open to a chat-scoped key. The plaintext key string is returned **only once**, at creation. Validation of the caller's own key lives at `POST /api/auth/validate` (a separate controller, not fenced) and accepts any valid key except one restricted with `allowedChats`, which it refuses with `403` like every route not open to a chat-scoped key.+API keys are managed under `/api/auth/api-keys`. All management routes (create/list/get/update/delete/revoke) require an **ADMIN** key **with no session scope**: the controller is fenced with `@RequireUnscopedKey`, so a key whose `allowedSessions` is non-empty is rejected with `403` whatever its role — otherwise a confined admin key could mint an unrestricted one. The guard evaluates the role requirement _before_ that fence, so a scoped VIEWER/OPERATOR key is refused with `Insufficient permissions. Required: admin`; only a scoped ADMIN key reaches the fence and sees `Session-scoped API keys are not permitted on this route`. Both are `403`. A key restricted with `allowedChats` that passes the role check is refused next, before the session fence, with `403 "API key is restricted to selected chats"`: no management route is open to a chat-scoped key. The plaintext key string is returned **only once**, at creation. Validation of the caller's own key lives at `POST /api/auth/validate` (a separate controller, not fenced) and accepts any valid key except one its `allowedIps` refuses or one restricted with `allowedChats`, each refused with `403` (the latter like every route not open to a chat-scoped key).#### GET /api/auth/api-keys@@ -5013,7 +5013,7 @@ Validate the supplied `X-API-Key` and report its validity, its role, and the eng**Auth:** API key (any valid role — VIEWER+)-The key is read from the `X-API-Key` header, not the body; send an empty body. This route sits behind the global guard (it is not `@Public`), so a missing/invalid/revoked/expired key is rejected with `401` at the guard before the handler runs. On success it returns the caller's role and `engineType`, the engine the process resolved at boot (`whatsapp-web.js` or `baileys`). The engine is reported to every role because `GET /api/infra/engines/current` is ADMIN-only. A key restricted with `allowedChats` is refused with `403 "API key is restricted to selected chats"`: the route is not open to a chat-scoped key.+The key is read from the `X-API-Key` header, not the body; send an empty body. This route sits behind the global guard (it is not `@Public`), so a missing/invalid/revoked/expired key is rejected with `401` at the guard before the handler runs, and a key refused by its `allowedIps` with `403`. On success it returns the caller's role and `engineType`, the engine the process resolved at boot (`whatsapp-web.js` or `baileys`). The engine is reported to every role because `GET /api/infra/engines/current` is ADMIN-only. A key restricted with `allowedChats` is refused with `403 "API key is restricted to selected chats"`: the route is not open to a chat-scoped key.**Response** `200`@@ -5021,7 +5021,7 @@ The key is read from the `X-API-Key` header, not the body; send an empty body. T{ "valid": true, "role": "operator", "engineType": "whatsapp-web.js" }```-**Errors:** `401` missing/invalid/revoked/expired key (raised by the global guard before the handler); `403` a key restricted with `allowedChats`+**Errors:** `401` missing/invalid/revoked/expired key (raised by the global guard before the handler); `403` a key refused by its `allowedIps` (blocked or undeterminable client IP), or one restricted with `allowedChats`> Implemented by `AuthValidateController` (`@Controller('auth')`), sharing the same `/api/auth` base.@@ -5199,7 +5199,7 @@ Notes: raw handler return. `timeSeries.timestamp` is a DB-formatted bucket strinGet statistics for a single session: identity, message counts, top chats, and 24 h hourly activity.-**Auth:** API key — any valid key (VIEWER and up); there is no `@RequireRole`. Scope still applies: the global guard feeds the `:sessionId` route param to the key's `allowedSessions`, so a session-scoped key asking for a session outside its list gets `401 "API key not authorized for this session"`. Only an unscoped key can read any session's stats.+**Auth:** API key — any valid key (VIEWER and up); there is no `@RequireRole`. Scope still applies: the global guard feeds the `:sessionId` route param to the key's `allowedSessions`, so a session-scoped key asking for a session outside its list gets `403 "API key not authorized for this session"`. Only an unscoped key can read any session's stats.**Path parameters**@@ -5223,7 +5223,7 @@ Get statistics for a single session: identity, message counts, top chats, and 24Notes: raw handler return. `session.status` is the `SessionStatus` enum value. `messages.sent`/`received` are all-time outgoing/incoming COUNTs; `today` is the total message count since local midnight; `failed` is the `FAILED`-status count. `topChats` is the top 10 by count DESC, with `lastActive` = `MAX(createdAt)` as a DB-native datetime string and `chatName` as in `GET /api/stats/messages`. `hourlyActivity` always has 24 entries (hour `0..23`), missing hours zero-filled, computed over the last 24 h.-**Errors:** `401` — missing/invalid API key, or the key is not scoped to this session · `404` — session not found (`Session not found`).+**Errors:** `401` — missing/invalid API key · `403` (the key is not scoped to this session) · `404` — session not found (`Session not found`).#### GET /api/settings@@ -6318,7 +6318,7 @@ Key facts:For `tools/call` the result is an MCP `CallToolResult` (`content` array of `text` or embedded base64 `resource` items — payloads over 4096 bytes become a `resource`). **Tool-level failures are returned in-band as `CallToolResult` with `isError:true`** (HTTP stays 200), including a role, session or chat refusal (`name:'ForbiddenException'`) and rate-limit hits (`message:'MCP rate limit exceeded'`).-**Errors:** `401` with a JSON-RPC error body for a missing or refused key · in-band JSON-RPC errors `-32601` (unknown method), `-32602` (invalid params / unknown tool), `-32700` (parse error), all at HTTP 200 · `500` if the key lookup fails for a reason other than a refused key, or if the transport throws before headers are sent · `404` when `MCP_ENABLED` is not `true`+**Errors:** `401` for a missing or invalid key and `403` for a key carrying `allowedIps`, each with a JSON-RPC error body · in-band JSON-RPC errors `-32601` (unknown method), `-32602` (invalid params / unknown tool), `-32700` (parse error), all at HTTP 200 · `500` if the key lookup fails for a reason other than a refused key, or if the transport throws before headers are sent · `404` when `MCP_ENABLED` is not `true`> The full catalog of MCP tools (names, tiers, schemas) is documented separately — see **doc 24, MCP Integration**. This section documents only the transport endpoint.diff --git a/docs/07-api-collection.md b/docs/07-api-collection.mdindex 48465d31f..933e241e9 100644--- a/docs/07-api-collection.md+++ b/docs/07-api-collection.md@@ -1210,7 +1210,7 @@ curl -X DELETE "$BASE/api/sessions/$SESSION_ID/webhooks/f1e2d3c4-b5a6-7890-1234-### 07.11 API Keys-All `/api/auth/api-keys` routes require an unscoped **ADMIN** key: one with `allowedSessions` or `allowedChats` set is refused with `403`. `POST /api/auth/validate` accepts any valid key except one restricted with `allowedChats`, which gets `403`. The plaintext key is returned only by the create call.+All `/api/auth/api-keys` routes require an unscoped **ADMIN** key: one with `allowedSessions` or `allowedChats` set is refused with `403`. `POST /api/auth/validate` accepts any valid key except one its `allowedIps` refuses or one restricted with `allowedChats`, each of which gets `403`. The plaintext key is returned only by the create call.#### GET /api/auth/api-keys@@ -1651,7 +1651,7 @@ curl -X DELETE "$BASE/api/plugins/chat-flow" \#### POST /mcp-MCP JSON-RPC 2.0 transport (no `/api` prefix; gated by `MCP_ENABLED=true`). The API key goes via `X-Api-Key` or `Authorization: Bearer` on every request, `initialize` and `tools/list` included (a missing or refused key answers `401`); role and session scope are checked per tool call. The server is **read-only by default** — write tools such as `MessageSendText` are only mounted when `MCP_READONLY=false`. See doc 24 for the tool catalog.+MCP JSON-RPC 2.0 transport (no `/api` prefix; gated by `MCP_ENABLED=true`). The API key goes via `X-Api-Key` or `Authorization: Bearer` on every request, `initialize` and `tools/list` included (a missing or invalid key answers `401`, a key carrying `allowedIps` `403`); role and session scope are checked per tool call. The server is **read-only by default** — write tools such as `MessageSendText` are only mounted when `MCP_READONLY=false`. See doc 24 for the tool catalog.```bash# Initialize handshakediff --git a/docs/17-dashboard-design.md b/docs/17-dashboard-design.mdindex 0c83c4af2..fbad8da2d 100644--- a/docs/17-dashboard-design.md+++ b/docs/17-dashboard-design.md@@ -470,8 +470,9 @@ context: `useTheme` is a plain hook that persists to `localStorage` and writes oThe client lives in `src/services/api.ts`. A single `request<T>()` helper attaches the `X-API-Key`header from `sessionStorage`, then returns **the parsed JSON body as-is** — the backend sends theraw handler payload, so `request<Session[]>('/sessions')` resolves to a bare `Session[]`, not-`{ data: Session[] }`. (A `204 No Content` resolves to `undefined`; a `401` clears the stored key-and redirects to login.) Endpoints are grouped into typed namespaces — `sessionApi`, `webhookApi`,+`{ data: Session[] }`. (A `204 No Content` resolves to `undefined`; a `401`, or a `403` because the+key's `allowedIps` refuse this client, clears the stored key and redirects to login; any other `403`+leaves the key in place.) Endpoints are grouped into typed namespaces — `sessionApi`, `webhookApi`,`templateApi`, `apiKeyApi`, `auditApi`, `messageApi`, `infraApi`, `pluginsApi`, `statsApi`, ...```typescriptdiff --git a/docs/18-sdk-design.md b/docs/18-sdk-design.mdindex 3d54974be..656ea3a7e 100644--- a/docs/18-sdk-design.md+++ b/docs/18-sdk-design.md@@ -358,7 +358,7 @@ On a non-2xx response the SDK throws a typed `OpenWAApiError` subclass carrying| Error class | HTTP status | Meaning || ------------------------------- | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || `OpenWAAuthError` | 401 | Missing or invalid API key. |-| `OpenWAForbiddenError` | 403 | The key's role is insufficient (e.g. an OPERATOR-only route). |+| `OpenWAForbiddenError` | 403 | The key's role or scope refuses the call (e.g. an OPERATOR-only route, or a session, IP or chat outside the key's allow-lists). || `OpenWANotFoundError` | 404 | Resource not found. || `OpenWAConflictError` | 409 | Conflict — typically the engine is not ready. || `OpenWARateLimitError` | 429 | Rate limited. The global rate limiter's 429 lifts when its window expires (seconds for the per-second tier, up to an hour for the hourly tier by default); its delay is only in the `Retry-After` response header, which the error does not carry. A 429 whose body has `code: "SEND_PACING_LIMITED"` is not transient: do not retry it before the body's `retryAfterSeconds`, which can be hours. |@@ -730,7 +730,7 @@ Every error inherits from `OpenWAError`. A non-2xx response raises an `OpenWAApi| Exception | Trigger || ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || `OpenWAAuthError` | HTTP `401` — missing or invalid API key |-| `OpenWAForbiddenError` | HTTP `403` — insufficient role |+| `OpenWAForbiddenError` | HTTP `403` — the key's role or scope (session, IP or chat allow-list) refuses the call || `OpenWANotFoundError` | HTTP `404` — resource not found || `OpenWAConflictError` | HTTP `409` — typically engine-not-ready || `OpenWARateLimitError` | HTTP `429` — too many requests. The global rate limiter's 429 lifts when its window expires (seconds for the per-second tier, up to an hour for the hourly tier by default); its delay is only in the `Retry-After` response header, which the error does not carry. A 429 whose body has `code: "SEND_PACING_LIMITED"` is not transient: do not retry it before the body's `retryAfterSeconds`, which can be hours. |@@ -1082,7 +1082,7 @@ All exceptions live in `OpenWA\Exceptions` and descend from `OpenWAException` (w| `OpenWAException` | `\Exception` | Base for all SDK errors (also thrown for missing `baseUrl`/`apiKey`). || `OpenWAApiException` | `OpenWAException` | Any non-2xx (including unfollowed 3xx and other 4xx/5xx). || `OpenWAAuthException` | `OpenWAApiException` | `401` — missing/invalid API key. |-| `OpenWAForbiddenException` | `OpenWAApiException` | `403` — insufficient role (e.g. operator-only endpoint). |+| `OpenWAForbiddenException` | `OpenWAApiException` | `403` — the key's role or scope refuses the call (e.g. operator-only endpoint, or a session, IP or chat outside its allow-lists). || `OpenWANotFoundException` | `OpenWAApiException` | `404` — resource not found. || `OpenWAConflictException` | `OpenWAApiException` | `409` — conflict (e.g. engine not ready). || `OpenWARateLimitException` | `OpenWAApiException` | `429` — rate limited. The global rate limiter's 429 lifts when its window expires (seconds for the per-second tier, up to an hour for the hourly tier by default); its delay is only in the `Retry-After` response header, which the error does not carry. A 429 whose body has `code: "SEND_PACING_LIMITED"` is not transient: do not retry it before the body's `retryAfterSeconds`, which can be hours. |diff --git a/src/core/agent-tools/tool-invoker.spec.ts b/src/core/agent-tools/tool-invoker.spec.tsindex 80b096f92..fbdd8ec27 100644--- a/src/core/agent-tools/tool-invoker.spec.ts+++ b/src/core/agent-tools/tool-invoker.spec.ts@@ -78,7 +78,7 @@ describe('invokeTool', () => {it('rejects when validateApiKey throws for an out-of-scope session', async () => {const a = auth();(a.validateApiKey as jest.Mock).mockRejectedValueOnce(- new UnauthorizedException('API key not authorized for this session'),+ new ForbiddenException('API key not authorized for this session'),);const scoped: ToolDescriptor = {...readTool,@@ -88,7 +88,7 @@ describe('invokeTool', () => {};await expect(invokeTool(scoped, { sessionId: 'other-session' }, 'rawkey', a as unknown as AuthService),- ).rejects.toBeInstanceOf(UnauthorizedException);+ ).rejects.toBeInstanceOf(ForbiddenException);});it('enforces requiredRole via hasPermission', async () => {@@ -150,11 +150,11 @@ describe('invokeTool', () => {it('is invoked when validateApiKey rejects (IP/revoked/expired/session-not-allowed)', async () => {const a = auth();- (a.validateApiKey as jest.Mock).mockRejectedValueOnce(new UnauthorizedException('IP address not allowed'));+ (a.validateApiKey as jest.Mock).mockRejectedValueOnce(new ForbiddenException('IP address not allowed'));const onAuthFailure = jest.fn();await expect(invokeTool(readTool, { n: 1 }, 'rawkey', a as unknown as AuthService, undefined, onAuthFailure),- ).rejects.toBeInstanceOf(UnauthorizedException);+ ).rejects.toBeInstanceOf(ForbiddenException);expect(onAuthFailure).toHaveBeenCalledTimes(1);});diff --git a/src/modules/auth/auth-validate.controller.ts b/src/modules/auth/auth-validate.controller.tsindex 2d355236e..905505178 100644--- a/src/modules/auth/auth-validate.controller.ts+++ b/src/modules/auth/auth-validate.controller.ts@@ -16,6 +16,11 @@ export class AuthValidateController {@ApiHeader({ name: 'X-API-Key', description: 'API key to validate' })@ApiResponse({ status: 200, description: 'API key is valid', type: ValidateApiKeyResponseDto })@ApiResponse({ status: 401, description: 'Invalid or missing API key' })+ @ApiResponse({+ status: 403,+ description:+ 'The key is valid but refused here: its allowedIps exclude this client, or it is restricted to selected chats',+ })validate(@CurrentApiKey() apiKey?: ApiKey): { valid: boolean; role?: string; engineType?: string } {// This route is behind the global API-key guard, so only a validated key reaches this handler// (a missing/invalid key 401s first). The guard has already verified the key — including itsdiff --git a/src/modules/auth/auth.service.spec.ts b/src/modules/auth/auth.service.spec.tsindex ea02d42e5..19b0cc6a3 100644--- a/src/modules/auth/auth.service.spec.ts+++ b/src/modules/auth/auth.service.spec.ts@@ -5,7 +5,7 @@ jest.mock('fs', () => ({ __esModule: true, ...jest.requireActual<typeof import('import { Test, TestingModule } from '@nestjs/testing';import { getRepositoryToken } from '@nestjs/typeorm';import { Repository } from 'typeorm';-import { UnauthorizedException, NotFoundException, ConflictException } from '@nestjs/common';+import { UnauthorizedException, NotFoundException, ConflictException, ForbiddenException } from '@nestjs/common';import { createHash, createHmac } from 'crypto';import * as fs from 'fs';import { AuthService, resolveSeedApiKey, bannerKeyLine, UnresolvedApiKeyException } from './auth.service';@@ -808,14 +808,16 @@ describe('AuthService', () => {await expect(service.validateApiKey('expired')).rejects.toThrow('API key has expired');});- it('should throw UnauthorizedException when IP is not allowed', async () => {+ it('answers 403, not 401, when the IP is not allowed', async () => {const key = createMockApiKey({allowedIps: ['10.0.0.1'],keyHash: hashKey('ip-restricted'),});(repository.findOne as jest.Mock).mockResolvedValue(key);- await expect(service.validateApiKey('ip-restricted', '192.168.1.1')).rejects.toThrow('IP address not allowed');+ const err = await service.validateApiKey('ip-restricted', '192.168.1.1').catch((e: unknown) => e);+ expect(err).toBeInstanceOf(ForbiddenException);+ expect((err as Error).message).toBe('IP address not allowed');});it('should pass when client IP matches allowed IPs', async () => {@@ -837,7 +839,9 @@ describe('AuthService', () => {});(repository.findOne as jest.Mock).mockResolvedValue(key);- await expect(service.validateApiKey('ip-no-client')).rejects.toThrow('Client IP could not be determined');+ const err = await service.validateApiKey('ip-no-client').catch((e: unknown) => e);+ expect(err).toBeInstanceOf(ForbiddenException);+ expect((err as Error).message).toBe('Client IP could not be determined');});it('rejects a malformed client IP instead of coercing it into an allowed range', async () => {@@ -852,16 +856,24 @@ describe('AuthService', () => {await expect(service.validateApiKey('ip-malformed', '10.0.0.1abc')).rejects.toThrow('IP address not allowed');});- it('should throw UnauthorizedException when session not in allowedSessions', async () => {+ it('answers 403, not 401, when the session is not in allowedSessions', async () => {const key = createMockApiKey({allowedSessions: ['session-A'],keyHash: hashKey('sess-restricted'),});(repository.findOne as jest.Mock).mockResolvedValue(key);- await expect(service.validateApiKey('sess-restricted', undefined, 'session-B')).rejects.toThrow(- 'API key not authorized for this session',- );+ const err = await service.validateApiKey('sess-restricted', undefined, 'session-B').catch((e: unknown) => e);+ expect(err).toBeInstanceOf(ForbiddenException);+ expect((err as Error).message).toBe('API key not authorized for this session');+ });++ it('keeps 401 for a revoked or expired key', async () => {+ for (const overrides of [{ isActive: false }, { expiresAt: new Date(Date.now() - 60_000) }]) {+ (repository.findOne as jest.Mock).mockResolvedValue(createMockApiKey(overrides));+ const err = await service.validateApiKey('raw').catch((e: unknown) => e);+ expect(err).toBeInstanceOf(UnauthorizedException);+ }});});diff --git a/src/modules/auth/auth.service.ts b/src/modules/auth/auth.service.tsindex 1d9bc26f2..901419b7f 100644--- a/src/modules/auth/auth.service.ts+++ b/src/modules/auth/auth.service.ts@@ -1,5 +1,6 @@import {ConflictException,+ ForbiddenException,Injectable,NotFoundException,UnauthorizedException,@@ -24,9 +25,9 @@ import { EventsGateway, type ApiKeyEvictionReason } from '../events/events.gatew/*** A 401 that names no stored key: the credential was missing or matched no row. Producing one costs- * the caller nothing, so its audit row is bounded per client IP. Every other 401 (revoked, expired,- * IP or session refused) required a real key and is audited on every attempt. The name stays- * `UnauthorizedException` because MCP tool errors carry it on the wire.+ * the caller nothing, so its audit row is bounded per client IP. Every other rejection (a revoked or+ * expired key's 401, an IP or session refusal's 403) required a real key and is audited on every+ * attempt. The name stays `UnauthorizedException` because MCP tool errors carry it on the wire.*/export class UnresolvedApiKeyException extends UnauthorizedException {constructor(message: string) {@@ -484,25 +485,28 @@ export class AuthService implements OnModuleInit, OnModuleDestroy {throw new UnauthorizedException('API key has expired');}+ // A live key refused by its own IP or session restriction answers 403, like every other scope+ // refusal (role, chats): the key is valid, so a client must not read it as one to discard.+// Check IP whitelist (fail closed: if a whitelist is configured but the client// IP could not be determined, reject rather than silently skipping the check)if (apiKey.allowedIps && apiKey.allowedIps.length > 0) {if (!clientIp) {- throw new UnauthorizedException('Client IP could not be determined');+ throw new ForbiddenException('Client IP could not be determined');}if (!this.isIpAllowed(clientIp, apiKey.allowedIps)) {this.logger.warn(`IP not allowed: ${clientIp}`, {keyId: apiKey.id,action: 'ip_rejected',});- throw new UnauthorizedException('IP address not allowed');+ throw new ForbiddenException('IP address not allowed');}}// Check session restrictionif (apiKey.allowedSessions && apiKey.allowedSessions.length > 0 && sessionId) {if (!apiKey.allowedSessions.includes(sessionId)) {- throw new UnauthorizedException('API key not authorized for this session');+ throw new ForbiddenException('API key not authorized for this session');}}diff --git a/src/modules/auth/guards/api-key.guard.spec.ts b/src/modules/auth/guards/api-key.guard.spec.tsindex 6afda9801..40c5f920c 100644--- a/src/modules/auth/guards/api-key.guard.spec.ts+++ b/src/modules/auth/guards/api-key.guard.spec.ts@@ -250,11 +250,15 @@ describe('ApiKeyGuard', () => {await settle();expect(auditService.logWarn).toHaveBeenCalledTimes(10);- for (const message of ['API key is revoked', 'API key has expired', 'API key not authorized for this session']) {- (authService.validateApiKey as jest.Mock).mockRejectedValue(new UnauthorizedException(message));- await expect(- guard.canActivate(createMockContext({ 'x-api-key': 'stored' }, {}, '198.51.100.74')),- ).rejects.toThrow(message);+ for (const err of [+ new UnauthorizedException('API key is revoked'),+ new UnauthorizedException('API key has expired'),+ new ForbiddenException('API key not authorized for this session'),+ ]) {+ (authService.validateApiKey as jest.Mock).mockRejectedValue(err);+ await expect(guard.canActivate(createMockContext({ 'x-api-key': 'stored' }, {}, '198.51.100.74'))).rejects.toBe(+ err,+ );}await settle();expect(auditService.logWarn).toHaveBeenCalledTimes(13);diff --git a/src/modules/mcp/mcp.server.spec.ts b/src/modules/mcp/mcp.server.spec.tsindex b10f12a56..74cc709ea 100644--- a/src/modules/mcp/mcp.server.spec.ts+++ b/src/modules/mcp/mcp.server.spec.ts@@ -198,9 +198,9 @@ describe('auditMcpAuthFailure (MCP auth-failure audit trail, mirrors REST ApiKeyexpect(call[1].errorMessage).toBe('API key lacks the required role');});- it('mirrors the REST guard exactly: IP-not-allowed (Unauthorized) is audited', () => {- // validateApiKey throws Unauthorized for IP-not-allowed / revoked / expired / session-not-allowed.- auditMcpAuthFailure(auditService, new UnauthorizedException('IP address not allowed'), reqContext);+ it('mirrors the REST guard exactly: IP-not-allowed (Forbidden) is audited', () => {+ // validateApiKey throws Forbidden for IP-not-allowed / session-not-allowed, Unauthorized for revoked / expired.+ auditMcpAuthFailure(auditService, new ForbiddenException('IP address not allowed'), reqContext);expect(auditService.logWarn).toHaveBeenCalledWith(AuditAction.API_KEY_AUTH_FAILED,expect.objectContaining({ errorMessage: 'IP address not allowed' }),diff --git a/test/global-routes-session-scope.e2e-spec.ts b/test/global-routes-session-scope.e2e-spec.tsindex 64ce2d408..c92db1b99 100644--- a/test/global-routes-session-scope.e2e-spec.ts+++ b/test/global-routes-session-scope.e2e-spec.ts@@ -9,9 +9,11 @@ import request from 'supertest';import { App } from 'supertest/types';import { AppModule } from './../src/app.module';import { applyGlobalValidation } from './../src/config/app-validation';+import { requestContextMiddleware } from './../src/common/middleware/request-context.middleware';import { AuthService } from './../src/modules/auth/auth.service';import { ApiKeyRole } from './../src/modules/auth/entities/api-key.entity';import { Session } from './../src/modules/session/entities/session.entity';+import { AuditAction, AuditLog } from './../src/modules/audit/entities/audit-log.entity';/*** Cross-session aggregates, environment-derived settings, and session creation all act outside any@@ -22,6 +24,7 @@ import { Session } from './../src/modules/session/entities/session.entity';describe('Global read and create routes reject session-scoped keys (e2e)', () => {let app: INestApplication<App>;let scopedAdminKey: string; // ADMIN, allowedSessions: [sessA]+ let scopedAdminKeyId: string;let scopedOperatorKey: string; // OPERATOR, allowedSessions: [sessA]let adminKey: string; // ADMIN, unrestrictedlet scopedSessionId: string; // the session the scoped keys are confined to@@ -30,6 +33,8 @@ describe('Global read and create routes reject session-scoped keys (e2e)', () =>const moduleFixture: TestingModule = await Test.createTestingModule({ imports: [AppModule] }).compile();app = moduleFixture.createNestApplication();applyGlobalValidation(app);+ // Installed by configureApp in production; audit rows take their key from this context.+ app.use(requestContextMiddleware);await app.init();const sessionRepo: Repository<Session> = app.get(getRepositoryToken(Session, 'data'));@@ -37,9 +42,13 @@ describe('Global read and create routes reject session-scoped keys (e2e)', () =>scopedSessionId = a.id;const authService = app.get(AuthService);- scopedAdminKey = (- await authService.createApiKey({ name: 'e2e-global-scoped', role: ApiKeyRole.ADMIN, allowedSessions: [a.id] })- ).rawKey;+ const scoped = await authService.createApiKey({+ name: 'e2e-global-scoped',+ role: ApiKeyRole.ADMIN,+ allowedSessions: [a.id],+ });+ scopedAdminKey = scoped.rawKey;+ scopedAdminKeyId = scoped.apiKey.id;scopedOperatorKey = (await authService.createApiKey({ name: 'e2e-global-op', role: ApiKeyRole.OPERATOR, allowedSessions: [a.id] })).rawKey;@@ -98,14 +107,24 @@ describe('Global read and create routes reject session-scoped keys (e2e)', () =>});it('denies a session-scoped key per-session stats for a session outside its scope', async () => {- // The param-scope check surfaces as 401 (the key is not authorized for that session) — a- // different code path than the fence's 403 above, pinned here so the two are not conflated.+ // The param-scope check refuses a live key, so it answers 403 like the fence above, and the audit+ // row names the key that was refused.const sessionRepo: Repository<Session> = app.get(getRepositoryToken(Session, 'data'));const other = await sessionRepo.save(sessionRepo.create({ name: `e2e-global-scope-other-${Date.now()}` }));- await request(app.getHttpServer())+ const res = await request(app.getHttpServer()).get(`/api/stats/sessions/${other.id}`).set('X-API-Key', scopedAdminKey)- .expect(401);+ .expect(403);+ expect((res.body as { message: string }).message).toBe('API key not authorized for this session');++ const auditRepo: Repository<AuditLog> = app.get(getRepositoryToken(AuditLog, 'main'));+ const path = `/api/stats/sessions/${other.id}`;+ let row: AuditLog | null = null;+ for (let i = 0; i < 50 && !row; i++) {+ row = await auditRepo.findOne({ where: { action: AuditAction.API_KEY_AUTH_FAILED, path } });+ if (!row) await new Promise(resolve => setTimeout(resolve, 20));+ }+ expect(row?.apiKeyId).toBe(scopedAdminKeyId);});it('leaves an unrestricted ADMIN able to create a session', async () => {diff --git a/test/mcp-auth.e2e-spec.ts b/test/mcp-auth.e2e-spec.tsindex de543e47e..5f72d174b 100644--- a/test/mcp-auth.e2e-spec.ts+++ b/test/mcp-auth.e2e-spec.ts@@ -164,7 +164,8 @@ describe('MCP server (e2e)', () => {.set('X-API-Key', ipKey).send(jsonRpcRequest('tools/list'));- expect(res.status).toBe(401);+ expect(res.status).toBe(403);+ expect(res.headers['www-authenticate']).toBeUndefined();});// Role, session and chat scope stay per tool call, answered in-band once the key passes the gate.