Give STOMP sessions a principal so /user/queue/errors is delivered

ChatWebSocketController reports send errors with convertAndSendToUser, but
CONNECT never set a user on the session, so those messages had no recipient.
The interceptor now sets a principal named after the user id on the message's
own accessor and allows subscriptions to /user/queue/** (resolved per session
by Spring, so it cannot reach another user's queue).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
SlimusMinus
2026-10-20 01:09:57 +03:00
parent 6b647e0bbf
commit 7b81c18614
2 changed files with 115 additions and 1 deletions

View File

@@ -3,6 +3,7 @@ package com.krylov.refound.util;
import com.krylov.refound.security.JwtService; import com.krylov.refound.security.JwtService;
import com.krylov.refound.service.ChatService; import com.krylov.refound.service.ChatService;
import com.krylov.refound.service.UserService; import com.krylov.refound.service.UserService;
import java.util.List;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@@ -13,6 +14,9 @@ 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;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@Slf4j @Slf4j
@@ -28,6 +32,12 @@ public class WsStompInterceptor implements ChannelInterceptor {
private static final Pattern UNREAD_TOPIC = Pattern.compile("^/topic/user/(\\d+)/unread$"); private static final Pattern UNREAD_TOPIC = Pattern.compile("^/topic/user/(\\d+)/unread$");
/** /user/{userId}/queue/** — личная очередь одного пользователя */ /** /user/{userId}/queue/** — личная очередь одного пользователя */
private static final Pattern USER_QUEUE = Pattern.compile("^/user/[^/]+/queue/.+$"); private static final Pattern USER_QUEUE = Pattern.compile("^/user/[^/]+/queue/.+$");
/**
* /user/queue/** — личная очередь текущей сессии. Spring сам подставляет в неё
* Principal сессии, поэтому чужую очередь так получить нельзя. Именно сюда
* доходят сообщения convertAndSendToUser (например, /user/queue/errors).
*/
private static final Pattern OWN_USER_QUEUE = Pattern.compile("^/user/queue/.+$");
private final JwtService jwtService; private final JwtService jwtService;
private final UserService userService; private final UserService userService;
@@ -45,7 +55,12 @@ public class WsStompInterceptor implements ChannelInterceptor {
@Override @Override
public Message<?> preSend(Message<?> message, MessageChannel channel) { public Message<?> preSend(Message<?> message, MessageChannel channel) {
StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message); // Изменяемый accessor самого сообщения: setUser на копии из wrap() не доходил бы
// до STOMP-сессии
StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
if (accessor == null) {
accessor = StompHeaderAccessor.wrap(message);
}
if (StompCommand.CONNECT.equals(accessor.getCommand())) { if (StompCommand.CONNECT.equals(accessor.getCommand())) {
handleConnect(accessor); handleConnect(accessor);
@@ -81,6 +96,10 @@ public class WsStompInterceptor implements ChannelInterceptor {
accessor.getSessionAttributes().put(USER_ID_ATTR, userId); accessor.getSessionAttributes().put(USER_ID_ATTR, userId);
accessor.getSessionAttributes().put(ROLE_ATTR, role); accessor.getSessionAttributes().put(ROLE_ATTR, role);
// Principal с именем = userId: без него convertAndSendToUser(userId, ...) никого
// не находил, и ошибки отправки сообщений (/queue/errors) терялись
accessor.setUser(new UsernamePasswordAuthenticationToken(userId.toString(), null,
List.of(new SimpleGrantedAuthority("ROLE_" + role))));
// Таймзону присылает клиент на CONNECT; применяется при сохранении Message // Таймзону присылает клиент на CONNECT; применяется при сохранении Message
String timezone = accessor.getFirstNativeHeader(TimeZoneContext.WS_HEADER); String timezone = accessor.getFirstNativeHeader(TimeZoneContext.WS_HEADER);
@@ -123,6 +142,10 @@ public class WsStompInterceptor implements ChannelInterceptor {
return; return;
} }
if (OWN_USER_QUEUE.matcher(destination).matches()) {
return;
}
if (USER_QUEUE.matcher(destination).matches()) { if (USER_QUEUE.matcher(destination).matches()) {
String[] parts = destination.split("/"); String[] parts = destination.split("/");
if (parts.length < 3 || !userId.toString().equals(parts[2])) { if (parts.length < 3 || !userId.toString().equals(parts[2])) {

View File

@@ -0,0 +1,91 @@
package com.krylov.refound.util;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.krylov.refound.security.JwtService;
import com.krylov.refound.service.ChatService;
import com.krylov.refound.service.UserService;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
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.MessageBuilder;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.test.util.ReflectionTestUtils;
class WsStompInterceptorTest {
private JwtService jwtService;
private WsStompInterceptor interceptor;
@BeforeEach
void setUp() {
jwtService = new JwtService();
ReflectionTestUtils.setField(jwtService, "secret", "test-secret-test-secret-test-secret-0123456789");
ReflectionTestUtils.setField(jwtService, "accessExpiration", 60_000L);
ReflectionTestUtils.setField(jwtService, "refreshExpiration", 600_000L);
UserService userService = mock(UserService.class);
when(userService.getUserIdByLogin("alice")).thenReturn(5L);
interceptor = new WsStompInterceptor(jwtService, userService, mock(ChatService.class));
}
@Test
void connectSetsPrincipalSoUserQueuesWork() {
Map<String, Object> session = new HashMap<>();
Message<?> connect = connect("Bearer " + jwtService.generateAccessToken("alice", "USER"), session);
interceptor.preSend(connect, mock(MessageChannel.class));
StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(connect, StompHeaderAccessor.class);
assertThat(accessor.getUser()).isNotNull();
assertThat(accessor.getUser().getName()).isEqualTo("5");
assertThat(session).containsEntry("userId", 5L);
}
@Test
void refreshTokenIsRejectedOnConnect() {
Message<?> connect = connect("Bearer " + jwtService.generateRefreshToken("alice"), new HashMap<>());
assertThatThrownBy(() -> interceptor.preSend(connect, mock(MessageChannel.class)))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void ownUserQueueIsAllowedAndForeignQueueIsNot() {
Map<String, Object> session = new HashMap<>();
session.put("userId", 5L);
session.put("role", "USER");
interceptor.preSend(subscribe("/user/queue/errors", session), mock(MessageChannel.class));
interceptor.preSend(subscribe("/user/5/queue/errors", session), mock(MessageChannel.class));
assertThatThrownBy(() -> interceptor.preSend(subscribe("/user/6/queue/errors", session), mock(MessageChannel.class)))
.isInstanceOf(MessagingException.class);
assertThatThrownBy(() -> interceptor.preSend(subscribe("/topic/ads/1/status", session), mock(MessageChannel.class)))
.isInstanceOf(MessagingException.class);
}
private static Message<?> connect(String authorization, Map<String, Object> session) {
StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.CONNECT);
accessor.setNativeHeader("Authorization", authorization);
accessor.setSessionAttributes(session);
accessor.setLeaveMutable(true);
return MessageBuilder.createMessage(new byte[0], accessor.getMessageHeaders());
}
private static Message<?> subscribe(String destination, Map<String, Object> session) {
StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.SUBSCRIBE);
accessor.setDestination(destination);
accessor.setSessionAttributes(session);
accessor.setLeaveMutable(true);
return MessageBuilder.createMessage(new byte[0], accessor.getMessageHeaders());
}
}