Debian Codegraph @

src/auth0/authentication/rest.py

raw symbols SCIP
1 from __future__ import annotations
2
3 import base64
4 import platform
5 import sys
6 from json import dumps, loads
7 from random import randint
8 from time import sleep
9 from typing import TYPE_CHECKING, Any, Mapping
10 from urllib.parse import urlencode
11
12 import requests
13 from .exceptions import Auth0Error, RateLimitError
14 from .types import RequestData, TimeoutType
15
16 if TYPE_CHECKING:
17 from .rest_async import RequestsResponse
18
19 UNKNOWN_ERROR = "a0.sdk.internal.unknown"
20
21
22 class RestClientOptions:
23 """Configuration object for RestClient. Used for configuring
24 additional RestClient options, such as rate-limit
25 retries.
26
27 Args:
28 telemetry (bool, optional): Enable or disable Telemetry
29 (defaults to True)
30 timeout (float or tuple, optional): Change the requests
31 connect and read timeout. Pass a tuple to specify
32 both values separately or a float to set both to it.
33 (defaults to 5.0 for both)
34 retries (integer): In the event an API request returns a
35 429 response header (indicating rate-limit has been
36 hit), the RestClient will retry the request this many
37 times using an exponential backoff strategy, before
38 raising a RateLimitError exception. 10 retries max.
39 (defaults to 3)
40 client_info (dict, optional): Custom telemetry data to send
41 in the Auth0-Client header instead of the default SDK
42 info. Useful for wrapper SDKs that need to identify
43 themselves. When provided, this dict is JSON-encoded
44 and base64-encoded as the header value. Ignored when
45 telemetry is False.
46 (defaults to None)
47 """
48
49 def __init__(
50 self,
51 telemetry: bool = True,
52 timeout: TimeoutType = 5.0,
53 retries: int = 3,
54 client_info: dict[str, Any] | None = None,
55 ) -> None:
56 self.telemetry = telemetry
57 self.timeout = timeout
58 self.retries = retries
59 self.client_info = client_info
60
61
62 class RestClient:
63 """Provides simple methods for handling all RESTful api endpoints.
64
65 Args:
66 jwt (str, optional): The JWT to be used with the RestClient.
67 telemetry (bool, optional): Enable or disable Telemetry
68 (defaults to True)
69 timeout (float or tuple, optional): Change the requests
70 connect and read timeout. Pass a tuple to specify
71 both values separately or a float to set both to it.
72 (defaults to 5.0 for both)
73 options (RestClientOptions): Pass an instance of
74 RestClientOptions to configure additional RestClient
75 options, such as rate-limit retries. Overrides matching
76 options passed to the constructor.
77 (defaults to 3)
78 """
79
80 def __init__(
81 self,
82 jwt: str | None,
83 telemetry: bool = True,
84 timeout: TimeoutType = 5.0,
85 options: RestClientOptions | None = None,
86 ) -> None:
87 if options is None:
88 options = RestClientOptions(telemetry=telemetry, timeout=timeout)
89
90 self.options = options
91 self.jwt = jwt
92
93 self._metrics = {"retries": 0, "backoff": []}
94 self._skip_sleep = False
95
96 self.base_headers = {
97 "Content-Type": "application/json",
98 }
99
100 if jwt is not None:
101 self.base_headers["Authorization"] = f"Bearer {self.jwt}"
102
103 if options.telemetry:
104 py_version = platform.python_version()
105
106 if options.client_info is not None:
107 auth0_client_dict = options.client_info
108 else:
109 version = sys.modules["auth0"].__version__
110 auth0_client_dict = {
111 "name": "auth0-python",
112 "version": version,
113 "env": {
114 "python": py_version,
115 },
116 }
117
118 auth0_client = dumps(auth0_client_dict).encode("utf-8")
119
120 self.base_headers.update(
121 {
122 "User-Agent": f"Python/{py_version}",
123 "Auth0-Client": base64.b64encode(auth0_client).decode(),
124 }
125 )
126
127 # Cap the maximum number of retries to 10 or fewer. Floor the retries at 0.
128 self._retries = min(self.MAX_REQUEST_RETRIES(), max(0, options.retries))
129
130 # For backwards compatibility reasons only
131 # TODO: Deprecate in the next major so we can prune these arguments. Guidance should be to use RestClient.options.*
132 self.telemetry = options.telemetry
133 self.timeout = options.timeout
134
135 # Returns a hard cap for the maximum number of retries allowed (10)
136 def MAX_REQUEST_RETRIES(self) -> int:
137 return 10
138
139 # Returns the maximum amount of jitter to introduce in milliseconds (100ms)
140 def MAX_REQUEST_RETRY_JITTER(self) -> int:
141 return 100
142
143 # Returns the maximum delay window allowed (1000ms)
144 def MAX_REQUEST_RETRY_DELAY(self) -> int:
145 return 1000
146
147 # Returns the minimum delay window allowed (100ms)
148 def MIN_REQUEST_RETRY_DELAY(self) -> int:
149 return 100
150
151 def _request(
152 self,
153 method: str,
154 url: str,
155 params: dict[str, Any] | None = None,
156 data: RequestData | None = None,
157 json: RequestData | None = None,
158 headers: dict[str, str] | None = None,
159 files: dict[str, Any] | None = None,
160 ) -> Any:
161 # Track the API request attempt number
162 attempt = 0
163
164 # Reset the metrics tracker
165 self._metrics = {"retries": 0, "backoff": []}
166
167 if data is None and json is not None and headers:
168 content_type = headers.get("Content-Type", "").lower() # Get Content-Type
169 if "application/x-www-form-urlencoded" in content_type:
170 data = urlencode(json) # Copy JSON data into data
171 json = None # Prevent JSON from being sent
172
173 kwargs = {
174 k: v
175 for k, v in {
176 "params": params,
177 "json": json,
178 "data": data,
179 "headers": headers,
180 "files": files,
181 "timeout": self.options.timeout,
182 }.items()
183 if v is not None
184 }
185
186 while True:
187 # Increment attempt number
188 attempt += 1
189
190 # Issue the request
191 response = requests.request(method, url, **kwargs)
192
193 # If the response did not have a 429 header, or the attempt number is greater than the configured retries, break
194 if response.status_code != 429 or attempt > self._retries:
195 break
196
197 wait = self._calculate_wait(attempt)
198
199 # Skip calling sleep() when running unit tests
200 if self._skip_sleep is False:
201 # sleep() functions in seconds, so convert the milliseconds formula above accordingly
202 sleep(wait / 1000)
203
204 # Return the final Response
205 return self._process_response(response)
206
207 def get(
208 self,
209 url: str,
210 params: dict[str, Any] | None = None,
211 headers: dict[str, str] | None = None,
212 ) -> Any:
213 request_headers = self.base_headers.copy()
214 request_headers.update(headers or {})
215 return self._request("GET", url, params=params, headers=request_headers)
216
217 def post(
218 self,
219 url: str,
220 data: RequestData | None = None,
221 headers: dict[str, str] | None = None,
222 ) -> Any:
223 request_headers = self.base_headers.copy()
224 request_headers.update(headers or {})
225 return self._request("POST", url, json=data, headers=request_headers)
226
227 def file_post(
228 self,
229 url: str,
230 data: RequestData | None = None,
231 files: dict[str, Any] | None = None,
232 ) -> Any:
233 headers = self.base_headers.copy()
234 headers.pop("Content-Type", None)
235 return self._request("POST", url, data=data, files=files, headers=headers)
236
237 def patch(self, url: str, data: RequestData | None = None) -> Any:
238 headers = self.base_headers.copy()
239 return self._request("PATCH", url, json=data, headers=headers)
240
241 def put(self, url: str, data: RequestData | None = None) -> Any:
242 headers = self.base_headers.copy()
243 return self._request("PUT", url, json=data, headers=headers)
244
245 def delete(
246 self,
247 url: str,
248 params: dict[str, Any] | None = None,
249 data: RequestData | None = None,
250 ) -> Any:
251 headers = self.base_headers.copy()
252 return self._request("DELETE", url, params=params, json=data, headers=headers)
253
254 def _calculate_wait(self, attempt: int) -> int:
255 # Retry the request. Apply a exponential backoff for subsequent attempts, using this formula:
256 # max(MIN_REQUEST_RETRY_DELAY, min(MAX_REQUEST_RETRY_DELAY, (100ms * (2 ** attempt - 1)) + random_between(1, MAX_REQUEST_RETRY_JITTER)))
257
258 # Increases base delay by (100ms * (2 ** attempt - 1))
259 wait = 100 * 2 ** (attempt - 1)
260
261 # Introduces jitter to the base delay; increases delay between 1ms to MAX_REQUEST_RETRY_JITTER (100ms)
262 wait += randint(1, self.MAX_REQUEST_RETRY_JITTER())
263
264 # Is never more than MAX_REQUEST_RETRY_DELAY (1s)
265 wait = min(self.MAX_REQUEST_RETRY_DELAY(), wait)
266
267 # Is never less than MIN_REQUEST_RETRY_DELAY (100ms)
268 wait = max(self.MIN_REQUEST_RETRY_DELAY(), wait)
269
270 self._metrics["retries"] = attempt
271 self._metrics["backoff"].append(wait) # type: ignore[attr-defined]
272
273 return wait
274
275 def _process_response(self, response: requests.Response) -> Any:
276 return self._parse(response).content()
277
278 def _parse(self, response: requests.Response) -> Response:
279 if not response.text:
280 return EmptyResponse(response.status_code)
281 try:
282 return JsonResponse(response)
283 except ValueError:
284 return PlainResponse(response)
285
286
287 class Response:
288 def __init__(
289 self, status_code: int, content: Any, headers: Mapping[str, str]
290 ) -> None:
291 self._status_code = status_code
292 self._content = content
293 self._headers = headers
294
295 def content(self) -> Any:
296 if self._is_error():
297 if self._status_code == 429:
298 reset_at = int(self._headers.get("x-ratelimit-reset", "-1"))
299 raise RateLimitError(
300 error_code=self._error_code(),
301 message=self._error_message(),
302 reset_at=reset_at,
303 headers=self._headers,
304 )
305 if self._error_code() == "mfa_required":
306 raise Auth0Error(
307 status_code=self._status_code,
308 error_code=self._error_code(),
309 message=self._error_message(),
310 content=self._content,
311 headers=self._headers
312 )
313
314 raise Auth0Error(
315 status_code=self._status_code,
316 error_code=self._error_code(),
317 message=self._error_message(),
318 headers=self._headers
319 )
320 else:
321 return self._content
322
323 def _is_error(self) -> bool:
324 return self._status_code is None or self._status_code >= 400
325
326 # Adding these methods to force implementation in subclasses because they are references in this parent class
327 def _error_code(self):
328 raise NotImplementedError
329
330 def _error_message(self):
331 raise NotImplementedError
332
333
334 class JsonResponse(Response):
335 def __init__(self, response: requests.Response | RequestsResponse) -> None:
336 content = loads(response.text)
337 super().__init__(response.status_code, content, response.headers)
338
339 def _error_code(self) -> str:
340 if "errorCode" in self._content:
341 return self._content.get("errorCode")
342 elif "error" in self._content:
343 return self._content.get("error")
344 elif "code" in self._content:
345 return self._content.get("code")
346 else:
347 return UNKNOWN_ERROR
348
349 def _error_message(self) -> str:
350 if "error_description" in self._content:
351 return self._content.get("error_description")
352 message = self._content.get("message", "")
353 if message is not None and message != "":
354 return message
355 return self._content.get("error", "")
356
357
358 class PlainResponse(Response):
359 def __init__(self, response: requests.Response | RequestsResponse) -> None:
360 super().__init__(response.status_code, response.text, response.headers)
361
362 def _error_code(self) -> str:
363 return UNKNOWN_ERROR
364
365 def _error_message(self) -> str:
366 return self._content
367
368
369 class EmptyResponse(Response):
370 def __init__(self, status_code: int) -> None:
371 super().__init__(status_code, "", {})
372
373 def _error_code(self) -> str:
374 return UNKNOWN_ERROR
375
376 def _error_message(self) -> str:
377 return ""