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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ Entity-removal helpers (run before any large cleanup):
- Course groups are the canonical uppercase list `CSA, CSP, CSH, CSSE`, configured as `courses.class-groups` plus `courses.periods[NAME]` in [application.properties](src/main/resources/application.properties) and bound by [CourseGroupProperties.java](src/main/java/com/open/spring/mvc/groups/CourseGroupProperties.java). That one config block drives both the `Groups` rows seeded by `ModelInit` and the class list `ClassGroupMembershipService` validates against, so course names and bell periods only need changing in one place. A single period can be overridden in `.env` (`courses.periods[CSA]=4`) because Spring merges map entries per key, whereas overriding `courses.class-groups` replaces the entire list. List order matters — it is the order memberships are returned in. Startup fails if a listed group has no period. Profile class selection syncs via `PUT /api/groups/class-memberships` (`GroupsApiController` → `ClassGroupMembershipService.syncMemberships`), which only adds/removes membership in those four groups and leaves all other groups untouched.
- Realtime chat uses STOMP over a **second connector on port 8589**: broker config in `WebSocketBrokerConfig.java` (`/ws-chat`, `/app`, `/topic`), port gating in `ChatWebSocketPortFilter.java`, presence in `GroupChatPresenceService.java`. The native `/websocket` endpoint in `mvc/mortevision/nativesocket/WebSocketConfig.java` is separate.
- Gotcha: Java package is `mvc.groups` (plural) but templates live in `templates/group/` (singular); static JS exists both as legacy files in `static/js/group-*.js` and packaged versions in `static/js/group/*.js` — prefer the latter.
- Mentors (`ROLE_MENTOR` without a teacher or admin role) are limited by `MentorRules` (static methods, `mvc/groups`) and `MentorAccess` (loads a group's members and whether it is a class group): no direct message that includes a mentor; a mentor uses only a non-class group they belong to with at least 2 members who aren't mentors; only the team or a teacher adds or removes a mentor, and a mentor adds no one. Refusals are 403 with a `reason`. The mentor rules leave everyone else's answers alone; the next line says who else may change a group. A new route that reads or writes a group's chat, or opens a direct message, must ask `MentorAccess` or `MentorRules` too, as the older `/api/chat` and the UI Builder's message-owner do. Membership checks use `GroupsJpaRepository.findMembersOf`, since `spring.jpa.open-in-view=false` stops `Groups.groupMembers` loading in the chat controller. Tests: `./mvnw test -Dtest='*Mentor*Test'`.
- Changing a group (`GroupsApiController`): adding or removing a member of an existing group (`POST` and `DELETE /api/groups/{id}/members/{personId}`) is for its members, teachers and admins (`managesGroup`), since a group has no owner. Outside the mentor rules, anyone may join or leave a group that isn't a class group. On these routes only teachers and admins add or remove people in a class group; students join and leave theirs through the classes on their Profile (`PUT /api/groups/class-memberships`). Changing a group's name, period or course (`PUT /api/groups/{id}`) is for teachers and admins. A class group keeps its name, and a new name can't be another group's or a class group's name, because Profile's class sync, a course's video call room and the assignment course sync find groups by name. No group name, made or renamed, can contain "/", since group chat's S3 folders use it. Deleting (`DELETE /api/groups/{id}`) is admin-only and never a class group, the same rule the Messages page uses to show Delete. Test: `GroupMembershipAccessTest`.
- A group's grades (`/api/groups/{id}/grades`): 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
Expand Down
27 changes: 25 additions & 2 deletions docs/group-chat-architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`)

Expand Down Expand Up @@ -143,6 +143,28 @@ 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 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}`; the older `/api/chat/{groupId}` (read, post) | Only a group they are a member of, that isn't a class group and has at least 2 members who aren't mentors (`mentor_not_in_group`, `mentor_class_group`, `mentor_team_too_small`) | As before |
| `GET /api/groups/person/{personId}`, `GET /api/groups/chat/analytics/{personId}` | Only their own id (`mentor_cannot_manage`). Their own group list holds only the groups they may use | As before |
| `GET /api/groups`, `/search`, `POST /api/groups`, `/bulk`, `PUT` and `DELETE /api/groups/{id}`, `/{id}/grades` | Refused (`mentor_cannot_manage`) | As before, except that a new group's `memberIds` may hold a mentor only if its maker could add them |
| `PUT /api/groups/class-memberships` | Only an empty list, to leave every class group; any class is refused (`mentor_class_group`) | As before |
| `POST /api/groups/{id}/members/{personId}` | Refused, themselves included (`mentor_cannot_manage`) | Adding a mentor needs a member who isn't a mentor, or a teacher (`team_manages_mentors`), and a group a mentor may use. Adding anyone else: as before |
| `DELETE /api/groups/{id}/members/{personId}` | Only themselves, to leave (`mentor_cannot_manage`) | Removing a mentor needs a member who isn't a mentor, or a teacher (`team_manages_mentors`). Leaving: always |
| `POST /api/dm/conversations`, `/api/dm/conversations/{id}/messages` (send, edit), and the UI Builder's `POST /api/ui-builder/published/{slug}/message-owner` | Refused (`mentor_no_direct_messages`) | Refused when the conversation would include a mentor. Reading old messages and deleting your own still work |

- A group response marks each member `"mentor": true` or `false`, so a page can list a team's mentors.
- `POST /api/groups/bulk` makes the other groups when one breaks a mentor rule, and lists that one under `errors` with the refusal's message (one bad group doesn't stop a teacher's batch), so its answer stays 200.
- Members are counted once each: a new group's `memberIds` may repeat an id, and the team size counts different people.
- If a team drops below 2 members who aren't mentors, its mentor loses the group until it is back to 2. Nobody is stopped from leaving. The mentor's unread count (`GET /api/groups/chat/unread`) leaves that group out too, as their own group list does, so the bell never points at a group they can't open.
- The socket follows the same rule: `GroupChatWebSocketController` drops a signed-in mentor's group events (send, file, join, typing, heartbeat) for a group they may not use. Leaving always works. A socket from Spring's own pages carries the roles of its sign-in, so only a mentor's events load their account; a role given after that sign-in counts from the next one.
- Not covered yet: anyone can still subscribe to `/topic/group/{id}` and read what is posted there live (see Known issues). A direct message topic already admits only that conversation's participants (`DirectMessageTopicGuard`).
- Tests: `./mvnw test -Dtest='*Mentor*Test'`.

## Persistence

| Data | Where | Notes |
Expand Down Expand Up @@ -171,7 +193,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, download and upload its files, and manage any group, its members and its grades. The membership checks in `GroupChatApiController` are commented out. Mentors are checked: see [Mentors](#mentors). The older `/api/chat/{groupId}` (`ChatApiController`, its own `chat_history.jsonl` per group) does check: only a group's members, teachers and admins read it, and only members post.
- **Anyone can follow a group's socket topic.** `/ws-chat` is `permitAll`, so anyone, signed in or not, can subscribe to `/topic/group/{id}` and receive what is posted there live. `GroupChatWebSocketController` drops an event from a socket with no signed-in identity, and checks no membership for one that has one (mentors are checked: see [Mentors](#mentors)). Direct message topics are guarded (`DirectMessageTopicGuard`).
- **Edit and delete require the stored author uid.** The REST controller passes the authenticated account's uid through the realtime service; display names never establish ownership. Legacy messages without `author_uid` cannot be edited or deleted through these routes. Teachers cannot delete another account's message.
- **Two sends at once can lose one.** Each send reads the group's S3 file, adds a line and writes the file back, without a lock.
- **The first group created after a restart fails on SQLite.** `POST /api/groups` returns 500 with `SQLITE_BUSY_SNAPSHOT` the first time after the server starts; the next attempt works. This is the `GenerationType.AUTO` lock problem described under Assignment grading in `AGENTS.md`, here on `submitter_seq`. Not checked on MySQL.
Expand Down
51 changes: 40 additions & 11 deletions src/main/java/com/open/spring/mvc/chat/ChatApiController.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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<Object> 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
Expand All @@ -46,27 +65,32 @@ public static class ChatMessageRequest {

@GetMapping("/{groupId}")
@Transactional(readOnly = true)
public ResponseEntity<List<ChatMessage>> getChat(@PathVariable Long groupId) {
public ResponseEntity<?> getChat(@PathVariable Long groupId) {
Optional<Groups> groupOpt = groupsRepository.findById(groupId);
if (groupOpt.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
ResponseEntity<Object> refusal = mentorRefusal(groupOpt.get());
if (refusal != null) {
return refusal;
}

// String currentUsername = getCurrentUsername();
// if (currentUsername == null) {
// return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
// }

// if (!isMember(groupOpt.get(), currentUsername)) {
// return new ResponseEntity<>(HttpStatus.FORBIDDEN);
// }
// Only the group's members, teachers and admins read its chat.
String currentUsername = getCurrentUsername();
if (currentUsername == null) {
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
}
if (!isMember(groupOpt.get(), currentUsername)
&& !MentorRules.isStaff(personRepository.findByUid(currentUsername))) {
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}

return new ResponseEntity<>(chatService.getChatHistory(groupId), HttpStatus.OK);
}

@PostMapping("/{groupId}")
@Transactional
public ResponseEntity<List<ChatMessage>> postChat(
public ResponseEntity<?> postChat(
@PathVariable Long groupId,
@RequestBody ChatMessageRequest request) {
Optional<Groups> groupOpt = groupsRepository.findById(groupId);
Expand All @@ -79,6 +103,11 @@ public ResponseEntity<List<ChatMessage>> postChat(
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
}

// A mentor hears why (MentorRules) before anyone outside the group gets a plain 403.
ResponseEntity<Object> refusal = mentorRefusal(groupOpt.get());
if (refusal != null) {
return refusal;
}
if (!isMember(groupOpt.get(), currentUsername)) {
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;

Expand Down Expand Up @@ -149,6 +151,12 @@ public ResponseEntity<Object> startConversation(
return new ResponseEntity<>(Map.of("error", "No valid recipients found"), HttpStatus.BAD_REQUEST);
}

Optional<MentorRules.Refusal> 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).
Expand Down Expand Up @@ -205,6 +213,11 @@ public ResponseEntity<Object> postMessage(
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}

Optional<MentorRules.Refusal> 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);
}
Expand Down Expand Up @@ -247,6 +260,11 @@ public ResponseEntity<Object> editMessage(
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}

Optional<MentorRules.Refusal> 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);
}
Expand Down
Loading