File: test_auth_oidc.py

package info (click to toggle)
pymongo 4.15.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 23,692 kB
  • sloc: python: 107,407; ansic: 4,601; javascript: 137; makefile: 30; sh: 10
file content (1192 lines) | stat: -rw-r--r-- 47,364 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
# Copyright 2023-present MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Test MONGODB-OIDC Authentication."""
from __future__ import annotations

import os
import sys
import time
import unittest
import warnings
from contextlib import asynccontextmanager
from pathlib import Path
from test.asynchronous import AsyncPyMongoTestCase
from test.asynchronous.helpers import ConcurrentRunner
from typing import Dict

import pytest

sys.path[0:0] = [""]

from test.asynchronous.unified_format import generate_test_classes
from test.utils_shared import EventListener, OvertCommandListener

from bson import SON
from pymongo import AsyncMongoClient
from pymongo._azure_helpers import _get_azure_response
from pymongo._gcp_helpers import _get_gcp_response
from pymongo.asynchronous.auth_oidc import (
    OIDCCallback,
    OIDCCallbackContext,
    OIDCCallbackResult,
    _get_authenticator,
)
from pymongo.auth_oidc_shared import _get_k8s_token
from pymongo.auth_shared import _build_credentials_tuple
from pymongo.cursor_shared import CursorType
from pymongo.errors import AutoReconnect, ConfigurationError, OperationFailure
from pymongo.hello import HelloCompat
from pymongo.operations import InsertOne
from pymongo.synchronous.uri_parser import parse_uri

_IS_SYNC = False

ROOT = Path(__file__).parent.parent.resolve()
TEST_PATH = ROOT / "auth" / "unified"
ENVIRON = os.environ.get("OIDC_ENV", "test")
DOMAIN = os.environ.get("OIDC_DOMAIN", "")
TOKEN_DIR = os.environ.get("OIDC_TOKEN_DIR", "")
TOKEN_FILE = os.environ.get("OIDC_TOKEN_FILE", "")

# Generate unified tests.
globals().update(generate_test_classes(str(TEST_PATH), module=__name__))

pytestmark = pytest.mark.auth_oidc


class OIDCTestBase(AsyncPyMongoTestCase):
    @classmethod
    def setUpClass(cls):
        cls.uri_single = os.environ["MONGODB_URI_SINGLE"]
        cls.uri_multiple = os.environ.get("MONGODB_URI_MULTI")
        cls.uri_admin = os.environ["MONGODB_URI"]
        if ENVIRON == "test":
            if not TOKEN_DIR:
                raise ValueError("Please set OIDC_TOKEN_DIR")
            if not TOKEN_FILE:
                raise ValueError("Please set OIDC_TOKEN_FILE")

    async def asyncSetUp(self):
        self.request_called = 0

    def get_token(self, username=None):
        """Get a token for the current provider."""
        if ENVIRON == "test":
            if username is None:
                token_file = TOKEN_FILE
            else:
                token_file = os.path.join(TOKEN_DIR, username)
            with open(token_file) as fid:  # noqa: ASYNC101,RUF100
                return fid.read()
        elif ENVIRON == "azure":
            opts = parse_uri(self.uri_single)["options"]
            token_aud = opts["authMechanismProperties"]["TOKEN_RESOURCE"]
            return _get_azure_response(token_aud, username)["access_token"]
        elif ENVIRON == "gcp":
            opts = parse_uri(self.uri_single)["options"]
            token_aud = opts["authMechanismProperties"]["TOKEN_RESOURCE"]
            return _get_gcp_response(token_aud, username)["access_token"]
        elif ENVIRON == "k8s":
            return _get_k8s_token()
        else:
            raise ValueError(f"Unknown ENVIRON: {ENVIRON}")

    @asynccontextmanager
    async def fail_point(self, command_args):
        cmd_on = SON([("configureFailPoint", "failCommand")])
        cmd_on.update(command_args)
        client = AsyncMongoClient(self.uri_admin)
        await client.admin.command(cmd_on)
        try:
            yield
        finally:
            await client.admin.command(
                "configureFailPoint", cmd_on["configureFailPoint"], mode="off"
            )
            await client.close()


class TestAuthOIDCHuman(OIDCTestBase):
    uri: str

    @classmethod
    def setUpClass(cls):
        if ENVIRON != "test":
            raise unittest.SkipTest("Human workflows are only tested with the test environment")
        if DOMAIN is None:
            raise ValueError("Missing OIDC_DOMAIN")
        super().setUpClass()

    async def asyncSetUp(self):
        self.refresh_present = 0
        await super().asyncSetUp()

    def create_request_cb(self, username="test_user1", sleep=0):
        def request_token(context: OIDCCallbackContext):
            # Validate the info.
            self.assertIsInstance(context.idp_info.issuer, str)
            if context.idp_info.clientId is not None:
                self.assertIsInstance(context.idp_info.clientId, str)

            # Validate the timeout.
            timeout_seconds = context.timeout_seconds
            self.assertEqual(timeout_seconds, 60 * 5)

            if context.refresh_token:
                self.refresh_present += 1

            token = self.get_token(username)
            resp = OIDCCallbackResult(access_token=token, refresh_token=token)

            time.sleep(sleep)
            self.request_called += 1
            return resp

        class Inner(OIDCCallback):
            def fetch(self, context):
                return request_token(context)

        return Inner()

    async def create_client(self, *args, **kwargs):
        username = kwargs.get("username", "test_user1")
        if kwargs.get("username") in ["test_user1", "test_user2"]:
            kwargs["username"] = f"{username}@{DOMAIN}"
        request_cb = kwargs.pop("request_cb", self.create_request_cb(username=username))
        props = kwargs.pop("authmechanismproperties", {"OIDC_HUMAN_CALLBACK": request_cb})
        kwargs["retryReads"] = False
        if not len(args):
            args = [self.uri_single]

        client = self.simple_client(*args, authmechanismproperties=props, **kwargs)

        return client

    async def test_1_1_single_principal_implicit_username(self):
        # Create default OIDC client with authMechanism=MONGODB-OIDC.
        client = await self.create_client()
        # Perform a find operation that succeeds.
        await client.test.test.find_one()
        # Close the client.
        await client.close()

    async def test_1_2_single_principal_explicit_username(self):
        # Create a client with MONGODB_URI_SINGLE, a username of test_user1, authMechanism=MONGODB-OIDC, and the OIDC human callback.
        client = await self.create_client(username="test_user1")
        # Perform a find operation that succeeds.
        await client.test.test.find_one()
        # Close the client.
        await client.close()

    async def test_1_3_multiple_principal_user_1(self):
        if not self.uri_multiple:
            raise unittest.SkipTest("Test Requires Server with Multiple Workflow IdPs")
        # Create a client with MONGODB_URI_MULTI, a username of test_user1, authMechanism=MONGODB-OIDC, and the OIDC human callback.
        client = await self.create_client(self.uri_multiple, username="test_user1")
        # Perform a find operation that succeeds.
        await client.test.test.find_one()
        # Close the client.
        await client.close()

    async def test_1_4_multiple_principal_user_2(self):
        if not self.uri_multiple:
            raise unittest.SkipTest("Test Requires Server with Multiple Workflow IdPs")
        # Create a human callback that reads in the generated test_user2 token file.
        # Create a client with MONGODB_URI_MULTI, a username of test_user2, authMechanism=MONGODB-OIDC, and the OIDC human callback.
        client = await self.create_client(self.uri_multiple, username="test_user2")
        # Perform a find operation that succeeds.
        await client.test.test.find_one()
        # Close the client.
        await client.close()

    async def test_1_5_multiple_principal_no_user(self):
        if not self.uri_multiple:
            raise unittest.SkipTest("Test Requires Server with Multiple Workflow IdPs")
        # Create a client with MONGODB_URI_MULTI, no username, authMechanism=MONGODB-OIDC, and the OIDC human callback.
        client = await self.create_client(self.uri_multiple)
        # Assert that a find operation fails.
        with self.assertRaises(OperationFailure):
            await client.test.test.find_one()
        # Close the client.
        await client.close()

    async def test_1_6_allowed_hosts_blocked(self):
        # Create a default OIDC client, with an ALLOWED_HOSTS that is an empty list.
        request_token = self.create_request_cb()
        props: Dict = {"OIDC_HUMAN_CALLBACK": request_token, "ALLOWED_HOSTS": []}
        client = await self.create_client(authmechanismproperties=props)
        # Assert that a find operation fails with a client-side error.
        with self.assertRaises(ConfigurationError):
            await client.test.test.find_one()
        # Close the client.
        await client.close()

        # Create a client that uses the URL mongodb://localhost/?authMechanism=MONGODB-OIDC&ignored=example.com,
        # a human callback, and an ALLOWED_HOSTS that contains ["example.com"].
        props: Dict = {
            "OIDC_HUMAN_CALLBACK": request_token,
            "ALLOWED_HOSTS": ["example.com"],
        }
        with warnings.catch_warnings():
            warnings.simplefilter("default")
            client = await self.create_client(
                self.uri_single + "&ignored=example.com",
                authmechanismproperties=props,
                connect=False,
            )
            # Assert that a find operation fails with a client-side error.
            with self.assertRaises(ConfigurationError):
                await client.test.test.find_one()
        # Close the client.
        await client.close()

    async def test_1_7_allowed_hosts_in_connection_string_ignored(self):
        # Create an OIDC configured client with the connection string: `mongodb+srv://example.com/?authMechanism=MONGODB-OIDC&authMechanismProperties=ALLOWED_HOSTS:%5B%22example.com%22%5D` and a Human Callback.
        # Assert that the creation of the client raises a configuration error.
        uri = "mongodb+srv://example.com?authMechanism=MONGODB-OIDC&authMechanismProperties=ALLOWED_HOSTS:%5B%22example.com%22%5D"
        with self.assertRaises(ConfigurationError), warnings.catch_warnings():
            warnings.simplefilter("ignore")
            c = AsyncMongoClient(
                uri,
                authmechanismproperties=dict(OIDC_HUMAN_CALLBACK=self.create_request_cb()),
            )
            await c.aconnect()

    async def test_1_8_machine_idp_human_callback(self):
        if not os.environ.get("OIDC_IS_LOCAL"):
            raise unittest.SkipTest("Test Requires Local OIDC server")
        # Create a client with MONGODB_URI_SINGLE, a username of test_machine, authMechanism=MONGODB-OIDC, and the OIDC human callback.
        client = await self.create_client(username="test_machine")
        # Perform a find operation that succeeds.
        await client.test.test.find_one()
        # Close the client.
        await client.close()

    async def test_2_1_valid_callback_inputs(self):
        # Create a AsyncMongoClient with a human callback that validates its inputs and returns a valid access token.
        client = await self.create_client()
        # Perform a find operation that succeeds. Verify that the human callback was called with the appropriate inputs, including the timeout parameter if possible.
        # Ensure that there are no unexpected fields.
        await client.test.test.find_one()
        # Close the client.
        await client.close()

    async def test_2_2_callback_returns_missing_data(self):
        # Create a AsyncMongoClient with a human callback that returns data not conforming to the OIDCCredential with missing fields.
        class CustomCB(OIDCCallback):
            def fetch(self, ctx):
                return dict()

        client = await self.create_client(request_cb=CustomCB())
        # Perform a find operation that fails.
        with self.assertRaises(ValueError):
            await client.test.test.find_one()
        # Close the client.
        await client.close()

    async def test_2_3_refresh_token_is_passed_to_the_callback(self):
        # Create a AsyncMongoClient with a human callback that checks for the presence of a refresh token.
        client = await self.create_client()

        # Perform a find operation that succeeds.
        await client.test.test.find_one()

        # Set a fail point for ``find`` commands.
        async with self.fail_point(
            {
                "mode": {"times": 1},
                "data": {"failCommands": ["find"], "errorCode": 391},
            }
        ):
            # Perform a ``find`` operation that succeeds.
            await client.test.test.find_one()

        # Assert that the callback has been called twice.
        self.assertEqual(self.request_called, 2)

        # Assert that the refresh token was used once.
        self.assertEqual(self.refresh_present, 1)

    async def test_3_1_uses_speculative_authentication_if_there_is_a_cached_token(self):
        # Create a client with a human callback that returns a valid token.
        client = await self.create_client()

        # Set a fail point for ``find`` commands.
        async with self.fail_point(
            {
                "mode": {"times": 1},
                "data": {"failCommands": ["find"], "errorCode": 391, "closeConnection": True},
            }
        ):
            # Perform a ``find`` operation that fails.
            with self.assertRaises(AutoReconnect):
                await client.test.test.find_one()

        # Set a fail point for ``saslStart`` commands.
        async with self.fail_point(
            {
                "mode": {"times": 1},
                "data": {"failCommands": ["saslStart"], "errorCode": 18},
            }
        ):
            # Perform a ``find`` operation that succeeds
            await client.test.test.find_one()

        # Close the client.
        await client.close()

    async def test_3_2_does_not_use_speculative_authentication_if_there_is_no_cached_token(self):
        # Create a ``AsyncMongoClient`` with a human callback that returns a valid token
        client = await self.create_client()

        # Set a fail point for ``saslStart`` commands.
        async with self.fail_point(
            {
                "mode": {"times": 1},
                "data": {"failCommands": ["saslStart"], "errorCode": 18},
            }
        ):
            # Perform a ``find`` operation that fails.
            with self.assertRaises(OperationFailure):
                await client.test.test.find_one()

        # Close the client.
        await client.close()

    async def test_4_1_reauthenticate_succeeds(self):
        # Create a default OIDC client and add an event listener.
        # The following assumes that the driver does not emit saslStart or saslContinue events.
        # If the driver does emit those events, ignore/filter them for the purposes of this test.
        listener = OvertCommandListener()
        client = await self.create_client(event_listeners=[listener])

        # Perform a find operation that succeeds.
        await client.test.test.find_one()

        # Assert that the human callback has been called once.
        self.assertEqual(self.request_called, 1)

        # Clear the listener state if possible.
        listener.reset()

        # Force a reauthenication using a fail point.
        async with self.fail_point(
            {
                "mode": {"times": 1},
                "data": {"failCommands": ["find"], "errorCode": 391},
            }
        ):
            # Perform another find operation that succeeds.
            await client.test.test.find_one()

        # Assert that the human callback has been called twice.
        self.assertEqual(self.request_called, 2)

        # Assert that the ordering of list started events is [find, find].
        # Note that if the listener stat could not be cleared then there will be an extra find command.
        started_events = [
            i.command_name for i in listener.started_events if not i.command_name.startswith("sasl")
        ]
        succeeded_events = [
            i.command_name
            for i in listener.succeeded_events
            if not i.command_name.startswith("sasl")
        ]
        failed_events = [
            i.command_name for i in listener.failed_events if not i.command_name.startswith("sasl")
        ]

        self.assertEqual(
            started_events,
            [
                "find",
                "find",
            ],
        )
        # Assert that the list of command succeeded events is [find].
        self.assertEqual(succeeded_events, ["find"])
        # Assert that a find operation failed once during the command execution.
        self.assertEqual(failed_events, ["find"])
        # Close the client.
        await client.close()

    async def test_4_2_reauthenticate_succeeds_no_refresh(self):
        # Create a default OIDC client with a human callback that does not return a refresh token.
        cb = self.create_request_cb()

        class CustomRequest(OIDCCallback):
            def fetch(self, *args, **kwargs):
                result = cb.fetch(*args, **kwargs)
                result.refresh_token = None
                return result

        client = await self.create_client(request_cb=CustomRequest())

        # Perform a find operation that succeeds.
        await client.test.test.find_one()

        # Assert that the human callback has been called once.
        self.assertEqual(self.request_called, 1)

        # Force a reauthenication using a fail point.
        async with self.fail_point(
            {
                "mode": {"times": 1},
                "data": {"failCommands": ["find"], "errorCode": 391},
            }
        ):
            # Perform a find operation that succeeds.
            await client.test.test.find_one()

        # Assert that the human callback has been called twice.
        self.assertEqual(self.request_called, 2)
        # Close the client.
        await client.close()

    async def test_4_3_reauthenticate_succeeds_after_refresh_fails(self):
        # Create a default OIDC client with a human callback that returns an invalid refresh token
        cb = self.create_request_cb()

        class CustomRequest(OIDCCallback):
            def fetch(self, *args, **kwargs):
                result = cb.fetch(*args, **kwargs)
                result.refresh_token = "bad"
                return result

        client = await self.create_client(request_cb=CustomRequest())

        # Perform a find operation that succeeds.
        await client.test.test.find_one()

        # Assert that the human callback has been called once.
        self.assertEqual(self.request_called, 1)

        # Force a reauthenication using a fail point.
        async with self.fail_point(
            {
                "mode": {"times": 1},
                "data": {"failCommands": ["find"], "errorCode": 391},
            }
        ):
            # Perform a find operation that succeeds.
            await client.test.test.find_one()

        # Assert that the human callback has been called 2 times.
        self.assertEqual(self.request_called, 2)

        # Close the client.
        await client.close()

    async def test_4_4_reauthenticate_fails(self):
        # Create a default OIDC client with a human callback that returns invalid refresh tokens and
        # Returns invalid access tokens after the first access.
        cb = self.create_request_cb()

        class CustomRequest(OIDCCallback):
            fetch_called = 0

            def fetch(self, *args, **kwargs):
                self.fetch_called += 1
                result = cb.fetch(*args, **kwargs)
                result.refresh_token = "bad"
                if self.fetch_called > 1:
                    result.access_token = "bad"
                return result

        client = await self.create_client(request_cb=CustomRequest())

        # Perform a find operation that succeeds (to force a speculative auth).
        await client.test.test.find_one()
        # Assert that the human callback has been called once.
        self.assertEqual(self.request_called, 1)

        # Force a reauthentication using a failCommand.
        async with self.fail_point(
            {
                "mode": {"times": 1},
                "data": {"failCommands": ["find"], "errorCode": 391},
            }
        ):
            # Perform a find operation that fails.
            with self.assertRaises(OperationFailure):
                await client.test.test.find_one()

        # Assert that the human callback has been called three times.
        self.assertEqual(self.request_called, 3)

        # Close the client.
        await client.close()

    async def test_request_callback_returns_null(self):
        class RequestTokenNull(OIDCCallback):
            def fetch(self, a):
                return None

        client = await self.create_client(request_cb=RequestTokenNull())
        with self.assertRaises(ValueError):
            await client.test.test.find_one()
        await client.close()

    async def test_request_callback_invalid_result(self):
        class CallbackInvalidToken(OIDCCallback):
            def fetch(self, a):
                return {}

        client = await self.create_client(request_cb=CallbackInvalidToken())
        with self.assertRaises(ValueError):
            await client.test.test.find_one()
        await client.close()

    async def test_reauthentication_succeeds_multiple_connections(self):
        request_cb = self.create_request_cb()

        # Create a client with the callback.
        client1 = await self.create_client(request_cb=request_cb)
        client2 = await self.create_client(request_cb=request_cb)

        # Perform an insert operation.
        await client1.test.test.insert_many([{"a": 1}, {"a": 1}])
        await client2.test.test.find_one()
        self.assertEqual(self.request_called, 2)

        # Use the same authenticator for both clients
        # to simulate a race condition with separate connections.
        # We should only see one extra callback despite both connections
        # needing to reauthenticate.
        client2.options.pool_options._credentials.cache.data = (
            client1.options.pool_options._credentials.cache.data
        )

        await client1.test.test.find_one()
        await client2.test.test.find_one()

        async with self.fail_point(
            {
                "mode": {"times": 1},
                "data": {"failCommands": ["find"], "errorCode": 391},
            }
        ):
            await client1.test.test.find_one()

        self.assertEqual(self.request_called, 3)

        async with self.fail_point(
            {
                "mode": {"times": 1},
                "data": {"failCommands": ["find"], "errorCode": 391},
            }
        ):
            await client2.test.test.find_one()

        self.assertEqual(self.request_called, 3)
        await client1.close()
        await client2.close()

    # PyMongo specific tests, since we have multiple code paths for reauth handling.

    async def test_reauthenticate_succeeds_bulk_write(self):
        # Create a client.
        client = await self.create_client()

        # Perform a find operation.
        await client.test.test.find_one()

        # Assert that the request callback has been called once.
        self.assertEqual(self.request_called, 1)

        async with self.fail_point(
            {
                "mode": {"times": 1},
                "data": {"failCommands": ["insert"], "errorCode": 391},
            }
        ):
            # Perform a bulk write operation.
            await client.test.test.bulk_write([InsertOne({})])  # type:ignore[type-var]

        # Assert that the request callback has been called twice.
        self.assertEqual(self.request_called, 2)
        await client.close()

    async def test_reauthenticate_succeeds_bulk_read(self):
        # Create a client.
        client = await self.create_client()

        # Perform a find operation.
        await client.test.test.find_one()

        # Perform a bulk write operation.
        await client.test.test.bulk_write([InsertOne({})])  # type:ignore[type-var]

        # Assert that the request callback has been called once.
        self.assertEqual(self.request_called, 1)

        async with self.fail_point(
            {
                "mode": {"times": 1},
                "data": {"failCommands": ["find"], "errorCode": 391},
            }
        ):
            # Perform a bulk read operation.
            cursor = client.test.test.find_raw_batches({})
            await cursor.to_list()

        # Assert that the request callback has been called twice.
        self.assertEqual(self.request_called, 2)
        await client.close()

    async def test_reauthenticate_succeeds_cursor(self):
        # Create a client.
        client = await self.create_client()

        # Perform an insert operation.
        await client.test.test.insert_one({"a": 1})

        # Assert that the request callback has been called once.
        self.assertEqual(self.request_called, 1)

        async with self.fail_point(
            {
                "mode": {"times": 1},
                "data": {"failCommands": ["find"], "errorCode": 391},
            }
        ):
            # Perform a find operation.
            cursor = client.test.test.find({"a": 1})
            self.assertGreaterEqual(len(await cursor.to_list()), 1)

        # Assert that the request callback has been called twice.
        self.assertEqual(self.request_called, 2)
        await client.close()

    async def test_reauthenticate_succeeds_get_more(self):
        # Create a client.
        client = await self.create_client()

        # Perform an insert operation.
        await client.test.test.insert_many([{"a": 1}, {"a": 1}])

        # Assert that the request callback has been called once.
        self.assertEqual(self.request_called, 1)

        async with self.fail_point(
            {
                "mode": {"times": 1},
                "data": {"failCommands": ["getMore"], "errorCode": 391},
            }
        ):
            # Perform a find operation.
            cursor = client.test.test.find({"a": 1}, batch_size=1)
            self.assertGreaterEqual(len(await cursor.to_list()), 1)

        # Assert that the request callback has been called twice.
        self.assertEqual(self.request_called, 2)
        await client.close()

    async def test_reauthenticate_succeeds_get_more_exhaust(self):
        # Ensure no mongos
        client = await self.create_client()
        hello = await client.admin.command(HelloCompat.LEGACY_CMD)
        if hello.get("msg") != "isdbgrid":
            raise unittest.SkipTest("Must not be a mongos")

        # Create a client with the callback.
        client = await self.create_client()

        # Perform an insert operation.
        await client.test.test.insert_many([{"a": 1}, {"a": 1}])

        # Assert that the request callback has been called once.
        self.assertEqual(self.request_called, 1)

        async with self.fail_point(
            {
                "mode": {"times": 1},
                "data": {"failCommands": ["getMore"], "errorCode": 391},
            }
        ):
            # Perform a find operation.
            cursor = client.test.test.find({"a": 1}, batch_size=1, cursor_type=CursorType.EXHAUST)
            self.assertGreaterEqual(len(await cursor.to_list()), 1)

        # Assert that the request callback has been called twice.
        self.assertEqual(self.request_called, 2)
        await client.close()

    async def test_reauthenticate_succeeds_command(self):
        # Create a client.
        client = await self.create_client()

        # Perform an insert operation.
        await client.test.test.insert_one({"a": 1})

        # Assert that the request callback has been called once.
        self.assertEqual(self.request_called, 1)

        async with self.fail_point(
            {
                "mode": {"times": 1},
                "data": {"failCommands": ["count"], "errorCode": 391},
            }
        ):
            # Perform a count operation.
            cursor = await client.test.command({"count": "test"})

        self.assertGreaterEqual(len(cursor), 1)

        # Assert that the request callback has been called twice.
        self.assertEqual(self.request_called, 2)
        await client.close()


class TestAuthOIDCMachine(OIDCTestBase):
    uri: str

    async def asyncSetUp(self):
        self.request_called = 0

    def create_request_cb(self, username=None, sleep=0):
        def request_token(context):
            assert isinstance(context.timeout_seconds, int)
            assert context.version == 1
            assert context.refresh_token is None
            assert context.idp_info is None
            token = self.get_token(username)
            time.sleep(sleep)
            self.request_called += 1
            return OIDCCallbackResult(access_token=token)

        class Inner(OIDCCallback):
            def fetch(self, context):
                return request_token(context)

        return Inner()

    async def create_client(self, *args, **kwargs):
        request_cb = kwargs.pop("request_cb", self.create_request_cb())
        props = kwargs.pop("authmechanismproperties", {"OIDC_CALLBACK": request_cb})
        kwargs["retryReads"] = False
        if not len(args):
            args = [self.uri_single]
        client = AsyncMongoClient(*args, authmechanismproperties=props, **kwargs)
        self.addAsyncCleanup(client.close)
        return client

    async def test_1_1_callback_is_called_during_reauthentication(self):
        # Create a ``AsyncMongoClient`` configured with a custom OIDC callback that
        # implements the provider logic.
        client = await self.create_client()
        # Perform a ``find`` operation that succeeds.
        await client.test.test.find_one()
        # Assert that the callback was called 1 time.
        self.assertEqual(self.request_called, 1)

    async def test_1_2_callback_is_called_once_for_multiple_connections(self):
        # Create a ``AsyncMongoClient`` configured with a custom OIDC callback that
        # implements the provider logic.
        client = await self.create_client()
        await client.aconnect()

        # Start 10 tasks and run 100 find operations that all succeed in each task.
        async def target():
            for _ in range(100):
                await client.test.test.find_one()

        tasks = []
        for i in range(10):
            tasks.append(ConcurrentRunner(target=target))
        for t in tasks:
            await t.start()
        for t in tasks:
            await t.join()
        # Assert that the callback was called 1 time.
        self.assertEqual(self.request_called, 1)

    async def test_2_1_valid_callback_inputs(self):
        # Create a AsyncMongoClient configured with an OIDC callback that validates its inputs and returns a valid access token.
        client = await self.create_client()
        # Perform a find operation that succeeds.
        await client.test.test.find_one()
        # Assert that the OIDC callback was called with the appropriate inputs, including the timeout parameter if possible. Ensure that there are no unexpected fields.
        self.assertEqual(self.request_called, 1)

    async def test_2_2_oidc_callback_returns_null(self):
        # Create a AsyncMongoClient configured with an OIDC callback that returns null.
        class CallbackNullToken(OIDCCallback):
            def fetch(self, a):
                return None

        client = await self.create_client(request_cb=CallbackNullToken())
        # Perform a find operation that fails.
        with self.assertRaises(ValueError):
            await client.test.test.find_one()

    async def test_2_3_oidc_callback_returns_missing_data(self):
        # Create a AsyncMongoClient configured with an OIDC callback that returns data not conforming to the OIDCCredential with missing fields.
        class CustomCallback(OIDCCallback):
            count = 0

            def fetch(self, a):
                self.count += 1
                return object()

        client = await self.create_client(request_cb=CustomCallback())
        # Perform a find operation that fails.
        with self.assertRaises(ValueError):
            await client.test.test.find_one()

    async def test_2_4_invalid_client_configuration_with_callback(self):
        # Create a AsyncMongoClient configured with an OIDC callback and auth mechanism property ENVIRONMENT:test.
        request_cb = self.create_request_cb()
        props: Dict = {"OIDC_CALLBACK": request_cb, "ENVIRONMENT": "test"}
        # Assert it returns a client configuration error.
        with self.assertRaises(ConfigurationError):
            await self.create_client(authmechanismproperties=props)

    async def test_2_5_invalid_use_of_ALLOWED_HOSTS(self):
        # Create an OIDC configured client with auth mechanism properties `{"ENVIRONMENT": "test", "ALLOWED_HOSTS": []}`.
        props: Dict = {"ENVIRONMENT": "test", "ALLOWED_HOSTS": []}
        # Assert it returns a client configuration error.
        with self.assertRaises(ConfigurationError):
            await self.create_client(authmechanismproperties=props)

        # Create an OIDC configured client with auth mechanism properties `{"OIDC_CALLBACK": "<my_callback>", "ALLOWED_HOSTS": []}`.
        props: Dict = {"OIDC_CALLBACK": self.create_request_cb(), "ALLOWED_HOSTS": []}
        # Assert it returns a client configuration error.
        with self.assertRaises(ConfigurationError):
            await self.create_client(authmechanismproperties=props)

    async def test_2_6_ALLOWED_HOSTS_defaults_ignored(self):
        # Create a MongoCredential for OIDC with a machine callback.
        props = {"OIDC_CALLBACK": self.create_request_cb()}
        extra = dict(authmechanismproperties=props)
        mongo_creds = _build_credentials_tuple("MONGODB-OIDC", None, "foo", None, extra, "test")
        # Assert that creating an authenticator for example.com does not result in an error.
        authenticator = _get_authenticator(mongo_creds, ("example.com", 30))
        assert authenticator.properties.username == "foo"

        # Create a MongoCredential for OIDC with an ENVIRONMENT.
        props = {"ENVIRONMENT": "test"}
        extra = dict(authmechanismproperties=props)
        mongo_creds = _build_credentials_tuple("MONGODB-OIDC", None, None, None, extra, "test")
        # Assert that creating an authenticator for example.com does not result in an error.
        authenticator = _get_authenticator(mongo_creds, ("example.com", 30))
        assert authenticator.properties.username == ""

    async def test_3_1_authentication_failure_with_cached_tokens_fetch_a_new_token_and_retry(self):
        # Create a AsyncMongoClient and an OIDC callback that implements the provider logic.
        client = await self.create_client()
        await client.aconnect()
        # Poison the cache with an invalid access token.
        # Set a fail point for ``find`` command.
        async with self.fail_point(
            {
                "mode": {"times": 1},
                "data": {"failCommands": ["find"], "errorCode": 391, "closeConnection": True},
            }
        ):
            # Perform a ``find`` operation that fails. This is to force the ``AsyncMongoClient``
            # to cache an access token.
            with self.assertRaises(AutoReconnect):
                await client.test.test.find_one()
        # Poison the cache of the client.
        client.options.pool_options._credentials.cache.data.access_token = "bad"
        # Reset the request count.
        self.request_called = 0
        # Verify that a find succeeds.
        await client.test.test.find_one()
        # Verify that the callback was called 1 time.
        self.assertEqual(self.request_called, 1)

    async def test_3_2_authentication_failures_without_cached_tokens_returns_an_error(self):
        # Create a AsyncMongoClient configured with retryReads=false and an OIDC callback that always returns invalid access tokens.
        class CustomCallback(OIDCCallback):
            count = 0

            def fetch(self, a):
                self.count += 1
                return OIDCCallbackResult(access_token="bad value")

        callback = CustomCallback()
        client = await self.create_client(request_cb=callback)
        # Perform a ``find`` operation that fails.
        with self.assertRaises(OperationFailure):
            await client.test.test.find_one()
        # Verify that the callback was called 1 time.
        self.assertEqual(callback.count, 1)

    async def test_3_3_unexpected_error_code_does_not_clear_cache(self):
        # Create a ``AsyncMongoClient`` with a human callback that returns a valid token
        client = await self.create_client()

        # Set a fail point for ``saslStart`` commands.
        async with self.fail_point(
            {
                "mode": {"times": 1},
                "data": {"failCommands": ["saslStart"], "errorCode": 20},
            }
        ):
            # Perform a ``find`` operation that fails.
            with self.assertRaises(OperationFailure):
                await client.test.test.find_one()

        # Assert that the callback has been called once.
        self.assertEqual(self.request_called, 1)

        # Perform a ``find`` operation that succeeds.
        await client.test.test.find_one()

        # Assert that the callback has been called once.
        self.assertEqual(self.request_called, 1)

    async def test_4_1_reauthentication_succeeds(self):
        # Create a ``AsyncMongoClient`` configured with a custom OIDC callback that
        # implements the provider logic.
        client = await self.create_client()
        await client.aconnect()

        # Set a fail point for the find command.
        async with self.fail_point(
            {
                "mode": {"times": 1},
                "data": {"failCommands": ["find"], "errorCode": 391},
            }
        ):
            # Perform a ``find`` operation that succeeds.
            await client.test.test.find_one()

        # Verify that the callback was called 2 times (once during the connection
        # handshake, and again during reauthentication).
        self.assertEqual(self.request_called, 2)

    async def test_4_2_read_commands_fail_if_reauthentication_fails(self):
        # Create a ``AsyncMongoClient`` whose OIDC callback returns one good token and then
        # bad tokens after the first call.
        get_token = self.get_token

        class CustomCallback(OIDCCallback):
            count = 0

            def fetch(self, _):
                self.count += 1
                if self.count == 1:
                    access_token = get_token()
                else:
                    access_token = "bad value"
                return OIDCCallbackResult(access_token=access_token)

        callback = CustomCallback()
        client = await self.create_client(request_cb=callback)

        # Perform a read operation that succeeds.
        await client.test.test.find_one()

        # Set a fail point for the find command.
        async with self.fail_point(
            {
                "mode": {"times": 1},
                "data": {"failCommands": ["find"], "errorCode": 391},
            }
        ):
            # Perform a ``find`` operation that fails.
            with self.assertRaises(OperationFailure):
                await client.test.test.find_one()

        # Verify that the callback was called 2 times.
        self.assertEqual(callback.count, 2)

    async def test_4_3_write_commands_fail_if_reauthentication_fails(self):
        # Create a ``AsyncMongoClient`` whose OIDC callback returns one good token and then
        # bad token after the first call.
        get_token = self.get_token

        class CustomCallback(OIDCCallback):
            count = 0

            def fetch(self, _):
                self.count += 1
                if self.count == 1:
                    access_token = get_token()
                else:
                    access_token = "bad value"
                return OIDCCallbackResult(access_token=access_token)

        callback = CustomCallback()
        client = await self.create_client(request_cb=callback)

        # Perform an insert operation that succeeds.
        await client.test.test.insert_one({})

        # Set a fail point for the find command.
        async with self.fail_point(
            {
                "mode": {"times": 1},
                "data": {"failCommands": ["insert"], "errorCode": 391},
            }
        ):
            # Perform a ``insert`` operation that fails.
            with self.assertRaises(OperationFailure):
                await client.test.test.insert_one({})

        # Verify that the callback was called 2 times.
        self.assertEqual(callback.count, 2)

    async def test_4_4_speculative_authentication_should_be_ignored_on_reauthentication(self):
        # Create an OIDC configured client that can listen for `SaslStart` commands.
        listener = EventListener()
        client = await self.create_client(event_listeners=[listener])
        await client.aconnect()

        # Preload the *Client Cache* with a valid access token to enforce Speculative Authentication.
        client2 = await self.create_client()
        await client2.test.test.find_one()
        client.options.pool_options._credentials.cache.data = (
            client2.options.pool_options._credentials.cache.data
        )
        await client2.close()
        self.request_called = 0

        # Perform an `insert` operation that succeeds.
        await client.test.test.insert_one({})

        # Assert that the callback was not called.
        self.assertEqual(self.request_called, 0)

        # Assert there were no `SaslStart` commands executed.
        assert not any(
            event.command_name.lower() == "saslstart" for event in listener.started_events
        )
        listener.reset()

        # Set a fail point for `insert` commands of the form:
        async with self.fail_point(
            {
                "mode": {"times": 1},
                "data": {"failCommands": ["insert"], "errorCode": 391},
            }
        ):
            # Perform an `insert` operation that succeeds.
            await client.test.test.insert_one({})

        # Assert that the callback was called once.
        self.assertEqual(self.request_called, 1)

        # Assert there were `SaslStart` commands executed.
        assert any(event.command_name.lower() == "saslstart" for event in listener.started_events)

    async def test_4_5_reauthentication_succeeds_when_a_session_is_involved(self):
        # Create an OIDC configured client.
        client = await self.create_client()

        # Set a fail point for `find` commands of the form:
        async with self.fail_point(
            {
                "mode": {"times": 1},
                "data": {"failCommands": ["find"], "errorCode": 391},
            }
        ):
            # Start a new session.
            async with client.start_session() as session:
                # In the started session perform a `find` operation that succeeds.
                await client.test.test.find_one({}, session=session)

        # Assert that the callback was called 2 times (once during the connection handshake, and again during reauthentication).
        self.assertEqual(self.request_called, 2)

    async def test_5_1_azure_with_no_username(self):
        if ENVIRON != "azure":
            raise unittest.SkipTest("Test is only supported on Azure")
        opts = parse_uri(self.uri_single)["options"]
        resource = opts["authMechanismProperties"]["TOKEN_RESOURCE"]

        props = dict(TOKEN_RESOURCE=resource, ENVIRONMENT="azure")
        client = await self.create_client(authMechanismProperties=props)
        await client.test.test.find_one()

    async def test_5_2_azure_with_bad_username(self):
        if ENVIRON != "azure":
            raise unittest.SkipTest("Test is only supported on Azure")

        opts = parse_uri(self.uri_single)["options"]
        token_aud = opts["authMechanismProperties"]["TOKEN_RESOURCE"]

        props = dict(TOKEN_RESOURCE=token_aud, ENVIRONMENT="azure")
        client = await self.create_client(username="bad", authmechanismproperties=props)
        with self.assertRaises(ValueError):
            await client.test.test.find_one()

    async def test_speculative_auth_success(self):
        client1 = await self.create_client()
        await client1.test.test.find_one()
        client2 = await self.create_client()
        await client2.aconnect()

        # Prime the cache of the second client.
        client2.options.pool_options._credentials.cache.data = (
            client1.options.pool_options._credentials.cache.data
        )

        # Set a fail point for saslStart commands.
        async with self.fail_point(
            {
                "mode": {"times": 2},
                "data": {"failCommands": ["saslStart"], "errorCode": 18},
            }
        ):
            # Perform a find operation.
            await client2.test.test.find_one()

    async def test_reauthentication_succeeds_multiple_connections(self):
        client1 = await self.create_client()
        client2 = await self.create_client()

        # Perform an insert operation.
        await client1.test.test.insert_many([{"a": 1}, {"a": 1}])
        await client2.test.test.find_one()
        self.assertEqual(self.request_called, 2)

        # Use the same authenticator for both clients
        # to simulate a race condition with separate connections.
        # We should only see one extra callback despite both connections
        # needing to reauthenticate.
        client2.options.pool_options._credentials.cache.data = (
            client1.options.pool_options._credentials.cache.data
        )

        await client1.test.test.find_one()
        await client2.test.test.find_one()

        async with self.fail_point(
            {
                "mode": {"times": 1},
                "data": {"failCommands": ["find"], "errorCode": 391},
            }
        ):
            await client1.test.test.find_one()

        self.assertEqual(self.request_called, 3)

        async with self.fail_point(
            {
                "mode": {"times": 1},
                "data": {"failCommands": ["find"], "errorCode": 391},
            }
        ):
            await client2.test.test.find_one()

        self.assertEqual(self.request_called, 3)


if __name__ == "__main__":
    unittest.main()