Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion docs/group-chat-architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -26,8 +27,9 @@
* <li>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.</li>
* <li>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.</li>
* <li>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}.</li>
* <li>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
Expand Down Expand Up @@ -102,8 +104,8 @@ private String whySubscribeIsRefused(String destination, Map<String, Object> 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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,15 @@
* <p>
* 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;

Expand Down Expand Up @@ -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");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down