Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(auth): trust the guard's result in /auth/validate instead of re-validating (#507)
Yudhi Armyndharisf9aa2b9c451a
diff --git a/src/modules/auth/auth-validate.controller.spec.ts b/src/modules/auth/auth-validate.controller.spec.tsnew file mode 100644index 000000000..f0e8b7d3e--- /dev/null+++ b/src/modules/auth/auth-validate.controller.spec.ts@@ -0,0 +1,28 @@+import { AuthValidateController } from './auth-validate.controller';+import { ApiKey, ApiKeyRole } from './entities/api-key.entity';++describe('AuthValidateController', () => {+ const controller = new AuthValidateController();++ const makeKey = (over: Partial<ApiKey> = {}): ApiKey =>+ ({ id: 'k1', role: ApiKeyRole.OPERATOR, isActive: true, allowedIps: null, ...over }) as ApiKey;++ it('reports the guard-validated key as valid, echoing its role', () => {+ expect(controller.validate(makeKey({ role: ApiKeyRole.ADMIN }))).toEqual({+ valid: true,+ role: ApiKeyRole.ADMIN,+ });+ });++ it('returns valid:true for an IP-restricted key (no IP-less re-validation false negative)', () => {+ // The global guard already validated this key against the real client IP and attached it.+ // The handler must NOT re-validate without an IP, which previously fail-closed and wrongly+ // reported valid:false for any key carrying an allowedIps restriction.+ const key = makeKey({ allowedIps: ['10.0.0.0/24'] });+ expect(controller.validate(key)).toEqual({ valid: true, role: key.role });+ });++ it('returns valid:false when no key is attached (defense-in-depth)', () => {+ expect(controller.validate(undefined)).toEqual({ valid: false });+ });+});diff --git a/src/modules/auth/auth-validate.controller.ts b/src/modules/auth/auth-validate.controller.tsindex 71c5c6ba5..53387b6ce 100644--- a/src/modules/auth/auth-validate.controller.ts+++ b/src/modules/auth/auth-validate.controller.ts@@ -1,39 +1,28 @@-import { Controller, Post, Headers, HttpCode, HttpStatus } from '@nestjs/common';+import { Controller, Post, HttpCode, HttpStatus } from '@nestjs/common';import { ApiTags, ApiOperation, ApiResponse, ApiHeader } from '@nestjs/swagger';-import { AuthService } from './auth.service';-import { createLogger } from '../../common/services/logger.service';+import { CurrentApiKey } from './decorators/auth.decorators';+import { ApiKey } from './entities/api-key.entity';@ApiTags('auth')@Controller('auth')export class AuthValidateController {- private readonly logger = createLogger('AuthValidateController');-- constructor(private readonly authService: AuthService) {}-@Post('validate')@HttpCode(HttpStatus.OK)@ApiOperation({ summary: 'Validate an API key' })@ApiHeader({ name: 'X-API-Key', description: 'API key to validate' })@ApiResponse({ status: 200, description: 'API key is valid' })@ApiResponse({ status: 401, description: 'Invalid or missing API key' })- async validate(@Headers('x-api-key') apiKey?: string): Promise<{ valid: boolean; role?: string }> {- // This route is behind the global API-key guard, so in normal operation only a valid key- // reaches this handler (a missing/invalid key 401s first) and the `valid:false` branches- // below are unreachable. They are retained as defense-in-depth in case the guard- // config ever changes — they are cheap and keep the endpoint safe to expose directly.+ validate(@CurrentApiKey() apiKey?: ApiKey): { valid: boolean; role?: 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 its+ // client-IP and session-scope restrictions — and attached it to the request. Re-validating here+ // would repeat that work without the client IP, double-counting usage and, for an IP-restricted+ // key, failing closed (no IP) and wrongly reporting valid:false. So we trust the guard's result.+ // The valid:false branch is unreachable in normal operation; it's retained as defense-in-depth in+ // case the guard config ever changes, keeping the endpoint safe to expose directly.if (!apiKey) {return { valid: false };}-- try {- const keyEntity = await this.authService.validateApiKey(apiKey);- if (keyEntity && keyEntity.isActive) {- return { valid: true, role: keyEntity.role };- }- return { valid: false };- } catch (error) {- this.logger.warn('API key validation error', { error: error instanceof Error ? error.message : String(error) });- return { valid: false };- }+ return { valid: true, role: apiKey.role };}}