File: test_chained_token_credential_async.py

package info (click to toggle)
python-azure 20250603%2Bgit-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 851,724 kB
  • sloc: python: 7,362,925; ansic: 804; javascript: 287; makefile: 195; sh: 145; xml: 109
file content (306 lines) | stat: -rw-r--r-- 12,144 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
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
import time
from unittest.mock import Mock, patch

from azure.core.credentials import AccessToken, AccessTokenInfo
from azure.core.exceptions import ClientAuthenticationError
from azure.identity import CredentialUnavailableError, ClientSecretCredential
from azure.identity.aio import ChainedTokenCredential, ManagedIdentityCredential
from azure.identity._credentials.imds import IMDS_TOKEN_PATH, IMDS_AUTHORITY
from azure.identity._internal.user_agent import USER_AGENT
import pytest

from helpers import mock_response, Request, GET_TOKEN_METHODS
from helpers_async import get_completed_future, wrap_in_future, async_validating_transport


@pytest.mark.asyncio
async def test_close():
    credentials = [Mock(close=Mock(wraps=get_completed_future)) for _ in range(5)]
    chain = ChainedTokenCredential(*credentials)

    await chain.close()

    for credential in credentials:
        assert credential.close.call_count == 1


@pytest.mark.asyncio
async def test_context_manager():
    credentials = [Mock(close=Mock(wraps=get_completed_future)) for _ in range(5)]
    chain = ChainedTokenCredential(*credentials)

    async with chain:
        pass

    for credential in credentials:
        assert credential.close.call_count == 1


@pytest.mark.asyncio
@pytest.mark.parametrize("get_token_method", GET_TOKEN_METHODS)
async def test_credential_chain_error_message(get_token_method):
    first_error = "first_error"
    first_credential = Mock(
        spec=ClientSecretCredential,
        get_token=Mock(side_effect=CredentialUnavailableError(first_error)),
        get_token_info=Mock(side_effect=CredentialUnavailableError(first_error)),
    )
    second_error = "second_error"
    second_credential = Mock(
        name="second_credential",
        get_token=Mock(side_effect=ClientAuthenticationError(second_error)),
        get_token_info=Mock(side_effect=ClientAuthenticationError(second_error)),
    )

    with pytest.raises(ClientAuthenticationError) as ex:
        await getattr(ChainedTokenCredential(first_credential, second_credential), get_token_method)("scope")

    assert "ClientSecretCredential" in ex.value.message
    assert first_error in ex.value.message
    assert second_error in ex.value.message


@pytest.mark.asyncio
@pytest.mark.parametrize("get_token_method", GET_TOKEN_METHODS)
async def test_chain_attempts_all_credentials(get_token_method):
    async def credential_unavailable(message="it didn't work", **_):
        raise CredentialUnavailableError(message)

    access_token = "expected_token"
    credentials = [
        Mock(
            spec_set=["get_token", "get_token_info"],
            get_token=Mock(wraps=credential_unavailable),
            get_token_info=Mock(wraps=credential_unavailable),
        ),
        Mock(
            spec_set=["get_token", "get_token_info"],
            get_token=Mock(wraps=credential_unavailable),
            get_token_info=Mock(wraps=credential_unavailable),
        ),
        Mock(
            spec_set=["get_token", "get_token_info"],
            get_token=wrap_in_future(lambda _, **__: AccessToken(access_token, 42)),
            get_token_info=wrap_in_future(lambda _, **__: AccessTokenInfo(access_token, 42)),
        ),
    ]

    token = await getattr(ChainedTokenCredential(*credentials), get_token_method)("scope")
    assert token.token == access_token

    for credential in credentials[:-1]:
        assert getattr(credential, get_token_method).call_count == 1


