-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathoauth2_test.py
More file actions
496 lines (449 loc) · 17 KB
/
oauth2_test.py
File metadata and controls
496 lines (449 loc) · 17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
"""
Python SDK for OpenFGA
API version: 1.x
Website: https://openfga.dev
Documentation: https://openfga.dev/docs
Support: https://openfga.dev/community
License: [Apache-2.0](https://github.com/openfga/python-sdk/blob/main/LICENSE)
NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT.
"""
from datetime import datetime, timedelta
from unittest import IsolatedAsyncioTestCase
from unittest.mock import patch
import urllib3
from openfga_sdk import rest
from openfga_sdk.configuration import Configuration
from openfga_sdk.credentials import CredentialConfiguration, Credentials
from openfga_sdk.exceptions import AuthenticationError
from openfga_sdk.oauth2 import OAuth2Client
# Helper function to construct mock response
def mock_response(body, status):
headers = urllib3.response.HTTPHeaderDict({"content-type": "application/json"})
obj = urllib3.HTTPResponse(body, headers, status, preload_content=False)
return rest.RESTResponse(obj, obj.data)
class TestOAuth2Client(IsolatedAsyncioTestCase):
"""TestOAuth2Client unit test"""
def setUp(self):
pass
def tearDown(self):
pass
async def test_get_authentication_valid_client_credentials(self):
"""
Test getting authentication header when method is client credentials
"""
client = OAuth2Client(None)
client._access_token = "XYZ123"
client._access_expiry_time = datetime.now() + timedelta(seconds=60)
auth_header = await client.get_authentication_header(None)
self.assertEqual(auth_header, {"Authorization": "Bearer XYZ123"})
@patch.object(rest.RESTClientObject, "request")
async def test_get_authentication_obtain_client_credentials(self, mock_request):
"""
Test getting authentication header when method is client credential and we need to obtain token
"""
response_body = """
{
"expires_in": 120,
"access_token": "AABBCCDD"
}
"""
mock_request.return_value = mock_response(response_body, 200)
credentials = Credentials(
method="client_credentials",
configuration=CredentialConfiguration(
client_id="myclientid",
client_secret="mysecret",
api_issuer="issuer.fga.example",
api_audience="myaudience",
),
)
rest_client = rest.RESTClientObject(Configuration())
current_time = datetime.now()
client = OAuth2Client(credentials)
auth_header = await client.get_authentication_header(rest_client)
self.assertEqual(auth_header, {"Authorization": "Bearer AABBCCDD"})
self.assertEqual(client._access_token, "AABBCCDD")
self.assertGreaterEqual(
client._access_expiry_time, current_time + timedelta(seconds=120)
)
expected_header = urllib3.response.HTTPHeaderDict(
{
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded",
"User-Agent": "openfga-sdk (python) 0.9.4",
}
)
mock_request.assert_called_once_with(
method="POST",
url="https://issuer.fga.example/oauth/token",
headers=expected_header,
query_params=None,
body=None,
_preload_content=True,
_request_timeout=None,
post_params={
"client_id": "myclientid",
"client_secret": "mysecret",
"audience": "myaudience",
"grant_type": "client_credentials",
},
)
await rest_client.close()
@patch.object(rest.RESTClientObject, "request")
async def test_get_authentication_obtain_client_credentials_failed(
self, mock_request
):
"""
Test getting authentication header when method is client credential and we fail to obtain token
"""
response_body = """
{
"reason": "Unauthorized"
}
"""
mock_request.return_value = mock_response(response_body, 403)
credentials = Credentials(
method="client_credentials",
configuration=CredentialConfiguration(
client_id="myclientid",
client_secret="mysecret",
api_issuer="issuer.fga.example",
api_audience="myaudience",
),
)
rest_client = rest.RESTClientObject(Configuration())
client = OAuth2Client(credentials)
with self.assertRaises(AuthenticationError):
await client.get_authentication_header(rest_client)
await rest_client.close()
@patch.object(rest.RESTClientObject, "request")
async def test_get_authentication_obtain_with_expired_client_credentials_failed(
self, mock_request
):
"""
Expired token should trigger a new token request
"""
response_body = """
{
"reason": "Unauthorized"
}
"""
mock_request.return_value = mock_response(response_body, 403)
credentials = Credentials(
method="client_credentials",
configuration=CredentialConfiguration(
client_id="myclientid",
client_secret="mysecret",
api_issuer="issuer.fga.example",
api_audience="myaudience",
),
)
rest_client = rest.RESTClientObject(Configuration())
client = OAuth2Client(credentials)
client._access_token = "XYZ123"
client._access_expiry_time = datetime.now() - timedelta(seconds=240)
with self.assertRaises(AuthenticationError):
await client.get_authentication_header(rest_client)
await rest_client.close()
@patch.object(rest.RESTClientObject, "request")
async def test_get_authentication_unexpected_response_fails(self, mock_request):
"""
Receiving an unexpected response from the server should raise an exception
"""
response_body = """
This is not a JSON response
"""
mock_request.return_value = mock_response(response_body, 200)
credentials = Credentials(
method="client_credentials",
configuration=CredentialConfiguration(
client_id="myclientid",
client_secret="mysecret",
api_issuer="issuer.fga.example",
api_audience="myaudience",
),
)
rest_client = rest.RESTClientObject(Configuration())
client = OAuth2Client(credentials)
with self.assertRaises(AuthenticationError):
await client.get_authentication_header(rest_client)
await rest_client.close()
@patch.object(rest.RESTClientObject, "request")
async def test_get_authentication_erroneous_response_fails(self, mock_request):
"""
Receiving an erroneous response from the server that's missing properties should raise an exception
"""
response_body = """
{
"access_token": "AABBCCDD"
}
"""
mock_request.return_value = mock_response(response_body, 200)
credentials = Credentials(
method="client_credentials",
configuration=CredentialConfiguration(
client_id="myclientid",
client_secret="mysecret",
api_issuer="issuer.fga.example",
api_audience="myaudience",
),
)
rest_client = rest.RESTClientObject(Configuration())
client = OAuth2Client(credentials)
with self.assertRaises(AuthenticationError):
await client.get_authentication_header(rest_client)
await rest_client.close()
@patch.object(rest.RESTClientObject, "request")
async def test_get_authentication_retries_5xx_responses(self, mock_request):
"""
Receiving a 5xx response from the server should be retried
"""
error_response_body = """
{
"code": "rate_limit_exceeded",
"message": "Rate Limit exceeded"
}
"""
response_body = """
{
"expires_in": 120,
"access_token": "AABBCCDD"
}
"""
mock_request.side_effect = [
mock_response(error_response_body, 429),
mock_response(error_response_body, 429),
mock_response(error_response_body, 429),
mock_response(response_body, 200),
]
credentials = Credentials(
method="client_credentials",
configuration=CredentialConfiguration(
client_id="myclientid",
client_secret="mysecret",
api_issuer="issuer.fga.example",
api_audience="myaudience",
),
)
configuration = Configuration()
configuration.retry_params.max_retry = 5
configuration.retry_params.retry_interval = 0
rest_client = rest.RESTClientObject(configuration)
client = OAuth2Client(credentials, configuration)
auth_header = await client.get_authentication_header(rest_client)
mock_request.assert_called()
self.assertEqual(mock_request.call_count, 4) # 3 retries, 1 success
self.assertEqual(auth_header, {"Authorization": "Bearer AABBCCDD"})
await rest_client.close()
@patch.object(rest.RESTClientObject, "request")
async def test_get_authentication_keep_full_url(self, mock_request):
"""
Fully qualified issuer URLs should not get manipulated.
"""
response_body = """
{
"expires_in": 120,
"access_token": "AABBCCDD"
}
"""
mock_request.return_value = mock_response(response_body, 200)
credentials = Credentials(
method="client_credentials",
configuration=CredentialConfiguration(
client_id="myclientid",
client_secret="mysecret",
api_issuer="https://issuer.fga.example/something",
api_audience="myaudience",
),
)
rest_client = rest.RESTClientObject(Configuration())
current_time = datetime.now()
client = OAuth2Client(credentials)
auth_header = await client.get_authentication_header(rest_client)
self.assertEqual(auth_header, {"Authorization": "Bearer AABBCCDD"})
self.assertEqual(client._access_token, "AABBCCDD")
self.assertGreaterEqual(
client._access_expiry_time, current_time + timedelta(seconds=120)
)
expected_header = urllib3.response.HTTPHeaderDict(
{
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded",
"User-Agent": "openfga-sdk (python) 0.9.4",
}
)
mock_request.assert_called_once_with(
method="POST",
url="https://issuer.fga.example/something",
headers=expected_header,
query_params=None,
body=None,
_preload_content=True,
_request_timeout=None,
post_params={
"client_id": "myclientid",
"client_secret": "mysecret",
"audience": "myaudience",
"grant_type": "client_credentials",
},
)
await rest_client.close()
@patch.object(rest.RESTClientObject, "request")
async def test_get_authentication_add_scheme(self, mock_request):
"""
Issuer URLs without scheme should get scheme prefix added.
"""
response_body = """
{
"expires_in": 120,
"access_token": "AABBCCDD"
}
"""
mock_request.return_value = mock_response(response_body, 200)
credentials = Credentials(
method="client_credentials",
configuration=CredentialConfiguration(
client_id="myclientid",
client_secret="mysecret",
api_issuer="issuer.fga.example/something",
api_audience="myaudience",
),
)
rest_client = rest.RESTClientObject(Configuration())
current_time = datetime.now()
client = OAuth2Client(credentials)
auth_header = await client.get_authentication_header(rest_client)
self.assertEqual(auth_header, {"Authorization": "Bearer AABBCCDD"})
self.assertEqual(client._access_token, "AABBCCDD")
self.assertGreaterEqual(
client._access_expiry_time, current_time + timedelta(seconds=120)
)
expected_header = urllib3.response.HTTPHeaderDict(
{
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded",
"User-Agent": "openfga-sdk (python) 0.9.4",
}
)
mock_request.assert_called_once_with(
method="POST",
url="https://issuer.fga.example/something",
headers=expected_header,
query_params=None,
body=None,
_preload_content=True,
_request_timeout=None,
post_params={
"client_id": "myclientid",
"client_secret": "mysecret",
"audience": "myaudience",
"grant_type": "client_credentials",
},
)
await rest_client.close()
@patch.object(rest.RESTClientObject, "request")
async def test_get_authentication_add_path(self, mock_request):
"""
Issuer URLs without scheme should get scheme prefix added.
"""
response_body = """
{
"expires_in": 120,
"access_token": "AABBCCDD"
}
"""
mock_request.return_value = mock_response(response_body, 200)
credentials = Credentials(
method="client_credentials",
configuration=CredentialConfiguration(
client_id="myclientid",
client_secret="mysecret",
api_issuer="https://issuer.fga.example",
api_audience="myaudience",
),
)
rest_client = rest.RESTClientObject(Configuration())
current_time = datetime.now()
client = OAuth2Client(credentials)
auth_header = await client.get_authentication_header(rest_client)
self.assertEqual(auth_header, {"Authorization": "Bearer AABBCCDD"})
self.assertEqual(client._access_token, "AABBCCDD")
self.assertGreaterEqual(
client._access_expiry_time, current_time + timedelta(seconds=120)
)
expected_header = urllib3.response.HTTPHeaderDict(
{
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded",
"User-Agent": "openfga-sdk (python) 0.9.4",
}
)
mock_request.assert_called_once_with(
method="POST",
url="https://issuer.fga.example/oauth/token",
headers=expected_header,
query_params=None,
body=None,
_preload_content=True,
_request_timeout=None,
post_params={
"client_id": "myclientid",
"client_secret": "mysecret",
"audience": "myaudience",
"grant_type": "client_credentials",
},
)
await rest_client.close()
@patch.object(rest.RESTClientObject, "request")
async def test_get_authentication_add_scheme_and_path(self, mock_request):
"""
Issuer URLs without scheme should get scheme prefix added.
"""
response_body = """
{
"expires_in": 120,
"access_token": "AABBCCDD"
}
"""
mock_request.return_value = mock_response(response_body, 200)
credentials = Credentials(
method="client_credentials",
configuration=CredentialConfiguration(
client_id="myclientid",
client_secret="mysecret",
api_issuer="issuer.fga.example",
api_audience="myaudience",
),
)
rest_client = rest.RESTClientObject(Configuration())
current_time = datetime.now()
client = OAuth2Client(credentials)
auth_header = await client.get_authentication_header(rest_client)
self.assertEqual(auth_header, {"Authorization": "Bearer AABBCCDD"})
self.assertEqual(client._access_token, "AABBCCDD")
self.assertGreaterEqual(
client._access_expiry_time, current_time + timedelta(seconds=120)
)
expected_header = urllib3.response.HTTPHeaderDict(
{
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded",
"User-Agent": "openfga-sdk (python) 0.9.4",
}
)
mock_request.assert_called_once_with(
method="POST",
url="https://issuer.fga.example/oauth/token",
headers=expected_header,
query_params=None,
body=None,
_preload_content=True,
_request_timeout=None,
post_params={
"client_id": "myclientid",
"client_secret": "mysecret",
"audience": "myaudience",
"grant_type": "client_credentials",
},
)
await rest_client.close()