Debian Codegraph @

ansible_collections/community/dns/plugins/module_utils/_hosttech/json_api.py

raw
1 # Copyright (c) 2017-2021 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 # The API documentation can be found here: https://api.ns1.hosttech.eu/api/documentation/
9
10 from __future__ import annotations
11
12 import typing as t
13
14 from ansible_collections.community.dns.plugins.module_utils._json_api_helper import (
15 JSONAPIHelper,
16 )
17 from ansible_collections.community.dns.plugins.module_utils._record import DNSRecord
18 from ansible_collections.community.dns.plugins.module_utils._zone import (
19 DNSZone,
20 DNSZoneWithRecords,
21 )
22 from ansible_collections.community.dns.plugins.module_utils._zone_record_api import (
23 NOT_PROVIDED,
24 DNSAPIError,
25 ZoneRecordAPI,
26 filter_records,
27 )
28
29 if t.TYPE_CHECKING:
30 from collections.abc import Sequence # pragma: no cover
31
32 from .._http import HTTPHelper # pragma: no cover
33 from .._record import IDNSRecord # pragma: no cover
34 from .._zone_record_api import NotProvidedType # pragma: no cover
35
36
37 def _create_record_from_json(
38 source: dict[str, t.Any], record_type: str | None = None
39 ) -> DNSRecord[int]:
40 source = dict(source)
41 record_type = source.pop("type", record_type)
42 if record_type is None:
43 raise DNSAPIError("Record from API has no type")
44
45 name: str | None = source.pop("name", None)
46 target: str
47 if record_type == "A":
48 target = source.pop("ipv4")
49 elif record_type == "AAAA":
50 target = source.pop("ipv6")
51 elif record_type == "CAA":
52 target = f"{source.pop('flag')} {source.pop('tag')} \"{source.pop('value')}\""
53 elif record_type == "CNAME":
54 target = source.pop("cname")
55 elif record_type == "MX":
56 mx_name, name = name, source.pop("ownername")
57 target = f"{source.pop('pref')} {mx_name}"
58 elif record_type == "NS":
59 name = source.pop("ownername")
60 target = source.pop("targetname")
61 elif record_type == "PTR":
62 ptr_name, name = name, ""
63 target = f"{source.pop('origin')} {ptr_name}"
64 elif record_type == "SRV":
65 name = source.pop("service")
66 target = f"{source.pop('priority')} {source.pop('weight')} {source.pop('port')} {source.pop('target')}"
67 elif record_type in ("TXT", "TLSA"):
68 target = source.pop("text")
69 else:
70 raise DNSAPIError(f"Cannot parse unknown record type: {record_type}")
71
72 result = DNSRecord(
73 record_id=source.pop("id"), record_type=record_type, target=target
74 )
75 ttl = source.pop("ttl")
76 result.ttl = int(ttl) if ttl is not None else None
77 result.extra["comment"] = source.pop("comment")
78 result.prefix = name or None # API returns '', we want None
79 result.extra.update(source)
80 return result
81
82
83 def _create_zone_from_json(source: dict[str, t.Any]) -> DNSZone[int]:
84 zone = DNSZone(zone_id=source["id"], name=source["name"])
85 zone.info = {
86 "dnssec": source["dnssec"],
87 "dnssec_email": source.get("dnssec_email"),
88 "ds_records": source.get("ds_records"),
89 "email": source.get("email"),
90 "ttl": source["ttl"],
91 }
92 return zone
93
94
95 def _create_zone_with_records_from_json(
96 source: dict[str, t.Any],
97 prefix: str | None | NotProvidedType = NOT_PROVIDED,
98 record_type: str | NotProvidedType = NOT_PROVIDED,
99 ) -> DNSZoneWithRecords[int, int]:
100 return DNSZoneWithRecords(
101 _create_zone_from_json(source),
102 filter_records(
103 [_create_record_from_json(record) for record in source["records"]],
104 prefix=prefix,
105 record_type=record_type,
106 ),
107 )
108
109
110 def _record_to_json(
111 record: IDNSRecord[int | None], include_id: bool = False, include_type: bool = True
112 ) -> dict[str, t.Any]:
113 result: dict[str, t.Any] = {
114 "ttl": record.ttl,
115 "comment": record.extra.get("comment") or "",
116 }
117 if include_type:
118 result["type"] = record.type
119 if include_id:
120 result["id"] = record.id
121
122 if record.type == "A":
123 result["name"] = record.prefix or ""
124 result["ipv4"] = record.target
125 elif record.type == "AAAA":
126 result["name"] = record.prefix or ""
127 result["ipv6"] = record.target
128 elif record.type == "CAA":
129 result["name"] = record.prefix or ""
130 try:
131 flag, tag, value = record.target.split(" ", 2)
132 if value.startswith('"') and value.endswith('"'):
133 value = value[1:-1]
134 result["flag"] = flag
135 result["tag"] = tag
136 result["value"] = value
137 except Exception as e:
138 raise DNSAPIError(
139 f'Cannot split {record.type} record "{record.target}" into flag, tag and value: {e}'
140 ) from e
141 elif record.type == "CNAME":
142 result["name"] = record.prefix or ""
143 result["cname"] = record.target
144 elif record.type == "MX":
145 result["ownername"] = record.prefix or ""
146 try:
147 pref, name = record.target.split(" ", 1)
148 result["pref"] = int(pref)
149 result["name"] = name
150 except Exception as e:
151 raise DNSAPIError(
152 f'Cannot split {record.type} record "{record.target}" into integer preference and name: {e}'
153 ) from e
154 elif record.type == "NS":
155 result["ownername"] = record.prefix or ""
156 result["targetname"] = record.target
157 elif record.type == "PTR":
158 try:
159 origin, name = record.target.split(" ", 1)
160 result["origin"] = origin
161 result["name"] = name
162 except Exception as e:
163 raise DNSAPIError(
164 f'Cannot split {record.type} record "{record.target}" into origin and name: {e}'
165 ) from e
166 elif record.type == "SRV":
167 result["service"] = record.prefix or ""
168 try:
169 priority, weight, port, target = record.target.split(" ", 3)
170 result["priority"] = int(priority)
171 result["weight"] = int(weight)
172 result["port"] = int(port)
173 result["target"] = target
174 except Exception as e:
175 raise DNSAPIError(
176 f'Cannot split {record.type} record "{record.target}" into integer priority, integer weight, integer port and target: {e}'
177 ) from e
178 elif record.type in ("TXT", "TLSA"):
179 result["name"] = record.prefix or ""
180 result["text"] = record.target
181 else:
182 raise DNSAPIError(f"Cannot serialize unknown record type: {record.type}")
183
184 return result
185
186
187 def _pagination_query(
188 query: dict[str, str] | Sequence[tuple[str, str]] | None,
189 *,
190 block_size: int,
191 offset: int,
192 ) -> dict[str, str] | Sequence[tuple[str, str]]:
193 if isinstance(query, dict):
194 query_map = query.copy()
195 query_map["limit"] = str(block_size)
196 query_map["offset"] = str(offset)
197 return query_map
198 query_list = list(query) if query else []
199 query_list.append(("limit", str(block_size)))
200 query_list.append(("offset", str(offset)))
201 return query_list
202
203
204 class HostTechJSONAPI(ZoneRecordAPI[int, int], JSONAPIHelper):
205 def __init__(
206 self,
207 http_helper: HTTPHelper,
208 token: str,
209 api="https://api.ns1.hosttech.eu/api/",
210 debug: bool = False,
211 ) -> None:
212 """
213 Create a new HostTech API instance with given API token.
214 """
215 JSONAPIHelper.__init__(self, http_helper, token, api=api, debug=debug)
216
217 def _extract_error_message(self, result: t.Any | None) -> str:
218 if result is None:
219 return ""
220 if isinstance(result, dict):
221 res = ""
222 if result.get("message"):
223 res = f"{res} with message \"{result['message']}\""
224 if "errors" in result and isinstance(result["errors"], dict):
225 for k, v in sorted(result["errors"].items()):
226 if isinstance(v, list):
227 v = "; ".join(v)
228 res = f'{res} (field "{k}": {v})'
229 if res:
230 return res
231 return f" with data: {result}"
232
233 def _create_headers(self) -> dict[str, str]:
234 return {
235 "accept": "application/json",
236 "authorization": f"Bearer {self._token}",
237 }
238
239 def _list_pagination(
240 self,
241 url: str,
242 query: dict[str, str] | Sequence[tuple[str, str]] | None = None,
243 block_size: int = 100,
244 ) -> list[t.Any]:
245 result = []
246 offset = 0
247 while True:
248 query_ = _pagination_query(query, block_size=block_size, offset=offset)
249 res, dummy = self._get(
250 url,
251 query=query_,
252 must_have_content=True,
253 expected=[200],
254 require_json_object=True,
255 )
256 result.extend(res["data"])
257 if len(res["data"]) < block_size:
258 return result
259 offset += block_size
260
261 def get_zone_with_records_by_id(
262 self,
263 zone_id: int,
264 prefix: str | None | NotProvidedType = NOT_PROVIDED,
265 record_type: str | NotProvidedType = NOT_PROVIDED,
266 ) -> DNSZoneWithRecords[int, int] | None:
267 """
268 Given a zone ID, return the zone contents with records if found.
269
270 @param zone_id: The zone ID
271 @param prefix: The prefix to filter for, if provided. Since None is a valid value,
272 the special constant NOT_PROVIDED indicates that we are not filtering.
273 @param record_type: The record type to filter for, if provided
274 @return The zone information with records (DNSZoneWithRecords), or None if not found
275 """
276 result, info = self._get(
277 f"user/v1/zones/{zone_id}",
278 expected=[200, 404],
279 must_have_content=[200],
280 require_json_object=True,
281 )
282 if info["status"] == 404 or result is None:
283 return None
284 return _create_zone_with_records_from_json(
285 result["data"], prefix=prefix, record_type=record_type
286 )
287
288 def get_zone_with_records_by_name(
289 self,
290 name: str,
291 prefix: str | None | NotProvidedType = NOT_PROVIDED,
292 record_type: str | NotProvidedType = NOT_PROVIDED,
293 ) -> DNSZoneWithRecords[int, int] | None:
294 """
295 Given a zone name, return the zone contents with records if found.
296
297 @param name: The zone name (string)
298 @param prefix: The prefix to filter for, if provided. Since None is a valid value,
299 the special constant NOT_PROVIDED indicates that we are not filtering.
300 @param record_type: The record type to filter for, if provided
301 @return The zone information with records (DNSZoneWithRecords), or None if not found
302 """
303 result = self._list_pagination("user/v1/zones", query={"query": name})
304 for zone in result:
305 if zone["name"] == name:
306 zone_result, dummy = self._get(
307 f"user/v1/zones/{zone['id']}",
308 expected=[200],
309 require_json_object=True,
310 )
311 return _create_zone_with_records_from_json(
312 zone_result["data"], prefix=prefix, record_type=record_type
313 )
314 return None
315
316 def get_zone_records(
317 self,
318 zone_id: int,
319 prefix: str | None | NotProvidedType = NOT_PROVIDED,
320 record_type: str | NotProvidedType = NOT_PROVIDED,
321 ) -> list[DNSRecord[int]] | None:
322 """
323 Given a zone ID, return a list of records, optionally filtered by the provided criteria.
324
325 @param zone_id: The zone ID
326 @param prefix: The prefix to filter for, if provided. Since None is a valid value,
327 the special constant NOT_PROVIDED indicates that we are not filtering.
328 @param record_type: The record type to filter for, if provided
329 @return A list of DNSrecord objects, or None if zone was not found
330 """
331 query: dict[str, str] = {}
332 if record_type is not NOT_PROVIDED:
333 query["type"] = record_type.upper() # type: ignore # Is a string
334 result, info = self._get(
335 f"user/v1/zones/{zone_id}/records",
336 query=query,
337 expected=[200, 404],
338 must_have_content=[200],
339 require_json_object=True,
340 )
341 if info["status"] == 404 or result is None:
342 return None
343 return filter_records(
344 [_create_record_from_json(record) for record in result["data"]],
345 prefix=prefix,
346 record_type=record_type,
347 )
348
349 def get_zone_by_name(self, name: str) -> DNSZone[int] | None:
350 """
351 Given a zone name, return the zone contents if found.
352
353 @param name: The zone name (string)
354 @return The zone information (DNSZone), or None if not found
355 """
356 result = self._list_pagination("user/v1/zones", query={"query": name})
357 for zone in result:
358 if zone["name"] == name:
359 # We cannot simply return `_create_zone_from_json(zone)`, since this contains less information!
360 return self.get_zone_by_id(zone["id"])
361 return None
362
363 def get_zone_by_id(self, zone_id: int) -> DNSZone[int] | None:
364 """
365 Given a zone ID, return the zone contents if found.
366
367 @param zone_id: The zone ID
368 @return The zone information (DNSZone), or None if not found
369 """
370 result, info = self._get(
371 f"user/v1/zones/{zone_id}",
372 expected=[200, 404],
373 must_have_content=[200],
374 require_json_object=True,
375 )
376 if info["status"] == 404 or result is None:
377 return None
378 return _create_zone_from_json(result["data"])
379
380 def add_record(
381 self, zone_id: int, record: IDNSRecord[int | None]
382 ) -> DNSRecord[int]:
383 """
384 Adds a new record to an existing zone.
385
386 @param zone_id: The zone ID
387 @param record: The DNS record (DNSRecord)
388 @return The created DNS record (DNSRecord)
389 """
390 data = _record_to_json(record, include_id=False, include_type=True)
391 result, dummy = self._post(
392 f"user/v1/zones/{zone_id}/records",
393 data=data,
394 expected=[201],
395 require_json_object=True,
396 )
397 return _create_record_from_json(result["data"])
398
399 def update_record(self, zone_id: int, record: DNSRecord[int]) -> DNSRecord[int]:
400 """
401 Update a record.
402
403 @param zone_id: The zone ID
404 @param record: The DNS record (DNSRecord)
405 @return The DNS record (DNSRecord)
406 """
407 if record.id is None:
408 raise DNSAPIError("Need record ID to update record!")
409 data = _record_to_json(record, include_id=False, include_type=False)
410 result, dummy = self._put(
411 f"user/v1/zones/{zone_id}/records/{record.id}",
412 data=data,
413 expected=[200],
414 require_json_object=True,
415 )
416 return _create_record_from_json(result["data"])
417
418 def delete_record(self, zone_id: int, record: DNSRecord[int]) -> bool:
419 """
420 Delete a record.
421
422 @param zone_id: The zone ID
423 @param record: The DNS record (DNSRecord)
424 @return True in case of success (boolean)
425 """
426 if record.id is None:
427 raise DNSAPIError("Need record ID to delete record!")
428 dummy, info = self._delete(
429 f"user/v1/zones/{zone_id}/records/{record.id}",
430 must_have_content=False,
431 expected=[204, 404],
432 require_json_object=True,
433 )
434 return info["status"] == 204