forked from mongodb/libmongocrypt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_mongocrypt.py
More file actions
1538 lines (1346 loc) · 61.1 KB
/
Copy pathtest_mongocrypt.py
File metadata and controls
1538 lines (1346 loc) · 61.1 KB
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 the mongocrypt module."""
import base64
import copy
import os
import sys
import bson
import httpx
from bson import json_util
from bson.binary import Binary, UuidRepresentation
from bson.codec_options import CodecOptions
from bson.json_util import JSONOptions
from bson.raw_bson import RawBSONDocument
from bson.son import SON
import pymongocrypt.mongocrypt
from pymongocrypt.binary import MongoCryptBinaryIn, MongoCryptBinaryOut
from pymongocrypt.options import MongoCryptOptions
sys.path[0:0] = [""]
import unittest
import unittest.mock
import respx
from pymongo import MongoClient
from pymongo_auth_aws.auth import AwsCredential
from pymongocrypt.asynchronous.auto_encrypter import AsyncAutoEncrypter
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.errors import MongoCryptError
from pymongocrypt.mongocrypt import MongoCrypt
from pymongocrypt.synchronous.auto_encrypter import AutoEncrypter
from pymongocrypt.synchronous.explicit_encrypter import ExplicitEncrypter
from pymongocrypt.synchronous.state_machine import MongoCryptCallback
# Data for testing libbmongocrypt binding.
DATA_DIR = os.path.realpath(os.path.join(os.path.dirname(__file__), "data"))
def to_base64(data):
b64 = base64.b64encode(data)
if not PY3:
return unicode_type(b64)
return b64.decode("utf-8")
class TestMongoCryptBinary(unittest.TestCase):
def test_mongocrypt_binary_in(self):
with MongoCryptBinaryIn(b"1\x0023") as binary:
self.assertIsNotNone(binary.bin)
self.assertEqual(binary.to_bytes(), b"1\x0023")
self.assertIsNone(binary.bin)
with MongoCryptBinaryIn(b"") as binary:
self.assertIsNotNone(binary.bin)
self.assertEqual(binary.to_bytes(), b"")
self.assertIsNone(binary.bin)
# Memoryview
with MongoCryptBinaryIn(memoryview(b"1\x0023")) as binary:
self.assertIsNotNone(binary.bin)
self.assertEqual(binary.to_bytes(), b"1\x0023")
self.assertIsNone(binary.bin)
def test_mongocrypt_binary_out(self):
with MongoCryptBinaryOut() as binary:
self.assertIsNotNone(binary.bin)
self.assertEqual(binary.to_bytes(), b"")
self.assertIsNone(binary.bin)
class TestMongoCryptOptions(unittest.TestCase):
def test_mongocrypt_options(self):
schema_map = bson_data("schema-map.json")
valid = [
({"local": {"key": b"1" * 96}}, None),
({"aws": {}}, schema_map),
({"aws": {"accessKeyId": "", "secretAccessKey": ""}}, schema_map),
({"aws": {"accessKeyId": "foo", "secretAccessKey": "foo"}}, None),
(
{
"aws": {
"accessKeyId": "foo",
"secretAccessKey": "foo",
"sessionToken": "token",
}
},
None,
),
(
{
"aws": {"accessKeyId": "foo", "secretAccessKey": "foo"},
"local": {"key": b"1" * 96},
},
None,
),
({"local": {"key": to_base64(b"1" * 96)}}, None),
({"local": {"key": Binary(b"1" * 96)}}, None),
({"azure": {}}, None),
({"azure": {"clientId": "foo", "clientSecret": "bar"}}, None),
({"gcp": {}}, None),
({"gcp": {"email": "foo@bar.baz", "privateKey": b"1"}}, None),
({"gcp": {"email": "foo@bar.baz", "privateKey": to_base64(b"1")}}, None),
({"gcp": {"email": "foo@bar.baz", "privateKey": Binary(b"1")}}, None),
({"kmip": {"endpoint": "localhost"}}, None),
]
# Add tests for named KMS providers.
for kms_providers, schema_map in valid:
for name, val in list(kms_providers.items()):
kms_providers[f"{name}:named"] = val
for kms_providers, schema_map in valid:
opts = MongoCryptOptions(kms_providers, schema_map)
self.assertEqual(opts.kms_providers, kms_providers, msg=kms_providers)
self.assertEqual(opts.schema_map, schema_map)
self.assertIsNone(opts.encrypted_fields_map)
self.assertFalse(opts.bypass_query_analysis)
encrypted_fields_map = bson_data("encrypted-field-config-map.json")
opts = MongoCryptOptions(
valid[0][0],
schema_map,
encrypted_fields_map=encrypted_fields_map,
bypass_query_analysis=True,
)
self.assertEqual(opts.encrypted_fields_map, encrypted_fields_map)
self.assertTrue(opts.bypass_query_analysis)
for expiration in [0, 1, 1000000]:
opts = MongoCryptOptions(
valid[0][0], schema_map, key_expiration_ms=expiration
)
self.assertEqual(opts.key_expiration_ms, expiration)
def test_mongocrypt_options_validation(self):
with self.assertRaisesRegex(
ValueError, "at least one KMS provider must be configured"
):
MongoCryptOptions({})
for invalid_kms_providers in [
{"aws": {"accessKeyId": "foo"}},
{"aws": {"secretAccessKey": "foo"}},
{"aws:foo": {"accessKeyId": "foo"}},
{"aws:foo": {"secretAccessKey": "foo"}},
]:
name = next(iter(invalid_kms_providers))
with self.assertRaisesRegex(
ValueError,
rf"kms_providers\[{name!r}\] must contain "
"'accessKeyId' and 'secretAccessKey'",
):
MongoCryptOptions(invalid_kms_providers)
with self.assertRaisesRegex(
TypeError,
r"kms_providers\['local'\]\['key'\] must be an "
r"instance of bytes or str",
):
MongoCryptOptions({"local": {"key": None}})
with self.assertRaisesRegex(
TypeError,
r"kms_providers\['gcp'\]\['privateKey'\] must be an "
r"instance of bytes or str",
):
MongoCryptOptions({"gcp": {"email": "foo@bar.baz", "privateKey": None}})
with self.assertRaisesRegex(
ValueError, r"kms_providers\['kmip'\] must contain 'endpoint'"
):
MongoCryptOptions({"kmip": {}})
with self.assertRaisesRegex(
TypeError,
r"kms_providers\['kmip'\]\['endpoint'\] must be an instance of str",
):
MongoCryptOptions({"kmip": {"endpoint": None}})
valid_kms = {"aws": {"accessKeyId": "", "secretAccessKey": ""}}
with self.assertRaisesRegex(TypeError, "schema_map must be bytes or None"):
MongoCryptOptions(valid_kms, schema_map={})
with self.assertRaisesRegex(
TypeError, "encrypted_fields_map must be bytes or None"
):
MongoCryptOptions(valid_kms, encrypted_fields_map={})
with self.assertRaisesRegex(TypeError, "key_expiration_ms must be int or None"):
MongoCryptOptions(valid_kms, key_expiration_ms="123")
with self.assertRaisesRegex(
ValueError, "key_expiration_ms must be >=0 or None"
):
MongoCryptOptions(valid_kms, key_expiration_ms=-1)
class TestMongoCrypt(unittest.TestCase):
maxDiff = None
def test_mongocrypt(self):
kms_providers = {"aws": {"accessKeyId": "foo", "secretAccessKey": "foo"}}
opts = MongoCryptOptions(kms_providers)
mc = MongoCrypt(opts, MockCallback())
mc.close()
mc.close()
def test_mongocrypt_aws_session_token(self):
kms_providers = {
"aws": {
"accessKeyId": "foo",
"secretAccessKey": "foo",
"sessionToken": "token",
}
}
opts = MongoCryptOptions(kms_providers)
mc = MongoCrypt(opts, MockCallback())
mc.close()
def test_mongocrypt_validation(self):
callback = MockCallback()
options = MongoCryptOptions({"local": {"key": b"\x00" * 96}})
with self.assertRaisesRegex(TypeError, "options must be a MongoCryptOptions"):
MongoCrypt({}, callback)
with self.assertRaisesRegex(TypeError, "options must be a MongoCryptOptions"):
MongoCrypt(None, callback)
with self.assertRaisesRegex(
TypeError,
"callback must be a MongoCryptCallback or AsyncMongoCryptCallback",
):
MongoCrypt(options, {})
with self.assertRaisesRegex(
TypeError,
"callback must be a MongoCryptCallback or AsyncMongoCryptCallback",
):
MongoCrypt(options, None)
invalid_key_len_opts = MongoCryptOptions({"local": {"key": b"1"}})
with self.assertRaisesRegex(MongoCryptError, "local key must be 96 bytes"):
MongoCrypt(invalid_key_len_opts, callback)
def test_setopt_kms_provider_base64_or_bytes(self):
test_fields = [("local", "key"), ("gcp", "privateKey")]
callback = MockCallback()
base_kms_dict = {
"local": {"key": b"\x00" * 96},
"gcp": {"email": "foo@bar.baz", "privateKey": b"\x00"},
}
for f1, f2 in test_fields:
kms_dict = copy.deepcopy(base_kms_dict)
# Case 1: pass key as string containing bytes (valid)
kms_dict[f1][f2] = b"\x00" * 96
options = MongoCryptOptions(kms_dict)
mc = MongoCrypt(options, callback)
mc.close()
# Case 2: pass key as base64-encoded unicode literal (valid)
kms_dict[f1][f2] = to_base64(b"\x00" * 96)
options = MongoCryptOptions(kms_dict)
mc = MongoCrypt(options, callback)
mc.close()
# Case 3: pass key as unicode string containing bytes (invalid)
kms_dict[f1][f2] = unicode_type(b"\x00" * 96)
options = MongoCryptOptions(kms_dict)
with self.assertRaisesRegex(
MongoCryptError, "unable to parse base64 from UTF-8 field"
):
MongoCrypt(options, callback)
# Case 4: pass key as base64-encoded string (invalid)
# Only applicable to "local" as key length is not validated for gcp.
kms_dict = copy.deepcopy(base_kms_dict)
kms_dict["local"]["key"] = base64.b64encode(b"\x00" * 96)
options = MongoCryptOptions(kms_dict)
with self.assertRaisesRegex(MongoCryptError, "local key must be 96 bytes"):
MongoCrypt(options, callback)
@staticmethod
def create_mongocrypt(**kwargs):
return MongoCrypt(
MongoCryptOptions(
{
"aws": {"accessKeyId": "example", "secretAccessKey": "example"},
"local": {"key": b"\x00" * 96},
},
**kwargs,
),
MockCallback(),
)
def _test_kms_context(self, ctx):
key_filter = ctx.mongo_operation()
self.assertEqual(key_filter, bson_data("key-filter.json"))
ctx.add_mongo_operation_result(bson_data("key-document.json"))
ctx.complete_mongo_operation()
self.assertEqual(ctx.state, lib.MONGOCRYPT_CTX_NEED_KMS)
km_contexts = list(ctx.kms_contexts())
self.assertEqual(len(km_contexts), 1)
with km_contexts[0] as kms_ctx:
self.assertEqual(kms_ctx.kms_provider, "aws")
self.assertEqual(kms_ctx.endpoint, "kms.us-east-1.amazonaws.com:443")
self.assertEqual(len(kms_ctx.message), 790)
self.assertEqual(kms_ctx.bytes_needed, 1024)
kms_ctx.feed(http_data("kms-reply.txt"))
self.assertEqual(kms_ctx.bytes_needed, 0)
self.assertEqual(kms_ctx.kms_provider, "aws")
ctx.complete_kms()
def test_encrypt(self):
mc = self.create_mongocrypt()
self.addCleanup(mc.close)
if mc.crypt_shared_lib_version is not None:
self.skipTest("this test must be skipped when crypt_shared is loaded")
with mc.encryption_context("text", bson_data("command.json")) as ctx:
self.assertEqual(ctx.state, lib.MONGOCRYPT_CTX_NEED_MONGO_COLLINFO)
list_colls_filter = ctx.mongo_operation()
self.assertEqual(
list_colls_filter, bson_data("list-collections-filter.json")
)
ctx.add_mongo_operation_result(bson_data("collection-info.json"))
ctx.complete_mongo_operation()
self.assertEqual(ctx.state, lib.MONGOCRYPT_CTX_NEED_MONGO_MARKINGS)
mongocryptd_cmd = ctx.mongo_operation()
self.assertEqual(
bson.decode(mongocryptd_cmd, OPTS),
json_data("mongocryptd-command.json"),
)
self.assertEqual(mongocryptd_cmd, bson_data("mongocryptd-command.json"))
ctx.add_mongo_operation_result(bson_data("mongocryptd-reply.json"))
ctx.complete_mongo_operation()
self.assertEqual(ctx.state, lib.MONGOCRYPT_CTX_NEED_MONGO_KEYS)
self._test_kms_context(ctx)
self.assertEqual(ctx.state, lib.MONGOCRYPT_CTX_READY)
encrypted = ctx.finish()
self.assertEqual(
bson.decode(encrypted, OPTS), json_data("encrypted-command.json")
)
self.assertEqual(encrypted, bson_data("encrypted-command.json"))
self.assertEqual(ctx.state, lib.MONGOCRYPT_CTX_DONE)
def test_decrypt(self):
mc = self.create_mongocrypt()
self.addCleanup(mc.close)
with mc.decryption_context(bson_data("encrypted-command-reply.json")) as ctx:
self.assertEqual(ctx.state, lib.MONGOCRYPT_CTX_NEED_MONGO_KEYS)
self._test_kms_context(ctx)
self.assertEqual(ctx.state, lib.MONGOCRYPT_CTX_READY)
encrypted = ctx.finish()
self.assertEqual(
bson.decode(encrypted, OPTS), json_data("command-reply.json")
)
self.assertEqual(encrypted, bson_data("command-reply.json"))
self.assertEqual(ctx.state, lib.MONGOCRYPT_CTX_DONE)
def test_encrypt_encrypted_fields_map(self):
encrypted_fields_map = bson_data(
"compact/success/encrypted-field-config-map.json"
)
mc = self.create_mongocrypt(encrypted_fields_map=encrypted_fields_map)
self.addCleanup(mc.close)
with mc.encryption_context("db", bson_data("compact/success/cmd.json")) as ctx:
self.assertEqual(ctx.state, lib.MONGOCRYPT_CTX_NEED_MONGO_KEYS)
ctx.mongo_operation()
ctx.add_mongo_operation_result(
bson_data("keys/12345678123498761234123456789012-local-document.json")
)
self.assertEqual(ctx.state, lib.MONGOCRYPT_CTX_NEED_MONGO_KEYS)
ctx.mongo_operation()
ctx.add_mongo_operation_result(
bson_data("keys/ABCDEFAB123498761234123456789012-local-document.json")
)
self.assertEqual(ctx.state, lib.MONGOCRYPT_CTX_NEED_MONGO_KEYS)
ctx.mongo_operation()
ctx.add_mongo_operation_result(
bson_data("keys/12345678123498761234123456789013-local-document.json")
)
ctx.complete_mongo_operation()
self.assertEqual(ctx.state, lib.MONGOCRYPT_CTX_READY)
encrypted = ctx.finish()
self.assertEqual(
bson.decode(encrypted, OPTS),
json_data("compact/success/encrypted-payload.json"),
)
self.assertEqual(
encrypted, bson_data("compact/success/encrypted-payload.json")
)
self.assertEqual(ctx.state, lib.MONGOCRYPT_CTX_DONE)
def test_pymongo_imports(self):
from pymongocrypt.auto_encrypter import AutoEncrypter # type:ignore[import]
from pymongocrypt.errors import MongoCryptError # type:ignore[import]
from pymongocrypt.explicit_encrypter import (
ExplicitEncrypter, # type:ignore[import]
)
from pymongocrypt.mongocrypt import MongoCryptOptions # type:ignore[import]
from pymongocrypt.state_machine import MongoCryptCallback # type:ignore[import]
class MockCallback(MongoCryptCallback):
def __init__(
self,
list_colls_result=None,
mongocryptd_reply=None,
key_docs=None,
kms_reply=None,
):
self.list_colls_result = list_colls_result
self.mongocryptd_reply = mongocryptd_reply
self.key_docs = key_docs
self.kms_reply = kms_reply
self.kms_endpoint = None
def kms_request(self, kms_context):
self.kms_endpoint = kms_context.endpoint
kms_context.feed(self.kms_reply)
def collection_info(self, ns, filter):
return self.list_colls_result
def mark_command(self, ns, cmd):
return self.mongocryptd_reply
def fetch_keys(self, filter):
return self.key_docs
def insert_data_key(self, data_key):
raise NotImplementedError
def bson_encode(self, doc):
return bson.encode(doc)
def close(self):
pass
class MockAsyncCallback(AsyncMongoCryptCallback):
def __init__(
self,
list_colls_result=None,
mongocryptd_reply=None,
key_docs=None,
kms_reply=None,
):
self.list_colls_result = list_colls_result
self.mongocryptd_reply = mongocryptd_reply
self.key_docs = key_docs
self.kms_reply = kms_reply
self.kms_endpoint = None
async def kms_request(self, kms_context):
self.kms_endpoint = kms_context.endpoint
kms_context.feed(self.kms_reply)
async def collection_info(self, ns, filter):
return self.list_colls_result
async def mark_command(self, ns, cmd):
return self.mongocryptd_reply
async def fetch_keys(self, filter):
for doc in self.key_docs:
yield doc
async def insert_data_key(self, data_key):
raise NotImplementedError
def bson_encode(self, doc):
return bson.encode(doc)
async def close(self):
pass
class TestMongoCryptCallback(unittest.TestCase):
maxDiff = None
@staticmethod
def mongo_crypt_opts():
return MongoCryptOptions(
{
"aws": {"accessKeyId": "example", "secretAccessKey": "example"},
"local": {"key": b"\x00" * 96},
}
)
@unittest.skipUnless(
os.getenv("TEST_CRYPT_SHARED"), "this test requires TEST_CRYPT_SHARED=1"
)
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), MockCallback())
self.addCleanup(mc.close)
self.assertIsNotNone(mc.crypt_shared_lib_version)
# Test that we can pick up crypt_shared automatically
encrypter = AutoEncrypter(
MockCallback(),
MongoCryptOptions(
kms_providers, bypass_encryption=False, crypt_shared_lib_required=True
),
)
self.addCleanup(encrypter.close)
encrypter = AutoEncrypter(
MockCallback(),
MongoCryptOptions(
kms_providers,
crypt_shared_lib_path=os.environ["CRYPT_SHARED_PATH"],
crypt_shared_lib_required=True,
),
)
self.addCleanup(encrypter.close)
with self.assertRaisesRegex(MongoCryptError, "/doesnotexist"):
AutoEncrypter(
MockCallback(),
MongoCryptOptions(
kms_providers,
crypt_shared_lib_path="/doesnotexist",
crypt_shared_lib_required=True,
),
)
def test_encrypt(self):
encrypter = AutoEncrypter(
MockCallback(
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.addCleanup(encrypter.close)
encrypted = 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"))
def test_decrypt(self):
encrypter = AutoEncrypter(
MockCallback(
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.addCleanup(encrypter.close)
decrypted = 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"))
def test_need_kms_aws_credentials(self):
kms_providers = {"aws": {}}
opts = MongoCryptOptions(kms_providers)
callback = MockCallback(
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 = AutoEncrypter(callback, opts)
self.addCleanup(encrypter.close)
with unittest.mock.patch(
"pymongocrypt.synchronous.credentials.aws_temp_credentials"
) as m:
m.return_value = AwsCredential("example", "example", None)
decrypted = encrypter.decrypt(bson_data("encrypted-command-reply.json"))
self.assertTrue(m.called)
self.assertEqual(bson.decode(decrypted, OPTS), json_data("command-reply.json"))
self.assertEqual(decrypted, bson_data("command-reply.json"))
def test_need_kms_gcp_credentials(self):
kms_providers = {"gcp": {}}
opts = MongoCryptOptions(kms_providers)
callback = MockCallback(
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 = AutoEncrypter(callback, opts)
self.addCleanup(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 = encrypter.decrypt(bson_data("encrypted-command-reply.json"))
self.assertTrue(len(router.calls))
self.assertEqual(bson.decode(decrypted, OPTS), json_data("command-reply.json"))
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},
}
)
@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="/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")
)
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.assertTrue(m.called)
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))
)
decrypted = await encrypter.decrypt(
bson_data("encrypted-command-reply.json")
)
self.assertTrue(len(router.calls))
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"),
),
self.mongo_crypt_opts(),
)
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
)
self.assertEqual(
bson.decode(encrypted, OPTS), json_data("encrypted-value.json")
)
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_decrypt(self):
key_id = json_data("key-document.json")["_id"]
await self._test_encrypt_decrypt(key_id=key_id)
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)
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)
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
)
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)
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)
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_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)
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_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)
result = await encrypter.rewrap_many_data_key({})
raw_doc = RawBSONDocument(result)
assert len(raw_doc["v"]) == 2
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)
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(