Debian Codegraph @

src/auth0/management/management_client.py

raw symbols SCIP
1 from __future__ import annotations
2
3 import base64
4 import re
5 from json import dumps
6 from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Union
7
8 from .core.request_options import RequestOptions
9
10 import httpx
11 from .client import AsyncAuth0, Auth0
12 from .token_provider import TokenProvider
13
14 CUSTOM_DOMAIN_HEADER = "Auth0-Custom-Domain"
15
16 WHITELISTED_PATH_PATTERNS: List[re.Pattern[str]] = [
17 re.compile(r"^/api/v2/jobs/verification-email$"),
18 re.compile(r"^/api/v2/tickets/email-verification$"),
19 re.compile(r"^/api/v2/tickets/password-change$"),
20 re.compile(r"^/api/v2/organizations/[^/]+/invitations$"),
21 re.compile(r"^/api/v2/users$"),
22 re.compile(r"^/api/v2/users/[^/]+$"),
23 re.compile(r"^/api/v2/guardian/enrollments/ticket$"),
24 re.compile(r"^/api/v2/self-service-profiles/[^/]+/sso-ticket$"),
25 ]
26
27
28 def _is_path_whitelisted(path: str) -> bool:
29 """Check if the given path is whitelisted for the custom domain header."""
30 return any(p.match(path) for p in WHITELISTED_PATH_PATTERNS)
31
32
33 def _enforce_custom_domain_whitelist(request: httpx.Request) -> None:
34 """httpx event hook that strips Auth0-Custom-Domain on non-whitelisted paths."""
35 if CUSTOM_DOMAIN_HEADER in request.headers and not _is_path_whitelisted(
36 request.url.path
37 ):
38 del request.headers[CUSTOM_DOMAIN_HEADER]
39
40
41 def CustomDomainHeader(domain: str) -> RequestOptions:
42 """Create request options that set the Auth0-Custom-Domain header for a single request.
43
44 When both a global custom_domain (set at client init) and a per-request
45 custom_domain_header are provided, the per-request value takes precedence.
46 The header is only sent on whitelisted endpoints.
47
48 Usage::
49
50 from auth0.management import ManagementClient, CustomDomainHeader
51
52 client = ManagementClient(domain="tenant.auth0.com", token="TOKEN")
53 client.users.create(
54 connection="Username-Password-Authentication",
55 email="[email protected]",
56 password="...",
57 request_options=CustomDomainHeader("login.mycompany.com"),
58 )
59 """
60 return {"additional_headers": {CUSTOM_DOMAIN_HEADER: domain}}
61
62 if TYPE_CHECKING:
63 from .actions.client import ActionsClient, AsyncActionsClient
64 from .anomaly.client import AnomalyClient, AsyncAnomalyClient
65 from .attack_protection.client import AsyncAttackProtectionClient, AttackProtectionClient
66 from .branding.client import AsyncBrandingClient, BrandingClient
67 from .client_grants.client import AsyncClientGrantsClient, ClientGrantsClient
68 from .clients.client import AsyncClientsClient, ClientsClient
69 from .connections.client import AsyncConnectionsClient, ConnectionsClient
70 from .custom_domains.client import AsyncCustomDomainsClient, CustomDomainsClient
71 from .device_credentials.client import AsyncDeviceCredentialsClient, DeviceCredentialsClient
72 from .email_templates.client import AsyncEmailTemplatesClient, EmailTemplatesClient
73 from .emails.client import AsyncEmailsClient, EmailsClient
74 from .event_streams.client import AsyncEventStreamsClient, EventStreamsClient
75 from .flows.client import AsyncFlowsClient, FlowsClient
76 from .forms.client import AsyncFormsClient, FormsClient
77 from .guardian.client import AsyncGuardianClient, GuardianClient
78 from .hooks.client import AsyncHooksClient, HooksClient
79 from .jobs.client import AsyncJobsClient, JobsClient
80 from .keys.client import AsyncKeysClient, KeysClient
81 from .log_streams.client import AsyncLogStreamsClient, LogStreamsClient
82 from .logs.client import AsyncLogsClient, LogsClient
83 from .network_acls.client import AsyncNetworkAclsClient, NetworkAclsClient
84 from .organizations.client import AsyncOrganizationsClient, OrganizationsClient
85 from .prompts.client import AsyncPromptsClient, PromptsClient
86 from .refresh_tokens.client import AsyncRefreshTokensClient, RefreshTokensClient
87 from .resource_servers.client import AsyncResourceServersClient, ResourceServersClient
88 from .roles.client import AsyncRolesClient, RolesClient
89 from .rules.client import AsyncRulesClient, RulesClient
90 from .rules_configs.client import AsyncRulesConfigsClient, RulesConfigsClient
91 from .self_service_profiles.client import AsyncSelfServiceProfilesClient, SelfServiceProfilesClient
92 from .sessions.client import AsyncSessionsClient, SessionsClient
93 from .stats.client import AsyncStatsClient, StatsClient
94 from .supplemental_signals.client import AsyncSupplementalSignalsClient, SupplementalSignalsClient
95 from .tenants.client import AsyncTenantsClient, TenantsClient
96 from .tickets.client import AsyncTicketsClient, TicketsClient
97 from .token_exchange_profiles.client import AsyncTokenExchangeProfilesClient, TokenExchangeProfilesClient
98 from .user_blocks.client import AsyncUserBlocksClient, UserBlocksClient
99 from .user_grants.client import AsyncUserGrantsClient, UserGrantsClient
100 from .users.client import AsyncUsersClient, UsersClient
101 from .verifiable_credentials.client import AsyncVerifiableCredentialsClient, VerifiableCredentialsClient
102
103
104 class ManagementClient:
105 """
106 Auth0 Management API client with automatic token management.
107
108 Supports two initialization patterns:
109
110 1. With an existing token:
111
112 client = ManagementClient(
113 domain="tenant.auth0.com",
114 token="your_token"
115 )
116
117 2. With client credentials (automatic token acquisition and refresh):
118
119 client = ManagementClient(
120 domain="tenant.auth0.com",
121 client_id="your_client_id",
122 client_secret="your_client_secret"
123 )
124
125 Parameters
126 ----------
127 domain : str
128 Your Auth0 domain (e.g., "your-tenant.auth0.com").
129 token : Optional[Union[str, Callable[[], str]]]
130 A static token string or a callable that returns a token.
131 Required if client_id/client_secret are not provided.
132 client_id : Optional[str]
133 Your Auth0 application client ID.
134 Required along with client_secret for automatic token acquisition.
135 client_secret : Optional[str]
136 Your Auth0 application client secret.
137 Required along with client_id for automatic token acquisition.
138 audience : Optional[str]
139 The API audience. Defaults to https://{domain}/api/v2/
140 headers : Optional[Dict[str, str]]
141 Additional headers to send with requests.
142 custom_domain : Optional[str]
143 A custom domain to send via the Auth0-Custom-Domain header.
144 The header is only sent on whitelisted endpoints. Use
145 ``CustomDomainHeader()`` for per-request overrides.
146 client_info : Optional[Dict[str, Any]]
147 Custom telemetry data for the Auth0-Client header. When provided,
148 overrides the default SDK telemetry. Useful for wrapper SDKs that
149 need to identify themselves (e.g., ``{"name": "my-sdk", "version": "1.0.0"}``).
150 timeout : Optional[float]
151 Request timeout in seconds. Defaults to 60.
152 httpx_client : Optional[httpx.Client]
153 Custom httpx client for requests.
154
155 Raises
156 ------
157 ValueError
158 If neither token nor client_id/client_secret are provided.
159 """
160
161 def __init__(
162 self,
163 *,
164 domain: str,
165 token: Optional[Union[str, Callable[[], str]]] = None,
166 client_id: Optional[str] = None,
167 client_secret: Optional[str] = None,
168 audience: Optional[str] = None,
169 headers: Optional[Dict[str, str]] = None,
170 custom_domain: Optional[str] = None,
171 client_info: Optional[Dict[str, Any]] = None,
172 timeout: Optional[float] = None,
173 httpx_client: Optional[httpx.Client] = None,
174 ):
175 # Validate auth options
176 has_token = token is not None
177 has_credentials = client_id is not None and client_secret is not None
178
179 if not has_token and not has_credentials:
180 raise ValueError("Either 'token' or both 'client_id' and 'client_secret' must be provided")
181
182 # Create token supplier
183 if has_credentials and not has_token:
184 provider = TokenProvider(
185 domain=domain,
186 client_id=client_id, # type: ignore[arg-type]
187 client_secret=client_secret, # type: ignore[arg-type]
188 audience=audience,
189 )
190 resolved_token: Union[str, Callable[[], str]] = provider.get_token
191 else:
192 resolved_token = token # type: ignore[assignment]
193
194 # Set up custom domain header with whitelist enforcement
195 if custom_domain is not None:
196 headers = {**(headers or {}), CUSTOM_DOMAIN_HEADER: custom_domain}
197 if httpx_client is None:
198 httpx_client = httpx.Client(timeout=timeout or 60, follow_redirects=True)
199 httpx_client.event_hooks.setdefault("request", []).append(
200 _enforce_custom_domain_whitelist
201 )
202
203 # Encode client_info into Auth0-Client header to override default telemetry
204 if client_info is not None:
205 encoded = base64.b64encode(
206 dumps(client_info).encode("utf-8")
207 ).decode()
208 headers = {**(headers or {}), "Auth0-Client": encoded}
209
210 # Create underlying client
211 self._api = Auth0(
212 base_url=f"https://{domain}/api/v2",
213 token=resolved_token,
214 headers=headers,
215 timeout=timeout,
216 httpx_client=httpx_client,
217 )
218
219 # Forward all sub-client properties
220 @property
221 def actions(self) -> "ActionsClient":
222 return self._api.actions
223
224 @property
225 def anomaly(self) -> "AnomalyClient":
226 return self._api.anomaly
227
228 @property
229 def attack_protection(self) -> "AttackProtectionClient":
230 return self._api.attack_protection
231
232 @property
233 def branding(self) -> "BrandingClient":
234 return self._api.branding
235
236 @property
237 def client_grants(self) -> "ClientGrantsClient":
238 return self._api.client_grants
239
240 @property
241 def clients(self) -> "ClientsClient":
242 return self._api.clients
243
244 @property
245 def connections(self) -> "ConnectionsClient":
246 return self._api.connections
247
248 @property
249 def custom_domains(self) -> "CustomDomainsClient":
250 return self._api.custom_domains
251
252 @property
253 def device_credentials(self) -> "DeviceCredentialsClient":
254 return self._api.device_credentials
255
256 @property
257 def email_templates(self) -> "EmailTemplatesClient":
258 return self._api.email_templates
259
260 @property
261 def emails(self) -> "EmailsClient":
262 return self._api.emails
263
264 @property
265 def event_streams(self) -> "EventStreamsClient":
266 return self._api.event_streams
267
268 @property
269 def flows(self) -> "FlowsClient":
270 return self._api.flows
271
272 @property
273 def forms(self) -> "FormsClient":
274 return self._api.forms
275
276 @property
277 def guardian(self) -> "GuardianClient":
278 return self._api.guardian
279
280 @property
281 def hooks(self) -> "HooksClient":
282 return self._api.hooks
283
284 @property
285 def jobs(self) -> "JobsClient":
286 return self._api.jobs
287
288 @property
289 def keys(self) -> "KeysClient":
290 return self._api.keys
291
292 @property
293 def log_streams(self) -> "LogStreamsClient":
294 return self._api.log_streams
295
296 @property
297 def logs(self) -> "LogsClient":
298 return self._api.logs
299
300 @property
301 def network_acls(self) -> "NetworkAclsClient":
302 return self._api.network_acls
303
304 @property
305 def organizations(self) -> "OrganizationsClient":
306 return self._api.organizations
307
308 @property
309 def prompts(self) -> "PromptsClient":
310 return self._api.prompts
311
312 @property
313 def refresh_tokens(self) -> "RefreshTokensClient":
314 return self._api.refresh_tokens
315
316 @property
317 def resource_servers(self) -> "ResourceServersClient":
318 return self._api.resource_servers
319
320 @property
321 def roles(self) -> "RolesClient":
322 return self._api.roles
323
324 @property
325 def rules(self) -> "RulesClient":
326 return self._api.rules
327
328 @property
329 def rules_configs(self) -> "RulesConfigsClient":
330 return self._api.rules_configs
331
332 @property
333 def self_service_profiles(self) -> "SelfServiceProfilesClient":
334 return self._api.self_service_profiles
335
336 @property
337 def sessions(self) -> "SessionsClient":
338 return self._api.sessions
339
340 @property
341 def stats(self) -> "StatsClient":
342 return self._api.stats
343
344 @property
345 def supplemental_signals(self) -> "SupplementalSignalsClient":
346 return self._api.supplemental_signals
347
348 @property
349 def tenants(self) -> "TenantsClient":
350 return self._api.tenants
351
352 @property
353 def tickets(self) -> "TicketsClient":
354 return self._api.tickets
355
356 @property
357 def token_exchange_profiles(self) -> "TokenExchangeProfilesClient":
358 return self._api.token_exchange_profiles
359
360 @property
361 def user_blocks(self) -> "UserBlocksClient":
362 return self._api.user_blocks
363
364 @property
365 def user_grants(self) -> "UserGrantsClient":
366 return self._api.user_grants
367
368 @property
369 def users(self) -> "UsersClient":
370 return self._api.users
371
372 @property
373 def verifiable_credentials(self) -> "VerifiableCredentialsClient":
374 return self._api.verifiable_credentials
375
376
377 class AsyncManagementClient:
378 """
379 Async Auth0 Management API client with automatic token management.
380
381 Supports two initialization patterns:
382
383 1. With an existing token:
384
385 client = AsyncManagementClient(
386 domain="tenant.auth0.com",
387 token="your_token"
388 )
389
390 2. With client credentials (automatic token acquisition and refresh):
391
392 client = AsyncManagementClient(
393 domain="tenant.auth0.com",
394 client_id="your_client_id",
395 client_secret="your_client_secret"
396 )
397
398 Parameters
399 ----------
400 domain : str
401 Your Auth0 domain (e.g., "your-tenant.auth0.com").
402 token : Optional[Union[str, Callable[[], str]]]
403 A static token string or a callable that returns a token.
404 Required if client_id/client_secret are not provided.
405 client_id : Optional[str]
406 Your Auth0 application client ID.
407 Required along with client_secret for automatic token acquisition.
408 client_secret : Optional[str]
409 Your Auth0 application client secret.
410 Required along with client_id for automatic token acquisition.
411 audience : Optional[str]
412 The API audience. Defaults to https://{domain}/api/v2/
413 headers : Optional[Dict[str, str]]
414 Additional headers to send with requests.
415 custom_domain : Optional[str]
416 A custom domain to send via the Auth0-Custom-Domain header.
417 The header is only sent on whitelisted endpoints. Use
418 ``CustomDomainHeader()`` for per-request overrides.
419 client_info : Optional[Dict[str, Any]]
420 Custom telemetry data for the Auth0-Client header. When provided,
421 overrides the default SDK telemetry. Useful for wrapper SDKs that
422 need to identify themselves (e.g., ``{"name": "my-sdk", "version": "1.0.0"}``).
423 timeout : Optional[float]
424 Request timeout in seconds. Defaults to 60.
425 httpx_client : Optional[httpx.AsyncClient]
426 Custom httpx async client for requests.
427
428 Raises
429 ------
430 ValueError
431 If neither token nor client_id/client_secret are provided.
432 """
433
434 def __init__(
435 self,
436 *,
437 domain: str,
438 token: Optional[Union[str, Callable[[], str]]] = None,
439 client_id: Optional[str] = None,
440 client_secret: Optional[str] = None,
441 audience: Optional[str] = None,
442 headers: Optional[Dict[str, str]] = None,
443 custom_domain: Optional[str] = None,
444 client_info: Optional[Dict[str, Any]] = None,
445 timeout: Optional[float] = None,
446 httpx_client: Optional[httpx.AsyncClient] = None,
447 ):
448 # Validate auth options
449 has_token = token is not None
450 has_credentials = client_id is not None and client_secret is not None
451
452 if not has_token and not has_credentials:
453 raise ValueError("Either 'token' or both 'client_id' and 'client_secret' must be provided")
454
455 # Create token supplier
456 # Note: AsyncAuth0Api expects a sync callable for token, so we use
457 # the sync TokenProvider. This is safe because httpx sync calls work
458 # in async contexts.
459 if has_credentials and not has_token:
460 provider = TokenProvider(
461 domain=domain,
462 client_id=client_id, # type: ignore[arg-type]
463 client_secret=client_secret, # type: ignore[arg-type]
464 audience=audience,
465 )
466 resolved_token: Union[str, Callable[[], str]] = provider.get_token
467 else:
468 resolved_token = token # type: ignore[assignment]
469
470 # Set up custom domain header with whitelist enforcement
471 if custom_domain is not None:
472 headers = {**(headers or {}), CUSTOM_DOMAIN_HEADER: custom_domain}
473 if httpx_client is None:
474 httpx_client = httpx.AsyncClient(timeout=timeout or 60, follow_redirects=True)
475 httpx_client.event_hooks.setdefault("request", []).append(
476 _enforce_custom_domain_whitelist
477 )
478
479 # Encode client_info into Auth0-Client header to override default telemetry
480 if client_info is not None:
481 encoded = base64.b64encode(
482 dumps(client_info).encode("utf-8")
483 ).decode()
484 headers = {**(headers or {}), "Auth0-Client": encoded}
485
486 # Create underlying client
487 self._api = AsyncAuth0(
488 base_url=f"https://{domain}/api/v2",
489 token=resolved_token,
490 headers=headers,
491 timeout=timeout,
492 httpx_client=httpx_client,
493 )
494
495 # Forward all sub-client properties
496 @property
497 def actions(self) -> "AsyncActionsClient":
498 return self._api.actions
499
500 @property
501 def anomaly(self) -> "AsyncAnomalyClient":
502 return self._api.anomaly
503
504 @property
505 def attack_protection(self) -> "AsyncAttackProtectionClient":
506 return self._api.attack_protection
507
508 @property
509 def branding(self) -> "AsyncBrandingClient":
510 return self._api.branding
511
512 @property
513 def client_grants(self) -> "AsyncClientGrantsClient":
514 return self._api.client_grants
515
516 @property
517 def clients(self) -> "AsyncClientsClient":
518 return self._api.clients
519
520 @property
521 def connections(self) -> "AsyncConnectionsClient":
522 return self._api.connections
523
524 @property
525 def custom_domains(self) -> "AsyncCustomDomainsClient":
526 return self._api.custom_domains
527
528 @property
529 def device_credentials(self) -> "AsyncDeviceCredentialsClient":
530 return self._api.device_credentials
531
532 @property
533 def email_templates(self) -> "AsyncEmailTemplatesClient":
534 return self._api.email_templates
535
536 @property
537 def emails(self) -> "AsyncEmailsClient":
538 return self._api.emails
539
540 @property
541 def event_streams(self) -> "AsyncEventStreamsClient":
542 return self._api.event_streams
543
544 @property
545 def flows(self) -> "AsyncFlowsClient":
546 return self._api.flows
547
548 @property
549 def forms(self) -> "AsyncFormsClient":
550 return self._api.forms
551
552 @property
553 def guardian(self) -> "AsyncGuardianClient":
554 return self._api.guardian
555
556 @property
557 def hooks(self) -> "AsyncHooksClient":
558 return self._api.hooks
559
560 @property
561 def jobs(self) -> "AsyncJobsClient":
562 return self._api.jobs
563
564 @property
565 def keys(self) -> "AsyncKeysClient":
566 return self._api.keys
567
568 @property
569 def log_streams(self) -> "AsyncLogStreamsClient":
570 return self._api.log_streams
571
572 @property
573 def logs(self) -> "AsyncLogsClient":
574 return self._api.logs
575
576 @property
577 def network_acls(self) -> "AsyncNetworkAclsClient":
578 return self._api.network_acls
579
580 @property
581 def organizations(self) -> "AsyncOrganizationsClient":
582 return self._api.organizations
583
584 @property
585 def prompts(self) -> "AsyncPromptsClient":
586 return self._api.prompts
587
588 @property
589 def refresh_tokens(self) -> "AsyncRefreshTokensClient":
590 return self._api.refresh_tokens
591
592 @property
593 def resource_servers(self) -> "AsyncResourceServersClient":
594 return self._api.resource_servers
595
596 @property
597 def roles(self) -> "AsyncRolesClient":
598 return self._api.roles
599
600 @property
601 def rules(self) -> "AsyncRulesClient":
602 return self._api.rules
603
604 @property
605 def rules_configs(self) -> "AsyncRulesConfigsClient":
606 return self._api.rules_configs
607
608 @property
609 def self_service_profiles(self) -> "AsyncSelfServiceProfilesClient":
610 return self._api.self_service_profiles
611
612 @property
613 def sessions(self) -> "AsyncSessionsClient":
614 return self._api.sessions
615
616 @property
617 def stats(self) -> "AsyncStatsClient":
618 return self._api.stats
619
620 @property
621 def supplemental_signals(self) -> "AsyncSupplementalSignalsClient":
622 return self._api.supplemental_signals
623
624 @property
625 def tenants(self) -> "AsyncTenantsClient":
626 return self._api.tenants
627
628 @property
629 def tickets(self) -> "AsyncTicketsClient":
630 return self._api.tickets
631
632 @property
633 def token_exchange_profiles(self) -> "AsyncTokenExchangeProfilesClient":
634 return self._api.token_exchange_profiles
635
636 @property
637 def user_blocks(self) -> "AsyncUserBlocksClient":
638 return self._api.user_blocks
639
640 @property
641 def user_grants(self) -> "AsyncUserGrantsClient":
642 return self._api.user_grants
643
644 @property
645 def users(self) -> "AsyncUsersClient":
646 return self._api.users
647
648 @property
649 def verifiable_credentials(self) -> "AsyncVerifiableCredentialsClient":
650 return self._api.verifiable_credentials