-
Notifications
You must be signed in to change notification settings - Fork 183
Expand file tree
/
Copy pathtest_management_client.py
More file actions
480 lines (417 loc) · 16.2 KB
/
test_management_client.py
File metadata and controls
480 lines (417 loc) · 16.2 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
import time
from unittest.mock import MagicMock, patch
import httpx
import pytest
from auth0.management import (
AsyncManagementClient,
AsyncTokenProvider,
CustomDomainHeader,
ManagementClient,
TokenProvider,
)
from auth0.management.management_client import (
CUSTOM_DOMAIN_HEADER as _CUSTOM_DOMAIN_HEADER,
)
from auth0.management.management_client import (
_enforce_custom_domain_whitelist,
_is_path_whitelisted,
)
class TestManagementClientInit:
"""Tests for ManagementClient initialization."""
def test_init_with_token_string(self):
"""Should initialize with a static token string."""
client = ManagementClient(
domain="test.auth0.com",
token="my-test-token",
)
assert client._api is not None
def test_init_with_token_callable(self):
"""Should initialize with a token callable."""
token_fn = lambda: "dynamic-token"
client = ManagementClient(
domain="test.auth0.com",
token=token_fn,
)
assert client._api is not None
def test_init_with_client_credentials(self):
"""Should initialize with client_id and client_secret."""
client = ManagementClient(
domain="test.auth0.com",
client_id="my-client-id",
client_secret="my-client-secret",
)
assert client._api is not None
def test_init_with_custom_audience(self):
"""Should initialize with a custom audience."""
client = ManagementClient(
domain="test.auth0.com",
client_id="my-client-id",
client_secret="my-client-secret",
audience="https://custom-api.example.com/",
)
assert client._api is not None
def test_init_requires_auth(self):
"""Should raise ValueError when no auth is provided."""
with pytest.raises(ValueError) as exc_info:
ManagementClient(domain="test.auth0.com")
assert "token" in str(exc_info.value)
assert "client_id" in str(exc_info.value)
def test_init_requires_both_credentials(self):
"""Should raise ValueError when only client_id is provided."""
with pytest.raises(ValueError):
ManagementClient(
domain="test.auth0.com",
client_id="my-client-id",
)
def test_init_with_custom_timeout(self):
"""Should initialize with custom timeout."""
client = ManagementClient(
domain="test.auth0.com",
token="my-token",
timeout=30.0,
)
assert client._api is not None
def test_init_with_custom_headers(self):
"""Should initialize with custom headers."""
client = ManagementClient(
domain="test.auth0.com",
token="my-token",
headers={"X-Custom-Header": "custom-value"},
)
assert client._api is not None
class TestManagementClientProperties:
"""Tests for ManagementClient sub-client properties."""
@pytest.fixture
def client(self):
return ManagementClient(
domain="test.auth0.com",
token="test-token",
)
def test_has_users_property(self, client):
"""Should have users property."""
assert hasattr(client, "users")
def test_has_organizations_property(self, client):
"""Should have organizations property."""
assert hasattr(client, "organizations")
def test_has_actions_property(self, client):
"""Should have actions property."""
assert hasattr(client, "actions")
def test_has_all_expected_properties(self, client):
"""Should have all expected sub-client properties."""
expected_properties = [
"actions",
"anomaly",
"attack_protection",
"branding",
"client_grants",
"clients",
"connections",
"custom_domains",
"device_credentials",
"email_templates",
"emails",
"event_streams",
"flows",
"forms",
"guardian",
"hooks",
"jobs",
"keys",
"log_streams",
"logs",
"network_acls",
"organizations",
"prompts",
"refresh_tokens",
"resource_servers",
"roles",
"rules",
"rules_configs",
"self_service_profiles",
"sessions",
"stats",
"supplemental_signals",
"tenants",
"tickets",
"token_exchange_profiles",
"user_blocks",
"user_grants",
"users",
"verifiable_credentials",
]
for prop in expected_properties:
assert hasattr(client, prop), f"Missing property: {prop}"
class TestAsyncManagementClientInit:
"""Tests for AsyncManagementClient initialization."""
def test_init_with_token_string(self):
"""Should initialize with a static token string."""
client = AsyncManagementClient(
domain="test.auth0.com",
token="my-test-token",
)
assert client._api is not None
def test_init_with_client_credentials(self):
"""Should initialize with client_id and client_secret."""
client = AsyncManagementClient(
domain="test.auth0.com",
client_id="my-client-id",
client_secret="my-client-secret",
)
assert client._api is not None
def test_init_requires_auth(self):
"""Should raise ValueError when no auth is provided."""
with pytest.raises(ValueError):
AsyncManagementClient(domain="test.auth0.com")
class TestTokenProvider:
"""Tests for TokenProvider."""
def test_init_with_defaults(self):
"""Should initialize with default audience."""
provider = TokenProvider(
domain="test.auth0.com",
client_id="client-id",
client_secret="client-secret",
)
assert provider._audience == "https://test.auth0.com/api/v2/"
def test_init_with_custom_audience(self):
"""Should initialize with custom audience."""
provider = TokenProvider(
domain="test.auth0.com",
client_id="client-id",
client_secret="client-secret",
audience="https://custom.api.com/",
)
assert provider._audience == "https://custom.api.com/"
@patch("auth0.management.token_provider.httpx.Client")
def test_get_token_fetches_on_first_call(self, mock_client_class):
"""Should fetch token on first call."""
mock_response = MagicMock()
mock_response.json.return_value = {
"access_token": "new-token",
"expires_in": 86400,
}
mock_client = MagicMock()
mock_client.__enter__ = MagicMock(return_value=mock_client)
mock_client.__exit__ = MagicMock(return_value=False)
mock_client.post.return_value = mock_response
mock_client_class.return_value = mock_client
provider = TokenProvider(
domain="test.auth0.com",
client_id="client-id",
client_secret="client-secret",
)
token = provider.get_token()
assert token == "new-token"
mock_client.post.assert_called_once()
@patch("auth0.management.token_provider.httpx.Client")
def test_get_token_returns_cached_token(self, mock_client_class):
"""Should return cached token on subsequent calls."""
mock_response = MagicMock()
mock_response.json.return_value = {
"access_token": "cached-token",
"expires_in": 86400,
}
mock_client = MagicMock()
mock_client.__enter__ = MagicMock(return_value=mock_client)
mock_client.__exit__ = MagicMock(return_value=False)
mock_client.post.return_value = mock_response
mock_client_class.return_value = mock_client
provider = TokenProvider(
domain="test.auth0.com",
client_id="client-id",
client_secret="client-secret",
)
# First call fetches
token1 = provider.get_token()
# Second call returns cached
token2 = provider.get_token()
assert token1 == token2 == "cached-token"
# Should only fetch once
assert mock_client.post.call_count == 1
@patch("auth0.management.token_provider.httpx.Client")
def test_get_token_refreshes_expired_token(self, mock_client_class):
"""Should refresh token when expired (with 10s leeway)."""
mock_response = MagicMock()
mock_response.json.return_value = {
"access_token": "refreshed-token",
"expires_in": 86400,
}
mock_client = MagicMock()
mock_client.__enter__ = MagicMock(return_value=mock_client)
mock_client.__exit__ = MagicMock(return_value=False)
mock_client.post.return_value = mock_response
mock_client_class.return_value = mock_client
provider = TokenProvider(
domain="test.auth0.com",
client_id="client-id",
client_secret="client-secret",
)
# First call
provider.get_token()
# Simulate token being close to expiration (within leeway)
provider._expires_at = time.time() + 5 # 5 seconds left, less than 10s leeway
# This should trigger a refresh
token = provider.get_token()
assert token == "refreshed-token"
assert mock_client.post.call_count == 2
@patch("auth0.management.token_provider.httpx.Client")
def test_token_request_payload(self, mock_client_class):
"""Should send correct payload to token endpoint."""
mock_response = MagicMock()
mock_response.json.return_value = {
"access_token": "token",
"expires_in": 86400,
}
mock_client = MagicMock()
mock_client.__enter__ = MagicMock(return_value=mock_client)
mock_client.__exit__ = MagicMock(return_value=False)
mock_client.post.return_value = mock_response
mock_client_class.return_value = mock_client
provider = TokenProvider(
domain="test.auth0.com",
client_id="my-client",
client_secret="my-secret",
audience="https://api.example.com/",
)
provider.get_token()
mock_client.post.assert_called_once_with(
"https://test.auth0.com/oauth/token",
data={
"grant_type": "client_credentials",
"client_id": "my-client",
"client_secret": "my-secret",
"audience": "https://api.example.com/",
},
)
class TestAsyncTokenProvider:
"""Tests for AsyncTokenProvider."""
def test_init_with_defaults(self):
"""Should initialize with default audience."""
provider = AsyncTokenProvider(
domain="test.auth0.com",
client_id="client-id",
client_secret="client-secret",
)
assert provider._audience == "https://test.auth0.com/api/v2/"
def test_init_with_custom_audience(self):
"""Should initialize with custom audience."""
provider = AsyncTokenProvider(
domain="test.auth0.com",
client_id="client-id",
client_secret="client-secret",
audience="https://custom.api.com/",
)
assert provider._audience == "https://custom.api.com/"
class TestCustomDomainHeader:
"""Tests for Auth0-Custom-Domain header support."""
def test_init_with_custom_domain(self):
"""Should set Auth0-Custom-Domain header when custom_domain is provided."""
client = ManagementClient(
domain="test.auth0.com",
token="my-token",
custom_domain="login.mycompany.com",
)
custom_headers = client._api._client_wrapper.get_custom_headers()
assert custom_headers is not None
assert custom_headers[_CUSTOM_DOMAIN_HEADER] == "login.mycompany.com"
def test_init_custom_domain_with_existing_headers(self):
"""Should merge custom_domain with other custom headers."""
client = ManagementClient(
domain="test.auth0.com",
token="my-token",
headers={"X-Custom": "value"},
custom_domain="login.mycompany.com",
)
custom_headers = client._api._client_wrapper.get_custom_headers()
assert custom_headers is not None
assert custom_headers["X-Custom"] == "value"
assert custom_headers[_CUSTOM_DOMAIN_HEADER] == "login.mycompany.com"
def test_init_without_custom_domain(self):
"""Should not set Auth0-Custom-Domain header when custom_domain is not provided."""
client = ManagementClient(
domain="test.auth0.com",
token="my-token",
)
custom_headers = client._api._client_wrapper.get_custom_headers()
assert custom_headers is None or _CUSTOM_DOMAIN_HEADER not in custom_headers
def test_custom_domain_header_helper(self):
"""Should return correct request options dict."""
result = CustomDomainHeader("login.mycompany.com")
assert result == {
"additional_headers": {
_CUSTOM_DOMAIN_HEADER: "login.mycompany.com",
}
}
def test_async_init_with_custom_domain(self):
"""Should set Auth0-Custom-Domain header on async client."""
client = AsyncManagementClient(
domain="test.auth0.com",
token="my-token",
custom_domain="login.mycompany.com",
)
custom_headers = client._api._client_wrapper.get_custom_headers()
assert custom_headers is not None
assert custom_headers[_CUSTOM_DOMAIN_HEADER] == "login.mycompany.com"
def test_whitelist_strips_header_on_non_whitelisted_path(self):
"""Should strip Auth0-Custom-Domain header on non-whitelisted paths."""
request = httpx.Request(
"GET",
"https://test.auth0.com/api/v2/clients",
headers={_CUSTOM_DOMAIN_HEADER: "login.mycompany.com"},
)
_enforce_custom_domain_whitelist(request)
assert _CUSTOM_DOMAIN_HEADER not in request.headers
def test_whitelist_keeps_header_on_whitelisted_path(self):
"""Should keep Auth0-Custom-Domain header on whitelisted paths."""
request = httpx.Request(
"POST",
"https://test.auth0.com/api/v2/users",
headers={_CUSTOM_DOMAIN_HEADER: "login.mycompany.com"},
)
_enforce_custom_domain_whitelist(request)
assert request.headers[_CUSTOM_DOMAIN_HEADER] == "login.mycompany.com"
@pytest.mark.parametrize(
"path",
[
"/api/v2/jobs/verification-email",
"/api/v2/tickets/email-verification",
"/api/v2/tickets/password-change",
"/api/v2/organizations/org_abc123/invitations",
"/api/v2/users",
"/api/v2/users/auth0|abc123",
"/api/v2/guardian/enrollments/ticket",
"/api/v2/self-service-profiles/ssp_abc123/sso-ticket",
],
)
def test_whitelisted_paths_match(self, path):
"""Should match all 8 whitelisted path patterns."""
assert _is_path_whitelisted(path) is True
@pytest.mark.parametrize(
"path",
[
"/api/v2/clients",
"/api/v2/connections",
"/api/v2/roles",
"/api/v2/users/auth0|abc123/roles",
"/api/v2/jobs/users-imports",
"/api/v2/tenants/settings",
],
)
def test_non_whitelisted_paths_do_not_match(self, path):
"""Should not match non-whitelisted paths."""
assert _is_path_whitelisted(path) is False
class TestImports:
"""Tests for module imports."""
def test_import_from_management(self):
"""Should be able to import from auth0.management."""
from auth0.management import (
AsyncManagementClient,
AsyncTokenProvider,
CustomDomainHeader,
ManagementClient,
TokenProvider,
)
assert ManagementClient is not None
assert AsyncManagementClient is not None
assert TokenProvider is not None
assert AsyncTokenProvider is not None
assert CustomDomainHeader is not None