encryption_options.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  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. """Support for automatic client-side field level encryption."""
  15. import copy
  16. try:
  17. import pymongocrypt
  18. _HAVE_PYMONGOCRYPT = True
  19. except ImportError:
  20. _HAVE_PYMONGOCRYPT = False
  21. from pymongo.errors import ConfigurationError
  22. class AutoEncryptionOpts(object):
  23. """Options to configure automatic client-side field level encryption."""
  24. def __init__(self, kms_providers, key_vault_namespace,
  25. key_vault_client=None,
  26. schema_map=None,
  27. bypass_auto_encryption=False,
  28. mongocryptd_uri='mongodb://localhost:27020',
  29. mongocryptd_bypass_spawn=False,
  30. mongocryptd_spawn_path='mongocryptd',
  31. mongocryptd_spawn_args=None):
  32. """Options to configure automatic client-side field level encryption.
  33. Automatic client-side field level encryption requires MongoDB 4.2
  34. enterprise or a MongoDB 4.2 Atlas cluster. Automatic encryption is not
  35. supported for operations on a database or view and will result in
  36. error.
  37. Although automatic encryption requires MongoDB 4.2 enterprise or a
  38. MongoDB 4.2 Atlas cluster, automatic *decryption* is supported for all
  39. users. To configure automatic *decryption* without automatic
  40. *encryption* set ``bypass_auto_encryption=True``. Explicit
  41. encryption and explicit decryption is also supported for all users
  42. with the :class:`~pymongo.encryption.ClientEncryption` class.
  43. See :ref:`automatic-client-side-encryption` for an example.
  44. :Parameters:
  45. - `kms_providers`: Map of KMS provider options. Two KMS providers
  46. are supported: "aws" and "local". The kmsProviders map values
  47. differ by provider:
  48. - `aws`: Map with "accessKeyId" and "secretAccessKey" as strings.
  49. These are the AWS access key ID and AWS secret access key used
  50. to generate KMS messages. An optional "sessionToken" may be
  51. included to support temporary AWS credentials.
  52. - `azure`: Map with "tenantId", "clientId", and "clientSecret" as
  53. strings. Additionally, "identityPlatformEndpoint" may also be
  54. specified as a string (defaults to 'login.microsoftonline.com').
  55. These are the Azure Active Directory credentials used to
  56. generate Azure Key Vault messages.
  57. - `gcp`: Map with "email" as a string and "privateKey"
  58. as `bytes` or a base64 encoded string (unicode on Python 2).
  59. Additionally, "endpoint" may also be specified as a string
  60. (defaults to 'oauth2.googleapis.com'). These are the
  61. credentials used to generate Google Cloud KMS messages.
  62. - `local`: Map with "key" as `bytes` (96 bytes in length) or
  63. a base64 encoded string (unicode on Python 2) which decodes
  64. to 96 bytes. "key" is the master key used to encrypt/decrypt
  65. data keys. This key should be generated and stored as securely
  66. as possible.
  67. - `key_vault_namespace`: The namespace for the key vault collection.
  68. The key vault collection contains all data keys used for encryption
  69. and decryption. Data keys are stored as documents in this MongoDB
  70. collection. Data keys are protected with encryption by a KMS
  71. provider.
  72. - `key_vault_client` (optional): By default the key vault collection
  73. is assumed to reside in the same MongoDB cluster as the encrypted
  74. MongoClient. Use this option to route data key queries to a
  75. separate MongoDB cluster.
  76. - `schema_map` (optional): Map of collection namespace ("db.coll") to
  77. JSON Schema. By default, a collection's JSONSchema is periodically
  78. polled with the listCollections command. But a JSONSchema may be
  79. specified locally with the schemaMap option.
  80. **Supplying a `schema_map` provides more security than relying on
  81. JSON Schemas obtained from the server. It protects against a
  82. malicious server advertising a false JSON Schema, which could trick
  83. the client into sending unencrypted data that should be
  84. encrypted.**
  85. Schemas supplied in the schemaMap only apply to configuring
  86. automatic encryption for client side encryption. Other validation
  87. rules in the JSON schema will not be enforced by the driver and
  88. will result in an error.
  89. - `bypass_auto_encryption` (optional): If ``True``, automatic
  90. encryption will be disabled but automatic decryption will still be
  91. enabled. Defaults to ``False``.
  92. - `mongocryptd_uri` (optional): The MongoDB URI used to connect
  93. to the *local* mongocryptd process. Defaults to
  94. ``'mongodb://localhost:27020'``.
  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. .. versionadded:: 3.9
  107. """
  108. if not _HAVE_PYMONGOCRYPT:
  109. raise ConfigurationError(
  110. "client side encryption requires the pymongocrypt library: "
  111. "install a compatible version with: "
  112. "python -m pip install 'pymongo[encryption]'")
  113. self._kms_providers = kms_providers
  114. self._key_vault_namespace = key_vault_namespace
  115. self._key_vault_client = key_vault_client
  116. self._schema_map = schema_map
  117. self._bypass_auto_encryption = bypass_auto_encryption
  118. self._mongocryptd_uri = mongocryptd_uri
  119. self._mongocryptd_bypass_spawn = mongocryptd_bypass_spawn
  120. self._mongocryptd_spawn_path = mongocryptd_spawn_path
  121. self._mongocryptd_spawn_args = (copy.copy(mongocryptd_spawn_args) or
  122. ['--idleShutdownTimeoutSecs=60'])
  123. if not isinstance(self._mongocryptd_spawn_args, list):
  124. raise TypeError('mongocryptd_spawn_args must be a list')
  125. if not any('idleShutdownTimeoutSecs' in s
  126. for s in self._mongocryptd_spawn_args):
  127. self._mongocryptd_spawn_args.append('--idleShutdownTimeoutSecs=60')
  128. def validate_auto_encryption_opts_or_none(option, value):
  129. """Validate the driver keyword arg."""
  130. if value is None:
  131. return value
  132. if not isinstance(value, AutoEncryptionOpts):
  133. raise TypeError("%s must be an instance of AutoEncryptionOpts" % (
  134. option,))
  135. return value