serializers.py 40 KB

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