@pytest.mark.asyncio
@pytest.mark.parametrize("get_token_method", GET_TOKEN_METHODS)
async def test_chain_raises_for_unexpected_error(get_token_method):
    """the chain should not continue after an unexpected error (i.e. anything but CredentialUnavailableError)"""

    async def credential_unavailable(message="it didn't work", **_):
        raise CredentialUnavailableError(message)

    expected_message = "it can't be done"

    credentials = [
        Mock(
            spec_set=["get_token", "get_token_info"],
            get_token=Mock(wraps=credential_unavailable),
            get_token_info=Mock(wraps=credential_unavailable),
        ),
        Mock(
            spec_set=["get_token", "get_token_info"],
            get_token=Mock(side_effect=ValueError(expected_message)),
            get_token_info=Mock(side_effect=ValueError(expected_message)),
        ),
        Mock(
            spec_set=["get_token", "get_token_info"],
            get_token=Mock(wraps=wrap_in_future(lambda _, **__: AccessToken("**", 42))),
            get_token_info=Mock(wraps=wrap_in_future(lambda _, **__: AccessTokenInfo("**", 42))),
        ),
    ]

    with pytest.raises(ClientAuthenticationError) as ex:
        await getattr(ChainedTokenCredential(*credentials), get_token_method)("scope")

    assert expected_message in ex.value.message
    assert getattr(credentials[-1], get_token_method).call_count == 0


@pytest.mark.asyncio
@pytest.mark.parametrize("get_token_method", GET_TOKEN_METHODS)
async def test_returns_first_token(get_token_method):
    access_token = "expected_token"
    first_credential = Mock(
        spec_set=["get_token", "get_token_info"],
        get_token=wrap_in_future(lambda _, **__: AccessToken(access_token, 42)),
        get_token_info=wrap_in_future(lambda _, **__: AccessTokenInfo(access_token, 42)),
    )
    second_credential = Mock(spec_set=["get_token", "get_token_info"], get_token=Mock(), get_token_info=Mock())

    aggregate = ChainedTokenCredential(first_credential, second_credential)
    token = await getattr(aggregate, get_token_method)("scope")

    assert token.token == access_token
    assert getattr(second_credential, get_token_method).call_count == 0


@pytest.mark.asyncio
@pytest.mark.parametrize("get_token_method", GET_TOKEN_METHODS)
async def test_managed_identity_imds_probe(get_token_method):
    access_token = "****"
    expires_on = 42
    scope = "scope"
    transport = async_validating_transport(
        requests=[
            Request(base_url=IMDS_AUTHORITY + IMDS_TOKEN_PATH),
            Request(
                base_url=IMDS_AUTHORITY + IMDS_TOKEN_PATH,
                method="GET",
                required_headers={"Metadata": "true", "User-Agent": USER_AGENT},
                required_params={"api-version": "2018-02-01", "resource": scope},
            ),
        ],
        responses=[
            mock_response(status_code=400, json_payload={"error": "this is an error message"}),
            mock_response(
                json_payload={
                    "access_token": access_token,
                    "expires_in": 42,
                    "expires_on": expires_on,
                    "ext_expires_in": 42,
                    "not_before": int(time.time()),
                    "resource": scope,
                    "token_type": "Bearer",
                }
            ),
        ],
    )

    # ensure e.g. $MSI_ENDPOINT isn't set, so we get ImdsCredential
    with patch.dict("os.environ", clear=True):
        credentials = [
            Mock(
                spec_set=["get_token", "get_token_info"],
                get_token=Mock(side_effect=CredentialUnavailableError(message="")),
                get_token_info=Mock(side_effect=CredentialUnavailableError(message="")),
            ),
            ManagedIdentityCredential(transport=transport),
        ]
        token = await getattr(ChainedTokenCredential(*credentials), get_token_method)(scope)
    assert token.token == access_token


