Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Communication: Fix mentioned users recieving notifications in conversations they are not part of #9814

Merged

Conversation

PaRangger
Copy link
Contributor

@PaRangger PaRangger commented Nov 18, 2024

Checklist

General

Server

  • Important: I implemented the changes with a very good performance and prevented too many (unnecessary) and too complex database calls.
  • I strictly followed the principle of data economy for all database calls.
  • I strictly followed the server coding and design guidelines.
  • I documented the Java code using JavaDoc style.

Motivation and Context

Currently, when a user who is not part of a conversation (e.g., private channels) is mentioned in that conversation, the server stores a notification for them in the database. This behavior grants the user access to view messages from the conversation despite not being a participant, resulting in potential information leakage.

Addresses #9588

Description

This was not the case for answer posts. Thus I used the filtering method of the answer posts function to check if a mentioned user is permitted to recieve a notification. This should not lead to additional calls to the database, since the method used is the .getConversation method of a post, which is used beforehand.

Steps for Testing

Prerequisites:

  • 1 Instructor
  • 2 Students
  • 1 Course with communication enabled
  1. Log in to Artemis with Student A/Instructor
  2. Navigate to course
  3. Navigate to communication
  4. Create a private channel with Student B
  5. Mention Instructor if logged in as Student A and Student A if logged in as the Instructor
  6. Log into mentioned User
  7. Check if notification does not show up
  8. Do the same in a channel where the recipient is a part of and check if they get the notification

Testserver States

Note

These badges show the state of the test servers.
Green = Currently available, Red = Currently locked
Click on the badges to get to the test servers.







Review Progress

Code Review

  • Code Review 1
  • Code Review 2

Manual Tests

  • Test 1
  • Test 2

Test Coverage

Server

Class/File Line Coverage Confirmation (assert/expect)
ConversationNotificationService.java 94%
SingleUserNotificationService.java 95%

Summary by CodeRabbit

  • New Features

    • Enhanced user notification handling for message replies, improving filtering of recipients based on conversation context.
    • Introduced a new method to streamline the filtering of allowed recipients for notifications.
  • Bug Fixes

    • Refactored notification logic to improve clarity and maintainability, reducing complexity in the notification process.
  • Documentation

    • Updated method signatures and added new methods for better understanding of notification workflows.

@PaRangger PaRangger added bugfix communication Pull requests that affect the corresponding module labels Nov 18, 2024
@PaRangger PaRangger self-assigned this Nov 18, 2024
@github-actions github-actions bot added the server Pull requests that update Java code. (Added Automatically!) label Nov 18, 2024
@PaRangger PaRangger temporarily deployed to artemis-test3.artemis.cit.tum.de November 18, 2024 14:11 — with GitHub Actions Inactive
@PaRangger PaRangger marked this pull request as ready for review November 18, 2024 14:21
@PaRangger PaRangger requested a review from a team as a code owner November 18, 2024 14:21
Copy link

coderabbitai bot commented Nov 18, 2024

Walkthrough

The changes involve modifications to the ConversationNotificationService and SingleUserNotificationService classes. The ConversationNotificationService now includes a new dependency, SingleUserNotificationService, which is injected via the constructor. The createNotification method has been updated to pass an additional createdMessage parameter to the save method, which has also been modified to utilize the new service for filtering recipients. The SingleUserNotificationService has been refactored to simplify the notification logic by introducing a new method for filtering allowed recipients.

Changes

File Change Summary
src/main/java/de/tum/cit/aet/artemis/communication/service/notifications/ConversationNotificationService.java - Constructor updated to include SingleUserNotificationService.
- save method signature updated to accept Post createdMessage.
- Logic in save method adjusted to use singleUserNotificationService.filterAllowedRecipientsInMentionedUsers.
src/main/java/de/tum/cit/aet/artemis/communication/service/notifications/SingleUserNotificationService.java - New method filterAllowedRecipientsInMentionedUsers added to encapsulate filtering logic for mentioned users.
- Refactored notifyInvolvedUsersAboutNewMessageReply to use the new filtering method.

Suggested labels

ready to merge, component:Communication, tests

Suggested reviewers

  • JohannesStoehr
  • edkaya
  • pzdr7
  • az108
  • Strohgelaender
  • farisd16

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 pmd
src/main/java/de/tum/cit/aet/artemis/communication/service/notifications/ConversationNotificationService.java

