Debian Codegraph @

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

raw
1 # Copyright (c) 2017-2020 Felix Fontein
2 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # SPDX-License-Identifier: GPL-3.0-or-later
4
5 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
6 # Do not use this from other collections or standalone plugins/modules!
7
8 from __future__ import annotations
9
10 import typing as t
11
12 from ansible.module_utils.common.text.converters import to_native
13
14 try:
15 import lxml.etree
16
17 HAS_LXML_ETREE = True
18 except ImportError:
19 HAS_LXML_ETREE = False
20
21 from ansible_collections.community.dns.plugins.module_utils._http import NetworkError
22
23 if t.TYPE_CHECKING:
24 from collections.abc import Mapping # pragma: no cover
25
26 from ._http import HTTPHelper # pragma: no cover
27
28
29 class WSDLException(Exception):
30 pass
31
32
33 class WSDLNetworkError(WSDLException):
34 pass
35
36
37 class WSDLError(WSDLException):
38 def __init__(self, origin, error_code, message):
39 super().__init__(f"{origin} ({error_code}): {message}")
40 self.error_origin = origin
41 self.error_code = error_code
42 self.error_message = message
43
44
45 class WSDLCodingException(WSDLException):
46 pass
47
48
49 def _split_text_namespace(
50 node: lxml.etree.Element, text: str
51 ) -> tuple[str, str | None]:
52 i = text.find(":")
53 if i < 0:
54 return text, None
55 ns = node.nsmap.get(text[:i])
56 text = text[i + 1 :]
57 return text, ns
58
59
60 _NAMESPACE_ENVELOPE = "http://schemas.xmlsoap.org/soap/envelope/"
61 _NAMESPACE_XSI = "http://www.w3.org/2001/XMLSchema-instance"
62 _NAMESPACE_XSD = "http://www.w3.org/2001/XMLSchema"
63 _NAMESPACE_XML_SOAP = "http://xml.apache.org/xml-soap"
64 _NAMESPACE_XML_SOAP_ENCODING = "http://schemas.xmlsoap.org/soap/encoding/"
65
66
67 def _set_type(
68 node: lxml.etree.Element, type_value: str, namespace: str | None = None
69 ) -> None:
70 tv: lxml.etree.QName | str
71 if namespace is not None:
72 tv = lxml.etree.QName(namespace, type_value)
73 else:
74 tv = type_value
75 node.set(lxml.etree.QName(_NAMESPACE_XSI, "type").text, tv)
76
77
78 def encode_wsdl(node: lxml.etree.Element, value: t.Any) -> None:
79 if value is None:
80 node.set(lxml.etree.QName(_NAMESPACE_XSI, "nil").text, "true")
81 elif isinstance(value, str):
82 _set_type(node, "xsd:string")
83 node.text = value
84 elif isinstance(value, int):
85 _set_type(node, "xsd:int")
86 node.text = str(value)
87 elif isinstance(value, bool):
88 _set_type(node, "xsd:boolean")
89 node.text = "true" if value else "false"
90 elif isinstance(value, dict):
91 _set_type(node, "Map", _NAMESPACE_XML_SOAP)
92 for key, val in sorted(value.items()):
93 child = lxml.etree.Element("item")
94 ke = lxml.etree.Element("key")
95 encode_wsdl(ke, key)
96 child.append(ke)
97 ve = lxml.etree.Element("value")
98 encode_wsdl(ve, val)
99 child.append(ve)
100 node.append(child)
101 elif isinstance(value, list):
102 _set_type(node, "SOAP-ENC:Array")
103 for elt in value:
104 child = lxml.etree.Element("item")
105 encode_wsdl(child, elt)
106 node.append(child)
107 else:
108 raise WSDLCodingException(f"Do not know how to encode {type(value)}!")
109
110
111 def _decode_wsdl_array(
112 result: list[t.Any],
113 node: lxml.etree.Element,
114 root_ns: str | None,
115 ids: dict[str, str],
116 ):
117 for item in node:
118 if item.tag != "item":
119 raise WSDLCodingException(f"Invalid child tag {item.tag!r} in map!")
120 result.append(decode_wsdl(item, root_ns, ids))
121
122
123 def decode_wsdl(
124 node: lxml.etree.Element, root_ns: str | None, ids: dict[str, str]
125 ) -> t.Any:
126 href = node.get("href")
127 nil = node.get(lxml.etree.QName(_NAMESPACE_XSI, "nil"))
128 nid = node.get("id")
129 result: t.Any
130 if href is not None:
131 if not href.startswith("#"):
132 raise WSDLCodingException(f'Global reference "{href}" not supported!')
133 href = href[1:]
134 if href not in ids:
135 raise WSDLCodingException(f'ID "{href}" not yet defined!')
136 result = ids[href]
137 elif nil == "true":
138 result = None
139 else:
140 type_with_ns = node.get(lxml.etree.QName(_NAMESPACE_XSI, "type"))
141 if type_with_ns is None:
142 raise WSDLCodingException(f'Element "{node}" has no "xsi:type" tag!')
143 ntype, ns = _split_text_namespace(node, type_with_ns)
144 if ns is None:
145 raise WSDLCodingException(f'Cannot find namespace for "{type_with_ns}"!')
146 if ns == _NAMESPACE_XSD:
147 if ntype == "boolean":
148 if node.text == "true":
149 result = True
150 elif node.text == "false":
151 result = False
152 else:
153 raise WSDLCodingException(
154 f"Invalid value for boolean: {node.text!r}"
155 )
156 elif ntype == "int":
157 try:
158 if node.text is None:
159 raise TypeError
160 result = int(node.text)
161 except (TypeError, ValueError) as exc:
162 raise WSDLCodingException(
163 f"Invalid value for int: {node.text!r}"
164 ) from exc
165 elif ntype == "string":
166 result = node.text
167 else:
168 raise WSDLCodingException(f'Unknown XSD type "{ntype}"!')
169 elif ns == _NAMESPACE_XML_SOAP:
170 if ntype == "Map":
171 result = {}
172 if nid is not None:
173 ids[nid] = result
174 for item in node:
175 if item.tag != "item":
176 raise WSDLCodingException(
177 f"Invalid child tag {item.tag!r} in map!"
178 )
179 key = item.find("key")
180 if key is None:
181 raise WSDLCodingException(f"Cannot find key for {item!r}!")
182 key = decode_wsdl(key, root_ns, ids)
183 value = item.find("value")
184 if value is None:
185 raise WSDLCodingException(f"Cannot find value for {item!r}!")
186 value = decode_wsdl(value, root_ns, ids)
187 result[key] = value
188 return result
189 raise WSDLCodingException(f'Unknown XSD type "{ntype}"!')
190 elif ns == _NAMESPACE_XML_SOAP_ENCODING:
191 if ntype == "Array":
192 result = []
193 if nid is not None:
194 ids[nid] = result
195 _decode_wsdl_array(result, node, root_ns, ids)
196 else:
197 raise WSDLCodingException(f'Unknown XSD type "{ntype}"!')
198 elif ns == root_ns:
199 array_type = node.get(
200 lxml.etree.QName(_NAMESPACE_XML_SOAP_ENCODING, "arrayType")
201 )
202 if array_type is not None:
203 result = []
204 if nid is not None:
205 ids[nid] = result
206 _decode_wsdl_array(result, node, root_ns, ids)
207 else:
208 result = {}
209 if nid is not None:
210 ids[nid] = result
211 for item in node:
212 result[item.tag] = decode_wsdl(item, root_ns, ids)
213 else:
214 raise WSDLCodingException(
215 f'Unknown type namespace "{ns}" (with type "{ntype}")!'
216 )
217 if nid is not None:
218 ids[nid] = result
219 return result
220
221
222 class Parser:
223 def _parse(
224 self, result: dict[str, t.Any], node: lxml.etree.Element, where: str
225 ) -> None:
226 for child in node:
227 assert isinstance(child.tag, (str, bytes, lxml.etree.QName))
228 tag = lxml.etree.QName(child.tag)
229 if tag.namespace != self._api:
230 raise WSDLCodingException(
231 f'Cannot interpret {where} item of type "{tag}"!'
232 )
233 for res in child.iter("return"):
234 result[tag.localname] = decode_wsdl(res, self._api, {})
235
236 def __init__(self, api: str, root: lxml.etree.Element) -> None:
237 self._main_ns = _NAMESPACE_ENVELOPE
238 self._api = api
239 self._root = root
240 for fault in self._root.iter(lxml.etree.QName(self._main_ns, "Fault").text):
241 fault_code = fault.find("faultcode")
242 fault_code_val = None
243 fault_string = fault.find("faultstring")
244 origin = "server"
245 if fault_code is not None and fault_code.text:
246 code, code_ns = _split_text_namespace(fault, fault_code.text)
247 fault_code_val = code
248 if code_ns == self._main_ns:
249 origin = code.lower()
250 if fault_string is not None and fault_string.text:
251 raise WSDLError(origin, fault_code_val, fault_string.text)
252 raise WSDLError(
253 origin, fault_code_val, lxml.etree.tostring(fault).decode("utf-8")
254 )
255 self._header: dict[str, t.Any] = {}
256 self._body: dict[str, t.Any] = {}
257 for header in self._root.iter(lxml.etree.QName(self._main_ns, "Header").text):
258 self._parse(self._header, header, "header")
259 for body in self._root.iter(lxml.etree.QName(self._main_ns, "Body").text):
260 self._parse(self._body, body, "body")
261
262 def get_header(self, header: str) -> t.Any:
263 return self._header[header]
264
265 def get_result(self, body: str) -> t.Any:
266 return self._body[body]
267
268 def __str__(self) -> str:
269 return f"header={self._header}, body={self._body}"
270
271 def __repr__(self) -> str:
272 return (
273 """<?xml version='1.0' encoding='utf-8'?>"""
274 + "\n"
275 + lxml.etree.tostring(self._root, pretty_print=True).decode("utf-8")
276 )
277
278
279 class Composer:
280 @staticmethod
281 def _create(tag: str, namespace: str | None = None, **kwarg) -> lxml.etree.Element:
282 if namespace:
283 return lxml.etree.Element(lxml.etree.QName(namespace, tag), **kwarg)
284 return lxml.etree.Element(tag, **kwarg)
285
286 def __str__(self) -> str:
287 return (
288 """<?xml version='1.0' encoding='utf-8'?>"""
289 + "\n"
290 + lxml.etree.tostring(self._root, pretty_print=True).decode("utf-8")
291 )
292
293 def _create_envelope(self, tag: str, **kwarg) -> lxml.etree.Element:
294 return self._create(tag, self._main_ns, **kwarg)
295
296 def __init__(
297 self,
298 http_helper: HTTPHelper,
299 api: str,
300 namespaces: Mapping[str, str] | None = None,
301 ) -> None:
302 self._http_helper = http_helper
303 self._main_ns = _NAMESPACE_ENVELOPE
304 self._api = api
305 # Compose basic document
306 all_namespaces = {
307 "SOAP-ENV": _NAMESPACE_ENVELOPE,
308 "xsd": _NAMESPACE_XSD,
309 "xsi": _NAMESPACE_XSI,
310 "ns2": "auth",
311 "SOAP-ENC": _NAMESPACE_XML_SOAP_ENCODING,
312 }
313 if namespaces is not None:
314 all_namespaces.update(namespaces)
315 self._root = self._create_envelope("Envelope", nsmap=all_namespaces)
316 self._root.set(
317 lxml.etree.QName(self._main_ns, "encodingStyle").text,
318 _NAMESPACE_XML_SOAP_ENCODING,
319 )
320 self._header = self._create_envelope("Header")
321 self._root.append(self._header)
322 self._body = self._create_envelope("Body")
323 self._root.append(self._body)
324 self._command: str | None = None
325
326 def add_auth(self, username: str, password: str) -> None:
327 auth = self._create("authenticate", "auth")
328 user = self._create("UserName")
329 user.text = username
330 auth.append(user)
331 pw = self._create("Password")
332 pw.text = password
333 auth.append(pw)
334 self._header.append(auth)
335
336 def add_simple_command(self, command: str, **args) -> None:
337 self._command = command
338 cmd = self._create(command, self._api)
339 for arg, value in args.items():
340 arg_elt = self._create(arg)
341 encode_wsdl(arg_elt, value)
342 cmd.append(arg_elt)
343 self._body.append(cmd)
344
345 def execute(self, debug: bool = False) -> Parser:
346 payload = (
347 b"""<?xml version='1.0' encoding='utf-8'?>"""
348 + b"\n"
349 + lxml.etree.tostring(self._root)
350 + b"\n"
351 )
352 try:
353 headers = {
354 "Content-Type": "text/xml; charset=utf-8",
355 "Content-Length": str(len(payload)),
356 }
357 if self._command:
358 headers["SOAPAction"] = f'"{self._api}#{self._command}"'
359 result, info = self._http_helper.fetch_url(
360 self._api, data=payload, method="POST", timeout=300, headers=headers
361 )
362 code = info["status"]
363 except NetworkError as e:
364 raise WSDLNetworkError(to_native(e)) from e
365 # if debug:
366 # q.q('Result: {0}, content: {1}'.format(code, result.decode('utf-8')))
367 try:
368 node = lxml.etree.fromstring(result or b"")
369 except Exception as exc:
370 raise WSDLError(
371 "server",
372 "",
373 f"Error while parsing WSDL command result: {exc}\nResult:\n{(result or b'').decode('utf-8')}",
374 ) from exc
375 parser = Parser(self._api, node)
376 if code < 200 or code >= 300:
377 raise WSDLError(
378 "server",
379 "",
380 f"Error {code} while executing WSDL command:\n{(result or b'').decode('utf-8')}",
381 )
382 return parser