diff --git a/.github/workflows/dist-python.yml b/.github/workflows/dist-python.yml
index bfe83ca16..872a8eacc 100644
--- a/.github/workflows/dist-python.yml
+++ b/.github/workflows/dist-python.yml
@@ -47,7 +47,7 @@ jobs:
- uses: actions/setup-python@v6
with:
- python-version: "3.9"
+ python-version: "3.11"
cache: 'pip'
cache-dependency-path: 'bindings/python/pyproject.toml'
allow-prereleases: true
diff --git a/.github/workflows/test-python.yml b/.github/workflows/test-python.yml
index 1806711fc..ea702018f 100644
--- a/.github/workflows/test-python.yml
+++ b/.github/workflows/test-python.yml
@@ -43,7 +43,7 @@ jobs:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
- python-version: ["3.9", "3.13", "3.14"]
+ python-version: ["3.11", "3.13", "3.14"]
steps:
- uses: actions/checkout@v5
diff --git a/bindings/python/.evergreen/utils.sh b/bindings/python/.evergreen/utils.sh
index d05fb9b29..ce7b04217 100755
--- a/bindings/python/.evergreen/utils.sh
+++ b/bindings/python/.evergreen/utils.sh
@@ -34,19 +34,19 @@ createvirtualenv () {
# Prints each usable interpreter from the space-separated candidate list,
# one per line, ascending by version. An interpreter is usable if it is
-# version 3.9 or later, a final release, and not free-threaded.
+# version 3.11 or later, a final release, and not free-threaded.
_probe_pythons() {
for bin in $1; do
[ -x "$bin" ] || continue
"$bin" -c 'import sys
-ok = sys.version_info >= (3, 9) and sys.version_info.releaselevel == "final" and "free-threading" not in sys.version
+ok = sys.version_info >= (3, 11) and sys.version_info.releaselevel == "final" and "free-threading" not in sys.version
exit(0 if ok else 1)' 2>/dev/null || continue
printf '%s\t%s\n' "$("$bin" -c 'import sys; print("%04d" % (sys.version_info[0] * 1000 + sys.version_info[1]))')" "$bin"
done | sort | cut -f2-
}
# Prints the Python interpreters in the standard numbered toolchain locations,
-# one per line, ascending by version, Python 3.9+ only. Only plain version
+# one per line, ascending by version, Python 3.11+ only. Only plain version
# directories are matched (e.g. 3.14, not 3.14-asan-ubsan, 3.14t, or on
# Windows Python314t/Python314-arm64). On Linux, falls back to the latest
# MongoDB toolchain interpreter when the Python toolchain is absent, then to
diff --git a/bindings/python/CHANGELOG.rst b/bindings/python/CHANGELOG.rst
index c5ce869dd..eb282b41f 100644
--- a/bindings/python/CHANGELOG.rst
+++ b/bindings/python/CHANGELOG.rst
@@ -4,6 +4,8 @@ Changelog
Changes in Version 1.21.0
-------------------------
+- Drop support for Python 3.9 and 3.10, and for PyPy. Python >=3.11 is now
+ required.
- Bundle libmongocrypt 1.21.0 in release wheels.
- Removed the deprecated "prefixPreview", "suffixPreview", and
"substringPreview" query types. Use "prefix", "suffix", and "substring"
diff --git a/bindings/python/README.rst b/bindings/python/README.rst
index 91b265ac6..92c32ae7f 100644
--- a/bindings/python/README.rst
+++ b/bindings/python/README.rst
@@ -13,7 +13,7 @@ Python wrapper library for libmongocrypt that supports client side encryption
in drivers. PyMongoCrypt uses `cffi `_ and
`cryptography `_.
-PyMongoCrypt supports Python 3.8+ and PyPy3.9+.
+PyMongoCrypt supports Python 3.11+.
Support / Feedback
==================
@@ -157,7 +157,7 @@ for encryption and decryption::
Dependencies
============
-PyMongoCrypt supports Python 3.8+ and PyPy3.9+.
+PyMongoCrypt supports Python 3.11+.
PyMongoCrypt requires `cffi `_ and
`cryptography `_.
@@ -175,11 +175,11 @@ installed you will see an error like this:
from pymongocrypt.binding import libmongocrypt_version, lib
File "pymongocrypt/binding.py", line 803, in
lib = ffi.dlopen(os.environ.get('PYMONGOCRYPT_LIB', 'mongocrypt'))
- File "/.../lib/python3.8/site-packages/cffi/api.py", line 146, in dlopen
+ File "/.../lib/python3.11/site-packages/cffi/api.py", line 146, in dlopen
lib, function_cache = _make_ffi_library(self, name, flags)
- File "/.../lib/python3.8/site-packages/cffi/api.py", line 828, in _make_ffi_library
+ File "/.../lib/python3.11/site-packages/cffi/api.py", line 828, in _make_ffi_library
backendlib = _load_backend_lib(backend, libname, flags)
- File "/.../lib/python3.8/site-packages/cffi/api.py", line 823, in _load_backend_lib
+ File "/.../lib/python3.11/site-packages/cffi/api.py", line 823, in _load_backend_lib
raise OSError(msg)
OSError: ctypes.util.find_library() did not manage to locate a library called 'mongocrypt'
diff --git a/bindings/python/RELEASE.rst b/bindings/python/RELEASE.rst
index a49a0f6d8..6493f12c1 100644
--- a/bindings/python/RELEASE.rst
+++ b/bindings/python/RELEASE.rst
@@ -68,10 +68,10 @@ Manually Creating Wheels
$ git clone git@github.com:mongodb/libmongocrypt.git
$ cd libmongocrypt/bindings/python
$ git checkout "pymongocrypt "
- $ MACOS_TARGET=macos_x86_64 PYTHON= ./release.sh
- $ PYTHON= ./release.sh
+ $ MACOS_TARGET=macos_x86_64 PYTHON= ./release.sh
+ $ PYTHON= ./release.sh
- Make sure to run using the official binaries for Python 3.8 and 3.10. You
+ Make sure to run using the official binaries for Python 3.11. You
should end up with the same files created by Evergreen (except for the Windows wheel).
#. To build the release package for Windows, launch a windows-64-vsMulti-small
diff --git a/bindings/python/pymongocrypt/asynchronous/credentials.py b/bindings/python/pymongocrypt/asynchronous/credentials.py
index 2f81dc0d6..6f7ddd980 100644
--- a/bindings/python/pymongocrypt/asynchronous/credentials.py
+++ b/bindings/python/pymongocrypt/asynchronous/credentials.py
@@ -13,7 +13,7 @@
# limitations under the License.
import os
from collections import namedtuple
-from datetime import datetime, timedelta, timezone
+from datetime import UTC, datetime, timedelta
try:
from pymongo_auth_aws.auth import aws_temp_credentials
@@ -74,7 +74,7 @@ async def _get_azure_credentials():
# Credentials are considered expired when: Expiration - now < 1 mins.
creds = _azure_creds_cache
if creds:
- if creds.expires_utc - datetime.now(tz=timezone.utc) < timedelta(seconds=60):
+ if creds.expires_utc - datetime.now(tz=UTC) < timedelta(seconds=60):
_azure_creds_cache = None
else:
return {"accessToken": creds.access_token}
@@ -114,7 +114,7 @@ async def _get_azure_credentials():
% response.content
) from e
- expires_utc = datetime.now(tz=timezone.utc) + timedelta(seconds=expires_in)
+ expires_utc = datetime.now(tz=UTC) + timedelta(seconds=expires_in)
_azure_creds_cache = _azure_creds(data["access_token"], expires_utc)
return {"accessToken": data["access_token"]}
diff --git a/bindings/python/pymongocrypt/compat.py b/bindings/python/pymongocrypt/compat.py
index 032ab635d..b1ce5a226 100644
--- a/bindings/python/pymongocrypt/compat.py
+++ b/bindings/python/pymongocrypt/compat.py
@@ -14,19 +14,9 @@
"""Utility functions and definitions for Python compatibility."""
-import sys
+from abc import ABC # noqa: F401 # re-exported for pymongocrypt.*.state_machine
-PY3 = sys.version_info[0] >= 3
-
-if PY3:
- from abc import ABC
-
- unicode_type = str
-else:
- from abc import ABCMeta as _ABCMeta
-
- ABC = _ABCMeta("ABC", (object,), {})
- unicode_type = "unicode"
+unicode_type = str
def str_to_bytes(string):
diff --git a/bindings/python/pymongocrypt/mongocrypt.py b/bindings/python/pymongocrypt/mongocrypt.py
index a0e1da6cc..3f0b8704b 100644
--- a/bindings/python/pymongocrypt/mongocrypt.py
+++ b/bindings/python/pymongocrypt/mongocrypt.py
@@ -52,7 +52,7 @@ def __init__(self, options, callback):
if not isinstance(options, MongoCryptOptions):
raise TypeError("options must be a MongoCryptOptions")
- if not isinstance(callback, (AsyncMongoCryptCallback, MongoCryptCallback)):
+ if not isinstance(callback, AsyncMongoCryptCallback | MongoCryptCallback):
raise TypeError(
"callback must be a MongoCryptCallback or AsyncMongoCryptCallback"
)
diff --git a/bindings/python/pymongocrypt/options.py b/bindings/python/pymongocrypt/options.py
index b275d929a..a1d93d830 100644
--- a/bindings/python/pymongocrypt/options.py
+++ b/bindings/python/pymongocrypt/options.py
@@ -1,6 +1,3 @@
-from pymongocrypt.compat import unicode_type
-
-
class MongoCryptOptions:
def __init__(
self,
@@ -114,7 +111,7 @@ def __init__(
f"kms_providers[{name!r}] must contain "
"'email' and 'privateKey'"
)
- if not isinstance(provider["privateKey"], (bytes, unicode_type)):
+ if not isinstance(provider["privateKey"], bytes | str):
raise TypeError(
f"kms_providers[{name!r}]['privateKey'] must "
"be an instance of bytes or str"
@@ -122,7 +119,7 @@ def __init__(
elif provider_type == "kmip":
if "endpoint" not in provider:
raise ValueError(f"kms_providers[{name!r}] must contain 'endpoint'")
- if not isinstance(provider["endpoint"], (str, unicode_type)):
+ if not isinstance(provider["endpoint"], str):
raise TypeError(
f"kms_providers[{name!r}]['endpoint'] must "
"be an instance of str"
@@ -130,7 +127,7 @@ def __init__(
elif provider_type == "local":
if "key" not in provider:
raise ValueError(f"kms_providers[{name!r}] must contain 'key'")
- if not isinstance(provider["key"], (bytes, unicode_type)):
+ if not isinstance(provider["key"], bytes | str):
raise TypeError(
f"kms_providers[{name!r}]['key'] must be an "
"instance of bytes or str"
diff --git a/bindings/python/pymongocrypt/synchronous/credentials.py b/bindings/python/pymongocrypt/synchronous/credentials.py
index 9090dae8e..0f96fbd3b 100644
--- a/bindings/python/pymongocrypt/synchronous/credentials.py
+++ b/bindings/python/pymongocrypt/synchronous/credentials.py
@@ -13,7 +13,7 @@
# limitations under the License.
import os
from collections import namedtuple
-from datetime import datetime, timedelta, timezone
+from datetime import UTC, datetime, timedelta
try:
from pymongo_auth_aws.auth import aws_temp_credentials
@@ -74,7 +74,7 @@ def _get_azure_credentials():
# Credentials are considered expired when: Expiration - now < 1 mins.
creds = _azure_creds_cache
if creds:
- if creds.expires_utc - datetime.now(tz=timezone.utc) < timedelta(seconds=60):
+ if creds.expires_utc - datetime.now(tz=UTC) < timedelta(seconds=60):
_azure_creds_cache = None
else:
return {"accessToken": creds.access_token}
@@ -114,7 +114,7 @@ def _get_azure_credentials():
% response.content
) from e
- expires_utc = datetime.now(tz=timezone.utc) + timedelta(seconds=expires_in)
+ expires_utc = datetime.now(tz=UTC) + timedelta(seconds=expires_in)
_azure_creds_cache = _azure_creds(data["access_token"], expires_utc)
return {"accessToken": data["access_token"]}
diff --git a/bindings/python/pyproject.toml b/bindings/python/pyproject.toml
index 5859d13bf..b6c301c2a 100644
--- a/bindings/python/pyproject.toml
+++ b/bindings/python/pyproject.toml
@@ -8,7 +8,7 @@ dynamic = ["version", "dependencies", "optional-dependencies"]
description = "Python bindings for libmongocrypt"
readme = "README.rst"
license = {file="LICENSE"}
-requires-python = ">=3.9"
+requires-python = ">=3.11"
authors = [
{ name = "Shane Harvey", email = "mongodb-user@googlegroups.com" },
]
@@ -30,9 +30,6 @@ classifiers = [
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: Implementation :: CPython",
- "Programming Language :: Python :: Implementation :: PyPy",
- "Programming Language :: Python :: 3.9",
- "Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
diff --git a/bindings/python/scripts/update_binding.py b/bindings/python/scripts/update_binding.py
index 6f13a7651..8db41532c 100644
--- a/bindings/python/scripts/update_binding.py
+++ b/bindings/python/scripts/update_binding.py
@@ -16,24 +16,13 @@
"""
import re
+from itertools import pairwise
from pathlib import Path
DROP_RE = re.compile(r"^\s*(#|MONGOCRYPT_EXPORT)")
HERE = Path(__file__).absolute().parent
-# itertools.pairwise backport for Python 3.9 support.
-def pairwise(iterable):
- # pairwise('ABCDEFG') → AB BC CD DE EF FG
-
- iterator = iter(iterable)
- a = next(iterator, None)
-
- for b in iterator:
- yield a, b
- a = b
-
-
def strip_file(content):
fold = content.replace("\\\n", " ")
all_lines = [*fold.split("\n"), ""]
diff --git a/bindings/python/test/test_mongocrypt.py b/bindings/python/test/test_mongocrypt.py
index c8b8dc4c6..2c990b810 100644
--- a/bindings/python/test/test_mongocrypt.py
+++ b/bindings/python/test/test_mongocrypt.py
@@ -45,7 +45,7 @@
from pymongocrypt.asynchronous.explicit_encrypter import AsyncExplicitEncrypter
from pymongocrypt.asynchronous.state_machine import AsyncMongoCryptCallback
from pymongocrypt.binding import lib
-from pymongocrypt.compat import PY3, unicode_type
+from pymongocrypt.compat import unicode_type
from pymongocrypt.errors import MongoCryptError
from pymongocrypt.mongocrypt import MongoCrypt
from pymongocrypt.synchronous.auto_encrypter import AutoEncrypter
@@ -58,8 +58,6 @@
def to_base64(data):
b64 = base64.b64encode(data)
- if not PY3:
- return unicode_type(b64)
return b64.decode("utf-8")
@@ -634,469 +632,454 @@ def test_need_kms_gcp_credentials(self):
self.assertEqual(decrypted, bson_data("command-reply.json"))
-if sys.version_info >= (3, 8, 0): # noqa: UP036
-
- class TestAsyncMongoCryptCallback(unittest.IsolatedAsyncioTestCase):
- maxDiff = None
-
- @staticmethod
- def mongo_crypt_opts():
- return MongoCryptOptions(
- {
- "aws": {"accessKeyId": "example", "secretAccessKey": "example"},
- "local": {"key": b"\x00" * 96},
- }
- )
+class TestAsyncMongoCryptCallback(unittest.IsolatedAsyncioTestCase):
+ maxDiff = None
- @unittest.skipUnless(
- os.getenv("TEST_CRYPT_SHARED"), "this test requires TEST_CRYPT_SHARED=1"
- )
- async def test_crypt_shared(self):
- if sys.platform == "darwin":
- raise unittest.SkipTest("Skipping due to SERVER-101020")
- kms_providers = {
+ @staticmethod
+ def mongo_crypt_opts():
+ return MongoCryptOptions(
+ {
"aws": {"accessKeyId": "example", "secretAccessKey": "example"},
"local": {"key": b"\x00" * 96},
}
- mc = MongoCrypt(MongoCryptOptions(kms_providers), MockAsyncCallback())
- self.addCleanup(mc.close)
- self.assertIsNotNone(mc.crypt_shared_lib_version)
- # Test that we can pick up crypt_shared automatically
- encrypter = AsyncAutoEncrypter(
- MockAsyncCallback(),
- MongoCryptOptions(
- kms_providers,
- bypass_encryption=False,
- crypt_shared_lib_required=True,
- ),
- )
- self.addAsyncCleanup(encrypter.close)
- encrypter = AsyncAutoEncrypter(
+ )
+
+ @unittest.skipUnless(
+ os.getenv("TEST_CRYPT_SHARED"), "this test requires TEST_CRYPT_SHARED=1"
+ )
+ async def test_crypt_shared(self):
+ if sys.platform == "darwin":
+ raise unittest.SkipTest("Skipping due to SERVER-101020")
+ kms_providers = {
+ "aws": {"accessKeyId": "example", "secretAccessKey": "example"},
+ "local": {"key": b"\x00" * 96},
+ }
+ mc = MongoCrypt(MongoCryptOptions(kms_providers), MockAsyncCallback())
+ self.addCleanup(mc.close)
+ self.assertIsNotNone(mc.crypt_shared_lib_version)
+ # Test that we can pick up crypt_shared automatically
+ encrypter = AsyncAutoEncrypter(
+ MockAsyncCallback(),
+ MongoCryptOptions(
+ kms_providers,
+ bypass_encryption=False,
+ crypt_shared_lib_required=True,
+ ),
+ )
+ self.addAsyncCleanup(encrypter.close)
+ encrypter = AsyncAutoEncrypter(
+ MockAsyncCallback(),
+ MongoCryptOptions(
+ kms_providers,
+ crypt_shared_lib_path=os.environ["CRYPT_SHARED_PATH"],
+ crypt_shared_lib_required=True,
+ ),
+ )
+ self.addAsyncCleanup(encrypter.close)
+ with self.assertRaisesRegex(MongoCryptError, "/doesnotexist"):
+ AsyncAutoEncrypter(
MockAsyncCallback(),
MongoCryptOptions(
kms_providers,
- crypt_shared_lib_path=os.environ["CRYPT_SHARED_PATH"],
+ crypt_shared_lib_path="/doesnotexist",
crypt_shared_lib_required=True,
),
)
- self.addAsyncCleanup(encrypter.close)
- with self.assertRaisesRegex(MongoCryptError, "/doesnotexist"):
- AsyncAutoEncrypter(
- MockAsyncCallback(),
- MongoCryptOptions(
- kms_providers,
- crypt_shared_lib_path="/doesnotexist",
- crypt_shared_lib_required=True,
- ),
- )
- async def test_encrypt(self):
- encrypter = AsyncAutoEncrypter(
- MockAsyncCallback(
- list_colls_result=bson_data("collection-info.json"),
- mongocryptd_reply=bson_data("mongocryptd-reply.json"),
- key_docs=[bson_data("key-document.json")],
- kms_reply=http_data("kms-reply.txt"),
- ),
- self.mongo_crypt_opts(),
- )
- self.addAsyncCleanup(encrypter.close)
- encrypted = await encrypter.encrypt("test", bson_data("command.json"))
- self.assertEqual(
- bson.decode(encrypted, OPTS), json_data("encrypted-command.json")
+ async def test_encrypt(self):
+ encrypter = AsyncAutoEncrypter(
+ MockAsyncCallback(
+ list_colls_result=bson_data("collection-info.json"),
+ mongocryptd_reply=bson_data("mongocryptd-reply.json"),
+ key_docs=[bson_data("key-document.json")],
+ kms_reply=http_data("kms-reply.txt"),
+ ),
+ self.mongo_crypt_opts(),
+ )
+ self.addAsyncCleanup(encrypter.close)
+ encrypted = await encrypter.encrypt("test", bson_data("command.json"))
+ self.assertEqual(
+ bson.decode(encrypted, OPTS), json_data("encrypted-command.json")
+ )
+ self.assertEqual(encrypted, bson_data("encrypted-command.json"))
+
+ async def test_decrypt(self):
+ encrypter = AsyncAutoEncrypter(
+ MockAsyncCallback(
+ list_colls_result=bson_data("collection-info.json"),
+ mongocryptd_reply=bson_data("mongocryptd-reply.json"),
+ key_docs=[bson_data("key-document.json")],
+ kms_reply=http_data("kms-reply.txt"),
+ ),
+ self.mongo_crypt_opts(),
+ )
+ self.addAsyncCleanup(encrypter.close)
+ decrypted = await encrypter.decrypt(bson_data("encrypted-command-reply.json"))
+ self.assertEqual(bson.decode(decrypted, OPTS), json_data("command-reply.json"))
+ self.assertEqual(decrypted, bson_data("command-reply.json"))
+
+ async def test_need_kms_aws_credentials(self):
+ kms_providers = {"aws": {}}
+ opts = MongoCryptOptions(kms_providers)
+ callback = MockAsyncCallback(
+ list_colls_result=bson_data("collection-info.json"),
+ mongocryptd_reply=bson_data("mongocryptd-reply.json"),
+ key_docs=[bson_data("key-document.json")],
+ kms_reply=http_data("kms-reply.txt"),
+ )
+ encrypter = AsyncAutoEncrypter(callback, opts)
+ self.addAsyncCleanup(encrypter.close)
+
+ with unittest.mock.patch(
+ "pymongocrypt.asynchronous.credentials.aws_temp_credentials"
+ ) as m:
+ m.return_value = AwsCredential("example", "example", None)
+ decrypted = await encrypter.decrypt(
+ bson_data("encrypted-command-reply.json")
)
- self.assertEqual(encrypted, bson_data("encrypted-command.json"))
+ self.assertTrue(m.called)
- async def test_decrypt(self):
- encrypter = AsyncAutoEncrypter(
- MockAsyncCallback(
- list_colls_result=bson_data("collection-info.json"),
- mongocryptd_reply=bson_data("mongocryptd-reply.json"),
- key_docs=[bson_data("key-document.json")],
- kms_reply=http_data("kms-reply.txt"),
- ),
- self.mongo_crypt_opts(),
+ self.assertEqual(bson.decode(decrypted, OPTS), json_data("command-reply.json"))
+ self.assertEqual(decrypted, bson_data("command-reply.json"))
+
+ async def test_need_kms_gcp_credentials(self):
+ kms_providers = {"gcp": {}}
+ opts = MongoCryptOptions(kms_providers)
+ callback = MockAsyncCallback(
+ list_colls_result=bson_data("collection-info.json"),
+ mongocryptd_reply=bson_data("mongocryptd-reply.json"),
+ key_docs=[bson_data("key-document-gcp.json")],
+ kms_reply=http_data("kms-reply-gcp.txt"),
+ )
+ encrypter = AsyncAutoEncrypter(callback, opts)
+ self.addAsyncCleanup(encrypter.close)
+
+ with respx.mock(using="httpx") as router:
+ data = {"access_token": "foo"}
+ url = "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token"
+ router.add(
+ respx.get(url=url).mock(return_value=httpx.Response(200, json=data))
)
- self.addAsyncCleanup(encrypter.close)
decrypted = await encrypter.decrypt(
bson_data("encrypted-command-reply.json")
)
- self.assertEqual(
- bson.decode(decrypted, OPTS), json_data("command-reply.json")
- )
- self.assertEqual(decrypted, bson_data("command-reply.json"))
+ self.assertTrue(len(router.calls))
- async def test_need_kms_aws_credentials(self):
- kms_providers = {"aws": {}}
- opts = MongoCryptOptions(kms_providers)
- callback = MockAsyncCallback(
- list_colls_result=bson_data("collection-info.json"),
- mongocryptd_reply=bson_data("mongocryptd-reply.json"),
+ self.assertEqual(bson.decode(decrypted, OPTS), json_data("command-reply.json"))
+ self.assertEqual(decrypted, bson_data("command-reply.json"))
+
+
+class TestAsyncExplicitEncryption(unittest.IsolatedAsyncioTestCase):
+ maxDiff = None
+
+ @staticmethod
+ def mongo_crypt_opts():
+ return MongoCryptOptions(
+ {
+ "aws": {"accessKeyId": "example", "secretAccessKey": "example"},
+ "local": {"key": b"\x00" * 96},
+ }
+ )
+
+ async def _test_encrypt_decrypt(self, key_id=None, key_alt_name=None):
+ encrypter = AsyncExplicitEncrypter(
+ MockAsyncCallback(
key_docs=[bson_data("key-document.json")],
kms_reply=http_data("kms-reply.txt"),
- )
- encrypter = AsyncAutoEncrypter(callback, opts)
- self.addAsyncCleanup(encrypter.close)
-
- with unittest.mock.patch(
- "pymongocrypt.asynchronous.credentials.aws_temp_credentials"
- ) as m:
- m.return_value = AwsCredential("example", "example", None)
- decrypted = await encrypter.decrypt(
- bson_data("encrypted-command-reply.json")
- )
- self.assertTrue(m.called)
+ ),
+ self.mongo_crypt_opts(),
+ )
+ self.addCleanup(encrypter.close)
- self.assertEqual(
- bson.decode(decrypted, OPTS), json_data("command-reply.json")
- )
- self.assertEqual(decrypted, bson_data("command-reply.json"))
+ val = {"v": "hello"}
+ encoded_val = bson.encode(val)
+ algo = "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic"
+ encrypted = await encrypter.encrypt(
+ encoded_val, algo, key_id=key_id, key_alt_name=key_alt_name
+ )
+ self.assertEqual(
+ bson.decode(encrypted, OPTS), json_data("encrypted-value.json")
+ )
+ self.assertEqual(encrypted, bson_data("encrypted-value.json"))
- async def test_need_kms_gcp_credentials(self):
- kms_providers = {"gcp": {}}
- opts = MongoCryptOptions(kms_providers)
- callback = MockAsyncCallback(
- list_colls_result=bson_data("collection-info.json"),
- mongocryptd_reply=bson_data("mongocryptd-reply.json"),
- key_docs=[bson_data("key-document-gcp.json")],
- kms_reply=http_data("kms-reply-gcp.txt"),
- )
- encrypter = AsyncAutoEncrypter(callback, opts)
- self.addAsyncCleanup(encrypter.close)
-
- with respx.mock(using="httpx") as router:
- data = {"access_token": "foo"}
- url = "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token"
- router.add(
- respx.get(url=url).mock(return_value=httpx.Response(200, json=data))
- )
- decrypted = await encrypter.decrypt(
- bson_data("encrypted-command-reply.json")
- )
- self.assertTrue(len(router.calls))
+ decrypted = await encrypter.decrypt(encrypted)
+ self.assertEqual(bson.decode(decrypted, OPTS), val)
+ self.assertEqual(encoded_val, decrypted)
- self.assertEqual(
- bson.decode(decrypted, OPTS), json_data("command-reply.json")
- )
- self.assertEqual(decrypted, bson_data("command-reply.json"))
+ async def test_encrypt_decrypt(self):
+ key_id = json_data("key-document.json")["_id"]
+ await self._test_encrypt_decrypt(key_id=key_id)
- class TestAsyncExplicitEncryption(unittest.IsolatedAsyncioTestCase):
- maxDiff = None
+ async def test_encrypt_decrypt_key_alt_name(self):
+ key_alt_name = json_data("key-document.json")["keyAltNames"][0]
+ await self._test_encrypt_decrypt(key_alt_name=key_alt_name)
- @staticmethod
- def mongo_crypt_opts():
- return MongoCryptOptions(
- {
- "aws": {"accessKeyId": "example", "secretAccessKey": "example"},
- "local": {"key": b"\x00" * 96},
- }
- )
+ async def test_encrypt_errors(self):
+ key_id = json_data("key-document.json")["_id"]
+ encrypter = AsyncExplicitEncrypter(
+ MockAsyncCallback(key_docs=[]), self.mongo_crypt_opts()
+ )
+ self.addCleanup(encrypter.close)
- async def _test_encrypt_decrypt(self, key_id=None, key_alt_name=None):
- encrypter = AsyncExplicitEncrypter(
- MockAsyncCallback(
- key_docs=[bson_data("key-document.json")],
- kms_reply=http_data("kms-reply.txt"),
- ),
- self.mongo_crypt_opts(),
+ val = {"v": "value123"}
+ encoded_val = bson.encode(val)
+ # Invalid algorithm.
+ with self.assertRaisesRegex(MongoCryptError, "algorithm"):
+ await encrypter.encrypt(encoded_val, "Invalid", key_id)
+ # Invalid query_type type.
+ with self.assertRaisesRegex(TypeError, "query_type"):
+ await encrypter.encrypt(encoded_val, "Indexed", key_id, query_type=42)
+ # Invalid query_type string.
+ with self.assertRaisesRegex(MongoCryptError, "query_type"):
+ await encrypter.encrypt(
+ encoded_val,
+ "Indexed",
+ key_id,
+ query_type="invalid query type string",
)
- self.addCleanup(encrypter.close)
-
- val = {"v": "hello"}
- encoded_val = bson.encode(val)
- algo = "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic"
- encrypted = await encrypter.encrypt(
- encoded_val, algo, key_id=key_id, key_alt_name=key_alt_name
+ # Invalid contention_factor type.
+ with self.assertRaisesRegex(TypeError, "contention_factor"):
+ await encrypter.encrypt(
+ encoded_val, "Indexed", key_id, contention_factor="not an int"
)
- self.assertEqual(
- bson.decode(encrypted, OPTS), json_data("encrypted-value.json")
+ with self.assertRaisesRegex(MongoCryptError, "contention"):
+ await encrypter.encrypt(
+ encoded_val, "Indexed", key_id, contention_factor=-1
+ )
+ # Invalid: Unindexed + query_type is an error.
+ with self.assertRaisesRegex(MongoCryptError, "query"):
+ await encrypter.encrypt(
+ encoded_val, "Unindexed", key_id, query_type="equality"
+ )
+ # Invalid: Unindexed + contention_factor is an error.
+ with self.assertRaisesRegex(MongoCryptError, "contention"):
+ await encrypter.encrypt(
+ encoded_val, "Unindexed", key_id, contention_factor=1
)
- self.assertEqual(encrypted, bson_data("encrypted-value.json"))
- decrypted = await encrypter.decrypt(encrypted)
- self.assertEqual(bson.decode(decrypted, OPTS), val)
- self.assertEqual(encoded_val, decrypted)
+ async def test_encrypt_indexed(self):
+ key_path = "keys/ABCDEFAB123498761234123456789012-local-document.json"
+ key_id = json_data(key_path)["_id"]
+ encrypter = AsyncExplicitEncrypter(
+ MockAsyncCallback(
+ key_docs=[bson_data(key_path)], kms_reply=http_data("kms-reply.txt")
+ ),
+ self.mongo_crypt_opts(),
+ )
+ self.addCleanup(encrypter.close)
- async def test_encrypt_decrypt(self):
- key_id = json_data("key-document.json")["_id"]
- await self._test_encrypt_decrypt(key_id=key_id)
+ val = {"v": "value123"}
+ encoded_val = bson.encode(val)
+ for kwargs in [
+ dict(algorithm="Indexed", contention_factor=0),
+ dict(algorithm="Indexed", query_type="equality", contention_factor=0),
+ dict(algorithm="Indexed", contention_factor=100),
+ dict(algorithm="Unindexed"),
+ ]:
+ kwargs["key_id"] = key_id
+ encrypted = await encrypter.encrypt(encoded_val, **kwargs)
+ encrypted_val = bson.decode(encrypted, OPTS)["v"]
+ self.assertIsInstance(encrypted_val, Binary)
+ self.assertEqual(encrypted_val.subtype, 6)
- async def test_encrypt_decrypt_key_alt_name(self):
- key_alt_name = json_data("key-document.json")["keyAltNames"][0]
- await self._test_encrypt_decrypt(key_alt_name=key_alt_name)
+ # Queryable Encryption find payloads cannot be round-tripped.
+ if "query_type" not in kwargs:
+ decrypted = await encrypter.decrypt(encrypted)
+ self.assertEqual(bson.decode(decrypted, OPTS), val)
+ self.assertEqual(encoded_val, decrypted)
- async def test_encrypt_errors(self):
- key_id = json_data("key-document.json")["_id"]
- encrypter = AsyncExplicitEncrypter(
- MockAsyncCallback(key_docs=[]), self.mongo_crypt_opts()
+ async def test_data_key_creation(self):
+ mock_key_vault = AsyncKeyVaultCallback(
+ kms_reply=http_data("kms-encrypt-reply.txt")
+ )
+ opts = MongoCryptOptions(
+ {
+ "aws": {"accessKeyId": "example", "secretAccessKey": "example"},
+ "aws:named": {
+ "accessKeyId": "example",
+ "secretAccessKey": "example",
+ },
+ "local": {"key": b"\x00" * 96},
+ "local:named": {"key": b"\x01" * 96},
+ }
+ )
+ encrypter = AsyncExplicitEncrypter(mock_key_vault, opts)
+ self.addCleanup(encrypter.close)
+
+ valid_args = [
+ ("local", None, ["first", "second"]),
+ ("local:named", None, ["local:named"]),
+ ("aws", {"region": "region", "key": "cmk"}, ["third", "forth"]),
+ ("aws:named", {"region": "region", "key": "cmk"}, ["aws:named"]),
+ # Unicode region and key
+ ("aws", {"region": "region-unicode", "key": "cmk-unicode"}, []),
+ # Endpoint
+ (
+ "aws",
+ {
+ "region": "region",
+ "key": "cmk",
+ "endpoint": "kms.us-east-1.amazonaws.com:443",
+ },
+ [],
+ ),
+ ]
+ for kms_provider, master_key, key_alt_names in valid_args:
+ key_id = await encrypter.create_data_key(
+ kms_provider, master_key=master_key, key_alt_names=key_alt_names
)
- self.addCleanup(encrypter.close)
+ self.assertIsInstance(key_id, Binary)
+ self.assertEqual(key_id.subtype, 4)
+ data_key = bson.decode(mock_key_vault.data_key, OPTS)
+ # CDRIVER-3277 The order of key_alt_names is not maintained.
+ for name in key_alt_names:
+ self.assertIn(name, data_key["keyAltNames"])
- val = {"v": "value123"}
- encoded_val = bson.encode(val)
- # Invalid algorithm.
- with self.assertRaisesRegex(MongoCryptError, "algorithm"):
- await encrypter.encrypt(encoded_val, "Invalid", key_id)
- # Invalid query_type type.
- with self.assertRaisesRegex(TypeError, "query_type"):
- await encrypter.encrypt(encoded_val, "Indexed", key_id, query_type=42)
- # Invalid query_type string.
- with self.assertRaisesRegex(MongoCryptError, "query_type"):
- await encrypter.encrypt(
- encoded_val,
- "Indexed",
- key_id,
- query_type="invalid query type string",
- )
- # Invalid contention_factor type.
- with self.assertRaisesRegex(TypeError, "contention_factor"):
- await encrypter.encrypt(
- encoded_val, "Indexed", key_id, contention_factor="not an int"
- )
- with self.assertRaisesRegex(MongoCryptError, "contention"):
- await encrypter.encrypt(
- encoded_val, "Indexed", key_id, contention_factor=-1
- )
- # Invalid: Unindexed + query_type is an error.
- with self.assertRaisesRegex(MongoCryptError, "query"):
- await encrypter.encrypt(
- encoded_val, "Unindexed", key_id, query_type="equality"
- )
- # Invalid: Unindexed + contention_factor is an error.
- with self.assertRaisesRegex(MongoCryptError, "contention"):
- await encrypter.encrypt(
- encoded_val, "Unindexed", key_id, contention_factor=1
- )
+ # Assert that the custom endpoint is passed to libmongocrypt.
+ master_key = {"region": "region", "key": "key", "endpoint": "example.com"}
+ key_material = base64.b64decode(
+ "xPTAjBRG5JiPm+d3fj6XLi2q5DMXUS/f1f+SMAlhhwkhDRL0kr8r9GDLIGTAGlvC+HVjSIgdL+RKwZCvpXSyxTICWSXTUYsWYPyu3IoHbuBZdmw2faM3WhcRIgbMReU5"
+ )
+ await encrypter.create_data_key(
+ "aws", master_key=master_key, key_material=key_material
+ )
+ self.assertEqual("example.com:443", mock_key_vault.kms_endpoint)
- async def test_encrypt_indexed(self):
- key_path = "keys/ABCDEFAB123498761234123456789012-local-document.json"
- key_id = json_data(key_path)["_id"]
- encrypter = AsyncExplicitEncrypter(
- MockAsyncCallback(
- key_docs=[bson_data(key_path)], kms_reply=http_data("kms-reply.txt")
- ),
- self.mongo_crypt_opts(),
- )
- self.addCleanup(encrypter.close)
+ async def test_data_key_creation_bad_key_material(self):
+ mock_key_vault = AsyncKeyVaultCallback(
+ kms_reply=http_data("kms-encrypt-reply.txt")
+ )
+ encrypter = AsyncExplicitEncrypter(mock_key_vault, self.mongo_crypt_opts())
+ self.addCleanup(encrypter.close)
- val = {"v": "value123"}
- encoded_val = bson.encode(val)
- for kwargs in [
- dict(algorithm="Indexed", contention_factor=0),
- dict(algorithm="Indexed", query_type="equality", contention_factor=0),
- dict(algorithm="Indexed", contention_factor=100),
- dict(algorithm="Unindexed"),
- ]:
- kwargs["key_id"] = key_id
- encrypted = await encrypter.encrypt(encoded_val, **kwargs)
- encrypted_val = bson.decode(encrypted, OPTS)["v"]
- self.assertIsInstance(encrypted_val, Binary)
- self.assertEqual(encrypted_val.subtype, 6)
-
- # Queryable Encryption find payloads cannot be round-tripped.
- if "query_type" not in kwargs:
- decrypted = await encrypter.decrypt(encrypted)
- self.assertEqual(bson.decode(decrypted, OPTS), val)
- self.assertEqual(encoded_val, decrypted)
-
- async def test_data_key_creation(self):
- mock_key_vault = AsyncKeyVaultCallback(
- kms_reply=http_data("kms-encrypt-reply.txt")
- )
- opts = MongoCryptOptions(
- {
- "aws": {"accessKeyId": "example", "secretAccessKey": "example"},
- "aws:named": {
- "accessKeyId": "example",
- "secretAccessKey": "example",
- },
- "local": {"key": b"\x00" * 96},
- "local:named": {"key": b"\x01" * 96},
- }
- )
- encrypter = AsyncExplicitEncrypter(mock_key_vault, opts)
- self.addCleanup(encrypter.close)
+ key_material = Binary(b"0" * 97)
+ with self.assertRaisesRegex(
+ MongoCryptError, "keyMaterial should have length 96, but has length 97"
+ ):
+ await encrypter.create_data_key("local", key_material=key_material)
- valid_args = [
- ("local", None, ["first", "second"]),
- ("local:named", None, ["local:named"]),
- ("aws", {"region": "region", "key": "cmk"}, ["third", "forth"]),
- ("aws:named", {"region": "region", "key": "cmk"}, ["aws:named"]),
- # Unicode region and key
- ("aws", {"region": "region-unicode", "key": "cmk-unicode"}, []),
- # Endpoint
- (
- "aws",
- {
- "region": "region",
- "key": "cmk",
- "endpoint": "kms.us-east-1.amazonaws.com:443",
- },
- [],
- ),
- ]
- for kms_provider, master_key, key_alt_names in valid_args:
- key_id = await encrypter.create_data_key(
- kms_provider, master_key=master_key, key_alt_names=key_alt_names
- )
- self.assertIsInstance(key_id, Binary)
- self.assertEqual(key_id.subtype, 4)
- data_key = bson.decode(mock_key_vault.data_key, OPTS)
- # CDRIVER-3277 The order of key_alt_names is not maintained.
- for name in key_alt_names:
- self.assertIn(name, data_key["keyAltNames"])
-
- # Assert that the custom endpoint is passed to libmongocrypt.
- master_key = {"region": "region", "key": "key", "endpoint": "example.com"}
- key_material = base64.b64decode(
- "xPTAjBRG5JiPm+d3fj6XLi2q5DMXUS/f1f+SMAlhhwkhDRL0kr8r9GDLIGTAGlvC+HVjSIgdL+RKwZCvpXSyxTICWSXTUYsWYPyu3IoHbuBZdmw2faM3WhcRIgbMReU5"
- )
- if not PY3:
- key_material = Binary(key_material)
- await encrypter.create_data_key(
- "aws", master_key=master_key, key_material=key_material
- )
- self.assertEqual("example.com:443", mock_key_vault.kms_endpoint)
+ async def test_rewrap_many_data_key(self):
+ key_path = "keys/ABCDEFAB123498761234123456789012-local-document.json"
+ key_path2 = "keys/12345678123498761234123456789012-local-document.json"
+ encrypter = AsyncExplicitEncrypter(
+ MockAsyncCallback(key_docs=[bson_data(key_path), bson_data(key_path2)]),
+ self.mongo_crypt_opts(),
+ )
+ self.addCleanup(encrypter.close)
- async def test_data_key_creation_bad_key_material(self):
- mock_key_vault = AsyncKeyVaultCallback(
- kms_reply=http_data("kms-encrypt-reply.txt")
- )
- encrypter = AsyncExplicitEncrypter(mock_key_vault, self.mongo_crypt_opts())
- self.addCleanup(encrypter.close)
+ result = await encrypter.rewrap_many_data_key({})
+ raw_doc = RawBSONDocument(result)
+ assert len(raw_doc["v"]) == 2
- key_material = Binary(b"0" * 97)
- with self.assertRaisesRegex(
- MongoCryptError, "keyMaterial should have length 96, but has length 97"
- ):
- await encrypter.create_data_key("local", key_material=key_material)
+ async def test_range_query_int32(self):
+ key_path = "keys/ABCDEFAB123498761234123456789012-local-document.json"
+ key_id = json_data(key_path)["_id"]
+ encrypter = AsyncExplicitEncrypter(
+ MockAsyncCallback(
+ key_docs=[bson_data(key_path)], kms_reply=http_data("kms-reply.txt")
+ ),
+ self.mongo_crypt_opts(),
+ )
+ self.addCleanup(encrypter.close)
- async def test_rewrap_many_data_key(self):
- key_path = "keys/ABCDEFAB123498761234123456789012-local-document.json"
- key_path2 = "keys/12345678123498761234123456789012-local-document.json"
- encrypter = AsyncExplicitEncrypter(
- MockAsyncCallback(key_docs=[bson_data(key_path), bson_data(key_path2)]),
- self.mongo_crypt_opts(),
- )
- self.addCleanup(encrypter.close)
+ range_opts = bson_data("fle2-find-range-explicit-v2/int32/rangeopts.json")
+ value = bson_data("fle2-find-range-explicit-v2/int32/value-to-encrypt.json")
+ expected = json_data("fle2-find-range-explicit-v2/int32/encrypted-payload.json")
+ encrypted = await encrypter.encrypt(
+ value,
+ "range",
+ key_id=key_id,
+ query_type="range",
+ contention_factor=4,
+ range_opts=range_opts,
+ is_expression=True,
+ )
+ encrypted_val = bson.decode(encrypted, OPTS)
+ self.assertEqual(encrypted_val, adjust_range_counter(encrypted_val, expected))
- result = await encrypter.rewrap_many_data_key({})
- raw_doc = RawBSONDocument(result)
- assert len(raw_doc["v"]) == 2
+ async def test_text_query(self):
+ key_path = "keys/ABCDEFAB123498761234123456789012-local-document.json"
+ key_id = json_data(key_path)["_id"]
+ encrypter = AsyncExplicitEncrypter(
+ MockAsyncCallback(
+ key_docs=[bson_data(key_path)], kms_reply=http_data("kms-reply.txt")
+ ),
+ self.mongo_crypt_opts(),
+ )
+ self.addCleanup(encrypter.close)
- async def test_range_query_int32(self):
- key_path = "keys/ABCDEFAB123498761234123456789012-local-document.json"
- key_id = json_data(key_path)["_id"]
- encrypter = AsyncExplicitEncrypter(
- MockAsyncCallback(
- key_docs=[bson_data(key_path)], kms_reply=http_data("kms-reply.txt")
- ),
- self.mongo_crypt_opts(),
- )
- self.addCleanup(encrypter.close)
+ string_opts = bson_data("fle2-text-search/textopts.json")
+ expected = bson_data("fle2-text-search/encrypted-payload.json")
+ value = bson.encode({"v": "foo"})
+ encrypted = await encrypter.encrypt(
+ value,
+ "string",
+ key_id=key_id,
+ query_type="suffix",
+ contention_factor=0,
+ string_opts=string_opts,
+ )
+ self.assertEqual(encrypted, expected)
- range_opts = bson_data("fle2-find-range-explicit-v2/int32/rangeopts.json")
- value = bson_data("fle2-find-range-explicit-v2/int32/value-to-encrypt.json")
- expected = json_data(
- "fle2-find-range-explicit-v2/int32/encrypted-payload.json"
- )
- encrypted = await encrypter.encrypt(
- value,
- "range",
+ async def test_textPreview_query_fails(self):
+ key_path = "keys/ABCDEFAB123498761234123456789012-local-document.json"
+ key_id = json_data(key_path)["_id"]
+ encrypter = AsyncExplicitEncrypter(
+ MockAsyncCallback(
+ key_docs=[bson_data(key_path)],
+ kms_reply=http_data("kms-reply.txt"),
+ ),
+ self.mongo_crypt_opts(),
+ )
+ self.addCleanup(encrypter.close)
+
+ with self.assertRaisesRegex(
+ MongoCryptError,
+ "Algorithm 'textPreview' is deprecated, please use 'string'",
+ ):
+ await encrypter.encrypt(
+ bson.encode({"v": "foo"}),
+ "textPreview",
key_id=key_id,
- query_type="range",
- contention_factor=4,
- range_opts=range_opts,
- is_expression=True,
- )
- encrypted_val = bson.decode(encrypted, OPTS)
- self.assertEqual(
- encrypted_val, adjust_range_counter(encrypted_val, expected)
+ query_type="suffix",
+ contention_factor=0,
+ string_opts=bson_data("fle2-text-search/textopts.json"),
)
- async def test_text_query(self):
- key_path = "keys/ABCDEFAB123498761234123456789012-local-document.json"
- key_id = json_data(key_path)["_id"]
- encrypter = AsyncExplicitEncrypter(
- MockAsyncCallback(
- key_docs=[bson_data(key_path)], kms_reply=http_data("kms-reply.txt")
- ),
- self.mongo_crypt_opts(),
- )
- self.addCleanup(encrypter.close)
+ async def test_deprecated_preview_query_types(self):
+ # The "*Preview" query types error instead of aliasing to the GA
+ # names. MONGOCRYPT-938 drops them.
+ key_path = "keys/ABCDEFAB123498761234123456789012-local-document.json"
+ key_id = json_data(key_path)["_id"]
+ encrypter = AsyncExplicitEncrypter(
+ MockAsyncCallback(
+ key_docs=[bson_data(key_path)], kms_reply=http_data("kms-reply.txt")
+ ),
+ self.mongo_crypt_opts(),
+ )
+ self.addCleanup(encrypter.close)
- string_opts = bson_data("fle2-text-search/textopts.json")
- expected = bson_data("fle2-text-search/encrypted-payload.json")
- value = bson.encode({"v": "foo"})
- encrypted = await encrypter.encrypt(
+ string_opts = bson_data("fle2-text-search/textopts.json")
+ value = bson.encode({"v": "foo"})
+
+ async def encrypt(query_type):
+ return await encrypter.encrypt(
value,
"string",
key_id=key_id,
- query_type="suffix",
+ query_type=query_type,
contention_factor=0,
string_opts=string_opts,
)
- self.assertEqual(encrypted, expected)
- async def test_textPreview_query_fails(self):
- key_path = "keys/ABCDEFAB123498761234123456789012-local-document.json"
- key_id = json_data(key_path)["_id"]
- encrypter = AsyncExplicitEncrypter(
- MockAsyncCallback(
- key_docs=[bson_data(key_path)],
- kms_reply=http_data("kms-reply.txt"),
- ),
- self.mongo_crypt_opts(),
- )
- self.addCleanup(encrypter.close)
-
- with self.assertRaisesRegex(
- MongoCryptError,
- "Algorithm 'textPreview' is deprecated, please use 'string'",
- ):
- await encrypter.encrypt(
- bson.encode({"v": "foo"}),
- "textPreview",
- key_id=key_id,
- query_type="suffix",
- contention_factor=0,
- string_opts=bson_data("fle2-text-search/textopts.json"),
- )
-
- async def test_deprecated_preview_query_types(self):
- # The "*Preview" query types error instead of aliasing to the GA
- # names. MONGOCRYPT-938 drops them.
- key_path = "keys/ABCDEFAB123498761234123456789012-local-document.json"
- key_id = json_data(key_path)["_id"]
- encrypter = AsyncExplicitEncrypter(
- MockAsyncCallback(
- key_docs=[bson_data(key_path)], kms_reply=http_data("kms-reply.txt")
- ),
- self.mongo_crypt_opts(),
- )
- self.addCleanup(encrypter.close)
-
- string_opts = bson_data("fle2-text-search/textopts.json")
- value = bson.encode({"v": "foo"})
-
- async def encrypt(query_type):
- return await encrypter.encrypt(
- value,
- "string",
- key_id=key_id,
- query_type=query_type,
- contention_factor=0,
- string_opts=string_opts,
- )
-
- for query_type in ["prefix", "suffix", "substring"]:
- with self.subTest(query_type=query_type):
- # Expect error attempting to use '*Preview'.
- with self.assertRaisesRegex(
- MongoCryptError,
- f"Query type '{query_type}Preview' is deprecated, please use '{query_type}'",
- ):
- await encrypt(f"{query_type}Preview")
+ for query_type in ["prefix", "suffix", "substring"]:
+ with self.subTest(query_type=query_type):
+ # Expect error attempting to use '*Preview'.
+ with self.assertRaisesRegex(
+ MongoCryptError,
+ f"Query type '{query_type}Preview' is deprecated, please use '{query_type}'",
+ ):
+ await encrypt(f"{query_type}Preview")
class TestNeedKMSAzureCredentials(unittest.TestCase):
@@ -1455,8 +1438,6 @@ def test_data_key_creation(self):
key_material = base64.b64decode(
"xPTAjBRG5JiPm+d3fj6XLi2q5DMXUS/f1f+SMAlhhwkhDRL0kr8r9GDLIGTAGlvC+HVjSIgdL+RKwZCvpXSyxTICWSXTUYsWYPyu3IoHbuBZdmw2faM3WhcRIgbMReU5"
)
- if not PY3:
- key_material = Binary(key_material)
encrypter.create_data_key(
"aws", master_key=master_key, key_material=key_material
)