From 96a4cd90ce21999ac26276607480376bc285c4b0 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Sat, 21 Nov 2026 23:28:11 -0800 Subject: [PATCH 01/46] Reactions: keys, table and repository --- .../open/spring/mvc/reactions/ChatType.java | 7 +++ .../spring/mvc/reactions/MessageReaction.java | 57 +++++++++++++++++++ .../MessageReactionJpaRepository.java | 18 ++++++ .../MessageReactionTableInitializer.java | 45 +++++++++++++++ .../open/spring/mvc/reactions/Reaction.java | 34 +++++++++++ .../MessageReactionTableInitializerTest.java | 53 +++++++++++++++++ .../spring/mvc/reactions/ReactionTest.java | 34 +++++++++++ 7 files changed, 248 insertions(+) create mode 100644 src/main/java/com/open/spring/mvc/reactions/ChatType.java create mode 100644 src/main/java/com/open/spring/mvc/reactions/MessageReaction.java create mode 100644 src/main/java/com/open/spring/mvc/reactions/MessageReactionJpaRepository.java create mode 100644 src/main/java/com/open/spring/mvc/reactions/MessageReactionTableInitializer.java create mode 100644 src/main/java/com/open/spring/mvc/reactions/Reaction.java create mode 100644 src/test/java/com/open/spring/mvc/reactions/MessageReactionTableInitializerTest.java create mode 100644 src/test/java/com/open/spring/mvc/reactions/ReactionTest.java diff --git a/src/main/java/com/open/spring/mvc/reactions/ChatType.java b/src/main/java/com/open/spring/mvc/reactions/ChatType.java new file mode 100644 index 00000000..9e8583ed --- /dev/null +++ b/src/main/java/com/open/spring/mvc/reactions/ChatType.java @@ -0,0 +1,7 @@ +package com.open.spring.mvc.reactions; + +/** The kind of chat a reacted-to message is in: a DM conversation or a group chat. */ +public enum ChatType { + DM, + GROUP +} diff --git a/src/main/java/com/open/spring/mvc/reactions/MessageReaction.java b/src/main/java/com/open/spring/mvc/reactions/MessageReaction.java new file mode 100644 index 00000000..13cdfc27 --- /dev/null +++ b/src/main/java/com/open/spring/mvc/reactions/MessageReaction.java @@ -0,0 +1,57 @@ +package com.open.spring.mvc.reactions; + +import java.io.Serializable; + +import jakarta.persistence.Column; +import jakarta.persistence.Embeddable; +import jakarta.persistence.EmbeddedId; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.Table; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * One person's reaction to one message. The whole row is its key, so a person leaves each + * reaction at most once on a message. DM messages are rows and group messages live in S3, + * so a message is named by its chat and its id as text. + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@Entity +@Table(name = "message_reaction") +public class MessageReaction { + + @EmbeddedId + private Key key; + + /** Which chat, which message, who, and which emoji. */ + @Data + @NoArgsConstructor + @AllArgsConstructor + @Embeddable + public static class Key implements Serializable { + + @Enumerated(EnumType.STRING) + @Column(name = "chat_type", length = 8) + private ChatType chatType; + + /** The DM conversation's id or the group's id. */ + @Column(name = "chat_id") + private Long chatId; + + /** A DM message's numeric id as text, or a group message's UUID. */ + @Column(name = "message_id", length = 64) + private String messageId; + + @Column(name = "person_id") + private Long personId; + + @Enumerated(EnumType.STRING) + @Column(name = "reaction", length = 16) + private Reaction reaction; + } +} diff --git a/src/main/java/com/open/spring/mvc/reactions/MessageReactionJpaRepository.java b/src/main/java/com/open/spring/mvc/reactions/MessageReactionJpaRepository.java new file mode 100644 index 00000000..0a8fb8c7 --- /dev/null +++ b/src/main/java/com/open/spring/mvc/reactions/MessageReactionJpaRepository.java @@ -0,0 +1,18 @@ +package com.open.spring.mvc.reactions; + +import java.util.List; + +import org.springframework.data.jpa.repository.JpaRepository; + +/** Reactions, read by chat or by message. */ +public interface MessageReactionJpaRepository extends JpaRepository { + + /** Every reaction in one chat. */ + List findByKeyChatTypeAndKeyChatId(ChatType chatType, Long chatId); + + /** Every reaction on one message. */ + List findByKeyChatTypeAndKeyChatIdAndKeyMessageId(ChatType chatType, Long chatId, String messageId); + + /** Removes every reaction on one message, as when the message is deleted. */ + void deleteByKeyChatTypeAndKeyChatIdAndKeyMessageId(ChatType chatType, Long chatId, String messageId); +} diff --git a/src/main/java/com/open/spring/mvc/reactions/MessageReactionTableInitializer.java b/src/main/java/com/open/spring/mvc/reactions/MessageReactionTableInitializer.java new file mode 100644 index 00000000..ba70d3e5 --- /dev/null +++ b/src/main/java/com/open/spring/mvc/reactions/MessageReactionTableInitializer.java @@ -0,0 +1,45 @@ +package com.open.spring.mvc.reactions; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.ApplicationRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.dao.DataAccessException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Component; + +import lombok.RequiredArgsConstructor; + +/** + * Creates message_reaction for databases run with ddl-auto=none, and leaves an existing one + * as it is. The primary key is all five columns: that keeps a person to one of each reaction + * on a message, and it needs no auto-increment, so one statement in unquoted lowercase with + * plain types runs on both SQLite and MySQL. + */ +@Component +@RequiredArgsConstructor +public class MessageReactionTableInitializer { + + static final String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS message_reaction (" + + "chat_type varchar(8) NOT NULL, " + + "chat_id bigint NOT NULL, " + + "message_id varchar(64) NOT NULL, " + + "person_id bigint NOT NULL, " + + "reaction varchar(16) NOT NULL, " + + "PRIMARY KEY (chat_type, chat_id, message_id, person_id, reaction))"; + + private static final Logger logger = LoggerFactory.getLogger(MessageReactionTableInitializer.class); + + private final JdbcTemplate jdbcTemplate; + + @Bean + public ApplicationRunner migrateMessageReaction() { + return args -> { + try { + jdbcTemplate.execute(CREATE_TABLE); + } catch (DataAccessException e) { + logger.warn("Could not create the message_reaction table: {}", e.getMessage()); + } + }; + } +} diff --git a/src/main/java/com/open/spring/mvc/reactions/Reaction.java b/src/main/java/com/open/spring/mvc/reactions/Reaction.java new file mode 100644 index 00000000..bb778d61 --- /dev/null +++ b/src/main/java/com/open/spring/mvc/reactions/Reaction.java @@ -0,0 +1,34 @@ +package com.open.spring.mvc.reactions; + +import java.util.Arrays; +import java.util.Optional; + +/** + * The emoji a message can get. A row stores the enum name; routes and JSON use the lowercase + * key. Pages' Messages reactions.js lists the same keys in the same order, so change both + * together. + */ +public enum Reaction { + LIKE("like"), + LOVE("love"), + HAHA("haha"), + WOW("wow"), + SAD("sad"), + CELEBRATE("celebrate"); + + private final String key; + + Reaction(String key) { + this.key = key; + } + + /** The lowercase name a route and the page use, such as "like". */ + public String key() { + return key; + } + + /** The reaction with exactly this key, or empty for anything else, "LIKE" included. */ + public static Optional fromKey(String key) { + return Arrays.stream(values()).filter(reaction -> reaction.key.equals(key)).findFirst(); + } +} diff --git a/src/test/java/com/open/spring/mvc/reactions/MessageReactionTableInitializerTest.java b/src/test/java/com/open/spring/mvc/reactions/MessageReactionTableInitializerTest.java new file mode 100644 index 00000000..c34acaef --- /dev/null +++ b/src/test/java/com/open/spring/mvc/reactions/MessageReactionTableInitializerTest.java @@ -0,0 +1,53 @@ +package com.open.spring.mvc.reactions; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.dao.DataAccessException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.SingleConnectionDataSource; + +/** The statement that creates message_reaction at startup, run on SQLite as a local server does. */ +class MessageReactionTableInitializerTest { + + private static final String INSERT = "INSERT INTO message_reaction " + + "(chat_type, chat_id, message_id, person_id, reaction) VALUES (?, ?, ?, ?, ?)"; + + private SingleConnectionDataSource dataSource; + private JdbcTemplate jdbc; + + @BeforeEach + void setUp() { + dataSource = new SingleConnectionDataSource("jdbc:sqlite::memory:", true); + jdbc = new JdbcTemplate(dataSource); + } + + @AfterEach + void tearDown() { + dataSource.destroy(); + } + + @Test + void createsTheTableAndCanRunTwice() { + jdbc.execute(MessageReactionTableInitializer.CREATE_TABLE); + jdbc.execute(MessageReactionTableInitializer.CREATE_TABLE); + + jdbc.update(INSERT, "DM", 7L, "42", 1L, "LIKE"); + + assertEquals(1, jdbc.queryForObject("SELECT COUNT(*) FROM message_reaction", Integer.class)); + } + + @Test + void rejectsTheSameReactionTwice() { + jdbc.execute(MessageReactionTableInitializer.CREATE_TABLE); + jdbc.update(INSERT, "DM", 7L, "42", 1L, "LIKE"); + + assertThrows(DataAccessException.class, () -> jdbc.update(INSERT, "DM", 7L, "42", 1L, "LIKE")); + jdbc.update(INSERT, "DM", 7L, "42", 1L, "LOVE"); + + assertEquals(2, jdbc.queryForObject("SELECT COUNT(*) FROM message_reaction", Integer.class)); + } +} diff --git a/src/test/java/com/open/spring/mvc/reactions/ReactionTest.java b/src/test/java/com/open/spring/mvc/reactions/ReactionTest.java new file mode 100644 index 00000000..26f259e9 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/reactions/ReactionTest.java @@ -0,0 +1,34 @@ +package com.open.spring.mvc.reactions; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +import org.junit.jupiter.api.Test; + +/** + * The reaction keys are a contract with the Pages client: Messages' reactions.js lists the + * same keys in the same order, and a route's {reaction} is read with fromKey. + */ +class ReactionTest { + + @Test + void everyKeyRoundTrips() { + for (Reaction reaction : Reaction.values()) { + assertEquals(Optional.of(reaction), Reaction.fromKey(reaction.key())); + } + List keys = Arrays.stream(Reaction.values()).map(Reaction::key).toList(); + assertEquals(List.of("like", "love", "haha", "wow", "sad", "celebrate"), keys); + } + + @Test + void unknownKeysAreRefused() { + assertTrue(Reaction.fromKey(null).isEmpty()); + assertTrue(Reaction.fromKey("").isEmpty()); + assertTrue(Reaction.fromKey("LIKE").isEmpty()); + assertTrue(Reaction.fromKey("thumbsup").isEmpty()); + } +} From 8f749e9cb28e20b1202e528a154e677bc56f2ccf Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Sat, 21 Nov 2026 23:31:18 -0800 Subject: [PATCH 02/46] Reactions: a service that saves and summarizes them --- .../mvc/reactions/MessageReactionService.java | 123 ++++++++++++++++ .../reactions/MessageReactionServiceTest.java | 133 ++++++++++++++++++ 2 files changed, 256 insertions(+) create mode 100644 src/main/java/com/open/spring/mvc/reactions/MessageReactionService.java create mode 100644 src/test/java/com/open/spring/mvc/reactions/MessageReactionServiceTest.java diff --git a/src/main/java/com/open/spring/mvc/reactions/MessageReactionService.java b/src/main/java/com/open/spring/mvc/reactions/MessageReactionService.java new file mode 100644 index 00000000..806229c9 --- /dev/null +++ b/src/main/java/com/open/spring/mvc/reactions/MessageReactionService.java @@ -0,0 +1,123 @@ +package com.open.spring.mvc.reactions; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.stream.Collectors; + +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import com.open.spring.mvc.person.Person; +import com.open.spring.mvc.person.PersonJpaRepository; + +import lombok.RequiredArgsConstructor; + +/** + * Saves and summarizes the reactions on DM and group messages. It doesn't decide who may react + * or whether a message exists: each chat's own service checks that before calling here. + */ +@Service +@RequiredArgsConstructor +public class MessageReactionService { + + private static final Comparator BY_NAME = Comparator + .comparing((Reactor reactor) -> reactor.name() == null ? "" : reactor.name(), String.CASE_INSENSITIVE_ORDER) + .thenComparing(reactor -> reactor.uid() == null ? "" : reactor.uid()); + + private final MessageReactionJpaRepository repository; + private final PersonJpaRepository personRepository; + + /** Someone who reacted, as the page shows them. */ + public record Reactor(String uid, String name) { + } + + /** One emoji on a message, by its lowercase key, and everyone who left it. */ + public record ReactionSummary(String reaction, List people) { + } + + /** A message's reactions after a change: the body PUT and DELETE answer with. */ + public record MessageReactions(String messageId, List reactions) { + } + + /** Adds this person's reaction. Adding one that is already there changes nothing. */ + @Transactional + public void add(ChatType type, Long chatId, String messageId, Person person, Reaction reaction) { + MessageReaction.Key key = new MessageReaction.Key(type, chatId, messageId, person.getId(), reaction); + if (!repository.existsById(key)) { + repository.save(new MessageReaction(key)); + } + } + + /** Removes this person's reaction. Removing one that isn't there changes nothing. */ + @Transactional + public void remove(ChatType type, Long chatId, String messageId, Person person, Reaction reaction) { + MessageReaction.Key key = new MessageReaction.Key(type, chatId, messageId, person.getId(), reaction); + if (repository.existsById(key)) { + repository.deleteById(key); + } + } + + /** One message's reactions, in the enum's order. */ + @Transactional(readOnly = true) + public List forMessage(ChatType type, Long chatId, String messageId) { + List rows = repository.findByKeyChatTypeAndKeyChatIdAndKeyMessageId(type, chatId, messageId); + return summarize(rows, reactorsFor(rows)); + } + + /** Every reacted-to message in a chat, by message id. A message left with no reactions isn't listed. */ + @Transactional(readOnly = true) + public Map> forChat(ChatType type, Long chatId) { + List rows = repository.findByKeyChatTypeAndKeyChatId(type, chatId); + Map reactors = reactorsFor(rows); + Map> byMessage = rows.stream().collect( + Collectors.groupingBy(row -> row.getKey().getMessageId(), LinkedHashMap::new, Collectors.toList())); + Map> result = new LinkedHashMap<>(); + byMessage.forEach((messageId, messageRows) -> { + List summaries = summarize(messageRows, reactors); + if (!summaries.isEmpty()) { + result.put(messageId, summaries); + } + }); + return result; + } + + /** Removes every reaction on a message, as when the message is deleted. */ + @Transactional + public void removeAllFor(ChatType type, Long chatId, String messageId) { + repository.deleteByKeyChatTypeAndKeyChatIdAndKeyMessageId(type, chatId, messageId); + } + + // Everyone in one query. Someone whose account is gone isn't in the result, so they drop out. + private Map reactorsFor(List rows) { + List ids = rows.stream().map(row -> row.getKey().getPersonId()).distinct().toList(); + if (ids.isEmpty()) { + return Map.of(); + } + Map reactors = new HashMap<>(); + for (Person person : personRepository.findAllById(ids)) { + reactors.put(person.getId(), new Reactor(person.getUid(), person.getName())); + } + return reactors; + } + + private List summarize(List rows, Map reactors) { + List summaries = new ArrayList<>(); + for (Reaction reaction : Reaction.values()) { + List people = rows.stream() + .filter(row -> row.getKey().getReaction() == reaction) + .map(row -> reactors.get(row.getKey().getPersonId())) + .filter(Objects::nonNull) + .sorted(BY_NAME) + .toList(); + if (!people.isEmpty()) { + summaries.add(new ReactionSummary(reaction.key(), people)); + } + } + return summaries; + } +} diff --git a/src/test/java/com/open/spring/mvc/reactions/MessageReactionServiceTest.java b/src/test/java/com/open/spring/mvc/reactions/MessageReactionServiceTest.java new file mode 100644 index 00000000..ad00a6c1 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/reactions/MessageReactionServiceTest.java @@ -0,0 +1,133 @@ +package com.open.spring.mvc.reactions; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.test.util.ReflectionTestUtils; + +import com.open.spring.mvc.person.Person; +import com.open.spring.mvc.person.PersonJpaRepository; +import com.open.spring.mvc.reactions.MessageReactionService.ReactionSummary; +import com.open.spring.mvc.reactions.MessageReactionService.Reactor; + +/** + * Saving a reaction once, removing it safely, and the summaries both chats send: reactions in + * the enum's order, people by name, and nobody listed who no longer has an account. + */ +class MessageReactionServiceTest { + + private MessageReactionJpaRepository repository; + private PersonJpaRepository people; + private MessageReactionService service; + // "ada" is lowercase on purpose: it sorts before "Ana" only when case is ignored. + private Person ada; + private Person ana; + private Person ben; + + @BeforeEach + void setUp() { + repository = mock(MessageReactionJpaRepository.class); + people = mock(PersonJpaRepository.class); + service = new MessageReactionService(repository, people); + ada = person(1L, "ada", "ada"); + ana = person(2L, "ana", "Ana"); + ben = person(3L, "ben", "Ben"); + } + + @Test + void addSavesANewReactionOnce() { + MessageReaction.Key key = new MessageReaction.Key(ChatType.DM, 7L, "42", 1L, Reaction.LIKE); + when(repository.existsById(key)).thenReturn(true); + service.add(ChatType.DM, 7L, "42", ada, Reaction.LIKE); + verify(repository, never()).save(any()); + + when(repository.existsById(key)).thenReturn(false); + service.add(ChatType.DM, 7L, "42", ada, Reaction.LIKE); + verify(repository).save(new MessageReaction(key)); + } + + @Test + void removeIsFineWhenNothingIsThere() { + MessageReaction.Key key = new MessageReaction.Key(ChatType.DM, 7L, "42", 1L, Reaction.LIKE); + when(repository.existsById(key)).thenReturn(false); + service.remove(ChatType.DM, 7L, "42", ada, Reaction.LIKE); + verify(repository, never()).deleteById(any()); + + when(repository.existsById(key)).thenReturn(true); + service.remove(ChatType.DM, 7L, "42", ada, Reaction.LIKE); + verify(repository).deleteById(key); + } + + @Test + void summariesFollowTheTableOrderAndSortPeople() { + when(repository.findByKeyChatTypeAndKeyChatIdAndKeyMessageId(ChatType.DM, 7L, "42")).thenReturn(List.of( + row(ChatType.DM, 7L, "42", 3L, Reaction.WOW), + row(ChatType.DM, 7L, "42", 2L, Reaction.LIKE), + row(ChatType.DM, 7L, "42", 1L, Reaction.LIKE))); + when(people.findAllById(any())).thenReturn(List.of(ben, ana, ada)); + + List summaries = service.forMessage(ChatType.DM, 7L, "42"); + + assertEquals(List.of( + new ReactionSummary("like", List.of(new Reactor("ada", "ada"), new Reactor("ana", "Ana"))), + new ReactionSummary("wow", List.of(new Reactor("ben", "Ben")))), summaries); + } + + @Test + void aPersonWhoIsGoneIsLeftOut() { + when(repository.findByKeyChatTypeAndKeyChatIdAndKeyMessageId(ChatType.DM, 7L, "42")).thenReturn(List.of( + row(ChatType.DM, 7L, "42", 1L, Reaction.LIKE), + row(ChatType.DM, 7L, "42", 2L, Reaction.LIKE), + row(ChatType.DM, 7L, "42", 2L, Reaction.SAD))); + // Person 2's account is gone, so their Like goes and their Sad, now nobody's, goes too. + when(people.findAllById(any())).thenReturn(List.of(ada)); + + assertEquals(List.of(new ReactionSummary("like", List.of(new Reactor("ada", "ada")))), + service.forMessage(ChatType.DM, 7L, "42")); + } + + @Test + void forChatKeysByMessageId() { + when(repository.findByKeyChatTypeAndKeyChatId(ChatType.GROUP, 3L)).thenReturn(List.of( + row(ChatType.GROUP, 3L, "42", 1L, Reaction.LIKE), + row(ChatType.GROUP, 3L, "57", 3L, Reaction.HAHA), + row(ChatType.GROUP, 3L, "60", 9L, Reaction.LIKE))); + when(people.findAllById(any())).thenReturn(List.of(ada, ben)); + + Map> byMessage = service.forChat(ChatType.GROUP, 3L); + + // "60" is left out: its only reaction is from someone whose account is gone. + assertEquals(Map.of( + "42", List.of(new ReactionSummary("like", List.of(new Reactor("ada", "ada")))), + "57", List.of(new ReactionSummary("haha", List.of(new Reactor("ben", "Ben"))))), byMessage); + } + + @Test + void removeAllForDeletesThatMessagesReactions() { + service.removeAllFor(ChatType.GROUP, 3L, "abc"); + + verify(repository).deleteByKeyChatTypeAndKeyChatIdAndKeyMessageId(ChatType.GROUP, 3L, "abc"); + } + + private static MessageReaction row(ChatType type, long chatId, String messageId, long personId, Reaction reaction) { + return new MessageReaction(new MessageReaction.Key(type, chatId, messageId, personId, reaction)); + } + + private static Person person(long id, String uid, String name) { + Person person = new Person(); + // Submitter has no id setter; the DM tests set it the same way. + ReflectionTestUtils.setField(person, "id", id); + person.setUid(uid); + person.setName(name); + return person; + } +} From 363242fc12ee6b2da20623fda6978e00644d6321 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Sat, 21 Nov 2026 23:34:23 -0800 Subject: [PATCH 03/46] Reactions: react to a direct message --- .../DirectMessageApiController.java | 81 +++++++ .../directmessages/DirectMessageEvent.java | 13 +- .../directmessages/DirectMessageService.java | 41 ++++ .../DirectMessageReactionTest.java | 206 ++++++++++++++++++ .../DirectMessageServiceTest.java | 4 +- 5 files changed, 343 insertions(+), 2 deletions(-) create mode 100644 src/test/java/com/open/spring/mvc/directmessages/DirectMessageReactionTest.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..889c9ed5 100644 --- a/src/main/java/com/open/spring/mvc/directmessages/DirectMessageApiController.java +++ b/src/main/java/com/open/spring/mvc/directmessages/DirectMessageApiController.java @@ -17,6 +17,7 @@ import org.springframework.web.bind.annotation.PatchMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; @@ -24,6 +25,10 @@ import com.open.spring.mvc.person.Person; import com.open.spring.mvc.person.PersonJpaRepository; +import com.open.spring.mvc.reactions.ChatType; +import com.open.spring.mvc.reactions.MessageReactionService; +import com.open.spring.mvc.reactions.MessageReactionService.MessageReactions; +import com.open.spring.mvc.reactions.Reaction; import lombok.AllArgsConstructor; import lombok.Data; @@ -46,6 +51,7 @@ public class DirectMessageApiController { private final DirectMessageConversationJpaRepository conversationRepository; private final DirectMessageJpaRepository messageRepository; private final PersonJpaRepository personRepository; + private final MessageReactionService reactionService; @Data @NoArgsConstructor @@ -295,6 +301,81 @@ public ResponseEntity deleteMessage( } } + /** Every reaction in the conversation, by message id: what the page draws when it opens it. */ + @GetMapping("/conversations/{id}/reactions") + @Transactional(readOnly = true) + public ResponseEntity getReactions( + @AuthenticationPrincipal UserDetails userDetails, + @PathVariable("id") Long id) { + Person person = currentPerson(userDetails); + if (person == null) { + return new ResponseEntity<>(Map.of("error", "User not authenticated"), HttpStatus.UNAUTHORIZED); + } + + Optional conversationOpt = conversationRepository.findById(id); + if (conversationOpt.isEmpty()) { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + if (!directMessageService.isParticipant(conversationOpt.get(), person)) { + return new ResponseEntity<>(HttpStatus.FORBIDDEN); + } + + return new ResponseEntity<>(reactionService.forChat(ChatType.DM, id), HttpStatus.OK); + } + + /** Adds the caller's reaction, by its lowercase key such as "like", and answers with the message's reactions. */ + @PutMapping("/conversations/{id}/messages/{messageId}/reactions/{reaction}") + @Transactional + public ResponseEntity addReaction( + @AuthenticationPrincipal UserDetails userDetails, + @PathVariable("id") Long id, + @PathVariable("messageId") Long messageId, + @PathVariable("reaction") String reaction) { + return setReaction(userDetails, id, messageId, reaction, true); + } + + /** Removes the caller's reaction; removing one that isn't there still answers 200. */ + @DeleteMapping("/conversations/{id}/messages/{messageId}/reactions/{reaction}") + @Transactional + public ResponseEntity removeReaction( + @AuthenticationPrincipal UserDetails userDetails, + @PathVariable("id") Long id, + @PathVariable("messageId") Long messageId, + @PathVariable("reaction") String reaction) { + return setReaction(userDetails, id, messageId, reaction, false); + } + + private ResponseEntity setReaction(UserDetails userDetails, Long id, Long messageId, String key, boolean on) { + Person person = currentPerson(userDetails); + if (person == null) { + return new ResponseEntity<>(Map.of("error", "User not authenticated"), HttpStatus.UNAUTHORIZED); + } + + Optional conversationOpt = conversationRepository.findById(id); + if (conversationOpt.isEmpty()) { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + + DirectMessageConversation conversation = conversationOpt.get(); + if (!directMessageService.isParticipant(conversation, person)) { + return new ResponseEntity<>(HttpStatus.FORBIDDEN); + } + + Optional reaction = Reaction.fromKey(key); + if (reaction.isEmpty()) { + return new ResponseEntity<>(Map.of("error", "unknown reaction"), HttpStatus.BAD_REQUEST); + } + + try { + return new ResponseEntity<>(new MessageReactions(String.valueOf(messageId), + directMessageService.setReaction(conversation, person, messageId, reaction.get(), on)), HttpStatus.OK); + } catch (NoSuchElementException ex) { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } catch (IllegalStateException ex) { + return new ResponseEntity<>(Map.of("error", ex.getMessage()), HttpStatus.CONFLICT); + } + } + @PostMapping("/conversations/{id}/read") @Transactional public ResponseEntity markRead( diff --git a/src/main/java/com/open/spring/mvc/directmessages/DirectMessageEvent.java b/src/main/java/com/open/spring/mvc/directmessages/DirectMessageEvent.java index b68c9c46..09b7b42f 100644 --- a/src/main/java/com/open/spring/mvc/directmessages/DirectMessageEvent.java +++ b/src/main/java/com/open/spring/mvc/directmessages/DirectMessageEvent.java @@ -1,5 +1,10 @@ package com.open.spring.mvc.directmessages; +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.open.spring.mvc.reactions.MessageReactionService; + import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -16,7 +21,7 @@ public class DirectMessageEvent { private Long id; private Long conversationId; - private String type; // "message" for new posts, "edited" for edits + private String type; // "message", "edited", "deleted", or "reactions" private String senderUid; private String senderName; private String senderPfp; @@ -26,4 +31,10 @@ public class DirectMessageEvent { private String sentAt; private boolean deleted; private boolean edited; + /** + * On a "reactions" frame, the message's reactions after the change. Left out of every + * other frame, so those stay exactly as they were. + */ + @JsonInclude(JsonInclude.Include.NON_NULL) + private List reactions; } diff --git a/src/main/java/com/open/spring/mvc/directmessages/DirectMessageService.java b/src/main/java/com/open/spring/mvc/directmessages/DirectMessageService.java index 5c910139..5abc745e 100644 --- a/src/main/java/com/open/spring/mvc/directmessages/DirectMessageService.java +++ b/src/main/java/com/open/spring/mvc/directmessages/DirectMessageService.java @@ -15,6 +15,9 @@ import com.open.spring.mvc.person.Person; import com.open.spring.mvc.push.PushNotificationService; +import com.open.spring.mvc.reactions.ChatType; +import com.open.spring.mvc.reactions.MessageReactionService; +import com.open.spring.mvc.reactions.Reaction; import lombok.RequiredArgsConstructor; @@ -41,6 +44,7 @@ public class DirectMessageService { private final DirectMessageReadStateJpaRepository readStateRepository; private final SimpMessagingTemplate messagingTemplate; private final PushNotificationService pushNotificationService; + private final MessageReactionService reactionService; public record UnreadSender(String uid, String name) { } @@ -222,6 +226,8 @@ public void deleteMessage(DirectMessageConversation conversation, Person request message.setDeleted(true); message.setBody(""); messageRepository.save(message); + // A tombstone shows no reactions, so none are kept for it. + reactionService.removeAllFor(ChatType.DM, conversation.getId(), String.valueOf(messageId)); DirectMessageEvent event = DirectMessageEvent.builder() .id(message.getId()) @@ -235,6 +241,41 @@ public void deleteMessage(DirectMessageConversation conversation, Person request messagingTemplate.convertAndSend(DM_TOPIC_PREFIX + conversation.getId(), event); } + /** + * Adds ({@code on}) or removes {@code person}'s reaction to a message, then tells the + * conversation's topic with a "reactions" frame. A reaction isn't a message: nobody gets a + * phone notification and nothing becomes unread. Throws {@link NoSuchElementException} if + * the message isn't in this conversation and {@link IllegalStateException} if it was + * deleted; {@code noRollbackFor} for the reason given on {@link #editMessage}. + */ + @Transactional(noRollbackFor = {NoSuchElementException.class, IllegalStateException.class}) + public List setReaction(DirectMessageConversation conversation, + Person person, Long messageId, Reaction reaction, boolean on) { + DirectMessage message = messageRepository.findByIdAndConversation(messageId, conversation) + .orElseThrow(() -> new NoSuchElementException("Message not found")); + if (message.isDeleted()) { + throw new IllegalStateException("Message was deleted"); + } + + String key = String.valueOf(messageId); + if (on) { + reactionService.add(ChatType.DM, conversation.getId(), key, person, reaction); + } else { + reactionService.remove(ChatType.DM, conversation.getId(), key, person, reaction); + } + List reactions = + reactionService.forMessage(ChatType.DM, conversation.getId(), key); + + DirectMessageEvent event = DirectMessageEvent.builder() + .id(messageId) + .conversationId(conversation.getId()) + .type("reactions") + .reactions(reactions) + .build(); + messagingTemplate.convertAndSend(DM_TOPIC_PREFIX + conversation.getId(), event); + return reactions; + } + @Transactional(readOnly = true) public UnreadSummary getUnreadSummary(Person person) { Map people = new LinkedHashMap<>(); diff --git a/src/test/java/com/open/spring/mvc/directmessages/DirectMessageReactionTest.java b/src/test/java/com/open/spring/mvc/directmessages/DirectMessageReactionTest.java new file mode 100644 index 00000000..a3a81b48 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/directmessages/DirectMessageReactionTest.java @@ -0,0 +1,206 @@ +package com.open.spring.mvc.directmessages; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Optional; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.messaging.simp.SimpMessagingTemplate; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.test.util.ReflectionTestUtils; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.open.spring.mvc.person.Person; +import com.open.spring.mvc.person.PersonJpaRepository; +import com.open.spring.mvc.push.PushNotificationService; +import com.open.spring.mvc.reactions.ChatType; +import com.open.spring.mvc.reactions.MessageReactionService; +import com.open.spring.mvc.reactions.MessageReactionService.MessageReactions; +import com.open.spring.mvc.reactions.MessageReactionService.ReactionSummary; +import com.open.spring.mvc.reactions.MessageReactionService.Reactor; +import com.open.spring.mvc.reactions.Reaction; + +/** + * Reacting to a direct message: only participants, never on a deleted message, broadcast as a + * "reactions" frame, and never a phone notification or a change to what is unread. + */ +class DirectMessageReactionTest { + + private DirectMessageConversationJpaRepository conversationRepository; + private DirectMessageJpaRepository messageRepository; + private DirectMessageReadStateJpaRepository readStateRepository; + private SimpMessagingTemplate messagingTemplate; + private PushNotificationService pushNotificationService; + private MessageReactionService reactionService; + private PersonJpaRepository personRepository; + private DirectMessageService service; + private DirectMessageApiController controller; + private Person alice; + private Person bob; + private DirectMessageConversation conversation; + private DirectMessage message; + private List summaries; + + @BeforeEach + void setUp() { + conversationRepository = mock(DirectMessageConversationJpaRepository.class); + messageRepository = mock(DirectMessageJpaRepository.class); + readStateRepository = mock(DirectMessageReadStateJpaRepository.class); + messagingTemplate = mock(SimpMessagingTemplate.class); + pushNotificationService = mock(PushNotificationService.class); + reactionService = mock(MessageReactionService.class); + personRepository = mock(PersonJpaRepository.class); + service = new DirectMessageService(conversationRepository, messageRepository, readStateRepository, + messagingTemplate, pushNotificationService, reactionService); + controller = new DirectMessageApiController(service, conversationRepository, messageRepository, + personRepository, reactionService); + + alice = person(1L, "alice"); + bob = person(2L, "bob"); + Person carol = person(3L, "carol"); + when(personRepository.findByUid("alice")).thenReturn(alice); + when(personRepository.findByUid("carol")).thenReturn(carol); + + conversation = new DirectMessageConversation(List.of(alice, bob)); + ReflectionTestUtils.setField(conversation, "id", 7L); + when(conversationRepository.findById(7L)).thenReturn(Optional.of(conversation)); + + message = new DirectMessage(conversation, bob, "did anyone finish the FRQ?"); + ReflectionTestUtils.setField(message, "id", 42L); + when(messageRepository.findByIdAndConversation(42L, conversation)).thenReturn(Optional.of(message)); + + summaries = List.of(new ReactionSummary("like", List.of(new Reactor("alice", "alice")))); + when(reactionService.forMessage(ChatType.DM, 7L, "42")).thenReturn(summaries); + } + + @Test + void aReactionGoesOutAsAReactionsFrame() { + List result = service.setReaction(conversation, alice, 42L, Reaction.LIKE, true); + + verify(reactionService).add(ChatType.DM, 7L, "42", alice, Reaction.LIKE); + ArgumentCaptor frame = ArgumentCaptor.forClass(DirectMessageEvent.class); + verify(messagingTemplate).convertAndSend(eq("/topic/dm/7"), frame.capture()); + assertEquals("reactions", frame.getValue().getType()); + assertEquals(42L, frame.getValue().getId()); + assertEquals(7L, frame.getValue().getConversationId()); + assertEquals(summaries, frame.getValue().getReactions()); + assertEquals(summaries, result); + } + + @Test + void takingAReactionBackRemovesIt() { + service.setReaction(conversation, alice, 42L, Reaction.LIKE, false); + + verify(reactionService).remove(ChatType.DM, 7L, "42", alice, Reaction.LIKE); + verify(reactionService, never()).add(any(), any(), any(), any(), any()); + } + + @Test + void aReactionSendsNoPushAndLeavesReadStateAlone() { + service.setReaction(conversation, alice, 42L, Reaction.LIKE, true); + + verifyNoInteractions(pushNotificationService, readStateRepository); + } + + @Test + void aDeletedMessageCannotBeReactedTo() { + message.setDeleted(true); + + assertThrows(IllegalStateException.class, + () -> service.setReaction(conversation, alice, 42L, Reaction.LIKE, true)); + assertEquals(HttpStatus.CONFLICT, controller.addReaction(signedIn("alice"), 7L, 42L, "like").getStatusCode()); + verify(reactionService, never()).add(any(), any(), any(), any(), any()); + } + + @Test + void aMessageFromAnotherConversationIsNotFound() { + when(messageRepository.findByIdAndConversation(99L, conversation)).thenReturn(Optional.empty()); + + assertThrows(NoSuchElementException.class, + () -> service.setReaction(conversation, alice, 99L, Reaction.LIKE, true)); + assertEquals(HttpStatus.NOT_FOUND, controller.addReaction(signedIn("alice"), 7L, 99L, "like").getStatusCode()); + } + + @Test + void anUnknownReactionIs400() { + ResponseEntity response = controller.addReaction(signedIn("alice"), 7L, 42L, "thumbsup"); + + assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); + verify(reactionService, never()).add(any(), any(), any(), any(), any()); + } + + @Test + void onlyASignedInParticipantMayReactOrList() { + assertEquals(HttpStatus.UNAUTHORIZED, controller.addReaction(null, 7L, 42L, "like").getStatusCode()); + assertEquals(HttpStatus.FORBIDDEN, controller.addReaction(signedIn("carol"), 7L, 42L, "like").getStatusCode()); + assertEquals(HttpStatus.FORBIDDEN, controller.removeReaction(signedIn("carol"), 7L, 42L, "like").getStatusCode()); + assertEquals(HttpStatus.FORBIDDEN, controller.getReactions(signedIn("carol"), 7L).getStatusCode()); + verifyNoInteractions(reactionService); + } + + @Test + void theRoutesAnswerWithTheMessagesReactions() { + ResponseEntity added = controller.addReaction(signedIn("alice"), 7L, 42L, "like"); + assertEquals(HttpStatus.OK, added.getStatusCode()); + assertEquals(new MessageReactions("42", summaries), added.getBody()); + + ResponseEntity removed = controller.removeReaction(signedIn("alice"), 7L, 42L, "like"); + assertEquals(HttpStatus.OK, removed.getStatusCode()); + verify(reactionService).remove(ChatType.DM, 7L, "42", alice, Reaction.LIKE); + + Map> byMessage = Map.of("42", summaries); + when(reactionService.forChat(ChatType.DM, 7L)).thenReturn(byMessage); + ResponseEntity listed = controller.getReactions(signedIn("alice"), 7L); + assertEquals(HttpStatus.OK, listed.getStatusCode()); + assertEquals(byMessage, listed.getBody()); + } + + @Test + void deletingAMessageRemovesItsReactions() { + service.deleteMessage(conversation, bob, 42L); + + verify(reactionService).removeAllFor(ChatType.DM, 7L, "42"); + } + + @Test + void onlyAReactionsFrameCarriesReactions() throws Exception { + ObjectMapper json = new ObjectMapper(); + String messageFrame = json.writeValueAsString( + DirectMessageEvent.builder().type("message").id(1L).conversationId(7L).body("hi").build()); + String reactionsFrame = json.writeValueAsString( + DirectMessageEvent.builder().type("reactions").id(1L).conversationId(7L).reactions(summaries).build()); + + assertFalse(messageFrame.contains("\"reactions\"")); + assertTrue(reactionsFrame.contains("\"reactions\"")); + } + + private static UserDetails signedIn(String uid) { + return User.withUsername(uid).password("unused").build(); + } + + private static Person person(Long id, String uid) { + Person person = new Person(); + ReflectionTestUtils.setField(person, "id", id); + person.setUid(uid); + person.setName(uid); + return person; + } +} diff --git a/src/test/java/com/open/spring/mvc/directmessages/DirectMessageServiceTest.java b/src/test/java/com/open/spring/mvc/directmessages/DirectMessageServiceTest.java index dbde1e3e..2845cfed 100644 --- a/src/test/java/com/open/spring/mvc/directmessages/DirectMessageServiceTest.java +++ b/src/test/java/com/open/spring/mvc/directmessages/DirectMessageServiceTest.java @@ -21,6 +21,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.open.spring.mvc.push.PushNotificationService; import com.open.spring.mvc.push.PushSubscriptionJpaRepository; +import com.open.spring.mvc.reactions.MessageReactionService; import org.springframework.test.util.ReflectionTestUtils; import com.open.spring.mvc.person.Person; @@ -144,7 +145,8 @@ void setUp() { }), new ObjectMapper(), "", "", ""); service = new DirectMessageService(conversationRepository, messageRepository, readStateRepository, - new SimpMessagingTemplate((message, timeout) -> true), pushNotificationService); + new SimpMessagingTemplate((message, timeout) -> true), pushNotificationService, + org.mockito.Mockito.mock(MessageReactionService.class)); } @Test From adb17e1864cb326afea1a404b343856f507ee308 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Sat, 21 Nov 2026 23:37:37 -0800 Subject: [PATCH 04/46] Reactions: react to a group chat message --- .../mvc/groups/GroupChatApiController.java | 70 ++++++- .../spring/mvc/groups/GroupChatEvent.java | 9 + .../mvc/groups/GroupChatRealtimeService.java | 35 ++++ .../spring/mvc/groups/GroupChatFilesTest.java | 5 +- .../mvc/groups/GroupChatReactionTest.java | 181 ++++++++++++++++++ .../mvc/groups/GroupChatRegressionTest.java | 5 +- 6 files changed, 300 insertions(+), 5 deletions(-) create mode 100644 src/test/java/com/open/spring/mvc/groups/GroupChatReactionTest.java 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..c99381c1 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java @@ -4,6 +4,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.regex.Pattern; import java.nio.charset.StandardCharsets; @@ -20,6 +21,7 @@ import org.springframework.web.bind.annotation.PatchMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; @@ -28,6 +30,10 @@ import com.open.spring.mvc.groups.GroupChatIdentityService.AuthenticatedIdentity; import com.open.spring.mvc.person.Person; import com.open.spring.mvc.person.PersonJpaRepository; +import com.open.spring.mvc.reactions.ChatType; +import com.open.spring.mvc.reactions.MessageReactionService; +import com.open.spring.mvc.reactions.MessageReactionService.MessageReactions; +import com.open.spring.mvc.reactions.Reaction; import lombok.AllArgsConstructor; import lombok.Data; @@ -42,23 +48,31 @@ public class GroupChatApiController { // short outage clears in seconds. private static final int SHARE_RETRY_AFTER_SECONDS = 5; + // A saved group message's id is a UUID (GroupChatMessage). Reactions don't read the group's + // S3 file to check that the message exists, so the id at least has to look like one. + static final Pattern MESSAGE_ID = + Pattern.compile("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"); + private final GroupChatService groupChatService; private final GroupChatRealtimeService realtimeService; private final GroupChatReadService readService; private final GroupsJpaRepository groupsRepository; private final PersonJpaRepository personRepository; + private final MessageReactionService reactionService; public GroupChatApiController( GroupChatService groupChatService, GroupChatRealtimeService realtimeService, GroupChatReadService readService, GroupsJpaRepository groupsRepository, - PersonJpaRepository personRepository) { + PersonJpaRepository personRepository, + MessageReactionService reactionService) { this.groupChatService = groupChatService; this.realtimeService = realtimeService; this.readService = readService; this.groupsRepository = groupsRepository; this.personRepository = personRepository; + this.reactionService = reactionService; } @Data @@ -262,6 +276,60 @@ public ResponseEntity deleteMessage( return new ResponseEntity<>(HttpStatus.OK); } + /** + * Every reaction in the group's chat, by message id: what the page draws when it opens the + * chat. Like posting, it needs a signed-in person but not membership. + */ + @GetMapping("/{groupId}/reactions") + public ResponseEntity getReactions(@PathVariable Long groupId) { + if (currentPerson() == null) { + return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); + } + if (groupsRepository.findById(groupId).isEmpty()) { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + return new ResponseEntity<>(reactionService.forChat(ChatType.GROUP, groupId), HttpStatus.OK); + } + + /** Adds the caller's reaction, by its lowercase key such as "like", and answers with the message's reactions. */ + @PutMapping("/{groupId}/messages/{messageId}/reactions/{reaction}") + public ResponseEntity addReaction( + @PathVariable Long groupId, + @PathVariable String messageId, + @PathVariable String reaction) { + return setReaction(groupId, messageId, reaction, true); + } + + /** Removes the caller's reaction; removing one that isn't there still answers 200. */ + @DeleteMapping("/{groupId}/messages/{messageId}/reactions/{reaction}") + public ResponseEntity removeReaction( + @PathVariable Long groupId, + @PathVariable String messageId, + @PathVariable String reaction) { + return setReaction(groupId, messageId, reaction, false); + } + + private ResponseEntity setReaction(Long groupId, String messageId, String key, boolean on) { + Person person = currentPerson(); + if (person == null) { + return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); + } + if (groupsRepository.findById(groupId).isEmpty()) { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + Optional reaction = Reaction.fromKey(key); + if (reaction.isEmpty()) { + return new ResponseEntity<>("unknown reaction", HttpStatus.BAD_REQUEST); + } + if (messageId == null || !MESSAGE_ID.matcher(messageId).matches()) { + return new ResponseEntity<>("messageId is not a message id", HttpStatus.BAD_REQUEST); + } + + List reactions = + realtimeService.setReaction(groupId, person, messageId, reaction.get(), on); + return new ResponseEntity<>(new MessageReactions(messageId, reactions), HttpStatus.OK); + } + /** * Unread counts for the signed-in member's own groups, keyed by group id. Groups * with nothing unread are left out, so an empty map means nothing is waiting. diff --git a/src/main/java/com/open/spring/mvc/groups/GroupChatEvent.java b/src/main/java/com/open/spring/mvc/groups/GroupChatEvent.java index acedc9fd..00f671a3 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatEvent.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatEvent.java @@ -2,6 +2,9 @@ import java.util.List; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.open.spring.mvc.reactions.MessageReactionService; + import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -29,4 +32,10 @@ public class GroupChatEvent { private String error; private List participants; private boolean edited; + /** + * On a reactionsServer frame, the message's reactions after the change. Left out of every + * other frame, so those stay exactly as they were. + */ + @JsonInclude(JsonInclude.Include.NON_NULL) + private List reactions; } diff --git a/src/main/java/com/open/spring/mvc/groups/GroupChatRealtimeService.java b/src/main/java/com/open/spring/mvc/groups/GroupChatRealtimeService.java index 532b8d69..e29a1819 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatRealtimeService.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatRealtimeService.java @@ -1,12 +1,17 @@ package com.open.spring.mvc.groups; import java.time.Instant; +import java.util.List; import java.util.Optional; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.stereotype.Service; import com.open.spring.mvc.groups.GroupChatIdentityService.AuthenticatedIdentity; +import com.open.spring.mvc.person.Person; +import com.open.spring.mvc.reactions.ChatType; +import com.open.spring.mvc.reactions.MessageReactionService; +import com.open.spring.mvc.reactions.Reaction; import lombok.RequiredArgsConstructor; @@ -23,6 +28,7 @@ public class GroupChatRealtimeService { private final GroupChatService groupChatService; private final GroupsJpaRepository groupsRepository; private final SimpMessagingTemplate messagingTemplate; + private final MessageReactionService reactionService; public GroupChatEvent publishMessage(Long groupId, String message, String image, AuthenticatedIdentity identity) { Groups group = getGroupOrThrow(groupId); @@ -78,6 +84,7 @@ public boolean editMessage(Long groupId, String messageId, String newMessage, St public void deleteMessage(Long groupId, String messageId, String requesterUid) { Groups group = getGroupOrThrow(groupId); groupChatService.deleteMessage(group.getName(), messageId, requesterUid); + reactionService.removeAllFor(ChatType.GROUP, groupId, messageId); GroupChatEvent event = GroupChatEvent.builder() .context("deleteMessageServer") @@ -89,6 +96,34 @@ public void deleteMessage(Long groupId, String messageId, String requesterUid) { broadcastToGroup(groupId, event); } + /** + * Adds ({@code on}) or removes {@code person}'s reaction to a message, then tells the + * group's topic with a reactionsServer frame. Reactions are kept in the database, never in + * the group's S3 message file, so a reaction can't change or drop a message. + */ + public List setReaction( + Long groupId, Person person, String messageId, Reaction reaction, boolean on) { + getGroupOrThrow(groupId); + if (on) { + reactionService.add(ChatType.GROUP, groupId, messageId, person, reaction); + } else { + reactionService.remove(ChatType.GROUP, groupId, messageId, person, reaction); + } + List reactions = + reactionService.forMessage(ChatType.GROUP, groupId, messageId); + + GroupChatEvent event = GroupChatEvent.builder() + .context("reactionsServer") + .groupId(groupId) + .messageId(messageId) + .reactions(reactions) + .date(Instant.now().toString()) + .build(); + + broadcastToGroup(groupId, event); + return reactions; + } + /** * Stores a shared file and tells the group's topic about it. The frame names the file and * its size but carries no bytes: a big file sent to every member's socket could overflow 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..e4f83259 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupChatFilesTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatFilesTest.java @@ -40,6 +40,7 @@ import com.open.spring.mvc.S3uploads.S3FileHandler; import com.open.spring.mvc.person.Person; import com.open.spring.mvc.person.PersonJpaRepository; +import com.open.spring.mvc.reactions.MessageReactionService; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.services.s3.model.S3Exception; @@ -104,10 +105,10 @@ private void useStorage(InMemoryStorage store) { GroupChatService chat = new GroupChatService(storage, new ObjectMapper()); GroupsJpaRepository groups = mock(GroupsJpaRepository.class); messaging = mock(SimpMessagingTemplate.class); - GroupChatRealtimeService realtime = new GroupChatRealtimeService(chat, groups, messaging); + GroupChatRealtimeService realtime = new GroupChatRealtimeService(chat, groups, messaging, mock(MessageReactionService.class)); GroupChatReadService reads = new GroupChatReadService(mock(GroupChatReadStateJpaRepository.class), groups, chat); PersonJpaRepository people = mock(PersonJpaRepository.class); - controller = new GroupChatApiController(chat, realtime, reads, groups, people); + controller = new GroupChatApiController(chat, realtime, reads, groups, people, mock(MessageReactionService.class)); Groups group = new Groups(); group.setName("CSA"); diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatReactionTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatReactionTest.java new file mode 100644 index 00000000..e32cfd6f --- /dev/null +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatReactionTest.java @@ -0,0 +1,181 @@ +package com.open.spring.mvc.groups; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.messaging.simp.SimpMessagingTemplate; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.test.util.ReflectionTestUtils; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.open.spring.mvc.S3uploads.S3FileHandler; +import com.open.spring.mvc.person.Person; +import com.open.spring.mvc.person.PersonJpaRepository; +import com.open.spring.mvc.reactions.ChatType; +import com.open.spring.mvc.reactions.MessageReactionService; +import com.open.spring.mvc.reactions.MessageReactionService.MessageReactions; +import com.open.spring.mvc.reactions.MessageReactionService.ReactionSummary; +import com.open.spring.mvc.reactions.MessageReactionService.Reactor; +import com.open.spring.mvc.reactions.Reaction; + +/** + * Reacting to a group chat message: signed in, a real message id, broadcast as a + * reactionsServer frame, and never a read or write of the group's S3 message file. + */ +class GroupChatReactionTest { + + private static final String MESSAGE_ID = "3f2c8a8e-5b1d-4c7e-9a52-8f0e6d4b2a10"; + + private S3FileHandler storage; + private GroupChatService chat; + private SimpMessagingTemplate messaging; + private MessageReactionService reactionService; + private GroupChatRealtimeService realtime; + private GroupChatApiController controller; + private Person ada; + private List summaries; + + @BeforeEach + void setUp() { + storage = mock(S3FileHandler.class); + chat = spy(new GroupChatService(storage, new ObjectMapper())); + GroupsJpaRepository groups = mock(GroupsJpaRepository.class); + messaging = mock(SimpMessagingTemplate.class); + reactionService = mock(MessageReactionService.class); + realtime = new GroupChatRealtimeService(chat, groups, messaging, reactionService); + PersonJpaRepository people = mock(PersonJpaRepository.class); + GroupChatReadService reads = new GroupChatReadService(mock(GroupChatReadStateJpaRepository.class), groups, chat); + controller = new GroupChatApiController(chat, realtime, reads, groups, people, reactionService); + + Groups group = spy(new Groups()); + when(group.getId()).thenReturn(3L); + group.setName("Team Three"); + when(groups.findById(3L)).thenReturn(Optional.of(group)); + + ada = new Person(); + ReflectionTestUtils.setField(ada, "id", 1L); + ada.setUid("ada"); + ada.setName("Ada"); + when(people.findByUid("ada")).thenReturn(ada); + + summaries = List.of(new ReactionSummary("love", List.of(new Reactor("ada", "Ada")))); + when(reactionService.forMessage(ChatType.GROUP, 3L, MESSAGE_ID)).thenReturn(summaries); + } + + @AfterEach + void clearAuthentication() { + SecurityContextHolder.clearContext(); + } + + @Test + void aReactionGoesOutAsAReactionsServerFrame() { + List result = realtime.setReaction(3L, ada, MESSAGE_ID, Reaction.LOVE, true); + + verify(reactionService).add(ChatType.GROUP, 3L, MESSAGE_ID, ada, Reaction.LOVE); + ArgumentCaptor frame = ArgumentCaptor.forClass(GroupChatEvent.class); + verify(messaging).convertAndSend(eq("/topic/group/3"), frame.capture()); + assertEquals("reactionsServer", frame.getValue().getContext()); + assertEquals(3L, frame.getValue().getGroupId()); + assertEquals(MESSAGE_ID, frame.getValue().getMessageId()); + assertEquals(summaries, frame.getValue().getReactions()); + assertEquals(summaries, result); + } + + @Test + void aReactionNeverTouchesTheGroupsFile() { + signIn("ada"); + + ResponseEntity added = controller.addReaction(3L, MESSAGE_ID, "love"); + ResponseEntity removed = controller.removeReaction(3L, MESSAGE_ID, "love"); + when(reactionService.forChat(ChatType.GROUP, 3L)).thenReturn(java.util.Map.of(MESSAGE_ID, summaries)); + ResponseEntity listed = controller.getReactions(3L); + + assertEquals(HttpStatus.OK, added.getStatusCode()); + assertEquals(new MessageReactions(MESSAGE_ID, summaries), added.getBody()); + assertEquals(HttpStatus.OK, removed.getStatusCode()); + verify(reactionService).remove(ChatType.GROUP, 3L, MESSAGE_ID, ada, Reaction.LOVE); + assertEquals(java.util.Map.of(MESSAGE_ID, summaries), listed.getBody()); + verifyNoInteractions(storage); + } + + @Test + void signedOutIs401() { + assertEquals(HttpStatus.UNAUTHORIZED, controller.addReaction(3L, MESSAGE_ID, "love").getStatusCode()); + assertEquals(HttpStatus.UNAUTHORIZED, controller.removeReaction(3L, MESSAGE_ID, "love").getStatusCode()); + assertEquals(HttpStatus.UNAUTHORIZED, controller.getReactions(3L).getStatusCode()); + verifyNoInteractions(reactionService); + } + + @Test + void aBadMessageIdIs400() { + signIn("ada"); + + assertEquals(HttpStatus.BAD_REQUEST, controller.addReaction(3L, "not-a-message", "love").getStatusCode()); + assertEquals(HttpStatus.BAD_REQUEST, controller.addReaction(3L, "../shared-files", "love").getStatusCode()); + verify(reactionService, never()).add(any(), any(), any(), any(), any()); + } + + @Test + void anUnknownReactionIs400() { + signIn("ada"); + + assertEquals(HttpStatus.BAD_REQUEST, controller.addReaction(3L, MESSAGE_ID, "thumbsup").getStatusCode()); + verify(reactionService, never()).add(any(), any(), any(), any(), any()); + } + + @Test + void anUnknownGroupIs404() { + signIn("ada"); + + assertEquals(HttpStatus.NOT_FOUND, controller.addReaction(99L, MESSAGE_ID, "love").getStatusCode()); + assertEquals(HttpStatus.NOT_FOUND, controller.getReactions(99L).getStatusCode()); + verifyNoInteractions(reactionService); + } + + @Test + void deletingAMessageRemovesItsReactions() { + GroupChatMessage saved = new GroupChatMessage("Ada", "ada", "hello", "2026-11-21T00:00:00Z", null); + doReturn(new ArrayList<>(List.of(saved))).when(chat).getMessages("Team Three"); + + realtime.deleteMessage(3L, saved.getId(), "ada"); + + verify(reactionService).removeAllFor(ChatType.GROUP, 3L, saved.getId()); + } + + @Test + void onlyAReactionsFrameCarriesReactions() throws Exception { + ObjectMapper json = new ObjectMapper(); + String messageFrame = json.writeValueAsString(GroupChatEvent.builder() + .context("sendMessageServer").groupId(3L).messageId(MESSAGE_ID).message("hi").build()); + String reactionsFrame = json.writeValueAsString(GroupChatEvent.builder() + .context("reactionsServer").groupId(3L).messageId(MESSAGE_ID).reactions(summaries).build()); + + assertFalse(messageFrame.contains("\"reactions\"")); + assertTrue(reactionsFrame.contains("\"reactions\"")); + } + + private void signIn(String uid) { + SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(uid, null, List.of())); + } +} diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatRegressionTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatRegressionTest.java index c310e301..021a96c7 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupChatRegressionTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatRegressionTest.java @@ -30,6 +30,7 @@ import com.open.spring.mvc.S3uploads.S3FileHandler; import com.open.spring.mvc.person.Person; import com.open.spring.mvc.person.PersonJpaRepository; +import com.open.spring.mvc.reactions.MessageReactionService; class GroupChatRegressionTest { private S3FileHandler storage; @@ -50,9 +51,9 @@ void setUp() { groups = mock(GroupsJpaRepository.class); readStates = mock(GroupChatReadStateJpaRepository.class); reads = new GroupChatReadService(readStates, groups, chat); - realtime = new GroupChatRealtimeService(chat, groups, mock(SimpMessagingTemplate.class)); + realtime = new GroupChatRealtimeService(chat, groups, mock(SimpMessagingTemplate.class), mock(MessageReactionService.class)); PersonJpaRepository people = mock(PersonJpaRepository.class); - controller = new GroupChatApiController(chat, realtime, reads, groups, people); + controller = new GroupChatApiController(chat, realtime, reads, groups, people, mock(MessageReactionService.class)); Groups group = spy(new Groups()); when(group.getId()).thenReturn(7L); From bc79ac5997ad97cd3dfe98a328646b7c21713e96 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Sun, 22 Nov 2026 00:30:20 -0800 Subject: [PATCH 05/46] Group chat: a send keeps the history when S3 can't read it A send reads the group's whole messages file, adds the message and writes the file back. decodeFile answers null for any failure, not only a missing file, so when S3 timed out, was throttled or answered a 5xx, the send took the chat for empty and wrote the one new message over the whole history. It still answered 200 and broadcast the message. The send now reads with a strict decodeFileOrThrow, like fileExistsOrThrow: only S3's 404 means no messages yet. A timeout, no connection or a 5xx throws MessagesReadFailedException, nothing is saved or broadcast, and POST /api/groups/chat/{id}/messages answers 503 with Retry-After, the same as a shared-file check that fails. S3 refusing the read (a 4xx) or a bug here also writes nothing and gets the route's usual 400, since waiting won't fix it. S3 failures to read are logged with their cause. Without S3 settings a send still broadcasts live, as before. decodeFile, edits and deletes are unchanged. Tests send through the controller to a real S3FileHandler over a stand-in S3 client: a 503 and a timeout keep the stored file byte for byte and answer 503, a 403 and a bug write nothing and get no retry, a missing file starts the history, and a server without S3 still broadcasts. The two older tests that stub S3 now stub the strict read a send makes. --- .../spring/mvc/S3uploads/S3FileHandler.java | 25 +++ .../mvc/groups/GroupChatApiController.java | 14 +- .../spring/mvc/groups/GroupChatService.java | 30 ++- .../groups/MessagesReadFailedException.java | 14 ++ .../S3uploads/S3FileHandlerDecodeTest.java | 72 +++++++ .../mvc/groups/GroupChatMessageJsonTest.java | 2 +- .../spring/mvc/groups/GroupChatSendTest.java | 201 ++++++++++++++++++ .../mvc/groups/GroupChatServiceTest.java | 6 + 8 files changed, 357 insertions(+), 7 deletions(-) create mode 100644 src/main/java/com/open/spring/mvc/groups/MessagesReadFailedException.java create mode 100644 src/test/java/com/open/spring/mvc/S3uploads/S3FileHandlerDecodeTest.java create mode 100644 src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java diff --git a/src/main/java/com/open/spring/mvc/S3uploads/S3FileHandler.java b/src/main/java/com/open/spring/mvc/S3uploads/S3FileHandler.java index fafef205..62865a8f 100644 --- a/src/main/java/com/open/spring/mvc/S3uploads/S3FileHandler.java +++ b/src/main/java/com/open/spring/mvc/S3uploads/S3FileHandler.java @@ -264,6 +264,31 @@ public boolean fileExistsOrThrow(String uid, String filename) { } } + /** + * Like decodeFile, but only "not found" (404) reads as nothing stored: any other failure to + * read (a throttle, a 5xx, no connection) throws. For a caller that writes back what it read, + * a read that failed is not an empty file. With no S3 client there is nothing to read and + * nothing can be written, so that reads as nothing stored, as in decodeFile. + */ + public String decodeFileOrThrow(String uid, String filename) { + if (s3Client == null) { + log.warn("S3 download attempted but S3 client is not configured."); + return null; + } + try { + ResponseBytes objectBytes = s3Client.getObjectAsBytes(GetObjectRequest.builder() + .bucket(bucketName) + .key(generateKey(uid, filename)) + .build()); + return Base64.getEncoder().encodeToString(objectBytes.asByteArray()); + } catch (S3Exception e) { + if (e.statusCode() == 404) { + return null; + } + throw e; + } + } + private String generateKey(String uid, String filename) { return uid + "/" + filename; } diff --git a/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java b/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java index 60eaaf80..56db34d1 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java @@ -38,9 +38,9 @@ @CrossOrigin public class GroupChatApiController { - // How long to wait before sharing again when S3 couldn't check a path: a throttle or a - // short outage clears in seconds. - private static final int SHARE_RETRY_AFTER_SECONDS = 5; + // How long to wait before trying again when S3 couldn't check a shared path or read a + // group's messages: a throttle or a short outage clears in seconds. + private static final int RETRY_AFTER_SECONDS = 5; private final GroupChatService groupChatService; private final GroupChatRealtimeService realtimeService; @@ -192,6 +192,12 @@ public ResponseEntity postMessage( try { realtimeService.publishMessage(groupId, message.getMessage(), message.getImage(), identity); + } catch (MessagesReadFailedException ex) { + // S3 couldn't read the history, so nothing was saved or broadcast: saving would have + // replaced it. That's S3 being unavailable for a moment, not a bug here: a 503, and when. + return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE) + .header(HttpHeaders.RETRY_AFTER, String.valueOf(RETRY_AFTER_SECONDS)) + .body(ex.getMessage()); } catch (RuntimeException ex) { return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST); } @@ -406,7 +412,7 @@ public ResponseEntity uploadSharedFile( response.put("message", ex.getMessage()); response.put("filename", ex.getPath()); return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE) - .header(HttpHeaders.RETRY_AFTER, String.valueOf(SHARE_RETRY_AFTER_SECONDS)) + .header(HttpHeaders.RETRY_AFTER, String.valueOf(RETRY_AFTER_SECONDS)) .body(response); } catch (RuntimeException ex) { return new ResponseEntity<>("Upload failed", HttpStatus.INTERNAL_SERVER_ERROR); diff --git a/src/main/java/com/open/spring/mvc/groups/GroupChatService.java b/src/main/java/com/open/spring/mvc/groups/GroupChatService.java index d6189355..5f902092 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatService.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatService.java @@ -80,7 +80,33 @@ public void ensureGroupStorageExists(String groupName) { } public List getMessages(String groupName) { - String base64Data = s3FileHandler.decodeFile(groupName, MESSAGES_FILE); + return parseMessages(groupName, s3FileHandler.decodeFile(groupName, MESSAGES_FILE)); + } + + /** + * The group's messages for a send, which writes the whole file back. Strict: a read that + * failed throws rather than reading as an empty chat, which the send would save over the + * history. Only S3's 404 means no messages yet. S3 out of reach or answering a 5xx is + * something to wait out, so that throws MessagesReadFailedException; anything else goes up + * as it is. + */ + private List readMessagesOrThrow(String groupName) { + String base64Data; + try { + base64Data = s3FileHandler.decodeFileOrThrow(groupName, MESSAGES_FILE); + } catch (SdkClientException | S3Exception e) { + // Logged for every failure: the route answers a refused read without logging it. + log.warn("Could not read the messages of group {}", groupName, e); + if (e instanceof S3Exception answered && answered.statusCode() < 500) { + // S3 refused the request (no permission, a bad key): waiting won't fix that. + throw e; + } + throw new MessagesReadFailedException(e); + } + return parseMessages(groupName, base64Data); + } + + private List parseMessages(String groupName, String base64Data) { if (base64Data == null || base64Data.isBlank()) { return new ArrayList<>(); } @@ -119,7 +145,7 @@ public List getMessages(String groupName) { public List addMessage(String groupName, GroupChatMessage message) { synchronized (messageLocks.computeIfAbsent(groupName, name -> new Object())) { - List messages = getMessages(groupName); + List messages = readMessagesOrThrow(groupName); messages.add(message); String jsonl = messages.stream() diff --git a/src/main/java/com/open/spring/mvc/groups/MessagesReadFailedException.java b/src/main/java/com/open/spring/mvc/groups/MessagesReadFailedException.java new file mode 100644 index 00000000..f74fcda8 --- /dev/null +++ b/src/main/java/com/open/spring/mvc/groups/MessagesReadFailedException.java @@ -0,0 +1,14 @@ +package com.open.spring.mvc.groups; + +/** + * S3 couldn't read a group's messages for now: it timed out, couldn't be reached or answered + * with a 5xx (a throttle, an outage). A send writes the whole messages file back, so it's refused + * rather than save the new message over the history, and the API answers 503 with Retry-After, + * since S3 being unavailable for a moment isn't a bug in this server. + */ +public class MessagesReadFailedException extends RuntimeException { + + public MessagesReadFailedException(Throwable cause) { + super("Could not read this group's messages, so the message was not sent. Try again in a moment.", cause); + } +} diff --git a/src/test/java/com/open/spring/mvc/S3uploads/S3FileHandlerDecodeTest.java b/src/test/java/com/open/spring/mvc/S3uploads/S3FileHandlerDecodeTest.java new file mode 100644 index 00000000..181d4527 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/S3uploads/S3FileHandlerDecodeTest.java @@ -0,0 +1,72 @@ +package com.open.spring.mvc.S3uploads; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; + +import java.nio.charset.StandardCharsets; +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.test.util.ReflectionTestUtils; + +import software.amazon.awssdk.core.ResponseBytes; +import software.amazon.awssdk.core.exception.SdkClientException; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectResponse; +import software.amazon.awssdk.services.s3.model.NoSuchKeyException; +import software.amazon.awssdk.services.s3.model.S3Exception; + +/** + * decodeFileOrThrow tells "nothing stored" apart from "couldn't read": a caller that writes + * back what it read must not take a read that failed for an empty file. + */ +class S3FileHandlerDecodeTest { + + private static final String MESSAGES = "messages-images/messages.jsonl"; + + private S3Client s3; + private S3FileHandler handler; + + @BeforeEach + void setUp() { + s3 = mock(S3Client.class); + handler = new S3FileHandler(); + ReflectionTestUtils.setField(handler, "s3Client", s3); + } + + @Test + void aStoredFileComesBackAsBase64() { + doReturn(ResponseBytes.fromByteArray(GetObjectResponse.builder().build(), "hello".getBytes(StandardCharsets.UTF_8))) + .when(s3).getObjectAsBytes(any(GetObjectRequest.class)); + assertEquals("aGVsbG8=", handler.decodeFileOrThrow("CSA", MESSAGES)); + } + + @Test + void notFoundMeansNothingIsStored() { + doThrow(NoSuchKeyException.builder().statusCode(404).message("The specified key does not exist.").build()) + .when(s3).getObjectAsBytes(any(GetObjectRequest.class)); + assertNull(handler.decodeFileOrThrow("CSA", MESSAGES)); + } + + @Test + void anyOtherFailureThrowsInsteadOfReadingAsNothingStored() { + List failures = List.of( + (S3Exception) S3Exception.builder().statusCode(503).message("Slow Down").build(), + (S3Exception) S3Exception.builder().statusCode(403).message("Access Denied").build(), + SdkClientException.create("Unable to execute HTTP request: Read timed out")); + for (RuntimeException failure : failures) { + doThrow(failure).when(s3).getObjectAsBytes(any(GetObjectRequest.class)); + assertSame(failure, assertThrows(RuntimeException.class, () -> handler.decodeFileOrThrow("CSA", MESSAGES))); + // decodeFile keeps answering null, as its other callers expect. + assertNull(handler.decodeFile("CSA", MESSAGES)); + } + } +} diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatMessageJsonTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatMessageJsonTest.java index 175540a0..943a977e 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupChatMessageJsonTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatMessageJsonTest.java @@ -54,7 +54,7 @@ void messageIsWrittenWithAuthorNotName() throws Exception { @Test void addingAMessageKeepsTheSenderOfOlderLines() throws Exception { S3FileHandler s3 = mock(S3FileHandler.class); - when(s3.decodeFile("CSA", "messages-images/messages.jsonl")).thenReturn( + when(s3.decodeFileOrThrow("CSA", "messages-images/messages.jsonl")).thenReturn( Base64.getEncoder().encodeToString(SAVED_BEFORE_RENAME.getBytes(StandardCharsets.UTF_8))); GroupChatService service = new GroupChatService(s3, objectMapper); diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java new file mode 100644 index 00000000..b6c3b718 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java @@ -0,0 +1,201 @@ +package com.open.spring.mvc.groups; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.messaging.simp.SimpMessagingTemplate; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.test.util.ReflectionTestUtils; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.open.spring.mvc.S3uploads.S3FileHandler; +import com.open.spring.mvc.person.Person; +import com.open.spring.mvc.person.PersonJpaRepository; + +import software.amazon.awssdk.core.ResponseBytes; +import software.amazon.awssdk.core.exception.SdkClientException; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectResponse; +import software.amazon.awssdk.services.s3.model.NoSuchKeyException; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.PutObjectResponse; +import software.amazon.awssdk.services.s3.model.S3Exception; + +/** + * Sending a message reads the group's whole messages file, adds the message and writes the + * file back. A read that failed must not count as an empty chat: writing that back would + * replace the whole history with the one new message. + */ +class GroupChatSendTest { + + private static final String MESSAGES_KEY = "CSA/messages-images/messages.jsonl"; + private static final String ADA_LINE = "{\"id\":\"m1\",\"author\":\"Ada Lovelace\",\"author_uid\":\"ada\"," + + "\"message\":\"Meeting at 3\",\"date\":\"2026-11-21T10:00:00Z\",\"image\":null,\"edited\":false}"; + + /** S3's objects by key. The real S3FileHandler reads and writes them through a stand-in S3 client. */ + private final Map objects = new ConcurrentHashMap<>(); + private S3Client s3; + private SimpMessagingTemplate messaging; + private GroupChatApiController controller; + + @BeforeEach + void setUp() { + useFreshStorage(); + } + + @AfterEach + void signOut() { + SecurityContextHolder.clearContext(); + } + + /** An empty bucket behind a real S3FileHandler, as S3 answers: a missing key is a 404 NoSuchKey. */ + private void useFreshStorage() { + objects.clear(); + s3 = mock(S3Client.class); + when(s3.getObjectAsBytes(any(GetObjectRequest.class))).thenAnswer(call -> { + byte[] bytes = objects.get(call.getArgument(0).key()); + if (bytes == null) { + throw NoSuchKeyException.builder().statusCode(404).message("The specified key does not exist.").build(); + } + return ResponseBytes.fromByteArray(GetObjectResponse.builder().build(), bytes); + }); + when(s3.putObject(any(PutObjectRequest.class), any(RequestBody.class))).thenAnswer(call -> { + try (InputStream body = call.getArgument(1).contentStreamProvider().newStream()) { + objects.put(call.getArgument(0).key(), body.readAllBytes()); + } + return PutObjectResponse.builder().build(); + }); + S3FileHandler storage = new S3FileHandler(); + ReflectionTestUtils.setField(storage, "s3Client", s3); + ReflectionTestUtils.setField(storage, "bucketName", "chat-test"); + wire(storage); + } + + /** The send route over this storage, with Grace Hopper signed in. */ + private void wire(S3FileHandler storage) { + GroupChatService chat = new GroupChatService(storage, new ObjectMapper()); + GroupsJpaRepository groups = mock(GroupsJpaRepository.class); + messaging = mock(SimpMessagingTemplate.class); + 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); + + Groups group = new Groups(); + group.setName("CSA"); + when(groups.findById(7L)).thenReturn(Optional.of(group)); + Person grace = new Person(); + grace.setUid("grace"); + grace.setName("Grace Hopper"); + when(people.findByUid("grace")).thenReturn(grace); + SecurityContextHolder.getContext().setAuthentication( + new UsernamePasswordAuthenticationToken("grace", null, List.of())); + } + + private ResponseEntity send(String text) { + GroupChatMessage request = new GroupChatMessage(); + request.setMessage(text); + return controller.postMessage(7L, request); + } + + private String storedMessages() { + byte[] bytes = objects.get(MESSAGES_KEY); + return bytes == null ? null : new String(bytes, StandardCharsets.UTF_8); + } + + @Test + void aReadThatFailsRefusesTheSendWithA503AndKeepsTheHistory() { + // S3 throttled (503 Slow Down) or out of reach: failures that clear if you wait. + List failures = List.of( + (S3Exception) S3Exception.builder().statusCode(503).message("Slow Down").build(), + SdkClientException.create("Unable to execute HTTP request: Read timed out")); + for (RuntimeException failure : failures) { + useFreshStorage(); + objects.put(MESSAGES_KEY, ADA_LINE.getBytes(StandardCharsets.UTF_8)); + doThrow(failure).when(s3).getObjectAsBytes(any(GetObjectRequest.class)); + + ResponseEntity response = send("Works for me"); + + assertEquals(HttpStatus.SERVICE_UNAVAILABLE, response.getStatusCode(), failure.toString()); + String retryAfter = response.getHeaders().getFirst(HttpHeaders.RETRY_AFTER); + assertTrue(retryAfter != null && retryAfter.matches("[1-9][0-9]*"), "Retry-After: " + retryAfter); + assertEquals(ADA_LINE, storedMessages(), failure.toString()); + // The group isn't told about a message that wasn't saved. + verify(messaging, never()).convertAndSend(any(String.class), any(Object.class)); + } + } + + @Test + void aReadS3RefusesOrABugHereIsNotOfferedARetryAndWritesNothing() { + // No permission, a bad key, or a fault in this server: waiting won't fix these. + List faults = List.of( + (S3Exception) S3Exception.builder().statusCode(403).message("Access Denied").build(), + new NullPointerException("a bug here, not S3")); + for (RuntimeException fault : faults) { + useFreshStorage(); + objects.put(MESSAGES_KEY, ADA_LINE.getBytes(StandardCharsets.UTF_8)); + doThrow(fault).when(s3).getObjectAsBytes(any(GetObjectRequest.class)); + + ResponseEntity response = send("Works for me"); + + assertFalse(response.getStatusCode().is2xxSuccessful(), fault.toString()); + assertNotEquals(HttpStatus.SERVICE_UNAVAILABLE, response.getStatusCode(), fault.toString()); + assertNull(response.getHeaders().getFirst(HttpHeaders.RETRY_AFTER), fault.toString()); + assertEquals(ADA_LINE, storedMessages(), fault.toString()); + verify(messaging, never()).convertAndSend(any(String.class), any(Object.class)); + } + } + + @Test + void aGroupWithNoMessagesFileYetStartsItsHistoryWithTheSend() throws Exception { + // S3's 404: nothing is stored yet, so there's no history to lose. + ResponseEntity response = send("Works for me"); + + assertEquals(HttpStatus.OK, response.getStatusCode()); + List lines = storedMessages().lines().toList(); + assertEquals(1, lines.size(), storedMessages()); + GroupChatMessage saved = new ObjectMapper().readValue(lines.get(0), GroupChatMessage.class); + assertEquals("Works for me", saved.getMessage()); + assertEquals("grace", saved.getAuthor_uid()); + } + + @Test + void withoutS3SettingsASendIsStillBroadcastLive() { + // A local server without S3 saves nothing, but its chats keep working live. + wire(new S3FileHandler()); + + ResponseEntity response = send("Works for me"); + + assertEquals(HttpStatus.OK, response.getStatusCode()); + ArgumentCaptor frame = ArgumentCaptor.forClass(Object.class); + verify(messaging).convertAndSend(eq("/topic/group/7"), frame.capture()); + assertEquals("Works for me", ((GroupChatEvent) frame.getValue()).getMessage()); + } +} diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatServiceTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatServiceTest.java index b1d40b62..97ce7cc1 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupChatServiceTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatServiceTest.java @@ -57,6 +57,12 @@ public String decodeFile(String uid, String filename) { } return copy; } + + // Its reads never fail, so a send's strict read is the same read. + @Override + public String decodeFileOrThrow(String uid, String filename) { + return decodeFile(uid, filename); + } } private final ObjectMapper json = new ObjectMapper(); From 5b9931674d7ca23967842a7fad54c2f23bd4af2b Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Sat, 21 Nov 2026 23:00:05 -0800 Subject: [PATCH 06/46] Group chat: two message writes at once keep both changes Sending, editing and deleting a message each read the group's whole messages file from S3, change it and write the file back, with no lock. Two at once both read the same old copy, so the later write dropped the other's change: two people sending at the same moment lost a message, and an edit or delete during a send lost the edit or the new message. They now take one lock per group, the same pattern as the shared-files metadata lock. Reads don't wait, and other groups don't wait on each other. The lock only works within one server. Several servers writing the same file would need S3's conditional writes instead. Tests run two sends, an edit and a send, and a delete and a send at once against an S3 stub that holds each read until the other one has started. --- .../spring/mvc/groups/GroupChatService.java | 104 +++++++------ .../mvc/groups/GroupChatServiceTest.java | 146 ++++++++++++++++++ 2 files changed, 204 insertions(+), 46 deletions(-) create mode 100644 src/test/java/com/open/spring/mvc/groups/GroupChatServiceTest.java diff --git a/src/main/java/com/open/spring/mvc/groups/GroupChatService.java b/src/main/java/com/open/spring/mvc/groups/GroupChatService.java index 790db7d3..d6189355 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatService.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatService.java @@ -35,6 +35,12 @@ public class GroupChatService { private final S3FileHandler s3FileHandler; private final ObjectMapper objectMapper; + // One lock per group for its messages file. Sending, editing and deleting each read the + // whole file, change it and write it back, so two at once would both change the same old + // copy and the later write would drop the other's change. This keeps them apart within + // this server only; several servers would need S3's conditional writes instead. + private final Map messageLocks = new ConcurrentHashMap<>(); + // One lock per group for the "shared by" sidecar, which is read, changed and written // back on every upload: a folder shared from the page uploads several files at once, // and without this the last write would drop the others' attribution. @@ -112,18 +118,20 @@ public List getMessages(String groupName) { } public List addMessage(String groupName, GroupChatMessage message) { - List messages = getMessages(groupName); - messages.add(message); + synchronized (messageLocks.computeIfAbsent(groupName, name -> new Object())) { + List messages = getMessages(groupName); + messages.add(message); - String jsonl = messages.stream() - .map(this::toJson) - .collect(Collectors.joining("\n")); + String jsonl = messages.stream() + .map(this::toJson) + .collect(Collectors.joining("\n")); - String base64Data = Base64.getEncoder() - .encodeToString(jsonl.getBytes(StandardCharsets.UTF_8)); + String base64Data = Base64.getEncoder() + .encodeToString(jsonl.getBytes(StandardCharsets.UTF_8)); - s3FileHandler.uploadFile(base64Data, MESSAGES_FILE, groupName); - return messages; + s3FileHandler.uploadFile(base64Data, MESSAGES_FILE, groupName); + return messages; + } } /** @@ -133,58 +141,62 @@ public List addMessage(String groupName, GroupChatMessage mess */ public boolean editMessage(String groupName, String messageId, String newMessage, String requesterUid) { if (messageId == null) return false; - List messages = getMessages(groupName); - boolean found = false; - for (GroupChatMessage m : messages) { - if (messageId.equals(m.getId())) { - if (requesterUid == null || !requesterUid.equals(m.getAuthor_uid())) { - throw new SecurityException("Not the message sender"); + synchronized (messageLocks.computeIfAbsent(groupName, name -> new Object())) { + List messages = getMessages(groupName); + boolean found = false; + for (GroupChatMessage m : messages) { + if (messageId.equals(m.getId())) { + if (requesterUid == null || !requesterUid.equals(m.getAuthor_uid())) { + throw new SecurityException("Not the message sender"); + } + m.setMessage(newMessage); + m.setEdited(true); + found = true; + break; } - m.setMessage(newMessage); - m.setEdited(true); - found = true; - break; } - } - if (found) { - String jsonl = messages.stream() - .map(this::toJson) - .collect(Collectors.joining("\n")); + if (found) { + String jsonl = messages.stream() + .map(this::toJson) + .collect(Collectors.joining("\n")); - String base64Data = Base64.getEncoder() - .encodeToString(jsonl.getBytes(StandardCharsets.UTF_8)); + String base64Data = Base64.getEncoder() + .encodeToString(jsonl.getBytes(StandardCharsets.UTF_8)); - s3FileHandler.uploadFile(base64Data, MESSAGES_FILE, groupName); + s3FileHandler.uploadFile(base64Data, MESSAGES_FILE, groupName); + } + return found; } - return found; } /** Same ownership rule as {@link #editMessage}; throws {@link SecurityException} on mismatch. */ public void deleteMessage(String groupName, String messageId, String requesterUid) { if (messageId == null) return; - List messages = getMessages(groupName); - - GroupChatMessage target = messages.stream() - .filter(m -> messageId.equals(m.getId())) - .findFirst() - .orElse(null); - if (target == null) return; - if (requesterUid == null || !requesterUid.equals(target.getAuthor_uid())) { - throw new SecurityException("Not the message sender"); - } + synchronized (messageLocks.computeIfAbsent(groupName, name -> new Object())) { + List messages = getMessages(groupName); - boolean removed = messages.remove(target); + GroupChatMessage target = messages.stream() + .filter(m -> messageId.equals(m.getId())) + .findFirst() + .orElse(null); + if (target == null) return; + if (requesterUid == null || !requesterUid.equals(target.getAuthor_uid())) { + throw new SecurityException("Not the message sender"); + } - if (removed) { - String jsonl = messages.stream() - .map(this::toJson) - .collect(Collectors.joining("\n")); + boolean removed = messages.remove(target); - String base64Data = Base64.getEncoder() - .encodeToString(jsonl.getBytes(StandardCharsets.UTF_8)); + if (removed) { + String jsonl = messages.stream() + .map(this::toJson) + .collect(Collectors.joining("\n")); - s3FileHandler.uploadFile(base64Data, MESSAGES_FILE, groupName); + String base64Data = Base64.getEncoder() + .encodeToString(jsonl.getBytes(StandardCharsets.UTF_8)); + + s3FileHandler.uploadFile(base64Data, MESSAGES_FILE, groupName); + } } } diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatServiceTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatServiceTest.java new file mode 100644 index 00000000..b1d40b62 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatServiceTest.java @@ -0,0 +1,146 @@ +package com.open.spring.mvc.groups; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.open.spring.mvc.S3uploads.S3FileHandler; + +/** + * Two changes to one group's messages at the same time. Sending, editing and deleting each + * read the group's whole messages file, change it and write it back, and neither change may + * be lost. + */ +class GroupChatServiceTest { + + private static final String MESSAGES_KEY = "CSA/messages-images/messages.jsonl"; + + /** + * S3 kept in a map, keyed the way S3FileHandler keys objects: "group/filename". A read + * takes its copy, then waits until a second read has started (or half a second passes), + * so two writes that are not kept apart both change the same old copy of the file. + */ + static class OverlappingReads extends S3FileHandler { + final Map objects = new ConcurrentHashMap<>(); + final CountDownLatch bothReading = new CountDownLatch(2); + + @Override + public String uploadFile(String base64Data, String filename, String uid) { + objects.put(uid + "/" + filename, base64Data); + return filename; + } + + @Override + public String decodeFile(String uid, String filename) { + String copy = objects.get(uid + "/" + filename); + bothReading.countDown(); + try { + bothReading.await(500, TimeUnit.MILLISECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + return copy; + } + } + + private final ObjectMapper json = new ObjectMapper(); + private OverlappingReads storage; + private GroupChatService chat; + + @BeforeEach + void setUp() { + storage = new OverlappingReads(); + chat = new GroupChatService(storage, json); + } + + @Test + void twoMessagesSentAtOnceAreBothKept() throws Exception { + GroupChatMessage ada = message("Ada Lovelace", "ada", "Meeting at 3?"); + GroupChatMessage grace = message("Grace Hopper", "grace", "Works for me"); + + atOnce(() -> chat.addMessage("CSA", ada), () -> chat.addMessage("CSA", grace)); + + // Either send may get there first, so compare them in alphabetical order. + List saved = texts(chat.getMessages("CSA")).stream().sorted().collect(Collectors.toList()); + assertEquals(List.of("Meeting at 3?", "Works for me"), saved); + } + + @Test + void anEditWhileAnotherMessageIsSentKeepsBothChanges() throws Exception { + GroupChatMessage ada = message("Ada Lovelace", "ada", "Meeting at 3"); + store(ada); + GroupChatMessage grace = message("Grace Hopper", "grace", "Works for me"); + + atOnce(() -> chat.editMessage("CSA", ada.getId(), "Meeting at 4", "ada"), + () -> chat.addMessage("CSA", grace)); + + List saved = chat.getMessages("CSA"); + assertEquals(List.of("Meeting at 4", "Works for me"), texts(saved)); + assertTrue(saved.get(0).isEdited()); + } + + @Test + void aDeleteWhileAnotherMessageIsSentKeepsBothChanges() throws Exception { + GroupChatMessage plan = message("Ada Lovelace", "ada", "Meeting at 3"); + GroupChatMessage typo = message("Ada Lovelace", "ada", "Meetign at 3"); + store(plan, typo); + GroupChatMessage grace = message("Grace Hopper", "grace", "Works for me"); + + atOnce(() -> chat.deleteMessage("CSA", typo.getId(), "ada"), + () -> chat.addMessage("CSA", grace)); + + assertEquals(List.of("Meeting at 3", "Works for me"), texts(chat.getMessages("CSA"))); + } + + /** Starts both together on their own threads and waits for both, failing if either threw. */ + private static void atOnce(Runnable first, Runnable second) throws Exception { + ExecutorService pool = Executors.newFixedThreadPool(2); + CountDownLatch start = new CountDownLatch(1); + List> done = new ArrayList<>(); + for (Runnable task : List.of(first, second)) { + done.add(pool.submit(() -> { + start.await(); + task.run(); + return null; + })); + } + start.countDown(); + try { + for (Future future : done) future.get(10, TimeUnit.SECONDS); + } finally { + pool.shutdownNow(); + } + } + + private static GroupChatMessage message(String author, String uid, String text) { + return new GroupChatMessage(author, uid, text, "2026-11-21T10:00:00Z", null); + } + + /** Saves messages straight to the group's file, one JSON object per line, as the chat does. */ + private void store(GroupChatMessage... messages) throws Exception { + List lines = new ArrayList<>(); + for (GroupChatMessage message : messages) lines.add(json.writeValueAsString(message)); + String jsonl = String.join("\n", lines); + storage.objects.put(MESSAGES_KEY, Base64.getEncoder().encodeToString(jsonl.getBytes(StandardCharsets.UTF_8))); + } + + private static List texts(List messages) { + return messages.stream().map(GroupChatMessage::getMessage).collect(Collectors.toList()); + } +} From 7eb0e3580b94729309d52d8f1db2d3e86cabe017 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Sat, 21 Nov 2026 23:52:18 -0800 Subject: [PATCH 07/46] Reactions: document the routes and frames --- api/groups.http | 16 ++++++++++++++++ docs/group-chat-architecture.md | 18 +++++++++++++++++- 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/api/groups.http b/api/groups.http index c047fa49..e888e8be 100644 --- a/api/groups.http +++ b/api/groups.http @@ -133,6 +133,22 @@ Content-Type: application/json {"filename": "notes/hello.txt", "base64Data": "Z29vZGJ5ZQ=="} +### 13g. React to a message with a Like -> 200 with {messageId, reactions}, and a reactionsServer frame on /topic/group/{id} +# Any UUID is accepted: Spring doesn't read the S3 file to check the message, and a reaction +# on a message that doesn't exist is never shown. +PUT {{baseUrl}}/api/groups/chat/{{createGroup.response.body.$.id}}/messages/3f2c8a8e-5b1d-4c7e-9a52-8f0e6d4b2a10/reactions/like + +### 13h. List the chat's reactions -> 200 with {"3f2c8a8e-...": [{"reaction": "like", "people": [{uid, name}]}]} +GET {{baseUrl}}/api/groups/chat/{{createGroup.response.body.$.id}}/reactions + +### 13i. Take the Like back -> 200 with an empty reactions list +DELETE {{baseUrl}}/api/groups/chat/{{createGroup.response.body.$.id}}/messages/3f2c8a8e-5b1d-4c7e-9a52-8f0e6d4b2a10/reactions/like + +### 13j. A key that isn't one of the six is refused -> 400 +# Direct messages have the same three routes under /api/dm/conversations/{id}: GET .../reactions, +# and PUT or DELETE .../messages/{messageId}/reactions/{reaction}, for participants only. +PUT {{baseUrl}}/api/groups/chat/{{createGroup.response.body.$.id}}/messages/3f2c8a8e-5b1d-4c7e-9a52-8f0e6d4b2a10/reactions/thumbsup + ### 14. Remove yourself from the test group -> 200 DELETE {{baseUrl}}/api/groups/{{createGroup.response.body.$.id}}/members/{{me.response.body.$.id}} diff --git a/docs/group-chat-architecture.md b/docs/group-chat-architecture.md index 1d0dc01c..a961ee81 100644 --- a/docs/group-chat-architecture.md +++ b/docs/group-chat-architecture.md @@ -104,7 +104,7 @@ The client sends a `GroupChatEvent` JSON object whose `context` names the event. | `heartbeat` | `heartbeatServer` with `participants` | | | anything else | `errorServer` | `Unsupported context`. | -Edits and deletes made through REST are broadcast too, as `editMessageServer` and `deleteMessageServer`. +Edits and deletes made through REST are broadcast too, as `editMessageServer` and `deleteMessageServer`. So are reactions, as `reactionsServer` with the `messageId` and the message's `reactions` after the change (see Reactions). ## REST operations @@ -135,6 +135,9 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) | POST | `/api/groups/chat/{groupId}/messages` | Send `{message, image}`; broadcasts it and returns the history | Any signed-in account. The sender is the signed-in account. | | PATCH | `/api/groups/chat/{groupId}/messages/{messageId}` | Edit a message | Only its sender (403 otherwise) | | DELETE | `/api/groups/chat/{groupId}/messages/{messageId}` | Delete a message | Only its sender (403 otherwise) | +| GET | `/api/groups/chat/{groupId}/reactions` | Every reaction in the chat, as `{messageId: [{reaction, people: [{uid, name}]}]}` | Any signed-in account | +| PUT | `/api/groups/chat/{groupId}/messages/{messageId}/reactions/{reaction}` | Add your reaction (`like`, `love`, `haha`, `wow`, `sad`, `celebrate`); answers `{messageId, reactions}` and broadcasts `reactionsServer`. 400 for any other key, or a `messageId` that isn't a UUID | Any signed-in account | +| DELETE | `/api/groups/chat/{groupId}/messages/{messageId}/reactions/{reaction}` | Remove your reaction; the same answer and broadcast, and 200 even when it wasn't there | Any signed-in account | | GET | `/api/groups/chat/unread` | `{total, unreadByGroup}` across your groups | You | | POST | `/api/groups/chat/{groupId}/read` | Mark a group read | You | | GET | `/api/groups/chat/{groupId}/files` | Shared files with who uploaded them, each with its bytes as `base64Data` | Any signed-in account | @@ -149,6 +152,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) |---|---|---| | Groups and members | SQL: `groups`, `group_members`, and the shared `submitter` table | Ids come from `submitter_seq`, shared with `Person`. | | Read states | SQL: `group_chat_read_state` (`group_id`, `person_id`, `last_read_at`) | One row per member per group. | +| Reactions | SQL: `message_reaction` (`chat_type`, `chat_id`, `message_id`, `person_id`, `reaction`), created at startup by `MessageReactionTableInitializer` | Shared with direct messages (`chat_type` is `DM` or `GROUP`). All five columns are the primary key, so a person leaves each reaction once on a message. Never stored in the group's S3 file. | | Messages | S3: `/messages-images/messages.jsonl` | One JSON line per message: `id`, `author` (display name), `author_uid`, `message`, `date`, `image`, `edited`. | | Shared files | S3: `/shared-files/` plus `shared-files-meta.json` for who uploaded each | A file shared from a folder keeps its folders: `filename` is a path like `project/src/Main.java` (`SharedFilePaths`: no `..`, `.` or empty names, nothing absolute, no backslashes or control characters, at most 512 characters and 255 per name). A shared file is never written over: the same path again is refused with 409, and so is an upload of a path another upload is writing at that moment (`sharesInFlight`, within one server), so two people sharing `notes.md` at once keep both files. The page then shares its copy under the next free name. A file goes up as one base64 string in JSON, so `JsonLimitsConfig` lets a JSON string be up to 50,000,000 characters, enough for a 35 MB file (Jackson's default of 20,000,000 stopped uploads at about 14 MB; nginx caps a request at 50 MB). The existence check is strict (`S3FileHandler.fileExistsOrThrow`): only S3's 404 reads as free, and any other failure to check refuses the upload rather than risk writing over a file. When S3 timed out, couldn't be reached or answered with a 5xx (a throttle, an outage), that's a 503 with `Retry-After` (`SharedFileCheckFailedException`); S3 refusing the request (a 4xx) or a bug here is a 500. Writes to the metadata file take a lock per group, so uploads that land together keep every name. | | Presence | Memory only | Lost on restart; rebuilt as clients rejoin. | @@ -158,11 +162,22 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) - **Every new message rewrites the whole file**, read then write, with no lock. - **A shared file's bytes never go over the socket.** `sendFileServer` names the file and its size; a member downloads it from `/files/content`. Sending the bytes to every subscriber could overflow a session's 512 KB send buffer while another frame was queued, and Spring closes a session that overflows. +## Reactions + +People react to a message in a group chat or a direct message with one of six emoji. Spring stores the key, never the emoji: `like` 👍, `love` ❤️, `haha` 😂, `wow` 😮, `sad` 😢, `celebrate` 🎉. The list is `Reaction` in `mvc/reactions`, and Pages' Messages `reactions.js` lists the same keys in the same order, so change both together. + +- A person can leave several reactions on one message, one of each. PUT adds yours and DELETE removes it. Both answer `{messageId, reactions}`, where `reactions` is `[{reaction, people: [{uid, name}]}]` in the list's order, with people sorted by name. +- Group chats use the three routes in the table above. A reaction never reads or writes the group's S3 file: checking that the message exists would mean downloading the whole file, images and all, on every click. So the `messageId` only has to be a UUID, and a reaction on a message that doesn't exist is never shown. Deleting a message removes its reactions. +- Direct messages have the same three routes under `/api/dm/conversations/{id}`: `GET .../reactions`, and `PUT` or `DELETE .../messages/{messageId}/reactions/{reaction}`. Only the conversation's participants may use them (403 otherwise). A message from another conversation is 404, and a deleted one is 409. The change goes out on `/topic/dm/{id}` as `type: "reactions"`, with `id`, `conversationId` and `reactions`. +- A reaction is not a message. It sends no push notification, changes no unread count, and doesn't show up in search. +- `GroupChatEvent` and `DirectMessageEvent` carry `reactions` only on reaction frames (`@JsonInclude(NON_NULL)`), so every other frame is unchanged. The course chats ignore `reactionsServer`. + ## Testing - `api/groups.http`: open it in VS Code with the REST Client extension and run the requests in order. Set `baseUrl`, `adminUid` and `adminPassword` under `rest-client.environmentVariables` in the Git-ignored `.vscode/settings.json`. Never put passwords in the file. It creates a test group, adds you, sends and reads messages, checks unread counts, and deletes the group. - **The WebSocket can't be tested from a `.http` file.** To check it, open a course page with a chat against a local server and watch the browser's Network panel (WS filter) for frames on `/topic/group/{id}`. Or connect any STOMP client to `ws://localhost:8589/ws-chat/websocket` (SockJS's raw WebSocket transport), send `CONNECT`, `SUBSCRIBE` to `/topic/group/{id}`, and `SEND` JSON events to `/app/groups.chat`. A `SUBSCRIBE` to `/topic/dm/{id}` only goes through when the handshake carries a participant's `jwt_java_spring` cookie (a `Cookie` header) and an `Origin` header from the REST API's CORS list, such as `http://localhost:4500`. Without them, or for a wildcard subscription, a `/user/...` destination or a `SEND` to `/topic/dm/...`, the frame is dropped and the server logs a "refused" warning. Run the socket's own tests with `./mvnw test '-Dtest=DirectMessageTopic*Test,ChatSocketIdentityInterceptorTest,WebSocketBrokerConfigTest'`. - Run the chat regression tests with `./mvnw test '-Dtest=GroupChat*Test'`. They cover UID-based ownership, REST identity forwarding and unread counts. `GroupChatFilesTest` covers the file index, one-file downloads, the path rules, the bytes-free frame, uploads that land together, a path that is already shared, two uploads of one path at once, and a check that fails; `S3FileHandlerExistsTest` covers the strict check. +- Reactions: `./mvnw test '-Dtest=GroupChatReactionTest,DirectMessageReactionTest,MessageReaction*Test,ReactionTest'`. They cover both chats' frames and status codes, that a group reaction never touches S3 and a DM reaction never sends a push, the summaries' order, and the table's primary key on SQLite. ## Known issues @@ -180,5 +195,6 @@ These were each reproduced against a local server built from `master` on 2026-10 - Keep routes, event `context` names and JSON field names stable: the course site's chat pages depend on them. Change them together with the Pages client. - New tables need a `CREATE TABLE IF NOT EXISTS` that runs at startup, because Hibernate runs with `ddl-auto=none`. +- Reaction keys change in `Reaction` and in Pages' Messages `reactions.js` together. - Anything that needs to know who is sending must work over both REST and the WebSocket, or send through REST. - Update this guide and `api/groups.http` when routes, events or storage change. `README.md` and `AGENTS.md` link here. From 9a3bf22ba93a64a637c6a338d779d0a1bb38871c Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Sun, 22 Nov 2026 00:30:20 -0800 Subject: [PATCH 08/46] Group chat docs: a send reads its messages strictly The send route and the storage notes now say a send reads the messages file with decodeFileOrThrow: S3 being unavailable answers 503 with Retry-After and nothing is saved or broadcast, S3 refusing the read or a bug gets the route's usual 400, and edits and deletes still read with decodeFile. The testing list gets a bullet for GroupChatSendTest and S3FileHandlerDecodeTest, with the command that runs the S3 handler tests. --- docs/group-chat-architecture.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/group-chat-architecture.md b/docs/group-chat-architecture.md index 23be2235..2ed3e467 100644 --- a/docs/group-chat-architecture.md +++ b/docs/group-chat-architecture.md @@ -132,7 +132,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) | Method | Route | Operation | Who | |---|---|---|---| | GET | `/api/groups/chat/{groupId}/messages` | The group's messages | Any signed-in account | -| POST | `/api/groups/chat/{groupId}/messages` | Send `{message, image}`; broadcasts it and returns the history | Any signed-in account. The sender is the signed-in account. | +| POST | `/api/groups/chat/{groupId}/messages` | Send `{message, image}`; broadcasts it and returns the history. 503 with `Retry-After` when S3 can't read the group's messages for now, and then nothing is saved or broadcast | Any signed-in account. The sender is the signed-in account. | | PATCH | `/api/groups/chat/{groupId}/messages/{messageId}` | Edit a message | Only its sender (403 otherwise) | | DELETE | `/api/groups/chat/{groupId}/messages/{messageId}` | Delete a message | Only its sender (403 otherwise) | | GET | `/api/groups/chat/unread` | `{total, unreadByGroup}` across your groups | You | @@ -155,7 +155,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) - **History is keyed by group name, not id.** Renaming a group with `PUT /api/groups/{id}` leaves its history under the old name. - **Without S3 settings** (AWS credentials, region and bucket), the server logs `S3 is disabled` at startup. Sends still broadcast live, but nothing is saved, so history and files come back empty. This is the normal state of a local server. -- **Every new message rewrites the whole file**, read then write. Sending, editing and deleting take one lock per group (`messageLocks` in `GroupChatService`), so two at once keep both changes. The lock only holds within one server: several servers writing the same bucket would need S3's conditional writes. +- **Every new message rewrites the whole file**, read then write. Sending, editing and deleting take one lock per group (`messageLocks` in `GroupChatService`), so two at once keep both changes. The lock only holds within one server: several servers writing the same bucket would need S3's conditional writes. A send reads the file strictly (`S3FileHandler.decodeFileOrThrow`), since writing back an empty read would replace the whole history: only S3's 404 reads as no messages yet, and any other failure to read refuses the send. When S3 timed out, couldn't be reached or answered with a 5xx, that's a 503 with `Retry-After` (`MessagesReadFailedException`); S3 refusing the read (a 4xx) or a bug here gets the route's usual 400. Edits and deletes still read with `decodeFile`, which answers a failed read the same as a missing file, so after one they find nothing to change and write nothing. - **A shared file's bytes never go over the socket.** `sendFileServer` names the file and its size; a member downloads it from `/files/content`. Sending the bytes to every subscriber could overflow a session's 512 KB send buffer while another frame was queued, and Spring closes a session that overflows. ## Testing @@ -164,6 +164,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) - **The WebSocket can't be tested from a `.http` file.** To check it, open a course page with a chat against a local server and watch the browser's Network panel (WS filter) for frames on `/topic/group/{id}`. Or connect any STOMP client to `ws://localhost:8589/ws-chat/websocket` (SockJS's raw WebSocket transport), send `CONNECT`, `SUBSCRIBE` to `/topic/group/{id}`, and `SEND` JSON events to `/app/groups.chat`. A `SUBSCRIBE` to `/topic/dm/{id}` only goes through when the handshake carries a participant's `jwt_java_spring` cookie (a `Cookie` header) and an `Origin` header from the REST API's CORS list, such as `http://localhost:4500`. Without them, or for a wildcard subscription, a `/user/...` destination or a `SEND` to `/topic/dm/...`, the frame is dropped and the server logs a "refused" warning. Run the socket's own tests with `./mvnw test '-Dtest=DirectMessageTopic*Test,ChatSocketIdentityInterceptorTest,WebSocketBrokerConfigTest'`. - Run the chat regression tests with `./mvnw test '-Dtest=GroupChat*Test'`. They cover UID-based ownership, REST identity forwarding and unread counts. `GroupChatFilesTest` covers the file index, one-file downloads, the path rules, the bytes-free frame, uploads that land together, a path that is already shared, two uploads of one path at once, and a check that fails; `S3FileHandlerExistsTest` covers the strict check. - `GroupChatServiceTest` covers two sends, an edit and a send, and a delete and a send landing at once. +- `GroupChatSendTest` sends through the controller to a real `S3FileHandler` over a stand-in S3 client: a read that fails, a read S3 refuses, a bug, a group with no messages file yet, and a server without S3. `S3FileHandlerDecodeTest` covers the strict read. Run the S3 handler tests with `./mvnw test '-Dtest=S3FileHandler*Test'`. ## Known issues From af1dba22dec69a108b29bbca6215629d6eba0378 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Sat, 21 Nov 2026 23:01:17 -0800 Subject: [PATCH 09/46] Group chat docs: message writes take a lock per group The storage notes said every send rewrites the file with no lock, and Known issues listed two sends at once losing one. The note now says sending, editing and deleting take one lock per group, within one server only. The testing list names GroupChatServiceTest, and the known issue is gone. --- docs/group-chat-architecture.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/group-chat-architecture.md b/docs/group-chat-architecture.md index 1d0dc01c..23be2235 100644 --- a/docs/group-chat-architecture.md +++ b/docs/group-chat-architecture.md @@ -155,7 +155,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) - **History is keyed by group name, not id.** Renaming a group with `PUT /api/groups/{id}` leaves its history under the old name. - **Without S3 settings** (AWS credentials, region and bucket), the server logs `S3 is disabled` at startup. Sends still broadcast live, but nothing is saved, so history and files come back empty. This is the normal state of a local server. -- **Every new message rewrites the whole file**, read then write, with no lock. +- **Every new message rewrites the whole file**, read then write. Sending, editing and deleting take one lock per group (`messageLocks` in `GroupChatService`), so two at once keep both changes. The lock only holds within one server: several servers writing the same bucket would need S3's conditional writes. - **A shared file's bytes never go over the socket.** `sendFileServer` names the file and its size; a member downloads it from `/files/content`. Sending the bytes to every subscriber could overflow a session's 512 KB send buffer while another frame was queued, and Spring closes a session that overflows. ## Testing @@ -163,6 +163,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) - `api/groups.http`: open it in VS Code with the REST Client extension and run the requests in order. Set `baseUrl`, `adminUid` and `adminPassword` under `rest-client.environmentVariables` in the Git-ignored `.vscode/settings.json`. Never put passwords in the file. It creates a test group, adds you, sends and reads messages, checks unread counts, and deletes the group. - **The WebSocket can't be tested from a `.http` file.** To check it, open a course page with a chat against a local server and watch the browser's Network panel (WS filter) for frames on `/topic/group/{id}`. Or connect any STOMP client to `ws://localhost:8589/ws-chat/websocket` (SockJS's raw WebSocket transport), send `CONNECT`, `SUBSCRIBE` to `/topic/group/{id}`, and `SEND` JSON events to `/app/groups.chat`. A `SUBSCRIBE` to `/topic/dm/{id}` only goes through when the handshake carries a participant's `jwt_java_spring` cookie (a `Cookie` header) and an `Origin` header from the REST API's CORS list, such as `http://localhost:4500`. Without them, or for a wildcard subscription, a `/user/...` destination or a `SEND` to `/topic/dm/...`, the frame is dropped and the server logs a "refused" warning. Run the socket's own tests with `./mvnw test '-Dtest=DirectMessageTopic*Test,ChatSocketIdentityInterceptorTest,WebSocketBrokerConfigTest'`. - Run the chat regression tests with `./mvnw test '-Dtest=GroupChat*Test'`. They cover UID-based ownership, REST identity forwarding and unread counts. `GroupChatFilesTest` covers the file index, one-file downloads, the path rules, the bytes-free frame, uploads that land together, a path that is already shared, two uploads of one path at once, and a check that fails; `S3FileHandlerExistsTest` covers the strict check. +- `GroupChatServiceTest` covers two sends, an edit and a send, and a delete and a send landing at once. ## Known issues @@ -173,7 +174,6 @@ These were each reproduced against a local server built from `master` on 2026-10 - **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. - **Edit and delete require the stored author uid.** The REST controller passes the authenticated account's uid through the realtime service; display names never establish ownership. Legacy messages without `author_uid` cannot be edited or deleted through these routes. Teachers cannot delete another account's message. -- **Two sends at once can lose one.** Each send reads the group's S3 file, adds a line and writes the file back, without a lock. - **The first group created after a restart fails on SQLite.** `POST /api/groups` returns 500 with `SQLITE_BUSY_SNAPSHOT` the first time after the server starts; the next attempt works. This is the `GenerationType.AUTO` lock problem described under Assignment grading in `AGENTS.md`, here on `submitter_seq`. Not checked on MySQL. ## Change checklist From fd1a44e4771dbb3b1661d249aa9dbbd6e4400d43 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Thu, 19 Nov 2026 10:42:16 -0800 Subject: [PATCH 10/46] 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 457eb003eceb261b9467665e16a0df6cb50288fb Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Sun, 22 Nov 2026 23:16:14 -0800 Subject: [PATCH 11/46] Push: a DM's notification shows its words, not the page's markers or HTML MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The push text was the stored body with its whitespace collapsed, so a phone showed what the page reads: [[reply:…]], [[files:…]], [[code:…]] and [[pin:…]] markers, and the rich composer's HTML (,  ). Now the markers are left out, the HTML becomes the text a reader sees, and a message that was only a marker says what it did ("pinned a message", "sent code", "shared files"). A marker's payload can't hold a bracket, so a body full of unclosed "[[" is still matched in linear time. notifyPerson runs inside the message's transaction and never throws, so if the text can't be made from a body, the notification goes out without text and the DM is still sent. --- .../mvc/push/PushNotificationService.java | 66 +++++++++++++++++-- .../mvc/push/PushNotificationSnippetTest.java | 64 ++++++++++++++++++ 2 files changed, 126 insertions(+), 4 deletions(-) create mode 100644 src/test/java/com/open/spring/mvc/push/PushNotificationSnippetTest.java diff --git a/src/main/java/com/open/spring/mvc/push/PushNotificationService.java b/src/main/java/com/open/spring/mvc/push/PushNotificationService.java index 08f63862..1ba9a0c3 100644 --- a/src/main/java/com/open/spring/mvc/push/PushNotificationService.java +++ b/src/main/java/com/open/spring/mvc/push/PushNotificationService.java @@ -4,14 +4,19 @@ import java.security.Security; import java.time.Duration; import java.time.Instant; +import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.function.Predicate; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import org.apache.http.HttpResponse; import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.jsoup.Jsoup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; @@ -49,6 +54,13 @@ public class PushNotificationService { private static final Logger log = LoggerFactory.getLogger(PushNotificationService.class); private static final int TTL_SECONDS = 60 * 60 * 24; // keep undelivered pushes for a day private static final int MAX_BODY_CHARS = 140; + // The markers Messages puts in a body for the page to read: a reply's quote, shared files, + // a code block, a pin, and the course chats' events and lessons. A phone shouldn't show them. + // Pages lists the same names in ANY_MARKER_PATTERN (assets/js/chat/chat-reply.js), so a + // marker added there needs adding here too, or its raw text shows up in DM notifications. + // No marker Pages writes has a bracket inside it (it escapes or URL-encodes them), so the + // payload leaves out "[" as well: that keeps matching linear when a body is full of "[[". + private static final Pattern CHAT_MARKER = Pattern.compile("\\[\\[(reply|event|lesson|files|code|pin|unpin):[^\\[\\]]*\\]\\]"); /** How long an unchanged subscription goes before a re-send refreshes last_used_at. */ private static final Duration RESEEN_AFTER = Duration.ofDays(1); @@ -174,7 +186,7 @@ public void notifyPerson(Person person, String title, String body, String url, S } Map payload = Map.of( "title", title == null ? "New message" : title, - "body", snippet(body), + "body", pushText(body), "url", url == null ? "/dm" : url, "tag", tag == null ? "ocs" : tag); Long personId = person.getId(); @@ -191,6 +203,17 @@ public void afterCommit() { } } + // notifyPerson never throws, and it runs inside the message's transaction, so a body the + // text can't be made from still sends the message and its notification, without text. + private static String pushText(String body) { + try { + return snippet(body); + } catch (RuntimeException ex) { + log.warn("Web push: could not make the notification's text ({})", ex.getMessage()); + return ""; + } + } + /** Runs on the sender thread: loads the person's subscriptions and pushes to each. */ private void sendToPerson(Long personId, Map payload) { List subscriptions; @@ -236,12 +259,47 @@ private void send(PushSubscriptionEntity subscription, String json) { } } + /** + * The notification's text: the message as a reader sees it in the chat, cut to + * {@value #MAX_BODY_CHARS} characters. The chat's markers are left out, and the rich + * composer's HTML becomes plain text (tags gone, entities decoded, {@code  } a space). + * If no words are left, the text says what the message did instead, such as "pinned a + * message", or just "sent a message". + */ static String snippet(String body) { - if (body == null) { + if (body == null || body.isBlank()) { return ""; } - String oneLine = body.replaceAll("\\s+", " ").trim(); - return oneLine.length() <= MAX_BODY_CHARS ? oneLine : oneLine.substring(0, MAX_BODY_CHARS - 1) + "…"; + Set markers = new HashSet<>(); + Matcher marker = CHAT_MARKER.matcher(body); + StringBuilder words = new StringBuilder(); + while (marker.find()) { + markers.add(marker.group(1)); + marker.appendReplacement(words, " "); + } + marker.appendTail(words); + String text = Jsoup.parse(words.toString()).text().replace('\u00A0', ' ').replaceAll("\\s+", " ").trim(); + if (text.isEmpty()) { + text = onlyMarkers(markers); + } + return text.length() <= MAX_BODY_CHARS ? text : text.substring(0, MAX_BODY_CHARS - 1) + "…"; + } + + // What a message that was only markers did, said after the sender's name (the title). + private static String onlyMarkers(Set markers) { + if (markers.contains("pin")) { + return "pinned a message"; + } + if (markers.contains("unpin")) { + return "unpinned a message"; + } + if (markers.contains("code")) { + return "sent code"; + } + if (markers.contains("files")) { + return "shared files"; + } + return "sent a message"; } @PreDestroy diff --git a/src/test/java/com/open/spring/mvc/push/PushNotificationSnippetTest.java b/src/test/java/com/open/spring/mvc/push/PushNotificationSnippetTest.java new file mode 100644 index 00000000..6b45dca8 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/push/PushNotificationSnippetTest.java @@ -0,0 +1,64 @@ +package com.open.spring.mvc.push; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; + +import java.time.Duration; + +import org.junit.jupiter.api.Test; + +/** + * The text a phone shows for a direct message: the words a reader sees in the chat, without + * the markers the page reads ([[reply:…]], [[files:…]], [[code:…]], [[pin:…]]) or the rich + * composer's HTML. + */ +class PushNotificationSnippetTest { + + @Test + void chatMarkersAreLeftOut() { + assertEquals("thanks!", PushNotificationService.snippet("[[reply:9|Bob|hey%20there]] thanks!")); + assertEquals("look", PushNotificationService.snippet("[[files:f~shots%2Fa.png~5]] look")); + // Pages escapes brackets, "|", "%", "<", ">" and "&" in code, but keeps quotes, tabs and newlines. + assertEquals("try this", PushNotificationService.snippet( + "[[code:python|print(\"hi\")\nfor i in range(3):\n\tprint(i)]] try this")); + assertEquals("see this", PushNotificationService.snippet( + "[[reply:9|Bob|hey]] [[files:f~a.txt~1]] [[code:java|int x;]] see this")); + } + + @Test + void aMessageThatIsOnlyAMarkerSaysWhatItDid() { + assertEquals("pinned a message", PushNotificationService.snippet("[[pin:401]]")); + assertEquals("unpinned a message", PushNotificationService.snippet("[[unpin:401]]")); + assertEquals("sent code", PushNotificationService.snippet("[[code:python|print(1)]]")); + assertEquals("shared files", PushNotificationService.snippet("[[files:f~a.png~5]]")); + // A reply that only attaches an image has nothing but its reply marker in the body. + assertEquals("sent a message", PushNotificationService.snippet("[[reply:9|Bob|hey]]")); + } + + @Test + void theComposersHtmlBecomesPlainText() { + assertEquals("check https://github.com/o/r/pull/3", PushNotificationService.snippet( + "check " + + "https://github.com/o/r/pull/3 ")); + assertEquals("Fish & chips tonight", PushNotificationService.snippet("Fish & chips
tonight")); + assertEquals("a < b", PushNotificationService.snippet("a < b")); + } + + @Test + void longTextIsCutAndBlankStaysBlank() { + String cut = PushNotificationService.snippet("x".repeat(200)); + assertEquals(140, cut.length()); + assertEquals('…', cut.charAt(139)); + assertEquals("", PushNotificationService.snippet(null)); + assertEquals("", PushNotificationService.snippet(" ")); + } + + @Test + void markerOpeningsThatNeverCloseStayFast() { + // None of these markers closes, so a pattern that rescans the rest of the body at each + // "[[" takes seconds here; matching has to stay linear. + String body = "[[code:".repeat(20_000); + String text = assertTimeoutPreemptively(Duration.ofSeconds(1), () -> PushNotificationService.snippet(body)); + assertEquals(140, text.length()); + } +} From 1b7fb8da5cc1f53fa9f9d8937c80c5d0db58c9a1 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Wed, 25 Nov 2026 19:03:10 -0800 Subject: [PATCH 12/46] Reactions: say who may make the six reaction requests PermissionsPolicyTest checks permissions.json against every request the controllers answer. The reaction routes for direct messages and group chats go with the other /api/dm and /api/groups/chat requests: any signed-in admin, student, teacher or user, as the filter chain answers today. --- src/main/resources/data/permissions.json | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/main/resources/data/permissions.json b/src/main/resources/data/permissions.json index 579ed3f9..607f05ef 100644 --- a/src/main/resources/data/permissions.json +++ b/src/main/resources/data/permissions.json @@ -476,6 +476,9 @@ "POST /api/dm/conversations/{id}/messages", "DELETE /api/dm/conversations/{id}/messages/{messageId}", "PATCH /api/dm/conversations/{id}/messages/{messageId}", + "DELETE /api/dm/conversations/{id}/messages/{messageId}/reactions/{reaction}", + "PUT /api/dm/conversations/{id}/messages/{messageId}/reactions/{reaction}", + "GET /api/dm/conversations/{id}/reactions", "POST /api/dm/conversations/{id}/read", "GET /api/dm/search", "GET /api/dm/unread", @@ -531,6 +534,9 @@ "POST /api/groups/chat/{groupId}/messages", "DELETE /api/groups/chat/{groupId}/messages/{messageId}", "PATCH /api/groups/chat/{groupId}/messages/{messageId}", + "DELETE /api/groups/chat/{groupId}/messages/{messageId}/reactions/{reaction}", + "PUT /api/groups/chat/{groupId}/messages/{messageId}/reactions/{reaction}", + "GET /api/groups/chat/{groupId}/reactions", "POST /api/groups/chat/{groupId}/read", "PUT /api/groups/class-memberships", "GET /api/groups/person/{personId}", From 4b746342c3607da907d953bd5d9b9472c260a0c3 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Mon, 23 Nov 2026 02:27:21 -0800 Subject: [PATCH 13/46] Chat socket: drop client SENDs to every /topic destination DirectMessageTopicGuard already dropped a client's SEND to a DM topic. It now drops a client's SEND to any destination the simple broker handles (WebSocketBrokerConfig.BROKER_PREFIX, "/topic"), so group chat topics get the same rule. Only the server publishes to topics: pages send group messages over REST, and Spring's group page sends to /app/groups.chat. The tests cover SENDs to DM, group and other topic destinations being dropped, and the server's own group broadcast still reaching its subscribers. --- AGENTS.md | 1 + docs/group-chat-architecture.md | 2 +- .../DirectMessageTopicGuard.java | 10 ++++--- .../mvc/groups/WebSocketBrokerConfig.java | 7 +++-- .../DirectMessageTopicBrokerTest.java | 29 +++++++++++++++++++ .../DirectMessageTopicGuardTest.java | 10 ++++--- 6 files changed, 48 insertions(+), 11 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 9e7bb279..4818603d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -38,6 +38,7 @@ Entity-removal helpers (run before any large cleanup): - Realtime chat uses STOMP over a **second connector on port 8589**: broker config in `WebSocketBrokerConfig.java` (`/ws-chat`, `/app`, `/topic`), port gating in `ChatWebSocketPortFilter.java`, presence in `GroupChatPresenceService.java`. The native `/websocket` endpoint in `mvc/mortevision/nativesocket/WebSocketConfig.java` is separate. - Gotcha: Java package is `mvc.groups` (plural) but templates live in `templates/group/` (singular); static JS exists both as legacy files in `static/js/group-*.js` and packaged versions in `static/js/group/*.js` — prefer the latter. - [docs/group-chat-architecture.md](docs/group-chat-architecture.md) covers every groups and chat route, the WebSocket event contexts, S3 message storage (keyed by group name, not id) and the known issues. Over the WebSocket there is no Spring Security context, so a service that needs the signed-in account (like `GroupChatIdentityService`) only works from REST. The socket does read the `jwt_java_spring` cookie when it opens (`ChatSocketIdentityInterceptor`, same checks as `JwtRequestFilter`, and only when the request's `Origin` is in the REST CORS list, since a cross-site GET carries the cookie but no Origin), but only for `DirectMessageTopicGuard`: only a conversation's participants can subscribe to `/topic/dm/{id}`, and wildcard subscriptions, `/user/...` destinations and client SENDs to DM topics are dropped. It sets no Principal, on purpose, so `GroupChatWebSocketController` still ignores events. HTTP: `api/groups.http`. +- A client's SEND to any `/topic/...` destination is dropped too, group topics included, because the simple broker relays it to every subscriber. Only the server publishes there (the prefix is `WebSocketBrokerConfig.BROKER_PREFIX`). ## Assignment grading diff --git a/docs/group-chat-architecture.md b/docs/group-chat-architecture.md index 1d0dc01c..3d8840bc 100644 --- a/docs/group-chat-architecture.md +++ b/docs/group-chat-architecture.md @@ -161,7 +161,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) ## Testing - `api/groups.http`: open it in VS Code with the REST Client extension and run the requests in order. Set `baseUrl`, `adminUid` and `adminPassword` under `rest-client.environmentVariables` in the Git-ignored `.vscode/settings.json`. Never put passwords in the file. It creates a test group, adds you, sends and reads messages, checks unread counts, and deletes the group. -- **The WebSocket can't be tested from a `.http` file.** To check it, open a course page with a chat against a local server and watch the browser's Network panel (WS filter) for frames on `/topic/group/{id}`. Or connect any STOMP client to `ws://localhost:8589/ws-chat/websocket` (SockJS's raw WebSocket transport), send `CONNECT`, `SUBSCRIBE` to `/topic/group/{id}`, and `SEND` JSON events to `/app/groups.chat`. A `SUBSCRIBE` to `/topic/dm/{id}` only goes through when the handshake carries a participant's `jwt_java_spring` cookie (a `Cookie` header) and an `Origin` header from the REST API's CORS list, such as `http://localhost:4500`. Without them, or for a wildcard subscription, a `/user/...` destination or a `SEND` to `/topic/dm/...`, the frame is dropped and the server logs a "refused" warning. Run the socket's own tests with `./mvnw test '-Dtest=DirectMessageTopic*Test,ChatSocketIdentityInterceptorTest,WebSocketBrokerConfigTest'`. +- **The WebSocket can't be tested from a `.http` file.** To check it, open a course page with a chat against a local server and watch the browser's Network panel (WS filter) for frames on `/topic/group/{id}`. Or connect any STOMP client to `ws://localhost:8589/ws-chat/websocket` (SockJS's raw WebSocket transport), send `CONNECT`, `SUBSCRIBE` to `/topic/group/{id}`, and `SEND` JSON events to `/app/groups.chat`. A `SUBSCRIBE` to `/topic/dm/{id}` only goes through when the handshake carries a participant's `jwt_java_spring` cookie (a `Cookie` header) and an `Origin` header from the REST API's CORS list, such as `http://localhost:4500`. Without them, or for a wildcard subscription, a `/user/...` destination or a `SEND` to any `/topic/...` destination, the frame is dropped and the server logs a "refused" warning. Only the server publishes to topics; clients send through REST or `/app/groups.chat`. Run the socket's own tests with `./mvnw test '-Dtest=DirectMessageTopic*Test,ChatSocketIdentityInterceptorTest,WebSocketBrokerConfigTest'`. - Run the chat regression tests with `./mvnw test '-Dtest=GroupChat*Test'`. They cover UID-based ownership, REST identity forwarding and unread counts. `GroupChatFilesTest` covers the file index, one-file downloads, the path rules, the bytes-free frame, uploads that land together, a path that is already shared, two uploads of one path at once, and a check that fails; `S3FileHandlerExistsTest` covers the strict check. ## Known issues diff --git a/src/main/java/com/open/spring/mvc/directmessages/DirectMessageTopicGuard.java b/src/main/java/com/open/spring/mvc/directmessages/DirectMessageTopicGuard.java index ac52e689..88776100 100644 --- a/src/main/java/com/open/spring/mvc/directmessages/DirectMessageTopicGuard.java +++ b/src/main/java/com/open/spring/mvc/directmessages/DirectMessageTopicGuard.java @@ -13,6 +13,7 @@ import org.springframework.util.PathMatcher; import com.open.spring.mvc.groups.ChatSocketIdentityInterceptor; +import com.open.spring.mvc.groups.WebSocketBrokerConfig; import lombok.extern.slf4j.Slf4j; @@ -26,8 +27,9 @@ *
  • No wildcard SUBSCRIBE on any topic. The broker matches {@code *}, {@code **}, {@code ?} * and {@code {name}} as patterns, so {@code /topic/**} would get every DM with no id at all. * No client uses one.
  • - *
  • No client SEND to a DM topic. The broker relays a client's SEND to every subscriber, so it - * would show up in someone's thread as a real message. Only the server posts there.
  • + *
  • No client SEND to any topic, DM or group ({@code /topic...}). The broker relays a client's + * SEND to every subscriber, so it would show up in someone's chat as a real message. Only the + * server posts there; pages send through REST or {@code /app/groups.chat}.
  • *
  • No SUBSCRIBE or SEND to a user destination ({@code /user/...}). Nothing on this socket uses * them, and Spring rewrites a {@code /user/X} subscription to X plus "-user" plus the session id * after this check. A SockJS client picks its own session id, so the two halves together can make @@ -102,8 +104,8 @@ private String whySubscribeIsRefused(String destination, Map ses /** Why a client's SEND is refused, or null to let it through. */ private static String whySendIsRefused(String destination) { - if (isDirectMessageTopic(destination)) { - return "only the server sends to direct message topics"; + if (destination != null && destination.startsWith(WebSocketBrokerConfig.BROKER_PREFIX)) { + return "only the server sends to topics"; } if (isUserDestination(destination)) { return NO_USER_DESTINATIONS; diff --git a/src/main/java/com/open/spring/mvc/groups/WebSocketBrokerConfig.java b/src/main/java/com/open/spring/mvc/groups/WebSocketBrokerConfig.java index 84ab9f48..590f56a5 100644 --- a/src/main/java/com/open/spring/mvc/groups/WebSocketBrokerConfig.java +++ b/src/main/java/com/open/spring/mvc/groups/WebSocketBrokerConfig.java @@ -20,12 +20,15 @@ *

    * When a socket opens, {@link ChatSocketIdentityInterceptor} reads the login cookie. Every frame a * client sends then passes {@link DirectMessageTopicGuard}, which lets only a conversation's - * participants subscribe to its /topic/dm/{id}. + * participants subscribe to its /topic/dm/{id} and keeps clients from sending to any topic. */ @Configuration @EnableWebSocketMessageBroker public class WebSocketBrokerConfig implements WebSocketMessageBrokerConfigurer { + /** The simple broker handles every destination that starts with this, so only the server may send there. */ + public static final String BROKER_PREFIX = "/topic"; + private final ChatSocketIdentityInterceptor identityInterceptor; private final DirectMessageTopicGuard directMessageTopicGuard; @@ -53,7 +56,7 @@ public void configureClientInboundChannel(ChannelRegistration registration) { @Override public void configureMessageBroker(MessageBrokerRegistry registry) { - registry.enableSimpleBroker("/topic"); + registry.enableSimpleBroker(BROKER_PREFIX); registry.setApplicationDestinationPrefixes("/app"); } } diff --git a/src/test/java/com/open/spring/mvc/directmessages/DirectMessageTopicBrokerTest.java b/src/test/java/com/open/spring/mvc/directmessages/DirectMessageTopicBrokerTest.java index d2f192fc..3d3e00ae 100644 --- a/src/test/java/com/open/spring/mvc/directmessages/DirectMessageTopicBrokerTest.java +++ b/src/test/java/com/open/spring/mvc/directmessages/DirectMessageTopicBrokerTest.java @@ -65,6 +65,35 @@ void tearDown() { broker.stop(); } + /** A group chat reader, signed out like a course chat visitor, must not get a frame a client made up. */ + @Test + void aClientSendToAGroupTopicReachesNobody() { + connect("reader-socket"); + connect("outsider-socket"); + subscribe("reader-socket", null, "/topic/group/7"); + + StompHeaderAccessor send = StompHeaderAccessor.create(StompCommand.SEND); + send.setSessionId("outsider-socket"); + send.setSessionAttributes(Map.of()); + send.setDestination("/topic/group/7"); + clientInbound.send(MessageBuilder.createMessage( + "{\"context\":\"sendMessageServer\",\"groupId\":7,\"sender\":\"Thomas Edison\",\"message\":\"FAKE: click this link\"}" + .getBytes(StandardCharsets.UTF_8), + send.getMessageHeaders())); + + assertEquals(List.of(), socketsThatReceivedSomething()); + } + + @Test + void theServersGroupBroadcastStillReachesSignedOutReaders() { + connect("reader-socket"); + subscribe("reader-socket", null, "/topic/group/7"); + + serverBroadcast("/topic/group/7", "{\"context\":\"sendMessageServer\",\"message\":\"hello class\"}"); + + assertEquals(List.of("reader-socket"), socketsThatReceivedSomething()); + } + /** * Spring turns SUBSCRIBE /user/X into a subscription to X + "-user" + the session id, which a * SockJS client picks itself. Session id "}" closes the brace this destination opens, so the diff --git a/src/test/java/com/open/spring/mvc/directmessages/DirectMessageTopicGuardTest.java b/src/test/java/com/open/spring/mvc/directmessages/DirectMessageTopicGuardTest.java index e2fd0814..834b7d24 100644 --- a/src/test/java/com/open/spring/mvc/directmessages/DirectMessageTopicGuardTest.java +++ b/src/test/java/com/open/spring/mvc/directmessages/DirectMessageTopicGuardTest.java @@ -91,10 +91,12 @@ void userDestinationsAreRefused() { assertNull(guard.preSend(frame(StompCommand.SEND, "/user/hop/queue/messages", SIGNED_OUT), channel)); } - @Test - void clientCannotSendToADmTopic() { - assertNull(guard.preSend(frame(StompCommand.SEND, "/topic/dm/1", HOP), channel)); - assertNull(guard.preSend(frame(StompCommand.SEND, "/topic/dm/1", SIGNED_OUT), channel)); + /** The broker relays a client's SEND to every subscriber of any destination starting with /topic. */ + @ParameterizedTest + @ValueSource(strings = {"/topic/dm/1", "/topic/group/7", "/topic/anything", "/topicx"}) + void clientCannotSendToAnyTopic(String destination) { + assertNull(guard.preSend(frame(StompCommand.SEND, destination, HOP), channel)); + assertNull(guard.preSend(frame(StompCommand.SEND, destination, SIGNED_OUT), channel)); } @Test From c1a3ab3c5782c14e0314722bef8bb0fae3d79e9a Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Thu, 19 Nov 2026 10:51:58 -0800 Subject: [PATCH 14/46] 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 15/46] 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 16/46] 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 5e000006b0411cd629b98c40c004516b771862a0 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Wed, 25 Nov 2026 19:34:46 -0800 Subject: [PATCH 17/46] Reactions: one-statement deletes, reactor names in one query, lowercase group ids A remove read the row and then deleted it, so a second remove at the same moment could fail. Removing one reaction and clearing a deleted message's reactions are now single delete statements. The names of the people who reacted come from one query for id, uid and name, instead of whole Person rows that also loaded each person's eager links. A group message id has to be a lowercase UUID, like the ids Spring saves, so an uppercase copy can't match some lookups and miss others on MySQL. --- docs/group-chat-architecture.md | 4 +- .../mvc/groups/GroupChatApiController.java | 7 +-- .../MessageReactionJpaRepository.java | 38 ++++++++++++++- .../mvc/reactions/MessageReactionService.java | 11 ++--- .../mvc/groups/GroupChatReactionTest.java | 2 + .../reactions/MessageReactionServiceTest.java | 47 ++++++++++++------- 6 files changed, 78 insertions(+), 31 deletions(-) diff --git a/docs/group-chat-architecture.md b/docs/group-chat-architecture.md index a961ee81..9e6be786 100644 --- a/docs/group-chat-architecture.md +++ b/docs/group-chat-architecture.md @@ -136,7 +136,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) | PATCH | `/api/groups/chat/{groupId}/messages/{messageId}` | Edit a message | Only its sender (403 otherwise) | | DELETE | `/api/groups/chat/{groupId}/messages/{messageId}` | Delete a message | Only its sender (403 otherwise) | | GET | `/api/groups/chat/{groupId}/reactions` | Every reaction in the chat, as `{messageId: [{reaction, people: [{uid, name}]}]}` | Any signed-in account | -| PUT | `/api/groups/chat/{groupId}/messages/{messageId}/reactions/{reaction}` | Add your reaction (`like`, `love`, `haha`, `wow`, `sad`, `celebrate`); answers `{messageId, reactions}` and broadcasts `reactionsServer`. 400 for any other key, or a `messageId` that isn't a UUID | Any signed-in account | +| PUT | `/api/groups/chat/{groupId}/messages/{messageId}/reactions/{reaction}` | Add your reaction (`like`, `love`, `haha`, `wow`, `sad`, `celebrate`); answers `{messageId, reactions}` and broadcasts `reactionsServer`. 400 for any other key, or a `messageId` that isn't a lowercase UUID | Any signed-in account | | DELETE | `/api/groups/chat/{groupId}/messages/{messageId}/reactions/{reaction}` | Remove your reaction; the same answer and broadcast, and 200 even when it wasn't there | Any signed-in account | | GET | `/api/groups/chat/unread` | `{total, unreadByGroup}` across your groups | You | | POST | `/api/groups/chat/{groupId}/read` | Mark a group read | You | @@ -167,7 +167,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) People react to a message in a group chat or a direct message with one of six emoji. Spring stores the key, never the emoji: `like` 👍, `love` ❤️, `haha` 😂, `wow` 😮, `sad` 😢, `celebrate` 🎉. The list is `Reaction` in `mvc/reactions`, and Pages' Messages `reactions.js` lists the same keys in the same order, so change both together. - A person can leave several reactions on one message, one of each. PUT adds yours and DELETE removes it. Both answer `{messageId, reactions}`, where `reactions` is `[{reaction, people: [{uid, name}]}]` in the list's order, with people sorted by name. -- Group chats use the three routes in the table above. A reaction never reads or writes the group's S3 file: checking that the message exists would mean downloading the whole file, images and all, on every click. So the `messageId` only has to be a UUID, and a reaction on a message that doesn't exist is never shown. Deleting a message removes its reactions. +- Group chats use the three routes in the table above. A reaction never reads or writes the group's S3 file: checking that the message exists would mean downloading the whole file, images and all, on every click. So the `messageId` only has to be a lowercase UUID, like the ids Spring saves, and a reaction on a message that doesn't exist is never shown. Deleting a message removes its reactions. - Direct messages have the same three routes under `/api/dm/conversations/{id}`: `GET .../reactions`, and `PUT` or `DELETE .../messages/{messageId}/reactions/{reaction}`. Only the conversation's participants may use them (403 otherwise). A message from another conversation is 404, and a deleted one is 409. The change goes out on `/topic/dm/{id}` as `type: "reactions"`, with `id`, `conversationId` and `reactions`. - A reaction is not a message. It sends no push notification, changes no unread count, and doesn't show up in search. - `GroupChatEvent` and `DirectMessageEvent` carry `reactions` only on reaction frames (`@JsonInclude(NON_NULL)`), so every other frame is unchanged. The course chats ignore `reactionsServer`. 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 c99381c1..5ef0f6fb 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java @@ -48,10 +48,11 @@ public class GroupChatApiController { // short outage clears in seconds. private static final int SHARE_RETRY_AFTER_SECONDS = 5; - // A saved group message's id is a UUID (GroupChatMessage). Reactions don't read the group's - // S3 file to check that the message exists, so the id at least has to look like one. + // A saved group message's id is a UUID (GroupChatMessage), written in lowercase. Reactions + // don't read the group's S3 file to check that the message exists, so the id at least has to + // look like one; an uppercase copy would match some lookups and not others on MySQL. static final Pattern MESSAGE_ID = - Pattern.compile("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"); + Pattern.compile("^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"); private final GroupChatService groupChatService; private final GroupChatRealtimeService realtimeService; diff --git a/src/main/java/com/open/spring/mvc/reactions/MessageReactionJpaRepository.java b/src/main/java/com/open/spring/mvc/reactions/MessageReactionJpaRepository.java index 0a8fb8c7..b920148d 100644 --- a/src/main/java/com/open/spring/mvc/reactions/MessageReactionJpaRepository.java +++ b/src/main/java/com/open/spring/mvc/reactions/MessageReactionJpaRepository.java @@ -1,8 +1,12 @@ package com.open.spring.mvc.reactions; +import java.util.Collection; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; /** Reactions, read by chat or by message. */ public interface MessageReactionJpaRepository extends JpaRepository { @@ -13,6 +17,36 @@ public interface MessageReactionJpaRepository extends JpaRepository findByKeyChatTypeAndKeyChatIdAndKeyMessageId(ChatType chatType, Long chatId, String messageId); - /** Removes every reaction on one message, as when the message is deleted. */ - void deleteByKeyChatTypeAndKeyChatIdAndKeyMessageId(ChatType chatType, Long chatId, String messageId); + /** + * Removes one person's reaction in one statement. Reading the row first and then deleting it + * let a second remove at the same moment fail; a statement that deletes 0 rows doesn't. + */ + @Modifying(flushAutomatically = true) + @Query("delete from MessageReaction r where r.key.chatType = :chatType and r.key.chatId = :chatId" + + " and r.key.messageId = :messageId and r.key.personId = :personId and r.key.reaction = :reaction") + int deleteOne(@Param("chatType") ChatType chatType, @Param("chatId") Long chatId, @Param("messageId") String messageId, + @Param("personId") Long personId, @Param("reaction") Reaction reaction); + + /** Removes every reaction on one message in one statement, as when the message is deleted. */ + @Modifying(flushAutomatically = true) + @Query("delete from MessageReaction r where r.key.chatType = :chatType and r.key.chatId = :chatId" + + " and r.key.messageId = :messageId") + int deleteAllOnMessage(@Param("chatType") ChatType chatType, @Param("chatId") Long chatId, + @Param("messageId") String messageId); + + /** + * The uid and name of each person who reacted, in one query. Loading whole Person rows + * would also load each one's eager links, several queries per person. + */ + @Query("select p.id as id, p.uid as uid, p.name as name from Person p where p.id in :ids") + List findReactorNames(@Param("ids") Collection ids); + + /** A person who reacted, as far as a reaction needs to know them. */ + interface ReactorName { + Long getId(); + + String getUid(); + + String getName(); + } } diff --git a/src/main/java/com/open/spring/mvc/reactions/MessageReactionService.java b/src/main/java/com/open/spring/mvc/reactions/MessageReactionService.java index 806229c9..68224e38 100644 --- a/src/main/java/com/open/spring/mvc/reactions/MessageReactionService.java +++ b/src/main/java/com/open/spring/mvc/reactions/MessageReactionService.java @@ -13,7 +13,6 @@ import org.springframework.transaction.annotation.Transactional; import com.open.spring.mvc.person.Person; -import com.open.spring.mvc.person.PersonJpaRepository; import lombok.RequiredArgsConstructor; @@ -30,7 +29,6 @@ public class MessageReactionService { .thenComparing(reactor -> reactor.uid() == null ? "" : reactor.uid()); private final MessageReactionJpaRepository repository; - private final PersonJpaRepository personRepository; /** Someone who reacted, as the page shows them. */ public record Reactor(String uid, String name) { @@ -56,10 +54,7 @@ public void add(ChatType type, Long chatId, String messageId, Person person, Rea /** Removes this person's reaction. Removing one that isn't there changes nothing. */ @Transactional public void remove(ChatType type, Long chatId, String messageId, Person person, Reaction reaction) { - MessageReaction.Key key = new MessageReaction.Key(type, chatId, messageId, person.getId(), reaction); - if (repository.existsById(key)) { - repository.deleteById(key); - } + repository.deleteOne(type, chatId, messageId, person.getId(), reaction); } /** One message's reactions, in the enum's order. */ @@ -89,7 +84,7 @@ public Map> forChat(ChatType type, Long chatId) { /** Removes every reaction on a message, as when the message is deleted. */ @Transactional public void removeAllFor(ChatType type, Long chatId, String messageId) { - repository.deleteByKeyChatTypeAndKeyChatIdAndKeyMessageId(type, chatId, messageId); + repository.deleteAllOnMessage(type, chatId, messageId); } // Everyone in one query. Someone whose account is gone isn't in the result, so they drop out. @@ -99,7 +94,7 @@ private Map reactorsFor(List rows) { return Map.of(); } Map reactors = new HashMap<>(); - for (Person person : personRepository.findAllById(ids)) { + for (MessageReactionJpaRepository.ReactorName person : repository.findReactorNames(ids)) { reactors.put(person.getId(), new Reactor(person.getUid(), person.getName())); } return reactors; diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatReactionTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatReactionTest.java index e32cfd6f..912fb128 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupChatReactionTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatReactionTest.java @@ -133,6 +133,8 @@ void aBadMessageIdIs400() { assertEquals(HttpStatus.BAD_REQUEST, controller.addReaction(3L, "not-a-message", "love").getStatusCode()); assertEquals(HttpStatus.BAD_REQUEST, controller.addReaction(3L, "../shared-files", "love").getStatusCode()); + // Saved ids are lowercase; an uppercase one would match some lookups and not others on MySQL. + assertEquals(HttpStatus.BAD_REQUEST, controller.addReaction(3L, MESSAGE_ID.toUpperCase(), "love").getStatusCode()); verify(reactionService, never()).add(any(), any(), any(), any(), any()); } diff --git a/src/test/java/com/open/spring/mvc/reactions/MessageReactionServiceTest.java b/src/test/java/com/open/spring/mvc/reactions/MessageReactionServiceTest.java index ad00a6c1..4f35ec82 100644 --- a/src/test/java/com/open/spring/mvc/reactions/MessageReactionServiceTest.java +++ b/src/test/java/com/open/spring/mvc/reactions/MessageReactionServiceTest.java @@ -15,7 +15,6 @@ import org.springframework.test.util.ReflectionTestUtils; import com.open.spring.mvc.person.Person; -import com.open.spring.mvc.person.PersonJpaRepository; import com.open.spring.mvc.reactions.MessageReactionService.ReactionSummary; import com.open.spring.mvc.reactions.MessageReactionService.Reactor; @@ -26,7 +25,6 @@ class MessageReactionServiceTest { private MessageReactionJpaRepository repository; - private PersonJpaRepository people; private MessageReactionService service; // "ada" is lowercase on purpose: it sorts before "Ana" only when case is ignored. private Person ada; @@ -36,8 +34,7 @@ class MessageReactionServiceTest { @BeforeEach void setUp() { repository = mock(MessageReactionJpaRepository.class); - people = mock(PersonJpaRepository.class); - service = new MessageReactionService(repository, people); + service = new MessageReactionService(repository); ada = person(1L, "ada", "ada"); ana = person(2L, "ana", "Ana"); ben = person(3L, "ben", "Ben"); @@ -56,15 +53,13 @@ void addSavesANewReactionOnce() { } @Test - void removeIsFineWhenNothingIsThere() { - MessageReaction.Key key = new MessageReaction.Key(ChatType.DM, 7L, "42", 1L, Reaction.LIKE); - when(repository.existsById(key)).thenReturn(false); + void removeIsOneDeleteStatement() { + // Read-then-delete let two removes at once fail the second; one statement just deletes 0 rows. service.remove(ChatType.DM, 7L, "42", ada, Reaction.LIKE); - verify(repository, never()).deleteById(any()); - when(repository.existsById(key)).thenReturn(true); - service.remove(ChatType.DM, 7L, "42", ada, Reaction.LIKE); - verify(repository).deleteById(key); + verify(repository).deleteOne(ChatType.DM, 7L, "42", 1L, Reaction.LIKE); + verify(repository, never()).existsById(any()); + verify(repository, never()).deleteById(any()); } @Test @@ -73,7 +68,7 @@ void summariesFollowTheTableOrderAndSortPeople() { row(ChatType.DM, 7L, "42", 3L, Reaction.WOW), row(ChatType.DM, 7L, "42", 2L, Reaction.LIKE), row(ChatType.DM, 7L, "42", 1L, Reaction.LIKE))); - when(people.findAllById(any())).thenReturn(List.of(ben, ana, ada)); + when(repository.findReactorNames(any())).thenReturn(List.of(name(ben), name(ana), name(ada))); List summaries = service.forMessage(ChatType.DM, 7L, "42"); @@ -89,7 +84,7 @@ void aPersonWhoIsGoneIsLeftOut() { row(ChatType.DM, 7L, "42", 2L, Reaction.LIKE), row(ChatType.DM, 7L, "42", 2L, Reaction.SAD))); // Person 2's account is gone, so their Like goes and their Sad, now nobody's, goes too. - when(people.findAllById(any())).thenReturn(List.of(ada)); + when(repository.findReactorNames(any())).thenReturn(List.of(name(ada))); assertEquals(List.of(new ReactionSummary("like", List.of(new Reactor("ada", "ada")))), service.forMessage(ChatType.DM, 7L, "42")); @@ -101,7 +96,7 @@ void forChatKeysByMessageId() { row(ChatType.GROUP, 3L, "42", 1L, Reaction.LIKE), row(ChatType.GROUP, 3L, "57", 3L, Reaction.HAHA), row(ChatType.GROUP, 3L, "60", 9L, Reaction.LIKE))); - when(people.findAllById(any())).thenReturn(List.of(ada, ben)); + when(repository.findReactorNames(any())).thenReturn(List.of(name(ada), name(ben))); Map> byMessage = service.forChat(ChatType.GROUP, 3L); @@ -112,10 +107,30 @@ void forChatKeysByMessageId() { } @Test - void removeAllForDeletesThatMessagesReactions() { + void removeAllForDeletesThatMessagesReactionsInOneStatement() { service.removeAllFor(ChatType.GROUP, 3L, "abc"); - verify(repository).deleteByKeyChatTypeAndKeyChatIdAndKeyMessageId(ChatType.GROUP, 3L, "abc"); + verify(repository).deleteAllOnMessage(ChatType.GROUP, 3L, "abc"); + } + + // Reactors are read as id, uid and name only, never as whole accounts with their links. + private static MessageReactionJpaRepository.ReactorName name(Person person) { + return new MessageReactionJpaRepository.ReactorName() { + @Override + public Long getId() { + return person.getId(); + } + + @Override + public String getUid() { + return person.getUid(); + } + + @Override + public String getName() { + return person.getName(); + } + }; } private static MessageReaction row(ChatType type, long chatId, String messageId, long personId, Reaction reaction) { From 39e4061a4fda8e6cbb02c96d08bb11c637250b70 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Wed, 25 Nov 2026 19:43:24 -0800 Subject: [PATCH 18/46] 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 c791798c610f0190b4f308cf9e2505f5e733bc7d Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Wed, 25 Nov 2026 19:59:30 -0800 Subject: [PATCH 19/46] Reactions: a DM's reactions frame goes out after the commit, read again then The frame was sent inside the change's transaction with the reactions read there, so two people reacting at the same moment could each send a list missing the other's reaction, and everyone in the chat would keep one of them. It is now sent once the transaction commits, with the reactions read in a transaction of their own. A group's reactions were already read after their change had committed. --- .../directmessages/DirectMessageService.java | 29 +++++++++++++++---- .../mvc/reactions/MessageReactionService.java | 10 +++++++ .../DirectMessageReactionTest.java | 24 +++++++++++++++ .../reactions/MessageReactionServiceTest.java | 9 ++++++ 4 files changed, 67 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/open/spring/mvc/directmessages/DirectMessageService.java b/src/main/java/com/open/spring/mvc/directmessages/DirectMessageService.java index 5abc745e..3ab1b53b 100644 --- a/src/main/java/com/open/spring/mvc/directmessages/DirectMessageService.java +++ b/src/main/java/com/open/spring/mvc/directmessages/DirectMessageService.java @@ -12,6 +12,8 @@ import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronization; +import org.springframework.transaction.support.TransactionSynchronizationManager; import com.open.spring.mvc.person.Person; import com.open.spring.mvc.push.PushNotificationService; @@ -266,16 +268,33 @@ public List setReaction(DirectMessageCon List reactions = reactionService.forMessage(ChatType.DM, conversation.getId(), key); - DirectMessageEvent event = DirectMessageEvent.builder() + // The frame goes out once this commits, with the reactions read again then. Read here, + // inside this transaction, they could miss a reaction someone else saved at the same time, + // and that person's frame would miss this one. + Long conversationId = conversation.getId(); + afterCommit(() -> messagingTemplate.convertAndSend(DM_TOPIC_PREFIX + conversationId, DirectMessageEvent.builder() .id(messageId) - .conversationId(conversation.getId()) + .conversationId(conversationId) .type("reactions") - .reactions(reactions) - .build(); - messagingTemplate.convertAndSend(DM_TOPIC_PREFIX + conversation.getId(), event); + .reactions(reactionService.forMessageNow(ChatType.DM, conversationId, key)) + .build())); return reactions; } + // Runs once the current transaction commits, or right away outside one. + private static void afterCommit(Runnable action) { + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { + @Override + public void afterCommit() { + action.run(); + } + }); + } else { + action.run(); + } + } + @Transactional(readOnly = true) public UnreadSummary getUnreadSummary(Person person) { Map people = new LinkedHashMap<>(); diff --git a/src/main/java/com/open/spring/mvc/reactions/MessageReactionService.java b/src/main/java/com/open/spring/mvc/reactions/MessageReactionService.java index 68224e38..f498f897 100644 --- a/src/main/java/com/open/spring/mvc/reactions/MessageReactionService.java +++ b/src/main/java/com/open/spring/mvc/reactions/MessageReactionService.java @@ -10,6 +10,7 @@ import java.util.stream.Collectors; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.open.spring.mvc.person.Person; @@ -64,6 +65,15 @@ public List forMessage(ChatType type, Long chatId, String messa return summarize(rows, reactorsFor(rows)); } + /** + * One message's reactions, read in a transaction of its own: for the frame a DM sends once its + * change has committed, so the read sees what everyone else committed by then. + */ + @Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = true) + public List forMessageNow(ChatType type, Long chatId, String messageId) { + return forMessage(type, chatId, messageId); + } + /** Every reacted-to message in a chat, by message id. A message left with no reactions isn't listed. */ @Transactional(readOnly = true) public Map> forChat(ChatType type, Long chatId) { diff --git a/src/test/java/com/open/spring/mvc/directmessages/DirectMessageReactionTest.java b/src/test/java/com/open/spring/mvc/directmessages/DirectMessageReactionTest.java index a3a81b48..01fcc894 100644 --- a/src/test/java/com/open/spring/mvc/directmessages/DirectMessageReactionTest.java +++ b/src/test/java/com/open/spring/mvc/directmessages/DirectMessageReactionTest.java @@ -26,6 +26,8 @@ import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.transaction.support.TransactionSynchronization; +import org.springframework.transaction.support.TransactionSynchronizationManager; import com.fasterxml.jackson.databind.ObjectMapper; import com.open.spring.mvc.person.Person; @@ -89,6 +91,7 @@ void setUp() { summaries = List.of(new ReactionSummary("like", List.of(new Reactor("alice", "alice")))); when(reactionService.forMessage(ChatType.DM, 7L, "42")).thenReturn(summaries); + when(reactionService.forMessageNow(ChatType.DM, 7L, "42")).thenReturn(summaries); } @Test @@ -105,6 +108,27 @@ void aReactionGoesOutAsAReactionsFrame() { assertEquals(summaries, result); } + @Test + void theFrameGoesOutAfterTheCommitWithReactionsReadThen() { + // Read after the commit, the list has a reaction someone else committed at the same time. + List fresh = List.of(new ReactionSummary("like", + List.of(new Reactor("alice", "alice"), new Reactor("bob", "bob")))); + when(reactionService.forMessageNow(ChatType.DM, 7L, "42")).thenReturn(fresh); + TransactionSynchronizationManager.initSynchronization(); + try { + service.setReaction(conversation, alice, 42L, Reaction.LIKE, true); + verify(messagingTemplate, never()).convertAndSend(eq("/topic/dm/7"), any(Object.class)); + + TransactionSynchronizationManager.getSynchronizations().forEach(TransactionSynchronization::afterCommit); + + ArgumentCaptor frame = ArgumentCaptor.forClass(DirectMessageEvent.class); + verify(messagingTemplate).convertAndSend(eq("/topic/dm/7"), frame.capture()); + assertEquals(fresh, frame.getValue().getReactions()); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + } + @Test void takingAReactionBackRemovesIt() { service.setReaction(conversation, alice, 42L, Reaction.LIKE, false); diff --git a/src/test/java/com/open/spring/mvc/reactions/MessageReactionServiceTest.java b/src/test/java/com/open/spring/mvc/reactions/MessageReactionServiceTest.java index 4f35ec82..d14b7a4b 100644 --- a/src/test/java/com/open/spring/mvc/reactions/MessageReactionServiceTest.java +++ b/src/test/java/com/open/spring/mvc/reactions/MessageReactionServiceTest.java @@ -90,6 +90,15 @@ void aPersonWhoIsGoneIsLeftOut() { service.forMessage(ChatType.DM, 7L, "42")); } + @Test + void forMessageNowReadsTheSameSummary() { + when(repository.findByKeyChatTypeAndKeyChatIdAndKeyMessageId(ChatType.DM, 7L, "42")).thenReturn(List.of( + row(ChatType.DM, 7L, "42", 1L, Reaction.LIKE))); + when(repository.findReactorNames(any())).thenReturn(List.of(name(ada))); + + assertEquals(service.forMessage(ChatType.DM, 7L, "42"), service.forMessageNow(ChatType.DM, 7L, "42")); + } + @Test void forChatKeysByMessageId() { when(repository.findByKeyChatTypeAndKeyChatId(ChatType.GROUP, 3L)).thenReturn(List.of( From 3e388494231a6519b2b215264cbcc690dadacadb Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Wed, 25 Nov 2026 20:06:24 -0800 Subject: [PATCH 20/46] Reactions: a table that can't be made is logged as an error Spring still starts, as it does when the calls or calendar tables can't be made, but the log now says reactions won't work instead of a warning that is easy to miss. --- .../MessageReactionTableInitializer.java | 4 +- .../MessageReactionTableInitializerTest.java | 43 +++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/open/spring/mvc/reactions/MessageReactionTableInitializer.java b/src/main/java/com/open/spring/mvc/reactions/MessageReactionTableInitializer.java index ba70d3e5..a2cbdfad 100644 --- a/src/main/java/com/open/spring/mvc/reactions/MessageReactionTableInitializer.java +++ b/src/main/java/com/open/spring/mvc/reactions/MessageReactionTableInitializer.java @@ -38,7 +38,9 @@ public ApplicationRunner migrateMessageReaction() { try { jdbcTemplate.execute(CREATE_TABLE); } catch (DataAccessException e) { - logger.warn("Could not create the message_reaction table: {}", e.getMessage()); + // The rest of Spring keeps running, as it does when another table can't be made; + // only the reaction routes fail, until the table exists. + logger.error("Could not create the message_reaction table, so reactions won't work: {}", e.getMessage()); } }; } diff --git a/src/test/java/com/open/spring/mvc/reactions/MessageReactionTableInitializerTest.java b/src/test/java/com/open/spring/mvc/reactions/MessageReactionTableInitializerTest.java index c34acaef..27093fe6 100644 --- a/src/test/java/com/open/spring/mvc/reactions/MessageReactionTableInitializerTest.java +++ b/src/test/java/com/open/spring/mvc/reactions/MessageReactionTableInitializerTest.java @@ -1,15 +1,26 @@ package com.open.spring.mvc.reactions; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; +import org.springframework.boot.ApplicationRunner; +import org.springframework.boot.DefaultApplicationArguments; import org.springframework.dao.DataAccessException; +import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.SingleConnectionDataSource; +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; + /** The statement that creates message_reaction at startup, run on SQLite as a local server does. */ class MessageReactionTableInitializerTest { @@ -50,4 +61,36 @@ void rejectsTheSameReactionTwice() { assertEquals(2, jdbc.queryForObject("SELECT COUNT(*) FROM message_reaction", Integer.class)); } + + // Startup goes on, as it does for the other tables (calls, calendar), but the log says plainly + // that reactions are broken: a warning was easy to miss. + @Test + void aFailedCreateIsLoggedAsAnErrorAndStartupGoesOn() { + JdbcTemplate failing = new JdbcTemplate(dataSource) { + @Override + public void execute(String sql) { + throw new DataAccessResourceFailureException("the database is read-only"); + } + }; + ApplicationRunner runner = new MessageReactionTableInitializer(failing).migrateMessageReaction(); + Logger logger = (Logger) LoggerFactory.getLogger(MessageReactionTableInitializer.class); + Level previous = logger.getLevel(); + ListAppender logs = new ListAppender<>(); + logs.start(); + logger.addAppender(logs); + logger.setLevel(Level.INFO); + try { + assertDoesNotThrow(() -> runner.run(new DefaultApplicationArguments())); + } finally { + logger.detachAppender(logs); + logger.setLevel(previous); + logs.stop(); + } + + assertEquals(1, logs.list.size()); + ILoggingEvent event = logs.list.get(0); + assertEquals(Level.ERROR, event.getLevel()); + assertTrue(event.getFormattedMessage().contains("reactions won't work"), event.getFormattedMessage()); + assertTrue(event.getFormattedMessage().contains("the database is read-only"), event.getFormattedMessage()); + } } From d6c2bfe9002b780325c5b51294efa4ddaf00138e Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Wed, 25 Nov 2026 20:11:15 -0800 Subject: [PATCH 21/46] Docs: list the reaction tests before the chat regression tests The group chat fixes (#296 to #299) each add a line after the chat regression tests, so the reactions line goes above it and the two change different places. --- docs/group-chat-architecture.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/group-chat-architecture.md b/docs/group-chat-architecture.md index 9e6be786..19a45f7e 100644 --- a/docs/group-chat-architecture.md +++ b/docs/group-chat-architecture.md @@ -176,8 +176,8 @@ People react to a message in a group chat or a direct message with one of six em - `api/groups.http`: open it in VS Code with the REST Client extension and run the requests in order. Set `baseUrl`, `adminUid` and `adminPassword` under `rest-client.environmentVariables` in the Git-ignored `.vscode/settings.json`. Never put passwords in the file. It creates a test group, adds you, sends and reads messages, checks unread counts, and deletes the group. - **The WebSocket can't be tested from a `.http` file.** To check it, open a course page with a chat against a local server and watch the browser's Network panel (WS filter) for frames on `/topic/group/{id}`. Or connect any STOMP client to `ws://localhost:8589/ws-chat/websocket` (SockJS's raw WebSocket transport), send `CONNECT`, `SUBSCRIBE` to `/topic/group/{id}`, and `SEND` JSON events to `/app/groups.chat`. A `SUBSCRIBE` to `/topic/dm/{id}` only goes through when the handshake carries a participant's `jwt_java_spring` cookie (a `Cookie` header) and an `Origin` header from the REST API's CORS list, such as `http://localhost:4500`. Without them, or for a wildcard subscription, a `/user/...` destination or a `SEND` to `/topic/dm/...`, the frame is dropped and the server logs a "refused" warning. Run the socket's own tests with `./mvnw test '-Dtest=DirectMessageTopic*Test,ChatSocketIdentityInterceptorTest,WebSocketBrokerConfigTest'`. -- Run the chat regression tests with `./mvnw test '-Dtest=GroupChat*Test'`. They cover UID-based ownership, REST identity forwarding and unread counts. `GroupChatFilesTest` covers the file index, one-file downloads, the path rules, the bytes-free frame, uploads that land together, a path that is already shared, two uploads of one path at once, and a check that fails; `S3FileHandlerExistsTest` covers the strict check. - Reactions: `./mvnw test '-Dtest=GroupChatReactionTest,DirectMessageReactionTest,MessageReaction*Test,ReactionTest'`. They cover both chats' frames and status codes, that a group reaction never touches S3 and a DM reaction never sends a push, the summaries' order, and the table's primary key on SQLite. +- Run the chat regression tests with `./mvnw test '-Dtest=GroupChat*Test'`. They cover UID-based ownership, REST identity forwarding and unread counts. `GroupChatFilesTest` covers the file index, one-file downloads, the path rules, the bytes-free frame, uploads that land together, a path that is already shared, two uploads of one path at once, and a check that fails; `S3FileHandlerExistsTest` covers the strict check. ## Known issues From 68186793d3d0847712694f5bc92051d304b7812b Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Wed, 25 Nov 2026 20:15:20 -0800 Subject: [PATCH 22/46] 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 d9a74b42b7839aa292d0d4201a9c0ffc946ff5c7 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Wed, 25 Nov 2026 20:21:35 -0800 Subject: [PATCH 23/46] Group chat tests: build the send test's controller from its constructor's types GroupChatSendTest built GroupChatApiController, GroupChatRealtimeService and GroupChatReadService by naming their constructors. Open PRs add constructor dependencies to the controller and the realtime service (#302 a MessageReactionService, #303 a MentorAccess), so once one of them and this test were both on master, the tests would stop compiling, with no merge conflict to show it. TestBeans builds a class through its biggest constructor: each parameter gets the first object the test passes that fits it, and a Mockito mock otherwise. The test then keeps compiling and running whatever dependencies those classes gain. --- .../spring/mvc/groups/GroupChatSendTest.java | 8 ++-- .../com/open/spring/mvc/groups/TestBeans.java | 37 +++++++++++++++++++ 2 files changed, 42 insertions(+), 3 deletions(-) create mode 100644 src/test/java/com/open/spring/mvc/groups/TestBeans.java diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java index b6c3b718..05c32271 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java @@ -103,10 +103,12 @@ private void wire(S3FileHandler storage) { GroupChatService chat = new GroupChatService(storage, new ObjectMapper()); GroupsJpaRepository groups = mock(GroupsJpaRepository.class); messaging = mock(SimpMessagingTemplate.class); - GroupChatRealtimeService realtime = new GroupChatRealtimeService(chat, groups, messaging); - GroupChatReadService reads = new GroupChatReadService(mock(GroupChatReadStateJpaRepository.class), groups, chat); + // Built from whatever their constructors take, so a new dependency elsewhere doesn't break this test. + GroupChatRealtimeService realtime = TestBeans.build(GroupChatRealtimeService.class, chat, groups, messaging); + GroupChatReadService reads = TestBeans.build(GroupChatReadService.class, + mock(GroupChatReadStateJpaRepository.class), groups, chat); PersonJpaRepository people = mock(PersonJpaRepository.class); - controller = new GroupChatApiController(chat, realtime, reads, groups, people); + controller = TestBeans.build(GroupChatApiController.class, chat, realtime, reads, groups, people); Groups group = new Groups(); group.setName("CSA"); diff --git a/src/test/java/com/open/spring/mvc/groups/TestBeans.java b/src/test/java/com/open/spring/mvc/groups/TestBeans.java new file mode 100644 index 00000000..2191bd37 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/groups/TestBeans.java @@ -0,0 +1,37 @@ +package com.open.spring.mvc.groups; + +import java.lang.reflect.Constructor; +import java.util.Arrays; +import java.util.Comparator; + +import org.mockito.Mockito; + +/** + * Builds a class through its constructor without naming the constructor's parameters. Each + * parameter gets the first object the test passes that fits it, and any other parameter gets a + * Mockito mock. So a test keeps compiling, and keeps running, when another change gives the + * class a dependency the test doesn't care about. + */ +final class TestBeans { + + private TestBeans() { + } + + static T build(Class type, Object... given) { + Constructor constructor = Arrays.stream(type.getDeclaredConstructors()) + .max(Comparator.comparingInt(Constructor::getParameterCount)) + .orElseThrow(); + Object[] args = Arrays.stream(constructor.getParameterTypes()) + .map(parameter -> Arrays.stream(given) + .filter(parameter::isInstance) + .findFirst() + .orElseGet(() -> Mockito.mock(parameter))) + .toArray(); + try { + constructor.setAccessible(true); + return type.cast(constructor.newInstance(args)); + } catch (ReflectiveOperationException e) { + throw new IllegalStateException("Could not build " + type.getSimpleName(), e); + } + } +} From 62179360095b51c0ca60400ff7409303a5d7ab20 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Thu, 19 Nov 2026 22:11:22 -0800 Subject: [PATCH 24/46] Group files: answer 503 when S3 can't take the write After the path check, the upload wrote the file with S3FileHandler.uploadFile, which catches every failure and answers null. So when S3 throttled the write, timed out or couldn't be reached, the upload got a 500 "Upload failed", which reads as a bug in this server. Shared files now write with uploadFileOrThrow, a strict version beside it, the way fileExistsOrThrow sits beside fileExists. uploadFile is unchanged for the other S3 features. A timeout, no connection or a 5xx on the write now answers 503 with a try-again message and Retry-After, like a failed check, and the file isn't shared: no "shared by" record and no socket frame. S3 refusing the write (a 4xx such as no permission) or a bug here is still a 500 "Upload failed", and every failed write is still logged. S3's RequestTimeout counts as a timeout too, for the check and the write: S3 sends it as a 400, but it means the connection was too slow, and the AWS SDK retries it like a 5xx. SharedFileCheckFailedException is now SharedFileStorageUnavailableException, since a failed write throws it too, so the 503 is still answered in one place. One check (isUnavailable) decides what counts as S3 being unavailable for both the check and the write. The architecture doc says the same. Tests cover a throttle, a timeout and a RequestTimeout on the write (503), an S3 403, an S3 400 and a bug (500), sharing again once S3 is back, and uploadFileOrThrow itself. --- docs/group-chat-architecture.md | 5 +- .../spring/mvc/S3uploads/S3FileHandler.java | 17 ++++ .../mvc/groups/GroupChatApiController.java | 11 ++- .../mvc/groups/GroupChatRealtimeService.java | 5 +- .../spring/mvc/groups/GroupChatService.java | 54 ++++++++-- .../SharedFileCheckFailedException.java | 21 ---- ...SharedFileStorageUnavailableException.java | 22 +++++ .../S3uploads/S3FileHandlerUploadTest.java | 79 +++++++++++++++ .../spring/mvc/groups/GroupChatFilesTest.java | 98 +++++++++++++++++++ 9 files changed, 270 insertions(+), 42 deletions(-) delete mode 100644 src/main/java/com/open/spring/mvc/groups/SharedFileCheckFailedException.java create mode 100644 src/main/java/com/open/spring/mvc/groups/SharedFileStorageUnavailableException.java create mode 100644 src/test/java/com/open/spring/mvc/S3uploads/S3FileHandlerUploadTest.java diff --git a/docs/group-chat-architecture.md b/docs/group-chat-architecture.md index 67f977ad..a02faa71 100644 --- a/docs/group-chat-architecture.md +++ b/docs/group-chat-architecture.md @@ -140,7 +140,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) | GET | `/api/groups/chat/{groupId}/files` | Shared files with who uploaded them, each with its bytes as `base64Data` | Any signed-in account | | GET | `/api/groups/chat/{groupId}/files/index` | Shared files as `[{path, size, uploadedBy, uploadedAt}]`, sorted by path, without bytes | Any signed-in account | | GET | `/api/groups/chat/{groupId}/files/content?path=` | One shared file's bytes (`application/octet-stream`, named by the last part of its path); 400 for a path that isn't valid, 404 when there is no such file | Any signed-in account | -| POST | `/api/groups/chat/{groupId}/files` | Upload `{filename, base64Data}`; 400 when `filename` isn't a valid path, 409 `{message, filename}` when a file is already shared at that path, 503 `{message, filename}` with `Retry-After` when S3 can't say for now whether the path is taken. Broadcasts `sendFileServer` with `filename` and `size`, not the bytes | Any signed-in account | +| POST | `/api/groups/chat/{groupId}/files` | Upload `{filename, base64Data}`; 400 when `filename` isn't a valid path, 409 `{message, filename}` when a file is already shared at that path, 503 `{message, filename}` with `Retry-After` when S3 is unavailable for a moment, checking the path or writing the file. Broadcasts `sendFileServer` with `filename` and `size`, not the bytes | Any signed-in account | | GET | `/api/groups/chat/analytics/{personId}` | Message and file counts across a person's groups | Any signed-in account | ## Persistence @@ -150,7 +150,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) | Groups and members | SQL: `groups`, `group_members`, and the shared `submitter` table | Ids come from `submitter_seq`, shared with `Person`. | | Read states | SQL: `group_chat_read_state` (`group_id`, `person_id`, `last_read_at`) | One row per member per group. | | Messages | S3: `/messages-images/messages.jsonl` | One JSON line per message: `id`, `author` (display name), `author_uid`, `message`, `date`, `image`, `edited`. | -| Shared files | S3: `/shared-files/` plus `shared-files-meta.json` for who uploaded each | A file shared from a folder keeps its folders: `filename` is a path like `project/src/Main.java` (`SharedFilePaths`: no `..`, `.` or empty names, nothing absolute, no backslashes or control characters, at most 512 characters and 255 per name). A shared file is never written over: the same path again is refused with 409, and so is an upload of a path another upload is writing at that moment (`sharesInFlight`, within one server), so two people sharing `notes.md` at once keep both files. The page then shares its copy under the next free name. A file goes up as one base64 string in JSON, so `JsonLimitsConfig` lets a JSON string be up to 50,000,000 characters, enough for a 35 MB file (Jackson's default of 20,000,000 stopped uploads at about 14 MB; nginx caps a request at 50 MB). The existence check is strict (`S3FileHandler.fileExistsOrThrow`): only S3's 404 reads as free, and any other failure to check refuses the upload rather than risk writing over a file. When S3 timed out, couldn't be reached or answered with a 5xx (a throttle, an outage), that's a 503 with `Retry-After` (`SharedFileCheckFailedException`); S3 refusing the request (a 4xx) or a bug here is a 500. Writes to the metadata file take a lock per group, so uploads that land together keep every name. | +| Shared files | S3: `/shared-files/` plus `shared-files-meta.json` for who uploaded each | A file shared from a folder keeps its folders: `filename` is a path like `project/src/Main.java` (`SharedFilePaths`: no `..`, `.` or empty names, nothing absolute, no backslashes or control characters, at most 512 characters and 255 per name). A shared file is never written over: the same path again is refused with 409, and so is an upload of a path another upload is writing at that moment (`sharesInFlight`, within one server), so two people sharing `notes.md` at once keep both files. The page then shares its copy under the next free name. A file goes up as one base64 string in JSON, so `JsonLimitsConfig` lets a JSON string be up to 50,000,000 characters, enough for a 35 MB file (Jackson's default of 20,000,000 stopped uploads at about 14 MB; nginx caps a request at 50 MB). The existence check is strict (`S3FileHandler.fileExistsOrThrow`): only S3's 404 reads as free, and any other failure to check refuses the upload rather than risk writing over a file. The write is strict too (`S3FileHandler.uploadFileOrThrow`): a failed write throws instead of answering null. When S3 timed out (its own `RequestTimeout` comes as a 400), couldn't be reached or answered with a 5xx (a throttle, an outage), checking or writing, that's a 503 with `Retry-After` (`SharedFileStorageUnavailableException`); S3 refusing the request (any other 4xx) or a bug here is a 500. Writes to the metadata file take a lock per group, so uploads that land together keep every name. | | Presence | Memory only | Lost on restart; rebuilt as clients rejoin. | - **History is keyed by group name, not id.** Renaming a group with `PUT /api/groups/{id}` leaves its history under the old name. @@ -167,6 +167,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) - `GroupChatServiceTest` covers two sends, an edit and a send, and a delete and a send landing at once. - `GroupChatSendTest` sends through the controller to a real `S3FileHandler` over a stand-in S3 client: a read that fails, a read S3 refuses, a bug, a group with no messages file yet, and a server without S3. `S3FileHandlerDecodeTest` covers the strict read. Run the S3 handler tests with `./mvnw test '-Dtest=S3FileHandler*Test'`. - `StartupServiceTest` runs the start-up check over a real `S3FileHandler` and a stand-in S3 client: checks that fail, a group that can't be checked among others, a group with no messages file yet, a group that has one, a server without S3, and a send during the check. Run it with `./mvnw test '-Dtest=StartupServiceTest'`. +- `GroupChatFilesTest` also covers a write that fails, including sharing again once S3 is back, and `S3FileHandlerUploadTest` covers the strict write. ## Known issues diff --git a/src/main/java/com/open/spring/mvc/S3uploads/S3FileHandler.java b/src/main/java/com/open/spring/mvc/S3uploads/S3FileHandler.java index fa2c9b82..8f1f4dab 100644 --- a/src/main/java/com/open/spring/mvc/S3uploads/S3FileHandler.java +++ b/src/main/java/com/open/spring/mvc/S3uploads/S3FileHandler.java @@ -110,6 +110,23 @@ public String uploadFile(String base64Data, String filename, String uid) { } } + /** + * Like uploadFile, but a write that fails throws instead of answering null, so a caller can + * tell S3 being unavailable for a moment (a throttle, a 5xx, no connection) from a request + * S3 refused. + */ + public String uploadFileOrThrow(String base64Data, String filename, String uid) { + if (s3Client == null) { + throw new IllegalStateException("S3 client is not configured"); + } + s3Client.putObject(PutObjectRequest.builder() + .bucket(bucketName) + .key(generateKey(uid, filename)) + .build(), + RequestBody.fromBytes(Base64.getDecoder().decode(base64Data))); + return filename; + } + @Override public String decodeFile(String uid, String filename) { if (s3Client == null) { 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 56db34d1..fcc528e3 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java @@ -38,8 +38,9 @@ @CrossOrigin public class GroupChatApiController { - // How long to wait before trying again when S3 couldn't check a shared path or read a - // group's messages: a throttle or a short outage clears in seconds. + // How long to wait before trying again when S3 was unavailable for a moment, checking or + // writing a shared file or reading a group's messages: a throttle or a short outage clears + // in seconds. private static final int RETRY_AFTER_SECONDS = 5; private final GroupChatService groupChatService; @@ -405,9 +406,9 @@ public ResponseEntity uploadSharedFile( response.put("message", ex.getMessage()); response.put("filename", ex.getPath()); return new ResponseEntity<>(response, HttpStatus.CONFLICT); - } catch (SharedFileCheckFailedException ex) { - // S3 couldn't say whether the path is taken, so nothing was written. That's S3 being - // unavailable for a moment, not a bug here: a 503, and when to try again. + } catch (SharedFileStorageUnavailableException ex) { + // S3 was unavailable for a moment, checking the path or writing the file, so the file + // isn't shared. That's not a bug here: a 503, and when to try again. Map response = new HashMap<>(); response.put("message", ex.getMessage()); response.put("filename", ex.getPath()); diff --git a/src/main/java/com/open/spring/mvc/groups/GroupChatRealtimeService.java b/src/main/java/com/open/spring/mvc/groups/GroupChatRealtimeService.java index 532b8d69..bac95d70 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatRealtimeService.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatRealtimeService.java @@ -101,10 +101,7 @@ public GroupChatEvent publishFile(Long groupId, String sender, String filename, throw new IllegalArgumentException("Invalid file path"); } - String uploadResult = groupChatService.uploadSharedFile(group.getName(), path, base64Data, sender); - if (uploadResult == null) { - throw new IllegalStateException("Upload failed"); - } + groupChatService.uploadSharedFile(group.getName(), path, base64Data, sender); GroupChatEvent event = GroupChatEvent.builder() .context("sendFileServer") diff --git a/src/main/java/com/open/spring/mvc/groups/GroupChatService.java b/src/main/java/com/open/spring/mvc/groups/GroupChatService.java index f1549961..afc92eee 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatService.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatService.java @@ -21,6 +21,7 @@ import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import software.amazon.awssdk.awscore.exception.AwsErrorDetails; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.services.s3.model.S3Exception; @@ -31,6 +32,8 @@ public class GroupChatService { private static final String MESSAGES_FILE = "messages-images/messages.jsonl"; private static final String SHARED_FILES_PREFIX = "shared-files/"; private static final String SHARED_FILES_META = "shared-files-meta.json"; + // S3's error code when a connection was too slow: a 400, but the AWS SDK retries it like a 5xx. + private static final String S3_REQUEST_TIMEOUT = "RequestTimeout"; private final S3FileHandler s3FileHandler; private final ObjectMapper objectMapper; @@ -306,7 +309,8 @@ public byte[] readSharedFile(String groupName, String path) { /** * Stores a shared file, never over one already there: that throws SharedFileExistsException. - * When S3 can't say for now whether the path is taken, it throws SharedFileCheckFailedException. + * When S3 is unavailable for a moment, checking the path or writing the file, it throws + * SharedFileStorageUnavailableException. */ public String uploadSharedFile(String groupName, String filename, String base64Data, String uploadedBy) { List key = List.of(groupName, filename); @@ -317,10 +321,7 @@ public String uploadSharedFile(String groupName, String filename, String base64D if (isAlreadyShared(groupName, filename)) { throw new SharedFileExistsException(filename); } - String result = s3FileHandler.uploadFile(base64Data, SHARED_FILES_PREFIX + filename, groupName); - if (result == null) { - return null; - } + String result = store(groupName, filename, base64Data); recordFileMeta(groupName, filename, uploadedBy); return result; } finally { @@ -330,20 +331,53 @@ public String uploadSharedFile(String groupName, String filename, String base64D /** * Whether a file is stored at this path. Strict: a check that failed throws, rather than - * reading as a free path. S3 out of reach or answering a 5xx is something to wait out, so - * that throws SharedFileCheckFailedException; anything else goes up as it is. + * reading as a free path. S3 being unavailable throws SharedFileStorageUnavailableException; + * anything else goes up as it is. */ private boolean isAlreadyShared(String groupName, String path) { try { return s3FileHandler.fileExistsOrThrow(groupName, SHARED_FILES_PREFIX + path); } catch (SdkClientException | S3Exception e) { - if (e instanceof S3Exception answered && answered.statusCode() < 500) { - // S3 refused the request (no permission, a bad key): waiting won't fix that. + if (!isUnavailable(e)) { throw e; } log.warn("Could not check whether {} is shared in group {}", path, groupName, e); - throw new SharedFileCheckFailedException(path, e); + throw new SharedFileStorageUnavailableException(path, e); + } + } + + /** + * Writes a shared file's bytes. S3 being unavailable throws + * SharedFileStorageUnavailableException; any other failure fails the upload as it always has. + */ + private String store(String groupName, String path, String base64Data) { + try { + return s3FileHandler.uploadFileOrThrow(base64Data, SHARED_FILES_PREFIX + path, groupName); + } catch (RuntimeException e) { + log.warn("Could not store {} in group {}", path, groupName, e); + if (isUnavailable(e)) { + throw new SharedFileStorageUnavailableException(path, e); + } + throw new IllegalStateException("Upload failed", e); + } + } + + /** + * S3 out of reach (a timeout, no connection), answering a 5xx (a throttle, an outage) or + * timing out the request itself (RequestTimeout, which comes as a 400): something to wait + * out. Any other 4xx is S3 refusing the request (no permission, a bad key), which waiting + * won't fix, and anything else is a fault here. + */ + private static boolean isUnavailable(RuntimeException e) { + if (e instanceof SdkClientException) { + return true; + } + if (e instanceof S3Exception answered) { + AwsErrorDetails details = answered.awsErrorDetails(); + return answered.statusCode() >= 500 + || (details != null && S3_REQUEST_TIMEOUT.equals(details.errorCode())); } + return false; } // --------------------------------------------------------------------------- diff --git a/src/main/java/com/open/spring/mvc/groups/SharedFileCheckFailedException.java b/src/main/java/com/open/spring/mvc/groups/SharedFileCheckFailedException.java deleted file mode 100644 index e71203dd..00000000 --- a/src/main/java/com/open/spring/mvc/groups/SharedFileCheckFailedException.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.open.spring.mvc.groups; - -/** - * S3 couldn't say for now whether a shared file is already stored at this path: it timed out, - * couldn't be reached or answered with a 5xx (a throttle, an outage). The upload is refused - * rather than risk writing over a file, and the API answers 503 with Retry-After, since S3 being - * unavailable for a moment isn't a bug in this server. - */ -public class SharedFileCheckFailedException extends RuntimeException { - - private final String path; - - public SharedFileCheckFailedException(String path, Throwable cause) { - super("Could not check whether " + path + " is already shared in this group. Try again in a moment.", cause); - this.path = path; - } - - public String getPath() { - return path; - } -} diff --git a/src/main/java/com/open/spring/mvc/groups/SharedFileStorageUnavailableException.java b/src/main/java/com/open/spring/mvc/groups/SharedFileStorageUnavailableException.java new file mode 100644 index 00000000..0f1ee102 --- /dev/null +++ b/src/main/java/com/open/spring/mvc/groups/SharedFileStorageUnavailableException.java @@ -0,0 +1,22 @@ +package com.open.spring.mvc.groups; + +/** + * S3 was unavailable for a moment while a file was being shared: it timed out, couldn't be + * reached or answered with a 5xx (a throttle, an outage). Either it couldn't say whether the + * path is taken, so the upload is refused rather than risk writing over a file, or the write + * itself failed. The file isn't shared, and the API answers 503 with Retry-After, since S3 being + * unavailable for a moment isn't a bug in this server. + */ +public class SharedFileStorageUnavailableException extends RuntimeException { + + private final String path; + + public SharedFileStorageUnavailableException(String path, Throwable cause) { + super("Could not share " + path + " in this group. Try again in a moment.", cause); + this.path = path; + } + + public String getPath() { + return path; + } +} diff --git a/src/test/java/com/open/spring/mvc/S3uploads/S3FileHandlerUploadTest.java b/src/test/java/com/open/spring/mvc/S3uploads/S3FileHandlerUploadTest.java new file mode 100644 index 00000000..0e35b375 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/S3uploads/S3FileHandlerUploadTest.java @@ -0,0 +1,79 @@ +package com.open.spring.mvc.S3uploads; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.Base64; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.test.util.ReflectionTestUtils; + +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.S3Exception; + +/** + * uploadFileOrThrow tells a stored file apart from a write that failed: it throws the failure + * where uploadFile answers null, so a caller can tell S3 being unavailable for a moment from a + * request S3 refused. + */ +class S3FileHandlerUploadTest { + + private static final String HELLO = Base64.getEncoder().encodeToString("hello".getBytes(StandardCharsets.UTF_8)); + + private S3Client s3; + private S3FileHandler handler; + + @BeforeEach + void setUp() { + s3 = mock(S3Client.class); + handler = new S3FileHandler(); + ReflectionTestUtils.setField(handler, "s3Client", s3); + ReflectionTestUtils.setField(handler, "bucketName", "pages-assignments"); + } + + @Test + void aWriteS3TakesStoresTheBytesUnderTheGroupsKey() throws Exception { + assertEquals("shared-files/notes.md", handler.uploadFileOrThrow(HELLO, "shared-files/notes.md", "CSA")); + + ArgumentCaptor request = ArgumentCaptor.forClass(PutObjectRequest.class); + ArgumentCaptor body = ArgumentCaptor.forClass(RequestBody.class); + verify(s3).putObject(request.capture(), body.capture()); + assertEquals("pages-assignments", request.getValue().bucket()); + assertEquals("CSA/shared-files/notes.md", request.getValue().key()); + try (InputStream bytes = body.getValue().contentStreamProvider().newStream()) { + assertArrayEquals("hello".getBytes(StandardCharsets.UTF_8), bytes.readAllBytes()); + } + } + + @Test + void aWriteThatFailsThrowsTheFailureInsteadOfAnsweringNull() { + S3Exception throttled = (S3Exception) S3Exception.builder().statusCode(503).message("Slow Down").build(); + when(s3.putObject(any(PutObjectRequest.class), any(RequestBody.class))).thenThrow(throttled); + + assertSame(throttled, assertThrows(S3Exception.class, + () -> handler.uploadFileOrThrow(HELLO, "shared-files/notes.md", "CSA"))); + // uploadFile keeps answering null, as its other callers expect. + assertNull(handler.uploadFile(HELLO, "shared-files/notes.md", "CSA")); + } + + @Test + void withoutS3ItThrowsInsteadOfAnsweringNull() { + S3FileHandler notConfigured = new S3FileHandler(); + + assertThrows(IllegalStateException.class, + () -> notConfigured.uploadFileOrThrow(HELLO, "shared-files/notes.md", "CSA")); + } +} diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatFilesTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatFilesTest.java index 6953ce1f..6e6efacd 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupChatFilesTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatFilesTest.java @@ -41,6 +41,7 @@ import com.open.spring.mvc.person.Person; import com.open.spring.mvc.person.PersonJpaRepository; +import software.amazon.awssdk.awscore.exception.AwsErrorDetails; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.services.s3.model.S3Exception; @@ -61,6 +62,12 @@ public String uploadFile(String base64Data, String filename, String uid) { return filename; } + // Stores the same way, so a test that slows uploadFile slows this too. + @Override + public String uploadFileOrThrow(String base64Data, String filename, String uid) { + return uploadFile(base64Data, filename, uid); + } + @Override public String decodeFile(String uid, String filename) { byte[] bytes = objects.get(uid + "/" + filename); @@ -90,6 +97,36 @@ public Map listFileSizes(String prefix) { } } + /** + * S3 that answers the check but fails the write of a shared file's bytes while `failure` is + * set, the way S3FileHandler sees it: uploadFile swallows the failure and answers null, and + * uploadFileOrThrow throws it. Other writes, like the "shared by" record, still go through. + */ + static class SharedFileWritesFail extends InMemoryStorage { + RuntimeException failure; + + SharedFileWritesFail(RuntimeException failure) { + this.failure = failure; + } + + private boolean failing(String filename) { + return failure != null && filename.startsWith("shared-files/"); + } + + @Override + public String uploadFile(String base64Data, String filename, String uid) { + return failing(filename) ? null : super.uploadFile(base64Data, filename, uid); + } + + @Override + public String uploadFileOrThrow(String base64Data, String filename, String uid) { + if (failing(filename)) { + throw failure; + } + return super.uploadFileOrThrow(base64Data, filename, uid); + } + } + private InMemoryStorage storage; private SimpMessagingTemplate messaging; private GroupChatApiController controller; @@ -323,6 +360,67 @@ public boolean fileExistsOrThrow(String uid, String filename) { } } + @Test + void aWriteThatFailsForAMomentIsA503AndSharesNothing() { + // The path is free, but S3 throttled the write (503 Slow Down), couldn't be reached, or + // timed out the request (its RequestTimeout comes as a 400). + List failures = List.of( + (S3Exception) S3Exception.builder().statusCode(503).message("Slow Down").build(), + SdkClientException.create("Unable to execute HTTP request: Read timed out"), + (S3Exception) S3Exception.builder().statusCode(400) + .awsErrorDetails(AwsErrorDetails.builder().errorCode("RequestTimeout").build()) + .message("Your socket connection to the server was not read from or written to within the timeout period.") + .build()); + for (RuntimeException failure : failures) { + useStorage(new SharedFileWritesFail(failure)); + + ResponseEntity response = upload("notes.md", "Grace's notes"); + + assertEquals(HttpStatus.SERVICE_UNAVAILABLE, response.getStatusCode(), failure.toString()); + String retryAfter = response.getHeaders().getFirst(HttpHeaders.RETRY_AFTER); + assertTrue(retryAfter != null && retryAfter.matches("[1-9][0-9]*"), "Retry-After: " + retryAfter); + @SuppressWarnings("unchecked") + Map body = (Map) response.getBody(); + assertEquals("notes.md", body.get("filename")); + // No file, no "shared by" record, and no frame telling the group a file arrived. + assertTrue(storage.objects.isEmpty(), "stored: " + storage.objects.keySet()); + verify(messaging, never()).convertAndSend(any(String.class), any(Object.class)); + } + } + + @Test + void aWriteS3RefusesOrABugIsStillA500() { + // S3 refusing the write (no permission, a bad request) or a fault in this server: trying + // again won't help, so none is a 503. + List faults = List.of( + new NullPointerException("a bug here, not S3"), + (S3Exception) S3Exception.builder().statusCode(403).message("Access Denied").build(), + (S3Exception) S3Exception.builder().statusCode(400) + .awsErrorDetails(AwsErrorDetails.builder().errorCode("InvalidRequest").build()) + .message("Invalid Request") + .build()); + for (RuntimeException fault : faults) { + useStorage(new SharedFileWritesFail(fault)); + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, upload("notes.md", "Grace's notes").getStatusCode(), fault.toString()); + } + } + + @Test + void aShareThatFailedForAMomentGoesThroughWhenTriedAgain() { + // What the 503 promises: once S3 takes writes again, the same share works, instead of + // finding the path still held by the upload that failed. + SharedFileWritesFail s3 = new SharedFileWritesFail( + SdkClientException.create("Unable to execute HTTP request: Connect timed out")); + useStorage(s3); + assertEquals(HttpStatus.SERVICE_UNAVAILABLE, upload("notes.md", "Grace's notes").getStatusCode()); + + s3.failure = null; + + assertEquals(HttpStatus.OK, upload("notes.md", "Grace's notes").getStatusCode()); + assertArrayEquals("Grace's notes".getBytes(StandardCharsets.UTF_8), storage.objects.get("CSA/shared-files/notes.md")); + } + @Test void aPathBeingWrittenInOneGroupDoesNotHoldUpALookAlikeInAnother() throws Exception { // "a/b" sharing "c" and "a" sharing "b/c" read the same if group and path are joined. From b30e611fa82f8cd983a1f0cb8617979ee7cef00d Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Sun, 22 Nov 2026 01:04:56 -0800 Subject: [PATCH 25/46] Group chat: a restart keeps the history when S3 can't check it At every start, StartupService checks each group's messages file and creates an empty one for a group that has none. The check used fileExists, which reads any failure (a throttle, a 5xx, a timeout) as a missing file, so a check that failed at boot wrote an empty file over that group's whole history. ensureGroupStorageExists now checks with fileExistsOrThrow: only S3's 404 creates the file, and any other failure throws before anything is written. StartupService logs that group with the cause and goes on to the next one, so the server still starts. The check holds the group's message lock, so a message sent while the server is starting isn't written over, and a server without S3 settings checks nothing (S3FileHandler.isConfigured). The shared-files/ placeholder keeps the lenient check: it is empty, so writing it again loses nothing. --- .../java/com/open/spring/StartupService.java | 12 +- .../spring/mvc/S3uploads/S3FileHandler.java | 5 + .../spring/mvc/groups/GroupChatService.java | 25 +- .../com/open/spring/StartupServiceTest.java | 291 ++++++++++++++++++ 4 files changed, 326 insertions(+), 7 deletions(-) create mode 100644 src/test/java/com/open/spring/StartupServiceTest.java diff --git a/src/main/java/com/open/spring/StartupService.java b/src/main/java/com/open/spring/StartupService.java index 0f6c434f..d2c28de6 100644 --- a/src/main/java/com/open/spring/StartupService.java +++ b/src/main/java/com/open/spring/StartupService.java @@ -11,9 +11,11 @@ import com.open.spring.mvc.groups.GroupsJpaRepository; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; @Component @RequiredArgsConstructor +@Slf4j public class StartupService { private final GroupsJpaRepository groupsRepository; @@ -25,9 +27,15 @@ public ApplicationRunner initializeGroupStorage() { // Fetch all existing groups from the database List groups = groupsRepository.findAll(); - // Ensure S3 storage exists for each group + // Ensure S3 storage exists for each group. A group whose storage can't be checked is + // left as it is until the next start, and the other groups are still checked, so one + // group can't stop the server from starting. for (Groups group : groups) { - groupChatService.ensureGroupStorageExists(group.getName()); + try { + groupChatService.ensureGroupStorageExists(group.getName()); + } catch (RuntimeException e) { + log.warn("Could not check the chat storage of group {}, so nothing was written to it", group.getName(), e); + } } }; } diff --git a/src/main/java/com/open/spring/mvc/S3uploads/S3FileHandler.java b/src/main/java/com/open/spring/mvc/S3uploads/S3FileHandler.java index 62865a8f..fa2c9b82 100644 --- a/src/main/java/com/open/spring/mvc/S3uploads/S3FileHandler.java +++ b/src/main/java/com/open/spring/mvc/S3uploads/S3FileHandler.java @@ -79,6 +79,11 @@ public void init() { this.s3Client = builder.build(); } + /** Whether this server has S3 settings (AWS credentials, region and bucket). Without them nothing is stored. */ + public boolean isConfigured() { + return s3Client != null; + } + @Override public String uploadFile(String base64Data, String filename, String uid) { if (s3Client == null) { diff --git a/src/main/java/com/open/spring/mvc/groups/GroupChatService.java b/src/main/java/com/open/spring/mvc/groups/GroupChatService.java index 5f902092..f1549961 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatService.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatService.java @@ -65,14 +65,29 @@ public void initGroupStorage(String groupName) { s3FileHandler.uploadFile(emptyBase64, SHARED_FILES_PREFIX, groupName); } + /** + * Creates the group's empty messages file and shared-files/ folder if they're missing. + * Strict for the messages file: only S3's 404 means missing, and a check that failed + * throws without writing, since an empty file written over the real one would erase the + * group's history. + */ public void ensureGroupStorageExists(String groupName) { - // Check if messages.jsonl exists, if not, create it - if (!s3FileHandler.fileExists(groupName, MESSAGES_FILE)) { - String emptyBase64 = Base64.getEncoder().encodeToString(new byte[0]); - s3FileHandler.uploadFile(emptyBase64, MESSAGES_FILE, groupName); + // Without S3 settings nothing is stored, so there's nothing to check. + if (!s3FileHandler.isConfigured()) { + return; + } + + // Check if messages.jsonl exists, if not, create it. Under the group's message lock, + // so a message sent between the check and the write isn't lost under the empty file. + synchronized (messageLocks.computeIfAbsent(groupName, name -> new Object())) { + if (!s3FileHandler.fileExistsOrThrow(groupName, MESSAGES_FILE)) { + String emptyBase64 = Base64.getEncoder().encodeToString(new byte[0]); + s3FileHandler.uploadFile(emptyBase64, MESSAGES_FILE, groupName); + } } - // Check if shared-files/ folder exists, if not, create it + // Check if shared-files/ folder exists, if not, create it. Its placeholder is empty, + // so writing it again loses nothing. if (!s3FileHandler.fileExists(groupName, SHARED_FILES_PREFIX)) { String emptyBase64 = Base64.getEncoder().encodeToString(new byte[0]); s3FileHandler.uploadFile(emptyBase64, SHARED_FILES_PREFIX, groupName); diff --git a/src/test/java/com/open/spring/StartupServiceTest.java b/src/test/java/com/open/spring/StartupServiceTest.java new file mode 100644 index 00000000..163d31d0 --- /dev/null +++ b/src/test/java/com/open/spring/StartupServiceTest.java @@ -0,0 +1,291 @@ +package com.open.spring; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; +import org.springframework.boot.DefaultApplicationArguments; +import org.springframework.test.util.ReflectionTestUtils; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.open.spring.mvc.S3uploads.S3FileHandler; +import com.open.spring.mvc.groups.GroupChatMessage; +import com.open.spring.mvc.groups.GroupChatService; +import com.open.spring.mvc.groups.Groups; +import com.open.spring.mvc.groups.GroupsJpaRepository; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; +import software.amazon.awssdk.core.ResponseBytes; +import software.amazon.awssdk.core.exception.SdkClientException; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectResponse; +import software.amazon.awssdk.services.s3.model.HeadObjectRequest; +import software.amazon.awssdk.services.s3.model.HeadObjectResponse; +import software.amazon.awssdk.services.s3.model.NoSuchKeyException; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.PutObjectResponse; +import software.amazon.awssdk.services.s3.model.S3Exception; + +/** + * At every start the server checks each group's chat files in S3 and creates an empty + * messages file for a group that has none. A check that failed must not count as none: + * the empty file would replace the group's whole history. + */ +class StartupServiceTest { + + private static final String CSA_MESSAGES = "CSA/messages-images/messages.jsonl"; + private static final String ADA_LINE = "{\"id\":\"m1\",\"author\":\"Ada Lovelace\",\"author_uid\":\"ada\"," + + "\"message\":\"Meeting at 3\",\"date\":\"2026-11-21T10:00:00Z\",\"image\":null,\"edited\":false}"; + + /** S3's objects by key. The real S3FileHandler reaches them through a stand-in S3 client. */ + private final Map objects = new ConcurrentHashMap<>(); + /** Groups S3 can't answer for right now: checking any of their files throws this. */ + private final Map failingChecks = new ConcurrentHashMap<>(); + private S3Client s3; + private GroupChatService chat; + private GroupsJpaRepository groups; + + @BeforeEach + void setUp() { + s3 = mock(S3Client.class); + // As S3 answers: a key that isn't stored is a 404 NoSuchKey. + when(s3.headObject(any(HeadObjectRequest.class))).thenAnswer(call -> { + String key = call.getArgument(0).key(); + RuntimeException failure = failingChecks.get(key.substring(0, key.indexOf('/'))); + if (failure != null) { + throw failure; + } + if (!objects.containsKey(key)) { + throw notFound(); + } + return HeadObjectResponse.builder().build(); + }); + when(s3.getObjectAsBytes(any(GetObjectRequest.class))).thenAnswer(call -> { + byte[] bytes = objects.get(call.getArgument(0).key()); + if (bytes == null) { + throw notFound(); + } + return ResponseBytes.fromByteArray(GetObjectResponse.builder().build(), bytes); + }); + when(s3.putObject(any(PutObjectRequest.class), any(RequestBody.class))).thenAnswer(call -> { + store(call.getArgument(0).key(), call.getArgument(1)); + return PutObjectResponse.builder().build(); + }); + S3FileHandler storage = new S3FileHandler(); + ReflectionTestUtils.setField(storage, "s3Client", s3); + ReflectionTestUtils.setField(storage, "bucketName", "chat-test"); + chat = new GroupChatService(storage, new ObjectMapper()); + groups = mock(GroupsJpaRepository.class); + } + + @Test + void aCheckThatFailsLeavesTheHistoryAsItIs() { + // S3 throttled (503 Slow Down), failing (500), refusing (403) or out of reach: none of + // these says the file is missing. + List failures = List.of( + answered(503, "Slow Down"), + answered(500, "We encountered an internal error. Please try again."), + answered(403, "Access Denied"), + SdkClientException.create("Unable to execute HTTP request: Connect timed out")); + for (RuntimeException failure : failures) { + objects.clear(); + objects.put(CSA_MESSAGES, ADA_LINE.getBytes(StandardCharsets.UTF_8)); + failingChecks.put("CSA", failure); + + assertDoesNotThrow(() -> startUp("CSA"), failure.toString()); + + assertEquals(ADA_LINE, stored(CSA_MESSAGES), failure.toString()); + } + } + + @Test + void aCheckThatFailsIsLoggedWithTheGroupAndTheCause() throws Exception { + objects.put(CSA_MESSAGES, ADA_LINE.getBytes(StandardCharsets.UTF_8)); + RuntimeException throttle = answered(503, "Slow Down"); + failingChecks.put("CSA", throttle); + + try (Warnings warnings = new Warnings(StartupService.class)) { + startUp("CSA"); + + assertEquals(1, warnings.list().size(), warnings.messages().toString()); + ILoggingEvent warning = warnings.list().get(0); + assertTrue(warning.getFormattedMessage().contains("CSA"), warning.getFormattedMessage()); + assertEquals(throttle.getClass().getName(), warning.getThrowableProxy().getClassName()); + } + } + + @Test + void aGroupThatCantBeCheckedDoesNotStopTheOthers() throws Exception { + objects.put(CSA_MESSAGES, ADA_LINE.getBytes(StandardCharsets.UTF_8)); + failingChecks.put("CSA", answered(503, "Slow Down")); + + startUp("CSA", "CSP"); + + assertEquals(ADA_LINE, stored(CSA_MESSAGES)); + assertEquals("", stored("CSP/messages-images/messages.jsonl")); + } + + @Test + void aGroupWithNoMessagesFileYetGetsAnEmptyOne() throws Exception { + // S3's 404: nothing is stored yet, so there's no history to lose. + startUp("CSA"); + + assertEquals("", stored(CSA_MESSAGES)); + assertArrayEquals(new byte[0], objects.get("CSA/shared-files/")); + } + + @Test + void aGroupThatHasItsMessagesKeepsThem() throws Exception { + objects.put(CSA_MESSAGES, ADA_LINE.getBytes(StandardCharsets.UTF_8)); + + startUp("CSA"); + + assertEquals(ADA_LINE, stored(CSA_MESSAGES)); + } + + @Test + void aServerWithoutS3StartsQuietly() { + // A local server without S3 settings stores nothing, so there's nothing to check. + chat = new GroupChatService(new S3FileHandler(), new ObjectMapper()); + + try (Warnings warnings = new Warnings(StartupService.class, GroupChatService.class, S3FileHandler.class)) { + assertDoesNotThrow(() -> startUp("CSA", "CSP")); + assertEquals(List.of(), warnings.messages()); + } + } + + @Test + void aMessageSentWhileTheCheckCreatesTheFileIsKept() throws Exception { + // The check finds no file, but S3's answer only arrives once a send has saved a + // message (or half a second passes). An empty file written after that would erase it. + CountDownLatch checking = new CountDownLatch(1); + CountDownLatch sendSaved = new CountDownLatch(1); + doAnswer(call -> { + String key = call.getArgument(0).key(); + boolean found = objects.containsKey(key); + if (CSA_MESSAGES.equals(key)) { + checking.countDown(); + sendSaved.await(500, TimeUnit.MILLISECONDS); + } + if (!found) { + throw notFound(); + } + return HeadObjectResponse.builder().build(); + }).when(s3).headObject(any(HeadObjectRequest.class)); + doAnswer(call -> { + String key = call.getArgument(0).key(); + store(key, call.getArgument(1)); + if (CSA_MESSAGES.equals(key) && objects.get(key).length > 0) { + sendSaved.countDown(); + } + return PutObjectResponse.builder().build(); + }).when(s3).putObject(any(PutObjectRequest.class), any(RequestBody.class)); + + ExecutorService pool = Executors.newSingleThreadExecutor(); + try { + Future send = pool.submit(() -> { + checking.await(5, TimeUnit.SECONDS); + return chat.addMessage("CSA", + new GroupChatMessage("Grace Hopper", "grace", "Works for me", "2026-11-22T08:00:00Z", null)); + }); + startUp("CSA"); + send.get(10, TimeUnit.SECONDS); + } finally { + pool.shutdownNow(); + } + + assertEquals(List.of("Works for me"), + chat.getMessages("CSA").stream().map(GroupChatMessage::getMessage).toList()); + } + + /** Runs the server's start-up check over groups with these names. */ + private void startUp(String... groupNames) throws Exception { + List found = new ArrayList<>(); + for (String name : groupNames) { + Groups group = new Groups(); + group.setName(name); + found.add(group); + } + when(groups.findAll()).thenReturn(found); + new StartupService(groups, chat).initializeGroupStorage().run(new DefaultApplicationArguments()); + } + + private void store(String key, RequestBody body) throws Exception { + try (InputStream bytes = body.contentStreamProvider().newStream()) { + objects.put(key, bytes.readAllBytes()); + } + } + + private String stored(String key) { + byte[] bytes = objects.get(key); + return bytes == null ? null : new String(bytes, StandardCharsets.UTF_8); + } + + private static S3Exception answered(int status, String message) { + return (S3Exception) S3Exception.builder().statusCode(status).message(message).build(); + } + + private static S3Exception notFound() { + return (S3Exception) NoSuchKeyException.builder().statusCode(404).message("The specified key does not exist.").build(); + } + + /** The warnings the given classes log while it's open. */ + private static final class Warnings implements AutoCloseable { + private final ListAppender appender = new ListAppender<>(); + private final List loggers = new ArrayList<>(); + private final List previousLevels = new ArrayList<>(); + + Warnings(Class... types) { + appender.start(); + for (Class type : types) { + Logger logger = (Logger) LoggerFactory.getLogger(type); + previousLevels.add(logger.getLevel()); + logger.setLevel(Level.WARN); + logger.addAppender(appender); + loggers.add(logger); + } + } + + List list() { + return List.copyOf(appender.list); + } + + List messages() { + return list().stream().map(ILoggingEvent::getFormattedMessage).toList(); + } + + @Override + public void close() { + for (int i = 0; i < loggers.size(); i++) { + loggers.get(i).detachAppender(appender); + loggers.get(i).setLevel(previousLevels.get(i)); + } + appender.stop(); + } + } +} From f34470635af9fcb68cd4050b148d0f741143c6c9 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Sun, 22 Nov 2026 01:21:35 -0800 Subject: [PATCH 26/46] Group chat: a send whose read times out answers 503 like a shared file S3's RequestTimeout comes as a 400, but it means the connection was too slow, and the AWS SDK retries it like a 5xx. The shared-file check and write already count it as S3 being unavailable (isUnavailable), but the send's strict read had its own rule that only counted a 5xx, so a timed-out read got the route's 400 instead of a 503 with Retry-After. The read now uses isUnavailable too, so one check decides it for the whole group chat. The history was kept either way: only the status was wrong. The send test adds a RequestTimeout to the failures that answer 503. --- docs/group-chat-architecture.md | 2 +- .../com/open/spring/mvc/groups/GroupChatService.java | 7 +++---- .../com/open/spring/mvc/groups/GroupChatSendTest.java | 10 ++++++++-- 3 files changed, 12 insertions(+), 7 deletions(-) diff --git a/docs/group-chat-architecture.md b/docs/group-chat-architecture.md index a02faa71..8801b33e 100644 --- a/docs/group-chat-architecture.md +++ b/docs/group-chat-architecture.md @@ -156,7 +156,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) - **History is keyed by group name, not id.** Renaming a group with `PUT /api/groups/{id}` leaves its history under the old name. - **Without S3 settings** (AWS credentials, region and bucket), the server logs `S3 is disabled` at startup. Sends still broadcast live, but nothing is saved, so history and files come back empty. This is the normal state of a local server. - **At every start, `StartupService` creates any missing chat files.** It checks each group and writes an empty messages file and `shared-files/` placeholder where they're missing; the four course groups that `ModelInit` seeds start with none. The check of the messages file is strict (`S3FileHandler.fileExistsOrThrow`), since an empty file written over the real one would erase the group's history: only S3's 404 means there is no file. Any other failure to check (a throttle, a 5xx, a timeout, S3 refusing it) is logged with the group's name and leaves that group as it is (the next start checks it again), and the other groups are still checked. The check holds the group's message lock, so a message sent while the server is starting isn't written over. Without S3 settings nothing is checked. -- **Every new message rewrites the whole file**, read then write. Sending, editing and deleting take one lock per group (`messageLocks` in `GroupChatService`), so two at once keep both changes. The lock only holds within one server: several servers writing the same bucket would need S3's conditional writes. A send reads the file strictly (`S3FileHandler.decodeFileOrThrow`), since writing back an empty read would replace the whole history: only S3's 404 reads as no messages yet, and any other failure to read refuses the send. When S3 timed out, couldn't be reached or answered with a 5xx, that's a 503 with `Retry-After` (`MessagesReadFailedException`); S3 refusing the read (a 4xx) or a bug here gets the route's usual 400. Edits and deletes still read with `decodeFile`, which answers a failed read the same as a missing file, so after one they find nothing to change and write nothing. +- **Every new message rewrites the whole file**, read then write. Sending, editing and deleting take one lock per group (`messageLocks` in `GroupChatService`), so two at once keep both changes. The lock only holds within one server: several servers writing the same bucket would need S3's conditional writes. A send reads the file strictly (`S3FileHandler.decodeFileOrThrow`), since writing back an empty read would replace the whole history: only S3's 404 reads as no messages yet, and any other failure to read refuses the send. When S3 timed out (its own `RequestTimeout` comes as a 400), couldn't be reached or answered with a 5xx, that's a 503 with `Retry-After` (`MessagesReadFailedException`), by the same rule as shared files; S3 refusing the read (any other 4xx) or a bug here gets the route's usual 400. Edits and deletes still read with `decodeFile`, which answers a failed read the same as a missing file, so after one they find nothing to change and write nothing. - **A shared file's bytes never go over the socket.** `sendFileServer` names the file and its size; a member downloads it from `/files/content`. Sending the bytes to every subscriber could overflow a session's 512 KB send buffer while another frame was queued, and Spring closes a session that overflows. ## Testing diff --git a/src/main/java/com/open/spring/mvc/groups/GroupChatService.java b/src/main/java/com/open/spring/mvc/groups/GroupChatService.java index afc92eee..d49755a6 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatService.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatService.java @@ -104,9 +104,8 @@ public List getMessages(String groupName) { /** * The group's messages for a send, which writes the whole file back. Strict: a read that * failed throws rather than reading as an empty chat, which the send would save over the - * history. Only S3's 404 means no messages yet. S3 out of reach or answering a 5xx is - * something to wait out, so that throws MessagesReadFailedException; anything else goes up - * as it is. + * history. Only S3's 404 means no messages yet. S3 being unavailable for a moment (see + * isUnavailable) throws MessagesReadFailedException; anything else goes up as it is. */ private List readMessagesOrThrow(String groupName) { String base64Data; @@ -115,7 +114,7 @@ private List readMessagesOrThrow(String groupName) { } catch (SdkClientException | S3Exception e) { // Logged for every failure: the route answers a refused read without logging it. log.warn("Could not read the messages of group {}", groupName, e); - if (e instanceof S3Exception answered && answered.statusCode() < 500) { + if (!isUnavailable(e)) { // S3 refused the request (no permission, a bad key): waiting won't fix that. throw e; } diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java index 05c32271..56c6b6bc 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java @@ -37,6 +37,7 @@ import com.open.spring.mvc.person.Person; import com.open.spring.mvc.person.PersonJpaRepository; +import software.amazon.awssdk.awscore.exception.AwsErrorDetails; import software.amazon.awssdk.core.ResponseBytes; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.sync.RequestBody; @@ -134,10 +135,15 @@ private String storedMessages() { @Test void aReadThatFailsRefusesTheSendWithA503AndKeepsTheHistory() { - // S3 throttled (503 Slow Down) or out of reach: failures that clear if you wait. + // S3 throttled (503 Slow Down), out of reach, or timing out the request (its RequestTimeout + // comes as a 400): failures that clear if you wait. List failures = List.of( (S3Exception) S3Exception.builder().statusCode(503).message("Slow Down").build(), - SdkClientException.create("Unable to execute HTTP request: Read timed out")); + SdkClientException.create("Unable to execute HTTP request: Read timed out"), + (S3Exception) S3Exception.builder().statusCode(400) + .awsErrorDetails(AwsErrorDetails.builder().errorCode("RequestTimeout").build()) + .message("Your socket connection to the server was not read from or written to within the timeout period.") + .build()); for (RuntimeException failure : failures) { useFreshStorage(); objects.put(MESSAGES_KEY, ADA_LINE.getBytes(StandardCharsets.UTF_8)); From 1bc72b0171b8b16e706f6005e80c6559b1d953e0 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Sun, 22 Nov 2026 01:07:21 -0800 Subject: [PATCH 27/46] Group chat docs: the start-up check writes only over a missing file The storage notes now say StartupService creates a group's empty messages file and shared-files/ placeholder only when S3 answers 404 (fileExistsOrThrow). Any other failure to check is logged and leaves that group as it is, the other groups are still checked, the check holds the group's message lock, and a server without S3 settings checks nothing. The testing list gets a bullet for StartupServiceTest, with its command. --- docs/group-chat-architecture.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/group-chat-architecture.md b/docs/group-chat-architecture.md index 2ed3e467..67f977ad 100644 --- a/docs/group-chat-architecture.md +++ b/docs/group-chat-architecture.md @@ -155,6 +155,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) - **History is keyed by group name, not id.** Renaming a group with `PUT /api/groups/{id}` leaves its history under the old name. - **Without S3 settings** (AWS credentials, region and bucket), the server logs `S3 is disabled` at startup. Sends still broadcast live, but nothing is saved, so history and files come back empty. This is the normal state of a local server. +- **At every start, `StartupService` creates any missing chat files.** It checks each group and writes an empty messages file and `shared-files/` placeholder where they're missing; the four course groups that `ModelInit` seeds start with none. The check of the messages file is strict (`S3FileHandler.fileExistsOrThrow`), since an empty file written over the real one would erase the group's history: only S3's 404 means there is no file. Any other failure to check (a throttle, a 5xx, a timeout, S3 refusing it) is logged with the group's name and leaves that group as it is (the next start checks it again), and the other groups are still checked. The check holds the group's message lock, so a message sent while the server is starting isn't written over. Without S3 settings nothing is checked. - **Every new message rewrites the whole file**, read then write. Sending, editing and deleting take one lock per group (`messageLocks` in `GroupChatService`), so two at once keep both changes. The lock only holds within one server: several servers writing the same bucket would need S3's conditional writes. A send reads the file strictly (`S3FileHandler.decodeFileOrThrow`), since writing back an empty read would replace the whole history: only S3's 404 reads as no messages yet, and any other failure to read refuses the send. When S3 timed out, couldn't be reached or answered with a 5xx, that's a 503 with `Retry-After` (`MessagesReadFailedException`); S3 refusing the read (a 4xx) or a bug here gets the route's usual 400. Edits and deletes still read with `decodeFile`, which answers a failed read the same as a missing file, so after one they find nothing to change and write nothing. - **A shared file's bytes never go over the socket.** `sendFileServer` names the file and its size; a member downloads it from `/files/content`. Sending the bytes to every subscriber could overflow a session's 512 KB send buffer while another frame was queued, and Spring closes a session that overflows. @@ -165,6 +166,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) - Run the chat regression tests with `./mvnw test '-Dtest=GroupChat*Test'`. They cover UID-based ownership, REST identity forwarding and unread counts. `GroupChatFilesTest` covers the file index, one-file downloads, the path rules, the bytes-free frame, uploads that land together, a path that is already shared, two uploads of one path at once, and a check that fails; `S3FileHandlerExistsTest` covers the strict check. - `GroupChatServiceTest` covers two sends, an edit and a send, and a delete and a send landing at once. - `GroupChatSendTest` sends through the controller to a real `S3FileHandler` over a stand-in S3 client: a read that fails, a read S3 refuses, a bug, a group with no messages file yet, and a server without S3. `S3FileHandlerDecodeTest` covers the strict read. Run the S3 handler tests with `./mvnw test '-Dtest=S3FileHandler*Test'`. +- `StartupServiceTest` runs the start-up check over a real `S3FileHandler` and a stand-in S3 client: checks that fail, a group that can't be checked among others, a group with no messages file yet, a group that has one, a server without S3, and a send during the check. Run it with `./mvnw test '-Dtest=StartupServiceTest'`. ## Known issues From 6a48a1428dbfa393760f2ff3136ad6aff8731c13 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Sun, 22 Nov 2026 01:26:21 -0800 Subject: [PATCH 28/46] Group files: note that a write that timed out may still be stored S3 can store a shared file and then fail to answer, and the AWS SDK's own retries can fail too. The upload then answers 503 without a "shared by" record or a sendFileServer frame, and sharing it again finds the path taken (409), which the page handles like any other taken name. Nothing is lost, and the old 500 ended the same way. Recognizing "this stored file is mine" on a retry would need a way to match the stored copy to the upload, so for now the doc and a comment at the write say what happens. --- docs/group-chat-architecture.md | 1 + src/main/java/com/open/spring/mvc/groups/GroupChatService.java | 2 ++ 2 files changed, 3 insertions(+) diff --git a/docs/group-chat-architecture.md b/docs/group-chat-architecture.md index 8801b33e..a5036c49 100644 --- a/docs/group-chat-architecture.md +++ b/docs/group-chat-architecture.md @@ -158,6 +158,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) - **At every start, `StartupService` creates any missing chat files.** It checks each group and writes an empty messages file and `shared-files/` placeholder where they're missing; the four course groups that `ModelInit` seeds start with none. The check of the messages file is strict (`S3FileHandler.fileExistsOrThrow`), since an empty file written over the real one would erase the group's history: only S3's 404 means there is no file. Any other failure to check (a throttle, a 5xx, a timeout, S3 refusing it) is logged with the group's name and leaves that group as it is (the next start checks it again), and the other groups are still checked. The check holds the group's message lock, so a message sent while the server is starting isn't written over. Without S3 settings nothing is checked. - **Every new message rewrites the whole file**, read then write. Sending, editing and deleting take one lock per group (`messageLocks` in `GroupChatService`), so two at once keep both changes. The lock only holds within one server: several servers writing the same bucket would need S3's conditional writes. A send reads the file strictly (`S3FileHandler.decodeFileOrThrow`), since writing back an empty read would replace the whole history: only S3's 404 reads as no messages yet, and any other failure to read refuses the send. When S3 timed out (its own `RequestTimeout` comes as a 400), couldn't be reached or answered with a 5xx, that's a 503 with `Retry-After` (`MessagesReadFailedException`), by the same rule as shared files; S3 refusing the read (any other 4xx) or a bug here gets the route's usual 400. Edits and deletes still read with `decodeFile`, which answers a failed read the same as a missing file, so after one they find nothing to change and write nothing. - **A shared file's bytes never go over the socket.** `sendFileServer` names the file and its size; a member downloads it from `/files/content`. Sending the bytes to every subscriber could overflow a session's 512 KB send buffer while another frame was queued, and Spring closes a session that overflows. +- **A shared file whose write timed out may still be stored.** S3 can store a file and then fail to answer, and the AWS SDK's own retries can fail too. The upload then answers 503 without a "shared by" record or a `sendFileServer` frame, and sharing it again finds the path taken (409), which the page handles like any other taken name. ## Testing diff --git a/src/main/java/com/open/spring/mvc/groups/GroupChatService.java b/src/main/java/com/open/spring/mvc/groups/GroupChatService.java index d49755a6..e64d59e0 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatService.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatService.java @@ -353,6 +353,8 @@ private String store(String groupName, String path, String base64Data) { try { return s3FileHandler.uploadFileOrThrow(base64Data, SHARED_FILES_PREFIX + path, groupName); } catch (RuntimeException e) { + // A write that timed out may still be stored (S3 lost its answer). Sharing it again + // then gets a 409, which the page handles like any other taken name. log.warn("Could not store {} in group {}", path, groupName, e); if (isUnavailable(e)) { throw new SharedFileStorageUnavailableException(path, e); From a8f1c657bc0bf143f88d19563f1c2fd7b633f4ce Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Wed, 25 Nov 2026 19:55:32 -0800 Subject: [PATCH 29/46] Group chat: a send, edit or delete answers 503 when S3 can't save it Sending, editing and deleting a message each read the group's messages file and save it back. The save used S3FileHandler.uploadFile, which catches every failure and answers null, so when S3 throttled, timed out or couldn't be reached on the upload, the route still answered 200: a send showed live and was gone after a reload, and an edit or a delete came back after one. Edits and deletes also read with the lenient decodeFile, so a failed read answered an edit with 404 and a delete with 200 (and told the group it was deleted). All three now read with readMessagesOrThrow and save with a strict writeMessagesOrThrow (uploadFileOrThrow). S3 being unavailable on either (isUnavailable) throws MessagesStorageUnavailableException, the renamed MessagesReadFailedException, and the send, edit and delete routes answer 503 with Retry-After. Nothing is broadcast. S3 refusing the request or a bug here still gets the route's usual 400, and the strict read now logs every failure, a bug included, the way the save does. Without S3 settings nothing is saved, and the chat still works live. A save that timed out may still be stored, so a send tried again can show up twice. That's easier to see than a message lost quietly. Tests: GroupChatSendTest adds an upload that fails after a good read, and GroupChatEditDeleteTest covers edits and deletes whose read or upload fails, that both still save when S3 is up, and that every failed read or upload is logged. The S3 failure lists move to S3Failures. GroupChatServiceTest, GroupChatMessageJsonTest and GroupChatRegressionTest now stand in for a configured S3 through the strict read and write; the regression test saves each upload back into its list, so its checks on what's stored can still fail. --- .../mvc/groups/GroupChatApiController.java | 27 +- .../spring/mvc/groups/GroupChatService.java | 77 +++--- .../groups/MessagesReadFailedException.java | 14 - .../MessagesStorageUnavailableException.java | 15 ++ .../mvc/groups/GroupChatEditDeleteTest.java | 241 ++++++++++++++++++ .../mvc/groups/GroupChatMessageJsonTest.java | 3 +- .../mvc/groups/GroupChatRegressionTest.java | 68 ++++- .../spring/mvc/groups/GroupChatSendTest.java | 57 +++-- .../mvc/groups/GroupChatServiceTest.java | 10 +- .../open/spring/mvc/groups/S3Failures.java | 35 +++ 10 files changed, 461 insertions(+), 86 deletions(-) delete mode 100644 src/main/java/com/open/spring/mvc/groups/MessagesReadFailedException.java create mode 100644 src/main/java/com/open/spring/mvc/groups/MessagesStorageUnavailableException.java create mode 100644 src/test/java/com/open/spring/mvc/groups/GroupChatEditDeleteTest.java create mode 100644 src/test/java/com/open/spring/mvc/groups/S3Failures.java 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 fcc528e3..08f5aca8 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java @@ -39,8 +39,8 @@ public class GroupChatApiController { // How long to wait before trying again when S3 was unavailable for a moment, checking or - // writing a shared file or reading a group's messages: a throttle or a short outage clears - // in seconds. + // writing a shared file or reading or saving a group's messages: a throttle or a short + // outage clears in seconds. private static final int RETRY_AFTER_SECONDS = 5; private final GroupChatService groupChatService; @@ -193,12 +193,8 @@ public ResponseEntity postMessage( try { realtimeService.publishMessage(groupId, message.getMessage(), message.getImage(), identity); - } catch (MessagesReadFailedException ex) { - // S3 couldn't read the history, so nothing was saved or broadcast: saving would have - // replaced it. That's S3 being unavailable for a moment, not a bug here: a 503, and when. - return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE) - .header(HttpHeaders.RETRY_AFTER, String.valueOf(RETRY_AFTER_SECONDS)) - .body(ex.getMessage()); + } catch (MessagesStorageUnavailableException ex) { + return tryAgainLater(ex); } catch (RuntimeException ex) { return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST); } @@ -232,6 +228,8 @@ public ResponseEntity editMessage( updated = realtimeService.editMessage(groupId, messageId, request.getMessage(), identity.getUid()); } catch (SecurityException ex) { return new ResponseEntity<>(HttpStatus.FORBIDDEN); + } catch (MessagesStorageUnavailableException ex) { + return tryAgainLater(ex); } catch (RuntimeException ex) { return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST); } @@ -262,6 +260,8 @@ public ResponseEntity deleteMessage( realtimeService.deleteMessage(groupId, messageId, identity.getUid()); } catch (SecurityException ex) { return new ResponseEntity<>(HttpStatus.FORBIDDEN); + } catch (MessagesStorageUnavailableException ex) { + return tryAgainLater(ex); } catch (RuntimeException ex) { return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST); } @@ -269,6 +269,17 @@ public ResponseEntity deleteMessage( return new ResponseEntity<>(HttpStatus.OK); } + /** + * S3 couldn't read or save the group's messages, so the change isn't broadcast (a save that + * timed out may still be stored). That's S3 being unavailable for a moment, not a bug here: + * a 503, and when to try again. + */ + private static ResponseEntity tryAgainLater(MessagesStorageUnavailableException ex) { + return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE) + .header(HttpHeaders.RETRY_AFTER, String.valueOf(RETRY_AFTER_SECONDS)) + .body(ex.getMessage()); + } + /** * Unread counts for the signed-in member's own groups, keyed by group id. Groups * with nothing unread are left out, so an empty map means nothing is waiting. diff --git a/src/main/java/com/open/spring/mvc/groups/GroupChatService.java b/src/main/java/com/open/spring/mvc/groups/GroupChatService.java index e64d59e0..9486c094 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatService.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatService.java @@ -102,27 +102,56 @@ public List getMessages(String groupName) { } /** - * The group's messages for a send, which writes the whole file back. Strict: a read that - * failed throws rather than reading as an empty chat, which the send would save over the - * history. Only S3's 404 means no messages yet. S3 being unavailable for a moment (see - * isUnavailable) throws MessagesReadFailedException; anything else goes up as it is. + * The group's messages for a send, an edit or a delete, which write the whole file back. + * Strict: a read that failed throws rather than reading as an empty chat, which a send would + * save over the history and an edit or delete would answer as "not found". Only S3's 404 + * means no messages yet. S3 being unavailable for a moment (see isUnavailable) throws + * MessagesStorageUnavailableException; anything else goes up as it is. */ private List readMessagesOrThrow(String groupName) { String base64Data; try { base64Data = s3FileHandler.decodeFileOrThrow(groupName, MESSAGES_FILE); - } catch (SdkClientException | S3Exception e) { - // Logged for every failure: the route answers a refused read without logging it. + } catch (RuntimeException e) { + // Logged for every failure: the route answers a refused read or a bug without logging it. log.warn("Could not read the messages of group {}", groupName, e); if (!isUnavailable(e)) { - // S3 refused the request (no permission, a bad key): waiting won't fix that. + // S3 refused the request (no permission, a bad key) or a bug here: waiting won't fix that. throw e; } - throw new MessagesReadFailedException(e); + throw new MessagesStorageUnavailableException(e); } return parseMessages(groupName, base64Data); } + /** + * Saves the group's whole messages file. Strict: a write that failed throws, so a send, an + * edit or a delete isn't answered as saved when it wasn't. S3 being unavailable for a moment + * (see isUnavailable) throws MessagesStorageUnavailableException; anything else goes up as + * it is. Without S3 settings nothing is stored, and the chat still works live. + */ + private void writeMessagesOrThrow(String groupName, List messages) { + if (!s3FileHandler.isConfigured()) { + return; + } + String jsonl = messages.stream() + .map(this::toJson) + .collect(Collectors.joining("\n")); + String base64Data = Base64.getEncoder().encodeToString(jsonl.getBytes(StandardCharsets.UTF_8)); + try { + s3FileHandler.uploadFileOrThrow(base64Data, MESSAGES_FILE, groupName); + } catch (RuntimeException e) { + // A write that timed out may still be stored (S3 lost its answer), so a send tried + // again can show up twice. That's easier to see and fix than a message lost quietly. + log.warn("Could not save the messages of group {}", groupName, e); + if (!isUnavailable(e)) { + // S3 refused the request (no permission, a bad key) or a bug here: waiting won't fix that. + throw e; + } + throw new MessagesStorageUnavailableException(e); + } + } + private List parseMessages(String groupName, String base64Data) { if (base64Data == null || base64Data.isBlank()) { return new ArrayList<>(); @@ -164,15 +193,7 @@ public List addMessage(String groupName, GroupChatMessage mess synchronized (messageLocks.computeIfAbsent(groupName, name -> new Object())) { List messages = readMessagesOrThrow(groupName); messages.add(message); - - String jsonl = messages.stream() - .map(this::toJson) - .collect(Collectors.joining("\n")); - - String base64Data = Base64.getEncoder() - .encodeToString(jsonl.getBytes(StandardCharsets.UTF_8)); - - s3FileHandler.uploadFile(base64Data, MESSAGES_FILE, groupName); + writeMessagesOrThrow(groupName, messages); return messages; } } @@ -185,7 +206,7 @@ public List addMessage(String groupName, GroupChatMessage mess public boolean editMessage(String groupName, String messageId, String newMessage, String requesterUid) { if (messageId == null) return false; synchronized (messageLocks.computeIfAbsent(groupName, name -> new Object())) { - List messages = getMessages(groupName); + List messages = readMessagesOrThrow(groupName); boolean found = false; for (GroupChatMessage m : messages) { if (messageId.equals(m.getId())) { @@ -200,14 +221,7 @@ public boolean editMessage(String groupName, String messageId, String newMessage } if (found) { - String jsonl = messages.stream() - .map(this::toJson) - .collect(Collectors.joining("\n")); - - String base64Data = Base64.getEncoder() - .encodeToString(jsonl.getBytes(StandardCharsets.UTF_8)); - - s3FileHandler.uploadFile(base64Data, MESSAGES_FILE, groupName); + writeMessagesOrThrow(groupName, messages); } return found; } @@ -217,7 +231,7 @@ public boolean editMessage(String groupName, String messageId, String newMessage public void deleteMessage(String groupName, String messageId, String requesterUid) { if (messageId == null) return; synchronized (messageLocks.computeIfAbsent(groupName, name -> new Object())) { - List messages = getMessages(groupName); + List messages = readMessagesOrThrow(groupName); GroupChatMessage target = messages.stream() .filter(m -> messageId.equals(m.getId())) @@ -231,14 +245,7 @@ public void deleteMessage(String groupName, String messageId, String requesterUi boolean removed = messages.remove(target); if (removed) { - String jsonl = messages.stream() - .map(this::toJson) - .collect(Collectors.joining("\n")); - - String base64Data = Base64.getEncoder() - .encodeToString(jsonl.getBytes(StandardCharsets.UTF_8)); - - s3FileHandler.uploadFile(base64Data, MESSAGES_FILE, groupName); + writeMessagesOrThrow(groupName, messages); } } } diff --git a/src/main/java/com/open/spring/mvc/groups/MessagesReadFailedException.java b/src/main/java/com/open/spring/mvc/groups/MessagesReadFailedException.java deleted file mode 100644 index f74fcda8..00000000 --- a/src/main/java/com/open/spring/mvc/groups/MessagesReadFailedException.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.open.spring.mvc.groups; - -/** - * S3 couldn't read a group's messages for now: it timed out, couldn't be reached or answered - * with a 5xx (a throttle, an outage). A send writes the whole messages file back, so it's refused - * rather than save the new message over the history, and the API answers 503 with Retry-After, - * since S3 being unavailable for a moment isn't a bug in this server. - */ -public class MessagesReadFailedException extends RuntimeException { - - public MessagesReadFailedException(Throwable cause) { - super("Could not read this group's messages, so the message was not sent. Try again in a moment.", cause); - } -} diff --git a/src/main/java/com/open/spring/mvc/groups/MessagesStorageUnavailableException.java b/src/main/java/com/open/spring/mvc/groups/MessagesStorageUnavailableException.java new file mode 100644 index 00000000..93274a54 --- /dev/null +++ b/src/main/java/com/open/spring/mvc/groups/MessagesStorageUnavailableException.java @@ -0,0 +1,15 @@ +package com.open.spring.mvc.groups; + +/** + * S3 couldn't read or save a group's messages for now: it timed out, couldn't be reached or + * answered with a 5xx (a throttle, an outage). Sending, editing and deleting a message each read + * the whole messages file and write it back, so the change is refused rather than half done, and + * the API answers 503 with Retry-After, since S3 being unavailable for a moment isn't a bug in + * this server. + */ +public class MessagesStorageUnavailableException extends RuntimeException { + + public MessagesStorageUnavailableException(Throwable cause) { + super("Could not save this change to the group's chat right now. Try again in a moment.", cause); + } +} diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatEditDeleteTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatEditDeleteTest.java new file mode 100644 index 00000000..2718c2f0 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatEditDeleteTest.java @@ -0,0 +1,241 @@ +package com.open.spring.mvc.groups; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.messaging.simp.SimpMessagingTemplate; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.test.util.ReflectionTestUtils; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.open.spring.mvc.S3uploads.S3FileHandler; +import com.open.spring.mvc.person.Person; +import com.open.spring.mvc.person.PersonJpaRepository; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; +import software.amazon.awssdk.core.ResponseBytes; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectResponse; +import software.amazon.awssdk.services.s3.model.NoSuchKeyException; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.PutObjectResponse; + +/** + * Editing and deleting a message read the group's whole messages file, change it and write the + * file back. When S3 can't do either for a moment, the route must say so (503) instead of + * answering as if the change was saved. + */ +class GroupChatEditDeleteTest { + + private static final String MESSAGES_KEY = "CSA/messages-images/messages.jsonl"; + private static final String GRACE_LINE = "{\"id\":\"m2\",\"author\":\"Grace Hopper\",\"author_uid\":\"grace\"," + + "\"message\":\"Meetign at 3\",\"date\":\"2026-11-21T10:05:00Z\",\"image\":null,\"edited\":false}"; + + /** S3's objects by key. The real S3FileHandler reads and writes them through a stand-in S3 client. */ + private final Map objects = new ConcurrentHashMap<>(); + private S3Client s3; + private SimpMessagingTemplate messaging; + private GroupChatApiController controller; + + @BeforeEach + void setUp() { + useFreshStorage(); + } + + @AfterEach + void signOut() { + SecurityContextHolder.clearContext(); + } + + /** Grace's message in a bucket behind a real S3FileHandler, as S3 answers: a missing key is a 404. */ + private void useFreshStorage() { + objects.clear(); + objects.put(MESSAGES_KEY, GRACE_LINE.getBytes(StandardCharsets.UTF_8)); + s3 = mock(S3Client.class); + when(s3.getObjectAsBytes(any(GetObjectRequest.class))).thenAnswer(call -> { + byte[] bytes = objects.get(call.getArgument(0).key()); + if (bytes == null) { + throw NoSuchKeyException.builder().statusCode(404).message("The specified key does not exist.").build(); + } + return ResponseBytes.fromByteArray(GetObjectResponse.builder().build(), bytes); + }); + when(s3.putObject(any(PutObjectRequest.class), any(RequestBody.class))).thenAnswer(call -> { + try (InputStream body = call.getArgument(1).contentStreamProvider().newStream()) { + objects.put(call.getArgument(0).key(), body.readAllBytes()); + } + return PutObjectResponse.builder().build(); + }); + S3FileHandler storage = new S3FileHandler(); + ReflectionTestUtils.setField(storage, "s3Client", s3); + ReflectionTestUtils.setField(storage, "bucketName", "chat-test"); + + GroupChatService chat = new GroupChatService(storage, new ObjectMapper()); + GroupsJpaRepository groups = mock(GroupsJpaRepository.class); + messaging = mock(SimpMessagingTemplate.class); + // Built from whatever their constructors take, so a new dependency elsewhere doesn't break this test. + GroupChatRealtimeService realtime = TestBeans.build(GroupChatRealtimeService.class, chat, groups, messaging); + GroupChatReadService reads = TestBeans.build(GroupChatReadService.class, + mock(GroupChatReadStateJpaRepository.class), groups, chat); + PersonJpaRepository people = mock(PersonJpaRepository.class); + controller = TestBeans.build(GroupChatApiController.class, chat, realtime, reads, groups, people); + + Groups group = new Groups(); + group.setName("CSA"); + when(groups.findById(7L)).thenReturn(Optional.of(group)); + Person grace = new Person(); + grace.setUid("grace"); + grace.setName("Grace Hopper"); + when(people.findByUid("grace")).thenReturn(grace); + SecurityContextHolder.getContext().setAuthentication( + new UsernamePasswordAuthenticationToken("grace", null, List.of())); + } + + private ResponseEntity edit() { + GroupChatMessage request = new GroupChatMessage(); + request.setMessage("Meeting at 3"); + return controller.editMessage(7L, "m2", request); + } + + private ResponseEntity delete() { + return controller.deleteMessage(7L, "m2"); + } + + private String storedMessages() { + byte[] bytes = objects.get(MESSAGES_KEY); + return bytes == null ? null : new String(bytes, StandardCharsets.UTF_8); + } + + /** S3 fails the read of the messages file, or the upload after it. */ + private void failS3(boolean onRead, RuntimeException failure) { + if (onRead) { + doThrow(failure).when(s3).getObjectAsBytes(any(GetObjectRequest.class)); + } else { + doThrow(failure).when(s3).putObject(any(PutObjectRequest.class), any(RequestBody.class)); + } + } + + /** S3 failing for a moment, on the read or the upload, gets a 503 with Retry-After and changes nothing. */ + private void assertRefusedForNow(Supplier> change) { + for (boolean onRead : List.of(true, false)) { + for (RuntimeException failure : S3Failures.unavailable()) { + useFreshStorage(); + failS3(onRead, failure); + String what = (onRead ? "read: " : "upload: ") + failure; + + ResponseEntity response = change.get(); + + assertEquals(HttpStatus.SERVICE_UNAVAILABLE, response.getStatusCode(), what); + String retryAfter = response.getHeaders().getFirst(HttpHeaders.RETRY_AFTER); + assertTrue(retryAfter != null && retryAfter.matches("[1-9][0-9]*"), what + ", Retry-After: " + retryAfter); + assertEquals(GRACE_LINE, storedMessages(), what); + // The group isn't told about a change that wasn't saved. + verify(messaging, never()).convertAndSend(any(String.class), any(Object.class)); + } + } + } + + @Test + void anEditAndADeleteAreSavedWhenS3IsUp() throws Exception { + assertEquals(HttpStatus.OK, edit().getStatusCode()); + GroupChatMessage saved = new ObjectMapper().readValue(storedMessages(), GroupChatMessage.class); + assertEquals("Meeting at 3", saved.getMessage()); + assertTrue(saved.isEdited()); + + assertEquals(HttpStatus.OK, delete().getStatusCode()); + assertEquals("", storedMessages()); + } + + @Test + void anEditS3CantReadOrSaveForAMomentAnswers503AndChangesNothing() { + assertRefusedForNow(this::edit); + } + + @Test + void aDeleteS3CantReadOrSaveForAMomentAnswers503AndKeepsTheMessage() { + assertRefusedForNow(this::delete); + } + + @Test + void anEditOrDeleteS3RefusesOrABugHereIsNotOfferedARetry() { + List>> changes = List.of(this::edit, this::delete); + for (Supplier> change : changes) { + for (boolean onRead : List.of(true, false)) { + for (RuntimeException fault : S3Failures.refusalsAndBugs()) { + useFreshStorage(); + failS3(onRead, fault); + String what = (onRead ? "read: " : "upload: ") + fault; + + ResponseEntity response = change.get(); + + assertFalse(response.getStatusCode().is2xxSuccessful(), what); + assertNotEquals(HttpStatus.SERVICE_UNAVAILABLE, response.getStatusCode(), what); + assertNull(response.getHeaders().getFirst(HttpHeaders.RETRY_AFTER), what); + assertEquals(GRACE_LINE, storedMessages(), what); + verify(messaging, never()).convertAndSend(any(String.class), any(Object.class)); + } + } + } + } + + @Test + void everyReadOrUploadThatFailsIsLoggedWithTheGroupAndTheCause() { + Logger logger = (Logger) LoggerFactory.getLogger(GroupChatService.class); + ListAppender warnings = new ListAppender<>(); + warnings.start(); + logger.addAppender(warnings); + try { + List failures = new ArrayList<>(S3Failures.unavailable()); + failures.addAll(S3Failures.refusalsAndBugs()); + for (boolean onRead : List.of(true, false)) { + for (RuntimeException failure : failures) { + useFreshStorage(); + failS3(onRead, failure); + warnings.list.clear(); + + edit(); + + String what = (onRead ? "read: " : "upload: ") + failure; + // The route answers some of these without logging, so the service logs each one. + assertTrue(warnings.list.stream().anyMatch(warning -> + warning.getFormattedMessage().contains("CSA") + && warning.getThrowableProxy() != null + && failure.getClass().getName().equals(warning.getThrowableProxy().getClassName())), + what + " was not logged: " + warnings.list); + } + } + } finally { + logger.detachAppender(warnings); + warnings.stop(); + } + } +} diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatMessageJsonTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatMessageJsonTest.java index 943a977e..068ed7cf 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupChatMessageJsonTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatMessageJsonTest.java @@ -54,6 +54,7 @@ void messageIsWrittenWithAuthorNotName() throws Exception { @Test void addingAMessageKeepsTheSenderOfOlderLines() throws Exception { S3FileHandler s3 = mock(S3FileHandler.class); + when(s3.isConfigured()).thenReturn(true); when(s3.decodeFileOrThrow("CSA", "messages-images/messages.jsonl")).thenReturn( Base64.getEncoder().encodeToString(SAVED_BEFORE_RENAME.getBytes(StandardCharsets.UTF_8))); GroupChatService service = new GroupChatService(s3, objectMapper); @@ -61,7 +62,7 @@ void addingAMessageKeepsTheSenderOfOlderLines() throws Exception { service.addMessage("CSA", new GroupChatMessage("Grace Hopper", "hop", "hello", "2026-10-30T17:00:00Z", null)); ArgumentCaptor uploaded = ArgumentCaptor.forClass(String.class); - verify(s3).uploadFile(uploaded.capture(), eq("messages-images/messages.jsonl"), eq("CSA")); + verify(s3).uploadFileOrThrow(uploaded.capture(), eq("messages-images/messages.jsonl"), eq("CSA")); String[] lines = new String(Base64.getDecoder().decode(uploaded.getValue()), StandardCharsets.UTF_8).split("\n"); assertEquals("Ada Lovelace", objectMapper.readTree(lines[0]).get("author").asText()); assertEquals("Grace Hopper", objectMapper.readTree(lines[1]).get("author").asText()); diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatRegressionTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatRegressionTest.java index c310e301..4959583f 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupChatRegressionTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatRegressionTest.java @@ -5,6 +5,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -13,14 +14,18 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; +import java.util.Base64; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.stream.Collectors; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; import org.springframework.http.HttpStatus; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; @@ -32,6 +37,8 @@ import com.open.spring.mvc.person.PersonJpaRepository; class GroupChatRegressionTest { + private static final String MESSAGES_FILE = "messages-images/messages.jsonl"; + private S3FileHandler storage; private GroupChatService chat; private GroupsJpaRepository groups; @@ -74,6 +81,49 @@ void setUp() { "2026-10-30T00:00:00Z", null); messages = new ArrayList<>(List.of(message)); doReturn(messages).when(chat).getMessages("CSA"); + // Edits and deletes read the messages file strictly and save it back, so S3 stands in + // for both: a read answers what's in `messages` at that moment, and a save replaces it. + when(storage.isConfigured()).thenReturn(true); + when(storage.decodeFileOrThrow("CSA", MESSAGES_FILE)).thenAnswer(call -> jsonlBase64(messages)); + doAnswer(call -> { + List saved = parse(call.getArgument(0)); + messages.clear(); + messages.addAll(saved); + return MESSAGES_FILE; + }).when(storage).uploadFileOrThrow(anyString(), eq(MESSAGES_FILE), eq("CSA")); + } + + private String jsonlBase64(List stored) throws Exception { + ObjectMapper json = new ObjectMapper(); + String jsonl = stored.stream().map(m -> { + try { + return json.writeValueAsString(m); + } catch (Exception e) { + throw new IllegalStateException(e); + } + }).collect(Collectors.joining("\n")); + return Base64.getEncoder().encodeToString(jsonl.getBytes(StandardCharsets.UTF_8)); + } + + /** The messages each save wrote, in order. */ + private List> saves(int expected) throws Exception { + ArgumentCaptor uploaded = ArgumentCaptor.forClass(String.class); + verify(storage, times(expected)).uploadFileOrThrow(uploaded.capture(), eq(MESSAGES_FILE), eq("CSA")); + List> saves = new ArrayList<>(); + for (String base64 : uploaded.getAllValues()) { + saves.add(parse(base64)); + } + return saves; + } + + private static List parse(String base64) throws Exception { + ObjectMapper json = new ObjectMapper(); + String jsonl = new String(Base64.getDecoder().decode(base64), StandardCharsets.UTF_8); + List saved = new ArrayList<>(); + for (String line : jsonl.split("\n")) { + if (!line.isBlank()) saved.add(json.readValue(line, GroupChatMessage.class)); + } + return saved; } @AfterEach @@ -82,18 +132,20 @@ void clearAuthentication() { } @Test - void ownerCanEditAndDeleteThroughRestAfterDisplayNameChange() { + void ownerCanEditAndDeleteThroughRestAfterDisplayNameChange() throws Exception { person.setName("Renamed Owner"); signIn("owner"); GroupChatMessage request = new GroupChatMessage(); request.setMessage("updated"); assertEquals(HttpStatus.OK, controller.editMessage(7L, message.getId(), request).getStatusCode()); - assertEquals("updated", message.getMessage()); - assertTrue(message.isEdited()); assertEquals(HttpStatus.OK, controller.deleteMessage(7L, message.getId()).getStatusCode()); + List> saves = saves(2); + assertEquals(1, saves.get(0).size()); + assertEquals("updated", saves.get(0).get(0).getMessage()); + assertTrue(saves.get(0).get(0).isEdited()); + assertTrue(saves.get(1).isEmpty()); assertTrue(messages.isEmpty()); - verify(storage, times(2)).uploadFile(anyString(), eq("messages-images/messages.jsonl"), eq("CSA")); } @Test @@ -104,9 +156,9 @@ void sameDisplayNameDoesNotAuthorizeAnotherAccount() { assertEquals(HttpStatus.FORBIDDEN, controller.editMessage(7L, message.getId(), request).getStatusCode()); assertEquals(HttpStatus.FORBIDDEN, controller.deleteMessage(7L, message.getId()).getStatusCode()); - assertEquals("original", message.getMessage()); assertEquals(1, messages.size()); - verify(storage, never()).uploadFile(anyString(), anyString(), anyString()); + assertEquals("original", messages.get(0).getMessage()); + verify(storage, never()).uploadFileOrThrow(anyString(), anyString(), anyString()); } @Test @@ -117,7 +169,7 @@ void unauthenticatedRequestsCannotEditOrDelete() { assertEquals(HttpStatus.UNAUTHORIZED, controller.editMessage(7L, message.getId(), request).getStatusCode()); assertEquals(HttpStatus.UNAUTHORIZED, controller.deleteMessage(7L, message.getId()).getStatusCode()); - verify(storage, never()).uploadFile(anyString(), anyString(), anyString()); + verify(storage, never()).uploadFileOrThrow(anyString(), anyString(), anyString()); } @Test @@ -128,7 +180,7 @@ void missingAuthorUidDoesNotFallBackToDisplayName() { () -> chat.editMessage("CSA", message.getId(), "updated", "owner")); assertThrows(SecurityException.class, () -> chat.deleteMessage("CSA", message.getId(), "owner")); - verify(storage, never()).uploadFile(anyString(), anyString(), anyString()); + verify(storage, never()).uploadFileOrThrow(anyString(), anyString(), anyString()); } @Test diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java index 56c6b6bc..a8b36d3d 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java @@ -37,9 +37,7 @@ import com.open.spring.mvc.person.Person; import com.open.spring.mvc.person.PersonJpaRepository; -import software.amazon.awssdk.awscore.exception.AwsErrorDetails; import software.amazon.awssdk.core.ResponseBytes; -import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.GetObjectRequest; @@ -47,7 +45,6 @@ import software.amazon.awssdk.services.s3.model.NoSuchKeyException; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.services.s3.model.PutObjectResponse; -import software.amazon.awssdk.services.s3.model.S3Exception; /** * Sending a message reads the group's whole messages file, adds the message and writes the @@ -133,18 +130,10 @@ private String storedMessages() { return bytes == null ? null : new String(bytes, StandardCharsets.UTF_8); } + @Test void aReadThatFailsRefusesTheSendWithA503AndKeepsTheHistory() { - // S3 throttled (503 Slow Down), out of reach, or timing out the request (its RequestTimeout - // comes as a 400): failures that clear if you wait. - List failures = List.of( - (S3Exception) S3Exception.builder().statusCode(503).message("Slow Down").build(), - SdkClientException.create("Unable to execute HTTP request: Read timed out"), - (S3Exception) S3Exception.builder().statusCode(400) - .awsErrorDetails(AwsErrorDetails.builder().errorCode("RequestTimeout").build()) - .message("Your socket connection to the server was not read from or written to within the timeout period.") - .build()); - for (RuntimeException failure : failures) { + for (RuntimeException failure : S3Failures.unavailable()) { useFreshStorage(); objects.put(MESSAGES_KEY, ADA_LINE.getBytes(StandardCharsets.UTF_8)); doThrow(failure).when(s3).getObjectAsBytes(any(GetObjectRequest.class)); @@ -162,11 +151,7 @@ void aReadThatFailsRefusesTheSendWithA503AndKeepsTheHistory() { @Test void aReadS3RefusesOrABugHereIsNotOfferedARetryAndWritesNothing() { - // No permission, a bad key, or a fault in this server: waiting won't fix these. - List faults = List.of( - (S3Exception) S3Exception.builder().statusCode(403).message("Access Denied").build(), - new NullPointerException("a bug here, not S3")); - for (RuntimeException fault : faults) { + for (RuntimeException fault : S3Failures.refusalsAndBugs()) { useFreshStorage(); objects.put(MESSAGES_KEY, ADA_LINE.getBytes(StandardCharsets.UTF_8)); doThrow(fault).when(s3).getObjectAsBytes(any(GetObjectRequest.class)); @@ -181,6 +166,42 @@ void aReadS3RefusesOrABugHereIsNotOfferedARetryAndWritesNothing() { } } + @Test + void anUploadThatFailsForAMomentRefusesTheSendWithA503AndKeepsTheHistory() { + // The read works, and then S3 can't take the upload for a moment. + for (RuntimeException failure : S3Failures.unavailable()) { + useFreshStorage(); + objects.put(MESSAGES_KEY, ADA_LINE.getBytes(StandardCharsets.UTF_8)); + doThrow(failure).when(s3).putObject(any(PutObjectRequest.class), any(RequestBody.class)); + + ResponseEntity response = send("Works for me"); + + assertEquals(HttpStatus.SERVICE_UNAVAILABLE, response.getStatusCode(), failure.toString()); + String retryAfter = response.getHeaders().getFirst(HttpHeaders.RETRY_AFTER); + assertTrue(retryAfter != null && retryAfter.matches("[1-9][0-9]*"), "Retry-After: " + retryAfter); + assertEquals(ADA_LINE, storedMessages(), failure.toString()); + // A message that wasn't saved isn't shown to the group as sent. + verify(messaging, never()).convertAndSend(any(String.class), any(Object.class)); + } + } + + @Test + void anUploadS3RefusesOrABugHereIsNotOfferedARetryAndIsNotShown() { + for (RuntimeException fault : S3Failures.refusalsAndBugs()) { + useFreshStorage(); + objects.put(MESSAGES_KEY, ADA_LINE.getBytes(StandardCharsets.UTF_8)); + doThrow(fault).when(s3).putObject(any(PutObjectRequest.class), any(RequestBody.class)); + + ResponseEntity response = send("Works for me"); + + assertFalse(response.getStatusCode().is2xxSuccessful(), fault.toString()); + assertNotEquals(HttpStatus.SERVICE_UNAVAILABLE, response.getStatusCode(), fault.toString()); + assertNull(response.getHeaders().getFirst(HttpHeaders.RETRY_AFTER), fault.toString()); + assertEquals(ADA_LINE, storedMessages(), fault.toString()); + verify(messaging, never()).convertAndSend(any(String.class), any(Object.class)); + } + } + @Test void aGroupWithNoMessagesFileYetStartsItsHistoryWithTheSend() throws Exception { // S3's 404: nothing is stored yet, so there's no history to lose. diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatServiceTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatServiceTest.java index 97ce7cc1..be0dd3c0 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupChatServiceTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatServiceTest.java @@ -40,8 +40,14 @@ static class OverlappingReads extends S3FileHandler { final Map objects = new ConcurrentHashMap<>(); final CountDownLatch bothReading = new CountDownLatch(2); + // A configured S3 whose writes never fail. @Override - public String uploadFile(String base64Data, String filename, String uid) { + public boolean isConfigured() { + return true; + } + + @Override + public String uploadFileOrThrow(String base64Data, String filename, String uid) { objects.put(uid + "/" + filename, base64Data); return filename; } @@ -58,7 +64,7 @@ public String decodeFile(String uid, String filename) { return copy; } - // Its reads never fail, so a send's strict read is the same read. + // Its reads never fail, so the strict read a change makes is the same read. @Override public String decodeFileOrThrow(String uid, String filename) { return decodeFile(uid, filename); diff --git a/src/test/java/com/open/spring/mvc/groups/S3Failures.java b/src/test/java/com/open/spring/mvc/groups/S3Failures.java new file mode 100644 index 00000000..344b77e8 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/groups/S3Failures.java @@ -0,0 +1,35 @@ +package com.open.spring.mvc.groups; + +import java.util.List; + +import software.amazon.awssdk.awscore.exception.AwsErrorDetails; +import software.amazon.awssdk.core.exception.SdkClientException; +import software.amazon.awssdk.services.s3.model.S3Exception; + +/** The S3 failures the group chat tests throw from a stand-in S3 client. */ +final class S3Failures { + + private S3Failures() { + } + + /** + * S3 throttled (503 Slow Down), out of reach, or timing out the request (its RequestTimeout + * comes as a 400): failures that clear if you wait. + */ + static List unavailable() { + return List.of( + (S3Exception) S3Exception.builder().statusCode(503).message("Slow Down").build(), + SdkClientException.create("Unable to execute HTTP request: Read timed out"), + (S3Exception) S3Exception.builder().statusCode(400) + .awsErrorDetails(AwsErrorDetails.builder().errorCode("RequestTimeout").build()) + .message("Your socket connection to the server was not read from or written to within the timeout period.") + .build()); + } + + /** No permission, a bad key, or a fault in this server: waiting won't fix these. */ + static List refusalsAndBugs() { + return List.of( + (S3Exception) S3Exception.builder().statusCode(403).message("Access Denied").build(), + new NullPointerException("a bug here, not S3")); + } +} From ee2af1939b08823c7edb2b34fc714e11881f40a9 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Wed, 25 Nov 2026 19:55:32 -0800 Subject: [PATCH 30/46] Group chat docs: sends, edits and deletes save their messages strictly The send, edit and delete routes now list their 503 with Retry-After, and that a save which timed out may still be stored. The storage note says all three read and save the messages file strictly (MessagesStorageUnavailableException), a new note says a save that timed out may still be stored, so a send tried again can show up twice, and the testing list names GroupChatEditDeleteTest. --- docs/group-chat-architecture.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/group-chat-architecture.md b/docs/group-chat-architecture.md index a5036c49..07a6536a 100644 --- a/docs/group-chat-architecture.md +++ b/docs/group-chat-architecture.md @@ -132,9 +132,9 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) | Method | Route | Operation | Who | |---|---|---|---| | GET | `/api/groups/chat/{groupId}/messages` | The group's messages | Any signed-in account | -| POST | `/api/groups/chat/{groupId}/messages` | Send `{message, image}`; broadcasts it and returns the history. 503 with `Retry-After` when S3 can't read the group's messages for now, and then nothing is saved or broadcast | Any signed-in account. The sender is the signed-in account. | -| PATCH | `/api/groups/chat/{groupId}/messages/{messageId}` | Edit a message | Only its sender (403 otherwise) | -| DELETE | `/api/groups/chat/{groupId}/messages/{messageId}` | Delete a message | Only its sender (403 otherwise) | +| POST | `/api/groups/chat/{groupId}/messages` | Send `{message, image}`; broadcasts it and returns the history. 503 with `Retry-After` when S3 can't read or save the group's messages for now, and then it isn't broadcast (a save that timed out may still be stored, see Persistence) | Any signed-in account. The sender is the signed-in account. | +| PATCH | `/api/groups/chat/{groupId}/messages/{messageId}` | Edit a message. 503 with `Retry-After` when S3 can't read or save the group's messages for now, and then it isn't broadcast (a save that timed out may still be stored, see Persistence) | Only its sender (403 otherwise) | +| DELETE | `/api/groups/chat/{groupId}/messages/{messageId}` | Delete a message. 503 with `Retry-After` when S3 can't read or save the group's messages for now, and then it isn't broadcast (a save that timed out may still be stored, see Persistence) | Only its sender (403 otherwise) | | GET | `/api/groups/chat/unread` | `{total, unreadByGroup}` across your groups | You | | POST | `/api/groups/chat/{groupId}/read` | Mark a group read | You | | GET | `/api/groups/chat/{groupId}/files` | Shared files with who uploaded them, each with its bytes as `base64Data` | Any signed-in account | @@ -156,9 +156,10 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) - **History is keyed by group name, not id.** Renaming a group with `PUT /api/groups/{id}` leaves its history under the old name. - **Without S3 settings** (AWS credentials, region and bucket), the server logs `S3 is disabled` at startup. Sends still broadcast live, but nothing is saved, so history and files come back empty. This is the normal state of a local server. - **At every start, `StartupService` creates any missing chat files.** It checks each group and writes an empty messages file and `shared-files/` placeholder where they're missing; the four course groups that `ModelInit` seeds start with none. The check of the messages file is strict (`S3FileHandler.fileExistsOrThrow`), since an empty file written over the real one would erase the group's history: only S3's 404 means there is no file. Any other failure to check (a throttle, a 5xx, a timeout, S3 refusing it) is logged with the group's name and leaves that group as it is (the next start checks it again), and the other groups are still checked. The check holds the group's message lock, so a message sent while the server is starting isn't written over. Without S3 settings nothing is checked. -- **Every new message rewrites the whole file**, read then write. Sending, editing and deleting take one lock per group (`messageLocks` in `GroupChatService`), so two at once keep both changes. The lock only holds within one server: several servers writing the same bucket would need S3's conditional writes. A send reads the file strictly (`S3FileHandler.decodeFileOrThrow`), since writing back an empty read would replace the whole history: only S3's 404 reads as no messages yet, and any other failure to read refuses the send. When S3 timed out (its own `RequestTimeout` comes as a 400), couldn't be reached or answered with a 5xx, that's a 503 with `Retry-After` (`MessagesReadFailedException`), by the same rule as shared files; S3 refusing the read (any other 4xx) or a bug here gets the route's usual 400. Edits and deletes still read with `decodeFile`, which answers a failed read the same as a missing file, so after one they find nothing to change and write nothing. +- **Every new message rewrites the whole file**, read then write. Sending, editing and deleting take one lock per group (`messageLocks` in `GroupChatService`), so two at once keep both changes. The lock only holds within one server: several servers writing the same bucket would need S3's conditional writes. Sending, editing and deleting read the file strictly (`S3FileHandler.decodeFileOrThrow`), since writing back an empty read would replace the whole history: only S3's 404 reads as no messages yet, and any other failure to read refuses the change. They save it strictly too (`S3FileHandler.uploadFileOrThrow`), so a change S3 didn't take isn't answered as saved. When S3 timed out (its own `RequestTimeout` comes as a 400), couldn't be reached or answered with a 5xx, reading or saving, that's a 503 with `Retry-After` (`MessagesStorageUnavailableException`), by the same rule as shared files; S3 refusing the request (any other 4xx) or a bug here gets the route's usual 400. - **A shared file's bytes never go over the socket.** `sendFileServer` names the file and its size; a member downloads it from `/files/content`. Sending the bytes to every subscriber could overflow a session's 512 KB send buffer while another frame was queued, and Spring closes a session that overflows. - **A shared file whose write timed out may still be stored.** S3 can store a file and then fail to answer, and the AWS SDK's own retries can fail too. The upload then answers 503 without a "shared by" record or a `sendFileServer` frame, and sharing it again finds the path taken (409), which the page handles like any other taken name. +- **A message whose save timed out may still be stored.** S3 can store the messages file and then fail to answer. The change then answers 503 and isn't broadcast, so a message stored that way shows only after a reload, and a send tried again shows up twice. An edit or delete tried again makes the same change, so it lands once. ## Testing @@ -169,6 +170,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) - `GroupChatSendTest` sends through the controller to a real `S3FileHandler` over a stand-in S3 client: a read that fails, a read S3 refuses, a bug, a group with no messages file yet, and a server without S3. `S3FileHandlerDecodeTest` covers the strict read. Run the S3 handler tests with `./mvnw test '-Dtest=S3FileHandler*Test'`. - `StartupServiceTest` runs the start-up check over a real `S3FileHandler` and a stand-in S3 client: checks that fail, a group that can't be checked among others, a group with no messages file yet, a group that has one, a server without S3, and a send during the check. Run it with `./mvnw test '-Dtest=StartupServiceTest'`. - `GroupChatFilesTest` also covers a write that fails, including sharing again once S3 is back, and `S3FileHandlerUploadTest` covers the strict write. +- `GroupChatSendTest` also covers an upload that fails after a good read, and `GroupChatEditDeleteTest` covers edits and deletes whose read or upload fails, both through the controller over a stand-in S3 client. ## Known issues From 258b8f6edd0fdeb54c882b26394735172eaf721e Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Wed, 25 Nov 2026 20:01:33 -0800 Subject: [PATCH 31/46] Group chat: a send or edit answers with the messages it saved After a send or an edit worked, the route read the group's messages file again with the lenient getMessages and answered with that. If S3 failed on that second read, decodeFile answered null and the route answered 200 with an empty list. The Messages page uses that list to show the sender's own message when its socket missed the frame, so they could see nothing and send again. Every send and edit also read the same S3 file twice. publishMessage now returns the list addMessage saved, and editMessage returns the saved list, or nothing when no message has that id (still a 404). The routes answer with that list and don't read the file again. Tests: a send and an edit whose save works, with every S3 read after it failing, answer with exactly what they saved. --- .../mvc/groups/GroupChatApiController.java | 20 ++++++------- .../mvc/groups/GroupChatRealtimeService.java | 23 ++++++++------- .../spring/mvc/groups/GroupChatService.java | 19 +++++++------ .../mvc/groups/GroupChatEditDeleteTest.java | 24 ++++++++++++++++ .../spring/mvc/groups/GroupChatSendTest.java | 28 +++++++++++++++++++ 5 files changed, 84 insertions(+), 30 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 08f5aca8..589e6209 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java @@ -191,17 +191,16 @@ public ResponseEntity postMessage( return new ResponseEntity<>("name and message are required", HttpStatus.BAD_REQUEST); } + // Answered from what was saved: a second read could fail and answer an empty chat. + List saved; try { - realtimeService.publishMessage(groupId, message.getMessage(), message.getImage(), identity); + saved = realtimeService.publishMessage(groupId, message.getMessage(), message.getImage(), identity); } catch (MessagesStorageUnavailableException ex) { return tryAgainLater(ex); } catch (RuntimeException ex) { return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST); } - - String groupName = groupOpt.get().getName(); - List updated = groupChatService.getMessages(groupName); - return new ResponseEntity<>(updated, HttpStatus.OK); + return new ResponseEntity<>(saved, HttpStatus.OK); } @PatchMapping("/{groupId}/messages/{messageId}") @@ -223,9 +222,9 @@ public ResponseEntity editMessage( return new ResponseEntity<>("message is required", HttpStatus.BAD_REQUEST); } - boolean updated; + Optional> saved; try { - updated = realtimeService.editMessage(groupId, messageId, request.getMessage(), identity.getUid()); + saved = realtimeService.editMessage(groupId, messageId, request.getMessage(), identity.getUid()); } catch (SecurityException ex) { return new ResponseEntity<>(HttpStatus.FORBIDDEN); } catch (MessagesStorageUnavailableException ex) { @@ -233,13 +232,10 @@ public ResponseEntity editMessage( } catch (RuntimeException ex) { return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST); } - if (!updated) { + if (saved.isEmpty()) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } - - String groupName = groupOpt.get().getName(); - List messages = groupChatService.getMessages(groupName); - return new ResponseEntity<>(messages, HttpStatus.OK); + return new ResponseEntity<>(saved.get(), HttpStatus.OK); } @DeleteMapping("/{groupId}/messages/{messageId}") diff --git a/src/main/java/com/open/spring/mvc/groups/GroupChatRealtimeService.java b/src/main/java/com/open/spring/mvc/groups/GroupChatRealtimeService.java index bac95d70..873f5f0f 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatRealtimeService.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatRealtimeService.java @@ -1,6 +1,7 @@ package com.open.spring.mvc.groups; import java.time.Instant; +import java.util.List; import java.util.Optional; import org.springframework.messaging.simp.SimpMessagingTemplate; @@ -24,7 +25,8 @@ public class GroupChatRealtimeService { private final GroupsJpaRepository groupsRepository; private final SimpMessagingTemplate messagingTemplate; - public GroupChatEvent publishMessage(Long groupId, String message, String image, AuthenticatedIdentity identity) { + /** Saves the message, tells the group, and returns the group's messages as saved. */ + public List publishMessage(Long groupId, String message, String image, AuthenticatedIdentity identity) { Groups group = getGroupOrThrow(groupId); if ((message == null || message.isBlank()) && (image == null || image.isBlank())) { @@ -34,7 +36,7 @@ public GroupChatEvent publishMessage(Long groupId, String message, String image, String date = Instant.now().toString(); GroupChatMessage persisted = new GroupChatMessage(identity.getDisplayName(), identity.getUid(), message, date, image); - groupChatService.addMessage(group.getName(), persisted); + List saved = groupChatService.addMessage(group.getName(), persisted); GroupChatEvent event = GroupChatEvent.builder() .context("sendMessageServer") @@ -47,18 +49,19 @@ public GroupChatEvent publishMessage(Long groupId, String message, String image, .build(); broadcastToGroup(groupId, event); - return event; + return saved; } /** - * Returns whether the message existed (and was broadcast as edited). Throws - * {@link SecurityException} if the authenticated requester's uid is not the author uid. + * Edits the message, tells the group, and returns the group's messages as saved, or nothing + * when the message isn't in this group. Throws {@link SecurityException} if the + * authenticated requester's uid is not the author uid. */ - public boolean editMessage(Long groupId, String messageId, String newMessage, String requesterUid) { + public Optional> editMessage(Long groupId, String messageId, String newMessage, String requesterUid) { Groups group = getGroupOrThrow(groupId); - boolean updated = groupChatService.editMessage(group.getName(), messageId, newMessage, requesterUid); - if (!updated) { - return false; + Optional> saved = groupChatService.editMessage(group.getName(), messageId, newMessage, requesterUid); + if (saved.isEmpty()) { + return saved; } GroupChatEvent event = GroupChatEvent.builder() @@ -71,7 +74,7 @@ public boolean editMessage(Long groupId, String messageId, String newMessage, St .build(); broadcastToGroup(groupId, event); - return true; + return saved; } /** Throws {@link SecurityException} if the authenticated requester didn't send it. */ diff --git a/src/main/java/com/open/spring/mvc/groups/GroupChatService.java b/src/main/java/com/open/spring/mvc/groups/GroupChatService.java index 9486c094..c1e60ca3 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatService.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatService.java @@ -9,6 +9,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; @@ -199,12 +200,13 @@ public List addMessage(String groupName, GroupChatMessage mess } /** - * Returns whether a message with that id was found (and updated) in this group. - * Throws {@link SecurityException} unless the authenticated requester's uid matches - * the stored author uid. Legacy messages without an author uid cannot be edited. + * Edits a message and returns the group's messages as saved, or nothing when no message + * with that id is in this group. Throws {@link SecurityException} unless the authenticated + * requester's uid matches the stored author uid. Legacy messages without an author uid + * cannot be edited. */ - public boolean editMessage(String groupName, String messageId, String newMessage, String requesterUid) { - if (messageId == null) return false; + public Optional> editMessage(String groupName, String messageId, String newMessage, String requesterUid) { + if (messageId == null) return Optional.empty(); synchronized (messageLocks.computeIfAbsent(groupName, name -> new Object())) { List messages = readMessagesOrThrow(groupName); boolean found = false; @@ -220,10 +222,11 @@ public boolean editMessage(String groupName, String messageId, String newMessage } } - if (found) { - writeMessagesOrThrow(groupName, messages); + if (!found) { + return Optional.empty(); } - return found; + writeMessagesOrThrow(groupName, messages); + return Optional.of(messages); } } diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatEditDeleteTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatEditDeleteTest.java index 2718c2f0..b76e3ab0 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupChatEditDeleteTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatEditDeleteTest.java @@ -6,6 +6,7 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -19,6 +20,7 @@ import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import org.junit.jupiter.api.AfterEach; @@ -175,6 +177,28 @@ void anEditAndADeleteAreSavedWhenS3IsUp() throws Exception { assertEquals("", storedMessages()); } + @Test + void anEditAnswersWithTheMessagesItSavedEvenWhenTheNextReadFails() { + // The first read of S3 works, and every read after it fails as a throttle. + AtomicInteger reads = new AtomicInteger(); + doAnswer(call -> { + if (reads.incrementAndGet() > 1) { + throw S3Failures.unavailable().get(0); + } + byte[] bytes = objects.get(call.getArgument(0).key()); + return ResponseBytes.fromByteArray(GetObjectResponse.builder().build(), bytes); + }).when(s3).getObjectAsBytes(any(GetObjectRequest.class)); + + ResponseEntity response = edit(); + + assertEquals(HttpStatus.OK, response.getStatusCode()); + List answered = (List) response.getBody(); + assertEquals(1, answered.size(), "answered: " + answered); + GroupChatMessage saved = (GroupChatMessage) answered.get(0); + assertEquals("Meeting at 3", saved.getMessage()); + assertTrue(saved.isEdited()); + } + @Test void anEditS3CantReadOrSaveForAMomentAnswers503AndChangesNothing() { assertRefusedForNow(this::edit); diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java index a8b36d3d..f8e71a46 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatSendTest.java @@ -7,6 +7,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -19,6 +20,7 @@ import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -125,6 +127,18 @@ private ResponseEntity send(String text) { return controller.postMessage(7L, request); } + /** The first read of S3 works, and every read after it fails as a throttle. */ + private void failReadsAfterTheFirst() { + AtomicInteger reads = new AtomicInteger(); + doAnswer(call -> { + if (reads.incrementAndGet() > 1) { + throw S3Failures.unavailable().get(0); + } + byte[] bytes = objects.get(call.getArgument(0).key()); + return ResponseBytes.fromByteArray(GetObjectResponse.builder().build(), bytes); + }).when(s3).getObjectAsBytes(any(GetObjectRequest.class)); + } + private String storedMessages() { byte[] bytes = objects.get(MESSAGES_KEY); return bytes == null ? null : new String(bytes, StandardCharsets.UTF_8); @@ -202,6 +216,20 @@ void anUploadS3RefusesOrABugHereIsNotOfferedARetryAndIsNotShown() { } } + @Test + void aSendAnswersWithTheMessagesItSavedEvenWhenTheNextReadFails() { + objects.put(MESSAGES_KEY, ADA_LINE.getBytes(StandardCharsets.UTF_8)); + failReadsAfterTheFirst(); + + ResponseEntity response = send("Works for me"); + + assertEquals(HttpStatus.OK, response.getStatusCode()); + List texts = ((List) response.getBody()).stream() + .map(saved -> ((GroupChatMessage) saved).getMessage()) + .toList(); + assertEquals(List.of("Meeting at 3", "Works for me"), texts); + } + @Test void aGroupWithNoMessagesFileYetStartsItsHistoryWithTheSend() throws Exception { // S3's 404: nothing is stored yet, so there's no history to lose. From 320171c1b6bcb45db1439938d4fcfc8e35d98852 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Wed, 25 Nov 2026 20:03:02 -0800 Subject: [PATCH 32/46] Group chat: a delete of a message that isn't saved answers 404 and tells no one Deleting a message that wasn't in the group's messages file returned quietly, and the route still broadcast deleteMessageServer to the whole group and answered 200. The ownership check only runs on a saved message, so any signed-in account could take any message off everyone's screen by sending its id. On a server without S3 settings, where nothing is saved, that worked for every live message. deleteMessage now returns whether a message with that id was removed. The realtime service only broadcasts when it was, and the route answers 404 otherwise, like an edit of an unknown id. Tests: a delete of an id that isn't saved, and any delete on a server without S3 settings, answer 404 and broadcast nothing. --- .../mvc/groups/GroupChatApiController.java | 7 ++++-- .../mvc/groups/GroupChatRealtimeService.java | 14 ++++++++--- .../spring/mvc/groups/GroupChatService.java | 19 +++++++------- .../mvc/groups/GroupChatEditDeleteTest.java | 25 +++++++++++++++++++ 4 files changed, 51 insertions(+), 14 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 589e6209..a6f6937f 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java @@ -252,8 +252,9 @@ public ResponseEntity deleteMessage( return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); } + boolean deleted; try { - realtimeService.deleteMessage(groupId, messageId, identity.getUid()); + deleted = realtimeService.deleteMessage(groupId, messageId, identity.getUid()); } catch (SecurityException ex) { return new ResponseEntity<>(HttpStatus.FORBIDDEN); } catch (MessagesStorageUnavailableException ex) { @@ -261,7 +262,9 @@ public ResponseEntity deleteMessage( } catch (RuntimeException ex) { return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST); } - + if (!deleted) { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } return new ResponseEntity<>(HttpStatus.OK); } diff --git a/src/main/java/com/open/spring/mvc/groups/GroupChatRealtimeService.java b/src/main/java/com/open/spring/mvc/groups/GroupChatRealtimeService.java index 873f5f0f..1242ac5d 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatRealtimeService.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatRealtimeService.java @@ -77,10 +77,17 @@ public Optional> editMessage(Long groupId, String message return saved; } - /** Throws {@link SecurityException} if the authenticated requester didn't send it. */ - public void deleteMessage(Long groupId, String messageId, String requesterUid) { + /** + * Deletes the message and tells the group, or returns false and tells no one when the + * message isn't in this group. Throws {@link SecurityException} if the authenticated + * requester didn't send it. + */ + public boolean deleteMessage(Long groupId, String messageId, String requesterUid) { Groups group = getGroupOrThrow(groupId); - groupChatService.deleteMessage(group.getName(), messageId, requesterUid); + if (!groupChatService.deleteMessage(group.getName(), messageId, requesterUid)) { + // Telling the group about a message that isn't saved would take it off everyone's screen. + return false; + } GroupChatEvent event = GroupChatEvent.builder() .context("deleteMessageServer") @@ -90,6 +97,7 @@ public void deleteMessage(Long groupId, String messageId, String requesterUid) { .build(); broadcastToGroup(groupId, event); + return true; } /** diff --git a/src/main/java/com/open/spring/mvc/groups/GroupChatService.java b/src/main/java/com/open/spring/mvc/groups/GroupChatService.java index c1e60ca3..9b9da570 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatService.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatService.java @@ -230,9 +230,12 @@ public Optional> editMessage(String groupName, String mes } } - /** Same ownership rule as {@link #editMessage}; throws {@link SecurityException} on mismatch. */ - public void deleteMessage(String groupName, String messageId, String requesterUid) { - if (messageId == null) return; + /** + * Deletes a message and returns whether one with that id was in this group. Same ownership + * rule as {@link #editMessage}; throws {@link SecurityException} on mismatch. + */ + public boolean deleteMessage(String groupName, String messageId, String requesterUid) { + if (messageId == null) return false; synchronized (messageLocks.computeIfAbsent(groupName, name -> new Object())) { List messages = readMessagesOrThrow(groupName); @@ -240,16 +243,14 @@ public void deleteMessage(String groupName, String messageId, String requesterUi .filter(m -> messageId.equals(m.getId())) .findFirst() .orElse(null); - if (target == null) return; + if (target == null) return false; if (requesterUid == null || !requesterUid.equals(target.getAuthor_uid())) { throw new SecurityException("Not the message sender"); } - boolean removed = messages.remove(target); - - if (removed) { - writeMessagesOrThrow(groupName, messages); - } + messages.remove(target); + writeMessagesOrThrow(groupName, messages); + return true; } } diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatEditDeleteTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatEditDeleteTest.java index b76e3ab0..16f5cefe 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupChatEditDeleteTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatEditDeleteTest.java @@ -100,7 +100,11 @@ private void useFreshStorage() { S3FileHandler storage = new S3FileHandler(); ReflectionTestUtils.setField(storage, "s3Client", s3); ReflectionTestUtils.setField(storage, "bucketName", "chat-test"); + wire(storage); + } + /** The edit and delete routes over this storage, with Grace Hopper signed in. */ + private void wire(S3FileHandler storage) { GroupChatService chat = new GroupChatService(storage, new ObjectMapper()); GroupsJpaRepository groups = mock(GroupsJpaRepository.class); messaging = mock(SimpMessagingTemplate.class); @@ -199,6 +203,27 @@ void anEditAnswersWithTheMessagesItSavedEvenWhenTheNextReadFails() { assertTrue(saved.isEdited()); } + @Test + void aDeleteOfAMessageThatIsntSavedAnswers404AndTellsNoOne() { + ResponseEntity response = controller.deleteMessage(7L, "not-a-saved-id"); + + assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode()); + assertEquals(GRACE_LINE, storedMessages()); + // Telling the group would take the message off everyone's screen. + verify(messaging, never()).convertAndSend(any(String.class), any(Object.class)); + } + + @Test + void withoutS3SettingsADeleteAnswers404AndTellsNoOne() { + // A local server without S3 saves nothing, so there's no message to delete, whoever sent it. + wire(new S3FileHandler()); + + ResponseEntity response = delete(); + + assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode()); + verify(messaging, never()).convertAndSend(any(String.class), any(Object.class)); + } + @Test void anEditS3CantReadOrSaveForAMomentAnswers503AndChangesNothing() { assertRefusedForNow(this::edit); From 1cc55364107ae4f1994b7315412f2863432b6dc7 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Wed, 25 Nov 2026 20:08:12 -0800 Subject: [PATCH 33/46] Group chat: a line that doesn't read as a message is kept when the file is saved parseMessages skipped a line of the messages file that didn't read as a message, and the next send, edit or delete wrote the file back without it, so one bad line was gone for good. toJson answered "{}" for a message it couldn't write, which replaced that message in the file with nothing. A send, an edit and a delete now read the file as MessagesLine entries: a message, or a line that didn't read as one, kept as it was. The save writes each message as JSON and each unreadable line back in its place, and loading the chat still leaves unreadable lines out. A message that can't be written now throws, so the change is refused and the file stays as it was; the log line names the message's id instead of printing its text. Tests: GroupChatMessagesFileTest keeps an unreadable line in place through a send, an edit and a delete, leaves it out when the chat loads, and refuses a message that can't be written without touching the file. --- .../spring/mvc/groups/GroupChatService.java | 121 +++++++++------ .../mvc/groups/GroupChatMessagesFileTest.java | 144 ++++++++++++++++++ 2 files changed, 215 insertions(+), 50 deletions(-) create mode 100644 src/test/java/com/open/spring/mvc/groups/GroupChatMessagesFileTest.java diff --git a/src/main/java/com/open/spring/mvc/groups/GroupChatService.java b/src/main/java/com/open/spring/mvc/groups/GroupChatService.java index 9b9da570..1e6bd635 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatService.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatService.java @@ -9,6 +9,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; @@ -103,13 +104,23 @@ public List getMessages(String groupName) { } /** - * The group's messages for a send, an edit or a delete, which write the whole file back. - * Strict: a read that failed throws rather than reading as an empty chat, which a send would - * save over the history and an edit or delete would answer as "not found". Only S3's 404 - * means no messages yet. S3 being unavailable for a moment (see isUnavailable) throws - * MessagesStorageUnavailableException; anything else goes up as it is. + * One line of a group's messages file: a message, or a line that didn't read as one, kept + * as it was so that saving the file again doesn't drop it. */ - private List readMessagesOrThrow(String groupName) { + private record MessagesLine(GroupChatMessage message, String unreadable) { + static MessagesLine of(GroupChatMessage message) { + return new MessagesLine(message, null); + } + } + + /** + * The group's messages file, line by line, for a send, an edit or a delete, which write the + * whole file back. Strict: a read that failed throws rather than reading as an empty chat, + * which a send would save over the history and an edit or delete would answer as "not + * found". Only S3's 404 means no messages yet. S3 being unavailable for a moment (see + * isUnavailable) throws MessagesStorageUnavailableException; anything else goes up as it is. + */ + private List readMessagesOrThrow(String groupName) { String base64Data; try { base64Data = s3FileHandler.decodeFileOrThrow(groupName, MESSAGES_FILE); @@ -122,21 +133,22 @@ private List readMessagesOrThrow(String groupName) { } throw new MessagesStorageUnavailableException(e); } - return parseMessages(groupName, base64Data); + return parseLines(groupName, base64Data); } /** - * Saves the group's whole messages file. Strict: a write that failed throws, so a send, an - * edit or a delete isn't answered as saved when it wasn't. S3 being unavailable for a moment - * (see isUnavailable) throws MessagesStorageUnavailableException; anything else goes up as - * it is. Without S3 settings nothing is stored, and the chat still works live. + * Saves the group's whole messages file: each message as JSON, and each line that didn't + * read as a message as it was. Strict: a write that failed throws, so a send, an edit or a + * delete isn't answered as saved when it wasn't. S3 being unavailable for a moment (see + * isUnavailable) throws MessagesStorageUnavailableException; anything else goes up as it is. + * Without S3 settings nothing is stored, and the chat still works live. */ - private void writeMessagesOrThrow(String groupName, List messages) { + private void writeMessagesOrThrow(String groupName, List lines) { if (!s3FileHandler.isConfigured()) { return; } - String jsonl = messages.stream() - .map(this::toJson) + String jsonl = lines.stream() + .map(line -> line.message() != null ? toJson(line.message()) : line.unreadable()) .collect(Collectors.joining("\n")); String base64Data = Base64.getEncoder().encodeToString(jsonl.getBytes(StandardCharsets.UTF_8)); try { @@ -154,6 +166,24 @@ private void writeMessagesOrThrow(String groupName, List messa } private List parseMessages(String groupName, String base64Data) { + return messagesOf(parseLines(groupName, base64Data)); + } + + private static List messagesOf(List lines) { + return lines.stream() + .map(MessagesLine::message) + .filter(Objects::nonNull) + .collect(Collectors.toCollection(ArrayList::new)); + } + + private static GroupChatMessage find(List lines, String messageId) { + return messagesOf(lines).stream() + .filter(m -> messageId.equals(m.getId())) + .findFirst() + .orElse(null); + } + + private List parseLines(String groupName, String base64Data) { if (base64Data == null || base64Data.isBlank()) { return new ArrayList<>(); } @@ -171,31 +201,32 @@ private List parseMessages(String groupName, String base64Data return new ArrayList<>(); } - List messages = new ArrayList<>(); + List lines = new ArrayList<>(); try (BufferedReader reader = new BufferedReader(new StringReader(jsonl))) { String line; while ((line = reader.readLine()) != null) { if (line.isBlank()) continue; try { - GroupChatMessage msg = objectMapper.readValue(line, GroupChatMessage.class); - messages.add(msg); + lines.add(MessagesLine.of(objectMapper.readValue(line, GroupChatMessage.class))); } catch (Exception e) { - log.warn("Skipping invalid message line for group {}: {}", groupName, line, e); + // Left out of the chat, but kept in the file: a save writes it back as it is. + log.warn("Keeping an unreadable message line of group {} as it is: {}", groupName, line, e); + lines.add(new MessagesLine(null, line)); } } } catch (Exception e) { log.warn("Failed reading messages for group {}", groupName, e); } - return messages; + return lines; } public List addMessage(String groupName, GroupChatMessage message) { synchronized (messageLocks.computeIfAbsent(groupName, name -> new Object())) { - List messages = readMessagesOrThrow(groupName); - messages.add(message); - writeMessagesOrThrow(groupName, messages); - return messages; + List lines = readMessagesOrThrow(groupName); + lines.add(MessagesLine.of(message)); + writeMessagesOrThrow(groupName, lines); + return messagesOf(lines); } } @@ -208,25 +239,18 @@ public List addMessage(String groupName, GroupChatMessage mess public Optional> editMessage(String groupName, String messageId, String newMessage, String requesterUid) { if (messageId == null) return Optional.empty(); synchronized (messageLocks.computeIfAbsent(groupName, name -> new Object())) { - List messages = readMessagesOrThrow(groupName); - boolean found = false; - for (GroupChatMessage m : messages) { - if (messageId.equals(m.getId())) { - if (requesterUid == null || !requesterUid.equals(m.getAuthor_uid())) { - throw new SecurityException("Not the message sender"); - } - m.setMessage(newMessage); - m.setEdited(true); - found = true; - break; - } - } - - if (!found) { + List lines = readMessagesOrThrow(groupName); + GroupChatMessage target = find(lines, messageId); + if (target == null) { return Optional.empty(); } - writeMessagesOrThrow(groupName, messages); - return Optional.of(messages); + if (requesterUid == null || !requesterUid.equals(target.getAuthor_uid())) { + throw new SecurityException("Not the message sender"); + } + target.setMessage(newMessage); + target.setEdited(true); + writeMessagesOrThrow(groupName, lines); + return Optional.of(messagesOf(lines)); } } @@ -237,19 +261,15 @@ public Optional> editMessage(String groupName, String mes public boolean deleteMessage(String groupName, String messageId, String requesterUid) { if (messageId == null) return false; synchronized (messageLocks.computeIfAbsent(groupName, name -> new Object())) { - List messages = readMessagesOrThrow(groupName); - - GroupChatMessage target = messages.stream() - .filter(m -> messageId.equals(m.getId())) - .findFirst() - .orElse(null); + List lines = readMessagesOrThrow(groupName); + GroupChatMessage target = find(lines, messageId); if (target == null) return false; if (requesterUid == null || !requesterUid.equals(target.getAuthor_uid())) { throw new SecurityException("Not the message sender"); } - messages.remove(target); - writeMessagesOrThrow(groupName, messages); + lines.removeIf(line -> line.message() == target); + writeMessagesOrThrow(groupName, lines); return true; } } @@ -496,8 +516,9 @@ private String toJson(GroupChatMessage message) { try { return objectMapper.writeValueAsString(message); } catch (Exception e) { - log.warn("Failed to serialize message: {}", message, e); - return "{}"; + // Writing "{}" instead would replace the message in the file with nothing. + log.warn("Could not write message {} of a group chat", message.getId(), e); + throw new IllegalStateException("Could not write message " + message.getId(), e); } } } diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatMessagesFileTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatMessagesFileTest.java new file mode 100644 index 00000000..4bd46524 --- /dev/null +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatMessagesFileTest.java @@ -0,0 +1,144 @@ +package com.open.spring.mvc.groups; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.open.spring.mvc.S3uploads.S3FileHandler; + +/** + * A group's messages file can hold a line that doesn't read as a message, and a message can + * fail to be written. Neither may quietly lose a message when the file is saved again. + */ +class GroupChatMessagesFileTest { + + private static final String MESSAGES_KEY = "CSA/messages-images/messages.jsonl"; + private static final String ADA_LINE = "{\"id\":\"m1\",\"author\":\"Ada Lovelace\",\"author_uid\":\"ada\"," + + "\"message\":\"Meeting at 3\",\"date\":\"2026-11-21T10:00:00Z\",\"image\":null,\"edited\":false}"; + private static final String GRACE_LINE = "{\"id\":\"m2\",\"author\":\"Grace Hopper\",\"author_uid\":\"grace\"," + + "\"message\":\"Meetign at 3\",\"date\":\"2026-11-21T10:05:00Z\",\"image\":null,\"edited\":false}"; + // A line that isn't a whole message: S3 holds it, but it doesn't read as JSON. + private static final String UNREADABLE = "{\"id\":\"m0\",\"author\":\"Ada Lovelace\",\"message\":\"Agenda for"; + + /** A configured S3 kept in a map, whose reads and writes never fail. */ + static class InMemoryS3 extends S3FileHandler { + final Map objects = new ConcurrentHashMap<>(); + + @Override + public boolean isConfigured() { + return true; + } + + @Override + public String decodeFile(String uid, String filename) { + return objects.get(uid + "/" + filename); + } + + @Override + public String decodeFileOrThrow(String uid, String filename) { + return decodeFile(uid, filename); + } + + @Override + public String uploadFileOrThrow(String base64Data, String filename, String uid) { + objects.put(uid + "/" + filename, base64Data); + return filename; + } + } + + private final ObjectMapper json = new ObjectMapper(); + private InMemoryS3 storage; + private GroupChatService chat; + + @BeforeEach + void setUp() { + storage = new InMemoryS3(); + chat = new GroupChatService(storage, json); + } + + private void store(String... lines) { + String jsonl = String.join("\n", lines); + storage.objects.put(MESSAGES_KEY, Base64.getEncoder().encodeToString(jsonl.getBytes(StandardCharsets.UTF_8))); + } + + private List storedLines() { + String base64 = storage.objects.get(MESSAGES_KEY); + return List.of(new String(Base64.getDecoder().decode(base64), StandardCharsets.UTF_8).split("\n")); + } + + private String text(String line) throws Exception { + return json.readValue(line, GroupChatMessage.class).getMessage(); + } + + @Test + void anUnreadableLineIsKeptWhereItWasWhenAMessageIsSent() throws Exception { + store(ADA_LINE, UNREADABLE, GRACE_LINE); + + chat.addMessage("CSA", new GroupChatMessage("Grace Hopper", "grace", "Works for me", "2026-11-21T10:06:00Z", null)); + + List lines = storedLines(); + assertEquals(4, lines.size(), lines.toString()); + assertEquals("Meeting at 3", text(lines.get(0))); + assertEquals(UNREADABLE, lines.get(1)); + assertEquals("Meetign at 3", text(lines.get(2))); + assertEquals("Works for me", text(lines.get(3))); + } + + @Test + void anUnreadableLineIsKeptWhenAMessageIsEditedOrDeleted() throws Exception { + store(ADA_LINE, UNREADABLE, GRACE_LINE); + + assertTrue(chat.editMessage("CSA", "m2", "Meeting at 3", "grace").isPresent()); + List lines = storedLines(); + assertEquals(3, lines.size(), lines.toString()); + assertEquals(List.of("Meeting at 3", UNREADABLE, "Meeting at 3"), + List.of(text(lines.get(0)), lines.get(1), text(lines.get(2)))); + + assertTrue(chat.deleteMessage("CSA", "m1", "ada")); + lines = storedLines(); + assertEquals(2, lines.size(), lines.toString()); + assertEquals(UNREADABLE, lines.get(0)); + assertEquals("Meeting at 3", text(lines.get(1))); + } + + @Test + void loadingTheChatSkipsAnUnreadableLine() { + store(ADA_LINE, UNREADABLE, GRACE_LINE); + + List texts = chat.getMessages("CSA").stream().map(GroupChatMessage::getMessage).toList(); + + assertEquals(List.of("Meeting at 3", "Meetign at 3"), texts); + } + + @Test + void aMessageThatCantBeWrittenRefusesTheChangeAndKeepsTheFile() { + ObjectMapper failsOnOneMessage = new ObjectMapper() { + @Override + public String writeValueAsString(Object value) throws JsonProcessingException { + if (value instanceof GroupChatMessage message && "can't write me".equals(message.getMessage())) { + throw new JsonMappingException(null, "can't write this message"); + } + return super.writeValueAsString(value); + } + }; + chat = new GroupChatService(storage, failsOnOneMessage); + store(ADA_LINE); + + assertThrows(RuntimeException.class, () -> chat.addMessage("CSA", + new GroupChatMessage("Grace Hopper", "grace", "can't write me", "2026-11-21T10:06:00Z", null))); + + assertEquals(List.of(ADA_LINE), storedLines()); + } +} From 8dfea9a83d4a207da842d570b8d18eb1440df64d Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Wed, 25 Nov 2026 20:01:33 -0800 Subject: [PATCH 34/46] Group chat docs: a send or edit returns the history as it was saved The send and edit routes now say they return the history as saved, the edit route lists its 404, and the testing list names the new checks. --- docs/group-chat-architecture.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/group-chat-architecture.md b/docs/group-chat-architecture.md index 07a6536a..1fd87049 100644 --- a/docs/group-chat-architecture.md +++ b/docs/group-chat-architecture.md @@ -132,8 +132,8 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) | Method | Route | Operation | Who | |---|---|---|---| | GET | `/api/groups/chat/{groupId}/messages` | The group's messages | Any signed-in account | -| POST | `/api/groups/chat/{groupId}/messages` | Send `{message, image}`; broadcasts it and returns the history. 503 with `Retry-After` when S3 can't read or save the group's messages for now, and then it isn't broadcast (a save that timed out may still be stored, see Persistence) | Any signed-in account. The sender is the signed-in account. | -| PATCH | `/api/groups/chat/{groupId}/messages/{messageId}` | Edit a message. 503 with `Retry-After` when S3 can't read or save the group's messages for now, and then it isn't broadcast (a save that timed out may still be stored, see Persistence) | Only its sender (403 otherwise) | +| POST | `/api/groups/chat/{groupId}/messages` | Send `{message, image}`; broadcasts it and returns the history as it was saved. 503 with `Retry-After` when S3 can't read or save the group's messages for now, and then it isn't broadcast (a save that timed out may still be stored, see Persistence) | Any signed-in account. The sender is the signed-in account. | +| PATCH | `/api/groups/chat/{groupId}/messages/{messageId}` | Edit a message; returns the history as it was saved, and 404 when no message has that id. 503 with `Retry-After` when S3 can't read or save the group's messages for now, and then it isn't broadcast (a save that timed out may still be stored, see Persistence) | Only its sender (403 otherwise) | | DELETE | `/api/groups/chat/{groupId}/messages/{messageId}` | Delete a message. 503 with `Retry-After` when S3 can't read or save the group's messages for now, and then it isn't broadcast (a save that timed out may still be stored, see Persistence) | Only its sender (403 otherwise) | | GET | `/api/groups/chat/unread` | `{total, unreadByGroup}` across your groups | You | | POST | `/api/groups/chat/{groupId}/read` | Mark a group read | You | @@ -171,6 +171,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) - `StartupServiceTest` runs the start-up check over a real `S3FileHandler` and a stand-in S3 client: checks that fail, a group that can't be checked among others, a group with no messages file yet, a group that has one, a server without S3, and a send during the check. Run it with `./mvnw test '-Dtest=StartupServiceTest'`. - `GroupChatFilesTest` also covers a write that fails, including sharing again once S3 is back, and `S3FileHandlerUploadTest` covers the strict write. - `GroupChatSendTest` also covers an upload that fails after a good read, and `GroupChatEditDeleteTest` covers edits and deletes whose read or upload fails, both through the controller over a stand-in S3 client. +- `GroupChatSendTest` and `GroupChatEditDeleteTest` also check that a send and an edit answer with the messages they saved, even when S3 fails right after. ## Known issues From aac4ab9c88d9f9898172fd136dd85d000d60446f Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Wed, 25 Nov 2026 20:03:02 -0800 Subject: [PATCH 35/46] Group chat docs: a delete of a message that isn't saved answers 404 The delete route lists its 404, the note on servers without S3 settings says edits and deletes answer 404 there, the note on saves that time out says a retried delete answers 404, and the testing list names the new checks. --- docs/group-chat-architecture.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/group-chat-architecture.md b/docs/group-chat-architecture.md index 1fd87049..7633261b 100644 --- a/docs/group-chat-architecture.md +++ b/docs/group-chat-architecture.md @@ -134,7 +134,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) | GET | `/api/groups/chat/{groupId}/messages` | The group's messages | Any signed-in account | | POST | `/api/groups/chat/{groupId}/messages` | Send `{message, image}`; broadcasts it and returns the history as it was saved. 503 with `Retry-After` when S3 can't read or save the group's messages for now, and then it isn't broadcast (a save that timed out may still be stored, see Persistence) | Any signed-in account. The sender is the signed-in account. | | PATCH | `/api/groups/chat/{groupId}/messages/{messageId}` | Edit a message; returns the history as it was saved, and 404 when no message has that id. 503 with `Retry-After` when S3 can't read or save the group's messages for now, and then it isn't broadcast (a save that timed out may still be stored, see Persistence) | Only its sender (403 otherwise) | -| DELETE | `/api/groups/chat/{groupId}/messages/{messageId}` | Delete a message. 503 with `Retry-After` when S3 can't read or save the group's messages for now, and then it isn't broadcast (a save that timed out may still be stored, see Persistence) | Only its sender (403 otherwise) | +| DELETE | `/api/groups/chat/{groupId}/messages/{messageId}` | Delete a message; 404 when no message has that id, and then nothing is broadcast. 503 with `Retry-After` when S3 can't read or save the group's messages for now, and then it isn't broadcast (a save that timed out may still be stored, see Persistence) | Only its sender (403 otherwise) | | GET | `/api/groups/chat/unread` | `{total, unreadByGroup}` across your groups | You | | POST | `/api/groups/chat/{groupId}/read` | Mark a group read | You | | GET | `/api/groups/chat/{groupId}/files` | Shared files with who uploaded them, each with its bytes as `base64Data` | Any signed-in account | @@ -154,12 +154,12 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) | Presence | Memory only | Lost on restart; rebuilt as clients rejoin. | - **History is keyed by group name, not id.** Renaming a group with `PUT /api/groups/{id}` leaves its history under the old name. -- **Without S3 settings** (AWS credentials, region and bucket), the server logs `S3 is disabled` at startup. Sends still broadcast live, but nothing is saved, so history and files come back empty. This is the normal state of a local server. +- **Without S3 settings** (AWS credentials, region and bucket), the server logs `S3 is disabled` at startup. Sends still broadcast live, but nothing is saved, so history and files come back empty, and an edit or delete answers 404 since there's no message to change. This is the normal state of a local server. - **At every start, `StartupService` creates any missing chat files.** It checks each group and writes an empty messages file and `shared-files/` placeholder where they're missing; the four course groups that `ModelInit` seeds start with none. The check of the messages file is strict (`S3FileHandler.fileExistsOrThrow`), since an empty file written over the real one would erase the group's history: only S3's 404 means there is no file. Any other failure to check (a throttle, a 5xx, a timeout, S3 refusing it) is logged with the group's name and leaves that group as it is (the next start checks it again), and the other groups are still checked. The check holds the group's message lock, so a message sent while the server is starting isn't written over. Without S3 settings nothing is checked. - **Every new message rewrites the whole file**, read then write. Sending, editing and deleting take one lock per group (`messageLocks` in `GroupChatService`), so two at once keep both changes. The lock only holds within one server: several servers writing the same bucket would need S3's conditional writes. Sending, editing and deleting read the file strictly (`S3FileHandler.decodeFileOrThrow`), since writing back an empty read would replace the whole history: only S3's 404 reads as no messages yet, and any other failure to read refuses the change. They save it strictly too (`S3FileHandler.uploadFileOrThrow`), so a change S3 didn't take isn't answered as saved. When S3 timed out (its own `RequestTimeout` comes as a 400), couldn't be reached or answered with a 5xx, reading or saving, that's a 503 with `Retry-After` (`MessagesStorageUnavailableException`), by the same rule as shared files; S3 refusing the request (any other 4xx) or a bug here gets the route's usual 400. - **A shared file's bytes never go over the socket.** `sendFileServer` names the file and its size; a member downloads it from `/files/content`. Sending the bytes to every subscriber could overflow a session's 512 KB send buffer while another frame was queued, and Spring closes a session that overflows. - **A shared file whose write timed out may still be stored.** S3 can store a file and then fail to answer, and the AWS SDK's own retries can fail too. The upload then answers 503 without a "shared by" record or a `sendFileServer` frame, and sharing it again finds the path taken (409), which the page handles like any other taken name. -- **A message whose save timed out may still be stored.** S3 can store the messages file and then fail to answer. The change then answers 503 and isn't broadcast, so a message stored that way shows only after a reload, and a send tried again shows up twice. An edit or delete tried again makes the same change, so it lands once. +- **A message whose save timed out may still be stored.** S3 can store the messages file and then fail to answer. The change then answers 503 and isn't broadcast, so a message stored that way shows only after a reload, and a send tried again shows up twice. An edit tried again makes the same change, so it lands once, and a delete tried again finds nothing and answers 404. ## Testing @@ -172,6 +172,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) - `GroupChatFilesTest` also covers a write that fails, including sharing again once S3 is back, and `S3FileHandlerUploadTest` covers the strict write. - `GroupChatSendTest` also covers an upload that fails after a good read, and `GroupChatEditDeleteTest` covers edits and deletes whose read or upload fails, both through the controller over a stand-in S3 client. - `GroupChatSendTest` and `GroupChatEditDeleteTest` also check that a send and an edit answer with the messages they saved, even when S3 fails right after. +- `GroupChatEditDeleteTest` also checks that a delete of a message that isn't saved answers 404 and tells no one, with or without S3 settings. ## Known issues From d5c385288d6ef6a941f6d046c1c48b02f2570fcd Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Wed, 25 Nov 2026 20:08:12 -0800 Subject: [PATCH 36/46] Group chat docs: a line that doesn't read as a message is kept A new note under Persistence says a send, edit or delete writes an unreadable line back as it was, loading leaves it out, and a message that can't be written refuses the change instead of being saved as {}. The testing list names GroupChatMessagesFileTest. --- docs/group-chat-architecture.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/group-chat-architecture.md b/docs/group-chat-architecture.md index 7633261b..4601a166 100644 --- a/docs/group-chat-architecture.md +++ b/docs/group-chat-architecture.md @@ -160,6 +160,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) - **A shared file's bytes never go over the socket.** `sendFileServer` names the file and its size; a member downloads it from `/files/content`. Sending the bytes to every subscriber could overflow a session's 512 KB send buffer while another frame was queued, and Spring closes a session that overflows. - **A shared file whose write timed out may still be stored.** S3 can store a file and then fail to answer, and the AWS SDK's own retries can fail too. The upload then answers 503 without a "shared by" record or a `sendFileServer` frame, and sharing it again finds the path taken (409), which the page handles like any other taken name. - **A message whose save timed out may still be stored.** S3 can store the messages file and then fail to answer. The change then answers 503 and isn't broadcast, so a message stored that way shows only after a reload, and a send tried again shows up twice. An edit tried again makes the same change, so it lands once, and a delete tried again finds nothing and answers 404. +- **A line that doesn't read as a message is kept.** Loading the chat leaves it out and logs a warning, and a send, edit or delete writes it back as it was (`MessagesLine` in `GroupChatService`), so one bad line isn't lost the next time the file is saved. A message that can't be written as JSON refuses the change, and the route gives its usual 400, instead of being saved as `{}`. ## Testing @@ -173,6 +174,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) - `GroupChatSendTest` also covers an upload that fails after a good read, and `GroupChatEditDeleteTest` covers edits and deletes whose read or upload fails, both through the controller over a stand-in S3 client. - `GroupChatSendTest` and `GroupChatEditDeleteTest` also check that a send and an edit answer with the messages they saved, even when S3 fails right after. - `GroupChatEditDeleteTest` also checks that a delete of a message that isn't saved answers 404 and tells no one, with or without S3 settings. +- `GroupChatMessagesFileTest` covers a line that doesn't read as a message, kept in place through a send, an edit and a delete and left out when the chat loads, and a message that can't be written. ## Known issues From 3ff34447652ceb19100ef837edeb708e13195a23 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Wed, 25 Nov 2026 21:02:01 -0800 Subject: [PATCH 37/46] 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 38/46] 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 39/46] 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 40/46] 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 41/46] 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 42/46] 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 43/46] 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()); From c535fbb1c7d90e7e721cf1954105e662111e43c6 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Thu, 26 Nov 2026 00:06:16 -0800 Subject: [PATCH 44/46] Mentors: reactions follow the mentor rules A group's reactions (reading them, adding one, taking one back) use the same mentor check as its messages. In a direct message that includes a mentor, adding or taking back a reaction is refused like sending, and reading reactions still works like reading messages. --- docs/group-chat-architecture.md | 4 ++-- .../DirectMessageApiController.java | 6 ++++++ .../mvc/groups/GroupChatApiController.java | 14 +++++++++++-- .../DirectMessageMentorTest.java | 11 ++++++++++ .../mvc/groups/GroupChatMentorTest.java | 21 +++++++++++++++++++ 5 files changed, 52 insertions(+), 4 deletions(-) diff --git a/docs/group-chat-architecture.md b/docs/group-chat-architecture.md index 52f0b19f..66cd8374 100644 --- a/docs/group-chat-architecture.md +++ b/docs/group-chat-architecture.md @@ -152,13 +152,13 @@ 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` (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 | +| `/api/groups/chat/{id}/messages` (read, send, edit, delete) and their reactions (`/reactions`, adding or taking one back), `/read`, `/files` (list, upload), `/files/index`, `/files/content`; `GET /api/groups/{id}`; the older `/api/chat/{groupId}` (read, post) | Only a group they are a member of, that isn't a class group and has at least 2 members who aren't mentors (`mentor_not_in_group`, `mentor_class_group`, `mentor_team_too_small`) | As before | | `GET /api/groups/person/{personId}`, `GET /api/groups/chat/analytics/{personId}` | Only their own id (`mentor_cannot_manage`). Their own group list holds only the groups they may use | As before | | `GET /api/groups`, `/search`, `POST /api/groups`, `/bulk`, `PUT` and `DELETE /api/groups/{id}`, `/{id}/grades` | Refused (`mentor_cannot_manage`) | As before, except that a new group's `memberIds` may hold a mentor only if its maker could add them | | `PUT /api/groups/class-memberships` | Only an empty list, to leave every class group; any class is refused (`mentor_class_group`) | As before | | `POST /api/groups/{id}/members/{personId}` | Refused, themselves included (`mentor_cannot_manage`) | Adding a mentor needs a member who isn't a mentor, or a teacher (`team_manages_mentors`), and a group a mentor may use. Adding anyone else: as before | | `DELETE /api/groups/{id}/members/{personId}` | Only themselves, to leave (`mentor_cannot_manage`) | Removing a mentor needs a member who isn't a mentor, or a teacher (`team_manages_mentors`). Leaving: always | -| `POST /api/dm/conversations`, `/api/dm/conversations/{id}/messages` (send, edit), and 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 | +| `POST /api/dm/conversations`, `/api/dm/conversations/{id}/messages` (send, edit, and adding or taking back a reaction), and the UI Builder's `POST /api/ui-builder/published/{slug}/message-owner` | Refused (`mentor_no_direct_messages`) | Refused when the conversation would include a mentor. Reading old messages and deleting your own still work | - A group response marks each member `"mentor": true` or `false`, so a page can list a team's mentors. - `POST /api/groups/bulk` makes the other groups when one breaks a mentor rule, and lists that one under `errors` with the refusal's message (one bad group doesn't stop a teacher's batch), so its answer stays 200. 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 5d85fdac..43a0a8a3 100644 --- a/src/main/java/com/open/spring/mvc/directmessages/DirectMessageApiController.java +++ b/src/main/java/com/open/spring/mvc/directmessages/DirectMessageApiController.java @@ -379,6 +379,12 @@ private ResponseEntity setReaction(UserDetails userDetails, Long id, Lon return new ResponseEntity<>(HttpStatus.FORBIDDEN); } + // Reacting follows the send rule, like posting and editing + Optional refusal = MentorRules.shareDirectMessages(conversation.getParticipants()); + if (refusal.isPresent()) { + return refusal.get().toResponse(); + } + Optional reaction = Reaction.fromKey(key); if (reaction.isEmpty()) { return new ResponseEntity<>(Map.of("error", "unknown reaction"), HttpStatus.BAD_REQUEST); 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 06bb4d5b..72f5cfe8 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatApiController.java @@ -338,9 +338,14 @@ public ResponseEntity getReactions(@PathVariable Long groupId) { if (currentPerson() == null) { return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); } - if (groupsRepository.findById(groupId).isEmpty()) { + Optional groupOpt = groupsRepository.findById(groupId); + if (groupOpt.isEmpty()) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } + ResponseEntity refusal = mentorRefusal(groupOpt.get()); + if (refusal != null) { + return refusal; + } return new ResponseEntity<>(reactionService.forChat(ChatType.GROUP, groupId), HttpStatus.OK); } @@ -367,9 +372,14 @@ private ResponseEntity setReaction(Long groupId, String messageId, String key if (person == null) { return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); } - if (groupsRepository.findById(groupId).isEmpty()) { + Optional groupOpt = groupsRepository.findById(groupId); + if (groupOpt.isEmpty()) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } + ResponseEntity refusal = mentorRefusal(groupOpt.get()); + if (refusal != null) { + return refusal; + } Optional reaction = Reaction.fromKey(key); if (reaction.isEmpty()) { return new ResponseEntity<>("unknown reaction", HttpStatus.BAD_REQUEST); diff --git a/src/test/java/com/open/spring/mvc/directmessages/DirectMessageMentorTest.java b/src/test/java/com/open/spring/mvc/directmessages/DirectMessageMentorTest.java index 453668d3..ff77aafe 100644 --- a/src/test/java/com/open/spring/mvc/directmessages/DirectMessageMentorTest.java +++ b/src/test/java/com/open/spring/mvc/directmessages/DirectMessageMentorTest.java @@ -2,6 +2,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; @@ -132,6 +133,16 @@ void editingInAConversationWithAMentorIsRefused() { verify(service, never()).editMessage(any(), any(), anyLong(), anyString()); } + /** Reacting is like sending, so it's refused in a conversation that includes a mentor; reading reactions still works. */ + @Test + void reactingInAConversationWithAMentorIsRefused() { + conversation(16L, student, mentor); + assertRefused(controller.addReaction(signedIn(student), 16L, 5L, "like")); + assertRefused(controller.removeReaction(signedIn(mentor), 16L, 5L, "like")); + verify(service, never()).setReaction(any(), any(), anyLong(), any(), anyBoolean()); + assertEquals(HttpStatus.OK, controller.getReactions(signedIn(student), 16L).getStatusCode()); + } + @Test void readingAnOldConversationWithAMentorStillWorks() { conversation(13L, student, mentor); 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 300baf3f..57051c82 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupChatMentorTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatMentorTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; @@ -142,6 +143,26 @@ void aMentorWhoIsNotAMemberIsRefusedEverywhere() { verify(chat, never()).readSharedFile(anyString(), anyString()); } + /** Reactions are part of a group's chat, so they follow the same mentor rules. */ + @Test + void aMentorWhoIsNotAMemberCannotSeeOrChangeReactions() { + signIn(otherMentor); + String reason = "mentor_not_in_group"; + String message = "0f8fad5b-d9cb-469f-a165-70867728950e"; + assertRefused(reason, controller.getReactions(TEAM)); + assertRefused(reason, controller.addReaction(TEAM, message, "like")); + assertRefused(reason, controller.removeReaction(TEAM, message, "like")); + verify(realtime, never()).setReaction(anyLong(), any(), anyString(), any(), anyBoolean()); + } + + @Test + void aMemberMentorWithATeamOfTwoReacts() { + signIn(mentor); + assertEquals(HttpStatus.OK, controller.getReactions(TEAM).getStatusCode()); + assertEquals(HttpStatus.OK, + controller.addReaction(TEAM, "0f8fad5b-d9cb-469f-a165-70867728950e", "like").getStatusCode()); + } + @Test void aMemberMentorWithATeamOfTwoReadsAndPosts() { signIn(mentor); From 8fc7ef69ede86b24e2983744f03545203b432b96 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Thu, 26 Nov 2026 00:16:32 -0800 Subject: [PATCH 45/46] Group chat: a delete still tells the group when its reactions can't be removed By the time the reactions are removed, the message is already gone from S3. A database error there answered an error and told no one, and a retry found nothing to delete (404). Now the error is logged, the group still gets deleteMessageServer, and the leftover reactions are never shown. --- docs/group-chat-architecture.md | 2 +- .../mvc/groups/GroupChatRealtimeService.java | 12 +++++++++++- .../spring/mvc/groups/GroupChatReactionTest.java | 15 +++++++++++++++ 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/docs/group-chat-architecture.md b/docs/group-chat-architecture.md index 8cf9e929..abd5ca3d 100644 --- a/docs/group-chat-architecture.md +++ b/docs/group-chat-architecture.md @@ -171,7 +171,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) People react to a message in a group chat or a direct message with one of six emoji. Spring stores the key, never the emoji: `like` 👍, `love` ❤️, `haha` 😂, `wow` 😮, `sad` 😢, `celebrate` 🎉. The list is `Reaction` in `mvc/reactions`, and Pages' Messages `reactions.js` lists the same keys in the same order, so change both together. - A person can leave several reactions on one message, one of each. PUT adds yours and DELETE removes it. Both answer `{messageId, reactions}`, where `reactions` is `[{reaction, people: [{uid, name}]}]` in the list's order, with people sorted by name. -- Group chats use the three routes in the table above. A reaction never reads or writes the group's S3 file: checking that the message exists would mean downloading the whole file, images and all, on every click. So the `messageId` only has to be a lowercase UUID, like the ids Spring saves, and a reaction on a message that doesn't exist is never shown. Deleting a message removes its reactions. +- Group chats use the three routes in the table above. A reaction never reads or writes the group's S3 file: checking that the message exists would mean downloading the whole file, images and all, on every click. So the `messageId` only has to be a lowercase UUID, like the ids Spring saves, and a reaction on a message that doesn't exist is never shown. Deleting a message removes its reactions. If the database can't remove them, the delete still goes through and is broadcast, the error is logged, and the leftover reactions are never shown. - Direct messages have the same three routes under `/api/dm/conversations/{id}`: `GET .../reactions`, and `PUT` or `DELETE .../messages/{messageId}/reactions/{reaction}`. Only the conversation's participants may use them (403 otherwise). A message from another conversation is 404, and a deleted one is 409. The change goes out on `/topic/dm/{id}` as `type: "reactions"`, with `id`, `conversationId` and `reactions`. - A reaction is not a message. It sends no push notification, changes no unread count, and doesn't show up in search. - `GroupChatEvent` and `DirectMessageEvent` carry `reactions` only on reaction frames (`@JsonInclude(NON_NULL)`), so every other frame is unchanged. The course chats ignore `reactionsServer`. diff --git a/src/main/java/com/open/spring/mvc/groups/GroupChatRealtimeService.java b/src/main/java/com/open/spring/mvc/groups/GroupChatRealtimeService.java index 9f8d1c69..11c24a52 100644 --- a/src/main/java/com/open/spring/mvc/groups/GroupChatRealtimeService.java +++ b/src/main/java/com/open/spring/mvc/groups/GroupChatRealtimeService.java @@ -4,6 +4,7 @@ import java.util.List; import java.util.Optional; +import org.springframework.dao.DataAccessException; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.stereotype.Service; @@ -14,6 +15,7 @@ import com.open.spring.mvc.reactions.Reaction; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; /** * Service to handle the real-time publishing of group chat messages and presence events. @@ -21,6 +23,7 @@ */ @Service @RequiredArgsConstructor +@Slf4j public class GroupChatRealtimeService { public static final String GROUP_TOPIC_PREFIX = "/topic/group/"; @@ -93,7 +96,14 @@ public boolean deleteMessage(Long groupId, String messageId, String requesterUid // Telling the group about a message that isn't saved would take it off everyone's screen. return false; } - reactionService.removeAllFor(ChatType.GROUP, groupId, messageId); + try { + reactionService.removeAllFor(ChatType.GROUP, groupId, messageId); + } catch (DataAccessException e) { + // The message is already gone from S3, so the group still has to hear about it, and a + // retry would find nothing to delete. Its reactions stay in the table, where no message + // shows them. + log.warn("Could not remove the reactions of deleted message {} in group {}", messageId, groupId, e); + } GroupChatEvent event = GroupChatEvent.builder() .context("deleteMessageServer") diff --git a/src/test/java/com/open/spring/mvc/groups/GroupChatReactionTest.java b/src/test/java/com/open/spring/mvc/groups/GroupChatReactionTest.java index d5d4d054..314a7ae0 100644 --- a/src/test/java/com/open/spring/mvc/groups/GroupChatReactionTest.java +++ b/src/test/java/com/open/spring/mvc/groups/GroupChatReactionTest.java @@ -6,6 +6,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; @@ -20,6 +21,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; +import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.messaging.simp.SimpMessagingTemplate; @@ -174,6 +176,19 @@ void deletingAMessageThatIsntSavedKeepsItsReactions() { verify(reactionService, never()).removeAllFor(any(), any(), any()); } + @Test + void aDeleteStillTellsTheGroupWhenItsReactionsCantBeRemoved() { + doReturn(true).when(chat).deleteMessage("Team Three", MESSAGE_ID, "ada"); + doThrow(new DataAccessResourceFailureException("no message_reaction table")) + .when(reactionService).removeAllFor(ChatType.GROUP, 3L, MESSAGE_ID); + + assertTrue(realtime.deleteMessage(3L, MESSAGE_ID, "ada")); + + ArgumentCaptor frame = ArgumentCaptor.forClass(GroupChatEvent.class); + verify(messaging).convertAndSend(eq("/topic/group/3"), frame.capture()); + assertEquals("deleteMessageServer", frame.getValue().getContext()); + } + @Test void onlyAReactionsFrameCarriesReactions() throws Exception { ObjectMapper json = new ObjectMapper(); From 6aa4b6a42e2d3086da006e7533230666dfd60c13 Mon Sep 17 00:00:00 2001 From: Samarth Vaka Date: Thu, 26 Nov 2026 00:21:27 -0800 Subject: [PATCH 46/46] Reactions: a DM delete no longer rolls back when its reactions can't be removed DirectMessageService.deleteMessage removed the message's reactions inside its own transaction, so any error from the reactions table, such as a missing message_reaction table under ddl-auto=none, rolled back the delete and sent no "deleted" frame. The reactions are now removed after the delete commits, and a failure there is logged. removeAllFor runs in a transaction of its own (REQUIRES_NEW), since Spring runs a transactional call made from afterCommit inside the finished transaction, where it would never commit. MessageReactionTableInitializer's comment now says what breaks without the table. --- docs/group-chat-architecture.md | 4 +-- .../directmessages/DirectMessageService.java | 19 ++++++++++++-- .../mvc/reactions/MessageReactionService.java | 8 ++++-- .../MessageReactionTableInitializer.java | 5 ++-- .../DirectMessageReactionTest.java | 25 +++++++++++++++++++ .../reactions/MessageReactionServiceTest.java | 14 +++++++++++ 6 files changed, 67 insertions(+), 8 deletions(-) diff --git a/docs/group-chat-architecture.md b/docs/group-chat-architecture.md index abd5ca3d..2f76a451 100644 --- a/docs/group-chat-architecture.md +++ b/docs/group-chat-architecture.md @@ -171,7 +171,7 @@ Every route needs a signed-in account (the JWT cookie from `POST /authenticate`) People react to a message in a group chat or a direct message with one of six emoji. Spring stores the key, never the emoji: `like` 👍, `love` ❤️, `haha` 😂, `wow` 😮, `sad` 😢, `celebrate` 🎉. The list is `Reaction` in `mvc/reactions`, and Pages' Messages `reactions.js` lists the same keys in the same order, so change both together. - A person can leave several reactions on one message, one of each. PUT adds yours and DELETE removes it. Both answer `{messageId, reactions}`, where `reactions` is `[{reaction, people: [{uid, name}]}]` in the list's order, with people sorted by name. -- Group chats use the three routes in the table above. A reaction never reads or writes the group's S3 file: checking that the message exists would mean downloading the whole file, images and all, on every click. So the `messageId` only has to be a lowercase UUID, like the ids Spring saves, and a reaction on a message that doesn't exist is never shown. Deleting a message removes its reactions. If the database can't remove them, the delete still goes through and is broadcast, the error is logged, and the leftover reactions are never shown. +- Group chats use the three routes in the table above. A reaction never reads or writes the group's S3 file: checking that the message exists would mean downloading the whole file, images and all, on every click. So the `messageId` only has to be a lowercase UUID, like the ids Spring saves, and a reaction on a message that doesn't exist is never shown. Deleting a message removes its reactions, a DM's once the delete commits. If the database can't remove them, the delete still goes through and is broadcast, and the error is logged. - Direct messages have the same three routes under `/api/dm/conversations/{id}`: `GET .../reactions`, and `PUT` or `DELETE .../messages/{messageId}/reactions/{reaction}`. Only the conversation's participants may use them (403 otherwise). A message from another conversation is 404, and a deleted one is 409. The change goes out on `/topic/dm/{id}` as `type: "reactions"`, with `id`, `conversationId` and `reactions`. - A reaction is not a message. It sends no push notification, changes no unread count, and doesn't show up in search. - `GroupChatEvent` and `DirectMessageEvent` carry `reactions` only on reaction frames (`@JsonInclude(NON_NULL)`), so every other frame is unchanged. The course chats ignore `reactionsServer`. @@ -180,7 +180,7 @@ People react to a message in a group chat or a direct message with one of six em - `api/groups.http`: open it in VS Code with the REST Client extension and run the requests in order. Set `baseUrl`, `adminUid` and `adminPassword` under `rest-client.environmentVariables` in the Git-ignored `.vscode/settings.json`. Never put passwords in the file. It creates a test group, adds you, sends and reads messages, checks unread counts, and deletes the group. - **The WebSocket can't be tested from a `.http` file.** To check it, open a course page with a chat against a local server and watch the browser's Network panel (WS filter) for frames on `/topic/group/{id}`. Or connect any STOMP client to `ws://localhost:8589/ws-chat/websocket` (SockJS's raw WebSocket transport), send `CONNECT`, `SUBSCRIBE` to `/topic/group/{id}`, and `SEND` JSON events to `/app/groups.chat`. A `SUBSCRIBE` to `/topic/dm/{id}` only goes through when the handshake carries a participant's `jwt_java_spring` cookie (a `Cookie` header) and an `Origin` header from the REST API's CORS list, such as `http://localhost:4500`. Without them, or for a wildcard subscription, a `/user/...` destination or a `SEND` to any `/topic/...` destination, the frame is dropped and the server logs a "refused" warning. Only the server publishes to topics; clients send through REST or `/app/groups.chat`. Run the socket's own tests with `./mvnw test '-Dtest=DirectMessageTopic*Test,ChatSocketIdentityInterceptorTest,WebSocketBrokerConfigTest'`. -- Reactions: `./mvnw test '-Dtest=GroupChatReactionTest,DirectMessageReactionTest,MessageReaction*Test,ReactionTest'`. They cover both chats' frames and status codes, that a group reaction never touches S3 and a DM reaction never sends a push, the summaries' order, and the table's primary key on SQLite. +- Reactions: `./mvnw test '-Dtest=GroupChatReactionTest,DirectMessageReactionTest,MessageReaction*Test,ReactionTest'`. They cover both chats' frames and status codes, that a group reaction never touches S3 and a DM reaction never sends a push, the summaries' order, the table's primary key on SQLite, and a delete whose reactions can't be removed. - Run the chat regression tests with `./mvnw test '-Dtest=GroupChat*Test'`. They cover UID-based ownership, REST identity forwarding and unread counts. `GroupChatFilesTest` covers the file index, one-file downloads, the path rules, the bytes-free frame, uploads that land together, a path that is already shared, two uploads of one path at once, and a check that fails; `S3FileHandlerExistsTest` covers the strict check. - `GroupChatServiceTest` covers two sends, an edit and a send, and a delete and a send landing at once. - `GroupChatSendTest` sends through the controller to a real `S3FileHandler` over a stand-in S3 client: a read that fails, a read S3 refuses, a bug, a group with no messages file yet, and a server without S3. `S3FileHandlerDecodeTest` covers the strict read. Run the S3 handler tests with `./mvnw test '-Dtest=S3FileHandler*Test'`. diff --git a/src/main/java/com/open/spring/mvc/directmessages/DirectMessageService.java b/src/main/java/com/open/spring/mvc/directmessages/DirectMessageService.java index 3ab1b53b..dc82a598 100644 --- a/src/main/java/com/open/spring/mvc/directmessages/DirectMessageService.java +++ b/src/main/java/com/open/spring/mvc/directmessages/DirectMessageService.java @@ -8,6 +8,7 @@ import java.util.NoSuchElementException; import java.util.Set; +import org.springframework.dao.DataAccessException; import org.springframework.data.domain.PageRequest; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.stereotype.Service; @@ -22,6 +23,7 @@ import com.open.spring.mvc.reactions.Reaction; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; /** * Business logic for direct messages: finding/creating conversations, checking @@ -31,6 +33,7 @@ */ @Service @RequiredArgsConstructor +@Slf4j public class DirectMessageService { public static final String DM_TOPIC_PREFIX = "/topic/dm/"; @@ -228,8 +231,10 @@ public void deleteMessage(DirectMessageConversation conversation, Person request message.setDeleted(true); message.setBody(""); messageRepository.save(message); - // A tombstone shows no reactions, so none are kept for it. - reactionService.removeAllFor(ChatType.DM, conversation.getId(), String.valueOf(messageId)); + // A tombstone shows no reactions, so none are kept for it. They're removed after the delete + // commits: an error from the reactions table inside this transaction would undo the delete. + Long conversationId = conversation.getId(); + afterCommit(() -> removeReactions(conversationId, messageId)); DirectMessageEvent event = DirectMessageEvent.builder() .id(message.getId()) @@ -282,6 +287,16 @@ public List setReaction(DirectMessageCon } // Runs once the current transaction commits, or right away outside one. + /** Removes a deleted message's reactions. The delete is already done, so a failure is only logged. */ + private void removeReactions(Long conversationId, Long messageId) { + try { + reactionService.removeAllFor(ChatType.DM, conversationId, String.valueOf(messageId)); + } catch (DataAccessException e) { + log.warn("Could not remove the reactions of deleted message {} in conversation {}", + messageId, conversationId, e); + } + } + private static void afterCommit(Runnable action) { if (TransactionSynchronizationManager.isSynchronizationActive()) { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { diff --git a/src/main/java/com/open/spring/mvc/reactions/MessageReactionService.java b/src/main/java/com/open/spring/mvc/reactions/MessageReactionService.java index f498f897..afb8540c 100644 --- a/src/main/java/com/open/spring/mvc/reactions/MessageReactionService.java +++ b/src/main/java/com/open/spring/mvc/reactions/MessageReactionService.java @@ -91,8 +91,12 @@ public Map> forChat(ChatType type, Long chatId) { return result; } - /** Removes every reaction on a message, as when the message is deleted. */ - @Transactional + /** + * Removes every reaction on a message, as when the message is deleted. The chats call it once + * their delete is done (a DM's after its transaction commits), so it runs in a transaction of + * its own: a transactional call made from inside a finished transaction never commits. + */ + @Transactional(propagation = Propagation.REQUIRES_NEW) public void removeAllFor(ChatType type, Long chatId, String messageId) { repository.deleteAllOnMessage(type, chatId, messageId); } diff --git a/src/main/java/com/open/spring/mvc/reactions/MessageReactionTableInitializer.java b/src/main/java/com/open/spring/mvc/reactions/MessageReactionTableInitializer.java index a2cbdfad..a7412931 100644 --- a/src/main/java/com/open/spring/mvc/reactions/MessageReactionTableInitializer.java +++ b/src/main/java/com/open/spring/mvc/reactions/MessageReactionTableInitializer.java @@ -38,8 +38,9 @@ public ApplicationRunner migrateMessageReaction() { try { jdbcTemplate.execute(CREATE_TABLE); } catch (DataAccessException e) { - // The rest of Spring keeps running, as it does when another table can't be made; - // only the reaction routes fail, until the table exists. + // The rest of Spring keeps running, as it does when another table can't be made. + // Until the table exists the reaction routes fail, and deleting a message still + // works but logs that its reactions couldn't be removed. logger.error("Could not create the message_reaction table, so reactions won't work: {}", e.getMessage()); } }; diff --git a/src/test/java/com/open/spring/mvc/directmessages/DirectMessageReactionTest.java b/src/test/java/com/open/spring/mvc/directmessages/DirectMessageReactionTest.java index 01fcc894..04197e05 100644 --- a/src/test/java/com/open/spring/mvc/directmessages/DirectMessageReactionTest.java +++ b/src/test/java/com/open/spring/mvc/directmessages/DirectMessageReactionTest.java @@ -6,6 +6,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -20,6 +21,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; +import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.messaging.simp.SimpMessagingTemplate; @@ -204,6 +206,29 @@ void deletingAMessageRemovesItsReactions() { verify(reactionService).removeAllFor(ChatType.DM, 7L, "42"); } + @Test + void aDeleteStillGoesThroughWhenItsReactionsCantBeRemoved() { + doThrow(new DataAccessResourceFailureException("no message_reaction table")) + .when(reactionService).removeAllFor(ChatType.DM, 7L, "42"); + TransactionSynchronizationManager.initSynchronization(); + try { + service.deleteMessage(conversation, bob, 42L); + + // Nothing in the delete's own transaction touches the reactions, so they can't undo it. + verify(reactionService, never()).removeAllFor(any(), any(), any()); + assertTrue(message.isDeleted()); + ArgumentCaptor frame = ArgumentCaptor.forClass(DirectMessageEvent.class); + verify(messagingTemplate).convertAndSend(eq("/topic/dm/7"), frame.capture()); + assertEquals("deleted", frame.getValue().getType()); + + // Once it commits they're removed, and a failure there is logged, not thrown at the caller. + TransactionSynchronizationManager.getSynchronizations().forEach(TransactionSynchronization::afterCommit); + verify(reactionService).removeAllFor(ChatType.DM, 7L, "42"); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + } + @Test void onlyAReactionsFrameCarriesReactions() throws Exception { ObjectMapper json = new ObjectMapper(); diff --git a/src/test/java/com/open/spring/mvc/reactions/MessageReactionServiceTest.java b/src/test/java/com/open/spring/mvc/reactions/MessageReactionServiceTest.java index d14b7a4b..aa27a3c2 100644 --- a/src/test/java/com/open/spring/mvc/reactions/MessageReactionServiceTest.java +++ b/src/test/java/com/open/spring/mvc/reactions/MessageReactionServiceTest.java @@ -13,6 +13,8 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; import com.open.spring.mvc.person.Person; import com.open.spring.mvc.reactions.MessageReactionService.ReactionSummary; @@ -154,4 +156,16 @@ private static Person person(long id, String uid, String name) { person.setName(name); return person; } + + @Test + void removingAMessagesReactionsCommitsOnItsOwn() throws Exception { + // Chats remove a deleted message's reactions after the delete commits. Spring runs a + // transactional call made then inside the finished transaction, where nothing commits, + // unless it asks for a new one. + Transactional transactional = MessageReactionService.class + .getMethod("removeAllFor", ChatType.class, Long.class, String.class) + .getAnnotation(Transactional.class); + + assertEquals(Propagation.REQUIRES_NEW, transactional.propagation()); + } }