records.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. import copy
  2. import django.core.exceptions
  3. import dns.name
  4. import dns.zone
  5. from django.core.validators import MinValueValidator
  6. from django.db.models import Q
  7. from django.utils import timezone
  8. from rest_framework import serializers
  9. from rest_framework.settings import api_settings
  10. from rest_framework.validators import UniqueTogetherValidator
  11. from api import settings
  12. from desecapi import models
  13. from desecapi.validators import ExclusionConstraintValidator, ReadOnlyOnUpdateValidator
  14. class ConditionalExistenceModelSerializer(serializers.ModelSerializer):
  15. """
  16. Only considers data with certain condition as existing data.
  17. If the existence condition does not hold, given instances are deleted, and no new instances are created,
  18. respectively. Also, to_representation and data will return None.
  19. Contrary, if the existence condition holds, the behavior is the same as DRF's ModelSerializer.
  20. """
  21. def exists(self, arg):
  22. """
  23. Determine if arg is to be considered existing.
  24. :param arg: Either a model instance or (possibly invalid!) data object.
  25. :return: Whether we treat this as non-existing instance.
  26. """
  27. raise NotImplementedError
  28. def to_representation(self, instance):
  29. return (
  30. None if not self.exists(instance) else super().to_representation(instance)
  31. )
  32. @property
  33. def data(self):
  34. try:
  35. return super().data
  36. except TypeError:
  37. return None
  38. def save(self, **kwargs):
  39. validated_data = {}
  40. validated_data.update(self.validated_data)
  41. validated_data.update(kwargs)
  42. known_instance = self.instance is not None
  43. data_exists = self.exists(validated_data)
  44. if known_instance and data_exists:
  45. self.instance = self.update(self.instance, validated_data)
  46. elif known_instance and not data_exists:
  47. self.delete()
  48. elif not known_instance and data_exists:
  49. self.instance = self.create(validated_data)
  50. elif not known_instance and not data_exists:
  51. pass # nothing to do
  52. return self.instance
  53. def delete(self):
  54. self.instance.delete()
  55. class NonBulkOnlyDefault:
  56. """
  57. This class may be used to provide default values that are only used
  58. for non-bulk operations, but that do not return any value for bulk
  59. operations.
  60. Implementation inspired by CreateOnlyDefault.
  61. """
  62. requires_context = True
  63. def __init__(self, default):
  64. self.default = default
  65. def __call__(self, serializer_field):
  66. is_many = getattr(serializer_field.root, "many", False)
  67. if is_many:
  68. raise serializers.SkipField()
  69. if callable(self.default):
  70. if getattr(self.default, "requires_context", False):
  71. return self.default(serializer_field)
  72. else:
  73. return self.default()
  74. return self.default
  75. def __repr__(self):
  76. return "%s(%s)" % (self.__class__.__name__, repr(self.default))
  77. class RRSerializer(serializers.ModelSerializer):
  78. class Meta:
  79. model = models.RR
  80. fields = ("content",)
  81. def to_internal_value(self, data):
  82. if not isinstance(data, str):
  83. raise serializers.ValidationError(
  84. "Must be a string.", code="must-be-a-string"
  85. )
  86. return super().to_internal_value({"content": data})
  87. def to_representation(self, instance):
  88. return instance.content
  89. class RRsetListSerializer(serializers.ListSerializer):
  90. default_error_messages = {
  91. **serializers.Serializer.default_error_messages,
  92. **serializers.ListSerializer.default_error_messages,
  93. **{"not_a_list": "Expected a list of items but got {input_type}."},
  94. }
  95. @staticmethod
  96. def _key(data_item):
  97. return data_item.get("subname"), data_item.get("type")
  98. @staticmethod
  99. def _types_by_position_string(conflicting_indices_by_type):
  100. types_by_position = {}
  101. for type_, conflict_positions in conflicting_indices_by_type.items():
  102. for position in conflict_positions:
  103. types_by_position.setdefault(position, []).append(type_)
  104. # Sort by position, None at the end
  105. types_by_position = dict(
  106. sorted(types_by_position.items(), key=lambda x: (x[0] is None, x))
  107. )
  108. db_conflicts = types_by_position.pop(None, None)
  109. if db_conflicts:
  110. types_by_position["database"] = db_conflicts
  111. for position, types in types_by_position.items():
  112. types_by_position[position] = ", ".join(sorted(types))
  113. types_by_position = [
  114. f"{position} ({types})" for position, types in types_by_position.items()
  115. ]
  116. return ", ".join(types_by_position)
  117. def to_internal_value(self, data):
  118. if not isinstance(data, list):
  119. message = self.error_messages["not_a_list"].format(
  120. input_type=type(data).__name__
  121. )
  122. raise serializers.ValidationError(
  123. {api_settings.NON_FIELD_ERRORS_KEY: [message]}, code="not_a_list"
  124. )
  125. if not self.allow_empty and len(data) == 0:
  126. if self.parent and self.partial:
  127. raise serializers.SkipField()
  128. else:
  129. self.fail("empty")
  130. partial = self.partial
  131. # build look-up objects for instances and data, so we can look them up with their keys
  132. try:
  133. known_instances = {(x.subname, x.type): x for x in self.instance}
  134. except TypeError: # in case self.instance is None (as during POST)
  135. known_instances = {}
  136. errors = [{} for _ in data]
  137. indices = {}
  138. for idx, item in enumerate(data):
  139. # Validate data types before using anything from it
  140. if not isinstance(item, dict):
  141. errors[idx].update(
  142. non_field_errors=f"Expected a dictionary, but got {type(item).__name__}."
  143. )
  144. continue
  145. s, t = self._key(item) # subname, type
  146. if not (isinstance(s, str) or s is None):
  147. errors[idx].update(
  148. subname=f"Expected a string, but got {type(s).__name__}."
  149. )
  150. if not (isinstance(t, str) or t is None):
  151. errors[idx].update(
  152. type=f"Expected a string, but got {type(t).__name__}."
  153. )
  154. if errors[idx]:
  155. continue
  156. # Construct an index of the RRsets in `data` by `s` and `t`. As (subname, type) may be given multiple times
  157. # (although invalid), we make indices[s][t] a set to properly keep track. We also check and record RRsets
  158. # which are known in the database (once per subname), using index `None` (for checking CNAME exclusivity).
  159. if s not in indices:
  160. types = self.child.domain.rrset_set.filter(subname=s).values_list(
  161. "type", flat=True
  162. )
  163. indices[s] = {type_: {None} for type_ in types}
  164. items = indices[s].setdefault(t, set())
  165. items.add(idx)
  166. collapsed_indices = copy.deepcopy(indices)
  167. for idx, item in enumerate(data):
  168. if errors[idx]:
  169. continue
  170. if item.get("records") == []:
  171. s, t = self._key(item)
  172. collapsed_indices[s][t] -= {idx, None}
  173. # Iterate over all rows in the data given
  174. ret = []
  175. for idx, item in enumerate(data):
  176. if errors[idx]:
  177. continue
  178. try:
  179. # see if other rows have the same key
  180. s, t = self._key(item)
  181. data_indices = indices[s][t] - {None}
  182. if len(data_indices) > 1:
  183. raise serializers.ValidationError(
  184. {
  185. "non_field_errors": [
  186. "Same subname and type as in position(s) %s, but must be unique."
  187. % ", ".join(map(str, data_indices - {idx}))
  188. ]
  189. }
  190. )
  191. # see if other rows violate CNAME exclusivity
  192. if item.get("records") != []:
  193. conflicting_indices_by_type = {
  194. k: v
  195. for k, v in collapsed_indices[s].items()
  196. if (k == "CNAME") != (t == "CNAME")
  197. }
  198. if any(conflicting_indices_by_type.values()):
  199. types_by_position = self._types_by_position_string(
  200. conflicting_indices_by_type
  201. )
  202. raise serializers.ValidationError(
  203. {
  204. "non_field_errors": [
  205. f"RRset with conflicting type present: {types_by_position}."
  206. " (No other RRsets are allowed alongside CNAME.)"
  207. ]
  208. }
  209. )
  210. # determine if this is a partial update (i.e. PATCH):
  211. # we allow partial update if a partial update method (i.e. PATCH) is used, as indicated by self.partial,
  212. # and if this is not actually a create request because it is unknown and nonempty
  213. unknown = self._key(item) not in known_instances.keys()
  214. nonempty = item.get("records", None) != []
  215. self.partial = partial and not (unknown and nonempty)
  216. self.child.instance = known_instances.get(self._key(item), None)
  217. # with partial value and instance in place, let the validation begin!
  218. validated = self.child.run_validation(item)
  219. except serializers.ValidationError as exc:
  220. errors[idx].update(exc.detail)
  221. else:
  222. ret.append(validated)
  223. self.partial = partial
  224. if any(errors):
  225. raise serializers.ValidationError(errors)
  226. return ret
  227. def update(self, instance, validated_data):
  228. """
  229. Creates, updates and deletes RRsets according to the validated_data given. Relevant instances must be passed as
  230. a queryset in the `instance` argument.
  231. RRsets that appear in `instance` are considered "known", other RRsets are considered "unknown". RRsets that
  232. appear in `validated_data` with records == [] are considered empty, otherwise non-empty.
  233. The update proceeds as follows:
  234. 1. All unknown, non-empty RRsets are created.
  235. 2. All known, non-empty RRsets are updated.
  236. 3. All known, empty RRsets are deleted.
  237. 4. Unknown, empty RRsets will not cause any action.
  238. Rationale:
  239. As both "known"/"unknown" and "empty"/"non-empty" are binary partitions on `everything`, the combination of
  240. both partitions `everything` in four disjoint subsets. Hence, every RRset in `everything` is taken care of.
  241. empty | non-empty
  242. ------- | -------- | -----------
  243. known | delete | update
  244. unknown | no-op | create
  245. :param instance: QuerySet of relevant RRset objects, i.e. the Django.Model subclass instances. Relevant are all
  246. instances that are referenced in `validated_data`. If a referenced RRset is missing from instances, it will be
  247. considered unknown and hence be created. This may cause a database integrity error. If an RRset is given, but
  248. not relevant (i.e. not referred to by `validated_data`), a ValueError will be raised.
  249. :param validated_data: List of RRset data objects, i.e. dictionaries.
  250. :return: List of RRset objects (Django.Model subclass) that have been created or updated.
  251. """
  252. def is_empty(data_item):
  253. return data_item.get("records", None) == []
  254. query = Q(
  255. pk__in=[]
  256. ) # start out with an always empty query, see https://stackoverflow.com/q/35893867/6867099
  257. for item in validated_data:
  258. query |= Q(
  259. type=item["type"], subname=item["subname"]
  260. ) # validation has ensured these fields exist
  261. instance = instance.filter(query)
  262. instance_index = {(rrset.subname, rrset.type): rrset for rrset in instance}
  263. data_index = {self._key(data): data for data in validated_data}
  264. if data_index.keys() | instance_index.keys() != data_index.keys():
  265. raise ValueError(
  266. "Given set of known RRsets (`instance`) is not a subset of RRsets referred to in"
  267. " `validated_data`. While this would produce a correct result, this is illegal due to its"
  268. " inefficiency."
  269. )
  270. everything = instance_index.keys() | data_index.keys()
  271. known = instance_index.keys()
  272. unknown = everything - known
  273. # noinspection PyShadowingNames
  274. empty = {self._key(data) for data in validated_data if is_empty(data)}
  275. nonempty = everything - empty
  276. # noinspection PyUnusedLocal
  277. noop = unknown & empty
  278. created = unknown & nonempty
  279. updated = known & nonempty
  280. deleted = known & empty
  281. ret = []
  282. # The above algorithm makes sure that created, updated, and deleted are disjoint. Thus, no "override cases"
  283. # (such as: an RRset should be updated and delete, what should be applied last?) need to be considered.
  284. # We apply deletion first to get any possible CNAME exclusivity collisions out of the way.
  285. for subname, type_ in deleted:
  286. instance_index[(subname, type_)].delete()
  287. for subname, type_ in created:
  288. ret.append(self.child.create(validated_data=data_index[(subname, type_)]))
  289. for subname, type_ in updated:
  290. ret.append(
  291. self.child.update(
  292. instance=instance_index[(subname, type_)],
  293. validated_data=data_index[(subname, type_)],
  294. )
  295. )
  296. return ret
  297. def save(self, **kwargs):
  298. kwargs.setdefault("domain", self.child.domain)
  299. return super().save(**kwargs)
  300. class RRsetSerializer(ConditionalExistenceModelSerializer):
  301. domain = serializers.SlugRelatedField(read_only=True, slug_field="name")
  302. records = RRSerializer(many=True)
  303. ttl = serializers.IntegerField(max_value=settings.MAXIMUM_TTL)
  304. class Meta:
  305. model = models.RRset
  306. fields = (
  307. "created",
  308. "domain",
  309. "subname",
  310. "name",
  311. "records",
  312. "ttl",
  313. "type",
  314. "touched",
  315. )
  316. extra_kwargs = {
  317. "subname": {"required": False, "default": NonBulkOnlyDefault("")}
  318. }
  319. list_serializer_class = RRsetListSerializer
  320. def __init__(self, *args, **kwargs):
  321. super().__init__(*args, **kwargs)
  322. try:
  323. self.domain = self.context["domain"]
  324. except KeyError:
  325. raise ValueError(
  326. "RRsetSerializer() must be given a domain object (to validate uniqueness constraints)."
  327. )
  328. self.minimum_ttl = self.context.get("minimum_ttl", self.domain.minimum_ttl)
  329. def get_fields(self):
  330. fields = super().get_fields()
  331. fields["subname"].validators.append(ReadOnlyOnUpdateValidator())
  332. fields["type"].validators.append(ReadOnlyOnUpdateValidator())
  333. fields["ttl"].validators.append(MinValueValidator(limit_value=self.minimum_ttl))
  334. return fields
  335. def get_validators(self):
  336. return [
  337. UniqueTogetherValidator(
  338. self.domain.rrset_set,
  339. ("subname", "type"),
  340. message="Another RRset with the same subdomain and type exists for this domain.",
  341. ),
  342. ExclusionConstraintValidator(
  343. self.domain.rrset_set,
  344. ("subname",),
  345. exclusion_condition=(
  346. "type",
  347. "CNAME",
  348. ),
  349. message="RRset with conflicting type present: database ({types})."
  350. " (No other RRsets are allowed alongside CNAME.)",
  351. ),
  352. ]
  353. @staticmethod
  354. def validate_type(value):
  355. if value not in models.RR_SET_TYPES_MANAGEABLE:
  356. # user cannot manage this type, let's try to tell her the reason
  357. if value in models.RR_SET_TYPES_AUTOMATIC:
  358. raise serializers.ValidationError(
  359. f"You cannot tinker with the {value} RR set. It is managed "
  360. f"automatically."
  361. )
  362. elif value.startswith("TYPE"):
  363. raise serializers.ValidationError(
  364. "Generic type format is not supported."
  365. )
  366. else:
  367. raise serializers.ValidationError(
  368. f"The {value} RR set type is currently unsupported."
  369. )
  370. return value
  371. def validate_records(self, value):
  372. # `records` is usually allowed to be empty (for idempotent delete), except for POST requests which are intended
  373. # for RRset creation only. We use the fact that DRF generic views pass the request in the serializer context.
  374. request = self.context.get("request")
  375. if request and request.method == "POST" and not value:
  376. raise serializers.ValidationError(
  377. "This field must not be empty when using POST."
  378. )
  379. return value
  380. def validate_subname(self, value):
  381. try:
  382. dns.name.from_text(value, dns.name.from_text(self.domain.name))
  383. except dns.name.NameTooLong:
  384. raise serializers.ValidationError(
  385. "This field combined with the domain name must not exceed 255 characters.",
  386. code="name_too_long",
  387. )
  388. return value
  389. def validate(self, attrs):
  390. if "records" in attrs:
  391. try:
  392. type_ = attrs["type"]
  393. except KeyError: # on the RRsetDetail endpoint, the type is not in attrs
  394. type_ = self.instance.type
  395. try:
  396. attrs["records"] = [
  397. {
  398. "content": models.RR.canonical_presentation_format(
  399. rr["content"], type_
  400. )
  401. }
  402. for rr in attrs["records"]
  403. ]
  404. except ValueError as ex:
  405. raise serializers.ValidationError(str(ex))
  406. # There is a 12 byte baseline requirement per record, c.f.
  407. # https://lists.isc.org/pipermail/bind-users/2008-April/070137.html
  408. # There also seems to be a 32 byte (?) baseline requirement per RRset, plus the qname length, see
  409. # https://lists.isc.org/pipermail/bind-users/2008-April/070148.html
  410. # The binary length of the record depends actually on the type, but it's never longer than vanilla len()
  411. qname = models.RRset.construct_name(
  412. attrs.get("subname", ""), self.domain.name
  413. )
  414. conservative_total_length = (
  415. 32
  416. + len(qname)
  417. + sum(12 + len(rr["content"]) for rr in attrs["records"])
  418. )
  419. # Add some leeway for RRSIG record (really ~110 bytes) and other data we have not thought of
  420. conservative_total_length += 256
  421. excess_length = conservative_total_length - 65535 # max response size
  422. if excess_length > 0:
  423. raise serializers.ValidationError(
  424. f"Total length of RRset exceeds limit by {excess_length} bytes.",
  425. code="max_length",
  426. )
  427. return attrs
  428. def exists(self, arg):
  429. if isinstance(arg, models.RRset):
  430. return arg.records.exists() if arg.pk else False
  431. else:
  432. return bool(arg.get("records")) if "records" in arg.keys() else True
  433. def create(self, validated_data):
  434. rrs_data = validated_data.pop("records")
  435. rrset = models.RRset.objects.create(**validated_data)
  436. self._set_all_record_contents(rrset, rrs_data)
  437. return rrset
  438. def update(self, instance: models.RRset, validated_data):
  439. rrs_data = validated_data.pop("records", None)
  440. if rrs_data is not None:
  441. self._set_all_record_contents(instance, rrs_data)
  442. ttl = validated_data.pop("ttl", None)
  443. if ttl and instance.ttl != ttl:
  444. instance.ttl = ttl
  445. instance.save() # also updates instance.touched
  446. else:
  447. # Update instance.touched without triggering post-save signal (no pdns action required)
  448. models.RRset.objects.filter(pk=instance.pk).update(touched=timezone.now())
  449. return instance
  450. def save(self, **kwargs):
  451. kwargs.setdefault("domain", self.domain)
  452. return super().save(**kwargs)
  453. @staticmethod
  454. def _set_all_record_contents(rrset: models.RRset, rrs):
  455. """
  456. Updates this RR set's resource records, discarding any old values.
  457. :param rrset: the RRset at which we overwrite all RRs
  458. :param rrs: list of RR representations
  459. """
  460. record_contents = [rr["content"] for rr in rrs]
  461. try:
  462. rrset.save_records(record_contents)
  463. except django.core.exceptions.ValidationError as e:
  464. raise serializers.ValidationError(e.messages, code="record-content")