-
Notifications
You must be signed in to change notification settings - Fork 17
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fixup! add support for mongodb Client Side Field Level Encryption (CS…
…FLE)
- Loading branch information
Showing
8 changed files
with
272 additions
and
5 deletions.
There are no files selected for viewing
This file contains 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 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 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,133 @@ | ||
from __future__ import annotations | ||
|
||
from typing import TYPE_CHECKING, TypeVar, Generic | ||
|
||
from cachetools import cached, RRCache | ||
|
||
from pymongo.encryption import ClientEncryption, Algorithm | ||
from pymongo.errors import EncryptionError | ||
|
||
|
||
if TYPE_CHECKING: | ||
from pymongo import MongoClient | ||
from ming import Document | ||
import ming.datastore | ||
|
||
|
||
class EncryptionConfig: | ||
|
||
def __init__(self, encryption_config): | ||
self._encryption_config = encryption_config | ||
|
||
@property | ||
def kms_providers(self) -> str: | ||
return self._encryption_config.get('kms_providers') | ||
|
||
@property | ||
def provider_options(self) -> str: | ||
return self._encryption_config.get('provider_options') | ||
|
||
@property | ||
def key_vault_namespace(self) -> str: | ||
return self._encryption_config.get('key_vault_namespace') | ||
|
||
|
||
T = TypeVar('T') | ||
|
||
|
||
class DecryptedField(Generic[T]): | ||
|
||
def __init__(self, field_type: type[T], encrypted_field: str): | ||
self.field_type = field_type | ||
self.encrypted_field = encrypted_field | ||
|
||
def __get__(self, instance: EncryptedDocumentMixin, owner) -> T: | ||
return instance.decr(getattr(instance, self.encrypted_field)) | ||
|
||
def __set__(self, instance: EncryptedDocumentMixin, value: T): | ||
if not isinstance(value, self.field_type): | ||
raise TypeError(f'not {self.field_type}, got {value!r}') | ||
setattr(instance, self.encrypted_field, instance.encr(value)) | ||
|
||
|
||
class EncryptedDocumentMixin: | ||
|
||
@classmethod | ||
@cached(RRCache(maxsize=99)) # needs to be per datastore, so we pass that as a param | ||
def encryptor(cls, ming_ds: ming.datastore.DataStore): | ||
conn: MongoClient = ming_ds.conn | ||
kms_providers = {"local": {"key": ming_ds.encryption_key}} | ||
encryption = ClientEncryption(kms_providers, ming_ds.encr_data_key_vault, | ||
conn, conn.codec_options) | ||
return encryption | ||
|
||
@classmethod | ||
def make_data_key(cls): | ||
ming_ds: ming.datastore.DataStore = cls.m.session.bind | ||
# index recommended by mongodb docs: | ||
key_vault_db_name, key_vault_coll_name = ming_ds.encr_data_key_vault.split('.') | ||
key_vault_coll = ming_ds.conn[key_vault_db_name][key_vault_coll_name] | ||
key_vault_coll.create_index("keyAltNames", unique=True, | ||
partialFilterExpression={"keyAltNames": {"$exists": True}}) | ||
cls.encryptor(ming_ds).create_data_key('local', key_alt_names=[ming_ds.encr_data_key_name]) | ||
|
||
# cls.encryptor(ming_ds).create_data_key('local', **ming_ds['provider_options']['local']) | ||
# cls.encryptor(ming_ds).create_data_key('aws', **ming_ds['provider_options']['aws']) | ||
|
||
@classmethod | ||
def encr(cls, s: str | None, _first_attempt=True) -> bytes | None: | ||
if s is None: | ||
return None | ||
try: | ||
ming_ds: ming.datastore.DataStore = cls.m.session.bind | ||
return cls.encryptor(ming_ds).encrypt(s, | ||
Algorithm.AEAD_AES_256_CBC_HMAC_SHA_512_Deterministic, | ||
key_alt_name=cls.ming_ds.encr_data_key_name) | ||
except EncryptionError as e: | ||
if _first_attempt and 'not all keys requested were satisfied' in str(e): | ||
cls.make_data_key() | ||
return cls.encr(s, _first_attempt=False) | ||
else: | ||
raise | ||
|
||
@classmethod | ||
def decr(cls, b: bytes | None) -> str | None: | ||
if b is None: | ||
return None | ||
return cls.encryptor(cls.m.session.bind).decrypt(b) | ||
|
||
@classmethod | ||
def decrypted_field_names(cls) -> list[str]: | ||
return [fld.replace('_encrypted', '') | ||
for fld in cls.encrypted_field_names()] | ||
|
||
@classmethod | ||
def encrypted_field_names(cls) -> list[str]: | ||
return [fld for fld in dir(cls) | ||
if fld.endswith('_encrypted')] | ||
|
||
@classmethod | ||
def encrypt_some_fields(cls, data: dict) -> dict: | ||
encrypted_data = data.copy() | ||
for fld in cls.decrypted_field_names(): | ||
if fld in encrypted_data: | ||
val = encrypted_data.pop(fld) | ||
encrypted_data[f'{fld}_encrypted'] = cls.encr(val) | ||
return encrypted_data | ||
|
||
def decrypt_some_fields(self) -> dict: | ||
# useful for json, removes encrypted fields and uses decrypted forms | ||
decrypted_data = dict(self) | ||
for k, v in self.items(): | ||
if k.endswith('_encrypted'): | ||
del decrypted_data[k] | ||
k_decrypted = k.replace('_encrypted', '') | ||
decrypted_data[k_decrypted] = getattr(self, k_decrypted) | ||
return decrypted_data | ||
|
||
@classmethod | ||
def make_encr(cls, data: dict) -> Document: | ||
# wrapper around regular ming .make() | ||
data_with_encryption = cls.encrypt_some_fields(data) | ||
return cls.make(data_with_encryption) | ||
|
This file contains 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 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 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 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,57 @@ | ||
|
||
from .exc import MingConfigError | ||
from .encryption import EncryptionConfig | ||
|
||
try: | ||
from formencode import schema, validators | ||
except ImportError: | ||
raise MingConfigError("Need to install FormEncode to use ``ming.encryption`` package") | ||
|
||
|
||
class EncryptionConfigValidator(validators.FancyValidator): | ||
""" | ||
Password string validation to refrain from usage of name, username or email id (full or partial) as its substrings | ||
""" | ||
accept_iterator = True | ||
|
||
VALID_KMS_PROVIDERS = ('local', 'aws', 'azure', 'gcp', 'kmip') | ||
|
||
messages = dict( | ||
InvalidKMSProvider=f"Invalid KMS Provider %(provider). Valid options are: {', '.join(VALID_KMS_PROVIDERS)}" | ||
) | ||
|
||
def _convert_to_python(self, field_dict, state): | ||
if not field_dict: | ||
return None | ||
return EncryptionConfig(field_dict) | ||
|
||
def _validate_python(self, config: EncryptionConfig, state): | ||
if not config: | ||
return # no encryption settings | ||
|
||
def validate_inner(): | ||
error_dict = {} | ||
if config.kms_providers: | ||
if not config.key_vault_namespace: | ||
error_dict['key_vault_namespace'] = validators.Invalid(self.message('InvalidKMSProvider', state), config, state) | ||
if not config.provider_options: | ||
error_dict['provider_options'] = validators.Invalid(self.message('InvalidKMSProvider', state), config, state) | ||
|
||
used_kms_providers = set() | ||
for key, settings in config.kms_providers.items(): | ||
if key not in self.VALID_KMS_PROVIDERS: | ||
error_dict['kms_providers'] = validators.Invalid(self.message('InvalidKMSProvider', state, provider=key), config, state) | ||
break | ||
used_kms_providers.add(key) | ||
|
||
if error_dict: | ||
return error_dict | ||
|
||
if 'local' in used_kms_providers: | ||
if 'key' not in config.kms_providers['local']: | ||
error_dict['kms_providers'] = validators.Invalid(f'Local KMS Provider requires a key', config, state) | ||
|
||
error_dict = validate_inner() | ||
|
||
if error_dict: | ||
raise validators.Invalid(f'Invalid Encryption Settings', config, state, error_dict=error_dict) |
This file contains 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