serializers.py 41 KB

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