serializers.py 34 KB

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