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

Use Conflict Suffixes from Ciphertext Files #275

Open
wants to merge 3 commits into
base: develop
Choose a base branch
from

Conversation

overheadhunter
Copy link
Member

This change attempts to solve cryptomator/cryptomator#3707.

The first commit is just a slight improvement for the regex matcher in order to make it faster and more robust.

The second commit alters the renameConflictingFile() method, which is now rather big, but I feel like it is the right amount of readability for this project. This is the new logic:

  1. assume that a sync client adds a "conflict suffix" to the end of the file (but before the file extension)
  2. extract this conflict suffix by looking at the part after the ciphertext and before the .c9r extension
  3. apply some length limiting to the extracted suffix and the cleartext name to not exceed the max filename length (to not trigger filename shortening)
  4. assemble new cleartext name lengthLimitedBasname + lengthLimitedConflictSuffix + fileExtension
  5. derive the corresponding ciphertext name and, if the name is still available, use it
  6. otherwise, fall back to a counter-based alternative name

On the test side, I altered/added the test scenarios:

conflicting ciphertext original cleartext new cleartext comment
foo (Created by Alice).c9r bar.txt bar (Created by Alice).txt testResolveConflictingFileByChoosingNewName, happy path
foo (Created by Alice).c9r bar.txt bar (1).txt testResolveConflictingFileByAddingNumericSuffix, preferred resolved file name already taken
foo (
Created by Alice on 2024-01-31
).c9r
this is a rather long file name
.txt
this is a rather lon (Created by Alice o
.txt
testResolveConflictingFileByChoosingNewLengthLimitedName, limiting both basename as well as conflict suffix

@overheadhunter overheadhunter requested a review from infeo February 1, 2025 15:40
Copy link

coderabbitai bot commented Feb 1, 2025

Walkthrough

The pull request introduces updates to the Maven project configuration and several Java classes. In the Maven pom.xml, a new property for the JMH library version is added along with dependencies for jmh-core (scoped for testing) and jmh-generator-annprocess (provided scope), with the latter also configured as an annotation processor for the Maven Compiler Plugin. In the C9rConflictResolver class, error logging is refined using placeholder formatting, and the method signature for renaming conflicting files is simplified to accept a Node object directly. The C9rDecryptor class sees an updated Base64 regex pattern and streamlined stream return logic. Additionally, a new test file, Base64UrlRegexTest, is introduced to validate and benchmark Base64 URL patterns using JUnit parameterized tests and JMH, while test cases in C9rConflictResolverTest and C9rDecryptorTest are adjusted with updated file naming conventions and input patterns.

Suggested labels

enhancement


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bb4911b and 0426d26.

📒 Files selected for processing (1)
  • src/main/java/org/cryptomator/cryptofs/dir/C9rConflictResolver.java (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/java/org/cryptomator/cryptofs/dir/C9rConflictResolver.java
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Analyse
  • GitHub Check: Build and Test

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 anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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

🧹 Nitpick comments (3)
src/test/java/org/cryptomator/cryptofs/dir/Base64UrlRegexTest.java (1)

127-133: Consider using parameterized inputs for benchmarking.

The benchmark could be more comprehensive by parameterizing the test inputs.

 @Benchmark
 public void testPattern(Blackhole bh) {
-    for (String input : TEST_INPUTS) {
+    @Param({"short", "medium", "long"})
+    private String inputType;
+    
+    private String[] inputs;
+    
+    @Setup(Level.Trial)
+    public void setupInputs() {
+        switch(inputType) {
+            case "short": inputs = new String[]{"aaaaBBBBccccDDDDeeeeFFFF"}; break;
+            case "medium": inputs = new String[]{"aaaaBBBBccccDDDDeeeeFFFFggggHH=="}; break;
+            case "long": inputs = new String[]{"-3h6-FSsYhMCJHSAV9cjJ89F7R73b0zIB4vvO01b7uWq28fWioRagWpMv-w0MA-2ORjbShuv"}; break;
+        }
+    }
+    
+    @Benchmark
+    public void testPattern(Blackhole bh) {
+        for (String input : inputs) {
             Matcher matcher = pattern.matcher(input);
             bh.consume(matcher.matches());
         }
     }
src/main/java/org/cryptomator/cryptofs/dir/C9rConflictResolver.java (2)

90-109: Consider extracting magic numbers into constants.

The logic for handling conflict suffixes and length restrictions is well-implemented and documented. However, consider extracting magic numbers like 5 (minimum conflict suffix length) into named constants for better maintainability.

+  private static final int MIN_CONFLICT_SUFFIX_LENGTH = 5;
+  private static final double CONFLICT_SUFFIX_MAX_RATIO = 0.5; // 50% of available space
   ...
-  final int conflictSuffixLen = Math.max(5, conflictSuffix.length());
+  final int conflictSuffixLen = Math.max(MIN_CONFLICT_SUFFIX_LENGTH, conflictSuffix.length());
-  final String conflictSuffix = originalConflictSuffix.substring(0, Math.min(originalConflictSuffix.length(), netCleartext / 2));
+  final String conflictSuffix = originalConflictSuffix.substring(0, Math.min(originalConflictSuffix.length(), (int)(netCleartext * CONFLICT_SUFFIX_MAX_RATIO)));

106-108: Consider extracting magic numbers and improving division logic

A few suggestions for improvement:

  1. The magic number '5' for minimum suffix length should be a named constant
  2. The integer division for space allocation could be made more explicit
+  private static final int MIN_CONFLICT_SUFFIX_LENGTH = 5;
+  private static final double CONFLICT_SUFFIX_SPACE_RATIO = 0.5; // 50% of available space
   
-  final String conflictSuffix = originalConflictSuffix.substring(0, Math.min(originalConflictSuffix.length(), netCleartext / 2));
-  final int conflictSuffixLen = Math.max(5, conflictSuffix.length());
+  final int maxConflictSuffixLength = (int)(netCleartext * CONFLICT_SUFFIX_SPACE_RATIO);
+  final String conflictSuffix = originalConflictSuffix.substring(0, Math.min(originalConflictSuffix.length(), maxConflictSuffixLength));
+  final int conflictSuffixLen = Math.max(MIN_CONFLICT_SUFFIX_LENGTH, conflictSuffix.length());
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ab87592 and bb4911b.

📒 Files selected for processing (6)
  • pom.xml (3 hunks)
  • src/main/java/org/cryptomator/cryptofs/dir/C9rConflictResolver.java (2 hunks)
  • src/main/java/org/cryptomator/cryptofs/dir/C9rDecryptor.java (2 hunks)
  • src/test/java/org/cryptomator/cryptofs/dir/Base64UrlRegexTest.java (1 hunks)
  • src/test/java/org/cryptomator/cryptofs/dir/C9rConflictResolverTest.java (3 hunks)
  • src/test/java/org/cryptomator/cryptofs/dir/C9rDecryptorTest.java (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyse
🔇 Additional comments (19)
src/main/java/org/cryptomator/cryptofs/dir/C9rDecryptor.java (2)

23-23: LGTM! The regex pattern is now more robust.

The updated pattern correctly handles Base64URL-encoded strings with proper padding rules:

  • Requires exactly 20 base64url chars at the start
  • Allows groups of 4 base64url chars in the middle
  • Handles proper base64url padding at the end

39-39: LGTM! Simplified stream return logic.

Using Optional.stream() is a cleaner way to convert an Optional to a Stream.

src/test/java/org/cryptomator/cryptofs/dir/C9rDecryptorTest.java (2)

37-37: LGTM! Added test case for valid Base64URL pattern.

The new test case validates Base64URL strings with proper padding and special characters.


48-50: LGTM! Added test cases for invalid Base64URL patterns.

The new test cases validate that the regex correctly rejects:

  • Strings with excessive padding
  • Strings with padding in wrong positions
src/test/java/org/cryptomator/cryptofs/dir/Base64UrlRegexTest.java (2)

35-45: LGTM! Comprehensive test data for Base64URL patterns.

The test data covers various scenarios:

  • Standard Base64URL strings
  • Strings with padding
  • Strings with special characters
  • Long Base64URL strings

101-107: LGTM! Well-configured JMH benchmark.

The benchmark is properly configured with:

  • Multiple forks for statistical significance
  • Appropriate warmup and measurement iterations
  • Average time measurement mode
  • Microsecond output unit
src/test/java/org/cryptomator/cryptofs/dir/C9rConflictResolverTest.java (3)

34-34: LGTM! Updated shorteningThreshold for longer cleartext names.

The increased threshold (84) allows for longer cleartext names (max 44 chars) in the tests.


80-94: LGTM! Added test for numeric suffix conflict resolution.

The new test verifies that:

  1. When a descriptive conflict suffix exists
  2. And the resolved name is occupied
  3. The resolver falls back to numeric suffixes

102-114: LGTM! Updated test for length-limited conflict resolution.

The test now uses more realistic filenames with:

  • Longer descriptive conflict suffixes
  • Longer base filenames
  • Proper length limitation verification
src/main/java/org/cryptomator/cryptofs/dir/C9rConflictResolver.java (7)

64-64: LGTM! Improved logging performance.

The change to use SLF4J placeholder format instead of string concatenation is a good practice that avoids unnecessary string concatenation when logging is disabled.


85-89: LGTM! Improved method signature.

The simplified method signature that uses the Node object directly improves code readability and reduces parameter count. The documentation has been updated accordingly.


110-123: LGTM! Robust alternative name generation.

The implementation handles alternative name generation well, including:

  • Length validation with assertions
  • Informative logging
  • Counter-based fallback for name conflicts

64-64: LGTM! Improved logging format

Updated to use SLF4J placeholder syntax which is more efficient as it avoids unnecessary string concatenation.


78-78: LGTM! Improved method signature

Good refactoring to use the Node object directly instead of passing individual parameters. This encapsulates the data better and simplifies the interface.

Also applies to: 86-89


Line range hint 121-127: LGTM! Robust post-resolution handling

Good use of assertions and atomic file operations to ensure data integrity during the rename operation.


100-101: Verify assumption about conflict suffix position

The code assumes the sync client always appends the conflict suffix after the ciphertext but before the .c9r extension. This assumption should be verified against all sync clients that might interact with the system.

✅ Verification successful

Conflict Suffix Position Assumption Verified

The repository’s tests and naming conventions confirm that the sync conflict string is indeed expected to be placed immediately after the extractedCiphertext and right before the file suffix (e.g., “.c9r”). The tests (e.g., in C9rConflictResolverTest.java and migration tests) consistently rely on this naming pattern. While it’s important to remain vigilant for future changes from sync clients, the current evidence supports the assumption made in the code.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for test cases or documentation about sync client conflict patterns
rg -l "conflict.*pattern|sync.*conflict" --type md

Length of output: 52


Script:

#!/bin/bash
echo "Searching in repository for sync conflict patterns in Markdown files:"
rg -n "sync.*conflict" --type md

echo "Searching in repository for conflict patterns in Java files:"
rg -n "conflict" --type java

echo "Searching occurrences of 'extractedCiphertext' to understand conflict suffix usage:"
rg -n "extractedCiphertext" --type java

echo "Displaying snippet of C9rConflictResolver.java (lines 80-130):"
sed -n '80,130p' src/main/java/org/cryptomator/cryptofs/dir/C9rConflictResolver.java

Length of output: 20344

pom.xml (3)

30-30: LGTM! Proper version management.

The JMH version is correctly defined as a property, following Maven best practices for version management.


127-138: LGTM! Correct JMH dependency configuration.

The JMH dependencies are properly configured with:

  • Correct scopes (test for core, provided for annotation processor)
  • Version referencing the property
  • Clear comment explaining the annotation processor scope

179-183: LGTM! Proper annotation processor configuration.

The JMH annotation processor is correctly configured in the Maven Compiler Plugin, using the version property.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant