|
| 1 | +# Copyright 2019-present MongoDB, Inc. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""Options to configure client side encryption.""" |
| 16 | + |
| 17 | +import copy |
| 18 | +import socket |
| 19 | + |
| 20 | +try: |
| 21 | + import pymongocrypt |
| 22 | + _HAVE_PYMONGOCRYPT = True |
| 23 | +except ImportError: |
| 24 | + _HAVE_PYMONGOCRYPT = False |
| 25 | + |
| 26 | +from pymongo.errors import ConfigurationError |
| 27 | + |
| 28 | + |
| 29 | +class AutoEncryptionOpts(object): |
| 30 | + """Options to configure automatic encryption.""" |
| 31 | + |
| 32 | + def __init__(self, kms_providers, key_vault_namespace, |
| 33 | + key_vault_client=None, schema_map=None, |
| 34 | + bypass_auto_encryption=False, |
| 35 | + mongocryptd_uri=None, |
| 36 | + mongocryptd_bypass_spawn=False, |
| 37 | + mongocryptd_spawn_path='mongocryptd', |
| 38 | + mongocryptd_spawn_args=None): |
| 39 | + """Options to configure automatic encryption. |
| 40 | +
|
| 41 | + Automatic encryption is an enterprise only feature that only |
| 42 | + applies to operations on a collection. Automatic encryption is not |
| 43 | + supported for operations on a database or view and will result in |
| 44 | + error. To bypass automatic encryption (but enable automatic |
| 45 | + decryption), set ``bypass_auto_encryption=True`` in |
| 46 | + AutoEncryptionOpts. |
| 47 | +
|
| 48 | + Explicit encryption/decryption and automatic decryption is a |
| 49 | + community feature. A MongoClient configured with |
| 50 | + bypassAutoEncryption=true will still automatically decrypt. |
| 51 | +
|
| 52 | + :Parameters: |
| 53 | + - `kms_providers`: Map of KMS provider options. Two KMS providers |
| 54 | + are supported: "aws" and "local". The kmsProviders map values |
| 55 | + differ by provider: |
| 56 | +
|
| 57 | + - `aws`: Map with "accessKeyId" and "secretAccessKey" as strings. |
| 58 | + These are the AWS access key ID and AWS secret access key used |
| 59 | + to generate KMS messages. |
| 60 | + - `local`: Map with "key" as a 96-byte array or string. "key" |
| 61 | + is the master key used to encrypt/decrypt data keys. This key |
| 62 | + should be generated and stored as securely as possible. |
| 63 | +
|
| 64 | + - `key_vault_namespace`: The namespace for the key vault collection. |
| 65 | + The key vault collection contains all data keys used for encryption |
| 66 | + and decryption. Data keys are stored as documents in this MongoDB |
| 67 | + collection. Data keys are protected with encryption by a KMS |
| 68 | + provider. |
| 69 | + - `key_vault_client` (optional): By default the key vault collection |
| 70 | + is assumed to reside in the same MongoDB cluster as the encrypted |
| 71 | + MongoClient. Use this option to route data key queries to a |
| 72 | + separate MongoDB cluster. |
| 73 | + - `schema_map` (optional): Map of collection namespace ("db.coll") to |
| 74 | + JSON Schema. By default, a collection's JSONSchema is periodically |
| 75 | + polled with the listCollections command. But a JSONSchema may be |
| 76 | + specified locally with the schemaMap option. |
| 77 | +
|
| 78 | + **Supplying a `schema_map` provides more security than relying on |
| 79 | + JSON Schemas obtained from the server. It protects against a |
| 80 | + malicious server advertising a false JSON Schema, which could trick |
| 81 | + the client into sending unencrypted data that should be |
| 82 | + encrypted.** |
| 83 | +
|
| 84 | + Schemas supplied in the schemaMap only apply to configuring |
| 85 | + automatic encryption for client side encryption. Other validation |
| 86 | + rules in the JSON schema will not be enforced by the driver and |
| 87 | + will result in an error. |
| 88 | + - `bypass_auto_encryption` (optional): If ``True``, automatic |
| 89 | + encryption will be disabled but automatic decryption will still be |
| 90 | + enabled. Defaults to ``False``. |
| 91 | + - `mongocryptd_uri` (optional): The MongoDB URI used to connect |
| 92 | + to the *local* mongocryptd process. Defaults to |
| 93 | + ``"mongodb://%2Ftmp%2Fmongocryptd.sock"`` if domain sockets are |
| 94 | + available or ``"mongodb://localhost:27020"`` otherwise. |
| 95 | + - `mongocryptd_bypass_spawn` (optional): If ``True``, the encrypted |
| 96 | + MongoClient will not attempt to spawn the mongocryptd process. |
| 97 | + Defaults to ``False``. |
| 98 | + - `mongocryptd_spawn_path` (optional): Used for spawning the |
| 99 | + mongocryptd process. Defaults to ``'mongocryptd'`` and spawns |
| 100 | + mongocryptd from the system path. |
| 101 | + - `mongocryptd_spawn_args` (optional): A list of string arguments to |
| 102 | + use when spawning the mongocryptd process. Defaults to |
| 103 | + ``['--idleShutdownTimeoutSecs=60']``. If the list does not include |
| 104 | + the ``idleShutdownTimeoutSecs`` option then |
| 105 | + ``'--idleShutdownTimeoutSecs=60'`` will be added. |
| 106 | +
|
| 107 | + .. versionadded:: 3.9 |
| 108 | + """ |
| 109 | + if not _HAVE_PYMONGOCRYPT: |
| 110 | + raise ConfigurationError( |
| 111 | + "client side encryption requires the pymongocrypt library: " |
| 112 | + "install a compatible version with: " |
| 113 | + "python -m pip install pymongo['encryption']") |
| 114 | + |
| 115 | + self._kms_providers = kms_providers |
| 116 | + self._key_vault_namespace = key_vault_namespace |
| 117 | + self._key_vault_client = key_vault_client |
| 118 | + self._schema_map = schema_map |
| 119 | + self._bypass_auto_encryption = bypass_auto_encryption |
| 120 | + if mongocryptd_uri is None: |
| 121 | + if hasattr(socket, 'AF_UNIX'): |
| 122 | + mongocryptd_uri = 'mongodb://%2Ftmp%2Fmongocryptd.sock' |
| 123 | + else: |
| 124 | + mongocryptd_uri = 'mongodb://localhost:27020' |
| 125 | + self._mongocryptd_uri = mongocryptd_uri |
| 126 | + self._mongocryptd_bypass_spawn = mongocryptd_bypass_spawn |
| 127 | + self._mongocryptd_spawn_path = mongocryptd_spawn_path |
| 128 | + self._mongocryptd_spawn_args = (copy.copy(mongocryptd_spawn_args) or |
| 129 | + ['--idleShutdownTimeoutSecs=60']) |
| 130 | + if not isinstance(self._mongocryptd_spawn_args, list): |
| 131 | + raise TypeError('mongocryptd_spawn_args must be a list') |
| 132 | + if not any('idleShutdownTimeoutSecs' in s |
| 133 | + for s in self._mongocryptd_spawn_args): |
| 134 | + self._mongocryptd_spawn_args.append('--idleShutdownTimeoutSecs=60') |
| 135 | + |
| 136 | + |
| 137 | +def validate_auto_encryption_opts_or_none(option, value): |
| 138 | + """Validate the driver keyword arg.""" |
| 139 | + if value is None: |
| 140 | + return value |
| 141 | + if not isinstance(value, AutoEncryptionOpts): |
| 142 | + raise TypeError("%s must be an instance of AutoEncryptionOpts" % ( |
| 143 | + option,)) |
| 144 | + |
| 145 | + return value |
0 commit comments