Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
refactor(auth): use the shared hardened IP matcher for the per-key allowlist (#519)
Yudhi Armyndharis1a2ac1da5282
diff --git a/src/modules/auth/auth.service.spec.ts b/src/modules/auth/auth.service.spec.tsindex 7cd02df82..aeb3864a7 100644--- a/src/modules/auth/auth.service.spec.ts+++ b/src/modules/auth/auth.service.spec.ts@@ -324,6 +324,18 @@ describe('AuthService', () => {await expect(service.validateApiKey('ip-no-client')).rejects.toThrow('Client IP could not be determined');});+ it('rejects a malformed client IP instead of coercing it into an allowed range', async () => {+ const key = createMockApiKey({+ allowedIps: ['10.0.0.1/32'],+ keyHash: hashKey('ip-malformed'),+ });+ (repository.findOne as jest.Mock).mockResolvedValue(key);++ // The previous lenient parser read '10.0.0.1abc' as 10.0.0.1 and let it through; the shared+ // hardened matcher rejects a non-numeric octet, so the per-key whitelist holds.+ 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 () => {const key = createMockApiKey({allowedSessions: ['session-A'],diff --git a/src/modules/auth/auth.service.ts b/src/modules/auth/auth.service.tsindex e40d1e632..e2bbcfd50 100644--- a/src/modules/auth/auth.service.ts+++ b/src/modules/auth/auth.service.ts@@ -5,6 +5,7 @@ import { randomBytes } from 'crypto';import { existsSync, readFileSync } from 'fs';import { join } from 'path';import { writeSecretFile } from '../../common/utils/secret-file';+import { ipMatches } from '../../common/utils/ip';import { hashApiKey } from './api-key-hash';import { ApiKey, ApiKeyRole } from './entities/api-key.entity';import { CreateApiKeyDto, UpdateApiKeyDto } from './dto';@@ -262,56 +263,10 @@ export class AuthService implements OnModuleInit {}private isIpAllowed(clientIp: string, allowedIps: string[]): boolean {- // Support both exact match and CIDR notation- for (const entry of allowedIps) {- if (entry.includes('/')) {- // CIDR notation (e.g., "10.0.0.0/24")- if (this.ipInCidr(clientIp, entry)) {- return true;- }- } else {- // Exact match- if (clientIp === entry) {- return true;- }- }- }- return false;- }-- /**- * Check if an IPv4 address is within a CIDR range- * @param ip - Client IP address (e.g., "192.168.1.100")- * @param cidr - CIDR notation (e.g., "192.168.1.0/24")- */- private ipInCidr(ip: string, cidr: string): boolean {- try {- const [range, bitsStr] = cidr.split('/');- const bits = parseInt(bitsStr, 10);-- if (isNaN(bits) || bits < 0 || bits > 32) {- return false;- }-- const mask = ~(2 ** (32 - bits) - 1);- const ipNum = this.ipToNumber(ip);- const rangeNum = this.ipToNumber(range);-- return (ipNum & mask) === (rangeNum & mask);- } catch (error) {- this.logger.warn(`Invalid CIDR format: ${cidr}`, { error: String(error) });- return false;- }- }-- /**- * Convert IPv4 address string to 32-bit number- */- private ipToNumber(ip: string): number {- const parts = ip.split('.');- if (parts.length !== 4) return 0;-- return parts.reduce((acc, octet) => (acc << 8) + parseInt(octet, 10), 0) >>> 0;+ // Delegate to the shared, hardened matcher (also used by the throttler and the API-key guard's IP+ // resolution): it handles both an exact IP entry and CIDR notation, and — unlike the previous local+ // parser — rejects a malformed octet instead of coercing it into range.+ return allowedIps.some(entry => ipMatches(clientIp, entry));}hasPermission(apiKey: ApiKey, requiredRole: ApiKeyRole): boolean {