encryption_options – Automatic Client-Side Field Level Encryption¶
Support for automatic client-side field level encryption.
See also
This module is compatible with both the synchronous and asynchronous PyMongo APIs.
- class pymongo.encryption_options.AsyncHTTPProxyKMSConnect(proxy_url, ssl_context=None, headers=None)¶
Route KMS connections through an HTTP proxy, for the asynchronous API.
Behaves exactly like
HTTPProxyKMSConnect, but is a coroutine callable and runs the blocking connect in a thread so the event loop stays free.Added in version 4.19.
- Parameters:
proxy_url (str)
ssl_context (Optional[ssl.SSLContext])
headers (Optional[Mapping[str, str]])
- class pymongo.encryption_options.AutoEncryptionOpts(kms_providers, key_vault_namespace, key_vault_client=None, schema_map=None, bypass_auto_encryption=False, mongocryptd_uri='mongodb://localhost:27020', mongocryptd_bypass_spawn=False, mongocryptd_spawn_path='mongocryptd', mongocryptd_spawn_args=None, kms_tls_options=None, crypt_shared_lib_path=None, crypt_shared_lib_required=False, bypass_query_analysis=False, encrypted_fields_map=None, key_expiration_ms=None, kms_connect_callback=None)¶
Options to configure automatic client-side field level encryption.
Automatic client-side field level encryption requires MongoDB enterprise or a MongoDB Atlas cluster. Automatic encryption is not supported for operations on a database or view and will result in error.
Although automatic encryption requires MongoDB enterprise or a MongoDB Atlas cluster, automatic decryption is supported for all users. To configure automatic decryption without automatic encryption set
bypass_auto_encryption=True. Explicit encryption and explicit decryption is also supported for all users with theAsyncClientEncryptionandClientEncryptionclasses.See client-side field level encryption for an example.
- Parameters:
kms_providers (Mapping[str, Any]) –
Map of KMS provider options. The kms_providers map values differ by provider:
aws: Map with “accessKeyId” and “secretAccessKey” as strings. These are the AWS access key ID and AWS secret access key used to generate KMS messages. An optional “sessionToken” may be included to support temporary AWS credentials.
azure: Map with “tenantId”, “clientId”, and “clientSecret” as strings. Additionally, “identityPlatformEndpoint” may also be specified as a string (defaults to ‘login.microsoftonline.com’). These are the Azure Active Directory credentials used to generate Azure Key Vault messages.
gcp: Map with “email” as a string and “privateKey” as bytes or a base64 encoded string. Additionally, “endpoint” may also be specified as a string (defaults to ‘oauth2.googleapis.com’). These are the credentials used to generate Google Cloud KMS messages.
kmip: Map with “endpoint” as a host with required port. For example:
{"endpoint": "example.com:443"}.local: Map with “key” as bytes (96 bytes in length) or a base64 encoded string which decodes to 96 bytes. “key” is the master key used to encrypt/decrypt data keys. This key should be generated and stored as securely as possible.
KMS providers may be specified with an optional name suffix separated by a colon, for example “kmip:name” or “aws:name”. Named KMS providers do not support CSFLE on-demand credentials. Named KMS providers enables more than one of each KMS provider type to be configured. For example, to configure multiple local KMS providers:
kms_providers = { "local": {"key": local_kek1}, # Unnamed KMS provider. "local:myname": {"key": local_kek2}, # Named KMS provider with name "myname". }
key_vault_namespace (str) – The namespace for the key vault collection. The key vault collection contains all data keys used for encryption and decryption. Data keys are stored as documents in this MongoDB collection. Data keys are protected with encryption by a KMS provider.
key_vault_client (Optional[_AgnosticMongoClient]) – By default, the key vault collection is assumed to reside in the same MongoDB cluster as the encrypted AsyncMongoClient/MongoClient. Use this option to route data key queries to a separate MongoDB cluster.
schema_map (Optional[Mapping[str, Any]]) –
Map of collection namespace (“db.coll”) to JSON Schema. By default, a collection’s JSONSchema is periodically polled with the listCollections command. But a JSONSchema may be specified locally with the schemaMap option.
Supplying a `schema_map` provides more security than relying on JSON Schemas obtained from the server. It protects against a malicious server advertising a false JSON Schema, which could trick the client into sending unencrypted data that should be encrypted.
Schemas supplied in the schemaMap only apply to configuring automatic encryption for client side encryption. Other validation rules in the JSON schema will not be enforced by the driver and will result in an error.
bypass_auto_encryption (bool) – If
True, automatic encryption will be disabled but automatic decryption will still be enabled. Defaults toFalse.mongocryptd_uri (str) – The MongoDB URI used to connect to the local mongocryptd process. Defaults to
'mongodb://localhost:27020'.mongocryptd_bypass_spawn (bool) – If
True, the encrypted AsyncMongoClient/MongoClient will not attempt to spawn the mongocryptd process. Defaults toFalse.mongocryptd_spawn_path (str) – Used for spawning the mongocryptd process. Defaults to
'mongocryptd'and spawns mongocryptd from the system path.mongocryptd_spawn_args (Optional[list[str]]) – A list of string arguments to use when spawning the mongocryptd process. Defaults to
['--idleShutdownTimeoutSecs=60']. If the list does not include theidleShutdownTimeoutSecsoption then'--idleShutdownTimeoutSecs=60'will be added.kms_tls_options (Optional[Mapping[str, Any]]) –
A map of KMS provider names to TLS options to use when creating secure connections to KMS providers. Accepts the same TLS options as
pymongo.mongo_client.AsyncMongoClientandpymongo.mongo_client.MongoClient. For example, to override the system default CA file:kms_tls_options={'kmip': {'tlsCAFile': certifi.where()}}
Or to supply a client certificate:
kms_tls_options={'kmip': {'tlsCertificateKeyFile': 'client.pem'}}
crypt_shared_lib_path (Optional[str]) – Override the path to load the crypt_shared library.
crypt_shared_lib_required (bool) – If True, raise an error if libmongocrypt is unable to load the crypt_shared library.
bypass_query_analysis (bool) – If
True, disable automatic analysis of outgoing commands. Set bypass_query_analysis to use explicit encryption on indexed fields without the MongoDB Enterprise Advanced licensed crypt_shared library.encrypted_fields_map (Optional[Mapping[str, Any]]) –
Map of collection namespace (“db.coll”) to documents that described the encrypted fields for Queryable Encryption. For example:
{ "db.encryptedCollection": { "escCollection": "enxcol_.encryptedCollection.esc", "ecocCollection": "enxcol_.encryptedCollection.ecoc", "fields": [ { "path": "firstName", "keyId": Binary.from_uuid(UUID('00000000-0000-0000-0000-000000000000')), "bsonType": "string", "queries": {"queryType": "equality"} }, { "path": "ssn", "keyId": Binary.from_uuid(UUID('04104104-1041-0410-4104-104104104104')), "bsonType": "string" } ] } }
key_expiration_ms (Optional[int]) – The cache expiration time for data encryption keys. Defaults to
Nonewhich defers to libmongocrypt’s default which is currently 60000. Set to 0 to disable key expiration.kms_connect_callback (Optional[Callable[[KMSConnectContext], Any]]) – A callable that opens the connection to a KMS host, used to route KMS requests through an HTTP proxy. It receives a
KMSConnectContextand returns a connected, unwrappedsocket.socket, over which the driver performs the KMS TLS handshake. Must be a coroutine function forAsyncMongoClientand a regular function forMongoClient. Defaults toNone, meaning the driver connects to KMS hosts directly.
Changed in version 4.19: Added the kms_connect_callback parameter.
Changed in version 4.12: Added the key_expiration_ms parameter.
Changed in version 4.2: Added the encrypted_fields_map, crypt_shared_lib_path, crypt_shared_lib_required, and bypass_query_analysis parameters.
Changed in version 4.0: Added the kms_tls_options parameter and the “kmip” KMS provider.
Added in version 3.9.
- class pymongo.encryption_options.HTTPProxyKMSConnect(proxy_url, ssl_context=None, headers=None)¶
Route KMS connections through an HTTP proxy, for the synchronous API.
Pass an instance as
kms_connect_callbackto reach KMS hosts through a forward proxy that speaks HTTPCONNECT:from pymongo.encryption_options import AutoEncryptionOpts, HTTPProxyKMSConnect opts = AutoEncryptionOpts( kms_providers={"aws": aws_creds}, key_vault_namespace="keyvault.datakeys", kms_connect_callback=HTTPProxyKMSConnect("http://proxy.example.com:8080"), )
To reach the proxy over TLS, use an
httpsproxy URL. Pass anssl.SSLContextto customize trust; the default context is used otherwise. It applies only to the proxy connection; KMS TLS is still negotiated end to end:import ssl proxy_tls = ssl.create_default_context(cafile="proxy-ca.pem") callback = HTTPProxyKMSConnect("https://proxy.example.com:8443", proxy_tls)
Use
AsyncHTTPProxyKMSConnectwith the asynchronous API.- Parameters:
proxy_url (str) – URL of the proxy, in the same form as a proxy configured for
urllib.request, e.g.http://proxy.example.com:8080. The scheme must behttporhttps, and the port defaults to 80 and 443, respectively. Userinfo, e.g.http://user:pass@proxy.example.com:8080, is sent as aProxy-Authorizationbasic auth header. When sending credentials, use anhttpsproxy URL so they are not sent in cleartext.ssl_context (Optional[ssl.SSLContext]) – Optional
ssl.SSLContextfor connecting to the proxy over TLS. Defaults toNone, meaning the default context for anhttpsproxy URL, or a plain connection forhttp.headers (Optional[Mapping[str, str]]) – Optional mapping of extra
CONNECTrequest headers, e.g.{"X-Trace-Id": "abc123"}.Hostis always set from the KMS address, andProxy-Authorizationfrom any proxy URL userinfo.
Added in version 4.19.
- class pymongo.encryption_options.KMSConnectContext(host, port, timeout)¶
Information about a pending KMS connection.
Passed to
kms_connect_callback, which must return a plain, unwrappedsocket.socket. The driver performs the KMS TLS handshake over it, verifying againsthostrather than the peer actually reached.Prefer
HTTPProxyKMSConnectorAsyncHTTPProxyKMSConnectover writing a callback.- Parameters:
host (str) – Hostname of the KMS server, and the TLS verification target.
port (int) – Port of the KMS server.
timeout (float) – Seconds allowed for the connection: the default KMS connect timeout, capped by the remaining
timeoutMSbudget.
Note
timeoutMSdoes not constrain KMS requests for explicit encryption, sotimeoutis always the default there. Automatic encryption passes the remaining budget. This deviates from the Client Side Operations Timeout specification; see PYTHON-6037.Added in version 4.19.
- class pymongo.encryption_options.PrefixOpts¶
Options for prefix string queries.
Added in version 4.15.
- class pymongo.encryption_options.RangeOpts(sparsity=None, trim_factor=None, min=None, max=None, precision=None)¶
Options to configure encrypted queries using the range algorithm.
- Parameters:
sparsity (Optional[int]) – An integer.
trim_factor (Optional[int]) – An integer.
min (Optional[Any]) – A BSON scalar value corresponding to the type being queried.
max (Optional[Any]) – A BSON scalar value corresponding to the type being queried.
precision (Optional[int]) – An integer, may only be set for double or decimal128 types.
Added in version 4.4.
- class pymongo.encryption_options.StringOpts(substring=None, prefix=None, suffix=None, case_sensitive=None, diacritic_sensitive=None)¶
Options to configure encrypted queries using the string algorithm.
- Parameters:
substring (Optional[SubstringOpts]) – Further options to support substring queries.
prefix (Optional[PrefixOpts]) – Further options to support prefix queries.
suffix (Optional[SuffixOpts]) – Further options to support suffix queries.
case_sensitive (Optional[bool]) – Whether string indexes for this field are case sensitive.
diacritic_sensitive (Optional[bool]) – Whether string indexes for this field are diacritic sensitive.
Added in version 4.18:
StringOptsreplacesTextOpts, which is deprecated.
- class pymongo.encryption_options.SubstringOpts¶
Options for substring string queries.
Added in version 4.15.
- class pymongo.encryption_options.SuffixOpts¶
Options for suffix string queries.
Added in version 4.15.
- class pymongo.encryption_options.TextOpts(*args, **kwargs)¶
Options to configure encrypted queries using the string algorithm.
- Parameters:
substring – Further options to support substring queries.
prefix – Further options to support prefix queries.
suffix – Further options to support suffix queries.
case_sensitive – Whether string indexes for this field are case sensitive.
diacritic_sensitive – Whether string indexes for this field are diacritic sensitive.
args (Any)
kwargs (Any)
Added in version 4.18:
StringOptsreplacesTextOpts, which is deprecated.
- pymongo.encryption_options.check_min_pymongocrypt()¶
Raise an appropriate error if the min pymongocrypt is not installed.
- Return type:
None