From fd1a44e4771dbb3b1661d249aa9dbbd6e4400d43 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Thu, 19 Nov 2026 10:42:16 -0800 Subject: [PATCH 01/13] Mentors can't send or receive direct messages A direct message that includes a mentor (ROLE_MENTOR and no teacher or admin role) can't be started, sent or edited, whoever is sending it. Reading old messages and deleting your own still work, so the navbar bell and /dm keep answering. Refusals answer 403 with an error and a reason (mentor_no_direct_messages) a page can show its own words for. The rules live in MentorRules, a class of static methods the controllers ask with the people they already loaded. --- .../DirectMessageApiController.java | 18 ++ .../open/spring/mvc/groups/MentorRules.java | 73 ++++++++ .../DirectMessageMentorTest.java | 156 ++++++++++++++++++ .../spring/mvc/groups/MentorRulesTest.java | 84 ++++++++++ 4 files changed, 331 insertions(+) create mode 100644 src/main/java/com/open/spring/mvc/groups/MentorRules.java create mode 100644 src/test/java/com/open/spring/mvc/directmessages/DirectMessageMentorTest.java create mode 100644 src/test/java/com/open/spring/mvc/groups/MentorRulesTest.java 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 9dab2859..0f51f7b8 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; @@ -22,6 +23,7 @@ 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; @@ -149,6 +151,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 +213,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 +260,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); } 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 00000000..e6381456 --- /dev/null +++ b/src/main/java/com/open/spring/mvc/groups/MentorRules.java @@ -0,0 +1,73 @@ +package com.open.spring.mvc.groups; + +import java.util.Collection; +import java.util.Map; +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. + * + * 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"; + + /** 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."); + + 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 && person.hasRole(ROLE_MENTOR) && !isStaff(person); + } + + /** True for a teacher or an admin. */ + public static boolean isStaff(Person person) { + return person != null && (person.hasRole("ROLE_TEACHER") || person.hasRole("ROLE_ADMIN")); + } + + /** 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(); + } +} 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 00000000..eb14f50b --- /dev/null +++ b/src/test/java/com/open/spring/mvc/directmessages/DirectMessageMentorTest.java @@ -0,0 +1,156 @@ +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.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; + +/** + * 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); + 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()); + } + + @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/groups/MentorRulesTest.java b/src/test/java/com/open/spring/mvc/groups/MentorRulesTest.java new file mode 100644 index 00000000..9ec0dc75 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/groups/MentorRulesTest.java @@ -0,0 +1,84 @@ +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)))); + } + + @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()); + } +} From c1a3ab3c5782c14e0314722bef8bb0fae3d79e9a Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Thu, 19 Nov 2026 10:51:58 -0800 Subject: [PATCH 02/13] Mentors use only their team's group, and the team manages its mentors A mentor (ROLE_MENTOR and no teacher or admin role) reads, posts and shares files only in a group they are a member of, that isn't a class group and has at least 2 members who aren't mentors. Only a member who isn't a mentor, or a teacher, adds or removes a mentor; a mentor adds no one and may only leave. A new group may start with a mentor only if its maker could have added them. Mentors can't list, search, make, rename or delete groups, change group grades, join class groups or read another person's groups. Everyone else gets the answers they had before. Refusals answer 403 with a reason. Group responses mark each member as a mentor or not. MentorAccess loads a group's members (one query, since open-in-view is off) and whether it is a class group, and asks MentorRules. --- AGENTS.md | 1 + docs/group-chat-architecture.md | 26 +- .../groups/ClassGroupMembershipService.java | 5 + .../mvc/groups/GroupChatApiController.java | 49 +++- .../mvc/groups/GroupsApiController.java | 163 +++++++++-- .../mvc/groups/GroupsJpaRepository.java | 19 ++ .../open/spring/mvc/groups/MentorAccess.java | 63 +++++ .../open/spring/mvc/groups/MentorRules.java | 126 ++++++++- .../ClassGroupMembershipServiceTest.java | 8 + .../spring/mvc/groups/GroupChatFilesTest.java | 3 +- .../mvc/groups/GroupChatMentorTest.java | 154 ++++++++++ .../mvc/groups/GroupChatRegressionTest.java | 3 +- .../mvc/groups/GroupMembersMentorTest.java | 264 ++++++++++++++++++ .../spring/mvc/groups/MentorRulesTest.java | 159 +++++++++++ 14 files changed, 1011 insertions(+), 32 deletions(-) create mode 100644 src/main/java/com/open/spring/mvc/groups/MentorAccess.java create mode 100644 src/test/java/com/open/spring/mvc/groups/GroupChatMentorTest.java create mode 100644 src/test/java/com/open/spring/mvc/groups/GroupMembersMentorTest.java diff --git a/AGENTS.md b/AGENTS.md index 9e7bb279..b060b462 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -37,6 +37,7 @@ 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`. Everyone else keeps the old answers, so leave those routes' non-mentor behavior alone. 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,GroupChatMentorTest,GroupMembersMentorTest,DirectMessageMentorTest'`. - [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`. ## Assignment grading diff --git a/docs/group-chat-architecture.md b/docs/group-chat-architecture.md index 1d0dc01c..3fd7c4f8 100644 --- a/docs/group-chat-architecture.md +++ b/docs/group-chat-architecture.md @@ -108,7 +108,7 @@ Edits and deletes made through REST are broadcast too, as `editMessageServer` an ## 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`) @@ -143,6 +143,27 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) | 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 | | 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 are answered as before, without the extra query. + +| Route | A mentor | Everyone else | +|---|---|---| +| `/api/groups/chat/{id}/messages` (read, send, edit, delete), `/read`, `/files`; `GET /api/groups/{id}` | 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`) | 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` | 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) | 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. +- Not covered yet: the group socket. Anyone can subscribe to `/topic/group/{id}`, and a socket `sendFile` needs no sign-in (see Known issues). A direct message topic already admits only that conversation's participants (`DirectMessageTopicGuard`). +- Tests: `./mvnw test -Dtest='Mentor*Test,GroupChatMentorTest,GroupMembersMentorTest,DirectMessageMentorTest'`. + ## Persistence | Data | Where | Notes | @@ -171,7 +192,8 @@ 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 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 group socket checks no one.** `/ws-chat` is `permitAll`, so anyone, signed in or not, can subscribe to `/topic/group/{id}` and receive what is posted there live, and `sendFile` stores a file in any group under the name the client gives. 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. 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 c65801af..4cfa374b 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 60eaaf80..04024a06 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java @@ -47,18 +47,29 @@ public class GroupChatApiController { private final GroupChatReadService readService; private final GroupsJpaRepository groupsRepository; private final PersonJpaRepository personRepository; + private final MentorAccess mentorAccess; public GroupChatApiController( GroupChatService groupChatService, GroupChatRealtimeService realtimeService, GroupChatReadService readService, GroupsJpaRepository groupsRepository, - PersonJpaRepository personRepository) { + PersonJpaRepository personRepository, + MentorAccess mentorAccess) { this.groupChatService = groupChatService; this.realtimeService = realtimeService; this.readService = readService; 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. 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 +139,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 +168,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 +200,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) { @@ -215,6 +242,10 @@ 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); @@ -250,6 +281,10 @@ public ResponseEntity deleteMessage( if (identity == null) { return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); } + ResponseEntity refusal = mentorRefusal(groupOpt.get()); + if (refusal != null) { + return refusal; + } try { realtimeService.deleteMessage(groupId, messageId, identity.getUid()); @@ -294,6 +329,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 +344,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) { @@ -365,6 +408,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) { 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 1454ca33..5d6cf820 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; @@ -23,6 +25,7 @@ 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 +47,11 @@ public class GroupsApiController { @Autowired private ClassGroupMembershipService classGroupMembershipService; + @Autowired + private MentorAccess mentorAccess; + + private static final RolesJsonConverter ROLES = new RolesJsonConverter(); + // ===== DTOs ===== @Data @NoArgsConstructor @@ -79,6 +87,37 @@ 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); + } + + /** 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 +126,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 +134,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 +150,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 +174,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 +195,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()) { @@ -172,8 +229,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 +264,11 @@ 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; + } try { if (dto.getName() == null || dto.getName().isEmpty()) { return new ResponseEntity<>( @@ -219,6 +284,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 +300,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 +325,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<>(); @@ -275,6 +349,14 @@ public ResponseEntity> bulkCreateGroups(@RequestBody BulkGro 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 +365,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 +402,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 +412,10 @@ public ResponseEntity> syncClassMemberships( ); } + if (MentorRules.isMentor(personRepository.findByUid(userDetails.getUsername()))) { + return MentorRules.Refusal.CLASS_GROUP.toResponse(); + } + try { List memberships = classGroupMembershipService.syncMemberships( userDetails.getUsername(), @@ -352,9 +435,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()) { @@ -392,7 +479,11 @@ 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; + } try { Optional groupOpt = groupsRepository.findById(id); if (groupOpt.isEmpty()) { @@ -422,7 +513,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 +536,12 @@ 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(); + } + if (!group.getGroupMembers().contains(person)) { return new ResponseEntity<>( Map.of("error", "Person not in group"), @@ -469,7 +566,7 @@ public ResponseEntity> removePersonFromGroup( */ @PostMapping("/{id}/members/{personId}") @Transactional - public ResponseEntity> addPersonToGroup( + public ResponseEntity addPersonToGroup( @PathVariable Long id, @PathVariable Long personId) { try { @@ -492,6 +589,12 @@ 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(); + } + if (group.getGroupMembers().contains(person)) { return new ResponseEntity<>( Map.of("error", "Person already in group"), @@ -515,6 +618,10 @@ 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); @@ -529,6 +636,10 @@ public ResponseEntity getGroupGrades(@PathVariable Long id) { @Transactional public ResponseEntity putGroupGrades(@PathVariable Long id, @RequestBody List> grades) { + ResponseEntity mentorRefusal = mentorManageRefusal(); + if (mentorRefusal != null) { + return mentorRefusal; + } Optional groupOpt = groupsRepository.findById(id); if (groupOpt.isEmpty()) return new ResponseEntity<>(HttpStatus.NOT_FOUND); @@ -548,6 +659,10 @@ 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); @@ -613,6 +728,10 @@ public ResponseEntity addGroupGrade(@PathVariable Long id, @DeleteMapping("/{id}/grades") @Transactional public ResponseEntity clearGroupGrades(@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); 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 911e4f55..448a40d9 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 00000000..1a1e4588 --- /dev/null +++ b/src/main/java/com/open/spring/mvc/groups/MentorAccess.java @@ -0,0 +1,63 @@ +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)); + } + + /** 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 index e6381456..5a9f1978 100644 --- a/src/main/java/com/open/spring/mvc/groups/MentorRules.java +++ b/src/main/java/com/open/spring/mvc/groups/MentorRules.java @@ -2,6 +2,7 @@ import java.util.Collection; import java.util.Map; +import java.util.Objects; import java.util.Optional; import org.springframework.http.HttpStatus; @@ -11,8 +12,13 @@ /** * 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. + * 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. @@ -22,10 +28,23 @@ 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."); + "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; @@ -56,12 +75,35 @@ 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 && person.hasRole(ROLE_MENTOR) && !isStaff(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 && (person.hasRole("ROLE_TEACHER") || person.hasRole("ROLE_ADMIN")); + 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. */ @@ -70,4 +112,78 @@ public static Optional shareDirectMessages(Collection people) { ? 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/test/java/com/open/spring/mvc/groups/ClassGroupMembershipServiceTest.java b/src/test/java/com/open/spring/mvc/groups/ClassGroupMembershipServiceTest.java index 86a41af4..4916809a 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/GroupChatFilesTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatFilesTest.java index 6953ce1f..e321585d 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupChatFilesTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatFilesTest.java @@ -107,7 +107,8 @@ private void useStorage(InMemoryStorage store) { GroupChatRealtimeService realtime = new GroupChatRealtimeService(chat, groups, messaging); 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, + new MentorAccess(groups, mock(ClassGroupMembershipService.class))); Groups group = new Groups(); group.setName("CSA"); 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 00000000..c2454f9e --- /dev/null +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatMentorTest.java @@ -0,0 +1,154 @@ +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.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; + +/** + * 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 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); + } + + @BeforeEach + void setUp() { + chat = mock(GroupChatService.class); + realtime = mock(GroupChatRealtimeService.class); + groups = mock(GroupsJpaRepository.class); + classGroups = mock(ClassGroupMembershipService.class); + people = mock(PersonJpaRepository.class); + controller = new GroupChatApiController(chat, realtime, mock(GroupChatReadService.class), groups, people, + 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")); + } + + 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="))); + verify(realtime, never()).publishMessage(anyLong(), anyString(), any(), any()); + verify(realtime, never()).publishFile(anyLong(), any(), anyString(), anyString()); + verify(chat, never()).getMessages(anyString()); + } + + @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"))); + } + + @Test + void aMentorInAClassGroupIsRefused() { + signIn(mentor); + assertRefused("mentor_class_group", controller.getMessages(CLASS)); + } + + @Test + void aStudentWhoIsNotAMemberStillReadsAsBefore() { + signIn(outsider); + assertEquals(HttpStatus.OK, controller.getMessages(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()); + } +} 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 c310e301..13046b0c 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupChatRegressionTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatRegressionTest.java @@ -52,7 +52,8 @@ void setUp() { reads = new GroupChatReadService(readStates, groups, chat); realtime = new GroupChatRealtimeService(chat, groups, mock(SimpMessagingTemplate.class)); PersonJpaRepository people = mock(PersonJpaRepository.class); - controller = new GroupChatApiController(chat, realtime, reads, groups, people); + controller = new GroupChatApiController(chat, realtime, reads, groups, people, + new MentorAccess(groups, mock(ClassGroupMembershipService.class))); Groups group = spy(new Groups()); when(group.getId()).thenReturn(7L); 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 00000000..4715f326 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/groups/GroupMembersMentorTest.java @@ -0,0 +1,264 @@ +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. Students + * manage everyone else as before. + */ +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 studentsStillAddStudentsAsBefore() { + signIn(outsider); + 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()); + } +} diff --git a/src/test/java/com/open/spring/mvc/groups/MentorRulesTest.java b/src/test/java/com/open/spring/mvc/groups/MentorRulesTest.java index 9ec0dc75..b9885f63 100644 --- a/src/test/java/com/open/spring/mvc/groups/MentorRulesTest.java +++ b/src/test/java/com/open/spring/mvc/groups/MentorRulesTest.java @@ -73,6 +73,165 @@ 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(); From 68224a852ab1323c82638acf2e43f3406ff101ea Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Thu, 19 Nov 2026 21:26:47 -0800 Subject: [PATCH 03/13] Mentors list and download shared files only in their team's group after the mentor rules were written, so a mentor could list and download any group's shared files. Both now ask MentorAccess like the other group chat routes: a mentor gets them only for a group they belong to, that isn't a class group and has at least 2 members who aren't mentors. Everyone else gets the answers they had before. --- docs/group-chat-architecture.md | 4 ++-- .../mvc/groups/GroupChatApiController.java | 8 ++++++++ .../mvc/groups/GroupChatMentorTest.java | 19 +++++++++++++++++++ 3 files changed, 29 insertions(+), 2 deletions(-) diff --git a/docs/group-chat-architecture.md b/docs/group-chat-architecture.md index 3fd7c4f8..cbd979cf 100644 --- a/docs/group-chat-architecture.md +++ b/docs/group-chat-architecture.md @@ -149,7 +149,7 @@ A mentor is an account with `ROLE_MENTOR` and no teacher or admin role. Flask ve | Route | A mentor | Everyone else | |---|---|---| -| `/api/groups/chat/{id}/messages` (read, send, edit, delete), `/read`, `/files`; `GET /api/groups/{id}` | 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 | +| `/api/groups/chat/{id}/messages` (read, send, edit, delete), `/read`, `/files` (list, upload), `/files/index`, `/files/content`; `GET /api/groups/{id}` | 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`) | 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` | Refused (`mentor_class_group`) | As before | @@ -192,7 +192,7 @@ 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 that isn't a mentor 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. Mentors are checked: see [Mentors](#mentors). +- **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 group socket checks no one.** `/ws-chat` is `permitAll`, so anyone, signed in or not, can subscribe to `/topic/group/{id}` and receive what is posted there live, and `sendFile` stores a file in any group under the name the client gives. 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. 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 04024a06..e34610db 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java @@ -373,6 +373,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); } @@ -387,6 +391,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); diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatMentorTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatMentorTest.java index c2454f9e..3a1c4e27 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupChatMentorTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatMentorTest.java @@ -1,5 +1,6 @@ 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.anyLong; @@ -9,6 +10,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; import java.util.Optional; @@ -108,9 +110,13 @@ void aMentorWhoIsNotAMemberIsRefusedEverywhere() { 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()); } @Test @@ -126,6 +132,18 @@ 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 @@ -138,6 +156,7 @@ void aMentorInAClassGroupIsRefused() { void aStudentWhoIsNotAMemberStillReadsAsBefore() { signIn(outsider); assertEquals(HttpStatus.OK, controller.getMessages(TEAM).getStatusCode()); + assertEquals(HttpStatus.OK, controller.getSharedFileIndex(TEAM).getStatusCode()); verify(groups, never()).findMembersOf(anyLong()); } From fd20fdb3c59c94afad4d6afa88af18be94d63771 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Wed, 25 Nov 2026 19:29:06 -0800 Subject: [PATCH 04/13] Mentors: the older chat, the UI Builder and a mentor's own list follow the rules too A review found three more ways around the mentor rules, and one rule that was too strict. - The older /api/chat/{groupId} keeps its own chat file per group. A mentor reads and posts there only where they may use the group's chat. - The UI Builder's "message the owner" opened a direct message without the check, so it now refuses one that would include a mentor (mentor_no_direct_messages, 403). - A mentor's own group list holds only the groups they may use, so no page offers one Spring would refuse, and they don't see its members. - A mentor may now send an empty class list, to leave every class group. Any class is still refused. The docs also no longer say a socket sendFile needs no sign-in: the socket drops events without a signed-in identity, but it doesn't check the mentor rules for one that has it. --- AGENTS.md | 2 +- docs/group-chat-architecture.md | 14 +- .../spring/mvc/chat/ChatApiController.java | 33 ++++- .../mvc/groups/GroupsApiController.java | 9 +- .../mvc/uibuilder/UiBuilderException.java | 2 +- .../mvc/uibuilder/UiBuilderPageService.java | 8 +- .../spring/mvc/chat/LegacyChatMentorTest.java | 140 ++++++++++++++++++ .../mvc/groups/GroupMembersMentorTest.java | 35 +++++ .../uibuilder/UiBuilderPageServiceTest.java | 14 ++ 9 files changed, 243 insertions(+), 14 deletions(-) create mode 100644 src/test/java/com/open/spring/mvc/chat/LegacyChatMentorTest.java diff --git a/AGENTS.md b/AGENTS.md index b060b462..77bed312 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -37,7 +37,7 @@ 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`. Everyone else keeps the old answers, so leave those routes' non-mentor behavior alone. 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,GroupChatMentorTest,GroupMembersMentorTest,DirectMessageMentorTest'`. +- 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`. Everyone else keeps the old answers, so leave those routes' non-mentor behavior alone. 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,GroupChatMentorTest,GroupMembersMentorTest,DirectMessageMentorTest'`. - [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`. ## Assignment grading diff --git a/docs/group-chat-architecture.md b/docs/group-chat-architecture.md index cbd979cf..2956b5d8 100644 --- a/docs/group-chat-architecture.md +++ b/docs/group-chat-architecture.md @@ -145,23 +145,23 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) ## 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 are answered as before, without the extra query. +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), `/read`, `/files` (list, upload), `/files/index`, `/files/content`; `GET /api/groups/{id}` | 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`) | As before | +| `/api/groups/chat/{id}/messages` (read, send, edit, delete), `/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` | Refused (`mentor_class_group`) | As before | +| `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) | Refused (`mentor_no_direct_messages`) | Refused when the conversation would include a mentor. Reading old messages and deleting your own still work | +| `POST /api/dm/conversations`, `/api/dm/conversations/{id}/messages` (send, edit), 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. -- Not covered yet: the group socket. Anyone can subscribe to `/topic/group/{id}`, and a socket `sendFile` needs no sign-in (see Known issues). A direct message topic already admits only that conversation's participants (`DirectMessageTopicGuard`). +- Not covered yet: the group socket. Anyone can subscribe to `/topic/group/{id}` and read what is posted there live, and `GroupChatWebSocketController` doesn't apply these rules to an event from a signed-in socket (see Known issues). A direct message topic already admits only that conversation's participants (`DirectMessageTopicGuard`). - Tests: `./mvnw test -Dtest='Mentor*Test,GroupChatMentorTest,GroupMembersMentorTest,DirectMessageMentorTest'`. ## Persistence @@ -193,7 +193,7 @@ These were each reproduced against a local server built from `master` on 2026-10 - **`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 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 group socket checks no one.** `/ws-chat` is `permitAll`, so anyone, signed in or not, can subscribe to `/topic/group/{id}` and receive what is posted there live, and `sendFile` stores a file in any group under the name the client gives. Direct message topics are guarded (`DirectMessageTopicGuard`). +- **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, but it checks no membership or mentor rule for one that has one. 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. 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 d1a6e1f0..1527b797 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,11 +65,15 @@ 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) { @@ -66,7 +89,7 @@ public ResponseEntity> getChat(@PathVariable Long groupId) { @PostMapping("/{groupId}") @Transactional - public ResponseEntity> postChat( + public ResponseEntity postChat( @PathVariable Long groupId, @RequestBody ChatMessageRequest request) { Optional groupOpt = groupsRepository.findById(groupId); @@ -82,6 +105,10 @@ public ResponseEntity> postChat( if (!isMember(groupOpt.get(), currentUsername)) { return new ResponseEntity<>(HttpStatus.FORBIDDEN); } + ResponseEntity refusal = mentorRefusal(groupOpt.get()); + if (refusal != null) { + return refusal; + } if (request == null || request.getContent() == null || request.getContent().isBlank()) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); 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 5d6cf820..8e17b217 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupsApiController.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupsApiController.java @@ -211,6 +211,11 @@ public ResponseEntity getGroupsByPersonId(@PathVariable Long personId) { } 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) { @@ -412,7 +417,9 @@ public ResponseEntity syncClassMemberships( ); } - if (MentorRules.isMentor(personRepository.findByUid(userDetails.getUsername()))) { + // 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(); } 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 2a6add9c..23f7aba0 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 e2c67316..e024832f 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/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 00000000..29fb5079 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/chat/LegacyChatMentorTest.java @@ -0,0 +1,140 @@ +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. A mentor uses it only where they may use the group's + * chat (MentorRules); everyone else reads and posts as before. + */ +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 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)) { + 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 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 studentsReadAnyOlderChatAndPostInTheirOwnAsBefore() { + signIn(outsider); + assertEquals(HttpStatus.OK, controller.getChat(OTHERS).getStatusCode()); + 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/groups/GroupMembersMentorTest.java b/src/test/java/com/open/spring/mvc/groups/GroupMembersMentorTest.java index 4715f326..8ada8e61 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupMembersMentorTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupMembersMentorTest.java @@ -261,4 +261,39 @@ void studentsListAndSearchGroupsAsBefore() { 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/uibuilder/UiBuilderPageServiceTest.java b/src/test/java/com/open/spring/mvc/uibuilder/UiBuilderPageServiceTest.java index 4936dc0e..b0b44121 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 From 39e4061a4fda8e6cbb02c96d08bb11c637250b70 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Wed, 25 Nov 2026 19:43:24 -0800 Subject: [PATCH 05/13] Mentors: the chat socket's group events follow the rules too A socket can carry a signed-in identity (a Spring /login session gives the handshake its Principal), and GroupChatWebSocketController then ran sendMessage, sendFile, joinGroup, typing and heartbeat for any group. It now drops those events when the mentor rules refuse the signed-in mentor that group, as the REST routes do. Leaving always works, and everyone else's events work as before. --- docs/group-chat-architecture.md | 5 +- .../groups/GroupChatWebSocketController.java | 23 ++++ .../mvc/groups/GroupChatSocketMentorTest.java | 113 ++++++++++++++++++ 3 files changed, 139 insertions(+), 2 deletions(-) create mode 100644 src/test/java/com/open/spring/mvc/groups/GroupChatSocketMentorTest.java diff --git a/docs/group-chat-architecture.md b/docs/group-chat-architecture.md index 2956b5d8..f4f4376b 100644 --- a/docs/group-chat-architecture.md +++ b/docs/group-chat-architecture.md @@ -161,7 +161,8 @@ A mentor is an account with `ROLE_MENTOR` and no teacher or admin role. Flask ve - `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. -- Not covered yet: the group socket. Anyone can subscribe to `/topic/group/{id}` and read what is posted there live, and `GroupChatWebSocketController` doesn't apply these rules to an event from a signed-in socket (see Known issues). A direct message topic already admits only that conversation's participants (`DirectMessageTopicGuard`). +- 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. +- 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,GroupChatMentorTest,GroupMembersMentorTest,DirectMessageMentorTest'`. ## Persistence @@ -193,7 +194,7 @@ These were each reproduced against a local server built from `master` on 2026-10 - **`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 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). -- **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, but it checks no membership or mentor rule for one that has one. Direct message topics are guarded (`DirectMessageTopicGuard`). +- **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. 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 30cee03f..6b7849f6 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatWebSocketController.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatWebSocketController.java @@ -7,6 +7,9 @@ import org.springframework.messaging.handler.annotation.Payload; import org.springframework.stereotype.Controller; +import com.open.spring.mvc.person.Person; +import com.open.spring.mvc.person.PersonJpaRepository; + import lombok.RequiredArgsConstructor; /** @@ -23,6 +26,9 @@ public class GroupChatWebSocketController { private final GroupChatIdentityService identityService; private final GroupChatRealtimeService realtimeService; private final GroupChatPresenceService presenceService; + private final MentorAccess mentorAccess; + private final PersonJpaRepository personRepository; + private final GroupsJpaRepository groupsRepository; @MessageMapping("/groups.chat") public void handleGroupEvent(@Payload GroupChatEvent event, @@ -41,6 +47,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(uid, groupId)) { + return; + } + switch (event.getContext()) { case "joinGroup" -> { if (groupId == null) { @@ -107,6 +119,17 @@ public void handleGroupEvent(@Payload GroupChatEvent event, } } + /** True when the mentor rules refuse this account the group. Only a mentor can be refused (see MentorRules). */ + private boolean mentorRefuses(String uid, Long groupId) { + Person person = personRepository.findByUid(uid); + if (!MentorRules.isMentor(person)) { + return false; + } + return groupsRepository.findById(groupId) + .map(group -> mentorAccess.toUse(person, group).isPresent()) + .orElse(false); + } + private void ensureJoined(String sessionId, Long groupId, String sender) { if (!presenceService.isSessionInGroup(sessionId, groupId)) { presenceService.joinGroup(sessionId, groupId, sender); 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 00000000..4fd3c28c --- /dev/null +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatSocketMentorTest.java @@ -0,0 +1,113 @@ +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.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.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. + */ +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, groups); + 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()); + } + + @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 studentsSocketsSendAsBefore() { + send(student, "sendMessage", OTHERS); + send(student, "sendMessage", SOLO); + verify(realtime, times(2)).publishMessage(anyLong(), anyString(), any(), any()); + verify(groups, never()).findMembersOf(anyLong()); + } +} From 68186793d3d0847712694f5bc92051d304b7812b Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Wed, 25 Nov 2026 20:15:20 -0800 Subject: [PATCH 06/13] Older chat: only a group's members, teachers and admins read /api/chat GET /api/chat/{groupId} had its membership check commented out, so any signed-in account could read any group's older chat. It now answers 403 to anyone who isn't in the group, unless they're a teacher or admin. Posting still needs membership, as before. No page reads this route. --- docs/group-chat-architecture.md | 2 +- .../spring/mvc/chat/ChatApiController.java | 17 ++++++------ .../spring/mvc/chat/LegacyChatMentorTest.java | 27 +++++++++++++++---- 3 files changed, 32 insertions(+), 14 deletions(-) diff --git a/docs/group-chat-architecture.md b/docs/group-chat-architecture.md index f4f4376b..b7ea6717 100644 --- a/docs/group-chat-architecture.md +++ b/docs/group-chat-architecture.md @@ -193,7 +193,7 @@ 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 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). +- **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. 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 1527b797..69e4e8f3 100644 --- a/src/main/java/com/open/spring/mvc/chat/ChatApiController.java +++ b/src/main/java/com/open/spring/mvc/chat/ChatApiController.java @@ -75,14 +75,15 @@ public ResponseEntity getChat(@PathVariable Long groupId) { 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); } diff --git a/src/test/java/com/open/spring/mvc/chat/LegacyChatMentorTest.java b/src/test/java/com/open/spring/mvc/chat/LegacyChatMentorTest.java index 29fb5079..68271a8f 100644 --- a/src/test/java/com/open/spring/mvc/chat/LegacyChatMentorTest.java +++ b/src/test/java/com/open/spring/mvc/chat/LegacyChatMentorTest.java @@ -30,8 +30,8 @@ import com.open.spring.mvc.person.PersonJpaRepository; /** - * The older /api/chat/{groupId} keeps its own chat file per group. A mentor uses it only where they may use the group's - * chat (MentorRules); everyone else reads and posts as before. + * 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 { @@ -54,6 +54,8 @@ private static Person person(long id, String... roles) { 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; @@ -77,7 +79,7 @@ void setUp() { 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)) { + for (Person person : List.of(student, teammate, mentor, outsider, teacher, admin)) { when(people.findByUid(person.getUid())).thenReturn(person); } group(OTHERS, "Team Rocket", student, teammate); @@ -129,9 +131,24 @@ void aMentorInTheirTeamUsesItsOlderChat() { } @Test - void studentsReadAnyOlderChatAndPostInTheirOwnAsBefore() { + 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.OK, controller.getChat(OTHERS).getStatusCode()); assertEquals(HttpStatus.FORBIDDEN, controller.postChat(OTHERS, text("hi")).getStatusCode()); signIn(student); assertEquals(HttpStatus.OK, controller.postChat(OTHERS, text("hi")).getStatusCode()); From 3ff34447652ceb19100ef837edeb708e13195a23 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Wed, 25 Nov 2026 21:02:01 -0800 Subject: [PATCH 07/13] Older chat: a mentor outside the group hears why a post is refused POST /api/chat/{groupId} checked membership before the mentor rule, so a mentor posting to a group they aren't in got a 403 with no reason. The mentor rule now goes first and answers mentor_not_in_group; anyone else outside the group still gets the plain 403. --- .../java/com/open/spring/mvc/chat/ChatApiController.java | 7 ++++--- .../com/open/spring/mvc/chat/LegacyChatMentorTest.java | 7 +++++++ 2 files changed, 11 insertions(+), 3 deletions(-) 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 69e4e8f3..d361e3ca 100644 --- a/src/main/java/com/open/spring/mvc/chat/ChatApiController.java +++ b/src/main/java/com/open/spring/mvc/chat/ChatApiController.java @@ -103,13 +103,14 @@ public ResponseEntity postChat( return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); } - if (!isMember(groupOpt.get(), currentUsername)) { - return new ResponseEntity<>(HttpStatus.FORBIDDEN); - } + // 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); + } if (request == null || request.getContent() == null || request.getContent().isBlank()) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); diff --git a/src/test/java/com/open/spring/mvc/chat/LegacyChatMentorTest.java b/src/test/java/com/open/spring/mvc/chat/LegacyChatMentorTest.java index 68271a8f..26595406 100644 --- a/src/test/java/com/open/spring/mvc/chat/LegacyChatMentorTest.java +++ b/src/test/java/com/open/spring/mvc/chat/LegacyChatMentorTest.java @@ -115,6 +115,13 @@ void aMentorWhoIsNotInTheGroupCantReadItsOlderChat() { 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); From db2251101cb0c62d33087a916e6bbc26bf9576cf Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Wed, 25 Nov 2026 21:20:51 -0800 Subject: [PATCH 08/13] Unread count: a mentor's leaves out the groups they may not use A mentor's own group list already leaves out a group Spring refuses them (a class group, or a team that dropped below 2 members who aren't mentors). The unread count still counted those groups, and marking one read is refused, so the bell kept saying "New messages in 1 group" with no way to open or clear it. MentorAccess.refusesGroup answers for one group id, and getUnread drops every group it refuses. Everyone else's count is unchanged. --- .../mvc/groups/GroupChatApiController.java | 5 ++- .../open/spring/mvc/groups/MentorAccess.java | 8 ++++ .../mvc/groups/GroupChatMentorTest.java | 40 ++++++++++++++++++- 3 files changed, 51 insertions(+), 2 deletions(-) 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 e34610db..9cc700f7 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java @@ -308,7 +308,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<>(); diff --git a/src/main/java/com/open/spring/mvc/groups/MentorAccess.java b/src/main/java/com/open/spring/mvc/groups/MentorAccess.java index 1a1e4588..f3a061ac 100644 --- a/src/main/java/com/open/spring/mvc/groups/MentorAccess.java +++ b/src/main/java/com/open/spring/mvc/groups/MentorAccess.java @@ -32,6 +32,14 @@ public Optional toUse(Person person, Groups group) { 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)) { diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatMentorTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatMentorTest.java index 3a1c4e27..cbc4394e 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupChatMentorTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatMentorTest.java @@ -11,6 +11,8 @@ 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; @@ -50,6 +52,8 @@ class GroupChatMentorTest { 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); @@ -57,6 +61,12 @@ private void group(long id, String name, boolean classGroup, Person... members) 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 @@ -66,7 +76,9 @@ void setUp() { groups = mock(GroupsJpaRepository.class); classGroups = mock(ClassGroupMembershipService.class); people = mock(PersonJpaRepository.class); - controller = new GroupChatApiController(chat, realtime, mock(GroupChatReadService.class), groups, people, + GroupChatReadService reads = + new GroupChatReadService(mock(GroupChatReadStateJpaRepository.class), groups, chat); + controller = new GroupChatApiController(chat, realtime, reads, groups, people, new MentorAccess(groups, classGroups)); for (Person person : List.of(student, teammate, mentor, otherMentor, outsider)) { when(people.findByUid(person.getUid())).thenReturn(person); @@ -92,6 +104,16 @@ private static void assertRefused(String reason, ResponseEntity response) { 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); @@ -170,4 +192,20 @@ void aMentorSeesOnlyTheirOwnChatAnalytics() { 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())); + } } From 8f478f073c23824396f245db1f38fd04cc84059f Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Wed, 25 Nov 2026 21:20:51 -0800 Subject: [PATCH 09/13] Chat socket: only a mentor's events load their account The mentor check loaded the person for every group event, typing and heartbeats included, for everyone with a signed-in socket. 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 now skips the lookup. A mentor's events still load the person and the group, through the same MentorAccess.refusesGroup the unread count uses. --- .../groups/GroupChatWebSocketController.java | 26 ++++++++------ .../mvc/groups/GroupChatSocketMentorTest.java | 35 +++++++++++++++++-- 2 files changed, 49 insertions(+), 12 deletions(-) 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 6b7849f6..bce64661 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatWebSocketController.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatWebSocketController.java @@ -1,13 +1,15 @@ 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.Person; import com.open.spring.mvc.person.PersonJpaRepository; import lombok.RequiredArgsConstructor; @@ -28,7 +30,6 @@ public class GroupChatWebSocketController { private final GroupChatPresenceService presenceService; private final MentorAccess mentorAccess; private final PersonJpaRepository personRepository; - private final GroupsJpaRepository groupsRepository; @MessageMapping("/groups.chat") public void handleGroupEvent(@Payload GroupChatEvent event, @@ -49,7 +50,7 @@ public void handleGroupEvent(@Payload GroupChatEvent event, // 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(uid, groupId)) { + if (groupId != null && !"leaveGroup".equals(event.getContext()) && mentorRefuses(principal, groupId)) { return; } @@ -119,15 +120,20 @@ public void handleGroupEvent(@Payload GroupChatEvent event, } } - /** True when the mentor rules refuse this account the group. Only a mentor can be refused (see MentorRules). */ - private boolean mentorRefuses(String uid, Long groupId) { - Person person = personRepository.findByUid(uid); - if (!MentorRules.isMentor(person)) { + /** + * 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 groupsRepository.findById(groupId) - .map(group -> mentorAccess.toUse(person, group).isPresent()) - .orElse(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) { diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatSocketMentorTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatSocketMentorTest.java index 4fd3c28c..85d5e65a 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupChatSocketMentorTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatSocketMentorTest.java @@ -4,6 +4,7 @@ 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; @@ -16,6 +17,8 @@ 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; @@ -24,7 +27,7 @@ /** * 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. + * 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 { @@ -59,7 +62,7 @@ void setUp() { classGroups = mock(ClassGroupMembershipService.class); people = mock(PersonJpaRepository.class); controller = new GroupChatWebSocketController(mock(GroupChatIdentityService.class), realtime, presence, - new MentorAccess(groups, classGroups), people, groups); + new MentorAccess(groups, classGroups), people); for (Person person : List.of(student, teammate, mentor)) { when(people.findByUid(person.getUid())).thenReturn(person); } @@ -75,6 +78,14 @@ private void send(Person person, String context, long groupId) { 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")) { @@ -103,6 +114,26 @@ void aMentorsSocketWorksInTheirTeamAndCanAlwaysLeave() { 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); From de44f736d0aaa49fcccb130deccb7b797f5141f8 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Wed, 25 Nov 2026 21:20:52 -0800 Subject: [PATCH 10/13] Mentor docs: the unread count, the socket's sign-in roles, one test command The Mentors section says the unread count leaves out a group the mentor may not use, and that the socket reads the sign-in's roles first (a role given since counts from the next sign-in). The test command in the doc and AGENTS.md missed the socket and older-chat tests; *Mentor*Test runs them all. --- AGENTS.md | 2 +- docs/group-chat-architecture.md | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 77bed312..5ed3a221 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -37,7 +37,7 @@ 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`. Everyone else keeps the old answers, so leave those routes' non-mentor behavior alone. 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,GroupChatMentorTest,GroupMembersMentorTest,DirectMessageMentorTest'`. +- 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`. Everyone else keeps the old answers, so leave those routes' non-mentor behavior alone. 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'`. - [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`. ## Assignment grading diff --git a/docs/group-chat-architecture.md b/docs/group-chat-architecture.md index b7ea6717..f9e342a0 100644 --- a/docs/group-chat-architecture.md +++ b/docs/group-chat-architecture.md @@ -160,10 +160,10 @@ A mentor is an account with `ROLE_MENTOR` and no teacher or admin role. Flask ve - 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 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. +- 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,GroupChatMentorTest,GroupMembersMentorTest,DirectMessageMentorTest'`. +- Tests: `./mvnw test -Dtest='*Mentor*Test'`. ## Persistence From 7ecc34977cf1909ffb3925db21b6ea86e200f452 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Wed, 25 Nov 2026 20:28:45 -0800 Subject: [PATCH 11/13] Groups: check who adds or removes members, edits or deletes a group Adding or removing a member of an existing group now needs the caller to be one of the group's members, a teacher or an admin. Outside the mentor rules, anyone may still join or leave a group that isn't a class group. Through the member routes only teachers and admins add or remove people in a class group; students join and leave theirs through the classes on their Profile. Changing a group's name, period or course 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. No group name, made or renamed, can contain "/". Deleting is admin-only and never a class group, the same rule the Messages page uses to show Delete. --- AGENTS.md | 3 +- .../mvc/groups/GroupsApiController.java | 99 ++++++++ .../mvc/groups/GroupMembersMentorTest.java | 9 +- .../mvc/groups/GroupMembershipAccessTest.java | 236 ++++++++++++++++++ 4 files changed, 342 insertions(+), 5 deletions(-) create mode 100644 src/test/java/com/open/spring/mvc/groups/GroupMembershipAccessTest.java diff --git a/AGENTS.md b/AGENTS.md index 5ed3a221..21eb0b69 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -37,7 +37,8 @@ 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`. Everyone else keeps the old answers, so leave those routes' non-mentor behavior alone. 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'`. +- 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`. - [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`. ## Assignment grading 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 8e17b217..017f887f 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupsApiController.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupsApiController.java @@ -105,6 +105,60 @@ 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); + } + /** 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<>(); @@ -274,6 +328,9 @@ public ResponseEntity createGroup(@RequestBody GroupCreateDto dto) { if (mentorRefusal != null) { return mentorRefusal; } + if (hasSlash(dto.getName())) { + return slashInName(); + } try { if (dto.getName() == null || dto.getName().isEmpty()) { return new ResponseEntity<>( @@ -349,6 +406,10 @@ public ResponseEntity bulkCreateGroups(@RequestBody BulkGroupCreateDto dto) { 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; @@ -459,6 +520,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()); @@ -491,6 +572,10 @@ public ResponseEntity deleteGroup (@PathVariable Long id) { 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()) { @@ -499,6 +584,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<>( @@ -549,6 +638,11 @@ public ResponseEntity removePersonFromGroup( 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"), @@ -602,6 +696,11 @@ public ResponseEntity addPersonToGroup( 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"), diff --git a/src/test/java/com/open/spring/mvc/groups/GroupMembersMentorTest.java b/src/test/java/com/open/spring/mvc/groups/GroupMembersMentorTest.java index 8ada8e61..80ed4f08 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupMembersMentorTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupMembersMentorTest.java @@ -30,8 +30,9 @@ /** * 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. Students - * manage everyone else as before. + * 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 { @@ -160,8 +161,8 @@ void aTeacherAddsAMentor() { } @Test - void studentsStillAddStudentsAsBefore() { - signIn(outsider); + void membersStillAddStudentsAsBefore() { + signIn(student); assertEquals(HttpStatus.OK, controller.addPersonToGroup(TEAM, thirdStudent.getId()).getStatusCode()); } 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 00000000..c9eb6a45 --- /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())); + } +} From 95a24791678530f9d3f3341d752d058fd2ec5bd9 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Wed, 25 Nov 2026 21:35:23 -0800 Subject: [PATCH 12/13] Group grades: only teachers, admins and the group's graders change them Replacing or clearing a group's grades (PUT and DELETE /api/groups/{id}/grades) is for teachers and admins, since that changes every assignment's entry at once. Adding one assignment's entry (POST), which also copies it into each member's own grades, is for them and for whoever grades the group on that assignment: its creators and graders, and the graders of the group's submission to it. Mentors still get the mentor refusal first. --- AGENTS.md | 1 + .../mvc/groups/GroupsApiController.java | 72 +++++++ .../mvc/groups/GroupGradesAccessTest.java | 198 ++++++++++++++++++ 3 files changed, 271 insertions(+) create mode 100644 src/test/java/com/open/spring/mvc/groups/GroupGradesAccessTest.java diff --git a/AGENTS.md b/AGENTS.md index 21eb0b69..ef272164 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -39,6 +39,7 @@ Entity-removal helpers (run before any large cleanup): - 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`): 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`. ## Assignment grading 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 017f887f..813fb36f 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupsApiController.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupsApiController.java @@ -23,6 +23,10 @@ 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; @@ -50,6 +54,15 @@ public class GroupsApiController { @Autowired private MentorAccess mentorAccess; + @Autowired + private AssignmentJpaRepository assignmentRepository; + + @Autowired + private AssignmentSubmissionJPA submissionRepository; + + @Autowired + private AssignmentAuthorizationService assignmentAuthorizationService; + private static final RolesJsonConverter ROLES = new RolesJsonConverter(); // ===== DTOs ===== @@ -159,6 +172,54 @@ 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)); + } + + /** 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<>(); @@ -746,6 +807,10 @@ public ResponseEntity putGroupGrades(@PathVariable Long id, 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); @@ -773,6 +838,9 @@ public ResponseEntity addGroupGrade(@PathVariable Long 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) --- @@ -838,6 +906,10 @@ public ResponseEntity clearGroupGrades(@PathVariable Long id) { 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/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 00000000..46d2dd40 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/groups/GroupGradesAccessTest.java @@ -0,0 +1,198 @@ +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 change a group's grades. 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.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()); + } + + @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())); + } +} From b567f3020f9f721f7f7db98267e4c4b426c45012 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Wed, 25 Nov 2026 22:19:17 -0800 Subject: [PATCH 13/13] Group grades: only members, graders and staff read them Reading a group's grades (GET /api/groups/{id}/grades) is now for its members, teachers and admins, and whoever grades one of its submissions, the same idea as the submission listings. Mentors still get the mentor refusal first. --- AGENTS.md | 2 +- .../mvc/groups/GroupsApiController.java | 27 +++++++++++++++++++ .../mvc/groups/GroupGradesAccessTest.java | 27 ++++++++++++++++--- 3 files changed, 52 insertions(+), 4 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index ef272164..332a3b08 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -39,7 +39,7 @@ Entity-removal helpers (run before any large cleanup): - 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`): 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`. +- 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`. ## Assignment grading 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 813fb36f..d36eee3f 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupsApiController.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupsApiController.java @@ -194,6 +194,30 @@ private boolean gradesGroupOn(Person caller, Groups group, Object assignmentIdVa .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) { @@ -791,6 +815,9 @@ public ResponseEntity getGroupGrades(@PathVariable Long id) { } 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); } diff --git a/src/test/java/com/open/spring/mvc/groups/GroupGradesAccessTest.java b/src/test/java/com/open/spring/mvc/groups/GroupGradesAccessTest.java index 46d2dd40..d151a228 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupGradesAccessTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupGradesAccessTest.java @@ -32,9 +32,11 @@ import com.open.spring.mvc.person.PersonJpaRepository; /** - * Who may change a group's grades. 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. + * 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 { @@ -78,6 +80,7 @@ void setUp() { 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}, @@ -170,6 +173,24 @@ void anEntryWithoutAnAssignmentIsForTeachersAndAdmins() { 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());