forked from mongodb/mongo-python-driver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_encryption.py
3204 lines (2791 loc) · 133 KB
/
test_encryption.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2019-present MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test client side encryption spec."""
from __future__ import annotations
import base64
import copy
import http.client
import json
import os
import pathlib
import re
import socket
import socketserver
import ssl
import sys
import textwrap
import traceback
import uuid
import warnings
from test.asynchronous import AsyncIntegrationTest, AsyncPyMongoTestCase, async_client_context
from test.asynchronous.test_bulk import AsyncBulkTestBase
from test.asynchronous.utils_spec_runner import AsyncSpecRunner, AsyncSpecTestCreator
from threading import Thread
from typing import Any, Dict, Mapping, Optional
import pytest
from pymongo.asynchronous.collection import AsyncCollection
from pymongo.asynchronous.helpers import anext
from pymongo.daemon import _spawn_daemon
try:
from pymongo.pyopenssl_context import IS_PYOPENSSL
except ImportError:
IS_PYOPENSSL = False
sys.path[0:0] = [""]
from test import (
unittest,
)
from test.asynchronous.test_bulk import AsyncBulkTestBase
from test.asynchronous.unified_format import generate_test_classes
from test.asynchronous.utils_spec_runner import AsyncSpecRunner
from test.helpers import (
AWS_CREDS,
AZURE_CREDS,
CA_PEM,
CLIENT_PEM,
GCP_CREDS,
KMIP_CREDS,
LOCAL_MASTER_KEY,
)
from test.utils_shared import (
AllowListEventListener,
OvertCommandListener,
TopologyEventListener,
async_wait_until,
camel_to_snake_args,
is_greenthread_patched,
)
from bson import DatetimeMS, Decimal128, encode, json_util
from bson.binary import UUID_SUBTYPE, Binary, UuidRepresentation
from bson.codec_options import CodecOptions
from bson.errors import BSONError
from bson.json_util import JSONOptions
from bson.son import SON
from pymongo import ReadPreference
from pymongo.asynchronous import encryption
from pymongo.asynchronous.encryption import Algorithm, AsyncClientEncryption, QueryType
from pymongo.asynchronous.mongo_client import AsyncMongoClient
from pymongo.cursor_shared import CursorType
from pymongo.encryption_options import _HAVE_PYMONGOCRYPT, AutoEncryptionOpts, RangeOpts
from pymongo.errors import (
AutoReconnect,
BulkWriteError,
ConfigurationError,
DuplicateKeyError,
EncryptedCollectionError,
EncryptionError,
InvalidOperation,
OperationFailure,
ServerSelectionTimeoutError,
WriteError,
)
from pymongo.operations import InsertOne, ReplaceOne, UpdateOne
from pymongo.write_concern import WriteConcern
_IS_SYNC = False
pytestmark = pytest.mark.encryption
KMS_PROVIDERS = {"local": {"key": b"\x00" * 96}}
def get_client_opts(client):
return client.options
class TestAutoEncryptionOpts(AsyncPyMongoTestCase):
@unittest.skipUnless(_HAVE_PYMONGOCRYPT, "pymongocrypt is not installed")
@unittest.skipUnless(os.environ.get("TEST_CRYPT_SHARED"), "crypt_shared lib is not installed")
async def test_crypt_shared(self):
# Test that we can pick up crypt_shared lib automatically
self.simple_client(
auto_encryption_opts=AutoEncryptionOpts(
KMS_PROVIDERS, "keyvault.datakeys", crypt_shared_lib_required=True
),
connect=False,
)
@unittest.skipIf(_HAVE_PYMONGOCRYPT, "pymongocrypt is installed")
def test_init_requires_pymongocrypt(self):
with self.assertRaises(ConfigurationError):
AutoEncryptionOpts({}, "keyvault.datakeys")
@unittest.skipUnless(_HAVE_PYMONGOCRYPT, "pymongocrypt is not installed")
def test_init(self):
opts = AutoEncryptionOpts({}, "keyvault.datakeys")
self.assertEqual(opts._kms_providers, {})
self.assertEqual(opts._key_vault_namespace, "keyvault.datakeys")
self.assertEqual(opts._key_vault_client, None)
self.assertEqual(opts._schema_map, None)
self.assertEqual(opts._bypass_auto_encryption, False)
self.assertEqual(opts._mongocryptd_uri, "mongodb://localhost:27020")
self.assertEqual(opts._mongocryptd_bypass_spawn, False)
self.assertEqual(opts._mongocryptd_spawn_path, "mongocryptd")
self.assertEqual(opts._mongocryptd_spawn_args, ["--idleShutdownTimeoutSecs=60"])
self.assertEqual(opts._kms_ssl_contexts, {})
@unittest.skipUnless(_HAVE_PYMONGOCRYPT, "pymongocrypt is not installed")
def test_init_spawn_args(self):
# User can override idleShutdownTimeoutSecs
opts = AutoEncryptionOpts(
{}, "keyvault.datakeys", mongocryptd_spawn_args=["--idleShutdownTimeoutSecs=88"]
)
self.assertEqual(opts._mongocryptd_spawn_args, ["--idleShutdownTimeoutSecs=88"])
# idleShutdownTimeoutSecs is added by default
opts = AutoEncryptionOpts({}, "keyvault.datakeys", mongocryptd_spawn_args=[])
self.assertEqual(opts._mongocryptd_spawn_args, ["--idleShutdownTimeoutSecs=60"])
# Also added when other options are given
opts = AutoEncryptionOpts(
{}, "keyvault.datakeys", mongocryptd_spawn_args=["--quiet", "--port=27020"]
)
self.assertEqual(
opts._mongocryptd_spawn_args,
["--quiet", "--port=27020", "--idleShutdownTimeoutSecs=60"],
)
@unittest.skipUnless(_HAVE_PYMONGOCRYPT, "pymongocrypt is not installed")
def test_init_kms_tls_options(self):
# Error cases:
with self.assertRaisesRegex(TypeError, r'kms_tls_options\["kmip"\] must be a dict'):
AutoEncryptionOpts({}, "k.d", kms_tls_options={"kmip": 1})
tls_opts: Any
for tls_opts in [
{"kmip": {"tls": True, "tlsInsecure": True}},
{"kmip": {"tls": True, "tlsAllowInvalidCertificates": True}},
{"kmip": {"tls": True, "tlsAllowInvalidHostnames": True}},
]:
with self.assertRaisesRegex(ConfigurationError, "Insecure TLS options prohibited"):
opts = AutoEncryptionOpts({}, "k.d", kms_tls_options=tls_opts)
with self.assertRaises(FileNotFoundError):
AutoEncryptionOpts({}, "k.d", kms_tls_options={"kmip": {"tlsCAFile": "does-not-exist"}})
# Success cases:
tls_opts: Any
for tls_opts in [None, {}]:
opts = AutoEncryptionOpts({}, "k.d", kms_tls_options=tls_opts)
self.assertEqual(opts._kms_ssl_contexts, {})
opts = AutoEncryptionOpts({}, "k.d", kms_tls_options={"kmip": {"tls": True}, "aws": {}})
ctx = opts._kms_ssl_contexts["kmip"]
self.assertEqual(ctx.check_hostname, True)
self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED)
ctx = opts._kms_ssl_contexts["aws"]
self.assertEqual(ctx.check_hostname, True)
self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED)
opts = AutoEncryptionOpts(
{},
"k.d",
kms_tls_options={"kmip": {"tlsCAFile": CA_PEM, "tlsCertificateKeyFile": CLIENT_PEM}},
)
ctx = opts._kms_ssl_contexts["kmip"]
self.assertEqual(ctx.check_hostname, True)
self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED)
class TestClientOptions(AsyncPyMongoTestCase):
async def test_default(self):
client = self.simple_client(connect=False)
self.assertEqual(get_client_opts(client).auto_encryption_opts, None)
client = self.simple_client(auto_encryption_opts=None, connect=False)
self.assertEqual(get_client_opts(client).auto_encryption_opts, None)
@unittest.skipUnless(_HAVE_PYMONGOCRYPT, "pymongocrypt is not installed")
async def test_kwargs(self):
opts = AutoEncryptionOpts(KMS_PROVIDERS, "keyvault.datakeys")
client = self.simple_client(auto_encryption_opts=opts, connect=False)
self.assertEqual(get_client_opts(client).auto_encryption_opts, opts)
class AsyncEncryptionIntegrationTest(AsyncIntegrationTest):
"""Base class for encryption integration tests."""
@unittest.skipUnless(_HAVE_PYMONGOCRYPT, "pymongocrypt is not installed")
@async_client_context.require_version_min(4, 2, -1)
async def asyncSetUp(self) -> None:
await super().asyncSetUp()
def assertEncrypted(self, val):
self.assertIsInstance(val, Binary)
self.assertEqual(val.subtype, 6)
def assertBinaryUUID(self, val):
self.assertIsInstance(val, Binary)
self.assertEqual(val.subtype, UUID_SUBTYPE)
def create_client_encryption(
self,
kms_providers: Mapping[str, Any],
key_vault_namespace: str,
key_vault_client: AsyncMongoClient,
codec_options: CodecOptions,
kms_tls_options: Optional[Mapping[str, Any]] = None,
):
client_encryption = AsyncClientEncryption(
kms_providers, key_vault_namespace, key_vault_client, codec_options, kms_tls_options
)
self.addAsyncCleanup(client_encryption.close)
return client_encryption
@classmethod
def unmanaged_create_client_encryption(
cls,
kms_providers: Mapping[str, Any],
key_vault_namespace: str,
key_vault_client: AsyncMongoClient,
codec_options: CodecOptions,
kms_tls_options: Optional[Mapping[str, Any]] = None,
):
client_encryption = AsyncClientEncryption(
kms_providers, key_vault_namespace, key_vault_client, codec_options, kms_tls_options
)
return client_encryption
# Location of JSON test files.
if _IS_SYNC:
BASE = os.path.join(pathlib.Path(__file__).resolve().parent, "client-side-encryption")
else:
BASE = os.path.join(pathlib.Path(__file__).resolve().parent.parent, "client-side-encryption")
SPEC_PATH = os.path.join(BASE, "spec")
OPTS = CodecOptions()
# Use SON to preserve the order of fields while parsing json. Use tz_aware
# =False to match how CodecOptions decodes dates.
JSON_OPTS = JSONOptions(document_class=SON, tz_aware=False)
def read(*paths):
with open(os.path.join(BASE, *paths)) as fp:
return fp.read()
def json_data(*paths):
return json_util.loads(read(*paths), json_options=JSON_OPTS)
def bson_data(*paths):
return encode(json_data(*paths), codec_options=OPTS)
class TestClientSimple(AsyncEncryptionIntegrationTest):
async def _test_auto_encrypt(self, opts):
client = await self.async_rs_or_single_client(auto_encryption_opts=opts)
# Create the encrypted field's data key.
key_vault = await create_key_vault(
self.client.keyvault.datakeys, json_data("custom", "key-document-local.json")
)
self.addAsyncCleanup(key_vault.drop)
# Collection.insert_one/insert_many auto encrypts.
docs = [
{"_id": 0, "ssn": "000"},
{"_id": 1, "ssn": "111"},
{"_id": 2, "ssn": "222"},
{"_id": 3, "ssn": "333"},
{"_id": 4, "ssn": "444"},
{"_id": 5, "ssn": "555"},
]
encrypted_coll = client.pymongo_test.test
await encrypted_coll.insert_one(docs[0])
await encrypted_coll.insert_many(docs[1:3])
unack = encrypted_coll.with_options(write_concern=WriteConcern(w=0))
await unack.insert_one(docs[3])
await unack.insert_many(docs[4:], ordered=False)
async def count_documents():
return await self.db.test.count_documents({}) == len(docs)
await async_wait_until(count_documents, "insert documents with w=0")
# Database.command auto decrypts.
res = await client.pymongo_test.command("find", "test", filter={"ssn": "000"})
decrypted_docs = res["cursor"]["firstBatch"]
self.assertEqual(decrypted_docs, [{"_id": 0, "ssn": "000"}])
# Collection.find auto decrypts.
decrypted_docs = await encrypted_coll.find().to_list()
self.assertEqual(decrypted_docs, docs)
# Collection.find auto decrypts getMores.
decrypted_docs = await encrypted_coll.find(batch_size=1).to_list()
self.assertEqual(decrypted_docs, docs)
# Collection.aggregate auto decrypts.
decrypted_docs = await (await encrypted_coll.aggregate([])).to_list()
self.assertEqual(decrypted_docs, docs)
# Collection.aggregate auto decrypts getMores.
decrypted_docs = await (await encrypted_coll.aggregate([], batchSize=1)).to_list()
self.assertEqual(decrypted_docs, docs)
# Collection.distinct auto decrypts.
decrypted_ssns = await encrypted_coll.distinct("ssn")
self.assertEqual(set(decrypted_ssns), {d["ssn"] for d in docs})
# Make sure the field is actually encrypted.
async for encrypted_doc in self.db.test.find():
self.assertIsInstance(encrypted_doc["_id"], int)
self.assertEncrypted(encrypted_doc["ssn"])
# Attempt to encrypt an unencodable object.
with self.assertRaises(BSONError):
await encrypted_coll.insert_one({"unencodeable": object()})
async def test_auto_encrypt(self):
# Configure the encrypted field via jsonSchema.
json_schema = json_data("custom", "schema.json")
await create_with_schema(self.db.test, json_schema)
self.addAsyncCleanup(self.db.test.drop)
opts = AutoEncryptionOpts(KMS_PROVIDERS, "keyvault.datakeys")
await self._test_auto_encrypt(opts)
async def test_auto_encrypt_local_schema_map(self):
# Configure the encrypted field via the local schema_map option.
schemas = {"pymongo_test.test": json_data("custom", "schema.json")}
opts = AutoEncryptionOpts(KMS_PROVIDERS, "keyvault.datakeys", schema_map=schemas)
await self._test_auto_encrypt(opts)
async def test_use_after_close(self):
opts = AutoEncryptionOpts(KMS_PROVIDERS, "keyvault.datakeys")
client = await self.async_rs_or_single_client(auto_encryption_opts=opts)
await client.admin.command("ping")
await client.aclose()
with self.assertRaisesRegex(InvalidOperation, "Cannot use AsyncMongoClient after close"):
await client.admin.command("ping")
@unittest.skipIf(
not hasattr(os, "register_at_fork"),
"register_at_fork not available in this version of Python",
)
@unittest.skipIf(
is_greenthread_patched(),
"gevent and eventlet do not support POSIX-style forking.",
)
@async_client_context.require_sync
async def test_fork(self):
self.skipTest("Test is flaky, PYTHON-4738")
opts = AutoEncryptionOpts(KMS_PROVIDERS, "keyvault.datakeys")
client = await self.async_rs_or_single_client(auto_encryption_opts=opts)
async def target():
with warnings.catch_warnings():
warnings.simplefilter("ignore")
await client.admin.command("ping")
with self.fork(target):
await target()
class TestEncryptedBulkWrite(AsyncBulkTestBase, AsyncEncryptionIntegrationTest):
async def test_upsert_uuid_standard_encrypt(self):
opts = AutoEncryptionOpts(KMS_PROVIDERS, "keyvault.datakeys")
client = await self.async_rs_or_single_client(auto_encryption_opts=opts)
options = CodecOptions(uuid_representation=UuidRepresentation.STANDARD)
encrypted_coll = client.pymongo_test.test
coll = encrypted_coll.with_options(codec_options=options)
uuids = [uuid.uuid4() for _ in range(3)]
result = await coll.bulk_write(
[
UpdateOne({"_id": uuids[0]}, {"$set": {"a": 0}}, upsert=True),
ReplaceOne({"a": 1}, {"_id": uuids[1]}, upsert=True),
# This is just here to make the counts right in all cases.
ReplaceOne({"_id": uuids[2]}, {"_id": uuids[2]}, upsert=True),
]
)
self.assertEqualResponse(
{
"nMatched": 0,
"nModified": 0,
"nUpserted": 3,
"nInserted": 0,
"nRemoved": 0,
"upserted": [
{"index": 0, "_id": uuids[0]},
{"index": 1, "_id": uuids[1]},
{"index": 2, "_id": uuids[2]},
],
},
result.bulk_api_result,
)
class TestClientMaxWireVersion(AsyncIntegrationTest):
@unittest.skipUnless(_HAVE_PYMONGOCRYPT, "pymongocrypt is not installed")
async def asyncSetUp(self):
await super().asyncSetUp()
@async_client_context.require_version_max(4, 0, 99)
async def test_raise_max_wire_version_error(self):
opts = AutoEncryptionOpts(KMS_PROVIDERS, "keyvault.datakeys")
client = await self.async_rs_or_single_client(auto_encryption_opts=opts)
msg = "Auto-encryption requires a minimum MongoDB version of 4.2"
with self.assertRaisesRegex(ConfigurationError, msg):
await client.test.test.insert_one({})
with self.assertRaisesRegex(ConfigurationError, msg):
await client.admin.command("ping")
with self.assertRaisesRegex(ConfigurationError, msg):
await client.test.test.find_one({})
with self.assertRaisesRegex(ConfigurationError, msg):
await client.test.test.bulk_write([InsertOne({})])
async def test_raise_unsupported_error(self):
opts = AutoEncryptionOpts(KMS_PROVIDERS, "keyvault.datakeys")
client = await self.async_rs_or_single_client(auto_encryption_opts=opts)
msg = "find_raw_batches does not support auto encryption"
with self.assertRaisesRegex(InvalidOperation, msg):
await client.test.test.find_raw_batches({})
msg = "aggregate_raw_batches does not support auto encryption"
with self.assertRaisesRegex(InvalidOperation, msg):
await client.test.test.aggregate_raw_batches([])
if async_client_context.is_mongos:
msg = "Exhaust cursors are not supported by mongos"
else:
msg = "exhaust cursors do not support auto encryption"
with self.assertRaisesRegex(InvalidOperation, msg):
await anext(client.test.test.find(cursor_type=CursorType.EXHAUST))
class TestExplicitSimple(AsyncEncryptionIntegrationTest):
async def test_encrypt_decrypt(self):
client_encryption = self.create_client_encryption(
KMS_PROVIDERS, "keyvault.datakeys", async_client_context.client, OPTS
)
# Use standard UUID representation.
key_vault = async_client_context.client.keyvault.get_collection(
"datakeys", codec_options=OPTS
)
self.addAsyncCleanup(key_vault.drop)
# Create the encrypted field's data key.
key_id = await client_encryption.create_data_key("local", key_alt_names=["name"])
self.assertBinaryUUID(key_id)
self.assertTrue(await key_vault.find_one({"_id": key_id}))
# Create an unused data key to make sure filtering works.
unused_key_id = await client_encryption.create_data_key("local", key_alt_names=["unused"])
self.assertBinaryUUID(unused_key_id)
self.assertTrue(await key_vault.find_one({"_id": unused_key_id}))
doc = {"_id": 0, "ssn": "000"}
encrypted_ssn = await client_encryption.encrypt(
doc["ssn"], Algorithm.AEAD_AES_256_CBC_HMAC_SHA_512_Deterministic, key_id=key_id
)
# Ensure encryption via key_alt_name for the same key produces the
# same output.
encrypted_ssn2 = await client_encryption.encrypt(
doc["ssn"], Algorithm.AEAD_AES_256_CBC_HMAC_SHA_512_Deterministic, key_alt_name="name"
)
self.assertEqual(encrypted_ssn, encrypted_ssn2)
# Test encryption via UUID
encrypted_ssn3 = await client_encryption.encrypt(
doc["ssn"],
Algorithm.AEAD_AES_256_CBC_HMAC_SHA_512_Deterministic,
key_id=key_id.as_uuid(),
)
self.assertEqual(encrypted_ssn, encrypted_ssn3)
# Test decryption.
decrypted_ssn = await client_encryption.decrypt(encrypted_ssn)
self.assertEqual(decrypted_ssn, doc["ssn"])
async def test_validation(self):
client_encryption = self.create_client_encryption(
KMS_PROVIDERS, "keyvault.datakeys", async_client_context.client, OPTS
)
msg = "value to decrypt must be a bson.binary.Binary with subtype 6"
with self.assertRaisesRegex(TypeError, msg):
await client_encryption.decrypt("str") # type: ignore[arg-type]
with self.assertRaisesRegex(TypeError, msg):
await client_encryption.decrypt(Binary(b"123"))
msg = "key_id must be a bson.binary.Binary with subtype 4"
algo = Algorithm.AEAD_AES_256_CBC_HMAC_SHA_512_Deterministic
with self.assertRaisesRegex(TypeError, msg):
await client_encryption.encrypt("str", algo, key_id=Binary(b"123"))
async def test_bson_errors(self):
client_encryption = self.create_client_encryption(
KMS_PROVIDERS, "keyvault.datakeys", async_client_context.client, OPTS
)
# Attempt to encrypt an unencodable object.
unencodable_value = object()
with self.assertRaises(BSONError):
await client_encryption.encrypt(
unencodable_value,
Algorithm.AEAD_AES_256_CBC_HMAC_SHA_512_Deterministic,
key_id=Binary.from_uuid(uuid.uuid4()),
)
async def test_codec_options(self):
with self.assertRaisesRegex(TypeError, "codec_options must be"):
self.create_client_encryption(
KMS_PROVIDERS,
"keyvault.datakeys",
async_client_context.client,
None, # type: ignore[arg-type]
)
opts = CodecOptions(uuid_representation=UuidRepresentation.JAVA_LEGACY)
client_encryption_legacy = self.create_client_encryption(
KMS_PROVIDERS, "keyvault.datakeys", async_client_context.client, opts
)
# Create the encrypted field's data key.
key_id = await client_encryption_legacy.create_data_key("local")
# Encrypt a UUID with JAVA_LEGACY codec options.
value = uuid.uuid4()
encrypted_legacy = await client_encryption_legacy.encrypt(
value, Algorithm.AEAD_AES_256_CBC_HMAC_SHA_512_Deterministic, key_id=key_id
)
decrypted_value_legacy = await client_encryption_legacy.decrypt(encrypted_legacy)
self.assertEqual(decrypted_value_legacy, value)
# Encrypt the same UUID with STANDARD codec options.
opts = CodecOptions(uuid_representation=UuidRepresentation.STANDARD)
client_encryption = self.create_client_encryption(
KMS_PROVIDERS, "keyvault.datakeys", async_client_context.client, opts
)
encrypted_standard = await client_encryption.encrypt(
value, Algorithm.AEAD_AES_256_CBC_HMAC_SHA_512_Deterministic, key_id=key_id
)
decrypted_standard = await client_encryption.decrypt(encrypted_standard)
self.assertEqual(decrypted_standard, value)
# Test that codec_options is applied during encryption.
self.assertNotEqual(encrypted_standard, encrypted_legacy)
# Test that codec_options is applied during decryption.
self.assertEqual(
await client_encryption_legacy.decrypt(encrypted_standard), Binary.from_uuid(value)
)
self.assertNotEqual(await client_encryption.decrypt(encrypted_legacy), value)
async def test_close(self):
client_encryption = self.create_client_encryption(
KMS_PROVIDERS, "keyvault.datakeys", async_client_context.client, OPTS
)
await client_encryption.close()
# Close can be called multiple times.
await client_encryption.close()
algo = Algorithm.AEAD_AES_256_CBC_HMAC_SHA_512_Deterministic
msg = "Cannot use closed AsyncClientEncryption"
with self.assertRaisesRegex(InvalidOperation, msg):
await client_encryption.create_data_key("local")
with self.assertRaisesRegex(InvalidOperation, msg):
await client_encryption.encrypt("val", algo, key_alt_name="name")
with self.assertRaisesRegex(InvalidOperation, msg):
await client_encryption.decrypt(Binary(b"", 6))
async def test_with_statement(self):
async with self.create_client_encryption(
KMS_PROVIDERS, "keyvault.datakeys", async_client_context.client, OPTS
) as client_encryption:
pass
with self.assertRaisesRegex(InvalidOperation, "Cannot use closed AsyncClientEncryption"):
await client_encryption.create_data_key("local")
# Spec tests
AWS_TEMP_CREDS = {
"accessKeyId": os.environ.get("CSFLE_AWS_TEMP_ACCESS_KEY_ID", ""),
"secretAccessKey": os.environ.get("CSFLE_AWS_TEMP_SECRET_ACCESS_KEY", ""),
"sessionToken": os.environ.get("CSFLE_AWS_TEMP_SESSION_TOKEN", ""),
}
AWS_TEMP_NO_SESSION_CREDS = {
"accessKeyId": os.environ.get("CSFLE_AWS_TEMP_ACCESS_KEY_ID", ""),
"secretAccessKey": os.environ.get("CSFLE_AWS_TEMP_SECRET_ACCESS_KEY", ""),
}
KMS_TLS_OPTS = {"kmip": {"tlsCAFile": CA_PEM, "tlsCertificateKeyFile": CLIENT_PEM}}
class AsyncTestSpec(AsyncSpecRunner):
@classmethod
@unittest.skipUnless(_HAVE_PYMONGOCRYPT, "pymongocrypt is not installed")
async def _setup_class(cls):
await super()._setup_class()
def parse_auto_encrypt_opts(self, opts):
"""Parse clientOptions.autoEncryptOpts."""
opts = camel_to_snake_args(opts)
kms_providers = opts["kms_providers"]
if "aws" in kms_providers:
kms_providers["aws"] = AWS_CREDS
if not any(AWS_CREDS.values()):
self.skipTest("AWS environment credentials are not set")
if "awsTemporary" in kms_providers:
kms_providers["aws"] = AWS_TEMP_CREDS
del kms_providers["awsTemporary"]
if not any(AWS_TEMP_CREDS.values()):
self.skipTest("AWS Temp environment credentials are not set")
if "awsTemporaryNoSessionToken" in kms_providers:
kms_providers["aws"] = AWS_TEMP_NO_SESSION_CREDS
del kms_providers["awsTemporaryNoSessionToken"]
if not any(AWS_TEMP_NO_SESSION_CREDS.values()):
self.skipTest("AWS Temp environment credentials are not set")
if "azure" in kms_providers:
kms_providers["azure"] = AZURE_CREDS
if not any(AZURE_CREDS.values()):
self.skipTest("Azure environment credentials are not set")
if "gcp" in kms_providers:
kms_providers["gcp"] = GCP_CREDS
if not any(AZURE_CREDS.values()):
self.skipTest("GCP environment credentials are not set")
if "kmip" in kms_providers:
kms_providers["kmip"] = KMIP_CREDS
opts["kms_tls_options"] = KMS_TLS_OPTS
if "key_vault_namespace" not in opts:
opts["key_vault_namespace"] = "keyvault.datakeys"
if "extra_options" in opts:
opts.update(camel_to_snake_args(opts.pop("extra_options")))
opts = dict(opts)
return AutoEncryptionOpts(**opts)
def parse_client_options(self, opts):
"""Override clientOptions parsing to support autoEncryptOpts."""
encrypt_opts = opts.pop("autoEncryptOpts", None)
if encrypt_opts:
opts["auto_encryption_opts"] = self.parse_auto_encrypt_opts(encrypt_opts)
return super().parse_client_options(opts)
def get_object_name(self, op):
"""Default object is collection."""
return op.get("object", "collection")
def maybe_skip_scenario(self, test):
super().maybe_skip_scenario(test)
desc = test["description"].lower()
if (
"timeoutms applied to listcollections to get collection schema" in desc
and sys.platform in ("win32", "darwin")
):
self.skipTest("PYTHON-3706 flaky test on Windows/macOS")
if "type=symbol" in desc:
self.skipTest("PyMongo does not support the symbol type")
if "timeoutms applied to listcollections to get collection schema" in desc and not _IS_SYNC:
self.skipTest("PYTHON-4844 flaky test on async")
async def setup_scenario(self, scenario_def):
"""Override a test's setup."""
key_vault_data = scenario_def["key_vault_data"]
encrypted_fields = scenario_def["encrypted_fields"]
json_schema = scenario_def["json_schema"]
data = scenario_def["data"]
coll = async_client_context.client.get_database("keyvault", codec_options=OPTS)["datakeys"]
await coll.delete_many({})
if key_vault_data:
await coll.insert_many(key_vault_data)
db_name = self.get_scenario_db_name(scenario_def)
coll_name = self.get_scenario_coll_name(scenario_def)
db = async_client_context.client.get_database(db_name, codec_options=OPTS)
await db.drop_collection(coll_name, encrypted_fields=encrypted_fields)
wc = WriteConcern(w="majority")
kwargs: Dict[str, Any] = {}
if json_schema:
kwargs["validator"] = {"$jsonSchema": json_schema}
kwargs["codec_options"] = OPTS
if not data:
kwargs["write_concern"] = wc
if encrypted_fields:
kwargs["encryptedFields"] = encrypted_fields
await db.create_collection(coll_name, **kwargs)
coll = db[coll_name]
if data:
# Load data.
await coll.with_options(write_concern=wc).insert_many(scenario_def["data"])
def allowable_errors(self, op):
"""Override expected error classes."""
errors = super().allowable_errors(op)
# An updateOne test expects encryption to error when no $ operator
# appears but pymongo raises a client side ValueError in this case.
if op["name"] == "updateOne":
errors += (ValueError,)
return errors
def create_test(scenario_def, test, name):
@async_client_context.require_test_commands
async def run_scenario(self):
await self.run_scenario(scenario_def, test)
return run_scenario
test_creator = AsyncSpecTestCreator(create_test, AsyncTestSpec, os.path.join(SPEC_PATH, "legacy"))
test_creator.create_tests()
if _HAVE_PYMONGOCRYPT:
globals().update(
generate_test_classes(
os.path.join(SPEC_PATH, "unified"),
module=__name__,
)
)
# Prose Tests
ALL_KMS_PROVIDERS = {
"aws": AWS_CREDS,
"azure": AZURE_CREDS,
"gcp": GCP_CREDS,
"kmip": KMIP_CREDS,
"local": {"key": LOCAL_MASTER_KEY},
}
LOCAL_KEY_ID = Binary(base64.b64decode(b"LOCALAAAAAAAAAAAAAAAAA=="), UUID_SUBTYPE)
AWS_KEY_ID = Binary(base64.b64decode(b"AWSAAAAAAAAAAAAAAAAAAA=="), UUID_SUBTYPE)
AZURE_KEY_ID = Binary(base64.b64decode(b"AZUREAAAAAAAAAAAAAAAAA=="), UUID_SUBTYPE)
GCP_KEY_ID = Binary(base64.b64decode(b"GCPAAAAAAAAAAAAAAAAAAA=="), UUID_SUBTYPE)
KMIP_KEY_ID = Binary(base64.b64decode(b"KMIPAAAAAAAAAAAAAAAAAA=="), UUID_SUBTYPE)
async def create_with_schema(coll, json_schema):
"""Create and return a Collection with a jsonSchema."""
await coll.with_options(write_concern=WriteConcern(w="majority")).drop()
return await coll.database.create_collection(
coll.name, validator={"$jsonSchema": json_schema}, codec_options=OPTS
)
async def create_key_vault(vault, *data_keys):
"""Create the key vault collection with optional data keys."""
vault = vault.with_options(write_concern=WriteConcern(w="majority"), codec_options=OPTS)
await vault.drop()
if data_keys:
await vault.insert_many(data_keys)
await vault.create_index(
"keyAltNames",
unique=True,
partialFilterExpression={"keyAltNames": {"$exists": True}},
)
return vault
class TestDataKeyDoubleEncryption(AsyncEncryptionIntegrationTest):
client_encrypted: AsyncMongoClient
client_encryption: AsyncClientEncryption
listener: OvertCommandListener
vault: Any
KMS_PROVIDERS = ALL_KMS_PROVIDERS
MASTER_KEYS = {
"aws": {
"region": "us-east-1",
"key": "arn:aws:kms:us-east-1:579766882180:key/89fcc2c4-08b0-4bd9-9f25-e30687b580d0",
},
"azure": {
"keyVaultEndpoint": "key-vault-csfle.vault.azure.net",
"keyName": "key-name-csfle",
},
"gcp": {
"projectId": "devprod-drivers",
"location": "global",
"keyRing": "key-ring-csfle",
"keyName": "key-name-csfle",
},
"kmip": {},
"local": None,
}
@unittest.skipUnless(
any([all(AWS_CREDS.values()), all(AZURE_CREDS.values()), all(GCP_CREDS.values())]),
"No environment credentials are set",
)
async def asyncSetUp(self):
await super().asyncSetUp()
self.listener = OvertCommandListener()
self.client = await self.async_rs_or_single_client(event_listeners=[self.listener])
await self.client.db.coll.drop()
self.vault = await create_key_vault(self.client.keyvault.datakeys)
# Configure the encrypted field via the local schema_map option.
schemas = {
"db.coll": {
"bsonType": "object",
"properties": {
"encrypted_placeholder": {
"encrypt": {
"keyId": "/placeholder",
"bsonType": "string",
"algorithm": "AEAD_AES_256_CBC_HMAC_SHA_512-Random",
}
}
},
}
}
opts = AutoEncryptionOpts(
self.KMS_PROVIDERS,
"keyvault.datakeys",
schema_map=schemas,
kms_tls_options=KMS_TLS_OPTS,
)
self.client_encrypted = await self.async_rs_or_single_client(
auto_encryption_opts=opts, uuidRepresentation="standard"
)
self.client_encryption = self.create_client_encryption(
self.KMS_PROVIDERS, "keyvault.datakeys", self.client, OPTS, kms_tls_options=KMS_TLS_OPTS
)
self.listener.reset()
async def asyncTearDown(self) -> None:
await self.vault.drop()
async def run_test(self, provider_name):
# Create data key.
master_key: Any = self.MASTER_KEYS[provider_name]
datakey_id = await self.client_encryption.create_data_key(
provider_name, master_key=master_key, key_alt_names=[f"{provider_name}_altname"]
)
self.assertBinaryUUID(datakey_id)
cmd = self.listener.started_events[-1]
self.assertEqual("insert", cmd.command_name)
self.assertEqual({"w": "majority"}, cmd.command.get("writeConcern"))
docs = await self.vault.find({"_id": datakey_id}).to_list()
self.assertEqual(len(docs), 1)
self.assertEqual(docs[0]["masterKey"]["provider"], provider_name)
# Encrypt by key_id.
encrypted = await self.client_encryption.encrypt(
f"hello {provider_name}",
Algorithm.AEAD_AES_256_CBC_HMAC_SHA_512_Deterministic,
key_id=datakey_id,
)
self.assertEncrypted(encrypted)
await self.client_encrypted.db.coll.insert_one({"_id": provider_name, "value": encrypted})
doc_decrypted = await self.client_encrypted.db.coll.find_one({"_id": provider_name})
self.assertEqual(doc_decrypted["value"], f"hello {provider_name}") # type: ignore
# Encrypt by key_alt_name.
encrypted_altname = await self.client_encryption.encrypt(
f"hello {provider_name}",
Algorithm.AEAD_AES_256_CBC_HMAC_SHA_512_Deterministic,
key_alt_name=f"{provider_name}_altname",
)
self.assertEqual(encrypted_altname, encrypted)
# Explicitly encrypting an auto encrypted field.
with self.assertRaisesRegex(EncryptionError, r"encrypt element of type"):
await self.client_encrypted.db.coll.insert_one({"encrypted_placeholder": encrypted})
async def test_data_key_local(self):
await self.run_test("local")
@unittest.skipUnless(any(AWS_CREDS.values()), "AWS environment credentials are not set")
async def test_data_key_aws(self):
await self.run_test("aws")
@unittest.skipUnless(any(AZURE_CREDS.values()), "Azure environment credentials are not set")
async def test_data_key_azure(self):
await self.run_test("azure")
@unittest.skipUnless(any(GCP_CREDS.values()), "GCP environment credentials are not set")
async def test_data_key_gcp(self):
await self.run_test("gcp")
async def test_data_key_kmip(self):
await self.run_test("kmip")
class TestExternalKeyVault(AsyncEncryptionIntegrationTest):
@staticmethod
def kms_providers():
return {"local": {"key": LOCAL_MASTER_KEY}}
async def _test_external_key_vault(self, with_external_key_vault):
await self.client.db.coll.drop()
vault = await create_key_vault(
self.client.keyvault.datakeys,
json_data("corpus", "corpus-key-local.json"),
json_data("corpus", "corpus-key-aws.json"),
)
self.addAsyncCleanup(vault.drop)
# Configure the encrypted field via the local schema_map option.
schemas = {"db.coll": json_data("external", "external-schema.json")}
if with_external_key_vault:
key_vault_client = await self.async_rs_or_single_client(
username="fake-user", password="fake-pwd"
)
else:
key_vault_client = async_client_context.client
opts = AutoEncryptionOpts(
self.kms_providers(),
"keyvault.datakeys",
schema_map=schemas,
key_vault_client=key_vault_client,
)
client_encrypted = await self.async_rs_or_single_client(
auto_encryption_opts=opts, uuidRepresentation="standard"
)
client_encryption = self.create_client_encryption(
self.kms_providers(), "keyvault.datakeys", key_vault_client, OPTS
)
if with_external_key_vault:
# Authentication error.
with self.assertRaises(EncryptionError) as ctx:
await client_encrypted.db.coll.insert_one({"encrypted": "test"})
# AuthenticationFailed error.
self.assertIsInstance(ctx.exception.cause, OperationFailure)
self.assertEqual(ctx.exception.cause.code, 18)
else:
await client_encrypted.db.coll.insert_one({"encrypted": "test"})
if with_external_key_vault:
# Authentication error.
with self.assertRaises(EncryptionError) as ctx:
await client_encryption.encrypt(
"test",
Algorithm.AEAD_AES_256_CBC_HMAC_SHA_512_Deterministic,
key_id=LOCAL_KEY_ID,
)
# AuthenticationFailed error.
self.assertIsInstance(ctx.exception.cause, OperationFailure)
self.assertEqual(ctx.exception.cause.code, 18)
else:
await client_encryption.encrypt(
"test", Algorithm.AEAD_AES_256_CBC_HMAC_SHA_512_Deterministic, key_id=LOCAL_KEY_ID
)
async def test_external_key_vault_1(self):
await self._test_external_key_vault(True)
async def test_external_key_vault_2(self):
await self._test_external_key_vault(False)
class TestViews(AsyncEncryptionIntegrationTest):
@staticmethod
def kms_providers():
return {"local": {"key": LOCAL_MASTER_KEY}}
async def test_views_are_prohibited(self):