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

feat:cipher negotiation #40

Merged
merged 4 commits into from
Jan 3, 2025
Merged

feat:cipher negotiation #40

merged 4 commits into from
Jan 3, 2025

Conversation

JarbasAl
Copy link
Member

@JarbasAl JarbasAl commented Jan 3, 2025

companion to JarbasHiveMind/hivemind-websocket-client#50

message size reduction showcase:

# CHACHA20-POLY1305 + JSON-Z85B  <- new default
# 2025-01-03 01:56:29.652 - HiveMind - hivemind_core.protocol:send:132 - DEBUG - unencrypted payload: 1151
# 2025-01-03 01:56:29.653 - HiveMind - hivemind_core.protocol:send:137 - DEBUG - encrypted payload: 1909

# CHACHA20-POLY1305 + JSON-B64
# 2025-01-03 01:58:28.429 - HiveMind - hivemind_core.protocol:send:132 - DEBUG - unencrypted payload: 1151
# 2025-01-03 01:58:28.430 - HiveMind - hivemind_core.protocol:send:137 - DEBUG - encrypted payload: 2038

# CHACHA20-POLY1305 + JSON-HEX
# 2025-01-03 01:58:48.465 - HiveMind - hivemind_core.protocol:send:132 - DEBUG - unencrypted payload: 1151
# 2025-01-03 01:58:48.466 - HiveMind - hivemind_core.protocol:send:137 - DEBUG - encrypted payload: 3028

# AES-GCM + JSON-Z85B
# 2025-01-03 02:00:15.392 - HiveMind - hivemind_core.protocol:send:132 - DEBUG - unencrypted payload: 1151
# 2025-01-03 02:00:15.393 - HiveMind - hivemind_core.protocol:send:137 - DEBUG - encrypted payload: 1914

# AES-GCM + JSON-B64
# 2025-01-03 01:59:53.382 - HiveMind - hivemind_core.protocol:send:132 - DEBUG - unencrypted payload: 1151
# 2025-01-03 01:59:53.383 - HiveMind - hivemind_core.protocol:send:137 - DEBUG - encrypted payload: 2046

# AES-GCM + JSON-HEX <- old default
# 2025-01-03 01:59:27.516 - HiveMind - hivemind_core.protocol:send:132 - DEBUG - unencrypted payload: 1151
# 2025-01-03 01:59:27.516 - HiveMind - hivemind_core.protocol:send:137 - DEBUG - encrypted payload: 3036

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Enhanced communication protocol with configurable encryption and encoding options.
    • Added support for client-side selection of encryption ciphers and message encoding formats.
    • Improved handshake process to validate and synchronize encryption preferences.
    • Introduced default settings for allowed encodings and ciphers in configuration management.
  • Bug Fixes

    • Ensured all default settings are applied to the database if missing.
  • Chores

    • Removed automated license testing workflow.
    • Updated dependency version for hivemind_bus_client.

Copy link

coderabbitai bot commented Jan 3, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

The pull request introduces enhancements to the hivemind_core/protocol.py file, focusing on improving the HiveMindClientConnection class's encryption and encoding capabilities. The changes allow clients to specify preferred encryption ciphers and encoding formats during the handshake process. New attributes cipher and encoding have been added to support dynamic selection of encryption methods, providing more flexibility in the communication protocol's security mechanisms. Additionally, updates to the hivemind_core/config.py file ensure that default configuration settings are applied to the database if they are missing.

Changes

File Change Summary
hivemind_core/protocol.py - Added cipher and encoding attributes to HiveMindClientConnection class
- Updated send and decode methods to use new encryption parameters
- Modified handle_handshake_message to validate and set client encryption preferences
- Updated authorize method with comments for clarity
hivemind_core/config.py - Added allowed_encodings and allowed_ciphers to _DEFAULT dictionary
- Enhanced get_server_config function to ensure all default settings are applied to the database
.github/workflows/license_tests.yml - Removed workflow for automated license testing
requirements.txt - Updated hivemind_bus_client version constraint from >=0.1.6,<1.0.0 to >=0.2.0,<1.0.0

Possibly related PRs

  • feat:cipher negotiation #40: The changes in this PR directly enhance the HiveMindClientConnection class in hivemind_core/protocol.py by adding new attributes for cipher and encoding, which are also introduced in the main PR, indicating a strong connection in terms of encryption and encoding mechanisms.

Suggested reviewers

  • goldyfruit

Poem

🔒 Encryption's Whisper 🐰
In bytes of code, a rabbit's might,
Ciphers dance with pure delight,
Handshake secrets, softly spun,
Encoding magic has begun!
Security hops from line to line 🌟


📜 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 b0ac893 and f292e86.

📒 Files selected for processing (3)
  • .github/workflows/license_tests.yml (0 hunks)
  • hivemind_core/protocol.py (9 hunks)
  • requirements.txt (1 hunks)

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.

@github-actions github-actions bot added feature and removed feature labels Jan 3, 2025
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 (8)
hivemind_core/protocol.py (8)

88-90: Consider configurable defaults for cipher and encoding
Hard-coding these fields is fine for now, but you may want to load or override them from a config file or environment variables to avoid frequent code changes if you later decide to update defaults.


129-129: Add error handling around binary encryption
If encrypt_bin fails (e.g., invalid key or cipher parameters), the exception will bubble up. Recommend adding a try-except block to log or gracefully handle encryption failures.

 try:
-    payload = encrypt_bin(key=self.crypto_key, plaintext=payload, cipher=self.cipher)
+    payload = encrypt_bin(key=self.crypto_key,
+                          plaintext=payload,
+                          cipher=self.cipher)
 except Exception as e:
     LOG.error(f"Encryption failed: {e}")
     return

134-135: Add consistent exception handling for JSON encryption
Similar to the binary encryption above, consider protecting encrypt_as_json with a try-except clause to handle any unexpected errors during encryption.

 try:
-    payload = encrypt_as_json(
-        key=self.crypto_key, plaintext=message.serialize(),
-        cipher=self.cipher, encoding=self.encoding
-    )
+    payload = encrypt_as_json(
+        key=self.crypto_key,
+        plaintext=message.serialize(),
+        cipher=self.cipher,
+        encoding=self.encoding
+    )
 except Exception as e:
     LOG.error(f"JSON encryption failed: {e}")
     return

148-149: Handle errors from binary decryption
Decryption errors can crash the server under certain conditions (e.g., malformed ciphertext). Consider wrapping decrypt_bin in a try-except.


152-153: Handle errors from JSON decryption
Similar to binary decryption, add a try-except for decrypt_from_json to log or reject malformed input.


274-275: Consider limiting advertised ciphers and encodings
Here you list all possible SupportedEncodings and SupportedCiphers to the client. In a more restrictive environment, you may want to omit or filter ciphers you don’t truly support to prevent misconfigurations.


476-479: Robust cipher selection
Automatically selecting the first cipher and encoding in the client’s list is simplistic. Consider implementing a more robust negotiation strategy (e.g., matching the highest-security cipher that both client and server support).


482-482: Investigate Tornado events
This comment suggests Tornado never emits certain events. Confirm if additional debugging or event handling is needed, or remove the comment if it’s no longer relevant.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 530a444 and 855fc28.

📒 Files selected for processing (1)
  • hivemind_core/protocol.py (9 hunks)
🔇 Additional comments (5)
hivemind_core/protocol.py (5)

18-20: Import statements look good
The encryption-related imports are consistent and appear correctly structured. No issues here.


173-175: No actionable changes in this comment block
These lines only contain a comment and do not affect code behavior. No issues to address.


460-463: Graceful fallback for missing handshake data
This logic correctly defaults to JSON_HEX or AES_GCM if the client doesn’t provide any encodings/ciphers. That is appropriate for backward compatibility.


512-515: Handshake message assembly looks correct
The handshake response includes encoding and cipher for proper synchronization. No issues here.


6-6: Ensure Python 3.8+ environment or backport Literal for broader compatibility
Using Literal is fine, but note that it was introduced in Python 3.8’s typing module. If older Python versions must be supported, consider a backport or alternative type annotations.

To confirm your environment compatibility, run:

hivemind_core/protocol.py Outdated Show resolved Hide resolved
@github-actions github-actions bot added feature and removed feature labels Jan 3, 2025
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

🧹 Nitpick comments (10)
hivemind_core/config.py (1)

41-43: Ensure concurrency-safety when updating defaults
When iterating over _DEFAULT.items() and updating db, consider potential concurrency issues if multiple threads call get_server_config() simultaneously. You might wrap this logic in a proper lock or transaction if the storage backend supports concurrent writes.

