File: test_mcspv2_authenticator.py

package info (click to toggle)
python-ibm-cloud-sdk-core 3.24.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 944 kB
  • sloc: python: 5,750; makefile: 40; xml: 7; sh: 7
file content (409 lines) | stat: -rw-r--r-- 15,426 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
# pylint: disable=missing-docstring
import logging
import json
import time
import jwt
import pytest
import responses

from ibm_cloud_sdk_core.authenticators import MCSPV2Authenticator, Authenticator
from ibm_cloud_sdk_core import MCSPV2TokenManager
from .utils.logger_utils import setup_test_logger

setup_test_logger(logging.ERROR)

MOCK_APIKEY = 'my-api-key'
MOCK_URL = 'https://mcspv2.ibm.com'
MOCK_SCOPE_COLLECTION_TYPE = 'accounts'
MOCK_SCOPE_ID = 'global_account'
MOCK_CALLER_EXT_CLAIM = {"productID": "prod-123"}
MOCK_HEADERS = {"header1": "value1", "header2": "value2"}
MOCK_PROXIES = {"https": "proxy1", "http": "proxy2"}
MOCK_PATH = '/api/2.0/{0}/{1}/apikeys/token'.format(MOCK_SCOPE_COLLECTION_TYPE, MOCK_SCOPE_ID)


# pylint: disable=too-many-statements
def test_mcspv2_authenticator1():
    # Use only required properties.
    authenticator = MCSPV2Authenticator(
        apikey=MOCK_APIKEY,
        url=MOCK_URL,
        scope_collection_type=MOCK_SCOPE_COLLECTION_TYPE,
        scope_id=MOCK_SCOPE_ID,
    )
    assert authenticator is not None
    assert authenticator.authentication_type() == Authenticator.AUTHTYPE_MCSPV2
    assert authenticator.token_manager.apikey == MOCK_APIKEY
    assert authenticator.token_manager.url == MOCK_URL
    assert authenticator.token_manager.scope_collection_type == MOCK_SCOPE_COLLECTION_TYPE
    assert authenticator.token_manager.scope_id == MOCK_SCOPE_ID
    assert authenticator.token_manager.include_builtin_actions is False
    assert authenticator.token_manager.include_custom_actions is False
    assert authenticator.token_manager.include_roles is True
    assert authenticator.token_manager.prefix_roles is False
    assert authenticator.token_manager.caller_ext_claim is None
    assert authenticator.token_manager.disable_ssl_verification is False
    assert authenticator.token_manager.headers is None
    assert authenticator.token_manager.proxies is None

    # Test setter functions.
    authenticator.set_scope_collection_type("subscriptions")
    assert authenticator.token_manager.scope_collection_type == "subscriptions"

    with pytest.raises(TypeError) as err:
        authenticator.set_scope_collection_type(None)
    assert str(err.value) == '"scope_collection_type" must be a string'

    authenticator.set_scope_id("new_id")
    assert authenticator.token_manager.scope_id == "new_id"

    with pytest.raises(TypeError) as err:
        authenticator.set_scope_id(None)
    assert str(err.value) == '"scope_id" must be a string'

    authenticator.set_include_builtin_actions(True)
    assert authenticator.token_manager.include_builtin_actions is True

    with pytest.raises(TypeError) as err:
        authenticator.set_include_builtin_actions('True')
    assert str(err.value) == '"include_builtin_actions" must be a bool'

    authenticator.set_include_custom_actions(True)
    assert authenticator.token_manager.include_custom_actions is True

    with pytest.raises(TypeError) as err:
        authenticator.set_include_custom_actions('not a bool')
    assert str(err.value) == '"include_custom_actions" must be a bool'

    authenticator.set_include_roles(True)
    assert authenticator.token_manager.include_roles is True

    with pytest.raises(TypeError) as err:
        authenticator.set_include_roles('nope')
    assert str(err.value) == '"include_roles" must be a bool'

    authenticator.set_prefix_roles(True)
    assert authenticator.token_manager.prefix_roles is True

    with pytest.raises(TypeError) as err:
        authenticator.set_prefix_roles('maybe')
    assert str(err.value) == '"prefix_roles" must be a bool'

    authenticator.set_caller_ext_claim(MOCK_CALLER_EXT_CLAIM)
    assert authenticator.token_manager.caller_ext_claim == MOCK_CALLER_EXT_CLAIM

    with pytest.raises(TypeError) as err:
        authenticator.set_caller_ext_claim('not a dictionary')
    assert str(err.value) == '"caller_ext_claim" must be a dictionary or None'

    authenticator.set_disable_ssl_verification(True)
    assert authenticator.token_manager.disable_ssl_verification is True

    with pytest.raises(TypeError) as err:
        authenticator.set_disable_ssl_verification('not a bool')
    assert str(err.value) == '"disable_ssl_verification" must be a bool'

    authenticator.set_headers(MOCK_HEADERS)
    assert authenticator.token_manager.headers == MOCK_HEADERS

    with pytest.raises(TypeError) as err:
        authenticator.set_headers('not a dictionary')
    assert str(err.value) == '"headers" must be a dictionary or None'

    authenticator.set_proxies(MOCK_PROXIES)
    assert authenticator.token_manager.proxies == MOCK_PROXIES

    with pytest.raises(TypeError) as err:
        authenticator.set_proxies('not a dictionary')
    assert str(err.value) == '"proxies" must be a dictionary or None'


