Skip to content

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
wants to merge 70 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
70 commits
Select commit Hold shift + click to select a range
bc52c8e
INTPYTHON-527 Add Queryable Encryption support
aclark4life Jun 25, 2025
38fb110
Fix test for unencrypted field not in field map
aclark4life Jun 27, 2025
65bd15a
Fix test for unencrypted field not in field map
aclark4life Jun 27, 2025
e08945b
Add comment about suppressing EncryptedCollectionError
aclark4life Jun 27, 2025
7b34b44
Don't rely on features to fall back to unencrypted
aclark4life Jun 27, 2025
8e83ada
Remove _nodb_cursor and disable version check
aclark4life Jun 28, 2025
4da895c
Don't surpress encrypted error
aclark4life Jun 28, 2025
ed54a9b
Rename get_encrypted_client -> get_client_encryption
aclark4life Jun 28, 2025
8a7766c
Add encryption router
aclark4life Jun 30, 2025
eab2f2e
Add "encryption" database to encryption tests
aclark4life Jun 30, 2025
10a361e
Move encrypted_fields_map to schema (1/2)
aclark4life Jul 1, 2025
01d5485
Move encrypted_fields_map to schema (2/x)
aclark4life Jul 1, 2025
db32487
Refactor helpers
aclark4life Jul 2, 2025
b2be223
Restore get_database_version functionality
aclark4life Jul 2, 2025
27d4b8e
Move encrypted router to tests
aclark4life Jul 2, 2025
c4d1c66
Fix router tests
aclark4life Jul 2, 2025
2772aff
Test feature `supports_queryable_encryption`
aclark4life Jul 2, 2025
d2ddf4e
Add path and bsonType to _get_encrypted_fields_map
aclark4life Jul 2, 2025
e25357e
Use the right database; rename some vars
aclark4life Jul 2, 2025
6487086
Refactor helpers again
aclark4life Jul 2, 2025
bc76db3
Allow user to customize some QE settings.
aclark4life Jul 2, 2025
4dbaa8f
Allow uer to customize KMS provider.
aclark4life Jul 2, 2025
9cc5ad2
Refactor
aclark4life Jul 2, 2025
c751b2d
Alpha sort helper functions
aclark4life Jul 2, 2025
b13a07f
Fix get_database_version
aclark4life Jul 3, 2025
534da6b
A better fix for using `buildInfo` command.
aclark4life Jul 3, 2025
13578ab
Add `queries` key to encrypted fields map
aclark4life Jul 4, 2025
3342d7f
Update django_mongodb_backend/schema.py
aclark4life Jul 7, 2025
9fd21e4
Update django_mongodb_backend/schema.py
aclark4life Jul 7, 2025
9bbe741
Update tests/encryption_/models.py
aclark4life Jul 7, 2025
d1eb737
Update tests/encryption_/models.py
aclark4life Jul 7, 2025
176f016
Fix conditional
aclark4life Jul 7, 2025
264b37a
Use column instead of name
aclark4life Jul 7, 2025
1771f56
Avoid double conditional
aclark4life Jul 7, 2025
819058a
Update tests and remove test router
aclark4life Jul 7, 2025
9a3c18e
Update django_mongodb_backend/fields/encryption.py
aclark4life Jul 7, 2025
071192e
Add deconstruct method for encryption fields
aclark4life Jul 7, 2025
b2a0534
Add setup & teardown for QE features test
aclark4life Jul 7, 2025
81cc887
Add query type classes and update test
aclark4life Jul 8, 2025
be3dd16
Add missing queries to deconstruct
aclark4life Jul 8, 2025
a2342e2
Add get_encrypted_fields_map management command
aclark4life Jul 8, 2025
05a7610
Add EncryptedRouter
aclark4life Jul 8, 2025
96b3fda
Optimistically add QE to release notes :-)
aclark4life Jul 8, 2025
1eb71d5
Fix label
aclark4life Jul 8, 2025
08209d3
Save encrypted models to encrypted db
aclark4life Jul 9, 2025
90fe562
Refactor and rename QueryTypes -> QueryType
aclark4life Jul 9, 2025
8c2b84c
Refactor, reword, alpha sort, add comments.
aclark4life Jul 9, 2025
ab680fd
Alpha-sort
aclark4life Jul 9, 2025
4a267f5
Document-driven design
aclark4life Jul 9, 2025
3fdc1f7
Document-driven design
aclark4life Jul 9, 2025
d562a76
Document-driven design
aclark4life Jul 9, 2025
163758d
Add encryption.rst
aclark4life Jul 9, 2025
b95c343
Make key_vault_namespace a required kwarg
aclark4life Jul 9, 2025
5205a0b
Reuse schema editor to create encrypted fields map
aclark4life Jul 9, 2025
b07c3e6
Add --database to get_encrypted_fields_map command
aclark4life Jul 9, 2025
e557632
Add WIP configuration docs
aclark4life Jul 9, 2025
c5f8888
Add check for mongodb 7.0
aclark4life Jul 9, 2025
a7bc5c5
Let's go with "Queryable Encryption" everywhere.
aclark4life Jul 9, 2025
09423bc
Update django_mongodb_backend/fields/encryption.py
aclark4life Jul 9, 2025
c756cf8
Update tests/encryption_/tests.py
aclark4life Jul 9, 2025
841797c
Update tests/encryption_/tests.py
aclark4life Jul 9, 2025
2386397
Remove gratuitous use of with and append
aclark4life Jul 10, 2025
d685d2a
Always use `assertRaisesMessage` for > precision
aclark4life Jul 10, 2025
08ea317
only include migratable models for given database
aclark4life Jul 10, 2025
3e839d7
Refactor QueryType, add encryptino_ migration
aclark4life Jul 10, 2025
75c6936
Refactor tests and fix schema test
aclark4life Jul 10, 2025
534452f
Remove migration, already tested by schema
aclark4life Jul 10, 2025
bf26a8a
Router & schema updates
aclark4life Jul 10, 2025
bf078ad
Re-add test routers
aclark4life Jul 10, 2025
2780e32
Fix test router
aclark4life Jul 10, 2025
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
28 changes: 27 additions & 1 deletion django_mongodb_backend/base.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import contextlib
import copy
import os