hivemind_core/protocol.py (9)

18-21: Usage of private encryption methods
The imports _norm_encoding and _norm_cipher are non-public (underscored) methods. Consider making them part of the public API if widely used, or encapsulate them in a dedicated helper to avoid relying on private functions that may change unexpectedly.


130-130: Check for potential size overhead in binary encryption
Register how large the output might grow. Some ciphers add an authentication tag, which increases payload size. Large sizes could degrade performance in networks with limited bandwidth.


135-136: Add error handling for encryption failures
If encrypt_as_json fails for some reason (e.g., invalid key), consider catching and logging or raising a specific exception to help with troubleshooting.


149-150: Decrypting binary data
Check if there's any need to verify the integrity of the decrypted payload (e.g., checking signatures or HMAC). Without it, there might be a risk of undetected data corruption.


153-154: Graceful fallback on decryption errors
When decrypt_from_json fails, consider whether we should explicitly handle the error to avoid cryptic stack traces. This might safeguard the entire handshake/communication mechanism.


174-176: Expand the TODO with a plan
This TODO around intent/skill blocking is crucial for security. Provide a more detailed plan or timeline to ensure it’s not left indefinitely.


465-470: Prefer single use of “preferences”
The code reads the requested encodings and ciphers from the client and normalizes them. If we expect a wide range of possible preferences, validate their correctness earlier to avoid normalizing invalid or malicious values.


471-475: Reference the server config only once
We read the server config again here. If possible, store its results in a local variable or pass them to reduce repeated I/O or function calls. This can enhance efficiency.


484-487: Honor client preference order
Grabbing the first option from the client preference list is fine, but consider including a server “priority order” for more robust negotiation if compatibility issues arise.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 855fc28 and b0ac893.

📒 Files selected for processing (2)
  • hivemind_core/config.py (2 hunks)
  • hivemind_core/protocol.py (9 hunks)
🔇 Additional comments (10)
hivemind_core/config.py (1)

8-10: Validate new default values with protocol usage
The newly added "allowed_encodings" and "allowed_ciphers" default values look good. Please ensure they remain in sync with the supported ones used in protocol.py, especially if we add or remove encodings/ciphers there.

hivemind_core/protocol.py (9)

6-6: Check Python version compatibility for Literal
Using Literal requires Python ≥ 3.8. Confirm that the environment meets this requirement, or otherwise include a compatibility library such as typing_extensions if needed.


14-14: Prevent potential circular imports
Ensure that importing get_server_config from hivemind_core.config does not create circular dependencies, especially now that hivemind_core/config.py references _DEFAULT used for protocol defaults.


89-91: Flexible default cipher and encoding
The addition of cipher and encoding with defaults (AES_GCM and JSON_HEX) is a good enhancement. Just ensure this is documented so future maintainers know the default security posture.


264-267: Synchronized server config usage
When pulling server config values (allowed_ciphers, allowed_encodings), confirm whether multiple calls to get_server_config remain consistent across threads or processes. If these values change at runtime, consider a caching strategy.


279-280: Transparent handshake message
These lines expose allowed encodings and ciphers to the client. Confirm that revealing these defaults doesn’t pose a security risk. Generally, listing available ciphers is acceptable, but be mindful of revealing too much internal knowledge.


476-478: Reject or degrade gracefully if no valid cipher/encoding remains
The filtering approach is good, but if no valid options remain, the code breaks the connection. Check whether a fallback or negotiation is needed for partial support.


479-483: Close handshake on invalid request
Disconnecting is appropriate for security. Ensure thorough logs are captured to facilitate debugging if a client is unexpectedly disconnected.


490-490: Clarify password handshake
Quick mention that the password handshake ensures a derived key is never transmitted. Good approach. Document any fallback or re-handshake logic if partial or multiple attempts are needed.


520-523: Explicit handshake confirmation
Returning the cipher and encoding is a solid finalization step. Confirm that clients subsequently adhere to these settings; if they deviate, consider forcibly dropping the connection.

@JarbasAl JarbasAl merged commit 28fb2b8 into dev Jan 3, 2025
1 check passed
@github-actions github-actions bot added feature and removed feature labels Jan 3, 2025
@JarbasAl JarbasAl mentioned this pull request Jan 3, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant