Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): harden the routing interceptor — client identity, malformed ids, forged hop markers

Yudhi Armyndharis43dcd9170c04
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 70c5a84ce..5f3995385 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -35,6 +35,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- A media-storage root the app cannot write to is caught at boot with a clear error, instead of failing on the first write (#1066).
- The bundled `docker-compose.yml` now forwards the `SEND_PACING_*`, `MEDIA_CONVERSION_*`/`FFMPEG_PATH` and session-ownership (`NODE_ID`, `NODE_URL`, lease/sweep) variables — previously these features could not be enabled from `.env` in a compose deployment at all.
- The four label write tools (`LabelUpsert`, `LabelDelete`, `LabelAddToChat`, `LabelRemoveFromChat`) answered `Internal error` over MCP even though the write had succeeded on WhatsApp, prompting agents to retry a completed operation; they now return `{ success: true }`.
+- **Multi-node request routing hardening:** forwarded requests now carry the client address in `x-forwarded-for` (so `allowedIps` keys and per-IP throttling see the real client once peer nodes are listed in `TRUSTED_PROXIES`), a malformed session id no longer 500s on Postgres in routed mode, and the client-settable forwarded marker is verified — a marked request landing on a live non-owner answers 409 instead of executing there.
- **Send pacing accounting:** forwards now pass through the cold-reachout gate (they were ungated while still draining the budget), replying to someone who wrote first today no longer spends the cold budget, and a pacing 429 inside a bulk batch is recorded as `SEND_PACING_LIMITED` instead of a generic `SEND_FAILED`.
- **Multi-node: a session claim could outlive its engine and pin the session to one node forever.** A failed start, a logout, a force-kill or an exhausted reconnect kept the ownership claim, and the heartbeat renewed it indefinitely — the session could not be started on any peer and the takeover sweep never saw it. Claims are now released on every teardown path, and the heartbeat only renews claims that still cover a live engine, an in-flight start or a pending reconnect. Starting a nonexistent session also answers 404 again instead of a misleading 409 "running on another node".
- Corrected column names in `docs/05-database-design.md`.
diff --git a/docs/13-horizontal-scaling.md b/docs/13-horizontal-scaling.md
index 386b1afc3..121dc0c58 100644
--- a/docs/13-horizontal-scaling.md
+++ b/docs/13-horizontal-scaling.md
@@ -41,11 +41,18 @@
> (`x-openwa-served-by` names it). The forward happens after API-key auth, carries the
> caller's credentials (both nodes share the auth database), is bounded by
> `SESSION_PROXY_TIMEOUT_MS` (default 60s), and is one hop only — a forwarded request is
-> never forwarded again, so stale ownership degrades to a wrong-node answer instead of a
-> loop. A lapsed owner is deliberately NOT forwarded to: the local node handles the request,
+> never forwarded again; one that still lands on a live non-owner (stale ownership, or a
+> client-forged hop marker) is refused with a retryable 409 rather than executed there. A
+> lapsed owner is deliberately NOT forwarded to: the local node handles the request,
> which is exactly how a takeover begins. Without `NODE_URL` the whole path is inert and
> single-node deployments pay nothing.
>
+> Forwards carry the client address in `x-forwarded-for` (inbound chain preserved, the
+> observed peer appended). For an `allowedIps`-restricted key or the per-IP throttler to see
+> the REAL client on forwarded calls, each node must list its peer nodes' addresses in its
+> `TRUSTED_PROXIES` — otherwise the owner (correctly) ignores the chain and every forwarded
+> request appears to come from the peer node itself.
+>
> **WebSocket events now fan out across replicas** when Redis is enabled (`REDIS_ENABLED=true`,
> the same flag the throttler and cache already use). The gateway broadcasts to rooms; a Redis
> pub/sub adapter attached to Socket.IO relays those broadcasts to every replica, so a client
diff --git a/src/modules/session/session-proxy.interceptor.spec.ts b/src/modules/session/session-proxy.interceptor.spec.ts
index 9784cda4e..e6957462a 100644
--- a/src/modules/session/session-proxy.interceptor.spec.ts
+++ b/src/modules/session/session-proxy.interceptor.spec.ts
@@ -14,8 +14,12 @@ import type { Session } from './entities/session.entity';
* would vacuously approve.
*/
describe('SessionProxyInterceptor', () => {
+ // A real UUID: the interceptor refuses to route malformed ids (they cannot name a session, and a
+ // raw uuid-column lookup on Postgres would 500 before the route pipe could answer 400).
+ const SID = '3f8d1c2a-4b6e-4f0d-9a7c-2e5b8d1f6a3c';
+
const row = (over: Partial<Session> = {}): Partial<Session> => ({
- id: 'sess-1',
+ id: SID,
nodeId: 'peer-node',
nodeUrl: 'http://127.0.0.1:9',
leaseExpiresAt: new Date(Date.now() + 60_000),
@@ -28,13 +32,14 @@ describe('SessionProxyInterceptor', () => {
method: string;
originalUrl: string;
body?: unknown;
+ socket?: { remoteAddress?: string };
};
const request = (over: Partial<Req> = {}): Req => ({
headers: { 'x-api-key': 'k-123', 'content-type': 'application/json' },
- params: { sessionId: 'sess-1' },
+ params: { sessionId: SID },
method: 'GET',
- originalUrl: '/api/sessions/sess-1/messages?limit=5',
+ originalUrl: `/api/sessions/${SID}/messages?limit=5`,
...over,
});
@@ -87,8 +92,31 @@ describe('SessionProxyInterceptor', () => {
expect(findOne).not.toHaveBeenCalled();
});
- it('never forwards a forwarded request (loop guard), even when the owner looks remote', async () => {
+ // The hop marker is client-settable: honoring it blindly would let any authenticated caller
+ // force local execution on a non-owner (a stop() here writes DISCONNECTED while the owner's
+ // engine stays up). The refusal doubles as the loop guard — a marked request is never
+ // forwarded again, it is answered with a retryable conflict instead.
+ it('refuses (409) a request already marked forwarded that lands on a live non-owner', async () => {
const req = request({ headers: { [FORWARDED_HEADER]: 'peer-node', 'x-api-key': 'k' } });
+ const { interceptor, context, next, handle } = build({ req });
+ await expect(interceptor.intercept(context, next)).rejects.toMatchObject({ status: 409 });
+ expect(handle).not.toHaveBeenCalled();
+ });
+
+ it('executes a forwarded request locally when this node hosts (or may host) the session', async () => {
+ const req = request({ headers: { [FORWARDED_HEADER]: 'peer-node', 'x-api-key': 'k' } });
+ const owned = build({ req, row: row({ nodeId: 'me' }) });
+ expect(await ranLocally(await owned.interceptor.intercept(owned.context, owned.next))).toBe(true);
+
+ const unowned = build({
+ req: request({ headers: { [FORWARDED_HEADER]: 'peer-node', 'x-api-key': 'k' } }),
+ row: row({ nodeId: null }),
+ });
+ expect(await ranLocally(await unowned.interceptor.intercept(unowned.context, unowned.next))).toBe(true);
+ });
+
+ it('skips routing for a malformed id — the route pipe answers 400, not a raw uuid-column query', async () => {
+ const req = request({ params: { sessionId: 'not-a-uuid' } });
const { interceptor, context, next, findOne } = build({ req });
expect(await ranLocally(await interceptor.intercept(context, next))).toBe(true);
expect(findOne).not.toHaveBeenCalled();
@@ -101,12 +129,12 @@ describe('SessionProxyInterceptor', () => {
});
it('reads :id only on @SessionScoped controllers', async () => {
- const req = request({ params: { id: 'sess-1' } });
+ const req = request({ params: { id: SID } });
const scoped = build({ req, sessionScoped: true, row: row({ nodeId: 'me' }) });
expect(await ranLocally(await scoped.interceptor.intercept(scoped.context, scoped.next))).toBe(true);
expect(scoped.findOne).toHaveBeenCalled();
- const unscoped = build({ req: request({ params: { id: 'sess-1' } }), sessionScoped: false });
+ const unscoped = build({ req: request({ params: { id: SID } }), sessionScoped: false });
expect(await ranLocally(await unscoped.interceptor.intercept(unscoped.context, unscoped.next))).toBe(true);
expect(unscoped.findOne).not.toHaveBeenCalled();
});
@@ -154,7 +182,7 @@ describe('SessionProxyInterceptor', () => {
it('relays method, path, query, body and auth to the owner, and the owner’s answer back', async () => {
const req = request({
method: 'POST',
- originalUrl: '/api/sessions/sess-1/messages/send-text?trace=1',
+ originalUrl: `/api/sessions/${SID}/messages/send-text?trace=1`,
body: { chatId: '[email protected]', text: 'halo' },
});
const { interceptor, context, next, handle, res } = build({ req, row: row({ nodeUrl: serverUrl }) });
@@ -166,7 +194,7 @@ describe('SessionProxyInterceptor', () => {
expect(seen).toHaveLength(1);
expect(seen[0].method).toBe('POST');
- expect(seen[0].url).toBe('/api/sessions/sess-1/messages/send-text?trace=1');
+ expect(seen[0].url).toBe(`/api/sessions/${SID}/messages/send-text?trace=1`);
expect(seen[0].headers['x-api-key']).toBe('k-123');
expect(seen[0].headers[FORWARDED_HEADER]).toBe('me');
expect(JSON.parse(seen[0].body)).toEqual({ chatId: '[email protected]', text: 'halo' });
@@ -188,6 +216,28 @@ describe('SessionProxyInterceptor', () => {
expect(seen[0].body).toBe('');
});
+ // Without the chain the owner sees every forwarded call as coming from THIS node — an
+ // allowedIps-restricted key 401s on every forwarded request, and the per-IP throttler pools
+ // all forwarded traffic into one bucket.
+ it('appends the observed peer to x-forwarded-for so the owner can resolve the real client', async () => {
+ const direct = build({
+ req: request({ socket: { remoteAddress: '::ffff:203.0.113.7' } }),
+ row: row({ nodeUrl: serverUrl }),
+ });
+ await direct.interceptor.intercept(direct.context, direct.next);
+ expect(seen[0].headers['x-forwarded-for']).toBe('203.0.113.7');
+
+ const chained = build({
+ req: request({
+ headers: { 'x-api-key': 'k-123', 'x-forwarded-for': '198.51.100.9' },
+ socket: { remoteAddress: '10.0.0.4' },
+ }),
+ row: row({ nodeUrl: serverUrl }),
+ });
+ await chained.interceptor.intercept(chained.context, chained.next);
+ expect(seen[1].headers['x-forwarded-for']).toBe('198.51.100.9, 10.0.0.4');
+ });
+
it('an unreachable owner answers 503 with the owner named, never a hang or a crash', async () => {
const { interceptor, context, next, handle, res } = build({
row: row({ nodeUrl: 'http://127.0.0.1:1' }),
diff --git a/src/modules/session/session-proxy.interceptor.ts b/src/modules/session/session-proxy.interceptor.ts
index ada05ebaa..efc8a835c 100644
--- a/src/modules/session/session-proxy.interceptor.ts
+++ b/src/modules/session/session-proxy.interceptor.ts
@@ -1,7 +1,15 @@
-import { CallHandler, ExecutionContext, Injectable, NestInterceptor, Optional } from '@nestjs/common';
+import {
+ CallHandler,
+ ConflictException,
+ ExecutionContext,
+ Injectable,
+ NestInterceptor,
+ Optional,
+} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Reflector } from '@nestjs/core';
import { InjectRepository } from '@nestjs/typeorm';
+import { isUUID } from 'class-validator';
import { Repository } from 'typeorm';
import { EMPTY, Observable } from 'rxjs';
import type { Request, Response } from 'express';
@@ -9,6 +17,7 @@ import { Session } from './entities/session.entity';
import { SessionOwnershipService } from './session-ownership.service';
import { SESSION_SCOPED_KEY } from '../auth/decorators/auth.decorators';
import { createLogger } from '../../common/services/logger.service';
+import { normalizeIp } from '../../common/utils/ip';
/** The request headers a forwarded call carries over. Everything else is this hop's business. */
const FORWARDED_REQUEST_HEADERS = ['x-api-key', 'authorization', 'content-type', 'accept'] as const;
@@ -37,8 +46,10 @@ export const FORWARDED_HEADER = 'x-openwa-forwarded';
* request (a POST /start claims it here) is the takeover semantic, not an error.
* - A live owner WITHOUT a nodeUrl cannot be reached; the request proceeds locally and the
* engine-level "held by another node" conflict answers it — precise, if unrouteable.
- * - One hop only: a forwarded request is never forwarded again (FORWARDED_HEADER), so stale
- * ownership data degrades to a wrong-node answer instead of a loop.
+ * - One hop only: a forwarded request is never forwarded again (FORWARDED_HEADER). The marker is
+ * client-settable, so it is verified rather than trusted: a marked request that still lands on a
+ * live non-owner — forged, or ownership moved mid-flight — is refused with a retryable 409
+ * instead of executed against a node with no engine.
*/
@Injectable()
export class SessionProxyInterceptor implements NestInterceptor {
@@ -61,10 +72,13 @@ export class SessionProxyInterceptor implements NestInterceptor {
if (!this.ownership.nodeUrl) return next.handle();
const request = context.switchToHttp().getRequest<Request>();
- if (request.headers[FORWARDED_HEADER]) return next.handle();
const sessionId = this.sessionIdOf(context, request);
if (!sessionId) return next.handle();
+ // A malformed id cannot name a routed session, and on Postgres a raw findOne against the uuid
+ // column throws (a 500) before the route's ParseUUIDPipe could answer 400 — skip routing and
+ // let the pipe reject it.
+ if (!isUUID(sessionId)) return next.handle();
const owner = await this.sessions.findOne({
where: { id: sessionId },
@@ -72,7 +86,17 @@ export class SessionProxyInterceptor implements NestInterceptor {
});
if (!owner?.nodeId || owner.nodeId === this.ownership.nodeId) return next.handle();
const leaseLive = owner.leaseExpiresAt != null && owner.leaseExpiresAt > new Date();
- if (!leaseLive || !owner.nodeUrl) return next.handle();
+ if (!leaseLive) return next.handle();
+
+ // One hop only — but never "execute anywhere": the hop marker is client-settable, so a request
+ // marked forwarded that still lands on a live non-owner (forged header, or ownership moved
+ // mid-flight) is refused rather than run here — a stop() on this node would write DISCONNECTED
+ // while the owner's engine stays up. A retry re-routes against fresh ownership data.
+ if (request.headers[FORWARDED_HEADER]) {
+ throw new ConflictException(`Session ${sessionId} is running on another node`);
+ }
+
+ if (!owner.nodeUrl) return next.handle();
await this.forward(request, context.switchToHttp().getResponse<Response>(), owner.nodeId, owner.nodeUrl);
// The response has been written; complete without emitting so nothing downstream re-answers it.
@@ -104,6 +128,17 @@ export class SessionProxyInterceptor implements NestInterceptor {
if (typeof value === 'string') headers[name] = value;
}
+ // The owner re-authenticates the forwarded call (allowedIps) and throttles per client IP, so
+ // the chain must carry what this hop observed — without it every forwarded call shows up as
+ // THIS node's address. Standard proxy behavior: relay the inbound chain, append the immediate
+ // peer. The owner only honors the chain when this node is in its TRUSTED_PROXIES (docs/13).
+ const inbound = request.headers['x-forwarded-for'];
+ const inboundChain = Array.isArray(inbound) ? inbound.join(', ') : inbound;
+ const observedPeer = normalizeIp(request.socket?.remoteAddress || request.ip || '');
+ if (observedPeer) {
+ headers['x-forwarded-for'] = inboundChain ? `${inboundChain}, ${observedPeer}` : observedPeer;
+ }
+
const hasBody = !['GET', 'HEAD'].includes(request.method);
try {
const upstream = await fetch(target, {