serializers.py 34 KB

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