Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(security): warn once when the throttler collapses onto a single proxy bucket

Yudhi Armyndharis759d51f8242d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d7333222a..ea42ab4e2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Fixed
+
+- A one-time warning fires when a proxied request arrives with an empty `TRUSTED_PROXIES`: every client then shares one rate-limit bucket keyed on the proxy. The nginx FAQ recipe now tells operators to set it.
+
### Security
- `PUT /sessions/{sessionId}/webhooks/{id}` now enforces the same 16-character webhook-secret floor as create; an empty string still clears signing.
diff --git a/docs/12-troubleshooting-faq.md b/docs/12-troubleshooting-faq.md
index fafc82968..634fd87f3 100644
--- a/docs/12-troubleshooting-faq.md
+++ b/docs/12-troubleshooting-faq.md
@@ -1135,6 +1135,16 @@ server {
}
```
+**Then set `TRUSTED_PROXIES` in your `.env`.** With it empty, OpenWA correctly refuses to trust the
+spoofable `X-Forwarded-For` header, which has a side effect worth knowing: every client appears as
+the proxy's address, so ALL traffic shares one rate-limit bucket (a single abuser rate-limits
+everyone) and per-key IP allowlists (`allowedIps`) evaluate the proxy for every caller. Name the
+proxy to key limits per client. For the bundled compose (whose published port traverses Docker's
+NAT, so the container sees the bridge gateway, not 127.0.0.1) use the compose network subnet, e.g.
+`TRUSTED_PROXIES=172.18.0.0/16`; a bare-metal nginx talking to the process directly can name
+`127.0.0.1`. OpenWA logs a one-time warning at the first proxied request when the header is present
+but the list is empty.
+
**Q: How to run behind Traefik / Coolify?**
Traefik forwards WebSocket upgrades automatically, so OpenWA's single-port Socket.IO channel works with a normal HTTP router. Two things keep a public deployment stable:
diff --git a/src/common/security/proxy-aware-throttler.guard.spec.ts b/src/common/security/proxy-aware-throttler.guard.spec.ts
index acae1544f..3fd14cdb3 100644
--- a/src/common/security/proxy-aware-throttler.guard.spec.ts
+++ b/src/common/security/proxy-aware-throttler.guard.spec.ts
@@ -6,8 +6,21 @@ import { ProxyAwareThrottlerGuard } from './proxy-aware-throttler.guard';
* Regression lock: the throttler must bucket on the resolved client IP, not the
* proxy IP — so one abusive client cannot rate-limit everyone behind a reverse proxy.
*/
+const reqFrom = (socketIp: string, xff?: string): unknown => ({
+ ip: socketIp,
+ socket: { remoteAddress: socketIp },
+ headers: xff !== undefined ? { 'x-forwarded-for': xff } : {},
+});
+
describe('ProxyAwareThrottlerGuard.getTracker', () => {
const orig = process.env.TRUSTED_PROXIES;
+ // The shared instance below trips the shared-bucket warning once (first test sends an XFF);
+ // silence it so the suite output stays clean; the warning itself has its own describe below.
+ let warn: jest.SpyInstance;
+ beforeEach(() => {
+ warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined);
+ });
+ afterEach(() => warn.mockRestore());
// getTracker uses only process.env + the pure resolveClientIp (no `this`), so we can
// invoke it on a prototype instance without the throttler's storage/reflector deps.
@@ -15,12 +28,6 @@ describe('ProxyAwareThrottlerGuard.getTracker', () => {
const track = (req: unknown): Promise<string> =>
(guard as unknown as { getTracker(r: unknown): Promise<string> }).getTracker(req);
- const reqFrom = (socketIp: string, xff?: string): unknown => ({
- ip: socketIp,
- socket: { remoteAddress: socketIp },
- headers: xff ? { 'x-forwarded-for': xff } : {},
- });
-
afterEach(() => {
if (orig === undefined) delete process.env.TRUSTED_PROXIES;
else process.env.TRUSTED_PROXIES = orig;
@@ -50,6 +57,64 @@ describe('ProxyAwareThrottlerGuard.getTracker', () => {
});
});
+/**
+ * An X-Forwarded-For header with an empty TRUSTED_PROXIES is the deployment-wide shared-bucket
+ * condition (every client keys on the proxy address); it must surface as a one-time warning rather
+ * than stay silent. The header stays untrusted either way; the fix is operator-side.
+ */
+describe('ProxyAwareThrottlerGuard shared-bucket warning', () => {
+ const orig = process.env.TRUSTED_PROXIES;
+ let warn: jest.SpyInstance;
+
+ const trackOn = (guard: unknown, req: unknown): Promise<string> =>
+ (guard as { getTracker(r: unknown): Promise<string> }).getTracker(req);
+
+ beforeEach(() => {
+ warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined);
+ });
+ afterEach(() => {
+ warn.mockRestore();
+ if (orig === undefined) delete process.env.TRUSTED_PROXIES;
+ else process.env.TRUSTED_PROXIES = orig;
+ });
+
+ it('warns exactly once when a proxied request arrives with no trusted proxies', async () => {
+ delete process.env.TRUSTED_PROXIES;
+ const guard = Object.create(ProxyAwareThrottlerGuard.prototype) as ProxyAwareThrottlerGuard;
+
+ expect(await trackOn(guard, reqFrom('172.18.0.5', '203.0.113.9'))).toBe('172.18.0.5');
+ expect(await trackOn(guard, reqFrom('172.18.0.5', '198.51.100.7'))).toBe('172.18.0.5');
+
+ expect(warn).toHaveBeenCalledTimes(1);
+ expect(String(warn.mock.calls[0])).toContain('TRUSTED_PROXIES is empty');
+ });
+
+ it('stays silent when the proxy is trusted', async () => {
+ process.env.TRUSTED_PROXIES = '172.18.0.0/16';
+ const guard = Object.create(ProxyAwareThrottlerGuard.prototype) as ProxyAwareThrottlerGuard;
+
+ expect(await trackOn(guard, reqFrom('172.18.0.5', '203.0.113.9'))).toBe('203.0.113.9');
+ expect(warn).not.toHaveBeenCalled();
+ });
+
+ it('warns for an empty-string XFF header too (a stripped header still means a proxy hop)', async () => {
+ delete process.env.TRUSTED_PROXIES;
+ const guard = Object.create(ProxyAwareThrottlerGuard.prototype) as ProxyAwareThrottlerGuard;
+
+ expect(await trackOn(guard, reqFrom('172.18.0.5', ''))).toBe('172.18.0.5');
+
+ expect(warn).toHaveBeenCalledTimes(1);
+ });
+
+ it('stays silent for direct traffic with no XFF header', async () => {
+ delete process.env.TRUSTED_PROXIES;
+ const guard = Object.create(ProxyAwareThrottlerGuard.prototype) as ProxyAwareThrottlerGuard;
+
+ expect(await trackOn(guard, reqFrom('203.0.113.9'))).toBe('203.0.113.9');
+ expect(warn).not.toHaveBeenCalled();
+ });
+});
+
/**
* Regression lock: a bare `@SkipThrottle()` must actually exempt the route.
*
diff --git a/src/common/security/proxy-aware-throttler.guard.ts b/src/common/security/proxy-aware-throttler.guard.ts
index 7ab8d9d52..615d81685 100644
--- a/src/common/security/proxy-aware-throttler.guard.ts
+++ b/src/common/security/proxy-aware-throttler.guard.ts
@@ -1,6 +1,9 @@
import { ExecutionContext, Injectable } from '@nestjs/common';
import { ThrottlerGuard } from '@nestjs/throttler';
import { resolveClientIp, RequestLike } from '../utils/ip';
+import { createLogger } from '../services/logger.service';
+
+const logger = createLogger('ProxyAwareThrottlerGuard');
/**
* The single metadata key a bare `@SkipThrottle()` writes.
@@ -25,11 +28,35 @@ const LIBRARY_DEFAULT_SKIP_KEY = 'THROTTLER:SKIPdefault';
*/
@Injectable()
export class ProxyAwareThrottlerGuard extends ThrottlerGuard {
+ /**
+ * The shared-bucket condition is deployment-wide, so the warning fires once per guard instance.
+ * In practice that is once per process: this guard runs as the singleton APP_GUARD. The only other
+ * instance is InstanceThrottlerGuard, whose defensive super.getTracker fallback (missing route
+ * params) is unreachable on the real ingress route, so at most one extra line could ever appear.
+ */
+ private warnedSharedProxyBucket = false;
+
protected getTracker(req: Record<string, unknown>): Promise<string> {
const trustedProxies = (process.env.TRUSTED_PROXIES || '')
.split(',')
.map(proxy => proxy.trim())
.filter(Boolean);
+ // An X-Forwarded-For header with an empty TRUSTED_PROXIES is the silent self-DoS this guard
+ // exists to prevent: every client collapses onto the proxy's socket address, so all traffic
+ // shares ONE bucket per tier and one abuser rate-limits everyone. The header itself must stay
+ // untrusted (spoofable), so the fix is operator-side: name the proxy in TRUSTED_PROXIES. Warn
+ // once instead of per request; the stock-resolve fallback below is still the safe default.
+ if (trustedProxies.length === 0 && !this.warnedSharedProxyBucket) {
+ const headers = (req.headers ?? {}) as Record<string, unknown>;
+ if (headers['x-forwarded-for'] !== undefined) {
+ this.warnedSharedProxyBucket = true;
+ logger.warn(
+ 'X-Forwarded-For is present but TRUSTED_PROXIES is empty: every client shares one ' +
+ 'rate-limit bucket keyed on the proxy address (and per-key IP allowlists see the proxy ' +
+ 'too). Set TRUSTED_PROXIES to the proxy address/subnet to key limits per client.',
+ );
+ }
+ }
return Promise.resolve(resolveClientIp(req as unknown as RequestLike, trustedProxies));
}