The following rules are missing or misspelled in your ruleset file category/vm/bestpractices.xml: BooleanInstantiation, DontImportJavaLang, DuplicateImports, EmptyFinallyBlock, EmptyIfStmt, EmptyInitializer, EmptyStatementBlock, EmptyStatementNotInLoop, EmptySwitchStatements, EmptySynchronizedBlock, EmptyTryBlock, EmptyWhileStmt, ExcessiveClassLength, ExcessiveMethodLength, ImportFromSamePackage, MissingBreakInSwitch, SimplifyBooleanAssertion. Please check your ruleset configuration.

src/main/java/de/tum/cit/aet/artemis/communication/service/notifications/SingleUserNotificationService.java

The following rules are missing or misspelled in your ruleset file category/vm/bestpractices.xml: BooleanInstantiation, DontImportJavaLang, DuplicateImports, EmptyFinallyBlock, EmptyIfStmt, EmptyInitializer, EmptyStatementBlock, EmptyStatementNotInLoop, EmptySwitchStatements, EmptySynchronizedBlock, EmptyTryBlock, EmptyWhileStmt, ExcessiveClassLength, ExcessiveMethodLength, ImportFromSamePackage, MissingBreakInSwitch, SimplifyBooleanAssertion. Please check your ruleset configuration.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai or @coderabbitai title anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (5)
src/main/java/de/tum/cit/aet/artemis/communication/service/notifications/ConversationNotificationService.java (2)

90-90: Update JavaDoc to reflect implementation details

While the code change is correct, consider updating the method's JavaDoc to document that the notification creation now includes recipient filtering based on conversation access.


103-106: Consider refactoring for better readability and separation of concerns

The current implementation combines filtering and notification creation in a complex stream operation. Consider breaking this down for better readability and maintainability:

     private void save(ConversationNotification notification, Set<User> mentionedUsers, String[] placeHolders, Post createdMessage) {
         conversationNotificationRepository.save(notification);
 
-        Set<SingleUserNotification> mentionedUserNotifications = singleUserNotificationService
-                .filterAllowedRecipientsInMentionedUsers(mentionedUsers, createdMessage.getConversation()).map(mentionedUser -> SingleUserNotificationFactory
-                        .createNotification(notification.getMessage(), NotificationType.CONVERSATION_USER_MENTIONED, notification.getText(), placeHolders, mentionedUser))
-                .collect(Collectors.toSet());
+        // First filter allowed recipients
+        Set<User> allowedRecipients = singleUserNotificationService
+                .filterAllowedRecipientsInMentionedUsers(mentionedUsers, createdMessage.getConversation())
+                .collect(Collectors.toSet());
+
+        // Then create notifications for allowed recipients
+        Set<SingleUserNotification> mentionedUserNotifications = allowedRecipients.stream()
+                .map(mentionedUser -> SingleUserNotificationFactory.createNotification(
+                        notification.getMessage(),
+                        NotificationType.CONVERSATION_USER_MENTIONED,
+                        notification.getText(),
+                        placeHolders,
+                        mentionedUser))
+                .collect(Collectors.toSet());
         singleUserNotificationRepository.saveAll(mentionedUserNotifications);
     }
src/main/java/de/tum/cit/aet/artemis/communication/service/notifications/SingleUserNotificationService.java (3)

461-472: Consider extracting complex conditions into well-named methods for better readability.

The filtering logic combines multiple conditions that could be more readable if extracted into separate methods.

Consider this refactoring:

 public Stream<User> filterAllowedRecipientsInMentionedUsers(Set<User> mentionedUsers, Conversation conversation) {
     return mentionedUsers.stream().filter(user -> {
-        boolean isChannelAndCourseWide = conversation instanceof Channel channel && channel.getIsCourseWide();
-        boolean isChannelVisibleToStudents = !(conversation instanceof Channel channel) || conversationService.isChannelVisibleToStudents(channel);
-        boolean isChannelVisibleToMentionedUser = isChannelVisibleToStudents || authorizationCheckService.isAtLeastTeachingAssistantInCourse(conversation.getCourse(), user);
-
-        // Only send a notification to the mentioned user if...
-        // (for course-wide channels) ...the course-wide channel is visible
-        // (for all other cases) ...the user is a member of the conversation
-        return (isChannelAndCourseWide && isChannelVisibleToMentionedUser) || conversationService.isMember(conversation.getId(), user.getId());
+        return canReceiveNotification(user, conversation);
     });
 }

