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 encryption issue in push notifications #10060

Merged

Conversation

PaRangger
Copy link
Contributor

@PaRangger PaRangger commented Dec 21, 2024

Checklist

General

Server

Motivation and Context

Currently there is an issue that causes notifications to be encrypted wrongly. This is due to a race condition where multiple threads access the same instance of a cipher object and overwrite its initialization vector while others are still encrypting. This leads to notification payloads like this:

{"notificationPlaceholders":["Patterns in Software Engineering (WS24/25)","Test reserveFittingPEV requries us to use the @Spy annotation for stubbing the ReservationManager. However Mockito requires a no args constructor to be able to use the @Spy annotati?��2�?���ۂGP��&"���5Ɩ��˓)h�r�J��n|8��ǁ�ب��b�ߔ

Description

Instead of having a static reference to a single cipher, the cipher instance is now initialized per-notification removing the possibility of overlaps.

Steps for Testing

Prerequisites:

  • 2 Students/Tutors/Instructors in the same course
  • 1 Android or iOS Device with Push Notifications enabled
  • 1 Course with communication enabled
  1. Log in to Artemis on the webclient with user 1 and on the native app with user 2
  2. Navigate to the course
  3. Navigate to the communication tab
  4. Write a post with user 2
  5. Answer to that post with user 1
  6. Wait until you get a notification on the native device
  7. Verify that the notification displays the proper text

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

TBD

Summary by CodeRabbit

  • Bug Fixes
    • Improved error handling in the encryption process for push notifications.
    • Addressed potential race conditions by creating a new instance of Cipher for each encryption operation.

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

coderabbitai bot commented Dec 21, 2024

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 (7.8.0)
src/main/java/de/tum/cit/aet/artemis/communication/service/notifications/push_notifications/PushNotificationService.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.

Walkthrough

The pull request modifies the PushNotificationService class, specifically addressing the encryption mechanism for push notifications. The primary change involves removing a static Cipher field and creating a new Cipher instance within the encrypt method for each encryption operation. This approach mitigates potential race conditions by ensuring thread-safe encryption. The error handling has been enhanced by expanding the catch block to include additional exception types related to cryptographic operations.

Changes

File Change Summary
src/main/java/de/tum/cit/aet/artemis/communication/service/notifications/push_notifications/PushNotificationService.java - Removed static Cipher field
- Modified encrypt method to create a new Cipher instance per encryption
- Expanded error handling with additional exception catches

Suggested labels

bugfix, ready to merge, component:Communication

Suggested reviewers

  • sachmii
  • cremertim
  • HawKhiem
  • asliayk
  • Cathy0123456789

Possibly related PRs

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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: 1

♻️ Duplicate comments (1)
src/main/java/de/tum/cit/aet/artemis/communication/service/notifications/push_notifications/PushNotificationService.java (1)

197-197: ⚠️ Potential issue

Security: Replace CBC mode with GCM for better security

The current encryption algorithm (AES/CBC/PKCS5Padding) has known vulnerabilities:

  • CBC mode is vulnerable to padding oracle attacks
  • Requires careful IV handling to prevent chosen-plaintext attacks

Recommend switching to AES/GCM/NoPadding which provides:

  • Authenticated encryption
  • Protection against tampering
  • No padding oracle vulnerabilities

Here's how to implement the change:

- var cipher = Cipher.getInstance(Constants.PUSH_NOTIFICATION_ENCRYPTION_ALGORITHM);
+ // Update the constant to use "AES/GCM/NoPadding"
+ var cipher = Cipher.getInstance("AES/GCM/NoPadding");
+ // GCM requires a 12-byte nonce instead of IV
+ byte[] nonce = new byte[12];
+ random.nextBytes(nonce);
+ GCMParameterSpec spec = new GCMParameterSpec(128, nonce);
+ cipher.init(Cipher.ENCRYPT_MODE, key, spec);

Note: This change requires updating the decryption logic on the client side and handling the nonce similar to how the IV is currently handled.

🧹 Nitpick comments (1)
src/main/java/de/tum/cit/aet/artemis/communication/service/notifications/push_notifications/PushNotificationService.java (1)

203-205: Enhance error logging for better debugging

While the error handling is comprehensive, the error message could be more specific to help with debugging encryption issues.

- log.error("Error encrypting push notification payload!", e);
+ log.error("Failed to encrypt push notification: {} (Key algorithm: {}, Key length: {} bits)", 
+     e.getMessage(), 
+     key.getAlgorithm(), 
+     key.getEncoded().length * 8, 
+     e);
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 50adb94 and b101c6f.

📒 Files selected for processing (1)
  • src/main/java/de/tum/cit/aet/artemis/communication/service/notifications/push_notifications/PushNotificationService.java (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
src/main/java/de/tum/cit/aet/artemis/communication/service/notifications/push_notifications/PushNotificationService.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

@krusche krusche added this to the 7.8.0 milestone Dec 21, 2024
@krusche krusche changed the title Notifications: Fix encryption issue in push notifications Communication: Fix encryption issue in push notifications Dec 22, 2024
@krusche krusche merged commit 35d113e into develop Dec 22, 2024
48 of 52 checks passed
@krusche krusche deleted the bugfix/notifications/fix-race-condition-for-notification-tasks branch December 22, 2024 09:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
communication Pull requests that affect the corresponding module component:Notification ready for review server Pull requests that update Java code. (Added Automatically!)
Projects
Status: Merged
Status: Done
Development

Successfully merging this pull request may close these issues.

2 participants