- Notifications
You must be signed in to change notification settings - Fork 23
INTPYTHON-527 Add Queryable Encryption support #329
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
Open
aclark4life wants to merge 41 commits into mongodb:main Choose a base branch from aclark4life:INTPYTHON-527
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline, and old review comments may become outdated.
+370 −4
Open
Changes from all commits
Commits
Show all changes
41 commits Select commit Hold shift + click to select a range
bc52c8e
INTPYTHON-527 Add Queryable Encryption support
aclark4life 38fb110
Fix test for unencrypted field not in field map
aclark4life 65bd15a
Fix test for unencrypted field not in field map
aclark4life e08945b
Add comment about suppressing EncryptedCollectionError
aclark4life 7b34b44
Don't rely on features to fall back to unencrypted
aclark4life 8e83ada
Remove _nodb_cursor and disable version check
aclark4life 4da895c
Don't surpress encrypted error
aclark4life ed54a9b
Rename get_encrypted_client -> get_client_encryption
aclark4life 8a7766c
Add encryption router
aclark4life eab2f2e
Add "encryption" database to encryption tests
aclark4life 10a361e
Move encrypted_fields_map to schema (1/2)
aclark4life 01d5485
Move encrypted_fields_map to schema (2/x)
aclark4life db32487
Refactor helpers
aclark4life b2be223
Restore get_database_version functionality
aclark4life 27d4b8e
Move encrypted router to tests
aclark4life c4d1c66
Fix router tests
aclark4life 2772aff
Test feature `supports_queryable_encryption`
aclark4life d2ddf4e
Add path and bsonType to _get_encrypted_fields_map
aclark4life e25357e
Use the right database; rename some vars
aclark4life 6487086
Refactor helpers again
aclark4life bc76db3
Allow user to customize some QE settings.
aclark4life 4dbaa8f
Allow uer to customize KMS provider.
aclark4life 9cc5ad2
Refactor
aclark4life c751b2d
Alpha sort helper functions
aclark4life b13a07f
Fix get_database_version
aclark4life 534da6b
A better fix for using `buildInfo` command.
aclark4life 13578ab
Add `queries` key to encrypted fields map
aclark4life 3342d7f
Update django_mongodb_backend/schema.py
aclark4life 9fd21e4
Update django_mongodb_backend/schema.py
aclark4life 9bbe741
Update tests/encryption_/models.py
aclark4life d1eb737
Update tests/encryption_/models.py
aclark4life 176f016
Fix conditional
aclark4life 264b37a
Use column instead of name
aclark4life 1771f56
Avoid double conditional
aclark4life 819058a
Update tests and remove test router
aclark4life 9a3c18e
Update django_mongodb_backend/fields/encryption.py
aclark4life 071192e
Add deconstruct method for encryption fields
aclark4life b2a0534
Add setup & teardown for QE features test
aclark4life 81cc887
Add query type classes and update test
aclark4life be3dd16
Add missing queries to deconstruct
aclark4life a2342e2
Add get_encrypted_fields_map management command
aclark4life File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,126 @@ | ||
# Queryable Encryption helpers | ||
# | ||
# TODO: Decide if these helpers should even exist, and if so, find a permanent | ||
# place for them. | ||
| ||
from bson.binary import STANDARD | ||
from bson.codec_options import CodecOptions | ||
from pymongo.encryption import AutoEncryptionOpts, ClientEncryption | ||
| ||
KEY_VAULT_DATABASE_NAME = "keyvault" | ||
KEY_VAULT_COLLECTION_NAME = "__keyVault" | ||
KMS_PROVIDER = "local" # e.g., "aws", "azure", "gcp", "kmip", or "local" | ||
| ||
| ||
class EqualityQuery: | ||
""" | ||
Represents an encrypted equality query for encrypted fields in MongoDB's | ||
Queryable Encryption. | ||
""" | ||
| ||
def __init__(self, contention=None): | ||
self.queryType = "equality" | ||
self.contention = contention | ||
| ||
def to_dict(self): | ||
query_type = {"queryType": self.queryType} | ||
if self.contention is not None: | ||
query_type["contention"] = self.contention | ||
return [query_type] | ||
| ||
| ||
class RangeQuery: | ||
"""Represents an encrypted range query configuration for encrypted fields in | ||
MongoDB's Queryable Encryption. | ||
""" | ||
| ||
def __init__(self, sparsity=None, precision=None, trimFactor=None): | ||
self.queryType = "range" | ||
self.sparsity = sparsity | ||
self.precision = precision | ||
self.trimFactor = trimFactor | ||
| ||
def to_dict(self): | ||
query_type = {"queryType": self.queryType} | ||
if self.sparsity is not None: | ||
query_type["sparsity"] = self.sparsity | ||
if self.precision is not None: | ||
query_type["precision"] = self.precision | ||
if self.trimFactor is not None: | ||
query_type["trimFactor"] = self.trimFactor | ||
return query_type | ||
| ||
| ||
class QueryTypes: | ||
""" | ||
Factory class for creating query type configurations for | ||
MongoDB Queryable Encryption. | ||
""" | ||
| ||
def equality(self, *, contention=None): | ||
return EqualityQuery(contention=contention) | ||
| ||
def range(self, *, sparsity=None, precision=None, trimFactor=None): | ||
return RangeQuery(sparsity=sparsity, precision=precision, trimFactor=trimFactor) | ||
| ||
| ||
def get_auto_encryption_opts( | ||
key_vault_namespace=None, crypt_shared_lib_path=None, kms_providers=None | ||
): | ||
""" | ||
Returns an `AutoEncryptionOpts` instance for MongoDB Client-Side Field | ||
Level Encryption (CSFLE) that can be used to create an encrypted connection. | ||
""" | ||
return AutoEncryptionOpts( | ||
key_vault_namespace=key_vault_namespace, | ||
kms_providers=kms_providers, | ||
crypt_shared_lib_path=crypt_shared_lib_path, | ||
) | ||
| ||
| ||
def get_client_encryption(client, key_vault_namespace=None, kms_providers=None): | ||
""" | ||
Returns a `ClientEncryption` instance for MongoDB Client-Side Field Level | ||
Encryption (CSFLE) that can be used to create an encrypted collection. | ||
""" | ||
| ||
codec_options = CodecOptions(uuid_representation=STANDARD) | ||
return ClientEncryption(kms_providers, key_vault_namespace, client, codec_options) | ||
| ||
| ||
def get_customer_master_key(): | ||
""" | ||
Returns a 96-byte local master key for use with MongoDB Client-Side Field Level | ||
Encryption (CSFLE). For local testing purposes only. In production, use a secure KMS | ||
like AWS, Azure, GCP, or KMIP. | ||
Returns: | ||
bytes: A 96-byte key. | ||
""" | ||
# WARNING: This is a static key for testing only. | ||
# Generate with: os.urandom(96) | ||
return bytes.fromhex( | ||
"000102030405060708090a0b0c0d0e0f" | ||
"101112131415161718191a1b1c1d1e1f" | ||
"202122232425262728292a2b2c2d2e2f" | ||
"303132333435363738393a3b3c3d3e3f" | ||
"404142434445464748494a4b4c4d4e4f" | ||
"505152535455565758595a5b5c5d5e5f" | ||
) | ||
| ||
| ||
def get_key_vault_namespace( | ||
key_vault_database_name=KEY_VAULT_DATABASE_NAME, | ||
key_vault_collection_name=KEY_VAULT_COLLECTION_NAME, | ||
): | ||
return f"{key_vault_database_name}.{key_vault_collection_name}" | ||
| ||
| ||
def get_kms_providers(): | ||
""" | ||
Return supported KMS providers for MongoDB Client-Side Field Level Encryption (CSFLE). | ||
""" | ||
return { | ||
"local": { | ||
"key": get_customer_master_key(), | ||
}, | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
from django.db import models | ||
| ||
| ||
class EncryptedCharField(models.CharField): | ||
encrypted = True | ||
queries = [] | ||
| ||
def __init__(self, *args, queries=None, **kwargs): | ||
self.queries = queries | ||
super().__init__(*args, **kwargs) | ||
| ||
def deconstruct(self): | ||
name, path, args, kwargs = super().deconstruct() | ||
| ||
# Add 'queries' to kwargs if it was set | ||
if self.queries is not None: | ||
kwargs["queries"] = self.queries | ||
| ||
# Normalize path if needed | ||
if path.startswith("django_mongodb_backend.fields.encryption"): | ||
path = path.replace( | ||
"django_mongodb_backend.fields.encryption", | ||
"django_mongodb_backend.fields", | ||
) | ||
| ||
return name, path, args, kwargs |
45 changes: 45 additions & 0 deletions 45 django_mongodb_backend/management/commands/get_encrypted_fields_map.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
import json | ||
| ||
from django.apps import apps | ||
from django.core.management.base import BaseCommand | ||
from django.db import DEFAULT_DB_ALIAS, connections | ||
| ||
| ||
class Command(BaseCommand): | ||
help = "Generate an encryptedFieldsMap for MongoDB automatic encryption" | ||
| ||
def handle(self, *args, **options): | ||
connection = connections[DEFAULT_DB_ALIAS] | ||
| ||
schema_map = self.generate_encrypted_fields_schema_map(connection) | ||
| ||
self.stdout.write(json.dumps(schema_map, indent=2)) | ||
| ||
def generate_encrypted_fields_schema_map(self, conn): | ||
schema_map = {} | ||
| ||
for model in apps.get_models(): | ||
encrypted_fields = self.get_encrypted_fields(model, conn) | ||
if encrypted_fields: | ||
collection = model._meta.db_table | ||
schema_map[collection] = {"fields": encrypted_fields} | ||
| ||
return schema_map | ||
| ||
def get_encrypted_fields(self, model, conn): | ||
fields = model._meta.fields | ||
encrypted_fields = [] | ||
| ||
for field in fields: | ||
if getattr(field, "encrypted", False): | ||
field_map = { | ||
"path": field.column, | ||
"bsonType": field.db_type(conn), | ||
} | ||
| ||
if getattr(field, "queries", None): | ||
field_map["queries"] = field.queries[0].to_dict() | ||
| ||
encrypted_fields.append(field_map) | ||
| ||
return encrypted_fields |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
Encrypted models | ||
================ | ||
| ||
``EncryptedCharField`` | ||
---------------------- | ||
| ||
The basics | ||
~~~~~~~~~~ | ||
| ||
Let's consider this example:: | ||
| ||
from django.db import models | ||
| ||
from django_mongodb_backend.fields import EncryptedCharField | ||
from django_mongodb_backend.models import EncryptedModel | ||
| ||
| ||
class Person(EncryptedModel): | ||
ssn = EncryptedCharField("ssn", max_length=11) | ||
| ||
def __str__(self): | ||
return self.ssn |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
| @@ -10,4 +10,5 @@ know: | |
| ||
cache | ||
embedded-models | ||
encrypted-models | ||
known-issues |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
from django.db import models | ||
| ||
from django_mongodb_backend.encryption import QueryTypes | ||
from django_mongodb_backend.fields import EncryptedCharField | ||
from django_mongodb_backend.models import EncryptedModel | ||
| ||
# Query types for encrypted fields with optional parameters | ||
query_types = QueryTypes() | ||
queries = [query_types.equality(contention=1), query_types.range(sparsity=2, precision=3)] | ||
| ||
| ||
class Person(EncryptedModel): | ||
name = models.CharField("name", max_length=100) | ||
ssn = EncryptedCharField("ssn", max_length=11, queries=queries) | ||
| ||
class Meta: | ||
required_db_features = {"supports_queryable_encryption"} | ||
| ||
def __str__(self): | ||
return self.name |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.