fix(websocket): add heartbeat scheduling and transport limits (#313)

This commit is contained in:
brios
2026-04-22 17:26:58 -04:00
committed by Zach Yale
parent 145b94dfc9
commit bfeeef268d
2 changed files with 90 additions and 25 deletions
@@ -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);
}
}
}
@@ -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<String> 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<String> 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<String> 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;
}