def test_mcspv2_authenticator2():
    # Test with all properties.
    authenticator = MCSPV2Authenticator(
        apikey=MOCK_APIKEY,
        url=MOCK_URL,
        scope_collection_type=MOCK_SCOPE_COLLECTION_TYPE,
        scope_id=MOCK_SCOPE_ID,
        include_builtin_actions=True,
        include_custom_actions=True,
        include_roles=False,
        prefix_roles=True,
        caller_ext_claim=MOCK_CALLER_EXT_CLAIM,
        disable_ssl_verification=True,
        headers=MOCK_HEADERS,
        proxies=MOCK_PROXIES,
    )
    assert authenticator.token_manager.apikey == MOCK_APIKEY
    assert authenticator.token_manager.url == MOCK_URL
    assert authenticator.token_manager.scope_collection_type == MOCK_SCOPE_COLLECTION_TYPE
    assert authenticator.token_manager.scope_id == MOCK_SCOPE_ID
    assert authenticator.token_manager.include_builtin_actions is True
    assert authenticator.token_manager.include_custom_actions is True
    assert authenticator.token_manager.include_roles is False
    assert authenticator.token_manager.prefix_roles is True
    assert authenticator.token_manager.caller_ext_claim == MOCK_CALLER_EXT_CLAIM
    assert authenticator.token_manager.disable_ssl_verification is True
    assert authenticator.token_manager.headers == MOCK_HEADERS
    assert authenticator.token_manager.proxies == MOCK_PROXIES


