serializers.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038
  1. import binascii
  2. import copy
  3. import json
  4. import re
  5. from base64 import b64encode
  6. from datetime import timedelta
  7. import django.core.exceptions
  8. import dns.name
  9. import dns.zone
  10. from captcha.audio import AudioCaptcha
  11. from captcha.image import ImageCaptcha
  12. from django.contrib.auth.password_validation import validate_password
  13. from django.core.validators import MinValueValidator
  14. from django.db.models import Model, Q
  15. from django.utils import timezone
  16. from netfields import rest_framework as netfields_rf
  17. from rest_framework import fields, serializers
  18. from rest_framework.settings import api_settings
  19. from rest_framework.validators import UniqueTogetherValidator, UniqueValidator, qs_filter
  20. from api import settings
  21. from desecapi import crypto, metrics, models, validators
  22. from desecapi.models import validate_domain_name
  23. class CaptchaSerializer(serializers.ModelSerializer):
  24. challenge = serializers.SerializerMethodField()
  25. class Meta:
  26. model = models.Captcha
  27. fields = ('id', 'challenge', 'kind') if not settings.DEBUG else ('id', 'challenge', 'kind', 'content')
  28. def get_challenge(self, obj: models.Captcha):
  29. # TODO Does this need to be stored in the object instance, in case this method gets called twice?
  30. if obj.kind == models.Captcha.Kind.IMAGE:
  31. challenge = ImageCaptcha().generate(obj.content).getvalue()
  32. elif obj.kind == models.Captcha.Kind.AUDIO:
  33. challenge = AudioCaptcha().generate(obj.content)
  34. else:
  35. raise ValueError(f'Unknown captcha type {obj.kind}')
  36. return b64encode(challenge)
  37. class CaptchaSolutionSerializer(serializers.Serializer):
  38. id = serializers.PrimaryKeyRelatedField(
  39. queryset=models.Captcha.objects.all(),
  40. error_messages={'does_not_exist': 'CAPTCHA does not exist.'}
  41. )
  42. solution = serializers.CharField(write_only=True, required=True)
  43. def validate(self, attrs):
  44. captcha = attrs['id'] # Note that this already is the Captcha object
  45. if not captcha.verify(attrs['solution']):
  46. raise serializers.ValidationError('CAPTCHA could not be validated. Please obtain a new one and try again.')
  47. return attrs
  48. class TokenSerializer(serializers.ModelSerializer):
  49. allowed_subnets = serializers.ListField(child=netfields_rf.CidrAddressField(), required=False)
  50. token = serializers.ReadOnlyField(source='plain')
  51. is_valid = serializers.ReadOnlyField()
  52. class Meta:
  53. model = models.Token
  54. fields = ('id', 'created', 'last_used', 'max_age', 'max_unused_period', 'name', 'perm_manage_tokens',
  55. 'allowed_subnets', 'is_valid', 'token',)
  56. read_only_fields = ('id', 'created', 'last_used', 'token')
  57. def __init__(self, *args, include_plain=False, **kwargs):
  58. self.include_plain = include_plain
  59. return super().__init__(*args, **kwargs)
  60. def get_fields(self):
  61. fields = super().get_fields()
  62. if not self.include_plain:
  63. fields.pop('token')
  64. return fields
  65. class DomainSlugRelatedField(serializers.SlugRelatedField):
  66. def get_queryset(self):
  67. return self.context['request'].user.domains
  68. class TokenDomainPolicySerializer(serializers.ModelSerializer):
  69. domain = DomainSlugRelatedField(allow_null=True, slug_field='name')
  70. class Meta:
  71. model = models.TokenDomainPolicy
  72. fields = ('domain', 'perm_dyndns', 'perm_rrsets',)
  73. def to_internal_value(self, data):
  74. return {**super().to_internal_value(data),
  75. 'token': self.context['request'].user.token_set.get(id=self.context['view'].kwargs['token_id'])}
  76. def save(self, **kwargs):
  77. try:
  78. return super().save(**kwargs)
  79. except django.core.exceptions.ValidationError as exc:
  80. raise serializers.ValidationError(exc.message_dict, code='precedence')
  81. class RequiredOnPartialUpdateCharField(serializers.CharField):
  82. """
  83. This field is always required, even for partial updates (e.g. using PATCH).
  84. """
  85. def validate_empty_values(self, data):
  86. if data is serializers.empty:
  87. self.fail('required')
  88. return super().validate_empty_values(data)
  89. class Validator:
  90. message = 'This field did not pass validation.'
  91. def __init__(self, message=None):
  92. self.field_name = None
  93. self.message = message or self.message
  94. self.instance = None
  95. def __call__(self, value):
  96. raise NotImplementedError
  97. def __repr__(self):
  98. return '<%s>' % self.__class__.__name__
  99. class ReadOnlyOnUpdateValidator(Validator):
  100. message = 'Can only be written on create.'
  101. requires_context = True
  102. def __call__(self, value, serializer_field):
  103. field_name = serializer_field.source_attrs[-1]
  104. instance = getattr(serializer_field.parent, 'instance', None)
  105. if isinstance(instance, Model) and value != getattr(instance, field_name):
  106. raise serializers.ValidationError(self.message, code='read-only-on-update')
  107. class ConditionalExistenceModelSerializer(serializers.ModelSerializer):
  108. """
  109. Only considers data with certain condition as existing data.
  110. If the existence condition does not hold, given instances are deleted, and no new instances are created,
  111. respectively. Also, to_representation and data will return None.
  112. Contrary, if the existence condition holds, the behavior is the same as DRF's ModelSerializer.
  113. """
  114. def exists(self, arg):
  115. """
  116. Determine if arg is to be considered existing.
  117. :param arg: Either a model instance or (possibly invalid!) data object.
  118. :return: Whether we treat this as non-existing instance.
  119. """
  120. raise NotImplementedError
  121. def to_representation(self, instance):
  122. return None if not self.exists(instance) else super().to_representation(instance)
  123. @property
  124. def data(self):
  125. try:
  126. return super().data
  127. except TypeError:
  128. return None
  129. def save(self, **kwargs):
  130. validated_data = {}
  131. validated_data.update(self.validated_data)
  132. validated_data.update(kwargs)
  133. known_instance = self.instance is not None
  134. data_exists = self.exists(validated_data)
  135. if known_instance and data_exists:
  136. self.instance = self.update(self.instance, validated_data)
  137. elif known_instance and not data_exists:
  138. self.delete()
  139. elif not known_instance and data_exists:
  140. self.instance = self.create(validated_data)
  141. elif not known_instance and not data_exists:
  142. pass # nothing to do
  143. return self.instance
  144. def delete(self):
  145. self.instance.delete()
  146. class NonBulkOnlyDefault:
  147. """
  148. This class may be used to provide default values that are only used
  149. for non-bulk operations, but that do not return any value for bulk
  150. operations.
  151. Implementation inspired by CreateOnlyDefault.
  152. """
  153. requires_context = True
  154. def __init__(self, default):
  155. self.default = default
  156. def __call__(self, serializer_field):
  157. is_many = getattr(serializer_field.root, 'many', False)
  158. if is_many:
  159. raise serializers.SkipField()
  160. if callable(self.default):
  161. if getattr(self.default, 'requires_context', False):
  162. return self.default(serializer_field)
  163. else:
  164. return self.default()
  165. return self.default
  166. def __repr__(self):
  167. return '%s(%s)' % (self.__class__.__name__, repr(self.default))
  168. class RRSerializer(serializers.ModelSerializer):
  169. class Meta:
  170. model = models.RR
  171. fields = ('content',)
  172. def to_internal_value(self, data):
  173. if not isinstance(data, str):
  174. raise serializers.ValidationError('Must be a string.', code='must-be-a-string')
  175. return super().to_internal_value({'content': data})
  176. def to_representation(self, instance):
  177. return instance.content
  178. class RRsetListSerializer(serializers.ListSerializer):
  179. default_error_messages = {
  180. **serializers.Serializer.default_error_messages,
  181. **serializers.ListSerializer.default_error_messages,
  182. **{'not_a_list': 'Expected a list of items but got {input_type}.'},
  183. }
  184. @staticmethod
  185. def _key(data_item):
  186. return data_item.get('subname'), data_item.get('type')
  187. @staticmethod
  188. def _types_by_position_string(conflicting_indices_by_type):
  189. types_by_position = {}
  190. for type_, conflict_positions in conflicting_indices_by_type.items():
  191. for position in conflict_positions:
  192. types_by_position.setdefault(position, []).append(type_)
  193. # Sort by position, None at the end
  194. types_by_position = dict(sorted(types_by_position.items(), key=lambda x: (x[0] is None, x)))
  195. db_conflicts = types_by_position.pop(None, None)
  196. if db_conflicts: types_by_position['database'] = db_conflicts
  197. for position, types in types_by_position.items():
  198. types_by_position[position] = ', '.join(sorted(types))
  199. types_by_position = [f'{position} ({types})' for position, types in types_by_position.items()]
  200. return ', '.join(types_by_position)
  201. def to_internal_value(self, data):
  202. if not isinstance(data, list):
  203. message = self.error_messages['not_a_list'].format(input_type=type(data).__name__)
  204. raise serializers.ValidationError({api_settings.NON_FIELD_ERRORS_KEY: [message]}, code='not_a_list')
  205. if not self.allow_empty and len(data) == 0:
  206. if self.parent and self.partial:
  207. raise serializers.SkipField()
  208. else:
  209. self.fail('empty')
  210. partial = self.partial
  211. # build look-up objects for instances and data, so we can look them up with their keys
  212. try:
  213. known_instances = {(x.subname, x.type): x for x in self.instance}
  214. except TypeError: # in case self.instance is None (as during POST)
  215. known_instances = {}
  216. errors = [{} for _ in data]
  217. indices = {}
  218. for idx, item in enumerate(data):
  219. # Validate data types before using anything from it
  220. if not isinstance(item, dict):
  221. errors[idx].update(non_field_errors=f"Expected a dictionary, but got {type(item).__name__}.")
  222. continue
  223. s, t = self._key(item) # subname, type
  224. if not (isinstance(s, str) or s is None):
  225. errors[idx].update(subname=f"Expected a string, but got {type(s).__name__}.")
  226. if not (isinstance(t, str) or t is None):
  227. errors[idx].update(type=f"Expected a string, but got {type(t).__name__}.")
  228. if errors[idx]:
  229. continue
  230. # Construct an index of the RRsets in `data` by `s` and `t`. As (subname, type) may be given multiple times
  231. # (although invalid), we make indices[s][t] a set to properly keep track. We also check and record RRsets
  232. # which are known in the database (once per subname), using index `None` (for checking CNAME exclusivity).
  233. if s not in indices:
  234. types = self.child.domain.rrset_set.filter(subname=s).values_list('type', flat=True)
  235. indices[s] = {type_: {None} for type_ in types}
  236. items = indices[s].setdefault(t, set())
  237. items.add(idx)
  238. collapsed_indices = copy.deepcopy(indices)
  239. for idx, item in enumerate(data):
  240. if errors[idx]:
  241. continue
  242. if item.get('records') == []:
  243. s, t = self._key(item)
  244. collapsed_indices[s][t] -= {idx, None}
  245. # Iterate over all rows in the data given
  246. ret = []
  247. for idx, item in enumerate(data):
  248. if errors[idx]:
  249. continue
  250. try:
  251. # see if other rows have the same key
  252. s, t = self._key(item)
  253. data_indices = indices[s][t] - {None}
  254. if len(data_indices) > 1:
  255. raise serializers.ValidationError({
  256. 'non_field_errors': [
  257. 'Same subname and type as in position(s) %s, but must be unique.' %
  258. ', '.join(map(str, data_indices - {idx}))
  259. ]
  260. })
  261. # see if other rows violate CNAME exclusivity
  262. if item.get('records') != []:
  263. conflicting_indices_by_type = {k: v for k, v in collapsed_indices[s].items()
  264. if (k == 'CNAME') != (t == 'CNAME')}
  265. if any(conflicting_indices_by_type.values()):
  266. types_by_position = self._types_by_position_string(conflicting_indices_by_type)
  267. raise serializers.ValidationError({
  268. 'non_field_errors': [
  269. f'RRset with conflicting type present: {types_by_position}.'
  270. ' (No other RRsets are allowed alongside CNAME.)'
  271. ]
  272. })
  273. # determine if this is a partial update (i.e. PATCH):
  274. # we allow partial update if a partial update method (i.e. PATCH) is used, as indicated by self.partial,
  275. # and if this is not actually a create request because it is unknown and nonempty
  276. unknown = self._key(item) not in known_instances.keys()
  277. nonempty = item.get('records', None) != []
  278. self.partial = partial and not (unknown and nonempty)
  279. self.child.instance = known_instances.get(self._key(item), None)
  280. # with partial value and instance in place, let the validation begin!
  281. validated = self.child.run_validation(item)
  282. except serializers.ValidationError as exc:
  283. errors[idx].update(exc.detail)
  284. else:
  285. ret.append(validated)
  286. self.partial = partial
  287. if any(errors):
  288. raise serializers.ValidationError(errors)
  289. return ret
  290. def update(self, instance, validated_data):
  291. """
  292. Creates, updates and deletes RRsets according to the validated_data given. Relevant instances must be passed as
  293. a queryset in the `instance` argument.
  294. RRsets that appear in `instance` are considered "known", other RRsets are considered "unknown". RRsets that
  295. appear in `validated_data` with records == [] are considered empty, otherwise non-empty.
  296. The update proceeds as follows:
  297. 1. All unknown, non-empty RRsets are created.
  298. 2. All known, non-empty RRsets are updated.
  299. 3. All known, empty RRsets are deleted.
  300. 4. Unknown, empty RRsets will not cause any action.
  301. Rationale:
  302. As both "known"/"unknown" and "empty"/"non-empty" are binary partitions on `everything`, the combination of
  303. both partitions `everything` in four disjoint subsets. Hence, every RRset in `everything` is taken care of.
  304. empty | non-empty
  305. ------- | -------- | -----------
  306. known | delete | update
  307. unknown | no-op | create
  308. :param instance: QuerySet of relevant RRset objects, i.e. the Django.Model subclass instances. Relevant are all
  309. instances that are referenced in `validated_data`. If a referenced RRset is missing from instances, it will be
  310. considered unknown and hence be created. This may cause a database integrity error. If an RRset is given, but
  311. not relevant (i.e. not referred to by `validated_data`), a ValueError will be raised.
  312. :param validated_data: List of RRset data objects, i.e. dictionaries.
  313. :return: List of RRset objects (Django.Model subclass) that have been created or updated.
  314. """
  315. def is_empty(data_item):
  316. return data_item.get('records', None) == []
  317. query = Q(pk__in=[]) # start out with an always empty query, see https://stackoverflow.com/q/35893867/6867099
  318. for item in validated_data:
  319. query |= Q(type=item['type'], subname=item['subname']) # validation has ensured these fields exist
  320. instance = instance.filter(query)
  321. instance_index = {(rrset.subname, rrset.type): rrset for rrset in instance}
  322. data_index = {self._key(data): data for data in validated_data}
  323. if data_index.keys() | instance_index.keys() != data_index.keys():
  324. raise ValueError('Given set of known RRsets (`instance`) is not a subset of RRsets referred to in'
  325. ' `validated_data`. While this would produce a correct result, this is illegal due to its'
  326. ' inefficiency.')
  327. everything = instance_index.keys() | data_index.keys()
  328. known = instance_index.keys()
  329. unknown = everything - known
  330. # noinspection PyShadowingNames
  331. empty = {self._key(data) for data in validated_data if is_empty(data)}
  332. nonempty = everything - empty
  333. # noinspection PyUnusedLocal
  334. noop = unknown & empty
  335. created = unknown & nonempty
  336. updated = known & nonempty
  337. deleted = known & empty
  338. ret = []
  339. # The above algorithm makes sure that created, updated, and deleted are disjoint. Thus, no "override cases"
  340. # (such as: an RRset should be updated and delete, what should be applied last?) need to be considered.
  341. # We apply deletion first to get any possible CNAME exclusivity collisions out of the way.
  342. for subname, type_ in deleted:
  343. instance_index[(subname, type_)].delete()
  344. for subname, type_ in created:
  345. ret.append(self.child.create(
  346. validated_data=data_index[(subname, type_)]
  347. ))
  348. for subname, type_ in updated:
  349. ret.append(self.child.update(
  350. instance=instance_index[(subname, type_)],
  351. validated_data=data_index[(subname, type_)]
  352. ))
  353. return ret
  354. def save(self, **kwargs):
  355. kwargs.setdefault('domain', self.child.domain)
  356. return super().save(**kwargs)
  357. class RRsetSerializer(ConditionalExistenceModelSerializer):
  358. domain = serializers.SlugRelatedField(read_only=True, slug_field='name')
  359. records = RRSerializer(many=True)
  360. ttl = serializers.IntegerField(max_value=settings.MAXIMUM_TTL)
  361. class Meta:
  362. model = models.RRset
  363. fields = ('created', 'domain', 'subname', 'name', 'records', 'ttl', 'type', 'touched',)
  364. extra_kwargs = {
  365. 'subname': {'required': False, 'default': NonBulkOnlyDefault('')}
  366. }
  367. list_serializer_class = RRsetListSerializer
  368. def __init__(self, *args, **kwargs):
  369. super().__init__(*args, **kwargs)
  370. try:
  371. self.domain = self.context['domain']
  372. except KeyError:
  373. raise ValueError('RRsetSerializer() must be given a domain object (to validate uniqueness constraints).')
  374. self.minimum_ttl = self.context.get('minimum_ttl', self.domain.minimum_ttl)
  375. def get_fields(self):
  376. fields = super().get_fields()
  377. fields['subname'].validators.append(ReadOnlyOnUpdateValidator())
  378. fields['type'].validators.append(ReadOnlyOnUpdateValidator())
  379. fields['ttl'].validators.append(MinValueValidator(limit_value=self.minimum_ttl))
  380. return fields
  381. def get_validators(self):
  382. return [
  383. UniqueTogetherValidator(
  384. self.domain.rrset_set,
  385. ('subname', 'type'),
  386. message='Another RRset with the same subdomain and type exists for this domain.',
  387. ),
  388. validators.ExclusionConstraintValidator(
  389. self.domain.rrset_set,
  390. ('subname',),
  391. exclusion_condition=('type', 'CNAME',),
  392. message='RRset with conflicting type present: database ({types}).'
  393. ' (No other RRsets are allowed alongside CNAME.)',
  394. ),
  395. ]
  396. @staticmethod
  397. def validate_type(value):
  398. if value not in models.RR_SET_TYPES_MANAGEABLE:
  399. # user cannot manage this type, let's try to tell her the reason
  400. if value in models.RR_SET_TYPES_AUTOMATIC:
  401. raise serializers.ValidationError(f'You cannot tinker with the {value} RR set. It is managed '
  402. f'automatically.')
  403. elif value.startswith('TYPE'):
  404. raise serializers.ValidationError('Generic type format is not supported.')
  405. else:
  406. raise serializers.ValidationError(f'The {value} RR set type is currently unsupported.')
  407. return value
  408. def validate_records(self, value):
  409. # `records` is usually allowed to be empty (for idempotent delete), except for POST requests which are intended
  410. # for RRset creation only. We use the fact that DRF generic views pass the request in the serializer context.
  411. request = self.context.get('request')
  412. if request and request.method == 'POST' and not value:
  413. raise serializers.ValidationError('This field must not be empty when using POST.')
  414. return value
  415. def validate_subname(self, value):
  416. try:
  417. dns.name.from_text(value, dns.name.from_text(self.domain.name))
  418. except dns.name.NameTooLong:
  419. raise serializers.ValidationError(
  420. 'This field combined with the domain name must not exceed 255 characters.', code='name_too_long')
  421. return value
  422. def validate(self, attrs):
  423. if 'records' in attrs:
  424. try:
  425. type_ = attrs['type']
  426. except KeyError: # on the RRsetDetail endpoint, the type is not in attrs
  427. type_ = self.instance.type
  428. try:
  429. attrs['records'] = [{'content': models.RR.canonical_presentation_format(rr['content'], type_)}
  430. for rr in attrs['records']]
  431. except ValueError as ex:
  432. raise serializers.ValidationError(str(ex))
  433. # There is a 12 byte baseline requirement per record, c.f.
  434. # https://lists.isc.org/pipermail/bind-users/2008-April/070137.html
  435. # There also seems to be a 32 byte (?) baseline requirement per RRset, plus the qname length, see
  436. # https://lists.isc.org/pipermail/bind-users/2008-April/070148.html
  437. # The binary length of the record depends actually on the type, but it's never longer than vanilla len()
  438. qname = models.RRset.construct_name(attrs.get('subname', ''), self.domain.name)
  439. conservative_total_length = 32 + len(qname) + sum(12 + len(rr['content']) for rr in attrs['records'])
  440. # Add some leeway for RRSIG record (really ~110 bytes) and other data we have not thought of
  441. conservative_total_length += 256
  442. excess_length = conservative_total_length - 65535 # max response size
  443. if excess_length > 0:
  444. raise serializers.ValidationError(f'Total length of RRset exceeds limit by {excess_length} bytes.',
  445. code='max_length')
  446. return attrs
  447. def exists(self, arg):
  448. if isinstance(arg, models.RRset):
  449. return arg.records.exists() if arg.pk else False
  450. else:
  451. return bool(arg.get('records')) if 'records' in arg.keys() else True
  452. def create(self, validated_data):
  453. rrs_data = validated_data.pop('records')
  454. rrset = models.RRset.objects.create(**validated_data)
  455. self._set_all_record_contents(rrset, rrs_data)
  456. return rrset
  457. def update(self, instance: models.RRset, validated_data):
  458. rrs_data = validated_data.pop('records', None)
  459. if rrs_data is not None:
  460. self._set_all_record_contents(instance, rrs_data)
  461. ttl = validated_data.pop('ttl', None)
  462. if ttl and instance.ttl != ttl:
  463. instance.ttl = ttl
  464. instance.save() # also updates instance.touched
  465. else:
  466. # Update instance.touched without triggering post-save signal (no pdns action required)
  467. models.RRset.objects.filter(pk=instance.pk).update(touched=timezone.now())
  468. return instance
  469. def save(self, **kwargs):
  470. kwargs.setdefault('domain', self.domain)
  471. return super().save(**kwargs)
  472. @staticmethod
  473. def _set_all_record_contents(rrset: models.RRset, rrs):
  474. """
  475. Updates this RR set's resource records, discarding any old values.
  476. :param rrset: the RRset at which we overwrite all RRs
  477. :param rrs: list of RR representations
  478. """
  479. record_contents = [rr['content'] for rr in rrs]
  480. try:
  481. rrset.save_records(record_contents)
  482. except django.core.exceptions.ValidationError as e:
  483. raise serializers.ValidationError(e.messages, code='record-content')
  484. class DomainSerializer(serializers.ModelSerializer):
  485. default_error_messages = {
  486. **serializers.Serializer.default_error_messages,
  487. 'name_unavailable': 'This domain name conflicts with an existing zone, or is disallowed by policy.',
  488. }
  489. zonefile = serializers.CharField(write_only=True, required=False, allow_blank=True)
  490. class Meta:
  491. model = models.Domain
  492. fields = ('created', 'published', 'name', 'keys', 'minimum_ttl', 'touched', 'zonefile')
  493. read_only_fields = ('published', 'minimum_ttl',)
  494. extra_kwargs = {
  495. 'name': {'trim_whitespace': False},
  496. }
  497. def __init__(self, *args, include_keys=False, **kwargs):
  498. self.include_keys = include_keys
  499. self.import_zone = None
  500. super().__init__(*args, **kwargs)
  501. def get_fields(self):
  502. fields = super().get_fields()
  503. if not self.include_keys:
  504. fields.pop('keys')
  505. fields['name'].validators.append(ReadOnlyOnUpdateValidator())
  506. return fields
  507. def validate_name(self, value):
  508. if not models.Domain(name=value, owner=self.context['request'].user).is_registrable():
  509. raise serializers.ValidationError(self.default_error_messages['name_unavailable'], code='name_unavailable')
  510. return value
  511. def parse_zonefile(self, domain_name: str, zonefile: str):
  512. try:
  513. self.import_zone = dns.zone.from_text(
  514. zonefile,
  515. origin=dns.name.from_text(domain_name),
  516. allow_include=False,
  517. check_origin=False,
  518. relativize=False,
  519. )
  520. except dns.zonefile.CNAMEAndOtherData:
  521. raise serializers.ValidationError(
  522. {'zonefile': ['No other records with the same name are allowed alongside a CNAME record.']})
  523. except ValueError as e:
  524. if 'has non-origin SOA' in str(e):
  525. raise serializers.ValidationError(
  526. {'zonefile': [f'Zonefile includes an SOA record for a name different from {domain_name}.']})
  527. raise e
  528. except dns.exception.SyntaxError as e:
  529. try:
  530. line = str(e).split(':')[1]
  531. raise serializers.ValidationError({'zonefile': [f'Zonefile contains syntax error in line {line}.']})
  532. except IndexError:
  533. raise serializers.ValidationError({'zonefile': [f'Could not parse zonefile: {str(e)}']})
  534. def validate(self, attrs):
  535. if attrs.get('zonefile') is not None:
  536. self.parse_zonefile(attrs.get('name'), attrs.pop('zonefile'))
  537. return super().validate(attrs)
  538. def create(self, validated_data):
  539. # save domain
  540. if 'minimum_ttl' not in validated_data and models.Domain(name=validated_data['name']).is_locally_registrable:
  541. validated_data.update(minimum_ttl=60)
  542. domain: models.Domain = super().create(validated_data)
  543. # save RRsets if zonefile was given
  544. nodes = getattr(self.import_zone, 'nodes', None)
  545. if nodes:
  546. zone_name = dns.name.from_text(validated_data['name'])
  547. min_ttl, max_ttl = domain.minimum_ttl, settings.MAXIMUM_TTL
  548. data = [
  549. {
  550. 'type': dns.rdatatype.to_text(rrset.rdtype),
  551. 'ttl': max(min_ttl, min(max_ttl, rrset.ttl)),
  552. 'subname': (owner_name - zone_name).to_text() if owner_name - zone_name != dns.name.empty else '',
  553. 'records': [rr.to_text() for rr in rrset],
  554. }
  555. for owner_name, node in nodes.items()
  556. for rrset in node.rdatasets
  557. if (
  558. dns.rdatatype.to_text(rrset.rdtype) not in (
  559. models.RR_SET_TYPES_AUTOMATIC | # do not import automatically managed record types
  560. {'CDS', 'CDNSKEY', 'DNSKEY'} # do not import these, as this would likely be unexpected
  561. )
  562. and not (owner_name - zone_name == dns.name.empty and rrset.rdtype == dns.rdatatype.NS) # ignore apex NS
  563. )
  564. ]
  565. rrset_list_serializer = RRsetSerializer(data=data, context=dict(domain=domain), many=True)
  566. # The following line raises if data passed validation by dnspython during zone file parsing,
  567. # but is rejected by validation in RRsetSerializer. See also
  568. # test_create_domain_zonefile_import_validation
  569. try:
  570. rrset_list_serializer.is_valid(raise_exception=True)
  571. except serializers.ValidationError as e:
  572. if isinstance(e.detail, serializers.ReturnList):
  573. # match the order of error messages with the RRsets provided to the
  574. # serializer to make sense to the client
  575. def fqdn(idx): return (data[idx]['subname'] + "." + domain.name).lstrip('.')
  576. raise serializers.ValidationError({
  577. 'zonefile': [
  578. f"{fqdn(idx)}/{data[idx]['type']}: {err}"
  579. for idx, d in enumerate(e.detail)
  580. for _, errs in d.items()
  581. for err in errs
  582. ]
  583. })
  584. raise e
  585. rrset_list_serializer.save()
  586. return domain
  587. class DonationSerializer(serializers.ModelSerializer):
  588. class Meta:
  589. model = models.Donation
  590. fields = ('name', 'iban', 'bic', 'amount', 'message', 'email', 'mref', 'interval')
  591. read_only_fields = ('mref',)
  592. extra_kwargs = { # do not return sensitive information
  593. 'iban': {'write_only': True},
  594. 'bic': {'write_only': True},
  595. 'message': {'write_only': True},
  596. }
  597. @staticmethod
  598. def validate_bic(value):
  599. return re.sub(r'[\s]', '', value)
  600. @staticmethod
  601. def validate_iban(value):
  602. return re.sub(r'[\s]', '', value)
  603. def create(self, validated_data):
  604. return self.Meta.model(**validated_data)
  605. class UserSerializer(serializers.ModelSerializer):
  606. class Meta:
  607. model = models.User
  608. fields = ('created', 'email', 'id', 'limit_domains', 'outreach_preference',)
  609. read_only_fields = ('created', 'email', 'id', 'limit_domains',)
  610. def validate_password(self, value):
  611. if value is not None:
  612. validate_password(value)
  613. return value
  614. def create(self, validated_data):
  615. return models.User.objects.create_user(**validated_data)
  616. class RegisterAccountSerializer(UserSerializer):
  617. domain = serializers.CharField(required=False, validators=validate_domain_name)
  618. captcha = CaptchaSolutionSerializer(required=False)
  619. class Meta:
  620. model = UserSerializer.Meta.model
  621. fields = ('email', 'password', 'domain', 'captcha', 'outreach_preference',)
  622. extra_kwargs = {
  623. 'password': {
  624. 'write_only': True, # Do not expose password field
  625. 'allow_null': True,
  626. }
  627. }
  628. def validate_domain(self, value):
  629. serializer = DomainSerializer(data=dict(name=value), context=self.context)
  630. try:
  631. serializer.is_valid(raise_exception=True)
  632. except serializers.ValidationError:
  633. raise serializers.ValidationError(serializer.default_error_messages['name_unavailable'],
  634. code='name_unavailable')
  635. return value
  636. def create(self, validated_data):
  637. validated_data.pop('domain', None)
  638. # If validated_data['captcha'] exists, the captcha was also validated, so we can set the user to verified
  639. if 'captcha' in validated_data:
  640. validated_data.pop('captcha')
  641. validated_data['needs_captcha'] = False
  642. return super().create(validated_data)
  643. class EmailSerializer(serializers.Serializer):
  644. email = serializers.EmailField()
  645. class EmailPasswordSerializer(EmailSerializer):
  646. password = serializers.CharField()
  647. class ChangeEmailSerializer(serializers.Serializer):
  648. new_email = serializers.EmailField()
  649. def validate_new_email(self, value):
  650. if value == self.context['request'].user.email:
  651. raise serializers.ValidationError('Email address unchanged.')
  652. return value
  653. class ResetPasswordSerializer(EmailSerializer):
  654. captcha = CaptchaSolutionSerializer(required=True)
  655. class CustomFieldNameUniqueValidator(UniqueValidator):
  656. """
  657. Does exactly what rest_framework's UniqueValidator does, however allows to further customize the
  658. query that is used to determine the uniqueness.
  659. More specifically, we allow that the field name the value is queried against is passed when initializing
  660. this validator. (At the time of writing, UniqueValidator insists that the field's name is used for the
  661. database query field; only how the lookup must match is allowed to be changed.)
  662. """
  663. def __init__(self, queryset, message=None, lookup='exact', lookup_field=None):
  664. self.lookup_field = lookup_field
  665. super().__init__(queryset, message, lookup)
  666. def filter_queryset(self, value, queryset, field_name):
  667. """
  668. Filter the queryset to all instances matching the given value on the specified lookup field.
  669. """
  670. filter_kwargs = {'%s__%s' % (self.lookup_field or field_name, self.lookup): value}
  671. return qs_filter(queryset, **filter_kwargs)
  672. class AuthenticatedActionSerializer(serializers.ModelSerializer):
  673. state = serializers.CharField() # serializer read-write, but model read-only field
  674. validity_period = settings.VALIDITY_PERIOD_VERIFICATION_SIGNATURE
  675. _crypto_context = 'desecapi.serializers.AuthenticatedActionSerializer'
  676. timestamp = None # is set to the code's timestamp during validation
  677. class Meta:
  678. model = models.AuthenticatedAction
  679. fields = ('state',)
  680. @classmethod
  681. def _pack_code(cls, data):
  682. payload = json.dumps(data).encode()
  683. code = crypto.encrypt(payload, context=cls._crypto_context).decode()
  684. return code.rstrip('=')
  685. @classmethod
  686. def _unpack_code(cls, code, *, ttl):
  687. code += -len(code) % 4 * '='
  688. try:
  689. timestamp, payload = crypto.decrypt(code.encode(), context=cls._crypto_context, ttl=ttl)
  690. return timestamp, json.loads(payload.decode())
  691. except (TypeError, UnicodeDecodeError, UnicodeEncodeError, json.JSONDecodeError, binascii.Error):
  692. raise ValueError
  693. def to_representation(self, instance: models.AuthenticatedAction):
  694. # do the regular business
  695. data = super().to_representation(instance)
  696. # encode into single string
  697. return {'code': self._pack_code(data)}
  698. def to_internal_value(self, data):
  699. # Allow injecting validity period from context. This is used, for example, for authentication, where the code's
  700. # integrity and timestamp is checked by AuthenticatedBasicUserActionSerializer with validity injected as needed.
  701. validity_period = self.context.get('validity_period', self.validity_period)
  702. # calculate code TTL
  703. try:
  704. ttl = validity_period.total_seconds()
  705. except AttributeError:
  706. ttl = None # infinite
  707. # decode from single string
  708. try:
  709. self.timestamp, unpacked_data = self._unpack_code(self.context['code'], ttl=ttl)
  710. except KeyError:
  711. raise serializers.ValidationError({'code': ['This field is required.']})
  712. except ValueError:
  713. if ttl is None:
  714. msg = 'This code is invalid.'
  715. else:
  716. msg = f'This code is invalid, possibly because it expired (validity: {validity_period}).'
  717. raise serializers.ValidationError({api_settings.NON_FIELD_ERRORS_KEY: msg})
  718. # add extra fields added by the user, but give precedence to fields unpacked from the code
  719. data = {**data, **unpacked_data}
  720. # do the regular business
  721. return super().to_internal_value(data)
  722. def act(self):
  723. self.instance.act()
  724. return self.instance
  725. def save(self, **kwargs):
  726. raise ValueError
  727. class AuthenticatedBasicUserActionMixin():
  728. def save(self, **kwargs):
  729. context = {**self.context, 'action_serializer': self}
  730. return self.action_user.send_email(self.reason, context=context, **kwargs)
  731. class AuthenticatedBasicUserActionSerializer(AuthenticatedBasicUserActionMixin, AuthenticatedActionSerializer):
  732. user = serializers.PrimaryKeyRelatedField(
  733. queryset=models.User.objects.all(),
  734. error_messages={'does_not_exist': 'This user does not exist.'},
  735. pk_field=serializers.UUIDField()
  736. )
  737. reason = None
  738. class Meta:
  739. model = models.AuthenticatedBasicUserAction
  740. fields = AuthenticatedActionSerializer.Meta.fields + ('user',)
  741. @property
  742. def action_user(self):
  743. return self.instance.user
  744. @classmethod
  745. def build_and_save(cls, **kwargs):
  746. action = cls.Meta.model(**kwargs)
  747. return cls(action).save()
  748. class AuthenticatedBasicUserActionListSerializer(AuthenticatedBasicUserActionMixin, serializers.ListSerializer):
  749. @property
  750. def reason(self):
  751. return self.child.reason
  752. @property
  753. def action_user(self):
  754. user = self.instance[0].user
  755. if any(instance.user != user for instance in self.instance):
  756. raise ValueError('Actions must belong to the same user.')
  757. return user
  758. class AuthenticatedChangeOutreachPreferenceUserActionSerializer(AuthenticatedBasicUserActionSerializer):
  759. reason = 'change-outreach-preference'
  760. validity_period = None
  761. class Meta:
  762. model = models.AuthenticatedChangeOutreachPreferenceUserAction
  763. fields = AuthenticatedBasicUserActionSerializer.Meta.fields + ('outreach_preference',)
  764. class AuthenticatedActivateUserActionSerializer(AuthenticatedBasicUserActionSerializer):
  765. captcha = CaptchaSolutionSerializer(required=False)
  766. reason = 'activate-account'
  767. class Meta(AuthenticatedBasicUserActionSerializer.Meta):
  768. model = models.AuthenticatedActivateUserAction
  769. fields = AuthenticatedBasicUserActionSerializer.Meta.fields + ('captcha', 'domain',)
  770. extra_kwargs = {
  771. 'domain': {'default': None, 'allow_null': True}
  772. }
  773. def validate(self, attrs):
  774. try:
  775. attrs.pop('captcha') # remove captcha from internal value to avoid passing to Meta.model(**kwargs)
  776. except KeyError:
  777. if attrs['user'].needs_captcha:
  778. raise serializers.ValidationError({'captcha': fields.Field.default_error_messages['required']})
  779. return attrs
  780. class AuthenticatedChangeEmailUserActionSerializer(AuthenticatedBasicUserActionSerializer):
  781. new_email = serializers.EmailField(
  782. validators=[
  783. CustomFieldNameUniqueValidator(
  784. queryset=models.User.objects.all(),
  785. lookup_field='email',
  786. message='You already have another account with this email address.',
  787. )
  788. ],
  789. required=True,
  790. )
  791. reason = 'change-email'
  792. class Meta(AuthenticatedBasicUserActionSerializer.Meta):
  793. model = models.AuthenticatedChangeEmailUserAction
  794. fields = AuthenticatedBasicUserActionSerializer.Meta.fields + ('new_email',)
  795. def save(self):
  796. return super().save(recipient=self.instance.new_email)
  797. class AuthenticatedConfirmAccountUserActionSerializer(AuthenticatedBasicUserActionSerializer):
  798. reason = 'confirm-account'
  799. validity_period = timedelta(days=14)
  800. class Meta(AuthenticatedBasicUserActionSerializer.Meta):
  801. model = models.AuthenticatedNoopUserAction # confirmation happens during authentication, so nothing left to do
  802. class AuthenticatedResetPasswordUserActionSerializer(AuthenticatedBasicUserActionSerializer):
  803. new_password = serializers.CharField(write_only=True)
  804. reason = 'reset-password'
  805. class Meta(AuthenticatedBasicUserActionSerializer.Meta):
  806. model = models.AuthenticatedResetPasswordUserAction
  807. fields = AuthenticatedBasicUserActionSerializer.Meta.fields + ('new_password',)
  808. class AuthenticatedDeleteUserActionSerializer(AuthenticatedBasicUserActionSerializer):
  809. reason = 'delete-account'
  810. class Meta(AuthenticatedBasicUserActionSerializer.Meta):
  811. model = models.AuthenticatedDeleteUserAction
  812. class AuthenticatedDomainBasicUserActionSerializer(AuthenticatedBasicUserActionSerializer):
  813. domain = serializers.PrimaryKeyRelatedField(
  814. queryset=models.Domain.objects.all(),
  815. error_messages={'does_not_exist': 'This domain does not exist.'},
  816. )
  817. class Meta:
  818. model = models.AuthenticatedDomainBasicUserAction
  819. fields = AuthenticatedBasicUserActionSerializer.Meta.fields + ('domain',)
  820. class AuthenticatedRenewDomainBasicUserActionSerializer(AuthenticatedDomainBasicUserActionSerializer):
  821. reason = 'renew-domain'
  822. validity_period = None
  823. class Meta(AuthenticatedDomainBasicUserActionSerializer.Meta):
  824. model = models.AuthenticatedRenewDomainBasicUserAction
  825. list_serializer_class = AuthenticatedBasicUserActionListSerializer