From 4b746342c3607da907d953bd5d9b9472c260a0c3 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Mon, 23 Nov 2026 02:27:21 -0800 Subject: [PATCH] Chat socket: drop client SENDs to every /topic destination DirectMessageTopicGuard already dropped a client's SEND to a DM topic. It now drops a client's SEND to any destination the simple broker handles (WebSocketBrokerConfig.BROKER_PREFIX, "/topic"), so group chat topics get the same rule. Only the server publishes to topics: pages send group messages over REST, and Spring's group page sends to /app/groups.chat. The tests cover SENDs to DM, group and other topic destinations being dropped, and the server's own group broadcast still reaching its subscribers. --- AGENTS.md | 1 + docs/group-chat-architecture.md | 2 +- .../DirectMessageTopicGuard.java | 10 ++++--- .../mvc/groups/WebSocketBrokerConfig.java | 7 +++-- .../DirectMessageTopicBrokerTest.java | 29 +++++++++++++++++++ .../DirectMessageTopicGuardTest.java | 10 ++++--- 6 files changed, 48 insertions(+), 11 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 9e7bb279..4818603d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -38,6 +38,7 @@ Entity-removal helpers (run before any large cleanup): - Realtime chat uses STOMP over a **second connector on port 8589**: broker config in `WebSocketBrokerConfig.java` (`/ws-chat`, `/app`, `/topic`), port gating in `ChatWebSocketPortFilter.java`, presence in `GroupChatPresenceService.java`. The native `/websocket` endpoint in `mvc/mortevision/nativesocket/WebSocketConfig.java` is separate. - Gotcha: Java package is `mvc.groups` (plural) but templates live in `templates/group/` (singular); static JS exists both as legacy files in `static/js/group-*.js` and packaged versions in `static/js/group/*.js` — prefer the latter. - [docs/group-chat-architecture.md](docs/group-chat-architecture.md) covers every groups and chat route, the WebSocket event contexts, S3 message storage (keyed by group name, not id) and the known issues. Over the WebSocket there is no Spring Security context, so a service that needs the signed-in account (like `GroupChatIdentityService`) only works from REST. The socket does read the `jwt_java_spring` cookie when it opens (`ChatSocketIdentityInterceptor`, same checks as `JwtRequestFilter`, and only when the request's `Origin` is in the REST CORS list, since a cross-site GET carries the cookie but no Origin), but only for `DirectMessageTopicGuard`: only a conversation's participants can subscribe to `/topic/dm/{id}`, and wildcard subscriptions, `/user/...` destinations and client SENDs to DM topics are dropped. It sets no Principal, on purpose, so `GroupChatWebSocketController` still ignores events. HTTP: `api/groups.http`. +- A client's SEND to any `/topic/...` destination is dropped too, group topics included, because the simple broker relays it to every subscriber. Only the server publishes there (the prefix is `WebSocketBrokerConfig.BROKER_PREFIX`). ## Assignment grading diff --git a/docs/group-chat-architecture.md b/docs/group-chat-architecture.md index 1d0dc01c..3d8840bc 100644 --- a/docs/group-chat-architecture.md +++ b/docs/group-chat-architecture.md @@ -161,7 +161,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) ## Testing - `api/groups.http`: open it in VS Code with the REST Client extension and run the requests in order. Set `baseUrl`, `adminUid` and `adminPassword` under `rest-client.environmentVariables` in the Git-ignored `.vscode/settings.json`. Never put passwords in the file. It creates a test group, adds you, sends and reads messages, checks unread counts, and deletes the group. -- **The WebSocket can't be tested from a `.http` file.** To check it, open a course page with a chat against a local server and watch the browser's Network panel (WS filter) for frames on `/topic/group/{id}`. Or connect any STOMP client to `ws://localhost:8589/ws-chat/websocket` (SockJS's raw WebSocket transport), send `CONNECT`, `SUBSCRIBE` to `/topic/group/{id}`, and `SEND` JSON events to `/app/groups.chat`. A `SUBSCRIBE` to `/topic/dm/{id}` only goes through when the handshake carries a participant's `jwt_java_spring` cookie (a `Cookie` header) and an `Origin` header from the REST API's CORS list, such as `http://localhost:4500`. Without them, or for a wildcard subscription, a `/user/...` destination or a `SEND` to `/topic/dm/...`, the frame is dropped and the server logs a "refused" warning. Run the socket's own tests with `./mvnw test '-Dtest=DirectMessageTopic*Test,ChatSocketIdentityInterceptorTest,WebSocketBrokerConfigTest'`. +- **The WebSocket can't be tested from a `.http` file.** To check it, open a course page with a chat against a local server and watch the browser's Network panel (WS filter) for frames on `/topic/group/{id}`. Or connect any STOMP client to `ws://localhost:8589/ws-chat/websocket` (SockJS's raw WebSocket transport), send `CONNECT`, `SUBSCRIBE` to `/topic/group/{id}`, and `SEND` JSON events to `/app/groups.chat`. A `SUBSCRIBE` to `/topic/dm/{id}` only goes through when the handshake carries a participant's `jwt_java_spring` cookie (a `Cookie` header) and an `Origin` header from the REST API's CORS list, such as `http://localhost:4500`. Without them, or for a wildcard subscription, a `/user/...` destination or a `SEND` to any `/topic/...` destination, the frame is dropped and the server logs a "refused" warning. Only the server publishes to topics; clients send through REST or `/app/groups.chat`. Run the socket's own tests with `./mvnw test '-Dtest=DirectMessageTopic*Test,ChatSocketIdentityInterceptorTest,WebSocketBrokerConfigTest'`. - Run the chat regression tests with `./mvnw test '-Dtest=GroupChat*Test'`. They cover UID-based ownership, REST identity forwarding and unread counts. `GroupChatFilesTest` covers the file index, one-file downloads, the path rules, the bytes-free frame, uploads that land together, a path that is already shared, two uploads of one path at once, and a check that fails; `S3FileHandlerExistsTest` covers the strict check. ## Known issues diff --git a/src/main/java/com/open/spring/mvc/directmessages/DirectMessageTopicGuard.java b/src/main/java/com/open/spring/mvc/directmessages/DirectMessageTopicGuard.java index ac52e689..88776100 100644 --- a/src/main/java/com/open/spring/mvc/directmessages/DirectMessageTopicGuard.java +++ b/src/main/java/com/open/spring/mvc/directmessages/DirectMessageTopicGuard.java @@ -13,6 +13,7 @@ import org.springframework.util.PathMatcher; import com.open.spring.mvc.groups.ChatSocketIdentityInterceptor; +import com.open.spring.mvc.groups.WebSocketBrokerConfig; import lombok.extern.slf4j.Slf4j; @@ -26,8 +27,9 @@ *
  • No wildcard SUBSCRIBE on any topic. The broker matches {@code *}, {@code **}, {@code ?} * and {@code {name}} as patterns, so {@code /topic/**} would get every DM with no id at all. * No client uses one.
  • - *
  • No client SEND to a DM topic. The broker relays a client's SEND to every subscriber, so it - * would show up in someone's thread as a real message. Only the server posts there.
  • + *
  • No client SEND to any topic, DM or group ({@code /topic...}). The broker relays a client's + * SEND to every subscriber, so it would show up in someone's chat as a real message. Only the + * server posts there; pages send through REST or {@code /app/groups.chat}.
  • *
  • No SUBSCRIBE or SEND to a user destination ({@code /user/...}). Nothing on this socket uses * them, and Spring rewrites a {@code /user/X} subscription to X plus "-user" plus the session id * after this check. A SockJS client picks its own session id, so the two halves together can make @@ -102,8 +104,8 @@ private String whySubscribeIsRefused(String destination, Map ses /** Why a client's SEND is refused, or null to let it through. */ private static String whySendIsRefused(String destination) { - if (isDirectMessageTopic(destination)) { - return "only the server sends to direct message topics"; + if (destination != null && destination.startsWith(WebSocketBrokerConfig.BROKER_PREFIX)) { + return "only the server sends to topics"; } if (isUserDestination(destination)) { return NO_USER_DESTINATIONS; diff --git a/src/main/java/com/open/spring/mvc/groups/WebSocketBrokerConfig.java b/src/main/java/com/open/spring/mvc/groups/WebSocketBrokerConfig.java index 84ab9f48..590f56a5 100644 --- a/src/main/java/com/open/spring/mvc/groups/WebSocketBrokerConfig.java +++ b/src/main/java/com/open/spring/mvc/groups/WebSocketBrokerConfig.java @@ -20,12 +20,15 @@ *

    * When a socket opens, {@link ChatSocketIdentityInterceptor} reads the login cookie. Every frame a * client sends then passes {@link DirectMessageTopicGuard}, which lets only a conversation's - * participants subscribe to its /topic/dm/{id}. + * participants subscribe to its /topic/dm/{id} and keeps clients from sending to any topic. */ @Configuration @EnableWebSocketMessageBroker public class WebSocketBrokerConfig implements WebSocketMessageBrokerConfigurer { + /** The simple broker handles every destination that starts with this, so only the server may send there. */ + public static final String BROKER_PREFIX = "/topic"; + private final ChatSocketIdentityInterceptor identityInterceptor; private final DirectMessageTopicGuard directMessageTopicGuard; @@ -53,7 +56,7 @@ public void configureClientInboundChannel(ChannelRegistration registration) { @Override public void configureMessageBroker(MessageBrokerRegistry registry) { - registry.enableSimpleBroker("/topic"); + registry.enableSimpleBroker(BROKER_PREFIX); registry.setApplicationDestinationPrefixes("/app"); } } diff --git a/src/test/java/com/open/spring/mvc/directmessages/DirectMessageTopicBrokerTest.java b/src/test/java/com/open/spring/mvc/directmessages/DirectMessageTopicBrokerTest.java index d2f192fc..3d3e00ae 100644 --- a/src/test/java/com/open/spring/mvc/directmessages/DirectMessageTopicBrokerTest.java +++ b/src/test/java/com/open/spring/mvc/directmessages/DirectMessageTopicBrokerTest.java @@ -65,6 +65,35 @@ void tearDown() { broker.stop(); } + /** A group chat reader, signed out like a course chat visitor, must not get a frame a client made up. */ + @Test + void aClientSendToAGroupTopicReachesNobody() { + connect("reader-socket"); + connect("outsider-socket"); + subscribe("reader-socket", null, "/topic/group/7"); + + StompHeaderAccessor send = StompHeaderAccessor.create(StompCommand.SEND); + send.setSessionId("outsider-socket"); + send.setSessionAttributes(Map.of()); + send.setDestination("/topic/group/7"); + clientInbound.send(MessageBuilder.createMessage( + "{\"context\":\"sendMessageServer\",\"groupId\":7,\"sender\":\"Thomas Edison\",\"message\":\"FAKE: click this link\"}" + .getBytes(StandardCharsets.UTF_8), + send.getMessageHeaders())); + + assertEquals(List.of(), socketsThatReceivedSomething()); + } + + @Test + void theServersGroupBroadcastStillReachesSignedOutReaders() { + connect("reader-socket"); + subscribe("reader-socket", null, "/topic/group/7"); + + serverBroadcast("/topic/group/7", "{\"context\":\"sendMessageServer\",\"message\":\"hello class\"}"); + + assertEquals(List.of("reader-socket"), socketsThatReceivedSomething()); + } + /** * Spring turns SUBSCRIBE /user/X into a subscription to X + "-user" + the session id, which a * SockJS client picks itself. Session id "}" closes the brace this destination opens, so the diff --git a/src/test/java/com/open/spring/mvc/directmessages/DirectMessageTopicGuardTest.java b/src/test/java/com/open/spring/mvc/directmessages/DirectMessageTopicGuardTest.java index e2fd0814..834b7d24 100644 --- a/src/test/java/com/open/spring/mvc/directmessages/DirectMessageTopicGuardTest.java +++ b/src/test/java/com/open/spring/mvc/directmessages/DirectMessageTopicGuardTest.java @@ -91,10 +91,12 @@ void userDestinationsAreRefused() { assertNull(guard.preSend(frame(StompCommand.SEND, "/user/hop/queue/messages", SIGNED_OUT), channel)); } - @Test - void clientCannotSendToADmTopic() { - assertNull(guard.preSend(frame(StompCommand.SEND, "/topic/dm/1", HOP), channel)); - assertNull(guard.preSend(frame(StompCommand.SEND, "/topic/dm/1", SIGNED_OUT), channel)); + /** The broker relays a client's SEND to every subscriber of any destination starting with /topic. */ + @ParameterizedTest + @ValueSource(strings = {"/topic/dm/1", "/topic/group/7", "/topic/anything", "/topicx"}) + void clientCannotSendToAnyTopic(String destination) { + assertNull(guard.preSend(frame(StompCommand.SEND, destination, HOP), channel)); + assertNull(guard.preSend(frame(StompCommand.SEND, destination, SIGNED_OUT), channel)); } @Test