def test_mcsp_authenticator_validate_failed():

    # Check each property individually.
    with pytest.raises(TypeError) as err:
        MCSPV2Authenticator(
            apikey=None,
            url=MOCK_URL,
            scope_collection_type=MOCK_SCOPE_COLLECTION_TYPE,
            scope_id=MOCK_SCOPE_ID,
        )
    assert str(err.value) == '"apikey" must be a string'

    with pytest.raises(TypeError) as err:
        MCSPV2Authenticator(
            apikey=MOCK_APIKEY,
            url=None,
            scope_collection_type=MOCK_SCOPE_COLLECTION_TYPE,
            scope_id=MOCK_SCOPE_ID,
        )
    assert str(err.value) == '"url" must be a string'

    with pytest.raises(TypeError) as err:
        MCSPV2Authenticator(
            apikey=MOCK_APIKEY,
            url=MOCK_URL,
            scope_collection_type=None,
            scope_id=MOCK_SCOPE_ID,
        )
    assert str(err.value) == '"scope_collection_type" must be a string'

    with pytest.raises(TypeError) as err:
        MCSPV2Authenticator(
            apikey=MOCK_APIKEY,
            url=MOCK_URL,
            scope_collection_type=MOCK_SCOPE_COLLECTION_TYPE,
            scope_id=None,
        )
    assert str(err.value) == '"scope_id" must be a string'

    with pytest.raises(TypeError) as err:
        MCSPV2Authenticator(
            apikey=MOCK_APIKEY,
            url=MOCK_URL,
            scope_collection_type=MOCK_SCOPE_COLLECTION_TYPE,
            scope_id=MOCK_SCOPE_ID,
            include_builtin_actions='not a bool',
        )
    assert str(err.value) == '"include_builtin_actions" must be a bool'

    with pytest.raises(TypeError) as err:
        MCSPV2Authenticator(
            apikey=MOCK_APIKEY,
            url=MOCK_URL,
            scope_collection_type=MOCK_SCOPE_COLLECTION_TYPE,
            scope_id=MOCK_SCOPE_ID,
            include_custom_actions=None,
        )
    assert str(err.value) == '"include_custom_actions" must be a bool'

    with pytest.raises(TypeError) as err:
        MCSPV2Authenticator(
            apikey=MOCK_APIKEY,
            url=MOCK_URL,
            scope_collection_type=MOCK_SCOPE_COLLECTION_TYPE,
            scope_id=MOCK_SCOPE_ID,
            include_roles=382636,
        )
    assert str(err.value) == '"include_roles" must be a bool'

    with pytest.raises(TypeError) as err:
        MCSPV2Authenticator(
            apikey=MOCK_APIKEY,
            url=MOCK_URL,
            scope_collection_type=MOCK_SCOPE_COLLECTION_TYPE,
            scope_id=MOCK_SCOPE_ID,
            prefix_roles=None,
        )
    assert str(err.value) == '"prefix_roles" must be a bool'


# utility function to construct a mock token server response containing an access token.
def get_mock_token_response(issued_at: int, time_to_live: int) -> str:
    access_token_layout = {
        "username": "dummy",
        "role": "Admin",
        "permissions": ["administrator", "manage_catalog"],
        "sub": "admin",
        "iss": "sss",
        "aud": "sss",
        "uid": "sss",
        "iat": issued_at,
        "exp": issued_at + time_to_live,
    }

    access_token = jwt.encode(
        access_token_layout, 'secret', algorithm='HS256', headers={'kid': '230498151c214b788dd97f22b85410a5'}
    )

    token_server_response = {
        "token": access_token,
        "token_type": "Bearer",
        "expires_in": time_to_live,
        "expiration": issued_at + time_to_live,
    }

    # For convenience, return both the server response and the access_token.
    return (json.dumps(token_server_response), access_token)


@responses.activate
def test_get_token():
    (response, access_token) = get_mock_token_response(int(time.time()), 7200)
    responses.add(responses.POST, MOCK_URL + MOCK_PATH, body=response, status=200)

    auth_headers = {'Host': 'mcsp.cloud.ibm.com:443'}
    authenticator = MCSPV2Authenticator(
        apikey=MOCK_APIKEY,
        url=MOCK_URL,
        scope_collection_type=MOCK_SCOPE_COLLECTION_TYPE,
        scope_id=MOCK_SCOPE_ID,
        headers=auth_headers,
    )

    # Authenticate the request and verify the Authorization header.
    request = {'headers': {}}
    authenticator.authenticate(request)
    assert request['headers']['Authorization'] == 'Bearer ' + access_token

    # Verify that the "get token" request contained the Host header.
    assert responses.calls[0].request.headers.get('Host') == 'mcsp.cloud.ibm.com:443'


@responses.activate
def test_get_token_cached():
    (response, access_token) = get_mock_token_response(int(time.time()), 7200)
    responses.add(responses.POST, MOCK_URL + MOCK_PATH, body=response, status=200)

    authenticator = MCSPV2Authenticator(
        apikey=MOCK_APIKEY,
        url=MOCK_URL,
        scope_collection_type=MOCK_SCOPE_COLLECTION_TYPE,
        scope_id=MOCK_SCOPE_ID,
    )

    # Authenticate the request and verify the Authorization header.
    request = {'headers': {}}
    authenticator.authenticate(request)
    assert request['headers']['Authorization'] == 'Bearer ' + access_token

    # Authenticate a second request and verify that we used the same access token.
    request = {'headers': {}}
    authenticator.authenticate(request)
    assert request['headers']['Authorization'] == 'Bearer ' + access_token


