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 org.booklore.config.security.interceptor.WebSocketAuthInterceptor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
import org.springframework.messaging.simp.config.ChannelRegistration; import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry; 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.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry; import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketTransportRegistration;
import java.util.Arrays; import java.util.Arrays;
@@ -27,11 +31,22 @@ public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override @Override
public void configureMessageBroker(MessageBrokerRegistry registry) { 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.setApplicationDestinationPrefixes("/app");
registry.setUserDestinationPrefix("/user"); registry.setUserDestinationPrefix("/user");
} }
@Bean
public TaskScheduler wsHeartbeatScheduler() {
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(1);
scheduler.setThreadNamePrefix("ws-heartbeat-");
scheduler.setDaemon(true);
return scheduler;
}
@Override @Override
public void registerStompEndpoints(StompEndpointRegistry registry) { public void registerStompEndpoints(StompEndpointRegistry registry) {
String allowedOrigins = env.getProperty("app.cors.allowed-origins", "*").trim(); 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 (*). " + 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."); "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()) { } 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)"); log.info("WebSocket endpoint registered at /ws (same-origin only)");
} else { } else {
String[] origins = Arrays.stream(allowedOrigins.split("\\s*,\\s*")) 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 @Override
public void configureClientInboundChannel(ChannelRegistration registration) { public void configureClientInboundChannel(ChannelRegistration registration) {
registration.interceptors(webSocketAuthInterceptor); registration.interceptors(webSocketAuthInterceptor);
} }
} }
@@ -7,6 +7,7 @@ import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order; import org.springframework.core.annotation.Order;
import org.springframework.messaging.Message; import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel; import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessagingException;
import org.springframework.messaging.simp.stomp.StompCommand; import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor; import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor; import org.springframework.messaging.support.ChannelInterceptor;
@@ -16,6 +17,7 @@ import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.util.List; import java.util.List;
import java.util.Set;
@Slf4j @Slf4j
@Component @Component
@@ -23,48 +25,89 @@ import java.util.List;
@RequiredArgsConstructor @RequiredArgsConstructor
public class WebSocketAuthInterceptor implements ChannelInterceptor { 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; private final JwtUtils jwtUtils;
@Override @Override
public Message<?> preSend(Message<?> message, MessageChannel channel) { public Message<?> preSend(Message<?> message, MessageChannel channel) {
StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class); StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
if (accessor == null || accessor.getCommand() == null) {
return message;
}
if (accessor != null && StompCommand.CONNECT.equals(accessor.getCommand())) { switch (accessor.getCommand()) {
List<String> authHeaders = accessor.getNativeHeader("Authorization"); case CONNECT -> handleConnect(accessor);
case SUBSCRIBE -> validateSubscription(accessor);
if (authHeaders == null || authHeaders.isEmpty()) { case SEND -> rejectSend(accessor);
log.debug("WebSocket connection rejected: No Authorization header"); case DISCONNECT -> log.debug("Client disconnected: {}", accessor.getUser());
throw new IllegalArgumentException("Missing Authorization header"); default -> { /* pass through */ }
}
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());
} }
return message; 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) { private Authentication authenticateToken(String token) {
if (token == null || token.trim().isEmpty()) { if (token == null || token.isBlank()) {
return null; return null;
} }
try { try {
if (jwtUtils.validateToken(token)) { if (jwtUtils.validateToken(token)) {
String username = jwtUtils.extractUsername(token); String username = jwtUtils.extractUsername(token);
if (username != null && !username.trim().isEmpty()) { if (username != null && !username.isBlank()) {
return new UsernamePasswordAuthenticationToken(username, null, null); return new UsernamePasswordAuthenticationToken(username, null, List.of());
} }
} }
} catch (Exception e) { } catch (Exception e) {
log.debug("Token authentication failed", e); log.debug("Token validation failed: {}", e.getMessage());
} }
return null; return null;
} }