from django.core.exceptions import ImproperlyConfigured
from django.db import DEFAULT_DB_ALIAS
from django.db.backends.base.base import BaseDatabaseWrapper
from django.db.backends.base.base import NO_DB_ALIAS, BaseDatabaseWrapper
from django.db.backends.utils import debug_transaction
from django.utils.asyncio import async_unsafe
from django.utils.functional import cached_property
Expand Down Expand Up @@ -156,6 +157,9 @@ def _isnull_operator(a, b):
def __init__(self, settings_dict, alias=DEFAULT_DB_ALIAS):
super().__init__(settings_dict, alias=alias)
self.session = None
# Cache the `settings_dict` in case we need to check for
# auto_encryption_opts later.
self.__dict__["_settings_dict"] = copy.deepcopy(settings_dict)

def get_collection(self, name, **kwargs):
collection = Collection(self.database, name, **kwargs)
Expand Down Expand Up @@ -287,3 +291,25 @@ def validate_no_broken_transaction(self):
def get_database_version(self):
"""Return a tuple of the database's version."""
return tuple(self.connection.server_info()["versionArray"])

@contextlib.contextmanager
def _nodb_cursor(self):
"""
Returns a cursor from an unencrypted connection for operations
that do not support encryption.
Encryption is only supported on encrypted models.
"""

# Remove auto_encryption_opts from OPTIONS
if self.settings_dict.get("OPTIONS", {}).get("auto_encryption_opts"):
self.settings_dict["OPTIONS"].pop("auto_encryption_opts")

# Create a new connection without OPTIONS["auto_encryption_opts": …]
conn = self.__class__({**self.settings_dict}, alias=NO_DB_ALIAS)

try:
with conn.cursor() as cursor:
yield cursor
finally:
conn.close()
66 changes: 66 additions & 0 deletions django_mongodb_backend/encryption.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# 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


def get_encrypted_client(auto_encryption_opts, encrypted_connection):
"""
Returns a `ClientEncryption` instance for MongoDB Client-Side Field Level
Encryption (CSFLE) that can be used to create an encrypted collection.
"""

key_vault_namespace = auto_encryption_opts._key_vault_namespace
kms_providers = auto_encryption_opts._kms_providers
codec_options = CodecOptions(uuid_representation=STANDARD)
return ClientEncryption(kms_providers, key_vault_namespace, encrypted_connection, codec_options)


