Debian Codegraph @

src/auth0/management/token_provider.py

raw symbols SCIP
1 import asyncio
2 import threading
3 import time
4 from typing import Optional
5
6 import httpx
7
8 LEEWAY_SECONDS = 10
9
10
11 class TokenProvider:
12 """
13 Sync token provider with caching and automatic refresh.
14
15 Fetches tokens via OAuth 2.0 client credentials grant and caches them
16 until they expire (with a 10-second leeway for safety).
17
18 Thread-safe: uses a lock to prevent concurrent token fetches.
19 """
20
21 def __init__(
22 self,
23 *,
24 domain: str,
25 client_id: str,
26 client_secret: str,
27 audience: Optional[str] = None,
28 ):
29 self._domain = domain
30 self._client_id = client_id
31 self._client_secret = client_secret
32 self._audience = audience or f"https://{domain}/api/v2/"
33
34 self._access_token: Optional[str] = None
35 self._expires_at: float = 0
36 self._lock = threading.Lock()
37
38 def get_token(self) -> str:
39 """
40 Get a valid access token, fetching a new one if expired.
41
42 Returns
43 -------
44 str
45 A valid access token.
46 """
47 # Fast path: return cached token if still valid
48 if self._access_token and time.time() < (self._expires_at - LEEWAY_SECONDS):
49 return self._access_token
50
51 with self._lock:
52 # Double-check after acquiring lock
53 if self._access_token and time.time() < (self._expires_at - LEEWAY_SECONDS):
54 return self._access_token
55 self._fetch_token()
56
57 return self._access_token # type: ignore[return-value]
58
59 def _fetch_token(self) -> None:
60 """Fetch a new token via client credentials grant."""
61 url = f"https://{self._domain}/oauth/token"
62 payload = {
63 "grant_type": "client_credentials",
64 "client_id": self._client_id,
65 "client_secret": self._client_secret,
66 "audience": self._audience,
67 }
68
69 with httpx.Client() as client:
70 response = client.post(url, data=payload)
71 response.raise_for_status()
72 data = response.json()
73
74 self._access_token = data["access_token"]
75 self._expires_at = time.time() + data["expires_in"]
76
77
78 class AsyncTokenProvider:
79 """
80 Async token provider with caching and automatic refresh.
81
82 Fetches tokens via OAuth 2.0 client credentials grant and caches them
83 until they expire (with a 10-second leeway for safety).
84
85 Coroutine-safe: uses an async lock to prevent concurrent token fetches.
86 """
87
88 def __init__(
89 self,
90 *,
91 domain: str,
92 client_id: str,
93 client_secret: str,
94 audience: Optional[str] = None,
95 ):
96 self._domain = domain
97 self._client_id = client_id
98 self._client_secret = client_secret
99 self._audience = audience or f"https://{domain}/api/v2/"
100
101 self._access_token: Optional[str] = None
102 self._expires_at: float = 0
103 self._lock = asyncio.Lock()
104
105 async def get_token(self) -> str:
106 """
107 Get a valid access token, fetching a new one if expired.
108
109 Returns
110 -------
111 str
112 A valid access token.
113 """
114 # Fast path: return cached token if still valid
115 if self._access_token and time.time() < (self._expires_at - LEEWAY_SECONDS):
116 return self._access_token
117
118 async with self._lock:
119 # Double-check after acquiring lock
120 if self._access_token and time.time() < (self._expires_at - LEEWAY_SECONDS):
121 return self._access_token
122 await self._fetch_token()
123
124 return self._access_token # type: ignore[return-value]
125
126 async def _fetch_token(self) -> None:
127 """Fetch a new token via client credentials grant."""
128 url = f"https://{self._domain}/oauth/token"
129 payload = {
130 "grant_type": "client_credentials",
131 "client_id": self._client_id,
132 "client_secret": self._client_secret,
133 "audience": self._audience,
134 }
135
136 async with httpx.AsyncClient() as client:
137 response = await client.post(url, data=payload)
138 response.raise_for_status()
139 data = response.json()
140
141 self._access_token = data["access_token"]
142 self._expires_at = time.time() + data["expires_in"]