Debian Codegraph @

tests/management/test_management_client.py

raw symbols SCIP
1 import base64
2 import json
3 import time
4 from unittest.mock import MagicMock, patch
5
6 import httpx
7 import pytest
8
9 from auth0.management import (
10 AsyncManagementClient,
11 AsyncTokenProvider,
12 CustomDomainHeader,
13 ManagementClient,
14 TokenProvider,
15 )
16 from auth0.management.management_client import (
17 CUSTOM_DOMAIN_HEADER as _CUSTOM_DOMAIN_HEADER,
18 )
19 from auth0.management.management_client import (
20 _enforce_custom_domain_whitelist,
21 _is_path_whitelisted,
22 )
23
24
25 class TestManagementClientInit:
26 """Tests for ManagementClient initialization."""
27
28 def test_init_with_token_string(self):
29 """Should initialize with a static token string."""
30 client = ManagementClient(
31 domain="test.auth0.com",
32 token="my-test-token",
33 )
34 assert client._api is not None
35
36 def test_init_with_token_callable(self):
37 """Should initialize with a token callable."""
38 token_fn = lambda: "dynamic-token"
39 client = ManagementClient(
40 domain="test.auth0.com",
41 token=token_fn,
42 )
43 assert client._api is not None
44
45 def test_init_with_client_credentials(self):
46 """Should initialize with client_id and client_secret."""
47 client = ManagementClient(
48 domain="test.auth0.com",
49 client_id="my-client-id",
50 client_secret="my-client-secret",
51 )
52 assert client._api is not None
53
54 def test_init_with_custom_audience(self):
55 """Should initialize with a custom audience."""
56 client = ManagementClient(
57 domain="test.auth0.com",
58 client_id="my-client-id",
59 client_secret="my-client-secret",
60 audience="https://custom-api.example.com/",
61 )
62 assert client._api is not None
63
64 def test_init_requires_auth(self):
65 """Should raise ValueError when no auth is provided."""
66 with pytest.raises(ValueError) as exc_info:
67 ManagementClient(domain="test.auth0.com")
68 assert "token" in str(exc_info.value)
69 assert "client_id" in str(exc_info.value)
70
71 def test_init_requires_both_credentials(self):
72 """Should raise ValueError when only client_id is provided."""
73 with pytest.raises(ValueError):
74 ManagementClient(
75 domain="test.auth0.com",
76 client_id="my-client-id",
77 )
78
79 def test_init_with_custom_timeout(self):
80 """Should initialize with custom timeout."""
81 client = ManagementClient(
82 domain="test.auth0.com",
83 token="my-token",
84 timeout=30.0,
85 )
86 assert client._api is not None
87
88 def test_init_with_custom_headers(self):
89 """Should initialize with custom headers."""
90 client = ManagementClient(
91 domain="test.auth0.com",
92 token="my-token",
93 headers={"X-Custom-Header": "custom-value"},
94 )
95 assert client._api is not None
96
97 def test_init_with_custom_client_info(self):
98 """Should encode client_info as Auth0-Client header."""
99 custom_info = {
100 "name": "auth0-ai-langchain",
101 "version": "1.0.0",
102 "env": {"python": "3.11.0"},
103 }
104 client = ManagementClient(
105 domain="test.auth0.com",
106 token="my-token",
107 client_info=custom_info,
108 )
109 # Verify the header was set on the underlying client wrapper
110 custom_headers = client._api._client_wrapper.get_custom_headers()
111 assert custom_headers is not None
112 encoded_header = custom_headers.get("Auth0-Client")
113 assert encoded_header is not None
114 decoded = json.loads(base64.b64decode(encoded_header).decode("utf-8"))
115 assert decoded == custom_info
116
117 def test_init_with_client_info_and_custom_headers(self):
118 """Should merge client_info with custom headers."""
119 custom_info = {"name": "my-sdk", "version": "2.0.0"}
120 client = ManagementClient(
121 domain="test.auth0.com",
122 token="my-token",
123 headers={"X-Custom": "value"},
124 client_info=custom_info,
125 )
126 custom_headers = client._api._client_wrapper.get_custom_headers()
127 assert custom_headers is not None
128 assert custom_headers.get("X-Custom") == "value"
129 assert "Auth0-Client" in custom_headers
130
131 def test_init_without_client_info_uses_default_telemetry(self):
132 """Should use default auth0-python telemetry when client_info is not provided."""
133 client = ManagementClient(
134 domain="test.auth0.com",
135 token="my-token",
136 )
137 # get_headers() includes the default Auth0-Client telemetry
138 headers = client._api._client_wrapper.get_headers()
139 encoded = headers.get("Auth0-Client")
140 assert encoded is not None
141 decoded = json.loads(base64.b64decode(encoded).decode("utf-8"))
142 assert decoded["name"] == "auth0-python"
143
144
145 class TestManagementClientProperties:
146 """Tests for ManagementClient sub-client properties."""
147
148 @pytest.fixture
149 def client(self):
150 return ManagementClient(
151 domain="test.auth0.com",
152 token="test-token",
153 )
154
155 def test_has_users_property(self, client):
156 """Should have users property."""
157 assert hasattr(client, "users")
158
159 def test_has_organizations_property(self, client):
160 """Should have organizations property."""
161 assert hasattr(client, "organizations")
162
163 def test_has_actions_property(self, client):
164 """Should have actions property."""
165 assert hasattr(client, "actions")
166
167 def test_has_all_expected_properties(self, client):
168 """Should have all expected sub-client properties."""
169 expected_properties = [
170 "actions",
171 "anomaly",
172 "attack_protection",
173 "branding",
174 "client_grants",
175 "clients",
176 "connections",
177 "custom_domains",
178 "device_credentials",
179 "email_templates",
180 "emails",
181 "event_streams",
182 "flows",
183 "forms",
184 "guardian",
185 "hooks",
186 "jobs",
187 "keys",
188 "log_streams",
189 "logs",
190 "network_acls",
191 "organizations",
192 "prompts",
193 "refresh_tokens",
194 "resource_servers",
195 "roles",
196 "rules",
197 "rules_configs",
198 "self_service_profiles",
199 "sessions",
200 "stats",
201 "supplemental_signals",
202 "tenants",
203 "tickets",
204 "token_exchange_profiles",
205 "user_blocks",
206 "user_grants",
207 "users",
208 "verifiable_credentials",
209 ]
210 for prop in expected_properties:
211 assert hasattr(client, prop), f"Missing property: {prop}"
212
213
214 class TestAsyncManagementClientInit:
215 """Tests for AsyncManagementClient initialization."""
216
217 def test_init_with_token_string(self):
218 """Should initialize with a static token string."""
219 client = AsyncManagementClient(
220 domain="test.auth0.com",
221 token="my-test-token",
222 )
223 assert client._api is not None
224
225 def test_init_with_client_credentials(self):
226 """Should initialize with client_id and client_secret."""
227 client = AsyncManagementClient(
228 domain="test.auth0.com",
229 client_id="my-client-id",
230 client_secret="my-client-secret",
231 )
232 assert client._api is not None
233
234 def test_init_requires_auth(self):
235 """Should raise ValueError when no auth is provided."""
236 with pytest.raises(ValueError):
237 AsyncManagementClient(domain="test.auth0.com")
238
239 def test_init_with_custom_client_info(self):
240 """Should encode client_info as Auth0-Client header."""
241 custom_info = {
242 "name": "auth0-ai-langchain",
243 "version": "1.0.0",
244 "env": {"python": "3.11.0"},
245 }
246 client = AsyncManagementClient(
247 domain="test.auth0.com",
248 token="my-token",
249 client_info=custom_info,
250 )
251 custom_headers = client._api._client_wrapper.get_custom_headers()
252 assert custom_headers is not None
253 encoded_header = custom_headers.get("Auth0-Client")
254 assert encoded_header is not None
255 decoded = json.loads(base64.b64decode(encoded_header).decode("utf-8"))
256 assert decoded == custom_info
257
258
259 class TestTokenProvider:
260 """Tests for TokenProvider."""
261
262 def test_init_with_defaults(self):
263 """Should initialize with default audience."""
264 provider = TokenProvider(
265 domain="test.auth0.com",
266 client_id="client-id",
267 client_secret="client-secret",
268 )
269 assert provider._audience == "https://test.auth0.com/api/v2/"
270
271 def test_init_with_custom_audience(self):
272 """Should initialize with custom audience."""
273 provider = TokenProvider(
274 domain="test.auth0.com",
275 client_id="client-id",
276 client_secret="client-secret",
277 audience="https://custom.api.com/",
278 )
279 assert provider._audience == "https://custom.api.com/"
280
281 @patch("auth0.management.token_provider.httpx.Client")
282 def test_get_token_fetches_on_first_call(self, mock_client_class):
283 """Should fetch token on first call."""
284 mock_response = MagicMock()
285 mock_response.json.return_value = {
286 "access_token": "new-token",
287 "expires_in": 86400,
288 }
289 mock_client = MagicMock()
290 mock_client.__enter__ = MagicMock(return_value=mock_client)
291 mock_client.__exit__ = MagicMock(return_value=False)
292 mock_client.post.return_value = mock_response
293 mock_client_class.return_value = mock_client
294
295 provider = TokenProvider(
296 domain="test.auth0.com",
297 client_id="client-id",
298 client_secret="client-secret",
299 )
300 token = provider.get_token()
301
302 assert token == "new-token"
303 mock_client.post.assert_called_once()
304
305 @patch("auth0.management.token_provider.httpx.Client")
306 def test_get_token_returns_cached_token(self, mock_client_class):
307 """Should return cached token on subsequent calls."""
308 mock_response = MagicMock()
309 mock_response.json.return_value = {
310 "access_token": "cached-token",
311 "expires_in": 86400,
312 }
313 mock_client = MagicMock()
314 mock_client.__enter__ = MagicMock(return_value=mock_client)
315 mock_client.__exit__ = MagicMock(return_value=False)
316 mock_client.post.return_value = mock_response
317 mock_client_class.return_value = mock_client
318
319 provider = TokenProvider(
320 domain="test.auth0.com",
321 client_id="client-id",
322 client_secret="client-secret",
323 )
324
325 # First call fetches
326 token1 = provider.get_token()
327 # Second call returns cached
328 token2 = provider.get_token()
329
330 assert token1 == token2 == "cached-token"
331 # Should only fetch once
332 assert mock_client.post.call_count == 1
333
334 @patch("auth0.management.token_provider.httpx.Client")
335 def test_get_token_refreshes_expired_token(self, mock_client_class):
336 """Should refresh token when expired (with 10s leeway)."""
337 mock_response = MagicMock()
338 mock_response.json.return_value = {
339 "access_token": "refreshed-token",
340 "expires_in": 86400,
341 }
342 mock_client = MagicMock()
343 mock_client.__enter__ = MagicMock(return_value=mock_client)
344 mock_client.__exit__ = MagicMock(return_value=False)
345 mock_client.post.return_value = mock_response
346 mock_client_class.return_value = mock_client
347
348 provider = TokenProvider(
349 domain="test.auth0.com",
350 client_id="client-id",
351 client_secret="client-secret",
352 )
353
354 # First call
355 provider.get_token()
356
357 # Simulate token being close to expiration (within leeway)
358 provider._expires_at = time.time() + 5 # 5 seconds left, less than 10s leeway
359
360 # This should trigger a refresh
361 token = provider.get_token()
362
363 assert token == "refreshed-token"
364 assert mock_client.post.call_count == 2
365
366 @patch("auth0.management.token_provider.httpx.Client")
367 def test_token_request_payload(self, mock_client_class):
368 """Should send correct payload to token endpoint."""
369 mock_response = MagicMock()
370 mock_response.json.return_value = {
371 "access_token": "token",
372 "expires_in": 86400,
373 }
374 mock_client = MagicMock()
375 mock_client.__enter__ = MagicMock(return_value=mock_client)
376 mock_client.__exit__ = MagicMock(return_value=False)
377 mock_client.post.return_value = mock_response
378 mock_client_class.return_value = mock_client
379
380 provider = TokenProvider(
381 domain="test.auth0.com",
382 client_id="my-client",
383 client_secret="my-secret",
384 audience="https://api.example.com/",
385 )
386 provider.get_token()
387
388 mock_client.post.assert_called_once_with(
389 "https://test.auth0.com/oauth/token",
390 data={
391 "grant_type": "client_credentials",
392 "client_id": "my-client",
393 "client_secret": "my-secret",
394 "audience": "https://api.example.com/",
395 },
396 )
397
398
399 class TestAsyncTokenProvider:
400 """Tests for AsyncTokenProvider."""
401
402 def test_init_with_defaults(self):
403 """Should initialize with default audience."""
404 provider = AsyncTokenProvider(
405 domain="test.auth0.com",
406 client_id="client-id",
407 client_secret="client-secret",
408 )
409 assert provider._audience == "https://test.auth0.com/api/v2/"
410
411 def test_init_with_custom_audience(self):
412 """Should initialize with custom audience."""
413 provider = AsyncTokenProvider(
414 domain="test.auth0.com",
415 client_id="client-id",
416 client_secret="client-secret",
417 audience="https://custom.api.com/",
418 )
419 assert provider._audience == "https://custom.api.com/"
420
421
422 class TestCustomDomainHeader:
423 """Tests for Auth0-Custom-Domain header support."""
424
425 def test_init_with_custom_domain(self):
426 """Should set Auth0-Custom-Domain header when custom_domain is provided."""
427 client = ManagementClient(
428 domain="test.auth0.com",
429 token="my-token",
430 custom_domain="login.mycompany.com",
431 )
432 custom_headers = client._api._client_wrapper.get_custom_headers()
433 assert custom_headers is not None
434 assert custom_headers[_CUSTOM_DOMAIN_HEADER] == "login.mycompany.com"
435
436 def test_init_custom_domain_with_existing_headers(self):
437 """Should merge custom_domain with other custom headers."""
438 client = ManagementClient(
439 domain="test.auth0.com",
440 token="my-token",
441 headers={"X-Custom": "value"},
442 custom_domain="login.mycompany.com",
443 )
444 custom_headers = client._api._client_wrapper.get_custom_headers()
445 assert custom_headers is not None
446 assert custom_headers["X-Custom"] == "value"
447 assert custom_headers[_CUSTOM_DOMAIN_HEADER] == "login.mycompany.com"
448
449 def test_init_without_custom_domain(self):
450 """Should not set Auth0-Custom-Domain header when custom_domain is not provided."""
451 client = ManagementClient(
452 domain="test.auth0.com",
453 token="my-token",
454 )
455 custom_headers = client._api._client_wrapper.get_custom_headers()
456 assert custom_headers is None or _CUSTOM_DOMAIN_HEADER not in custom_headers
457
458 def test_custom_domain_header_helper(self):
459 """Should return correct request options dict."""
460 result = CustomDomainHeader("login.mycompany.com")
461 assert result == {
462 "additional_headers": {
463 _CUSTOM_DOMAIN_HEADER: "login.mycompany.com",
464 }
465 }
466
467 def test_async_init_with_custom_domain(self):
468 """Should set Auth0-Custom-Domain header on async client."""
469 client = AsyncManagementClient(
470 domain="test.auth0.com",
471 token="my-token",
472 custom_domain="login.mycompany.com",
473 )
474 custom_headers = client._api._client_wrapper.get_custom_headers()
475 assert custom_headers is not None
476 assert custom_headers[_CUSTOM_DOMAIN_HEADER] == "login.mycompany.com"
477
478 def test_whitelist_strips_header_on_non_whitelisted_path(self):
479 """Should strip Auth0-Custom-Domain header on non-whitelisted paths."""
480 request = httpx.Request(
481 "GET",
482 "https://test.auth0.com/api/v2/clients",
483 headers={_CUSTOM_DOMAIN_HEADER: "login.mycompany.com"},
484 )
485 _enforce_custom_domain_whitelist(request)
486 assert _CUSTOM_DOMAIN_HEADER not in request.headers
487
488 def test_whitelist_keeps_header_on_whitelisted_path(self):
489 """Should keep Auth0-Custom-Domain header on whitelisted paths."""
490 request = httpx.Request(
491 "POST",
492 "https://test.auth0.com/api/v2/users",
493 headers={_CUSTOM_DOMAIN_HEADER: "login.mycompany.com"},
494 )
495 _enforce_custom_domain_whitelist(request)
496 assert request.headers[_CUSTOM_DOMAIN_HEADER] == "login.mycompany.com"
497
498 @pytest.mark.parametrize(
499 "path",
500 [
501 "/api/v2/jobs/verification-email",
502 "/api/v2/tickets/email-verification",
503 "/api/v2/tickets/password-change",
504 "/api/v2/organizations/org_abc123/invitations",
505 "/api/v2/users",
506 "/api/v2/users/auth0|abc123",
507 "/api/v2/guardian/enrollments/ticket",
508 "/api/v2/self-service-profiles/ssp_abc123/sso-ticket",
509 ],
510 )
511 def test_whitelisted_paths_match(self, path):
512 """Should match all 8 whitelisted path patterns."""
513 assert _is_path_whitelisted(path) is True
514
515 @pytest.mark.parametrize(
516 "path",
517 [
518 "/api/v2/clients",
519 "/api/v2/connections",
520 "/api/v2/roles",
521 "/api/v2/users/auth0|abc123/roles",
522 "/api/v2/jobs/users-imports",
523 "/api/v2/tenants/settings",
524 ],
525 )
526 def test_non_whitelisted_paths_do_not_match(self, path):
527 """Should not match non-whitelisted paths."""
528 assert _is_path_whitelisted(path) is False
529
530
531 class TestImports:
532 """Tests for module imports."""
533
534 def test_import_from_management(self):
535 """Should be able to import from auth0.management."""
536 from auth0.management import (
537 AsyncManagementClient,
538 AsyncTokenProvider,
539 CustomDomainHeader,
540 ManagementClient,
541 TokenProvider,
542 )
543
544 assert ManagementClient is not None
545 assert AsyncManagementClient is not None
546 assert TokenProvider is not None
547 assert AsyncTokenProvider is not None
548 assert CustomDomainHeader is not None