-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathoauth2_test.py
More file actions
276 lines (237 loc) · 9.13 KB
/
oauth2_test.py
File metadata and controls
276 lines (237 loc) · 9.13 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
"""
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.2",
}
)
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()