test_rrsets.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  1. from ipaddress import IPv4Network
  2. import re
  3. from itertools import product
  4. from django.conf import settings
  5. from django.core.exceptions import ValidationError
  6. from django.core.management import call_command
  7. from rest_framework import status
  8. from desecapi.models import Domain, RRset, RR_SET_TYPES_AUTOMATIC, RR_SET_TYPES_UNSUPPORTED
  9. from desecapi.tests.base import DesecTestCase, AuthenticatedRRSetBaseTestCase
  10. class UnauthenticatedRRSetTestCase(DesecTestCase):
  11. def test_unauthorized_access(self):
  12. url = self.reverse('v1:rrsets', name='example.com')
  13. for method in [
  14. self.client.get,
  15. self.client.post,
  16. self.client.put,
  17. self.client.delete,
  18. self.client.patch
  19. ]:
  20. response = method(url)
  21. self.assertStatus(response, status.HTTP_401_UNAUTHORIZED)
  22. class AuthenticatedRRSetTestCase(AuthenticatedRRSetBaseTestCase):
  23. def test_subname_validity(self):
  24. for subname in [
  25. 'aEroport',
  26. 'AEROPORT',
  27. 'aéroport'
  28. ]:
  29. with self.assertRaises(ValidationError):
  30. RRset(domain=self.my_domain, subname=subname, ttl=60, type='A').save()
  31. RRset(domain=self.my_domain, subname='aeroport', ttl=60, type='A').save()
  32. def test_retrieve_my_rr_sets(self):
  33. for response in [
  34. self.client.get_rr_sets(self.my_domain.name),
  35. self.client.get_rr_sets(self.my_domain.name, subname=''),
  36. ]:
  37. self.assertStatus(response, status.HTTP_200_OK)
  38. self.assertEqual(len(response.data), 1, response.data)
  39. def test_retrieve_my_rr_sets_pagination(self):
  40. def convert_links(links):
  41. mapping = {}
  42. for link in links.split(', '):
  43. _url, label = link.split('; ')
  44. label = re.search('rel="(.*)"', label).group(1)
  45. _url = _url[1:-1]
  46. assert label not in mapping
  47. mapping[label] = _url
  48. return mapping
  49. def assertPaginationResponse(response, expected_length, expected_directional_links=[]):
  50. self.assertStatus(response, status.HTTP_200_OK)
  51. self.assertEqual(len(response.data), expected_length)
  52. _links = convert_links(response['Link'])
  53. self.assertEqual(len(_links), len(expected_directional_links) + 1) # directional links, plus "first"
  54. self.assertTrue(_links['first'].endswith('/?cursor='))
  55. for directional_link in expected_directional_links:
  56. self.assertEqual(_links['first'].find('/?cursor='), _links[directional_link].find('/?cursor='))
  57. self.assertTrue(len(_links[directional_link]) > len(_links['first']))
  58. # Prepare extra records so that we get three pages (total: n + 1)
  59. n = int(settings.REST_FRAMEWORK['PAGE_SIZE'] * 2.5)
  60. RRset.objects.bulk_create(
  61. [RRset(domain=self.my_domain, subname=str(i), ttl=123, type='A') for i in range(n)]
  62. )
  63. # No pagination
  64. response = self.client.get_rr_sets(self.my_domain.name)
  65. self.assertStatus(response, status.HTTP_400_BAD_REQUEST)
  66. self.assertEqual(response.data['detail'],
  67. f'Pagination required. You can query up to {settings.REST_FRAMEWORK["PAGE_SIZE"]} items at a time ({n+1} total). '
  68. 'Please use the `first` page link (see Link header).')
  69. links = convert_links(response['Link'])
  70. self.assertEqual(len(links), 1)
  71. self.assertTrue(links['first'].endswith('/?cursor='))
  72. # First page
  73. url = links['first']
  74. response = self.client.get(url)
  75. assertPaginationResponse(response, settings.REST_FRAMEWORK['PAGE_SIZE'], ['next'])
  76. # Next
  77. url = convert_links(response['Link'])['next']
  78. response = self.client.get(url)
  79. assertPaginationResponse(response, settings.REST_FRAMEWORK['PAGE_SIZE'], ['next', 'prev'])
  80. data_next = response.data.copy()
  81. # Next-next (last) page
  82. url = convert_links(response['Link'])['next']
  83. response = self.client.get(url)
  84. assertPaginationResponse(response, n/5 + 1, ['prev'])
  85. # Prev
  86. url = convert_links(response['Link'])['prev']
  87. response = self.client.get(url)
  88. assertPaginationResponse(response, settings.REST_FRAMEWORK['PAGE_SIZE'], ['next', 'prev'])
  89. # Make sure that one step forward equals two steps forward and one step back
  90. self.assertEqual(response.data, data_next)
  91. def test_retrieve_other_rr_sets(self):
  92. self.assertStatus(self.client.get_rr_sets(self.other_domain.name), status.HTTP_404_NOT_FOUND)
  93. self.assertStatus(self.client.get_rr_sets(self.other_domain.name, subname='test'), status.HTTP_404_NOT_FOUND)
  94. self.assertStatus(self.client.get_rr_sets(self.other_domain.name, type='A'), status.HTTP_404_NOT_FOUND)
  95. def test_retrieve_my_rr_sets_filter(self):
  96. response = self.client.get_rr_sets(self.my_rr_set_domain.name, query='?cursor=')
  97. self.assertStatus(response, status.HTTP_200_OK)
  98. expected_number_of_rrsets = min(len(self._test_rr_sets()), settings.REST_FRAMEWORK['PAGE_SIZE'])
  99. self.assertEqual(len(response.data), expected_number_of_rrsets)
  100. for subname in self.SUBNAMES:
  101. response = self.client.get_rr_sets(self.my_rr_set_domain.name, subname=subname)
  102. self.assertStatus(response, status.HTTP_200_OK)
  103. self.assertRRSetsCount(response.data, [dict(subname=subname)],
  104. count=len(self._test_rr_sets(subname=subname)))
  105. for type_ in self.ALLOWED_TYPES:
  106. response = self.client.get_rr_sets(self.my_rr_set_domain.name, type=type_)
  107. self.assertStatus(response, status.HTTP_200_OK)
  108. def test_create_my_rr_sets(self):
  109. for subname in [None, 'create-my-rr-sets', 'foo.create-my-rr-sets', 'bar.baz.foo.create-my-rr-sets']:
  110. for data in [
  111. {'subname': subname, 'records': ['1.2.3.4'], 'ttl': 3660, 'type': 'A'},
  112. {'subname': '' if subname is None else subname, 'records': ['desec.io.'], 'ttl': 36900, 'type': 'PTR'},
  113. {'subname': '' if subname is None else subname, 'ttl': 3650, 'type': 'TXT', 'records': ['"foo"']},
  114. ]:
  115. # Try POST with missing subname
  116. if data['subname'] is None:
  117. data.pop('subname')
  118. with self.assertPdnsRequests(self.requests_desec_rr_sets_update(name=self.my_empty_domain.name)):
  119. response = self.client.post_rr_set(domain_name=self.my_empty_domain.name, **data)
  120. self.assertTrue(all(field in response.data for field in
  121. ['created', 'domain', 'subname', 'name', 'records', 'ttl', 'type', 'touched']))
  122. self.assertEqual(self.my_empty_domain.touched,
  123. max(rrset.touched for rrset in self.my_empty_domain.rrset_set.all()))
  124. self.assertStatus(response, status.HTTP_201_CREATED)
  125. # Check for uniqueness on second attempt
  126. response = self.client.post_rr_set(domain_name=self.my_empty_domain.name, **data)
  127. self.assertContains(response, 'Another RRset with the same subdomain and type exists for this domain.',
  128. status_code=status.HTTP_400_BAD_REQUEST)
  129. response = self.client.get_rr_sets(self.my_empty_domain.name)
  130. self.assertStatus(response, status.HTTP_200_OK)
  131. self.assertRRSetsCount(response.data, [data])
  132. response = self.client.get_rr_set(self.my_empty_domain.name, data.get('subname', ''), data['type'])
  133. self.assertStatus(response, status.HTTP_200_OK)
  134. self.assertRRSet(response.data, **data)
  135. def test_create_my_rr_sets_type_restriction(self):
  136. for subname in ['', 'create-my-rr-sets', 'foo.create-my-rr-sets', 'bar.baz.foo.create-my-rr-sets']:
  137. for data in [
  138. {'subname': subname, 'ttl': 60, 'type': 'a'},
  139. {'subname': subname, 'records': ['10 example.com.'], 'ttl': 60, 'type': 'txt'}
  140. ] + [
  141. {'subname': subname, 'records': ['10 example.com.'], 'ttl': 60, 'type': type_}
  142. for type_ in self.UNSUPPORTED_TYPES
  143. ] + [
  144. {'subname': subname, 'records': ['set.an.example. get.desec.io. 2584 10800 3600 604800 60'],
  145. 'ttl': 60, 'type': type_}
  146. for type_ in self.AUTOMATIC_TYPES
  147. ]:
  148. response = self.client.post_rr_set(self.my_domain.name, **data)
  149. self.assertStatus(response, status.HTTP_400_BAD_REQUEST)
  150. response = self.client.get_rr_sets(self.my_domain.name)
  151. self.assertStatus(response, status.HTTP_200_OK)
  152. self.assertRRSetsCount(response.data, [data], count=0)
  153. def test_create_my_rr_sets_without_records(self):
  154. for subname in ['', 'create-my-rr-sets', 'foo.create-my-rr-sets', 'bar.baz.foo.create-my-rr-sets']:
  155. for data in [
  156. {'subname': subname, 'records': [], 'ttl': 60, 'type': 'A'},
  157. {'subname': subname, 'ttl': 60, 'type': 'A'},
  158. ]:
  159. response = self.client.post_rr_set(self.my_empty_domain.name, **data)
  160. self.assertStatus(
  161. response,
  162. status.HTTP_400_BAD_REQUEST
  163. )
  164. response = self.client.get_rr_sets(self.my_empty_domain.name)
  165. self.assertStatus(response, status.HTTP_200_OK)
  166. self.assertRRSetsCount(response.data, [], count=0)
  167. def test_create_other_rr_sets(self):
  168. data = {'records': ['1.2.3.4'], 'ttl': 60, 'type': 'A'}
  169. response = self.client.post_rr_set(self.other_domain.name, **data)
  170. self.assertStatus(response, status.HTTP_404_NOT_FOUND)
  171. @staticmethod
  172. def _create_test_txt_record(record, type_='TXT'):
  173. return {'records': [f'{record}'], 'ttl': 3600, 'type': type_, 'subname': f'name{len(record)}'}
  174. def test_create_my_rr_sets_chunk_too_long(self):
  175. for l, t in product([1, 255, 256, 498], ['TXT', 'SPF']):
  176. with self.assertPdnsRequests(self.requests_desec_rr_sets_update(self.my_empty_domain.name)):
  177. response = self.client.post_rr_set(
  178. self.my_empty_domain.name,
  179. **self._create_test_txt_record(f'"{"A" * l}"', t)
  180. )
  181. self.assertStatus(response, status.HTTP_201_CREATED)
  182. with self.assertPdnsRequests(self.requests_desec_rr_sets_update(self.my_empty_domain.name)):
  183. self.client.delete_rr_set(self.my_empty_domain.name, type_=t, subname=f'name{l+2}')
  184. def test_create_my_rr_sets_too_long_content(self):
  185. for t in ['SPF', 'TXT']:
  186. response = self.client.post_rr_set(
  187. self.my_empty_domain.name,
  188. # record of wire length 501 bytes in chunks of max 255 each (RFC 4408)
  189. **self._create_test_txt_record(f'"{"A" * 255}" "{"A" * 244}"', t)
  190. )
  191. self.assertStatus(response, status.HTTP_400_BAD_REQUEST)
  192. self.assertIn(
  193. 'Ensure this value has no more than 500 byte in wire format (it has 501).',
  194. str(response.data)
  195. )
  196. with self.assertPdnsRequests(self.requests_desec_rr_sets_update(self.my_empty_domain.name)):
  197. response = self.client.post_rr_set(
  198. self.my_empty_domain.name,
  199. # record of wire length 500 bytes in chunks of max 255 each (RFC 4408)
  200. ** self._create_test_txt_record(f'"{"A" * 255}" "{"A" * 243}"')
  201. )
  202. self.assertStatus(response, status.HTTP_201_CREATED)
  203. def test_create_my_rr_sets_too_large_rrset(self):
  204. network = IPv4Network('127.0.0.0/20') # size: 4096 IP addresses
  205. data = {'records': [str(ip) for ip in network], 'ttl': 3600, 'type': 'A', 'subname': 'name'}
  206. response = self.client.post_rr_set(self.my_empty_domain.name, **data)
  207. self.assertStatus(response, status.HTTP_400_BAD_REQUEST)
  208. excess_length = 28743 + len(self.my_empty_domain.name)
  209. self.assertIn(f'Total length of RRset exceeds limit by {excess_length} bytes.', str(response.data))
  210. def test_create_my_rr_sets_twice(self):
  211. data = {'records': ['1.2.3.4'], 'ttl': 3660, 'type': 'A'}
  212. with self.assertPdnsRequests(self.requests_desec_rr_sets_update(self.my_empty_domain.name)):
  213. response = self.client.post_rr_set(self.my_empty_domain.name, **data)
  214. self.assertStatus(response, status.HTTP_201_CREATED)
  215. data['records'][0] = '3.2.2.1'
  216. response = self.client.post_rr_set(self.my_empty_domain.name, **data)
  217. self.assertStatus(response, status.HTTP_400_BAD_REQUEST)
  218. def test_create_my_rr_sets_duplicate_content(self):
  219. for records in [
  220. ['127.0.0.1', '127.00.0.1'],
  221. # TODO add more examples
  222. ]:
  223. data = {'records': records, 'ttl': 3660, 'type': 'A'}
  224. response = self.client.post_rr_set(self.my_empty_domain.name, **data)
  225. self.assertContains(response, 'Duplicate', status_code=status.HTTP_400_BAD_REQUEST)
  226. def test_create_my_rr_sets_upper_case(self):
  227. for subname in ['asdF', 'cAse', 'asdf.FOO', '--F', 'ALLCAPS']:
  228. data = {'records': ['1.2.3.4'], 'ttl': 60, 'type': 'A', 'subname': subname}
  229. response = self.client.post_rr_set(self.my_empty_domain.name, **data)
  230. self.assertStatus(response, status.HTTP_400_BAD_REQUEST)
  231. self.assertIn('Subname can only use (lowercase)', str(response.data))
  232. def test_create_my_rr_sets_empty_payload(self):
  233. response = self.client.post_rr_set(self.my_empty_domain.name)
  234. self.assertContains(response, 'No data provided', status_code=status.HTTP_400_BAD_REQUEST)
  235. def test_create_my_rr_sets_canonical_content(self):
  236. # TODO fill in more examples
  237. datas = [
  238. # record type: (non-canonical input, canonical output expectation)
  239. ('A', ('127.0.000.1', '127.0.0.1')),
  240. ('AAAA', ('0000::0000:0001', '::1')),
  241. ('AFSDB', ('02 turquoise.FEMTO.edu.', '2 turquoise.femto.edu.')),
  242. ('CAA', ('0128 "issue" "letsencrypt.org"', '128 issue "letsencrypt.org"')),
  243. ('CERT', ('06 00 00 sadfdd==', '6 0 0 sadfdQ==')),
  244. ('CNAME', ('EXAMPLE.COM.', 'example.com.')),
  245. ('DHCID', ('xxxx', 'xxxx')),
  246. ('DLV', ('6454 8 2 5CBA665A006F6487625C6218522F09BD3673C25FA10F25CB18459AA1 0DF1F520',
  247. '6454 8 2 5CBA665A006F6487625C6218522F09BD3673C25FA10F25CB18459AA10DF1F520'.lower())),
  248. ('DLV', ('6454 8 2 5C BA665A006F6487625C6218522F09BD3673C25FA10F25CB18459AA1 0DF1F520',
  249. '6454 8 2 5CBA665A006F6487625C6218522F09BD3673C25FA10F25CB18459AA10DF1F520'.lower())),
  250. ('DS', ('6454 8 2 5CBA665A006F6487625C6218522F09BD3673C25FA10F25CB18459AA1 0DF1F520',
  251. '6454 8 2 5CBA665A006F6487625C6218522F09BD3673C25FA10F25CB18459AA10DF1F520'.lower())),
  252. ('DS', ('6454 8 2 5C BA665A006F6487625C6218522F09BD3673C25FA10F25CB18459AA1 0DF1F520',
  253. '6454 8 2 5CBA665A006F6487625C6218522F09BD3673C25FA10F25CB18459AA10DF1F520'.lower())),
  254. ('EUI48', ('AA-BB-CC-DD-EE-FF', 'aa-bb-cc-dd-ee-ff')),
  255. ('EUI64', ('AA-BB-CC-DD-EE-FF-aa-aa', 'aa-bb-cc-dd-ee-ff-aa-aa')),
  256. ('HINFO', ('cpu os', '"cpu" "os"')),
  257. ('HINFO', ('"cpu" "os"', '"cpu" "os"')),
  258. # ('IPSECKEY', ('01 00 02 . ASDFAA==', '1 0 2 . ASDFAF==')),
  259. # ('IPSECKEY', ('01 00 02 . 00000w==', '1 0 2 . 000000==')),
  260. ('KX', ('010 example.com.', '10 example.com.')),
  261. ('LOC', ('023 012 59 N 042 022 48.500 W 65.00m 20.00m 10.00m 10.00m',
  262. '23 12 59.000 N 42 22 48.500 W 65.00m 20.00m 10.00m 10.00m')),
  263. ('MX', ('10 010.1.1.1.', '10 010.1.1.1.')),
  264. ('MX', ('010 010.1.1.2.', '10 010.1.1.2.')),
  265. ('NAPTR', ('100 50 "s" "z3950+I2L+I2C" "" _z3950._tcp.gatech.edu.',
  266. '100 50 "s" "z3950+I2L+I2C" "" _z3950._tcp.gatech.edu.')),
  267. ('NS', ('EXaMPLE.COM.', 'example.com.')),
  268. ('OPENPGPKEY', ('mG8EXtVIsRMFK4EEACIDAwQSZPNqE4tS xLFJYhX+uabSgMrhOqUizJhkLx82',
  269. 'mG8EXtVIsRMFK4EEACIDAwQSZPNqE4tSxLFJYhX+uabSgMrhOqUizJhkLx82')),
  270. ('PTR', ('EXAMPLE.COM.', 'example.com.')),
  271. ('RP', ('hostmaster.EXAMPLE.com. .', 'hostmaster.example.com. .')),
  272. # ('SMIMEA', ('3 01 0 aaBBccddeeff', '3 1 0 aabbccddeeff')),
  273. ('SPF', ('"v=spf1 ip4:10.1" ".1.1 ip4:127" ".0.0.0/16 ip4:192.168.0.0/27 include:example.com -all"',
  274. '"v=spf1 ip4:10.1" ".1.1 ip4:127" ".0.0.0/16 ip4:192.168.0.0/27 include:example.com -all"')),
  275. ('SPF', ('"foo" "bar"', '"foo" "bar"')),
  276. ('SPF', ('"foobar"', '"foobar"')),
  277. ('SRV', ('0 000 0 .', '0 0 0 .')),
  278. # ('SRV', ('100 1 5061 EXAMPLE.com.', '100 1 5061 example.com.')), # TODO fixed in dnspython 5c58601
  279. ('SRV', ('100 1 5061 example.com.', '100 1 5061 example.com.')),
  280. ('SSHFP', ('2 2 aabbccEEddff', '2 2 aabbcceeddff')),
  281. ('TLSA', ('3 0001 1 000AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA', '3 1 1 000aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')),
  282. ('TXT', ('"foo" "bar"', '"foo" "bar"')),
  283. ('TXT', ('"foobar"', '"foobar"')),
  284. ('TXT', ('"foo" "" "bar"', '"foo" "" "bar"')),
  285. ('TXT', ('"" "" "foo" "" "bar"', '"" "" "foo" "" "bar"')),
  286. ('URI', ('10 01 "ftp://ftp1.example.com/public"', '10 1 "ftp://ftp1.example.com/public"')),
  287. ]
  288. for t, (record, canonical_record) in datas:
  289. if not record:
  290. continue
  291. data = {'records': [record], 'ttl': 3660, 'type': t, 'subname': ''}
  292. with self.assertPdnsRequests(self.requests_desec_rr_sets_update(name=self.my_empty_domain.name)):
  293. response = self.client.post_rr_set(self.my_empty_domain.name, **data)
  294. self.assertStatus(response, status.HTTP_201_CREATED)
  295. self.assertEqual(canonical_record, response.data['records'][0],
  296. f'For RR set type {t}, expected \'{canonical_record}\' to be the canonical form of '
  297. f'\'{record}\', but saw \'{response.data["records"][0]}\'.')
  298. with self.assertPdnsRequests(self.requests_desec_rr_sets_update(name=self.my_empty_domain.name)):
  299. response = self.client.delete_rr_set(self.my_empty_domain.name, subname='', type_=t)
  300. self.assertStatus(response, status.HTTP_204_NO_CONTENT)
  301. self.assertAllSupportedRRSetTypes(set(t for t, _ in datas))
  302. def test_create_my_rr_sets_known_type_benign(self):
  303. # TODO fill in more examples
  304. datas = {
  305. 'A': ['127.0.0.1', '127.0.0.2'],
  306. 'AAAA': ['::1', '::2'],
  307. 'AFSDB': ['2 turquoise.femto.edu.'],
  308. 'CAA': ['128 issue "letsencrypt.org"', '128 iodef "mailto:desec@example.com"', '1 issue "letsencrypt.org"'],
  309. 'CERT': ['6 0 0 sadfdd=='],
  310. 'CNAME': ['example.com.'],
  311. 'DHCID': ['aaaaaaaaaaaa', 'aa aaa aaaa a a a'],
  312. 'DLV': ['39556 13 1 aabbccddeeff'],
  313. 'DS': ['39556 13 1 aabbccddeeff'],
  314. 'EUI48': ['aa-bb-cc-dd-ee-ff', 'AA-BB-CC-DD-EE-FF'],
  315. 'EUI64': ['aa-bb-cc-dd-ee-ff-00-11', 'AA-BB-CC-DD-EE-FF-00-11'],
  316. 'HINFO': ['"ARMv8-A" "Linux"'],
  317. # 'IPSECKEY': ['12 0 2 . asdfdf==', '03 1 1 127.0.00.1 asdfdf==', '12 3 1 example.com. asdfdf==',],
  318. 'KX': ['4 example.com.', '28 io.'],
  319. 'LOC': ['23 12 59.000 N 42 22 48.500 W 65.00m 20.00m 10.00m 10.00m'],
  320. 'MX': ['10 example.com.', '20 1.1.1.1.'],
  321. 'NAPTR': ['100 50 "s" "z3950+I2L+I2C" "" _z3950._tcp.gatech.edu.'],
  322. 'NS': ['ns1.example.com.'],
  323. 'OPENPGPKEY': [
  324. 'mG8EXtVIsRMFK4EEACIDAwQSZPNqE4tSxLFJYhX+uabSgMrhOqUizJhkLx82', # key incomplete
  325. 'YWFh\xf0\x9f\x92\xa9YWFh', # valid as non-alphabet bytes will be ignored
  326. ],
  327. 'PTR': ['example.com.', '*.example.com.'],
  328. 'RP': ['hostmaster.example.com. .'],
  329. # 'SMIMEA': ['3 1 0 aabbccddeeff'],
  330. 'SPF': ['"v=spf1 include:example.com ~all"',
  331. '"v=spf1 ip4:10.1.1.1 ip4:127.0.0.0/16 ip4:192.168.0.0/27 include:example.com -all"',
  332. '"spf2.0/pra,mfrom ip6:2001:558:fe14:76:68:87:28:0/120 -all"'],
  333. 'SRV': ['0 0 0 .', '100 1 5061 example.com.'],
  334. 'SSHFP': ['2 2 aabbcceeddff'],
  335. 'TLSA': ['3 1 1 AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'],
  336. 'TXT': ['"foobar"', '"foo" "bar"', '"“红色联合”对“四·二八兵团”总部大楼的攻击已持续了两天"', '"new\\010line"'
  337. '"🧥 👚 👕 👖 👔 👗 👙 👘 👠 👡 👢 👞 👟 🥾 🥿 🧦 🧤 🧣 🎩 🧢 👒 🎓 ⛑ 👑 👝 👛 👜 💼 🎒 👓 🕶 🥽 🥼 🌂 🧵"'],
  338. 'URI': ['10 1 "ftp://ftp1.example.com/public"'],
  339. }
  340. self.assertAllSupportedRRSetTypes(set(datas.keys()))
  341. for t, records in datas.items():
  342. for r in records:
  343. data = {'records': [r], 'ttl': 3660, 'type': t, 'subname': ''}
  344. with self.assertPdnsRequests(self.requests_desec_rr_sets_update(name=self.my_empty_domain.name)):
  345. response = self.client.post_rr_set(self.my_empty_domain.name, **data)
  346. self.assertStatus(response, status.HTTP_201_CREATED)
  347. with self.assertPdnsRequests(self.requests_desec_rr_sets_update(name=self.my_empty_domain.name)):
  348. response = self.client.delete_rr_set(self.my_empty_domain.name, subname='', type_=t)
  349. self.assertStatus(response, status.HTTP_204_NO_CONTENT)
  350. def test_create_my_rr_sets_known_type_invalid(self):
  351. # TODO fill in more examples
  352. datas = {
  353. # recordtype: [list of examples expected to be rejected, individually]
  354. 'A': ['127.0.0.999', '127.0.0.256', '::1', 'foobar', '10.0.1', '10!'],
  355. 'AAAA': ['::g', '1:1:1:1:1:1:1:1:', '1:1:1:1:1:1:1:1:1'],
  356. 'AFSDB': ['example.com.', '1 1', '1 de'],
  357. 'CAA': ['43235 issue "letsencrypt.org"'],
  358. 'CERT': ['6 0 sadfdd=='],
  359. 'CNAME': ['example.com', '10 example.com.'],
  360. 'DHCID': ['x', 'xx', 'xxx'],
  361. 'DLV': ['-34 13 1 aabbccddeeff'],
  362. 'DS': ['-34 13 1 aabbccddeeff'],
  363. 'EUI48': ['aa-bb-ccdd-ee-ff', 'AA-BB-CC-DD-EE-GG'],
  364. 'EUI64': ['aa-bb-cc-dd-ee-ff-gg-11', 'AA-BB-C C-DD-EE-FF-00-11'],
  365. 'HINFO': ['"ARMv8-A"', f'"a" "{"b"*256}"'],
  366. # 'IPSECKEY': [],
  367. 'KX': ['-1 example.com', '10 example.com'],
  368. 'LOC': ['23 12 61.000 N 42 22 48.500 W 65.00m 20.00m 10.00m 10.00m', 'foo', '1.1.1.1'],
  369. 'MX': ['10 example.com', 'example.com.', '-5 asdf.', '65537 asdf.'],
  370. 'NAPTR': ['100 50 "s" "z3950+I2L+I2C" "" _z3950._tcp.gatech.edu',
  371. '100 50 "s" "" _z3950._tcp.gatech.edu.',
  372. '100 50 3 2 "z3950+I2L+I2C" "" _z3950._tcp.gatech.edu.'],
  373. 'NS': ['ns1.example.com', '127.0.0.1'],
  374. 'OPENPGPKEY': ['1 2 3'],
  375. 'PTR': ['"example.com."', '10 *.example.com.'],
  376. 'RP': ['hostmaster.example.com.', '10 foo.'],
  377. # 'SMIMEA': ['3 1 0 aGVsbG8gd29ybGQh'],
  378. 'SPF': ['"v=spf1', 'v=spf1 include:example.com ~all'],
  379. 'SRV': ['0 0 0 0', '100 5061 example.com.'],
  380. 'SSHFP': ['aabbcceeddff'],
  381. 'TLSA': ['3 1 1 AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'],
  382. 'TXT': ['foob"ar', 'v=spf1 include:example.com ~all', '"foo\nbar"', '"\x00" "NUL byte yo"'],
  383. 'URI': ['"1" "2" "3"'],
  384. }
  385. self.assertAllSupportedRRSetTypes(set(datas.keys()))
  386. for t, records in datas.items():
  387. for r in records:
  388. data = {'records': [r], 'ttl': 3660, 'type': t, 'subname': ''}
  389. response = self.client.post_rr_set(self.my_empty_domain.name, **data)
  390. self.assertNotContains(response, 'Duplicate', status_code=status.HTTP_400_BAD_REQUEST)
  391. def test_create_my_rr_sets_txt_splitting(self):
  392. for t in ['TXT', 'SPF']:
  393. for l in [200, 255, 256, 300, 400]:
  394. data = {'records': [f'"{"a"*l}"'], 'ttl': 3660, 'type': t, 'subname': f'x{l}'}
  395. with self.assertPdnsRequests(self.requests_desec_rr_sets_update(name=self.my_empty_domain.name)):
  396. response = self.client.post_rr_set(self.my_empty_domain.name, **data)
  397. self.assertStatus(response, status.HTTP_201_CREATED)
  398. response = self.client.get_rr_set(self.my_empty_domain.name, f'x{l}', t)
  399. num_tokens = response.data['records'][0].count(' ') + 1
  400. num_tokens_expected = l // 256 + 1
  401. self.assertEqual(num_tokens, num_tokens_expected,
  402. f'For a {t} record with a token of length of {l}, expected to see '
  403. f'{num_tokens_expected} tokens in the canonical format, but saw {num_tokens}.')
  404. self.assertEqual("".join(r.strip('" ') for r in response.data['records'][0]), 'a'*l)
  405. def test_create_my_rr_sets_unknown_type(self):
  406. for _type in ['AA', 'ASDF'] + list(RR_SET_TYPES_AUTOMATIC | RR_SET_TYPES_UNSUPPORTED):
  407. response = self.client.post_rr_set(self.my_domain.name, records=['1234'], ttl=3660, type=_type)
  408. self.assertContains(
  409. response,
  410. text='managed automatically' if _type in RR_SET_TYPES_AUTOMATIC else 'type is currently unsupported',
  411. status_code=status.HTTP_400_BAD_REQUEST
  412. )
  413. def test_create_my_rr_sets_insufficient_ttl(self):
  414. ttl = settings.MINIMUM_TTL_DEFAULT - 1
  415. response = self.client.post_rr_set(self.my_empty_domain.name, records=['1.2.3.4'], ttl=ttl, type='A')
  416. self.assertStatus(response, status.HTTP_400_BAD_REQUEST)
  417. detail = f'Ensure this value is greater than or equal to {self.my_empty_domain.minimum_ttl}.'
  418. self.assertEqual(response.data['ttl'][0], detail)
  419. ttl += 1
  420. with self.assertPdnsRequests(self.requests_desec_rr_sets_update(name=self.my_empty_domain.name)):
  421. response = self.client.post_rr_set(self.my_empty_domain.name, records=['1.2.23.4'], ttl=ttl, type='A')
  422. self.assertStatus(response, status.HTTP_201_CREATED)
  423. def test_retrieve_my_rr_sets_apex(self):
  424. response = self.client.get_rr_set(self.my_rr_set_domain.name, subname='', type_='A')
  425. self.assertStatus(response, status.HTTP_200_OK)
  426. self.assertEqual(response.data['records'][0], '1.2.3.4')
  427. self.assertEqual(response.data['ttl'], 3620)
  428. def test_retrieve_my_rr_sets_restricted_types(self):
  429. for type_ in self.AUTOMATIC_TYPES:
  430. response = self.client.get_rr_sets(self.my_domain.name, type=type_)
  431. self.assertStatus(response, status.HTTP_403_FORBIDDEN)
  432. response = self.client.get_rr_sets(self.my_domain.name, type=type_, subname='')
  433. self.assertStatus(response, status.HTTP_403_FORBIDDEN)
  434. def test_update_my_rr_sets(self):
  435. for subname in self.SUBNAMES:
  436. with self.assertPdnsRequests(self.requests_desec_rr_sets_update(name=self.my_rr_set_domain.name)):
  437. data = {'records': ['2.2.3.4'], 'ttl': 3630, 'type': 'A', 'subname': subname}
  438. response = self.client.put_rr_set(self.my_rr_set_domain.name, subname, 'A', data)
  439. self.assertStatus(response, status.HTTP_200_OK)
  440. response = self.client.get_rr_set(self.my_rr_set_domain.name, subname, 'A')
  441. self.assertStatus(response, status.HTTP_200_OK)
  442. self.assertEqual(response.data['records'], ['2.2.3.4'])
  443. self.assertEqual(response.data['ttl'], 3630)
  444. response = self.client.put_rr_set(self.my_rr_set_domain.name, subname, 'A', {'records': ['2.2.3.5']})
  445. self.assertStatus(response, status.HTTP_400_BAD_REQUEST)
  446. response = self.client.put_rr_set(self.my_rr_set_domain.name, subname, 'A', {'ttl': 3637})
  447. self.assertStatus(response, status.HTTP_400_BAD_REQUEST)
  448. def test_update_my_rr_set_with_invalid_payload_type(self):
  449. for subname in self.SUBNAMES:
  450. data = [{'records': ['2.2.3.4'], 'ttl': 30, 'type': 'A', 'subname': subname}]
  451. response = self.client.put_rr_set(self.my_rr_set_domain.name, subname, 'A', data)
  452. self.assertStatus(response, status.HTTP_400_BAD_REQUEST)
  453. self.assertEquals(response.data['non_field_errors'][0],
  454. 'Invalid data. Expected a dictionary, but got list.')
  455. data = 'foobar'
  456. response = self.client.put_rr_set(self.my_rr_set_domain.name, subname, 'A', data)
  457. self.assertStatus(response, status.HTTP_400_BAD_REQUEST)
  458. self.assertEquals(response.data['non_field_errors'][0],
  459. 'Invalid data. Expected a dictionary, but got str.')
  460. def test_partially_update_my_rr_sets(self):
  461. for subname in self.SUBNAMES:
  462. current_rr_set = self.client.get_rr_set(self.my_rr_set_domain.name, subname, 'A').data
  463. for data in [
  464. {'records': ['2.2.3.4'], 'ttl': 3630},
  465. {'records': ['3.2.3.4']},
  466. {'records': ['3.2.3.4', '9.8.8.7']},
  467. {'ttl': 3637},
  468. ]:
  469. with self.assertPdnsRequests(self.requests_desec_rr_sets_update(name=self.my_rr_set_domain.name)):
  470. response = self.client.patch_rr_set(self.my_rr_set_domain.name, subname, 'A', data)
  471. self.assertStatus(response, status.HTTP_200_OK)
  472. response = self.client.get_rr_set(self.my_rr_set_domain.name, subname, 'A')
  473. self.assertStatus(response, status.HTTP_200_OK)
  474. current_rr_set.update(data)
  475. self.assertEqual(response.data['records'], current_rr_set['records'])
  476. self.assertEqual(response.data['ttl'], current_rr_set['ttl'])
  477. response = self.client.patch_rr_set(self.my_rr_set_domain.name, subname, 'A', {})
  478. self.assertStatus(response, status.HTTP_200_OK)
  479. def test_rr_sets_touched_if_noop(self):
  480. for subname in self.SUBNAMES:
  481. touched_old = RRset.objects.get(domain=self.my_rr_set_domain, type='A', subname=subname).touched
  482. response = self.client.patch_rr_set(self.my_rr_set_domain.name, subname, 'A', {})
  483. self.assertStatus(response, status.HTTP_200_OK)
  484. touched_new = RRset.objects.get(domain=self.my_rr_set_domain, type='A', subname=subname).touched
  485. self.assertGreater(touched_new, touched_old)
  486. self.assertEqual(Domain.objects.get(name=self.my_rr_set_domain.name).touched, touched_new)
  487. def test_partially_update_other_rr_sets(self):
  488. data = {'records': ['3.2.3.4'], 'ttl': 334}
  489. for subname in self.SUBNAMES:
  490. response = self.client.patch_rr_set(self.other_rr_set_domain.name, subname, 'A', data)
  491. self.assertStatus(response, status.HTTP_404_NOT_FOUND)
  492. def test_update_other_rr_sets(self):
  493. data = {'ttl': 305}
  494. for subname in self.SUBNAMES:
  495. response = self.client.patch_rr_set(self.other_rr_set_domain.name, subname, 'A', data)
  496. self.assertStatus(response, status.HTTP_404_NOT_FOUND)
  497. def test_update_essential_properties(self):
  498. # Changing the subname is expected to cause an error
  499. url = self.reverse('v1:rrset', name=self.my_rr_set_domain.name, subname='test', type='A')
  500. data = {'records': ['3.2.3.4'], 'ttl': 3620, 'subname': 'test2', 'type': 'A'}
  501. response = self.client.patch(url, data)
  502. self.assertStatus(response, status.HTTP_400_BAD_REQUEST)
  503. self.assertEquals(response.data['subname'][0].code, 'read-only-on-update')
  504. response = self.client.put(url, data)
  505. self.assertStatus(response, status.HTTP_400_BAD_REQUEST)
  506. self.assertEquals(response.data['subname'][0].code, 'read-only-on-update')
  507. # Changing the type is expected to cause an error
  508. data = {'records': ['3.2.3.4'], 'ttl': 3620, 'subname': 'test', 'type': 'TXT'}
  509. response = self.client.patch(url, data)
  510. self.assertStatus(response, status.HTTP_400_BAD_REQUEST)
  511. self.assertEquals(response.data['type'][0].code, 'read-only-on-update')
  512. response = self.client.put(url, data)
  513. self.assertStatus(response, status.HTTP_400_BAD_REQUEST)
  514. self.assertEquals(response.data['type'][0].code, 'read-only-on-update')
  515. # Changing "created" is no-op
  516. response = self.client.get(url)
  517. data = response.data
  518. created = data['created']
  519. data['created'] = '2019-07-19T17:22:49.575717Z'
  520. response = self.client.patch(url, data)
  521. self.assertStatus(response, status.HTTP_200_OK)
  522. response = self.client.put(url, data)
  523. self.assertStatus(response, status.HTTP_200_OK)
  524. # Check that nothing changed
  525. response = self.client.get(url)
  526. self.assertStatus(response, status.HTTP_200_OK)
  527. self.assertEqual(response.data['records'][0], '2.2.3.4')
  528. self.assertEqual(response.data['ttl'], 3620)
  529. self.assertEqual(response.data['name'], 'test.' + self.my_rr_set_domain.name + '.')
  530. self.assertEqual(response.data['subname'], 'test')
  531. self.assertEqual(response.data['type'], 'A')
  532. self.assertEqual(response.data['created'], created)
  533. # This is expected to work, but the fields are ignored
  534. data = {'records': ['3.2.3.4'], 'name': 'example.com.', 'domain': 'example.com'}
  535. with self.assertPdnsRequests(self.requests_desec_rr_sets_update(name=self.my_rr_set_domain.name)):
  536. response = self.client.patch(url, data)
  537. self.assertStatus(response, status.HTTP_200_OK)
  538. response = self.client.get(url)
  539. self.assertStatus(response, status.HTTP_200_OK)
  540. self.assertEqual(response.data['records'][0], '3.2.3.4')
  541. self.assertEqual(response.data['domain'], self.my_rr_set_domain.name)
  542. self.assertEqual(response.data['name'], 'test.' + self.my_rr_set_domain.name + '.')
  543. def test_update_unknown_rrset(self):
  544. url = self.reverse('v1:rrset', name=self.my_rr_set_domain.name, subname='doesnotexist', type='A')
  545. data = {'records': ['3.2.3.4'], 'ttl': 3620}
  546. response = self.client.patch(url, data)
  547. self.assertStatus(response, status.HTTP_404_NOT_FOUND)
  548. response = self.client.put(url, data)
  549. self.assertStatus(response, status.HTTP_404_NOT_FOUND)
  550. def test_delete_my_rr_sets_with_patch(self):
  551. data = {'records': []}
  552. for subname in self.SUBNAMES:
  553. with self.assertPdnsRequests(self.requests_desec_rr_sets_update(name=self.my_rr_set_domain.name)):
  554. response = self.client.patch_rr_set(self.my_rr_set_domain.name, subname, 'A', data)
  555. self.assertStatus(response, status.HTTP_204_NO_CONTENT)
  556. # Deletion is only idempotent via DELETE. For PATCH/PUT, the view raises 404 if the instance does not
  557. # exist. By that time, the view has not parsed the payload yet and does not know it is a deletion.
  558. response = self.client.patch_rr_set(self.my_rr_set_domain.name, subname, 'A', data)
  559. self.assertStatus(response, status.HTTP_404_NOT_FOUND)
  560. response = self.client.get_rr_set(self.my_rr_set_domain.name, subname, 'A')
  561. self.assertStatus(response, status.HTTP_404_NOT_FOUND)
  562. def test_delete_my_rr_sets_with_delete(self):
  563. for subname in self.SUBNAMES:
  564. with self.assertPdnsRequests(self.requests_desec_rr_sets_update(name=self.my_rr_set_domain.name)):
  565. response = self.client.delete_rr_set(self.my_rr_set_domain.name, subname=subname, type_='A')
  566. self.assertStatus(response, status.HTTP_204_NO_CONTENT)
  567. domain = Domain.objects.get(name=self.my_rr_set_domain.name)
  568. self.assertEqual(domain.touched, domain.published)
  569. response = self.client.delete_rr_set(self.my_rr_set_domain.name, subname=subname, type_='A')
  570. self.assertStatus(response, status.HTTP_204_NO_CONTENT)
  571. response = self.client.get_rr_set(self.my_rr_set_domain.name, subname=subname, type_='A')
  572. self.assertStatus(response, status.HTTP_404_NOT_FOUND)
  573. def test_delete_other_rr_sets(self):
  574. data = {'records': []}
  575. for subname in self.SUBNAMES:
  576. # Try PATCH empty
  577. response = self.client.patch_rr_set(self.other_rr_set_domain.name, subname, 'A', data)
  578. self.assertStatus(response, status.HTTP_404_NOT_FOUND)
  579. # Try DELETE
  580. response = self.client.delete_rr_set(self.other_rr_set_domain.name, subname, 'A')
  581. self.assertStatus(response, status.HTTP_404_NOT_FOUND)
  582. # Make sure it actually is still there
  583. self.assertGreater(len(self.other_rr_set_domain.rrset_set.filter(subname=subname, type='A')), 0)
  584. def test_import_rr_sets(self):
  585. with self.assertPdnsRequests(self.request_pdns_zone_retrieve(name=self.my_domain.name)):
  586. call_command('sync-from-pdns', self.my_domain.name)
  587. for response in [
  588. self.client.get_rr_sets(self.my_domain.name),
  589. self.client.get_rr_sets(self.my_domain.name, subname=''),
  590. ]:
  591. self.assertStatus(response, status.HTTP_200_OK)
  592. self.assertEqual(len(response.data), 1, response.data)
  593. self.assertContainsRRSets(response.data, [dict(subname='', records=settings.DEFAULT_NS, type='NS')])