From bfeeef268d7cfe1899133214c937c88325494647 Mon Sep 17 00:00:00 2001 From: brios <127139797+balazs-szucs@users.noreply.github.com> Date: Tue, 31 Mar 2026 22:21:15 +0200 Subject: [PATCH] fix(websocket): add heartbeat scheduling and transport limits (#313) --- .../org/booklore/config/WebSocketConfig.java | 28 +++++- .../interceptor/WebSocketAuthInterceptor.java | 87 ++++++++++++++----- 2 files changed, 90 insertions(+), 25 deletions(-) diff --git a/booklore-api/src/main/java/org/booklore/config/WebSocketConfig.java b/booklore-api/src/main/java/org/booklore/config/WebSocketConfig.java index 383c7bdec..66de8e272 100644 --- a/booklore-api/src/main/java/org/booklore/config/WebSocketConfig.java +++ b/booklore-api/src/main/java/org/booklore/config/WebSocketConfig.java @@ -2,13 +2,17 @@ package org.booklore.config; import org.booklore.config.security.interceptor.WebSocketAuthInterceptor; import lombok.extern.slf4j.Slf4j; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.messaging.simp.config.ChannelRegistration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; +import org.springframework.scheduling.TaskScheduler; +import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; +import org.springframework.web.socket.config.annotation.WebSocketTransportRegistration; import java.util.Arrays; @@ -27,11 +31,22 @@ public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker(MessageBrokerRegistry registry) { - registry.enableSimpleBroker("/queue", "/topic"); + registry.enableSimpleBroker("/queue", "/topic") + .setHeartbeatValue(new long[]{10_000, 10_000}) + .setTaskScheduler(wsHeartbeatScheduler()); registry.setApplicationDestinationPrefixes("/app"); registry.setUserDestinationPrefix("/user"); } + @Bean + public TaskScheduler wsHeartbeatScheduler() { + ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler(); + scheduler.setPoolSize(1); + scheduler.setThreadNamePrefix("ws-heartbeat-"); + scheduler.setDaemon(true); + return scheduler; + } + @Override public void registerStompEndpoints(StompEndpointRegistry registry) { String allowedOrigins = env.getProperty("app.cors.allowed-origins", "*").trim(); @@ -41,7 +56,6 @@ public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { log.warn("WebSocket endpoint is configured to allow all origins (*). " + "This is the default for backward compatibility, but it's recommended to set 'app.cors.allowed-origins' to an explicit list."); } else if (allowedOrigins.isEmpty()) { - // No explicit origins configured: enforce same-origin check (Spring WebSocket default) log.info("WebSocket endpoint registered at /ws (same-origin only)"); } else { String[] origins = Arrays.stream(allowedOrigins.split("\\s*,\\s*")) @@ -52,8 +66,16 @@ public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { } } + @Override + public void configureWebSocketTransport(WebSocketTransportRegistration registration) { + registration.setSendTimeLimit(15_000) + .setSendBufferSizeLimit(512 * 1024) + .setMessageSizeLimit(128 * 1024) + .setTimeToFirstMessage(30_000); + } + @Override public void configureClientInboundChannel(ChannelRegistration registration) { registration.interceptors(webSocketAuthInterceptor); } -} \ No newline at end of file +} diff --git a/booklore-api/src/main/java/org/booklore/config/security/interceptor/WebSocketAuthInterceptor.java b/booklore-api/src/main/java/org/booklore/config/security/interceptor/WebSocketAuthInterceptor.java index e5e910921..8b2f12172 100644 --- a/booklore-api/src/main/java/org/booklore/config/security/interceptor/WebSocketAuthInterceptor.java +++ b/booklore-api/src/main/java/org/booklore/config/security/interceptor/WebSocketAuthInterceptor.java @@ -7,6 +7,7 @@ import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; +import org.springframework.messaging.MessagingException; import org.springframework.messaging.simp.stomp.StompCommand; import org.springframework.messaging.simp.stomp.StompHeaderAccessor; import org.springframework.messaging.support.ChannelInterceptor; @@ -16,6 +17,7 @@ import org.springframework.security.core.Authentication; import org.springframework.stereotype.Component; import java.util.List; +import java.util.Set; @Slf4j @Component @@ -23,48 +25,89 @@ import java.util.List; @RequiredArgsConstructor public class WebSocketAuthInterceptor implements ChannelInterceptor { + private static final String BEARER_PREFIX = "Bearer "; + private static final Set ALLOWED_DEST_PREFIXES = Set.of("/topic/", "/user/queue/"); + private final JwtUtils jwtUtils; @Override public Message preSend(Message message, MessageChannel channel) { StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class); + if (accessor == null || accessor.getCommand() == null) { + return message; + } - if (accessor != null && StompCommand.CONNECT.equals(accessor.getCommand())) { - List authHeaders = accessor.getNativeHeader("Authorization"); - - if (authHeaders == null || authHeaders.isEmpty()) { - log.debug("WebSocket connection rejected: No Authorization header"); - throw new IllegalArgumentException("Missing Authorization header"); - } - - String token = authHeaders.getFirst().replace("Bearer ", ""); - Authentication auth = authenticateToken(token); - - if (auth == null) { - log.debug("WebSocket connection rejected: Invalid token"); - throw new IllegalArgumentException("Invalid Authorization token"); - } - - accessor.setUser(auth); - log.debug("WebSocket authentication successful for user: {}", auth.getName()); + switch (accessor.getCommand()) { + case CONNECT -> handleConnect(accessor); + case SUBSCRIBE -> validateSubscription(accessor); + case SEND -> rejectSend(accessor); + case DISCONNECT -> log.debug("Client disconnected: {}", accessor.getUser()); + default -> { /* pass through */ } } return message; } + private void handleConnect(StompHeaderAccessor accessor) { + List authHeaders = accessor.getNativeHeader("Authorization"); + if (authHeaders == null || authHeaders.isEmpty()) { + throw new MessagingException("Missing Authorization header"); + } + + String raw = authHeaders.getFirst().trim(); + if (!raw.startsWith(BEARER_PREFIX)) { + throw new MessagingException("Malformed Authorization header"); + } + + String token = raw.substring(BEARER_PREFIX.length()); + Authentication auth = authenticateToken(token); + if (auth == null) { + throw new MessagingException("Invalid or expired token"); + } + + accessor.setUser(auth); + log.debug("WebSocket authenticated: {}", auth.getName()); + } + + private void validateSubscription(StompHeaderAccessor accessor) { + requireAuthenticated(accessor); + + String destination = accessor.getDestination(); + if (destination == null || destination.contains("..")) { + throw new MessagingException("Invalid subscription destination"); + } + + boolean allowed = ALLOWED_DEST_PREFIXES.stream().anyMatch(destination::startsWith); + if (!allowed) { + log.warn("Subscription rejected: user={} dest='{}'", accessor.getUser(), destination); + throw new MessagingException("Destination '" + destination + "' is not allowed"); + } + } + + private void rejectSend(StompHeaderAccessor accessor) { + log.warn("SEND rejected: user={} dest='{}'", accessor.getUser(), accessor.getDestination()); + throw new MessagingException("Client SEND is not permitted"); + } + + private void requireAuthenticated(StompHeaderAccessor accessor) { + if (accessor.getUser() == null) { + throw new MessagingException("Not authenticated"); + } + } + private Authentication authenticateToken(String token) { - if (token == null || token.trim().isEmpty()) { + if (token == null || token.isBlank()) { return null; } try { if (jwtUtils.validateToken(token)) { String username = jwtUtils.extractUsername(token); - if (username != null && !username.trim().isEmpty()) { - return new UsernamePasswordAuthenticationToken(username, null, null); + if (username != null && !username.isBlank()) { + return new UsernamePasswordAuthenticationToken(username, null, List.of()); } } } catch (Exception e) { - log.debug("Token authentication failed", e); + log.debug("Token validation failed: {}", e.getMessage()); } return null; }