@pytest.mark.asyncio
@pytest.mark.parametrize("get_token_method", GET_TOKEN_METHODS)
async def test_managed_identity_failed_probe(get_token_method):
    async def credential_unavailable(message="it didn't work", **_):
        raise CredentialUnavailableError(message)

    mock_send = Mock(side_effect=Exception("timeout"))
    transport = Mock(send=wrap_in_future(mock_send))

    expected_token = "***"
    credentials = [
        Mock(
            spec_set=["get_token", "get_token_info"],
            get_token=Mock(wraps=credential_unavailable),
            get_token_info=Mock(wraps=credential_unavailable),
        ),
        ManagedIdentityCredential(transport=transport),
        Mock(
            spec_set=["get_token", "get_token_info"],
            get_token=Mock(wraps=wrap_in_future(lambda _, **__: AccessToken(expected_token, 42))),
            get_token_info=Mock(wraps=wrap_in_future(lambda _, **__: AccessTokenInfo(expected_token, 42))),
        ),
    ]

    with patch.dict("os.environ", clear=True):
        token = await getattr(ChainedTokenCredential(*credentials), get_token_method)("scope")

    assert token.token == expected_token
    # ManagedIdentityCredential should be tried and skipped with the last credential in the chain
    # being used.
    assert getattr(credentials[-1], get_token_method).call_count == 1


@pytest.mark.asyncio
async def test_credentials_with_no_get_token_info():
    """ChainedTokenCredential should work with credentials that don't implement get_token_info."""

    async def credential_unavailable(message="it didn't work", **_):
        raise CredentialUnavailableError(message)

    access_token = "****"
    credential1 = Mock(
        spec_set=["get_token_info"],
        get_token_info=Mock(wraps=credential_unavailable),
    )
    credential2 = Mock(
        spec_set=["get_token"],
        get_token=Mock(wraps=wrap_in_future(lambda _, **__: AccessToken(access_token, 42))),
    )
    credential3 = Mock(
        spec_set=["get_token", "get_token_info"],
        get_token=Mock(wraps=wrap_in_future(lambda _, **__: AccessToken("foo", 42))),
        get_token_info=Mock(wraps=wrap_in_future(lambda _, **__: AccessTokenInfo("bar", 42))),
    )
    chain = ChainedTokenCredential(credential1, credential2, credential3)  # type: ignore
    token_info = await chain.get_token_info("scope")
    assert token_info.token == access_token


@pytest.mark.asyncio
async def test_credentials_with_no_get_token():
    """ChainedTokenCredential should work with credentials that only implement get_token_info."""

    async def credential_unavailable(message="it didn't work", **_):
        raise CredentialUnavailableError(message)

    access_token = "****"
    credential1 = Mock(
        spec_set=["get_token"],
        get_token=Mock(wraps=credential_unavailable),
    )
    credential2 = Mock(
        spec_set=["get_token_info"],
        get_token_info=Mock(wraps=wrap_in_future(lambda _, **__: AccessTokenInfo(access_token, 42))),
    )
    credential3 = Mock(
        spec_set=["get_token", "get_token_info"],
        get_token=Mock(wraps=wrap_in_future(lambda _, **__: AccessToken("foo", 42))),
        get_token_info=Mock(wraps=wrap_in_future(lambda _, **__: AccessTokenInfo("bar", 42))),
    )
    chain = ChainedTokenCredential(credential1, credential2, credential3)  # type: ignore
    token_info = await chain.get_token("scope")
    assert token_info.token == access_token


@pytest.mark.asyncio
async def test_credentials_with_pop_option():
    """ChainedTokenCredential should skip credentials that don't support get_token_info and the pop option is set."""

    async def credential_unavailable(message="it didn't work", **_):
        raise CredentialUnavailableError(message)

    access_token = "****"
    credential1 = Mock(
        spec_set=["get_token_info"],
        get_token_info=Mock(wraps=credential_unavailable),
    )
    credential2 = Mock(
        spec_set=["get_token"],
        get_token=Mock(wraps=wrap_in_future(lambda _, **__: AccessToken("foo", 42))),
    )
    credential3 = Mock(
        spec_set=["get_token", "get_token_info"],
        get_token=Mock(wraps=wrap_in_future(lambda _, **__: AccessToken("bar", 42))),
        get_token_info=Mock(wraps=wrap_in_future(lambda _, **__: AccessTokenInfo(access_token, 42))),
    )
    chain = ChainedTokenCredential(credential1, credential2, credential3)  # type: ignore
    token_info = await chain.get_token_info("scope", options={"pop": True})  # type: ignore
    assert token_info.token == access_token