Skip to content

Conversation

@DiegoMirandaO
Copy link

@DiegoMirandaO DiegoMirandaO commented Aug 21, 2025

Summary by CodeRabbit

  • New Features
    • Improved compatibility with the latest PyMongo for client-side field encryption.
  • Bug Fixes
    • Corrected UUID handling for data keys to ensure proper encoding during encryption workflows.
  • Refactor
    • Added type annotations to enhance static typing and maintainability.
    • Updated internal imports to align with newer dependency structure.
  • Tests
    • Adjusted tests for typing clarity and updated imports accordingly.
  • Chores
    • Upgraded PyMongo dependency to 4.11.0.
    • No public API changes.

@coderabbitai
Copy link

coderabbitai bot commented Aug 21, 2025

Walkthrough

  • Updated import path for _EncryptionIO from pymongo.encryption to pymongo.synchronous.encryption in module and tests.
  • Bumped pymongo dependency from 3.13.0 to 4.11.0 in requirements.txt.
  • Adjusted get_data_key_binary to wrap data_key['_id'] directly in Binary without accessing .bytes.
  • Added/clarified type hints: module variable CODEC_OPTION annotated as CodecOptions; inline type comments for ClientEncryption context managers; tests use typing.cast for query result.
  • No changes to public function signatures or control flow beyond the Binary wrapping detail.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.


📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 108945e and 6680d6f.