def get_auto_encryption_opts(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.
"""
key_vault_database_name = "encryption"
key_vault_collection_name = "__keyVault"
key_vault_namespace = f"{key_vault_database_name}.{key_vault_collection_name}"
return AutoEncryptionOpts(
key_vault_namespace=key_vault_namespace,
Copy link
Collaborator

Choose a reason for hiding this comment

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

I think that either key_vault_namespace should be a required kwarg or there should be a fallback like:

if key_vault_namespace is None: key_vault_namespace = get_key_vault_namespace() 

Otherwise, not passing a value gives:

 File "/home/tim/code/django/django/db/backends/base/base.py", line 256, in connect self.connection = self.get_new_connection(conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/tim/code/django/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/home/tim/code/django-mongodb/django_mongodb_backend/base.py", line 198, in get_new_connection conn = MongoClient(**conn_params, driver=self._driver_info()) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/tim/.virtualenvs/django312/lib/python3.12/site-packages/pymongo/synchronous/mongo_client.py", line 875, in __init__ self._init_based_on_options(self._seeds, srv_max_hosts, srv_service_name) File "/home/tim/.virtualenvs/django312/lib/python3.12/site-packages/pymongo/synchronous/mongo_client.py", line 981, in _init_based_on_options self._encrypter = _Encrypter(self, self._options.auto_encryption_opts) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/tim/.virtualenvs/django312/lib/python3.12/site-packages/pymongo/synchronous/encryption.py", line 424, in __init__ db, coll = opts._key_vault_namespace.split(".", 1) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'NoneType' object has no attribute 'split' 
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Copy link
Collaborator

Choose a reason for hiding this comment

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

I know you're a fan of making things as simple as possible, and I fail to see the value of requiring users to pass encryption.get_key_vault_namespace() (without any value they customize). But I'll reserve judgement in case there is some future use case.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

You can judge! My current thinking is:

  • There could be a setting for KEY_VAULT_NAMESPACE
  • A user could use the helper to get a namespace without thinking.
  • A thinking user could set `KEY_VAULT_NAMESPACE = "some.key.vault.namespace"

Obviously relying on settings is not ideal but it's currently the least terrible way I can think of.

kms_providers=kms_providers,
crypt_shared_lib_path=crypt_shared_lib_path,
)


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_kms_providers():
"""
Return supported KMS providers for MongoDB Client-Side Field Level Encryption (CSFLE).
"""
return {
"local": {
"key": get_customer_master_key(),
},
}
15 changes: 15 additions & 0 deletions django_mongodb_backend/features.py
Original file line number Diff line number Diff line change
Expand Up @@ -624,3 +624,18 @@ def supports_transactions(self):
hello = client.command("hello")
# a replica set or a sharded cluster
return "setName" in hello or hello.get("msg") == "isdbgrid"

@cached_property
def supports_encryption(self):
"""
Encryption is supported if the server is Atlas or Enterprise
and is configured as a replica set or sharded cluster.
"""
self.connection.ensure_connection()
client = self.connection.connection.admin
build_info = client.command("buildInfo")
is_enterprise = "enterprise" in build_info.get("modules")
# `supports_transactions` already checks if the server is a
# replica set or sharded cluster.
is_not_single = self.supports_transactions
return is_enterprise and is_not_single
2 changes: 2 additions & 0 deletions django_mongodb_backend/fields/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from .duration import register_duration_field
from .embedded_model import EmbeddedModelField
from .embedded_model_array import EmbeddedModelArrayField
from .encryption import EncryptedCharField
from .json import register_json_field
from .objectid import ObjectIdField

Expand All @@ -11,6 +12,7 @@
"ArrayField",
"EmbeddedModelArrayField",
"EmbeddedModelField",
"EncryptedCharField",
"ObjectIdAutoField",
"ObjectIdField",
]
Expand Down
7 changes: 7 additions & 0 deletions django_mongodb_backend/fields/encryption.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from django.db import models


class EncryptedCharField(models.CharField):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.encrypted = True
23 changes: 23 additions & 0 deletions django_mongodb_backend/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,26 @@ def delete(self, *args, **kwargs):

def save(self, *args, **kwargs):
raise NotSupportedError("EmbeddedModels cannot be saved.")


class EncryptedModelBase(models.base.ModelBase):
def __new__(cls, name, bases, attrs, **kwargs):
new_class = super().__new__(cls, name, bases, attrs, **kwargs)

# Build a map of encrypted fields
encrypted_fields = {
"fields": {
field.name: field.__class__.__name__
for field in new_class._meta.fields
if getattr(field, "encrypted", False)
}
}

# Store it as a class-level attribute
new_class.encrypted_fields_map = encrypted_fields
return new_class


class EncryptedModel(models.Model, metaclass=EncryptedModelBase):
class Meta:
abstract = True
51 changes: 48 additions & 3 deletions django_mongodb_backend/schema.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import contextlib

from django.db.backends.base.schema import BaseDatabaseSchemaEditor
from django.db.models import Index, UniqueConstraint
from pymongo.encryption import EncryptedCollectionError
from pymongo.operations import SearchIndexModel

from django_mongodb_backend.indexes import SearchIndex

from .encryption import get_encrypted_client
from .fields import EmbeddedModelField
from .indexes import SearchIndex
from .query import wrap_database_errors
from .utils import OperationCollector

Expand Down Expand Up @@ -41,7 +44,7 @@ def get_database(self):
@wrap_database_errors
@ignore_embedded_models
def create_model(self, model):
self.get_database().create_collection(model._meta.db_table)
self._create_collection(model)
self._create_model_indexes(model)
# Make implicit M2M tables.
for field in model._meta.local_many_to_many:
Expand Down Expand Up @@ -418,3 +421,45 @@ def _field_should_have_unique(self, field):
db_type = field.db_type(self.connection)
# The _id column is automatically unique.
return db_type and field.unique and field.column != "_id"

def _supports_encryption(self, model):
"""
Check for `supports_encryption` feature and `auto_encryption_opts`
and `embedded_fields_map`. If `supports_encryption` is True and
`auto_encryption_opts` is in the cached connection settings and
the model has an embedded_fields_map property, then encryption
is supported.
"""
return (
self.connection.features.supports_encryption
and self.connection._settings_dict.get("OPTIONS", {}).get("auto_encryption_opts")
and hasattr(model, "encrypted_fields_map")
)

def _create_collection(self, model):
"""
Create a collection or, if encryption is supported, create
an encrypted connection then use it to create an encrypted
client then use that to create an encrypted collection.
"""

if self._supports_encryption(model):
auto_encryption_opts = self.connection._settings_dict.get("OPTIONS", {}).get(
"auto_encryption_opts"
)
# Use the cached settings dict to create a new connection
encrypted_connection = self.connection.get_new_connection(
self.connection._settings_dict
)
# Use the encrypted connection and auto_encryption_opts to create an encrypted client
encrypted_client = get_encrypted_client(auto_encryption_opts, encrypted_connection)

with contextlib.suppress(EncryptedCollectionError):
encrypted_client.create_encrypted_collection(
encrypted_connection[self.connection.database.name],
model._meta.db_table,
model.encrypted_fields_map,
"local", # TODO: KMS provider should be configurable
)
else:
self.get_database().create_collection(model._meta.db_table)
22 changes: 22 additions & 0 deletions docs/source/topics/encrypted-models.rst
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
1 change: 1 addition & 0 deletions docs/source/topics/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,5 @@ know:

cache
embedded-models
encrypted-models
known-issues
Empty file added tests/encryption_/__init__.py
Empty file.
9 changes: 9 additions & 0 deletions tests/encryption_/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
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
30 changes: 30 additions & 0 deletions tests/encryption_/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
from django.test import TestCase

from .models import Person


class EncryptedModelTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.objs = [Person.objects.create()]

def test_encrypted_fields_map_on_class(self):
expected = {
"fields": {
"ssn": "EncryptedCharField",
}
}
self.assertEqual(Person.encrypted_fields_map, expected)

def test_encrypted_fields_map_on_instance(self):
instance = Person(ssn="123-45-6789")
expected = {
"fields": {
"ssn": "EncryptedCharField",
}
}
self.assertEqual(instance.encrypted_fields_map, expected)

def test_non_encrypted_fields_not_included(self):
encrypted_field_names = Person.encrypted_fields_map.keys()
self.assertNotIn("ssn", encrypted_field_names)
Loading