diff --git a/AGENTS.md b/AGENTS.md index 9e7bb279a..c92bc8340 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -37,7 +37,11 @@ Entity-removal helpers (run before any large cleanup): - Course groups are the canonical uppercase list `CSA, CSP, CSH, CSSE`, configured as `courses.class-groups` plus `courses.periods[NAME]` in [application.properties](src/main/resources/application.properties) and bound by [CourseGroupProperties.java](src/main/java/com/open/spring/mvc/groups/CourseGroupProperties.java). That one config block drives both the `Groups` rows seeded by `ModelInit` and the class list `ClassGroupMembershipService` validates against, so course names and bell periods only need changing in one place. A single period can be overridden in `.env` (`courses.periods[CSA]=4`) because Spring merges map entries per key, whereas overriding `courses.class-groups` replaces the entire list. List order matters — it is the order memberships are returned in. Startup fails if a listed group has no period. Profile class selection syncs via `PUT /api/groups/class-memberships` (`GroupsApiController` → `ClassGroupMembershipService.syncMemberships`), which only adds/removes membership in those four groups and leaves all other groups untouched. - 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. +- Mentors (`ROLE_MENTOR` without a teacher or admin role) are limited by `MentorRules` (static methods, `mvc/groups`) and `MentorAccess` (loads a group's members and whether it is a class group): no direct message that includes a mentor; a mentor uses only a non-class group they belong to with at least 2 members who aren't mentors; only the team or a teacher adds or removes a mentor, and a mentor adds no one. Refusals are 403 with a `reason`. The mentor rules leave everyone else's answers alone; the next line says who else may change a group. A new route that reads or writes a group's chat, or opens a direct message, must ask `MentorAccess` or `MentorRules` too, as the older `/api/chat` and the UI Builder's message-owner do. Membership checks use `GroupsJpaRepository.findMembersOf`, since `spring.jpa.open-in-view=false` stops `Groups.groupMembers` loading in the chat controller. Tests: `./mvnw test -Dtest='*Mentor*Test'`. +- Changing a group (`GroupsApiController`): adding or removing a member of an existing group (`POST` and `DELETE /api/groups/{id}/members/{personId}`) is for its members, teachers and admins (`managesGroup`), since a group has no owner. Outside the mentor rules, anyone may join or leave a group that isn't a class group. On these routes only teachers and admins add or remove people in a class group; students join and leave theirs through the classes on their Profile (`PUT /api/groups/class-memberships`). Changing a group's name, period or course (`PUT /api/groups/{id}`) is for teachers and admins. A class group keeps its name, and a new name can't be another group's or a class group's name, because Profile's class sync, a course's video call room and the assignment course sync find groups by name. No group name, made or renamed, can contain "/", since group chat's S3 folders use it. Deleting (`DELETE /api/groups/{id}`) is admin-only and never a class group, the same rule the Messages page uses to show Delete. Test: `GroupMembershipAccessTest`. +- A group's grades (`/api/groups/{id}/grades`): reading them (`GET`) is for its members, teachers, admins and whoever grades one of its submissions (`seesGroupGrades`). Replacing or clearing them (`PUT`, `DELETE`) is for teachers and admins, since that changes every assignment's entry. Adding one assignment's entry (`POST`, which also copies it into each member's `gradesJson`) is for them and for whoever grades the group on that assignment (`gradesGroupOn`): its creators and graders (`AssignmentAuthorizationService.canManage`) and the graders of the group's submission to it. Test: `GroupGradesAccessTest`. - [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/api/groups.http b/api/groups.http index c047fa495..e888e8bea 100644 --- a/api/groups.http +++ b/api/groups.http @@ -133,6 +133,22 @@ Content-Type: application/json {"filename": "notes/hello.txt", "base64Data": "Z29vZGJ5ZQ=="} +### 13g. React to a message with a Like -> 200 with {messageId, reactions}, and a reactionsServer frame on /topic/group/{id} +# Any UUID is accepted: Spring doesn't read the S3 file to check the message, and a reaction +# on a message that doesn't exist is never shown. +PUT {{baseUrl}}/api/groups/chat/{{createGroup.response.body.$.id}}/messages/3f2c8a8e-5b1d-4c7e-9a52-8f0e6d4b2a10/reactions/like + +### 13h. List the chat's reactions -> 200 with {"3f2c8a8e-...": [{"reaction": "like", "people": [{uid, name}]}]} +GET {{baseUrl}}/api/groups/chat/{{createGroup.response.body.$.id}}/reactions + +### 13i. Take the Like back -> 200 with an empty reactions list +DELETE {{baseUrl}}/api/groups/chat/{{createGroup.response.body.$.id}}/messages/3f2c8a8e-5b1d-4c7e-9a52-8f0e6d4b2a10/reactions/like + +### 13j. A key that isn't one of the six is refused -> 400 +# Direct messages have the same three routes under /api/dm/conversations/{id}: GET .../reactions, +# and PUT or DELETE .../messages/{messageId}/reactions/{reaction}, for participants only. +PUT {{baseUrl}}/api/groups/chat/{{createGroup.response.body.$.id}}/messages/3f2c8a8e-5b1d-4c7e-9a52-8f0e6d4b2a10/reactions/thumbsup + ### 14. Remove yourself from the test group -> 200 DELETE {{baseUrl}}/api/groups/{{createGroup.response.body.$.id}}/members/{{me.response.body.$.id}} diff --git a/docs/group-chat-architecture.md b/docs/group-chat-architecture.md index 1d0dc01cb..c12c3e4ab 100644 --- a/docs/group-chat-architecture.md +++ b/docs/group-chat-architecture.md @@ -104,11 +104,11 @@ The client sends a `GroupChatEvent` JSON object whose `context` names the event. | `heartbeat` | `heartbeatServer` with `participants` | | | anything else | `errorServer` | `Unsupported context`. | -Edits and deletes made through REST are broadcast too, as `editMessageServer` and `deleteMessageServer`. +Edits and deletes made through REST are broadcast too, as `editMessageServer` and `deleteMessageServer`. So are reactions, as `reactionsServer` with the `messageId` and the message's `reactions` after the change (see Reactions). ## REST operations -Every route needs a signed-in account (the JWT cookie from `POST /authenticate`); without one the answer is 401. No route checks for a teacher or admin role. +Every route needs a signed-in account (the JWT cookie from `POST /authenticate`); without one the answer is 401. No route checks for a teacher or admin role. Mentors are the exception: see [Mentors](#mentors). ### Groups (`GroupsApiController`) @@ -132,37 +132,86 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) | Method | Route | Operation | Who | |---|---|---|---| | GET | `/api/groups/chat/{groupId}/messages` | The group's messages | Any signed-in account | -| POST | `/api/groups/chat/{groupId}/messages` | Send `{message, image}`; broadcasts it and returns the history | Any signed-in account. The sender is the signed-in account. | -| PATCH | `/api/groups/chat/{groupId}/messages/{messageId}` | Edit a message | Only its sender (403 otherwise) | -| DELETE | `/api/groups/chat/{groupId}/messages/{messageId}` | Delete a message | Only its sender (403 otherwise) | +| POST | `/api/groups/chat/{groupId}/messages` | Send `{message, image}`; broadcasts it and returns the history as it was saved. 503 with `Retry-After` when S3 can't read or save the group's messages for now, and then it isn't broadcast (a save that timed out may still be stored, see Persistence) | Any signed-in account. The sender is the signed-in account. | +| PATCH | `/api/groups/chat/{groupId}/messages/{messageId}` | Edit a message; returns the history as it was saved, and 404 when no message has that id. 503 with `Retry-After` when S3 can't read or save the group's messages for now, and then it isn't broadcast (a save that timed out may still be stored, see Persistence) | Only its sender (403 otherwise) | +| DELETE | `/api/groups/chat/{groupId}/messages/{messageId}` | Delete a message; 404 when no message has that id, and then nothing is broadcast. 503 with `Retry-After` when S3 can't read or save the group's messages for now, and then it isn't broadcast (a save that timed out may still be stored, see Persistence) | Only its sender (403 otherwise) | +| GET | `/api/groups/chat/{groupId}/reactions` | Every reaction in the chat, as `{messageId: [{reaction, people: [{uid, name}]}]}` | Any signed-in account | +| PUT | `/api/groups/chat/{groupId}/messages/{messageId}/reactions/{reaction}` | Add your reaction (`like`, `love`, `haha`, `wow`, `sad`, `celebrate`); answers `{messageId, reactions}` and broadcasts `reactionsServer`. 400 for any other key, or a `messageId` that isn't a lowercase UUID | Any signed-in account | +| DELETE | `/api/groups/chat/{groupId}/messages/{messageId}/reactions/{reaction}` | Remove your reaction; the same answer and broadcast, and 200 even when it wasn't there | Any signed-in account | | GET | `/api/groups/chat/unread` | `{total, unreadByGroup}` across your groups | You | | POST | `/api/groups/chat/{groupId}/read` | Mark a group read | You | | GET | `/api/groups/chat/{groupId}/files` | Shared files with who uploaded them, each with its bytes as `base64Data` | Any signed-in account | | GET | `/api/groups/chat/{groupId}/files/index` | Shared files as `[{path, size, uploadedBy, uploadedAt}]`, sorted by path, without bytes | Any signed-in account | | GET | `/api/groups/chat/{groupId}/files/content?path=` | One shared file's bytes (`application/octet-stream`, named by the last part of its path); 400 for a path that isn't valid, 404 when there is no such file | Any signed-in account | -| POST | `/api/groups/chat/{groupId}/files` | Upload `{filename, base64Data}`; 400 when `filename` isn't a valid path, 409 `{message, filename}` when a file is already shared at that path, 503 `{message, filename}` with `Retry-After` when S3 can't say for now whether the path is taken. Broadcasts `sendFileServer` with `filename` and `size`, not the bytes | Any signed-in account | +| POST | `/api/groups/chat/{groupId}/files` | Upload `{filename, base64Data}`; 400 when `filename` isn't a valid path, 409 `{message, filename}` when a file is already shared at that path, 503 `{message, filename}` with `Retry-After` when S3 is unavailable for a moment, checking the path or writing the file. Broadcasts `sendFileServer` with `filename` and `size`, not the bytes | Any signed-in account | | GET | `/api/groups/chat/analytics/{personId}` | Message and file counts across a person's groups | Any signed-in account | +## Mentors + +A mentor is an account with `ROLE_MENTOR` and no teacher or admin role. Flask verifies mentors, and `POST /api/person/mentor/confirm` gives the role. A mentor never talks with a student privately, and the team manages its mentors. `MentorRules` holds every rule as a static method; `MentorAccess` loads what they need about a group (its members, through `GroupsJpaRepository.findMembersOf`, and whether it is a class group). A refusal answers 403 with `{"error": ..., "reason": ...}`; a page shows its own words for the reason. Requests from and about anyone else get the same answers as before, and skip the members query. + +| Route | A mentor | Everyone else | +|---|---|---| +| `/api/groups/chat/{id}/messages` (read, send, edit, delete) and their reactions (`/reactions`, adding or taking one back), `/read`, `/files` (list, upload), `/files/index`, `/files/content`; `GET /api/groups/{id}`; the older `/api/chat/{groupId}` (read, post) | Only a group they are a member of, that isn't a class group and has at least 2 members who aren't mentors (`mentor_not_in_group`, `mentor_class_group`, `mentor_team_too_small`) | As before | +| `GET /api/groups/person/{personId}`, `GET /api/groups/chat/analytics/{personId}` | Only their own id (`mentor_cannot_manage`). Their own group list holds only the groups they may use | As before | +| `GET /api/groups`, `/search`, `POST /api/groups`, `/bulk`, `PUT` and `DELETE /api/groups/{id}`, `/{id}/grades` | Refused (`mentor_cannot_manage`) | As before, except that a new group's `memberIds` may hold a mentor only if its maker could add them | +| `PUT /api/groups/class-memberships` | Only an empty list, to leave every class group; any class is refused (`mentor_class_group`) | As before | +| `POST /api/groups/{id}/members/{personId}` | Refused, themselves included (`mentor_cannot_manage`) | Adding a mentor needs a member who isn't a mentor, or a teacher (`team_manages_mentors`), and a group a mentor may use. Adding anyone else: as before | +| `DELETE /api/groups/{id}/members/{personId}` | Only themselves, to leave (`mentor_cannot_manage`) | Removing a mentor needs a member who isn't a mentor, or a teacher (`team_manages_mentors`). Leaving: always | +| `POST /api/dm/conversations`, `/api/dm/conversations/{id}/messages` (send, edit, and adding or taking back a reaction), and the UI Builder's `POST /api/ui-builder/published/{slug}/message-owner` | Refused (`mentor_no_direct_messages`) | Refused when the conversation would include a mentor. Reading old messages and deleting your own still work | + +- A group response marks each member `"mentor": true` or `false`, so a page can list a team's mentors. +- `POST /api/groups/bulk` makes the other groups when one breaks a mentor rule, and lists that one under `errors` with the refusal's message (one bad group doesn't stop a teacher's batch), so its answer stays 200. +- Members are counted once each: a new group's `memberIds` may repeat an id, and the team size counts different people. +- If a team drops below 2 members who aren't mentors, its mentor loses the group until it is back to 2. Nobody is stopped from leaving. The mentor's unread count (`GET /api/groups/chat/unread`) leaves that group out too, as their own group list does, so the bell never points at a group they can't open. +- The socket follows the same rule: `GroupChatWebSocketController` drops a signed-in mentor's group events (send, file, join, typing, heartbeat) for a group they may not use. Leaving always works. A socket from Spring's own pages carries the roles of its sign-in, so only a mentor's events load their account; a role given after that sign-in counts from the next one. +- Not covered yet: anyone can still subscribe to `/topic/group/{id}` and read what is posted there live (see Known issues). A direct message topic already admits only that conversation's participants (`DirectMessageTopicGuard`). +- Tests: `./mvnw test -Dtest='*Mentor*Test'`. + ## Persistence | Data | Where | Notes | |---|---|---| | Groups and members | SQL: `groups`, `group_members`, and the shared `submitter` table | Ids come from `submitter_seq`, shared with `Person`. | | Read states | SQL: `group_chat_read_state` (`group_id`, `person_id`, `last_read_at`) | One row per member per group. | +| Reactions | SQL: `message_reaction` (`chat_type`, `chat_id`, `message_id`, `person_id`, `reaction`), created at startup by `MessageReactionTableInitializer` | Shared with direct messages (`chat_type` is `DM` or `GROUP`). All five columns are the primary key, so a person leaves each reaction once on a message. Never stored in the group's S3 file. | | Messages | S3: `/messages-images/messages.jsonl` | One JSON line per message: `id`, `author` (display name), `author_uid`, `message`, `date`, `image`, `edited`. | -| Shared files | S3: `/shared-files/` plus `shared-files-meta.json` for who uploaded each | A file shared from a folder keeps its folders: `filename` is a path like `project/src/Main.java` (`SharedFilePaths`: no `..`, `.` or empty names, nothing absolute, no backslashes or control characters, at most 512 characters and 255 per name). A shared file is never written over: the same path again is refused with 409, and so is an upload of a path another upload is writing at that moment (`sharesInFlight`, within one server), so two people sharing `notes.md` at once keep both files. The page then shares its copy under the next free name. A file goes up as one base64 string in JSON, so `JsonLimitsConfig` lets a JSON string be up to 50,000,000 characters, enough for a 35 MB file (Jackson's default of 20,000,000 stopped uploads at about 14 MB; nginx caps a request at 50 MB). The existence check is strict (`S3FileHandler.fileExistsOrThrow`): only S3's 404 reads as free, and any other failure to check refuses the upload rather than risk writing over a file. When S3 timed out, couldn't be reached or answered with a 5xx (a throttle, an outage), that's a 503 with `Retry-After` (`SharedFileCheckFailedException`); S3 refusing the request (a 4xx) or a bug here is a 500. Writes to the metadata file take a lock per group, so uploads that land together keep every name. | +| Shared files | S3: `/shared-files/` plus `shared-files-meta.json` for who uploaded each | A file shared from a folder keeps its folders: `filename` is a path like `project/src/Main.java` (`SharedFilePaths`: no `..`, `.` or empty names, nothing absolute, no backslashes or control characters, at most 512 characters and 255 per name). A shared file is never written over: the same path again is refused with 409, and so is an upload of a path another upload is writing at that moment (`sharesInFlight`, within one server), so two people sharing `notes.md` at once keep both files. The page then shares its copy under the next free name. A file goes up as one base64 string in JSON, so `JsonLimitsConfig` lets a JSON string be up to 50,000,000 characters, enough for a 35 MB file (Jackson's default of 20,000,000 stopped uploads at about 14 MB; nginx caps a request at 50 MB). The existence check is strict (`S3FileHandler.fileExistsOrThrow`): only S3's 404 reads as free, and any other failure to check refuses the upload rather than risk writing over a file. The write is strict too (`S3FileHandler.uploadFileOrThrow`): a failed write throws instead of answering null. When S3 timed out (its own `RequestTimeout` comes as a 400), couldn't be reached or answered with a 5xx (a throttle, an outage), checking or writing, that's a 503 with `Retry-After` (`SharedFileStorageUnavailableException`); S3 refusing the request (any other 4xx) or a bug here is a 500. Writes to the metadata file take a lock per group, so uploads that land together keep every name. | | Presence | Memory only | Lost on restart; rebuilt as clients rejoin. | - **History is keyed by group name, not id.** Renaming a group with `PUT /api/groups/{id}` leaves its history under the old name. -- **Without S3 settings** (AWS credentials, region and bucket), the server logs `S3 is disabled` at startup. Sends still broadcast live, but nothing is saved, so history and files come back empty. This is the normal state of a local server. -- **Every new message rewrites the whole file**, read then write, with no lock. +- **Without S3 settings** (AWS credentials, region and bucket), the server logs `S3 is disabled` at startup. Sends still broadcast live, but nothing is saved, so history and files come back empty, and an edit or delete answers 404 since there's no message to change. This is the normal state of a local server. +- **At every start, `StartupService` creates any missing chat files.** It checks each group and writes an empty messages file and `shared-files/` placeholder where they're missing; the four course groups that `ModelInit` seeds start with none. The check of the messages file is strict (`S3FileHandler.fileExistsOrThrow`), since an empty file written over the real one would erase the group's history: only S3's 404 means there is no file. Any other failure to check (a throttle, a 5xx, a timeout, S3 refusing it) is logged with the group's name and leaves that group as it is (the next start checks it again), and the other groups are still checked. The check holds the group's message lock, so a message sent while the server is starting isn't written over. Without S3 settings nothing is checked. +- **Every new message rewrites the whole file**, read then write. Sending, editing and deleting take one lock per group (`messageLocks` in `GroupChatService`), so two at once keep both changes. The lock only holds within one server: several servers writing the same bucket would need S3's conditional writes. Sending, editing and deleting read the file strictly (`S3FileHandler.decodeFileOrThrow`), since writing back an empty read would replace the whole history: only S3's 404 reads as no messages yet, and any other failure to read refuses the change. They save it strictly too (`S3FileHandler.uploadFileOrThrow`), so a change S3 didn't take isn't answered as saved. When S3 timed out (its own `RequestTimeout` comes as a 400), couldn't be reached or answered with a 5xx, reading or saving, that's a 503 with `Retry-After` (`MessagesStorageUnavailableException`), by the same rule as shared files; S3 refusing the request (any other 4xx) or a bug here gets the route's usual 400. - **A shared file's bytes never go over the socket.** `sendFileServer` names the file and its size; a member downloads it from `/files/content`. Sending the bytes to every subscriber could overflow a session's 512 KB send buffer while another frame was queued, and Spring closes a session that overflows. +- **A shared file whose write timed out may still be stored.** S3 can store a file and then fail to answer, and the AWS SDK's own retries can fail too. The upload then answers 503 without a "shared by" record or a `sendFileServer` frame, and sharing it again finds the path taken (409), which the page handles like any other taken name. +- **A message whose save timed out may still be stored.** S3 can store the messages file and then fail to answer. The change then answers 503 and isn't broadcast, so a message stored that way shows only after a reload, and a send tried again shows up twice. An edit tried again makes the same change, so it lands once, and a delete tried again finds nothing and answers 404. +- **A line that doesn't read as a message is kept.** Loading the chat leaves it out and logs a warning, and a send, edit or delete writes it back as it was (`MessagesLine` in `GroupChatService`), so one bad line isn't lost the next time the file is saved. A message that can't be written as JSON refuses the change, and the route gives its usual 400, instead of being saved as `{}`. + +## Reactions + +People react to a message in a group chat or a direct message with one of six emoji. Spring stores the key, never the emoji: `like` 👍, `love` ❤️, `haha` 😂, `wow` 😮, `sad` 😢, `celebrate` 🎉. The list is `Reaction` in `mvc/reactions`, and Pages' Messages `reactions.js` lists the same keys in the same order, so change both together. + +- A person can leave several reactions on one message, one of each. PUT adds yours and DELETE removes it. Both answer `{messageId, reactions}`, where `reactions` is `[{reaction, people: [{uid, name}]}]` in the list's order, with people sorted by name. +- Group chats use the three routes in the table above. A reaction never reads or writes the group's S3 file: checking that the message exists would mean downloading the whole file, images and all, on every click. So the `messageId` only has to be a lowercase UUID, like the ids Spring saves, and a reaction on a message that doesn't exist is never shown. Deleting a message removes its reactions, a DM's once the delete commits. If the database can't remove them, the delete still goes through and is broadcast, and the error is logged. +- Direct messages have the same three routes under `/api/dm/conversations/{id}`: `GET .../reactions`, and `PUT` or `DELETE .../messages/{messageId}/reactions/{reaction}`. Only the conversation's participants may use them (403 otherwise). A message from another conversation is 404, and a deleted one is 409. The change goes out on `/topic/dm/{id}` as `type: "reactions"`, with `id`, `conversationId` and `reactions`. +- A reaction is not a message. It sends no push notification, changes no unread count, and doesn't show up in search. +- `GroupChatEvent` and `DirectMessageEvent` carry `reactions` only on reaction frames (`@JsonInclude(NON_NULL)`), so every other frame is unchanged. The course chats ignore `reactionsServer`. ## 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'`. +- Reactions: `./mvnw test '-Dtest=GroupChatReactionTest,DirectMessageReactionTest,MessageReaction*Test,ReactionTest'`. They cover both chats' frames and status codes, that a group reaction never touches S3 and a DM reaction never sends a push, the summaries' order, the table's primary key on SQLite, and a delete whose reactions can't be removed. - 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. +- `GroupChatServiceTest` covers two sends, an edit and a send, and a delete and a send landing at once. +- `GroupChatSendTest` sends through the controller to a real `S3FileHandler` over a stand-in S3 client: a read that fails, a read S3 refuses, a bug, a group with no messages file yet, and a server without S3. `S3FileHandlerDecodeTest` covers the strict read. Run the S3 handler tests with `./mvnw test '-Dtest=S3FileHandler*Test'`. +- `StartupServiceTest` runs the start-up check over a real `S3FileHandler` and a stand-in S3 client: checks that fail, a group that can't be checked among others, a group with no messages file yet, a group that has one, a server without S3, and a send during the check. Run it with `./mvnw test '-Dtest=StartupServiceTest'`. +- `GroupChatFilesTest` also covers a write that fails, including sharing again once S3 is back, and `S3FileHandlerUploadTest` covers the strict write. +- `GroupChatSendTest` also covers an upload that fails after a good read, and `GroupChatEditDeleteTest` covers edits and deletes whose read or upload fails, both through the controller over a stand-in S3 client. +- `GroupChatSendTest` and `GroupChatEditDeleteTest` also check that a send and an edit answer with the messages they saved, even when S3 fails right after. +- `GroupChatEditDeleteTest` also checks that a delete of a message that isn't saved answers 404 and tells no one, with or without S3 settings. +- `GroupChatMessagesFileTest` covers a line that doesn't read as a message, kept in place through a send, an edit and a delete and left out when the chat loads, and a message that can't be written. ## Known issues @@ -171,14 +220,15 @@ These were each reproduced against a local server built from `master` on 2026-10 - **Sending a message over the WebSocket fails.** Since commit `27a58329` ("identity service delegation, remove client controlled sender"), `sendMessage` resolves the sender with `GroupChatIdentityService`, which reads Spring Security's context. Nothing puts the signed-in account into that context for WebSocket messages: `/ws-chat` is `permitAll`, and `ChatSocketIdentityInterceptor` reads the login cookie only for the direct message topic check, without setting a Principal. So every `sendMessage`, signed in or not, is answered with `errorServer` "Authentication required", and the message is neither saved nor broadcast. Sending with `POST /api/groups/chat/{groupId}/messages` works: the message is broadcast to every subscriber with the signed-in account's name. The course site's chats send over the WebSocket, so they are affected. - **`group_chat_read_state` is never created on an existing database.** #225 added the `GroupChatReadState` entity, but nothing creates its table, and Hibernate runs with `ddl-auto=none`. On a database without the table, `POST /api/groups/chat/{groupId}/read` returns 500 (`no such table: group_chat_read_state`), and `GET /api/groups/chat/unread` fails the same way for anyone in a group. `direct_message_read_state` is created in `ModelInit`; this table needs the same. - **The client chooses the name for presence and typing.** `joinGroup`, `typingStart` and `heartbeat` use the `sender` field the client sends, even from a socket that isn't signed in. -- **No membership checks.** Any signed-in account can read and send in any group, list and upload its files, and manage any group, its members and its grades. The membership checks in `GroupChatApiController` are commented out. +- **No membership checks.** Any signed-in account that isn't a mentor can read and send in any group, list, download and upload its files, and manage any group, its members and its grades. The membership checks in `GroupChatApiController` are commented out. Mentors are checked: see [Mentors](#mentors). The older `/api/chat/{groupId}` (`ChatApiController`, its own `chat_history.jsonl` per group) does check: only a group's members, teachers and admins read it, and only members post. +- **Anyone can follow a group's socket topic.** `/ws-chat` is `permitAll`, so anyone, signed in or not, can subscribe to `/topic/group/{id}` and receive what is posted there live. `GroupChatWebSocketController` drops an event from a socket with no signed-in identity, and checks no membership for one that has one (mentors are checked: see [Mentors](#mentors)). Direct message topics are guarded (`DirectMessageTopicGuard`). - **Edit and delete require the stored author uid.** The REST controller passes the authenticated account's uid through the realtime service; display names never establish ownership. Legacy messages without `author_uid` cannot be edited or deleted through these routes. Teachers cannot delete another account's message. -- **Two sends at once can lose one.** Each send reads the group's S3 file, adds a line and writes the file back, without a lock. - **The first group created after a restart fails on SQLite.** `POST /api/groups` returns 500 with `SQLITE_BUSY_SNAPSHOT` the first time after the server starts; the next attempt works. This is the `GenerationType.AUTO` lock problem described under Assignment grading in `AGENTS.md`, here on `submitter_seq`. Not checked on MySQL. ## Change checklist - Keep routes, event `context` names and JSON field names stable: the course site's chat pages depend on them. Change them together with the Pages client. - New tables need a `CREATE TABLE IF NOT EXISTS` that runs at startup, because Hibernate runs with `ddl-auto=none`. +- Reaction keys change in `Reaction` and in Pages' Messages `reactions.js` together. - Anything that needs to know who is sending must work over both REST and the WebSocket, or send through REST. - Update this guide and `api/groups.http` when routes, events or storage change. `README.md` and `AGENTS.md` link here. diff --git a/src/main/java/com/open/spring/StartupService.java b/src/main/java/com/open/spring/StartupService.java index 0f6c434f5..d2c28de6d 100644 --- a/src/main/java/com/open/spring/StartupService.java +++ b/src/main/java/com/open/spring/StartupService.java @@ -11,9 +11,11 @@ import com.open.spring.mvc.groups.GroupsJpaRepository; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; @Component @RequiredArgsConstructor +@Slf4j public class StartupService { private final GroupsJpaRepository groupsRepository; @@ -25,9 +27,15 @@ public ApplicationRunner initializeGroupStorage() { // Fetch all existing groups from the database List groups = groupsRepository.findAll(); - // Ensure S3 storage exists for each group + // Ensure S3 storage exists for each group. A group whose storage can't be checked is + // left as it is until the next start, and the other groups are still checked, so one + // group can't stop the server from starting. for (Groups group : groups) { - groupChatService.ensureGroupStorageExists(group.getName()); + try { + groupChatService.ensureGroupStorageExists(group.getName()); + } catch (RuntimeException e) { + log.warn("Could not check the chat storage of group {}, so nothing was written to it", group.getName(), e); + } } }; } diff --git a/src/main/java/com/open/spring/mvc/S3uploads/S3FileHandler.java b/src/main/java/com/open/spring/mvc/S3uploads/S3FileHandler.java index fafef2054..8f1f4dab7 100644 --- a/src/main/java/com/open/spring/mvc/S3uploads/S3FileHandler.java +++ b/src/main/java/com/open/spring/mvc/S3uploads/S3FileHandler.java @@ -79,6 +79,11 @@ public void init() { this.s3Client = builder.build(); } + /** Whether this server has S3 settings (AWS credentials, region and bucket). Without them nothing is stored. */ + public boolean isConfigured() { + return s3Client != null; + } + @Override public String uploadFile(String base64Data, String filename, String uid) { if (s3Client == null) { @@ -105,6 +110,23 @@ public String uploadFile(String base64Data, String filename, String uid) { } } + /** + * Like uploadFile, but a write that fails throws instead of answering null, so a caller can + * tell S3 being unavailable for a moment (a throttle, a 5xx, no connection) from a request + * S3 refused. + */ + public String uploadFileOrThrow(String base64Data, String filename, String uid) { + if (s3Client == null) { + throw new IllegalStateException("S3 client is not configured"); + } + s3Client.putObject(PutObjectRequest.builder() + .bucket(bucketName) + .key(generateKey(uid, filename)) + .build(), + RequestBody.fromBytes(Base64.getDecoder().decode(base64Data))); + return filename; + } + @Override public String decodeFile(String uid, String filename) { if (s3Client == null) { @@ -264,6 +286,31 @@ public boolean fileExistsOrThrow(String uid, String filename) { } } + /** + * Like decodeFile, but only "not found" (404) reads as nothing stored: any other failure to + * read (a throttle, a 5xx, no connection) throws. For a caller that writes back what it read, + * a read that failed is not an empty file. With no S3 client there is nothing to read and + * nothing can be written, so that reads as nothing stored, as in decodeFile. + */ + public String decodeFileOrThrow(String uid, String filename) { + if (s3Client == null) { + log.warn("S3 download attempted but S3 client is not configured."); + return null; + } + try { + ResponseBytes objectBytes = s3Client.getObjectAsBytes(GetObjectRequest.builder() + .bucket(bucketName) + .key(generateKey(uid, filename)) + .build()); + return Base64.getEncoder().encodeToString(objectBytes.asByteArray()); + } catch (S3Exception e) { + if (e.statusCode() == 404) { + return null; + } + throw e; + } + } + private String generateKey(String uid, String filename) { return uid + "/" + filename; } diff --git a/src/main/java/com/open/spring/mvc/chat/ChatApiController.java b/src/main/java/com/open/spring/mvc/chat/ChatApiController.java index d1a6e1f0e..d361e3cac 100644 --- a/src/main/java/com/open/spring/mvc/chat/ChatApiController.java +++ b/src/main/java/com/open/spring/mvc/chat/ChatApiController.java @@ -19,6 +19,10 @@ import com.open.spring.mvc.groups.Groups; import com.open.spring.mvc.groups.GroupsJpaRepository; +import com.open.spring.mvc.groups.MentorAccess; +import com.open.spring.mvc.groups.MentorRules; +import com.open.spring.mvc.person.Person; +import com.open.spring.mvc.person.PersonJpaRepository; import lombok.AllArgsConstructor; import lombok.Data; @@ -31,10 +35,25 @@ public class ChatApiController { private final ChatService chatService; private final GroupsJpaRepository groupsRepository; + private final PersonJpaRepository personRepository; + private final MentorAccess mentorAccess; - public ChatApiController(ChatService chatService, GroupsJpaRepository groupsRepository) { + public ChatApiController(ChatService chatService, GroupsJpaRepository groupsRepository, + PersonJpaRepository personRepository, MentorAccess mentorAccess) { this.chatService = chatService; this.groupsRepository = groupsRepository; + this.personRepository = personRepository; + this.mentorAccess = mentorAccess; + } + + /** + * A mentor rule's refusal for the signed-in account and this group, or null when it may go on. This older chat + * follows the same rule as the group chat (MentorRules): only a mentor can be refused. + */ + private ResponseEntity mentorRefusal(Groups group) { + String uid = getCurrentUsername(); + Person person = uid == null ? null : personRepository.findByUid(uid); + return mentorAccess.toUse(person, group).map(MentorRules.Refusal::toResponse).orElse(null); } @Data @@ -46,27 +65,32 @@ public static class ChatMessageRequest { @GetMapping("/{groupId}") @Transactional(readOnly = true) - public ResponseEntity> getChat(@PathVariable Long groupId) { + public ResponseEntity getChat(@PathVariable Long groupId) { Optional groupOpt = groupsRepository.findById(groupId); if (groupOpt.isEmpty()) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } + ResponseEntity refusal = mentorRefusal(groupOpt.get()); + if (refusal != null) { + return refusal; + } - // String currentUsername = getCurrentUsername(); - // if (currentUsername == null) { - // return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); - // } - - // if (!isMember(groupOpt.get(), currentUsername)) { - // return new ResponseEntity<>(HttpStatus.FORBIDDEN); - // } + // Only the group's members, teachers and admins read its chat. + String currentUsername = getCurrentUsername(); + if (currentUsername == null) { + return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); + } + if (!isMember(groupOpt.get(), currentUsername) + && !MentorRules.isStaff(personRepository.findByUid(currentUsername))) { + return new ResponseEntity<>(HttpStatus.FORBIDDEN); + } return new ResponseEntity<>(chatService.getChatHistory(groupId), HttpStatus.OK); } @PostMapping("/{groupId}") @Transactional - public ResponseEntity> postChat( + public ResponseEntity postChat( @PathVariable Long groupId, @RequestBody ChatMessageRequest request) { Optional groupOpt = groupsRepository.findById(groupId); @@ -79,6 +103,11 @@ public ResponseEntity> postChat( return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); } + // A mentor hears why (MentorRules) before anyone outside the group gets a plain 403. + ResponseEntity refusal = mentorRefusal(groupOpt.get()); + if (refusal != null) { + return refusal; + } if (!isMember(groupOpt.get(), currentUsername)) { return new ResponseEntity<>(HttpStatus.FORBIDDEN); } diff --git a/src/main/java/com/open/spring/mvc/directmessages/DirectMessageApiController.java b/src/main/java/com/open/spring/mvc/directmessages/DirectMessageApiController.java index 9dab2859f..43a0a8a39 100644 --- a/src/main/java/com/open/spring/mvc/directmessages/DirectMessageApiController.java +++ b/src/main/java/com/open/spring/mvc/directmessages/DirectMessageApiController.java @@ -6,6 +6,7 @@ import java.util.NoSuchElementException; import java.util.Optional; import java.util.Set; +import java.util.stream.Stream; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -17,13 +18,19 @@ import org.springframework.web.bind.annotation.PatchMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; +import com.open.spring.mvc.groups.MentorRules; import com.open.spring.mvc.person.Person; import com.open.spring.mvc.person.PersonJpaRepository; +import com.open.spring.mvc.reactions.ChatType; +import com.open.spring.mvc.reactions.MessageReactionService; +import com.open.spring.mvc.reactions.MessageReactionService.MessageReactions; +import com.open.spring.mvc.reactions.Reaction; import lombok.AllArgsConstructor; import lombok.Data; @@ -46,6 +53,7 @@ public class DirectMessageApiController { private final DirectMessageConversationJpaRepository conversationRepository; private final DirectMessageJpaRepository messageRepository; private final PersonJpaRepository personRepository; + private final MessageReactionService reactionService; @Data @NoArgsConstructor @@ -149,6 +157,12 @@ public ResponseEntity startConversation( return new ResponseEntity<>(Map.of("error", "No valid recipients found"), HttpStatus.BAD_REQUEST); } + Optional refusal = MentorRules.shareDirectMessages( + Stream.concat(Stream.of(person), others.stream()).toList()); + if (refusal.isPresent()) { + return refusal.get().toResponse(); + } + // Must run before a new conversation is persisted: a query afterwards auto-flushes it, and the // commit-time flush then compares its participants by Person.hashCode(), which recurses forever // through Person <-> Bank (both Lombok @Data). @@ -205,6 +219,11 @@ public ResponseEntity postMessage( return new ResponseEntity<>(HttpStatus.FORBIDDEN); } + Optional refusal = MentorRules.shareDirectMessages(conversation.getParticipants()); + if (refusal.isPresent()) { + return refusal.get().toResponse(); + } + if (request == null) { return new ResponseEntity<>(Map.of("error", "body is required"), HttpStatus.BAD_REQUEST); } @@ -247,6 +266,11 @@ public ResponseEntity editMessage( return new ResponseEntity<>(HttpStatus.FORBIDDEN); } + Optional refusal = MentorRules.shareDirectMessages(conversation.getParticipants()); + if (refusal.isPresent()) { + return refusal.get().toResponse(); + } + if (request == null || request.getBody() == null || request.getBody().isBlank()) { return new ResponseEntity<>(Map.of("error", "body is required"), HttpStatus.BAD_REQUEST); } @@ -295,6 +319,87 @@ public ResponseEntity deleteMessage( } } + /** Every reaction in the conversation, by message id: what the page draws when it opens it. */ + @GetMapping("/conversations/{id}/reactions") + @Transactional(readOnly = true) + public ResponseEntity getReactions( + @AuthenticationPrincipal UserDetails userDetails, + @PathVariable("id") Long id) { + Person person = currentPerson(userDetails); + if (person == null) { + return new ResponseEntity<>(Map.of("error", "User not authenticated"), HttpStatus.UNAUTHORIZED); + } + + Optional conversationOpt = conversationRepository.findById(id); + if (conversationOpt.isEmpty()) { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + if (!directMessageService.isParticipant(conversationOpt.get(), person)) { + return new ResponseEntity<>(HttpStatus.FORBIDDEN); + } + + return new ResponseEntity<>(reactionService.forChat(ChatType.DM, id), HttpStatus.OK); + } + + /** Adds the caller's reaction, by its lowercase key such as "like", and answers with the message's reactions. */ + @PutMapping("/conversations/{id}/messages/{messageId}/reactions/{reaction}") + @Transactional + public ResponseEntity addReaction( + @AuthenticationPrincipal UserDetails userDetails, + @PathVariable("id") Long id, + @PathVariable("messageId") Long messageId, + @PathVariable("reaction") String reaction) { + return setReaction(userDetails, id, messageId, reaction, true); + } + + /** Removes the caller's reaction; removing one that isn't there still answers 200. */ + @DeleteMapping("/conversations/{id}/messages/{messageId}/reactions/{reaction}") + @Transactional + public ResponseEntity removeReaction( + @AuthenticationPrincipal UserDetails userDetails, + @PathVariable("id") Long id, + @PathVariable("messageId") Long messageId, + @PathVariable("reaction") String reaction) { + return setReaction(userDetails, id, messageId, reaction, false); + } + + private ResponseEntity setReaction(UserDetails userDetails, Long id, Long messageId, String key, boolean on) { + Person person = currentPerson(userDetails); + if (person == null) { + return new ResponseEntity<>(Map.of("error", "User not authenticated"), HttpStatus.UNAUTHORIZED); + } + + Optional conversationOpt = conversationRepository.findById(id); + if (conversationOpt.isEmpty()) { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + + DirectMessageConversation conversation = conversationOpt.get(); + if (!directMessageService.isParticipant(conversation, person)) { + return new ResponseEntity<>(HttpStatus.FORBIDDEN); + } + + // Reacting follows the send rule, like posting and editing + Optional refusal = MentorRules.shareDirectMessages(conversation.getParticipants()); + if (refusal.isPresent()) { + return refusal.get().toResponse(); + } + + Optional reaction = Reaction.fromKey(key); + if (reaction.isEmpty()) { + return new ResponseEntity<>(Map.of("error", "unknown reaction"), HttpStatus.BAD_REQUEST); + } + + try { + return new ResponseEntity<>(new MessageReactions(String.valueOf(messageId), + directMessageService.setReaction(conversation, person, messageId, reaction.get(), on)), HttpStatus.OK); + } catch (NoSuchElementException ex) { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } catch (IllegalStateException ex) { + return new ResponseEntity<>(Map.of("error", ex.getMessage()), HttpStatus.CONFLICT); + } + } + @PostMapping("/conversations/{id}/read") @Transactional public ResponseEntity markRead( diff --git a/src/main/java/com/open/spring/mvc/directmessages/DirectMessageEvent.java b/src/main/java/com/open/spring/mvc/directmessages/DirectMessageEvent.java index b68c9c465..09b7b42f0 100644 --- a/src/main/java/com/open/spring/mvc/directmessages/DirectMessageEvent.java +++ b/src/main/java/com/open/spring/mvc/directmessages/DirectMessageEvent.java @@ -1,5 +1,10 @@ package com.open.spring.mvc.directmessages; +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.open.spring.mvc.reactions.MessageReactionService; + import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -16,7 +21,7 @@ public class DirectMessageEvent { private Long id; private Long conversationId; - private String type; // "message" for new posts, "edited" for edits + private String type; // "message", "edited", "deleted", or "reactions" private String senderUid; private String senderName; private String senderPfp; @@ -26,4 +31,10 @@ public class DirectMessageEvent { private String sentAt; private boolean deleted; private boolean edited; + /** + * On a "reactions" frame, the message's reactions after the change. Left out of every + * other frame, so those stay exactly as they were. + */ + @JsonInclude(JsonInclude.Include.NON_NULL) + private List reactions; } diff --git a/src/main/java/com/open/spring/mvc/directmessages/DirectMessageService.java b/src/main/java/com/open/spring/mvc/directmessages/DirectMessageService.java index 5c9101391..dc82a598c 100644 --- a/src/main/java/com/open/spring/mvc/directmessages/DirectMessageService.java +++ b/src/main/java/com/open/spring/mvc/directmessages/DirectMessageService.java @@ -8,15 +8,22 @@ import java.util.NoSuchElementException; import java.util.Set; +import org.springframework.dao.DataAccessException; import org.springframework.data.domain.PageRequest; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronization; +import org.springframework.transaction.support.TransactionSynchronizationManager; import com.open.spring.mvc.person.Person; import com.open.spring.mvc.push.PushNotificationService; +import com.open.spring.mvc.reactions.ChatType; +import com.open.spring.mvc.reactions.MessageReactionService; +import com.open.spring.mvc.reactions.Reaction; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; /** * Business logic for direct messages: finding/creating conversations, checking @@ -26,6 +33,7 @@ */ @Service @RequiredArgsConstructor +@Slf4j public class DirectMessageService { public static final String DM_TOPIC_PREFIX = "/topic/dm/"; @@ -41,6 +49,7 @@ public class DirectMessageService { private final DirectMessageReadStateJpaRepository readStateRepository; private final SimpMessagingTemplate messagingTemplate; private final PushNotificationService pushNotificationService; + private final MessageReactionService reactionService; public record UnreadSender(String uid, String name) { } @@ -222,6 +231,10 @@ public void deleteMessage(DirectMessageConversation conversation, Person request message.setDeleted(true); message.setBody(""); messageRepository.save(message); + // A tombstone shows no reactions, so none are kept for it. They're removed after the delete + // commits: an error from the reactions table inside this transaction would undo the delete. + Long conversationId = conversation.getId(); + afterCommit(() -> removeReactions(conversationId, messageId)); DirectMessageEvent event = DirectMessageEvent.builder() .id(message.getId()) @@ -235,6 +248,68 @@ public void deleteMessage(DirectMessageConversation conversation, Person request messagingTemplate.convertAndSend(DM_TOPIC_PREFIX + conversation.getId(), event); } + /** + * Adds ({@code on}) or removes {@code person}'s reaction to a message, then tells the + * conversation's topic with a "reactions" frame. A reaction isn't a message: nobody gets a + * phone notification and nothing becomes unread. Throws {@link NoSuchElementException} if + * the message isn't in this conversation and {@link IllegalStateException} if it was + * deleted; {@code noRollbackFor} for the reason given on {@link #editMessage}. + */ + @Transactional(noRollbackFor = {NoSuchElementException.class, IllegalStateException.class}) + public List setReaction(DirectMessageConversation conversation, + Person person, Long messageId, Reaction reaction, boolean on) { + DirectMessage message = messageRepository.findByIdAndConversation(messageId, conversation) + .orElseThrow(() -> new NoSuchElementException("Message not found")); + if (message.isDeleted()) { + throw new IllegalStateException("Message was deleted"); + } + + String key = String.valueOf(messageId); + if (on) { + reactionService.add(ChatType.DM, conversation.getId(), key, person, reaction); + } else { + reactionService.remove(ChatType.DM, conversation.getId(), key, person, reaction); + } + List reactions = + reactionService.forMessage(ChatType.DM, conversation.getId(), key); + + // The frame goes out once this commits, with the reactions read again then. Read here, + // inside this transaction, they could miss a reaction someone else saved at the same time, + // and that person's frame would miss this one. + Long conversationId = conversation.getId(); + afterCommit(() -> messagingTemplate.convertAndSend(DM_TOPIC_PREFIX + conversationId, DirectMessageEvent.builder() + .id(messageId) + .conversationId(conversationId) + .type("reactions") + .reactions(reactionService.forMessageNow(ChatType.DM, conversationId, key)) + .build())); + return reactions; + } + + // Runs once the current transaction commits, or right away outside one. + /** Removes a deleted message's reactions. The delete is already done, so a failure is only logged. */ + private void removeReactions(Long conversationId, Long messageId) { + try { + reactionService.removeAllFor(ChatType.DM, conversationId, String.valueOf(messageId)); + } catch (DataAccessException e) { + log.warn("Could not remove the reactions of deleted message {} in conversation {}", + messageId, conversationId, e); + } + } + + private static void afterCommit(Runnable action) { + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { + @Override + public void afterCommit() { + action.run(); + } + }); + } else { + action.run(); + } + } + @Transactional(readOnly = true) public UnreadSummary getUnreadSummary(Person person) { Map people = new LinkedHashMap<>(); 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 ac52e6895..887761000 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/ClassGroupMembershipService.java b/src/main/java/com/open/spring/mvc/groups/ClassGroupMembershipService.java index c65801af7..4cfa374b8 100644 --- a/src/main/java/com/open/spring/mvc/groups/ClassGroupMembershipService.java +++ b/src/main/java/com/open/spring/mvc/groups/ClassGroupMembershipService.java @@ -84,6 +84,11 @@ public List syncMemberships(String uid, List classes) { .toList(); } + /** Whether a group name is one of the class groups, ignoring case and spaces around it. */ + public boolean isClassGroup(String groupName) { + return groupName != null && classGroupNames.contains(groupName.trim().toUpperCase(Locale.ROOT)); + } + private Set normalizeClasses(List classes) { Set normalizedClasses = new LinkedHashSet<>(); if (classes == null) { diff --git a/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java b/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java index 60eaaf80f..72f5cfe8b 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java @@ -4,6 +4,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.regex.Pattern; import java.nio.charset.StandardCharsets; @@ -20,6 +21,7 @@ import org.springframework.web.bind.annotation.PatchMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; @@ -28,6 +30,10 @@ import com.open.spring.mvc.groups.GroupChatIdentityService.AuthenticatedIdentity; import com.open.spring.mvc.person.Person; import com.open.spring.mvc.person.PersonJpaRepository; +import com.open.spring.mvc.reactions.ChatType; +import com.open.spring.mvc.reactions.MessageReactionService; +import com.open.spring.mvc.reactions.MessageReactionService.MessageReactions; +import com.open.spring.mvc.reactions.Reaction; import lombok.AllArgsConstructor; import lombok.Data; @@ -38,27 +44,48 @@ @CrossOrigin public class GroupChatApiController { - // How long to wait before sharing again when S3 couldn't check a path: a throttle or a - // short outage clears in seconds. - private static final int SHARE_RETRY_AFTER_SECONDS = 5; + // How long to wait before trying again when S3 was unavailable for a moment, checking or + // writing a shared file or reading or saving a group's messages: a throttle or a short + // outage clears in seconds. + private static final int RETRY_AFTER_SECONDS = 5; + + // A saved group message's id is a UUID (GroupChatMessage), written in lowercase. Reactions + // don't read the group's S3 file to check that the message exists, so the id at least has to + // look like one; an uppercase copy would match some lookups and not others on MySQL. + static final Pattern MESSAGE_ID = + Pattern.compile("^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"); private final GroupChatService groupChatService; private final GroupChatRealtimeService realtimeService; private final GroupChatReadService readService; private final GroupsJpaRepository groupsRepository; private final PersonJpaRepository personRepository; + private final MessageReactionService reactionService; + private final MentorAccess mentorAccess; public GroupChatApiController( GroupChatService groupChatService, GroupChatRealtimeService realtimeService, GroupChatReadService readService, GroupsJpaRepository groupsRepository, - PersonJpaRepository personRepository) { + PersonJpaRepository personRepository, + MessageReactionService reactionService, + MentorAccess mentorAccess) { this.groupChatService = groupChatService; this.realtimeService = realtimeService; this.readService = readService; this.groupsRepository = groupsRepository; this.personRepository = personRepository; + this.reactionService = reactionService; + this.mentorAccess = mentorAccess; + } + + /** + * A mentor rule's refusal for the signed-in account and this group, or null when it may go on. Only a mentor + * can be refused here; everyone else's chat works as before (see MentorRules). + */ + private ResponseEntity mentorRefusal(Groups group) { + return mentorAccess.toUse(currentPerson(), group).map(MentorRules.Refusal::toResponse).orElse(null); } @Data @@ -128,6 +155,14 @@ private String resolveCurrentDisplayName() { @GetMapping("/analytics/{personId}") public ResponseEntity getUserAnalytics(@PathVariable Long personId) { + Person viewer = currentPerson(); + if (viewer != null && !personId.equals(viewer.getId())) { + Optional refusal = MentorRules.manageGroups(viewer); + if (refusal.isPresent()) { + return refusal.get().toResponse(); + } + } + Optional personOpt = personRepository.findById(personId); if (personOpt.isEmpty()) { return new ResponseEntity<>("Person not found", HttpStatus.NOT_FOUND); @@ -149,6 +184,10 @@ public ResponseEntity getMessages(@PathVariable Long groupId) { if (groupOpt.isEmpty()) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } + ResponseEntity refusal = mentorRefusal(groupOpt.get()); + if (refusal != null) { + return refusal; + } // String currentUsername = getCurrentUsername(); // if (currentUsername == null) { @@ -177,6 +216,10 @@ public ResponseEntity postMessage( if (identity == null) { return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); } + ResponseEntity refusal = mentorRefusal(groupOpt.get()); + if (refusal != null) { + return refusal; + } // String currentUsername = getCurrentUsername(); // if (currentUsername == null) { @@ -190,15 +233,16 @@ public ResponseEntity postMessage( return new ResponseEntity<>("name and message are required", HttpStatus.BAD_REQUEST); } + // Answered from what was saved: a second read could fail and answer an empty chat. + List saved; try { - realtimeService.publishMessage(groupId, message.getMessage(), message.getImage(), identity); + saved = realtimeService.publishMessage(groupId, message.getMessage(), message.getImage(), identity); + } catch (MessagesStorageUnavailableException ex) { + return tryAgainLater(ex); } catch (RuntimeException ex) { return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST); } - - String groupName = groupOpt.get().getName(); - List updated = groupChatService.getMessages(groupName); - return new ResponseEntity<>(updated, HttpStatus.OK); + return new ResponseEntity<>(saved, HttpStatus.OK); } @PatchMapping("/{groupId}/messages/{messageId}") @@ -215,26 +259,29 @@ public ResponseEntity editMessage( if (identity == null) { return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); } + ResponseEntity refusal = mentorRefusal(groupOpt.get()); + if (refusal != null) { + return refusal; + } if (request == null || request.getMessage() == null || request.getMessage().isBlank()) { return new ResponseEntity<>("message is required", HttpStatus.BAD_REQUEST); } - boolean updated; + Optional> saved; try { - updated = realtimeService.editMessage(groupId, messageId, request.getMessage(), identity.getUid()); + saved = realtimeService.editMessage(groupId, messageId, request.getMessage(), identity.getUid()); } catch (SecurityException ex) { return new ResponseEntity<>(HttpStatus.FORBIDDEN); + } catch (MessagesStorageUnavailableException ex) { + return tryAgainLater(ex); } catch (RuntimeException ex) { return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST); } - if (!updated) { + if (saved.isEmpty()) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } - - String groupName = groupOpt.get().getName(); - List messages = groupChatService.getMessages(groupName); - return new ResponseEntity<>(messages, HttpStatus.OK); + return new ResponseEntity<>(saved.get(), HttpStatus.OK); } @DeleteMapping("/{groupId}/messages/{messageId}") @@ -250,18 +297,102 @@ public ResponseEntity deleteMessage( if (identity == null) { return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); } + ResponseEntity refusal = mentorRefusal(groupOpt.get()); + if (refusal != null) { + return refusal; + } + boolean deleted; try { - realtimeService.deleteMessage(groupId, messageId, identity.getUid()); + deleted = realtimeService.deleteMessage(groupId, messageId, identity.getUid()); } catch (SecurityException ex) { return new ResponseEntity<>(HttpStatus.FORBIDDEN); + } catch (MessagesStorageUnavailableException ex) { + return tryAgainLater(ex); } catch (RuntimeException ex) { return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST); } - + if (!deleted) { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } return new ResponseEntity<>(HttpStatus.OK); } + /** + * S3 couldn't read or save the group's messages, so the change isn't broadcast (a save that + * timed out may still be stored). That's S3 being unavailable for a moment, not a bug here: + * a 503, and when to try again. + */ + private static ResponseEntity tryAgainLater(MessagesStorageUnavailableException ex) { + return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE) + .header(HttpHeaders.RETRY_AFTER, String.valueOf(RETRY_AFTER_SECONDS)) + .body(ex.getMessage()); + } + + /** + * Every reaction in the group's chat, by message id: what the page draws when it opens the + * chat. Like posting, it needs a signed-in person but not membership. + */ + @GetMapping("/{groupId}/reactions") + public ResponseEntity getReactions(@PathVariable Long groupId) { + if (currentPerson() == null) { + return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); + } + Optional groupOpt = groupsRepository.findById(groupId); + if (groupOpt.isEmpty()) { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + ResponseEntity refusal = mentorRefusal(groupOpt.get()); + if (refusal != null) { + return refusal; + } + return new ResponseEntity<>(reactionService.forChat(ChatType.GROUP, groupId), HttpStatus.OK); + } + + /** Adds the caller's reaction, by its lowercase key such as "like", and answers with the message's reactions. */ + @PutMapping("/{groupId}/messages/{messageId}/reactions/{reaction}") + public ResponseEntity addReaction( + @PathVariable Long groupId, + @PathVariable String messageId, + @PathVariable String reaction) { + return setReaction(groupId, messageId, reaction, true); + } + + /** Removes the caller's reaction; removing one that isn't there still answers 200. */ + @DeleteMapping("/{groupId}/messages/{messageId}/reactions/{reaction}") + public ResponseEntity removeReaction( + @PathVariable Long groupId, + @PathVariable String messageId, + @PathVariable String reaction) { + return setReaction(groupId, messageId, reaction, false); + } + + private ResponseEntity setReaction(Long groupId, String messageId, String key, boolean on) { + Person person = currentPerson(); + if (person == null) { + return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); + } + Optional groupOpt = groupsRepository.findById(groupId); + if (groupOpt.isEmpty()) { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + ResponseEntity refusal = mentorRefusal(groupOpt.get()); + if (refusal != null) { + return refusal; + } + Optional reaction = Reaction.fromKey(key); + if (reaction.isEmpty()) { + return new ResponseEntity<>("unknown reaction", HttpStatus.BAD_REQUEST); + } + if (messageId == null || !MESSAGE_ID.matcher(messageId).matches()) { + return new ResponseEntity<>("messageId is not a message id", HttpStatus.BAD_REQUEST); + } + + List reactions = + realtimeService.setReaction(groupId, person, messageId, reaction.get(), on); + return new ResponseEntity<>(new MessageReactions(messageId, reactions), HttpStatus.OK); + } + /** * Unread counts for the signed-in member's own groups, keyed by group id. Groups * with nothing unread are left out, so an empty map means nothing is waiting. @@ -273,7 +404,10 @@ public ResponseEntity getUnread() { return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); } - Map unreadByGroup = readService.unreadByGroup(person); + Map unreadByGroup = new HashMap<>(readService.unreadByGroup(person)); + // A mentor's count leaves out the groups their own list leaves out (MentorRules), so the bell never points + // at a group they can't open or mark read. + unreadByGroup.keySet().removeIf(groupId -> mentorAccess.refusesGroup(person, groupId)); long total = unreadByGroup.values().stream().mapToLong(Long::longValue).sum(); Map body = new HashMap<>(); @@ -294,6 +428,10 @@ public ResponseEntity markRead(@PathVariable Long groupId) { if (groupOpt.isEmpty()) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } + ResponseEntity refusal = mentorRefusal(groupOpt.get()); + if (refusal != null) { + return refusal; + } readService.markRead(groupOpt.get(), person); return new ResponseEntity<>(HttpStatus.OK); @@ -305,6 +443,10 @@ public ResponseEntity getSharedFiles(@PathVariable Long groupId) { if (groupOpt.isEmpty()) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } + ResponseEntity refusal = mentorRefusal(groupOpt.get()); + if (refusal != null) { + return refusal; + } // String currentUsername = getCurrentUsername(); // if (currentUsername == null) { @@ -330,6 +472,10 @@ public ResponseEntity getSharedFileIndex(@PathVariable Long groupId) { if (groupOpt.isEmpty()) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } + ResponseEntity refusal = mentorRefusal(groupOpt.get()); + if (refusal != null) { + return refusal; + } return new ResponseEntity<>(groupChatService.sharedFileIndex(groupOpt.get().getName()), HttpStatus.OK); } @@ -344,6 +490,10 @@ public ResponseEntity getSharedFileContent(@PathVariable Long groupId, @Reque if (groupOpt.isEmpty()) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } + ResponseEntity refusal = mentorRefusal(groupOpt.get()); + if (refusal != null) { + return refusal; + } byte[] bytes = groupChatService.readSharedFile(groupOpt.get().getName(), cleanPath); if (bytes == null) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); @@ -365,6 +515,10 @@ public ResponseEntity uploadSharedFile( if (groupOpt.isEmpty()) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } + ResponseEntity refusal = mentorRefusal(groupOpt.get()); + if (refusal != null) { + return refusal; + } // String currentUsername = getCurrentUsername(); // if (currentUsername == null) { @@ -399,14 +553,14 @@ public ResponseEntity uploadSharedFile( response.put("message", ex.getMessage()); response.put("filename", ex.getPath()); return new ResponseEntity<>(response, HttpStatus.CONFLICT); - } catch (SharedFileCheckFailedException ex) { - // S3 couldn't say whether the path is taken, so nothing was written. That's S3 being - // unavailable for a moment, not a bug here: a 503, and when to try again. + } catch (SharedFileStorageUnavailableException ex) { + // S3 was unavailable for a moment, checking the path or writing the file, so the file + // isn't shared. That's not a bug here: a 503, and when to try again. Map response = new HashMap<>(); response.put("message", ex.getMessage()); response.put("filename", ex.getPath()); return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE) - .header(HttpHeaders.RETRY_AFTER, String.valueOf(SHARE_RETRY_AFTER_SECONDS)) + .header(HttpHeaders.RETRY_AFTER, String.valueOf(RETRY_AFTER_SECONDS)) .body(response); } catch (RuntimeException ex) { return new ResponseEntity<>("Upload failed", HttpStatus.INTERNAL_SERVER_ERROR); diff --git a/src/main/java/com/open/spring/mvc/groups/GroupChatEvent.java b/src/main/java/com/open/spring/mvc/groups/GroupChatEvent.java index acedc9fd6..00f671a34 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatEvent.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatEvent.java @@ -2,6 +2,9 @@ import java.util.List; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.open.spring.mvc.reactions.MessageReactionService; + import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -29,4 +32,10 @@ public class GroupChatEvent { private String error; private List participants; private boolean edited; + /** + * On a reactionsServer frame, the message's reactions after the change. Left out of every + * other frame, so those stay exactly as they were. + */ + @JsonInclude(JsonInclude.Include.NON_NULL) + private List reactions; } diff --git a/src/main/java/com/open/spring/mvc/groups/GroupChatRealtimeService.java b/src/main/java/com/open/spring/mvc/groups/GroupChatRealtimeService.java index 532b8d698..11c24a523 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatRealtimeService.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatRealtimeService.java @@ -1,14 +1,21 @@ package com.open.spring.mvc.groups; import java.time.Instant; +import java.util.List; import java.util.Optional; +import org.springframework.dao.DataAccessException; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.stereotype.Service; import com.open.spring.mvc.groups.GroupChatIdentityService.AuthenticatedIdentity; +import com.open.spring.mvc.person.Person; +import com.open.spring.mvc.reactions.ChatType; +import com.open.spring.mvc.reactions.MessageReactionService; +import com.open.spring.mvc.reactions.Reaction; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; /** * Service to handle the real-time publishing of group chat messages and presence events. @@ -16,6 +23,7 @@ */ @Service @RequiredArgsConstructor +@Slf4j public class GroupChatRealtimeService { public static final String GROUP_TOPIC_PREFIX = "/topic/group/"; @@ -23,8 +31,10 @@ public class GroupChatRealtimeService { private final GroupChatService groupChatService; private final GroupsJpaRepository groupsRepository; private final SimpMessagingTemplate messagingTemplate; + private final MessageReactionService reactionService; - public GroupChatEvent publishMessage(Long groupId, String message, String image, AuthenticatedIdentity identity) { + /** Saves the message, tells the group, and returns the group's messages as saved. */ + public List publishMessage(Long groupId, String message, String image, AuthenticatedIdentity identity) { Groups group = getGroupOrThrow(groupId); if ((message == null || message.isBlank()) && (image == null || image.isBlank())) { @@ -34,7 +44,7 @@ public GroupChatEvent publishMessage(Long groupId, String message, String image, String date = Instant.now().toString(); GroupChatMessage persisted = new GroupChatMessage(identity.getDisplayName(), identity.getUid(), message, date, image); - groupChatService.addMessage(group.getName(), persisted); + List saved = groupChatService.addMessage(group.getName(), persisted); GroupChatEvent event = GroupChatEvent.builder() .context("sendMessageServer") @@ -47,18 +57,19 @@ public GroupChatEvent publishMessage(Long groupId, String message, String image, .build(); broadcastToGroup(groupId, event); - return event; + return saved; } /** - * Returns whether the message existed (and was broadcast as edited). Throws - * {@link SecurityException} if the authenticated requester's uid is not the author uid. + * Edits the message, tells the group, and returns the group's messages as saved, or nothing + * when the message isn't in this group. Throws {@link SecurityException} if the + * authenticated requester's uid is not the author uid. */ - public boolean editMessage(Long groupId, String messageId, String newMessage, String requesterUid) { + public Optional> editMessage(Long groupId, String messageId, String newMessage, String requesterUid) { Groups group = getGroupOrThrow(groupId); - boolean updated = groupChatService.editMessage(group.getName(), messageId, newMessage, requesterUid); - if (!updated) { - return false; + Optional> saved = groupChatService.editMessage(group.getName(), messageId, newMessage, requesterUid); + if (saved.isEmpty()) { + return saved; } GroupChatEvent event = GroupChatEvent.builder() @@ -71,13 +82,28 @@ public boolean editMessage(Long groupId, String messageId, String newMessage, St .build(); broadcastToGroup(groupId, event); - return true; + return saved; } - /** Throws {@link SecurityException} if the authenticated requester didn't send it. */ - public void deleteMessage(Long groupId, String messageId, String requesterUid) { + /** + * Deletes the message and its reactions and tells the group, or returns false and tells no + * one when the message isn't in this group. Throws {@link SecurityException} if the + * authenticated requester didn't send it. + */ + public boolean deleteMessage(Long groupId, String messageId, String requesterUid) { Groups group = getGroupOrThrow(groupId); - groupChatService.deleteMessage(group.getName(), messageId, requesterUid); + if (!groupChatService.deleteMessage(group.getName(), messageId, requesterUid)) { + // Telling the group about a message that isn't saved would take it off everyone's screen. + return false; + } + try { + reactionService.removeAllFor(ChatType.GROUP, groupId, messageId); + } catch (DataAccessException e) { + // The message is already gone from S3, so the group still has to hear about it, and a + // retry would find nothing to delete. Its reactions stay in the table, where no message + // shows them. + log.warn("Could not remove the reactions of deleted message {} in group {}", messageId, groupId, e); + } GroupChatEvent event = GroupChatEvent.builder() .context("deleteMessageServer") @@ -87,6 +113,35 @@ public void deleteMessage(Long groupId, String messageId, String requesterUid) { .build(); broadcastToGroup(groupId, event); + return true; + } + + /** + * Adds ({@code on}) or removes {@code person}'s reaction to a message, then tells the + * group's topic with a reactionsServer frame. Reactions are kept in the database, never in + * the group's S3 message file, so a reaction can't change or drop a message. + */ + public List setReaction( + Long groupId, Person person, String messageId, Reaction reaction, boolean on) { + getGroupOrThrow(groupId); + if (on) { + reactionService.add(ChatType.GROUP, groupId, messageId, person, reaction); + } else { + reactionService.remove(ChatType.GROUP, groupId, messageId, person, reaction); + } + List reactions = + reactionService.forMessage(ChatType.GROUP, groupId, messageId); + + GroupChatEvent event = GroupChatEvent.builder() + .context("reactionsServer") + .groupId(groupId) + .messageId(messageId) + .reactions(reactions) + .date(Instant.now().toString()) + .build(); + + broadcastToGroup(groupId, event); + return reactions; } /** @@ -101,10 +156,7 @@ public GroupChatEvent publishFile(Long groupId, String sender, String filename, throw new IllegalArgumentException("Invalid file path"); } - String uploadResult = groupChatService.uploadSharedFile(group.getName(), path, base64Data, sender); - if (uploadResult == null) { - throw new IllegalStateException("Upload failed"); - } + groupChatService.uploadSharedFile(group.getName(), path, base64Data, sender); GroupChatEvent event = GroupChatEvent.builder() .context("sendFileServer") diff --git a/src/main/java/com/open/spring/mvc/groups/GroupChatService.java b/src/main/java/com/open/spring/mvc/groups/GroupChatService.java index 790db7d3a..1e6bd6356 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatService.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatService.java @@ -9,6 +9,8 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; +import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; @@ -21,6 +23,7 @@ import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import software.amazon.awssdk.awscore.exception.AwsErrorDetails; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.services.s3.model.S3Exception; @@ -31,10 +34,18 @@ public class GroupChatService { private static final String MESSAGES_FILE = "messages-images/messages.jsonl"; private static final String SHARED_FILES_PREFIX = "shared-files/"; private static final String SHARED_FILES_META = "shared-files-meta.json"; + // S3's error code when a connection was too slow: a 400, but the AWS SDK retries it like a 5xx. + private static final String S3_REQUEST_TIMEOUT = "RequestTimeout"; private final S3FileHandler s3FileHandler; private final ObjectMapper objectMapper; + // One lock per group for its messages file. Sending, editing and deleting each read the + // whole file, change it and write it back, so two at once would both change the same old + // copy and the later write would drop the other's change. This keeps them apart within + // this server only; several servers would need S3's conditional writes instead. + private final Map messageLocks = new ConcurrentHashMap<>(); + // One lock per group for the "shared by" sidecar, which is read, changed and written // back on every upload: a folder shared from the page uploads several files at once, // and without this the last write would drop the others' attribution. @@ -59,14 +70,29 @@ public void initGroupStorage(String groupName) { s3FileHandler.uploadFile(emptyBase64, SHARED_FILES_PREFIX, groupName); } + /** + * Creates the group's empty messages file and shared-files/ folder if they're missing. + * Strict for the messages file: only S3's 404 means missing, and a check that failed + * throws without writing, since an empty file written over the real one would erase the + * group's history. + */ public void ensureGroupStorageExists(String groupName) { - // Check if messages.jsonl exists, if not, create it - if (!s3FileHandler.fileExists(groupName, MESSAGES_FILE)) { - String emptyBase64 = Base64.getEncoder().encodeToString(new byte[0]); - s3FileHandler.uploadFile(emptyBase64, MESSAGES_FILE, groupName); + // Without S3 settings nothing is stored, so there's nothing to check. + if (!s3FileHandler.isConfigured()) { + return; + } + + // Check if messages.jsonl exists, if not, create it. Under the group's message lock, + // so a message sent between the check and the write isn't lost under the empty file. + synchronized (messageLocks.computeIfAbsent(groupName, name -> new Object())) { + if (!s3FileHandler.fileExistsOrThrow(groupName, MESSAGES_FILE)) { + String emptyBase64 = Base64.getEncoder().encodeToString(new byte[0]); + s3FileHandler.uploadFile(emptyBase64, MESSAGES_FILE, groupName); + } } - // Check if shared-files/ folder exists, if not, create it + // Check if shared-files/ folder exists, if not, create it. Its placeholder is empty, + // so writing it again loses nothing. if (!s3FileHandler.fileExists(groupName, SHARED_FILES_PREFIX)) { String emptyBase64 = Base64.getEncoder().encodeToString(new byte[0]); s3FileHandler.uploadFile(emptyBase64, SHARED_FILES_PREFIX, groupName); @@ -74,7 +100,90 @@ public void ensureGroupStorageExists(String groupName) { } public List getMessages(String groupName) { - String base64Data = s3FileHandler.decodeFile(groupName, MESSAGES_FILE); + return parseMessages(groupName, s3FileHandler.decodeFile(groupName, MESSAGES_FILE)); + } + + /** + * One line of a group's messages file: a message, or a line that didn't read as one, kept + * as it was so that saving the file again doesn't drop it. + */ + private record MessagesLine(GroupChatMessage message, String unreadable) { + static MessagesLine of(GroupChatMessage message) { + return new MessagesLine(message, null); + } + } + + /** + * The group's messages file, line by line, for a send, an edit or a delete, which write the + * whole file back. Strict: a read that failed throws rather than reading as an empty chat, + * which a send would save over the history and an edit or delete would answer as "not + * found". Only S3's 404 means no messages yet. S3 being unavailable for a moment (see + * isUnavailable) throws MessagesStorageUnavailableException; anything else goes up as it is. + */ + private List readMessagesOrThrow(String groupName) { + String base64Data; + try { + base64Data = s3FileHandler.decodeFileOrThrow(groupName, MESSAGES_FILE); + } catch (RuntimeException e) { + // Logged for every failure: the route answers a refused read or a bug without logging it. + log.warn("Could not read the messages of group {}", groupName, e); + if (!isUnavailable(e)) { + // S3 refused the request (no permission, a bad key) or a bug here: waiting won't fix that. + throw e; + } + throw new MessagesStorageUnavailableException(e); + } + return parseLines(groupName, base64Data); + } + + /** + * Saves the group's whole messages file: each message as JSON, and each line that didn't + * read as a message as it was. Strict: a write that failed throws, so a send, an edit or a + * delete isn't answered as saved when it wasn't. S3 being unavailable for a moment (see + * isUnavailable) throws MessagesStorageUnavailableException; anything else goes up as it is. + * Without S3 settings nothing is stored, and the chat still works live. + */ + private void writeMessagesOrThrow(String groupName, List lines) { + if (!s3FileHandler.isConfigured()) { + return; + } + String jsonl = lines.stream() + .map(line -> line.message() != null ? toJson(line.message()) : line.unreadable()) + .collect(Collectors.joining("\n")); + String base64Data = Base64.getEncoder().encodeToString(jsonl.getBytes(StandardCharsets.UTF_8)); + try { + s3FileHandler.uploadFileOrThrow(base64Data, MESSAGES_FILE, groupName); + } catch (RuntimeException e) { + // A write that timed out may still be stored (S3 lost its answer), so a send tried + // again can show up twice. That's easier to see and fix than a message lost quietly. + log.warn("Could not save the messages of group {}", groupName, e); + if (!isUnavailable(e)) { + // S3 refused the request (no permission, a bad key) or a bug here: waiting won't fix that. + throw e; + } + throw new MessagesStorageUnavailableException(e); + } + } + + private List parseMessages(String groupName, String base64Data) { + return messagesOf(parseLines(groupName, base64Data)); + } + + private static List messagesOf(List lines) { + return lines.stream() + .map(MessagesLine::message) + .filter(Objects::nonNull) + .collect(Collectors.toCollection(ArrayList::new)); + } + + private static GroupChatMessage find(List lines, String messageId) { + return messagesOf(lines).stream() + .filter(m -> messageId.equals(m.getId())) + .findFirst() + .orElse(null); + } + + private List parseLines(String groupName, String base64Data) { if (base64Data == null || base64Data.isBlank()) { return new ArrayList<>(); } @@ -92,99 +201,76 @@ public List getMessages(String groupName) { return new ArrayList<>(); } - List messages = new ArrayList<>(); + List lines = new ArrayList<>(); try (BufferedReader reader = new BufferedReader(new StringReader(jsonl))) { String line; while ((line = reader.readLine()) != null) { if (line.isBlank()) continue; try { - GroupChatMessage msg = objectMapper.readValue(line, GroupChatMessage.class); - messages.add(msg); + lines.add(MessagesLine.of(objectMapper.readValue(line, GroupChatMessage.class))); } catch (Exception e) { - log.warn("Skipping invalid message line for group {}: {}", groupName, line, e); + // Left out of the chat, but kept in the file: a save writes it back as it is. + log.warn("Keeping an unreadable message line of group {} as it is: {}", groupName, line, e); + lines.add(new MessagesLine(null, line)); } } } catch (Exception e) { log.warn("Failed reading messages for group {}", groupName, e); } - return messages; + return lines; } public List addMessage(String groupName, GroupChatMessage message) { - List messages = getMessages(groupName); - messages.add(message); - - String jsonl = messages.stream() - .map(this::toJson) - .collect(Collectors.joining("\n")); - - String base64Data = Base64.getEncoder() - .encodeToString(jsonl.getBytes(StandardCharsets.UTF_8)); - - s3FileHandler.uploadFile(base64Data, MESSAGES_FILE, groupName); - return messages; + synchronized (messageLocks.computeIfAbsent(groupName, name -> new Object())) { + List lines = readMessagesOrThrow(groupName); + lines.add(MessagesLine.of(message)); + writeMessagesOrThrow(groupName, lines); + return messagesOf(lines); + } } /** - * Returns whether a message with that id was found (and updated) in this group. - * Throws {@link SecurityException} unless the authenticated requester's uid matches - * the stored author uid. Legacy messages without an author uid cannot be edited. + * Edits a message and returns the group's messages as saved, or nothing when no message + * with that id is in this group. Throws {@link SecurityException} unless the authenticated + * requester's uid matches the stored author uid. Legacy messages without an author uid + * cannot be edited. */ - public boolean editMessage(String groupName, String messageId, String newMessage, String requesterUid) { - if (messageId == null) return false; - List messages = getMessages(groupName); - boolean found = false; - for (GroupChatMessage m : messages) { - if (messageId.equals(m.getId())) { - if (requesterUid == null || !requesterUid.equals(m.getAuthor_uid())) { - throw new SecurityException("Not the message sender"); - } - m.setMessage(newMessage); - m.setEdited(true); - found = true; - break; + public Optional> editMessage(String groupName, String messageId, String newMessage, String requesterUid) { + if (messageId == null) return Optional.empty(); + synchronized (messageLocks.computeIfAbsent(groupName, name -> new Object())) { + List lines = readMessagesOrThrow(groupName); + GroupChatMessage target = find(lines, messageId); + if (target == null) { + return Optional.empty(); } + if (requesterUid == null || !requesterUid.equals(target.getAuthor_uid())) { + throw new SecurityException("Not the message sender"); + } + target.setMessage(newMessage); + target.setEdited(true); + writeMessagesOrThrow(groupName, lines); + return Optional.of(messagesOf(lines)); } - - if (found) { - String jsonl = messages.stream() - .map(this::toJson) - .collect(Collectors.joining("\n")); - - String base64Data = Base64.getEncoder() - .encodeToString(jsonl.getBytes(StandardCharsets.UTF_8)); - - s3FileHandler.uploadFile(base64Data, MESSAGES_FILE, groupName); - } - return found; } - /** Same ownership rule as {@link #editMessage}; throws {@link SecurityException} on mismatch. */ - public void deleteMessage(String groupName, String messageId, String requesterUid) { - if (messageId == null) return; - List messages = getMessages(groupName); - - GroupChatMessage target = messages.stream() - .filter(m -> messageId.equals(m.getId())) - .findFirst() - .orElse(null); - if (target == null) return; - if (requesterUid == null || !requesterUid.equals(target.getAuthor_uid())) { - throw new SecurityException("Not the message sender"); - } - - boolean removed = messages.remove(target); - - if (removed) { - String jsonl = messages.stream() - .map(this::toJson) - .collect(Collectors.joining("\n")); - - String base64Data = Base64.getEncoder() - .encodeToString(jsonl.getBytes(StandardCharsets.UTF_8)); + /** + * Deletes a message and returns whether one with that id was in this group. Same ownership + * rule as {@link #editMessage}; throws {@link SecurityException} on mismatch. + */ + public boolean deleteMessage(String groupName, String messageId, String requesterUid) { + if (messageId == null) return false; + synchronized (messageLocks.computeIfAbsent(groupName, name -> new Object())) { + List lines = readMessagesOrThrow(groupName); + GroupChatMessage target = find(lines, messageId); + if (target == null) return false; + if (requesterUid == null || !requesterUid.equals(target.getAuthor_uid())) { + throw new SecurityException("Not the message sender"); + } - s3FileHandler.uploadFile(base64Data, MESSAGES_FILE, groupName); + lines.removeIf(line -> line.message() == target); + writeMessagesOrThrow(groupName, lines); + return true; } } @@ -253,7 +339,8 @@ public byte[] readSharedFile(String groupName, String path) { /** * Stores a shared file, never over one already there: that throws SharedFileExistsException. - * When S3 can't say for now whether the path is taken, it throws SharedFileCheckFailedException. + * When S3 is unavailable for a moment, checking the path or writing the file, it throws + * SharedFileStorageUnavailableException. */ public String uploadSharedFile(String groupName, String filename, String base64Data, String uploadedBy) { List key = List.of(groupName, filename); @@ -264,10 +351,7 @@ public String uploadSharedFile(String groupName, String filename, String base64D if (isAlreadyShared(groupName, filename)) { throw new SharedFileExistsException(filename); } - String result = s3FileHandler.uploadFile(base64Data, SHARED_FILES_PREFIX + filename, groupName); - if (result == null) { - return null; - } + String result = store(groupName, filename, base64Data); recordFileMeta(groupName, filename, uploadedBy); return result; } finally { @@ -277,20 +361,55 @@ public String uploadSharedFile(String groupName, String filename, String base64D /** * Whether a file is stored at this path. Strict: a check that failed throws, rather than - * reading as a free path. S3 out of reach or answering a 5xx is something to wait out, so - * that throws SharedFileCheckFailedException; anything else goes up as it is. + * reading as a free path. S3 being unavailable throws SharedFileStorageUnavailableException; + * anything else goes up as it is. */ private boolean isAlreadyShared(String groupName, String path) { try { return s3FileHandler.fileExistsOrThrow(groupName, SHARED_FILES_PREFIX + path); } catch (SdkClientException | S3Exception e) { - if (e instanceof S3Exception answered && answered.statusCode() < 500) { - // S3 refused the request (no permission, a bad key): waiting won't fix that. + if (!isUnavailable(e)) { throw e; } log.warn("Could not check whether {} is shared in group {}", path, groupName, e); - throw new SharedFileCheckFailedException(path, e); + throw new SharedFileStorageUnavailableException(path, e); + } + } + + /** + * Writes a shared file's bytes. S3 being unavailable throws + * SharedFileStorageUnavailableException; any other failure fails the upload as it always has. + */ + private String store(String groupName, String path, String base64Data) { + try { + return s3FileHandler.uploadFileOrThrow(base64Data, SHARED_FILES_PREFIX + path, groupName); + } catch (RuntimeException e) { + // A write that timed out may still be stored (S3 lost its answer). Sharing it again + // then gets a 409, which the page handles like any other taken name. + log.warn("Could not store {} in group {}", path, groupName, e); + if (isUnavailable(e)) { + throw new SharedFileStorageUnavailableException(path, e); + } + throw new IllegalStateException("Upload failed", e); + } + } + + /** + * S3 out of reach (a timeout, no connection), answering a 5xx (a throttle, an outage) or + * timing out the request itself (RequestTimeout, which comes as a 400): something to wait + * out. Any other 4xx is S3 refusing the request (no permission, a bad key), which waiting + * won't fix, and anything else is a fault here. + */ + private static boolean isUnavailable(RuntimeException e) { + if (e instanceof SdkClientException) { + return true; + } + if (e instanceof S3Exception answered) { + AwsErrorDetails details = answered.awsErrorDetails(); + return answered.statusCode() >= 500 + || (details != null && S3_REQUEST_TIMEOUT.equals(details.errorCode())); } + return false; } // --------------------------------------------------------------------------- @@ -397,8 +516,9 @@ private String toJson(GroupChatMessage message) { try { return objectMapper.writeValueAsString(message); } catch (Exception e) { - log.warn("Failed to serialize message: {}", message, e); - return "{}"; + // Writing "{}" instead would replace the message in the file with nothing. + log.warn("Could not write message {} of a group chat", message.getId(), e); + throw new IllegalStateException("Could not write message " + message.getId(), e); } } } diff --git a/src/main/java/com/open/spring/mvc/groups/GroupChatWebSocketController.java b/src/main/java/com/open/spring/mvc/groups/GroupChatWebSocketController.java index 30cee03f7..bce646616 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatWebSocketController.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatWebSocketController.java @@ -1,12 +1,17 @@ package com.open.spring.mvc.groups; import java.security.Principal; +import java.util.List; import org.springframework.messaging.handler.annotation.Header; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.handler.annotation.Payload; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; import org.springframework.stereotype.Controller; +import com.open.spring.mvc.person.PersonJpaRepository; + import lombok.RequiredArgsConstructor; /** @@ -23,6 +28,8 @@ public class GroupChatWebSocketController { private final GroupChatIdentityService identityService; private final GroupChatRealtimeService realtimeService; private final GroupChatPresenceService presenceService; + private final MentorAccess mentorAccess; + private final PersonJpaRepository personRepository; @MessageMapping("/groups.chat") public void handleGroupEvent(@Payload GroupChatEvent event, @@ -41,6 +48,12 @@ public void handleGroupEvent(@Payload GroupChatEvent event, String sender = resolveSender(event, principal); // deprecated, remove later String uid = principal.getName(); + // The mentor rules hold on the socket as over REST: a mentor sends, joins and types only in a group they may + // use. Leaving always works. + if (groupId != null && !"leaveGroup".equals(event.getContext()) && mentorRefuses(principal, groupId)) { + return; + } + switch (event.getContext()) { case "joinGroup" -> { if (groupId == null) { @@ -107,6 +120,22 @@ public void handleGroupEvent(@Payload GroupChatEvent event, } } + /** + * True when the mentor rules refuse this account the group. Only a mentor can be refused (see MentorRules). A + * socket from Spring's own pages carries the roles of its sign-in, so an event from anyone that sign-in doesn't + * call a mentor is answered without loading them; a role given since counts from the next sign-in. + */ + private boolean mentorRefuses(Principal principal, Long groupId) { + if (principal instanceof Authentication signIn && !MentorRules.isMentorRoles(roleNames(signIn))) { + return false; + } + return mentorAccess.refusesGroup(personRepository.findByUid(principal.getName()), groupId); + } + + private static List roleNames(Authentication signIn) { + return signIn.getAuthorities().stream().map(GrantedAuthority::getAuthority).toList(); + } + private void ensureJoined(String sessionId, Long groupId, String sender) { if (!presenceService.isSessionInGroup(sessionId, groupId)) { presenceService.joinGroup(sessionId, groupId, sender); diff --git a/src/main/java/com/open/spring/mvc/groups/GroupsApiController.java b/src/main/java/com/open/spring/mvc/groups/GroupsApiController.java index 1454ca33f..d36eee3ff 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupsApiController.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupsApiController.java @@ -9,7 +9,9 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.security.core.Authentication; import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.DeleteMapping; @@ -21,8 +23,13 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; +import com.open.spring.mvc.assignments.Assignment; +import com.open.spring.mvc.assignments.AssignmentAuthorizationService; +import com.open.spring.mvc.assignments.AssignmentJpaRepository; +import com.open.spring.mvc.assignments.AssignmentSubmissionJPA; import com.open.spring.mvc.person.Person; import com.open.spring.mvc.person.PersonJpaRepository; +import com.open.spring.mvc.person.RolesJsonConverter; import lombok.AllArgsConstructor; import lombok.Data; @@ -44,6 +51,20 @@ public class GroupsApiController { @Autowired private ClassGroupMembershipService classGroupMembershipService; + @Autowired + private MentorAccess mentorAccess; + + @Autowired + private AssignmentJpaRepository assignmentRepository; + + @Autowired + private AssignmentSubmissionJPA submissionRepository; + + @Autowired + private AssignmentAuthorizationService assignmentAuthorizationService; + + private static final RolesJsonConverter ROLES = new RolesJsonConverter(); + // ===== DTOs ===== @Data @NoArgsConstructor @@ -79,6 +100,163 @@ public static class ClassMembershipSyncDto { } // ===== Helper Methods ===== + + /** The signed-in Person, or null when nobody is signed in. */ + private Person currentPerson() { + Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + if (auth == null || !auth.isAuthenticated() || "anonymousUser".equals(auth.getName())) { + return null; + } + return personRepository.findByUid(auth.getName()); + } + + /** + * Refuses a mentor the routes that look through or change groups (see MentorRules.manageGroups), or null when + * the signed-in account may go on. + */ + private ResponseEntity mentorManageRefusal() { + return MentorRules.manageGroups(currentPerson()).map(MentorRules.Refusal::toResponse).orElse(null); + } + + /** + * Who manages a group's members. A group has no owner, so its members do, as the Messages + * page's Members dialog lets them, and so do teachers and admins. A class group's members come + * from the classes on each student's Profile, so on these routes only teachers and admins + * change one. + */ + private boolean managesGroup(Person caller, Groups group) { + if (caller == null) { + return false; + } + if (isStaff(caller)) { + return true; + } + if (classGroupMembershipService.isClassGroup(group.getName())) { + return false; + } + return groupsRepository.findMembersOf(group.getId()).stream() + .anyMatch(member -> java.util.Objects.equals(member.getId(), caller.getId())); + } + + /** Joining and leaving: anyone adds or removes themselves, except in a class group. */ + private boolean joinsOrLeaves(Person caller, Groups group, Person person) { + return caller != null && person != null && java.util.Objects.equals(caller.getId(), person.getId()) + && !classGroupMembershipService.isClassGroup(group.getName()); + } + + /** True for a teacher or an admin. */ + private static boolean isStaff(Person caller) { + return caller != null && (caller.hasRole("ROLE_TEACHER") || caller.hasRole("ROLE_ADMIN")); + } + + private static ResponseEntity notStaff() { + return new ResponseEntity<>( + Map.of("error", "Only a teacher or an admin can change a group's name, period or course"), + HttpStatus.FORBIDDEN + ); + } + + private static ResponseEntity notYourGroup() { + return new ResponseEntity<>( + Map.of("error", "Only the group's members, a teacher or an admin can change this group"), + HttpStatus.FORBIDDEN + ); + } + + /** Group chat keeps a group's files in S3 under its name, so a name can't add a folder. */ + private static boolean hasSlash(String groupName) { + return groupName != null && groupName.contains("/"); + } + + private static ResponseEntity slashInName() { + return new ResponseEntity<>(Map.of("error", "A group name can't contain \"/\""), HttpStatus.BAD_REQUEST); + } + + /** + * Who grades a group on an assignment: teachers and admins, the assignment's creators and graders + * (AssignmentAuthorizationService.canManage), and the graders of the group's own submission to it. + */ + private boolean gradesGroupOn(Person caller, Groups group, Object assignmentIdValue) { + if (isStaff(caller)) { + return true; + } + Long assignmentId = idOf(assignmentIdValue); + if (caller == null || assignmentId == null) { + return false; + } + Optional assignment = assignmentRepository.findById(assignmentId); + if (assignment.isPresent() && assignmentAuthorizationService.canManage(caller, assignment.get())) { + return true; + } + return submissionRepository.findBySubmitterId(group.getId()).stream() + .filter(submission -> submission.getAssignment() != null + && assignmentId.equals(submission.getAssignment().getId())) + .anyMatch(submission -> assignmentAuthorizationService.canManageSubmission(caller, submission)); + } + + /** + * Who sees a group's grades: its members, teachers and admins, and whoever grades one of its + * submissions (AssignmentAuthorizationService.canManageSubmission). + */ + private boolean seesGroupGrades(Person caller, Groups group) { + if (caller == null) { + return false; + } + if (isStaff(caller)) { + return true; + } + boolean member = groupsRepository.findMembersOf(group.getId()).stream() + .anyMatch(person -> java.util.Objects.equals(person.getId(), caller.getId())); + return member || submissionRepository.findBySubmitterId(group.getId()).stream() + .anyMatch(submission -> assignmentAuthorizationService.canManageSubmission(caller, submission)); + } + + private static ResponseEntity notAllowedToSeeGrades() { + return new ResponseEntity<>( + Map.of("error", "Only the group's members, its graders, a teacher or an admin can see its grades"), + HttpStatus.FORBIDDEN + ); + } + + /** A grade entry's assignmentId as the upsert keys it (its text), or null when that isn't a whole number. */ + private static Long idOf(Object value) { + if (value == null) { + return null; + } + try { + return Long.valueOf(value.toString().trim()); + } catch (NumberFormatException e) { + return null; + } + } + + private static ResponseEntity notGroupGrader() { + return new ResponseEntity<>( + Map.of("error", "Only a teacher, an admin or someone who grades this group on that assignment can add its grade"), + HttpStatus.FORBIDDEN + ); + } + + private static ResponseEntity notStaffForGrades() { + return new ResponseEntity<>( + Map.of("error", "Only a teacher or an admin can replace or clear a group's grades"), + HttpStatus.FORBIDDEN + ); + } + + /** The people with these ids, in order, once each, leaving out ids that match no one. */ + private List findPeople(List personIds) { + List found = new ArrayList<>(); + if (personIds != null) { + for (Long personId : new java.util.LinkedHashSet<>(personIds)) { + if (personId != null) { + personRepository.findById(personId).ifPresent(found::add); + } + } + } + return found; + } + private Map buildGroupResponse(Groups group) { Map groupMap = new LinkedHashMap<>(); groupMap.put("id", group.getId()); @@ -87,7 +265,7 @@ private Map buildGroupResponse(Groups group) { groupMap.put("course", group.getCourse()); List> membersList = new ArrayList<>(); - List memberRows = groupsRepository.findGroupMembersRaw(group.getId()); + List memberRows = groupsRepository.findGroupMembersWithRolesRaw(group.getId()); for (Object[] row : memberRows) { Map member = new LinkedHashMap<>(); @@ -95,6 +273,8 @@ private Map buildGroupResponse(Groups group) { member.put("uid", (String) row[1]); member.put("name", (String) row[2]); member.put("email", (String) row[3]); + // So a page can show a team's mentors without asking about each member + member.put("mentor", MentorRules.isMentorRoles(ROLES.convertToEntityAttribute((String) row[4]))); membersList.add(member); } @@ -109,7 +289,11 @@ private Map buildGroupResponse(Groups group) { */ @GetMapping @Transactional(readOnly = true) - public ResponseEntity>> getAllGroups() { + public ResponseEntity getAllGroups() { + ResponseEntity refusal = mentorManageRefusal(); + if (refusal != null) { + return refusal; + } try { List groups = groupsRepository.findAll(); List> result = new ArrayList<>(); @@ -129,12 +313,16 @@ public ResponseEntity>> getAllGroups() { */ @GetMapping("/{id}") @Transactional(readOnly = true) - public ResponseEntity> getGroupById(@PathVariable Long id) { + public ResponseEntity getGroupById(@PathVariable Long id) { try { Optional groupOpt = groupsRepository.findById(id); if (groupOpt.isEmpty()) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } + Optional refusal = mentorAccess.toUse(currentPerson(), groupOpt.get()); + if (refusal.isPresent()) { + return refusal.get().toResponse(); + } return new ResponseEntity<>(buildGroupResponse(groupOpt.get()), HttpStatus.OK); } catch (Exception e) { return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); @@ -146,7 +334,15 @@ public ResponseEntity> getGroupById(@PathVariable Long id) { */ @GetMapping("/person/{personId}") @Transactional(readOnly = true) - public ResponseEntity>> getGroupsByPersonId(@PathVariable Long personId) { + public ResponseEntity getGroupsByPersonId(@PathVariable Long personId) { + Person viewer = currentPerson(); + if (viewer != null && !personId.equals(viewer.getId())) { + // A mentor sees only their own groups + ResponseEntity refusal = mentorManageRefusal(); + if (refusal != null) { + return refusal; + } + } try { Optional personOpt = personRepository.findById(personId); if (personOpt.isEmpty()) { @@ -154,6 +350,11 @@ public ResponseEntity>> getGroupsByPersonId(@PathVariab } List groups = groupsRepository.findGroupsByPersonId(personId); + // A mentor's own list holds only the groups they may use (MentorRules), so no page offers a group Spring + // would refuse them, and they never see the members of one. + if (MentorRules.isMentor(viewer)) { + groups = groups.stream().filter(group -> mentorAccess.toUse(viewer, group).isEmpty()).toList(); + } List> result = new ArrayList<>(); for (Groups group : groups) { @@ -172,8 +373,12 @@ public ResponseEntity>> getGroupsByPersonId(@PathVariab */ @GetMapping("/search") @Transactional(readOnly = true) - public ResponseEntity>> searchGroupsByName( + public ResponseEntity searchGroupsByName( @org.springframework.web.bind.annotation.RequestParam(value = "name", required = true) String searchTerm) { + ResponseEntity refusal = mentorManageRefusal(); + if (refusal != null) { + return refusal; + } try { if (searchTerm == null || searchTerm.trim().isEmpty()) { return new ResponseEntity<>( @@ -203,7 +408,14 @@ public ResponseEntity>> searchGroupsByName( */ @PostMapping @Transactional - public ResponseEntity> createGroup(@RequestBody GroupCreateDto dto) { + public ResponseEntity createGroup(@RequestBody GroupCreateDto dto) { + ResponseEntity mentorRefusal = mentorManageRefusal(); + if (mentorRefusal != null) { + return mentorRefusal; + } + if (hasSlash(dto.getName())) { + return slashInName(); + } try { if (dto.getName() == null || dto.getName().isEmpty()) { return new ResponseEntity<>( @@ -219,6 +431,13 @@ public ResponseEntity> createGroup(@RequestBody GroupCreateD ); } + // A group can start with a mentor only when its maker could have added them (MentorRules.startGroup) + List initialMembers = findPeople(dto.getMemberIds()); + Optional refusal = mentorAccess.toStart(currentPerson(), dto.getName(), initialMembers); + if (refusal.isPresent()) { + return refusal.get().toResponse(); + } + Groups group = new Groups(); group.setName(dto.getName()); group.setPeriod(dto.getPeriod()); @@ -228,11 +447,8 @@ public ResponseEntity> createGroup(@RequestBody GroupCreateD // Add members if provided if (dto.getMemberIds() != null) { - for (Long personId : dto.getMemberIds()) { - Optional personOpt = personRepository.findById(personId); - if (personOpt.isPresent()) { - savedGroup.addPerson(personOpt.get()); - } + for (Person person : initialMembers) { + savedGroup.addPerson(person); } savedGroup = groupsRepository.save(savedGroup); } @@ -256,7 +472,12 @@ public ResponseEntity> createGroup(@RequestBody GroupCreateD */ @PostMapping("/bulk") @Transactional - public ResponseEntity> bulkCreateGroups(@RequestBody BulkGroupCreateDto dto) { + public ResponseEntity bulkCreateGroups(@RequestBody BulkGroupCreateDto dto) { + ResponseEntity mentorRefusal = mentorManageRefusal(); + if (mentorRefusal != null) { + return mentorRefusal; + } + Person actor = currentPerson(); try { List> created = new ArrayList<>(); List errors = new ArrayList<>(); @@ -270,11 +491,23 @@ public ResponseEntity> bulkCreateGroups(@RequestBody BulkGro for (GroupCreateDto groupDto : dto.getGroups()) { try { + if (hasSlash(groupDto.getName())) { + errors.add("Group name '" + groupDto.getName() + "' can't contain \"/\""); + continue; + } if (groupsRepository.findByName(groupDto.getName()).isPresent()) { errors.add("Group with name '" + groupDto.getName() + "' already exists"); continue; } + List initialMembers = findPeople(groupDto.getMemberIds()); + Optional refusal = + mentorAccess.toStart(actor, groupDto.getName(), initialMembers); + if (refusal.isPresent()) { + errors.add("Group '" + groupDto.getName() + "': " + refusal.get().message()); + continue; + } + Groups group = new Groups(); group.setName(groupDto.getName()); group.setPeriod(groupDto.getPeriod()); @@ -283,11 +516,8 @@ public ResponseEntity> bulkCreateGroups(@RequestBody BulkGro Groups savedGroup = groupsRepository.save(group); if (groupDto.getMemberIds() != null) { - for (Long personId : groupDto.getMemberIds()) { - Optional personOpt = personRepository.findById(personId); - if (personOpt.isPresent()) { - savedGroup.addPerson(personOpt.get()); - } + for (Person person : initialMembers) { + savedGroup.addPerson(person); } savedGroup = groupsRepository.save(savedGroup); } @@ -323,7 +553,7 @@ public ResponseEntity> bulkCreateGroups(@RequestBody BulkGro * groups with the classes selected on their profile. */ @PutMapping("/class-memberships") - public ResponseEntity> syncClassMemberships( + public ResponseEntity syncClassMemberships( @AuthenticationPrincipal UserDetails userDetails, @RequestBody ClassMembershipSyncDto dto) { if (userDetails == null) { @@ -333,6 +563,12 @@ public ResponseEntity> syncClassMemberships( ); } + // A mentor may leave every class group (an empty list) but join none. + boolean joins = dto != null && dto.getClasses() != null && !dto.getClasses().isEmpty(); + if (joins && MentorRules.isMentor(personRepository.findByUid(userDetails.getUsername()))) { + return MentorRules.Refusal.CLASS_GROUP.toResponse(); + } + try { List memberships = classGroupMembershipService.syncMemberships( userDetails.getUsername(), @@ -352,9 +588,13 @@ public ResponseEntity> syncClassMemberships( */ @PutMapping("/{id}") @Transactional - public ResponseEntity> updateGroup( + public ResponseEntity updateGroup( @PathVariable Long id, @RequestBody GroupUpdateDto dto) { + ResponseEntity refusal = mentorManageRefusal(); + if (refusal != null) { + return refusal; + } try { Optional groupOpt = groupsRepository.findById(id); if (groupOpt.isEmpty()) { @@ -365,6 +605,26 @@ public ResponseEntity> updateGroup( } Groups group = groupOpt.get(); + // Nothing in pages edits a group, and anyone can join a group that isn't a class group and then counts as a member + if (!isStaff(currentPerson())) { + return notStaff(); + } + if (hasSlash(dto.getName())) { + return slashInName(); + } + boolean renames = dto.getName() != null && !dto.getName().isEmpty() && !dto.getName().equals(group.getName()); + if (renames && classGroupMembershipService.isClassGroup(group.getName())) { + return new ResponseEntity<>(Map.of("error", "A class group can't be renamed"), HttpStatus.FORBIDDEN); + } + // Profile's class sync, a course's video call room and the assignment course sync find a group by name, so names stay unique + if (renames + && (groupsRepository.findByName(dto.getName()).isPresent() + || classGroupMembershipService.isClassGroup(dto.getName()))) { + return new ResponseEntity<>( + Map.of("error", "A group named '" + dto.getName() + "' already exists"), + HttpStatus.CONFLICT + ); + } if (dto.getName() != null && !dto.getName().isEmpty()) { group.setName(dto.getName()); @@ -392,7 +652,15 @@ public ResponseEntity> updateGroup( @DeleteMapping("/{id}") - public ResponseEntity> deleteGroup (@PathVariable Long id) { + public ResponseEntity deleteGroup (@PathVariable Long id) { + ResponseEntity refusal = mentorManageRefusal(); + if (refusal != null) { + return refusal; + } + Person caller = currentPerson(); + if (caller == null || !caller.hasRole("ROLE_ADMIN")) { + return new ResponseEntity<>(Map.of("error", "Only an admin can delete a group"), HttpStatus.FORBIDDEN); + } try { Optional groupOpt = groupsRepository.findById(id); if (groupOpt.isEmpty()) { @@ -401,6 +669,10 @@ public ResponseEntity> deleteGroup (@PathVariable Long id) { HttpStatus.NOT_FOUND ); } + // A class group's members come from the classes on each student's Profile; the Messages page never offers to delete one + if (classGroupMembershipService.isClassGroup(groupOpt.get().getName())) { + return new ResponseEntity<>(Map.of("error", "A class group can't be deleted"), HttpStatus.FORBIDDEN); + } groupsRepository.deleteById(id); return new ResponseEntity<>( @@ -422,7 +694,7 @@ public ResponseEntity> deleteGroup (@PathVariable Long id) { */ @DeleteMapping("/{id}/members/{personId}") @Transactional - public ResponseEntity> removePersonFromGroup( + public ResponseEntity removePersonFromGroup( @PathVariable Long id, @PathVariable Long personId) { try { @@ -445,6 +717,17 @@ public ResponseEntity> removePersonFromGroup( Groups group = groupOpt.get(); Person person = personOpt.get(); + // The team manages its mentors; a mentor may only leave + Optional refusal = mentorAccess.toRemove(currentPerson(), group, person); + if (refusal.isPresent()) { + return refusal.get().toResponse(); + } + + Person caller = currentPerson(); + if (!managesGroup(caller, group) && !joinsOrLeaves(caller, group, person)) { + return notYourGroup(); + } + if (!group.getGroupMembers().contains(person)) { return new ResponseEntity<>( Map.of("error", "Person not in group"), @@ -469,7 +752,7 @@ public ResponseEntity> removePersonFromGroup( */ @PostMapping("/{id}/members/{personId}") @Transactional - public ResponseEntity> addPersonToGroup( + public ResponseEntity addPersonToGroup( @PathVariable Long id, @PathVariable Long personId) { try { @@ -492,6 +775,17 @@ public ResponseEntity> addPersonToGroup( Groups group = groupOpt.get(); Person person = personOpt.get(); + // A team member or a teacher adds a mentor, and only to a group a mentor may use + Optional refusal = mentorAccess.toAdd(currentPerson(), group, person); + if (refusal.isPresent()) { + return refusal.get().toResponse(); + } + + Person caller = currentPerson(); + if (!managesGroup(caller, group) && !joinsOrLeaves(caller, group, person)) { + return notYourGroup(); + } + if (group.getGroupMembers().contains(person)) { return new ResponseEntity<>( Map.of("error", "Person already in group"), @@ -515,8 +809,15 @@ public ResponseEntity> addPersonToGroup( @GetMapping("/{id}/grades") @Transactional(readOnly = true) public ResponseEntity getGroupGrades(@PathVariable Long id) { + ResponseEntity mentorRefusal = mentorManageRefusal(); + if (mentorRefusal != null) { + return mentorRefusal; + } Optional groupOpt = groupsRepository.findById(id); if (groupOpt.isEmpty()) return new ResponseEntity<>(HttpStatus.NOT_FOUND); + if (!seesGroupGrades(currentPerson(), groupOpt.get())) { + return notAllowedToSeeGrades(); + } return new ResponseEntity<>(groupOpt.get().getGradesJson(), HttpStatus.OK); } @@ -529,6 +830,14 @@ public ResponseEntity getGroupGrades(@PathVariable Long id) { @Transactional public ResponseEntity putGroupGrades(@PathVariable Long id, @RequestBody List> grades) { + ResponseEntity mentorRefusal = mentorManageRefusal(); + if (mentorRefusal != null) { + return mentorRefusal; + } + // Replacing the blob changes every assignment's entry at once + if (!isStaff(currentPerson())) { + return notStaffForGrades(); + } Optional groupOpt = groupsRepository.findById(id); if (groupOpt.isEmpty()) return new ResponseEntity<>(HttpStatus.NOT_FOUND); @@ -548,10 +857,17 @@ public ResponseEntity putGroupGrades(@PathVariable Long id, @Transactional public ResponseEntity addGroupGrade(@PathVariable Long id, @RequestBody Map gradeEntry) { + ResponseEntity mentorRefusal = mentorManageRefusal(); + if (mentorRefusal != null) { + return mentorRefusal; + } Optional groupOpt = groupsRepository.findById(id); if (groupOpt.isEmpty()) return new ResponseEntity<>(HttpStatus.NOT_FOUND); Groups group = groupOpt.get(); + if (!gradesGroupOn(currentPerson(), group, gradeEntry == null ? null : gradeEntry.get("assignmentId"))) { + return notGroupGrader(); + } if (group.getGradesJson() == null) group.setGradesJson(new ArrayList<>()); // --- Build a canonical group-grade entry (so group + persons get same schema) --- @@ -613,6 +929,14 @@ public ResponseEntity addGroupGrade(@PathVariable Long id, @DeleteMapping("/{id}/grades") @Transactional public ResponseEntity clearGroupGrades(@PathVariable Long id) { + ResponseEntity mentorRefusal = mentorManageRefusal(); + if (mentorRefusal != null) { + return mentorRefusal; + } + // Clearing the blob removes every assignment's entry at once + if (!isStaff(currentPerson())) { + return notStaffForGrades(); + } Optional groupOpt = groupsRepository.findById(id); if (groupOpt.isEmpty()) return new ResponseEntity<>(HttpStatus.NOT_FOUND); diff --git a/src/main/java/com/open/spring/mvc/groups/GroupsJpaRepository.java b/src/main/java/com/open/spring/mvc/groups/GroupsJpaRepository.java index 911e4f55f..448a40d9d 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupsJpaRepository.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupsJpaRepository.java @@ -8,6 +8,8 @@ import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; +import com.open.spring.mvc.person.Person; + public interface GroupsJpaRepository extends JpaRepository { // Find a group by its ID @@ -43,6 +45,23 @@ List findCourseMembershipsByPersonIds( @Query("SELECT g FROM Groups g WHERE SIZE(g.groupMembers) = :memberCount") List findGroupsByMemberCount(@Param("memberCount") int memberCount); + /** + * A group's members, for MentorRules. One query, so it works outside a transaction + * (spring.jpa.open-in-view is false, so Groups.groupMembers can't be read lazily there). + */ + @Query("SELECT p FROM Groups g JOIN g.groupMembers p WHERE g.id = :groupId") + List findMembersOf(@Param("groupId") Long groupId); + + /** + * The rows a group response lists its members from: id, uid, name, email and roles_json, the roles saying + * whether each member is a mentor. Kept apart from findGroupMembersRaw, which other services read. + */ + @Query(value = "SELECT p.id, p.uid, p.name, p.email, p.roles_json FROM group_members gm " + + "JOIN person p ON gm.person_id = p.id " + + "WHERE gm.group_id = :groupId " + + "ORDER BY p.id", nativeQuery = true) + List findGroupMembersWithRolesRaw(@Param("groupId") Long groupId); + // Get raw member data for a group (avoids Hibernate hydration issues) @Query(value = "SELECT p.id, p.uid, p.name, p.email FROM group_members gm " + "JOIN person p ON gm.person_id = p.id " + diff --git a/src/main/java/com/open/spring/mvc/groups/MentorAccess.java b/src/main/java/com/open/spring/mvc/groups/MentorAccess.java new file mode 100644 index 000000000..f3a061ac1 --- /dev/null +++ b/src/main/java/com/open/spring/mvc/groups/MentorAccess.java @@ -0,0 +1,71 @@ +package com.open.spring.mvc.groups; + +import java.util.Collection; +import java.util.List; +import java.util.Optional; + +import org.springframework.stereotype.Service; + +import com.open.spring.mvc.person.Person; + +/** + * Loads what MentorRules needs about a group (its members, and whether it is a class group) and asks the rules. A + * request from someone who isn't a mentor, about someone who isn't a mentor, is answered without loading anything, + * since the rules leave those as they were. + */ +@Service +public class MentorAccess { + + private final GroupsJpaRepository groups; + private final ClassGroupMembershipService classGroups; + + public MentorAccess(GroupsJpaRepository groups, ClassGroupMembershipService classGroups) { + this.groups = groups; + this.classGroups = classGroups; + } + + /** Whether person may read the group, post in its chat and share its files. */ + public Optional toUse(Person person, Groups group) { + if (!MentorRules.isMentor(person)) { + return Optional.empty(); + } + return MentorRules.useGroup(person, isClassGroup(group), membersOf(group)); + } + + /** True when the rules refuse person the group with this id. Only a mentor is refused, by a group that exists. */ + public boolean refusesGroup(Person person, Long groupId) { + if (!MentorRules.isMentor(person) || groupId == null) { + return false; + } + return groups.findById(groupId).map(group -> toUse(person, group).isPresent()).orElse(false); + } + + /** Whether actor may add newMember to the group. */ + public Optional toAdd(Person actor, Groups group, Person newMember) { + if (!MentorRules.isMentor(actor) && !MentorRules.isMentor(newMember)) { + return Optional.empty(); + } + return MentorRules.addMember(actor, newMember, isClassGroup(group), membersOf(group)); + } + + /** Whether actor may take member out of the group. */ + public Optional toRemove(Person actor, Groups group, Person member) { + if (!MentorRules.isMentor(actor) && !MentorRules.isMentor(member)) { + return Optional.empty(); + } + return MentorRules.removeMember(actor, member, membersOf(group)); + } + + /** Whether actor may make a group with this name that starts with these members. */ + public Optional toStart(Person actor, String groupName, Collection members) { + return MentorRules.startGroup(actor, classGroups.isClassGroup(groupName), members); + } + + private boolean isClassGroup(Groups group) { + return classGroups.isClassGroup(group.getName()); + } + + private List membersOf(Groups group) { + return groups.findMembersOf(group.getId()); + } +} diff --git a/src/main/java/com/open/spring/mvc/groups/MentorRules.java b/src/main/java/com/open/spring/mvc/groups/MentorRules.java new file mode 100644 index 000000000..5a9f19789 --- /dev/null +++ b/src/main/java/com/open/spring/mvc/groups/MentorRules.java @@ -0,0 +1,189 @@ +package com.open.spring.mvc.groups; + +import java.util.Collection; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; + +import com.open.spring.mvc.person.Person; + +/** + * What a mentor may do in chat. A mentor is an account with ROLE_MENTOR and no teacher or admin role: Flask + * verifies mentors, and Spring gives the role at login when Flask's signed statement says so. + * + * A mentor never talks with a student privately. So no direct message that includes a mentor can be started, sent + * or edited, and a mentor uses only a group a team added them to, with at least MIN_TEAM_SIZE members who aren't + * mentors, never a class group. The team manages its mentors: only a member who isn't a mentor, or a teacher, adds or + * removes one. A mentor adds no one, and can't look through or change groups. Everyone else keeps the answers they + * had before these rules. + * + * Every method is static and decides only from what it is given, like Java's Math. The controllers load the people + * involved and ask; the rules stay in this one place. + */ +public final class MentorRules { + + /** The role Spring gives an account that Flask says is a verified mentor. */ + public static final String ROLE_MENTOR = "ROLE_MENTOR"; + + /** The fewest members who aren't mentors that a group needs before a mentor can be in it. */ + public static final int MIN_TEAM_SIZE = 2; + + /** Why a mentor rule refused a request. Each one is answered with 403 and its reason. */ + public enum Refusal { + NO_DIRECT_MESSAGES("mentor_no_direct_messages", + "Mentors can't send or receive direct messages. Talk with a team in its group."), + NOT_IN_GROUP("mentor_not_in_group", + "This chat is for the group's members and its mentors."), + TEAM_TOO_SMALL("mentor_team_too_small", + "A mentor can only be in a group with at least " + MIN_TEAM_SIZE + " members who aren't mentors."), + CLASS_GROUP("mentor_class_group", + "Mentors can't be in class groups."), + CANNOT_MANAGE("mentor_cannot_manage", + "Mentors can't add people to groups, or make, change or look through groups."), + TEAM_MANAGES_MENTORS("team_manages_mentors", + "Only the group's members or a teacher can add or remove its mentor."); + + private final String reason; + private final String message; + + Refusal(String reason, String message) { + this.reason = reason; + this.message = message; + } + + /** The code a page shows its own words for. */ + public String reason() { + return reason; + } + + /** The sentence sent as the error, for anyone reading the API directly. */ + public String message() { + return message; + } + + /** 403 with a body of error and reason. */ + public ResponseEntity toResponse() { + return new ResponseEntity<>(Map.of("error", message, "reason", reason), HttpStatus.FORBIDDEN); + } + } + + private MentorRules() { + } + + /** True for an account with ROLE_MENTOR and neither ROLE_TEACHER nor ROLE_ADMIN. */ + public static boolean isMentor(Person person) { + return person != null && isMentorRoles(person.getRoles()); + } + + /** The same question asked of a list of role names, for rows read without a Person. */ + public static boolean isMentorRoles(Collection roles) { + return roles != null && roles.contains(ROLE_MENTOR) && !isStaffRoles(roles); + } + + /** True for a teacher or an admin. */ + public static boolean isStaff(Person person) { + return person != null && isStaffRoles(person.getRoles()); + } + + private static boolean isStaffRoles(Collection roles) { + return roles != null && (roles.contains("ROLE_TEACHER") || roles.contains("ROLE_ADMIN")); + } + + /** How many different people among the members aren't mentors; someone listed twice counts once. */ + public static long teamSize(Collection members) { + return members.stream().filter(member -> !isMentor(member)).map(Person::getId).distinct().count(); + } + + /** + * Whether a person is one of the members. Compared by id: Person's equals compares every field, so the same + * person loaded twice may not be equal. + */ + public static boolean isMember(Person person, Collection members) { + return person != null && person.getId() != null + && members.stream().anyMatch(member -> Objects.equals(member.getId(), person.getId())); + } + + /** Refuses a direct message that would include a mentor, whoever is sending it. */ + public static Optional shareDirectMessages(Collection people) { + return people.stream().anyMatch(MentorRules::isMentor) + ? Optional.of(Refusal.NO_DIRECT_MESSAGES) + : Optional.empty(); + } + + /** + * Whether a person may read a group, post in its chat and share its files. A mentor needs to be a member of a + * group that isn't a class group and has at least MIN_TEAM_SIZE members who aren't mentors. + */ + public static Optional useGroup(Person person, boolean classGroup, Collection members) { + if (!isMentor(person)) { + return Optional.empty(); + } + if (!isMember(person, members)) { + return Optional.of(Refusal.NOT_IN_GROUP); + } + if (classGroup) { + return Optional.of(Refusal.CLASS_GROUP); + } + return teamSize(members) < MIN_TEAM_SIZE ? Optional.of(Refusal.TEAM_TOO_SMALL) : Optional.empty(); + } + + /** + * Whether actor may add newMember to a group with these members. A mentor adds no one. Adding a mentor needs a + * teacher, or a member who isn't a mentor, and a group a mentor may use. + */ + public static Optional addMember( + Person actor, Person newMember, boolean classGroup, Collection members) { + if (isMentor(actor)) { + return Optional.of(Refusal.CANNOT_MANAGE); + } + if (!isMentor(newMember)) { + return Optional.empty(); + } + if (!isStaff(actor) && !isMember(actor, members)) { + return Optional.of(Refusal.TEAM_MANAGES_MENTORS); + } + if (classGroup) { + return Optional.of(Refusal.CLASS_GROUP); + } + return teamSize(members) < MIN_TEAM_SIZE ? Optional.of(Refusal.TEAM_TOO_SMALL) : Optional.empty(); + } + + /** + * Whether actor may take member out of a group with these members. A mentor may only leave. Removing a mentor + * needs a teacher or a member who isn't a mentor. Leaving is never refused to anyone else. + */ + public static Optional removeMember(Person actor, Person member, Collection members) { + boolean leaving = actor != null && member != null && Objects.equals(actor.getId(), member.getId()); + if (isMentor(actor)) { + return leaving ? Optional.empty() : Optional.of(Refusal.CANNOT_MANAGE); + } + if (!isMentor(member) || isStaff(actor) || isMember(actor, members)) { + return Optional.empty(); + } + return Optional.of(Refusal.TEAM_MANAGES_MENTORS); + } + + /** Whether a new group may start with these members: each mentor in it must be one the actor could add. */ + public static Optional startGroup(Person actor, boolean classGroup, Collection members) { + Optional refusal = manageGroups(actor); + if (refusal.isPresent()) { + return refusal; + } + return members.stream() + .filter(MentorRules::isMentor) + .map(mentor -> addMember(actor, mentor, classGroup, members)) + .flatMap(Optional::stream) + .findFirst(); + } + + /** + * Refuses a mentor the routes that look through or change groups: every group, search, making, renaming and + * deleting groups, group grades, and another person's groups. + */ + public static Optional manageGroups(Person person) { + return isMentor(person) ? Optional.of(Refusal.CANNOT_MANAGE) : Optional.empty(); + } +} diff --git a/src/main/java/com/open/spring/mvc/groups/MessagesStorageUnavailableException.java b/src/main/java/com/open/spring/mvc/groups/MessagesStorageUnavailableException.java new file mode 100644 index 000000000..93274a547 --- /dev/null +++ b/src/main/java/com/open/spring/mvc/groups/MessagesStorageUnavailableException.java @@ -0,0 +1,15 @@ +package com.open.spring.mvc.groups; + +/** + * S3 couldn't read or save a group's messages for now: it timed out, couldn't be reached or + * answered with a 5xx (a throttle, an outage). Sending, editing and deleting a message each read + * the whole messages file and write it back, so the change is refused rather than half done, and + * the API answers 503 with Retry-After, since S3 being unavailable for a moment isn't a bug in + * this server. + */ +public class MessagesStorageUnavailableException extends RuntimeException { + + public MessagesStorageUnavailableException(Throwable cause) { + super("Could not save this change to the group's chat right now. Try again in a moment.", cause); + } +} diff --git a/src/main/java/com/open/spring/mvc/groups/SharedFileCheckFailedException.java b/src/main/java/com/open/spring/mvc/groups/SharedFileCheckFailedException.java deleted file mode 100644 index e71203dd8..000000000 --- a/src/main/java/com/open/spring/mvc/groups/SharedFileCheckFailedException.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.open.spring.mvc.groups; - -/** - * S3 couldn't say for now whether a shared file is already stored at this path: it timed out, - * couldn't be reached or answered with a 5xx (a throttle, an outage). The upload is refused - * rather than risk writing over a file, and the API answers 503 with Retry-After, since S3 being - * unavailable for a moment isn't a bug in this server. - */ -public class SharedFileCheckFailedException extends RuntimeException { - - private final String path; - - public SharedFileCheckFailedException(String path, Throwable cause) { - super("Could not check whether " + path + " is already shared in this group. Try again in a moment.", cause); - this.path = path; - } - - public String getPath() { - return path; - } -} diff --git a/src/main/java/com/open/spring/mvc/groups/SharedFileStorageUnavailableException.java b/src/main/java/com/open/spring/mvc/groups/SharedFileStorageUnavailableException.java new file mode 100644 index 000000000..0f1ee1027 --- /dev/null +++ b/src/main/java/com/open/spring/mvc/groups/SharedFileStorageUnavailableException.java @@ -0,0 +1,22 @@ +package com.open.spring.mvc.groups; + +/** + * S3 was unavailable for a moment while a file was being shared: it timed out, couldn't be + * reached or answered with a 5xx (a throttle, an outage). Either it couldn't say whether the + * path is taken, so the upload is refused rather than risk writing over a file, or the write + * itself failed. The file isn't shared, and the API answers 503 with Retry-After, since S3 being + * unavailable for a moment isn't a bug in this server. + */ +public class SharedFileStorageUnavailableException extends RuntimeException { + + private final String path; + + public SharedFileStorageUnavailableException(String path, Throwable cause) { + super("Could not share " + path + " in this group. Try again in a moment.", cause); + this.path = path; + } + + public String getPath() { + return path; + } +} 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 84ab9f480..590f56a54 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/main/java/com/open/spring/mvc/push/PushNotificationService.java b/src/main/java/com/open/spring/mvc/push/PushNotificationService.java index 08f63862b..1ba9a0c3c 100644 --- a/src/main/java/com/open/spring/mvc/push/PushNotificationService.java +++ b/src/main/java/com/open/spring/mvc/push/PushNotificationService.java @@ -4,14 +4,19 @@ import java.security.Security; import java.time.Duration; import java.time.Instant; +import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.function.Predicate; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import org.apache.http.HttpResponse; import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.jsoup.Jsoup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; @@ -49,6 +54,13 @@ public class PushNotificationService { private static final Logger log = LoggerFactory.getLogger(PushNotificationService.class); private static final int TTL_SECONDS = 60 * 60 * 24; // keep undelivered pushes for a day private static final int MAX_BODY_CHARS = 140; + // The markers Messages puts in a body for the page to read: a reply's quote, shared files, + // a code block, a pin, and the course chats' events and lessons. A phone shouldn't show them. + // Pages lists the same names in ANY_MARKER_PATTERN (assets/js/chat/chat-reply.js), so a + // marker added there needs adding here too, or its raw text shows up in DM notifications. + // No marker Pages writes has a bracket inside it (it escapes or URL-encodes them), so the + // payload leaves out "[" as well: that keeps matching linear when a body is full of "[[". + private static final Pattern CHAT_MARKER = Pattern.compile("\\[\\[(reply|event|lesson|files|code|pin|unpin):[^\\[\\]]*\\]\\]"); /** How long an unchanged subscription goes before a re-send refreshes last_used_at. */ private static final Duration RESEEN_AFTER = Duration.ofDays(1); @@ -174,7 +186,7 @@ public void notifyPerson(Person person, String title, String body, String url, S } Map payload = Map.of( "title", title == null ? "New message" : title, - "body", snippet(body), + "body", pushText(body), "url", url == null ? "/dm" : url, "tag", tag == null ? "ocs" : tag); Long personId = person.getId(); @@ -191,6 +203,17 @@ public void afterCommit() { } } + // notifyPerson never throws, and it runs inside the message's transaction, so a body the + // text can't be made from still sends the message and its notification, without text. + private static String pushText(String body) { + try { + return snippet(body); + } catch (RuntimeException ex) { + log.warn("Web push: could not make the notification's text ({})", ex.getMessage()); + return ""; + } + } + /** Runs on the sender thread: loads the person's subscriptions and pushes to each. */ private void sendToPerson(Long personId, Map payload) { List subscriptions; @@ -236,12 +259,47 @@ private void send(PushSubscriptionEntity subscription, String json) { } } + /** + * The notification's text: the message as a reader sees it in the chat, cut to + * {@value #MAX_BODY_CHARS} characters. The chat's markers are left out, and the rich + * composer's HTML becomes plain text (tags gone, entities decoded, {@code  } a space). + * If no words are left, the text says what the message did instead, such as "pinned a + * message", or just "sent a message". + */ static String snippet(String body) { - if (body == null) { + if (body == null || body.isBlank()) { return ""; } - String oneLine = body.replaceAll("\\s+", " ").trim(); - return oneLine.length() <= MAX_BODY_CHARS ? oneLine : oneLine.substring(0, MAX_BODY_CHARS - 1) + "…"; + Set markers = new HashSet<>(); + Matcher marker = CHAT_MARKER.matcher(body); + StringBuilder words = new StringBuilder(); + while (marker.find()) { + markers.add(marker.group(1)); + marker.appendReplacement(words, " "); + } + marker.appendTail(words); + String text = Jsoup.parse(words.toString()).text().replace('\u00A0', ' ').replaceAll("\\s+", " ").trim(); + if (text.isEmpty()) { + text = onlyMarkers(markers); + } + return text.length() <= MAX_BODY_CHARS ? text : text.substring(0, MAX_BODY_CHARS - 1) + "…"; + } + + // What a message that was only markers did, said after the sender's name (the title). + private static String onlyMarkers(Set markers) { + if (markers.contains("pin")) { + return "pinned a message"; + } + if (markers.contains("unpin")) { + return "unpinned a message"; + } + if (markers.contains("code")) { + return "sent code"; + } + if (markers.contains("files")) { + return "shared files"; + } + return "sent a message"; } @PreDestroy diff --git a/src/main/java/com/open/spring/mvc/reactions/ChatType.java b/src/main/java/com/open/spring/mvc/reactions/ChatType.java new file mode 100644 index 000000000..9e8583ed8 --- /dev/null +++ b/src/main/java/com/open/spring/mvc/reactions/ChatType.java @@ -0,0 +1,7 @@ +package com.open.spring.mvc.reactions; + +/** The kind of chat a reacted-to message is in: a DM conversation or a group chat. */ +public enum ChatType { + DM, + GROUP +} diff --git a/src/main/java/com/open/spring/mvc/reactions/MessageReaction.java b/src/main/java/com/open/spring/mvc/reactions/MessageReaction.java new file mode 100644 index 000000000..13cdfc279 --- /dev/null +++ b/src/main/java/com/open/spring/mvc/reactions/MessageReaction.java @@ -0,0 +1,57 @@ +package com.open.spring.mvc.reactions; + +import java.io.Serializable; + +import jakarta.persistence.Column; +import jakarta.persistence.Embeddable; +import jakarta.persistence.EmbeddedId; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.Table; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * One person's reaction to one message. The whole row is its key, so a person leaves each + * reaction at most once on a message. DM messages are rows and group messages live in S3, + * so a message is named by its chat and its id as text. + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@Entity +@Table(name = "message_reaction") +public class MessageReaction { + + @EmbeddedId + private Key key; + + /** Which chat, which message, who, and which emoji. */ + @Data + @NoArgsConstructor + @AllArgsConstructor + @Embeddable + public static class Key implements Serializable { + + @Enumerated(EnumType.STRING) + @Column(name = "chat_type", length = 8) + private ChatType chatType; + + /** The DM conversation's id or the group's id. */ + @Column(name = "chat_id") + private Long chatId; + + /** A DM message's numeric id as text, or a group message's UUID. */ + @Column(name = "message_id", length = 64) + private String messageId; + + @Column(name = "person_id") + private Long personId; + + @Enumerated(EnumType.STRING) + @Column(name = "reaction", length = 16) + private Reaction reaction; + } +} diff --git a/src/main/java/com/open/spring/mvc/reactions/MessageReactionJpaRepository.java b/src/main/java/com/open/spring/mvc/reactions/MessageReactionJpaRepository.java new file mode 100644 index 000000000..b920148df --- /dev/null +++ b/src/main/java/com/open/spring/mvc/reactions/MessageReactionJpaRepository.java @@ -0,0 +1,52 @@ +package com.open.spring.mvc.reactions; + +import java.util.Collection; +import java.util.List; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +/** Reactions, read by chat or by message. */ +public interface MessageReactionJpaRepository extends JpaRepository { + + /** Every reaction in one chat. */ + List findByKeyChatTypeAndKeyChatId(ChatType chatType, Long chatId); + + /** Every reaction on one message. */ + List findByKeyChatTypeAndKeyChatIdAndKeyMessageId(ChatType chatType, Long chatId, String messageId); + + /** + * Removes one person's reaction in one statement. Reading the row first and then deleting it + * let a second remove at the same moment fail; a statement that deletes 0 rows doesn't. + */ + @Modifying(flushAutomatically = true) + @Query("delete from MessageReaction r where r.key.chatType = :chatType and r.key.chatId = :chatId" + + " and r.key.messageId = :messageId and r.key.personId = :personId and r.key.reaction = :reaction") + int deleteOne(@Param("chatType") ChatType chatType, @Param("chatId") Long chatId, @Param("messageId") String messageId, + @Param("personId") Long personId, @Param("reaction") Reaction reaction); + + /** Removes every reaction on one message in one statement, as when the message is deleted. */ + @Modifying(flushAutomatically = true) + @Query("delete from MessageReaction r where r.key.chatType = :chatType and r.key.chatId = :chatId" + + " and r.key.messageId = :messageId") + int deleteAllOnMessage(@Param("chatType") ChatType chatType, @Param("chatId") Long chatId, + @Param("messageId") String messageId); + + /** + * The uid and name of each person who reacted, in one query. Loading whole Person rows + * would also load each one's eager links, several queries per person. + */ + @Query("select p.id as id, p.uid as uid, p.name as name from Person p where p.id in :ids") + List findReactorNames(@Param("ids") Collection ids); + + /** A person who reacted, as far as a reaction needs to know them. */ + interface ReactorName { + Long getId(); + + String getUid(); + + String getName(); + } +} diff --git a/src/main/java/com/open/spring/mvc/reactions/MessageReactionService.java b/src/main/java/com/open/spring/mvc/reactions/MessageReactionService.java new file mode 100644 index 000000000..afb8540c0 --- /dev/null +++ b/src/main/java/com/open/spring/mvc/reactions/MessageReactionService.java @@ -0,0 +1,132 @@ +package com.open.spring.mvc.reactions; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.stream.Collectors; + +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import com.open.spring.mvc.person.Person; + +import lombok.RequiredArgsConstructor; + +/** + * Saves and summarizes the reactions on DM and group messages. It doesn't decide who may react + * or whether a message exists: each chat's own service checks that before calling here. + */ +@Service +@RequiredArgsConstructor +public class MessageReactionService { + + private static final Comparator BY_NAME = Comparator + .comparing((Reactor reactor) -> reactor.name() == null ? "" : reactor.name(), String.CASE_INSENSITIVE_ORDER) + .thenComparing(reactor -> reactor.uid() == null ? "" : reactor.uid()); + + private final MessageReactionJpaRepository repository; + + /** Someone who reacted, as the page shows them. */ + public record Reactor(String uid, String name) { + } + + /** One emoji on a message, by its lowercase key, and everyone who left it. */ + public record ReactionSummary(String reaction, List people) { + } + + /** A message's reactions after a change: the body PUT and DELETE answer with. */ + public record MessageReactions(String messageId, List reactions) { + } + + /** Adds this person's reaction. Adding one that is already there changes nothing. */ + @Transactional + public void add(ChatType type, Long chatId, String messageId, Person person, Reaction reaction) { + MessageReaction.Key key = new MessageReaction.Key(type, chatId, messageId, person.getId(), reaction); + if (!repository.existsById(key)) { + repository.save(new MessageReaction(key)); + } + } + + /** Removes this person's reaction. Removing one that isn't there changes nothing. */ + @Transactional + public void remove(ChatType type, Long chatId, String messageId, Person person, Reaction reaction) { + repository.deleteOne(type, chatId, messageId, person.getId(), reaction); + } + + /** One message's reactions, in the enum's order. */ + @Transactional(readOnly = true) + public List forMessage(ChatType type, Long chatId, String messageId) { + List rows = repository.findByKeyChatTypeAndKeyChatIdAndKeyMessageId(type, chatId, messageId); + return summarize(rows, reactorsFor(rows)); + } + + /** + * One message's reactions, read in a transaction of its own: for the frame a DM sends once its + * change has committed, so the read sees what everyone else committed by then. + */ + @Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = true) + public List forMessageNow(ChatType type, Long chatId, String messageId) { + return forMessage(type, chatId, messageId); + } + + /** Every reacted-to message in a chat, by message id. A message left with no reactions isn't listed. */ + @Transactional(readOnly = true) + public Map> forChat(ChatType type, Long chatId) { + List rows = repository.findByKeyChatTypeAndKeyChatId(type, chatId); + Map reactors = reactorsFor(rows); + Map> byMessage = rows.stream().collect( + Collectors.groupingBy(row -> row.getKey().getMessageId(), LinkedHashMap::new, Collectors.toList())); + Map> result = new LinkedHashMap<>(); + byMessage.forEach((messageId, messageRows) -> { + List summaries = summarize(messageRows, reactors); + if (!summaries.isEmpty()) { + result.put(messageId, summaries); + } + }); + return result; + } + + /** + * Removes every reaction on a message, as when the message is deleted. The chats call it once + * their delete is done (a DM's after its transaction commits), so it runs in a transaction of + * its own: a transactional call made from inside a finished transaction never commits. + */ + @Transactional(propagation = Propagation.REQUIRES_NEW) + public void removeAllFor(ChatType type, Long chatId, String messageId) { + repository.deleteAllOnMessage(type, chatId, messageId); + } + + // Everyone in one query. Someone whose account is gone isn't in the result, so they drop out. + private Map reactorsFor(List rows) { + List ids = rows.stream().map(row -> row.getKey().getPersonId()).distinct().toList(); + if (ids.isEmpty()) { + return Map.of(); + } + Map reactors = new HashMap<>(); + for (MessageReactionJpaRepository.ReactorName person : repository.findReactorNames(ids)) { + reactors.put(person.getId(), new Reactor(person.getUid(), person.getName())); + } + return reactors; + } + + private List summarize(List rows, Map reactors) { + List summaries = new ArrayList<>(); + for (Reaction reaction : Reaction.values()) { + List people = rows.stream() + .filter(row -> row.getKey().getReaction() == reaction) + .map(row -> reactors.get(row.getKey().getPersonId())) + .filter(Objects::nonNull) + .sorted(BY_NAME) + .toList(); + if (!people.isEmpty()) { + summaries.add(new ReactionSummary(reaction.key(), people)); + } + } + return summaries; + } +} diff --git a/src/main/java/com/open/spring/mvc/reactions/MessageReactionTableInitializer.java b/src/main/java/com/open/spring/mvc/reactions/MessageReactionTableInitializer.java new file mode 100644 index 000000000..a74129315 --- /dev/null +++ b/src/main/java/com/open/spring/mvc/reactions/MessageReactionTableInitializer.java @@ -0,0 +1,48 @@ +package com.open.spring.mvc.reactions; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.ApplicationRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.dao.DataAccessException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Component; + +import lombok.RequiredArgsConstructor; + +/** + * Creates message_reaction for databases run with ddl-auto=none, and leaves an existing one + * as it is. The primary key is all five columns: that keeps a person to one of each reaction + * on a message, and it needs no auto-increment, so one statement in unquoted lowercase with + * plain types runs on both SQLite and MySQL. + */ +@Component +@RequiredArgsConstructor +public class MessageReactionTableInitializer { + + static final String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS message_reaction (" + + "chat_type varchar(8) NOT NULL, " + + "chat_id bigint NOT NULL, " + + "message_id varchar(64) NOT NULL, " + + "person_id bigint NOT NULL, " + + "reaction varchar(16) NOT NULL, " + + "PRIMARY KEY (chat_type, chat_id, message_id, person_id, reaction))"; + + private static final Logger logger = LoggerFactory.getLogger(MessageReactionTableInitializer.class); + + private final JdbcTemplate jdbcTemplate; + + @Bean + public ApplicationRunner migrateMessageReaction() { + return args -> { + try { + jdbcTemplate.execute(CREATE_TABLE); + } catch (DataAccessException e) { + // The rest of Spring keeps running, as it does when another table can't be made. + // Until the table exists the reaction routes fail, and deleting a message still + // works but logs that its reactions couldn't be removed. + logger.error("Could not create the message_reaction table, so reactions won't work: {}", e.getMessage()); + } + }; + } +} diff --git a/src/main/java/com/open/spring/mvc/reactions/Reaction.java b/src/main/java/com/open/spring/mvc/reactions/Reaction.java new file mode 100644 index 000000000..bb778d619 --- /dev/null +++ b/src/main/java/com/open/spring/mvc/reactions/Reaction.java @@ -0,0 +1,34 @@ +package com.open.spring.mvc.reactions; + +import java.util.Arrays; +import java.util.Optional; + +/** + * The emoji a message can get. A row stores the enum name; routes and JSON use the lowercase + * key. Pages' Messages reactions.js lists the same keys in the same order, so change both + * together. + */ +public enum Reaction { + LIKE("like"), + LOVE("love"), + HAHA("haha"), + WOW("wow"), + SAD("sad"), + CELEBRATE("celebrate"); + + private final String key; + + Reaction(String key) { + this.key = key; + } + + /** The lowercase name a route and the page use, such as "like". */ + public String key() { + return key; + } + + /** The reaction with exactly this key, or empty for anything else, "LIKE" included. */ + public static Optional fromKey(String key) { + return Arrays.stream(values()).filter(reaction -> reaction.key.equals(key)).findFirst(); + } +} diff --git a/src/main/java/com/open/spring/mvc/uibuilder/UiBuilderException.java b/src/main/java/com/open/spring/mvc/uibuilder/UiBuilderException.java index 2a6add9c6..23f7aba0d 100644 --- a/src/main/java/com/open/spring/mvc/uibuilder/UiBuilderException.java +++ b/src/main/java/com/open/spring/mvc/uibuilder/UiBuilderException.java @@ -55,7 +55,7 @@ public static HttpStatus statusOf(Outcome outcome) { case NO_CONTENT -> HttpStatus.NO_CONTENT; case INVALID_SPEC, INVALID_GROUP, INVALID_VISIBILITY, INVALID_UNTIL, INVALID_COURSE, INVALID_SCOPE, SLUG_REQUIRED, INVALID_SLUG, SLUG_RESERVED, LOOPBACK_SOURCE, OWN_PAGE -> HttpStatus.BAD_REQUEST; - case FORBIDDEN -> HttpStatus.FORBIDDEN; + case FORBIDDEN, MENTOR_NO_DIRECT_MESSAGES -> HttpStatus.FORBIDDEN; case NOT_FOUND -> HttpStatus.NOT_FOUND; case VERSION_CONFLICT, SLUG_TAKEN, SLUG_LOCKED, NOT_PUBLISHED, PUBLISHED_CHANGED, TOO_MANY_PAGES -> HttpStatus.CONFLICT; }; diff --git a/src/main/java/com/open/spring/mvc/uibuilder/UiBuilderPageService.java b/src/main/java/com/open/spring/mvc/uibuilder/UiBuilderPageService.java index e2c673168..e024832fc 100644 --- a/src/main/java/com/open/spring/mvc/uibuilder/UiBuilderPageService.java +++ b/src/main/java/com/open/spring/mvc/uibuilder/UiBuilderPageService.java @@ -39,6 +39,7 @@ import com.open.spring.mvc.groups.CourseGroupProperties; import com.open.spring.mvc.groups.Groups; import com.open.spring.mvc.groups.GroupsJpaRepository; +import com.open.spring.mvc.groups.MentorRules; import com.open.spring.mvc.person.Person; import com.open.spring.mvc.person.PersonJpaRepository; import com.open.spring.mvc.uibuilder.UiBuilderPageApiRestController.BulkResult; @@ -110,7 +111,9 @@ public enum Outcome { NOT_FOUND, FORBIDDEN, VERSION_CONFLICT, INVALID_SPEC, INVALID_GROUP, INVALID_VISIBILITY, INVALID_UNTIL, INVALID_COURSE, INVALID_SCOPE, SLUG_REQUIRED, INVALID_SLUG, SLUG_RESERVED, SLUG_TAKEN, SLUG_LOCKED, - LOOPBACK_SOURCE, NOT_PUBLISHED, PUBLISHED_CHANGED, OWN_PAGE, TOO_MANY_PAGES + LOOPBACK_SOURCE, NOT_PUBLISHED, PUBLISHED_CHANGED, OWN_PAGE, TOO_MANY_PAGES, + // A mentor would be in the conversation, and MentorRules allows no direct message that includes one. + MENTOR_NO_DIRECT_MESSAGES } /** @@ -847,6 +850,9 @@ public Result messageOwner(Caller caller, String slug) { if (owner.isEmpty() || me.isEmpty()) { return Result.refused(Outcome.NOT_FOUND); } + if (MentorRules.shareDirectMessages(List.of(me.get(), owner.get())).isPresent()) { + return Result.refused(Outcome.MENTOR_NO_DIRECT_MESSAGES); + } DirectMessageConversation conversation = directMessages.getOrCreateConversation(me.get(), List.of(owner.get())); return Result.ok(new ConversationRef(conversation.getId())); } diff --git a/src/main/resources/data/permissions.json b/src/main/resources/data/permissions.json index 579ed3f9c..607f05ef1 100644 --- a/src/main/resources/data/permissions.json +++ b/src/main/resources/data/permissions.json @@ -476,6 +476,9 @@ "POST /api/dm/conversations/{id}/messages", "DELETE /api/dm/conversations/{id}/messages/{messageId}", "PATCH /api/dm/conversations/{id}/messages/{messageId}", + "DELETE /api/dm/conversations/{id}/messages/{messageId}/reactions/{reaction}", + "PUT /api/dm/conversations/{id}/messages/{messageId}/reactions/{reaction}", + "GET /api/dm/conversations/{id}/reactions", "POST /api/dm/conversations/{id}/read", "GET /api/dm/search", "GET /api/dm/unread", @@ -531,6 +534,9 @@ "POST /api/groups/chat/{groupId}/messages", "DELETE /api/groups/chat/{groupId}/messages/{messageId}", "PATCH /api/groups/chat/{groupId}/messages/{messageId}", + "DELETE /api/groups/chat/{groupId}/messages/{messageId}/reactions/{reaction}", + "PUT /api/groups/chat/{groupId}/messages/{messageId}/reactions/{reaction}", + "GET /api/groups/chat/{groupId}/reactions", "POST /api/groups/chat/{groupId}/read", "PUT /api/groups/class-memberships", "GET /api/groups/person/{personId}", diff --git a/src/test/java/com/open/spring/StartupServiceTest.java b/src/test/java/com/open/spring/StartupServiceTest.java new file mode 100644 index 000000000..163d31d00 --- /dev/null +++ b/src/test/java/com/open/spring/StartupServiceTest.java @@ -0,0 +1,291 @@ +package com.open.spring; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; +import org.springframework.boot.DefaultApplicationArguments; +import org.springframework.test.util.ReflectionTestUtils; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.open.spring.mvc.S3uploads.S3FileHandler; +import com.open.spring.mvc.groups.GroupChatMessage; +import com.open.spring.mvc.groups.GroupChatService; +import com.open.spring.mvc.groups.Groups; +import com.open.spring.mvc.groups.GroupsJpaRepository; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; +import software.amazon.awssdk.core.ResponseBytes; +import software.amazon.awssdk.core.exception.SdkClientException; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectResponse; +import software.amazon.awssdk.services.s3.model.HeadObjectRequest; +import software.amazon.awssdk.services.s3.model.HeadObjectResponse; +import software.amazon.awssdk.services.s3.model.NoSuchKeyException; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.PutObjectResponse; +import software.amazon.awssdk.services.s3.model.S3Exception; + +/** + * At every start the server checks each group's chat files in S3 and creates an empty + * messages file for a group that has none. A check that failed must not count as none: + * the empty file would replace the group's whole history. + */ +class StartupServiceTest { + + private static final String CSA_MESSAGES = "CSA/messages-images/messages.jsonl"; + private static final String ADA_LINE = "{\"id\":\"m1\",\"author\":\"Ada Lovelace\",\"author_uid\":\"ada\"," + + "\"message\":\"Meeting at 3\",\"date\":\"2026-11-21T10:00:00Z\",\"image\":null,\"edited\":false}"; + + /** S3's objects by key. The real S3FileHandler reaches them through a stand-in S3 client. */ + private final Map objects = new ConcurrentHashMap<>(); + /** Groups S3 can't answer for right now: checking any of their files throws this. */ + private final Map failingChecks = new ConcurrentHashMap<>(); + private S3Client s3; + private GroupChatService chat; + private GroupsJpaRepository groups; + + @BeforeEach + void setUp() { + s3 = mock(S3Client.class); + // As S3 answers: a key that isn't stored is a 404 NoSuchKey. + when(s3.headObject(any(HeadObjectRequest.class))).thenAnswer(call -> { + String key = call.getArgument(0).key(); + RuntimeException failure = failingChecks.get(key.substring(0, key.indexOf('/'))); + if (failure != null) { + throw failure; + } + if (!objects.containsKey(key)) { + throw notFound(); + } + return HeadObjectResponse.builder().build(); + }); + when(s3.getObjectAsBytes(any(GetObjectRequest.class))).thenAnswer(call -> { + byte[] bytes = objects.get(call.getArgument(0).key()); + if (bytes == null) { + throw notFound(); + } + return ResponseBytes.fromByteArray(GetObjectResponse.builder().build(), bytes); + }); + when(s3.putObject(any(PutObjectRequest.class), any(RequestBody.class))).thenAnswer(call -> { + store(call.getArgument(0).key(), call.getArgument(1)); + return PutObjectResponse.builder().build(); + }); + S3FileHandler storage = new S3FileHandler(); + ReflectionTestUtils.setField(storage, "s3Client", s3); + ReflectionTestUtils.setField(storage, "bucketName", "chat-test"); + chat = new GroupChatService(storage, new ObjectMapper()); + groups = mock(GroupsJpaRepository.class); + } + + @Test + void aCheckThatFailsLeavesTheHistoryAsItIs() { + // S3 throttled (503 Slow Down), failing (500), refusing (403) or out of reach: none of + // these says the file is missing. + List failures = List.of( + answered(503, "Slow Down"), + answered(500, "We encountered an internal error. Please try again."), + answered(403, "Access Denied"), + SdkClientException.create("Unable to execute HTTP request: Connect timed out")); + for (RuntimeException failure : failures) { + objects.clear(); + objects.put(CSA_MESSAGES, ADA_LINE.getBytes(StandardCharsets.UTF_8)); + failingChecks.put("CSA", failure); + + assertDoesNotThrow(() -> startUp("CSA"), failure.toString()); + + assertEquals(ADA_LINE, stored(CSA_MESSAGES), failure.toString()); + } + } + + @Test + void aCheckThatFailsIsLoggedWithTheGroupAndTheCause() throws Exception { + objects.put(CSA_MESSAGES, ADA_LINE.getBytes(StandardCharsets.UTF_8)); + RuntimeException throttle = answered(503, "Slow Down"); + failingChecks.put("CSA", throttle); + + try (Warnings warnings = new Warnings(StartupService.class)) { + startUp("CSA"); + + assertEquals(1, warnings.list().size(), warnings.messages().toString()); + ILoggingEvent warning = warnings.list().get(0); + assertTrue(warning.getFormattedMessage().contains("CSA"), warning.getFormattedMessage()); + assertEquals(throttle.getClass().getName(), warning.getThrowableProxy().getClassName()); + } + } + + @Test + void aGroupThatCantBeCheckedDoesNotStopTheOthers() throws Exception { + objects.put(CSA_MESSAGES, ADA_LINE.getBytes(StandardCharsets.UTF_8)); + failingChecks.put("CSA", answered(503, "Slow Down")); + + startUp("CSA", "CSP"); + + assertEquals(ADA_LINE, stored(CSA_MESSAGES)); + assertEquals("", stored("CSP/messages-images/messages.jsonl")); + } + + @Test + void aGroupWithNoMessagesFileYetGetsAnEmptyOne() throws Exception { + // S3's 404: nothing is stored yet, so there's no history to lose. + startUp("CSA"); + + assertEquals("", stored(CSA_MESSAGES)); + assertArrayEquals(new byte[0], objects.get("CSA/shared-files/")); + } + + @Test + void aGroupThatHasItsMessagesKeepsThem() throws Exception { + objects.put(CSA_MESSAGES, ADA_LINE.getBytes(StandardCharsets.UTF_8)); + + startUp("CSA"); + + assertEquals(ADA_LINE, stored(CSA_MESSAGES)); + } + + @Test + void aServerWithoutS3StartsQuietly() { + // A local server without S3 settings stores nothing, so there's nothing to check. + chat = new GroupChatService(new S3FileHandler(), new ObjectMapper()); + + try (Warnings warnings = new Warnings(StartupService.class, GroupChatService.class, S3FileHandler.class)) { + assertDoesNotThrow(() -> startUp("CSA", "CSP")); + assertEquals(List.of(), warnings.messages()); + } + } + + @Test + void aMessageSentWhileTheCheckCreatesTheFileIsKept() throws Exception { + // The check finds no file, but S3's answer only arrives once a send has saved a + // message (or half a second passes). An empty file written after that would erase it. + CountDownLatch checking = new CountDownLatch(1); + CountDownLatch sendSaved = new CountDownLatch(1); + doAnswer(call -> { + String key = call.getArgument(0).key(); + boolean found = objects.containsKey(key); + if (CSA_MESSAGES.equals(key)) { + checking.countDown(); + sendSaved.await(500, TimeUnit.MILLISECONDS); + } + if (!found) { + throw notFound(); + } + return HeadObjectResponse.builder().build(); + }).when(s3).headObject(any(HeadObjectRequest.class)); + doAnswer(call -> { + String key = call.getArgument(0).key(); + store(key, call.getArgument(1)); + if (CSA_MESSAGES.equals(key) && objects.get(key).length > 0) { + sendSaved.countDown(); + } + return PutObjectResponse.builder().build(); + }).when(s3).putObject(any(PutObjectRequest.class), any(RequestBody.class)); + + ExecutorService pool = Executors.newSingleThreadExecutor(); + try { + Future send = pool.submit(() -> { + checking.await(5, TimeUnit.SECONDS); + return chat.addMessage("CSA", + new GroupChatMessage("Grace Hopper", "grace", "Works for me", "2026-11-22T08:00:00Z", null)); + }); + startUp("CSA"); + send.get(10, TimeUnit.SECONDS); + } finally { + pool.shutdownNow(); + } + + assertEquals(List.of("Works for me"), + chat.getMessages("CSA").stream().map(GroupChatMessage::getMessage).toList()); + } + + /** Runs the server's start-up check over groups with these names. */ + private void startUp(String... groupNames) throws Exception { + List found = new ArrayList<>(); + for (String name : groupNames) { + Groups group = new Groups(); + group.setName(name); + found.add(group); + } + when(groups.findAll()).thenReturn(found); + new StartupService(groups, chat).initializeGroupStorage().run(new DefaultApplicationArguments()); + } + + private void store(String key, RequestBody body) throws Exception { + try (InputStream bytes = body.contentStreamProvider().newStream()) { + objects.put(key, bytes.readAllBytes()); + } + } + + private String stored(String key) { + byte[] bytes = objects.get(key); + return bytes == null ? null : new String(bytes, StandardCharsets.UTF_8); + } + + private static S3Exception answered(int status, String message) { + return (S3Exception) S3Exception.builder().statusCode(status).message(message).build(); + } + + private static S3Exception notFound() { + return (S3Exception) NoSuchKeyException.builder().statusCode(404).message("The specified key does not exist.").build(); + } + + /** The warnings the given classes log while it's open. */ + private static final class Warnings implements AutoCloseable { + private final ListAppender appender = new ListAppender<>(); + private final List loggers = new ArrayList<>(); + private final List previousLevels = new ArrayList<>(); + + Warnings(Class... types) { + appender.start(); + for (Class type : types) { + Logger logger = (Logger) LoggerFactory.getLogger(type); + previousLevels.add(logger.getLevel()); + logger.setLevel(Level.WARN); + logger.addAppender(appender); + loggers.add(logger); + } + } + + List list() { + return List.copyOf(appender.list); + } + + List messages() { + return list().stream().map(ILoggingEvent::getFormattedMessage).toList(); + } + + @Override + public void close() { + for (int i = 0; i < loggers.size(); i++) { + loggers.get(i).detachAppender(appender); + loggers.get(i).setLevel(previousLevels.get(i)); + } + appender.stop(); + } + } +} diff --git a/src/test/java/com/open/spring/mvc/S3uploads/S3FileHandlerDecodeTest.java b/src/test/java/com/open/spring/mvc/S3uploads/S3FileHandlerDecodeTest.java new file mode 100644 index 000000000..181d4527f --- /dev/null +++ b/src/test/java/com/open/spring/mvc/S3uploads/S3FileHandlerDecodeTest.java @@ -0,0 +1,72 @@ +package com.open.spring.mvc.S3uploads; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; + +import java.nio.charset.StandardCharsets; +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.test.util.ReflectionTestUtils; + +import software.amazon.awssdk.core.ResponseBytes; +import software.amazon.awssdk.core.exception.SdkClientException; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectResponse; +import software.amazon.awssdk.services.s3.model.NoSuchKeyException; +import software.amazon.awssdk.services.s3.model.S3Exception; + +/** + * decodeFileOrThrow tells "nothing stored" apart from "couldn't read": a caller that writes + * back what it read must not take a read that failed for an empty file. + */ +class S3FileHandlerDecodeTest { + + private static final String MESSAGES = "messages-images/messages.jsonl"; + + private S3Client s3; + private S3FileHandler handler; + + @BeforeEach + void setUp() { + s3 = mock(S3Client.class); + handler = new S3FileHandler(); + ReflectionTestUtils.setField(handler, "s3Client", s3); + } + + @Test + void aStoredFileComesBackAsBase64() { + doReturn(ResponseBytes.fromByteArray(GetObjectResponse.builder().build(), "hello".getBytes(StandardCharsets.UTF_8))) + .when(s3).getObjectAsBytes(any(GetObjectRequest.class)); + assertEquals("aGVsbG8=", handler.decodeFileOrThrow("CSA", MESSAGES)); + } + + @Test + void notFoundMeansNothingIsStored() { + doThrow(NoSuchKeyException.builder().statusCode(404).message("The specified key does not exist.").build()) + .when(s3).getObjectAsBytes(any(GetObjectRequest.class)); + assertNull(handler.decodeFileOrThrow("CSA", MESSAGES)); + } + + @Test + void anyOtherFailureThrowsInsteadOfReadingAsNothingStored() { + List failures = List.of( + (S3Exception) S3Exception.builder().statusCode(503).message("Slow Down").build(), + (S3Exception) S3Exception.builder().statusCode(403).message("Access Denied").build(), + SdkClientException.create("Unable to execute HTTP request: Read timed out")); + for (RuntimeException failure : failures) { + doThrow(failure).when(s3).getObjectAsBytes(any(GetObjectRequest.class)); + assertSame(failure, assertThrows(RuntimeException.class, () -> handler.decodeFileOrThrow("CSA", MESSAGES))); + // decodeFile keeps answering null, as its other callers expect. + assertNull(handler.decodeFile("CSA", MESSAGES)); + } + } +} diff --git a/src/test/java/com/open/spring/mvc/S3uploads/S3FileHandlerUploadTest.java b/src/test/java/com/open/spring/mvc/S3uploads/S3FileHandlerUploadTest.java new file mode 100644 index 000000000..0e35b375c --- /dev/null +++ b/src/test/java/com/open/spring/mvc/S3uploads/S3FileHandlerUploadTest.java @@ -0,0 +1,79 @@ +package com.open.spring.mvc.S3uploads; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.Base64; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.test.util.ReflectionTestUtils; + +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.S3Exception; + +/** + * uploadFileOrThrow tells a stored file apart from a write that failed: it throws the failure + * where uploadFile answers null, so a caller can tell S3 being unavailable for a moment from a + * request S3 refused. + */ +class S3FileHandlerUploadTest { + + private static final String HELLO = Base64.getEncoder().encodeToString("hello".getBytes(StandardCharsets.UTF_8)); + + private S3Client s3; + private S3FileHandler handler; + + @BeforeEach + void setUp() { + s3 = mock(S3Client.class); + handler = new S3FileHandler(); + ReflectionTestUtils.setField(handler, "s3Client", s3); + ReflectionTestUtils.setField(handler, "bucketName", "pages-assignments"); + } + + @Test + void aWriteS3TakesStoresTheBytesUnderTheGroupsKey() throws Exception { + assertEquals("shared-files/notes.md", handler.uploadFileOrThrow(HELLO, "shared-files/notes.md", "CSA")); + + ArgumentCaptor request = ArgumentCaptor.forClass(PutObjectRequest.class); + ArgumentCaptor body = ArgumentCaptor.forClass(RequestBody.class); + verify(s3).putObject(request.capture(), body.capture()); + assertEquals("pages-assignments", request.getValue().bucket()); + assertEquals("CSA/shared-files/notes.md", request.getValue().key()); + try (InputStream bytes = body.getValue().contentStreamProvider().newStream()) { + assertArrayEquals("hello".getBytes(StandardCharsets.UTF_8), bytes.readAllBytes()); + } + } + + @Test + void aWriteThatFailsThrowsTheFailureInsteadOfAnsweringNull() { + S3Exception throttled = (S3Exception) S3Exception.builder().statusCode(503).message("Slow Down").build(); + when(s3.putObject(any(PutObjectRequest.class), any(RequestBody.class))).thenThrow(throttled); + + assertSame(throttled, assertThrows(S3Exception.class, + () -> handler.uploadFileOrThrow(HELLO, "shared-files/notes.md", "CSA"))); + // uploadFile keeps answering null, as its other callers expect. + assertNull(handler.uploadFile(HELLO, "shared-files/notes.md", "CSA")); + } + + @Test + void withoutS3ItThrowsInsteadOfAnsweringNull() { + S3FileHandler notConfigured = new S3FileHandler(); + + assertThrows(IllegalStateException.class, + () -> notConfigured.uploadFileOrThrow(HELLO, "shared-files/notes.md", "CSA")); + } +} diff --git a/src/test/java/com/open/spring/mvc/chat/LegacyChatMentorTest.java b/src/test/java/com/open/spring/mvc/chat/LegacyChatMentorTest.java new file mode 100644 index 000000000..265954063 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/chat/LegacyChatMentorTest.java @@ -0,0 +1,164 @@ +package com.open.spring.mvc.chat; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.test.util.ReflectionTestUtils; + +import com.open.spring.mvc.groups.ClassGroupMembershipService; +import com.open.spring.mvc.groups.Groups; +import com.open.spring.mvc.groups.GroupsJpaRepository; +import com.open.spring.mvc.groups.MentorAccess; +import com.open.spring.mvc.person.Person; +import com.open.spring.mvc.person.PersonJpaRepository; + +/** + * The older /api/chat/{groupId} keeps its own chat file per group. Only the group's members, teachers and admins read it, + * and only members post. A mentor uses it only where they may use the group's chat (MentorRules). + */ +class LegacyChatMentorTest { + + private ChatService chat; + private GroupsJpaRepository groups; + private ClassGroupMembershipService classGroups; + private PersonJpaRepository people; + private ChatApiController controller; + + private static Person person(long id, String... roles) { + Person person = new Person(); + ReflectionTestUtils.setField(person, "id", id); + person.setUid("person" + id); + person.setName("Person " + id); + person.setRoles(new ArrayList<>(List.of(roles))); + return person; + } + + private final Person student = person(1, "ROLE_USER", "ROLE_STUDENT"); + private final Person teammate = person(2, "ROLE_USER", "ROLE_STUDENT"); + private final Person mentor = person(3, "ROLE_USER", "ROLE_MENTOR"); + private final Person outsider = person(5, "ROLE_USER", "ROLE_STUDENT"); + private final Person teacher = person(8, "ROLE_USER", "ROLE_TEACHER"); + private final Person admin = person(9, "ROLE_USER", "ROLE_ADMIN"); + + private static final long OTHERS = 7L; + private static final long SOLO = 8L; + private static final long TEAM = 9L; + + private void group(long id, String name, Person... members) { + Groups group = new Groups(); + ReflectionTestUtils.setField(group, "id", id); + group.setName(name); + for (Person member : members) { + group.getGroupMembers().add(member); + } + when(groups.findById(id)).thenReturn(Optional.of(group)); + when(groups.findMembersOf(id)).thenReturn(List.of(members)); + } + + @BeforeEach + void setUp() { + chat = mock(ChatService.class); + groups = mock(GroupsJpaRepository.class); + classGroups = mock(ClassGroupMembershipService.class); + people = mock(PersonJpaRepository.class); + controller = new ChatApiController(chat, groups, people, new MentorAccess(groups, classGroups)); + for (Person person : List.of(student, teammate, mentor, outsider, teacher, admin)) { + when(people.findByUid(person.getUid())).thenReturn(person); + } + group(OTHERS, "Team Rocket", student, teammate); + group(SOLO, "Just Us", student, mentor); + group(TEAM, "Team Plasma", student, teammate, mentor); + when(chat.getChatHistory(anyLong())).thenReturn(List.of()); + when(chat.addMessage(anyLong(), any())).thenReturn(List.of()); + } + + @AfterEach + void signOut() { + SecurityContextHolder.clearContext(); + } + + private void signIn(Person person) { + SecurityContextHolder.getContext().setAuthentication( + new UsernamePasswordAuthenticationToken(person.getUid(), null, List.of())); + } + + private static void assertRefused(String reason, ResponseEntity response) { + assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode()); + assertEquals(reason, ((Map) response.getBody()).get("reason")); + } + + private static ChatApiController.ChatMessageRequest text(String content) { + return new ChatApiController.ChatMessageRequest(content); + } + + @Test + void aMentorWhoIsNotInTheGroupCantReadItsOlderChat() { + signIn(mentor); + assertRefused("mentor_not_in_group", controller.getChat(OTHERS)); + verify(chat, never()).getChatHistory(anyLong()); + } + + @Test + void aMentorWhoIsNotInTheGroupIsToldWhyTheyCantPostToItsOlderChat() { + signIn(mentor); + assertRefused("mentor_not_in_group", controller.postChat(OTHERS, text("hi"))); + verify(chat, never()).addMessage(anyLong(), any()); + } + + @Test + void aMentorWithATeamOfOneCantUseItsOlderChat() { + signIn(mentor); + assertRefused("mentor_team_too_small", controller.getChat(SOLO)); + assertRefused("mentor_team_too_small", controller.postChat(SOLO, text("just us"))); + verify(chat, never()).addMessage(anyLong(), any()); + } + + @Test + void aMentorInTheirTeamUsesItsOlderChat() { + signIn(mentor); + assertEquals(HttpStatus.OK, controller.getChat(TEAM).getStatusCode()); + assertEquals(HttpStatus.OK, controller.postChat(TEAM, text("hi team")).getStatusCode()); + } + + @Test + void someoneOutsideTheGroupCantReadItsOlderChat() { + signIn(outsider); + assertEquals(HttpStatus.FORBIDDEN, controller.getChat(OTHERS).getStatusCode()); + verify(chat, never()).getChatHistory(anyLong()); + } + + @Test + void membersTeachersAndAdminsReadTheOlderChat() { + for (Person reader : List.of(student, teacher, admin)) { + signIn(reader); + assertEquals(HttpStatus.OK, controller.getChat(OTHERS).getStatusCode(), reader.getUid()); + } + verify(groups, never()).findMembersOf(anyLong()); + } + + @Test + void onlyMembersPostAsBefore() { + signIn(outsider); + assertEquals(HttpStatus.FORBIDDEN, controller.postChat(OTHERS, text("hi")).getStatusCode()); + signIn(student); + assertEquals(HttpStatus.OK, controller.postChat(OTHERS, text("hi")).getStatusCode()); + verify(groups, never()).findMembersOf(anyLong()); + } +} diff --git a/src/test/java/com/open/spring/mvc/directmessages/DirectMessageMentorTest.java b/src/test/java/com/open/spring/mvc/directmessages/DirectMessageMentorTest.java new file mode 100644 index 000000000..ff77aafea --- /dev/null +++ b/src/test/java/com/open/spring/mvc/directmessages/DirectMessageMentorTest.java @@ -0,0 +1,168 @@ +package com.open.spring.mvc.directmessages; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.test.util.ReflectionTestUtils; + +import com.open.spring.mvc.groups.MentorRules; +import com.open.spring.mvc.person.Person; +import com.open.spring.mvc.person.PersonJpaRepository; +import com.open.spring.mvc.reactions.MessageReactionService; + +/** + * Mentors and direct messages: a mentor can't open a direct message with a student or post in one, and a student + * can't message a mentor directly. Reading old messages and deleting your own still work, so the navbar bell and + * /dm keep answering. + */ +class DirectMessageMentorTest { + + private DirectMessageService service; + private DirectMessageConversationJpaRepository conversations; + private PersonJpaRepository people; + private DirectMessageApiController controller; + + private final Person student = person(1L, "student", "ROLE_USER", "ROLE_STUDENT"); + private final Person otherStudent = person(2L, "other", "ROLE_USER", "ROLE_STUDENT"); + private final Person mentor = person(3L, "mentor", "ROLE_USER", MentorRules.ROLE_MENTOR); + private final Person teacher = person(4L, "teacher", "ROLE_USER", "ROLE_TEACHER"); + + private static Person person(Long id, String uid, String... roles) { + Person person = new Person(); + ReflectionTestUtils.setField(person, "id", id); + person.setUid(uid); + person.setName(uid); + person.setRoles(new ArrayList<>(List.of(roles))); + return person; + } + + private static UserDetails signedIn(Person person) { + return User.withUsername(person.getUid()).password("unused").authorities("ROLE_USER").build(); + } + + private DirectMessageConversation conversation(long id, Person... participants) { + DirectMessageConversation conversation = new DirectMessageConversation(new ArrayList<>(List.of(participants))); + ReflectionTestUtils.setField(conversation, "id", id); + when(conversations.findById(id)).thenReturn(Optional.of(conversation)); + when(service.isParticipant(any(), any())).thenCallRealMethod(); + return conversation; + } + + @BeforeEach + void setUp() { + service = mock(DirectMessageService.class); + conversations = mock(DirectMessageConversationJpaRepository.class); + people = mock(PersonJpaRepository.class); + controller = new DirectMessageApiController( + service, conversations, mock(DirectMessageJpaRepository.class), people, mock(MessageReactionService.class)); + for (Person person : List.of(student, otherStudent, mentor, teacher)) { + when(people.findByUid(person.getUid())).thenReturn(person); + when(people.findById(person.getId())).thenReturn(Optional.of(person)); + } + when(service.getUnreadSummary(any())).thenReturn(new DirectMessageService.UnreadSummary(List.of(), Map.of())); + } + + private static void assertRefused(ResponseEntity response) { + assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode()); + assertEquals("mentor_no_direct_messages", ((Map) response.getBody()).get("reason")); + } + + private ResponseEntity start(Person from, Person... to) { + List ids = new ArrayList<>(); + for (Person person : to) { + ids.add(person.getId()); + } + return controller.startConversation(signedIn(from), + new DirectMessageApiController.StartConversationRequest(ids)); + } + + private ResponseEntity post(Person from, long conversationId) { + return controller.postMessage(signedIn(from), conversationId, + new DirectMessageApiController.SendMessageRequest("hi", null)); + } + + @Test + void aMentorCannotOpenADirectMessageWithAStudent() { + assertRefused(start(mentor, student)); + verify(service, never()).getOrCreateConversation(any(), any()); + } + + @Test + void aStudentCannotOpenADirectMessageWithAMentor() { + assertRefused(start(student, otherStudent, mentor)); + verify(service, never()).getOrCreateConversation(any(), any()); + } + + @Test + void aMentorCannotPostToADirectMessageWithAStudent() { + conversation(10L, mentor, student); + assertRefused(post(mentor, 10L)); + verify(service, never()).postMessage(any(), any(), anyString(), any()); + } + + @Test + void aStudentCannotPostToAConversationThatIncludesAMentor() { + conversation(11L, student, otherStudent, mentor); + assertRefused(post(student, 11L)); + verify(service, never()).postMessage(any(), any(), anyString(), any()); + } + + @Test + void editingInAConversationWithAMentorIsRefused() { + conversation(12L, student, mentor); + assertRefused(controller.editMessage(signedIn(student), 12L, 5L, + new DirectMessageApiController.SendMessageRequest("changed", null))); + verify(service, never()).editMessage(any(), any(), anyLong(), anyString()); + } + + /** Reacting is like sending, so it's refused in a conversation that includes a mentor; reading reactions still works. */ + @Test + void reactingInAConversationWithAMentorIsRefused() { + conversation(16L, student, mentor); + assertRefused(controller.addReaction(signedIn(student), 16L, 5L, "like")); + assertRefused(controller.removeReaction(signedIn(mentor), 16L, 5L, "like")); + verify(service, never()).setReaction(any(), any(), anyLong(), any(), anyBoolean()); + assertEquals(HttpStatus.OK, controller.getReactions(signedIn(student), 16L).getStatusCode()); + } + + @Test + void readingAnOldConversationWithAMentorStillWorks() { + conversation(13L, student, mentor); + when(service.getMessages(any())).thenReturn(List.of()); + assertEquals(HttpStatus.OK, controller.getMessages(signedIn(student), 13L).getStatusCode()); + assertEquals(HttpStatus.OK, controller.getMessages(signedIn(mentor), 13L).getStatusCode()); + } + + @Test + void deletingYourOwnMessageStillWorks() { + conversation(14L, student, mentor); + assertEquals(HttpStatus.NO_CONTENT, controller.deleteMessage(signedIn(student), 14L, 5L).getStatusCode()); + } + + @Test + void studentsAndTeachersStillMessageEachOther() { + DirectMessageConversation existing = conversation(15L, student, teacher); + when(service.getOrCreateConversation(any(), any())).thenReturn(existing); + when(service.postMessage(any(), any(), anyString(), any())).thenReturn(null); + assertEquals(HttpStatus.OK, start(student, teacher).getStatusCode()); + assertEquals(HttpStatus.OK, post(teacher, 15L).getStatusCode()); + } +} diff --git a/src/test/java/com/open/spring/mvc/directmessages/DirectMessageReactionTest.java b/src/test/java/com/open/spring/mvc/directmessages/DirectMessageReactionTest.java new file mode 100644 index 000000000..04197e050 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/directmessages/DirectMessageReactionTest.java @@ -0,0 +1,255 @@ +package com.open.spring.mvc.directmessages; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Optional; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.messaging.simp.SimpMessagingTemplate; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.transaction.support.TransactionSynchronization; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.open.spring.mvc.person.Person; +import com.open.spring.mvc.person.PersonJpaRepository; +import com.open.spring.mvc.push.PushNotificationService; +import com.open.spring.mvc.reactions.ChatType; +import com.open.spring.mvc.reactions.MessageReactionService; +import com.open.spring.mvc.reactions.MessageReactionService.MessageReactions; +import com.open.spring.mvc.reactions.MessageReactionService.ReactionSummary; +import com.open.spring.mvc.reactions.MessageReactionService.Reactor; +import com.open.spring.mvc.reactions.Reaction; + +/** + * Reacting to a direct message: only participants, never on a deleted message, broadcast as a + * "reactions" frame, and never a phone notification or a change to what is unread. + */ +class DirectMessageReactionTest { + + private DirectMessageConversationJpaRepository conversationRepository; + private DirectMessageJpaRepository messageRepository; + private DirectMessageReadStateJpaRepository readStateRepository; + private SimpMessagingTemplate messagingTemplate; + private PushNotificationService pushNotificationService; + private MessageReactionService reactionService; + private PersonJpaRepository personRepository; + private DirectMessageService service; + private DirectMessageApiController controller; + private Person alice; + private Person bob; + private DirectMessageConversation conversation; + private DirectMessage message; + private List summaries; + + @BeforeEach + void setUp() { + conversationRepository = mock(DirectMessageConversationJpaRepository.class); + messageRepository = mock(DirectMessageJpaRepository.class); + readStateRepository = mock(DirectMessageReadStateJpaRepository.class); + messagingTemplate = mock(SimpMessagingTemplate.class); + pushNotificationService = mock(PushNotificationService.class); + reactionService = mock(MessageReactionService.class); + personRepository = mock(PersonJpaRepository.class); + service = new DirectMessageService(conversationRepository, messageRepository, readStateRepository, + messagingTemplate, pushNotificationService, reactionService); + controller = new DirectMessageApiController(service, conversationRepository, messageRepository, + personRepository, reactionService); + + alice = person(1L, "alice"); + bob = person(2L, "bob"); + Person carol = person(3L, "carol"); + when(personRepository.findByUid("alice")).thenReturn(alice); + when(personRepository.findByUid("carol")).thenReturn(carol); + + conversation = new DirectMessageConversation(List.of(alice, bob)); + ReflectionTestUtils.setField(conversation, "id", 7L); + when(conversationRepository.findById(7L)).thenReturn(Optional.of(conversation)); + + message = new DirectMessage(conversation, bob, "did anyone finish the FRQ?"); + ReflectionTestUtils.setField(message, "id", 42L); + when(messageRepository.findByIdAndConversation(42L, conversation)).thenReturn(Optional.of(message)); + + summaries = List.of(new ReactionSummary("like", List.of(new Reactor("alice", "alice")))); + when(reactionService.forMessage(ChatType.DM, 7L, "42")).thenReturn(summaries); + when(reactionService.forMessageNow(ChatType.DM, 7L, "42")).thenReturn(summaries); + } + + @Test + void aReactionGoesOutAsAReactionsFrame() { + List result = service.setReaction(conversation, alice, 42L, Reaction.LIKE, true); + + verify(reactionService).add(ChatType.DM, 7L, "42", alice, Reaction.LIKE); + ArgumentCaptor frame = ArgumentCaptor.forClass(DirectMessageEvent.class); + verify(messagingTemplate).convertAndSend(eq("/topic/dm/7"), frame.capture()); + assertEquals("reactions", frame.getValue().getType()); + assertEquals(42L, frame.getValue().getId()); + assertEquals(7L, frame.getValue().getConversationId()); + assertEquals(summaries, frame.getValue().getReactions()); + assertEquals(summaries, result); + } + + @Test + void theFrameGoesOutAfterTheCommitWithReactionsReadThen() { + // Read after the commit, the list has a reaction someone else committed at the same time. + List fresh = List.of(new ReactionSummary("like", + List.of(new Reactor("alice", "alice"), new Reactor("bob", "bob")))); + when(reactionService.forMessageNow(ChatType.DM, 7L, "42")).thenReturn(fresh); + TransactionSynchronizationManager.initSynchronization(); + try { + service.setReaction(conversation, alice, 42L, Reaction.LIKE, true); + verify(messagingTemplate, never()).convertAndSend(eq("/topic/dm/7"), any(Object.class)); + + TransactionSynchronizationManager.getSynchronizations().forEach(TransactionSynchronization::afterCommit); + + ArgumentCaptor frame = ArgumentCaptor.forClass(DirectMessageEvent.class); + verify(messagingTemplate).convertAndSend(eq("/topic/dm/7"), frame.capture()); + assertEquals(fresh, frame.getValue().getReactions()); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + } + + @Test + void takingAReactionBackRemovesIt() { + service.setReaction(conversation, alice, 42L, Reaction.LIKE, false); + + verify(reactionService).remove(ChatType.DM, 7L, "42", alice, Reaction.LIKE); + verify(reactionService, never()).add(any(), any(), any(), any(), any()); + } + + @Test + void aReactionSendsNoPushAndLeavesReadStateAlone() { + service.setReaction(conversation, alice, 42L, Reaction.LIKE, true); + + verifyNoInteractions(pushNotificationService, readStateRepository); + } + + @Test + void aDeletedMessageCannotBeReactedTo() { + message.setDeleted(true); + + assertThrows(IllegalStateException.class, + () -> service.setReaction(conversation, alice, 42L, Reaction.LIKE, true)); + assertEquals(HttpStatus.CONFLICT, controller.addReaction(signedIn("alice"), 7L, 42L, "like").getStatusCode()); + verify(reactionService, never()).add(any(), any(), any(), any(), any()); + } + + @Test + void aMessageFromAnotherConversationIsNotFound() { + when(messageRepository.findByIdAndConversation(99L, conversation)).thenReturn(Optional.empty()); + + assertThrows(NoSuchElementException.class, + () -> service.setReaction(conversation, alice, 99L, Reaction.LIKE, true)); + assertEquals(HttpStatus.NOT_FOUND, controller.addReaction(signedIn("alice"), 7L, 99L, "like").getStatusCode()); + } + + @Test + void anUnknownReactionIs400() { + ResponseEntity response = controller.addReaction(signedIn("alice"), 7L, 42L, "thumbsup"); + + assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); + verify(reactionService, never()).add(any(), any(), any(), any(), any()); + } + + @Test + void onlyASignedInParticipantMayReactOrList() { + assertEquals(HttpStatus.UNAUTHORIZED, controller.addReaction(null, 7L, 42L, "like").getStatusCode()); + assertEquals(HttpStatus.FORBIDDEN, controller.addReaction(signedIn("carol"), 7L, 42L, "like").getStatusCode()); + assertEquals(HttpStatus.FORBIDDEN, controller.removeReaction(signedIn("carol"), 7L, 42L, "like").getStatusCode()); + assertEquals(HttpStatus.FORBIDDEN, controller.getReactions(signedIn("carol"), 7L).getStatusCode()); + verifyNoInteractions(reactionService); + } + + @Test + void theRoutesAnswerWithTheMessagesReactions() { + ResponseEntity added = controller.addReaction(signedIn("alice"), 7L, 42L, "like"); + assertEquals(HttpStatus.OK, added.getStatusCode()); + assertEquals(new MessageReactions("42", summaries), added.getBody()); + + ResponseEntity removed = controller.removeReaction(signedIn("alice"), 7L, 42L, "like"); + assertEquals(HttpStatus.OK, removed.getStatusCode()); + verify(reactionService).remove(ChatType.DM, 7L, "42", alice, Reaction.LIKE); + + Map> byMessage = Map.of("42", summaries); + when(reactionService.forChat(ChatType.DM, 7L)).thenReturn(byMessage); + ResponseEntity listed = controller.getReactions(signedIn("alice"), 7L); + assertEquals(HttpStatus.OK, listed.getStatusCode()); + assertEquals(byMessage, listed.getBody()); + } + + @Test + void deletingAMessageRemovesItsReactions() { + service.deleteMessage(conversation, bob, 42L); + + verify(reactionService).removeAllFor(ChatType.DM, 7L, "42"); + } + + @Test + void aDeleteStillGoesThroughWhenItsReactionsCantBeRemoved() { + doThrow(new DataAccessResourceFailureException("no message_reaction table")) + .when(reactionService).removeAllFor(ChatType.DM, 7L, "42"); + TransactionSynchronizationManager.initSynchronization(); + try { + service.deleteMessage(conversation, bob, 42L); + + // Nothing in the delete's own transaction touches the reactions, so they can't undo it. + verify(reactionService, never()).removeAllFor(any(), any(), any()); + assertTrue(message.isDeleted()); + ArgumentCaptor frame = ArgumentCaptor.forClass(DirectMessageEvent.class); + verify(messagingTemplate).convertAndSend(eq("/topic/dm/7"), frame.capture()); + assertEquals("deleted", frame.getValue().getType()); + + // Once it commits they're removed, and a failure there is logged, not thrown at the caller. + TransactionSynchronizationManager.getSynchronizations().forEach(TransactionSynchronization::afterCommit); + verify(reactionService).removeAllFor(ChatType.DM, 7L, "42"); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + } + + @Test + void onlyAReactionsFrameCarriesReactions() throws Exception { + ObjectMapper json = new ObjectMapper(); + String messageFrame = json.writeValueAsString( + DirectMessageEvent.builder().type("message").id(1L).conversationId(7L).body("hi").build()); + String reactionsFrame = json.writeValueAsString( + DirectMessageEvent.builder().type("reactions").id(1L).conversationId(7L).reactions(summaries).build()); + + assertFalse(messageFrame.contains("\"reactions\"")); + assertTrue(reactionsFrame.contains("\"reactions\"")); + } + + private static UserDetails signedIn(String uid) { + return User.withUsername(uid).password("unused").build(); + } + + private static Person person(Long id, String uid) { + Person person = new Person(); + ReflectionTestUtils.setField(person, "id", id); + person.setUid(uid); + person.setName(uid); + return person; + } +} diff --git a/src/test/java/com/open/spring/mvc/directmessages/DirectMessageServiceTest.java b/src/test/java/com/open/spring/mvc/directmessages/DirectMessageServiceTest.java index dbde1e3e2..2845cfedf 100644 --- a/src/test/java/com/open/spring/mvc/directmessages/DirectMessageServiceTest.java +++ b/src/test/java/com/open/spring/mvc/directmessages/DirectMessageServiceTest.java @@ -21,6 +21,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.open.spring.mvc.push.PushNotificationService; import com.open.spring.mvc.push.PushSubscriptionJpaRepository; +import com.open.spring.mvc.reactions.MessageReactionService; import org.springframework.test.util.ReflectionTestUtils; import com.open.spring.mvc.person.Person; @@ -144,7 +145,8 @@ void setUp() { }), new ObjectMapper(), "", "", ""); service = new DirectMessageService(conversationRepository, messageRepository, readStateRepository, - new SimpMessagingTemplate((message, timeout) -> true), pushNotificationService); + new SimpMessagingTemplate((message, timeout) -> true), pushNotificationService, + org.mockito.Mockito.mock(MessageReactionService.class)); } @Test 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 d2f192fc4..3d3e00ae0 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 e2fd0814f..834b7d247 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 diff --git a/src/test/java/com/open/spring/mvc/groups/ClassGroupMembershipServiceTest.java b/src/test/java/com/open/spring/mvc/groups/ClassGroupMembershipServiceTest.java index 86a41af4e..4916809ab 100644 --- a/src/test/java/com/open/spring/mvc/groups/ClassGroupMembershipServiceTest.java +++ b/src/test/java/com/open/spring/mvc/groups/ClassGroupMembershipServiceTest.java @@ -94,6 +94,14 @@ void syncMembershipsJoinsSelectedGroupsAndLeavesDeselectedCourseGroups() { assertEquals(List.of(csa, csp, csh), savedGroupBatches.get(0)); } + @Test + void isClassGroupKnowsTheConfiguredGroupsWhateverTheCase() { + assertTrue(service.isClassGroup("CSA")); + assertTrue(service.isClassGroup(" csse ")); + assertFalse(service.isClassGroup("Team Rocket")); + assertFalse(service.isClassGroup(null)); + } + @Test void syncMembershipsMapsEverySupportedClassToItsSameNamedGroup() { for (String className : List.of("CSA", "CSP", "CSH", "CSSE")) { diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatEditDeleteTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatEditDeleteTest.java new file mode 100644 index 000000000..16f5cefea --- /dev/null +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatEditDeleteTest.java @@ -0,0 +1,290 @@ +package com.open.spring.mvc.groups; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.messaging.simp.SimpMessagingTemplate; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.test.util.ReflectionTestUtils; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.open.spring.mvc.S3uploads.S3FileHandler; +import com.open.spring.mvc.person.Person; +import com.open.spring.mvc.person.PersonJpaRepository; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; +import software.amazon.awssdk.core.ResponseBytes; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectResponse; +import software.amazon.awssdk.services.s3.model.NoSuchKeyException; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.PutObjectResponse; + +/** + * Editing and deleting a message read the group's whole messages file, change it and write the + * file back. When S3 can't do either for a moment, the route must say so (503) instead of + * answering as if the change was saved. + */ +class GroupChatEditDeleteTest { + + private static final String MESSAGES_KEY = "CSA/messages-images/messages.jsonl"; + private static final String GRACE_LINE = "{\"id\":\"m2\",\"author\":\"Grace Hopper\",\"author_uid\":\"grace\"," + + "\"message\":\"Meetign at 3\",\"date\":\"2026-11-21T10:05:00Z\",\"image\":null,\"edited\":false}"; + + /** S3's objects by key. The real S3FileHandler reads and writes them through a stand-in S3 client. */ + private final Map objects = new ConcurrentHashMap<>(); + private S3Client s3; + private SimpMessagingTemplate messaging; + private GroupChatApiController controller; + + @BeforeEach + void setUp() { + useFreshStorage(); + } + + @AfterEach + void signOut() { + SecurityContextHolder.clearContext(); + } + + /** Grace's message in a bucket behind a real S3FileHandler, as S3 answers: a missing key is a 404. */ + private void useFreshStorage() { + objects.clear(); + objects.put(MESSAGES_KEY, GRACE_LINE.getBytes(StandardCharsets.UTF_8)); + s3 = mock(S3Client.class); + when(s3.getObjectAsBytes(any(GetObjectRequest.class))).thenAnswer(call -> { + byte[] bytes = objects.get(call.getArgument(0).key()); + if (bytes == null) { + throw NoSuchKeyException.builder().statusCode(404).message("The specified key does not exist.").build(); + } + return ResponseBytes.fromByteArray(GetObjectResponse.builder().build(), bytes); + }); + when(s3.putObject(any(PutObjectRequest.class), any(RequestBody.class))).thenAnswer(call -> { + try (InputStream body = call.getArgument(1).contentStreamProvider().newStream()) { + objects.put(call.getArgument(0).key(), body.readAllBytes()); + } + return PutObjectResponse.builder().build(); + }); + S3FileHandler storage = new S3FileHandler(); + ReflectionTestUtils.setField(storage, "s3Client", s3); + ReflectionTestUtils.setField(storage, "bucketName", "chat-test"); + wire(storage); + } + + /** The edit and delete routes over this storage, with Grace Hopper signed in. */ + private void wire(S3FileHandler storage) { + GroupChatService chat = new GroupChatService(storage, new ObjectMapper()); + GroupsJpaRepository groups = mock(GroupsJpaRepository.class); + messaging = mock(SimpMessagingTemplate.class); + // Built from whatever their constructors take, so a new dependency elsewhere doesn't break this test. + GroupChatRealtimeService realtime = TestBeans.build(GroupChatRealtimeService.class, chat, groups, messaging); + GroupChatReadService reads = TestBeans.build(GroupChatReadService.class, + mock(GroupChatReadStateJpaRepository.class), groups, chat); + PersonJpaRepository people = mock(PersonJpaRepository.class); + controller = TestBeans.build(GroupChatApiController.class, chat, realtime, reads, groups, people); + + Groups group = new Groups(); + group.setName("CSA"); + when(groups.findById(7L)).thenReturn(Optional.of(group)); + Person grace = new Person(); + grace.setUid("grace"); + grace.setName("Grace Hopper"); + when(people.findByUid("grace")).thenReturn(grace); + SecurityContextHolder.getContext().setAuthentication( + new UsernamePasswordAuthenticationToken("grace", null, List.of())); + } + + private ResponseEntity edit() { + GroupChatMessage request = new GroupChatMessage(); + request.setMessage("Meeting at 3"); + return controller.editMessage(7L, "m2", request); + } + + private ResponseEntity delete() { + return controller.deleteMessage(7L, "m2"); + } + + private String storedMessages() { + byte[] bytes = objects.get(MESSAGES_KEY); + return bytes == null ? null : new String(bytes, StandardCharsets.UTF_8); + } + + /** S3 fails the read of the messages file, or the upload after it. */ + private void failS3(boolean onRead, RuntimeException failure) { + if (onRead) { + doThrow(failure).when(s3).getObjectAsBytes(any(GetObjectRequest.class)); + } else { + doThrow(failure).when(s3).putObject(any(PutObjectRequest.class), any(RequestBody.class)); + } + } + + /** S3 failing for a moment, on the read or the upload, gets a 503 with Retry-After and changes nothing. */ + private void assertRefusedForNow(Supplier> change) { + for (boolean onRead : List.of(true, false)) { + for (RuntimeException failure : S3Failures.unavailable()) { + useFreshStorage(); + failS3(onRead, failure); + String what = (onRead ? "read: " : "upload: ") + failure; + + ResponseEntity response = change.get(); + + assertEquals(HttpStatus.SERVICE_UNAVAILABLE, response.getStatusCode(), what); + String retryAfter = response.getHeaders().getFirst(HttpHeaders.RETRY_AFTER); + assertTrue(retryAfter != null && retryAfter.matches("[1-9][0-9]*"), what + ", Retry-After: " + retryAfter); + assertEquals(GRACE_LINE, storedMessages(), what); + // The group isn't told about a change that wasn't saved. + verify(messaging, never()).convertAndSend(any(String.class), any(Object.class)); + } + } + } + + @Test + void anEditAndADeleteAreSavedWhenS3IsUp() throws Exception { + assertEquals(HttpStatus.OK, edit().getStatusCode()); + GroupChatMessage saved = new ObjectMapper().readValue(storedMessages(), GroupChatMessage.class); + assertEquals("Meeting at 3", saved.getMessage()); + assertTrue(saved.isEdited()); + + assertEquals(HttpStatus.OK, delete().getStatusCode()); + assertEquals("", storedMessages()); + } + + @Test + void anEditAnswersWithTheMessagesItSavedEvenWhenTheNextReadFails() { + // The first read of S3 works, and every read after it fails as a throttle. + AtomicInteger reads = new AtomicInteger(); + doAnswer(call -> { + if (reads.incrementAndGet() > 1) { + throw S3Failures.unavailable().get(0); + } + byte[] bytes = objects.get(call.getArgument(0).key()); + return ResponseBytes.fromByteArray(GetObjectResponse.builder().build(), bytes); + }).when(s3).getObjectAsBytes(any(GetObjectRequest.class)); + + ResponseEntity response = edit(); + + assertEquals(HttpStatus.OK, response.getStatusCode()); + List answered = (List) response.getBody(); + assertEquals(1, answered.size(), "answered: " + answered); + GroupChatMessage saved = (GroupChatMessage) answered.get(0); + assertEquals("Meeting at 3", saved.getMessage()); + assertTrue(saved.isEdited()); + } + + @Test + void aDeleteOfAMessageThatIsntSavedAnswers404AndTellsNoOne() { + ResponseEntity response = controller.deleteMessage(7L, "not-a-saved-id"); + + assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode()); + assertEquals(GRACE_LINE, storedMessages()); + // Telling the group would take the message off everyone's screen. + verify(messaging, never()).convertAndSend(any(String.class), any(Object.class)); + } + + @Test + void withoutS3SettingsADeleteAnswers404AndTellsNoOne() { + // A local server without S3 saves nothing, so there's no message to delete, whoever sent it. + wire(new S3FileHandler()); + + ResponseEntity response = delete(); + + assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode()); + verify(messaging, never()).convertAndSend(any(String.class), any(Object.class)); + } + + @Test + void anEditS3CantReadOrSaveForAMomentAnswers503AndChangesNothing() { + assertRefusedForNow(this::edit); + } + + @Test + void aDeleteS3CantReadOrSaveForAMomentAnswers503AndKeepsTheMessage() { + assertRefusedForNow(this::delete); + } + + @Test + void anEditOrDeleteS3RefusesOrABugHereIsNotOfferedARetry() { + List>> changes = List.of(this::edit, this::delete); + for (Supplier> change : changes) { + for (boolean onRead : List.of(true, false)) { + for (RuntimeException fault : S3Failures.refusalsAndBugs()) { + useFreshStorage(); + failS3(onRead, fault); + String what = (onRead ? "read: " : "upload: ") + fault; + + ResponseEntity response = change.get(); + + assertFalse(response.getStatusCode().is2xxSuccessful(), what); + assertNotEquals(HttpStatus.SERVICE_UNAVAILABLE, response.getStatusCode(), what); + assertNull(response.getHeaders().getFirst(HttpHeaders.RETRY_AFTER), what); + assertEquals(GRACE_LINE, storedMessages(), what); + verify(messaging, never()).convertAndSend(any(String.class), any(Object.class)); + } + } + } + } + + @Test + void everyReadOrUploadThatFailsIsLoggedWithTheGroupAndTheCause() { + Logger logger = (Logger) LoggerFactory.getLogger(GroupChatService.class); + ListAppender warnings = new ListAppender<>(); + warnings.start(); + logger.addAppender(warnings); + try { + List failures = new ArrayList<>(S3Failures.unavailable()); + failures.addAll(S3Failures.refusalsAndBugs()); + for (boolean onRead : List.of(true, false)) { + for (RuntimeException failure : failures) { + useFreshStorage(); + failS3(onRead, failure); + warnings.list.clear(); + + edit(); + + String what = (onRead ? "read: " : "upload: ") + failure; + // The route answers some of these without logging, so the service logs each one. + assertTrue(warnings.list.stream().anyMatch(warning -> + warning.getFormattedMessage().contains("CSA") + && warning.getThrowableProxy() != null + && failure.getClass().getName().equals(warning.getThrowableProxy().getClassName())), + what + " was not logged: " + warnings.list); + } + } + } finally { + logger.detachAppender(warnings); + warnings.stop(); + } + } +} diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatFilesTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatFilesTest.java index 6953ce1fb..ea3296be9 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupChatFilesTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatFilesTest.java @@ -40,7 +40,9 @@ import com.open.spring.mvc.S3uploads.S3FileHandler; import com.open.spring.mvc.person.Person; import com.open.spring.mvc.person.PersonJpaRepository; +import com.open.spring.mvc.reactions.MessageReactionService; +import software.amazon.awssdk.awscore.exception.AwsErrorDetails; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.services.s3.model.S3Exception; @@ -61,6 +63,12 @@ public String uploadFile(String base64Data, String filename, String uid) { return filename; } + // Stores the same way, so a test that slows uploadFile slows this too. + @Override + public String uploadFileOrThrow(String base64Data, String filename, String uid) { + return uploadFile(base64Data, filename, uid); + } + @Override public String decodeFile(String uid, String filename) { byte[] bytes = objects.get(uid + "/" + filename); @@ -90,6 +98,36 @@ public Map listFileSizes(String prefix) { } } + /** + * S3 that answers the check but fails the write of a shared file's bytes while `failure` is + * set, the way S3FileHandler sees it: uploadFile swallows the failure and answers null, and + * uploadFileOrThrow throws it. Other writes, like the "shared by" record, still go through. + */ + static class SharedFileWritesFail extends InMemoryStorage { + RuntimeException failure; + + SharedFileWritesFail(RuntimeException failure) { + this.failure = failure; + } + + private boolean failing(String filename) { + return failure != null && filename.startsWith("shared-files/"); + } + + @Override + public String uploadFile(String base64Data, String filename, String uid) { + return failing(filename) ? null : super.uploadFile(base64Data, filename, uid); + } + + @Override + public String uploadFileOrThrow(String base64Data, String filename, String uid) { + if (failing(filename)) { + throw failure; + } + return super.uploadFileOrThrow(base64Data, filename, uid); + } + } + private InMemoryStorage storage; private SimpMessagingTemplate messaging; private GroupChatApiController controller; @@ -104,10 +142,11 @@ private void useStorage(InMemoryStorage store) { GroupChatService chat = new GroupChatService(storage, new ObjectMapper()); GroupsJpaRepository groups = mock(GroupsJpaRepository.class); messaging = mock(SimpMessagingTemplate.class); - GroupChatRealtimeService realtime = new GroupChatRealtimeService(chat, groups, messaging); + GroupChatRealtimeService realtime = new GroupChatRealtimeService(chat, groups, messaging, mock(MessageReactionService.class)); GroupChatReadService reads = new GroupChatReadService(mock(GroupChatReadStateJpaRepository.class), groups, chat); PersonJpaRepository people = mock(PersonJpaRepository.class); - controller = new GroupChatApiController(chat, realtime, reads, groups, people); + controller = new GroupChatApiController(chat, realtime, reads, groups, people, mock(MessageReactionService.class), + new MentorAccess(groups, mock(ClassGroupMembershipService.class))); Groups group = new Groups(); group.setName("CSA"); @@ -323,6 +362,67 @@ public boolean fileExistsOrThrow(String uid, String filename) { } } + @Test + void aWriteThatFailsForAMomentIsA503AndSharesNothing() { + // The path is free, but S3 throttled the write (503 Slow Down), couldn't be reached, or + // timed out the request (its RequestTimeout comes as a 400). + List failures = List.of( + (S3Exception) S3Exception.builder().statusCode(503).message("Slow Down").build(), + SdkClientException.create("Unable to execute HTTP request: Read timed out"), + (S3Exception) S3Exception.builder().statusCode(400) + .awsErrorDetails(AwsErrorDetails.builder().errorCode("RequestTimeout").build()) + .message("Your socket connection to the server was not read from or written to within the timeout period.") + .build()); + for (RuntimeException failure : failures) { + useStorage(new SharedFileWritesFail(failure)); + + ResponseEntity response = upload("notes.md", "Grace's notes"); + + assertEquals(HttpStatus.SERVICE_UNAVAILABLE, response.getStatusCode(), failure.toString()); + String retryAfter = response.getHeaders().getFirst(HttpHeaders.RETRY_AFTER); + assertTrue(retryAfter != null && retryAfter.matches("[1-9][0-9]*"), "Retry-After: " + retryAfter); + @SuppressWarnings("unchecked") + Map body = (Map) response.getBody(); + assertEquals("notes.md", body.get("filename")); + // No file, no "shared by" record, and no frame telling the group a file arrived. + assertTrue(storage.objects.isEmpty(), "stored: " + storage.objects.keySet()); + verify(messaging, never()).convertAndSend(any(String.class), any(Object.class)); + } + } + + @Test + void aWriteS3RefusesOrABugIsStillA500() { + // S3 refusing the write (no permission, a bad request) or a fault in this server: trying + // again won't help, so none is a 503. + List faults = List.of( + new NullPointerException("a bug here, not S3"), + (S3Exception) S3Exception.builder().statusCode(403).message("Access Denied").build(), + (S3Exception) S3Exception.builder().statusCode(400) + .awsErrorDetails(AwsErrorDetails.builder().errorCode("InvalidRequest").build()) + .message("Invalid Request") + .build()); + for (RuntimeException fault : faults) { + useStorage(new SharedFileWritesFail(fault)); + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, upload("notes.md", "Grace's notes").getStatusCode(), fault.toString()); + } + } + + @Test + void aShareThatFailedForAMomentGoesThroughWhenTriedAgain() { + // What the 503 promises: once S3 takes writes again, the same share works, instead of + // finding the path still held by the upload that failed. + SharedFileWritesFail s3 = new SharedFileWritesFail( + SdkClientException.create("Unable to execute HTTP request: Connect timed out")); + useStorage(s3); + assertEquals(HttpStatus.SERVICE_UNAVAILABLE, upload("notes.md", "Grace's notes").getStatusCode()); + + s3.failure = null; + + assertEquals(HttpStatus.OK, upload("notes.md", "Grace's notes").getStatusCode()); + assertArrayEquals("Grace's notes".getBytes(StandardCharsets.UTF_8), storage.objects.get("CSA/shared-files/notes.md")); + } + @Test void aPathBeingWrittenInOneGroupDoesNotHoldUpALookAlikeInAnother() throws Exception { // "a/b" sharing "c" and "a" sharing "b/c" read the same if group and path are joined. diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatMentorTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatMentorTest.java new file mode 100644 index 000000000..57051c82f --- /dev/null +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatMentorTest.java @@ -0,0 +1,233 @@ +package com.open.spring.mvc.groups; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.test.util.ReflectionTestUtils; + +import com.open.spring.mvc.person.Person; +import com.open.spring.mvc.person.PersonJpaRepository; +import com.open.spring.mvc.reactions.MessageReactionService; + +/** + * A mentor reads, posts and shares files only in a group they were added to, with at least two members who aren't + * mentors, and never in a class group. Everyone else's group chat works as before. + */ +class GroupChatMentorTest { + + private GroupChatService chat; + private GroupChatRealtimeService realtime; + private GroupsJpaRepository groups; + private ClassGroupMembershipService classGroups; + private PersonJpaRepository people; + private GroupChatApiController controller; + + private final Person student = MentorRulesTest.student(1); + private final Person teammate = MentorRulesTest.student(2); + private final Person mentor = MentorRulesTest.mentor(3); + private final Person otherMentor = MentorRulesTest.mentor(4); + private final Person outsider = MentorRulesTest.student(5); + + private static final long TEAM = 7L; + private static final long SOLO = 8L; + private static final long CLASS = 9L; + + private final Map made = new HashMap<>(); + + private void group(long id, String name, boolean classGroup, Person... members) { + Groups group = new Groups(); + ReflectionTestUtils.setField(group, "id", id); + group.setName(name); + when(groups.findById(id)).thenReturn(Optional.of(group)); + when(groups.findMembersOf(id)).thenReturn(List.of(members)); + when(classGroups.isClassGroup(name)).thenReturn(classGroup); + made.put(id, group); + } + + /** The groups person is in, as the repository lists them. */ + private void groupsOf(Person person, long... ids) { + when(groups.findGroupsByPersonId(person.getId())).thenReturn(Arrays.stream(ids).mapToObj(made::get).toList()); + } + + @BeforeEach + void setUp() { + chat = mock(GroupChatService.class); + realtime = mock(GroupChatRealtimeService.class); + groups = mock(GroupsJpaRepository.class); + classGroups = mock(ClassGroupMembershipService.class); + people = mock(PersonJpaRepository.class); + GroupChatReadService reads = + new GroupChatReadService(mock(GroupChatReadStateJpaRepository.class), groups, chat); + controller = new GroupChatApiController(chat, realtime, reads, groups, people, + mock(MessageReactionService.class), new MentorAccess(groups, classGroups)); + for (Person person : List.of(student, teammate, mentor, otherMentor, outsider)) { + when(people.findByUid(person.getUid())).thenReturn(person); + } + group(TEAM, "Team Rocket", false, student, teammate, mentor); + group(SOLO, "Just Us", false, student, mentor); + group(CLASS, "CSA", true, student, teammate, mentor); + when(chat.getMessages(anyString())).thenReturn(List.of()); + } + + @AfterEach + void signOut() { + SecurityContextHolder.clearContext(); + } + + private void signIn(Person person) { + SecurityContextHolder.getContext().setAuthentication( + new UsernamePasswordAuthenticationToken(person.getUid(), null, List.of())); + } + + private static void assertRefused(String reason, ResponseEntity response) { + assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode()); + assertEquals(reason, ((Map) response.getBody()).get("reason")); + } + + @SuppressWarnings("unchecked") + private static Map unreadIn(ResponseEntity response) { + assertEquals(HttpStatus.OK, response.getStatusCode()); + return (Map) ((Map) response.getBody()).get("unreadByGroup"); + } + + private GroupChatMessage fromTeammate() { + return new GroupChatMessage(teammate.getName(), teammate.getUid(), "hi", "2026-11-25T00:00:01Z", null); + } + + private static GroupChatMessage text(String body) { + GroupChatMessage message = new GroupChatMessage(); + message.setMessage(body); + return message; + } + + @Test + void aMentorWhoIsNotAMemberIsRefusedEverywhere() { + signIn(otherMentor); + String reason = "mentor_not_in_group"; + assertRefused(reason, controller.getMessages(TEAM)); + assertRefused(reason, controller.postMessage(TEAM, text("hello"))); + assertRefused(reason, controller.editMessage(TEAM, "m1", text("changed"))); + assertRefused(reason, controller.deleteMessage(TEAM, "m1")); + assertRefused(reason, controller.markRead(TEAM)); + assertRefused(reason, controller.getSharedFiles(TEAM)); + assertRefused(reason, controller.uploadSharedFile(TEAM, + new GroupChatApiController.FileUploadRequest("notes.txt", "aGk="))); + assertRefused(reason, controller.getSharedFileIndex(TEAM)); + assertRefused(reason, controller.getSharedFileContent(TEAM, "notes.txt")); + verify(realtime, never()).publishMessage(anyLong(), anyString(), any(), any()); + verify(realtime, never()).publishFile(anyLong(), any(), anyString(), anyString()); + verify(chat, never()).getMessages(anyString()); + verify(chat, never()).sharedFileIndex(anyString()); + verify(chat, never()).readSharedFile(anyString(), anyString()); + } + + /** Reactions are part of a group's chat, so they follow the same mentor rules. */ + @Test + void aMentorWhoIsNotAMemberCannotSeeOrChangeReactions() { + signIn(otherMentor); + String reason = "mentor_not_in_group"; + String message = "0f8fad5b-d9cb-469f-a165-70867728950e"; + assertRefused(reason, controller.getReactions(TEAM)); + assertRefused(reason, controller.addReaction(TEAM, message, "like")); + assertRefused(reason, controller.removeReaction(TEAM, message, "like")); + verify(realtime, never()).setReaction(anyLong(), any(), anyString(), any(), anyBoolean()); + } + + @Test + void aMemberMentorWithATeamOfTwoReacts() { + signIn(mentor); + assertEquals(HttpStatus.OK, controller.getReactions(TEAM).getStatusCode()); + assertEquals(HttpStatus.OK, + controller.addReaction(TEAM, "0f8fad5b-d9cb-469f-a165-70867728950e", "like").getStatusCode()); + } + + @Test + void aMemberMentorWithATeamOfTwoReadsAndPosts() { + signIn(mentor); + assertEquals(HttpStatus.OK, controller.getMessages(TEAM).getStatusCode()); + assertEquals(HttpStatus.OK, controller.postMessage(TEAM, text("hello team")).getStatusCode()); + verify(realtime).publishMessage(any(), any(), any(), any()); + } + + @Test + void aMentorWithATeamOfOneIsRefused() { + signIn(mentor); + assertRefused("mentor_team_too_small", controller.getMessages(SOLO)); + assertRefused("mentor_team_too_small", controller.postMessage(SOLO, text("just us"))); + assertRefused("mentor_team_too_small", controller.getSharedFileIndex(SOLO)); + assertRefused("mentor_team_too_small", controller.getSharedFileContent(SOLO, "notes.txt")); + } + + @Test + void aMemberMentorWithATeamOfTwoListsAndDownloadsTheTeamsFiles() { + when(chat.readSharedFile("Team Rocket", "notes.txt")).thenReturn("hi".getBytes(StandardCharsets.UTF_8)); + signIn(mentor); + assertEquals(HttpStatus.OK, controller.getSharedFileIndex(TEAM).getStatusCode()); + ResponseEntity file = controller.getSharedFileContent(TEAM, "notes.txt"); + assertEquals(HttpStatus.OK, file.getStatusCode()); + assertArrayEquals("hi".getBytes(StandardCharsets.UTF_8), (byte[]) file.getBody()); + } + + @Test + void aMentorInAClassGroupIsRefused() { + signIn(mentor); + assertRefused("mentor_class_group", controller.getMessages(CLASS)); + } + + @Test + void aStudentWhoIsNotAMemberStillReadsAsBefore() { + signIn(outsider); + assertEquals(HttpStatus.OK, controller.getMessages(TEAM).getStatusCode()); + assertEquals(HttpStatus.OK, controller.getSharedFileIndex(TEAM).getStatusCode()); + verify(groups, never()).findMembersOf(anyLong()); + } + + @Test + void aMentorSeesOnlyTheirOwnChatAnalytics() { + when(groups.findGroupsByPersonId(anyLong())).thenReturn(List.of()); + when(people.findById(1L)).thenReturn(Optional.of(student)); + when(people.findById(3L)).thenReturn(Optional.of(mentor)); + when(chat.getUserAnalytics(anyString(), any())).thenReturn(new java.util.HashMap<>()); + signIn(mentor); + assertRefused("mentor_cannot_manage", controller.getUserAnalytics(1L)); + assertEquals(HttpStatus.OK, controller.getUserAnalytics(3L).getStatusCode()); + } + + @Test + void aMentorsUnreadCountLeavesOutTheGroupsTheyMayNotUse() { + groupsOf(mentor, TEAM, SOLO, CLASS); + when(chat.getMessages(anyString())).thenReturn(List.of(fromTeammate())); + signIn(mentor); + assertEquals(Map.of(TEAM, 1L), unreadIn(controller.getUnread())); + } + + @Test + void everyoneElsesUnreadCountCoversAllTheirGroups() { + groupsOf(student, TEAM, SOLO, CLASS); + when(chat.getMessages(anyString())).thenReturn(List.of(fromTeammate())); + signIn(student); + assertEquals(Map.of(TEAM, 1L, SOLO, 1L, CLASS, 1L), unreadIn(controller.getUnread())); + } +} diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatMessageJsonTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatMessageJsonTest.java index 175540a0e..068ed7cf3 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupChatMessageJsonTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatMessageJsonTest.java @@ -54,14 +54,15 @@ void messageIsWrittenWithAuthorNotName() throws Exception { @Test void addingAMessageKeepsTheSenderOfOlderLines() throws Exception { S3FileHandler s3 = mock(S3FileHandler.class); - when(s3.decodeFile("CSA", "messages-images/messages.jsonl")).thenReturn( + when(s3.isConfigured()).thenReturn(true); + when(s3.decodeFileOrThrow("CSA", "messages-images/messages.jsonl")).thenReturn( Base64.getEncoder().encodeToString(SAVED_BEFORE_RENAME.getBytes(StandardCharsets.UTF_8))); GroupChatService service = new GroupChatService(s3, objectMapper); service.addMessage("CSA", new GroupChatMessage("Grace Hopper", "hop", "hello", "2026-10-30T17:00:00Z", null)); ArgumentCaptor uploaded = ArgumentCaptor.forClass(String.class); - verify(s3).uploadFile(uploaded.capture(), eq("messages-images/messages.jsonl"), eq("CSA")); + verify(s3).uploadFileOrThrow(uploaded.capture(), eq("messages-images/messages.jsonl"), eq("CSA")); String[] lines = new String(Base64.getDecoder().decode(uploaded.getValue()), StandardCharsets.UTF_8).split("\n"); assertEquals("Ada Lovelace", objectMapper.readTree(lines[0]).get("author").asText()); assertEquals("Grace Hopper", objectMapper.readTree(lines[1]).get("author").asText()); diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatMessagesFileTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatMessagesFileTest.java new file mode 100644 index 000000000..4bd465241 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatMessagesFileTest.java @@ -0,0 +1,144 @@ +package com.open.spring.mvc.groups; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.open.spring.mvc.S3uploads.S3FileHandler; + +/** + * A group's messages file can hold a line that doesn't read as a message, and a message can + * fail to be written. Neither may quietly lose a message when the file is saved again. + */ +class GroupChatMessagesFileTest { + + private static final String MESSAGES_KEY = "CSA/messages-images/messages.jsonl"; + private static final String ADA_LINE = "{\"id\":\"m1\",\"author\":\"Ada Lovelace\",\"author_uid\":\"ada\"," + + "\"message\":\"Meeting at 3\",\"date\":\"2026-11-21T10:00:00Z\",\"image\":null,\"edited\":false}"; + private static final String GRACE_LINE = "{\"id\":\"m2\",\"author\":\"Grace Hopper\",\"author_uid\":\"grace\"," + + "\"message\":\"Meetign at 3\",\"date\":\"2026-11-21T10:05:00Z\",\"image\":null,\"edited\":false}"; + // A line that isn't a whole message: S3 holds it, but it doesn't read as JSON. + private static final String UNREADABLE = "{\"id\":\"m0\",\"author\":\"Ada Lovelace\",\"message\":\"Agenda for"; + + /** A configured S3 kept in a map, whose reads and writes never fail. */ + static class InMemoryS3 extends S3FileHandler { + final Map objects = new ConcurrentHashMap<>(); + + @Override + public boolean isConfigured() { + return true; + } + + @Override + public String decodeFile(String uid, String filename) { + return objects.get(uid + "/" + filename); + } + + @Override + public String decodeFileOrThrow(String uid, String filename) { + return decodeFile(uid, filename); + } + + @Override + public String uploadFileOrThrow(String base64Data, String filename, String uid) { + objects.put(uid + "/" + filename, base64Data); + return filename; + } + } + + private final ObjectMapper json = new ObjectMapper(); + private InMemoryS3 storage; + private GroupChatService chat; + + @BeforeEach + void setUp() { + storage = new InMemoryS3(); + chat = new GroupChatService(storage, json); + } + + private void store(String... lines) { + String jsonl = String.join("\n", lines); + storage.objects.put(MESSAGES_KEY, Base64.getEncoder().encodeToString(jsonl.getBytes(StandardCharsets.UTF_8))); + } + + private List storedLines() { + String base64 = storage.objects.get(MESSAGES_KEY); + return List.of(new String(Base64.getDecoder().decode(base64), StandardCharsets.UTF_8).split("\n")); + } + + private String text(String line) throws Exception { + return json.readValue(line, GroupChatMessage.class).getMessage(); + } + + @Test + void anUnreadableLineIsKeptWhereItWasWhenAMessageIsSent() throws Exception { + store(ADA_LINE, UNREADABLE, GRACE_LINE); + + chat.addMessage("CSA", new GroupChatMessage("Grace Hopper", "grace", "Works for me", "2026-11-21T10:06:00Z", null)); + + List lines = storedLines(); + assertEquals(4, lines.size(), lines.toString()); + assertEquals("Meeting at 3", text(lines.get(0))); + assertEquals(UNREADABLE, lines.get(1)); + assertEquals("Meetign at 3", text(lines.get(2))); + assertEquals("Works for me", text(lines.get(3))); + } + + @Test + void anUnreadableLineIsKeptWhenAMessageIsEditedOrDeleted() throws Exception { + store(ADA_LINE, UNREADABLE, GRACE_LINE); + + assertTrue(chat.editMessage("CSA", "m2", "Meeting at 3", "grace").isPresent()); + List lines = storedLines(); + assertEquals(3, lines.size(), lines.toString()); + assertEquals(List.of("Meeting at 3", UNREADABLE, "Meeting at 3"), + List.of(text(lines.get(0)), lines.get(1), text(lines.get(2)))); + + assertTrue(chat.deleteMessage("CSA", "m1", "ada")); + lines = storedLines(); + assertEquals(2, lines.size(), lines.toString()); + assertEquals(UNREADABLE, lines.get(0)); + assertEquals("Meeting at 3", text(lines.get(1))); + } + + @Test + void loadingTheChatSkipsAnUnreadableLine() { + store(ADA_LINE, UNREADABLE, GRACE_LINE); + + List texts = chat.getMessages("CSA").stream().map(GroupChatMessage::getMessage).toList(); + + assertEquals(List.of("Meeting at 3", "Meetign at 3"), texts); + } + + @Test + void aMessageThatCantBeWrittenRefusesTheChangeAndKeepsTheFile() { + ObjectMapper failsOnOneMessage = new ObjectMapper() { + @Override + public String writeValueAsString(Object value) throws JsonProcessingException { + if (value instanceof GroupChatMessage message && "can't write me".equals(message.getMessage())) { + throw new JsonMappingException(null, "can't write this message"); + } + return super.writeValueAsString(value); + } + }; + chat = new GroupChatService(storage, failsOnOneMessage); + store(ADA_LINE); + + assertThrows(RuntimeException.class, () -> chat.addMessage("CSA", + new GroupChatMessage("Grace Hopper", "grace", "can't write me", "2026-11-21T10:06:00Z", null))); + + assertEquals(List.of(ADA_LINE), storedLines()); + } +} diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatReactionTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatReactionTest.java new file mode 100644 index 000000000..5918e071d --- /dev/null +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatReactionTest.java @@ -0,0 +1,208 @@ +package com.open.spring.mvc.groups; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.Optional; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.messaging.simp.SimpMessagingTemplate; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.test.util.ReflectionTestUtils; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.open.spring.mvc.S3uploads.S3FileHandler; +import com.open.spring.mvc.person.Person; +import com.open.spring.mvc.person.PersonJpaRepository; +import com.open.spring.mvc.reactions.ChatType; +import com.open.spring.mvc.reactions.MessageReactionService; +import com.open.spring.mvc.reactions.MessageReactionService.MessageReactions; +import com.open.spring.mvc.reactions.MessageReactionService.ReactionSummary; +import com.open.spring.mvc.reactions.MessageReactionService.Reactor; +import com.open.spring.mvc.reactions.Reaction; + +/** + * Reacting to a group chat message: signed in, a real message id, broadcast as a + * reactionsServer frame, and never a read or write of the group's S3 message file. + */ +class GroupChatReactionTest { + + private static final String MESSAGE_ID = "3f2c8a8e-5b1d-4c7e-9a52-8f0e6d4b2a10"; + + private S3FileHandler storage; + private GroupChatService chat; + private SimpMessagingTemplate messaging; + private MessageReactionService reactionService; + private GroupChatRealtimeService realtime; + private GroupChatApiController controller; + private Person ada; + private List summaries; + + @BeforeEach + void setUp() { + storage = mock(S3FileHandler.class); + chat = spy(new GroupChatService(storage, new ObjectMapper())); + GroupsJpaRepository groups = mock(GroupsJpaRepository.class); + messaging = mock(SimpMessagingTemplate.class); + reactionService = mock(MessageReactionService.class); + realtime = new GroupChatRealtimeService(chat, groups, messaging, reactionService); + PersonJpaRepository people = mock(PersonJpaRepository.class); + GroupChatReadService reads = new GroupChatReadService(mock(GroupChatReadStateJpaRepository.class), groups, chat); + controller = new GroupChatApiController(chat, realtime, reads, groups, people, reactionService, + new MentorAccess(groups, mock(ClassGroupMembershipService.class))); + + Groups group = spy(new Groups()); + when(group.getId()).thenReturn(3L); + group.setName("Team Three"); + when(groups.findById(3L)).thenReturn(Optional.of(group)); + + ada = new Person(); + ReflectionTestUtils.setField(ada, "id", 1L); + ada.setUid("ada"); + ada.setName("Ada"); + when(people.findByUid("ada")).thenReturn(ada); + + summaries = List.of(new ReactionSummary("love", List.of(new Reactor("ada", "Ada")))); + when(reactionService.forMessage(ChatType.GROUP, 3L, MESSAGE_ID)).thenReturn(summaries); + } + + @AfterEach + void clearAuthentication() { + SecurityContextHolder.clearContext(); + } + + @Test + void aReactionGoesOutAsAReactionsServerFrame() { + List result = realtime.setReaction(3L, ada, MESSAGE_ID, Reaction.LOVE, true); + + verify(reactionService).add(ChatType.GROUP, 3L, MESSAGE_ID, ada, Reaction.LOVE); + ArgumentCaptor frame = ArgumentCaptor.forClass(GroupChatEvent.class); + verify(messaging).convertAndSend(eq("/topic/group/3"), frame.capture()); + assertEquals("reactionsServer", frame.getValue().getContext()); + assertEquals(3L, frame.getValue().getGroupId()); + assertEquals(MESSAGE_ID, frame.getValue().getMessageId()); + assertEquals(summaries, frame.getValue().getReactions()); + assertEquals(summaries, result); + } + + @Test + void aReactionNeverTouchesTheGroupsFile() { + signIn("ada"); + + ResponseEntity added = controller.addReaction(3L, MESSAGE_ID, "love"); + ResponseEntity removed = controller.removeReaction(3L, MESSAGE_ID, "love"); + when(reactionService.forChat(ChatType.GROUP, 3L)).thenReturn(java.util.Map.of(MESSAGE_ID, summaries)); + ResponseEntity listed = controller.getReactions(3L); + + assertEquals(HttpStatus.OK, added.getStatusCode()); + assertEquals(new MessageReactions(MESSAGE_ID, summaries), added.getBody()); + assertEquals(HttpStatus.OK, removed.getStatusCode()); + verify(reactionService).remove(ChatType.GROUP, 3L, MESSAGE_ID, ada, Reaction.LOVE); + assertEquals(java.util.Map.of(MESSAGE_ID, summaries), listed.getBody()); + verifyNoInteractions(storage); + } + + @Test + void signedOutIs401() { + assertEquals(HttpStatus.UNAUTHORIZED, controller.addReaction(3L, MESSAGE_ID, "love").getStatusCode()); + assertEquals(HttpStatus.UNAUTHORIZED, controller.removeReaction(3L, MESSAGE_ID, "love").getStatusCode()); + assertEquals(HttpStatus.UNAUTHORIZED, controller.getReactions(3L).getStatusCode()); + verifyNoInteractions(reactionService); + } + + @Test + void aBadMessageIdIs400() { + signIn("ada"); + + assertEquals(HttpStatus.BAD_REQUEST, controller.addReaction(3L, "not-a-message", "love").getStatusCode()); + assertEquals(HttpStatus.BAD_REQUEST, controller.addReaction(3L, "../shared-files", "love").getStatusCode()); + // Saved ids are lowercase; an uppercase one would match some lookups and not others on MySQL. + assertEquals(HttpStatus.BAD_REQUEST, controller.addReaction(3L, MESSAGE_ID.toUpperCase(), "love").getStatusCode()); + verify(reactionService, never()).add(any(), any(), any(), any(), any()); + } + + @Test + void anUnknownReactionIs400() { + signIn("ada"); + + assertEquals(HttpStatus.BAD_REQUEST, controller.addReaction(3L, MESSAGE_ID, "thumbsup").getStatusCode()); + verify(reactionService, never()).add(any(), any(), any(), any(), any()); + } + + @Test + void anUnknownGroupIs404() { + signIn("ada"); + + assertEquals(HttpStatus.NOT_FOUND, controller.addReaction(99L, MESSAGE_ID, "love").getStatusCode()); + assertEquals(HttpStatus.NOT_FOUND, controller.getReactions(99L).getStatusCode()); + verifyNoInteractions(reactionService); + } + + @Test + void deletingAMessageRemovesItsReactions() { + GroupChatMessage saved = new GroupChatMessage("Ada", "ada", "hello", "2026-11-21T00:00:00Z", null); + // The chat's delete reads S3 itself and says whether it found the message. + doReturn(true).when(chat).deleteMessage("Team Three", saved.getId(), "ada"); + + realtime.deleteMessage(3L, saved.getId(), "ada"); + + verify(reactionService).removeAllFor(ChatType.GROUP, 3L, saved.getId()); + } + + @Test + void deletingAMessageThatIsntSavedKeepsItsReactions() { + doReturn(false).when(chat).deleteMessage("Team Three", MESSAGE_ID, "ada"); + + assertFalse(realtime.deleteMessage(3L, MESSAGE_ID, "ada")); + + verify(reactionService, never()).removeAllFor(any(), any(), any()); + } + + @Test + void aDeleteStillTellsTheGroupWhenItsReactionsCantBeRemoved() { + doReturn(true).when(chat).deleteMessage("Team Three", MESSAGE_ID, "ada"); + doThrow(new DataAccessResourceFailureException("no message_reaction table")) + .when(reactionService).removeAllFor(ChatType.GROUP, 3L, MESSAGE_ID); + + assertTrue(realtime.deleteMessage(3L, MESSAGE_ID, "ada")); + + ArgumentCaptor frame = ArgumentCaptor.forClass(GroupChatEvent.class); + verify(messaging).convertAndSend(eq("/topic/group/3"), frame.capture()); + assertEquals("deleteMessageServer", frame.getValue().getContext()); + } + + @Test + void onlyAReactionsFrameCarriesReactions() throws Exception { + ObjectMapper json = new ObjectMapper(); + String messageFrame = json.writeValueAsString(GroupChatEvent.builder() + .context("sendMessageServer").groupId(3L).messageId(MESSAGE_ID).message("hi").build()); + String reactionsFrame = json.writeValueAsString(GroupChatEvent.builder() + .context("reactionsServer").groupId(3L).messageId(MESSAGE_ID).reactions(summaries).build()); + + assertFalse(messageFrame.contains("\"reactions\"")); + assertTrue(reactionsFrame.contains("\"reactions\"")); + } + + private void signIn(String uid) { + SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(uid, null, List.of())); + } +} diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatRegressionTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatRegressionTest.java index c310e3011..533eb50bc 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupChatRegressionTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatRegressionTest.java @@ -5,6 +5,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -13,14 +14,18 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; +import java.util.Base64; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.stream.Collectors; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; import org.springframework.http.HttpStatus; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; @@ -30,8 +35,11 @@ import com.open.spring.mvc.S3uploads.S3FileHandler; import com.open.spring.mvc.person.Person; import com.open.spring.mvc.person.PersonJpaRepository; +import com.open.spring.mvc.reactions.MessageReactionService; class GroupChatRegressionTest { + private static final String MESSAGES_FILE = "messages-images/messages.jsonl"; + private S3FileHandler storage; private GroupChatService chat; private GroupsJpaRepository groups; @@ -50,9 +58,10 @@ void setUp() { groups = mock(GroupsJpaRepository.class); readStates = mock(GroupChatReadStateJpaRepository.class); reads = new GroupChatReadService(readStates, groups, chat); - realtime = new GroupChatRealtimeService(chat, groups, mock(SimpMessagingTemplate.class)); + realtime = new GroupChatRealtimeService(chat, groups, mock(SimpMessagingTemplate.class), mock(MessageReactionService.class)); PersonJpaRepository people = mock(PersonJpaRepository.class); - controller = new GroupChatApiController(chat, realtime, reads, groups, people); + controller = new GroupChatApiController(chat, realtime, reads, groups, people, mock(MessageReactionService.class), + new MentorAccess(groups, mock(ClassGroupMembershipService.class))); Groups group = spy(new Groups()); when(group.getId()).thenReturn(7L); @@ -74,6 +83,49 @@ void setUp() { "2026-10-30T00:00:00Z", null); messages = new ArrayList<>(List.of(message)); doReturn(messages).when(chat).getMessages("CSA"); + // Edits and deletes read the messages file strictly and save it back, so S3 stands in + // for both: a read answers what's in `messages` at that moment, and a save replaces it. + when(storage.isConfigured()).thenReturn(true); + when(storage.decodeFileOrThrow("CSA", MESSAGES_FILE)).thenAnswer(call -> jsonlBase64(messages)); + doAnswer(call -> { + List saved = parse(call.getArgument(0)); + messages.clear(); + messages.addAll(saved); + return MESSAGES_FILE; + }).when(storage).uploadFileOrThrow(anyString(), eq(MESSAGES_FILE), eq("CSA")); + } + + private String jsonlBase64(List stored) throws Exception { + ObjectMapper json = new ObjectMapper(); + String jsonl = stored.stream().map(m -> { + try { + return json.writeValueAsString(m); + } catch (Exception e) { + throw new IllegalStateException(e); + } + }).collect(Collectors.joining("\n")); + return Base64.getEncoder().encodeToString(jsonl.getBytes(StandardCharsets.UTF_8)); + } + + /** The messages each save wrote, in order. */ + private List> saves(int expected) throws Exception { + ArgumentCaptor uploaded = ArgumentCaptor.forClass(String.class); + verify(storage, times(expected)).uploadFileOrThrow(uploaded.capture(), eq(MESSAGES_FILE), eq("CSA")); + List> saves = new ArrayList<>(); + for (String base64 : uploaded.getAllValues()) { + saves.add(parse(base64)); + } + return saves; + } + + private static List parse(String base64) throws Exception { + ObjectMapper json = new ObjectMapper(); + String jsonl = new String(Base64.getDecoder().decode(base64), StandardCharsets.UTF_8); + List saved = new ArrayList<>(); + for (String line : jsonl.split("\n")) { + if (!line.isBlank()) saved.add(json.readValue(line, GroupChatMessage.class)); + } + return saved; } @AfterEach @@ -82,18 +134,20 @@ void clearAuthentication() { } @Test - void ownerCanEditAndDeleteThroughRestAfterDisplayNameChange() { + void ownerCanEditAndDeleteThroughRestAfterDisplayNameChange() throws Exception { person.setName("Renamed Owner"); signIn("owner"); GroupChatMessage request = new GroupChatMessage(); request.setMessage("updated"); assertEquals(HttpStatus.OK, controller.editMessage(7L, message.getId(), request).getStatusCode()); - assertEquals("updated", message.getMessage()); - assertTrue(message.isEdited()); assertEquals(HttpStatus.OK, controller.deleteMessage(7L, message.getId()).getStatusCode()); + List> saves = saves(2); + assertEquals(1, saves.get(0).size()); + assertEquals("updated", saves.get(0).get(0).getMessage()); + assertTrue(saves.get(0).get(0).isEdited()); + assertTrue(saves.get(1).isEmpty()); assertTrue(messages.isEmpty()); - verify(storage, times(2)).uploadFile(anyString(), eq("messages-images/messages.jsonl"), eq("CSA")); } @Test @@ -104,9 +158,9 @@ void sameDisplayNameDoesNotAuthorizeAnotherAccount() { assertEquals(HttpStatus.FORBIDDEN, controller.editMessage(7L, message.getId(), request).getStatusCode()); assertEquals(HttpStatus.FORBIDDEN, controller.deleteMessage(7L, message.getId()).getStatusCode()); - assertEquals("original", message.getMessage()); assertEquals(1, messages.size()); - verify(storage, never()).uploadFile(anyString(), anyString(), anyString()); + assertEquals("original", messages.get(0).getMessage()); + verify(storage, never()).uploadFileOrThrow(anyString(), anyString(), anyString()); } @Test @@ -117,7 +171,7 @@ void unauthenticatedRequestsCannotEditOrDelete() { assertEquals(HttpStatus.UNAUTHORIZED, controller.editMessage(7L, message.getId(), request).getStatusCode()); assertEquals(HttpStatus.UNAUTHORIZED, controller.deleteMessage(7L, message.getId()).getStatusCode()); - verify(storage, never()).uploadFile(anyString(), anyString(), anyString()); + verify(storage, never()).uploadFileOrThrow(anyString(), anyString(), anyString()); } @Test @@ -128,7 +182,7 @@ void missingAuthorUidDoesNotFallBackToDisplayName() { () -> chat.editMessage("CSA", message.getId(), "updated", "owner")); assertThrows(SecurityException.class, () -> chat.deleteMessage("CSA", message.getId(), "owner")); - verify(storage, never()).uploadFile(anyString(), anyString(), anyString()); + verify(storage, never()).uploadFileOrThrow(anyString(), anyString(), anyString()); } @Test diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java new file mode 100644 index 000000000..f8e71a460 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java @@ -0,0 +1,258 @@ +package com.open.spring.mvc.groups; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.messaging.simp.SimpMessagingTemplate; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.test.util.ReflectionTestUtils; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.open.spring.mvc.S3uploads.S3FileHandler; +import com.open.spring.mvc.person.Person; +import com.open.spring.mvc.person.PersonJpaRepository; + +import software.amazon.awssdk.core.ResponseBytes; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectResponse; +import software.amazon.awssdk.services.s3.model.NoSuchKeyException; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.PutObjectResponse; + +/** + * Sending a message reads the group's whole messages file, adds the message and writes the + * file back. A read that failed must not count as an empty chat: writing that back would + * replace the whole history with the one new message. + */ +class GroupChatSendTest { + + private static final String MESSAGES_KEY = "CSA/messages-images/messages.jsonl"; + private static final String ADA_LINE = "{\"id\":\"m1\",\"author\":\"Ada Lovelace\",\"author_uid\":\"ada\"," + + "\"message\":\"Meeting at 3\",\"date\":\"2026-11-21T10:00:00Z\",\"image\":null,\"edited\":false}"; + + /** S3's objects by key. The real S3FileHandler reads and writes them through a stand-in S3 client. */ + private final Map objects = new ConcurrentHashMap<>(); + private S3Client s3; + private SimpMessagingTemplate messaging; + private GroupChatApiController controller; + + @BeforeEach + void setUp() { + useFreshStorage(); + } + + @AfterEach + void signOut() { + SecurityContextHolder.clearContext(); + } + + /** An empty bucket behind a real S3FileHandler, as S3 answers: a missing key is a 404 NoSuchKey. */ + private void useFreshStorage() { + objects.clear(); + s3 = mock(S3Client.class); + when(s3.getObjectAsBytes(any(GetObjectRequest.class))).thenAnswer(call -> { + byte[] bytes = objects.get(call.getArgument(0).key()); + if (bytes == null) { + throw NoSuchKeyException.builder().statusCode(404).message("The specified key does not exist.").build(); + } + return ResponseBytes.fromByteArray(GetObjectResponse.builder().build(), bytes); + }); + when(s3.putObject(any(PutObjectRequest.class), any(RequestBody.class))).thenAnswer(call -> { + try (InputStream body = call.getArgument(1).contentStreamProvider().newStream()) { + objects.put(call.getArgument(0).key(), body.readAllBytes()); + } + return PutObjectResponse.builder().build(); + }); + S3FileHandler storage = new S3FileHandler(); + ReflectionTestUtils.setField(storage, "s3Client", s3); + ReflectionTestUtils.setField(storage, "bucketName", "chat-test"); + wire(storage); + } + + /** The send route over this storage, with Grace Hopper signed in. */ + private void wire(S3FileHandler storage) { + GroupChatService chat = new GroupChatService(storage, new ObjectMapper()); + GroupsJpaRepository groups = mock(GroupsJpaRepository.class); + messaging = mock(SimpMessagingTemplate.class); + // Built from whatever their constructors take, so a new dependency elsewhere doesn't break this test. + GroupChatRealtimeService realtime = TestBeans.build(GroupChatRealtimeService.class, chat, groups, messaging); + GroupChatReadService reads = TestBeans.build(GroupChatReadService.class, + mock(GroupChatReadStateJpaRepository.class), groups, chat); + PersonJpaRepository people = mock(PersonJpaRepository.class); + controller = TestBeans.build(GroupChatApiController.class, chat, realtime, reads, groups, people); + + Groups group = new Groups(); + group.setName("CSA"); + when(groups.findById(7L)).thenReturn(Optional.of(group)); + Person grace = new Person(); + grace.setUid("grace"); + grace.setName("Grace Hopper"); + when(people.findByUid("grace")).thenReturn(grace); + SecurityContextHolder.getContext().setAuthentication( + new UsernamePasswordAuthenticationToken("grace", null, List.of())); + } + + private ResponseEntity send(String text) { + GroupChatMessage request = new GroupChatMessage(); + request.setMessage(text); + return controller.postMessage(7L, request); + } + + /** The first read of S3 works, and every read after it fails as a throttle. */ + private void failReadsAfterTheFirst() { + AtomicInteger reads = new AtomicInteger(); + doAnswer(call -> { + if (reads.incrementAndGet() > 1) { + throw S3Failures.unavailable().get(0); + } + byte[] bytes = objects.get(call.getArgument(0).key()); + return ResponseBytes.fromByteArray(GetObjectResponse.builder().build(), bytes); + }).when(s3).getObjectAsBytes(any(GetObjectRequest.class)); + } + + private String storedMessages() { + byte[] bytes = objects.get(MESSAGES_KEY); + return bytes == null ? null : new String(bytes, StandardCharsets.UTF_8); + } + + + @Test + void aReadThatFailsRefusesTheSendWithA503AndKeepsTheHistory() { + for (RuntimeException failure : S3Failures.unavailable()) { + useFreshStorage(); + objects.put(MESSAGES_KEY, ADA_LINE.getBytes(StandardCharsets.UTF_8)); + doThrow(failure).when(s3).getObjectAsBytes(any(GetObjectRequest.class)); + + ResponseEntity response = send("Works for me"); + + assertEquals(HttpStatus.SERVICE_UNAVAILABLE, response.getStatusCode(), failure.toString()); + String retryAfter = response.getHeaders().getFirst(HttpHeaders.RETRY_AFTER); + assertTrue(retryAfter != null && retryAfter.matches("[1-9][0-9]*"), "Retry-After: " + retryAfter); + assertEquals(ADA_LINE, storedMessages(), failure.toString()); + // The group isn't told about a message that wasn't saved. + verify(messaging, never()).convertAndSend(any(String.class), any(Object.class)); + } + } + + @Test + void aReadS3RefusesOrABugHereIsNotOfferedARetryAndWritesNothing() { + for (RuntimeException fault : S3Failures.refusalsAndBugs()) { + useFreshStorage(); + objects.put(MESSAGES_KEY, ADA_LINE.getBytes(StandardCharsets.UTF_8)); + doThrow(fault).when(s3).getObjectAsBytes(any(GetObjectRequest.class)); + + ResponseEntity response = send("Works for me"); + + assertFalse(response.getStatusCode().is2xxSuccessful(), fault.toString()); + assertNotEquals(HttpStatus.SERVICE_UNAVAILABLE, response.getStatusCode(), fault.toString()); + assertNull(response.getHeaders().getFirst(HttpHeaders.RETRY_AFTER), fault.toString()); + assertEquals(ADA_LINE, storedMessages(), fault.toString()); + verify(messaging, never()).convertAndSend(any(String.class), any(Object.class)); + } + } + + @Test + void anUploadThatFailsForAMomentRefusesTheSendWithA503AndKeepsTheHistory() { + // The read works, and then S3 can't take the upload for a moment. + for (RuntimeException failure : S3Failures.unavailable()) { + useFreshStorage(); + objects.put(MESSAGES_KEY, ADA_LINE.getBytes(StandardCharsets.UTF_8)); + doThrow(failure).when(s3).putObject(any(PutObjectRequest.class), any(RequestBody.class)); + + ResponseEntity response = send("Works for me"); + + assertEquals(HttpStatus.SERVICE_UNAVAILABLE, response.getStatusCode(), failure.toString()); + String retryAfter = response.getHeaders().getFirst(HttpHeaders.RETRY_AFTER); + assertTrue(retryAfter != null && retryAfter.matches("[1-9][0-9]*"), "Retry-After: " + retryAfter); + assertEquals(ADA_LINE, storedMessages(), failure.toString()); + // A message that wasn't saved isn't shown to the group as sent. + verify(messaging, never()).convertAndSend(any(String.class), any(Object.class)); + } + } + + @Test + void anUploadS3RefusesOrABugHereIsNotOfferedARetryAndIsNotShown() { + for (RuntimeException fault : S3Failures.refusalsAndBugs()) { + useFreshStorage(); + objects.put(MESSAGES_KEY, ADA_LINE.getBytes(StandardCharsets.UTF_8)); + doThrow(fault).when(s3).putObject(any(PutObjectRequest.class), any(RequestBody.class)); + + ResponseEntity response = send("Works for me"); + + assertFalse(response.getStatusCode().is2xxSuccessful(), fault.toString()); + assertNotEquals(HttpStatus.SERVICE_UNAVAILABLE, response.getStatusCode(), fault.toString()); + assertNull(response.getHeaders().getFirst(HttpHeaders.RETRY_AFTER), fault.toString()); + assertEquals(ADA_LINE, storedMessages(), fault.toString()); + verify(messaging, never()).convertAndSend(any(String.class), any(Object.class)); + } + } + + @Test + void aSendAnswersWithTheMessagesItSavedEvenWhenTheNextReadFails() { + objects.put(MESSAGES_KEY, ADA_LINE.getBytes(StandardCharsets.UTF_8)); + failReadsAfterTheFirst(); + + ResponseEntity response = send("Works for me"); + + assertEquals(HttpStatus.OK, response.getStatusCode()); + List texts = ((List) response.getBody()).stream() + .map(saved -> ((GroupChatMessage) saved).getMessage()) + .toList(); + assertEquals(List.of("Meeting at 3", "Works for me"), texts); + } + + @Test + void aGroupWithNoMessagesFileYetStartsItsHistoryWithTheSend() throws Exception { + // S3's 404: nothing is stored yet, so there's no history to lose. + ResponseEntity response = send("Works for me"); + + assertEquals(HttpStatus.OK, response.getStatusCode()); + List lines = storedMessages().lines().toList(); + assertEquals(1, lines.size(), storedMessages()); + GroupChatMessage saved = new ObjectMapper().readValue(lines.get(0), GroupChatMessage.class); + assertEquals("Works for me", saved.getMessage()); + assertEquals("grace", saved.getAuthor_uid()); + } + + @Test + void withoutS3SettingsASendIsStillBroadcastLive() { + // A local server without S3 saves nothing, but its chats keep working live. + wire(new S3FileHandler()); + + ResponseEntity response = send("Works for me"); + + assertEquals(HttpStatus.OK, response.getStatusCode()); + ArgumentCaptor frame = ArgumentCaptor.forClass(Object.class); + verify(messaging).convertAndSend(eq("/topic/group/7"), frame.capture()); + assertEquals("Works for me", ((GroupChatEvent) frame.getValue()).getMessage()); + } +} diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatServiceTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatServiceTest.java new file mode 100644 index 000000000..be0dd3c06 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatServiceTest.java @@ -0,0 +1,158 @@ +package com.open.spring.mvc.groups; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.open.spring.mvc.S3uploads.S3FileHandler; + +/** + * Two changes to one group's messages at the same time. Sending, editing and deleting each + * read the group's whole messages file, change it and write it back, and neither change may + * be lost. + */ +class GroupChatServiceTest { + + private static final String MESSAGES_KEY = "CSA/messages-images/messages.jsonl"; + + /** + * S3 kept in a map, keyed the way S3FileHandler keys objects: "group/filename". A read + * takes its copy, then waits until a second read has started (or half a second passes), + * so two writes that are not kept apart both change the same old copy of the file. + */ + static class OverlappingReads extends S3FileHandler { + final Map objects = new ConcurrentHashMap<>(); + final CountDownLatch bothReading = new CountDownLatch(2); + + // A configured S3 whose writes never fail. + @Override + public boolean isConfigured() { + return true; + } + + @Override + public String uploadFileOrThrow(String base64Data, String filename, String uid) { + objects.put(uid + "/" + filename, base64Data); + return filename; + } + + @Override + public String decodeFile(String uid, String filename) { + String copy = objects.get(uid + "/" + filename); + bothReading.countDown(); + try { + bothReading.await(500, TimeUnit.MILLISECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + return copy; + } + + // Its reads never fail, so the strict read a change makes is the same read. + @Override + public String decodeFileOrThrow(String uid, String filename) { + return decodeFile(uid, filename); + } + } + + private final ObjectMapper json = new ObjectMapper(); + private OverlappingReads storage; + private GroupChatService chat; + + @BeforeEach + void setUp() { + storage = new OverlappingReads(); + chat = new GroupChatService(storage, json); + } + + @Test + void twoMessagesSentAtOnceAreBothKept() throws Exception { + GroupChatMessage ada = message("Ada Lovelace", "ada", "Meeting at 3?"); + GroupChatMessage grace = message("Grace Hopper", "grace", "Works for me"); + + atOnce(() -> chat.addMessage("CSA", ada), () -> chat.addMessage("CSA", grace)); + + // Either send may get there first, so compare them in alphabetical order. + List saved = texts(chat.getMessages("CSA")).stream().sorted().collect(Collectors.toList()); + assertEquals(List.of("Meeting at 3?", "Works for me"), saved); + } + + @Test + void anEditWhileAnotherMessageIsSentKeepsBothChanges() throws Exception { + GroupChatMessage ada = message("Ada Lovelace", "ada", "Meeting at 3"); + store(ada); + GroupChatMessage grace = message("Grace Hopper", "grace", "Works for me"); + + atOnce(() -> chat.editMessage("CSA", ada.getId(), "Meeting at 4", "ada"), + () -> chat.addMessage("CSA", grace)); + + List saved = chat.getMessages("CSA"); + assertEquals(List.of("Meeting at 4", "Works for me"), texts(saved)); + assertTrue(saved.get(0).isEdited()); + } + + @Test + void aDeleteWhileAnotherMessageIsSentKeepsBothChanges() throws Exception { + GroupChatMessage plan = message("Ada Lovelace", "ada", "Meeting at 3"); + GroupChatMessage typo = message("Ada Lovelace", "ada", "Meetign at 3"); + store(plan, typo); + GroupChatMessage grace = message("Grace Hopper", "grace", "Works for me"); + + atOnce(() -> chat.deleteMessage("CSA", typo.getId(), "ada"), + () -> chat.addMessage("CSA", grace)); + + assertEquals(List.of("Meeting at 3", "Works for me"), texts(chat.getMessages("CSA"))); + } + + /** Starts both together on their own threads and waits for both, failing if either threw. */ + private static void atOnce(Runnable first, Runnable second) throws Exception { + ExecutorService pool = Executors.newFixedThreadPool(2); + CountDownLatch start = new CountDownLatch(1); + List> done = new ArrayList<>(); + for (Runnable task : List.of(first, second)) { + done.add(pool.submit(() -> { + start.await(); + task.run(); + return null; + })); + } + start.countDown(); + try { + for (Future future : done) future.get(10, TimeUnit.SECONDS); + } finally { + pool.shutdownNow(); + } + } + + private static GroupChatMessage message(String author, String uid, String text) { + return new GroupChatMessage(author, uid, text, "2026-11-21T10:00:00Z", null); + } + + /** Saves messages straight to the group's file, one JSON object per line, as the chat does. */ + private void store(GroupChatMessage... messages) throws Exception { + List lines = new ArrayList<>(); + for (GroupChatMessage message : messages) lines.add(json.writeValueAsString(message)); + String jsonl = String.join("\n", lines); + storage.objects.put(MESSAGES_KEY, Base64.getEncoder().encodeToString(jsonl.getBytes(StandardCharsets.UTF_8))); + } + + private static List texts(List messages) { + return messages.stream().map(GroupChatMessage::getMessage).collect(Collectors.toList()); + } +} diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatSocketMentorTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatSocketMentorTest.java new file mode 100644 index 000000000..85d5e65a5 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatSocketMentorTest.java @@ -0,0 +1,144 @@ +package com.open.spring.mvc.groups; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.security.Principal; +import java.util.List; +import java.util.Optional; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.test.util.ReflectionTestUtils; + +import com.open.spring.mvc.person.Person; +import com.open.spring.mvc.person.PersonJpaRepository; + +/** + * Group events on the chat socket follow the mentor rules, as REST does: a socket with a signed-in mentor sends, + * joins and types only in groups the mentor may use (MentorRules). Leaving always works, and everyone else's events + * work as before. A socket from Spring's own pages carries its sign-in's roles, so only a mentor's events load anyone. + */ +class GroupChatSocketMentorTest { + + private GroupChatRealtimeService realtime; + private GroupChatPresenceService presence; + private GroupsJpaRepository groups; + private ClassGroupMembershipService classGroups; + private PersonJpaRepository people; + private GroupChatWebSocketController controller; + + private final Person student = MentorRulesTest.student(1); + private final Person teammate = MentorRulesTest.student(2); + private final Person mentor = MentorRulesTest.mentor(3); + + private static final long OTHERS = 7L; + private static final long SOLO = 8L; + private static final long TEAM = 9L; + + private void group(long id, String name, Person... members) { + Groups group = new Groups(); + ReflectionTestUtils.setField(group, "id", id); + group.setName(name); + when(groups.findById(id)).thenReturn(Optional.of(group)); + when(groups.findMembersOf(id)).thenReturn(List.of(members)); + } + + @BeforeEach + void setUp() { + realtime = mock(GroupChatRealtimeService.class); + presence = mock(GroupChatPresenceService.class); + groups = mock(GroupsJpaRepository.class); + classGroups = mock(ClassGroupMembershipService.class); + people = mock(PersonJpaRepository.class); + controller = new GroupChatWebSocketController(mock(GroupChatIdentityService.class), realtime, presence, + new MentorAccess(groups, classGroups), people); + for (Person person : List.of(student, teammate, mentor)) { + when(people.findByUid(person.getUid())).thenReturn(person); + } + group(OTHERS, "Team Rocket", student, teammate); + group(SOLO, "Just Us", student, mentor); + group(TEAM, "Team Plasma", student, teammate, mentor); + } + + private void send(Person person, String context, long groupId) { + GroupChatEvent event = GroupChatEvent.builder().context(context).groupId(groupId) + .message("hi").filename("notes.txt").base64Data("aGk=").build(); + Principal principal = person::getUid; + controller.handleGroupEvent(event, principal, "session-" + person.getId()); + } + + /** The same event from a socket whose sign-in carries the person's roles, as Spring's form login gives it. */ + private void sendSignedIn(Person person, String context, long groupId) { + GroupChatEvent event = GroupChatEvent.builder().context(context).groupId(groupId).message("hi").build(); + List roles = person.getRoles().stream().map(SimpleGrantedAuthority::new).toList(); + controller.handleGroupEvent(event, new UsernamePasswordAuthenticationToken(person.getUid(), null, roles), + "session-" + person.getId()); + } + + @Test + void aMentorsSocketCantSendOrShowUpInAGroupTheyArentIn() { + for (String context : List.of("joinGroup", "sendMessage", "sendFile", "typingStart", "heartbeat")) { + send(mentor, context, OTHERS); + } + verify(realtime, never()).publishMessage(anyLong(), anyString(), any(), any()); + verify(realtime, never()).publishFile(anyLong(), anyString(), anyString(), anyString()); + verify(realtime, never()).publishTyping(anyLong(), anyString(), anyBoolean()); + verify(realtime, never()).publishPresence(anyLong(), anyString(), anyString(), any()); + verify(presence, never()).joinGroup(anyString(), anyLong(), anyString()); + } + + @Test + void aMentorsSocketCantSendToATeamOfOne() { + send(mentor, "sendMessage", SOLO); + send(mentor, "sendFile", SOLO); + verify(realtime, never()).publishMessage(anyLong(), anyString(), any(), any()); + verify(realtime, never()).publishFile(anyLong(), anyString(), anyString(), anyString()); + } + + @Test + void aMentorsSocketWorksInTheirTeamAndCanAlwaysLeave() { + send(mentor, "sendMessage", TEAM); + verify(realtime, times(1)).publishMessage(anyLong(), anyString(), any(), any()); + send(mentor, "leaveGroup", OTHERS); + verify(presence).leaveGroup("session-3", OTHERS); + } + + @Test + void aSignInThatIsntAMentorsLoadsNoOne() { + Person mentoringTeacher = MentorRulesTest.person(6, "ROLE_USER", MentorRules.ROLE_MENTOR, "ROLE_TEACHER"); + for (String context : List.of("typingStart", "heartbeat", "sendMessage")) { + sendSignedIn(student, context, OTHERS); + sendSignedIn(mentoringTeacher, context, OTHERS); + } + verify(people, never()).findByUid(anyString()); + verify(groups, never()).findById(anyLong()); + verify(realtime, times(2)).publishMessage(eq(OTHERS), anyString(), any(), any()); + } + + @Test + void aMentorsSignInIsStillCheckedAgainstTheGroup() { + sendSignedIn(mentor, "sendMessage", OTHERS); + sendSignedIn(mentor, "sendMessage", TEAM); + verify(realtime, never()).publishMessage(eq(OTHERS), anyString(), any(), any()); + verify(realtime, times(1)).publishMessage(eq(TEAM), anyString(), any(), any()); + } + + @Test + void studentsSocketsSendAsBefore() { + send(student, "sendMessage", OTHERS); + send(student, "sendMessage", SOLO); + verify(realtime, times(2)).publishMessage(anyLong(), anyString(), any(), any()); + verify(groups, never()).findMembersOf(anyLong()); + } +} diff --git a/src/test/java/com/open/spring/mvc/groups/GroupGradesAccessTest.java b/src/test/java/com/open/spring/mvc/groups/GroupGradesAccessTest.java new file mode 100644 index 000000000..d151a2286 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/groups/GroupGradesAccessTest.java @@ -0,0 +1,219 @@ +package com.open.spring.mvc.groups; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.test.util.ReflectionTestUtils; + +import com.open.spring.mvc.assignments.Assignment; +import com.open.spring.mvc.assignments.AssignmentAuthorizationService; +import com.open.spring.mvc.assignments.AssignmentJpaRepository; +import com.open.spring.mvc.assignments.AssignmentSubmission; +import com.open.spring.mvc.assignments.AssignmentSubmissionJPA; +import com.open.spring.mvc.person.Person; +import com.open.spring.mvc.person.PersonJpaRepository; + +/** + * Who may see and change a group's grades. Its members, its graders, teachers and admins read + * them. Replacing or clearing all of them is for teachers and admins. Adding one assignment's + * entry, which also copies it into each member's own grades, is for them and for whoever already + * grades the group on that assignment: its creators and graders, and the graders of the group's + * submission to it. + */ +class GroupGradesAccessTest { + + private static final long TEAM = 7L; + private static final long HW1 = 101L; + private static final long HW2 = 102L; + + private final GroupsJpaRepository groups = mock(GroupsJpaRepository.class); + private final PersonJpaRepository people = mock(PersonJpaRepository.class); + private final ClassGroupMembershipService classGroups = mock(ClassGroupMembershipService.class); + private final AssignmentJpaRepository assignments = mock(AssignmentJpaRepository.class); + private final AssignmentSubmissionJPA submissions = mock(AssignmentSubmissionJPA.class); + private GroupsApiController controller; + + private final Person member = MentorRulesTest.student(1); + private final Person teammate = MentorRulesTest.student(2); + private final Person outsider = MentorRulesTest.student(5); + private final Person assignmentGrader = MentorRulesTest.student(6); + private final Person submissionGrader = MentorRulesTest.student(7); + private final Person creator = MentorRulesTest.student(9); + private final Person teacher = MentorRulesTest.teacher(8); + private final Person admin = MentorRulesTest.person(10, "ROLE_USER", "ROLE_ADMIN"); + + @BeforeEach + void setUp() { + controller = new GroupsApiController(); + ReflectionTestUtils.setField(controller, "groupsRepository", groups); + ReflectionTestUtils.setField(controller, "personRepository", people); + ReflectionTestUtils.setField(controller, "groupChatService", mock(GroupChatService.class)); + ReflectionTestUtils.setField(controller, "classGroupMembershipService", classGroups); + ReflectionTestUtils.setField(controller, "mentorAccess", new MentorAccess(groups, classGroups)); + ReflectionTestUtils.setField(controller, "assignmentRepository", assignments); + ReflectionTestUtils.setField(controller, "submissionRepository", submissions); + ReflectionTestUtils.setField(controller, "assignmentAuthorizationService", new AssignmentAuthorizationService()); + for (Person person : List.of(member, teammate, outsider, assignmentGrader, submissionGrader, creator, teacher, admin)) { + when(people.findByUid(person.getUid())).thenReturn(person); + } + + Groups team = new Groups(); + ReflectionTestUtils.setField(team, "id", TEAM); + team.setName("Team Rocket"); + team.getGroupMembers().addAll(List.of(member, teammate)); + when(groups.findById(TEAM)).thenReturn(Optional.of(team)); + when(groups.findMembersOf(TEAM)).thenReturn(List.of(member, teammate)); + when(groups.save(any(Groups.class))).thenAnswer(call -> call.getArgument(0)); + when(groups.findGroupMembersRaw(TEAM)).thenReturn(List.of( + new Object[] {1L, member.getUid(), member.getName(), null}, + new Object[] {2L, teammate.getUid(), teammate.getName(), null})); + when(people.findAllById(anyList())).thenReturn(List.of(member, teammate)); + + Assignment hw1 = assignment(HW1, "hw-1"); + hw1.setAssignedGraders(new ArrayList<>(List.of(assignmentGrader))); + hw1.getCreators().add(creator); + when(assignments.findById(HW1)).thenReturn(Optional.of(hw1)); + when(assignments.findById(HW2)).thenReturn(Optional.of(assignment(HW2, "hw-2"))); + + AssignmentSubmission teamHw1 = new AssignmentSubmission(); + teamHw1.setId(55L); + teamHw1.setAssignment(hw1); + teamHw1.setSubmitter(team); + teamHw1.setAssignedGraders(new ArrayList<>(List.of(submissionGrader))); + when(submissions.findBySubmitterId(TEAM)).thenReturn(List.of(teamHw1)); + } + + @AfterEach + void signOut() { + SecurityContextHolder.clearContext(); + } + + /** Being in the group, or outside it, isn't grading it. */ + @Test + void membersAndOutsidersCannotChangeAGroupsGrades() { + for (Person notGrader : List.of(member, outsider)) { + signIn(notGrader); + assertEquals(HttpStatus.FORBIDDEN, controller.putGroupGrades(TEAM, grades()).getStatusCode()); + assertEquals(HttpStatus.FORBIDDEN, controller.addGroupGrade(TEAM, entry(HW1)).getStatusCode()); + assertEquals(HttpStatus.FORBIDDEN, controller.clearGroupGrades(TEAM).getStatusCode()); + } + verify(groups, never()).save(any(Groups.class)); + verify(people, never()).saveAll(anyList()); + } + + @Test + void teachersAndAdminsReplaceAddAndClearAGroupsGrades() { + for (Person staff : List.of(teacher, admin)) { + signIn(staff); + assertEquals(HttpStatus.OK, controller.putGroupGrades(TEAM, grades()).getStatusCode()); + assertEquals(HttpStatus.OK, controller.addGroupGrade(TEAM, entry(HW2)).getStatusCode()); + assertEquals(HttpStatus.NO_CONTENT, controller.clearGroupGrades(TEAM).getStatusCode()); + } + } + + /** hw-1's creator, its grader and the grader of the group's hw-1 submission add that entry and nothing else. */ + @Test + void whoeverGradesTheGroupOnAnAssignmentAddsOnlyThatEntry() { + for (Person grader : List.of(assignmentGrader, creator, submissionGrader)) { + signIn(grader); + assertEquals(HttpStatus.OK, controller.addGroupGrade(TEAM, entry(HW1)).getStatusCode()); + assertEquals(HttpStatus.FORBIDDEN, controller.addGroupGrade(TEAM, entry(HW2)).getStatusCode()); + assertEquals(HttpStatus.FORBIDDEN, controller.putGroupGrades(TEAM, grades()).getStatusCode()); + assertEquals(HttpStatus.FORBIDDEN, controller.clearGroupGrades(TEAM).getStatusCode()); + } + } + + /** hw-1's creator and grader grade it for every group, even one that hasn't handed anything in yet. */ + @Test + void anAssignmentsGradersAddItsEntryBeforeTheGroupHandsIn() { + when(submissions.findBySubmitterId(TEAM)).thenReturn(List.of()); + for (Person grader : List.of(assignmentGrader, creator)) { + signIn(grader); + assertEquals(HttpStatus.OK, controller.addGroupGrade(TEAM, entry(HW1)).getStatusCode()); + } + signIn(submissionGrader); + assertEquals(HttpStatus.FORBIDDEN, controller.addGroupGrade(TEAM, entry(HW1)).getStatusCode()); + } + + @Test + void anAddedEntryIsCopiedIntoEachMembersGrades() { + signIn(assignmentGrader); + assertEquals(HttpStatus.OK, controller.addGroupGrade(TEAM, entry(HW1)).getStatusCode()); + for (Person person : List.of(member, teammate)) { + assertTrue(person.getGradesJson().stream() + .anyMatch(grade -> String.valueOf(HW1).equals(String.valueOf(grade.get("assignmentId"))))); + } + } + + /** Without an assignment there's no one who grades it, so only teachers and admins add such an entry. */ + @Test + void anEntryWithoutAnAssignmentIsForTeachersAndAdmins() { + signIn(assignmentGrader); + assertEquals(HttpStatus.FORBIDDEN, controller.addGroupGrade(TEAM, new HashMap<>(Map.of("score", 90))).getStatusCode()); + + signIn(teacher); + assertEquals(HttpStatus.OK, controller.addGroupGrade(TEAM, new HashMap<>(Map.of("score", 90))).getStatusCode()); + } + + /** A group's grades are read by its members, whoever grades one of its submissions, teachers and admins. */ + @Test + void membersGradersAndStaffReadAGroupsGrades() { + for (Person reader : List.of(member, teammate, assignmentGrader, creator, submissionGrader, teacher, admin)) { + signIn(reader); + assertEquals(HttpStatus.OK, controller.getGroupGrades(TEAM).getStatusCode()); + } + } + + @Test + void someoneOutsideTheGroupCannotReadItsGrades() { + signIn(outsider); + assertEquals(HttpStatus.FORBIDDEN, controller.getGroupGrades(TEAM).getStatusCode()); + + SecurityContextHolder.clearContext(); + assertEquals(HttpStatus.FORBIDDEN, controller.getGroupGrades(TEAM).getStatusCode()); + } + + @Test + void signedOutCannotChangeAGroupsGrades() { + assertEquals(HttpStatus.FORBIDDEN, controller.putGroupGrades(TEAM, grades()).getStatusCode()); + assertEquals(HttpStatus.FORBIDDEN, controller.addGroupGrade(TEAM, entry(HW1)).getStatusCode()); + assertEquals(HttpStatus.FORBIDDEN, controller.clearGroupGrades(TEAM).getStatusCode()); + } + + private static Assignment assignment(long id, String name) { + Assignment assignment = new Assignment(name, "auto-created", "[CONTENT_URL: csa/" + name + "/]", 1.0, "10/25/2026", "file"); + assignment.setId(id); + return assignment; + } + + private static List> grades() { + return new ArrayList<>(List.of(new HashMap<>(Map.of("assignmentId", HW1, "score", 95)))); + } + + private static Map entry(long assignmentId) { + return new HashMap<>(Map.of("assignmentId", assignmentId, "score", 90)); + } + + private void signIn(Person person) { + SecurityContextHolder.getContext().setAuthentication( + new UsernamePasswordAuthenticationToken(person.getUid(), null, List.of())); + } +} diff --git a/src/test/java/com/open/spring/mvc/groups/GroupMembersMentorTest.java b/src/test/java/com/open/spring/mvc/groups/GroupMembersMentorTest.java new file mode 100644 index 000000000..80ed4f082 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/groups/GroupMembersMentorTest.java @@ -0,0 +1,300 @@ +package com.open.spring.mvc.groups; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.test.util.ReflectionTestUtils; + +import com.open.spring.mvc.person.Person; +import com.open.spring.mvc.person.PersonJpaRepository; + +/** + * The team manages its mentors: a member of a group (or a teacher) adds and removes its mentor, a mentor adds no one, + * and a mentor never ends up alone with one student. Mentors can't look through or change groups either. Everyone + * else is added and removed by the group's members, teachers and admins, or joins and leaves on their own (see + * GroupMembershipAccessTest). + */ +class GroupMembersMentorTest { + + private GroupsJpaRepository groups; + private PersonJpaRepository people; + private ClassGroupMembershipService classGroups; + private GroupsApiController controller; + + private final Person student = MentorRulesTest.student(1); + private final Person teammate = MentorRulesTest.student(2); + private final Person mentor = MentorRulesTest.mentor(3); + private final Person outsider = MentorRulesTest.student(5); + private final Person teacher = MentorRulesTest.teacher(8); + private final Person thirdStudent = MentorRulesTest.student(6); + + private static final long TEAM = 7L; + private static final long SOLO = 8L; + + /** The group's members as the database holds them: a group answers from these rows. */ + private final Map> members = new java.util.HashMap<>(); + + private Groups group(long id, String name, Person... initial) { + Groups group = new Groups(); + ReflectionTestUtils.setField(group, "id", id); + group.setName(name); + members.put(id, new ArrayList<>(List.of(initial))); + for (Person person : initial) { + group.getGroupMembers().add(person); + } + when(groups.findById(id)).thenReturn(Optional.of(group)); + when(groups.findMembersOf(id)).thenAnswer(call -> List.copyOf(members.get(id))); + when(groups.findGroupMembersWithRolesRaw(id)).thenAnswer(call -> rows(members.get(id))); + when(groups.save(group)).thenAnswer(call -> { + members.put(id, new ArrayList<>(group.getGroupMembers())); + return group; + }); + return group; + } + + private static List rows(List people) { + List rows = new ArrayList<>(); + for (Person person : people) { + rows.add(new Object[] {person.getId(), person.getUid(), person.getName(), person.getUid() + "@example.com", + new com.open.spring.mvc.person.RolesJsonConverter().convertToDatabaseColumn(person.getRoles())}); + } + return rows; + } + + @BeforeEach + void setUp() { + groups = mock(GroupsJpaRepository.class); + people = mock(PersonJpaRepository.class); + classGroups = mock(ClassGroupMembershipService.class); + controller = new GroupsApiController(); + ReflectionTestUtils.setField(controller, "groupsRepository", groups); + ReflectionTestUtils.setField(controller, "personRepository", people); + ReflectionTestUtils.setField(controller, "groupChatService", mock(GroupChatService.class)); + ReflectionTestUtils.setField(controller, "classGroupMembershipService", classGroups); + ReflectionTestUtils.setField(controller, "mentorAccess", new MentorAccess(groups, classGroups)); + for (Person person : List.of(student, teammate, mentor, outsider, teacher, thirdStudent)) { + when(people.findByUid(person.getUid())).thenReturn(person); + when(people.findById(person.getId())).thenReturn(Optional.of(person)); + } + group(TEAM, "Team Rocket", student, teammate); + group(SOLO, "Just Us", student); + when(groups.findAll()).thenReturn(List.of()); + when(groups.searchByName(anyString())).thenReturn(List.of()); + when(groups.findGroupsByPersonId(anyLong())).thenReturn(List.of()); + } + + @AfterEach + void signOut() { + SecurityContextHolder.clearContext(); + } + + private void signIn(Person person) { + SecurityContextHolder.getContext().setAuthentication( + new UsernamePasswordAuthenticationToken(person.getUid(), null, List.of())); + } + + private static void assertRefused(String reason, ResponseEntity response) { + assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode()); + assertEquals(reason, ((Map) response.getBody()).get("reason")); + } + + @SuppressWarnings("unchecked") + private static Map memberById(ResponseEntity response, long id) { + List> list = (List>) ((Map) response.getBody()).get("members"); + return list.stream().filter(member -> ((Number) member.get("id")).longValue() == id).findFirst().orElseThrow(); + } + + @Test + void aTeamMemberAddsAMentorAndTheMemberListMarksThem() { + signIn(student); + ResponseEntity response = controller.addPersonToGroup(TEAM, mentor.getId()); + assertEquals(HttpStatus.OK, response.getStatusCode()); + assertEquals(true, memberById(response, mentor.getId()).get("mentor")); + assertEquals(false, memberById(response, student.getId()).get("mentor")); + } + + @Test + void aStudentOutsideTheTeamCannotAddAMentor() { + signIn(outsider); + assertRefused("team_manages_mentors", controller.addPersonToGroup(TEAM, mentor.getId())); + verify(groups, never()).save(any()); + } + + @Test + void aMentorCannotAddThemselvesOrAnyoneElse() { + signIn(mentor); + assertRefused("mentor_cannot_manage", controller.addPersonToGroup(TEAM, mentor.getId())); + assertRefused("mentor_cannot_manage", controller.addPersonToGroup(TEAM, outsider.getId())); + verify(groups, never()).save(any()); + } + + @Test + void aMentorCannotBeAddedToAOneStudentGroup() { + signIn(student); + assertRefused("mentor_team_too_small", controller.addPersonToGroup(SOLO, mentor.getId())); + } + + @Test + void aTeacherAddsAMentor() { + signIn(teacher); + assertEquals(HttpStatus.OK, controller.addPersonToGroup(TEAM, mentor.getId()).getStatusCode()); + } + + @Test + void membersStillAddStudentsAsBefore() { + signIn(student); + assertEquals(HttpStatus.OK, controller.addPersonToGroup(TEAM, thirdStudent.getId()).getStatusCode()); + } + + @Test + void aMentorLeavesButCannotRemoveOthers() { + signIn(student); + controller.addPersonToGroup(TEAM, mentor.getId()); + signIn(mentor); + assertRefused("mentor_cannot_manage", controller.removePersonFromGroup(TEAM, teammate.getId())); + assertEquals(HttpStatus.OK, controller.removePersonFromGroup(TEAM, mentor.getId()).getStatusCode()); + assertFalse(members.get(TEAM).contains(mentor)); + } + + @Test + void onlyTheTeamOrATeacherRemovesTheMentor() { + signIn(student); + controller.addPersonToGroup(TEAM, mentor.getId()); + signIn(outsider); + assertRefused("team_manages_mentors", controller.removePersonFromGroup(TEAM, mentor.getId())); + signIn(teammate); + assertEquals(HttpStatus.OK, controller.removePersonFromGroup(TEAM, mentor.getId()).getStatusCode()); + } + + @Test + void aNewGroupStartsWithAMentorOnlyWhenTheTeamCouldAddThem() { + when(groups.findByName(anyString())).thenReturn(Optional.empty()); + when(groups.save(any(Groups.class))).thenAnswer(call -> call.getArgument(0)); + signIn(student); + assertRefused("mentor_team_too_small", controller.createGroup(new GroupsApiController.GroupCreateDto( + "Pair", "3", "CSP", List.of(student.getId(), mentor.getId())))); + assertRefused("team_manages_mentors", controller.createGroup(new GroupsApiController.GroupCreateDto( + "Not mine", "3", "CSP", List.of(teammate.getId(), thirdStudent.getId(), mentor.getId())))); + assertEquals(HttpStatus.CREATED, controller.createGroup(new GroupsApiController.GroupCreateDto( + "Our team", "3", "CSP", List.of(student.getId(), teammate.getId(), mentor.getId()))).getStatusCode()); + } + + @Test + void aStudentListedTwiceIsStillOneStudent() { + when(groups.findByName(anyString())).thenReturn(Optional.empty()); + when(groups.save(any(Groups.class))).thenAnswer(call -> call.getArgument(0)); + signIn(student); + assertRefused("mentor_team_too_small", controller.createGroup(new GroupsApiController.GroupCreateDto( + "Pair again", "3", "CSP", List.of(student.getId(), student.getId(), mentor.getId())))); + } + + @Test + void bulkCreateSkipsAGroupThatWouldBreakTheMentorRule() { + when(groups.findByName(anyString())).thenReturn(Optional.empty()); + when(groups.save(any(Groups.class))).thenAnswer(call -> call.getArgument(0)); + signIn(teacher); + GroupsApiController.BulkGroupCreateDto dto = new GroupsApiController.BulkGroupCreateDto(List.of( + new GroupsApiController.GroupCreateDto("Pair", "3", "CSP", List.of(student.getId(), mentor.getId())), + new GroupsApiController.GroupCreateDto("Team", "3", "CSP", + List.of(student.getId(), teammate.getId(), mentor.getId())))); + @SuppressWarnings("unchecked") + Map body = (Map) controller.bulkCreateGroups(dto).getBody(); + assertEquals(1, ((List) body.get("created")).size()); + assertTrue(body.get("errors").toString().contains("Pair")); + } + + @Test + void mentorsCannotLookThroughOrChangeGroups() { + signIn(mentor); + String reason = "mentor_cannot_manage"; + assertRefused(reason, controller.getAllGroups()); + assertRefused(reason, controller.searchGroupsByName("Team")); + assertRefused(reason, controller.createGroup(new GroupsApiController.GroupCreateDto("Mine", "3", "CSP", List.of()))); + assertRefused(reason, controller.bulkCreateGroups(new GroupsApiController.BulkGroupCreateDto(List.of()))); + assertRefused(reason, controller.updateGroup(TEAM, new GroupsApiController.GroupUpdateDto("Renamed", null, null))); + assertRefused(reason, controller.deleteGroup(TEAM)); + assertRefused(reason, controller.getGroupGrades(TEAM)); + assertRefused(reason, controller.putGroupGrades(TEAM, new ArrayList<>())); + assertRefused(reason, controller.addGroupGrade(TEAM, new java.util.HashMap<>())); + assertRefused(reason, controller.clearGroupGrades(TEAM)); + assertRefused(reason, controller.getGroupsByPersonId(student.getId())); + assertRefused("mentor_class_group", controller.syncClassMemberships( + org.springframework.security.core.userdetails.User.withUsername(mentor.getUid()) + .password("unused").authorities("ROLE_USER").build(), + new GroupsApiController.ClassMembershipSyncDto(List.of("CSA")))); + verify(groups, never()).deleteById(anyLong()); + } + + @Test + void aMentorSeesTheirOwnGroupsAndTheGroupsTheyAreIn() { + signIn(student); + controller.addPersonToGroup(TEAM, mentor.getId()); + signIn(mentor); + assertEquals(HttpStatus.OK, controller.getGroupsByPersonId(mentor.getId()).getStatusCode()); + assertEquals(HttpStatus.OK, controller.getGroupById(TEAM).getStatusCode()); + assertRefused("mentor_not_in_group", controller.getGroupById(SOLO)); + } + + @Test + void studentsListAndSearchGroupsAsBefore() { + signIn(outsider); + assertEquals(HttpStatus.OK, controller.getAllGroups().getStatusCode()); + assertEquals(HttpStatus.OK, controller.searchGroupsByName("Team").getStatusCode()); + assertEquals(HttpStatus.OK, controller.getGroupById(SOLO).getStatusCode()); + } + + @Test + void aMentorsOwnListHasOnlyTheGroupsTheyMayUse() { + Groups team = group(20L, "Team Plasma", student, teammate, mentor); + Groups solo = group(21L, "Pat And Ana", student, mentor); + Groups csa = group(22L, "CSA", student, teammate, thirdStudent, mentor); + when(classGroups.isClassGroup("CSA")).thenReturn(true); + when(groups.findGroupsByPersonId(mentor.getId())).thenReturn(List.of(team, solo, csa)); + when(groups.findGroupsByPersonId(student.getId())).thenReturn(List.of(team, solo, csa)); + + signIn(mentor); + assertEquals(List.of(20L), groupIds(controller.getGroupsByPersonId(mentor.getId()))); + signIn(student); + assertEquals(List.of(20L, 21L, 22L), groupIds(controller.getGroupsByPersonId(student.getId()))); + } + + @Test + void aMentorMayLeaveEveryClassGroupButJoinNone() { + org.springframework.security.core.userdetails.UserDetails login = org.springframework.security.core.userdetails.User + .withUsername(mentor.getUid()).password("unused").authorities("ROLE_USER").build(); + when(classGroups.syncMemberships(mentor.getUid(), List.of())).thenReturn(List.of()); + + assertEquals(HttpStatus.OK, controller.syncClassMemberships(login, + new GroupsApiController.ClassMembershipSyncDto(List.of())).getStatusCode()); + assertRefused("mentor_class_group", controller.syncClassMemberships(login, + new GroupsApiController.ClassMembershipSyncDto(List.of("CSA")))); + verify(classGroups, never()).syncMemberships(mentor.getUid(), List.of("CSA")); + } + + @SuppressWarnings("unchecked") + private static List groupIds(ResponseEntity response) { + assertEquals(HttpStatus.OK, response.getStatusCode()); + return ((List>) response.getBody()).stream() + .map(group -> ((Number) group.get("id")).longValue()).toList(); + } +} diff --git a/src/test/java/com/open/spring/mvc/groups/GroupMembershipAccessTest.java b/src/test/java/com/open/spring/mvc/groups/GroupMembershipAccessTest.java new file mode 100644 index 000000000..c9eb6a458 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/groups/GroupMembershipAccessTest.java @@ -0,0 +1,236 @@ +package com.open.spring.mvc.groups; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.test.util.ReflectionTestUtils; + +import com.open.spring.mvc.person.Person; +import com.open.spring.mvc.person.PersonJpaRepository; + +/** + * Who may change a group. A group has no owner, so its members add and remove people, as the + * Messages page's Members dialog already lets them, and so do teachers and admins. Anyone may join + * or leave a group that isn't a class group (Join and Leave), but a class group's members come from + * the classes on each student's Profile. Changing a group's name, period or course is for teachers + * and admins, and a group name has no "/", because group chat stores its files under the name. + */ +class GroupMembershipAccessTest { + + private static final long TEAM = 7L; + private static final long CLASS = 9L; + + private final GroupsJpaRepository groups = mock(GroupsJpaRepository.class); + private final PersonJpaRepository people = mock(PersonJpaRepository.class); + private final ClassGroupMembershipService classGroups = mock(ClassGroupMembershipService.class); + private GroupsApiController controller; + + private final Person member = MentorRulesTest.student(1); + private final Person teammate = MentorRulesTest.student(2); + private final Person outsider = MentorRulesTest.student(5); + private final Person another = MentorRulesTest.student(6); + private final Person teacher = MentorRulesTest.teacher(8); + private final Person admin = MentorRulesTest.person(10, "ROLE_USER", "ROLE_ADMIN"); + private Groups team; + + @BeforeEach + void setUp() { + controller = new GroupsApiController(); + ReflectionTestUtils.setField(controller, "groupsRepository", groups); + ReflectionTestUtils.setField(controller, "personRepository", people); + ReflectionTestUtils.setField(controller, "groupChatService", mock(GroupChatService.class)); + ReflectionTestUtils.setField(controller, "classGroupMembershipService", classGroups); + ReflectionTestUtils.setField(controller, "mentorAccess", new MentorAccess(groups, classGroups)); + for (Person person : List.of(member, teammate, outsider, another, teacher, admin)) { + when(people.findByUid(person.getUid())).thenReturn(person); + when(people.findById(person.getId())).thenReturn(Optional.of(person)); + } + team = group(TEAM, "Team Rocket", member, teammate); + group(CLASS, "CSA", member); + when(classGroups.isClassGroup("CSA")).thenReturn(true); + when(groups.findGroupMembersWithRolesRaw(anyLong())).thenReturn(List.of()); + when(groups.findGroupsByPersonId(anyLong())).thenReturn(List.of()); + when(groups.findByName(anyString())).thenReturn(Optional.empty()); + when(groups.save(any(Groups.class))).thenAnswer(call -> call.getArgument(0)); + } + + @AfterEach + void signOut() { + SecurityContextHolder.clearContext(); + } + + @Test + void aMemberAddsAndRemovesOthers() { + signIn(member); + + assertEquals(HttpStatus.OK, controller.addPersonToGroup(TEAM, another.getId()).getStatusCode()); + assertEquals(HttpStatus.OK, controller.removePersonFromGroup(TEAM, teammate.getId()).getStatusCode()); + } + + @Test + void someoneOutsideTheGroupCannotChangeWhoIsInIt() { + signIn(outsider); + + assertEquals(HttpStatus.FORBIDDEN, controller.addPersonToGroup(TEAM, another.getId()).getStatusCode()); + assertEquals(HttpStatus.FORBIDDEN, controller.removePersonFromGroup(TEAM, teammate.getId()).getStatusCode()); + assertEquals(List.of(member, teammate), team.getGroupMembers()); + } + + /** Messages' Find a group adds the signed-in person, and Leave removes them. */ + @Test + void anyoneJoinsAndLeavesAGroupThatIsNotAClassGroup() { + signIn(outsider); + + assertEquals(HttpStatus.OK, controller.addPersonToGroup(TEAM, outsider.getId()).getStatusCode()); + assertEquals(HttpStatus.OK, controller.removePersonFromGroup(TEAM, outsider.getId()).getStatusCode()); + } + + /** The classes on each student's Profile decide who is in a class group, so on these routes only teachers and admins change one. */ + @Test + void onlyTeachersAndAdminsChangeAClassGroup() { + signIn(outsider); + assertEquals(HttpStatus.FORBIDDEN, controller.addPersonToGroup(CLASS, outsider.getId()).getStatusCode()); + + signIn(member); + assertEquals(HttpStatus.FORBIDDEN, controller.addPersonToGroup(CLASS, another.getId()).getStatusCode()); + assertEquals(HttpStatus.FORBIDDEN, controller.removePersonFromGroup(CLASS, member.getId()).getStatusCode()); + assertEquals(HttpStatus.FORBIDDEN, + controller.updateGroup(CLASS, new GroupsApiController.GroupUpdateDto("Not CSA", null, null)).getStatusCode()); + + signIn(teacher); + assertEquals(HttpStatus.OK, controller.addPersonToGroup(CLASS, outsider.getId()).getStatusCode()); + } + + @Test + void teachersAndAdminsManageAnyGroup() { + for (Person staff : List.of(teacher, admin)) { + signIn(staff); + assertEquals(HttpStatus.OK, controller.addPersonToGroup(TEAM, another.getId()).getStatusCode()); + assertEquals(HttpStatus.OK, controller.removePersonFromGroup(TEAM, another.getId()).getStatusCode()); + assertEquals(HttpStatus.OK, rename("Team Rocket 2").getStatusCode()); + } + } + + /** Nothing in pages renames a group, and anyone can be a member of a group they just joined. */ + @Test + void onlyTeachersAndAdminsRenameAGroup() { + for (Person notStaff : List.of(outsider, member)) { + signIn(notStaff); + assertEquals(HttpStatus.FORBIDDEN, rename("Mine now").getStatusCode()); + } + assertEquals("Team Rocket", team.getName()); + + signIn(teacher); + assertEquals(HttpStatus.OK, rename("Team Rocket 2").getStatusCode()); + assertEquals("Team Rocket 2", team.getName()); + } + + /** Profile's class sync, a course's video call room and the assignment course sync find a group by its name. */ + @Test + void aRenameCannotTakeAnotherGroupsName() { + signIn(teacher); + when(groups.findByName("Other Team")).thenReturn(Optional.of(new Groups())); + + assertEquals(HttpStatus.CONFLICT, rename("Other Team").getStatusCode()); + assertEquals(HttpStatus.CONFLICT, rename("CSA").getStatusCode()); + assertEquals("Team Rocket", team.getName()); + } + + /** Those lookups find a class group by its exact name too, so it keeps it. Its period and course can still change. */ + @Test + void aClassGroupKeepsItsName() { + Groups csa = groups.findById(CLASS).orElseThrow(); + for (Person staff : List.of(teacher, admin)) { + signIn(staff); + for (String newName : List.of("Not CSA", "csa")) { + assertEquals(HttpStatus.FORBIDDEN, controller.updateGroup(CLASS, + new GroupsApiController.GroupUpdateDto(newName, null, null)).getStatusCode()); + } + } + assertEquals("CSA", csa.getName()); + + signIn(teacher); + assertEquals(HttpStatus.OK, controller.updateGroup(CLASS, + new GroupsApiController.GroupUpdateDto("CSA", "3", null)).getStatusCode()); + assertEquals("3", csa.getPeriod()); + } + + /** + * Deleting a group also deletes its grades and its group submissions. The Messages page offers + * Delete only to admins, and never for a class group. + */ + @Test + void onlyAnAdminDeletesAGroupAndNeverAClassGroup() { + for (Person notAdmin : List.of(outsider, member, teacher)) { + signIn(notAdmin); + assertEquals(HttpStatus.FORBIDDEN, controller.deleteGroup(TEAM).getStatusCode()); + } + signIn(admin); + assertEquals(HttpStatus.FORBIDDEN, controller.deleteGroup(CLASS).getStatusCode()); + verify(groups, never()).deleteById(anyLong()); + + assertEquals(HttpStatus.OK, controller.deleteGroup(TEAM).getStatusCode()); + verify(groups).deleteById(TEAM); + } + + @Test + void signedOutCannotChangeAGroup() { + assertEquals(HttpStatus.FORBIDDEN, controller.addPersonToGroup(TEAM, outsider.getId()).getStatusCode()); + assertEquals(HttpStatus.FORBIDDEN, controller.removePersonFromGroup(TEAM, teammate.getId()).getStatusCode()); + assertEquals(HttpStatus.FORBIDDEN, rename("x").getStatusCode()); + assertEquals(HttpStatus.FORBIDDEN, controller.deleteGroup(TEAM).getStatusCode()); + } + + @Test + void aGroupNameHasNoSlash() { + signIn(teacher); + assertEquals(HttpStatus.BAD_REQUEST, rename("hop/team").getStatusCode()); + assertEquals("Team Rocket", team.getName()); + + signIn(member); + assertEquals(HttpStatus.BAD_REQUEST, controller.createGroup( + new GroupsApiController.GroupCreateDto("hop/team", "1", "csa", List.of(member.getId()))).getStatusCode()); + + signIn(teacher); + Object bulk = controller.bulkCreateGroups(new GroupsApiController.BulkGroupCreateDto(List.of( + new GroupsApiController.GroupCreateDto("hop/team", "1", "csa", List.of())))).getBody(); + assertEquals(List.of(), ((Map) bulk).get("created")); + verify(groups, never()).save(any(Groups.class)); + } + + private org.springframework.http.ResponseEntity rename(String name) { + return controller.updateGroup(TEAM, new GroupsApiController.GroupUpdateDto(name, null, null)); + } + + private Groups group(long id, String name, Person... initial) { + Groups group = new Groups(); + ReflectionTestUtils.setField(group, "id", id); + group.setName(name); + group.getGroupMembers().addAll(new ArrayList<>(List.of(initial))); + when(groups.findById(id)).thenReturn(Optional.of(group)); + when(groups.findMembersOf(id)).thenAnswer(call -> List.copyOf(group.getGroupMembers())); + return group; + } + + private void signIn(Person person) { + SecurityContextHolder.getContext().setAuthentication( + new UsernamePasswordAuthenticationToken(person.getUid(), null, List.of())); + } +} diff --git a/src/test/java/com/open/spring/mvc/groups/MentorRulesTest.java b/src/test/java/com/open/spring/mvc/groups/MentorRulesTest.java new file mode 100644 index 000000000..b9885f63f --- /dev/null +++ b/src/test/java/com/open/spring/mvc/groups/MentorRulesTest.java @@ -0,0 +1,243 @@ +package com.open.spring.mvc.groups; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.util.ReflectionTestUtils; + +import com.open.spring.mvc.person.Person; + +/** + * MentorRules: who counts as a mentor, and what a mentor may do in chat. A mentor never talks with a student + * privately: not in a direct message. + */ +class MentorRulesTest { + + static Person person(long id, String... roles) { + Person person = new Person(); + ReflectionTestUtils.setField(person, "id", id); + person.setUid("person" + id); + person.setName("Person " + id); + person.setRoles(new ArrayList<>(List.of(roles))); + return person; + } + + static Person student(long id) { + return person(id, "ROLE_USER", "ROLE_STUDENT"); + } + + static Person mentor(long id) { + return person(id, "ROLE_USER", MentorRules.ROLE_MENTOR); + } + + static Person teacher(long id) { + return person(id, "ROLE_USER", "ROLE_TEACHER"); + } + + @Test + void aMentorIsAnAccountWithTheMentorRoleAndNoStaffRole() { + assertTrue(MentorRules.isMentor(mentor(1))); + assertFalse(MentorRules.isMentor(person(2, "ROLE_USER", MentorRules.ROLE_MENTOR, "ROLE_TEACHER"))); + assertFalse(MentorRules.isMentor(person(3, "ROLE_USER", MentorRules.ROLE_MENTOR, "ROLE_ADMIN"))); + assertFalse(MentorRules.isMentor(student(4))); + assertFalse(MentorRules.isMentor(null)); + } + + @Test + void staffAreTeachersAndAdmins() { + assertTrue(MentorRules.isStaff(teacher(1))); + assertTrue(MentorRules.isStaff(person(2, "ROLE_USER", "ROLE_ADMIN"))); + assertFalse(MentorRules.isStaff(student(3))); + assertFalse(MentorRules.isStaff(mentor(4))); + assertFalse(MentorRules.isStaff(null)); + } + + @Test + void directMessagesWithAMentorAreRefused() { + Optional refusal = MentorRules.shareDirectMessages(List.of(student(1), mentor(2))); + assertEquals(Optional.of(MentorRules.Refusal.NO_DIRECT_MESSAGES), refusal); + assertEquals("mentor_no_direct_messages", refusal.get().reason()); + } + + @Test + void directMessagesBetweenStudentsAndTeachersAreAllowed() { + assertEquals(Optional.empty(), MentorRules.shareDirectMessages(List.of(student(1), student(2), teacher(3)))); + } + + // --- Groups: a mentor uses only the team groups they were added to --- + + private static final boolean CLASS_GROUP = true; + private static final boolean TEAM_GROUP = false; + + private static Optional refused(MentorRules.Refusal refusal) { + return Optional.of(refusal); + } + + @Test + void theTeamSizeCountsMembersWhoAreNotMentors() { + assertEquals(2, MentorRules.teamSize(List.of(student(1), teacher(2), mentor(3)))); + assertEquals(0, MentorRules.teamSize(List.of(mentor(3)))); + } + + @Test + void aRepeatedMemberCountsOnce() { + Person mentor = mentor(3); + List sameStudentTwice = List.of(student(1), student(1), mentor); + assertEquals(1, MentorRules.teamSize(sameStudentTwice)); + assertEquals(refused(MentorRules.Refusal.TEAM_TOO_SMALL), MentorRules.useGroup(mentor, TEAM_GROUP, sameStudentTwice)); + assertEquals(refused(MentorRules.Refusal.TEAM_TOO_SMALL), MentorRules.startGroup(student(1), TEAM_GROUP, sameStudentTwice)); + } + + @Test + void membershipIsByIdNotByObject() { + Person loadedOnce = student(1); + Person loadedAgain = student(1); + loadedAgain.setName("Renamed since"); + assertTrue(MentorRules.isMember(loadedOnce, List.of(loadedAgain, student(2)))); + assertFalse(MentorRules.isMember(student(3), List.of(loadedAgain, student(2)))); + assertFalse(MentorRules.isMember(null, List.of(student(2)))); + } + + @Test + void aMemberMentorWithATeamOfTwoCanUseTheGroup() { + Person mentor = mentor(3); + assertEquals(Optional.empty(), MentorRules.useGroup(mentor, TEAM_GROUP, List.of(student(1), student(2), mentor))); + } + + @Test + void aMentorWhoIsNotAMemberIsRefused() { + assertEquals(refused(MentorRules.Refusal.NOT_IN_GROUP), + MentorRules.useGroup(mentor(3), TEAM_GROUP, List.of(student(1), student(2)))); + } + + @Test + void aMentorInAClassGroupIsRefused() { + Person mentor = mentor(3); + assertEquals(refused(MentorRules.Refusal.CLASS_GROUP), + MentorRules.useGroup(mentor, CLASS_GROUP, List.of(student(1), student(2), mentor))); + } + + @Test + void aMentorLosesTheGroupWhenTheTeamDropsBelowTwo() { + Person mentor = mentor(3); + assertEquals(refused(MentorRules.Refusal.TEAM_TOO_SMALL), + MentorRules.useGroup(mentor, TEAM_GROUP, List.of(student(1), mentor))); + assertEquals(refused(MentorRules.Refusal.TEAM_TOO_SMALL), + MentorRules.useGroup(mentor, TEAM_GROUP, List.of(student(1), mentor(4), mentor))); + } + + @Test + void studentsAndTeachersUseGroupsAsBefore() { + assertEquals(Optional.empty(), MentorRules.useGroup(student(1), TEAM_GROUP, List.of(student(2)))); + assertEquals(Optional.empty(), MentorRules.useGroup(teacher(1), CLASS_GROUP, List.of())); + } + + @Test + void aTeamMemberCanAddAMentor() { + Person member = student(1); + assertEquals(Optional.empty(), + MentorRules.addMember(member, mentor(3), TEAM_GROUP, List.of(member, student(2)))); + } + + @Test + void aStudentOutsideTheTeamCannotAddAMentor() { + assertEquals(refused(MentorRules.Refusal.TEAM_MANAGES_MENTORS), + MentorRules.addMember(student(9), mentor(3), TEAM_GROUP, List.of(student(1), student(2)))); + } + + @Test + void aMentorCannotAddAnyoneNotEvenThemselves() { + Person mentor = mentor(3); + List team = List.of(student(1), student(2)); + assertEquals(refused(MentorRules.Refusal.CANNOT_MANAGE), MentorRules.addMember(mentor, mentor, TEAM_GROUP, team)); + assertEquals(refused(MentorRules.Refusal.CANNOT_MANAGE), + MentorRules.addMember(mentor, student(5), TEAM_GROUP, team)); + } + + @Test + void aTeacherCanAddAMentorToAnyTeamGroup() { + assertEquals(Optional.empty(), + MentorRules.addMember(teacher(8), mentor(3), TEAM_GROUP, List.of(student(1), student(2)))); + } + + @Test + void aMentorCannotJoinAOneStudentGroup() { + Person member = student(1); + assertEquals(refused(MentorRules.Refusal.TEAM_TOO_SMALL), + MentorRules.addMember(member, mentor(3), TEAM_GROUP, List.of(member))); + assertEquals(refused(MentorRules.Refusal.TEAM_TOO_SMALL), + MentorRules.addMember(teacher(8), mentor(3), TEAM_GROUP, List.of(student(1)))); + } + + @Test + void aMentorCannotJoinAClassGroup() { + assertEquals(refused(MentorRules.Refusal.CLASS_GROUP), + MentorRules.addMember(teacher(8), mentor(3), CLASS_GROUP, List.of(student(1), student(2)))); + } + + @Test + void addingStudentsWorksAsBefore() { + assertEquals(Optional.empty(), MentorRules.addMember(student(9), student(5), TEAM_GROUP, List.of(student(1)))); + assertEquals(Optional.empty(), MentorRules.addMember(student(9), student(5), CLASS_GROUP, List.of())); + } + + @Test + void aMentorCanLeave() { + Person mentor = mentor(3); + assertEquals(Optional.empty(), MentorRules.removeMember(mentor, mentor(3), List.of(student(1), mentor))); + } + + @Test + void aMentorCannotRemoveAStudent() { + Person mentor = mentor(3); + assertEquals(refused(MentorRules.Refusal.CANNOT_MANAGE), + MentorRules.removeMember(mentor, student(1), List.of(student(1), student(2), mentor))); + } + + @Test + void aStudentCanAlwaysLeave() { + Person member = student(1); + assertEquals(Optional.empty(), MentorRules.removeMember(member, member, List.of(member, mentor(3)))); + } + + @Test + void onlyTheTeamOrATeacherRemovesAMentor() { + Person member = student(1); + Person mentor = mentor(3); + List team = List.of(member, student(2), mentor); + assertEquals(Optional.empty(), MentorRules.removeMember(member, mentor, team)); + assertEquals(Optional.empty(), MentorRules.removeMember(teacher(8), mentor, team)); + assertEquals(refused(MentorRules.Refusal.TEAM_MANAGES_MENTORS), MentorRules.removeMember(student(9), mentor, team)); + } + + @Test + void mentorsCannotManageGroups() { + assertEquals(refused(MentorRules.Refusal.CANNOT_MANAGE), MentorRules.manageGroups(mentor(3))); + assertEquals(Optional.empty(), MentorRules.manageGroups(student(1))); + assertEquals(Optional.empty(), MentorRules.manageGroups(teacher(8))); + } + + @Test + void everyReasonIsDistinct() { + long reasons = java.util.Arrays.stream(MentorRules.Refusal.values()).map(MentorRules.Refusal::reason).distinct().count(); + assertEquals(MentorRules.Refusal.values().length, reasons); + } + + @Test + void aRefusalAnswers403WithItsReason() { + ResponseEntity response = MentorRules.Refusal.NO_DIRECT_MESSAGES.toResponse(); + assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode()); + assertEquals(Map.of( + "error", MentorRules.Refusal.NO_DIRECT_MESSAGES.message(), + "reason", "mentor_no_direct_messages"), response.getBody()); + } +} diff --git a/src/test/java/com/open/spring/mvc/groups/S3Failures.java b/src/test/java/com/open/spring/mvc/groups/S3Failures.java new file mode 100644 index 000000000..344b77e85 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/groups/S3Failures.java @@ -0,0 +1,35 @@ +package com.open.spring.mvc.groups; + +import java.util.List; + +import software.amazon.awssdk.awscore.exception.AwsErrorDetails; +import software.amazon.awssdk.core.exception.SdkClientException; +import software.amazon.awssdk.services.s3.model.S3Exception; + +/** The S3 failures the group chat tests throw from a stand-in S3 client. */ +final class S3Failures { + + private S3Failures() { + } + + /** + * S3 throttled (503 Slow Down), out of reach, or timing out the request (its RequestTimeout + * comes as a 400): failures that clear if you wait. + */ + static List unavailable() { + return List.of( + (S3Exception) S3Exception.builder().statusCode(503).message("Slow Down").build(), + SdkClientException.create("Unable to execute HTTP request: Read timed out"), + (S3Exception) S3Exception.builder().statusCode(400) + .awsErrorDetails(AwsErrorDetails.builder().errorCode("RequestTimeout").build()) + .message("Your socket connection to the server was not read from or written to within the timeout period.") + .build()); + } + + /** No permission, a bad key, or a fault in this server: waiting won't fix these. */ + static List refusalsAndBugs() { + return List.of( + (S3Exception) S3Exception.builder().statusCode(403).message("Access Denied").build(), + new NullPointerException("a bug here, not S3")); + } +} diff --git a/src/test/java/com/open/spring/mvc/groups/TestBeans.java b/src/test/java/com/open/spring/mvc/groups/TestBeans.java new file mode 100644 index 000000000..2191bd37a --- /dev/null +++ b/src/test/java/com/open/spring/mvc/groups/TestBeans.java @@ -0,0 +1,37 @@ +package com.open.spring.mvc.groups; + +import java.lang.reflect.Constructor; +import java.util.Arrays; +import java.util.Comparator; + +import org.mockito.Mockito; + +/** + * Builds a class through its constructor without naming the constructor's parameters. Each + * parameter gets the first object the test passes that fits it, and any other parameter gets a + * Mockito mock. So a test keeps compiling, and keeps running, when another change gives the + * class a dependency the test doesn't care about. + */ +final class TestBeans { + + private TestBeans() { + } + + static T build(Class type, Object... given) { + Constructor constructor = Arrays.stream(type.getDeclaredConstructors()) + .max(Comparator.comparingInt(Constructor::getParameterCount)) + .orElseThrow(); + Object[] args = Arrays.stream(constructor.getParameterTypes()) + .map(parameter -> Arrays.stream(given) + .filter(parameter::isInstance) + .findFirst() + .orElseGet(() -> Mockito.mock(parameter))) + .toArray(); + try { + constructor.setAccessible(true); + return type.cast(constructor.newInstance(args)); + } catch (ReflectiveOperationException e) { + throw new IllegalStateException("Could not build " + type.getSimpleName(), e); + } + } +} diff --git a/src/test/java/com/open/spring/mvc/push/PushNotificationSnippetTest.java b/src/test/java/com/open/spring/mvc/push/PushNotificationSnippetTest.java new file mode 100644 index 000000000..6b45dca88 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/push/PushNotificationSnippetTest.java @@ -0,0 +1,64 @@ +package com.open.spring.mvc.push; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; + +import java.time.Duration; + +import org.junit.jupiter.api.Test; + +/** + * The text a phone shows for a direct message: the words a reader sees in the chat, without + * the markers the page reads ([[reply:…]], [[files:…]], [[code:…]], [[pin:…]]) or the rich + * composer's HTML. + */ +class PushNotificationSnippetTest { + + @Test + void chatMarkersAreLeftOut() { + assertEquals("thanks!", PushNotificationService.snippet("[[reply:9|Bob|hey%20there]] thanks!")); + assertEquals("look", PushNotificationService.snippet("[[files:f~shots%2Fa.png~5]] look")); + // Pages escapes brackets, "|", "%", "<", ">" and "&" in code, but keeps quotes, tabs and newlines. + assertEquals("try this", PushNotificationService.snippet( + "[[code:python|print(\"hi\")\nfor i in range(3):\n\tprint(i)]] try this")); + assertEquals("see this", PushNotificationService.snippet( + "[[reply:9|Bob|hey]] [[files:f~a.txt~1]] [[code:java|int x;]] see this")); + } + + @Test + void aMessageThatIsOnlyAMarkerSaysWhatItDid() { + assertEquals("pinned a message", PushNotificationService.snippet("[[pin:401]]")); + assertEquals("unpinned a message", PushNotificationService.snippet("[[unpin:401]]")); + assertEquals("sent code", PushNotificationService.snippet("[[code:python|print(1)]]")); + assertEquals("shared files", PushNotificationService.snippet("[[files:f~a.png~5]]")); + // A reply that only attaches an image has nothing but its reply marker in the body. + assertEquals("sent a message", PushNotificationService.snippet("[[reply:9|Bob|hey]]")); + } + + @Test + void theComposersHtmlBecomesPlainText() { + assertEquals("check https://github.com/o/r/pull/3", PushNotificationService.snippet( + "check " + + "https://github.com/o/r/pull/3 ")); + assertEquals("Fish & chips tonight", PushNotificationService.snippet("Fish & chips
    tonight")); + assertEquals("a < b", PushNotificationService.snippet("a < b")); + } + + @Test + void longTextIsCutAndBlankStaysBlank() { + String cut = PushNotificationService.snippet("x".repeat(200)); + assertEquals(140, cut.length()); + assertEquals('…', cut.charAt(139)); + assertEquals("", PushNotificationService.snippet(null)); + assertEquals("", PushNotificationService.snippet(" ")); + } + + @Test + void markerOpeningsThatNeverCloseStayFast() { + // None of these markers closes, so a pattern that rescans the rest of the body at each + // "[[" takes seconds here; matching has to stay linear. + String body = "[[code:".repeat(20_000); + String text = assertTimeoutPreemptively(Duration.ofSeconds(1), () -> PushNotificationService.snippet(body)); + assertEquals(140, text.length()); + } +} diff --git a/src/test/java/com/open/spring/mvc/reactions/MessageReactionServiceTest.java b/src/test/java/com/open/spring/mvc/reactions/MessageReactionServiceTest.java new file mode 100644 index 000000000..aa27a3c2b --- /dev/null +++ b/src/test/java/com/open/spring/mvc/reactions/MessageReactionServiceTest.java @@ -0,0 +1,171 @@ +package com.open.spring.mvc.reactions; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import com.open.spring.mvc.person.Person; +import com.open.spring.mvc.reactions.MessageReactionService.ReactionSummary; +import com.open.spring.mvc.reactions.MessageReactionService.Reactor; + +/** + * Saving a reaction once, removing it safely, and the summaries both chats send: reactions in + * the enum's order, people by name, and nobody listed who no longer has an account. + */ +class MessageReactionServiceTest { + + private MessageReactionJpaRepository repository; + private MessageReactionService service; + // "ada" is lowercase on purpose: it sorts before "Ana" only when case is ignored. + private Person ada; + private Person ana; + private Person ben; + + @BeforeEach + void setUp() { + repository = mock(MessageReactionJpaRepository.class); + service = new MessageReactionService(repository); + ada = person(1L, "ada", "ada"); + ana = person(2L, "ana", "Ana"); + ben = person(3L, "ben", "Ben"); + } + + @Test + void addSavesANewReactionOnce() { + MessageReaction.Key key = new MessageReaction.Key(ChatType.DM, 7L, "42", 1L, Reaction.LIKE); + when(repository.existsById(key)).thenReturn(true); + service.add(ChatType.DM, 7L, "42", ada, Reaction.LIKE); + verify(repository, never()).save(any()); + + when(repository.existsById(key)).thenReturn(false); + service.add(ChatType.DM, 7L, "42", ada, Reaction.LIKE); + verify(repository).save(new MessageReaction(key)); + } + + @Test + void removeIsOneDeleteStatement() { + // Read-then-delete let two removes at once fail the second; one statement just deletes 0 rows. + service.remove(ChatType.DM, 7L, "42", ada, Reaction.LIKE); + + verify(repository).deleteOne(ChatType.DM, 7L, "42", 1L, Reaction.LIKE); + verify(repository, never()).existsById(any()); + verify(repository, never()).deleteById(any()); + } + + @Test + void summariesFollowTheTableOrderAndSortPeople() { + when(repository.findByKeyChatTypeAndKeyChatIdAndKeyMessageId(ChatType.DM, 7L, "42")).thenReturn(List.of( + row(ChatType.DM, 7L, "42", 3L, Reaction.WOW), + row(ChatType.DM, 7L, "42", 2L, Reaction.LIKE), + row(ChatType.DM, 7L, "42", 1L, Reaction.LIKE))); + when(repository.findReactorNames(any())).thenReturn(List.of(name(ben), name(ana), name(ada))); + + List summaries = service.forMessage(ChatType.DM, 7L, "42"); + + assertEquals(List.of( + new ReactionSummary("like", List.of(new Reactor("ada", "ada"), new Reactor("ana", "Ana"))), + new ReactionSummary("wow", List.of(new Reactor("ben", "Ben")))), summaries); + } + + @Test + void aPersonWhoIsGoneIsLeftOut() { + when(repository.findByKeyChatTypeAndKeyChatIdAndKeyMessageId(ChatType.DM, 7L, "42")).thenReturn(List.of( + row(ChatType.DM, 7L, "42", 1L, Reaction.LIKE), + row(ChatType.DM, 7L, "42", 2L, Reaction.LIKE), + row(ChatType.DM, 7L, "42", 2L, Reaction.SAD))); + // Person 2's account is gone, so their Like goes and their Sad, now nobody's, goes too. + when(repository.findReactorNames(any())).thenReturn(List.of(name(ada))); + + assertEquals(List.of(new ReactionSummary("like", List.of(new Reactor("ada", "ada")))), + service.forMessage(ChatType.DM, 7L, "42")); + } + + @Test + void forMessageNowReadsTheSameSummary() { + when(repository.findByKeyChatTypeAndKeyChatIdAndKeyMessageId(ChatType.DM, 7L, "42")).thenReturn(List.of( + row(ChatType.DM, 7L, "42", 1L, Reaction.LIKE))); + when(repository.findReactorNames(any())).thenReturn(List.of(name(ada))); + + assertEquals(service.forMessage(ChatType.DM, 7L, "42"), service.forMessageNow(ChatType.DM, 7L, "42")); + } + + @Test + void forChatKeysByMessageId() { + when(repository.findByKeyChatTypeAndKeyChatId(ChatType.GROUP, 3L)).thenReturn(List.of( + row(ChatType.GROUP, 3L, "42", 1L, Reaction.LIKE), + row(ChatType.GROUP, 3L, "57", 3L, Reaction.HAHA), + row(ChatType.GROUP, 3L, "60", 9L, Reaction.LIKE))); + when(repository.findReactorNames(any())).thenReturn(List.of(name(ada), name(ben))); + + Map> byMessage = service.forChat(ChatType.GROUP, 3L); + + // "60" is left out: its only reaction is from someone whose account is gone. + assertEquals(Map.of( + "42", List.of(new ReactionSummary("like", List.of(new Reactor("ada", "ada")))), + "57", List.of(new ReactionSummary("haha", List.of(new Reactor("ben", "Ben"))))), byMessage); + } + + @Test + void removeAllForDeletesThatMessagesReactionsInOneStatement() { + service.removeAllFor(ChatType.GROUP, 3L, "abc"); + + verify(repository).deleteAllOnMessage(ChatType.GROUP, 3L, "abc"); + } + + // Reactors are read as id, uid and name only, never as whole accounts with their links. + private static MessageReactionJpaRepository.ReactorName name(Person person) { + return new MessageReactionJpaRepository.ReactorName() { + @Override + public Long getId() { + return person.getId(); + } + + @Override + public String getUid() { + return person.getUid(); + } + + @Override + public String getName() { + return person.getName(); + } + }; + } + + private static MessageReaction row(ChatType type, long chatId, String messageId, long personId, Reaction reaction) { + return new MessageReaction(new MessageReaction.Key(type, chatId, messageId, personId, reaction)); + } + + private static Person person(long id, String uid, String name) { + Person person = new Person(); + // Submitter has no id setter; the DM tests set it the same way. + ReflectionTestUtils.setField(person, "id", id); + person.setUid(uid); + person.setName(name); + return person; + } + + @Test + void removingAMessagesReactionsCommitsOnItsOwn() throws Exception { + // Chats remove a deleted message's reactions after the delete commits. Spring runs a + // transactional call made then inside the finished transaction, where nothing commits, + // unless it asks for a new one. + Transactional transactional = MessageReactionService.class + .getMethod("removeAllFor", ChatType.class, Long.class, String.class) + .getAnnotation(Transactional.class); + + assertEquals(Propagation.REQUIRES_NEW, transactional.propagation()); + } +} diff --git a/src/test/java/com/open/spring/mvc/reactions/MessageReactionTableInitializerTest.java b/src/test/java/com/open/spring/mvc/reactions/MessageReactionTableInitializerTest.java new file mode 100644 index 000000000..27093fe61 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/reactions/MessageReactionTableInitializerTest.java @@ -0,0 +1,96 @@ +package com.open.spring.mvc.reactions; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; +import org.springframework.boot.ApplicationRunner; +import org.springframework.boot.DefaultApplicationArguments; +import org.springframework.dao.DataAccessException; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.SingleConnectionDataSource; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; + +/** The statement that creates message_reaction at startup, run on SQLite as a local server does. */ +class MessageReactionTableInitializerTest { + + private static final String INSERT = "INSERT INTO message_reaction " + + "(chat_type, chat_id, message_id, person_id, reaction) VALUES (?, ?, ?, ?, ?)"; + + private SingleConnectionDataSource dataSource; + private JdbcTemplate jdbc; + + @BeforeEach + void setUp() { + dataSource = new SingleConnectionDataSource("jdbc:sqlite::memory:", true); + jdbc = new JdbcTemplate(dataSource); + } + + @AfterEach + void tearDown() { + dataSource.destroy(); + } + + @Test + void createsTheTableAndCanRunTwice() { + jdbc.execute(MessageReactionTableInitializer.CREATE_TABLE); + jdbc.execute(MessageReactionTableInitializer.CREATE_TABLE); + + jdbc.update(INSERT, "DM", 7L, "42", 1L, "LIKE"); + + assertEquals(1, jdbc.queryForObject("SELECT COUNT(*) FROM message_reaction", Integer.class)); + } + + @Test + void rejectsTheSameReactionTwice() { + jdbc.execute(MessageReactionTableInitializer.CREATE_TABLE); + jdbc.update(INSERT, "DM", 7L, "42", 1L, "LIKE"); + + assertThrows(DataAccessException.class, () -> jdbc.update(INSERT, "DM", 7L, "42", 1L, "LIKE")); + jdbc.update(INSERT, "DM", 7L, "42", 1L, "LOVE"); + + assertEquals(2, jdbc.queryForObject("SELECT COUNT(*) FROM message_reaction", Integer.class)); + } + + // Startup goes on, as it does for the other tables (calls, calendar), but the log says plainly + // that reactions are broken: a warning was easy to miss. + @Test + void aFailedCreateIsLoggedAsAnErrorAndStartupGoesOn() { + JdbcTemplate failing = new JdbcTemplate(dataSource) { + @Override + public void execute(String sql) { + throw new DataAccessResourceFailureException("the database is read-only"); + } + }; + ApplicationRunner runner = new MessageReactionTableInitializer(failing).migrateMessageReaction(); + Logger logger = (Logger) LoggerFactory.getLogger(MessageReactionTableInitializer.class); + Level previous = logger.getLevel(); + ListAppender logs = new ListAppender<>(); + logs.start(); + logger.addAppender(logs); + logger.setLevel(Level.INFO); + try { + assertDoesNotThrow(() -> runner.run(new DefaultApplicationArguments())); + } finally { + logger.detachAppender(logs); + logger.setLevel(previous); + logs.stop(); + } + + assertEquals(1, logs.list.size()); + ILoggingEvent event = logs.list.get(0); + assertEquals(Level.ERROR, event.getLevel()); + assertTrue(event.getFormattedMessage().contains("reactions won't work"), event.getFormattedMessage()); + assertTrue(event.getFormattedMessage().contains("the database is read-only"), event.getFormattedMessage()); + } +} diff --git a/src/test/java/com/open/spring/mvc/reactions/ReactionTest.java b/src/test/java/com/open/spring/mvc/reactions/ReactionTest.java new file mode 100644 index 000000000..26f259e98 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/reactions/ReactionTest.java @@ -0,0 +1,34 @@ +package com.open.spring.mvc.reactions; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +import org.junit.jupiter.api.Test; + +/** + * The reaction keys are a contract with the Pages client: Messages' reactions.js lists the + * same keys in the same order, and a route's {reaction} is read with fromKey. + */ +class ReactionTest { + + @Test + void everyKeyRoundTrips() { + for (Reaction reaction : Reaction.values()) { + assertEquals(Optional.of(reaction), Reaction.fromKey(reaction.key())); + } + List keys = Arrays.stream(Reaction.values()).map(Reaction::key).toList(); + assertEquals(List.of("like", "love", "haha", "wow", "sad", "celebrate"), keys); + } + + @Test + void unknownKeysAreRefused() { + assertTrue(Reaction.fromKey(null).isEmpty()); + assertTrue(Reaction.fromKey("").isEmpty()); + assertTrue(Reaction.fromKey("LIKE").isEmpty()); + assertTrue(Reaction.fromKey("thumbsup").isEmpty()); + } +} diff --git a/src/test/java/com/open/spring/mvc/uibuilder/UiBuilderPageServiceTest.java b/src/test/java/com/open/spring/mvc/uibuilder/UiBuilderPageServiceTest.java index 4936dc0ea..b0b441214 100644 --- a/src/test/java/com/open/spring/mvc/uibuilder/UiBuilderPageServiceTest.java +++ b/src/test/java/com/open/spring/mvc/uibuilder/UiBuilderPageServiceTest.java @@ -712,6 +712,20 @@ void messagingTheOwnerOpensOneConversationButNotWithYourself() { assertEquals(Outcome.NOT_FOUND, service.messageOwner(ada, "draft-page").outcome()); } + @Test + void messagingTheOwnerIsRefusedWhenAMentorWouldBeInTheConversation() { + publish(hop, create(hop, "Flood Watch"), "flood-watch"); + Person patPerson = store.person(9, "pat", "Pat Mentor"); + patPerson.setRoles(new java.util.ArrayList<>(List.of("ROLE_USER", "ROLE_MENTOR"))); + + assertEquals(Outcome.MENTOR_NO_DIRECT_MESSAGES, service.messageOwner(UiBuilderTestStore.student(patPerson), "flood-watch").outcome()); + hopPerson.setRoles(new java.util.ArrayList<>(List.of("ROLE_USER", "ROLE_MENTOR"))); + assertEquals(Outcome.MENTOR_NO_DIRECT_MESSAGES, service.messageOwner(ada, "flood-watch").outcome()); + verify(store.directMessages, never()).getOrCreateConversation(any(), anyList()); + assertEquals(HttpStatus.FORBIDDEN, UiBuilderException.statusOf(Outcome.MENTOR_NO_DIRECT_MESSAGES)); + assertEquals("mentor_no_direct_messages", UiBuilderException.codeOf(Outcome.MENTOR_NO_DIRECT_MESSAGES)); + } + // ---- leases ---- @Test