📒 Files selected for processing (5)
  • mongoengine_plus/types/encrypted_string/__init__.py (1 hunks)
  • mongoengine_plus/types/encrypted_string/base.py (2 hunks)
  • mongoengine_plus/types/encrypted_string/fields.py (3 hunks)
  • requirements.txt (1 hunks)
  • tests/types/test_encrypted_string.py (3 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.py

⚙️ CodeRabbit configuration file

**/*.py: Enforce Relative Imports for Internal Modules

Ensure that any imports referencing internal modules use relative paths. However, if modules reside in the main module directories (for example /src or /library_or_app_name) —and relative imports are not feasible—absolute imports are acceptable. Additionally, if a module is located outside the main module structure (for example, in /tests or /scripts at a similar level), absolute imports are also valid.

Examples and Guidelines:

  1. If a module is in the same folder or a subfolder of the current file, use relative imports. For instance: from .some_module import SomeClass
  2. If the module is located under /src or /library_or_app_name and cannot be imported relatively, absolute imports are allowed (e.g., from library_or_app_name.utilities import helper_method).
  3. If a module is outside the main module directories (for example, in /tests, /scripts, or any similarly placed directory), absolute imports are valid.
  4. External (third-party) libraries should be imported absolutely (e.g., import requests).

**/*.py:
Rule: Enforce Snake Case in Python Backend

  1. New or Modified Code: Use snake_case for all variables, functions, methods, and class attributes.
  2. Exceptions (Pydantic models for API responses):
    • Primary fields must be snake_case.
    • If older clients expect camelCase, create a computed or alias field that references the snake_case field.
    • Mark any camelCase fields as deprecated or transitional.

Examples

Invalid:

class CardConfiguration(BaseModel):
    title: str
    subTitle: str  # ❌ Modified or new field in camelCase

Valid:

class CardConfiguration(BaseModel):
    title: str
    subtitle: str  # ✅ snake_case for new/modified field

    @computed_field
    def subTitle(self) -> str:  # camelCase allowed only for compatibility
        return self.subtitle

Any direct use of camelCase in new or updated code outside of these exceptions should be flagged.

`*...

Files:

  • mongoengine_plus/types/encrypted_string/__init__.py
  • tests/types/test_encrypted_string.py
  • mongoengine_plus/types/encrypted_string/fields.py
  • mongoengine_plus/types/encrypted_string/base.py
🔇 Additional comments (11)
requirements.txt (1)

4-4: Verify encryption private API compatibility before finalizing PyMongo upgrade

Our search confirmed that aside from standard imports, there are no uses of removed or renamed MongoClient options (e.g. connect, waitQueueMultiple, socketKeepAlive) or deprecated error classes elsewhere in the codebase. However, the following files import the private module pymongo.synchronous.encryption._EncryptionIO, which is not part of the documented public API and may have moved or been renamed in PyMongo 4.x:

  • tests/types/test_encrypted_string.py
  • mongoengine_plus/types/encrypted_string/init.py

Please ensure:

  • The _EncryptionIO class still exists under pymongo.synchronous.encryption in PyMongo 4.11.0.
  • All encryption tests pass against the new driver version (including private‐API paths).

If these checks succeed, the upgrade can proceed safely.

mongoengine_plus/types/encrypted_string/__init__.py (1)

6-6: Import path update aligns with PyMongo 4.x structure.

The import path change from pymongo.encryption to pymongo.synchronous.encryption correctly reflects the PyMongo 4.x API restructuring where encryption modules were reorganized into synchronous/asynchronous variants.

mongoengine_plus/types/encrypted_string/base.py (2)

35-35: Binary constructor change aligns with PyMongo 4.x requirements.

Removing .bytes from the Binary constructor call is correct for PyMongo 4.x. In the newer version, data_key['_id'] already returns the appropriate UUID object that can be passed directly to Binary().


60-60: Type hint improves code clarity.

The inline type annotation for client_encryption enhances type safety and IDE support without affecting runtime behavior.

tests/types/test_encrypted_string.py (4)

2-2: Good practice: Adding explicit type casting.

The import of cast from typing module supports the explicit type casting added later in the test, improving type safety.


10-10: Import path update maintains consistency across the codebase.

The import path change from pymongo.synchronous.encryption matches the same update made in the main module, ensuring consistency after the PyMongo 4.x upgrade.


88-88: Explicit type casting improves type safety.

Using typing.cast to explicitly cast the MongoDB query result to dict improves type safety and makes the expected type clear to both type checkers and developers.


122-122: Type annotation enhances code clarity.

The inline type hint for the ClientEncryption context manager improves type safety and provides better IDE support.

mongoengine_plus/types/encrypted_string/fields.py (3)

11-11: Type annotation improves code documentation.

Adding explicit type annotation CodecOptions to the CODEC_OPTION variable enhances type safety and makes the expected type clear.


62-62: Type hint enhances development experience.

The inline type annotation for client_encryption provides better IDE support and type checking without affecting runtime behavior.


71-71: Consistent type annotations across ClientEncryption usage.

The type hint maintains consistency with the other ClientEncryption context manager usage in the same file.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

# Buscamos el data key
data_key = get_data_key(key_namespace, key_name)
uuid_data_key = data_key['_id']
return Binary(uuid_data_key.bytes, UUID_SUBTYPE)
Copy link
Author

Choose a reason for hiding this comment

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

@alexviquez el Lint me marcaba que uuid_data_key no tiene el parametro bytes, y por lo que me meti aver efectivamente no lo tiene.
Quite el key y los test pasaron. Aun asi no estoy seguro que sea eso y como se use.
Dejo este comentario porque no se si eso realmente esta funcionando, pero tampoco se como probarlo.

Copy link
Contributor

@felipao-mx felipao-mx left a comment

Choose a reason for hiding this comment

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

este cambio es crítico porque toca un campo cifrado que usamos en otros proyectos. Para asegurar retrocompatiblidad favor de realizar la siguiente prueba

  1. crear un Document que contenga EncryptedStringField con la versión 1.2.1 de este paquete. Pueden guiarse del README.md.
  2. Guardar algún dato de prueba en este campo cifrado. Debe ser posible guardar y leer el dato.
  3. Deben crear un paquete pre-release de esta rama.
  4. Actualizar este paquete a la versión pre-release en el script de pruebas con el modelo que definieron en el paso 1.
  5. Con la versión pre-release deben intentar leer el campo encriptado y comparar que sea exactamente igual a lo que se guardó en el paso 2.

Como plan de rollback se debe asegurar que guardando algún dato con la versión pre-release también pueda leerse con la versión 1.2.1. Entonces deben hacer una prueba inversa a los pasos anteriores.

@gmorales96 gmorales96 mentioned this pull request Nov 12, 2025
@gmorales96 gmorales96 closed this Nov 13, 2025
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.

3 participants