base.py 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024
  1. import base64
  2. import operator
  3. import random
  4. import re
  5. import string
  6. from contextlib import nullcontext
  7. from functools import partial, reduce
  8. from json import JSONDecodeError
  9. from typing import Union, List, Dict
  10. from unittest import mock
  11. from django.conf import settings
  12. from django.contrib.auth.hashers import check_password
  13. from django.db import connection
  14. from httpretty import httpretty, core as hr_core
  15. from rest_framework.reverse import reverse
  16. from rest_framework.test import APITestCase, APIClient
  17. from rest_framework.utils import json
  18. from desecapi.models import User, Domain, Token, RRset, RR, psl, RR_SET_TYPES_AUTOMATIC, RR_SET_TYPES_UNSUPPORTED, \
  19. RR_SET_TYPES_MANAGEABLE
  20. class DesecAPIClient(APIClient):
  21. @staticmethod
  22. def _http_header_base64_conversion(content):
  23. return base64.b64encode(content.encode()).decode()
  24. def set_credentials(self, authorization):
  25. self.credentials(HTTP_AUTHORIZATION=authorization)
  26. def set_credentials_basic_auth(self, part_1, part_2=None):
  27. if not part_1 and not part_2:
  28. self.set_credentials('')
  29. else:
  30. s = part_1 if not part_2 else '%s:%s' % (part_1, part_2)
  31. self.set_credentials('Basic ' + self._http_header_base64_conversion(s))
  32. def set_credentials_token_auth(self, token):
  33. if token is None:
  34. self.set_credentials('')
  35. else:
  36. self.set_credentials('Token ' + token)
  37. def __init__(self, *args, **kwargs):
  38. super().__init__(*args, **kwargs)
  39. self.reverse = DesecTestCase.reverse
  40. def bulk_patch_rr_sets(self, domain_name, payload):
  41. return self.patch(
  42. self.reverse('v1:rrsets', name=domain_name),
  43. payload,
  44. )
  45. def bulk_post_rr_sets(self, domain_name, payload):
  46. return self.post(
  47. self.reverse('v1:rrsets', name=domain_name),
  48. payload,
  49. )
  50. def bulk_put_rr_sets(self, domain_name, payload):
  51. return self.put(
  52. self.reverse('v1:rrsets', name=domain_name),
  53. payload,
  54. )
  55. def post_rr_set(self, domain_name, **kwargs):
  56. data = kwargs or None
  57. if data:
  58. data.setdefault('ttl', 60)
  59. return self.post(
  60. self.reverse('v1:rrsets', name=domain_name),
  61. data=data,
  62. )
  63. def get_rr_sets(self, domain_name, **kwargs):
  64. return self.get(
  65. self.reverse('v1:rrsets', name=domain_name) + kwargs.pop('query', ''),
  66. kwargs
  67. )
  68. def get_rr_set(self, domain_name, subname, type_):
  69. return self.get(
  70. self.reverse('v1:rrset@', name=domain_name, subname=subname, type=type_)
  71. )
  72. def put_rr_set(self, domain_name, subname, type_, data):
  73. return self.put(
  74. self.reverse('v1:rrset@', name=domain_name, subname=subname, type=type_),
  75. data
  76. )
  77. def patch_rr_set(self, domain_name, subname, type_, data):
  78. return self.patch(
  79. self.reverse('v1:rrset@', name=domain_name, subname=subname, type=type_),
  80. data
  81. )
  82. def delete_rr_set(self, domain_name, subname, type_):
  83. return self.delete(
  84. self.reverse('v1:rrset@', name=domain_name, subname=subname, type=type_)
  85. )
  86. # TODO add and use {post,get,delete,...}_domain
  87. class SQLiteReadUncommitted:
  88. def __init__(self):
  89. self.read_uncommitted = None
  90. def __enter__(self):
  91. with connection.cursor() as cursor:
  92. cursor.execute('PRAGMA read_uncommitted;')
  93. self.read_uncommitted = True if cursor.fetchone()[0] else False
  94. cursor.execute('PRAGMA read_uncommitted = true;')
  95. def __exit__(self, exc_type, exc_val, exc_tb):
  96. if self.read_uncommitted is None:
  97. return
  98. with connection.cursor() as cursor:
  99. if self.read_uncommitted:
  100. cursor.execute('PRAGMA read_uncommitted = true;')
  101. else:
  102. cursor.execute('PRAGMA read_uncommitted = false;')
  103. class AssertRequestsContextManager:
  104. """
  105. Checks that in its context, certain expected requests are made.
  106. """
  107. @classmethod
  108. def _flatten_nested_lists(cls, l):
  109. for i in l:
  110. if isinstance(i, list) or isinstance(i, tuple):
  111. yield from cls._flatten_nested_lists(i)
  112. else:
  113. yield i
  114. def __init__(self, test_case, expected_requests, single_expectation_single_request=True, expect_order=True):
  115. """
  116. Initialize a context that checks for made HTTP requests.
  117. Args:
  118. test_case: Test case in which this context lives. Used to fail test if observed requests do not meet
  119. expectations.
  120. expected_requests: (Possibly nested) list of requests, represented by kwarg-dictionaries for
  121. `httpretty.register_uri`.
  122. single_expectation_single_request: If True (default), each expected request needs to be matched by exactly
  123. one observed request.
  124. expect_order: If True (default), requests made are expected in order of expectations given.
  125. """
  126. self.test_case = test_case
  127. self.expected_requests = list(self._flatten_nested_lists(expected_requests))
  128. self.single_expectation_single_request = single_expectation_single_request
  129. self.expect_order = expect_order
  130. self.old_httpretty_entries = None
  131. def __enter__(self):
  132. hr_core.POTENTIAL_HTTP_PORTS.add(8081) # FIXME should depend on self.expected_requests
  133. # noinspection PyProtectedMember
  134. self.old_httpretty_entries = httpretty._entries.copy() # FIXME accessing private properties of httpretty
  135. for request in self.expected_requests:
  136. httpretty.register_uri(**request)
  137. @staticmethod
  138. def _find_matching_request(pattern, requests):
  139. for request in requests:
  140. if pattern['method'] == request[0] and pattern['uri'].match(request[1]):
  141. if pattern.get('payload') and pattern['payload'] not in request[2]:
  142. continue
  143. return request
  144. return None
  145. def __exit__(self, exc_type, exc_val, exc_tb):
  146. # organize seen requests in a primitive data structure
  147. seen_requests = [
  148. (r.command, 'http://%s%s' % (r.headers['Host'], r.path), r.parsed_body) for r in httpretty.latest_requests
  149. ]
  150. httpretty.reset()
  151. hr_core.POTENTIAL_HTTP_PORTS.add(8081) # FIXME should depend on self.expected_requests
  152. httpretty._entries = self.old_httpretty_entries
  153. unmatched_requests = seen_requests[:]
  154. # go through expected requests one by one
  155. requests_to_check = list(self.expected_requests)[:]
  156. while requests_to_check:
  157. request = requests_to_check.pop(0)
  158. # match request
  159. match = None
  160. if self.expect_order:
  161. if not self.single_expectation_single_request:
  162. raise ValueError(
  163. 'Checking of multiple (possibly zero) requests per expectation and checking of request '
  164. 'order simultaneously is not implemented, sorry.')
  165. if unmatched_requests:
  166. match = self._find_matching_request(request, [unmatched_requests[0]])
  167. else:
  168. match = self._find_matching_request(
  169. request, unmatched_requests if self.single_expectation_single_request else seen_requests)
  170. # check match
  171. if not match and self.single_expectation_single_request:
  172. self.test_case.fail(('Expected to see a %s request on\n\n%s,\n\nbut only saw these %i '
  173. 'requests:\n\n%s\n\nAll expected requests:\n\n%s\n\n'
  174. 'Hint: check for possible duplicates in your expectation.\n' +
  175. ('Hint: Is the expectation order correct?' if self.expect_order else '')) % (
  176. request['method'], request['uri'], len(seen_requests),
  177. '\n'.join(map(str, seen_requests)),
  178. '\n'.join(map(str, [(r['method'], r['uri']) for r in self.expected_requests])),
  179. ))
  180. if match:
  181. unmatched_requests.remove(match)
  182. # see if any requests were unexpected
  183. if unmatched_requests and self.single_expectation_single_request:
  184. self.test_case.fail('While waiting for %i request(s), we saw %i unexpected request(s). The unexpected '
  185. 'request(s) was/were:\n\n%s\n\nAll recorded requests:\n\n%s\n\nAll expected requests:'
  186. '\n\n%s' % (
  187. len(self.expected_requests),
  188. len(unmatched_requests),
  189. '\n'.join(map(str, unmatched_requests)),
  190. '\n'.join(map(str, seen_requests)),
  191. '\n'.join(map(str, [(r['method'], r['uri']) for r in self.expected_requests])),
  192. ))
  193. class MockPDNSTestCase(APITestCase):
  194. """
  195. This test case provides a "mocked Internet" environment with a mock pdns API interface. All internet connections,
  196. HTTP or otherwise, that this test case is unaware of will result in an exception.
  197. By default, requests are intercepted but unexpected will result in a failed test. To set pdns API request
  198. expectations, use the `with MockPDNSTestCase.assertPdns*` context managers.
  199. Subclasses may not touch httpretty.enable() or httpretty.disable(). For 'local' usage, httpretty.register_uri()
  200. and httpretty.reset() may be used.
  201. """
  202. PDNS_ZONES = r'/zones\?rrsets=false'
  203. PDNS_ZONE_CRYPTO_KEYS = r'/zones/(?P<id>[^/]+)/cryptokeys'
  204. PDNS_ZONE = r'/zones/(?P<id>[^/]+)'
  205. PDNS_ZONE_AXFR = r'/zones/(?P<id>[^/]+)/axfr-retrieve'
  206. @classmethod
  207. def get_full_pdns_url(cls, path_regex, ns='LORD', **kwargs):
  208. api = getattr(settings, 'NS%s_PDNS_API' % ns)
  209. return re.compile('^' + api + cls.fill_regex_groups(path_regex, **kwargs) + '$')
  210. @classmethod
  211. def fill_regex_groups(cls, template, **kwargs):
  212. s = template
  213. for name, value in kwargs.items():
  214. if value is None:
  215. continue
  216. pattern = r'\(\?P\<%s\>[^\)]+\)' % name
  217. if not re.search(pattern, s):
  218. raise ValueError('Tried to fill field %s in template %s, but it does not exist.' % (name, template))
  219. s = re.sub(
  220. pattern=pattern,
  221. repl=value,
  222. string=s,
  223. )
  224. return s
  225. @classmethod
  226. def _pdns_zone_id_heuristic(cls, name):
  227. """
  228. Returns an educated guess of the pdns zone id for a given zone name.
  229. """
  230. if not name:
  231. return None
  232. name = cls._normalize_name(name)
  233. return name.translate(str.maketrans({'/': '=2F', '_': '=5F'})) # make sure =5F is not lower-cased
  234. @classmethod
  235. def _normalize_name(cls, arg):
  236. if not arg:
  237. return None
  238. if not isinstance(arg, list):
  239. return cls._normalize_name([arg])[0]
  240. else:
  241. return [x.rstrip('.') + '.' for x in arg]
  242. @classmethod
  243. def request_pdns_zone_create(cls, ns, **kwargs):
  244. return {
  245. 'method': 'POST',
  246. 'uri': cls.get_full_pdns_url(cls.PDNS_ZONES, ns=ns),
  247. 'status': 201,
  248. 'body': '',
  249. 'match_querystring': True,
  250. **kwargs
  251. }
  252. def request_pdns_zone_create_assert_name(self, ns, name):
  253. def request_callback(r, _, response_headers):
  254. body = json.loads(r.parsed_body)
  255. self.failIf('name' not in body.keys(),
  256. 'pdns domain creation request malformed: did not contain a domain name.')
  257. try: # if an assertion fails, an exception is raised. We want to send a reply anyway!
  258. self.assertEqual(name, body['name'], 'Expected to see a domain creation request with name %s, '
  259. 'but name %s was sent.' % (name, body['name']))
  260. finally:
  261. return [201, response_headers, '']
  262. request = self.request_pdns_zone_create(ns)
  263. request.pop('status')
  264. # noinspection PyTypeChecker
  265. request['body'] = request_callback
  266. return request
  267. @classmethod
  268. def request_pdns_zone_create_422(cls):
  269. request = cls.request_pdns_zone_create(ns='LORD')
  270. request['status'] = 422
  271. return request
  272. @classmethod
  273. def request_pdns_zone_delete(cls, name=None, ns='LORD'):
  274. return {
  275. 'method': 'DELETE',
  276. 'uri': cls.get_full_pdns_url(cls.PDNS_ZONE, ns=ns, id=cls._pdns_zone_id_heuristic(name)),
  277. 'status': 200,
  278. 'body': '',
  279. }
  280. @classmethod
  281. def request_pdns_zone_update(cls, name=None):
  282. return {
  283. 'method': 'PATCH',
  284. 'uri': cls.get_full_pdns_url(cls.PDNS_ZONE, id=cls._pdns_zone_id_heuristic(name)),
  285. 'status': 200,
  286. 'body': '',
  287. }
  288. def request_pdns_zone_update_assert_body(self, name: str = None, updated_rr_sets: Union[List[RRset], Dict] = None):
  289. if updated_rr_sets is None:
  290. updated_rr_sets = []
  291. def request_callback(r, _, response_headers):
  292. if not updated_rr_sets:
  293. # nothing to assert
  294. return [200, response_headers, '']
  295. body = json.loads(r.parsed_body)
  296. self.failIf('rrsets' not in body.keys(),
  297. 'pdns zone update request malformed: did not contain a list of RR sets.')
  298. try: # if an assertion fails, an exception is raised. We want to send a reply anyway!
  299. with SQLiteReadUncommitted(): # tests are wrapped in uncommitted transactions, so we need to see inside
  300. # convert updated_rr_sets into a plain data type, if Django models were given
  301. if isinstance(updated_rr_sets, list):
  302. updated_rr_sets_dict = {}
  303. for rr_set in updated_rr_sets:
  304. updated_rr_sets_dict[(rr_set.type, rr_set.subname, rr_set.ttl)] = rrs = []
  305. for rr in rr_set.records.all():
  306. rrs.append(rr.content)
  307. elif isinstance(updated_rr_sets, dict):
  308. updated_rr_sets_dict = updated_rr_sets
  309. else:
  310. raise ValueError('updated_rr_sets must be a list of RRSets or a dict.')
  311. # check expectations
  312. self.assertEqual(len(updated_rr_sets_dict), len(body['rrsets']),
  313. 'Saw an unexpected number of RR set updates: expected %i, intercepted %i.' %
  314. (len(updated_rr_sets_dict), len(body['rrsets'])))
  315. for (exp_type, exp_subname, exp_ttl), exp_records in updated_rr_sets_dict.items():
  316. expected_name = '.'.join(filter(None, [exp_subname, name])) + '.'
  317. for seen_rr_set in body['rrsets']:
  318. if (expected_name == seen_rr_set['name'] and
  319. exp_type == seen_rr_set['type']):
  320. # TODO replace the following asserts by assertTTL, assertRecords, ... or similar
  321. if len(exp_records):
  322. self.assertEqual(exp_ttl, seen_rr_set['ttl'])
  323. self.assertEqual(
  324. set(exp_records),
  325. set([rr['content'] for rr in seen_rr_set['records']]),
  326. )
  327. break
  328. else:
  329. # we did not break out, i.e. we did not find a matching RR set in body['rrsets']
  330. self.fail('Expected to see an pdns zone update request for RR set of domain `%s` with name '
  331. '`%s` and type `%s`, but did not see one. Seen update request on %s for RR sets:'
  332. '\n\n%s'
  333. % (name, expected_name, exp_type, request['uri'],
  334. json.dumps(body['rrsets'], indent=4)))
  335. finally:
  336. return [200, response_headers, '']
  337. request = self.request_pdns_zone_update(name)
  338. request.pop('status')
  339. # noinspection PyTypeChecker
  340. request['body'] = request_callback
  341. return request
  342. @classmethod
  343. def request_pdns_zone_retrieve(cls, name=None):
  344. return {
  345. 'method': 'GET',
  346. 'uri': cls.get_full_pdns_url(cls.PDNS_ZONE, id=cls._pdns_zone_id_heuristic(name)),
  347. 'status': 200,
  348. 'body': json.dumps({
  349. 'rrsets': [{
  350. 'comments': [],
  351. 'name': cls._normalize_name(name) if name else 'test.mock.',
  352. 'ttl': 60,
  353. 'type': 'NS',
  354. 'records': [{'content': ns} for ns in settings.DEFAULT_NS],
  355. }]
  356. }),
  357. }
  358. @classmethod
  359. def request_pdns_zone_retrieve_crypto_keys(cls, name=None):
  360. return {
  361. 'method': 'GET',
  362. 'uri': cls.get_full_pdns_url(cls.PDNS_ZONE_CRYPTO_KEYS, id=cls._pdns_zone_id_heuristic(name)),
  363. 'status': 200,
  364. 'body': json.dumps([
  365. {
  366. 'active': True,
  367. 'algorithm': 'ECDSAP256SHA256',
  368. 'bits': 256,
  369. 'dnskey': '257 3 13 EVBcsqrnOp6RGWtsrr9QW8cUtt/'
  370. 'WI5C81RcCZDTGNI9elAiMQlxRdnic+7V+b7jJDE2vgY08qAbxiNh5NdzkzA==',
  371. 'ds': [
  372. '62745 13 1 642d70d9bb84903ca4c4ca08a6e4f1e9465aeaa6',
  373. '62745 13 2 5cddaeaa383e2ea7de49bd1212bf520228f0e3b334626517e5f6a68eb85b48f6',
  374. '62745 13 4 b3f2565901ddcb0b78337301cf863d1045774377bca05c7ad69e17a167734b92'
  375. '9f0a49b7edcca913eb6f5dfeac4645b8'
  376. ],
  377. 'flags': 257,
  378. 'id': 179425943,
  379. 'keytype': key_type,
  380. 'type': 'Cryptokey',
  381. }
  382. for key_type in ['csk', 'ksk', 'zsk']
  383. ])
  384. }
  385. @classmethod
  386. def request_pdns_zone_axfr(cls, name=None):
  387. return {
  388. 'method': 'PUT',
  389. 'uri': cls.get_full_pdns_url(cls.PDNS_ZONE_AXFR, ns='MASTER', id=cls._pdns_zone_id_heuristic(name)),
  390. 'status': 200,
  391. 'body': '',
  392. }
  393. @classmethod
  394. def request_pdns_update_catalog(cls):
  395. return {
  396. 'method': 'PATCH',
  397. 'uri': cls.get_full_pdns_url(cls.PDNS_ZONE, ns='MASTER', id=cls._pdns_zone_id_heuristic('catalog.internal')),
  398. 'status': 204,
  399. 'body': '',
  400. 'priority': 1, # avoid collision with DELETE zones/(?P<id>[^/]+)$ (httpretty does not match the method)
  401. }
  402. def assertPdnsRequests(self, *expected_requests, expect_order=True):
  403. """
  404. Assert the given requests are made. To build requests, use the `MockPDNSTestCase.request_*` functions.
  405. Unmet expectations will fail the test.
  406. Args:
  407. *expected_requests: List of expected requests.
  408. expect_order: If True (default), the order of observed requests is checked.
  409. """
  410. return AssertRequestsContextManager(
  411. test_case=self,
  412. expected_requests=expected_requests,
  413. expect_order=expect_order,
  414. )
  415. def assertPdnsNoRequestsBut(self, *expected_requests):
  416. """
  417. Assert no requests other than the given ones are made. Each request can be matched more than once, unmatched
  418. expectations WILL NOT fail the test.
  419. Args:
  420. *expected_requests: List of acceptable requests to be made.
  421. """
  422. return AssertRequestsContextManager(
  423. test_case=self,
  424. expected_requests=expected_requests,
  425. single_expectation_single_request=False,
  426. expect_order=False,
  427. )
  428. def assertPdnsZoneCreation(self):
  429. """
  430. Asserts that nslord is contact and a zone is created.
  431. """
  432. return AssertRequestsContextManager(
  433. test_case=self,
  434. expected_requests=[
  435. self.request_pdns_zone_create(ns='LORD'),
  436. self.request_pdns_zone_create(ns='MASTER')
  437. ],
  438. )
  439. def assertPdnsZoneDeletion(self, name=None):
  440. """
  441. Asserts that nslord and nsmaster are contacted to delete a zone.
  442. Args:
  443. name: If given, the test is restricted to the name of this zone.
  444. """
  445. return AssertRequestsContextManager(
  446. test_case=self,
  447. expected_requests=[
  448. self.request_pdns_zone_delete(ns='LORD', name=name),
  449. self.request_pdns_zone_delete(ns='MASTER', name=name),
  450. ],
  451. )
  452. def assertStatus(self, response, status):
  453. if response.status_code != status:
  454. self.fail((
  455. 'Expected a response with status %i, but saw response with status %i. ' +
  456. (
  457. '\n@@@@@ THE REQUEST CAUSING THIS RESPONSE WAS UNEXPECTED BY THE TEST @@@@@\n'
  458. if response.status_code == 599 else ''
  459. ) +
  460. 'The response was %s.\n'
  461. 'The response body was\n\n%s') % (
  462. status,
  463. response.status_code,
  464. response,
  465. str(response.data).replace('\\n', '\n') if hasattr(response, 'data') else '',
  466. ))
  467. def assertResponse(self, response, code=None, body=None):
  468. if code:
  469. self.assertStatus(response, code)
  470. if body:
  471. self.assertJSONEqual(response.content, body)
  472. def assertToken(self, plain, user=None):
  473. user = user or self.owner
  474. self.assertTrue(any(check_password(plain, hashed, preferred='pbkdf2_sha256_iter1')
  475. for hashed in Token.objects.filter(user=user).values_list('key', flat=True)))
  476. self.assertEqual(len(Token.make_hash(plain).split('$')), 4)
  477. @classmethod
  478. def setUpTestData(cls):
  479. httpretty.enable(allow_net_connect=False)
  480. httpretty.reset()
  481. hr_core.POTENTIAL_HTTP_PORTS.add(8081) # FIXME static dependency on settings variable
  482. for request in [
  483. cls.request_pdns_zone_create(ns='LORD'),
  484. cls.request_pdns_zone_create(ns='MASTER'),
  485. cls.request_pdns_zone_axfr(),
  486. cls.request_pdns_zone_update(),
  487. cls.request_pdns_zone_retrieve_crypto_keys(),
  488. cls.request_pdns_zone_retrieve()
  489. ]:
  490. httpretty.register_uri(**request)
  491. cls.setUpTestDataWithPdns()
  492. httpretty.reset()
  493. @classmethod
  494. def setUpTestDataWithPdns(cls):
  495. """
  496. Override this method to set up test data. During the run of this method, httpretty is configured to accept
  497. all pdns API requests.
  498. """
  499. pass
  500. @classmethod
  501. def tearDownClass(cls):
  502. super().tearDownClass()
  503. httpretty.disable()
  504. def setUp(self):
  505. def request_callback(r, _, response_headers):
  506. try:
  507. request = json.loads(r.parsed_body)
  508. except JSONDecodeError:
  509. request = r.parsed_body
  510. return [
  511. 599,
  512. response_headers,
  513. json.dumps(
  514. {
  515. 'MockPDNSTestCase': 'This response was generated upon an unexpected request.',
  516. 'request': request,
  517. 'method': str(r.method),
  518. 'requestline': str(r.raw_requestline),
  519. 'host': str(r.headers['Host']) if 'Host' in r.headers else None,
  520. 'headers': {str(key): str(value) for key, value in r.headers.items()},
  521. },
  522. indent=4
  523. )
  524. ]
  525. super().setUp()
  526. httpretty.reset()
  527. hr_core.POTENTIAL_HTTP_PORTS.add(8081) # FIXME should depend on self.expected_requests
  528. for method in [
  529. httpretty.GET, httpretty.PUT, httpretty.POST, httpretty.DELETE, httpretty.HEAD, httpretty.PATCH,
  530. httpretty.OPTIONS, httpretty.CONNECT
  531. ]:
  532. for ns in ['LORD', 'MASTER']:
  533. httpretty.register_uri(
  534. method,
  535. self.get_full_pdns_url('.*', ns),
  536. body=request_callback,
  537. status=599,
  538. priority=-100,
  539. )
  540. class DesecTestCase(MockPDNSTestCase):
  541. """
  542. This test case is run in the "standard" deSEC e.V. setting, i.e. with an API that is aware of the public suffix
  543. domains AUTO_DELEGATION_DOMAINS.
  544. The test case aims to be as close to the deployment as possible and may be extended as the deployment evolves.
  545. The test case provides an admin user and a regular user for testing.
  546. """
  547. client_class = DesecAPIClient
  548. AUTO_DELEGATION_DOMAINS = settings.LOCAL_PUBLIC_SUFFIXES
  549. PUBLIC_SUFFIXES = {'de', 'com', 'io', 'gov.cd', 'edu.ec', 'xxx', 'pinb.gov.pl', 'valer.ostfold.no',
  550. 'kota.aichi.jp', 's3.amazonaws.com', 'wildcard.ck'}
  551. SUPPORTED_RR_SET_TYPES = {'A', 'AAAA', 'AFSDB', 'APL', 'CAA', 'CERT', 'CNAME', 'DHCID', 'DLV', 'DS', 'EUI48',
  552. 'EUI64', 'HINFO', 'KX', 'LOC', 'MX', 'NAPTR', 'NS', 'OPENPGPKEY', 'PTR', 'RP',
  553. 'SMIMEA', 'SPF', 'SRV', 'SSHFP', 'TLSA', 'TXT', 'URI'}
  554. admin = None
  555. auto_delegation_domains = None
  556. user = None
  557. @classmethod
  558. def reverse(cls, view_name, **kwargs):
  559. return reverse(view_name, kwargs=kwargs)
  560. @classmethod
  561. def setUpTestDataWithPdns(cls):
  562. super().setUpTestDataWithPdns()
  563. random.seed(0xde5ec)
  564. cls.admin = cls.create_user(is_admin=True)
  565. cls.auto_delegation_domains = [cls.create_domain(name=name) for name in cls.AUTO_DELEGATION_DOMAINS]
  566. cls.user = cls.create_user()
  567. @classmethod
  568. def random_string(cls, length=6, chars=string.ascii_letters + string.digits):
  569. return ''.join(random.choice(chars) for _ in range(length))
  570. @classmethod
  571. def random_password(cls, length=12):
  572. return cls.random_string(
  573. length,
  574. chars=string.ascii_letters + string.digits + string.punctuation +
  575. 'some 💩🐬 UTF-8: “红色联合”对“四·二八兵团”总部大楼的攻击已持续了两天"'
  576. )
  577. @classmethod
  578. def random_ip(cls, proto=None):
  579. proto = proto or random.choice([4, 6])
  580. if proto == 4:
  581. return '.'.join([str(random.randrange(256)) for _ in range(4)])
  582. elif proto == 6:
  583. return '2001:' + ':'.join(['%x' % random.randrange(16**4) for _ in range(7)])
  584. else:
  585. raise ValueError('Unknown IP protocol version %s. Expected int 4 or int 6.' % str(proto))
  586. @classmethod
  587. def random_username(cls, host=None):
  588. host = host or cls.random_domain_name(cls.PUBLIC_SUFFIXES)
  589. return cls.random_string() + '+test@' + host.lower()
  590. @classmethod
  591. def random_domain_name(cls, suffix=None):
  592. if not suffix:
  593. suffix = cls.PUBLIC_SUFFIXES
  594. if isinstance(suffix, set):
  595. suffix = random.sample(suffix, 1)[0]
  596. return (random.choice(string.ascii_letters) + cls.random_string() + '--test' + '.' + suffix).lower()
  597. @classmethod
  598. def has_local_suffix(cls, domain_name: str):
  599. return any([domain_name.endswith(f'.{suffix}') for suffix in settings.LOCAL_PUBLIC_SUFFIXES])
  600. @classmethod
  601. def create_token(cls, user, name=''):
  602. token = Token.objects.create(user=user, name=name)
  603. token.save()
  604. return token
  605. @classmethod
  606. def create_user(cls, **kwargs):
  607. kwargs.setdefault('email', cls.random_username())
  608. user = User(**kwargs)
  609. user.plain_password = cls.random_string(length=12)
  610. user.set_password(user.plain_password)
  611. user.save()
  612. return user
  613. @classmethod
  614. def create_domain(cls, suffix=None, **kwargs):
  615. kwargs.setdefault('owner', cls.create_user())
  616. kwargs.setdefault('name', cls.random_domain_name(suffix))
  617. domain = Domain(**kwargs)
  618. domain.save()
  619. return domain
  620. @classmethod
  621. def create_rr_set(cls, domain, records, **kwargs):
  622. if isinstance(domain, str):
  623. domain = Domain.objects.get(name=domain)
  624. domain.save()
  625. rr_set = RRset(domain=domain, **kwargs)
  626. rr_set.save()
  627. for r in records:
  628. RR(content=r, rrset=rr_set).save()
  629. return rr_set
  630. @classmethod
  631. def _find_auto_delegation_zone(cls, name):
  632. if not name:
  633. return None
  634. parents = [parent for parent in cls.AUTO_DELEGATION_DOMAINS if name.endswith('.' + parent)]
  635. if not parents:
  636. raise ValueError('Could not find auto delegation zone for zone %s; searched in %s' % (
  637. name,
  638. cls.AUTO_DELEGATION_DOMAINS
  639. ))
  640. return parents[0]
  641. @classmethod
  642. def requests_desec_domain_creation(cls, name=None):
  643. soa_content = 'get.desec.io. get.desec.io. 1 86400 86400 2419200 3600'
  644. return [
  645. cls.request_pdns_zone_create(ns='LORD', payload=soa_content),
  646. cls.request_pdns_zone_create(ns='MASTER'),
  647. cls.request_pdns_update_catalog(),
  648. cls.request_pdns_zone_axfr(name=name),
  649. cls.request_pdns_zone_retrieve_crypto_keys(name=name),
  650. ]
  651. @classmethod
  652. def requests_desec_domain_deletion(cls, domain):
  653. requests = [
  654. cls.request_pdns_zone_delete(name=domain.name, ns='LORD'),
  655. cls.request_pdns_zone_delete(name=domain.name, ns='MASTER'),
  656. cls.request_pdns_update_catalog(),
  657. ]
  658. if domain.is_locally_registrable:
  659. delegate_at = cls._find_auto_delegation_zone(domain.name)
  660. requests += [
  661. cls.request_pdns_zone_update(name=delegate_at),
  662. cls.request_pdns_zone_axfr(name=delegate_at),
  663. ]
  664. return requests
  665. @classmethod
  666. def requests_desec_domain_creation_auto_delegation(cls, name=None):
  667. delegate_at = cls._find_auto_delegation_zone(name)
  668. return cls.requests_desec_domain_creation(name=name) + [
  669. cls.request_pdns_zone_update(name=delegate_at),
  670. cls.request_pdns_zone_axfr(name=delegate_at),
  671. ]
  672. @classmethod
  673. def requests_desec_rr_sets_update(cls, name=None):
  674. return [
  675. cls.request_pdns_zone_update(name=name),
  676. cls.request_pdns_zone_axfr(name=name),
  677. ]
  678. def assertRRSet(self, response_rr, domain=None, subname=None, records=None, type_=None, **kwargs):
  679. kwargs['domain'] = domain
  680. kwargs['subname'] = subname
  681. kwargs['records'] = records
  682. kwargs['type'] = type_
  683. for key, value in kwargs.items():
  684. if value is not None:
  685. self.assertEqual(
  686. response_rr[key], value,
  687. 'RR set did not have the expected %s: Expected "%s" but was "%s" in %s' % (
  688. key, value, response_rr[key], response_rr
  689. )
  690. )
  691. @staticmethod
  692. def _count_occurrences_by_mask(rr_sets, masks):
  693. def _cmp(key, a, b):
  694. if key == 'records':
  695. a = sorted(a)
  696. b = sorted(b)
  697. return a == b
  698. def _filter_rr_sets_by_mask(rr_sets_, mask):
  699. return [
  700. rr_set for rr_set in rr_sets_
  701. if reduce(operator.and_, [_cmp(key, rr_set.get(key, None), value) for key, value in mask.items()])
  702. ]
  703. return [len(_filter_rr_sets_by_mask(rr_sets, mask)) for mask in masks]
  704. def assertRRSetsCount(self, rr_sets, masks, count=1):
  705. actual_counts = self._count_occurrences_by_mask(rr_sets, masks)
  706. if not all([actual_count == count for actual_count in actual_counts]):
  707. self.fail('Expected to find %i RR set(s) for each of %s, but distribution is %s in %s.' % (
  708. count, masks, actual_counts, rr_sets
  709. ))
  710. def assertContainsRRSets(self, rr_sets_haystack, rr_sets_needle):
  711. if not all(self._count_occurrences_by_mask(rr_sets_haystack, rr_sets_needle)):
  712. self.fail('Expected to find RR sets with %s, but only got %s.' % (
  713. rr_sets_needle, rr_sets_haystack
  714. ))
  715. def assertContains(self, response, text, count=None, status_code=200, msg_prefix='', html=False):
  716. # convenience method to check the status separately, which yields nicer error messages
  717. self.assertStatus(response, status_code)
  718. # same for the substring check
  719. self.assertIn(text, response.content.decode(response.charset),
  720. f'Could not find {text} in the following response:\n{response.content.decode(response.charset)}')
  721. return super().assertContains(response, text, count, status_code, msg_prefix, html)
  722. def assertAllSupportedRRSetTypes(self, types):
  723. self.assertEqual(types, self.SUPPORTED_RR_SET_TYPES, 'Either some RR types given are unsupported, or not all '
  724. 'supported RR types were in the given set.')
  725. class PublicSuffixMockMixin():
  726. def _mock_get_public_suffix(self, domain_name, public_suffixes=None):
  727. if public_suffixes is None:
  728. public_suffixes = settings.LOCAL_PUBLIC_SUFFIXES | self.PUBLIC_SUFFIXES
  729. # Poor man's PSL interpreter. First, find all known suffixes covering the domain.
  730. suffixes = [suffix for suffix in public_suffixes
  731. if '.{}'.format(domain_name).endswith('.{}'.format(suffix))]
  732. # Also, consider TLD.
  733. suffixes += [domain_name.rsplit('.')[-1]]
  734. # Select the candidate with the most labels.
  735. return max(suffixes, key=lambda suffix: suffix.count('.'))
  736. @staticmethod
  737. def _mock_is_public_suffix(name):
  738. return name == psl.get_public_suffix(name)
  739. def get_psl_context_manager(self, side_effect_parameter):
  740. if side_effect_parameter is None:
  741. return nullcontext()
  742. if callable(side_effect_parameter):
  743. side_effect = side_effect_parameter
  744. else:
  745. side_effect = partial(
  746. self._mock_get_public_suffix,
  747. public_suffixes=[side_effect_parameter] if not isinstance(side_effect_parameter, list) else list(side_effect_parameter)
  748. )
  749. return mock.patch.object(psl, 'get_public_suffix', side_effect=side_effect)
  750. def setUpMockPatch(self):
  751. mock.patch.object(psl, 'get_public_suffix', side_effect=self._mock_get_public_suffix).start()
  752. mock.patch.object(psl, 'is_public_suffix', side_effect=self._mock_is_public_suffix).start()
  753. self.addCleanup(mock.patch.stopall)
  754. class DomainOwnerTestCase(DesecTestCase, PublicSuffixMockMixin):
  755. """
  756. This test case creates a domain owner, some domains for her and some domains that are owned by other users.
  757. DomainOwnerTestCase.client is authenticated with the owner's token.
  758. """
  759. DYN = False
  760. NUM_OWNED_DOMAINS = 2
  761. NUM_OTHER_DOMAINS = 20
  762. owner = None
  763. my_domains = None
  764. other_domains = None
  765. my_domain = None
  766. other_domain = None
  767. token = None
  768. @classmethod
  769. def setUpTestDataWithPdns(cls):
  770. super().setUpTestDataWithPdns()
  771. cls.owner = cls.create_user()
  772. domain_kwargs = {'suffix': cls.AUTO_DELEGATION_DOMAINS if cls.DYN else None}
  773. if cls.DYN:
  774. domain_kwargs['minimum_ttl'] = 60
  775. cls.my_domains = [
  776. cls.create_domain(owner=cls.owner, **domain_kwargs)
  777. for _ in range(cls.NUM_OWNED_DOMAINS)
  778. ]
  779. cls.other_domains = [
  780. cls.create_domain(**domain_kwargs)
  781. for _ in range(cls.NUM_OTHER_DOMAINS)
  782. ]
  783. if cls.DYN:
  784. for domain in cls.my_domains + cls.other_domains:
  785. parent_domain = Domain.objects.get(name=domain.parent_domain_name)
  786. parent_domain.update_delegation(domain)
  787. cls.my_domain = cls.my_domains[0]
  788. cls.other_domain = cls.other_domains[0]
  789. cls.create_rr_set(cls.my_domain, ['127.0.0.1', '127.0.1.1'], type='A', ttl=123)
  790. cls.create_rr_set(cls.other_domain, ['40.1.1.1', '40.2.2.2'], type='A', ttl=456)
  791. cls.token = cls.create_token(user=cls.owner)
  792. def setUp(self):
  793. super().setUp()
  794. self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token.plain)
  795. self.setUpMockPatch()
  796. class DynDomainOwnerTestCase(DomainOwnerTestCase):
  797. DYN = True
  798. @classmethod
  799. def request_pdns_zone_axfr(cls, name=None):
  800. return super().request_pdns_zone_axfr(name.lower() if name else None)
  801. @classmethod
  802. def request_pdns_zone_update(cls, name=None):
  803. return super().request_pdns_zone_update(name.lower() if name else None)
  804. def _assertDynDNS12Update(self, requests, mock_remote_addr='', **kwargs):
  805. with self.assertPdnsRequests(requests):
  806. if mock_remote_addr:
  807. return self.client.get(self.reverse('v1:dyndns12update'), kwargs, REMOTE_ADDR=mock_remote_addr)
  808. else:
  809. return self.client.get(self.reverse('v1:dyndns12update'), kwargs)
  810. def assertDynDNS12Update(self, domain_name=None, mock_remote_addr='', **kwargs):
  811. pdns_name = self._normalize_name(domain_name).lower() if domain_name else None
  812. return self._assertDynDNS12Update(
  813. [self.request_pdns_zone_update(name=pdns_name), self.request_pdns_zone_axfr(name=pdns_name)],
  814. mock_remote_addr,
  815. **kwargs
  816. )
  817. def assertDynDNS12NoUpdate(self, mock_remote_addr='', **kwargs):
  818. return self._assertDynDNS12Update([], mock_remote_addr, **kwargs)
  819. def setUp(self):
  820. super().setUp()
  821. self.client_token_authorized = self.client_class()
  822. self.client.set_credentials_basic_auth(self.my_domain.name.lower(), self.token.plain)
  823. self.client_token_authorized.set_credentials_token_auth(self.token.plain)
  824. class AuthenticatedRRSetBaseTestCase(DomainOwnerTestCase):
  825. UNSUPPORTED_TYPES = RR_SET_TYPES_UNSUPPORTED
  826. AUTOMATIC_TYPES = RR_SET_TYPES_AUTOMATIC
  827. ALLOWED_TYPES = RR_SET_TYPES_MANAGEABLE
  828. SUBNAMES = ['foo', 'bar.baz', 'q.w.e.r.t', '*', '*.foobar', '_', '-foo.test', '_bar']
  829. @classmethod
  830. def _test_rr_sets(cls, subname=None, type_=None, records=None, ttl=None):
  831. """
  832. Gives a list of example RR sets for testing.
  833. Args:
  834. subname: Filter by subname. None to allow any.
  835. type_: Filter by type. None to allow any.
  836. records: Filter by records. Must match exactly. None to allow any.
  837. ttl: Filter by ttl. None to allow any.
  838. Returns: Returns a list of tuples that represents example RR sets represented as 4-tuples consisting of
  839. subname, type_, records, ttl
  840. """
  841. # TODO add more examples of cls.ALLOWED_TYPES
  842. # NOTE The validity of the RRset contents it *not* verified. We currently leave this task to pdns.
  843. rr_sets = [
  844. ('', 'A', ['1.2.3.4'], 3620),
  845. ('test', 'A', ['2.2.3.4'], 3620),
  846. ('test', 'TXT', ['"foobar"'], 3620),
  847. ] + [
  848. (subname_, 'TXT', ['"hey ho, let\'s go!"'], 134)
  849. for subname_ in cls.SUBNAMES
  850. ] + [
  851. (subname_, type_, ['10 mx1.example.com.'], 101)
  852. for subname_ in cls.SUBNAMES
  853. for type_ in ['MX', 'SPF']
  854. ] + [
  855. (subname_, 'A', ['1.2.3.4'], 187)
  856. for subname_ in cls.SUBNAMES
  857. ]
  858. if subname or type_ or records or ttl:
  859. rr_sets = [
  860. rr_set for rr_set in rr_sets
  861. if (
  862. (subname is None or subname == rr_set[0]) and
  863. (type_ is None or type_ == rr_set[1]) and
  864. (records is None or records == rr_set[2]) and
  865. (ttl is None or ttl == rr_set[3])
  866. )
  867. ]
  868. return rr_sets
  869. @classmethod
  870. def setUpTestDataWithPdns(cls):
  871. super().setUpTestDataWithPdns()
  872. # TODO this test does not cover "dyn" / auto delegation domains
  873. cls.my_empty_domain = cls.create_domain(suffix='', owner=cls.owner)
  874. cls.my_rr_set_domain = cls.create_domain(suffix='', owner=cls.owner)
  875. cls.other_rr_set_domain = cls.create_domain(suffix='')
  876. for domain in [cls.my_rr_set_domain, cls.other_rr_set_domain]:
  877. for (subname, type_, records, ttl) in cls._test_rr_sets():
  878. cls.create_rr_set(domain, subname=subname, type=type_, records=records, ttl=ttl)