Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(auth): prevent X-Forwarded-For IP spoofing of the API-key whitelist (#211)
Yudhi Armyndharis7da5c841d847
diff --git a/.env.example b/.env.exampleindex dd481681e..181e429a9 100644--- a/.env.example+++ b/.env.example@@ -26,6 +26,13 @@ CORS_ORIGINS=*# TRAEFIK_ACME_STORAGE=/letsencrypt/acme.json+# Trusted reverse proxies (comma-separated IPs/CIDRs) whose X-Forwarded-For+# header is trusted to determine the real client IP for API-key IP whitelisting.+# Leave empty (default) to ignore X-Forwarded-For and use the direct socket+# address, which prevents IP spoofing. If you run behind Traefik/nginx AND use+# per-key allowedIps restrictions, set this to the proxy's address/subnet, e.g.:+# TRUSTED_PROXIES=172.18.0.0/16+# =============================================================================# COMPONENTS (enable/disable container profiles)# =============================================================================diff --git a/src/common/utils/ip.spec.ts b/src/common/utils/ip.spec.tsnew file mode 100644index 000000000..4210838bc--- /dev/null+++ b/src/common/utils/ip.spec.ts@@ -0,0 +1,42 @@+import { normalizeIp, ipMatches } from './ip';++describe('normalizeIp', () => {+ it('strips an IPv4-mapped IPv6 prefix', () => {+ expect(normalizeIp('::ffff:172.18.0.1')).toBe('172.18.0.1');+ });++ it('leaves a plain IPv4 address untouched', () => {+ expect(normalizeIp('10.0.0.1')).toBe('10.0.0.1');+ });++ it('leaves a real IPv6 address untouched', () => {+ expect(normalizeIp('2001:db8::1')).toBe('2001:db8::1');+ });+});++describe('ipMatches', () => {+ it('matches an exact IP', () => {+ expect(ipMatches('10.0.0.5', '10.0.0.5')).toBe(true);+ expect(ipMatches('10.0.0.6', '10.0.0.5')).toBe(false);+ });++ it('matches within an IPv4 CIDR range', () => {+ expect(ipMatches('172.18.3.4', '172.18.0.0/16')).toBe(true);+ expect(ipMatches('172.19.0.1', '172.18.0.0/16')).toBe(false);+ });++ it('normalizes an IPv4-mapped IPv6 address before matching a CIDR', () => {+ expect(ipMatches('::ffff:172.18.0.9', '172.18.0.0/16')).toBe(true);+ });++ it('handles /32 and /0 boundaries', () => {+ expect(ipMatches('1.2.3.4', '1.2.3.4/32')).toBe(true);+ expect(ipMatches('1.2.3.5', '1.2.3.4/32')).toBe(false);+ expect(ipMatches('9.9.9.9', '0.0.0.0/0')).toBe(true);+ });++ it('returns false for malformed input rather than throwing', () => {+ expect(ipMatches('not-an-ip', '10.0.0.0/8')).toBe(false);+ expect(ipMatches('10.0.0.1', 'garbage/99')).toBe(false);+ });+});diff --git a/src/common/utils/ip.ts b/src/common/utils/ip.tsnew file mode 100644index 000000000..8f1bee54c--- /dev/null+++ b/src/common/utils/ip.ts@@ -0,0 +1,49 @@+/**+ * Strip an IPv4-mapped IPv6 prefix so comparisons work consistently.+ * Node often reports socket addresses as `::ffff:1.2.3.4` behind dual-stack+ * listeners; this returns the bare `1.2.3.4`.+ */+export function normalizeIp(ip: string): string {+ if (!ip) return ip;+ const match = ip.match(/^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i);+ return match ? match[1] : ip;+}++function ipv4ToInt(ip: string): number | null {+ const parts = ip.split('.');+ if (parts.length !== 4) return null;+ let result = 0;+ for (const part of parts) {+ if (!/^\d{1,3}$/.test(part)) return null;+ const octet = Number(part);+ if (octet > 255) return null;+ result = result * 256 + octet;+ }+ return result >>> 0;+}++/**+ * True if `ip` equals or falls within `target`, where `target` is either an+ * exact IP or an IPv4 CIDR (e.g. `172.18.0.0/16`). IPv4-mapped IPv6 inputs are+ * normalized first. Malformed input yields `false` rather than throwing.+ */+export function ipMatches(ip: string, target: string): boolean {+ const candidate = normalizeIp((ip || '').trim());+ const ref = (target || '').trim();++ if (!ref.includes('/')) {+ return normalizeIp(ref) === candidate;+ }++ const [range, bitsRaw] = ref.split('/');+ const bits = Number(bitsRaw);+ if (!Number.isInteger(bits) || bits < 0 || bits > 32) return false;++ const ipInt = ipv4ToInt(candidate);+ const rangeInt = ipv4ToInt(normalizeIp(range));+ if (ipInt === null || rangeInt === null) return false;++ if (bits === 0) return true;+ const mask = (0xffffffff << (32 - bits)) >>> 0;+ return (ipInt & mask) === (rangeInt & mask);+}diff --git a/src/config/configuration.ts b/src/config/configuration.tsindex 2df110b07..bca9ce844 100644--- a/src/config/configuration.ts+++ b/src/config/configuration.ts@@ -77,6 +77,18 @@ export default () => ({},},+ // Security configuration+ security: {+ // Comma-separated IPs/CIDRs of reverse proxies whose X-Forwarded-For header+ // may be trusted for client-IP resolution. Empty by default: X-Forwarded-For+ // is ignored and the direct socket address is used, preventing spoofing of+ // the API-key allowedIps whitelist.+ trustedProxies: (process.env.TRUSTED_PROXIES || '')+ .split(',')+ .map(proxy => proxy.trim())+ .filter(Boolean),+ },+// Storage configurationstorage: {type: process.env.STORAGE_TYPE || 'local',diff --git a/src/modules/auth/guards/api-key.guard.spec.ts b/src/modules/auth/guards/api-key.guard.spec.tsindex 7d8c01d7f..87dd1fd45 100644--- a/src/modules/auth/guards/api-key.guard.spec.ts+++ b/src/modules/auth/guards/api-key.guard.spec.ts@@ -1,5 +1,6 @@import { ExecutionContext, UnauthorizedException } from '@nestjs/common';import { Reflector } from '@nestjs/core';+import { ConfigService } from '@nestjs/config';import { ApiKeyGuard } from './api-key.guard';import { AuthService } from '../auth.service';import { ApiKey, ApiKeyRole } from '../entities/api-key.entity';@@ -26,12 +27,13 @@ function createMockApiKey(overrides: Partial<ApiKey> = {}): ApiKey {function createMockContext(headers: Record<string, string> = {},params: Record<string, string> = {},+ socketIp = '127.0.0.1',): ExecutionContext {const request = {headers,params,- ip: '127.0.0.1',- socket: { remoteAddress: '127.0.0.1' },+ ip: socketIp,+ socket: { remoteAddress: socketIp },};return {@@ -47,6 +49,14 @@ describe('ApiKeyGuard', () => {let guard: ApiKeyGuard;let authService: jest.Mocked<Partial<AuthService>>;let reflector: jest.Mocked<Reflector>;+ let configService: jest.Mocked<Partial<ConfigService>>;++ function buildGuard(trustedProxies: string[] = []): ApiKeyGuard {+ configService = {+ get: jest.fn().mockReturnValue(trustedProxies),+ };+ return new ApiKeyGuard(authService as AuthService, reflector, configService as ConfigService);+ }beforeEach(() => {authService = {@@ -58,7 +68,7 @@ describe('ApiKeyGuard', () => {getAllAndOverride: jest.fn(),} as unknown as jest.Mocked<Reflector>;- guard = new ApiKeyGuard(authService as AuthService, reflector);+ guard = buildGuard();});it('should allow access to @Public() routes without API key', async () => {@@ -144,18 +154,64 @@ describe('ApiKeyGuard', () => {expect(authService.validateApiKey).toHaveBeenCalledWith('key', '127.0.0.1', 'sess-123');});- it('should extract client IP from X-Forwarded-For header', async () => {+ it('ignores X-Forwarded-For by default (no trusted proxies) to prevent IP spoofing', async () => {reflector.getAllAndOverride.mockReturnValueOnce(false).mockReturnValueOnce(undefined);const apiKey = createMockApiKey();(authService.validateApiKey as jest.Mock).mockResolvedValue(apiKey);+ // Attacker forges X-Forwarded-For; the direct socket IP must win.const context = createMockContext({'x-api-key': 'key','x-forwarded-for': '203.0.113.50, 70.41.3.18',});await guard.canActivate(context);+ expect(authService.validateApiKey).toHaveBeenCalledWith('key', '127.0.0.1', undefined);+ });++ it('uses the rightmost untrusted hop when the request comes from a trusted proxy', async () => {+ guard = buildGuard(['10.0.0.0/8']);+ reflector.getAllAndOverride.mockReturnValueOnce(false).mockReturnValueOnce(undefined);++ const apiKey = createMockApiKey();+ (authService.validateApiKey as jest.Mock).mockResolvedValue(apiKey);++ // Direct peer 10.0.0.1 is a trusted proxy; XFF = [real client, inner proxy].+ const context = createMockContext(+ { 'x-api-key': 'key', 'x-forwarded-for': '203.0.113.50, 10.0.0.5' },+ {},+ '10.0.0.1',+ );+ await guard.canActivate(context);++ expect(authService.validateApiKey).toHaveBeenCalledWith('key', '203.0.113.50', undefined);+ });++ it('ignores X-Forwarded-For when the direct peer is not a trusted proxy', async () => {+ guard = buildGuard(['10.0.0.0/8']);+ reflector.getAllAndOverride.mockReturnValueOnce(false).mockReturnValueOnce(undefined);++ const apiKey = createMockApiKey();+ (authService.validateApiKey as jest.Mock).mockResolvedValue(apiKey);++ // Attacker connects directly (203.0.113.99) and forges a trusted-looking XFF.+ const context = createMockContext({ 'x-api-key': 'key', 'x-forwarded-for': '10.0.0.5' }, {}, '203.0.113.99');+ await guard.canActivate(context);++ expect(authService.validateApiKey).toHaveBeenCalledWith('key', '203.0.113.99', undefined);+ });++ it('normalizes an IPv4-mapped IPv6 proxy address (e.g. ::ffff:10.0.0.1)', async () => {+ guard = buildGuard(['10.0.0.0/8']);+ reflector.getAllAndOverride.mockReturnValueOnce(false).mockReturnValueOnce(undefined);++ const apiKey = createMockApiKey();+ (authService.validateApiKey as jest.Mock).mockResolvedValue(apiKey);++ const context = createMockContext({ 'x-api-key': 'key', 'x-forwarded-for': '203.0.113.50' }, {}, '::ffff:10.0.0.1');+ await guard.canActivate(context);+expect(authService.validateApiKey).toHaveBeenCalledWith('key', '203.0.113.50', undefined);});});diff --git a/src/modules/auth/guards/api-key.guard.ts b/src/modules/auth/guards/api-key.guard.tsindex ed91c7293..61b6fb6f7 100644--- a/src/modules/auth/guards/api-key.guard.ts+++ b/src/modules/auth/guards/api-key.guard.ts@@ -1,15 +1,18 @@import { Injectable, CanActivate, ExecutionContext, UnauthorizedException } from '@nestjs/common';import { Reflector } from '@nestjs/core';+import { ConfigService } from '@nestjs/config';import { Request } from 'express';import { AuthService } from '../auth.service';import { ApiKeyRole } from '../entities/api-key.entity';import { REQUIRED_ROLE_KEY, PUBLIC_KEY } from '../decorators/auth.decorators';+import { ipMatches, normalizeIp } from '../../../common/utils/ip';@Injectable()export class ApiKeyGuard implements CanActivate {constructor(private readonly authService: AuthService,private readonly reflector: Reflector,+ private readonly configService: ConfigService,) {}async canActivate(context: ExecutionContext): Promise<boolean> {@@ -63,12 +66,47 @@ export class ApiKeyGuard implements CanActivate {return undefined;}+ /**+ * Resolve the real client IP used for the API key's allowedIps whitelist.+ *+ * X-Forwarded-For is client-controllable, so it is only honored when the+ * request actually arrives from a configured trusted proxy (TRUSTED_PROXIES).+ * With no trusted proxies configured, the header is ignored entirely and the+ * direct socket address is used — preventing IP-whitelist spoofing.+ */private getClientIp(request: Request): string {+ const socketIp = normalizeIp(request.socket?.remoteAddress || request.ip || '');+ const trustedProxies = this.configService.get<string[]>('security.trustedProxies') ?? [];++ if (trustedProxies.length === 0) {+ return socketIp;+ }++ const isTrusted = (ip: string): boolean => trustedProxies.some(proxy => ipMatches(ip, proxy));++ // Only trust the forwarded chain if the immediate peer is a trusted proxy.+ if (!isTrusted(socketIp)) {+ return socketIp;+ }+const forwarded = request.headers['x-forwarded-for'];- if (forwarded) {- const ips = (forwarded as string).split(',');- return ips[0].trim();+ if (!forwarded) {+ return socketIp;}- return request.ip || request.socket.remoteAddress || '';++ const hops = (Array.isArray(forwarded) ? forwarded.join(',') : forwarded)+ .split(',')+ .map(hop => normalizeIp(hop.trim()))+ .filter(Boolean);++ // Walk right-to-left and return the first hop that is not a trusted proxy:+ // the closest address the trusted infrastructure actually observed.+ for (let i = hops.length - 1; i >= 0; i--) {+ if (!isTrusted(hops[i])) {+ return hops[i];+ }+ }++ return socketIp;}}