Debian Codegraph @

ansible_collections/community/crypto/plugins/module_utils/_acme/errors.py

raw
1 # Copyright (c) 2016 Michael Gruener <[email protected]>
2 # Copyright (c) 2021 Felix Fontein <[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 typing as t
12 from http.client import responses as http_responses
13
14 from ansible.module_utils.common.text.converters import to_text
15
16 if t.TYPE_CHECKING:
17 import http.client # pragma: no cover
18 import urllib.error # pragma: no cover
19
20 from ansible.module_utils.basic import AnsibleModule # pragma: no cover
21
22
23 def format_http_status(status_code: int) -> str:
24 expl = http_responses.get(status_code)
25 if not expl:
26 return str(status_code)
27 return f"{status_code} {expl}"
28
29
30 def format_error_problem(
31 problem: dict[str, t.Any], *, subproblem_prefix: str = ""
32 ) -> str:
33 error_type = problem.get(
34 "type", "about:blank"
35 ) # https://www.rfc-editor.org/rfc/rfc7807#section-3.1
36 if "title" in problem:
37 msg = f'Error "{problem["title"]}" ({error_type})'
38 else:
39 msg = f"Error {error_type}"
40 if "detail" in problem:
41 msg += f': "{problem["detail"]}"'
42 subproblems = problem.get("subproblems")
43 if subproblems is not None:
44 msg = f"{msg} Subproblems:"
45 for index, subproblem in enumerate(subproblems):
46 index_str = f"{subproblem_prefix}{index}"
47 subproblem_str = format_error_problem(
48 subproblem, subproblem_prefix=f"{index_str}."
49 )
50 msg = f"{msg}\n({index_str}) {subproblem_str}"
51 return msg
52
53
54 class ModuleFailException(Exception):
55 """
56 If raised, module.fail_json() will be called with the given parameters after cleanup.
57 """
58
59 def __init__(self, msg: str, **args: t.Any) -> None:
60 super().__init__(self, msg)
61 self.msg = msg
62 self.module_fail_args = args
63
64 def do_fail(self, *, module: AnsibleModule, **arguments: t.Any) -> t.NoReturn:
65 module.fail_json(msg=self.msg, other=self.module_fail_args, **arguments)
66
67
68 class ACMEProtocolException(ModuleFailException):
69 def __init__(
70 self,
71 *,
72 module: AnsibleModule,
73 msg: str | None = None,
74 info: dict[str, t.Any] | None = None,
75 response: urllib.error.HTTPError | http.client.HTTPResponse | None = None,
76 content: bytes | None = None,
77 content_json: object | bytes | None = None,
78 extras: dict[str, t.Any] | None = None,
79 ) -> None:
80 # Try to get hold of content, if response is given and content is not provided
81 if content is None and content_json is None and response is not None:
82 try:
83 # In Python 2, reading from a closed response yields a TypeError.
84 # In Python 3, read() simply returns ''
85 if response.closed:
86 raise TypeError
87 content = response.read()
88 except (AttributeError, TypeError):
89 if info is not None:
90 content = info.pop("body", None)
91
92 # Make sure that content_json is None or a dictionary
93 content_json_json: dict[str, t.Any] | None = None
94 if content_json is not None and not isinstance(content_json, dict):
95 if content is None and isinstance(content_json, bytes):
96 content = content_json
97 content_json = None
98 elif content_json is not None:
99 content_json_json = content_json.copy()
100
101 # Try to get hold of JSON decoded content, when content is given and JSON not provided
102 if content_json_json is None and content is not None and module is not None:
103 try:
104 cjj = module.from_json(to_text(content))
105 if isinstance(cjj, dict):
106 content_json_json = cjj
107 except Exception:
108 pass
109
110 extras = extras or {}
111 error_code = None
112 error_type = None
113
114 if msg is None:
115 msg = "ACME request failed"
116 add_msg = ""
117
118 if info is not None:
119 url = info["url"]
120 code = info["status"]
121 extras["http_url"] = url
122 extras["http_status"] = code
123 error_code = code
124 if (
125 code is not None
126 and code >= 400
127 and content_json_json is not None
128 and "type" in content_json_json
129 ):
130 error_type = content_json_json["type"]
131 if (
132 "status" in content_json_json
133 and content_json_json["status"] != code
134 ):
135 code_msg = f"status {content_json_json['status']} (HTTP status: {format_http_status(code)})"
136 else:
137 code_msg = f"status {format_http_status(code)}"
138 if code == -1 and info.get("msg"):
139 code_msg = f"error: {info['msg']}"
140 subproblems = content_json_json.pop("subproblems", None)
141 add_msg = f" {format_error_problem(content_json_json)}."
142 extras["problem"] = content_json_json
143 extras["subproblems"] = subproblems or []
144 if subproblems is not None:
145 add_msg = f"{add_msg} Subproblems:"
146 for index, problem in enumerate(subproblems):
147 problem = format_error_problem(
148 problem, subproblem_prefix=f"{index}."
149 )
150 add_msg = f"{add_msg}\n({index}) {problem}."
151 else:
152 code_msg = f"HTTP status {format_http_status(code)}"
153 if code == -1 and info.get("msg"):
154 code_msg = f"error: {info['msg']}"
155 if content_json_json is not None:
156 add_msg = f" The JSON error result: {content_json_json}"
157 elif content is not None:
158 add_msg = f" The raw error result: {to_text(content)}"
159 msg = f"{msg} for {url} with {code_msg}"
160 elif content_json_json is not None:
161 add_msg = f" The JSON result: {content_json_json}"
162 elif content is not None:
163 add_msg = f" The raw result: {to_text(content)}"
164
165 super().__init__(f"{msg}.{add_msg}", **extras)
166 self.problem: dict[str, t.Any] = {}
167 self.subproblems: list[dict[str, t.Any]] = []
168 self.error_code = error_code
169 self.error_type = error_type
170 for k, v in extras.items():
171 setattr(self, k, v)
172
173
174 class BackendException(ModuleFailException):
175 pass
176
177
178 class NetworkException(ModuleFailException):
179 pass
180
181
182 class KeyParsingError(ModuleFailException):
183 pass
184
185
186 __all__ = (
187 "ACMEProtocolException",
188 "BackendException",
189 "KeyParsingError",
190 "ModuleFailException",
191 "NetworkException",
192 "format_error_problem",
193 "format_http_status",
194 )