test_user_management.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820
  1. """
  2. This module tests deSEC's user management.
  3. The tests are separated into two categories, where
  4. (a) the client has an associated user account and
  5. (b) does not have an associated user account.
  6. This involves testing five separate endpoints:
  7. (1) Registration endpoint,
  8. (2) Reset password endpoint,
  9. (3) Change email address endpoint,
  10. (4) delete user endpoint, and
  11. (5) verify endpoint.
  12. """
  13. import random
  14. import re
  15. from unittest import mock
  16. from urllib.parse import urlparse
  17. from django.contrib.auth.hashers import is_password_usable
  18. from django.core import mail
  19. from django.urls import resolve
  20. from django.utils import timezone
  21. from rest_framework import status
  22. from rest_framework.reverse import reverse
  23. from rest_framework.test import APIClient
  24. from api import settings
  25. from desecapi.models import Domain, User, Captcha, Token
  26. from desecapi.serializers import AuthenticatedActionSerializer
  27. from desecapi.tests.base import DesecTestCase, PublicSuffixMockMixin
  28. class UserManagementClient(APIClient):
  29. def register(self, email, password, captcha_id, captcha_solution, **kwargs):
  30. return self.post(reverse('v1:register'), {
  31. 'email': email,
  32. 'password': password,
  33. 'captcha': {'id': captcha_id, 'solution': captcha_solution},
  34. **kwargs
  35. })
  36. def login_user(self, email, password):
  37. return self.post(reverse('v1:login'), {
  38. 'email': email,
  39. 'password': password,
  40. })
  41. def reset_password(self, email):
  42. return self.post(reverse('v1:account-reset-password'), {
  43. 'email': email,
  44. })
  45. def change_email(self, email, password, **payload):
  46. payload['email'] = email
  47. payload['password'] = password
  48. return self.post(reverse('v1:account-change-email'), payload)
  49. def change_email_token_auth(self, token, **payload):
  50. return self.post(reverse('v1:account-change-email'), payload, HTTP_AUTHORIZATION='Token {}'.format(token))
  51. def delete_account(self, email, password):
  52. return self.post(reverse('v1:account-delete'), {
  53. 'email': email,
  54. 'password': password,
  55. })
  56. def view_account(self, token):
  57. return self.get(reverse('v1:account'), HTTP_AUTHORIZATION='Token {}'.format(token))
  58. def verify(self, url, **kwargs):
  59. return self.post(url, kwargs) if kwargs else self.get(url)
  60. def obtain_captcha(self, **kwargs):
  61. return self.post(reverse('v1:captcha'))
  62. class UserManagementTestCase(DesecTestCase, PublicSuffixMockMixin):
  63. client_class = UserManagementClient
  64. password = None
  65. token = None
  66. def get_captcha(self):
  67. data = self.client.obtain_captcha().data
  68. id = data['id']
  69. solution = Captcha.objects.get(id=id).content
  70. return id, solution
  71. def register_user(self, email=None, password=None, **kwargs):
  72. email = email if email is not None else self.random_username()
  73. captcha_id, captcha_solution = self.get_captcha()
  74. return email.strip(), password, self.client.register(email, password, captcha_id, captcha_solution, **kwargs)
  75. def login_user(self, email, password):
  76. response = self.client.login_user(email, password)
  77. token = response.data.get('auth_token')
  78. return token, response
  79. def reset_password(self, email):
  80. return self.client.reset_password(email)
  81. def change_email(self, new_email):
  82. return self.client.change_email(self.email, self.password, new_email=new_email)
  83. def delete_account(self, email, password):
  84. return self.client.delete_account(email, password)
  85. def assertContains(self, response, text, count=None, status_code=200, msg_prefix='', html=False):
  86. msg_prefix += '\nResponse: %s' % response.data
  87. super().assertContains(response, text, count, status_code, msg_prefix, html)
  88. def assertPassword(self, email, password):
  89. if password is None:
  90. self.assertFalse(is_password_usable(User.objects.get(email=email).password))
  91. return
  92. password = password.strip()
  93. self.assertTrue(User.objects.get(email=email).check_password(password),
  94. 'Expected user password to be "%s" (potentially trimmed), but check failed.' % password)
  95. def assertUserExists(self, email):
  96. try:
  97. User.objects.get(email=email)
  98. except User.DoesNotExist:
  99. self.fail('Expected user %s to exist, but did not.' % email)
  100. def assertUserDoesNotExist(self, email):
  101. # noinspection PyTypeChecker
  102. with self.assertRaises(User.DoesNotExist):
  103. User.objects.get(email=email)
  104. def assertNoEmailSent(self):
  105. self.assertFalse(mail.outbox, "Expected no email to be sent, but %i were sent. First subject line is '%s'." %
  106. (len(mail.outbox), mail.outbox[0].subject if mail.outbox else '<n/a>'))
  107. def assertEmailSent(self, subject_contains='', body_contains='', recipient=None, reset=True, pattern=None):
  108. total = 1
  109. self.assertEqual(len(mail.outbox), total, "Expected %i message in the outbox, but found %i." %
  110. (total, len(mail.outbox)))
  111. email = mail.outbox[-1]
  112. self.assertTrue(subject_contains in email.subject,
  113. "Expected '%s' in the email subject, but found '%s'" %
  114. (subject_contains, email.subject))
  115. self.assertTrue(body_contains in email.body,
  116. "Expected '%s' in the email body, but found '%s'" %
  117. (body_contains, email.body))
  118. if recipient is not None:
  119. if isinstance(recipient, list):
  120. self.assertListEqual(recipient, email.recipients())
  121. else:
  122. self.assertIn(recipient, email.recipients())
  123. body = email.body
  124. if reset:
  125. mail.outbox = []
  126. return body if not pattern else re.search(pattern, body).group(1)
  127. def assertRegistrationEmail(self, recipient, reset=True):
  128. return self.assertEmailSent(
  129. subject_contains='deSEC',
  130. body_contains='Thank you for registering with deSEC!',
  131. recipient=[recipient],
  132. reset=reset,
  133. pattern=r'following link:\s+([^\s]*)',
  134. )
  135. def assertResetPasswordEmail(self, recipient, reset=True):
  136. return self.assertEmailSent(
  137. subject_contains='Password reset',
  138. body_contains='We received a request to reset the password for your deSEC account.',
  139. recipient=[recipient],
  140. reset=reset,
  141. pattern=r'following link:\s+([^\s]*)',
  142. )
  143. def assertChangeEmailVerificationEmail(self, recipient, reset=True):
  144. return self.assertEmailSent(
  145. subject_contains='Confirmation required: Email address change',
  146. body_contains='You requested to change the email address associated',
  147. recipient=[recipient],
  148. reset=reset,
  149. pattern=r'following link:\s+([^\s]*)',
  150. )
  151. def assertChangeEmailNotificationEmail(self, recipient, reset=True):
  152. return self.assertEmailSent(
  153. subject_contains='Account email address changed',
  154. body_contains='We\'re writing to let you know that the email address associated with',
  155. recipient=[recipient],
  156. reset=reset,
  157. )
  158. def assertDeleteAccountEmail(self, recipient, reset=True):
  159. return self.assertEmailSent(
  160. subject_contains='Confirmation required: Delete account',
  161. body_contains='confirm once more',
  162. recipient=[recipient],
  163. reset=reset,
  164. pattern=r'following link:\s+([^\s]*)',
  165. )
  166. def assertRegistrationSuccessResponse(self, response):
  167. return self.assertContains(
  168. response=response,
  169. text="Welcome! Please check your mailbox.",
  170. status_code=status.HTTP_202_ACCEPTED
  171. )
  172. def assertLoginSuccessResponse(self, response):
  173. return self.assertContains(
  174. response=response,
  175. text="auth_token",
  176. status_code=status.HTTP_200_OK
  177. )
  178. def assertRegistrationFailurePasswordRequiredResponse(self, response):
  179. self.assertContains(
  180. response=response,
  181. text="This field may not be blank",
  182. status_code=status.HTTP_400_BAD_REQUEST
  183. )
  184. self.assertEqual(response.data['password'][0].code, 'blank')
  185. def assertRegistrationFailureDomainUnavailableResponse(self, response, domain):
  186. self.assertContains(
  187. response=response,
  188. text='This domain name is unavailable',
  189. status_code=status.HTTP_400_BAD_REQUEST,
  190. msg_prefix=str(response.data)
  191. )
  192. def assertRegistrationFailureDomainInvalidResponse(self, response, domain):
  193. self.assertContains(
  194. response=response,
  195. text="Invalid value (not a DNS name)",
  196. status_code=status.HTTP_400_BAD_REQUEST,
  197. msg_prefix=str(response.data)
  198. )
  199. def assertRegistrationFailureCaptchaInvalidResponse(self, response):
  200. self.assertContains(
  201. response=response,
  202. text='CAPTCHA could not be validated. Please obtain a new one and try again.',
  203. status_code=status.HTTP_400_BAD_REQUEST,
  204. msg_prefix=str(response.data)
  205. )
  206. def assertRegistrationVerificationSuccessResponse(self, response):
  207. return self.assertContains(
  208. response=response,
  209. text="Success! Please log in at",
  210. status_code=status.HTTP_200_OK
  211. )
  212. def assertRegistrationWithDomainVerificationSuccessResponse(self, response, domain=None, email=None):
  213. if domain and self.has_local_suffix(domain):
  214. body = self.assertEmailSent('', body_contains=domain, recipient=email)
  215. self.assertTrue(any(token.key in body for token in Token.objects.filter(user__email=email).all()))
  216. text = 'Success! Here is the password'
  217. else:
  218. self.assertNoEmailSent()
  219. text = 'Success! Please check the docs for the next steps'
  220. self.assertContains(response=response, text=text, status_code=status.HTTP_200_OK)
  221. def assertResetPasswordSuccessResponse(self, response):
  222. return self.assertContains(
  223. response=response,
  224. text="Please check your mailbox for further password reset instructions.",
  225. status_code=status.HTTP_202_ACCEPTED
  226. )
  227. def assertResetPasswordVerificationSuccessResponse(self, response):
  228. return self.assertContains(
  229. response=response,
  230. text="Success! Your password has been changed.",
  231. status_code=status.HTTP_200_OK
  232. )
  233. def assertChangeEmailSuccessResponse(self, response):
  234. return self.assertContains(
  235. response=response,
  236. text="Please check your mailbox to confirm email address change.",
  237. status_code=status.HTTP_202_ACCEPTED
  238. )
  239. def assert401InvalidPasswordResponse(self, response):
  240. return self.assertContains(
  241. response=response,
  242. text="Invalid password.",
  243. status_code=status.HTTP_401_UNAUTHORIZED
  244. )
  245. def assertChangeEmailFailureAddressTakenResponse(self, response):
  246. return self.assertContains(
  247. response=response,
  248. text="You already have another account with this email address.",
  249. status_code=status.HTTP_400_BAD_REQUEST
  250. )
  251. def assertChangeEmailFailureSameAddressResponse(self, response):
  252. return self.assertContains(
  253. response=response,
  254. text="Email address unchanged.",
  255. status_code=status.HTTP_400_BAD_REQUEST
  256. )
  257. def assertChangeEmailVerificationSuccessResponse(self, response):
  258. return self.assertContains(
  259. response=response,
  260. text="Success! Your email address has been changed to",
  261. status_code=status.HTTP_200_OK
  262. )
  263. def assertChangeEmailVerificationFailureChangePasswordResponse(self, response):
  264. return self.assertContains(
  265. response=response,
  266. text="This field is not allowed for action ",
  267. status_code=status.HTTP_400_BAD_REQUEST
  268. )
  269. def assertDeleteAccountSuccessResponse(self, response):
  270. return self.assertContains(
  271. response=response,
  272. text="Please check your mailbox for further account deletion instructions.",
  273. status_code=status.HTTP_202_ACCEPTED
  274. )
  275. def assertDeleteAccountFailureStillHasDomainsResponse(self, response):
  276. return self.assertContains(
  277. response=response,
  278. text="To delete your user account, first delete all of your domains.",
  279. status_code=status.HTTP_409_CONFLICT
  280. )
  281. def assertDeleteAccountVerificationSuccessResponse(self, response):
  282. return self.assertContains(
  283. response=response,
  284. text="All your data has been deleted. Bye bye, see you soon! <3",
  285. status_code=status.HTTP_200_OK
  286. )
  287. def assertVerificationFailureInvalidCodeResponse(self, response):
  288. return self.assertContains(
  289. response=response,
  290. text="Bad signature.",
  291. status_code=status.HTTP_400_BAD_REQUEST
  292. )
  293. def assertVerificationFailureExpiredCodeResponse(self, response):
  294. return self.assertContains(
  295. response=response,
  296. text="Code expired",
  297. status_code=status.HTTP_400_BAD_REQUEST
  298. )
  299. def assertVerificationFailureUnknownUserResponse(self, response):
  300. return self.assertContains(
  301. response=response,
  302. text="This user does not exist.",
  303. status_code=status.HTTP_400_BAD_REQUEST
  304. )
  305. def _test_registration(self, email=None, password=None, **kwargs):
  306. email, password, response = self.register_user(email, password, **kwargs)
  307. self.assertRegistrationSuccessResponse(response)
  308. self.assertUserExists(email)
  309. self.assertFalse(User.objects.get(email=email).is_active)
  310. self.assertPassword(email, password)
  311. confirmation_link = self.assertRegistrationEmail(email)
  312. self.assertRegistrationVerificationSuccessResponse(self.client.verify(confirmation_link))
  313. self.assertTrue(User.objects.get(email=email).is_active)
  314. self.assertPassword(email, password)
  315. return email, password
  316. def _test_registration_with_domain(self, email=None, password=None, domain=None, expect_failure_response=None,
  317. tampered_domain=None, local=False):
  318. domain = domain or self.random_domain_name()
  319. email, password, response = self.register_user(email, password, domain=domain)
  320. if expect_failure_response:
  321. expect_failure_response(response, domain)
  322. self.assertUserDoesNotExist(email)
  323. return
  324. self.assertRegistrationSuccessResponse(response)
  325. self.assertUserExists(email)
  326. self.assertFalse(User.objects.get(email=email).is_active)
  327. self.assertPassword(email, password)
  328. confirmation_link = self.assertRegistrationEmail(email)
  329. if tampered_domain is not None:
  330. path = urlparse(confirmation_link).path
  331. code = resolve(path).kwargs.get('code')
  332. data = AuthenticatedActionSerializer._unpack_code(code)
  333. data['domain'] = tampered_domain
  334. tampered_code = AuthenticatedActionSerializer._pack_code(data)
  335. confirmation_link = confirmation_link.replace(code, tampered_code)
  336. response = self.client.verify(confirmation_link)
  337. self.assertVerificationFailureInvalidCodeResponse(response)
  338. return
  339. if self.has_local_suffix(domain):
  340. cm = self.requests_desec_domain_creation_auto_delegation(domain)
  341. else:
  342. cm = self.requests_desec_domain_creation(domain)
  343. with self.assertPdnsRequests(cm[:-1]):
  344. response = self.client.verify(confirmation_link)
  345. self.assertRegistrationWithDomainVerificationSuccessResponse(response, domain, email)
  346. self.assertTrue(User.objects.get(email=email).is_active)
  347. self.assertPassword(email, password)
  348. self.assertTrue(Domain.objects.filter(name=domain, owner__email=email).exists())
  349. return email, password, domain
  350. def _test_login(self):
  351. token, response = self.login_user(self.email, self.password)
  352. self.assertLoginSuccessResponse(response)
  353. return token
  354. def _test_reset_password(self, email, new_password=None, **kwargs):
  355. new_password = new_password or self.random_password()
  356. self.assertResetPasswordSuccessResponse(self.reset_password(email))
  357. confirmation_link = self.assertResetPasswordEmail(email)
  358. self.assertResetPasswordVerificationSuccessResponse(
  359. self.client.verify(confirmation_link, new_password=new_password, **kwargs))
  360. self.assertPassword(email, new_password)
  361. return new_password
  362. def _test_change_email(self):
  363. old_email = self.email
  364. new_email = ' {} '.format(self.random_username()) # test trimming
  365. self.assertChangeEmailSuccessResponse(self.change_email(new_email))
  366. new_email = new_email.strip()
  367. confirmation_link = self.assertChangeEmailVerificationEmail(new_email)
  368. self.assertChangeEmailVerificationSuccessResponse(self.client.verify(confirmation_link))
  369. self.assertChangeEmailNotificationEmail(old_email)
  370. self.assertUserExists(new_email)
  371. self.assertUserDoesNotExist(old_email)
  372. self.email = new_email
  373. return self.email
  374. def _test_delete_account(self, email, password):
  375. self.assertDeleteAccountSuccessResponse(self.delete_account(email, password))
  376. confirmation_link = self.assertDeleteAccountEmail(email)
  377. self.assertDeleteAccountVerificationSuccessResponse(self.client.verify(confirmation_link))
  378. self.assertUserDoesNotExist(email)
  379. class UserLifeCycleTestCase(UserManagementTestCase):
  380. def test_life_cycle(self):
  381. self.email, self.password = self._test_registration()
  382. self.password = self._test_reset_password(self.email)
  383. mail.outbox = []
  384. self.token = self._test_login()
  385. email = self._test_change_email()
  386. self._test_delete_account(email, self.password)
  387. class NoUserAccountTestCase(UserLifeCycleTestCase):
  388. def test_home(self):
  389. self.assertResponse(self.client.get(reverse('v1:root')), status.HTTP_200_OK)
  390. def test_registration(self):
  391. self._test_registration(password=self.random_password())
  392. def test_registration_trim_email(self):
  393. user_email = ' {} '.format(self.random_username())
  394. email, _ = self._test_registration(user_email)
  395. self.assertEqual(email, user_email.strip())
  396. def test_registration_with_domain(self):
  397. PublicSuffixMockMixin.setUpMockPatch(self)
  398. with self.get_psl_context_manager('.'):
  399. _, _, domain = self._test_registration_with_domain()
  400. self._test_registration_with_domain(domain=domain, expect_failure_response=self.assertRegistrationFailureDomainUnavailableResponse)
  401. self._test_registration_with_domain(domain='töö--', expect_failure_response=self.assertRegistrationFailureDomainInvalidResponse)
  402. with self.get_psl_context_manager('co.uk'):
  403. self._test_registration_with_domain(domain='co.uk', expect_failure_response=self.assertRegistrationFailureDomainUnavailableResponse)
  404. local_public_suffix = random.sample(self.AUTO_DELEGATION_DOMAINS, 1)[0]
  405. with self.get_psl_context_manager(local_public_suffix):
  406. self._test_registration_with_domain(domain=self.random_domain_name(suffix=local_public_suffix), local=True)
  407. def test_registration_with_tampered_domain(self):
  408. PublicSuffixMockMixin.setUpMockPatch(self)
  409. with self.get_psl_context_manager('.'):
  410. self._test_registration_with_domain(tampered_domain='evil.com')
  411. def test_registration_known_account(self):
  412. email, _ = self._test_registration()
  413. self.assertRegistrationSuccessResponse(self.register_user(email, self.random_password())[2])
  414. self.assertNoEmailSent()
  415. def test_registration_password_required(self):
  416. email = self.random_username()
  417. self.assertRegistrationFailurePasswordRequiredResponse(
  418. response=self.register_user(email=email, password='')[2]
  419. )
  420. self.assertNoEmailSent()
  421. self.assertUserDoesNotExist(email)
  422. def test_no_login_with_unusable_password(self):
  423. email, password = self._test_registration(password=None)
  424. response = self.client.login_user(email, password)
  425. self.assertStatus(response, status.HTTP_400_BAD_REQUEST)
  426. self.assertEqual(response.data['password'][0], 'This field may not be null.')
  427. def test_registration_spam_protection(self):
  428. email = self.random_username()
  429. self.assertRegistrationSuccessResponse(
  430. response=self.register_user(email=email)[2]
  431. )
  432. self.assertRegistrationEmail(email)
  433. for _ in range(5):
  434. self.assertRegistrationSuccessResponse(
  435. response=self.register_user(email=email)[2]
  436. )
  437. self.assertNoEmailSent()
  438. def test_registration_wrong_captcha(self):
  439. email = self.random_username()
  440. password = self.random_password()
  441. captcha_id, _ = self.get_captcha()
  442. self.assertRegistrationFailureCaptchaInvalidResponse(
  443. self.client.register(email, password, captcha_id, 'this is most definitely not a correct CAPTCHA solution')
  444. )
  445. class OtherUserAccountTestCase(UserManagementTestCase):
  446. def setUp(self):
  447. super().setUp()
  448. self.other_email, self.other_password = self._test_registration(password=self.random_password())
  449. def test_reset_password_unknown_user(self):
  450. self.assertResetPasswordSuccessResponse(
  451. response=self.reset_password(self.random_username())
  452. )
  453. self.assertNoEmailSent()
  454. class HasUserAccountTestCase(UserManagementTestCase):
  455. def __init__(self, methodName: str = ...) -> None:
  456. super().__init__(methodName)
  457. self.email = None
  458. self.password = None
  459. def setUp(self):
  460. super().setUp()
  461. self.email, self.password = self._test_registration(password=self.random_password())
  462. self.token = self._test_login()
  463. def _start_reset_password(self):
  464. self.assertResetPasswordSuccessResponse(
  465. response=self.reset_password(self.email)
  466. )
  467. return self.assertResetPasswordEmail(self.email)
  468. def _start_change_email(self):
  469. new_email = self.random_username()
  470. self.assertChangeEmailSuccessResponse(
  471. response=self.change_email(new_email)
  472. )
  473. return self.assertChangeEmailVerificationEmail(new_email), new_email
  474. def _start_delete_account(self):
  475. self.assertDeleteAccountSuccessResponse(self.delete_account(self.email, self.password))
  476. return self.assertDeleteAccountEmail(self.email)
  477. def _finish_reset_password(self, confirmation_link, expect_success=True):
  478. new_password = self.random_password()
  479. response = self.client.verify(confirmation_link, new_password=new_password)
  480. if expect_success:
  481. self.assertResetPasswordVerificationSuccessResponse(response=response)
  482. else:
  483. self.assertVerificationFailureInvalidCodeResponse(response)
  484. return new_password
  485. def _finish_change_email(self, confirmation_link, expect_success=True):
  486. response = self.client.verify(confirmation_link)
  487. if expect_success:
  488. self.assertChangeEmailVerificationSuccessResponse(response)
  489. self.assertChangeEmailNotificationEmail(self.email)
  490. else:
  491. self.assertVerificationFailureInvalidCodeResponse(response)
  492. def _finish_delete_account(self, confirmation_link):
  493. self.assertDeleteAccountVerificationSuccessResponse(self.client.verify(confirmation_link))
  494. self.assertUserDoesNotExist(self.email)
  495. def test_view_account(self):
  496. response = self.client.view_account(self.token)
  497. self.assertEqual(response.status_code, 200)
  498. self.assertTrue('created' in response.data)
  499. self.assertEqual(response.data['email'], self.email)
  500. self.assertEqual(response.data['id'], User.objects.get(email=self.email).pk)
  501. self.assertEqual(response.data['limit_domains'], settings.LIMIT_USER_DOMAIN_COUNT_DEFAULT)
  502. def test_view_account_read_only(self):
  503. # Should this test ever be removed (to allow writeable fields), make sure to
  504. # add new tests for each read-only field individually (such as limit_domains)!
  505. for method in [self.client.patch, self.client.put, self.client.post, self.client.delete]:
  506. response = method(
  507. reverse('v1:account'),
  508. {'limit_domains': 99},
  509. HTTP_AUTHORIZATION='Token {}'.format(self.token)
  510. )
  511. self.assertResponse(response, status.HTTP_405_METHOD_NOT_ALLOWED)
  512. def test_reset_password(self):
  513. self._test_reset_password(self.email)
  514. def test_reset_password_inactive_user(self):
  515. user = User.objects.get(email=self.email)
  516. user.is_active = False
  517. user.save()
  518. self.assertResetPasswordSuccessResponse(self.reset_password(self.email))
  519. self.assertNoEmailSent()
  520. def test_reset_password_multiple_times(self):
  521. for _ in range(3):
  522. self._test_reset_password(self.email)
  523. mail.outbox = []
  524. def test_reset_password_during_change_email_interleaved(self):
  525. reset_password_verification_code = self._start_reset_password()
  526. change_email_verification_code, new_email = self._start_change_email()
  527. new_password = self._finish_reset_password(reset_password_verification_code)
  528. self._finish_change_email(change_email_verification_code, expect_success=False)
  529. self.assertUserExists(self.email)
  530. self.assertUserDoesNotExist(new_email)
  531. self.assertPassword(self.email, new_password)
  532. def test_reset_password_during_change_email_nested(self):
  533. change_email_verification_code, new_email = self._start_change_email()
  534. reset_password_verification_code = self._start_reset_password()
  535. new_password = self._finish_reset_password(reset_password_verification_code)
  536. self._finish_change_email(change_email_verification_code, expect_success=False)
  537. self.assertUserExists(self.email)
  538. self.assertUserDoesNotExist(new_email)
  539. self.assertPassword(self.email, new_password)
  540. def test_reset_password_validation_unknown_user(self):
  541. confirmation_link = self._start_reset_password()
  542. self._test_delete_account(self.email, self.password)
  543. self.assertVerificationFailureUnknownUserResponse(
  544. response=self.client.verify(confirmation_link)
  545. )
  546. self.assertNoEmailSent()
  547. def test_change_email(self):
  548. self._test_change_email()
  549. def test_change_email_requires_password(self):
  550. # Make sure that the account's email address cannot be changed with a token (password required)
  551. new_email = self.random_username()
  552. response = self.client.change_email_token_auth(self.token, new_email=new_email)
  553. self.assertStatus(response, status.HTTP_400_BAD_REQUEST)
  554. self.assertEqual(response.data['email'][0], 'This field is required.')
  555. self.assertEqual(response.data['password'][0], 'This field is required.')
  556. self.assertNoEmailSent()
  557. def test_change_email_multiple_times(self):
  558. for _ in range(3):
  559. self._test_change_email()
  560. def test_change_email_user_exists(self):
  561. known_email, _ = self._test_registration()
  562. # We send a verification link to the new email and check account existence only later, upon verification
  563. self.assertChangeEmailSuccessResponse(
  564. response=self.change_email(known_email)
  565. )
  566. def test_change_email_verification_user_exists(self):
  567. new_email = self.random_username()
  568. self.assertChangeEmailSuccessResponse(self.change_email(new_email))
  569. confirmation_link = self.assertChangeEmailVerificationEmail(new_email)
  570. new_email, new_password = self._test_registration(new_email)
  571. self.assertChangeEmailFailureAddressTakenResponse(
  572. response=self.client.verify(confirmation_link)
  573. )
  574. self.assertUserExists(self.email)
  575. self.assertPassword(self.email, self.password)
  576. self.assertUserExists(new_email)
  577. self.assertPassword(new_email, new_password)
  578. def test_change_email_verification_change_password(self):
  579. new_email = self.random_username()
  580. self.assertChangeEmailSuccessResponse(self.change_email(new_email))
  581. confirmation_link = self.assertChangeEmailVerificationEmail(new_email)
  582. response = self.client.verify(confirmation_link, new_password=self.random_password())
  583. self.assertStatus(response, status.HTTP_405_METHOD_NOT_ALLOWED)
  584. def test_change_email_same_email(self):
  585. self.assertChangeEmailFailureSameAddressResponse(
  586. response=self.change_email(self.email)
  587. )
  588. self.assertUserExists(self.email)
  589. def test_change_email_during_reset_password_interleaved(self):
  590. change_email_verification_code, new_email = self._start_change_email()
  591. reset_password_verification_code = self._start_reset_password()
  592. self._finish_change_email(change_email_verification_code)
  593. self._finish_reset_password(reset_password_verification_code, expect_success=False)
  594. self.assertUserExists(new_email)
  595. self.assertUserDoesNotExist(self.email)
  596. self.assertPassword(new_email, self.password)
  597. def test_change_email_during_reset_password_nested(self):
  598. reset_password_verification_code = self._start_reset_password()
  599. change_email_verification_code, new_email = self._start_change_email()
  600. self._finish_change_email(change_email_verification_code)
  601. self._finish_reset_password(reset_password_verification_code, expect_success=False)
  602. self.assertUserExists(new_email)
  603. self.assertUserDoesNotExist(self.email)
  604. self.assertPassword(new_email, self.password)
  605. def test_change_email_nested(self):
  606. verification_code_1, new_email_1 = self._start_change_email()
  607. verification_code_2, new_email_2 = self._start_change_email()
  608. self._finish_change_email(verification_code_2)
  609. self.assertUserDoesNotExist(self.email)
  610. self.assertUserDoesNotExist(new_email_1)
  611. self.assertUserExists(new_email_2)
  612. self._finish_change_email(verification_code_1, expect_success=False)
  613. self.assertUserDoesNotExist(self.email)
  614. self.assertUserDoesNotExist(new_email_1)
  615. self.assertUserExists(new_email_2)
  616. def test_change_email_interleaved(self):
  617. verification_code_1, new_email_1 = self._start_change_email()
  618. verification_code_2, new_email_2 = self._start_change_email()
  619. self._finish_change_email(verification_code_1)
  620. self.assertUserDoesNotExist(self.email)
  621. self.assertUserExists(new_email_1)
  622. self.assertUserDoesNotExist(new_email_2)
  623. self._finish_change_email(verification_code_2, expect_success=False)
  624. self.assertUserDoesNotExist(self.email)
  625. self.assertUserExists(new_email_1)
  626. self.assertUserDoesNotExist(new_email_2)
  627. def test_change_email_validation_unknown_user(self):
  628. confirmation_link, new_email = self._start_change_email()
  629. self._test_delete_account(self.email, self.password)
  630. self.assertVerificationFailureUnknownUserResponse(
  631. response=self.client.verify(confirmation_link)
  632. )
  633. self.assertNoEmailSent()
  634. def test_delete_account_validation_unknown_user(self):
  635. confirmation_link = self._start_delete_account()
  636. self._test_delete_account(self.email, self.password)
  637. self.assertVerificationFailureUnknownUserResponse(
  638. response=self.client.verify(confirmation_link)
  639. )
  640. self.assertNoEmailSent()
  641. def test_delete_account_domains_present(self):
  642. user = User.objects.get(email=self.email)
  643. domain = self.create_domain(owner=user)
  644. self.assertDeleteAccountFailureStillHasDomainsResponse(self.delete_account(self.email, self.password))
  645. domain.delete()
  646. confirmation_link = self._start_delete_account()
  647. domain = self.create_domain(owner=user)
  648. self.assertDeleteAccountFailureStillHasDomainsResponse(response=self.client.verify(confirmation_link))
  649. domain.delete()
  650. self._finish_delete_account(confirmation_link)
  651. def test_reset_password_password_strip(self):
  652. password = ' %s ' % self.random_password()
  653. self._test_reset_password(self.email, password)
  654. self.assertPassword(self.email, password.strip())
  655. self.assertPassword(self.email, password)
  656. def test_reset_password_no_code_override(self):
  657. password = self.random_password()
  658. self._test_reset_password(self.email, password, code='foobar')
  659. self.assertPassword(self.email, password)
  660. def test_action_code_expired(self):
  661. self.assertResetPasswordSuccessResponse(self.reset_password(self.email))
  662. confirmation_link = self.assertResetPasswordEmail(self.email)
  663. with mock.patch('desecapi.models.timezone.now',
  664. return_value=timezone.now() + settings.VALIDITY_PERIOD_VERIFICATION_SIGNATURE):
  665. response = self.client.verify(confirmation_link, new_password=self.random_password())
  666. self.assertVerificationFailureExpiredCodeResponse(response)
  667. def test_action_code_confusion(self):
  668. # Obtain change password code
  669. self.assertResetPasswordSuccessResponse(self.reset_password(self.email))
  670. reset_password_link = self.assertResetPasswordEmail(self.email)
  671. path = urlparse(reset_password_link).path
  672. reset_password_code = resolve(path).kwargs.get('code')
  673. # Obtain deletion code
  674. self.assertDeleteAccountSuccessResponse(self.delete_account(self.email, self.password))
  675. delete_link = self.assertDeleteAccountEmail(self.email)
  676. path = urlparse(delete_link).path
  677. deletion_code = resolve(path).kwargs.get('code')
  678. # Swap codes
  679. self.assertNotEqual(reset_password_code, deletion_code)
  680. delete_link = delete_link.replace(deletion_code, reset_password_code)
  681. reset_password_link = reset_password_link.replace(reset_password_code, deletion_code)
  682. # Make sure links don't work
  683. self.assertVerificationFailureInvalidCodeResponse(self.client.verify(delete_link))
  684. self.assertVerificationFailureInvalidCodeResponse(self.client.verify(reset_password_link, new_password='dummy'))