Debian Codegraph @

ansible_collections/community/dns/plugins/module_utils/_json_api_helper.py

raw
1 # Copyright (c) 2021 Felix Fontein
2 # Copyright (c) 2020 Markus Bergholz <[email protected]>
3 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5
6 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
7 # Do not use this from other collections or standalone plugins/modules!
8
9 from __future__ import annotations
10
11 import json
12 import time
13 import typing as t
14 from collections.abc import Sequence
15 from urllib.parse import urlencode
16
17 from ansible.module_utils.common.text.converters import to_native
18
19 from ansible_collections.community.dns.plugins.module_utils._zone_record_api import (
20 DNSAPIAuthenticationError,
21 DNSAPIError,
22 )
23
24 if t.TYPE_CHECKING:
25 from collections.abc import Collection # pragma: no cover
26
27 from ._http import HTTPHelper, HTTPMethod # pragma: no cover
28
29 class _RequestKwarg(t.TypedDict): # pragma: no cover
30 method: t.NotRequired[HTTPMethod] # pragma: no cover
31 headers: t.NotRequired[dict[str, str] | None] # pragma: no cover
32 data: t.NotRequired[bytes | None] # pragma: no cover
33 timeout: t.NotRequired[int | None] # pragma: no cover
34
35
36 ERROR_CODES: dict[int, str] = {
37 200: "Successful response",
38 401: "Unauthorized",
39 403: "Forbidden",
40 404: "Not found",
41 406: "Not acceptable",
42 409: "Conflict",
43 422: "Unprocessable entity",
44 500: "Internal Server Error",
45 }
46 UNKNOWN_ERROR = "Unknown Error"
47
48
49 def _get_header_value(
50 info: dict[str, t.Any],
51 header_name: str,
52 ) -> str | None:
53 header_name = header_name.lower()
54 header_value = info.get(header_name)
55 for k, v in info.items():
56 if k.lower() == header_name:
57 header_value = v
58 return header_value
59
60
61 class JSONAPIHelper:
62 def __init__(
63 self,
64 http_helper: HTTPHelper,
65 token: str,
66 api: str,
67 debug: bool = False,
68 ) -> None:
69 """
70 Create a new JSON API helper instance with given API key.
71 """
72 self._api = api
73 self._http_helper = http_helper
74 self._token = token
75 self._debug = debug
76
77 def _build_url(
78 self,
79 url: str,
80 query: dict[str, str] | Sequence[tuple[str, str]] | None = None,
81 ) -> str:
82 return f"{self._api}{url}{'?' + urlencode(query) if query else ''}"
83
84 def _extract_error_message(
85 self,
86 result: t.Any | None,
87 ) -> str:
88 if result is None:
89 return ""
90 return f" with data: {result!r}"
91
92 def _validate(
93 self,
94 *,
95 result: t.Any | None = None,
96 info: dict[str, t.Any],
97 expected: Collection[int] | None = None,
98 method: HTTPMethod = "GET",
99 ) -> None:
100 status = info["status"]
101 url = info.get("url") # not present when using open_url
102 # Check expected status
103 error_code = ERROR_CODES.get(status, UNKNOWN_ERROR)
104 if expected is not None:
105 if status not in expected:
106 more = self._extract_error_message(result)
107 statuses = ", ".join([f"{e}" for e in expected])
108 raise DNSAPIError(
109 f"Expected HTTP status {statuses} for {method} {url}, but got HTTP status {status} ({error_code}){more}"
110 )
111 else:
112 if status < 200 or status >= 300:
113 more = self._extract_error_message(result)
114 raise DNSAPIError(
115 f"Expected successful HTTP status for {method} {url}, but got HTTP status {status} ({error_code}){more}"
116 )
117
118 def _process_json_result(
119 self,
120 content: bytes | None,
121 info: dict[str, t.Any],
122 *,
123 must_have_content: bool | Sequence[int] = True,
124 method: HTTPMethod = "GET",
125 expected: Collection[int] | None = None,
126 require_json_object: bool = False,
127 ) -> tuple[dict[str, t.Any] | list[t.Any] | None, dict[str, t.Any]]:
128 if isinstance(must_have_content, Sequence):
129 must_have_content = info["status"] in must_have_content
130 # Check for unauthenticated
131 if info["status"] == 401:
132 message = "Unauthorized: the authentication parameters are incorrect (HTTP status 401)"
133 try:
134 body = json.loads(content.decode("utf8")) # type: ignore
135 if body["message"]:
136 message = f"{message}: {body['message']}"
137 except Exception:
138 pass
139 raise DNSAPIAuthenticationError(message)
140 if info["status"] == 403:
141 message = (
142 "Forbidden: you do not have access to this resource (HTTP status 403)"
143 )
144 try:
145 body = json.loads(content.decode("utf8")) # type: ignore
146 if body["message"]:
147 message = f"{message}: {body['message']}"
148 except Exception:
149 pass
150 raise DNSAPIAuthenticationError(message)
151 # Check Content-Type header
152 content_type = _get_header_value(info, "content-type")
153 if content_type != "application/json" and (
154 content_type is None or not content_type.startswith("application/json;")
155 ):
156 if must_have_content:
157 raise DNSAPIError(
158 f"{method} {info['url']} did not yield JSON data, but HTTP status code {info['status']}"
159 f" with Content-Type {content_type!r} and data: {to_native(content)}"
160 )
161 self._validate(result=content, info=info, expected=expected, method=method)
162 return None, info
163 # Decode content as JSON
164 try:
165 result = json.loads(content.decode("utf8")) # type: ignore
166 except Exception as exc:
167 # TODO: This looks like a bug; decoding errors are not "empty"!
168 if must_have_content:
169 raise DNSAPIError(
170 f"{method} {info['url']} did not yield JSON data, but HTTP status code {info['status']} with data: {to_native(content)}"
171 ) from exc
172 self._validate(result=content, info=info, expected=expected, method=method)
173 return None, info
174 if not isinstance(result, dict):
175 if require_json_object:
176 raise DNSAPIError(
177 f"{method} {info['url']} did not yield a JSON object, but {type(result)}"
178 )
179 if not isinstance(result, list):
180 raise DNSAPIError(
181 f"{method} {info['url']} did not yield a JSON object or a JSON array, but {type(result)}"
182 )
183 self._validate(result=result, info=info, expected=expected, method=method)
184 return result, info
185
186 def _is_rate_limiting_result(
187 self, content: bytes | None, info: dict[str, t.Any]
188 ) -> bool | int | float:
189 if info["status"] != 429:
190 return False
191 try:
192 hv = _get_header_value(info, "retry-after")
193 if hv is None:
194 raise TypeError
195 return max(min(float(hv), 60), 1)
196 except (ValueError, TypeError):
197 return 10
198
199 def _should_retry(self, content: bytes | None, info: dict[str, t.Any]) -> bool:
200 return info["status"] in (-1, 502, 503, 504)
201
202 def _request(
203 self, url: str, **kwargs: t.Unpack[_RequestKwarg]
204 ) -> tuple[bytes | None, dict[str, t.Any]]:
205 """Execute a HTTP request and handle common things like rate limiting."""
206 number_retries = 10
207 countdown = number_retries + 1
208 cause = ""
209 while True:
210 content, info = self._http_helper.fetch_url(url, **kwargs)
211 countdown -= 1
212 retry_wait = None
213 if self._should_retry(content, info):
214 retry_wait = 0.5
215 cause = (
216 "a local HTTP request error"
217 if info["status"] == -1
218 else f"HTTP status {info['status']}"
219 )
220 else:
221 retry_after = self._is_rate_limiting_result(content, info)
222 if retry_after is not False:
223 cause = "429 Too Many Attempts"
224 retry_wait = 10 if retry_after is True else retry_after
225 if retry_wait is not None:
226 if countdown <= 0:
227 break
228 time.sleep(retry_wait)
229 continue
230 return content, info
231 raise DNSAPIError(
232 f"Stopping after {number_retries} failed retries with {cause}"
233 )
234
235 def _create_headers(self) -> dict[str, str]:
236 return {
237 "accept": "application/json",
238 }
239
240 def _create_post_headers(self) -> dict[str, str]:
241 return self._create_headers()
242
243 def _create_put_headers(self) -> dict[str, str]:
244 return self._create_headers()
245
246 @t.overload
247 def _get(
248 self,
249 url: str,
250 *,
251 query: dict[str, str] | Sequence[tuple[str, str]] | None = None,
252 must_have_content: t.Literal[True] = True,
253 expected: Collection[int] | None = None,
254 require_json_object: t.Literal[True],
255 ) -> tuple[dict[str, t.Any], dict[str, t.Any]]: ...
256
257 @t.overload
258 def _get(
259 self,
260 url: str,
261 *,
262 query: dict[str, str] | Sequence[tuple[str, str]] | None = None,
263 must_have_content: t.Literal[True] = True,
264 expected: Collection[int] | None = None,
265 require_json_object: bool = False,
266 ) -> tuple[dict[str, t.Any] | list[t.Any], dict[str, t.Any]]: ...
267
268 @t.overload
269 def _get(
270 self,
271 url: str,
272 *,
273 query: dict[str, str] | Sequence[tuple[str, str]] | None = None,
274 must_have_content: bool | Sequence[int] = True,
275 expected: Collection[int] | None = None,
276 require_json_object: t.Literal[True],
277 ) -> tuple[dict[str, t.Any] | None, dict[str, t.Any]]: ...
278
279 @t.overload
280 def _get(
281 self,
282 url: str,
283 *,
284 query: dict[str, str] | Sequence[tuple[str, str]] | None = None,
285 must_have_content: bool | Sequence[int] = True,
286 expected: Collection[int] | None = None,
287 require_json_object: bool = False,
288 ) -> tuple[dict[str, t.Any] | list[t.Any] | None, dict[str, t.Any]]: ...
289
290 def _get(
291 self,
292 url: str,
293 *,
294 query: dict[str, str] | Sequence[tuple[str, str]] | None = None,
295 must_have_content: bool | Sequence[int] = True,
296 expected: Collection[int] | None = None,
297 require_json_object: bool = False,
298 ) -> tuple[dict[str, t.Any] | list[t.Any] | None, dict[str, t.Any]]:
299 full_url = self._build_url(url, query)
300 if self._debug:
301 pass # pragma: no cover
302 # q.q('Request: GET {0}'.format(full_url))
303 headers = self._create_headers()
304 content, info = self._request(full_url, headers=headers, method="GET")
305 return self._process_json_result(
306 content,
307 info,
308 must_have_content=must_have_content,
309 method="GET",
310 expected=expected,
311 require_json_object=require_json_object,
312 )
313
314 @t.overload
315 def _post(
316 self,
317 url: str,
318 *,
319 data: dict[str, t.Any] | None = None,
320 query: dict[str, str] | Sequence[tuple[str, str]] | None = None,
321 must_have_content: t.Literal[True] = True,
322 expected: Collection[int] | None = None,
323 require_json_object: t.Literal[True],
324 ) -> tuple[dict[str, t.Any], dict[str, t.Any]]: ...
325
326 @t.overload
327 def _post(
328 self,
329 url: str,
330 *,
331 data: dict[str, t.Any] | None = None,
332 query: dict[str, str] | Sequence[tuple[str, str]] | None = None,
333 must_have_content: t.Literal[True] = True,
334 expected: Collection[int] | None = None,
335 require_json_object: bool = False,
336 ) -> tuple[dict[str, t.Any] | list[t.Any], dict[str, t.Any]]: ...
337
338 @t.overload
339 def _post(
340 self,
341 url: str,
342 *,
343 data: dict[str, t.Any] | None = None,
344 query: dict[str, str] | Sequence[tuple[str, str]] | None = None,
345 must_have_content: bool | Sequence[int] = True,
346 expected: Collection[int] | None = None,
347 require_json_object: t.Literal[True],
348 ) -> tuple[dict[str, t.Any] | None, dict[str, t.Any]]: ...
349
350 @t.overload
351 def _post(
352 self,
353 url: str,
354 *,
355 data: dict[str, t.Any] | None = None,
356 query: dict[str, str] | Sequence[tuple[str, str]] | None = None,
357 must_have_content: bool | Sequence[int] = True,
358 expected: Collection[int] | None = None,
359 require_json_object: bool = False,
360 ) -> tuple[dict[str, t.Any] | list[t.Any] | None, dict[str, t.Any]]: ...
361
362 def _post(
363 self,
364 url: str,
365 *,
366 data: dict[str, t.Any] | None = None,
367 query: dict[str, str] | Sequence[tuple[str, str]] | None = None,
368 must_have_content: bool | Sequence[int] = True,
369 expected: Collection[int] | None = None,
370 require_json_object: bool = False,
371 ) -> tuple[dict[str, t.Any] | list[t.Any] | None, dict[str, t.Any]]:
372 full_url = self._build_url(url, query)
373 if self._debug:
374 pass # pragma: no cover
375 # q.q('Request: POST {0}'.format(full_url))
376 headers = self._create_post_headers()
377 encoded_data = None
378 if data is not None:
379 headers["content-type"] = "application/json"
380 encoded_data = json.dumps(data).encode("utf-8")
381 content, info = self._request(
382 full_url, headers=headers, method="POST", data=encoded_data
383 )
384 return self._process_json_result(
385 content,
386 info,
387 must_have_content=must_have_content,
388 method="POST",
389 expected=expected,
390 require_json_object=require_json_object,
391 )
392
393 @t.overload
394 def _put(
395 self,
396 url: str,
397 *,
398 data: dict[str, t.Any] | None = None,
399 query: dict[str, str] | Sequence[tuple[str, str]] | None = None,
400 must_have_content: t.Literal[True] = True,
401 expected: Collection[int] | None = None,
402 require_json_object: t.Literal[True],
403 ) -> tuple[dict[str, t.Any], dict[str, t.Any]]: ...
404
405 @t.overload
406 def _put(
407 self,
408 url: str,
409 *,
410 data: dict[str, t.Any] | None = None,
411 query: dict[str, str] | Sequence[tuple[str, str]] | None = None,
412 must_have_content: t.Literal[True] = True,
413 expected: Collection[int] | None = None,
414 require_json_object: bool = False,
415 ) -> tuple[dict[str, t.Any] | list[t.Any], dict[str, t.Any]]: ...
416
417 @t.overload
418 def _put(
419 self,
420 url: str,
421 *,
422 data: dict[str, t.Any] | None = None,
423 query: dict[str, str] | Sequence[tuple[str, str]] | None = None,
424 must_have_content: bool | Sequence[int] = True,
425 expected: Collection[int] | None = None,
426 require_json_object: t.Literal[True],
427 ) -> tuple[dict[str, t.Any] | None, dict[str, t.Any]]: ...
428
429 @t.overload
430 def _put(
431 self,
432 url: str,
433 *,
434 data: dict[str, t.Any] | None = None,
435 query: dict[str, str] | Sequence[tuple[str, str]] | None = None,
436 must_have_content: bool | Sequence[int] = True,
437 expected: Collection[int] | None = None,
438 require_json_object: bool = False,
439 ) -> tuple[dict[str, t.Any] | list[t.Any] | None, dict[str, t.Any]]: ...
440
441 def _put(
442 self,
443 url: str,
444 *,
445 data: dict[str, t.Any] | None = None,
446 query: dict[str, str] | Sequence[tuple[str, str]] | None = None,
447 must_have_content: bool | Sequence[int] = True,
448 expected: Collection[int] | None = None,
449 require_json_object: bool = False,
450 ) -> tuple[dict[str, t.Any] | list[t.Any] | None, dict[str, t.Any]]:
451 full_url = self._build_url(url, query)
452 if self._debug:
453 pass # pragma: no cover
454 # q.q('Request: PUT {0}'.format(full_url))
455 headers = self._create_put_headers()
456 encoded_data = None
457 if data is not None:
458 headers["content-type"] = "application/json"
459 encoded_data = json.dumps(data).encode("utf-8")
460 content, info = self._request(
461 full_url, headers=headers, method="PUT", data=encoded_data
462 )
463 return self._process_json_result(
464 content,
465 info,
466 must_have_content=must_have_content,
467 method="PUT",
468 expected=expected,
469 require_json_object=require_json_object,
470 )
471
472 @t.overload
473 def _delete(
474 self,
475 url: str,
476 *,
477 query: dict[str, str] | Sequence[tuple[str, str]] | None = None,
478 must_have_content: t.Literal[True] = True,
479 expected: Collection[int] | None = None,
480 require_json_object: t.Literal[True],
481 ) -> tuple[dict[str, t.Any], dict[str, t.Any]]: ...
482
483 @t.overload
484 def _delete(
485 self,
486 url: str,
487 *,
488 query: dict[str, str] | Sequence[tuple[str, str]] | None = None,
489 must_have_content: t.Literal[True] = True,
490 expected: Collection[int] | None = None,
491 require_json_object: bool = False,
492 ) -> tuple[dict[str, t.Any] | list[t.Any], dict[str, t.Any]]: ...
493
494 @t.overload
495 def _delete(
496 self,
497 url: str,
498 *,
499 query: dict[str, str] | Sequence[tuple[str, str]] | None = None,
500 must_have_content: bool | Sequence[int] = True,
501 expected: Collection[int] | None = None,
502 require_json_object: t.Literal[True],
503 ) -> tuple[dict[str, t.Any] | None, dict[str, t.Any]]: ...
504
505 @t.overload
506 def _delete(
507 self,
508 url: str,
509 *,
510 query: dict[str, str] | Sequence[tuple[str, str]] | None = None,
511 must_have_content: bool | Sequence[int] = True,
512 expected: Collection[int] | None = None,
513 require_json_object: bool = False,
514 ) -> tuple[dict[str, t.Any] | list[t.Any] | None, dict[str, t.Any]]: ...
515
516 def _delete(
517 self,
518 url: str,
519 *,
520 query: dict[str, str] | Sequence[tuple[str, str]] | None = None,
521 must_have_content: bool | Sequence[int] = True,
522 expected: Collection[int] | None = None,
523 require_json_object: bool = False,
524 ) -> tuple[dict[str, t.Any] | list[t.Any] | None, dict[str, t.Any]]:
525 full_url = self._build_url(url, query)
526 if self._debug:
527 pass # pragma: no cover
528 # q.q('Request: DELETE {0}'.format(full_url))
529 headers = self._create_headers()
530 content, info = self._request(full_url, headers=headers, method="DELETE")
531 return self._process_json_result(
532 content,
533 info,
534 must_have_content=must_have_content,
535 method="DELETE",
536 expected=expected,
537 require_json_object=require_json_object,
538 )