@responses.activate
def test_get_token_background_refresh():
    t1 = time.time()
    t2 = t1 + 7200

    # Setup the first token response.
    (response1, access_token1) = get_mock_token_response(int(t1), 7200)
    responses.add(responses.POST, MOCK_URL + MOCK_PATH, body=response1, status=200)

    # Setup the second token response.
    (response2, access_token2) = get_mock_token_response(int(t2), 7200)
    responses.add(responses.POST, MOCK_URL + MOCK_PATH, body=response2, status=200)

    authenticator = MCSPV2Authenticator(
        apikey=MOCK_APIKEY,
        url=MOCK_URL,
        scope_collection_type=MOCK_SCOPE_COLLECTION_TYPE,
        scope_id=MOCK_SCOPE_ID,
    )

    # Authenticate the request and verify that the first access_token is used.
    request = {'headers': {}}
    authenticator.authenticate(request)
    assert request['headers']['Authorization'] == 'Bearer ' + access_token1

    # Now put the token manager in the refresh window to trigger a background refresh scenario.
    authenticator.token_manager.refresh_time = t1 - 1

    # Authenticate a second request and verify that the correct access token is used.
    # Note: Ideally, the token manager would trigger the refresh in a separate thread
    # and it "should" return the first access token for this second authentication request
    # while the token manager is obtaining a new access token.
    # Unfortunately, the TokenManager class  method does the refresh request synchronously,
    # so we get back the second access token here instead.
    # If we "fix" the TokenManager class to refresh asynchronously, we'll need to
    # change this test case to expect the first access token here.
    request = {'headers': {}}
    authenticator.authenticate(request)
    assert request['headers']['Authorization'] == 'Bearer ' + access_token2

    # Wait for the background refresh to finish.
    # No need to wait due to the synchronous logic in the TokenManager class mentioned above.
    # time.sleep(2)

    # Authenticate another request and verify that the second access token is used again.
    request = {'headers': {}}
    authenticator.authenticate(request)
    assert request['headers']['Authorization'] == 'Bearer ' + access_token2


@responses.activate
def test_request_token():
    (response, access_token) = get_mock_token_response(time.time(), 30)
    responses.add(responses.POST, MOCK_URL + MOCK_PATH, body=response, status=200)

    token_manager = MCSPV2TokenManager(
        apikey=MOCK_APIKEY,
        url=MOCK_URL,
        scope_collection_type=MOCK_SCOPE_COLLECTION_TYPE,
        scope_id=MOCK_SCOPE_ID,
        disable_ssl_verification=True,
    )
    token = token_manager.get_token()

    assert len(responses.calls) == 1
    assert (
        responses.calls[0].request.url
        == MOCK_URL
        + MOCK_PATH
        + '?includeBuiltinActions=false&includeCustomActions=false&'
        + 'includeRoles=true&prefixRolesWithDefinitionScope=false'
    )
    assert responses.calls[0].request.headers.get('User-Agent').startswith('ibm-python-sdk-core/mcspv2-authenticator')
    assert token == access_token


@responses.activate
def test_request_token_unsuccessful():
    response = """{
        "errorCode": "BXNIM0415E",
        "errorMessage": "Provided API key could not be found"
    }
    """
    responses.add(responses.POST, url=MOCK_URL + MOCK_PATH, body=response, status=400)

    token_manager = MCSPV2TokenManager(
        apikey="bad-api-key",
        url=MOCK_URL,
        scope_collection_type=MOCK_SCOPE_COLLECTION_TYPE,
        scope_id=MOCK_SCOPE_ID,
        disable_ssl_verification=True,
    )
    with pytest.raises(Exception):
        token_manager.request_token()

    assert len(responses.calls) == 1
    assert (
        responses.calls[0].request.url
        == MOCK_URL
        + MOCK_PATH
        + '?includeBuiltinActions=false&includeCustomActions=false&'
        + 'includeRoles=true&prefixRolesWithDefinitionScope=false'
    )
    assert responses.calls[0].response.text == response