+private boolean canReceiveNotification(User user, Conversation conversation) {
+    if (conversation instanceof Channel channel) {
+        if (channel.getIsCourseWide()) {
+            return isChannelVisibleToUser(channel, user);
+        }
+    }
+    return conversationService.isMember(conversation.getId(), user.getId());
+}
+
+private boolean isChannelVisibleToUser(Channel channel, User user) {
+    return conversationService.isChannelVisibleToStudents(channel) || 
+           authorizationCheckService.isAtLeastTeachingAssistantInCourse(channel.getCourse(), user);
+}

446-447: Add defensive programming checks for robustness.

The method should handle potential null values and service exceptions gracefully.

Consider adding these safety checks:

+        if (mentionedUsers == null || mentionedUsers.isEmpty()) {
+            return;
+        }
+        try {
             filterAllowedRecipientsInMentionedUsers(mentionedUsers, post.getConversation())
                     .forEach(mentionedUser -> notifyUserAboutNewMessageReply(savedAnswerMessage, notification, mentionedUser, author, CONVERSATION_USER_MENTIONED));
+        } catch (Exception e) {
+            // Log error but don't block the notification flow for other users
+            log.error("Failed to process mentioned users notifications", e);
+        }

454-473: Implementation effectively addresses the security concern.

The new filtering logic successfully prevents unauthorized access to conversation content by:

  1. Properly checking conversation membership
  2. Respecting channel visibility settings
  3. Handling both course-wide channels and private conversations

Consider adding metrics to monitor filtered notifications for security auditing purposes.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1786886 and 101d4ea.

📒 Files selected for processing (2)
  • src/main/java/de/tum/cit/aet/artemis/communication/service/notifications/ConversationNotificationService.java (3 hunks)
  • src/main/java/de/tum/cit/aet/artemis/communication/service/notifications/SingleUserNotificationService.java (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
src/main/java/de/tum/cit/aet/artemis/communication/service/notifications/ConversationNotificationService.java (1)

Pattern src/main/java/**/*.java: naming:CamelCase; principles:{single_responsibility,small_methods,no_duplication}; db:{perf_queries,datetime_not_timestamp}; rest:{stateless,singleton,delegate_logic,http_only,minimal_dtos}; dtos:{java_records,no_entities,min_data,single_resp}; di:constructor_injection; kiss:simple_code; file_handling:os_indep_paths; practices:{least_access,avoid_transactions,code_reuse,static_member_ref,prefer_primitives}; sql:{param_annotation,uppercase,avoid_subqueries};java:avoid_star_imports

src/main/java/de/tum/cit/aet/artemis/communication/service/notifications/SingleUserNotificationService.java (1)

Pattern src/main/java/**/*.java: naming:CamelCase; principles:{single_responsibility,small_methods,no_duplication}; db:{perf_queries,datetime_not_timestamp}; rest:{stateless,singleton,delegate_logic,http_only,minimal_dtos}; dtos:{java_records,no_entities,min_data,single_resp}; di:constructor_injection; kiss:simple_code; file_handling:os_indep_paths; practices:{least_access,avoid_transactions,code_reuse,static_member_ref,prefer_primitives}; sql:{param_annotation,uppercase,avoid_subqueries};java:avoid_star_imports

🔇 Additional comments (2)
src/main/java/de/tum/cit/aet/artemis/communication/service/notifications/ConversationNotificationService.java (2)

44-52: LGTM: Clean dependency injection implementation

The addition of SingleUserNotificationService follows best practices with constructor injection and immutable field declaration.


100-100: Security fix implemented correctly

The method now properly filters recipients based on conversation access, addressing the security issue where users could receive notifications for conversations they're not part of.

Copy link

@sachmii sachmii left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tested on TS3. Notification does not appear after mentioning the student in private chat, which is not part of that private chat.

Copy link

@HawKhiem HawKhiem left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tested on TS6. Everything works as described

Screenshot 2024-11-18 221640
Screenshot 2024-11-18 221745
Screenshot 2024-11-18 221751

Copy link
Contributor

@asliayk asliayk left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tested on ts3 and everything worked correctly

Copy link

@Cathy0123456789 Cathy0123456789 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tested on TS1. Works as described

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bugfix communication Pull requests that affect the corresponding module component:Communication ready to merge server Pull requests that update Java code. (Added Automatically!) small
Projects
Archived in project
Development

Successfully merging this pull request may close these issues.

7 participants