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 @@ *
* 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