File: client_side_encryption_prose_test.go

package info (click to toggle)
golang-mongodb-mongo-driver 1.17.1%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: experimental, sid, trixie
  • size: 25,988 kB
  • sloc: perl: 533; ansic: 491; python: 432; sh: 327; makefile: 174
file content (3218 lines) | stat: -rw-r--r-- 134,039 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
// Copyright (C) MongoDB, Inc. 2017-present.
//
// 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

//go:build cse
// +build cse

package integration

import (
	"context"
	"crypto/tls"
	"encoding/base64"
	"fmt"
	"io/ioutil"
	"net"
	"net/http"
	"os"
	"path/filepath"
	"strings"
	"testing"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/bsontype"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/event"
	"go.mongodb.org/mongo-driver/internal/assert"
	"go.mongodb.org/mongo-driver/internal/handshake"
	"go.mongodb.org/mongo-driver/internal/integtest"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/integration/mtest"
	"go.mongodb.org/mongo-driver/mongo/options"
	"go.mongodb.org/mongo-driver/mongo/writeconcern"
	"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
	"go.mongodb.org/mongo-driver/x/mongo/driver/mongocrypt"
	mongocryptopts "go.mongodb.org/mongo-driver/x/mongo/driver/mongocrypt/options"
)

var (
	localMasterKey = []byte("2x44+xduTaBBkY16Er5DuADaghvS4vwdkg8tpPp3tz6gV01A1CwbD9itQ2HFDgPWOp8eMaC1Oi766JzXZBdBdbdMurdonJ1d")
)

const (
	clientEncryptionProseDir      = "../../testdata/client-side-encryption-prose"
	deterministicAlgorithm        = "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic"
	randomAlgorithm               = "AEAD_AES_256_CBC_HMAC_SHA_512-Random"
	kvNamespace                   = "keyvault.datakeys" // default namespace for the key vault collection
	keySubtype               byte = 4                   // expected subtype for data keys
	encryptedValueSubtype    byte = 6                   // expected subtypes for encrypted values
	cryptMaxBatchSizeBytes        = 2097152             // max bytes in write batch when auto encryption is enabled
	maxBsonObjSize                = 16777216            // max bytes in BSON object
)

func containsSubstring(possibleSubstrings []string, str string) bool {
	for _, possibleSubstring := range possibleSubstrings {
		if strings.Contains(str, possibleSubstring) {
			return true
		}
	}

	return false
}

func TestClientSideEncryptionProse(t *testing.T) {
	t.Parallel()

	verifyClientSideEncryptionVarsSet(t)
	mt := mtest.New(t, mtest.NewOptions().MinServerVersion("4.2").Enterprise(true).CreateClient(false))

	defaultKvClientOptions := options.Client().ApplyURI(mtest.ClusterURI())
	integtest.AddTestServerAPIVersion(defaultKvClientOptions)
	fullKmsProvidersMap := map[string]map[string]interface{}{
		"aws": {
			"accessKeyId":     awsAccessKeyID,
			"secretAccessKey": awsSecretAccessKey,
		},
		"azure": {
			"tenantId":     azureTenantID,
			"clientId":     azureClientID,
			"clientSecret": azureClientSecret,
		},
		"gcp": {
			"email":      gcpEmail,
			"privateKey": gcpPrivateKey,
		},
		"local": {"key": localMasterKey},
		"kmip": {
			"endpoint": "localhost:5698",
		},
	}

	mt.Run("1. custom key material test", func(mt *mtest.T) {
		const (
			dkCollection = "datakeys"
			idKey        = "_id"
			kvDatabase   = "keyvault"
		)

		// Create a ClientEncryption object (referred to as client_encryption) with client set as the keyVaultClient.
		// Using client, drop the collection keyvault.datakeys.
		cse := setup(mt, nil, defaultKvClientOptions, options.ClientEncryption().
			SetKmsProviders(fullKmsProvidersMap).
			SetKeyVaultNamespace(kvNamespace))

		err := cse.kvClient.Database(kvDatabase).Collection(dkCollection).Drop(context.Background())
		assert.Nil(mt, err, "error dropping %q namespace: %v", kvNamespace, err)

		// Using client_encryption, create a data key with a local KMS provider and the declared b64 custom key material
		// (given as base64).
		const b641 = `xPTAjBRG5JiPm+d3fj6XLi2q5DMXUS/f1f+SMAlhhwkhDRL0kr8r9GDLIGTAGlvC+HVjSIgdL+RKwZCvpXSyxTICWSXT` +
			`UYsWYPyu3IoHbuBZdmw2faM3WhcRIgbMReU5`

		// Decode the base64-encoded keyMaterial string.
		km, err := base64.StdEncoding.DecodeString(b641)
		assert.Nil(mt, err, "error decoding b64: %v", err)

		_, err = cse.clientEnc.CreateDataKey(context.Background(), "local", options.DataKey().SetKeyMaterial(km))
		assert.Nil(mt, err, "error creating data key: %v", err)

		// Find the resulting key document in keyvault.datakeys, save a copy of the key document, then remove the key
		// document from the collection.
		coll := cse.kvClient.Database(kvDatabase).Collection(dkCollection)

		keydoc, err := coll.FindOne(context.Background(), bson.D{}).Raw()
		assert.Nil(mt, err, "error in decoding bytes: %v", err)

		// Remove the key document from the collection.
		id, err := keydoc.LookupErr(idKey)
		assert.Nil(mt, err, "error looking up %s: %v", idKey, err)

		_, err = coll.DeleteOne(context.Background(), bson.D{{idKey, id}})
		assert.Nil(mt, err, "error deleting key document: %v", err)

		// Replace the _id field in the copied key document with a UUID with base64 value AAAAAAAAAAAAAAAAAAAAAA== (16
		// bytes all equal to 0x00) and insert the modified key document into keyvault.datakeys with majority write
		// concern.
		cidx, alteredKeydoc := bsoncore.AppendDocumentStart(nil)
		docElems, _ := keydoc.Elements()
		for _, element := range docElems {
			if key := element.Key(); key != idKey {
				alteredKeydoc = bsoncore.AppendValueElement(alteredKeydoc, key, rawValueToCoreValue(element.Value()))
			}
		}
		empty := [16]byte{}
		uuidSubtype, _ := keydoc.Lookup(idKey).Binary()
		alteredKeydoc = bsoncore.AppendBinaryElement(alteredKeydoc, idKey, uuidSubtype, empty[:])
		alteredKeydoc, _ = bsoncore.AppendDocumentEnd(alteredKeydoc, cidx)

		// Insert the copied key document into keyvault.datakeys with majority write concern.
		wcMajority := writeconcern.New(writeconcern.WMajority(), writeconcern.WTimeout(1*time.Second))
		wcMajorityCollectionOpts := options.Collection().SetWriteConcern(wcMajority)
		wcmColl := cse.kvClient.Database(kvDatabase).Collection(dkCollection, wcMajorityCollectionOpts)
		_, err = wcmColl.InsertOne(context.Background(), alteredKeydoc)
		assert.Nil(mt, err, "error inserting altered key document: %v", err)

		// Using client_encryption, encrypt the string "test" with the modified data key using the
		// AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic algorithm and assert the resulting value is equal to the
		// declared b64 constant.
		const b642 = `AQAAAAAAAAAAAAAAAAAAAAACz0ZOLuuhEYi807ZXTdhbqhLaS2/t9wLifJnnNYwiw79d75QYIZ6M/aYC1h9nCzCjZ7pG` +
			`UpAuNnkUhnIXM3PjrA==`

		empty = [16]byte{}
		keyid := primitive.Binary{Subtype: 0x04, Data: empty[:]}

		encOpts := options.Encrypt().SetAlgorithm(deterministicAlgorithm).SetKeyID(keyid)
		testVal := bson.RawValue{
			Type:  bson.TypeString,
			Value: bsoncore.AppendString(nil, "test"),
		}
		actual, err := cse.clientEnc.Encrypt(context.Background(), testVal, encOpts)
		assert.Nil(mt, err, "error encrypting data: %v", err)

		expected := primitive.Binary{Subtype: 0x06}
		expected.Data, _ = base64.StdEncoding.DecodeString(b642)

		assert.Equal(t, actual, expected, "expected: %v, got: %v", actual, expected)
	})
	mt.RunOpts("2. data key and double encryption", noClientOpts, func(mt *mtest.T) {
		// set up options structs
		schema := bson.D{
			{"bsonType", "object"},
			{"properties", bson.D{
				{"encrypted_placeholder", bson.D{
					{"encrypt", bson.D{
						{"keyId", "/placeholder"},
						{"bsonType", "string"},
						{"algorithm", "AEAD_AES_256_CBC_HMAC_SHA_512-Random"},
					}},
				}},
			}},
		}
		schemaMap := map[string]interface{}{"db.coll": schema}
		tlsConfig := make(map[string]*tls.Config)
		if tlsCAFileKMIP != "" && tlsClientCertificateKeyFileKMIP != "" {
			tlsOpts := map[string]interface{}{
				"tlsCertificateKeyFile": tlsClientCertificateKeyFileKMIP,
				"tlsCAFile":             tlsCAFileKMIP,
			}
			kmipConfig, err := options.BuildTLSConfig(tlsOpts)
			assert.Nil(mt, err, "BuildTLSConfig error: %v", err)
			tlsConfig["kmip"] = kmipConfig
		}

		aeo := options.AutoEncryption().
			SetKmsProviders(fullKmsProvidersMap).
			SetKeyVaultNamespace(kvNamespace).
			SetSchemaMap(schemaMap).
			SetTLSConfig(tlsConfig).
			SetExtraOptions(getCryptSharedLibExtraOptions())

		ceo := options.ClientEncryption().
			SetKmsProviders(fullKmsProvidersMap).
			SetKeyVaultNamespace(kvNamespace).
			SetTLSConfig(tlsConfig)

		awsMasterKey := bson.D{
			{"region", "us-east-1"},
			{"key", "arn:aws:kms:us-east-1:579766882180:key/89fcc2c4-08b0-4bd9-9f25-e30687b580d0"},
		}
		azureMasterKey := bson.D{
			{"keyVaultEndpoint", "key-vault-csfle.vault.azure.net"},
			{"keyName", "key-name-csfle"},
		}
		gcpMasterKey := bson.D{
			{"projectId", "devprod-drivers"},
			{"location", "global"},
			{"keyRing", "key-ring-csfle"},
			{"keyName", "key-name-csfle"},
		}
		kmipMasterKey := bson.D{}
		testCases := []struct {
			provider  string
			masterKey interface{}
		}{
			{"local", nil},
			{"aws", awsMasterKey},
			{"azure", azureMasterKey},
			{"gcp", gcpMasterKey},
			{"kmip", kmipMasterKey},
		}
		for _, tc := range testCases {
			mt.Run(tc.provider, func(mt *mtest.T) {
				if tc.provider == "kmip" && "" == os.Getenv("KMS_MOCK_SERVERS_RUNNING") {
					mt.Skipf("Skipping test as KMS_MOCK_SERVERS_RUNNING is not set")
				}
				var startedEvents []*event.CommandStartedEvent
				monitor := &event.CommandMonitor{
					Started: func(_ context.Context, evt *event.CommandStartedEvent) {
						startedEvents = append(startedEvents, evt)
					},
				}
				kvClientOpts := options.Client().ApplyURI(mtest.ClusterURI()).SetMonitor(monitor)
				integtest.AddTestServerAPIVersion(kvClientOpts)
				cpt := setup(mt, aeo, kvClientOpts, ceo)
				defer cpt.teardown(mt)

				// create data key
				keyAltName := fmt.Sprintf("%s_altname", tc.provider)
				dataKeyOpts := options.DataKey().SetKeyAltNames([]string{keyAltName})
				if tc.masterKey != nil {
					dataKeyOpts.SetMasterKey(tc.masterKey)
				}
				dataKeyID, err := cpt.clientEnc.CreateDataKey(context.Background(), tc.provider, dataKeyOpts)
				assert.Nil(mt, err, "CreateDataKey error: %v", err)
				assert.Equal(mt, keySubtype, dataKeyID.Subtype,
					"expected data key subtype %v, got %v", keySubtype, dataKeyID.Subtype)

				// assert that the key exists in the key vault
				cursor, err := cpt.keyVaultColl.Find(context.Background(), bson.D{{"_id", dataKeyID}})
				assert.Nil(mt, err, "key vault Find error: %v", err)
				assert.True(mt, cursor.Next(context.Background()), "no keys found in key vault")
				provider := cursor.Current.Lookup("masterKey", "provider").StringValue()
				assert.Equal(mt, tc.provider, provider, "expected provider %v, got %v", tc.provider, provider)
				assert.False(mt, cursor.Next(context.Background()), "unexpected document in key vault: %v", cursor.Current)

				// verify that the key was inserted using write concern majority
				assert.Equal(mt, 1, len(startedEvents), "expected 1 CommandStartedEvent, got %v", len(startedEvents))
				evt := startedEvents[0]
				assert.Equal(mt, "insert", evt.CommandName, "expected command 'insert', got '%v'", evt.CommandName)
				writeConcernVal, err := evt.Command.LookupErr("writeConcern")
				assert.Nil(mt, err, "expected writeConcern in command %s", evt.Command)
				wString := writeConcernVal.Document().Lookup("w").StringValue()
				assert.Equal(mt, "majority", wString, "expected write concern 'majority', got %v", wString)

				// encrypt a value with the new key by ID
				valueToEncrypt := fmt.Sprintf("hello %s", tc.provider)
				rawVal := bson.RawValue{Type: bson.TypeString, Value: bsoncore.AppendString(nil, valueToEncrypt)}
				encrypted, err := cpt.clientEnc.Encrypt(context.Background(), rawVal,
					options.Encrypt().SetAlgorithm(deterministicAlgorithm).SetKeyID(dataKeyID))
				assert.Nil(mt, err, "Encrypt error while encrypting value by ID: %v", err)
				assert.Equal(mt, encryptedValueSubtype, encrypted.Subtype,
					"expected encrypted value subtype %v, got %v", encryptedValueSubtype, encrypted.Subtype)

				// insert an encrypted value. the value shouldn't be encrypted again because it's not in the schema.
				_, err = cpt.cseColl.InsertOne(context.Background(), bson.D{{"_id", tc.provider}, {"value", encrypted}})
				assert.Nil(mt, err, "InsertOne error: %v", err)

				// find the inserted document. the value should be decrypted automatically
				resBytes, err := cpt.cseColl.FindOne(context.Background(), bson.D{{"_id", tc.provider}}).Raw()
				assert.Nil(mt, err, "Find error: %v", err)
				foundVal := resBytes.Lookup("value").StringValue()
				assert.Equal(mt, valueToEncrypt, foundVal, "expected value %v, got %v", valueToEncrypt, foundVal)

				// encrypt a value with an alternate name for the new key
				altEncrypted, err := cpt.clientEnc.Encrypt(context.Background(), rawVal,
					options.Encrypt().SetAlgorithm(deterministicAlgorithm).SetKeyAltName(keyAltName))
				assert.Nil(mt, err, "Encrypt error while encrypting value by alt key name: %v", err)
				assert.Equal(mt, encryptedValueSubtype, altEncrypted.Subtype,
					"expected encrypted value subtype %v, got %v", encryptedValueSubtype, altEncrypted.Subtype)
				assert.Equal(mt, encrypted.Data, altEncrypted.Data,
					"expected data %v, got %v", encrypted.Data, altEncrypted.Data)

				// insert an encrypted value for an auto-encrypted field
				_, err = cpt.cseColl.InsertOne(context.Background(), bson.D{{"encrypted_placeholder", encrypted}})
				assert.NotNil(mt, err, "expected InsertOne error, got nil")
			})
		}
	})
	mt.RunOpts("3. external key vault", noClientOpts, func(mt *mtest.T) {
		testCases := []struct {
			name          string
			externalVault bool
		}{
			{"with external vault", true},
			{"without external vault", false},
		}

		for _, tc := range testCases {
			mt.Run(tc.name, func(mt *mtest.T) {
				// setup options structs
				kmsProviders := map[string]map[string]interface{}{
					"local": {
						"key": localMasterKey,
					},
				}
				schemaMap := map[string]interface{}{"db.coll": readJSONFile(mt, "external-schema.json")}
				aeo := options.AutoEncryption().
					SetKmsProviders(kmsProviders).
					SetKeyVaultNamespace(kvNamespace).
					SetSchemaMap(schemaMap).
					SetExtraOptions(getCryptSharedLibExtraOptions())
				ceo := options.ClientEncryption().
					SetKmsProviders(kmsProviders).
					SetKeyVaultNamespace(kvNamespace)
				kvClientOpts := defaultKvClientOptions

				if tc.externalVault {
					externalKvOpts := options.Client().ApplyURI(mtest.ClusterURI()).SetAuth(options.Credential{
						Username: "fake-user",
						Password: "fake-password",
					})
					integtest.AddTestServerAPIVersion(externalKvOpts)
					aeo.SetKeyVaultClientOptions(externalKvOpts)
					kvClientOpts = externalKvOpts
				}
				cpt := setup(mt, aeo, kvClientOpts, ceo)
				defer cpt.teardown(mt)

				// manually insert data key
				key := readJSONFile(mt, "external-key.json")
				_, err := cpt.keyVaultColl.InsertOne(context.Background(), key)
				assert.Nil(mt, err, "InsertOne error for data key: %v", err)
				subtype, data := key.Lookup("_id").Binary()
				dataKeyID := primitive.Binary{Subtype: subtype, Data: data}

				doc := bson.D{{"encrypted", "test"}}
				_, insertErr := cpt.cseClient.Database("db").Collection("coll").InsertOne(context.Background(), doc)
				rawVal := bson.RawValue{Type: bson.TypeString, Value: bsoncore.AppendString(nil, "test")}
				_, encErr := cpt.clientEnc.Encrypt(context.Background(), rawVal,
					options.Encrypt().SetKeyID(dataKeyID).SetAlgorithm(deterministicAlgorithm))

				if tc.externalVault {
					assert.NotNil(mt, insertErr, "expected InsertOne auth error, got nil")
					assert.NotNil(mt, encErr, "expected Encrypt auth error, got nil")
					assert.True(mt, strings.Contains(insertErr.Error(), "auth error"),
						"expected InsertOne auth error, got %v", insertErr)
					assert.True(mt, strings.Contains(encErr.Error(), "auth error"),
						"expected Encrypt auth error, got %v", insertErr)
					return
				}
				assert.Nil(mt, insertErr, "InsertOne error: %v", insertErr)
				assert.Nil(mt, encErr, "Encrypt error: %v", err)
			})
		}
	})
	mt.Run("4. bson size limits", func(mt *mtest.T) {
		kmsProviders := map[string]map[string]interface{}{
			"local": {
				"key": localMasterKey,
			},
		}
		aeo := options.AutoEncryption().
			SetKmsProviders(kmsProviders).
			SetKeyVaultNamespace(kvNamespace).
			SetExtraOptions(getCryptSharedLibExtraOptions())
		cpt := setup(mt, aeo, nil, nil)
		defer cpt.teardown(mt)

		// create coll with JSON schema
		err := mt.Client.Database("db").RunCommand(context.Background(), bson.D{
			{"create", "coll"},
			{"validator", bson.D{
				{"$jsonSchema", readJSONFile(mt, "limits-schema.json")},
			}},
		}).Err()
		assert.Nil(mt, err, "create error with validator: %v", err)

		// insert key
		key := readJSONFile(mt, "limits-key.json")
		_, err = cpt.keyVaultColl.InsertOne(context.Background(), key)
		assert.Nil(mt, err, "InsertOne error for key: %v", err)

		var builder2mb, builder16mb strings.Builder
		for i := 0; i < cryptMaxBatchSizeBytes; i++ {
			builder2mb.WriteByte('a')
		}
		for i := 0; i < maxBsonObjSize; i++ {
			builder16mb.WriteByte('a')
		}
		complete2mbStr := builder2mb.String()
		complete16mbStr := builder16mb.String()

		// insert a document over 2MiB
		doc := bson.D{{"over_2mib_under_16mib", complete2mbStr}}
		_, err = cpt.cseColl.InsertOne(context.Background(), doc)
		assert.Nil(mt, err, "InsertOne error for 2MiB document: %v", err)

		str := complete2mbStr[:cryptMaxBatchSizeBytes-2000] // remove last 2000 bytes
		limitsDoc := readJSONFile(mt, "limits-doc.json")

		// insert a doc smaller than 2MiB that is bigger than 2MiB after encryption
		var extendedLimitsDoc []byte
		extendedLimitsDoc = append(extendedLimitsDoc, limitsDoc...)
		extendedLimitsDoc = extendedLimitsDoc[:len(extendedLimitsDoc)-1] // remove last byte to add new fields
		extendedLimitsDoc = bsoncore.AppendStringElement(extendedLimitsDoc, "_id", "encryption_exceeds_2mib")
		extendedLimitsDoc = bsoncore.AppendStringElement(extendedLimitsDoc, "unencrypted", str)
		extendedLimitsDoc, _ = bsoncore.AppendDocumentEnd(extendedLimitsDoc, 0)
		_, err = cpt.cseColl.InsertOne(context.Background(), extendedLimitsDoc)
		assert.Nil(mt, err, "error inserting extended limits document: %v", err)

		// bulk insert two 2MiB documents, each over 2 MiB
		// each document should be split into its own batch because the documents are bigger than 2MiB but smaller
		// than 16MiB
		cpt.cseStarted = cpt.cseStarted[:0]
		firstDoc := bson.D{{"_id", "over_2mib_1"}, {"unencrypted", complete2mbStr}}
		secondDoc := bson.D{{"_id", "over_2mib_2"}, {"unencrypted", complete2mbStr}}
		_, err = cpt.cseColl.InsertMany(context.Background(), []interface{}{firstDoc, secondDoc})
		assert.Nil(mt, err, "InsertMany error for small documents: %v", err)
		assert.Equal(mt, 2, len(cpt.cseStarted), "expected 2 insert events, got %d", len(cpt.cseStarted))

		// bulk insert two documents
		str = complete2mbStr[:cryptMaxBatchSizeBytes-20000]
		firstBulkDoc := make([]byte, len(limitsDoc))
		copy(firstBulkDoc, limitsDoc)
		firstBulkDoc = firstBulkDoc[:len(firstBulkDoc)-1] // remove last byte to append new fields
		firstBulkDoc = bsoncore.AppendStringElement(firstBulkDoc, "_id", "encryption_exceeds_2mib_1")
		firstBulkDoc = bsoncore.AppendStringElement(firstBulkDoc, "unencrypted", string(str))
		firstBulkDoc, _ = bsoncore.AppendDocumentEnd(firstBulkDoc, 0)

		secondBulkDoc := make([]byte, len(limitsDoc))
		copy(secondBulkDoc, limitsDoc)
		secondBulkDoc = secondBulkDoc[:len(secondBulkDoc)-1] // remove last byte to append new fields
		secondBulkDoc = bsoncore.AppendStringElement(secondBulkDoc, "_id", "encryption_exceeds_2mib_2")
		secondBulkDoc = bsoncore.AppendStringElement(secondBulkDoc, "unencrypted", string(str))
		secondBulkDoc, _ = bsoncore.AppendDocumentEnd(secondBulkDoc, 0)

		cpt.cseStarted = cpt.cseStarted[:0]
		_, err = cpt.cseColl.InsertMany(context.Background(), []interface{}{firstBulkDoc, secondBulkDoc})
		assert.Nil(mt, err, "InsertMany error for large documents: %v", err)
		assert.Equal(mt, 2, len(cpt.cseStarted), "expected 2 insert events, got %d", len(cpt.cseStarted))

		// insert a document slightly smaller than 16MiB and expect the operation to succeed
		doc = bson.D{{"_id", "under_16mib"}, {"unencrypted", complete16mbStr[:maxBsonObjSize-2000]}}
		_, err = cpt.cseColl.InsertOne(context.Background(), doc)
		assert.Nil(mt, err, "InsertOne error: %v", err)

		// insert a document over 16MiB and expect the operation to fail
		var over16mb []byte
		over16mb = append(over16mb, limitsDoc...)
		over16mb = over16mb[:len(over16mb)-1] // remove last byte
		over16mb = bsoncore.AppendStringElement(over16mb, "_id", "encryption_exceeds_16mib")
		over16mb = bsoncore.AppendStringElement(over16mb, "unencrypted", complete16mbStr[:maxBsonObjSize-2000])
		over16mb, _ = bsoncore.AppendDocumentEnd(over16mb, 0)
		_, err = cpt.cseColl.InsertOne(context.Background(), over16mb)
		assert.NotNil(mt, err, "expected InsertOne error for document over 16MiB, got nil")
	})
	mt.Run("5. views are prohibited", func(mt *mtest.T) {
		mt.Parallel()

		kmsProviders := map[string]map[string]interface{}{
			"local": {
				"key": localMasterKey,
			},
		}
		aeo := options.AutoEncryption().
			SetKmsProviders(kmsProviders).
			SetKeyVaultNamespace(kvNamespace).
			SetExtraOptions(getCryptSharedLibExtraOptions())
		cpt := setup(mt, aeo, nil, nil)
		defer cpt.teardown(mt)

		// create view on db.coll
		mt.CreateCollection(mtest.Collection{
			Name:         "view",
			DB:           cpt.cseColl.Database().Name(),
			ViewOn:       "coll",
			ViewPipeline: mongo.Pipeline{},
		}, true)

		view := cpt.cseColl.Database().Collection("view")
		_, err := view.InsertOne(context.Background(), bson.D{{"_id", "insert_on_view"}})
		assert.NotNil(mt, err, "expected InsertOne error on view, got nil")
		errStr := strings.ToLower(err.Error())
		viewErrSubstr := "cannot auto encrypt a view"
		assert.True(mt, strings.Contains(errStr, viewErrSubstr),
			"expected error '%v' to contain substring '%v'", errStr, viewErrSubstr)
	})
	mt.RunOpts("6. corpus test", noClientOpts, func(mt *mtest.T) {
		if "" == os.Getenv("KMS_MOCK_SERVERS_RUNNING") {
			mt.Skipf("Skipping test as KMS_MOCK_SERVERS_RUNNING is not set")
		}
		corpusSchema := readJSONFile(mt, "corpus-schema.json")
		localSchemaMap := map[string]interface{}{
			"db.coll": corpusSchema,
		}

		tlsConfig := make(map[string]*tls.Config)
		if tlsCAFileKMIP != "" && tlsClientCertificateKeyFileKMIP != "" {
			tlsOpts := map[string]interface{}{
				"tlsCertificateKeyFile": tlsClientCertificateKeyFileKMIP,
				"tlsCAFile":             tlsCAFileKMIP,
			}
			kmipConfig, err := options.BuildTLSConfig(tlsOpts)
			assert.Nil(mt, err, "BuildTLSConfig error: %v", err)
			tlsConfig["kmip"] = kmipConfig
		}

		getBaseAutoEncryptionOpts := func() *options.AutoEncryptionOptions {
			return options.AutoEncryption().
				SetKmsProviders(fullKmsProvidersMap).
				SetKeyVaultNamespace(kvNamespace).
				SetTLSConfig(tlsConfig).
				SetExtraOptions(getCryptSharedLibExtraOptions())
		}

		testCases := []struct {
			name   string
			aeo    *options.AutoEncryptionOptions
			schema bson.Raw // the schema to create the collection. if nil, the collection won't be explicitly created
		}{
			{"remote schema", getBaseAutoEncryptionOpts(), corpusSchema},
			{"local schema", getBaseAutoEncryptionOpts().SetSchemaMap(localSchemaMap), nil},
		}

		for _, tc := range testCases {
			mt.Run(tc.name, func(mt *mtest.T) {
				ceo := options.ClientEncryption().
					SetKmsProviders(fullKmsProvidersMap).
					SetKeyVaultNamespace(kvNamespace).
					SetTLSConfig(tlsConfig)

				cpt := setup(mt, tc.aeo, defaultKvClientOptions, ceo)
				defer cpt.teardown(mt)

				// create collection with JSON schema
				if tc.schema != nil {
					db := cpt.coll.Database()
					err := db.RunCommand(context.Background(), bson.D{
						{"create", "coll"},
						{"validator", bson.D{
							{"$jsonSchema", readJSONFile(mt, "corpus-schema.json")},
						}},
					}).Err()
					assert.Nil(mt, err, "create error with validator: %v", err)
				}

				// Manually insert keys for each KMS provider into the key vault.
				_, err := cpt.keyVaultColl.InsertMany(context.Background(), []interface{}{
					readJSONFile(mt, "corpus-key-local.json"),
					readJSONFile(mt, "corpus-key-aws.json"),
					readJSONFile(mt, "corpus-key-azure.json"),
					readJSONFile(mt, "corpus-key-gcp.json"),
					readJSONFile(mt, "corpus-key-kmip.json"),
				})
				assert.Nil(mt, err, "InsertMany error for key vault: %v", err)

				// read original corpus and recursively copy over each value to new corpus, encrypting certain values
				// when needed
				corpus := readJSONFile(mt, "corpus.json")
				cidx, copied := bsoncore.AppendDocumentStart(nil)
				elems, _ := corpus.Elements()

				// Keys for top-level non-document elements that should be copied directly.
				copiedKeys := map[string]struct{}{
					"_id":           {},
					"altname_aws":   {},
					"altname_local": {},
					"altname_azure": {},
					"altname_gcp":   {},
					"altname_kmip":  {},
				}

				for _, elem := range elems {
					key := elem.Key()
					val := elem.Value()

					if _, ok := copiedKeys[key]; ok {
						copied = bsoncore.AppendStringElement(copied, key, val.StringValue())
						continue
					}

					doc := val.Document()
					switch method := doc.Lookup("method").StringValue(); method {
					case "auto":
						// Copy the value directly because it will be auto-encrypted later.
						copied = bsoncore.AppendDocumentElement(copied, key, doc)
						continue
					case "explicit":
						// Handled below.
					default:
						mt.Fatalf("unrecognized 'method' value %q", method)
					}

					// explicitly encrypt value
					algorithm := deterministicAlgorithm
					if doc.Lookup("algo").StringValue() == "rand" {
						algorithm = randomAlgorithm
					}
					eo := options.Encrypt().SetAlgorithm(algorithm)

					identifier := doc.Lookup("identifier").StringValue()
					kms := doc.Lookup("kms").StringValue()
					switch identifier {
					case "id":
						var keyID string
						switch kms {
						case "local":
							keyID = "LOCALAAAAAAAAAAAAAAAAA=="
						case "aws":
							keyID = "AWSAAAAAAAAAAAAAAAAAAA=="
						case "azure":
							keyID = "AZUREAAAAAAAAAAAAAAAAA=="
						case "gcp":
							keyID = "GCPAAAAAAAAAAAAAAAAAAA=="
						case "kmip":
							keyID = "KMIPAAAAAAAAAAAAAAAAAA=="
						default:
							mt.Fatalf("unrecognized KMS provider %q", kms)
						}

						keyIDBytes, err := base64.StdEncoding.DecodeString(keyID)
						assert.Nil(mt, err, "base64 DecodeString error: %v", err)
						eo.SetKeyID(primitive.Binary{Subtype: 4, Data: keyIDBytes})
					case "altname":
						eo.SetKeyAltName(kms) // alt name for a key is the same as the KMS name
					default:
						mt.Fatalf("unrecognized identifier: %v", identifier)
					}

					// iterate over all elements in the document. copy elements directly, except for ones that need to
					// be encrypted, which should be copied after encryption.
					var nestedIdx int32
					nestedIdx, copied = bsoncore.AppendDocumentElementStart(copied, key)
					docElems, _ := doc.Elements()
					for _, de := range docElems {
						deKey := de.Key()
						deVal := de.Value()

						// element to encrypt has key "value"
						if deKey != "value" {
							copied = bsoncore.AppendValueElement(copied, deKey, rawValueToCoreValue(deVal))
							continue
						}

						encrypted, err := cpt.clientEnc.Encrypt(context.Background(), deVal, eo)
						if !doc.Lookup("allowed").Boolean() {
							// if allowed is false, encryption should error. in this case, the unencrypted value should be
							// copied over
							assert.NotNil(mt, err, "expected error encrypting value for key %v, got nil", key)
							copied = bsoncore.AppendValueElement(copied, deKey, rawValueToCoreValue(deVal))
							continue
						}

						// copy encrypted value
						assert.Nil(mt, err, "Encrypt error for key %v: %v", key, err)
						copied = bsoncore.AppendBinaryElement(copied, deKey, encrypted.Subtype, encrypted.Data)
					}
					copied, _ = bsoncore.AppendDocumentEnd(copied, nestedIdx)
				}
				copied, _ = bsoncore.AppendDocumentEnd(copied, cidx)

				// insert document with encrypted values
				_, err = cpt.cseColl.InsertOne(context.Background(), copied)
				assert.Nil(mt, err, "InsertOne error for corpus document: %v", err)

				// find document using client with encryption and assert it matches original
				decryptedDoc, err := cpt.cseColl.FindOne(context.Background(), bson.D{}).Raw()
				assert.Nil(mt, err, "Find error with encrypted client: %v", err)
				assert.Equal(mt, corpus, decryptedDoc, "expected document %v, got %v", corpus, decryptedDoc)

				// find document using a client without encryption enabled and assert fields remain encrypted
				corpusEncrypted := readJSONFile(mt, "corpus-encrypted.json")
				foundDoc, err := cpt.coll.FindOne(context.Background(), bson.D{}).Raw()
				assert.Nil(mt, err, "Find error with unencrypted client: %v", err)

				encryptedElems, _ := corpusEncrypted.Elements()
				for _, encryptedElem := range encryptedElems {
					// skip non-document fields
					encryptedDoc, ok := encryptedElem.Value().DocumentOK()
					if !ok {
						continue
					}

					allowed := encryptedDoc.Lookup("allowed").Boolean()
					expectedKey := encryptedElem.Key()
					expectedVal := encryptedDoc.Lookup("value")
					foundVal := foundDoc.Lookup(expectedKey).Document().Lookup("value")

					// for deterministic encryption, the value should be exactly equal
					// for random encryption, the value should not be equal if allowed is true
					algo := encryptedDoc.Lookup("algo").StringValue()
					switch algo {
					case "det":
						assert.True(mt, expectedVal.Equal(foundVal),
							"expected value %v for key %v, got %v", expectedVal, expectedKey, foundVal)
					case "rand":
						if allowed {
							assert.False(mt, expectedVal.Equal(foundVal),
								"expected values for key %v to be different but were %v", expectedKey, expectedVal)
						}
					}

					// if allowed is true, decrypt both values with clientEnc and validate equality
					if allowed {
						sub, data := expectedVal.Binary()
						expectedDecrypted, err := cpt.clientEnc.Decrypt(context.Background(), primitive.Binary{Subtype: sub, Data: data})
						assert.Nil(mt, err, "Decrypt error: %v", err)
						sub, data = foundVal.Binary()
						actualDecrypted, err := cpt.clientEnc.Decrypt(context.Background(), primitive.Binary{Subtype: sub, Data: data})
						assert.Nil(mt, err, "Decrypt error: %v", err)

						assert.True(mt, expectedDecrypted.Equal(actualDecrypted),
							"expected decrypted value %v for key %v, got %v", expectedDecrypted, expectedKey, actualDecrypted)
						continue
					}

					// if allowed is false, validate found value equals the original value in corpus
					corpusVal := corpus.Lookup(expectedKey).Document().Lookup("value")
					assert.True(mt, corpusVal.Equal(foundVal),
						"expected value %v for key %v, got %v", corpusVal, expectedKey, foundVal)
				}
			})
		}
	})
	mt.Run("7. custom endpoint", func(mt *mtest.T) {
		validKmsProviders := map[string]map[string]interface{}{
			"aws": {
				"accessKeyId":     awsAccessKeyID,
				"secretAccessKey": awsSecretAccessKey,
			},
			"azure": {
				"tenantId":                 azureTenantID,
				"clientId":                 azureClientID,
				"clientSecret":             azureClientSecret,
				"identityPlatformEndpoint": "login.microsoftonline.com:443",
			},
			"gcp": {
				"email":      gcpEmail,
				"privateKey": gcpPrivateKey,
				"endpoint":   "oauth2.googleapis.com:443",
			},
			"kmip": {
				"endpoint": "localhost:5698",
			},
		}

		tlsConfig := make(map[string]*tls.Config)
		if tlsCAFileKMIP != "" && tlsClientCertificateKeyFileKMIP != "" {
			tlsOpts := map[string]interface{}{
				"tlsCertificateKeyFile": tlsClientCertificateKeyFileKMIP,
				"tlsCAFile":             tlsCAFileKMIP,
			}
			kmipConfig, err := options.BuildTLSConfig(tlsOpts)
			assert.Nil(mt, err, "BuildTLSConfig error: %v", err)
			tlsConfig["kmip"] = kmipConfig
		}

		validClientEncryptionOptions := options.ClientEncryption().
			SetKmsProviders(validKmsProviders).
			SetKeyVaultNamespace(kvNamespace).
			SetTLSConfig(tlsConfig)

		invalidKmsProviders := map[string]map[string]interface{}{
			"azure": {
				"tenantId":                 azureTenantID,
				"clientId":                 azureClientID,
				"clientSecret":             azureClientSecret,
				"identityPlatformEndpoint": "doesnotexist.invalid:443",
			},
			"gcp": {
				"email":      gcpEmail,
				"privateKey": gcpPrivateKey,
				"endpoint":   "doesnotexist.invalid:443",
			},
			"kmip": {
				"endpoint": "doesnotexist.local:5698",
			},
		}

		invalidClientEncryptionOptions := options.ClientEncryption().
			SetKmsProviders(invalidKmsProviders).
			SetKeyVaultNamespace(kvNamespace).
			SetTLSConfig(tlsConfig)

		awsSuccessWithoutEndpoint := map[string]interface{}{
			"region": "us-east-1",
			"key":    "arn:aws:kms:us-east-1:579766882180:key/89fcc2c4-08b0-4bd9-9f25-e30687b580d0",
		}
		awsSuccessWithEndpoint := map[string]interface{}{
			"region":   "us-east-1",
			"key":      "arn:aws:kms:us-east-1:579766882180:key/89fcc2c4-08b0-4bd9-9f25-e30687b580d0",
			"endpoint": "kms.us-east-1.amazonaws.com",
		}
		awsSuccessWithHTTPSEndpoint := map[string]interface{}{
			"region":   "us-east-1",
			"key":      "arn:aws:kms:us-east-1:579766882180:key/89fcc2c4-08b0-4bd9-9f25-e30687b580d0",
			"endpoint": "kms.us-east-1.amazonaws.com:443",
		}
		awsFailureConnectionError := map[string]interface{}{
			"region":   "us-east-1",
			"key":      "arn:aws:kms:us-east-1:579766882180:key/89fcc2c4-08b0-4bd9-9f25-e30687b580d0",
			"endpoint": "kms.us-east-1.amazonaws.com:12345",
		}
		awsFailureInvalidEndpoint := map[string]interface{}{
			"region":   "us-east-1",
			"key":      "arn:aws:kms:us-east-1:579766882180:key/89fcc2c4-08b0-4bd9-9f25-e30687b580d0",
			"endpoint": "kms.us-east-2.amazonaws.com",
		}
		awsFailureParseError := map[string]interface{}{
			"region":   "us-east-1",
			"key":      "arn:aws:kms:us-east-1:579766882180:key/89fcc2c4-08b0-4bd9-9f25-e30687b580d0",
			"endpoint": "doesnotexist.invalid",
		}
		azure := map[string]interface{}{
			"keyVaultEndpoint": "key-vault-csfle.vault.azure.net",
			"keyName":          "key-name-csfle",
		}
		gcpSuccess := map[string]interface{}{
			"projectId": "devprod-drivers",
			"location":  "global",
			"keyRing":   "key-ring-csfle",
			"keyName":   "key-name-csfle",
			"endpoint":  "cloudkms.googleapis.com:443",
		}
		gcpFailure := map[string]interface{}{
			"projectId": "devprod-drivers",
			"location":  "global",
			"keyRing":   "key-ring-csfle",
			"keyName":   "key-name-csfle",
			"endpoint":  "doesnotexist.invalid:443",
		}
		kmipSuccessWithoutEndpoint := map[string]interface{}{
			"keyId": "1",
		}
		kmipSuccessWithEndpoint := map[string]interface{}{
			"keyId":    "1",
			"endpoint": "localhost:5698",
		}
		kmipFailureInvalidEndpoint := map[string]interface{}{
			"keyId":    "1",
			"endpoint": "doesnotexist.local:5698",
		}

		const (
			errConnectionRefused           = "connection refused"
			errInvalidKMSResponse          = "Invalid KMS response"
			errMongocryptError             = "mongocrypt error"
			errNoSuchHost                  = "no such host"
			errServerMisbehaving           = "server misbehaving"
			errWindowsTLSConnectionRefused = "No connection could be made because the target machine actively refused it"
		)

		testCases := []struct {
			name                                  string
			provider                              string
			masterKey                             interface{}
			errorSubstring                        []string
			testInvalidClientEncryption           bool
			invalidClientEncryptionErrorSubstring []string
		}{
			{
				name:                                  "Case 1: aws success without endpoint",
				provider:                              "aws",
				masterKey:                             awsSuccessWithoutEndpoint,
				errorSubstring:                        []string{},
				testInvalidClientEncryption:           false,
				invalidClientEncryptionErrorSubstring: []string{},
			},
			{
				name:                                  "Case 2: aws success with endpoint",
				provider:                              "aws",
				masterKey:                             awsSuccessWithEndpoint,
				errorSubstring:                        []string{},
				testInvalidClientEncryption:           false,
				invalidClientEncryptionErrorSubstring: []string{},
			},
			{
				name:                                  "Case 3: aws success with https endpoint",
				provider:                              "aws",
				masterKey:                             awsSuccessWithHTTPSEndpoint,
				errorSubstring:                        []string{},
				testInvalidClientEncryption:           false,
				invalidClientEncryptionErrorSubstring: []string{},
			},
			{
				name:                                  "Case 4: aws failure with connection error",
				provider:                              "aws",
				masterKey:                             awsFailureConnectionError,
				errorSubstring:                        []string{errConnectionRefused, errWindowsTLSConnectionRefused},
				testInvalidClientEncryption:           false,
				invalidClientEncryptionErrorSubstring: []string{},
			},
			{
				name:                                  "Case 5: aws failure with wrong endpoint",
				provider:                              "aws",
				masterKey:                             awsFailureInvalidEndpoint,
				errorSubstring:                        []string{errMongocryptError},
				testInvalidClientEncryption:           false,
				invalidClientEncryptionErrorSubstring: []string{},
			},
			{
				name:                                  "Case 6: aws failure with parse error",
				provider:                              "aws",
				masterKey:                             awsFailureParseError,
				errorSubstring:                        []string{errNoSuchHost, errServerMisbehaving},
				testInvalidClientEncryption:           false,
				invalidClientEncryptionErrorSubstring: []string{},
			},
			{
				name:                                  "Case 7: azure success",
				provider:                              "azure",
				masterKey:                             azure,
				errorSubstring:                        []string{},
				testInvalidClientEncryption:           true,
				invalidClientEncryptionErrorSubstring: []string{errNoSuchHost, errServerMisbehaving},
			},
			{
				name:                                  "Case 8: gcp success",
				provider:                              "gcp",
				masterKey:                             gcpSuccess,
				errorSubstring:                        []string{},
				testInvalidClientEncryption:           true,
				invalidClientEncryptionErrorSubstring: []string{errNoSuchHost, errServerMisbehaving},
			},
			{
				name:                                  "Case 9: gcp failure",
				provider:                              "gcp",
				masterKey:                             gcpFailure,
				errorSubstring:                        []string{errInvalidKMSResponse},
				testInvalidClientEncryption:           false,
				invalidClientEncryptionErrorSubstring: []string{},
			},
			{
				name:                                  "Case 10: kmip success without endpoint",
				provider:                              "kmip",
				masterKey:                             kmipSuccessWithoutEndpoint,
				errorSubstring:                        []string{},
				testInvalidClientEncryption:           true,
				invalidClientEncryptionErrorSubstring: []string{errNoSuchHost, errServerMisbehaving},
			},
			{
				name:                                  "Case 11: kmip success with endpoint",
				provider:                              "kmip",
				masterKey:                             kmipSuccessWithEndpoint,
				errorSubstring:                        []string{},
				testInvalidClientEncryption:           false,
				invalidClientEncryptionErrorSubstring: []string{},
			},
			{
				name:                                  "Case 12: kmip failure with invalid endpoint",
				provider:                              "kmip",
				masterKey:                             kmipFailureInvalidEndpoint,
				errorSubstring:                        []string{errNoSuchHost, errServerMisbehaving},
				testInvalidClientEncryption:           false,
				invalidClientEncryptionErrorSubstring: []string{},
			},
		}
		for _, tc := range testCases {
			mt.Run(tc.name, func(mt *mtest.T) {
				if strings.Contains(tc.name, "kmip") && "" == os.Getenv("KMS_MOCK_SERVERS_RUNNING") {
					mt.Skipf("Skipping test as KMS_MOCK_SERVERS_RUNNING is not set")
				}
				cpt := setup(mt, nil, defaultKvClientOptions, validClientEncryptionOptions)
				defer cpt.teardown(mt)

				dkOpts := options.DataKey().SetMasterKey(tc.masterKey)
				createdKey, err := cpt.clientEnc.CreateDataKey(context.Background(), tc.provider, dkOpts)
				if len(tc.errorSubstring) > 0 {
					assert.NotNil(mt, err, "expected error, got nil")

					assert.True(t, containsSubstring(tc.errorSubstring, err.Error()),
						"expected tc.errorSubstring=%v to contain %v, but it didn't", tc.errorSubstring, err.Error())

					return
				}
				assert.Nil(mt, err, "CreateDataKey error: %v", err)

				encOpts := options.Encrypt().SetKeyID(createdKey).SetAlgorithm(deterministicAlgorithm)
				testVal := bson.RawValue{
					Type:  bson.TypeString,
					Value: bsoncore.AppendString(nil, "test"),
				}
				encrypted, err := cpt.clientEnc.Encrypt(context.Background(), testVal, encOpts)
				assert.Nil(mt, err, "Encrypt error: %v", err)
				decrypted, err := cpt.clientEnc.Decrypt(context.Background(), encrypted)
				assert.Nil(mt, err, "Decrypt error: %v", err)
				assert.Equal(mt, testVal, decrypted, "expected value %s, got %s", testVal, decrypted)

				if !tc.testInvalidClientEncryption {
					return
				}

				invalidClientEncryption, err := mongo.NewClientEncryption(cpt.kvClient, invalidClientEncryptionOptions)
				assert.Nil(mt, err, "error creating invalidClientEncryption object: %v", err)
				defer invalidClientEncryption.Close(context.Background())

				invalidKeyOpts := options.DataKey().SetMasterKey(tc.masterKey)
				_, err = invalidClientEncryption.CreateDataKey(context.Background(), tc.provider, invalidKeyOpts)
				assert.NotNil(mt, err, "expected CreateDataKey error, got nil")

				assert.True(t, containsSubstring(tc.invalidClientEncryptionErrorSubstring, err.Error()),
					"expected tc.invalidClientEncryptionErrorSubstring=%v to contain %v, but it didn't",
					tc.invalidClientEncryptionErrorSubstring, err.Error())
			})
		}
	})
	mt.RunOpts("8. bypass mongocryptd spawning", noClientOpts, func(mt *mtest.T) {
		mt.Parallel()

		kmsProviders := map[string]map[string]interface{}{
			"local": {
				"key": localMasterKey,
			},
		}
		schemaMap := map[string]interface{}{
			"db.coll": readJSONFile(mt, "external-schema.json"),
		}

		// All mongocryptd options use port 27021 instead of the default 27020 to avoid interference
		// with mongocryptd instances spawned by previous tests. Explicitly disable loading the
		// crypt_shared library to make sure we're testing mongocryptd spawning behavior that is not
		// influenced by loading the crypt_shared library.
		mongocryptdBypassSpawnTrue := map[string]interface{}{
			"mongocryptdBypassSpawn":              true,
			"mongocryptdURI":                      "mongodb://localhost:27021/db?serverSelectionTimeoutMS=1000",
			"mongocryptdSpawnArgs":                []string{"--pidfilepath=bypass-spawning-mongocryptd.pid", "--port=27021"},
			"__cryptSharedLibDisabledForTestOnly": true, // Disable loading the crypt_shared library.
		}
		mongocryptdBypassSpawnFalse := map[string]interface{}{
			"mongocryptdBypassSpawn":              false,
			"mongocryptdSpawnArgs":                []string{"--pidfilepath=bypass-spawning-mongocryptd.pid", "--port=27021"},
			"__cryptSharedLibDisabledForTestOnly": true, // Disable loading the crypt_shared library.
		}
		mongocryptdBypassSpawnNotSet := map[string]interface{}{
			"mongocryptdSpawnArgs":                []string{"--pidfilepath=bypass-spawning-mongocryptd.pid", "--port=27021"},
			"__cryptSharedLibDisabledForTestOnly": true, // Disable loading the crypt_shared library.
		}

		testCases := []struct {
			name                    string
			mongocryptdOpts         map[string]interface{}
			setBypassAutoEncryption bool
			bypassAutoEncryption    bool
			bypassQueryAnalysis     bool
			useSharedLib            bool
		}{
			{
				name:            "mongocryptdBypassSpawn only",
				mongocryptdOpts: mongocryptdBypassSpawnTrue,
			},
			{
				name:                    "bypassAutoEncryption only",
				mongocryptdOpts:         mongocryptdBypassSpawnNotSet,
				setBypassAutoEncryption: true,
				bypassAutoEncryption:    true,
			},
			{
				name:                    "mongocryptdBypassSpawn false, bypassAutoEncryption true",
				mongocryptdOpts:         mongocryptdBypassSpawnFalse,
				setBypassAutoEncryption: true,
				bypassAutoEncryption:    true,
			},
			{
				name:                    "mongocryptdBypassSpawn true, bypassAutoEncryption false",
				mongocryptdOpts:         mongocryptdBypassSpawnTrue,
				setBypassAutoEncryption: true,
				bypassAutoEncryption:    false,
			},
			{
				name:                "bypassQueryAnalysis only",
				mongocryptdOpts:     mongocryptdBypassSpawnNotSet,
				bypassQueryAnalysis: true,
			},
			{
				name:         "use shared library",
				useSharedLib: true,
				mongocryptdOpts: map[string]interface{}{
					"mongocryptdURI":       "mongodb://localhost:27021/db?serverSelectionTimeoutMS=1000",
					"mongocryptdSpawnArgs": []string{"--pidfilepath=bypass-spawning-mongocryptd.pid", "--port=27021"},
					"cryptSharedLibPath":   os.Getenv("CRYPT_SHARED_LIB_PATH"),
					"cryptSharedRequired":  true,
				},
			},
		}
		for _, tc := range testCases {
			mt.Run(tc.name, func(mt *mtest.T) {
				if tc.useSharedLib && os.Getenv("CRYPT_SHARED_LIB_PATH") == "" {
					mt.Skip("CRYPT_SHARED_LIB_PATH not set, skipping")
					return
				}
				aeo := options.AutoEncryption().
					SetKmsProviders(kmsProviders).
					SetKeyVaultNamespace(kvNamespace).
					SetSchemaMap(schemaMap).
					SetExtraOptions(tc.mongocryptdOpts)
				if tc.setBypassAutoEncryption {
					aeo.SetBypassAutoEncryption(tc.bypassAutoEncryption)
				}
				aeo.SetBypassQueryAnalysis(tc.bypassQueryAnalysis)
				cpt := setup(mt, aeo, nil, nil)
				defer cpt.teardown(mt)

				_, err := cpt.cseColl.InsertOne(context.Background(), bson.D{{"unencrypted", "test"}})

				// Check for mongocryptd server selection error if auto encryption needed mongocryptd.
				if !(tc.setBypassAutoEncryption && tc.bypassAutoEncryption) && !tc.bypassQueryAnalysis && !tc.useSharedLib {
					assert.NotNil(mt, err, "expected InsertOne error, got nil")
					mcryptErr, ok := err.(mongo.MongocryptdError)
					assert.True(mt, ok, "expected error type %T, got %v of type %T", mongo.MongocryptdError{}, err, err)
					assert.True(mt, strings.Contains(mcryptErr.Error(), "server selection error"),
						"expected mongocryptd server selection error, got %v", err)
					return
				}

				// If mongocryptd was not needed, the command should succeed. Create a new client to connect to
				// mongocryptd and verify it is not running.
				assert.Nil(mt, err, "InsertOne error: %v", err)

				mcryptOpts := options.Client().ApplyURI("mongodb://localhost:27021").
					SetServerSelectionTimeout(1 * time.Second)
				integtest.AddTestServerAPIVersion(mcryptOpts)
				mcryptClient, err := mongo.Connect(context.Background(), mcryptOpts)
				assert.Nil(mt, err, "mongocryptd Connect error: %v", err)

				err = mcryptClient.Database("admin").RunCommand(context.Background(), bson.D{{handshake.LegacyHelloLowercase, 1}}).Err()
				assert.NotNil(mt, err, "expected mongocryptd legacy hello error, got nil")
				assert.True(mt, strings.Contains(err.Error(), "server selection error"),
					"expected mongocryptd server selection error, got %v", err)
			})
		}
	})
	changeStreamOpts := mtest.NewOptions().
		CreateClient(false).
		Topologies(mtest.ReplicaSet)
	mt.RunOpts("change streams", changeStreamOpts, func(mt *mtest.T) {
		// Change streams can't easily fit into the spec test format because of their tailable nature, so there are two
		// prose tests for them instead:
		//
		// 1. Auto-encryption errors for Watch operations. Collection-level change streams error because the
		// $changeStream aggregation stage is not valid for encryption. Client and database-level streams error because
		// only collection-level operations are valid for encryption.
		//
		// 2. Events are automatically decrypted: If the Watch() is done with BypassAutoEncryption=true, the Watch
		// should succeed and subsequent getMore calls should decrypt documents when necessary.

		var testConfig struct {
			JSONSchema        bson.Raw   `bson:"json_schema"`
			KeyVaultData      []bson.Raw `bson:"key_vault_data"`
			EncryptedDocument bson.Raw   `bson:"encrypted_document"`
			DecryptedDocument bson.Raw   `bson:"decrytped_document"`
		}
		decodeJSONFile(mt, "change-streams-test.json", &testConfig)

		schemaMap := map[string]interface{}{
			"db.coll": testConfig.JSONSchema,
		}
		kmsProviders := map[string]map[string]interface{}{
			"aws": {
				"accessKeyId":     awsAccessKeyID,
				"secretAccessKey": awsSecretAccessKey,
			},
		}

		testCases := []struct {
			name       string
			streamType mongo.StreamType
		}{
			{"client", mongo.ClientStream},
			{"database", mongo.DatabaseStream},
			{"collection", mongo.CollectionStream},
		}
		mt.RunOpts("auto encryption errors", noClientOpts, func(mt *mtest.T) {
			mt.Parallel()

			for _, tc := range testCases {
				mt.Run(tc.name, func(mt *mtest.T) {
					autoEncryptionOpts := options.AutoEncryption().
						SetKmsProviders(kmsProviders).
						SetKeyVaultNamespace(kvNamespace).
						SetSchemaMap(schemaMap).
						SetExtraOptions(getCryptSharedLibExtraOptions())
					cpt := setup(mt, autoEncryptionOpts, nil, nil)
					defer cpt.teardown(mt)

					_, err := getWatcher(mt, tc.streamType, cpt).Watch(context.Background(), mongo.Pipeline{})
					assert.NotNil(mt, err, "expected Watch error: %v", err)
				})
			}
		})
		mt.RunOpts("events are automatically decrypted", noClientOpts, func(mt *mtest.T) {
			for _, tc := range testCases {
				mt.Run(tc.name, func(mt *mtest.T) {
					autoEncryptionOpts := options.AutoEncryption().
						SetKmsProviders(kmsProviders).
						SetKeyVaultNamespace(kvNamespace).
						SetSchemaMap(schemaMap).
						SetBypassAutoEncryption(true)
					cpt := setup(mt, autoEncryptionOpts, nil, nil)
					defer cpt.teardown(mt)

					// Insert key vault data so the key can be accessed when starting the change stream.
					insertDocuments(mt, cpt.keyVaultColl, testConfig.KeyVaultData)

					stream, err := getWatcher(mt, tc.streamType, cpt).Watch(context.Background(), mongo.Pipeline{})
					assert.Nil(mt, err, "Watch error: %v", err)
					defer stream.Close(context.Background())

					// Insert already encrypted data and verify that it is automatically decrypted by Next().
					insertDocuments(mt, cpt.coll, []bson.Raw{testConfig.EncryptedDocument})
					assert.True(mt, stream.Next(context.Background()), "expected Next to return true, got false")
					gotValue, err := stream.Current.LookupErr("fullDocument")
					assert.Nil(mt, err, "did not find fullDocument in stream.Current: %v", stream.Current)
					gotDocument := gotValue.Document()
					err = compareDocs(mt, testConfig.DecryptedDocument, gotDocument)
					assert.Nil(mt, err, "compareDocs error: %v", err)
				})
			}
		})
	})
	mt.RunOpts("9. deadlock tests", noClientOpts, func(mt *mtest.T) {
		testcases := []struct {
			description                            string
			maxPoolSize                            uint64
			bypassAutoEncryption                   bool
			keyVaultClientSet                      bool
			clientEncryptedTopologyOpeningExpected int
			clientEncryptedCommandStartedExpected  []startedEvent
			clientKeyVaultCommandStartedExpected   []startedEvent
		}{
			// In the following comments, "special auto encryption options" refers to the "bypassAutoEncryption" and
			// "keyVaultClient" options
			{
				// If the client has a limited maxPoolSize, and no special auto-encryption options are set, the
				// driver should create an internal Client for metadata/keyVault operations.
				"deadlock case 1", 1, false, false, 2,
				[]startedEvent{{"listCollections", "db"}, {"find", "keyvault"}, {"insert", "db"}, {"find", "db"}},
				nil,
			},
			{
				// If the client has a limited maxPoolSize, and a keyVaultClient is set, the driver should create
				// an internal Client for metadata operations.
				"deadlock case 2", 1, false, true, 2,
				[]startedEvent{{"listCollections", "db"}, {"insert", "db"}, {"find", "db"}},
				[]startedEvent{{"find", "keyvault"}},
			},
			{
				// If the client has a limited maxPoolSize, and a bypassAutomaticEncryption=true, the driver should
				// create an internal Client for keyVault operations.
				"deadlock case 3", 1, true, false, 2,
				[]startedEvent{{"find", "db"}, {"find", "keyvault"}},
				nil,
			},
			{
				// If the client has a limited maxPoolSize, bypassAutomaticEncryption=true, and a keyVaultClient is set,
				// the driver should not create an internal Client.
				"deadlock case 4", 1, true, true, 1,
				[]startedEvent{{"find", "db"}},
				[]startedEvent{{"find", "keyvault"}},
			},
			{
				// If the client has an unlimited maxPoolSize, and no special auto-encryption options are set,  the
				// driver should reuse the client for metadata/keyVault operations
				"deadlock case 5", 0, false, false, 1,
				[]startedEvent{{"listCollections", "db"}, {"listCollections", "keyvault"}, {"find", "keyvault"}, {"insert", "db"}, {"find", "db"}},
				nil,
			},
			{
				// If the client has an unlimited maxPoolSize, and a keyVaultClient is set, the driver should reuse the
				// client for metadata operations.
				"deadlock case 6", 0, false, true, 1,
				[]startedEvent{{"listCollections", "db"}, {"insert", "db"}, {"find", "db"}},
				[]startedEvent{{"find", "keyvault"}},
			},
			{
				// If the client has an unlimited maxPoolSize, and bypassAutomaticEncryption=true, the driver should
				// reuse the client for keyVault operations
				"deadlock case 7", 0, true, false, 1,
				[]startedEvent{{"find", "db"}, {"find", "keyvault"}},
				nil,
			},
			{
				// If the client has an unlimited maxPoolSize, bypassAutomaticEncryption=true, and a keyVaultClient is
				// set, the driver should not create an internal Client.
				"deadlock case 8", 0, true, true, 1,
				[]startedEvent{{"find", "db"}},
				[]startedEvent{{"find", "keyvault"}},
			},
		}

		for _, tc := range testcases {
			mt.Run(tc.description, func(mt *mtest.T) {
				var clientEncryptedEvents []startedEvent
				var clientEncryptedTopologyOpening int

				d := newDeadlockTest(mt)
				defer d.disconnect(mt)

				kmsProviders := map[string]map[string]interface{}{
					"local": {"key": localMasterKey},
				}
				aeOpts := options.AutoEncryption()
				aeOpts.SetKeyVaultNamespace("keyvault.datakeys").
					SetKmsProviders(kmsProviders).
					SetBypassAutoEncryption(tc.bypassAutoEncryption)

				// Only set the crypt_shared library extra options if bypassAutoEncryption isn't
				// true because it's invalid to set cryptSharedLibRequired=true and
				// bypassAutoEncryption=true together.
				if !tc.bypassAutoEncryption {
					aeOpts.SetExtraOptions(getCryptSharedLibExtraOptions())
				}

				if tc.keyVaultClientSet {
					integtest.AddTestServerAPIVersion(d.clientKeyVaultOpts)
					aeOpts.SetKeyVaultClientOptions(d.clientKeyVaultOpts)
				}

				ceOpts := options.Client().ApplyURI(mtest.ClusterURI()).
					SetMonitor(&event.CommandMonitor{
						Started: func(ctx context.Context, event *event.CommandStartedEvent) {
							clientEncryptedEvents = append(clientEncryptedEvents, startedEvent{event.CommandName, event.DatabaseName})
						},
					}).
					SetServerMonitor(&event.ServerMonitor{
						TopologyOpening: func(event *event.TopologyOpeningEvent) {
							clientEncryptedTopologyOpening++
						},
					}).
					SetMaxPoolSize(tc.maxPoolSize).
					SetAutoEncryptionOptions(aeOpts)

				integtest.AddTestServerAPIVersion(ceOpts)
				clientEncrypted, err := mongo.Connect(context.Background(), ceOpts)
				assert.Nil(mt, err, "Connect error: %v", err)
				defer clientEncrypted.Disconnect(context.Background())

				coll := clientEncrypted.Database("db").Collection("coll")
				if !tc.bypassAutoEncryption {
					_, err = coll.InsertOne(context.Background(), bson.M{"_id": 0, "encrypted": "string0"})
				} else {
					unencryptedColl := d.clientTest.Database("db").Collection("coll")
					_, err = unencryptedColl.InsertOne(context.Background(), bson.M{"_id": 0, "encrypted": d.ciphertext})
				}
				assert.Nil(mt, err, "InsertOne error: %v", err)

				raw, err := coll.FindOne(context.Background(), bson.M{"_id": 0}).Raw()
				assert.Nil(mt, err, "FindOne error: %v", err)

				expected := bsoncore.NewDocumentBuilder().
					AppendInt32("_id", 0).
					AppendString("encrypted", "string0").
					Build()
				assert.Equal(mt, bson.Raw(expected), raw, "returned value unequal, expected: %v, got: %v", expected, raw)

				assert.Equal(mt, clientEncryptedEvents, tc.clientEncryptedCommandStartedExpected, "mismatched events for clientEncrypted. Expected %v, got %v", clientEncryptedEvents, tc.clientEncryptedCommandStartedExpected)
				assert.Equal(mt, d.clientKeyVaultEvents, tc.clientKeyVaultCommandStartedExpected, "mismatched events for clientKeyVault. Expected %v, got %v", d.clientKeyVaultEvents, tc.clientKeyVaultCommandStartedExpected)
				assert.Equal(mt, clientEncryptedTopologyOpening, tc.clientEncryptedTopologyOpeningExpected, "wrong number of TopologyOpening events. Expected %v, got %v", tc.clientEncryptedTopologyOpeningExpected, clientEncryptedTopologyOpening)
			})
		}
	})

	// These tests only run when 3 KMS HTTP servers and 1 KMS KMIP server are running. See specification for port numbers and necessary arguments:
	// https://github.com/mongodb/specifications/blob/master/source/client-side-encryption/tests/README.rst#kms-tls-options-tests
	mt.RunOpts("10. kms tls tests", noClientOpts, func(mt *mtest.T) {
		kmsTlsTestcase := os.Getenv("KMS_TLS_TESTCASE")
		if kmsTlsTestcase == "" {
			mt.Skipf("Skipping test as KMS_TLS_TESTCASE is not set")
		}

		testcases := []struct {
			name       string
			port       int
			envValue   string
			errMessage string
		}{
			{
				"invalid certificate",
				9000,
				"INVALID_CERT",
				"expired",
			},
			{
				"invalid hostname",
				9001,
				"INVALID_HOSTNAME",
				"SANs",
			},
		}

		for _, tc := range testcases {
			mt.Run(tc.name, func(mt *mtest.T) {
				// Only run test if correct KMS mock server is running.
				if kmsTlsTestcase != tc.envValue {
					mt.Skipf("Skipping test as KMS_TLS_TESTCASE is set to %q, expected %v", kmsTlsTestcase, tc.envValue)
				}

				ceo := options.ClientEncryption().
					SetKmsProviders(fullKmsProvidersMap).
					SetKeyVaultNamespace(kvNamespace)
				cpt := setup(mt, nil, nil, ceo)
				defer cpt.teardown(mt)

				_, err := cpt.clientEnc.CreateDataKey(context.Background(), "aws", options.DataKey().SetMasterKey(
					bson.D{
						{"region", "us-east-1"},
						{"key", "arn:aws:kms:us-east-1:579766882180:key/89fcc2c4-08b0-4bd9-9f25-e30687b580d0"},
						{"endpoint", fmt.Sprintf("127.0.0.1:%d", tc.port)},
					},
				))
				assert.NotNil(mt, err, "expected CreateDataKey error, got nil")
				assert.True(mt, strings.Contains(err.Error(), tc.errMessage),
					"expected CreateDataKey error to contain %v, got %v", tc.errMessage, err.Error())
			})
		}
	})

	// These tests only run when 3 KMS HTTP servers and 1 KMS KMIP server are running. See specification for port numbers and necessary arguments:
	// https://github.com/mongodb/specifications/blob/master/source/client-side-encryption/tests/README.rst#kms-tls-options-tests
	mt.RunOpts("11. kms tls options tests", noClientOpts, func(mt *mtest.T) {
		if os.Getenv("KMS_MOCK_SERVERS_RUNNING") == "" {
			mt.Skipf("Skipping test as KMS_MOCK_SERVERS_RUNNING is not set")
		}
		validKmsProviders := map[string]map[string]interface{}{
			"aws": {
				"accessKeyId":     awsAccessKeyID,
				"secretAccessKey": awsSecretAccessKey,
			},
			"azure": {
				"tenantId":                 azureTenantID,
				"clientId":                 azureClientID,
				"clientSecret":             azureClientSecret,
				"identityPlatformEndpoint": "127.0.0.1:9002",
			},
			"gcp": {
				"email":      gcpEmail,
				"privateKey": gcpPrivateKey,
				"endpoint":   "127.0.0.1:9002",
			},
			"kmip": {
				"endpoint": "127.0.0.1:5698",
			},
		}

		expiredKmsProviders := map[string]map[string]interface{}{
			"aws": {
				"accessKeyId":     awsAccessKeyID,
				"secretAccessKey": awsSecretAccessKey,
			},
			"azure": {
				"tenantId":                 azureTenantID,
				"clientId":                 azureClientID,
				"clientSecret":             azureClientSecret,
				"identityPlatformEndpoint": "127.0.0.1:9000",
			},
			"gcp": {
				"email":      gcpEmail,
				"privateKey": gcpPrivateKey,
				"endpoint":   "127.0.0.1:9000",
			},
			"kmip": {
				"endpoint": "127.0.0.1:9000",
			},
		}

		invalidKmsProviders := map[string]map[string]interface{}{
			"aws": {
				"accessKeyId":     awsAccessKeyID,
				"secretAccessKey": awsSecretAccessKey,
			},
			"azure": {
				"tenantId":                 azureTenantID,
				"clientId":                 azureClientID,
				"clientSecret":             azureClientSecret,
				"identityPlatformEndpoint": "127.0.0.1:9001",
			},
			"gcp": {
				"email":      gcpEmail,
				"privateKey": gcpPrivateKey,
				"endpoint":   "127.0.0.1:9001",
			},
			"kmip": {
				"endpoint": "127.0.0.1:9001",
			},
		}

		// create valid Client Encryption options without a client certificate
		validClientEncryptionOptionsWithoutClientCert := options.ClientEncryption().
			SetKmsProviders(validKmsProviders).
			SetKeyVaultNamespace(kvNamespace)

		// make TLS opts containing client certificate and CA file
		tlsConfig := make(map[string]*tls.Config)
		if tlsCAFileKMIP != "" && tlsClientCertificateKeyFileKMIP != "" {
			clientAndCATlsMap := map[string]interface{}{
				"tlsCertificateKeyFile": tlsClientCertificateKeyFileKMIP,
				"tlsCAFile":             tlsCAFileKMIP,
			}
			certConfig, err := options.BuildTLSConfig(clientAndCATlsMap)
			assert.Nil(mt, err, "BuildTLSConfig error: %v", err)
			tlsConfig["aws"] = certConfig
			tlsConfig["azure"] = certConfig
			tlsConfig["gcp"] = certConfig
			tlsConfig["kmip"] = certConfig
		}

		// create valid Client Encryption options and set valid TLS options
		validClientEncryptionOptionsWithTLS := options.ClientEncryption().
			SetKmsProviders(validKmsProviders).
			SetKeyVaultNamespace(kvNamespace).
			SetTLSConfig(tlsConfig)

		// make TLS opts containing only CA file
		if tlsCAFileKMIP != "" {
			caTlsMap := map[string]interface{}{
				"tlsCAFile": tlsCAFileKMIP,
			}
			certConfig, err := options.BuildTLSConfig(caTlsMap)
			assert.Nil(mt, err, "BuildTLSConfig error: %v", err)
			tlsConfig["aws"] = certConfig
			tlsConfig["azure"] = certConfig
			tlsConfig["gcp"] = certConfig
			tlsConfig["kmip"] = certConfig
		}

		// create invalid Client Encryption options with expired credentials
		expiredClientEncryptionOptions := options.ClientEncryption().
			SetKmsProviders(expiredKmsProviders).
			SetKeyVaultNamespace(kvNamespace).
			SetTLSConfig(tlsConfig)

		// create invalid Client Encryption options with invalid hostnames
		invalidHostnameClientEncryptionOptions := options.ClientEncryption().
			SetKmsProviders(invalidKmsProviders).
			SetKeyVaultNamespace(kvNamespace).
			SetTLSConfig(tlsConfig)

		awsMasterKeyNoClientCert := map[string]interface{}{
			"region":   "us-east-1",
			"key":      "arn:aws:kms:us-east-1:579766882180:key/89fcc2c4-08b0-4bd9-9f25-e30687b580d0",
			"endpoint": "127.0.0.1:9002",
		}
		awsMasterKeyWithTLS := map[string]interface{}{
			"region":   "us-east-1",
			"key":      "arn:aws:kms:us-east-1:579766882180:key/89fcc2c4-08b0-4bd9-9f25-e30687b580d0",
			"endpoint": "127.0.0.1:9002",
		}
		awsMasterKeyExpired := map[string]interface{}{
			"region":   "us-east-1",
			"key":      "arn:aws:kms:us-east-1:579766882180:key/89fcc2c4-08b0-4bd9-9f25-e30687b580d0",
			"endpoint": "127.0.0.1:9000",
		}
		awsMasterKeyInvalidHostname := map[string]interface{}{
			"region":   "us-east-1",
			"key":      "arn:aws:kms:us-east-1:579766882180:key/89fcc2c4-08b0-4bd9-9f25-e30687b580d0",
			"endpoint": "127.0.0.1:9001",
		}
		azureMasterKey := map[string]interface{}{
			"keyVaultEndpoint": "doesnotexist.local",
			"keyName":          "foo",
		}
		gcpMasterKey := map[string]interface{}{
			"projectId": "foo",
			"location":  "bar",
			"keyRing":   "baz",
			"keyName":   "foo",
		}
		kmipMasterKey := map[string]interface{}{}

		testCases := []struct {
			name                     string
			masterKeyNoClientCert    interface{}
			masterKeyWithTLS         interface{}
			masterKeyExpired         interface{}
			masterKeyInvalidHostname interface{}
			tlsError                 string
			expiredError             string
			invalidHostnameError     string
		}{
			{"aws", awsMasterKeyNoClientCert, awsMasterKeyWithTLS, awsMasterKeyExpired, awsMasterKeyInvalidHostname, "parse error", "certificate has expired", "cannot validate certificate"},
			{"azure", azureMasterKey, azureMasterKey, azureMasterKey, azureMasterKey, "HTTP status=404", "certificate has expired", "cannot validate certificate"},
			{"gcp", gcpMasterKey, gcpMasterKey, gcpMasterKey, gcpMasterKey, "HTTP status=404", "certificate has expired", "cannot validate certificate"},
			{"kmip", kmipMasterKey, kmipMasterKey, kmipMasterKey, kmipMasterKey, "", "certificate has expired", "cannot validate certificate"},
		}

		for _, tc := range testCases {
			mt.Run(tc.name, func(mt *mtest.T) {
				if tc.name == "kmip" && "" == os.Getenv("KMS_MOCK_SERVERS_RUNNING") {
					mt.Skipf("Skipping test as KMS_MOCK_SERVERS_RUNNING is not set")
				}
				// call CreateDataKey with CEO no TLS with each provider and corresponding master key
				cpt := setup(mt, nil, defaultKvClientOptions, validClientEncryptionOptionsWithoutClientCert)
				defer cpt.teardown(mt)

				dkOpts := options.DataKey().SetMasterKey(tc.masterKeyNoClientCert)
				_, err := cpt.clientEnc.CreateDataKey(context.Background(), tc.name, dkOpts)

				assert.NotNil(mt, err, "expected error, got nil")

				possibleErrors := []string{
					"x509: certificate signed by unknown authority",                   // Windows
					"x509: “valid.testing.golang.invalid” certificate is not trusted", // MacOS
					"x509: certificate is not authorized to sign other certificates",  // All others
				}

				assert.True(t, containsSubstring(possibleErrors, err.Error()),
					"expected possibleErrors=%v to contain %v, but it didn't",
					possibleErrors, err.Error())

				// call CreateDataKey with CEO & TLS with each provider and corresponding master key
				cpt = setup(mt, nil, defaultKvClientOptions, validClientEncryptionOptionsWithTLS)

				dkOpts = options.DataKey().SetMasterKey(tc.masterKeyWithTLS)
				_, err = cpt.clientEnc.CreateDataKey(context.Background(), tc.name, dkOpts)
				// check if current test case is KMIP, which should pass
				if tc.name == "kmip" {
					assert.Nil(mt, err, "expected no error, got err: %v", err)
				} else {
					assert.NotNil(mt, err, "expected error, got nil")
					assert.True(mt, strings.Contains(err.Error(), tc.tlsError),
						"expected error '%s' to contain '%s'", err.Error(), tc.tlsError)
				}

				// call CreateDataKey with expired CEO each provider and same masterKey
				cpt = setup(mt, nil, defaultKvClientOptions, expiredClientEncryptionOptions)

				dkOpts = options.DataKey().SetMasterKey(tc.masterKeyExpired)
				_, err = cpt.clientEnc.CreateDataKey(context.Background(), tc.name, dkOpts)
				assert.NotNil(mt, err, "expected error, got nil")
				assert.True(mt, strings.Contains(err.Error(), tc.expiredError),
					"expected error '%s' to contain '%s'", err.Error(), tc.expiredError)

				// call CreateDataKey with invalid hostname CEO with each provider and same masterKey
				cpt = setup(mt, nil, defaultKvClientOptions, invalidHostnameClientEncryptionOptions)

				dkOpts = options.DataKey().SetMasterKey(tc.masterKeyInvalidHostname)
				_, err = cpt.clientEnc.CreateDataKey(context.Background(), tc.name, dkOpts)
				assert.NotNil(mt, err, "expected error, got nil")
				assert.True(mt, strings.Contains(err.Error(), tc.invalidHostnameError),
					"expected error '%s' to contain '%s'", err.Error(), tc.invalidHostnameError)
			})
		}
	})
	runOpts := mtest.NewOptions().MinServerVersion("7.0").Topologies(mtest.ReplicaSet, mtest.LoadBalanced, mtest.ShardedReplicaSet)
	// Only test MongoDB Server 7.0+. MongoDB Server 7.0 introduced a backwards breaking change to the Queryable Encryption (QE) protocol: QEv2.
	// libmongocrypt is configured to use the QEv2 protocol.
	mt.RunOpts("12. explicit encryption", runOpts, func(mt *mtest.T) {
		// Test Setup ... begin
		encryptedFields := readJSONFile(mt, "encrypted-fields.json")
		key1Document := readJSONFile(mt, "key1-document.json")
		var key1ID primitive.Binary
		{
			subtype, data := key1Document.Lookup("_id").Binary()
			key1ID = primitive.Binary{Subtype: subtype, Data: data}
		}

		testSetup := func() (*mongo.Client, *mongo.ClientEncryption) {
			mtest.DropEncryptedCollection(mt, mt.Client.Database("db").Collection("explicit_encryption"), encryptedFields)
			cco := options.CreateCollection().SetEncryptedFields(encryptedFields)
			err := mt.Client.Database("db").CreateCollection(context.Background(), "explicit_encryption", cco)
			assert.Nil(mt, err, "error on CreateCollection: %v", err)
			err = mt.Client.Database("keyvault").Collection("datakeys").Drop(context.Background())
			assert.Nil(mt, err, "error on Drop: %v", err)
			keyVaultClient, err := mongo.Connect(context.Background(), options.Client().ApplyURI(mtest.ClusterURI()))
			assert.Nil(mt, err, "error on Connect: %v", err)
			datakeysColl := keyVaultClient.Database("keyvault").Collection("datakeys", options.Collection().SetWriteConcern(mtest.MajorityWc))
			_, err = datakeysColl.InsertOne(context.Background(), key1Document)
			assert.Nil(mt, err, "error on InsertOne: %v", err)
			// Create a ClientEncryption.
			ceo := options.ClientEncryption().
				SetKeyVaultNamespace("keyvault.datakeys").
				SetKmsProviders(fullKmsProvidersMap)
			clientEncryption, err := mongo.NewClientEncryption(keyVaultClient, ceo)
			assert.Nil(mt, err, "error on NewClientEncryption: %v", err)

			// Create a MongoClient with AutoEncryptionOpts and bypassQueryAnalysis=true.
			aeo := options.AutoEncryption().
				SetKeyVaultNamespace("keyvault.datakeys").
				SetKmsProviders(fullKmsProvidersMap).
				SetBypassQueryAnalysis(true)
			co := options.Client().SetAutoEncryptionOptions(aeo).ApplyURI(mtest.ClusterURI())
			encryptedClient, err := mongo.Connect(context.Background(), co)
			assert.Nil(mt, err, "error on Connect: %v", err)
			return encryptedClient, clientEncryption
		}
		// Test Setup ... end

		mt.Run("case 1: can insert encrypted indexed and find", func(mt *mtest.T) {
			encryptedClient, clientEncryption := testSetup()
			defer clientEncryption.Close(context.Background())
			defer encryptedClient.Disconnect(context.Background())

			// Explicit encrypt the value "encrypted indexed value" with algorithm: "Indexed".
			eo := options.Encrypt().SetAlgorithm("Indexed").SetKeyID(key1ID).SetContentionFactor(0)
			valueToEncrypt := "encrypted indexed value"
			rawVal := bson.RawValue{Type: bson.TypeString, Value: bsoncore.AppendString(nil, valueToEncrypt)}
			insertPayload, err := clientEncryption.Encrypt(context.Background(), rawVal, eo)
			assert.Nil(mt, err, "error in Encrypt: %v", err)
			// Insert.
			coll := encryptedClient.Database("db").Collection("explicit_encryption")
			_, err = coll.InsertOne(context.Background(), bson.D{{"_id", 1}, {"encryptedIndexed", insertPayload}})
			assert.Nil(mt, err, "Error in InsertOne: %v", err)
			// Explicit encrypt an indexed value to find.
			eo = options.Encrypt().SetAlgorithm("Indexed").SetKeyID(key1ID).SetQueryType(options.QueryTypeEquality).SetContentionFactor(0)
			findPayload, err := clientEncryption.Encrypt(context.Background(), rawVal, eo)
			assert.Nil(mt, err, "error in Encrypt: %v", err)
			// Find.
			res := coll.FindOne(context.Background(), bson.D{{"encryptedIndexed", findPayload}})
			assert.Nil(mt, res.Err(), "Error in FindOne: %v", res.Err())
			got, err := res.Raw()
			assert.Nil(mt, err, "error in Raw: %v", err)
			gotValue, err := got.LookupErr("encryptedIndexed")
			assert.Nil(mt, err, "error in LookupErr: %v", err)
			assert.Equal(mt, gotValue.StringValue(), valueToEncrypt, "expected %q, got %q", valueToEncrypt, gotValue.StringValue())
		})
		mt.Run("case 2: can insert encrypted indexed and find with non-zero contention", func(mt *mtest.T) {
			encryptedClient, clientEncryption := testSetup()
			defer clientEncryption.Close(context.Background())
			defer encryptedClient.Disconnect(context.Background())

			coll := encryptedClient.Database("db").Collection("explicit_encryption")
			valueToEncrypt := "encrypted indexed value"
			rawVal := bson.RawValue{Type: bson.TypeString, Value: bsoncore.AppendString(nil, valueToEncrypt)}

			for i := 0; i < 10; i++ {
				// Explicit encrypt the value "encrypted indexed value" with algorithm: "Indexed".
				eo := options.Encrypt().SetAlgorithm("Indexed").SetKeyID(key1ID).SetContentionFactor(10)
				insertPayload, err := clientEncryption.Encrypt(context.Background(), rawVal, eo)
				assert.Nil(mt, err, "error in Encrypt: %v", err)
				// Insert.
				_, err = coll.InsertOne(context.Background(), bson.D{{"_id", i}, {"encryptedIndexed", insertPayload}})
				assert.Nil(mt, err, "Error in InsertOne: %v", err)
			}

			// Explicit encrypt an indexed value to find with default contentionFactor 0.
			{
				eo := options.Encrypt().SetAlgorithm("Indexed").SetKeyID(key1ID).SetQueryType(options.QueryTypeEquality).SetContentionFactor(0)
				findPayload, err := clientEncryption.Encrypt(context.Background(), rawVal, eo)
				assert.Nil(mt, err, "error in Encrypt: %v", err)
				// Find with contentionFactor=0.
				cursor, err := coll.Find(context.Background(), bson.D{{"encryptedIndexed", findPayload}})
				assert.Nil(mt, err, "error in Find: %v", err)
				var got []bson.Raw
				err = cursor.All(context.Background(), &got)
				assert.Nil(mt, err, "error in All: %v", err)
				assert.True(mt, len(got) < 10, "expected len(got) < 10, got: %v", len(got))
				for _, doc := range got {
					gotValue, err := doc.LookupErr("encryptedIndexed")
					assert.Nil(mt, err, "error in LookupErr: %v", err)
					assert.Equal(mt, gotValue.StringValue(), valueToEncrypt, "expected %q, got %q", valueToEncrypt, gotValue.StringValue())
				}
			}

			// Explicit encrypt an indexed value to find with contentionFactor 10.
			{
				eo := options.Encrypt().SetAlgorithm("Indexed").SetKeyID(key1ID).SetQueryType(options.QueryTypeEquality).SetContentionFactor(10)
				findPayload2, err := clientEncryption.Encrypt(context.Background(), rawVal, eo)
				assert.Nil(mt, err, "error in Encrypt: %v", err)
				// Find with contentionFactor=10.
				cursor, err := coll.Find(context.Background(), bson.D{{"encryptedIndexed", findPayload2}})
				assert.Nil(mt, err, "error in Find: %v", err)
				var got []bson.Raw
				err = cursor.All(context.Background(), &got)
				assert.Nil(mt, err, "error in All: %v", err)
				assert.True(mt, len(got) == 10, "expected len(got) == 10, got: %v", len(got))
				for _, doc := range got {
					gotValue, err := doc.LookupErr("encryptedIndexed")
					assert.Nil(mt, err, "error in LookupErr: %v", err)
					assert.Equal(mt, gotValue.StringValue(), valueToEncrypt, "expected %q, got %q", valueToEncrypt, gotValue.StringValue())
				}
			}
		})
		mt.Run("case 3: can insert encrypted unindexed", func(mt *mtest.T) {
			encryptedClient, clientEncryption := testSetup()
			defer clientEncryption.Close(context.Background())
			defer encryptedClient.Disconnect(context.Background())

			// Explicit encrypt the value "encrypted indexed value" with algorithm: "Indexed".
			eo := options.Encrypt().SetAlgorithm("Unindexed").SetKeyID(key1ID)
			valueToEncrypt := "encrypted unindexed value"
			rawVal := bson.RawValue{Type: bson.TypeString, Value: bsoncore.AppendString(nil, valueToEncrypt)}
			insertPayload, err := clientEncryption.Encrypt(context.Background(), rawVal, eo)
			assert.Nil(mt, err, "error in Encrypt: %v", err)
			// Insert.
			coll := encryptedClient.Database("db").Collection("explicit_encryption")
			_, err = coll.InsertOne(context.Background(), bson.D{{"_id", 1}, {"encryptedUnindexed", insertPayload}})
			assert.Nil(mt, err, "Error in InsertOne: %v", err)
			// Find.
			res := coll.FindOne(context.Background(), bson.D{{"_id", 1}})
			assert.Nil(mt, res.Err(), "Error in FindOne: %v", res.Err())
			got, err := res.Raw()
			assert.Nil(mt, err, "error in Raw: %v", err)
			gotValue, err := got.LookupErr("encryptedUnindexed")
			assert.Nil(mt, err, "error in LookupErr: %v", err)
			assert.Equal(mt, gotValue.StringValue(), valueToEncrypt, "expected %q, got %q", valueToEncrypt, gotValue.StringValue())
		})
		mt.Run("case 4: can roundtrip encrypted indexed", func(mt *mtest.T) {
			encryptedClient, clientEncryption := testSetup()
			defer clientEncryption.Close(context.Background())
			defer encryptedClient.Disconnect(context.Background())

			// Explicit encrypt the value "encrypted indexed value" with algorithm: "Indexed".
			eo := options.Encrypt().SetAlgorithm("Indexed").SetKeyID(key1ID).SetContentionFactor(0)
			valueToEncrypt := "encrypted indexed value"
			rawVal := bson.RawValue{Type: bson.TypeString, Value: bsoncore.AppendString(nil, valueToEncrypt)}
			payload, err := clientEncryption.Encrypt(context.Background(), rawVal, eo)
			assert.Nil(mt, err, "error in Encrypt: %v", err)
			gotValue, err := clientEncryption.Decrypt(context.Background(), payload)
			assert.Nil(mt, err, "error in Decrypt: %v", err)
			assert.Equal(mt, gotValue.StringValue(), valueToEncrypt, "expected %q, got %q", valueToEncrypt, gotValue.StringValue())
		})
		mt.Run("case 5: can roundtrip encrypted unindexed", func(mt *mtest.T) {
			encryptedClient, clientEncryption := testSetup()
			defer clientEncryption.Close(context.Background())
			defer encryptedClient.Disconnect(context.Background())

			// Explicit encrypt the value "encrypted indexed value" with algorithm: "Indexed".
			eo := options.Encrypt().SetAlgorithm("Unindexed").SetKeyID(key1ID)
			valueToEncrypt := "encrypted unindexed value"
			rawVal := bson.RawValue{Type: bson.TypeString, Value: bsoncore.AppendString(nil, valueToEncrypt)}
			payload, err := clientEncryption.Encrypt(context.Background(), rawVal, eo)
			assert.Nil(mt, err, "error in Encrypt: %v", err)
			gotValue, err := clientEncryption.Decrypt(context.Background(), payload)
			assert.Nil(mt, err, "error in Decrypt: %v", err)
			assert.Equal(mt, gotValue.StringValue(), valueToEncrypt, "expected %q, got %q", valueToEncrypt, gotValue.StringValue())
		})
	})

	runOpts = mtest.NewOptions().MinServerVersion("4.2").
		Topologies(mtest.ReplicaSet, mtest.LoadBalanced, mtest.ShardedReplicaSet)
	mt.RunOpts("13. Unique Index on keyAltNames", runOpts, func(mt *mtest.T) {
		const (
			dkCollection  = "datakeys"
			idKey         = "_id"
			kvDatabase    = "keyvault"
			defKeyAltName = "def"
			abcKeyAltName = "abc"
		)

		var cse *cseProseTest

		var initialize = func() primitive.Binary {
			// Create a ClientEncryption object (referred to as client_encryption) with client set as the keyVaultClient.
			// Using client, drop the collection keyvault.datakeys.
			cse = setup(mt, nil, defaultKvClientOptions, options.ClientEncryption().
				SetKmsProviders(fullKmsProvidersMap).
				SetKeyVaultNamespace(kvNamespace))

			err := cse.kvClient.Database(kvDatabase).Collection(dkCollection).Drop(context.Background())
			assert.Nil(mt, err, "error dropping %q namespace: %v", kvNamespace, err)

			// Using client, create a unique index on keyAltNames with a partial index filter for only documents where
			// keyAltNames exists using writeConcern "majority".
			keyVaultIndex := mongo.IndexModel{
				Keys: bson.D{{"keyAltNames", 1}},
				Options: options.Index().
					SetUnique(true).
					SetName("keyAltNames_1").
					SetPartialFilterExpression(bson.D{
						{"keyAltNames", bson.D{
							{"$exists", true},
						}},
					}),
			}

			wcMajority := writeconcern.New(writeconcern.WMajority(), writeconcern.WTimeout(1*time.Second))
			wcMajorityCollectionOpts := options.Collection().SetWriteConcern(wcMajority)
			wcmColl := cse.kvClient.Database(kvDatabase).Collection(dkCollection, wcMajorityCollectionOpts)
			_, err = wcmColl.Indexes().CreateOne(context.Background(), keyVaultIndex)
			assert.Nil(mt, err, "error creating keyAltNames index: %v", err)

			// Using client_encryption, create a data key with a local KMS provider and the keyAltName "def".
			opts := options.DataKey().SetKeyAltNames([]string{defKeyAltName})
			defKeyID, err := cse.clientEnc.CreateDataKey(context.Background(), "local", opts)
			assert.Nil(mt, err, "error creating %q data key: %v", defKeyAltName, err)
			return defKeyID
		}

		var validateAddKeyAltName = func(mt *mtest.T, cse *cseProseTest, res *mongo.SingleResult, expected ...string) {
			assert.Nil(mt, res.Err(), "error adding key alt name: %v", res.Err())

			resbytes, err := res.Raw()
			assert.Nil(mt, err, "error decoding result bytes: %v", err)

			idsubtype, iddata := bson.RawValue{Type: bsontype.EmbeddedDocument, Value: resbytes}.
				Document().Lookup("_id").Binary()
			filter := bsoncore.NewDocumentBuilder().AppendBinary("_id", idsubtype, iddata).Build()

			ctx := context.Background()
			updatedData, err := cse.keyVaultColl.FindOne(ctx, filter).Raw()
			assert.Nil(mt, err, "error decoding result bytes: %v", err)

			updated := bson.RawValue{Type: bsontype.EmbeddedDocument, Value: updatedData}
			updatedKeyAltNames, err := updated.Document().Lookup("keyAltNames").Array().Values()
			assert.Nil(mt, err, "error looking up raw keyAltNames: %v", err)
			assert.Equal(mt, len(updatedKeyAltNames), len(expected), "expected raw keyAltNames length to be 1")

			for idx, keyAltName := range updatedKeyAltNames {
				str := keyAltName.StringValue()
				assert.Equal(mt, str, expected[idx], "expected keyAltName to be %q, got: %q", expected[idx], str)
			}
		}

		mt.Run("case 1: createKey()", func(mt *mtest.T) {
			initialize()

			// Use client_encryption to create a new local data key with a keyAltName "abc" and assert the operation
			// does not fail.
			opts := options.DataKey().SetKeyAltNames([]string{abcKeyAltName})
			_, err := cse.clientEnc.CreateDataKey(context.Background(), "local", opts)
			assert.Nil(mt, err, "error creating %q data key: %v", abcKeyAltName, err)

			// Repeat Step 1 and assert the operation fails due to a duplicate key server error (error code 11000).
			opts = options.DataKey().SetKeyAltNames([]string{abcKeyAltName})
			_, err = cse.clientEnc.CreateDataKey(context.Background(), "local", opts)
			assert.NotNil(mt, err, "duplicate %q key did not propagate expected error", abcKeyAltName)

			e110000 := "E11000 duplicate key"
			correctError := strings.Contains(err.Error(), e110000)
			assert.True(t, correctError, "expected error to contain %q, got: %v", e110000, err)

			// Use client_encryption to create a new local data key with a keyAltName "def" and assert the operation
			// fails due to a duplicate key server error (error code 11000).
			opts = options.DataKey().SetKeyAltNames([]string{defKeyAltName})
			_, err = cse.clientEnc.CreateDataKey(context.Background(), "local", opts)
			assert.NotNil(mt, err, "duplicate %q key did not propagate expected error", defKeyAltName)

			e110000 = "E11000 duplicate key"
			correctError = strings.Contains(err.Error(), e110000)
			assert.True(t, correctError, "expected error to contain %q, got: %v", e110000, err)
		})

		mt.Run("case 2: addKeyAltName()", func(t *mtest.T) {
			defKeyID := initialize()

			var someNewKeyID primitive.Binary
			// Use client_encryption to create a new local data key and assert the operation does not fail.
			var err error
			someNewKeyID, err = cse.clientEnc.CreateDataKey(context.Background(), "local")
			assert.Nil(mt, err, "error creating data key: %v", err)

			// Use client_encryption to add a keyAltName "abc" to the key created in Step 1 and assert the operation
			// does not fail.
			res := cse.clientEnc.AddKeyAltName(context.Background(), someNewKeyID, abcKeyAltName)
			validateAddKeyAltName(mt, cse, res, abcKeyAltName)

			// Repeat Step 2, assert the operation does not fail, and assert the returned key document contains the
			// keyAltName "abc" added in Step 2.
			res = cse.clientEnc.AddKeyAltName(context.Background(), someNewKeyID, abcKeyAltName)
			validateAddKeyAltName(mt, cse, res, abcKeyAltName)

			// Use client_encryption to add a keyAltName "def" to the key created in Step 1 and assert the operation
			// fails due to a duplicate key server error (error code 11000).
			res = cse.clientEnc.AddKeyAltName(context.Background(), someNewKeyID, defKeyAltName)
			assert.NotNil(mt, res.Err(), "duplicate %q key did not propagate expected error", defKeyAltName)

			e110000 := "E11000 duplicate key"
			correctError := strings.Contains(res.Err().Error(), e110000)
			assert.True(t, correctError, "expected error to contain %q, got: %v", e110000, res.Err())

			// Use client_encryption to add a keyAltName "def" to the existing key, assert the operation does not fail,
			// and assert the returned key document contains the keyAltName "def" added during Setup.
			res = cse.clientEnc.AddKeyAltName(context.Background(), defKeyID, defKeyAltName)
			validateAddKeyAltName(mt, cse, res, defKeyAltName)
		})

	})

	mt.RunOpts("16. Rewrap", runOpts, func(mt *mtest.T) {
		mt.Run("Case 1: Rewrap with separate ClientEncryption", func(mt *mtest.T) {
			dataKeyMap := map[string]bson.M{
				"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": {},
			}

			tlsConfig := make(map[string]*tls.Config)
			if tlsCAFileKMIP != "" && tlsClientCertificateKeyFileKMIP != "" {
				tlsOpts := map[string]interface{}{
					"tlsCertificateKeyFile": tlsClientCertificateKeyFileKMIP,
					"tlsCAFile":             tlsCAFileKMIP,
				}
				kmipConfig, err := options.BuildTLSConfig(tlsOpts)
				assert.Nil(mt, err, "BuildTLSConfig error: %v", err)
				tlsConfig["kmip"] = kmipConfig
			}

			kmsProviders := []string{"local", "aws", "gcp", "azure", "kmip"}
			for _, srcProvider := range kmsProviders {
				for _, dstProvider := range kmsProviders {
					mt.Run(fmt.Sprintf("%s to %s", srcProvider, dstProvider), func(mt *mtest.T) {
						var err error
						// Drop the collection ``keyvault.datakeys``.
						{
							err = mt.Client.Database("keyvault").Collection("datakeys").Drop(context.Background())
							assert.Nil(mt, err, "error on Drop: %v", err)
						}

						// Create a ``ClientEncryption`` object named ``clientEncryption1``.
						var clientEncryption1 *mongo.ClientEncryption
						{
							var keyVaultClient *mongo.Client
							{
								co := options.Client().ApplyURI(mtest.ClusterURI())
								keyVaultClient, err = mongo.Connect(context.Background(), co)
								defer keyVaultClient.Disconnect(context.Background())
								integtest.AddTestServerAPIVersion(co)
								assert.Nil(mt, err, "error on Connect: %v", err)
							}
							ceOpts := options.ClientEncryption().
								SetKeyVaultNamespace("keyvault.datakeys").
								SetKmsProviders(fullKmsProvidersMap).
								SetTLSConfig(tlsConfig)
							clientEncryption1, err = mongo.NewClientEncryption(keyVaultClient, ceOpts)
							assert.Nil(mt, err, "error in NewClientEncryption: %v", err)
							defer clientEncryption1.Close(context.Background())
						}

						// Call ``clientEncryption1.createDataKey``.
						var keyID primitive.Binary
						{
							dkOpts := options.DataKey()
							if val, ok := dataKeyMap[srcProvider]; ok {
								dkOpts.SetMasterKey(val)
							}
							keyID, err = clientEncryption1.CreateDataKey(context.Background(), srcProvider, dkOpts)
							assert.Nil(mt, err, "error in CreateDataKey: %v", err)
						}

						// Call ``clientEncryption1.encrypt`` with the value "test".
						var ciphertext primitive.Binary
						{
							t, value, err := bson.MarshalValue("test")
							assert.Nil(mt, err, "error in MarshalValue: %v", err)
							plaintext := bson.RawValue{Type: t, Value: value}
							eOpts := options.Encrypt().SetKeyID(keyID).SetAlgorithm("AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic")
							ciphertext, err = clientEncryption1.Encrypt(context.Background(), plaintext, eOpts)
							assert.Nil(mt, err, "error in Encrypt: %v", err)
						}

						// Create a ``ClientEncryption`` object named ``clientEncryption2``.
						var clientEncryption2 *mongo.ClientEncryption
						{
							var keyVaultClient *mongo.Client
							{
								co := options.Client().ApplyURI(mtest.ClusterURI())
								keyVaultClient, err = mongo.Connect(context.Background(), co)
								defer keyVaultClient.Disconnect(context.Background())
								integtest.AddTestServerAPIVersion(co)
								assert.Nil(mt, err, "error on Connect: %v", err)
							}
							ceOpts := options.ClientEncryption().
								SetKeyVaultNamespace("keyvault.datakeys").
								SetKmsProviders(fullKmsProvidersMap).
								SetTLSConfig(tlsConfig)
							clientEncryption2, err = mongo.NewClientEncryption(keyVaultClient, ceOpts)
							assert.Nil(mt, err, "error in NewClientEncryption: %v", err)
							defer clientEncryption2.Close(context.Background())
						}

						// Call ``clientEncryption2.rewrapManyDataKey`` with an empty ``filter``.
						{
							rwOpts := options.RewrapManyDataKey().SetProvider(dstProvider)
							if val, ok := dataKeyMap[dstProvider]; ok {
								rwOpts.SetMasterKey(val)
							}
							res, err := clientEncryption2.RewrapManyDataKey(context.Background(), bson.D{}, rwOpts)
							assert.Nil(mt, err, "error in RewrapManyDataKey: %v", err)
							assert.Equal(mt, res.BulkWriteResult.ModifiedCount, int64(1), "expected ModifiedCount of 1, got %v", res.BulkWriteResult.ModifiedCount)
						}

						// Call ``clientEncryption1.decrypt`` with the ``ciphertext``.
						{
							plaintext, err := clientEncryption1.Decrypt(context.Background(), ciphertext)
							assert.Nil(mt, err, "error in Decrypt: %v", err)
							assert.Equal(mt, plaintext.StringValue(), "test", "expected plaintext 'test', got %q", plaintext.StringValue())
						}

						// Call ``clientEncryption2.decrypt`` with the ``ciphertext``.
						{
							plaintext, err := clientEncryption2.Decrypt(context.Background(), ciphertext)
							assert.Nil(mt, err, "error in Decrypt: %v", err)
							assert.Equal(mt, plaintext.StringValue(), "test", "expected plaintext 'test', got %q", plaintext.StringValue())
						}
					})
				}
			}
		})

		mt.Run("Case 2: RewrapManyDataKeyOpts.provider is not optional", func(mt *mtest.T) {
			var err error
			var clientEncryption *mongo.ClientEncryption
			{
				var keyVaultClient *mongo.Client
				{
					co := options.Client().ApplyURI(mtest.ClusterURI())
					keyVaultClient, err = mongo.Connect(context.Background(), co)
					defer keyVaultClient.Disconnect(context.Background())
					integtest.AddTestServerAPIVersion(co)
					assert.Nil(mt, err, "error on Connect: %v", err)
				}
				ceOpts := options.ClientEncryption().
					SetKeyVaultNamespace("keyvault.datakeys").
					SetKmsProviders(fullKmsProvidersMap)
				clientEncryption, err = mongo.NewClientEncryption(keyVaultClient, ceOpts)
				assert.Nil(mt, err, "error in NewClientEncryption: %v", err)
				defer clientEncryption.Close(context.Background())
			}

			_, err = clientEncryption.RewrapManyDataKey(context.Background(), bson.D{}, options.RewrapManyDataKey().SetMasterKey(bson.D{}))
			assert.ErrorContains(mt, err, "expected 'Provider' to be set to identify type of 'MasterKey'")
		})
	})

	mt.RunOpts("18. Azure IMDS Credentials", noClientOpts, func(mt *mtest.T) {
		buf := make([]byte, 0, 256)
		kmsProvidersMap := map[string]map[string]interface{}{
			"azure": {},
		}
		p, err := bson.MarshalAppend(buf[:0], kmsProvidersMap)
		assert.Nil(mt, err, "error in MarshalAppendWithRegistry: %v", err)

		getClient := func(header http.Header) *http.Client {
			lt := &localTransport{
				header: header,
				rt:     http.DefaultTransport,
			}
			return &http.Client{
				Timeout:   30 * time.Second,
				Transport: lt,
			}
		}

		mt.Run("Case 1: Success", func(mt *mtest.T) {
			opts := &mongocryptopts.MongoCryptOptions{
				KmsProviders: p,
				HTTPClient:   getClient(nil),
			}
			crypt, err := mongocrypt.NewMongoCrypt(opts)
			assert.Nil(mt, err, "error in NewMongoCrypt: %v", err)
			doc, err := crypt.GetKmsProviders(context.Background())
			assert.Nil(mt, err, "error in GetKmsProviders: %v", err)
			val, err := doc.LookupErr("azure")
			assert.Nil(mt, err, "error in LookupErr: %v", err)
			assert.Equal(mt, `{"accessToken": "magic-cookie"}`, val.String(), "expected accessToken, got %s", val.String())
		})
		mt.Run("Case 2: Empty JSON", func(mt *mtest.T) {
			header := make(http.Header)
			header.Set("X-MongoDB-HTTP-TestParams", "case=empty-json")
			opts := &mongocryptopts.MongoCryptOptions{
				KmsProviders: p,
				HTTPClient:   getClient(header),
			}
			crypt, err := mongocrypt.NewMongoCrypt(opts)
			assert.Nil(mt, err, "error in NewMongoCrypt: %v", err)
			_, err = crypt.GetKmsProviders(context.Background())
			assert.ErrorContains(mt, err, "got unexpected empty accessToken")
		})
		mt.Run("Case 3: Bad JSON", func(mt *mtest.T) {
			header := make(http.Header)
			header.Set("X-MongoDB-HTTP-TestParams", "case=bad-json")
			opts := &mongocryptopts.MongoCryptOptions{
				KmsProviders: p,
				HTTPClient:   getClient(header),
			}
			crypt, err := mongocrypt.NewMongoCrypt(opts)
			assert.Nil(mt, err, "error in NewMongoCrypt: %v", err)
			_, err = crypt.GetKmsProviders(context.Background())
			assert.ErrorContains(mt, err, "error reading body JSON")
		})
		mt.Run("Case 4: HTTP 404", func(mt *mtest.T) {
			header := make(http.Header)
			header.Set("X-MongoDB-HTTP-TestParams", "case=404")
			opts := &mongocryptopts.MongoCryptOptions{
				KmsProviders: p,
				HTTPClient:   getClient(header),
			}
			crypt, err := mongocrypt.NewMongoCrypt(opts)
			assert.Nil(mt, err, "error in NewMongoCrypt: %v", err)
			_, err = crypt.GetKmsProviders(context.Background())
			assert.ErrorContains(mt, err, "got StatusCode: 404")
		})
		mt.Run("Case 5: HTTP 500", func(mt *mtest.T) {
			header := make(http.Header)
			header.Set("X-MongoDB-HTTP-TestParams", "case=500")
			opts := &mongocryptopts.MongoCryptOptions{
				KmsProviders: p,
				HTTPClient:   getClient(header),
			}
			crypt, err := mongocrypt.NewMongoCrypt(opts)
			assert.Nil(mt, err, "error in NewMongoCrypt: %v", err)
			_, err = crypt.GetKmsProviders(context.Background())
			assert.ErrorContains(mt, err, "got StatusCode: 500")
		})
		mt.Run("Case 6: Slow Response", func(mt *mtest.T) {
			header := make(http.Header)
			header.Set("X-MongoDB-HTTP-TestParams", "case=slow")
			opts := &mongocryptopts.MongoCryptOptions{
				KmsProviders: p,
				HTTPClient:   getClient(header),
			}
			crypt, err := mongocrypt.NewMongoCrypt(opts)
			assert.Nil(mt, err, "error in NewMongoCrypt: %v", err)
			_, err = crypt.GetKmsProviders(context.Background())

			possibleErrors := []string{
				"error reading response body: context deadline exceeded",    // <= 1.19 + RHEL & macOS
				"Client.Timeout or context cancellation while reading body", // > 1.20 on all OS
			}

			assert.True(t, containsSubstring(possibleErrors, err.Error()),
				"expected possibleErrors=%v to contain %v, but it didn't",
				possibleErrors, err.Error())
		})
	})

	mt.RunOpts("20. Bypass creating mongocryptd client when shared library is loaded",
		noClientOpts, func(mt *mtest.T) {
			cryptSharedLibPath := os.Getenv("CRYPT_SHARED_LIB_PATH")
			if cryptSharedLibPath == "" {
				mt.Skip("CRYPT_SHARED_LIB_PATH not set, skipping")
				return
			}

			kmsProviders := map[string]map[string]interface{}{
				"local": {
					"key": localMasterKey,
				},
			}

			// Listen for connections in a separate goroutine.
			listener := listenForConnections(t, func(c net.Conn) {
				mt.Fatalf("Unexpected connection created to mock mongocryptd goroutine")
				c.Close()
			})
			defer listener.Close()

			uri := "mongodb://" + listener.Addr().String()
			mongocryptdSpawnArgs := map[string]interface{}{
				"mongocryptdURI":     uri,
				"cryptSharedLibPath": cryptSharedLibPath,
			}

			aeo := options.AutoEncryption().SetKmsProviders(kmsProviders).
				SetExtraOptions(mongocryptdSpawnArgs)
			cliOpts := options.Client().ApplyURI(mtest.ClusterURI()).SetAutoEncryptionOptions(aeo)
			integtest.AddTestServerAPIVersion(cliOpts)
			encClient, err := mongo.Connect(context.Background(), cliOpts)
			assert.Nil(mt, err, "Connect error: %v", err)
			defer func() {
				err = encClient.Disconnect(context.Background())
				assert.Nil(mt, err, "encrypted client Disconnect error: %v", err)
			}()

			// Run an Insert through the encrypted client to make sure mongocryptd is started ('insert' uses the
			// mongocryptd and will wait for it to be active).
			_, err = encClient.Database("db").Collection("coll").InsertOne(context.Background(), bson.D{{"unencrypted", "test"}})
			assert.Nil(mt, err, "InsertOne error: %v", err)
		})

	// qeRunOpts are requirements for Queryable Encryption.
	qeRunOpts := mtest.NewOptions().MinServerVersion("7.0").Topologies(mtest.ReplicaSet, mtest.Sharded, mtest.LoadBalanced, mtest.ShardedReplicaSet)
	// Only test MongoDB Server 7.0+. MongoDB Server 7.0 introduced a backwards breaking change to the Queryable Encryption (QE) protocol: QEv2.
	// libmongocrypt is configured to use the QEv2 protocol.
	mt.RunOpts("21. automatic data encryption keys", qeRunOpts, func(mt *mtest.T) {
		setup := func() (*mongo.Client, *mongo.ClientEncryption, error) {
			opts := options.Client().ApplyURI(mtest.ClusterURI())
			client, err := mongo.Connect(context.Background(), opts)
			if err != nil {
				return nil, nil, err
			}
			client.Database("keyvault").Collection("datakeys").Drop(context.Background())
			client.Database("db").Drop(context.Background())
			ceo := options.ClientEncryption().
				SetKmsProviders(fullKmsProvidersMap).
				SetKeyVaultNamespace(kvNamespace)
			clientEnc, err := mongo.NewClientEncryption(client, ceo)
			if err != nil {
				return nil, nil, err
			}
			return client, clientEnc, nil
		}

		type KMSProviderTestcase struct {
			kmsProvider string
			masterKey   *bson.D
		}

		testcases := []KMSProviderTestcase{
			{
				kmsProvider: "local",
				masterKey:   nil,
			},
			{
				kmsProvider: "aws",
				masterKey: &bson.D{
					{"region", "us-east-1"},
					{"key", "arn:aws:kms:us-east-1:579766882180:key/89fcc2c4-08b0-4bd9-9f25-e30687b580d0"},
				},
			},
		}

		for _, tc := range testcases {
			mt.Run(tc.kmsProvider, func(mt *mtest.T) {

				mt.Run("case 1: simple creation and validation", func(mt *mtest.T) {
					client, clientEnc, err := setup()
					assert.Nil(mt, err, "setup error: %v", err)
					defer func() {
						err := clientEnc.Close(context.Background())
						assert.Nil(mt, err, "error in Close")
					}()

					var encryptedFields bson.Raw
					err = bson.UnmarshalExtJSON([]byte(`{
				"fields": [{
					"path": "ssn",
					"bsonType": "string",
					"keyId": null
				}]
			}`), true /* canonical */, &encryptedFields)
					assert.Nil(mt, err, "Unmarshal error: %v", err)

					coll, _, err := clientEnc.CreateEncryptedCollection(
						context.Background(),
						client.Database("db"),
						"testing1", options.CreateCollection().SetEncryptedFields(encryptedFields),
						"local", nil,
					)
					assert.Nil(mt, err, "CreateCollection error: %v", err)

					_, err = coll.InsertOne(context.Background(), bson.D{{"ssn", "123-45-6789"}})
					assert.ErrorContains(mt, err, "Document failed validation")
				})
				mt.Run("case 2: missing encryptedFields", func(mt *mtest.T) {
					client, clientEnc, err := setup()
					assert.Nil(mt, err, "setup error: %v", err)
					defer func() {
						err := clientEnc.Close(context.Background())
						assert.Nil(mt, err, "error in Close")
					}()

					coll, _, err := clientEnc.CreateEncryptedCollection(
						context.Background(),
						client.Database("db"),
						"testing1", options.CreateCollection(),
						"local", nil,
					)
					assert.Nil(mt, coll, "expect nil collection")
					assert.EqualError(mt, err, "no EncryptedFields defined for the collection")
				})
				mt.Run("case 3: invalid keyId", func(mt *mtest.T) {
					client, clientEnc, err := setup()
					assert.Nil(mt, err, "setup error: %v", err)
					defer func() {
						err := clientEnc.Close(context.Background())
						assert.Nil(mt, err, "error in Close")
					}()

					var encryptedFields bson.Raw
					err = bson.UnmarshalExtJSON([]byte(`{
				"fields": [{
					"path": "ssn",
					"bsonType": "string",
					"keyId": false
				}]
			}`), true /* canonical */, &encryptedFields)
					assert.Nil(mt, err, "Unmarshal error: %v", err)

					_, _, err = clientEnc.CreateEncryptedCollection(
						context.Background(),
						client.Database("db"),
						"testing1", options.CreateCollection().SetEncryptedFields(encryptedFields),
						"local", nil,
					)
					assert.ErrorContains(mt, err, "BSON field 'create.encryptedFields.fields.keyId' is the wrong type 'bool', expected type 'binData'")
				})
				mt.Run("case 4: insert encrypted value", func(mt *mtest.T) {
					client, clientEnc, err := setup()
					assert.Nil(mt, err, "setup error: %v", err)
					defer func() {
						err := clientEnc.Close(context.Background())
						assert.Nil(mt, err, "error in Close")
					}()

					var encryptedFields bson.Raw
					err = bson.UnmarshalExtJSON([]byte(`{
				"fields": [{
					"path": "ssn",
					"bsonType": "string",
					"keyId": null
				}]
			}`), true /* canonical */, &encryptedFields)
					assert.Nil(mt, err, "Unmarshal error: %v", err)

					coll, ef, err := clientEnc.CreateEncryptedCollection(
						context.Background(),
						client.Database("db"),
						"testing1", options.CreateCollection().SetEncryptedFields(encryptedFields),
						"local", nil,
					)
					assert.Nil(mt, err, "CreateCollection error: %v", err)

					keyid := ef["fields"].(bson.A)[0].(bson.M)["keyId"].(primitive.Binary)
					rawValueType, rawValueData, err := bson.MarshalValue("123-45-6789")
					assert.Nil(mt, err, "MarshalValue error: %v", err)
					rawValue := bson.RawValue{Type: rawValueType, Value: rawValueData}
					encryptionOpts := options.Encrypt().
						SetAlgorithm("Unindexed").
						SetKeyID(keyid)
					encryptedField, err := clientEnc.Encrypt(
						context.Background(),
						rawValue,
						encryptionOpts)
					assert.Nil(mt, err, "Encrypt error: %v", err)

					_, err = coll.InsertOne(context.Background(), bson.D{{"ssn", encryptedField}})
					assert.Nil(mt, err, "InsertOne error: %v", err)
				})
			})
		}
	})

	qeRunOpts22 := qeRunOpts.MinServerVersion("8.0")
	mt.RunOpts("22. range explicit encryption", qeRunOpts22, func(mt *mtest.T) {
		type testcase struct {
			typeStr       string
			field         string
			typeBson      bsontype.Type
			rangeOpts     options.RangeOptions
			zero          bson.RawValue
			six           bson.RawValue
			thirty        bson.RawValue
			twoHundred    bson.RawValue
			twoHundredOne bson.RawValue
		}

		trimFactor := int32(1)
		sparsity := int64(1)
		precision := int32(2)

		d128_0, err := primitive.ParseDecimal128("0")
		assert.Nil(mt, err)
		d128_6, err := primitive.ParseDecimal128("6")
		assert.Nil(mt, err)
		d128_30, err := primitive.ParseDecimal128("30")
		assert.Nil(mt, err)
		d128_200, err := primitive.ParseDecimal128("200")
		assert.Nil(mt, err)
		d128_201, err := primitive.ParseDecimal128("201")
		assert.Nil(mt, err)

		tests := []testcase{
			{
				typeStr:  "DecimalNoPrecision",
				field:    "encryptedDecimalNoPrecision",
				typeBson: bson.TypeDecimal128,
				rangeOpts: options.RangeOptions{
					TrimFactor: &trimFactor,
					Sparsity:   &sparsity,
				},
				zero:          bson.RawValue{Type: bson.TypeDecimal128, Value: bsoncore.AppendDecimal128(nil, d128_0)},
				six:           bson.RawValue{Type: bson.TypeDecimal128, Value: bsoncore.AppendDecimal128(nil, d128_6)},
				thirty:        bson.RawValue{Type: bson.TypeDecimal128, Value: bsoncore.AppendDecimal128(nil, d128_30)},
				twoHundred:    bson.RawValue{Type: bson.TypeDecimal128, Value: bsoncore.AppendDecimal128(nil, d128_200)},
				twoHundredOne: bson.RawValue{Type: bson.TypeDecimal128, Value: bsoncore.AppendDecimal128(nil, d128_201)},
			},
			{
				typeStr:  "DecimalPrecision",
				field:    "encryptedDecimalPrecision",
				typeBson: bson.TypeDecimal128,
				rangeOpts: options.RangeOptions{
					Min:        &bson.RawValue{Type: bson.TypeDecimal128, Value: bsoncore.AppendDecimal128(nil, d128_0)},
					Max:        &bson.RawValue{Type: bson.TypeDecimal128, Value: bsoncore.AppendDecimal128(nil, d128_200)},
					TrimFactor: &trimFactor,
					Sparsity:   &sparsity,
					Precision:  &precision,
				},
				zero:          bson.RawValue{Type: bson.TypeDecimal128, Value: bsoncore.AppendDecimal128(nil, d128_0)},
				six:           bson.RawValue{Type: bson.TypeDecimal128, Value: bsoncore.AppendDecimal128(nil, d128_6)},
				thirty:        bson.RawValue{Type: bson.TypeDecimal128, Value: bsoncore.AppendDecimal128(nil, d128_30)},
				twoHundred:    bson.RawValue{Type: bson.TypeDecimal128, Value: bsoncore.AppendDecimal128(nil, d128_200)},
				twoHundredOne: bson.RawValue{Type: bson.TypeDecimal128, Value: bsoncore.AppendDecimal128(nil, d128_201)},
			},
			{
				typeStr:  "DoubleNoPrecision",
				field:    "encryptedDoubleNoPrecision",
				typeBson: bson.TypeDouble,
				rangeOpts: options.RangeOptions{
					TrimFactor: &trimFactor,
					Sparsity:   &sparsity,
				},
				zero:          bson.RawValue{Type: bson.TypeDouble, Value: bsoncore.AppendDouble(nil, 0)},
				six:           bson.RawValue{Type: bson.TypeDouble, Value: bsoncore.AppendDouble(nil, 6)},
				thirty:        bson.RawValue{Type: bson.TypeDouble, Value: bsoncore.AppendDouble(nil, 30)},
				twoHundred:    bson.RawValue{Type: bson.TypeDouble, Value: bsoncore.AppendDouble(nil, 200)},
				twoHundredOne: bson.RawValue{Type: bson.TypeDouble, Value: bsoncore.AppendDouble(nil, 201)},
			},
			{
				typeStr:  "DoublePrecision",
				field:    "encryptedDoublePrecision",
				typeBson: bson.TypeDouble,
				rangeOpts: options.RangeOptions{
					Min:        &bson.RawValue{Type: bson.TypeDouble, Value: bsoncore.AppendDouble(nil, 0)},
					Max:        &bson.RawValue{Type: bson.TypeDouble, Value: bsoncore.AppendDouble(nil, 200)},
					TrimFactor: &trimFactor,
					Sparsity:   &sparsity,
					Precision:  &precision,
				},
				zero:          bson.RawValue{Type: bson.TypeDouble, Value: bsoncore.AppendDouble(nil, 0)},
				six:           bson.RawValue{Type: bson.TypeDouble, Value: bsoncore.AppendDouble(nil, 6)},
				thirty:        bson.RawValue{Type: bson.TypeDouble, Value: bsoncore.AppendDouble(nil, 30)},
				twoHundred:    bson.RawValue{Type: bson.TypeDouble, Value: bsoncore.AppendDouble(nil, 200)},
				twoHundredOne: bson.RawValue{Type: bson.TypeDouble, Value: bsoncore.AppendDouble(nil, 201)},
			},
			{
				typeStr:  "Date",
				field:    "encryptedDate",
				typeBson: bson.TypeDateTime,
				rangeOpts: options.RangeOptions{
					Min:        &bson.RawValue{Type: bson.TypeDateTime, Value: bsoncore.AppendDateTime(nil, 0)},
					Max:        &bson.RawValue{Type: bson.TypeDateTime, Value: bsoncore.AppendDateTime(nil, 200)},
					TrimFactor: &trimFactor,
					Sparsity:   &sparsity,
				},
				zero:          bson.RawValue{Type: bson.TypeDateTime, Value: bsoncore.AppendDateTime(nil, 0)},
				six:           bson.RawValue{Type: bson.TypeDateTime, Value: bsoncore.AppendDateTime(nil, 6)},
				thirty:        bson.RawValue{Type: bson.TypeDateTime, Value: bsoncore.AppendDateTime(nil, 30)},
				twoHundred:    bson.RawValue{Type: bson.TypeDateTime, Value: bsoncore.AppendDateTime(nil, 200)},
				twoHundredOne: bson.RawValue{Type: bson.TypeDateTime, Value: bsoncore.AppendDateTime(nil, 201)},
			},
			{
				typeStr:  "Int",
				field:    "encryptedInt",
				typeBson: bson.TypeInt32,
				rangeOpts: options.RangeOptions{
					Min:        &bson.RawValue{Type: bson.TypeInt32, Value: bsoncore.AppendInt32(nil, 0)},
					Max:        &bson.RawValue{Type: bson.TypeInt32, Value: bsoncore.AppendInt32(nil, 200)},
					TrimFactor: &trimFactor,
					Sparsity:   &sparsity,
				},
				zero:          bson.RawValue{Type: bson.TypeInt32, Value: bsoncore.AppendInt32(nil, 0)},
				six:           bson.RawValue{Type: bson.TypeInt32, Value: bsoncore.AppendInt32(nil, 6)},
				thirty:        bson.RawValue{Type: bson.TypeInt32, Value: bsoncore.AppendInt32(nil, 30)},
				twoHundred:    bson.RawValue{Type: bson.TypeInt32, Value: bsoncore.AppendInt32(nil, 200)},
				twoHundredOne: bson.RawValue{Type: bson.TypeInt32, Value: bsoncore.AppendInt32(nil, 201)},
			},
			{
				typeStr:  "Long",
				field:    "encryptedLong",
				typeBson: bson.TypeInt64,
				rangeOpts: options.RangeOptions{
					Min:        &bson.RawValue{Type: bson.TypeInt64, Value: bsoncore.AppendInt64(nil, 0)},
					Max:        &bson.RawValue{Type: bson.TypeInt64, Value: bsoncore.AppendInt64(nil, 200)},
					TrimFactor: &trimFactor,
					Sparsity:   &sparsity,
				},
				zero:          bson.RawValue{Type: bson.TypeInt64, Value: bsoncore.AppendInt64(nil, 0)},
				six:           bson.RawValue{Type: bson.TypeInt64, Value: bsoncore.AppendInt64(nil, 6)},
				thirty:        bson.RawValue{Type: bson.TypeInt64, Value: bsoncore.AppendInt64(nil, 30)},
				twoHundred:    bson.RawValue{Type: bson.TypeInt64, Value: bsoncore.AppendInt64(nil, 200)},
				twoHundredOne: bson.RawValue{Type: bson.TypeInt64, Value: bsoncore.AppendInt64(nil, 201)},
			},
		}

		for _, test := range tests {
			mt.Run(test.typeStr, func(mt *mtest.T) {
				if test.typeStr == "DecimalNoPrecision" && mtest.ClusterTopologyKind() != mtest.ReplicaSet {
					mt.Skipf("Skipping DecimalNoPrecision tests on a non ReplicaSet topology. DecimalNoPrecision queries are expected to take a long time and may exceed the default mongos timeout")
				}

				// Test Setup ... begin
				encryptedFields := readJSONFile(mt, fmt.Sprintf("range-encryptedFields-%v.json", test.typeStr))
				key1Document := readJSONFile(mt, "key1-document.json")
				var key1ID primitive.Binary
				{
					subtype, data := key1Document.Lookup("_id").Binary()
					key1ID = primitive.Binary{Subtype: subtype, Data: data}
				}

				testSetup := func() (*mongo.Client, *mongo.ClientEncryption) {
					mtest.DropEncryptedCollection(mt, mt.Client.Database("db").Collection("explicit_encryption"), encryptedFields)
					cco := options.CreateCollection().SetEncryptedFields(encryptedFields)
					err := mt.Client.Database("db").CreateCollection(context.Background(), "explicit_encryption", cco)
					assert.Nil(mt, err, "error on CreateCollection: %v", err)
					err = mt.Client.Database("keyvault").Collection("datakeys").Drop(context.Background())
					assert.Nil(mt, err, "error on Drop: %v", err)
					keyVaultClient, err := mongo.Connect(context.Background(), options.Client().ApplyURI(mtest.ClusterURI()))
					assert.Nil(mt, err, "error on Connect: %v", err)
					datakeysColl := keyVaultClient.Database("keyvault").Collection("datakeys", options.Collection().SetWriteConcern(mtest.MajorityWc))
					_, err = datakeysColl.InsertOne(context.Background(), key1Document)
					assert.Nil(mt, err, "error on InsertOne: %v", err)
					// Create a ClientEncryption.
					ceo := options.ClientEncryption().
						SetKeyVaultNamespace("keyvault.datakeys").
						SetKmsProviders(fullKmsProvidersMap)
					clientEncryption, err := mongo.NewClientEncryption(keyVaultClient, ceo)
					assert.Nil(mt, err, "error on NewClientEncryption: %v", err)

					// Create a MongoClient with AutoEncryptionOpts and bypassQueryAnalysis=true.
					aeo := options.AutoEncryption().
						SetKeyVaultNamespace("keyvault.datakeys").
						SetKmsProviders(fullKmsProvidersMap).
						SetBypassQueryAnalysis(true)
					co := options.Client().SetAutoEncryptionOptions(aeo).ApplyURI(mtest.ClusterURI())
					encryptedClient, err := mongo.Connect(context.Background(), co)
					assert.Nil(mt, err, "error on Connect: %v", err)

					// Insert 0, 6, 30, and 200.
					coll := encryptedClient.Database("db").Collection("explicit_encryption")
					eo := options.Encrypt().
						SetAlgorithm("Range").
						SetKeyID(key1ID).
						SetContentionFactor(0).
						SetRangeOptions(test.rangeOpts)
					// Insert 0.
					insertPayloadZero, err := clientEncryption.Encrypt(context.Background(), test.zero, eo)
					assert.Nil(mt, err, "error in Encrypt: %v", err)
					_, err = coll.InsertOne(context.Background(), bson.D{{"_id", 0}, {test.field, insertPayloadZero}})
					assert.Nil(mt, err, "error in InsertOne: %v", err)
					// Insert 6.
					insertPayloadSix, err := clientEncryption.Encrypt(context.Background(), test.six, eo)
					assert.Nil(mt, err, "error in Encrypt: %v", err)
					_, err = coll.InsertOne(context.Background(), bson.D{{"_id", 1}, {test.field, insertPayloadSix}})
					assert.Nil(mt, err, "error in InsertOne: %v", err)
					// Insert 30.
					insertPayloadThirty, err := clientEncryption.Encrypt(context.Background(), test.thirty, eo)
					assert.Nil(mt, err, "error in Encrypt: %v", err)
					_, err = coll.InsertOne(context.Background(), bson.D{{"_id", 2}, {test.field, insertPayloadThirty}})
					assert.Nil(mt, err, "error in InsertOne: %v", err)
					// Insert 200.
					insertPayloadTwoHundred, err := clientEncryption.Encrypt(context.Background(), test.twoHundred, eo)
					assert.Nil(mt, err, "error in Encrypt: %v", err)
					_, err = coll.InsertOne(context.Background(), bson.D{{"_id", 3}, {test.field, insertPayloadTwoHundred}})
					assert.Nil(mt, err, "error in InsertOne: %v", err)

					return encryptedClient, clientEncryption
				}
				// Test Setup ... end

				// checkCursorResults checks documents returned by a cursor.
				// Expects document i to have field `field` with value `values[i]`.
				// Expects exactly len(values) documents to be returned.
				checkCursorResults := func(cursor *mongo.Cursor, field string, values ...bson.RawValue) {
					for i, v := range values {
						assert.True(mt, cursor.Next(context.Background()), "expected Next true, got false. Expected document %v with value: %v", i, v)
						got, err := cursor.Current.LookupErr(test.field)
						assert.Nil(mt, err, "%v not found in document %v: %v", test.field, i, cursor.Current)
						assert.Equal(mt, v, got, "expected %v, got %v in document %v", v, got, i)
					}
					assert.False(mt, cursor.Next(context.Background()), "expected Next false, got true with document: %v", cursor.Current)
				}

				mt.Run("Case 1: can decrypt a payload", func(mt *mtest.T) {
					encryptedClient, clientEncryption := testSetup()
					defer clientEncryption.Close(context.Background())
					defer encryptedClient.Disconnect(context.Background())
					eo := options.Encrypt().
						SetAlgorithm("Range").
						SetKeyID(key1ID).
						SetContentionFactor(0).
						SetRangeOptions(test.rangeOpts)
					insertPayloadSix, err := clientEncryption.Encrypt(context.Background(), test.six, eo)
					assert.Nil(mt, err, "error in Encrypt: %v", err)
					got, err := clientEncryption.Decrypt(context.Background(), insertPayloadSix)
					assert.Nil(mt, err, "error in Decrypt: %v", err)
					assert.Equal(mt, test.six, got, "expected %v, got %v", test.six, got)
				})

				mt.Run("Case 2: can find encrypted range and return the maximum", func(mt *mtest.T) {
					encryptedClient, clientEncryption := testSetup()
					defer clientEncryption.Close(context.Background())
					defer encryptedClient.Disconnect(context.Background())
					eo := options.Encrypt().
						SetAlgorithm("Range").
						SetKeyID(key1ID).
						SetContentionFactor(0).
						SetQueryType("range").
						SetRangeOptions(test.rangeOpts)

					expr := bson.M{
						"$and": bson.A{
							bson.M{
								test.field: bson.M{
									"$gte": test.six,
								},
							},
							bson.M{
								test.field: bson.M{
									"$lte": test.twoHundred,
								},
							},
						},
					}

					// Encrypt.
					var encryptedExpr bson.Raw
					{
						err := clientEncryption.EncryptExpression(context.Background(), expr, &encryptedExpr, eo)
						assert.Nil(mt, err, "error in EncryptExpression: %v", err)
					}

					coll := encryptedClient.Database("db").Collection("explicit_encryption")
					opts := options.Find().SetSort(bson.D{{"_id", 1}})
					cursor, err := coll.Find(context.Background(), encryptedExpr, opts)
					assert.Nil(mt, err, "error in coll.Find: %v", err)
					defer cursor.Close(context.Background())

					checkCursorResults(cursor, test.field, test.six, test.thirty, test.twoHundred)
				})

				mt.Run("Case 3: can find encrypted range and return the minimum", func(mt *mtest.T) {
					encryptedClient, clientEncryption := testSetup()
					defer clientEncryption.Close(context.Background())
					defer encryptedClient.Disconnect(context.Background())
					eo := options.Encrypt().
						SetAlgorithm("Range").
						SetKeyID(key1ID).
						SetContentionFactor(0).
						SetQueryType("range").
						SetRangeOptions(test.rangeOpts)

					expr := bson.M{
						"$and": bson.A{
							bson.M{
								test.field: bson.M{
									"$gte": test.zero,
								},
							},
							bson.M{
								test.field: bson.M{
									"$lte": test.six,
								},
							},
						},
					}

					// Encrypt.
					var encryptedExpr bson.Raw
					{
						err := clientEncryption.EncryptExpression(context.Background(), expr, &encryptedExpr, eo)
						assert.Nil(mt, err, "error in EncryptExpression: %v", err)
					}

					coll := encryptedClient.Database("db").Collection("explicit_encryption")
					opts := options.Find().SetSort(bson.D{{"_id", 1}})
					cursor, err := coll.Find(context.Background(), encryptedExpr, opts)
					assert.Nil(mt, err, "error in coll.Find: %v", err)
					defer cursor.Close(context.Background())

					checkCursorResults(cursor, test.field, test.zero, test.six)
				})

				mt.Run("Case 4: can find encrypted range with an open range query", func(mt *mtest.T) {
					encryptedClient, clientEncryption := testSetup()
					defer clientEncryption.Close(context.Background())
					defer encryptedClient.Disconnect(context.Background())
					eo := options.Encrypt().
						SetAlgorithm("Range").
						SetKeyID(key1ID).
						SetContentionFactor(0).
						SetQueryType("range").
						SetRangeOptions(test.rangeOpts)

					expr := bson.M{
						"$and": bson.A{
							bson.M{
								test.field: bson.M{
									"$gt": test.thirty,
								},
							},
						},
					}

					// Encrypt.
					var encryptedExpr bson.Raw
					{
						err := clientEncryption.EncryptExpression(context.Background(), expr, &encryptedExpr, eo)
						assert.Nil(mt, err, "error in EncryptExpression: %v", err)
					}

					coll := encryptedClient.Database("db").Collection("explicit_encryption")
					opts := options.Find().SetSort(bson.D{{"_id", 1}})
					cursor, err := coll.Find(context.Background(), encryptedExpr, opts)
					assert.Nil(mt, err, "error in coll.Find: %v", err)
					defer cursor.Close(context.Background())

					checkCursorResults(cursor, test.field, test.twoHundred)
				})

				mt.Run("Case 5: can run an aggregation expression inside $expr", func(mt *mtest.T) {
					encryptedClient, clientEncryption := testSetup()
					defer clientEncryption.Close(context.Background())
					defer encryptedClient.Disconnect(context.Background())
					eo := options.Encrypt().
						SetAlgorithm("Range").
						SetKeyID(key1ID).
						SetContentionFactor(0).
						SetQueryType("range").
						SetRangeOptions(test.rangeOpts)

					expr := bson.M{
						"$and": bson.A{
							bson.M{
								"$lt": bson.A{
									fmt.Sprintf("$%v", test.field),
									test.thirty,
								},
							},
						},
					}

					// Encrypt.
					var encryptedExpr bson.Raw
					{
						err := clientEncryption.EncryptExpression(context.Background(), expr, &encryptedExpr, eo)
						assert.Nil(mt, err, "error in EncryptExpression: %v", err)
					}

					coll := encryptedClient.Database("db").Collection("explicit_encryption")
					opts := options.Find().SetSort(bson.D{{"_id", 1}})
					cursor, err := coll.Find(context.Background(), bson.M{"$expr": encryptedExpr}, opts)
					assert.Nil(mt, err, "error in coll.Find: %v", err)
					defer cursor.Close(context.Background())

					checkCursorResults(cursor, test.field, test.zero, test.six)
				})

				if test.field != "encryptedDoubleNoPrecision" && test.field != "encryptedDecimalNoPrecision" {
					mt.Run("Case 6: encrypting a document greater than the maximum errors", func(mt *mtest.T) {
						encryptedClient, clientEncryption := testSetup()
						defer clientEncryption.Close(context.Background())
						defer encryptedClient.Disconnect(context.Background())
						eo := options.Encrypt().
							SetAlgorithm("Range").
							SetKeyID(key1ID).
							SetContentionFactor(0).
							SetRangeOptions(test.rangeOpts)

						_, err := clientEncryption.Encrypt(context.Background(), test.twoHundredOne, eo)
						assert.NotNil(mt, err, "expected error, but got none")
					})

					mt.Run("Case 7: encrypting a document of a different type errors", func(mt *mtest.T) {
						encryptedClient, clientEncryption := testSetup()
						defer clientEncryption.Close(context.Background())
						defer encryptedClient.Disconnect(context.Background())
						eo := options.Encrypt().
							SetAlgorithm("Range").
							SetKeyID(key1ID).
							SetContentionFactor(0).
							SetRangeOptions(test.rangeOpts)

						var val bson.RawValue
						if test.field == "encryptedInt" {
							val = bson.RawValue{Type: bson.TypeDouble, Value: bsoncore.AppendDouble(nil, 6)}
						} else {
							val = bson.RawValue{Type: bson.TypeInt32, Value: bsoncore.AppendInt32(nil, 6)}
						}

						_, err := clientEncryption.Encrypt(context.Background(), val, eo)
						assert.NotNil(mt, err, "expected error, but got none")
					})
				}

				if test.field != "encryptedDoubleNoPrecision" && test.field != "encryptedDoublePrecision" && test.field != "encryptedDecimalNoPrecision" && test.field != "encryptedDecimalPrecision" {
					mt.Run("Case 8: setting precision errors if the type is not a double", func(mt *mtest.T) {
						encryptedClient, clientEncryption := testSetup()
						defer clientEncryption.Close(context.Background())
						defer encryptedClient.Disconnect(context.Background())

						// Copy rangeOpts and set precision.
						ro := test.rangeOpts
						ro.SetPrecision(2)
						eo := options.Encrypt().
							SetAlgorithm("Range").
							SetKeyID(key1ID).
							SetContentionFactor(0).
							SetRangeOptions(ro)

						_, err := clientEncryption.Encrypt(context.Background(), test.six, eo)
						assert.NotNil(mt, err, "expected error, but got none")
					})
				}
			})
		}
	})

	mt.RunOpts("22. range explicit encryption applies defaults", qeRunOpts22, func(mt *mtest.T) {
		err := mt.Client.Database("keyvault").Collection("datakeys").Drop(context.Background())
		assert.Nil(mt, err, "error on Drop: %v", err)

		testVal := bson.RawValue{Type: bson.TypeInt32, Value: bsoncore.AppendInt32(nil, 123)}

		keyVaultClient, err := mongo.Connect(context.Background(), options.Client().ApplyURI(mtest.ClusterURI()))
		assert.Nil(mt, err, "error on Connect: %v", err)

		ceo := options.ClientEncryption().
			SetKeyVaultNamespace("keyvault.datakeys").
			SetKmsProviders(fullKmsProvidersMap)
		clientEncryption, err := mongo.NewClientEncryption(keyVaultClient, ceo)
		assert.Nil(mt, err, "error on NewClientEncryption: %v", err)

		dkOpts := options.DataKey()
		keyID, err := clientEncryption.CreateDataKey(context.Background(), "local", dkOpts)
		assert.Nil(mt, err, "error in CreateDataKey: %v", err)

		eo := options.Encrypt().
			SetAlgorithm("Range").
			SetKeyID(keyID).
			SetContentionFactor(0).
			SetRangeOptions(options.RangeOptions{
				Min: &bson.RawValue{Type: bson.TypeInt32, Value: bsoncore.AppendInt32(nil, 0)},
				Max: &bson.RawValue{Type: bson.TypeInt32, Value: bsoncore.AppendInt32(nil, 1000)},
			})
		payloadDefaults, err := clientEncryption.Encrypt(context.Background(), testVal, eo)
		assert.Nil(mt, err, "error in Encrypt: %v", err)

		mt.Run("Case 1: uses libmongocrypt defaults", func(mt *mtest.T) {
			trimFactor := int32(6)
			sparsity := int64(2)
			eo := options.Encrypt().
				SetAlgorithm("Range").
				SetKeyID(keyID).
				SetContentionFactor(0).
				SetRangeOptions(options.RangeOptions{
					Min:        &bson.RawValue{Type: bson.TypeInt32, Value: bsoncore.AppendInt32(nil, 0)},
					Max:        &bson.RawValue{Type: bson.TypeInt32, Value: bsoncore.AppendInt32(nil, 1000)},
					TrimFactor: &trimFactor,
					Sparsity:   &sparsity,
				})
			payload, err := clientEncryption.Encrypt(context.Background(), testVal, eo)
			assert.Nil(mt, err, "error in Encrypt: %v", err)
			assert.Equalf(mt, len(payload.Data), len(payloadDefaults.Data), "the returned payload size is expected to be %d", len(payloadDefaults.Data))
		})

		mt.Run("Case 2: accepts trimFactor 0", func(mt *mtest.T) {
			trimFactor := int32(0)
			eo := options.Encrypt().
				SetAlgorithm("Range").
				SetKeyID(keyID).
				SetContentionFactor(0).
				SetRangeOptions(options.RangeOptions{
					Min:        &bson.RawValue{Type: bson.TypeInt32, Value: bsoncore.AppendInt32(nil, 0)},
					Max:        &bson.RawValue{Type: bson.TypeInt32, Value: bsoncore.AppendInt32(nil, 1000)},
					TrimFactor: &trimFactor,
				})
			payload, err := clientEncryption.Encrypt(context.Background(), testVal, eo)
			assert.Nil(mt, err, "error in Encrypt: %v", err)
			assert.Greater(t, len(payload.Data), len(payloadDefaults.Data), "the returned payload size is expected to be greater than %d", len(payloadDefaults.Data))
		})
	})
}

func getWatcher(mt *mtest.T, streamType mongo.StreamType, cpt *cseProseTest) watcher {
	mt.Helper()

	switch streamType {
	case mongo.ClientStream:
		return cpt.cseClient
	case mongo.DatabaseStream:
		return cpt.cseColl.Database()
	case mongo.CollectionStream:
		return cpt.cseColl
	default:
		mt.Fatalf("unknown stream type %v", streamType)
	}
	return nil
}

type cseProseTest struct {
	coll         *mongo.Collection // collection db.coll
	kvClient     *mongo.Client
	keyVaultColl *mongo.Collection
	cseClient    *mongo.Client     // encrypted client
	cseColl      *mongo.Collection // db.coll with encrypted client
	clientEnc    *mongo.ClientEncryption
	cseStarted   []*event.CommandStartedEvent
}

func setup(mt *mtest.T, aeo *options.AutoEncryptionOptions, kvClientOpts *options.ClientOptions,
	ceo *options.ClientEncryptionOptions) *cseProseTest {
	mt.Helper()
	var cpt cseProseTest
	var err error
	cpt.coll = mt.CreateCollection(mtest.Collection{
		Name: "coll",
		DB:   "db",
		Opts: options.Collection().SetWriteConcern(mtest.MajorityWc),
	}, false)
	cpt.keyVaultColl = mt.CreateCollection(mtest.Collection{
		Name: "datakeys",
		DB:   "keyvault",
		Opts: options.Collection().SetWriteConcern(mtest.MajorityWc),
	}, false)

	if aeo != nil {
		cseMonitor := &event.CommandMonitor{
			Started: func(_ context.Context, evt *event.CommandStartedEvent) {
				cpt.cseStarted = append(cpt.cseStarted, evt)
			},
		}
		opts := options.Client().ApplyURI(mtest.ClusterURI()).SetWriteConcern(mtest.MajorityWc).
			SetReadPreference(mtest.PrimaryRp).SetAutoEncryptionOptions(aeo).SetMonitor(cseMonitor)
		integtest.AddTestServerAPIVersion(opts)
		cpt.cseClient, err = mongo.Connect(context.Background(), opts)
		assert.Nil(mt, err, "Connect error for encrypted client: %v", err)
		cpt.cseColl = cpt.cseClient.Database("db").Collection("coll")
	}
	if ceo != nil {
		cpt.kvClient, err = mongo.Connect(context.Background(), kvClientOpts)
		assert.Nil(mt, err, "Connect error for ClientEncryption key vault client: %v", err)
		cpt.clientEnc, err = mongo.NewClientEncryption(cpt.kvClient, ceo)
		assert.Nil(mt, err, "NewClientEncryption error: %v", err)
	}
	return &cpt
}

func (cpt *cseProseTest) teardown(mt *mtest.T) {
	mt.Helper()

	if cpt.cseClient != nil {
		_ = cpt.cseClient.Disconnect(context.Background())
	}
	if cpt.clientEnc != nil {
		_ = cpt.clientEnc.Close(context.Background())
	}
}

func readJSONFile(mt *mtest.T, file string) bson.Raw {
	mt.Helper()

	content, err := ioutil.ReadFile(filepath.Join(clientEncryptionProseDir, file))
	assert.Nil(mt, err, "ReadFile error for %v: %v", file, err)

	var doc bson.Raw
	err = bson.UnmarshalExtJSON(content, true, &doc)
	assert.Nil(mt, err, "UnmarshalExtJSON error for file %v: %v", file, err)
	return doc
}

func decodeJSONFile(mt *mtest.T, file string, val interface{}) bson.Raw {
	mt.Helper()

	content, err := ioutil.ReadFile(filepath.Join(clientEncryptionProseDir, file))
	assert.Nil(mt, err, "ReadFile error for %v: %v", file, err)

	var doc bson.Raw
	err = bson.UnmarshalExtJSON(content, true, val)
	assert.Nil(mt, err, "UnmarshalExtJSON error for file %v: %v", file, err)
	return doc
}

func rawValueToCoreValue(rv bson.RawValue) bsoncore.Value {
	return bsoncore.Value{Type: rv.Type, Data: rv.Value}
}

type deadlockTest struct {
	clientTest           *mongo.Client
	clientKeyVaultOpts   *options.ClientOptions
	clientKeyVaultEvents []startedEvent
	clientEncryption     *mongo.ClientEncryption
	ciphertext           primitive.Binary
}

type startedEvent struct {
	Command  string
	Database string
}

func newDeadlockTest(mt *mtest.T) *deadlockTest {
	mt.Helper()

	var d deadlockTest
	var err error

	clientTestOpts := options.Client().ApplyURI(mtest.ClusterURI()).SetWriteConcern(mtest.MajorityWc)
	integtest.AddTestServerAPIVersion(clientTestOpts)
	if d.clientTest, err = mongo.Connect(context.Background(), clientTestOpts); err != nil {
		mt.Fatalf("Connect error: %v", err)
	}

	clientKeyVaultMonitor := &event.CommandMonitor{
		Started: func(ctx context.Context, event *event.CommandStartedEvent) {
			startedEvent := startedEvent{event.CommandName, event.DatabaseName}
			d.clientKeyVaultEvents = append(d.clientKeyVaultEvents, startedEvent)
		},
	}

	d.clientKeyVaultOpts = options.Client().ApplyURI(mtest.ClusterURI()).
		SetMaxPoolSize(1).SetMonitor(clientKeyVaultMonitor)

	keyvaultColl := d.clientTest.Database("keyvault").Collection("datakeys")
	dataColl := d.clientTest.Database("db").Collection("coll")
	err = dataColl.Drop(context.Background())
	assert.Nil(mt, err, "Drop error for collection db.coll: %v", err)

	err = keyvaultColl.Drop(context.Background())
	assert.Nil(mt, err, "Drop error for key vault collection: %v", err)

	keyDoc := readJSONFile(mt, "external-key.json")
	_, err = keyvaultColl.InsertOne(context.Background(), keyDoc)
	assert.Nil(mt, err, "InsertOne error into key vault collection: %v", err)

	schemaDoc := readJSONFile(mt, "external-schema.json")
	createOpts := options.CreateCollection().SetValidator(bson.M{"$jsonSchema": schemaDoc})
	err = d.clientTest.Database("db").CreateCollection(context.Background(), "coll", createOpts)
	assert.Nil(mt, err, "CreateCollection error: %v", err)

	kmsProviders := map[string]map[string]interface{}{
		"local": {"key": localMasterKey},
	}
	ceOpts := options.ClientEncryption().SetKmsProviders(kmsProviders).SetKeyVaultNamespace("keyvault.datakeys")
	d.clientEncryption, err = mongo.NewClientEncryption(d.clientTest, ceOpts)
	assert.Nil(mt, err, "NewClientEncryption error: %v", err)

	t, value, err := bson.MarshalValue("string0")
	assert.Nil(mt, err, "MarshalValue error: %v", err)
	in := bson.RawValue{Type: t, Value: value}
	eopts := options.Encrypt().SetAlgorithm("AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic").SetKeyAltName("local")
	d.ciphertext, err = d.clientEncryption.Encrypt(context.Background(), in, eopts)
	assert.Nil(mt, err, "Encrypt error: %v", err)

	return &d
}

func (d *deadlockTest) disconnect(mt *mtest.T) {
	mt.Helper()
	err := d.clientEncryption.Close(context.Background())
	assert.Nil(mt, err, "clientEncryption Close error: %v", err)
	d.clientTest.Disconnect(context.Background())
	assert.Nil(mt, err, "clientTest Disconnect error: %v", err)
}

// listenForConnections creates a listener that will listen for connections.
// The user provided run function will be called with the accepted
// connection. The user is responsible for calling Close on the returned listener.
func listenForConnections(t *testing.T, run func(net.Conn)) net.Listener {
	t.Helper()

	l, err := net.Listen("tcp", "localhost:0")
	if err != nil {
		t.Errorf("Could not set up a listener: %v", err)
		t.FailNow()
	}
	go func() {
		for {
			// Ignore errors due to closing the listener connection.
			c, _ := l.Accept()
			if c == nil {
				break
			}
			go run(c)
		}
	}()
	return l
}

type localTransport struct {
	rt http.RoundTripper

	header http.Header
}

func (t *localTransport) RoundTrip(req *http.Request) (*http.Response, error) {
	r := req.Clone(req.Context())
	r.URL.Host = "localhost:8080"
	for key, vals := range t.header {
		for _, val := range vals {
			r.Header.Add(key, val)
		}
	}
	return t.rt.RoundTrip(r)
}