From f8329c29b1869b3f8d56cb6f3d76313f438baeef Mon Sep 17 00:00:00 2001 From: Dani Lipari <64545085+danilipari@users.noreply.github.com> Date: Mon, 16 Feb 2026 08:34:50 +0100 Subject: [PATCH] [core] fix: harden auth middleware, WebSocket guard, and policies guard (#1899) - Add missing return after socket.close() in WebSocket gateway to prevent cross-session event subscription on forbidden connections - Return 401 Unauthorized instead of 500 Internal Server Error when API key header is missing or malformed - Deny by default in PoliciesGuard when no @CheckPolicies handlers are defined, preventing accidental exposure of undecorated endpoints Co-authored-by: Dani Lipari --- src/api/websocket.gateway.core.ts | 1 + src/core/auth/api-key-auth.middleware.ts | 3 +-- src/core/auth/policies.guard.ts | 4 ++++ 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/api/websocket.gateway.core.ts b/src/api/websocket.gateway.core.ts index b39a8615..28eb9b33 100644 --- a/src/api/websocket.gateway.core.ts +++ b/src/api/websocket.gateway.core.ts @@ -93,6 +93,7 @@ export class WebsocketGatewayCore if (!ability.can(Action.Use, new SessionName(session))) { socket.close(WebSocketCloseCode.POLICY_VIOLATION, 'Forbidden'); + return; } this.logger.debug(`New client connected: ${request.url} - ${socket.id}`); diff --git a/src/core/auth/api-key-auth.middleware.ts b/src/core/auth/api-key-auth.middleware.ts index ce3ea200..9c8b5b31 100644 --- a/src/core/auth/api-key-auth.middleware.ts +++ b/src/core/auth/api-key-auth.middleware.ts @@ -1,6 +1,5 @@ import { Injectable, - InternalServerErrorException, NestMiddleware, UnauthorizedException, } from '@nestjs/common'; @@ -16,7 +15,7 @@ export class ApiKeyAuthMiddleware implements NestMiddleware { const exception = err instanceof UnauthorizedException ? err - : new InternalServerErrorException(); + : new UnauthorizedException(); res.status(exception.getStatus()).json(exception.getResponse()); return; } diff --git a/src/core/auth/policies.guard.ts b/src/core/auth/policies.guard.ts index 0b7bdff3..6ae843cc 100644 --- a/src/core/auth/policies.guard.ts +++ b/src/core/auth/policies.guard.ts @@ -26,6 +26,10 @@ export class PoliciesGuard implements CanActivate { context.getClass(), ]) || []; + if (handlers.length === 0) { + throw new ForbiddenException(); + } + const req = context.switchToHttp().getRequest(); const user = req.user; const ability = this.caslAbilityFactory.createForUser(user);