test_views.py 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991
  1. import datetime
  2. import hashlib
  3. import io
  4. import logging
  5. import uuid
  6. from unittest.mock import PropertyMock, patch
  7. from django.contrib.contenttypes.models import ContentType
  8. from django.contrib.messages import get_messages
  9. from django.test import tag
  10. from django.urls import reverse
  11. from django.utils.html import escape
  12. from django.utils.timezone import now
  13. from core.choices import JobStatusChoices, ManagedFileRootPathChoices
  14. from core.events import *
  15. from core.models import DataFile, DataSource, Job, ObjectType
  16. from dcim.models import DeviceType, Manufacturer, Site
  17. from extras.choices import *
  18. from extras.models import *
  19. from extras.scripts import BooleanVar, IntegerVar, MultiChoiceVar, StringVar
  20. from extras.scripts import Script as PythonClass
  21. from netbox.choices import CSVDelimiterChoices, ImportFormatChoices
  22. from users.models import Group, ObjectPermission, User
  23. from utilities.testing import TestCase, ViewTestCases
  24. from utilities.views import get_action_url
  25. class CustomFieldTestCase(ViewTestCases.PrimaryObjectViewTestCase):
  26. model = CustomField
  27. @classmethod
  28. def setUpTestData(cls):
  29. site_type = ObjectType.objects.get_for_model(Site)
  30. CustomFieldChoiceSet.objects.create(
  31. name='Choice Set 1',
  32. extra_choices=(
  33. ('A', 'A'),
  34. ('B', 'B'),
  35. ('C', 'C'),
  36. )
  37. )
  38. custom_fields = (
  39. CustomField(name='field1', label='Field 1', type=CustomFieldTypeChoices.TYPE_TEXT),
  40. CustomField(name='field2', label='Field 2', type=CustomFieldTypeChoices.TYPE_TEXT),
  41. CustomField(name='field3', label='Field 3', type=CustomFieldTypeChoices.TYPE_TEXT),
  42. )
  43. for customfield in custom_fields:
  44. customfield.save()
  45. customfield.object_types.add(site_type)
  46. cls.form_data = {
  47. 'name': 'field_x',
  48. 'label': 'Field X',
  49. 'type': 'text',
  50. 'object_types': [site_type.pk],
  51. 'search_weight': 2000,
  52. 'filter_logic': CustomFieldFilterLogicChoices.FILTER_EXACT,
  53. 'default': None,
  54. 'weight': 200,
  55. 'required': True,
  56. 'ui_visible': CustomFieldUIVisibleChoices.ALWAYS,
  57. 'ui_editable': CustomFieldUIEditableChoices.YES,
  58. }
  59. cls.csv_data = (
  60. 'name,label,type,object_types,related_object_type,weight,search_weight,filter_logic,choice_set,validation_minimum,validation_maximum,validation_regex,ui_visible,ui_editable',
  61. 'field4,Field 4,text,dcim.site,,100,1000,exact,,,,[a-z]{3},always,yes',
  62. 'field5,Field 5,integer,dcim.site,,100,2000,exact,,1,100,,always,yes',
  63. 'field6,Field 6,select,dcim.site,,100,3000,exact,Choice Set 1,,,,always,yes',
  64. 'field7,Field 7,object,dcim.site,dcim.region,100,4000,exact,,,,,always,yes',
  65. )
  66. cls.csv_update_data = (
  67. 'id,label',
  68. f'{custom_fields[0].pk},New label 1',
  69. f'{custom_fields[1].pk},New label 2',
  70. f'{custom_fields[2].pk},New label 3',
  71. )
  72. cls.bulk_edit_data = {
  73. 'required': True,
  74. 'weight': 200,
  75. }
  76. def test_related_objects_links(self):
  77. """
  78. Check that each related object type links to its list view filtered on the custom field.
  79. """
  80. site_type = ObjectType.objects.get_for_model(Site)
  81. cf_exact = CustomField.objects.create(
  82. name='cf_exact', type=CustomFieldTypeChoices.TYPE_TEXT,
  83. filter_logic=CustomFieldFilterLogicChoices.FILTER_EXACT
  84. )
  85. cf_loose = CustomField.objects.create(
  86. name='cf_loose', type=CustomFieldTypeChoices.TYPE_TEXT,
  87. filter_logic=CustomFieldFilterLogicChoices.FILTER_LOOSE
  88. )
  89. cf_disabled = CustomField.objects.create(
  90. name='cf_disabled', type=CustomFieldTypeChoices.TYPE_TEXT,
  91. filter_logic=CustomFieldFilterLogicChoices.FILTER_DISABLED
  92. )
  93. for cf in (cf_exact, cf_loose, cf_disabled):
  94. cf.object_types.add(site_type)
  95. Site.objects.create(
  96. name='Site 1', slug='site-1',
  97. custom_field_data={'cf_exact': 'foo', 'cf_loose': 'foo', 'cf_disabled': 'bar'}
  98. )
  99. self.add_permissions('extras.view_customfield', 'dcim.view_site')
  100. list_url = reverse('dcim:site_list')
  101. for cf in (cf_exact, cf_loose):
  102. response = self.client.get(cf.get_absolute_url())
  103. self.assertHttpStatus(response, 200)
  104. self.assertContains(response, f'href="{list_url}?cf_{cf.name}__empty=false"')
  105. # No link is rendered when filtering is disabled for the custom field
  106. response = self.client.get(cf_disabled.get_absolute_url())
  107. self.assertHttpStatus(response, 200)
  108. self.assertNotContains(response, f'href="{list_url}?cf_cf_disabled__empty')
  109. def test_related_objects_links_without_view_permission(self):
  110. """
  111. Check that no link is rendered for a related object type the user cannot view.
  112. """
  113. cf = CustomField.objects.create(
  114. name='cf_exact', type=CustomFieldTypeChoices.TYPE_TEXT,
  115. filter_logic=CustomFieldFilterLogicChoices.FILTER_EXACT
  116. )
  117. cf.object_types.add(ObjectType.objects.get_for_model(Site))
  118. self.add_permissions('extras.view_customfield')
  119. response = self.client.get(cf.get_absolute_url())
  120. self.assertHttpStatus(response, 200)
  121. self.assertNotContains(response, f'href="{reverse("dcim:site_list")}?cf_cf_exact__empty')
  122. class CustomFieldChoiceSetTestCase(ViewTestCases.PrimaryObjectViewTestCase):
  123. model = CustomFieldChoiceSet
  124. @classmethod
  125. def setUpTestData(cls):
  126. choice_sets = (
  127. CustomFieldChoiceSet(
  128. name='Choice Set 1',
  129. extra_choices=(('A1', 'Choice 1'), ('A2', 'Choice 2'), ('A3', 'Choice 3'))
  130. ),
  131. CustomFieldChoiceSet(
  132. name='Choice Set 2',
  133. extra_choices=(('B1', 'Choice 1'), ('B2', 'Choice 2'), ('B3', 'Choice 3'))
  134. ),
  135. CustomFieldChoiceSet(
  136. name='Choice Set 3',
  137. extra_choices=(('C1', 'Choice 1'), ('C2', 'Choice 2'), ('C3', 'Choice 3'))
  138. ),
  139. CustomFieldChoiceSet(
  140. name='Choice Set 4',
  141. extra_choices=(('D1', 'Choice 1'), ('D2', 'Choice 2'), ('D3', 'Choice 3'))
  142. ),
  143. )
  144. CustomFieldChoiceSet.objects.bulk_create(choice_sets)
  145. cls.form_data = {
  146. 'name': 'Choice Set X',
  147. 'extra_choices': '\n'.join(['X1:Choice 1', 'X2:Choice 2', 'X3:Choice 3'])
  148. }
  149. cls.csv_data = (
  150. 'name,extra_choices',
  151. 'Choice Set 5,"D1,D2,D3"',
  152. 'Choice Set 6,"E1,E2,E3"',
  153. 'Choice Set 7,"F1,F2,F3"',
  154. 'Choice Set 8,"F1:L1,F2:L2,F3:L3"',
  155. )
  156. cls.csv_update_data = (
  157. 'id,extra_choices',
  158. f'{choice_sets[0].pk},"A,B,C"',
  159. f'{choice_sets[1].pk},"A,B,C"',
  160. f'{choice_sets[2].pk},"A,B,C"',
  161. f'{choice_sets[3].pk},"A:L1,B:L2,C:L3"',
  162. )
  163. cls.bulk_edit_data = {
  164. 'description': 'New description',
  165. }
  166. # This is here as extra_choices field splits on colon, but is returned
  167. # from DB as comma separated.
  168. def assertInstanceEqual(self, instance, data, exclude=None, api=False):
  169. if 'extra_choices' in data:
  170. data['extra_choices'] = data['extra_choices'].replace(':', ',')
  171. return super().assertInstanceEqual(instance, data, exclude, api)
  172. class CustomLinkTestCase(ViewTestCases.PrimaryObjectViewTestCase):
  173. model = CustomLink
  174. @classmethod
  175. def setUpTestData(cls):
  176. site_type = ObjectType.objects.get_for_model(Site)
  177. custom_links = (
  178. CustomLink(name='Custom Link 1', enabled=True, link_text='Link 1', link_url='http://example.com/?1'),
  179. CustomLink(name='Custom Link 2', enabled=True, link_text='Link 2', link_url='http://example.com/?2'),
  180. CustomLink(name='Custom Link 3', enabled=False, link_text='Link 3', link_url='http://example.com/?3'),
  181. )
  182. CustomLink.objects.bulk_create(custom_links)
  183. for i, custom_link in enumerate(custom_links):
  184. custom_link.object_types.set([site_type])
  185. cls.form_data = {
  186. 'name': 'Custom Link X',
  187. 'object_types': [site_type.pk],
  188. 'enabled': False,
  189. 'weight': 100,
  190. 'button_class': CustomLinkButtonClassChoices.DEFAULT,
  191. 'link_text': 'Link X',
  192. 'link_url': 'http://example.com/?x'
  193. }
  194. cls.csv_data = (
  195. "name,object_types,enabled,weight,button_class,link_text,link_url",
  196. "Custom Link 4,dcim.site,True,100,blue,Link 4,http://exmaple.com/?4",
  197. "Custom Link 5,dcim.site,True,100,blue,Link 5,http://exmaple.com/?5",
  198. "Custom Link 6,dcim.site,False,100,blue,Link 6,http://exmaple.com/?6",
  199. )
  200. cls.csv_update_data = (
  201. "id,name",
  202. f"{custom_links[0].pk},Custom Link 7",
  203. f"{custom_links[1].pk},Custom Link 8",
  204. f"{custom_links[2].pk},Custom Link 9",
  205. )
  206. cls.bulk_edit_data = {
  207. 'button_class': CustomLinkButtonClassChoices.CYAN,
  208. 'enabled': False,
  209. 'weight': 200,
  210. }
  211. class CustomLinkRenderingTestCase(TestCase):
  212. user_permissions = ['dcim.view_site', 'extras.view_customlink']
  213. def test_view_object_with_custom_link(self):
  214. customlink = CustomLink(
  215. name='Test',
  216. link_text='FOO {{ object.name }} BAR',
  217. link_url='http://example.com/?site={{ object.slug }}',
  218. new_window=False
  219. )
  220. customlink.save()
  221. customlink.object_types.set([ObjectType.objects.get_for_model(Site)])
  222. site = Site(name='Test Site', slug='test-site')
  223. site.save()
  224. response = self.client.get(site.get_absolute_url(), follow=True)
  225. self.assertEqual(response.status_code, 200)
  226. self.assertIn(f'FOO {site.name} BAR', str(response.content))
  227. def test_list_view_custom_link_column(self):
  228. # A custom link column must render in the list view when the user can view the CustomLink.
  229. customlink = CustomLink(
  230. name='Test',
  231. link_text='FOO {{ object.name }} BAR',
  232. link_url='http://example.com/?site={{ object.slug }}',
  233. new_window=False
  234. )
  235. customlink.save()
  236. customlink.object_types.set([ObjectType.objects.get_for_model(Site)])
  237. site = Site(name='Test Site', slug='test-site')
  238. site.save()
  239. # Custom link columns are hidden by default; explicitly include the column
  240. response = self.client.get(f"{reverse('dcim:site_list')}?include_columns=cl_Test")
  241. self.assertEqual(response.status_code, 200)
  242. self.assertIn(f'FOO {site.name} BAR', str(response.content))
  243. def test_list_view_custom_link_column_hidden_without_permission(self):
  244. # A custom link column must be excluded from the list view when the user cannot view the
  245. # CustomLink, even if explicitly requested (#22439).
  246. customlink = CustomLink(
  247. name='Test',
  248. link_text='FOO {{ object.name }} BAR',
  249. link_url='http://example.com/?site={{ object.slug }}',
  250. new_window=False
  251. )
  252. customlink.save()
  253. customlink.object_types.set([ObjectType.objects.get_for_model(Site)])
  254. site = Site(name='Test Site', slug='test-site')
  255. site.save()
  256. # Revoke permission to view custom links
  257. self.remove_permissions('extras.view_customlink')
  258. response = self.client.get(f"{reverse('dcim:site_list')}?include_columns=cl_Test")
  259. self.assertEqual(response.status_code, 200)
  260. self.assertNotIn(f'FOO {site.name} BAR', str(response.content))
  261. def test_list_view_custom_link_column_escapes_render_error(self):
  262. # Jinja2 includes the invalid key verbatim in UndefinedError; this test intentionally depends on that format.
  263. payload = '" ></span><script>alert(1)</script>'
  264. customlink = CustomLink(
  265. name='Test',
  266. link_text=f"{{{{ ''['{payload}'] + 1 }}}}",
  267. link_url='http://example.com/',
  268. new_window=False
  269. )
  270. customlink.save()
  271. customlink.object_types.set([ObjectType.objects.get_for_model(Site)])
  272. site = Site(name='Test Site', slug='test-site')
  273. site.save()
  274. response = self.client.get(f"{reverse('dcim:site_list')}?include_columns=cl_Test")
  275. self.assertEqual(response.status_code, 200)
  276. content = response.content.decode()
  277. # The error element must be present, but the payload must appear only in escaped form
  278. self.assertIn('<span class="text-danger" title="', content)
  279. self.assertNotIn(payload, content)
  280. self.assertIn(escape(payload), content)
  281. class SavedFilterTestCase(ViewTestCases.PrimaryObjectViewTestCase):
  282. model = SavedFilter
  283. @classmethod
  284. def setUpTestData(cls):
  285. site_type = ObjectType.objects.get_for_model(Site)
  286. users = (
  287. User(username='User 1'),
  288. User(username='User 2'),
  289. User(username='User 3'),
  290. )
  291. User.objects.bulk_create(users)
  292. saved_filters = (
  293. SavedFilter(
  294. name='Saved Filter 1',
  295. slug='saved-filter-1',
  296. user=users[0],
  297. weight=100,
  298. parameters={'status': ['active']}
  299. ),
  300. SavedFilter(
  301. name='Saved Filter 2',
  302. slug='saved-filter-2',
  303. user=users[1],
  304. weight=200,
  305. parameters={'status': ['planned']}
  306. ),
  307. SavedFilter(
  308. name='Saved Filter 3',
  309. slug='saved-filter-3',
  310. user=users[2],
  311. weight=300,
  312. parameters={'status': ['retired']}
  313. ),
  314. )
  315. SavedFilter.objects.bulk_create(saved_filters)
  316. for i, savedfilter in enumerate(saved_filters):
  317. savedfilter.object_types.set([site_type])
  318. cls.form_data = {
  319. 'name': 'Saved Filter X',
  320. 'slug': 'saved-filter-x',
  321. 'object_types': [site_type.pk],
  322. 'description': 'Foo',
  323. 'weight': 1000,
  324. 'enabled': True,
  325. 'shared': True,
  326. 'parameters': '{"foo": 123}',
  327. }
  328. cls.csv_data = (
  329. 'name,slug,object_types,weight,enabled,shared,parameters',
  330. 'Saved Filter 4,saved-filter-4,dcim.device,400,True,True,{"foo": "a"}',
  331. 'Saved Filter 5,saved-filter-5,dcim.device,500,True,True,{"foo": "b"}',
  332. 'Saved Filter 6,saved-filter-6,dcim.device,600,True,True,{"foo": "c"}',
  333. )
  334. cls.csv_update_data = (
  335. "id,name",
  336. f"{saved_filters[0].pk},Saved Filter 7",
  337. f"{saved_filters[1].pk},Saved Filter 8",
  338. f"{saved_filters[2].pk},Saved Filter 9",
  339. )
  340. cls.bulk_edit_data = {
  341. 'weight': 999,
  342. }
  343. class TableConfigTestCase(
  344. ViewTestCases.GetObjectViewTestCase,
  345. ViewTestCases.GetObjectChangelogViewTestCase,
  346. ViewTestCases.CreateObjectViewTestCase,
  347. ViewTestCases.EditObjectViewTestCase,
  348. ViewTestCases.DeleteObjectViewTestCase,
  349. ViewTestCases.ListObjectsViewTestCase,
  350. ViewTestCases.BulkEditObjectsViewTestCase,
  351. ViewTestCases.BulkDeleteObjectsViewTestCase,
  352. ):
  353. model = TableConfig
  354. # Selected columns are POSTed as a list but compared as a CSV string
  355. validation_excluded_fields = ('columns',)
  356. @classmethod
  357. def setUpTestData(cls):
  358. site_type = ObjectType.objects.get_for_model(Site)
  359. users = (
  360. User(username='User 1'),
  361. User(username='User 2'),
  362. User(username='User 3'),
  363. )
  364. User.objects.bulk_create(users)
  365. table_configs = (
  366. TableConfig(
  367. name='Table Config 1',
  368. object_type=site_type,
  369. table='SiteTable',
  370. user=users[0],
  371. columns=['name', 'status'],
  372. ),
  373. TableConfig(
  374. name='Table Config 2',
  375. object_type=site_type,
  376. table='SiteTable',
  377. user=users[1],
  378. columns=['name', 'region'],
  379. ),
  380. TableConfig(
  381. name='Table Config 3',
  382. object_type=site_type,
  383. table='SiteTable',
  384. user=users[2],
  385. columns=['name', 'tenant'],
  386. ),
  387. )
  388. TableConfig.objects.bulk_create(table_configs)
  389. cls.form_data = {
  390. 'name': 'Table Config X',
  391. 'object_type': site_type.pk,
  392. 'table': 'SiteTable',
  393. 'description': 'A table config',
  394. 'weight': 100,
  395. 'enabled': True,
  396. 'shared': True,
  397. 'columns': ['name', 'status'],
  398. 'ordering': 'name',
  399. }
  400. cls.bulk_edit_data = {
  401. 'weight': 999,
  402. }
  403. def _get_url(self, action, instance=None):
  404. url = super()._get_url(action, instance)
  405. # The add view requires the table context from the source table view
  406. if action == 'add':
  407. site_type = ObjectType.objects.get_for_model(Site)
  408. url = f'{url}?object_type={site_type.pk}&table=SiteTable'
  409. return url
  410. def test_add_view_without_table_context(self):
  411. """A GET without the table context params must redirect to the home page."""
  412. self.add_permissions('extras.add_tableconfig')
  413. response = self.client.get(reverse('extras:tableconfig_add'))
  414. self.assertRedirects(response, reverse('home'))
  415. messages_list = list(get_messages(response.wsgi_request))
  416. self.assertEqual(len(messages_list), 1)
  417. self.assertEqual(str(messages_list[0]), 'Table configurations must be created from an object list view.')
  418. def test_add_view_post_without_table_context(self):
  419. """A POST without the table context must return form errors rather than a server error."""
  420. self.add_permissions('extras.add_tableconfig')
  421. response = self.client.post(reverse('extras:tableconfig_add'), data={})
  422. self.assertHttpStatus(response, 200)
  423. class BookmarkTestCase(
  424. ViewTestCases.DeleteObjectViewTestCase,
  425. ViewTestCases.ListObjectsViewTestCase,
  426. ViewTestCases.BulkDeleteObjectsViewTestCase
  427. ):
  428. model = Bookmark
  429. @classmethod
  430. def setUpTestData(cls):
  431. site_ct = ContentType.objects.get_for_model(Site)
  432. sites = (
  433. Site(name='Site 1', slug='site-1'),
  434. Site(name='Site 2', slug='site-2'),
  435. Site(name='Site 3', slug='site-3'),
  436. Site(name='Site 4', slug='site-4'),
  437. )
  438. Site.objects.bulk_create(sites)
  439. cls.form_data = {
  440. 'object_type': site_ct.pk,
  441. 'object_id': sites[3].pk,
  442. }
  443. def setUp(self):
  444. super().setUp()
  445. sites = Site.objects.all()
  446. user = self.user
  447. bookmarks = (
  448. Bookmark(object=sites[0], user=user),
  449. Bookmark(object=sites[1], user=user),
  450. Bookmark(object=sites[2], user=user),
  451. )
  452. Bookmark.objects.bulk_create(bookmarks)
  453. def _get_url(self, action, instance=None):
  454. if action == 'list':
  455. return reverse('account:bookmarks')
  456. return super()._get_url(action, instance)
  457. def test_list_objects_anonymous(self):
  458. return
  459. def test_export_objects_anonymous(self):
  460. return
  461. def test_list_objects_with_constrained_permission(self):
  462. return
  463. class ImageAttachmentTestCase(
  464. ViewTestCases.GetObjectViewTestCase,
  465. ViewTestCases.ListObjectsViewTestCase,
  466. ViewTestCases.DeleteObjectViewTestCase,
  467. ViewTestCases.BulkDeleteObjectsViewTestCase,
  468. ):
  469. # Add/Edit/BulkEdit are omitted: ImageField.save() re-reads the file to
  470. # populate image_height / image_width, which fails when fixtures use
  471. # placeholder URLs instead of real images on disk.
  472. model = ImageAttachment
  473. def setUp(self):
  474. super().setUp()
  475. # The fixtures use placeholder image URLs with no file on disk, so rendering the thumbnail
  476. # column logs a FileNotFoundError traceback for every attachment. The missing files are
  477. # expected here, so mute the sorl-thumbnail logger to keep the test output clean.
  478. logger = logging.getLogger('sorl.thumbnail')
  479. original_level = logger.level
  480. logger.setLevel(logging.CRITICAL)
  481. self.addCleanup(logger.setLevel, original_level)
  482. @classmethod
  483. def setUpTestData(cls):
  484. ct = ContentType.objects.get_for_model(Site)
  485. site = Site.objects.create(name='Site 1', slug='site-1')
  486. ImageAttachment.objects.bulk_create(
  487. [
  488. ImageAttachment(
  489. object_type=ct,
  490. object_id=site.pk,
  491. name='Image Attachment 1',
  492. image='http://example.com/image1.png',
  493. image_height=100,
  494. image_width=100,
  495. image_size=1024,
  496. ),
  497. ImageAttachment(
  498. object_type=ct,
  499. object_id=site.pk,
  500. name='Image Attachment 2',
  501. image='http://example.com/image2.png',
  502. image_height=100,
  503. image_width=100,
  504. image_size=2048,
  505. ),
  506. ImageAttachment(
  507. object_type=ct,
  508. object_id=site.pk,
  509. name='Image Attachment 3',
  510. image='http://example.com/image3.png',
  511. image_height=100,
  512. image_width=100,
  513. image_size=4096,
  514. ),
  515. ]
  516. )
  517. @tag('regression')
  518. def test_add_form_submission_guard(self):
  519. """The add form opts into the duplicate submission guard."""
  520. self.add_permissions('extras.add_imageattachment')
  521. site = Site.objects.get(slug='site-1')
  522. response = self.client.get(reverse('extras:imageattachment_add'), {
  523. 'object_type': ContentType.objects.get_for_model(Site).pk,
  524. 'object_id': site.pk,
  525. })
  526. self.assertHttpStatus(response, 200)
  527. self.assertIn(
  528. '<form action="" method="post" enctype="multipart/form-data" '
  529. 'class="object-edit object-edit--with-sticky-actions mt-5" data-disable-on-submit>',
  530. response.content.decode(),
  531. )
  532. def test_object_image_attachments_view_with_constrained_permission(self):
  533. """The image attachments tab of an object lists only the attachments the user may view."""
  534. self.add_permissions('dcim.view_site')
  535. obj_perm = ObjectPermission(
  536. name='View one image attachment',
  537. constraints={'name': 'Image Attachment 1'},
  538. actions=['view'],
  539. )
  540. obj_perm.save()
  541. obj_perm.users.add(self.user)
  542. obj_perm.object_types.add(ObjectType.objects.get_for_model(ImageAttachment))
  543. site = Site.objects.get(slug='site-1')
  544. response = self.client.get(get_action_url(site, 'image-attachments', kwargs={'pk': site.pk}))
  545. self.assertHttpStatus(response, 200)
  546. self.assertEqual(
  547. [image.name for image in response.context['image_attachments']],
  548. ['Image Attachment 1'],
  549. )
  550. def test_object_image_attachments_view_without_permission(self):
  551. """A user who can view the object but no image attachments sees an empty list."""
  552. self.add_permissions('dcim.view_site')
  553. site = Site.objects.get(slug='site-1')
  554. response = self.client.get(get_action_url(site, 'image-attachments', kwargs={'pk': site.pk}))
  555. self.assertHttpStatus(response, 200)
  556. self.assertEqual(list(response.context['image_attachments']), [])
  557. class ExportTemplateTestCase(ViewTestCases.PrimaryObjectViewTestCase):
  558. model = ExportTemplate
  559. @classmethod
  560. def setUpTestData(cls):
  561. site_type = ObjectType.objects.get_for_model(Site)
  562. TEMPLATE_CODE = """{% for object in queryset %}{{ object }}{% endfor %}"""
  563. ENVIRONMENT_PARAMS = """{"trim_blocks": true}"""
  564. export_templates = (
  565. ExportTemplate(name='Export Template 1', template_code=TEMPLATE_CODE),
  566. ExportTemplate(
  567. name='Export Template 2', template_code=TEMPLATE_CODE, environment_params={"trim_blocks": True}
  568. ),
  569. ExportTemplate(name='Export Template 3', template_code=TEMPLATE_CODE, file_name='export_template_3')
  570. )
  571. ExportTemplate.objects.bulk_create(export_templates)
  572. for et in export_templates:
  573. et.object_types.set([site_type])
  574. datasource = DataSource.objects.create(
  575. name='Data Source 1',
  576. type='local',
  577. source_url='file:///tmp/netbox-datasource/',
  578. )
  579. cls.file_data = b'{% for object in queryset %}{{ object.name }}{% endfor %}'
  580. cls.datafile = DataFile.objects.create(
  581. source=datasource,
  582. path='exports/sites.j2',
  583. last_updated=now(),
  584. size=len(cls.file_data),
  585. hash=hashlib.sha256(cls.file_data).hexdigest(),
  586. data=cls.file_data,
  587. )
  588. # The same path in two sources, so a path alone cannot identify the file
  589. other_datasource = DataSource.objects.create(
  590. name='Data Source 2',
  591. type='local',
  592. source_url='file:///tmp/netbox-datasource-2/',
  593. )
  594. cls.shared_path = 'exports/shared.j2'
  595. cls.shared_datafile = DataFile.objects.create(
  596. source=datasource,
  597. path=cls.shared_path,
  598. last_updated=now(),
  599. size=len(cls.file_data),
  600. hash=hashlib.sha256(cls.file_data).hexdigest(),
  601. data=cls.file_data,
  602. )
  603. DataFile.objects.create(
  604. source=other_datasource,
  605. path=cls.shared_path,
  606. last_updated=now(),
  607. size=len(cls.file_data),
  608. hash=hashlib.sha256(cls.file_data).hexdigest(),
  609. data=cls.file_data,
  610. )
  611. cls.form_data = {
  612. 'name': 'Export Template X',
  613. 'object_types': [site_type.pk],
  614. 'template_code': TEMPLATE_CODE,
  615. 'environment_params': ENVIRONMENT_PARAMS,
  616. 'file_name': 'template_x',
  617. }
  618. cls.csv_data = {
  619. 'default': (
  620. "name,object_types,template_code,file_name",
  621. f"Export Template 4,dcim.site,{TEMPLATE_CODE},",
  622. f"Export Template 5,dcim.site,{TEMPLATE_CODE},template_5",
  623. f"Export Template 6,dcim.site,{TEMPLATE_CODE},",
  624. ),
  625. 'with_data_file': (
  626. "name,object_types,data_file,auto_sync_enabled",
  627. f"Export Template 10,dcim.site,{cls.datafile.path},true",
  628. ),
  629. 'with_duplicate_path': (
  630. "name,object_types,data_source,data_file",
  631. f"Export Template 12,dcim.site,{datasource.name},{cls.shared_path}",
  632. ),
  633. }
  634. cls.csv_update_data = (
  635. "id,name",
  636. f"{export_templates[0].pk},Export Template 7",
  637. f"{export_templates[1].pk},Export Template 8",
  638. f"{export_templates[2].pk},Export Template 9",
  639. )
  640. cls.bulk_edit_data = {
  641. 'mime_type': 'text/html',
  642. 'file_extension': 'html',
  643. 'as_attachment': True,
  644. }
  645. def test_bulk_import_objects_with_permission(self):
  646. def verify_data_file(scenario_name):
  647. if scenario_name != 'with_data_file':
  648. return
  649. export_template = ExportTemplate.objects.get(name='Export Template 10')
  650. self.assertEqual(export_template.data_file, self.datafile)
  651. self.assertEqual(export_template.data_source, self.datafile.source)
  652. self.assertEqual(export_template.data_path, self.datafile.path)
  653. self.assertEqual(export_template.template_code, self.file_data.decode('utf-8'))
  654. self.assertTrue(export_template.auto_sync_enabled)
  655. def verify_duplicate_path(scenario_name):
  656. if scenario_name != 'with_duplicate_path':
  657. return
  658. export_template = ExportTemplate.objects.get(name='Export Template 12')
  659. self.assertEqual(export_template.data_file, self.shared_datafile)
  660. def verify(scenario_name):
  661. verify_data_file(scenario_name)
  662. verify_duplicate_path(scenario_name)
  663. super().test_bulk_import_objects_with_permission(post_import_callback=verify)
  664. def test_bulk_import_without_content_or_data_file(self):
  665. """A row supplying neither template code nor a data file is rejected."""
  666. self.add_permissions('extras.add_exporttemplate')
  667. initial_count = ExportTemplate.objects.count()
  668. response = self.client.post(self._get_url('bulk_import'), {
  669. 'data': "name,object_types\nExport Template 11,dcim.site",
  670. 'format': ImportFormatChoices.CSV,
  671. 'csv_delimiter': CSVDelimiterChoices.AUTO,
  672. })
  673. self.assertHttpStatus(response, 200)
  674. self.assertEqual(ExportTemplate.objects.count(), initial_count)
  675. def test_bulk_import_with_source_id_column(self):
  676. """A data_source.id column scopes the file lookup, and a malformed id is a row error."""
  677. self.add_permissions('core.view_datafile', 'core.view_datasource', 'extras.add_exporttemplate')
  678. source_id = self.shared_datafile.source_id
  679. for label, value, expected_status in (
  680. ('valid', str(source_id), 302),
  681. ('malformed', 'not-a-number', 200),
  682. ):
  683. with self.subTest(source_id=label):
  684. response = self.client.post(self._get_url('bulk_import'), {
  685. 'data': f"name,object_types,data_source.id,data_file\n"
  686. f"Export Template {label},dcim.site,{value},{self.shared_path}",
  687. 'format': ImportFormatChoices.CSV,
  688. 'csv_delimiter': CSVDelimiterChoices.AUTO,
  689. })
  690. self.assertHttpStatus(response, expected_status)
  691. export_template = ExportTemplate.objects.get(name='Export Template valid')
  692. self.assertEqual(export_template.data_file, self.shared_datafile)
  693. self.assertFalse(ExportTemplate.objects.filter(name='Export Template malformed').exists())
  694. def test_bulk_import_update_with_source_but_no_file_column(self):
  695. """An update record naming a source but no file does not trip the scoped file lookup."""
  696. self.add_permissions(
  697. 'core.view_datafile',
  698. 'core.view_datasource',
  699. 'extras.add_exporttemplate',
  700. 'extras.change_exporttemplate',
  701. )
  702. export_template = ExportTemplate.objects.get(name='Export Template 1')
  703. response = self.client.post(self._get_url('bulk_import'), {
  704. 'data': f"id,data_source\n{export_template.pk},{self.datafile.source.name}",
  705. 'format': ImportFormatChoices.CSV,
  706. 'csv_delimiter': CSVDelimiterChoices.AUTO,
  707. })
  708. self.assertHttpStatus(response, 302)
  709. def test_bulk_import_update_cannot_blank_template_code(self):
  710. """An update row clearing template code on a template with no data file is rejected."""
  711. self.add_permissions('extras.add_exporttemplate', 'extras.change_exporttemplate')
  712. export_template = ExportTemplate.objects.get(name='Export Template 1')
  713. response = self.client.post(self._get_url('bulk_import'), {
  714. 'data': f"id,template_code\n{export_template.pk},",
  715. 'format': ImportFormatChoices.CSV,
  716. 'csv_delimiter': CSVDelimiterChoices.AUTO,
  717. })
  718. self.assertHttpStatus(response, 200)
  719. export_template.refresh_from_db()
  720. self.assertNotEqual(export_template.template_code, '')
  721. def test_content_is_not_cacheable(self):
  722. """
  723. The detail view renders the template code inline, which may have been synced from a data
  724. file containing sensitive values, so the response must not be cached by the browser.
  725. """
  726. export_template = ExportTemplate.objects.first()
  727. export_template.template_code = 'super-secret-password'
  728. export_template.save()
  729. self.add_permissions('extras.view_exporttemplate')
  730. response = self.client.get(export_template.get_absolute_url())
  731. self.assertHttpStatus(response, 200)
  732. # Confirm the template code is in fact rendered in the response
  733. self.assertIn(b'super-secret-password', response.content)
  734. self.assertNotCacheable(response)
  735. class ExportTemplateExportFlowTestCase(TestCase):
  736. """
  737. End-to-end test for ExportTemplate invocation via a list view's ?export=<name> query param.
  738. """
  739. @classmethod
  740. def setUpTestData(cls):
  741. Site.objects.bulk_create([
  742. Site(name='Site A', slug='site-a'),
  743. Site(name='Site B', slug='site-b'),
  744. ])
  745. site_type = ObjectType.objects.get_for_model(Site)
  746. ok_template = ExportTemplate.objects.create(
  747. name='Sites Export',
  748. template_code='{% for obj in queryset %}{{ obj.name }}\n{% endfor %}',
  749. mime_type='text/plain',
  750. file_extension='txt',
  751. )
  752. ok_template.object_types.set([site_type])
  753. broken_template = ExportTemplate.objects.create(
  754. name='Broken Export',
  755. template_code='{% for obj in queryset %}{{ obj.name ', # unterminated expression
  756. )
  757. broken_template.object_types.set([site_type])
  758. def test_export_template_invocation(self):
  759. self.add_permissions('dcim.view_site', 'extras.view_exporttemplate')
  760. url = reverse('dcim:site_list')
  761. response = self.client.get(f'{url}?export=Sites Export')
  762. self.assertEqual(response.status_code, 200)
  763. self.assertEqual(response['Content-Type'], 'text/plain')
  764. self.assertEqual(response['Content-Disposition'], 'attachment; filename="netbox_sites.txt"')
  765. # The rendered queryset reflects whatever ordering the list view applies. Assert on set
  766. # membership rather than line order so the test isn't coupled to Site's natural ordering.
  767. rendered_names = set(filter(None, response.content.decode().split('\n')))
  768. self.assertEqual(rendered_names, {'Site A', 'Site B'})
  769. def test_export_template_render_error_redirects(self):
  770. self.add_permissions('dcim.view_site', 'extras.view_exporttemplate')
  771. url = reverse('dcim:site_list')
  772. # A broken template surfaces an exception during render; the view catches it and redirects
  773. # back to the (filtered) list view rather than returning a 500.
  774. response = self.client.get(f'{url}?export=Broken Export')
  775. self.assertEqual(response.status_code, 302)
  776. self.assertTrue(response['Location'].startswith(url))
  777. self.assertNotIn('export=', response['Location'])
  778. class WebhookTestCase(ViewTestCases.PrimaryObjectViewTestCase):
  779. model = Webhook
  780. @classmethod
  781. def setUpTestData(cls):
  782. webhooks = (
  783. Webhook(name='Webhook 1', payload_url='http://example.com/?1', http_method='POST'),
  784. Webhook(name='Webhook 2', payload_url='http://example.com/?2', http_method='POST'),
  785. Webhook(name='Webhook 3', payload_url='http://example.com/?3', http_method='POST'),
  786. )
  787. for webhook in webhooks:
  788. webhook.save()
  789. cls.form_data = {
  790. 'name': 'Webhook X',
  791. 'payload_url': 'http://example.com/?x',
  792. 'http_method': 'GET',
  793. 'http_content_type': 'application/foo',
  794. 'timeout': 45,
  795. 'description': 'My webhook',
  796. }
  797. cls.csv_data = (
  798. "name,payload_url,http_method,http_content_type,timeout,description",
  799. "Webhook 4,http://example.com/?4,GET,application/json,15,Foo",
  800. "Webhook 5,http://example.com/?5,GET,application/json,,Bar",
  801. "Webhook 6,http://example.com/?6,GET,application/json,,Baz",
  802. )
  803. cls.csv_update_data = (
  804. "id,name,description",
  805. f"{webhooks[0].pk},Webhook 7,Foo",
  806. f"{webhooks[1].pk},Webhook 8,Bar",
  807. f"{webhooks[2].pk},Webhook 9,Baz",
  808. )
  809. cls.bulk_edit_data = {
  810. 'http_method': 'GET',
  811. 'timeout': 60,
  812. }
  813. class EventRulesTestCase(ViewTestCases.PrimaryObjectViewTestCase):
  814. model = EventRule
  815. @classmethod
  816. def setUpTestData(cls):
  817. webhooks = (
  818. Webhook(name='Webhook 1', payload_url='http://example.com/?1', http_method='POST'),
  819. Webhook(name='Webhook 2', payload_url='http://example.com/?2', http_method='POST'),
  820. Webhook(name='Webhook 3', payload_url='http://example.com/?3', http_method='POST'),
  821. )
  822. for webhook in webhooks:
  823. webhook.save()
  824. site_type = ObjectType.objects.get_for_model(Site)
  825. event_rules = (
  826. EventRule(name='EventRule 1', event_types=[OBJECT_CREATED], action_object=webhooks[0]),
  827. EventRule(name='EventRule 2', event_types=[OBJECT_CREATED], action_object=webhooks[1]),
  828. EventRule(name='EventRule 3', event_types=[OBJECT_CREATED], action_object=webhooks[2]),
  829. )
  830. for event in event_rules:
  831. event.save()
  832. event.object_types.add(site_type)
  833. webhook_ct = ContentType.objects.get_for_model(Webhook)
  834. cls.form_data = {
  835. 'name': 'Event X',
  836. 'object_types': [site_type.pk],
  837. 'event_types': [OBJECT_UPDATED, OBJECT_DELETED],
  838. 'conditions': None,
  839. 'action_type': 'webhook',
  840. 'action_object_type': webhook_ct.pk,
  841. 'action_object_id': webhooks[0].pk,
  842. 'action_choice': webhooks[0],
  843. 'description': 'New description',
  844. }
  845. cls.csv_data = (
  846. 'name,object_types,event_types,action_type,action_object',
  847. f'Webhook 4,dcim.site,"{OBJECT_CREATED},{OBJECT_UPDATED}",webhook,Webhook 1',
  848. )
  849. cls.csv_update_data = (
  850. "id,name",
  851. f"{event_rules[0].pk},Event 7",
  852. f"{event_rules[1].pk},Event 8",
  853. f"{event_rules[2].pk},Event 9",
  854. )
  855. cls.bulk_edit_data = {
  856. 'description': 'New description',
  857. }
  858. class TagTestCase(ViewTestCases.OrganizationalObjectViewTestCase):
  859. model = Tag
  860. @classmethod
  861. def setUpTestData(cls):
  862. site_ct = ContentType.objects.get_for_model(Site)
  863. tags = (
  864. Tag(name='Tag 1', slug='tag-1'),
  865. Tag(name='Tag 2', slug='tag-2', weight=1),
  866. Tag(name='Tag 3', slug='tag-3', weight=32767),
  867. )
  868. Tag.objects.bulk_create(tags)
  869. cls.form_data = {
  870. 'name': 'Tag X',
  871. 'slug': 'tag-x',
  872. 'color': 'c0c0c0',
  873. 'comments': 'Some comments',
  874. 'object_types': [site_ct.pk],
  875. 'weight': 11,
  876. }
  877. cls.csv_data = (
  878. "name,slug,color,description,object_types,weight",
  879. "Tag 4,tag-4,ff0000,Fourth tag,dcim.interface,0",
  880. "Tag 5,tag-5,00ff00,Fifth tag,'dcim.device,dcim.site',1111",
  881. "Tag 6,tag-6,0000ff,Sixth tag,dcim.site,0",
  882. )
  883. cls.csv_update_data = (
  884. "id,name,description",
  885. f"{tags[0].pk},Tag 7,Fourth tag7",
  886. f"{tags[1].pk},Tag 8,Fifth tag8",
  887. f"{tags[2].pk},Tag 9,Sixth tag9",
  888. )
  889. cls.bulk_edit_data = {
  890. 'color': '00ff00',
  891. }
  892. class ConfigContextProfileTestCase(ViewTestCases.PrimaryObjectViewTestCase):
  893. model = ConfigContextProfile
  894. @classmethod
  895. def setUpTestData(cls):
  896. profiles = (
  897. ConfigContextProfile(
  898. name='Config Context Profile 1',
  899. schema={
  900. "properties": {
  901. "foo": {
  902. "type": "string"
  903. }
  904. },
  905. "required": [
  906. "foo"
  907. ]
  908. }
  909. ),
  910. ConfigContextProfile(
  911. name='Config Context Profile 2',
  912. schema={
  913. "properties": {
  914. "bar": {
  915. "type": "string"
  916. }
  917. },
  918. "required": [
  919. "bar"
  920. ]
  921. }
  922. ),
  923. ConfigContextProfile(
  924. name='Config Context Profile 3',
  925. schema={
  926. "properties": {
  927. "baz": {
  928. "type": "string"
  929. }
  930. },
  931. "required": [
  932. "baz"
  933. ]
  934. }
  935. ),
  936. )
  937. ConfigContextProfile.objects.bulk_create(profiles)
  938. cls.form_data = {
  939. 'name': 'Config Context Profile X',
  940. 'description': 'A new config context profile',
  941. }
  942. cls.bulk_edit_data = {
  943. 'description': 'New description',
  944. }
  945. cls.csv_data = (
  946. 'name,description',
  947. 'Config context profile 1,Foo',
  948. 'Config context profile 2,Bar',
  949. 'Config context profile 3,Baz',
  950. )
  951. cls.csv_update_data = (
  952. "id,description",
  953. f"{profiles[0].pk},New description",
  954. f"{profiles[1].pk},New description",
  955. f"{profiles[2].pk},New description",
  956. )
  957. def test_content_is_not_cacheable(self):
  958. """
  959. The detail view renders the schema inline, which may have been synced from a data file
  960. containing sensitive values, so the response must not be cached by the browser.
  961. """
  962. instance = ConfigContextProfile.objects.first()
  963. instance.schema = {
  964. 'properties': {
  965. 'password': {
  966. 'type': 'string',
  967. 'default': 'super-secret-password',
  968. }
  969. }
  970. }
  971. instance.save()
  972. self.add_permissions('extras.view_configcontextprofile')
  973. response = self.client.get(instance.get_absolute_url())
  974. self.assertHttpStatus(response, 200)
  975. # Confirm the schema is in fact rendered in the response
  976. self.assertIn(b'super-secret-password', response.content)
  977. self.assertNotCacheable(response)
  978. # TODO: Change base class to PrimaryObjectViewTestCase
  979. # Blocked by absence of standard create/edit, bulk create views
  980. class ConfigContextTestCase(
  981. ViewTestCases.GetObjectViewTestCase,
  982. ViewTestCases.GetObjectChangelogViewTestCase,
  983. ViewTestCases.DeleteObjectViewTestCase,
  984. ViewTestCases.ListObjectsViewTestCase,
  985. ViewTestCases.BulkEditObjectsViewTestCase,
  986. ViewTestCases.BulkDeleteObjectsViewTestCase
  987. ):
  988. model = ConfigContext
  989. @classmethod
  990. def setUpTestData(cls):
  991. manufacturer = Manufacturer.objects.create(name='Manufacturer 1', slug='manufacturer-1')
  992. devicetype = DeviceType.objects.create(manufacturer=manufacturer, model='Device Type 1', slug='device-type-1')
  993. # Create three ConfigContexts
  994. for i in range(1, 4):
  995. configcontext = ConfigContext(
  996. name='Config Context {}'.format(i),
  997. data={'foo': i}
  998. )
  999. configcontext.save()
  1000. configcontext.device_types.add(devicetype)
  1001. cls.form_data = {
  1002. 'name': 'Config Context X',
  1003. 'weight': 200,
  1004. 'description': 'A new config context',
  1005. 'is_active': True,
  1006. 'regions': [],
  1007. 'sites': [],
  1008. 'roles': [],
  1009. 'platforms': [],
  1010. 'tenant_groups': [],
  1011. 'tenants': [],
  1012. 'device_types': [devicetype.id],
  1013. 'tags': [],
  1014. 'data': '{"foo": 123}',
  1015. }
  1016. cls.bulk_edit_data = {
  1017. 'weight': 300,
  1018. 'is_active': False,
  1019. 'description': 'New description',
  1020. }
  1021. def test_content_is_not_cacheable(self):
  1022. """
  1023. The detail view renders the data inline, which may have been synced from a data
  1024. file containing sensitive values, so the response must not be cached by the browser.
  1025. """
  1026. instance = ConfigContext.objects.first()
  1027. instance.data = {'password': 'super-secret-password'}
  1028. instance.save()
  1029. self.add_permissions('extras.view_configcontext')
  1030. response = self.client.get(instance.get_absolute_url())
  1031. self.assertHttpStatus(response, 200)
  1032. # Confirm the context data is in fact rendered in the response
  1033. self.assertIn(b'super-secret-password', response.content)
  1034. self.assertNotCacheable(response)
  1035. class ConfigTemplateTestCase(
  1036. ViewTestCases.GetObjectViewTestCase,
  1037. ViewTestCases.GetObjectChangelogViewTestCase,
  1038. ViewTestCases.DeleteObjectViewTestCase,
  1039. ViewTestCases.ListObjectsViewTestCase,
  1040. ViewTestCases.BulkEditObjectsViewTestCase,
  1041. ViewTestCases.BulkDeleteObjectsViewTestCase
  1042. ):
  1043. model = ConfigTemplate
  1044. @classmethod
  1045. def setUpTestData(cls):
  1046. TEMPLATE_CODE = """Foo: {{ foo }}"""
  1047. ENVIRONMENT_PARAMS = """{"trim_blocks": true}"""
  1048. config_templates = (
  1049. ConfigTemplate(
  1050. name='Config Template 1',
  1051. template_code=TEMPLATE_CODE)
  1052. ,
  1053. ConfigTemplate(
  1054. name='Config Template 2',
  1055. template_code=TEMPLATE_CODE,
  1056. environment_params={"trim_blocks": True},
  1057. ),
  1058. ConfigTemplate(
  1059. name='Config Template 3',
  1060. template_code=TEMPLATE_CODE,
  1061. file_name='config_template_3',
  1062. ),
  1063. )
  1064. ConfigTemplate.objects.bulk_create(config_templates)
  1065. cls.form_data = {
  1066. 'name': 'Config Template X',
  1067. 'description': 'Config template',
  1068. 'template_code': TEMPLATE_CODE,
  1069. 'environment_params': ENVIRONMENT_PARAMS,
  1070. 'file_name': 'config_x',
  1071. }
  1072. cls.csv_update_data = (
  1073. "id,name",
  1074. f"{config_templates[0].pk},Config Template 7",
  1075. f"{config_templates[1].pk},Config Template 8",
  1076. f"{config_templates[2].pk},Config Template 9",
  1077. )
  1078. cls.bulk_edit_data = {
  1079. 'description': 'New description',
  1080. 'mime_type': 'text/html',
  1081. 'file_name': 'output',
  1082. 'file_extension': 'html',
  1083. 'as_attachment': True,
  1084. }
  1085. def test_content_is_not_cacheable(self):
  1086. """
  1087. The detail view renders the template code inline, which may have been synced from a data
  1088. file containing sensitive values, so the response must not be cached by the browser.
  1089. """
  1090. instance = ConfigTemplate.objects.first()
  1091. instance.template_code = 'super-secret-password'
  1092. instance.save()
  1093. self.add_permissions('extras.view_configtemplate')
  1094. response = self.client.get(instance.get_absolute_url())
  1095. self.assertHttpStatus(response, 200)
  1096. # Confirm the template code is in fact rendered in the response
  1097. self.assertIn(b'super-secret-password', response.content)
  1098. self.assertNotCacheable(response)
  1099. class JournalEntryTestCase(
  1100. # ViewTestCases.GetObjectViewTestCase,
  1101. ViewTestCases.CreateObjectViewTestCase,
  1102. ViewTestCases.EditObjectViewTestCase,
  1103. ViewTestCases.DeleteObjectViewTestCase,
  1104. ViewTestCases.ListObjectsViewTestCase,
  1105. ViewTestCases.BulkEditObjectsViewTestCase,
  1106. ViewTestCases.BulkDeleteObjectsViewTestCase
  1107. ):
  1108. model = JournalEntry
  1109. @classmethod
  1110. def setUpTestData(cls):
  1111. site_ct = ContentType.objects.get_for_model(Site)
  1112. site = Site.objects.create(name='Site 1', slug='site-1')
  1113. user = User.objects.create(username='User 1')
  1114. JournalEntry.objects.bulk_create((
  1115. JournalEntry(assigned_object=site, created_by=user, comments='First entry'),
  1116. JournalEntry(assigned_object=site, created_by=user, comments='Second entry'),
  1117. JournalEntry(assigned_object=site, created_by=user, comments='Third entry'),
  1118. ))
  1119. cls.form_data = {
  1120. 'assigned_object_type': site_ct.pk,
  1121. 'assigned_object_id': site.pk,
  1122. 'kind': 'info',
  1123. 'comments': 'A new entry',
  1124. }
  1125. cls.bulk_edit_data = {
  1126. 'kind': 'success',
  1127. 'comments': 'Overwritten',
  1128. }
  1129. class SubscriptionTestCase(
  1130. ViewTestCases.CreateObjectViewTestCase,
  1131. ViewTestCases.DeleteObjectViewTestCase,
  1132. ViewTestCases.ListObjectsViewTestCase,
  1133. ViewTestCases.BulkDeleteObjectsViewTestCase
  1134. ):
  1135. model = Subscription
  1136. @classmethod
  1137. def setUpTestData(cls):
  1138. site_ct = ContentType.objects.get_for_model(Site)
  1139. sites = (
  1140. Site(name='Site 1', slug='site-1'),
  1141. Site(name='Site 2', slug='site-2'),
  1142. Site(name='Site 3', slug='site-3'),
  1143. Site(name='Site 4', slug='site-4'),
  1144. )
  1145. Site.objects.bulk_create(sites)
  1146. cls.form_data = {
  1147. 'object_type': site_ct.pk,
  1148. 'object_id': sites[3].pk,
  1149. }
  1150. def setUp(self):
  1151. super().setUp()
  1152. sites = Site.objects.all()
  1153. user = self.user
  1154. subscriptions = (
  1155. Subscription(object=sites[0], user=user),
  1156. Subscription(object=sites[1], user=user),
  1157. Subscription(object=sites[2], user=user),
  1158. )
  1159. Subscription.objects.bulk_create(subscriptions)
  1160. def _get_url(self, action, instance=None):
  1161. if action == 'list':
  1162. return reverse('account:subscriptions')
  1163. return super()._get_url(action, instance)
  1164. def test_list_objects_anonymous(self):
  1165. self.client.logout()
  1166. url = reverse('account:subscriptions')
  1167. login_url = reverse('login')
  1168. self.assertRedirects(self.client.get(url), f'{login_url}?next={url}')
  1169. def test_export_objects_anonymous(self):
  1170. return
  1171. def test_list_objects_with_permission(self):
  1172. return
  1173. def test_list_objects_with_constrained_permission(self):
  1174. return
  1175. class NotificationGroupTestCase(ViewTestCases.PrimaryObjectViewTestCase):
  1176. model = NotificationGroup
  1177. @classmethod
  1178. def setUpTestData(cls):
  1179. users = (
  1180. User(username='User 1'),
  1181. User(username='User 2'),
  1182. User(username='User 3'),
  1183. )
  1184. User.objects.bulk_create(users)
  1185. groups = (
  1186. Group(name='Group 1'),
  1187. Group(name='Group 2'),
  1188. Group(name='Group 3'),
  1189. )
  1190. Group.objects.bulk_create(groups)
  1191. notification_groups = (
  1192. NotificationGroup(name='Notification Group 1'),
  1193. NotificationGroup(name='Notification Group 2'),
  1194. NotificationGroup(name='Notification Group 3'),
  1195. )
  1196. NotificationGroup.objects.bulk_create(notification_groups)
  1197. for i, notification_group in enumerate(notification_groups):
  1198. notification_group.users.add(users[i])
  1199. notification_group.groups.add(groups[i])
  1200. cls.form_data = {
  1201. 'name': 'Notification Group X',
  1202. 'description': 'Blah',
  1203. 'users': [users[0].pk, users[1].pk],
  1204. 'groups': [groups[0].pk, groups[1].pk],
  1205. }
  1206. cls.csv_data = (
  1207. 'name,description,users,groups',
  1208. 'Notification Group 4,Foo,"User 1,User 2","Group 1,Group 2"',
  1209. 'Notification Group 5,Bar,"User 1,User 2","Group 1,Group 2"',
  1210. 'Notification Group 6,Baz,"User 1,User 2","Group 1,Group 2"',
  1211. )
  1212. cls.csv_update_data = (
  1213. "id,name",
  1214. f"{notification_groups[0].pk},Notification Group 7",
  1215. f"{notification_groups[1].pk},Notification Group 8",
  1216. f"{notification_groups[2].pk},Notification Group 9",
  1217. )
  1218. cls.bulk_edit_data = {
  1219. 'description': 'New description',
  1220. }
  1221. class NotificationTestCase(
  1222. ViewTestCases.DeleteObjectViewTestCase,
  1223. ViewTestCases.ListObjectsViewTestCase,
  1224. ViewTestCases.BulkDeleteObjectsViewTestCase
  1225. ):
  1226. model = Notification
  1227. @classmethod
  1228. def setUpTestData(cls):
  1229. site_ct = ContentType.objects.get_for_model(Site)
  1230. sites = (
  1231. Site(name='Site 1', slug='site-1'),
  1232. Site(name='Site 2', slug='site-2'),
  1233. Site(name='Site 3', slug='site-3'),
  1234. Site(name='Site 4', slug='site-4'),
  1235. )
  1236. Site.objects.bulk_create(sites)
  1237. cls.form_data = {
  1238. 'object_type': site_ct.pk,
  1239. 'object_id': sites[3].pk,
  1240. }
  1241. def setUp(self):
  1242. super().setUp()
  1243. sites = Site.objects.all()
  1244. user = self.user
  1245. notifications = (
  1246. Notification(object=sites[0], user=user),
  1247. Notification(object=sites[1], user=user),
  1248. Notification(object=sites[2], user=user),
  1249. )
  1250. Notification.objects.bulk_create(notifications)
  1251. def _get_url(self, action, instance=None):
  1252. if action == 'list':
  1253. return reverse('account:notifications')
  1254. return super()._get_url(action, instance)
  1255. def test_list_objects_anonymous(self):
  1256. self.client.logout()
  1257. url = reverse('account:notifications')
  1258. login_url = reverse('login')
  1259. self.assertRedirects(self.client.get(url), f'{login_url}?next={url}')
  1260. def test_export_objects_anonymous(self):
  1261. return
  1262. def test_list_objects_with_permission(self):
  1263. return
  1264. def test_list_objects_with_constrained_permission(self):
  1265. return
  1266. class ScriptListViewTestCase(TestCase):
  1267. user_permissions = ['extras.view_script']
  1268. def test_script_list_embedded_parameter(self):
  1269. """Test that ScriptListView accepts embedded parameter without error"""
  1270. url = reverse('extras:script_list')
  1271. # Test normal request
  1272. response = self.client.get(url)
  1273. self.assertEqual(response.status_code, 200)
  1274. self.assertTemplateUsed(response, 'extras/script_list.html')
  1275. # Test embedded request
  1276. response = self.client.get(url, {'embedded': 'true'})
  1277. self.assertEqual(response.status_code, 200)
  1278. self.assertTemplateUsed(response, 'extras/inc/script_list_content.html')
  1279. class ScriptModuleCreateViewTestCase(TestCase):
  1280. user_permissions = ['core.add_managedfile', 'extras.add_scriptmodule']
  1281. @tag('regression')
  1282. def test_default_return_url(self):
  1283. """
  1284. The add view should fall back to the scripts list as its return URL.
  1285. """
  1286. response = self.client.get(reverse('extras:scriptmodule_add'))
  1287. self.assertEqual(response.status_code, 200)
  1288. self.assertEqual(response.context['return_url'], reverse('extras:script_list'))
  1289. class ScriptDefaultBackfillTestCase(TestCase):
  1290. """
  1291. The UI and the REST API now share prepare_script_form(), so the UI's back-filling of
  1292. declared defaults (previously inline in ScriptView.post()) must keep working after
  1293. that logic moved into the helper.
  1294. """
  1295. user_permissions = ['extras.view_script', 'extras.run_script']
  1296. class TestScriptClass(PythonClass):
  1297. class Meta:
  1298. name = 'Backfill test'
  1299. commit_default = False
  1300. label = StringVar(default='hello')
  1301. flag = BooleanVar(default=True)
  1302. picks = MultiChoiceVar(choices=(('a', 'A'), ('b', 'B'), ('c', 'C')), default=['a', 'b'])
  1303. def run(self, data, commit):
  1304. return 'Complete'
  1305. @classmethod
  1306. def setUpTestData(cls):
  1307. with patch.object(ScriptModule, 'sync_classes'):
  1308. module = ScriptModule.objects.create(
  1309. file_root=ManagedFileRootPathChoices.SCRIPTS,
  1310. file_path='backfill_script.py',
  1311. )
  1312. cls.script = Script.objects.create(module=module, name='Backfill test', is_executable=True)
  1313. def setUp(self):
  1314. super().setUp()
  1315. python_class_patch = patch.object(Script, 'python_class', new=self.TestScriptClass)
  1316. python_class_patch.start()
  1317. self.addCleanup(python_class_patch.stop)
  1318. @tag('regression')
  1319. def test_ui_backfills_declared_defaults(self):
  1320. url = reverse('extras:script', kwargs={'pk': self.script.pk})
  1321. with (
  1322. patch('extras.views.any_workers_for_queue', return_value=True),
  1323. patch('extras.jobs.ScriptJob.enqueue') as mock_enqueue,
  1324. ):
  1325. mock_enqueue.return_value.pk = 1
  1326. response = self.client.post(url, {'_commit': 'true'})
  1327. self.assertEqual(response.status_code, 302)
  1328. data = mock_enqueue.call_args.kwargs['data']
  1329. self.assertEqual(data['label'], 'hello')
  1330. self.assertIs(data['flag'], True)
  1331. # A multi-value default must be set on the QueryDict with setlist(): a plain
  1332. # assignment stores the list as one nested value, which the multi-select widget
  1333. # then rejects as a single invalid choice.
  1334. self.assertEqual(data['picks'], ['a', 'b'])
  1335. class ScriptValidationErrorTestCase(TestCase):
  1336. user_permissions = ['extras.view_script', 'extras.run_script']
  1337. class TestScriptMixin:
  1338. bar = IntegerVar(min_value=0, max_value=30)
  1339. class TestScriptClass(TestScriptMixin, PythonClass):
  1340. class Meta:
  1341. name = 'Test script'
  1342. commit_default = False
  1343. fieldsets = (("Logging", ("debug_mode",)),)
  1344. debug_mode = BooleanVar(default=False)
  1345. def run(self, data, commit):
  1346. return "Complete"
  1347. @classmethod
  1348. def setUpTestData(cls):
  1349. # Avoid trying to import a non-existent on-disk module during setup.
  1350. # This test creates the Script row explicitly and monkey-patches
  1351. # Script.python_class below.
  1352. with patch.object(ScriptModule, 'sync_classes'):
  1353. module = ScriptModule.objects.create(
  1354. file_root=ManagedFileRootPathChoices.SCRIPTS,
  1355. file_path='test_script.py',
  1356. )
  1357. cls.script = Script.objects.create(module=module, name='Test script', is_executable=True)
  1358. def setUp(self):
  1359. super().setUp()
  1360. python_class_patch = patch.object(Script, 'python_class', new=self.TestScriptClass)
  1361. python_class_patch.start()
  1362. self.addCleanup(python_class_patch.stop)
  1363. @tag('regression')
  1364. def test_script_validation_error_displays_message(self):
  1365. url = reverse('extras:script', kwargs={'pk': self.script.pk})
  1366. with patch('extras.views.any_workers_for_queue', return_value=True):
  1367. response = self.client.post(url, {'debug_mode': 'true', '_commit': 'true'})
  1368. self.assertEqual(response.status_code, 200)
  1369. messages = list(response.context['messages'])
  1370. self.assertEqual(len(messages), 1)
  1371. self.assertEqual(str(messages[0]), "bar: This field is required.")
  1372. @tag('regression')
  1373. def test_script_validation_error_no_toast_for_fieldset_fields(self):
  1374. class FieldsetScript(PythonClass):
  1375. class Meta:
  1376. name = 'Fieldset test'
  1377. commit_default = False
  1378. fieldsets = (("Fields", ("required_field",)),)
  1379. required_field = IntegerVar(min_value=10)
  1380. def run(self, data, commit):
  1381. return "Complete"
  1382. url = reverse('extras:script', kwargs={'pk': self.script.pk})
  1383. with patch.object(Script, 'python_class', new_callable=PropertyMock) as mock_python_class:
  1384. mock_python_class.return_value = FieldsetScript
  1385. with patch('extras.views.any_workers_for_queue', return_value=True):
  1386. response = self.client.post(url, {'required_field': '5', '_commit': 'true'})
  1387. self.assertEqual(response.status_code, 200)
  1388. messages = list(response.context['messages'])
  1389. self.assertEqual(len(messages), 0)
  1390. class ScriptMetaValidationViewTestCase(TestCase):
  1391. """
  1392. A script whose Meta declares an invalid job_timeout or notifications_default must surface an actionable error on
  1393. the run view rather than returning an HTTP 500 (#22872).
  1394. """
  1395. user_permissions = ['extras.view_script', 'extras.run_script']
  1396. class BadTimeoutScript(PythonClass):
  1397. class Meta:
  1398. name = 'Bad Timeout'
  1399. job_timeout = 'not-a-timeout'
  1400. def run(self, data, commit):
  1401. return "Complete"
  1402. class BadNotificationsScript(PythonClass):
  1403. class Meta:
  1404. name = 'Bad Notifications'
  1405. notifications_default = 'on_error'
  1406. def run(self, data, commit):
  1407. return "Complete"
  1408. @classmethod
  1409. def setUpTestData(cls):
  1410. with patch.object(ScriptModule, 'sync_classes'):
  1411. module = ScriptModule.objects.create(
  1412. file_root=ManagedFileRootPathChoices.SCRIPTS,
  1413. file_path='bad_meta.py',
  1414. )
  1415. cls.script = Script.objects.create(module=module, name='Bad meta', is_executable=True)
  1416. def _run_and_assert(self, python_class):
  1417. url = reverse('extras:script', kwargs={'pk': self.script.pk})
  1418. with patch.object(Script, 'python_class', new_callable=PropertyMock) as mock_python_class:
  1419. mock_python_class.return_value = python_class
  1420. with patch('extras.views.any_workers_for_queue', return_value=True):
  1421. with self.captureOnCommitCallbacks(execute=True):
  1422. # Quick-run style: omit _notifications
  1423. response = self.client.post(url, {'_commit': 'true'})
  1424. # Re-render with an error message, not a 500, and no Job enqueued
  1425. self.assertEqual(response.status_code, 200)
  1426. messages = list(response.context['messages'])
  1427. self.assertEqual(len(messages), 1)
  1428. self.assertIn('Unable to run script', str(messages[0]))
  1429. self.assertEqual(Job.objects.count(), 0)
  1430. @tag('regression')
  1431. def test_invalid_job_timeout_shows_error(self):
  1432. self._run_and_assert(self.BadTimeoutScript)
  1433. @tag('regression')
  1434. def test_invalid_notifications_default_shows_error(self):
  1435. self._run_and_assert(self.BadNotificationsScript)
  1436. class ScriptDefaultValuesTestCase(TestCase):
  1437. user_permissions = ['extras.view_script', 'extras.run_script']
  1438. class TestScriptClass(PythonClass):
  1439. class Meta:
  1440. name = 'Test script'
  1441. commit_default = False
  1442. bool_default_true = BooleanVar(default=True)
  1443. bool_default_false = BooleanVar(default=False)
  1444. int_with_default = IntegerVar(default=0)
  1445. int_without_default = IntegerVar(required=False)
  1446. def run(self, data, commit):
  1447. return "Complete"
  1448. @classmethod
  1449. def setUpTestData(cls):
  1450. # Avoid trying to import a non-existent on-disk module during setup.
  1451. # This test creates the Script row explicitly and monkey-patches
  1452. # Script.python_class below.
  1453. with patch.object(ScriptModule, 'sync_classes'):
  1454. module = ScriptModule.objects.create(
  1455. file_root=ManagedFileRootPathChoices.SCRIPTS,
  1456. file_path='test_script.py',
  1457. )
  1458. cls.script = Script.objects.create(module=module, name='Test script', is_executable=True)
  1459. def setUp(self):
  1460. super().setUp()
  1461. python_class_patch = patch.object(Script, 'python_class', new=self.TestScriptClass)
  1462. python_class_patch.start()
  1463. self.addCleanup(python_class_patch.stop)
  1464. def test_default_values_are_used(self):
  1465. url = reverse('extras:script', kwargs={'pk': self.script.pk})
  1466. with patch('extras.views.any_workers_for_queue', return_value=True):
  1467. with patch('extras.jobs.ScriptJob.enqueue') as mock_enqueue:
  1468. mock_enqueue.return_value.pk = 1
  1469. self.client.post(url, {})
  1470. call_kwargs = mock_enqueue.call_args.kwargs
  1471. self.assertEqual(call_kwargs['data']['bool_default_true'], True)
  1472. self.assertEqual(call_kwargs['data']['bool_default_false'], False)
  1473. self.assertEqual(call_kwargs['data']['int_with_default'], 0)
  1474. self.assertIsNone(call_kwargs['data']['int_without_default'])
  1475. class ScriptResultViewTestCase(TestCase):
  1476. SECRET_OUTPUT = 'my secret script output'
  1477. @classmethod
  1478. def setUpTestData(cls):
  1479. with patch.object(ScriptModule, 'sync_classes'):
  1480. module = ScriptModule.objects.create(
  1481. file_root=ManagedFileRootPathChoices.SCRIPTS,
  1482. file_path='test_script.py',
  1483. )
  1484. cls.allowed_script = Script.objects.create(
  1485. module=module, name='Allowed script', is_executable=True
  1486. )
  1487. cls.secret_script = Script.objects.create(
  1488. module=module, name='Secret script', is_executable=True
  1489. )
  1490. script_type = ObjectType.objects.get_for_model(Script)
  1491. cls.allowed_job = Job.objects.create(
  1492. object_type=script_type,
  1493. object_id=cls.allowed_script.pk,
  1494. name='allowed-job',
  1495. job_id=uuid.uuid4(),
  1496. status=JobStatusChoices.STATUS_COMPLETED,
  1497. data={'log': [], 'output': 'benign output'},
  1498. )
  1499. cls.secret_job = Job.objects.create(
  1500. object_type=script_type,
  1501. object_id=cls.secret_script.pk,
  1502. name='secret-job',
  1503. job_id=uuid.uuid4(),
  1504. status=JobStatusChoices.STATUS_COMPLETED,
  1505. data={'log': [], 'output': cls.SECRET_OUTPUT},
  1506. )
  1507. def test_get_without_view_job_permission_returns_404(self):
  1508. """
  1509. A user with extras.view_script but no core.view_job must not retrieve any job result
  1510. via ScriptResultView, even for the script whose object-level permission they hold.
  1511. """
  1512. self.add_permissions('extras.view_script')
  1513. url = reverse('extras:script_result', kwargs={'job_pk': self.allowed_job.pk})
  1514. self.assertHttpStatus(self.client.get(url), 404)
  1515. url = reverse('extras:script_result', kwargs={'job_pk': self.secret_job.pk})
  1516. self.assertHttpStatus(self.client.get(url), 404)
  1517. def test_get_export_output_without_view_job_permission_returns_404(self):
  1518. """
  1519. Regression for the PoC: the ?export=output path must not leak job.data['output']
  1520. when the user lacks core.view_job.
  1521. """
  1522. self.add_permissions('extras.view_script')
  1523. url = reverse('extras:script_result', kwargs={'job_pk': self.secret_job.pk})
  1524. response = self.client.get(url, {'export': 'output'})
  1525. self.assertHttpStatus(response, 404)
  1526. self.assertNotIn(self.SECRET_OUTPUT.encode(), response.content)
  1527. def test_get_with_constrained_view_job_permission(self):
  1528. """
  1529. With core.view_job constrained to the allowed job only, the user can fetch the allowed
  1530. result but the secret result is hidden (404).
  1531. """
  1532. self.add_permissions('extras.view_script')
  1533. obj_perm = ObjectPermission(
  1534. name='View allowed job only',
  1535. constraints={'pk': self.allowed_job.pk},
  1536. actions=['view'],
  1537. )
  1538. obj_perm.save()
  1539. obj_perm.users.add(self.user)
  1540. obj_perm.object_types.add(ObjectType.objects.get_for_model(Job))
  1541. url = reverse('extras:script_result', kwargs={'job_pk': self.allowed_job.pk})
  1542. self.assertHttpStatus(self.client.get(url), 200)
  1543. url = reverse('extras:script_result', kwargs={'job_pk': self.secret_job.pk})
  1544. response = self.client.get(url, {'export': 'output'})
  1545. self.assertHttpStatus(response, 404)
  1546. self.assertNotIn(self.SECRET_OUTPUT.encode(), response.content)
  1547. class ScriptJobsRestrictionTestCase(TestCase):
  1548. """
  1549. Script views must display only the Jobs which the user is permitted to view.
  1550. """
  1551. # ScriptModule is a proxy model, so viewing it is governed by its concrete model's permission
  1552. user_permissions = ('extras.view_script', 'core.view_managedfile')
  1553. class TestScriptClass(PythonClass):
  1554. class Meta:
  1555. name = 'Restriction test'
  1556. def run(self, data, commit):
  1557. return 'Complete'
  1558. @classmethod
  1559. def setUpTestData(cls):
  1560. with patch.object(ScriptModule, 'sync_classes'):
  1561. module = ScriptModule.objects.create(
  1562. file_root=ManagedFileRootPathChoices.SCRIPTS,
  1563. file_path='restriction_script.py',
  1564. )
  1565. cls.script = Script.objects.create(module=module, name='Restriction test', is_executable=True)
  1566. cls.other_user = User.objects.create_user(username='otheruser')
  1567. # The other user's Job is the most recent, so that the script list must skip it (rather than
  1568. # hide it) to find the most recent Job the user is permitted to view
  1569. cls.system_job = cls._create_job('system-job', user=None, minutes_ago=30)
  1570. cls.other_job = cls._create_job('other-job', user=cls.other_user, minutes_ago=10)
  1571. @classmethod
  1572. def _create_job(cls, name, user, minutes_ago):
  1573. started = now() - datetime.timedelta(minutes=minutes_ago)
  1574. return Job.objects.create(
  1575. name=name,
  1576. object_type=ObjectType.objects.get_for_model(Script),
  1577. object_id=cls.script.pk,
  1578. status=JobStatusChoices.STATUS_COMPLETED,
  1579. job_id=uuid.uuid4(),
  1580. user=user,
  1581. started=started,
  1582. completed=started,
  1583. )
  1584. def setUp(self):
  1585. super().setUp()
  1586. python_class_patch = patch.object(Script, 'python_class', new=self.TestScriptClass)
  1587. python_class_patch.start()
  1588. self.addCleanup(python_class_patch.stop)
  1589. self.own_job = self._create_job('own-job', user=self.user, minutes_ago=20)
  1590. def _grant_view_job(self, constraints=None):
  1591. obj_perm = ObjectPermission(name='View jobs', constraints=constraints, actions=['view'])
  1592. obj_perm.save()
  1593. obj_perm.users.add(self.user)
  1594. obj_perm.object_types.add(ObjectType.objects.get_for_model(Job))
  1595. def _assert_script_views_show(self, expected_jobs):
  1596. """
  1597. Assert that the script's Jobs table and job count reflect only the expected Jobs.
  1598. """
  1599. response = self.client.get(reverse('extras:script_jobs', kwargs={'pk': self.script.pk}))
  1600. self.assertHttpStatus(response, 200)
  1601. self.assertEqual({row.record for row in response.context['table'].rows}, expected_jobs)
  1602. self.assertEqual(response.context['job_count'], len(expected_jobs))
  1603. for view_name in ('extras:script', 'extras:script_source'):
  1604. response = self.client.get(reverse(view_name, kwargs={'pk': self.script.pk}))
  1605. self.assertHttpStatus(response, 200)
  1606. self.assertEqual(response.context['job_count'], len(expected_jobs))
  1607. def _assert_script_list_shows(self, expected_job):
  1608. """
  1609. Assert that the script list displays the expected Job (or none) as the script's most recent result.
  1610. """
  1611. response = self.client.get(reverse('extras:script_list'))
  1612. self.assertHttpStatus(response, 200)
  1613. content = response.content.decode()
  1614. for job in (self.own_job, self.other_job, self.system_job):
  1615. result_url = reverse('extras:script_result', kwargs={'job_pk': job.pk})
  1616. if job == expected_job:
  1617. self.assertIn(result_url, content)
  1618. else:
  1619. self.assertNotIn(result_url, content)
  1620. def test_unconstrained_permission(self):
  1621. self._grant_view_job()
  1622. self._assert_script_views_show({self.own_job, self.other_job, self.system_job})
  1623. self._assert_script_list_shows(self.other_job)
  1624. def test_user_constrained_permission(self):
  1625. self._grant_view_job(constraints={'user': '$user'})
  1626. self._assert_script_views_show({self.own_job})
  1627. self._assert_script_list_shows(self.own_job)
  1628. def test_without_view_job_permission(self):
  1629. self._assert_script_views_show(set())
  1630. self._assert_script_list_shows(None)
  1631. class ScriptSourceViewTestCase(TestCase):
  1632. """
  1633. The Source tab must show the script's actual location in the scripts storage backend,
  1634. not a path derived from the current working directory (#23511).
  1635. """
  1636. user_permissions = ['extras.view_script']
  1637. SCRIPT_CONTENT = (
  1638. "from extras.scripts import Script\n\n\n"
  1639. "class TestScript(Script):\n pass\n"
  1640. )
  1641. @classmethod
  1642. def setUpTestData(cls):
  1643. with patch.object(ScriptModule, 'sync_classes'):
  1644. cls.module = ScriptModule.objects.create(
  1645. file_root=ManagedFileRootPathChoices.SCRIPTS,
  1646. file_path='test_script.py',
  1647. )
  1648. cls.script = Script.objects.create(module=cls.module, name='TestScript', is_executable=True)
  1649. def setUp(self):
  1650. super().setUp()
  1651. content = self.SCRIPT_CONTENT.encode()
  1652. class _Storage:
  1653. def open(self, name, mode='rb'):
  1654. if 'b' in mode:
  1655. return io.BytesIO(content)
  1656. return io.StringIO(content.decode())
  1657. self._module_storage_patch = patch('extras.models.mixins.storages')
  1658. self._script_storage_patch = patch('extras.scripts.storages')
  1659. module_storage = self._module_storage_patch.start()
  1660. script_storage = self._script_storage_patch.start()
  1661. module_storage.__getitem__.return_value = _Storage()
  1662. script_storage.backends = {'scripts': {}}
  1663. script_storage.create_storage.return_value = _Storage()
  1664. self.addCleanup(self._script_storage_patch.stop)
  1665. self.addCleanup(self._module_storage_patch.stop)
  1666. def test_source_view_shows_storage_location(self):
  1667. url = reverse('extras:script_source', kwargs={'pk': self.script.pk})
  1668. response = self.client.get(url)
  1669. self.assertHttpStatus(response, 200)
  1670. self.assertContains(response, self.module.full_path)
  1671. self.assertContains(response, 'class TestScript(Script):')