api_admin.py 110 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575
  1. # -*- encoding: utf8 -*-
  2. #
  3. # The Qubes OS Project, http://www.qubes-os.org
  4. #
  5. # Copyright (C) 2017 Marek Marczykowski-Górecki
  6. # <marmarek@invisiblethingslab.com>
  7. #
  8. # This program is free software; you can redistribute it and/or modify
  9. # it under the terms of the GNU General Public License as published by
  10. # the Free Software Foundation; either version 2 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License along
  19. # with this program; if not, see <http://www.gnu.org/licenses/>.
  20. ''' Tests for management calls endpoints '''
  21. import asyncio
  22. import operator
  23. import os
  24. import shutil
  25. import tempfile
  26. import unittest.mock
  27. import libvirt
  28. import copy
  29. import qubes
  30. import qubes.devices
  31. import qubes.firewall
  32. import qubes.api.admin
  33. import qubes.tests
  34. import qubes.storage
  35. # properties defined in API
  36. volume_properties = [
  37. 'pool', 'vid', 'size', 'usage', 'rw', 'source',
  38. 'save_on_stop', 'snap_on_start']
  39. class AdminAPITestCase(qubes.tests.QubesTestCase):
  40. def setUp(self):
  41. super().setUp()
  42. self.test_base_dir = '/tmp/qubes-test-dir'
  43. self.base_dir_patch = unittest.mock.patch.dict(qubes.config.system_path,
  44. {'qubes_base_dir': self.test_base_dir})
  45. self.base_dir_patch2 = unittest.mock.patch(
  46. 'qubes.config.qubes_base_dir', self.test_base_dir)
  47. self.base_dir_patch3 = unittest.mock.patch.dict(
  48. qubes.config.defaults['pool_configs']['varlibqubes'],
  49. {'dir_path': self.test_base_dir})
  50. self.base_dir_patch.start()
  51. self.base_dir_patch2.start()
  52. self.base_dir_patch3.start()
  53. app = qubes.Qubes('/tmp/qubes-test.xml', load=False)
  54. app.vmm = unittest.mock.Mock(spec=qubes.app.VMMConnection)
  55. app.load_initial_values()
  56. app.default_kernel = '1.0'
  57. app.default_netvm = None
  58. self.template = app.add_new_vm('TemplateVM', label='black',
  59. name='test-template')
  60. app.default_template = 'test-template'
  61. with qubes.tests.substitute_entry_points('qubes.storage',
  62. 'qubes.tests.storage'):
  63. app.add_pool('test', driver='test')
  64. app.default_pool = 'varlibqubes'
  65. app.save = unittest.mock.Mock()
  66. self.vm = app.add_new_vm('AppVM', label='red', name='test-vm1',
  67. template='test-template')
  68. self.app = app
  69. libvirt_attrs = {
  70. 'libvirt_conn.lookupByUUID.return_value.isActive.return_value':
  71. False,
  72. 'libvirt_conn.lookupByUUID.return_value.state.return_value':
  73. [libvirt.VIR_DOMAIN_SHUTOFF],
  74. }
  75. app.vmm.configure_mock(**libvirt_attrs)
  76. self.emitter = qubes.tests.TestEmitter()
  77. self.app.domains[0].fire_event = self.emitter.fire_event
  78. def tearDown(self):
  79. self.base_dir_patch3.stop()
  80. self.base_dir_patch2.stop()
  81. self.base_dir_patch.stop()
  82. if os.path.exists(self.test_base_dir):
  83. shutil.rmtree(self.test_base_dir)
  84. del self.vm
  85. del self.template
  86. self.app.close()
  87. del self.app
  88. del self.emitter
  89. super(AdminAPITestCase, self).tearDown()
  90. def call_mgmt_func(self, method, dest, arg=b'', payload=b''):
  91. mgmt_obj = qubes.api.admin.QubesAdminAPI(self.app, b'dom0', method, dest, arg)
  92. loop = asyncio.get_event_loop()
  93. response = loop.run_until_complete(
  94. mgmt_obj.execute(untrusted_payload=payload))
  95. self.assertEventFired(self.emitter,
  96. 'admin-permission:' + method.decode('ascii'))
  97. return response
  98. class TC_00_VMs(AdminAPITestCase):
  99. def test_000_vm_list(self):
  100. value = self.call_mgmt_func(b'admin.vm.List', b'dom0')
  101. self.assertEqual(value,
  102. 'dom0 class=AdminVM state=Running\n'
  103. 'test-template class=TemplateVM state=Halted\n'
  104. 'test-vm1 class=AppVM state=Halted\n')
  105. def test_001_vm_list_single(self):
  106. value = self.call_mgmt_func(b'admin.vm.List', b'test-vm1')
  107. self.assertEqual(value,
  108. 'test-vm1 class=AppVM state=Halted\n')
  109. def test_010_vm_property_list(self):
  110. # this test is kind of stupid, but at least check if appropriate
  111. # admin-permission event is fired
  112. value = self.call_mgmt_func(b'admin.vm.property.List', b'test-vm1')
  113. properties = self.app.domains['test-vm1'].property_list()
  114. self.assertEqual(value,
  115. ''.join('{}\n'.format(prop.__name__) for prop in properties))
  116. def test_020_vm_property_get_str(self):
  117. value = self.call_mgmt_func(b'admin.vm.property.Get', b'test-vm1',
  118. b'name')
  119. self.assertEqual(value, 'default=False type=str test-vm1')
  120. def test_021_vm_property_get_int(self):
  121. value = self.call_mgmt_func(b'admin.vm.property.Get', b'test-vm1',
  122. b'vcpus')
  123. self.assertEqual(value, 'default=True type=int 2')
  124. def test_022_vm_property_get_bool(self):
  125. value = self.call_mgmt_func(b'admin.vm.property.Get', b'test-vm1',
  126. b'provides_network')
  127. self.assertEqual(value, 'default=True type=bool False')
  128. def test_023_vm_property_get_label(self):
  129. value = self.call_mgmt_func(b'admin.vm.property.Get', b'test-vm1',
  130. b'label')
  131. self.assertEqual(value, 'default=False type=label red')
  132. def test_024_vm_property_get_vm(self):
  133. value = self.call_mgmt_func(b'admin.vm.property.Get', b'test-vm1',
  134. b'template')
  135. self.assertEqual(value, 'default=False type=vm test-template')
  136. def test_025_vm_property_get_vm_none(self):
  137. value = self.call_mgmt_func(b'admin.vm.property.Get', b'test-vm1',
  138. b'netvm')
  139. self.assertEqual(value, 'default=True type=vm ')
  140. def test_030_vm_property_set_vm(self):
  141. netvm = self.app.add_new_vm('AppVM', label='red', name='test-net',
  142. template='test-template', provides_network=True)
  143. with unittest.mock.patch('qubes.vm.VMProperty.__set__') as mock:
  144. value = self.call_mgmt_func(b'admin.vm.property.Set', b'test-vm1',
  145. b'netvm', b'test-net')
  146. self.assertIsNone(value)
  147. mock.assert_called_once_with(self.vm, 'test-net')
  148. self.app.save.assert_called_once_with()
  149. def test_0301_vm_property_set_vm_none(self):
  150. netvm = self.app.add_new_vm('AppVM', label='red', name='test-net',
  151. template='test-template', provides_network=True)
  152. with unittest.mock.patch('qubes.vm.VMProperty.__set__') as mock:
  153. value = self.call_mgmt_func(b'admin.vm.property.Set', b'test-vm1',
  154. b'netvm', b'')
  155. self.assertIsNone(value)
  156. mock.assert_called_once_with(self.vm, '')
  157. self.app.save.assert_called_once_with()
  158. def test_032_vm_property_set_vm_invalid1(self):
  159. with unittest.mock.patch('qubes.vm.VMProperty.__set__') as mock:
  160. with self.assertRaises(qubes.exc.QubesValueError):
  161. self.call_mgmt_func(b'admin.vm.property.Set', b'test-vm1',
  162. b'netvm', b'forbidden-chars/../!')
  163. self.assertFalse(mock.called)
  164. self.assertFalse(self.app.save.called)
  165. def test_033_vm_property_set_vm_invalid2(self):
  166. with unittest.mock.patch('qubes.vm.VMProperty.__set__') as mock:
  167. with self.assertRaises(qubes.exc.QubesValueError):
  168. self.call_mgmt_func(b'admin.vm.property.Set', b'test-vm1',
  169. b'netvm', b'\x80\x90\xa0')
  170. self.assertFalse(mock.called)
  171. self.assertFalse(self.app.save.called)
  172. def test_034_vm_propert_set_bool_true(self):
  173. with unittest.mock.patch('qubes.property.__set__') as mock:
  174. value = self.call_mgmt_func(b'admin.vm.property.Set', b'test-vm1',
  175. b'autostart', b'True')
  176. self.assertIsNone(value)
  177. mock.assert_called_once_with(self.vm, True)
  178. self.app.save.assert_called_once_with()
  179. def test_035_vm_propert_set_bool_false(self):
  180. with unittest.mock.patch('qubes.property.__set__') as mock:
  181. value = self.call_mgmt_func(b'admin.vm.property.Set', b'test-vm1',
  182. b'autostart', b'False')
  183. self.assertIsNone(value)
  184. mock.assert_called_once_with(self.vm, False)
  185. self.app.save.assert_called_once_with()
  186. def test_036_vm_propert_set_bool_invalid1(self):
  187. with unittest.mock.patch('qubes.property.__set__') as mock:
  188. with self.assertRaises(qubes.exc.QubesValueError):
  189. self.call_mgmt_func(b'admin.vm.property.Set', b'test-vm1',
  190. b'autostart', b'some string')
  191. self.assertFalse(mock.called)
  192. self.assertFalse(self.app.save.called)
  193. def test_037_vm_propert_set_bool_invalid2(self):
  194. with unittest.mock.patch('qubes.property.__set__') as mock:
  195. with self.assertRaises(qubes.exc.QubesValueError):
  196. self.call_mgmt_func(b'admin.vm.property.Set', b'test-vm1',
  197. b'autostart', b'\x80\x90@#$%^&*(')
  198. self.assertFalse(mock.called)
  199. self.assertFalse(self.app.save.called)
  200. def test_038_vm_propert_set_str(self):
  201. with unittest.mock.patch('qubes.property.__set__') as mock:
  202. value = self.call_mgmt_func(b'admin.vm.property.Set', b'test-vm1',
  203. b'kernel', b'1.0')
  204. self.assertIsNone(value)
  205. mock.assert_called_once_with(self.vm, '1.0')
  206. self.app.save.assert_called_once_with()
  207. def test_039_vm_propert_set_str_invalid1(self):
  208. with unittest.mock.patch('qubes.property.__set__') as mock:
  209. with self.assertRaises(qubes.exc.QubesValueError):
  210. self.call_mgmt_func(b'admin.vm.property.Set', b'test-vm1',
  211. b'kernel', b'some, non-ASCII: \x80\xd2')
  212. self.assertFalse(mock.called)
  213. self.assertFalse(self.app.save.called)
  214. def test_040_vm_propert_set_int(self):
  215. with unittest.mock.patch('qubes.property.__set__') as mock:
  216. value = self.call_mgmt_func(b'admin.vm.property.Set', b'test-vm1',
  217. b'maxmem', b'1024000')
  218. self.assertIsNone(value)
  219. mock.assert_called_once_with(self.vm, 1024000)
  220. self.app.save.assert_called_once_with()
  221. def test_041_vm_propert_set_int_invalid1(self):
  222. with unittest.mock.patch('qubes.property.__set__') as mock:
  223. with self.assertRaises(qubes.exc.QubesValueError):
  224. self.call_mgmt_func(b'admin.vm.property.Set', b'test-vm1',
  225. b'maxmem', b'fourty two')
  226. self.assertFalse(mock.called)
  227. self.assertFalse(self.app.save.called)
  228. def test_042_vm_propert_set_label(self):
  229. with unittest.mock.patch('qubes.property.__set__') as mock:
  230. value = self.call_mgmt_func(b'admin.vm.property.Set', b'test-vm1',
  231. b'label', b'green')
  232. self.assertIsNone(value)
  233. mock.assert_called_once_with(self.vm, 'green')
  234. self.app.save.assert_called_once_with()
  235. def test_043_vm_propert_set_label_invalid1(self):
  236. with unittest.mock.patch('qubes.property.__set__') as mock:
  237. with self.assertRaises(qubes.exc.QubesValueError):
  238. self.call_mgmt_func(b'admin.vm.property.Set', b'test-vm1',
  239. b'maxmem', b'some, non-ASCII: \x80\xd2')
  240. self.assertFalse(mock.called)
  241. self.assertFalse(self.app.save.called)
  242. @unittest.skip('label existence not checked before actual setter yet')
  243. def test_044_vm_propert_set_label_invalid2(self):
  244. with unittest.mock.patch('qubes.property.__set__') as mock:
  245. with self.assertRaises(qubes.exc.QubesValueError):
  246. self.call_mgmt_func(b'admin.vm.property.Set', b'test-vm1',
  247. b'maxmem', b'non-existing-color')
  248. self.assertFalse(mock.called)
  249. self.assertFalse(self.app.save.called)
  250. def test_050_vm_property_help(self):
  251. value = self.call_mgmt_func(b'admin.vm.property.Help', b'test-vm1',
  252. b'label')
  253. self.assertEqual(value,
  254. 'Colourful label assigned to VM. This is where the colour of the '
  255. 'padlock is set.')
  256. self.assertFalse(self.app.save.called)
  257. def test_052_vm_property_help_invalid_property(self):
  258. with self.assertRaises(qubes.exc.QubesNoSuchPropertyError):
  259. self.call_mgmt_func(b'admin.vm.property.Help', b'test-vm1',
  260. b'no-such-property')
  261. self.assertFalse(self.app.save.called)
  262. def test_060_vm_property_reset(self):
  263. with unittest.mock.patch('qubes.property.__delete__') as mock:
  264. value = self.call_mgmt_func(b'admin.vm.property.Reset', b'test-vm1',
  265. b'default_user')
  266. mock.assert_called_with(self.vm)
  267. self.assertIsNone(value)
  268. self.app.save.assert_called_once_with()
  269. def test_062_vm_property_reset_invalid_property(self):
  270. with unittest.mock.patch('qubes.property.__delete__') as mock:
  271. with self.assertRaises(qubes.exc.QubesNoSuchPropertyError):
  272. self.call_mgmt_func(b'admin.vm.property.Help', b'test-vm1',
  273. b'no-such-property')
  274. self.assertFalse(mock.called)
  275. self.assertFalse(self.app.save.called)
  276. def test_070_vm_volume_list(self):
  277. self.vm.volumes = unittest.mock.Mock()
  278. volumes_conf = {
  279. 'keys.return_value': ['root', 'private', 'volatile', 'kernel']
  280. }
  281. self.vm.volumes.configure_mock(**volumes_conf)
  282. value = self.call_mgmt_func(b'admin.vm.volume.List', b'test-vm1')
  283. self.assertEqual(value, 'root\nprivate\nvolatile\nkernel\n')
  284. # check if _only_ keys were accessed
  285. self.assertEqual(self.vm.volumes.mock_calls,
  286. [unittest.mock.call.keys()])
  287. def test_080_vm_volume_info(self):
  288. self.vm.volumes = unittest.mock.MagicMock()
  289. volumes_conf = {
  290. 'keys.return_value': ['root', 'private', 'volatile', 'kernel']
  291. }
  292. for prop in volume_properties:
  293. volumes_conf[
  294. '__getitem__.return_value.{}'.format(prop)] = prop +'-value'
  295. self.vm.volumes.configure_mock(**volumes_conf)
  296. value = self.call_mgmt_func(b'admin.vm.volume.Info', b'test-vm1',
  297. b'private')
  298. self.assertEqual(value,
  299. ''.join('{p}={p}-value\n'.format(p=p) for p in volume_properties))
  300. self.assertEqual(self.vm.volumes.mock_calls,
  301. [unittest.mock.call.keys(),
  302. unittest.mock.call.__getattr__('__getitem__')('private')])
  303. def test_080_vm_volume_info_invalid_volume(self):
  304. self.vm.volumes = unittest.mock.MagicMock()
  305. volumes_conf = {
  306. 'keys.return_value': ['root', 'private', 'volatile', 'kernel']
  307. }
  308. self.vm.volumes.configure_mock(**volumes_conf)
  309. with self.assertRaises(AssertionError):
  310. self.call_mgmt_func(b'admin.vm.volume.Info', b'test-vm1',
  311. b'no-such-volume')
  312. self.assertEqual(self.vm.volumes.mock_calls,
  313. [unittest.mock.call.keys()])
  314. def test_090_vm_volume_listsnapshots(self):
  315. self.vm.volumes = unittest.mock.MagicMock()
  316. volumes_conf = {
  317. 'keys.return_value': ['root', 'private', 'volatile', 'kernel'],
  318. '__getitem__.return_value.revisions': ['rev1', 'rev2'],
  319. }
  320. self.vm.volumes.configure_mock(**volumes_conf)
  321. value = self.call_mgmt_func(b'admin.vm.volume.ListSnapshots',
  322. b'test-vm1', b'private')
  323. self.assertEqual(value,
  324. 'rev1\nrev2\n')
  325. self.assertEqual(self.vm.volumes.mock_calls,
  326. [unittest.mock.call.keys(),
  327. unittest.mock.call.__getattr__('__getitem__')('private')])
  328. def test_090_vm_volume_listsnapshots_invalid_volume(self):
  329. self.vm.volumes = unittest.mock.MagicMock()
  330. volumes_conf = {
  331. 'keys.return_value': ['root', 'private', 'volatile', 'kernel']
  332. }
  333. self.vm.volumes.configure_mock(**volumes_conf)
  334. with self.assertRaises(AssertionError):
  335. self.call_mgmt_func(b'admin.vm.volume.ListSnapshots', b'test-vm1',
  336. b'no-such-volume')
  337. self.assertEqual(self.vm.volumes.mock_calls,
  338. [unittest.mock.call.keys()])
  339. @unittest.skip('method not implemented yet')
  340. def test_100_vm_volume_snapshot(self):
  341. pass
  342. @unittest.skip('method not implemented yet')
  343. def test_100_vm_volume_snapshot_invalid_volume(self):
  344. self.vm.volumes = unittest.mock.MagicMock()
  345. volumes_conf = {
  346. 'keys.return_value': ['root', 'private', 'volatile', 'kernel'],
  347. '__getitem__.return_value.revisions': ['rev1', 'rev2'],
  348. }
  349. self.vm.volumes.configure_mock(**volumes_conf)
  350. with self.assertRaises(AssertionError):
  351. self.call_mgmt_func(b'admin.vm.volume.Snapshots',
  352. b'test-vm1', b'no-such-volume')
  353. self.assertEqual(self.vm.volumes.mock_calls,
  354. [unittest.mock.call.keys()])
  355. @unittest.skip('method not implemented yet')
  356. def test_100_vm_volume_snapshot_invalid_revision(self):
  357. self.vm.volumes = unittest.mock.MagicMock()
  358. volumes_conf = {
  359. 'keys.return_value': ['root', 'private', 'volatile', 'kernel']
  360. }
  361. self.vm.volumes.configure_mock(**volumes_conf)
  362. with self.assertRaises(AssertionError):
  363. self.call_mgmt_func(b'admin.vm.volume.Snapshots',
  364. b'test-vm1', b'private', b'no-such-rev')
  365. self.assertEqual(self.vm.volumes.mock_calls,
  366. [unittest.mock.call.keys(),
  367. unittest.mock.call.__getattr__('__getitem__')('private')])
  368. def test_110_vm_volume_revert(self):
  369. self.vm.volumes = unittest.mock.MagicMock()
  370. volumes_conf = {
  371. 'keys.return_value': ['root', 'private', 'volatile', 'kernel'],
  372. '__getitem__.return_value.revisions': ['rev1', 'rev2'],
  373. }
  374. self.vm.volumes.configure_mock(**volumes_conf)
  375. del self.vm.volumes['private'].revert('rev1')._is_coroutine
  376. self.vm.storage = unittest.mock.Mock()
  377. value = self.call_mgmt_func(b'admin.vm.volume.Revert',
  378. b'test-vm1', b'private', b'rev1')
  379. self.assertIsNone(value)
  380. self.assertEqual(self.vm.volumes.mock_calls, [
  381. ('__getitem__', ('private', ), {}),
  382. ('__getitem__().revert', ('rev1', ), {}),
  383. ('keys', (), {}),
  384. ('__getitem__', ('private', ), {}),
  385. ('__getitem__().__hash__', (), {}),
  386. ('__getitem__().revert', ('rev1', ), {}),
  387. ])
  388. self.assertEqual(self.vm.storage.mock_calls, [])
  389. def test_110_vm_volume_revert_invalid_rev(self):
  390. self.vm.volumes = unittest.mock.MagicMock()
  391. volumes_conf = {
  392. 'keys.return_value': ['root', 'private', 'volatile', 'kernel'],
  393. '__getitem__.return_value.revisions': ['rev1', 'rev2'],
  394. }
  395. self.vm.volumes.configure_mock(**volumes_conf)
  396. self.vm.storage = unittest.mock.Mock()
  397. with self.assertRaises(AssertionError):
  398. self.call_mgmt_func(b'admin.vm.volume.Revert',
  399. b'test-vm1', b'private', b'no-such-rev')
  400. self.assertEqual(self.vm.volumes.mock_calls,
  401. [unittest.mock.call.keys(),
  402. unittest.mock.call.__getattr__('__getitem__')('private')])
  403. self.assertFalse(self.vm.storage.called)
  404. def test_120_vm_volume_resize(self):
  405. self.vm.volumes = unittest.mock.MagicMock()
  406. volumes_conf = {
  407. 'keys.return_value': ['root', 'private', 'volatile', 'kernel'],
  408. }
  409. self.vm.volumes.configure_mock(**volumes_conf)
  410. self.vm.storage = unittest.mock.Mock()
  411. self.vm.storage.resize.side_effect = self.dummy_coro
  412. value = self.call_mgmt_func(b'admin.vm.volume.Resize',
  413. b'test-vm1', b'private', b'1024000000')
  414. self.assertIsNone(value)
  415. self.assertEqual(self.vm.volumes.mock_calls,
  416. [unittest.mock.call.keys()])
  417. self.assertEqual(self.vm.storage.mock_calls,
  418. [unittest.mock.call.resize('private', 1024000000)])
  419. def test_120_vm_volume_resize_invalid_size1(self):
  420. self.vm.volumes = unittest.mock.MagicMock()
  421. volumes_conf = {
  422. 'keys.return_value': ['root', 'private', 'volatile', 'kernel'],
  423. }
  424. self.vm.volumes.configure_mock(**volumes_conf)
  425. self.vm.storage = unittest.mock.Mock()
  426. self.vm.storage.resize.side_effect = self.dummy_coro
  427. with self.assertRaises(AssertionError):
  428. self.call_mgmt_func(b'admin.vm.volume.Resize',
  429. b'test-vm1', b'private', b'no-int-size')
  430. self.assertEqual(self.vm.volumes.mock_calls,
  431. [unittest.mock.call.keys()])
  432. self.assertFalse(self.vm.storage.called)
  433. def test_120_vm_volume_resize_invalid_size2(self):
  434. self.vm.volumes = unittest.mock.MagicMock()
  435. volumes_conf = {
  436. 'keys.return_value': ['root', 'private', 'volatile', 'kernel'],
  437. }
  438. self.vm.volumes.configure_mock(**volumes_conf)
  439. self.vm.storage = unittest.mock.Mock()
  440. self.vm.storage.resize.side_effect = self.dummy_coro
  441. with self.assertRaises(AssertionError):
  442. self.call_mgmt_func(b'admin.vm.volume.Resize',
  443. b'test-vm1', b'private', b'-1')
  444. self.assertEqual(self.vm.volumes.mock_calls,
  445. [unittest.mock.call.keys()])
  446. self.assertFalse(self.vm.storage.called)
  447. def test_130_pool_list(self):
  448. self.app.pools = ['file', 'lvm']
  449. value = self.call_mgmt_func(b'admin.pool.List', b'dom0')
  450. self.assertEqual(value, 'file\nlvm\n')
  451. self.assertFalse(self.app.save.called)
  452. @unittest.mock.patch('qubes.storage.pool_drivers')
  453. @unittest.mock.patch('qubes.storage.driver_parameters')
  454. def test_140_pool_listdrivers(self, mock_parameters, mock_drivers):
  455. self.app.pools = ['file', 'lvm']
  456. mock_drivers.return_value = ['driver1', 'driver2']
  457. mock_parameters.side_effect = \
  458. lambda driver: {
  459. 'driver1': ['param1', 'param2'],
  460. 'driver2': ['param3', 'param4']
  461. }[driver]
  462. value = self.call_mgmt_func(b'admin.pool.ListDrivers', b'dom0')
  463. self.assertEqual(value,
  464. 'driver1 param1 param2\ndriver2 param3 param4\n')
  465. self.assertEqual(mock_drivers.mock_calls, [unittest.mock.call()])
  466. self.assertEqual(mock_parameters.mock_calls,
  467. [unittest.mock.call('driver1'), unittest.mock.call('driver2')])
  468. self.assertFalse(self.app.save.called)
  469. def test_150_pool_info(self):
  470. self.app.pools = {
  471. 'pool1': unittest.mock.Mock(config={
  472. 'param1': 'value1', 'param2': 'value2'})
  473. }
  474. value = self.call_mgmt_func(b'admin.pool.Info', b'dom0', b'pool1')
  475. self.assertEqual(value, 'param1=value1\nparam2=value2\n')
  476. self.assertFalse(self.app.save.called)
  477. @unittest.mock.patch('qubes.storage.pool_drivers')
  478. @unittest.mock.patch('qubes.storage.driver_parameters')
  479. def test_160_pool_add(self, mock_parameters, mock_drivers):
  480. self.app.pools = {
  481. 'file': unittest.mock.Mock(),
  482. 'lvm': unittest.mock.Mock()
  483. }
  484. mock_drivers.return_value = ['driver1', 'driver2']
  485. mock_parameters.side_effect = \
  486. lambda driver: {
  487. 'driver1': ['param1', 'param2'],
  488. 'driver2': ['param3', 'param4']
  489. }[driver]
  490. self.app.add_pool = unittest.mock.Mock()
  491. value = self.call_mgmt_func(b'admin.pool.Add', b'dom0', b'driver1',
  492. b'name=test-pool\nparam1=some-value\n')
  493. self.assertIsNone(value)
  494. self.assertEqual(mock_drivers.mock_calls, [unittest.mock.call()])
  495. self.assertEqual(mock_parameters.mock_calls,
  496. [unittest.mock.call('driver1')])
  497. self.assertEqual(self.app.add_pool.mock_calls,
  498. [unittest.mock.call(name='test-pool', driver='driver1',
  499. param1='some-value')])
  500. self.assertTrue(self.app.save.called)
  501. @unittest.mock.patch('qubes.storage.pool_drivers')
  502. @unittest.mock.patch('qubes.storage.driver_parameters')
  503. def test_160_pool_add_invalid_driver(self, mock_parameters, mock_drivers):
  504. self.app.pools = {
  505. 'file': unittest.mock.Mock(),
  506. 'lvm': unittest.mock.Mock()
  507. }
  508. mock_drivers.return_value = ['driver1', 'driver2']
  509. mock_parameters.side_effect = \
  510. lambda driver: {
  511. 'driver1': ['param1', 'param2'],
  512. 'driver2': ['param3', 'param4']
  513. }[driver]
  514. self.app.add_pool = unittest.mock.Mock()
  515. with self.assertRaises(AssertionError):
  516. self.call_mgmt_func(b'admin.pool.Add', b'dom0',
  517. b'no-such-driver', b'name=test-pool\nparam1=some-value\n')
  518. self.assertEqual(mock_drivers.mock_calls, [unittest.mock.call()])
  519. self.assertEqual(mock_parameters.mock_calls, [])
  520. self.assertEqual(self.app.add_pool.mock_calls, [])
  521. self.assertFalse(self.app.save.called)
  522. @unittest.mock.patch('qubes.storage.pool_drivers')
  523. @unittest.mock.patch('qubes.storage.driver_parameters')
  524. def test_160_pool_add_invalid_param(self, mock_parameters, mock_drivers):
  525. self.app.pools = {
  526. 'file': unittest.mock.Mock(),
  527. 'lvm': unittest.mock.Mock()
  528. }
  529. mock_drivers.return_value = ['driver1', 'driver2']
  530. mock_parameters.side_effect = \
  531. lambda driver: {
  532. 'driver1': ['param1', 'param2'],
  533. 'driver2': ['param3', 'param4']
  534. }[driver]
  535. self.app.add_pool = unittest.mock.Mock()
  536. with self.assertRaises(AssertionError):
  537. self.call_mgmt_func(b'admin.pool.Add', b'dom0',
  538. b'driver1', b'name=test-pool\nparam3=some-value\n')
  539. self.assertEqual(mock_drivers.mock_calls, [unittest.mock.call()])
  540. self.assertEqual(mock_parameters.mock_calls,
  541. [unittest.mock.call('driver1')])
  542. self.assertEqual(self.app.add_pool.mock_calls, [])
  543. self.assertFalse(self.app.save.called)
  544. @unittest.mock.patch('qubes.storage.pool_drivers')
  545. @unittest.mock.patch('qubes.storage.driver_parameters')
  546. def test_160_pool_add_missing_name(self, mock_parameters, mock_drivers):
  547. self.app.pools = {
  548. 'file': unittest.mock.Mock(),
  549. 'lvm': unittest.mock.Mock()
  550. }
  551. mock_drivers.return_value = ['driver1', 'driver2']
  552. mock_parameters.side_effect = \
  553. lambda driver: {
  554. 'driver1': ['param1', 'param2'],
  555. 'driver2': ['param3', 'param4']
  556. }[driver]
  557. self.app.add_pool = unittest.mock.Mock()
  558. with self.assertRaises(AssertionError):
  559. self.call_mgmt_func(b'admin.pool.Add', b'dom0',
  560. b'driver1', b'param1=value\nparam2=some-value\n')
  561. self.assertEqual(mock_drivers.mock_calls, [unittest.mock.call()])
  562. self.assertEqual(mock_parameters.mock_calls, [])
  563. self.assertEqual(self.app.add_pool.mock_calls, [])
  564. self.assertFalse(self.app.save.called)
  565. @unittest.mock.patch('qubes.storage.pool_drivers')
  566. @unittest.mock.patch('qubes.storage.driver_parameters')
  567. def test_160_pool_add_existing_pool(self, mock_parameters, mock_drivers):
  568. self.app.pools = {
  569. 'file': unittest.mock.Mock(),
  570. 'lvm': unittest.mock.Mock()
  571. }
  572. mock_drivers.return_value = ['driver1', 'driver2']
  573. mock_parameters.side_effect = \
  574. lambda driver: {
  575. 'driver1': ['param1', 'param2'],
  576. 'driver2': ['param3', 'param4']
  577. }[driver]
  578. self.app.add_pool = unittest.mock.Mock()
  579. with self.assertRaises(AssertionError):
  580. self.call_mgmt_func(b'admin.pool.Add', b'dom0',
  581. b'driver1', b'name=file\nparam1=value\nparam2=some-value\n')
  582. self.assertEqual(mock_drivers.mock_calls, [unittest.mock.call()])
  583. self.assertEqual(mock_parameters.mock_calls, [])
  584. self.assertEqual(self.app.add_pool.mock_calls, [])
  585. self.assertFalse(self.app.save.called)
  586. @unittest.mock.patch('qubes.storage.pool_drivers')
  587. @unittest.mock.patch('qubes.storage.driver_parameters')
  588. def test_160_pool_add_invalid_config_format(self, mock_parameters,
  589. mock_drivers):
  590. self.app.pools = {
  591. 'file': unittest.mock.Mock(),
  592. 'lvm': unittest.mock.Mock()
  593. }
  594. mock_drivers.return_value = ['driver1', 'driver2']
  595. mock_parameters.side_effect = \
  596. lambda driver: {
  597. 'driver1': ['param1', 'param2'],
  598. 'driver2': ['param3', 'param4']
  599. }[driver]
  600. self.app.add_pool = unittest.mock.Mock()
  601. with self.assertRaises(AssertionError):
  602. self.call_mgmt_func(b'admin.pool.Add', b'dom0',
  603. b'driver1', b'name=test-pool\nparam 1=value\n_param2\n')
  604. self.assertEqual(mock_drivers.mock_calls, [unittest.mock.call()])
  605. self.assertEqual(mock_parameters.mock_calls, [])
  606. self.assertEqual(self.app.add_pool.mock_calls, [])
  607. self.assertFalse(self.app.save.called)
  608. def test_170_pool_remove(self):
  609. self.app.pools = {
  610. 'file': unittest.mock.Mock(),
  611. 'lvm': unittest.mock.Mock(),
  612. 'test-pool': unittest.mock.Mock(),
  613. }
  614. self.app.remove_pool = unittest.mock.Mock()
  615. value = self.call_mgmt_func(b'admin.pool.Remove', b'dom0', b'test-pool')
  616. self.assertIsNone(value)
  617. self.assertEqual(self.app.remove_pool.mock_calls,
  618. [unittest.mock.call('test-pool')])
  619. self.assertTrue(self.app.save.called)
  620. def test_170_pool_remove_invalid_pool(self):
  621. self.app.pools = {
  622. 'file': unittest.mock.Mock(),
  623. 'lvm': unittest.mock.Mock(),
  624. 'test-pool': unittest.mock.Mock(),
  625. }
  626. self.app.remove_pool = unittest.mock.Mock()
  627. with self.assertRaises(AssertionError):
  628. self.call_mgmt_func(b'admin.pool.Remove', b'dom0',
  629. b'no-such-pool')
  630. self.assertEqual(self.app.remove_pool.mock_calls, [])
  631. self.assertFalse(self.app.save.called)
  632. def test_180_label_list(self):
  633. value = self.call_mgmt_func(b'admin.label.List', b'dom0')
  634. self.assertEqual(value,
  635. ''.join('{}\n'.format(l.name) for l in self.app.labels.values()))
  636. self.assertFalse(self.app.save.called)
  637. def test_190_label_get(self):
  638. self.app.get_label = unittest.mock.Mock()
  639. self.app.get_label.configure_mock(**{'return_value.color': '0xff0000'})
  640. value = self.call_mgmt_func(b'admin.label.Get', b'dom0', b'red')
  641. self.assertEqual(value, '0xff0000')
  642. self.assertEqual(self.app.get_label.mock_calls,
  643. [unittest.mock.call('red')])
  644. self.assertFalse(self.app.save.called)
  645. def test_195_label_index(self):
  646. self.app.get_label = unittest.mock.Mock()
  647. self.app.get_label.configure_mock(**{'return_value.index': 1})
  648. value = self.call_mgmt_func(b'admin.label.Index', b'dom0', b'red')
  649. self.assertEqual(value, '1')
  650. self.assertEqual(self.app.get_label.mock_calls,
  651. [unittest.mock.call('red')])
  652. self.assertFalse(self.app.save.called)
  653. def test_200_label_create(self):
  654. self.app.get_label = unittest.mock.Mock()
  655. self.app.get_label.side_effect=KeyError
  656. self.app.labels = unittest.mock.MagicMock()
  657. labels_config = {
  658. 'keys.return_value': range(1, 9),
  659. }
  660. self.app.labels.configure_mock(**labels_config)
  661. value = self.call_mgmt_func(b'admin.label.Create', b'dom0', b'cyan',
  662. b'0x00ffff')
  663. self.assertIsNone(value)
  664. self.assertEqual(self.app.get_label.mock_calls,
  665. [unittest.mock.call('cyan')])
  666. self.assertEqual(self.app.labels.mock_calls,
  667. [unittest.mock.call.keys(),
  668. unittest.mock.call.__getattr__('__setitem__')(9,
  669. qubes.Label(9, '0x00ffff', 'cyan'))])
  670. self.assertTrue(self.app.save.called)
  671. def test_200_label_create_invalid_color(self):
  672. self.app.get_label = unittest.mock.Mock()
  673. self.app.get_label.side_effect=KeyError
  674. self.app.labels = unittest.mock.MagicMock()
  675. labels_config = {
  676. 'keys.return_value': range(1, 9),
  677. }
  678. self.app.labels.configure_mock(**labels_config)
  679. with self.assertRaises(AssertionError):
  680. self.call_mgmt_func(b'admin.label.Create', b'dom0', b'cyan',
  681. b'abcd')
  682. self.assertEqual(self.app.get_label.mock_calls,
  683. [unittest.mock.call('cyan')])
  684. self.assertEqual(self.app.labels.mock_calls, [])
  685. self.assertFalse(self.app.save.called)
  686. def test_200_label_create_invalid_name(self):
  687. self.app.get_label = unittest.mock.Mock()
  688. self.app.get_label.side_effect=KeyError
  689. self.app.labels = unittest.mock.MagicMock()
  690. labels_config = {
  691. 'keys.return_value': range(1, 9),
  692. }
  693. self.app.labels.configure_mock(**labels_config)
  694. with self.assertRaises(AssertionError):
  695. self.call_mgmt_func(b'admin.label.Create', b'dom0', b'01',
  696. b'0xff0000')
  697. with self.assertRaises(AssertionError):
  698. self.call_mgmt_func(b'admin.label.Create', b'dom0', b'../xxx',
  699. b'0xff0000')
  700. with self.assertRaises(AssertionError):
  701. self.call_mgmt_func(b'admin.label.Create', b'dom0',
  702. b'strange-name!@#$',
  703. b'0xff0000')
  704. self.assertEqual(self.app.get_label.mock_calls, [])
  705. self.assertEqual(self.app.labels.mock_calls, [])
  706. self.assertFalse(self.app.save.called)
  707. def test_200_label_create_already_exists(self):
  708. self.app.get_label = unittest.mock.Mock(wraps=self.app.get_label)
  709. with self.assertRaises(qubes.exc.QubesValueError):
  710. self.call_mgmt_func(b'admin.label.Create', b'dom0', b'red',
  711. b'abcd')
  712. self.assertEqual(self.app.get_label.mock_calls,
  713. [unittest.mock.call('red')])
  714. self.assertFalse(self.app.save.called)
  715. def test_210_label_remove(self):
  716. label = qubes.Label(9, '0x00ffff', 'cyan')
  717. self.app.labels[9] = label
  718. self.app.get_label = unittest.mock.Mock(wraps=self.app.get_label,
  719. **{'return_value.index': 9})
  720. self.app.labels = unittest.mock.MagicMock(wraps=self.app.labels)
  721. value = self.call_mgmt_func(b'admin.label.Remove', b'dom0', b'cyan')
  722. self.assertIsNone(value)
  723. self.assertEqual(self.app.get_label.mock_calls,
  724. [unittest.mock.call('cyan')])
  725. self.assertEqual(self.app.labels.mock_calls,
  726. [unittest.mock.call.__delitem__(9)])
  727. self.assertTrue(self.app.save.called)
  728. def test_210_label_remove_invalid_label(self):
  729. with self.assertRaises(qubes.exc.QubesValueError):
  730. self.call_mgmt_func(b'admin.label.Remove', b'dom0',
  731. b'no-such-label')
  732. self.assertFalse(self.app.save.called)
  733. def test_210_label_remove_default_label(self):
  734. self.app.labels = unittest.mock.MagicMock(wraps=self.app.labels)
  735. self.app.get_label = unittest.mock.Mock(wraps=self.app.get_label,
  736. **{'return_value.index': 6})
  737. with self.assertRaises(AssertionError):
  738. self.call_mgmt_func(b'admin.label.Remove', b'dom0',
  739. b'blue')
  740. self.assertEqual(self.app.labels.mock_calls, [])
  741. self.assertFalse(self.app.save.called)
  742. def test_210_label_remove_in_use(self):
  743. self.app.labels = unittest.mock.MagicMock(wraps=self.app.labels)
  744. self.app.get_label = unittest.mock.Mock(wraps=self.app.get_label,
  745. **{'return_value.index': 1})
  746. with self.assertRaises(AssertionError):
  747. self.call_mgmt_func(b'admin.label.Remove', b'dom0',
  748. b'red')
  749. self.assertEqual(self.app.labels.mock_calls, [])
  750. self.assertFalse(self.app.save.called)
  751. def test_220_start(self):
  752. func_mock = unittest.mock.Mock()
  753. @asyncio.coroutine
  754. def coroutine_mock(*args, **kwargs):
  755. return func_mock(*args, **kwargs)
  756. self.vm.start = coroutine_mock
  757. value = self.call_mgmt_func(b'admin.vm.Start', b'test-vm1')
  758. self.assertIsNone(value)
  759. func_mock.assert_called_once_with()
  760. def test_230_shutdown(self):
  761. func_mock = unittest.mock.Mock()
  762. @asyncio.coroutine
  763. def coroutine_mock(*args, **kwargs):
  764. return func_mock(*args, **kwargs)
  765. self.vm.shutdown = coroutine_mock
  766. value = self.call_mgmt_func(b'admin.vm.Shutdown', b'test-vm1')
  767. self.assertIsNone(value)
  768. func_mock.assert_called_once_with()
  769. def test_240_pause(self):
  770. func_mock = unittest.mock.Mock()
  771. @asyncio.coroutine
  772. def coroutine_mock(*args, **kwargs):
  773. return func_mock(*args, **kwargs)
  774. self.vm.pause = coroutine_mock
  775. value = self.call_mgmt_func(b'admin.vm.Pause', b'test-vm1')
  776. self.assertIsNone(value)
  777. func_mock.assert_called_once_with()
  778. def test_250_unpause(self):
  779. func_mock = unittest.mock.Mock()
  780. @asyncio.coroutine
  781. def coroutine_mock(*args, **kwargs):
  782. return func_mock(*args, **kwargs)
  783. self.vm.unpause = coroutine_mock
  784. value = self.call_mgmt_func(b'admin.vm.Unpause', b'test-vm1')
  785. self.assertIsNone(value)
  786. func_mock.assert_called_once_with()
  787. def test_260_kill(self):
  788. func_mock = unittest.mock.Mock()
  789. @asyncio.coroutine
  790. def coroutine_mock(*args, **kwargs):
  791. return func_mock(*args, **kwargs)
  792. self.vm.kill = coroutine_mock
  793. value = self.call_mgmt_func(b'admin.vm.Kill', b'test-vm1')
  794. self.assertIsNone(value)
  795. func_mock.assert_called_once_with()
  796. def test_270_events(self):
  797. send_event = unittest.mock.Mock(spec=[])
  798. mgmt_obj = qubes.api.admin.QubesAdminAPI(self.app, b'dom0', b'admin.Events',
  799. b'dom0', b'', send_event=send_event)
  800. @asyncio.coroutine
  801. def fire_event():
  802. self.vm.fire_event('test-event', arg1='abc')
  803. mgmt_obj.cancel()
  804. loop = asyncio.get_event_loop()
  805. execute_task = asyncio.ensure_future(
  806. mgmt_obj.execute(untrusted_payload=b''))
  807. asyncio.ensure_future(fire_event())
  808. loop.run_until_complete(execute_task)
  809. self.assertIsNone(execute_task.result())
  810. self.assertEventFired(self.emitter,
  811. 'admin-permission:' + 'admin.Events')
  812. self.assertEqual(send_event.mock_calls,
  813. [
  814. unittest.mock.call(self.app, 'connection-established'),
  815. unittest.mock.call(self.vm, 'test-event', arg1='abc')
  816. ])
  817. def test_271_events_add_vm(self):
  818. send_event = unittest.mock.Mock(spec=[])
  819. mgmt_obj = qubes.api.admin.QubesAdminAPI(self.app, b'dom0', b'admin.Events',
  820. b'dom0', b'', send_event=send_event)
  821. @asyncio.coroutine
  822. def fire_event():
  823. self.vm.fire_event('test-event', arg1='abc')
  824. # add VM _after_ starting admin.Events call
  825. vm = self.app.add_new_vm('AppVM', label='red', name='test-vm2',
  826. template='test-template')
  827. vm.fire_event('test-event2', arg1='abc')
  828. mgmt_obj.cancel()
  829. return vm
  830. loop = asyncio.get_event_loop()
  831. execute_task = asyncio.ensure_future(
  832. mgmt_obj.execute(untrusted_payload=b''))
  833. event_task = asyncio.ensure_future(fire_event())
  834. loop.run_until_complete(execute_task)
  835. vm2 = event_task.result()
  836. self.assertIsNone(execute_task.result())
  837. self.assertEventFired(self.emitter,
  838. 'admin-permission:' + 'admin.Events')
  839. self.assertEqual(send_event.mock_calls,
  840. [
  841. unittest.mock.call(self.app, 'connection-established'),
  842. unittest.mock.call(self.vm, 'test-event', arg1='abc'),
  843. unittest.mock.call(self.app, 'domain-add', vm=vm2),
  844. unittest.mock.call(vm2, 'test-event2', arg1='abc'),
  845. ])
  846. def test_280_feature_list(self):
  847. self.vm.features['test-feature'] = 'some-value'
  848. value = self.call_mgmt_func(b'admin.vm.feature.List', b'test-vm1')
  849. self.assertEqual(value, 'test-feature\n')
  850. self.assertFalse(self.app.save.called)
  851. def test_290_feature_get(self):
  852. self.vm.features['test-feature'] = 'some-value'
  853. value = self.call_mgmt_func(b'admin.vm.feature.Get', b'test-vm1',
  854. b'test-feature')
  855. self.assertEqual(value, 'some-value')
  856. self.assertFalse(self.app.save.called)
  857. def test_291_feature_get_none(self):
  858. with self.assertRaises(qubes.exc.QubesFeatureNotFoundError):
  859. self.call_mgmt_func(b'admin.vm.feature.Get',
  860. b'test-vm1', b'test-feature')
  861. self.assertFalse(self.app.save.called)
  862. def test_300_feature_remove(self):
  863. self.vm.features['test-feature'] = 'some-value'
  864. value = self.call_mgmt_func(b'admin.vm.feature.Remove', b'test-vm1',
  865. b'test-feature')
  866. self.assertIsNone(value, None)
  867. self.assertNotIn('test-feature', self.vm.features)
  868. self.assertTrue(self.app.save.called)
  869. def test_301_feature_remove_none(self):
  870. with self.assertRaises(qubes.exc.QubesFeatureNotFoundError):
  871. self.call_mgmt_func(b'admin.vm.feature.Remove',
  872. b'test-vm1', b'test-feature')
  873. self.assertFalse(self.app.save.called)
  874. def test_310_feature_checkwithtemplate(self):
  875. self.vm.features['test-feature'] = 'some-value'
  876. value = self.call_mgmt_func(b'admin.vm.feature.CheckWithTemplate',
  877. b'test-vm1', b'test-feature')
  878. self.assertEqual(value, 'some-value')
  879. self.assertFalse(self.app.save.called)
  880. def test_311_feature_checkwithtemplate_tpl(self):
  881. self.template.features['test-feature'] = 'some-value'
  882. value = self.call_mgmt_func(b'admin.vm.feature.CheckWithTemplate',
  883. b'test-vm1', b'test-feature')
  884. self.assertEqual(value, 'some-value')
  885. self.assertFalse(self.app.save.called)
  886. def test_312_feature_checkwithtemplate_none(self):
  887. with self.assertRaises(qubes.exc.QubesFeatureNotFoundError):
  888. self.call_mgmt_func(b'admin.vm.feature.CheckWithTemplate',
  889. b'test-vm1', b'test-feature')
  890. self.assertFalse(self.app.save.called)
  891. def test_320_feature_set(self):
  892. value = self.call_mgmt_func(b'admin.vm.feature.Set',
  893. b'test-vm1', b'test-feature', b'some-value')
  894. self.assertIsNone(value)
  895. self.assertEqual(self.vm.features['test-feature'], 'some-value')
  896. self.assertTrue(self.app.save.called)
  897. def test_321_feature_set_empty(self):
  898. value = self.call_mgmt_func(b'admin.vm.feature.Set',
  899. b'test-vm1', b'test-feature', b'')
  900. self.assertIsNone(value)
  901. self.assertEqual(self.vm.features['test-feature'], '')
  902. self.assertTrue(self.app.save.called)
  903. def test_320_feature_set_invalid(self):
  904. with self.assertRaises(UnicodeDecodeError):
  905. self.call_mgmt_func(b'admin.vm.feature.Set',
  906. b'test-vm1', b'test-feature', b'\x02\x03\xffsome-value')
  907. self.assertNotIn('test-feature', self.vm.features)
  908. self.assertFalse(self.app.save.called)
  909. @asyncio.coroutine
  910. def dummy_coro(self, *args, **kwargs):
  911. pass
  912. @unittest.mock.patch('qubes.storage.Storage.create')
  913. def test_330_vm_create_standalone(self, storage_mock):
  914. storage_mock.side_effect = self.dummy_coro
  915. self.call_mgmt_func(b'admin.vm.Create.StandaloneVM',
  916. b'dom0', b'', b'name=test-vm2 label=red')
  917. self.assertIn('test-vm2', self.app.domains)
  918. vm = self.app.domains['test-vm2']
  919. self.assertIsInstance(vm, qubes.vm.standalonevm.StandaloneVM)
  920. self.assertEqual(vm.label, self.app.get_label('red'))
  921. self.assertEqual(storage_mock.mock_calls,
  922. [unittest.mock.call(self.app.domains['test-vm2']).create()])
  923. self.assertTrue(os.path.exists(os.path.join(
  924. self.test_base_dir, 'appvms', 'test-vm2')))
  925. self.assertTrue(self.app.save.called)
  926. @unittest.mock.patch('qubes.storage.Storage.create')
  927. def test_331_vm_create_standalone_spurious_template(self, storage_mock):
  928. storage_mock.side_effect = self.dummy_coro
  929. with self.assertRaises(AssertionError):
  930. self.call_mgmt_func(b'admin.vm.Create.StandaloneVM',
  931. b'dom0', b'test-template', b'name=test-vm2 label=red')
  932. self.assertNotIn('test-vm2', self.app.domains)
  933. self.assertEqual(storage_mock.mock_calls, [])
  934. self.assertFalse(os.path.exists(os.path.join(
  935. self.test_base_dir, 'appvms', 'test-vm2')))
  936. self.assertNotIn('test-vm2', self.app.domains)
  937. self.assertFalse(self.app.save.called)
  938. @unittest.mock.patch('qubes.storage.Storage.create')
  939. def test_332_vm_create_app(self, storage_mock):
  940. storage_mock.side_effect = self.dummy_coro
  941. self.call_mgmt_func(b'admin.vm.Create.AppVM',
  942. b'dom0', b'test-template', b'name=test-vm2 label=red')
  943. self.assertIn('test-vm2', self.app.domains)
  944. vm = self.app.domains['test-vm2']
  945. self.assertEqual(vm.label, self.app.get_label('red'))
  946. self.assertEqual(vm.template, self.app.domains['test-template'])
  947. self.assertEqual(storage_mock.mock_calls,
  948. [unittest.mock.call(self.app.domains['test-vm2']).create()])
  949. self.assertTrue(os.path.exists(os.path.join(
  950. self.test_base_dir, 'appvms', 'test-vm2')))
  951. self.assertTrue(self.app.save.called)
  952. @unittest.mock.patch('qubes.storage.Storage.create')
  953. def test_333_vm_create_app_default_template(self, storage_mock):
  954. storage_mock.side_effect = self.dummy_coro
  955. self.call_mgmt_func(b'admin.vm.Create.AppVM',
  956. b'dom0', b'', b'name=test-vm2 label=red')
  957. self.assertEqual(storage_mock.mock_calls,
  958. [unittest.mock.call(self.app.domains['test-vm2']).create()])
  959. self.assertIn('test-vm2', self.app.domains)
  960. self.assertEqual(self.app.domains['test-vm2'].template,
  961. self.app.default_template)
  962. self.assertTrue(self.app.save.called)
  963. @unittest.mock.patch('qubes.storage.Storage.create')
  964. def test_334_vm_create_invalid_name(self, storage_mock):
  965. storage_mock.side_effect = self.dummy_coro
  966. with self.assertRaises(qubes.exc.QubesValueError):
  967. self.call_mgmt_func(b'admin.vm.Create.AppVM',
  968. b'dom0', b'test-template', b'name=test-###')
  969. self.assertNotIn('test-###', self.app.domains)
  970. self.assertFalse(self.app.save.called)
  971. @unittest.mock.patch('qubes.storage.Storage.create')
  972. def test_335_vm_create_missing_name(self, storage_mock):
  973. storage_mock.side_effect = self.dummy_coro
  974. with self.assertRaises(AssertionError):
  975. self.call_mgmt_func(b'admin.vm.Create.AppVM',
  976. b'dom0', b'test-template', b'label=red')
  977. self.assertFalse(self.app.save.called)
  978. @unittest.mock.patch('qubes.storage.Storage.create')
  979. def test_336_vm_create_spurious_pool(self, storage_mock):
  980. storage_mock.side_effect = self.dummy_coro
  981. with self.assertRaises(AssertionError):
  982. self.call_mgmt_func(b'admin.vm.Create.AppVM',
  983. b'dom0', b'test-template',
  984. b'name=test-vm2 label=red pool=default')
  985. self.assertNotIn('test-vm2', self.app.domains)
  986. self.assertFalse(self.app.save.called)
  987. @unittest.mock.patch('qubes.storage.Storage.create')
  988. def test_337_vm_create_duplicate_name(self, storage_mock):
  989. storage_mock.side_effect = self.dummy_coro
  990. with self.assertRaises(qubes.exc.QubesException):
  991. self.call_mgmt_func(b'admin.vm.Create.AppVM',
  992. b'dom0', b'test-template',
  993. b'name=test-vm1 label=red')
  994. self.assertFalse(self.app.save.called)
  995. @unittest.mock.patch('qubes.storage.Storage.create')
  996. def test_338_vm_create_name_twice(self, storage_mock):
  997. storage_mock.side_effect = self.dummy_coro
  998. with self.assertRaises(AssertionError):
  999. self.call_mgmt_func(b'admin.vm.Create.AppVM',
  1000. b'dom0', b'test-template',
  1001. b'name=test-vm2 name=test-vm3 label=red')
  1002. self.assertNotIn('test-vm2', self.app.domains)
  1003. self.assertNotIn('test-vm3', self.app.domains)
  1004. self.assertFalse(self.app.save.called)
  1005. @unittest.mock.patch('qubes.storage.Storage.create')
  1006. def test_340_vm_create_in_pool_app(self, storage_mock):
  1007. storage_mock.side_effect = self.dummy_coro
  1008. self.call_mgmt_func(b'admin.vm.CreateInPool.AppVM',
  1009. b'dom0', b'test-template', b'name=test-vm2 label=red '
  1010. b'pool=test')
  1011. self.assertIn('test-vm2', self.app.domains)
  1012. vm = self.app.domains['test-vm2']
  1013. self.assertEqual(vm.label, self.app.get_label('red'))
  1014. self.assertEqual(vm.template, self.app.domains['test-template'])
  1015. # setting pool= affect only volumes actually created for this VM,
  1016. # not used from a template or so
  1017. self.assertEqual(vm.volume_config['root']['pool'],
  1018. self.template.volumes['root'].pool)
  1019. self.assertEqual(vm.volume_config['private']['pool'], 'test')
  1020. self.assertEqual(vm.volume_config['volatile']['pool'], 'test')
  1021. self.assertEqual(vm.volume_config['kernel']['pool'], 'linux-kernel')
  1022. self.assertEqual(storage_mock.mock_calls,
  1023. [unittest.mock.call(self.app.domains['test-vm2']).create()])
  1024. self.assertTrue(os.path.exists(os.path.join(
  1025. self.test_base_dir, 'appvms', 'test-vm2')))
  1026. self.assertTrue(self.app.save.called)
  1027. @unittest.mock.patch('qubes.storage.Storage.create')
  1028. def test_341_vm_create_in_pool_private(self, storage_mock):
  1029. storage_mock.side_effect = self.dummy_coro
  1030. self.call_mgmt_func(b'admin.vm.CreateInPool.AppVM',
  1031. b'dom0', b'test-template', b'name=test-vm2 label=red '
  1032. b'pool:private=test')
  1033. self.assertIn('test-vm2', self.app.domains)
  1034. vm = self.app.domains['test-vm2']
  1035. self.assertEqual(vm.label, self.app.get_label('red'))
  1036. self.assertEqual(vm.template, self.app.domains['test-template'])
  1037. self.assertEqual(vm.volume_config['root']['pool'],
  1038. self.template.volumes['root'].pool)
  1039. self.assertEqual(vm.volume_config['private']['pool'], 'test')
  1040. self.assertEqual(vm.volume_config['volatile']['pool'],
  1041. self.app.default_pool_volatile)
  1042. self.assertEqual(vm.volume_config['kernel']['pool'], 'linux-kernel')
  1043. self.assertEqual(storage_mock.mock_calls,
  1044. [unittest.mock.call(self.app.domains['test-vm2']).create()])
  1045. self.assertTrue(os.path.exists(os.path.join(
  1046. self.test_base_dir, 'appvms', 'test-vm2')))
  1047. self.assertTrue(self.app.save.called)
  1048. @unittest.mock.patch('qubes.storage.Storage.create')
  1049. def test_342_vm_create_in_pool_invalid_pool(self, storage_mock):
  1050. storage_mock.side_effect = self.dummy_coro
  1051. with self.assertRaises(qubes.exc.QubesException):
  1052. self.call_mgmt_func(b'admin.vm.CreateInPool.AppVM',
  1053. b'dom0', b'test-template', b'name=test-vm2 label=red '
  1054. b'pool=no-such-pool')
  1055. self.assertFalse(self.app.save.called)
  1056. @unittest.mock.patch('qubes.storage.Storage.create')
  1057. def test_343_vm_create_in_pool_invalid_pool2(self, storage_mock):
  1058. storage_mock.side_effect = self.dummy_coro
  1059. with self.assertRaises(qubes.exc.QubesException):
  1060. self.call_mgmt_func(b'admin.vm.CreateInPool.AppVM',
  1061. b'dom0', b'test-template', b'name=test-vm2 label=red '
  1062. b'pool:private=no-such-pool')
  1063. self.assertNotIn('test-vm2', self.app.domains)
  1064. self.assertFalse(self.app.save.called)
  1065. @unittest.mock.patch('qubes.storage.Storage.create')
  1066. def test_344_vm_create_in_pool_invalid_volume(self, storage_mock):
  1067. storage_mock.side_effect = self.dummy_coro
  1068. with self.assertRaises(AssertionError):
  1069. self.call_mgmt_func(b'admin.vm.CreateInPool.AppVM',
  1070. b'dom0', b'test-template', b'name=test-vm2 label=red '
  1071. b'pool:invalid=test')
  1072. self.assertNotIn('test-vm2', self.app.domains)
  1073. self.assertFalse(self.app.save.called)
  1074. @unittest.mock.patch('qubes.storage.Storage.create')
  1075. def test_345_vm_create_in_pool_app_root(self, storage_mock):
  1076. # setting custom pool for 'root' volume of AppVM should not be
  1077. # allowed - this volume belongs to the template
  1078. storage_mock.side_effect = self.dummy_coro
  1079. with self.assertRaises(qubes.exc.QubesException):
  1080. self.call_mgmt_func(b'admin.vm.CreateInPool.AppVM',
  1081. b'dom0', b'test-template', b'name=test-vm2 label=red '
  1082. b'pool:root=test')
  1083. self.assertNotIn('test-vm2', self.app.domains)
  1084. self.assertFalse(self.app.save.called)
  1085. @unittest.mock.patch('qubes.storage.Storage.create')
  1086. def test_346_vm_create_in_pool_duplicate_pool(self, storage_mock):
  1087. # setting custom pool for 'root' volume of AppVM should not be
  1088. # allowed - this volume belongs to the template
  1089. storage_mock.side_effect = self.dummy_coro
  1090. with self.assertRaises(AssertionError):
  1091. self.call_mgmt_func(b'admin.vm.CreateInPool.AppVM',
  1092. b'dom0', b'test-template', b'name=test-vm2 label=red '
  1093. b'pool=test pool:root=test')
  1094. self.assertNotIn('test-vm2', self.app.domains)
  1095. self.assertFalse(self.app.save.called)
  1096. def test_400_property_list(self):
  1097. # actual function tested for admin.vm.property.* already
  1098. # this test is kind of stupid, but at least check if appropriate
  1099. # admin-permission event is fired
  1100. value = self.call_mgmt_func(b'admin.property.List', b'dom0')
  1101. properties = self.app.property_list()
  1102. self.assertEqual(value,
  1103. ''.join('{}\n'.format(prop.__name__) for prop in properties))
  1104. def test_410_property_get_str(self):
  1105. # actual function tested for admin.vm.property.* already
  1106. value = self.call_mgmt_func(b'admin.property.Get', b'dom0',
  1107. b'default_kernel')
  1108. self.assertEqual(value, 'default=False type=str 1.0')
  1109. def test_420_propert_set_str(self):
  1110. # actual function tested for admin.vm.property.* already
  1111. with unittest.mock.patch('qubes.property.__set__') as mock:
  1112. value = self.call_mgmt_func(b'admin.property.Set', b'dom0',
  1113. b'default_kernel', b'1.0')
  1114. self.assertIsNone(value)
  1115. mock.assert_called_once_with(self.app, '1.0')
  1116. self.app.save.assert_called_once_with()
  1117. def test_440_property_help(self):
  1118. # actual function tested for admin.vm.property.* already
  1119. value = self.call_mgmt_func(b'admin.property.Help', b'dom0',
  1120. b'clockvm')
  1121. self.assertEqual(value,
  1122. 'Which VM to use as NTP proxy for updating AdminVM')
  1123. self.assertFalse(self.app.save.called)
  1124. def test_450_property_reset(self):
  1125. # actual function tested for admin.vm.property.* already
  1126. with unittest.mock.patch('qubes.property.__delete__') as mock:
  1127. value = self.call_mgmt_func(b'admin.property.Reset', b'dom0',
  1128. b'clockvm')
  1129. mock.assert_called_with(self.app)
  1130. self.assertIsNone(value)
  1131. self.app.save.assert_called_once_with()
  1132. def device_list_testclass(self, vm, event):
  1133. if vm is not self.vm:
  1134. return
  1135. dev = qubes.devices.DeviceInfo(self.vm, '1234')
  1136. dev.description = 'Some device'
  1137. dev.extra_prop = 'xx'
  1138. yield dev
  1139. dev = qubes.devices.DeviceInfo(self.vm, '4321')
  1140. dev.description = 'Some other device'
  1141. yield dev
  1142. def test_460_vm_device_available(self):
  1143. self.vm.add_handler('device-list:testclass', self.device_list_testclass)
  1144. value = self.call_mgmt_func(b'admin.vm.device.testclass.Available',
  1145. b'test-vm1')
  1146. self.assertEqual(value,
  1147. '1234 extra_prop=xx description=Some '
  1148. 'device\n'
  1149. '4321 description=Some other device\n')
  1150. self.assertFalse(self.app.save.called)
  1151. def test_461_vm_device_available_specific(self):
  1152. self.vm.add_handler('device-list:testclass', self.device_list_testclass)
  1153. value = self.call_mgmt_func(b'admin.vm.device.testclass.Available',
  1154. b'test-vm1', b'4321')
  1155. self.assertEqual(value,
  1156. '4321 description=Some other device\n')
  1157. self.assertFalse(self.app.save.called)
  1158. def test_462_vm_device_available_invalid(self):
  1159. self.vm.add_handler('device-list:testclass', self.device_list_testclass)
  1160. value = self.call_mgmt_func(b'admin.vm.device.testclass.Available',
  1161. b'test-vm1', b'no-such-device')
  1162. self.assertEqual(value, '')
  1163. self.assertFalse(self.app.save.called)
  1164. def test_470_vm_device_list_persistent(self):
  1165. assignment = qubes.devices.DeviceAssignment(self.vm, '1234',
  1166. persistent=True)
  1167. self.loop.run_until_complete(
  1168. self.vm.devices['testclass'].attach(assignment))
  1169. value = self.call_mgmt_func(b'admin.vm.device.testclass.List',
  1170. b'test-vm1')
  1171. self.assertEqual(value,
  1172. 'test-vm1+1234 persistent=yes\n')
  1173. self.assertFalse(self.app.save.called)
  1174. def test_471_vm_device_list_persistent_options(self):
  1175. assignment = qubes.devices.DeviceAssignment(self.vm, '1234',
  1176. persistent=True, options={'opt1': 'value'})
  1177. self.loop.run_until_complete(
  1178. self.vm.devices['testclass'].attach(assignment))
  1179. assignment = qubes.devices.DeviceAssignment(self.vm, '4321',
  1180. persistent=True)
  1181. self.loop.run_until_complete(
  1182. self.vm.devices['testclass'].attach(assignment))
  1183. value = self.call_mgmt_func(b'admin.vm.device.testclass.List',
  1184. b'test-vm1')
  1185. self.assertEqual(value,
  1186. 'test-vm1+1234 opt1=value persistent=yes\n'
  1187. 'test-vm1+4321 persistent=yes\n')
  1188. self.assertFalse(self.app.save.called)
  1189. def device_list_attached_testclass(self, vm, event, **kwargs):
  1190. if vm is not self.vm:
  1191. return
  1192. dev = qubes.devices.DeviceInfo(self.vm, '1234')
  1193. yield (dev, {'attach_opt': 'value'})
  1194. def test_472_vm_device_list_temporary(self):
  1195. self.vm.add_handler('device-list-attached:testclass',
  1196. self.device_list_attached_testclass)
  1197. value = self.call_mgmt_func(b'admin.vm.device.testclass.List',
  1198. b'test-vm1')
  1199. self.assertEqual(value,
  1200. 'test-vm1+1234 attach_opt=value persistent=no\n')
  1201. self.assertFalse(self.app.save.called)
  1202. def test_473_vm_device_list_mixed(self):
  1203. self.vm.add_handler('device-list-attached:testclass',
  1204. self.device_list_attached_testclass)
  1205. assignment = qubes.devices.DeviceAssignment(self.vm, '4321',
  1206. persistent=True)
  1207. self.loop.run_until_complete(
  1208. self.vm.devices['testclass'].attach(assignment))
  1209. value = self.call_mgmt_func(b'admin.vm.device.testclass.List',
  1210. b'test-vm1')
  1211. self.assertEqual(value,
  1212. 'test-vm1+1234 attach_opt=value persistent=no\n'
  1213. 'test-vm1+4321 persistent=yes\n')
  1214. self.assertFalse(self.app.save.called)
  1215. def test_474_vm_device_list_specific(self):
  1216. self.vm.add_handler('device-list-attached:testclass',
  1217. self.device_list_attached_testclass)
  1218. assignment = qubes.devices.DeviceAssignment(self.vm, '4321',
  1219. persistent=True)
  1220. self.loop.run_until_complete(
  1221. self.vm.devices['testclass'].attach(assignment))
  1222. value = self.call_mgmt_func(b'admin.vm.device.testclass.List',
  1223. b'test-vm1', b'test-vm1+1234')
  1224. self.assertEqual(value,
  1225. 'test-vm1+1234 attach_opt=value persistent=no\n')
  1226. self.assertFalse(self.app.save.called)
  1227. def test_480_vm_device_attach(self):
  1228. self.vm.add_handler('device-list:testclass', self.device_list_testclass)
  1229. mock_attach = unittest.mock.Mock()
  1230. mock_attach.return_value = None
  1231. del mock_attach._is_coroutine
  1232. self.vm.add_handler('device-attach:testclass', mock_attach)
  1233. with unittest.mock.patch.object(qubes.vm.qubesvm.QubesVM,
  1234. 'is_halted', lambda _: False):
  1235. value = self.call_mgmt_func(b'admin.vm.device.testclass.Attach',
  1236. b'test-vm1', b'test-vm1+1234')
  1237. self.assertIsNone(value)
  1238. mock_attach.assert_called_once_with(self.vm, 'device-attach:testclass',
  1239. device=self.vm.devices['testclass']['1234'],
  1240. options={})
  1241. self.assertEqual(len(self.vm.devices['testclass'].persistent()), 0)
  1242. self.app.save.assert_called_once_with()
  1243. def test_481_vm_device_attach(self):
  1244. self.vm.add_handler('device-list:testclass', self.device_list_testclass)
  1245. mock_attach = unittest.mock.Mock()
  1246. mock_attach.return_value = None
  1247. del mock_attach._is_coroutine
  1248. self.vm.add_handler('device-attach:testclass', mock_attach)
  1249. with unittest.mock.patch.object(qubes.vm.qubesvm.QubesVM,
  1250. 'is_halted', lambda _: False):
  1251. value = self.call_mgmt_func(b'admin.vm.device.testclass.Attach',
  1252. b'test-vm1', b'test-vm1+1234', b'persistent=no')
  1253. self.assertIsNone(value)
  1254. mock_attach.assert_called_once_with(self.vm, 'device-attach:testclass',
  1255. device=self.vm.devices['testclass']['1234'],
  1256. options={})
  1257. self.assertEqual(len(self.vm.devices['testclass'].persistent()), 0)
  1258. self.app.save.assert_called_once_with()
  1259. def test_482_vm_device_attach_not_running(self):
  1260. self.vm.add_handler('device-list:testclass', self.device_list_testclass)
  1261. mock_attach = unittest.mock.Mock()
  1262. del mock_attach._is_coroutine
  1263. self.vm.add_handler('device-attach:testclass', mock_attach)
  1264. with self.assertRaises(qubes.exc.QubesVMNotRunningError):
  1265. self.call_mgmt_func(b'admin.vm.device.testclass.Attach',
  1266. b'test-vm1', b'test-vm1+1234')
  1267. self.assertFalse(mock_attach.called)
  1268. self.assertEqual(len(self.vm.devices['testclass'].persistent()), 0)
  1269. self.assertFalse(self.app.save.called)
  1270. def test_483_vm_device_attach_persistent(self):
  1271. self.vm.add_handler('device-list:testclass', self.device_list_testclass)
  1272. mock_attach = unittest.mock.Mock()
  1273. mock_attach.return_value = None
  1274. del mock_attach._is_coroutine
  1275. self.vm.add_handler('device-attach:testclass', mock_attach)
  1276. with unittest.mock.patch.object(qubes.vm.qubesvm.QubesVM,
  1277. 'is_halted', lambda _: False):
  1278. value = self.call_mgmt_func(b'admin.vm.device.testclass.Attach',
  1279. b'test-vm1', b'test-vm1+1234', b'persistent=yes')
  1280. self.assertIsNone(value)
  1281. dev = self.vm.devices['testclass']['1234']
  1282. mock_attach.assert_called_once_with(self.vm, 'device-attach:testclass',
  1283. device=dev,
  1284. options={})
  1285. self.assertIn(dev, self.vm.devices['testclass'].persistent())
  1286. self.app.save.assert_called_once_with()
  1287. def test_484_vm_device_attach_persistent_not_running(self):
  1288. self.vm.add_handler('device-list:testclass', self.device_list_testclass)
  1289. mock_attach = unittest.mock.Mock()
  1290. mock_attach.return_value = None
  1291. del mock_attach._is_coroutine
  1292. self.vm.add_handler('device-attach:testclass', mock_attach)
  1293. value = self.call_mgmt_func(b'admin.vm.device.testclass.Attach',
  1294. b'test-vm1', b'test-vm1+1234', b'persistent=yes')
  1295. self.assertIsNone(value)
  1296. dev = self.vm.devices['testclass']['1234']
  1297. mock_attach.assert_called_once_with(self.vm, 'device-attach:testclass',
  1298. device=dev,
  1299. options={})
  1300. self.assertIn(dev, self.vm.devices['testclass'].persistent())
  1301. self.app.save.assert_called_once_with()
  1302. def test_485_vm_device_attach_options(self):
  1303. self.vm.add_handler('device-list:testclass', self.device_list_testclass)
  1304. mock_attach = unittest.mock.Mock()
  1305. mock_attach.return_value = None
  1306. del mock_attach._is_coroutine
  1307. self.vm.add_handler('device-attach:testclass', mock_attach)
  1308. with unittest.mock.patch.object(qubes.vm.qubesvm.QubesVM,
  1309. 'is_halted', lambda _: False):
  1310. value = self.call_mgmt_func(b'admin.vm.device.testclass.Attach',
  1311. b'test-vm1', b'test-vm1+1234', b'option1=value2')
  1312. self.assertIsNone(value)
  1313. dev = self.vm.devices['testclass']['1234']
  1314. mock_attach.assert_called_once_with(self.vm, 'device-attach:testclass',
  1315. device=dev,
  1316. options={'option1': 'value2'})
  1317. self.app.save.assert_called_once_with()
  1318. def test_490_vm_device_detach(self):
  1319. self.vm.add_handler('device-list:testclass', self.device_list_testclass)
  1320. self.vm.add_handler('device-list-attached:testclass',
  1321. self.device_list_attached_testclass)
  1322. mock_detach = unittest.mock.Mock()
  1323. mock_detach.return_value = None
  1324. del mock_detach._is_coroutine
  1325. self.vm.add_handler('device-detach:testclass', mock_detach)
  1326. with unittest.mock.patch.object(qubes.vm.qubesvm.QubesVM,
  1327. 'is_halted', lambda _: False):
  1328. value = self.call_mgmt_func(b'admin.vm.device.testclass.Detach',
  1329. b'test-vm1', b'test-vm1+1234')
  1330. self.assertIsNone(value)
  1331. mock_detach.assert_called_once_with(self.vm, 'device-detach:testclass',
  1332. device=self.vm.devices['testclass']['1234'])
  1333. self.app.save.assert_called_once_with()
  1334. def test_491_vm_device_detach_not_attached(self):
  1335. mock_detach = unittest.mock.Mock()
  1336. mock_detach.return_value = None
  1337. del mock_detach._is_coroutine
  1338. self.vm.add_handler('device-detach:testclass', mock_detach)
  1339. with unittest.mock.patch.object(qubes.vm.qubesvm.QubesVM,
  1340. 'is_halted', lambda _: False):
  1341. with self.assertRaises(qubes.devices.DeviceNotAttached):
  1342. self.call_mgmt_func(b'admin.vm.device.testclass.Detach',
  1343. b'test-vm1', b'test-vm1+1234')
  1344. self.assertFalse(mock_detach.called)
  1345. self.assertFalse(self.app.save.called)
  1346. @unittest.mock.patch('qubes.storage.Storage.remove')
  1347. @unittest.mock.patch('shutil.rmtree')
  1348. def test_500_vm_remove(self, mock_rmtree, mock_remove):
  1349. mock_remove.side_effect = self.dummy_coro
  1350. value = self.call_mgmt_func(b'admin.vm.Remove', b'test-vm1')
  1351. self.assertIsNone(value)
  1352. mock_rmtree.assert_called_once_with(
  1353. '/tmp/qubes-test-dir/appvms/test-vm1')
  1354. mock_remove.assert_called_once_with()
  1355. self.app.save.assert_called_once_with()
  1356. @unittest.mock.patch('qubes.storage.Storage.remove')
  1357. @unittest.mock.patch('shutil.rmtree')
  1358. def test_501_vm_remove_running(self, mock_rmtree, mock_remove):
  1359. mock_remove.side_effect = self.dummy_coro
  1360. with unittest.mock.patch.object(
  1361. self.vm, 'get_power_state', lambda: 'Running'):
  1362. with self.assertRaises(qubes.exc.QubesVMNotHaltedError):
  1363. self.call_mgmt_func(b'admin.vm.Remove', b'test-vm1')
  1364. self.assertFalse(mock_rmtree.called)
  1365. self.assertFalse(mock_remove.called)
  1366. self.assertFalse(self.app.save.called)
  1367. def test_510_vm_volume_import(self):
  1368. value = self.call_mgmt_func(b'admin.vm.volume.Import', b'test-vm1',
  1369. b'private')
  1370. self.assertEqual(value, '{} {}'.format(
  1371. 2*2**30, '/tmp/qubes-test-dir/appvms/test-vm1/private.img'))
  1372. self.assertFalse(self.app.save.called)
  1373. def test_511_vm_volume_import_running(self):
  1374. with unittest.mock.patch.object(
  1375. self.vm, 'get_power_state', lambda: 'Running'):
  1376. with self.assertRaises(qubes.exc.QubesVMNotHaltedError):
  1377. self.call_mgmt_func(b'admin.vm.volume.Import', b'test-vm1',
  1378. b'private')
  1379. def setup_for_clone(self):
  1380. self.pool = unittest.mock.MagicMock()
  1381. self.app.pools['test'] = self.pool
  1382. self.vm2 = self.app.add_new_vm('AppVM', label='red',
  1383. name='test-vm2',
  1384. template='test-template', kernel='')
  1385. self.pool.configure_mock(**{
  1386. 'volumes': qubes.storage.VolumesCollection(self.pool),
  1387. 'init_volume.return_value.pool': self.pool,
  1388. '__str__.return_value': 'test',
  1389. 'get_volume.side_effect': (lambda vid:
  1390. self.vm.volumes['private']
  1391. if vid is self.vm.volumes['private'].vid
  1392. else self.vm2.volumes['private']
  1393. ),
  1394. })
  1395. self.loop.run_until_complete(
  1396. self.vm.create_on_disk(pool='test'))
  1397. self.loop.run_until_complete(
  1398. self.vm2.create_on_disk(pool='test'))
  1399. # the call replaces self.vm.volumes[...] with result of import
  1400. # operation - make sure it stays as the same object
  1401. self.vm.volumes['private'].import_volume.return_value = \
  1402. self.vm.volumes['private']
  1403. self.vm2.volumes['private'].import_volume.return_value = \
  1404. self.vm2.volumes['private']
  1405. self.addCleanup(self.cleanup_for_clone)
  1406. def cleanup_for_clone(self):
  1407. del self.vm2
  1408. del self.pool
  1409. def test_520_vm_volume_clone(self):
  1410. self.setup_for_clone()
  1411. token = self.call_mgmt_func(b'admin.vm.volume.CloneFrom',
  1412. b'test-vm1', b'private', b'')
  1413. # token
  1414. self.assertEqual(len(token), 32)
  1415. self.assertFalse(self.app.save.called)
  1416. value = self.call_mgmt_func(b'admin.vm.volume.CloneTo',
  1417. b'test-vm2', b'private', token.encode())
  1418. self.assertIsNone(value)
  1419. self.vm2.volumes['private'].import_volume.assert_called_once_with(
  1420. self.vm.volumes['private']
  1421. )
  1422. self.vm2.volumes['private'].import_volume.assert_called_once_with(
  1423. self.vm2.volumes['private']
  1424. )
  1425. self.app.save.assert_called_once_with()
  1426. def test_521_vm_volume_clone_invalid_volume(self):
  1427. self.setup_for_clone()
  1428. with self.assertRaises(AssertionError):
  1429. self.call_mgmt_func(b'admin.vm.volume.CloneFrom',
  1430. b'test-vm1', b'private123', None)
  1431. self.assertNotIn('init_volume().import_volume',
  1432. map(operator.itemgetter(0), self.pool.mock_calls))
  1433. self.assertFalse(self.app.save.called)
  1434. def test_522_vm_volume_clone_invalid_volume2(self):
  1435. self.setup_for_clone()
  1436. token = self.call_mgmt_func(b'admin.vm.volume.CloneFrom',
  1437. b'test-vm1', b'private', b'')
  1438. with self.assertRaises(AssertionError):
  1439. self.call_mgmt_func(b'admin.vm.volume.CloneTo',
  1440. b'test-vm1', b'private123', token.encode())
  1441. self.assertNotIn('init_volume().import_volume',
  1442. map(operator.itemgetter(0), self.pool.mock_calls))
  1443. self.assertFalse(self.app.save.called)
  1444. def test_523_vm_volume_clone_removed_volume(self):
  1445. self.setup_for_clone()
  1446. token = self.call_mgmt_func(b'admin.vm.volume.CloneFrom',
  1447. b'test-vm1', b'private', b'')
  1448. def get_volume(vid):
  1449. if vid == self.vm.volumes['private']:
  1450. raise KeyError(vid)
  1451. else:
  1452. return unittest.mock.DEFAULT
  1453. self.pool.get_volume.side_effect = get_volume
  1454. with self.assertRaises(AssertionError):
  1455. self.call_mgmt_func(b'admin.vm.volume.CloneTo',
  1456. b'test-vm1', b'private', token.encode())
  1457. self.assertNotIn('init_volume().import_volume',
  1458. map(operator.itemgetter(0), self.pool.mock_calls))
  1459. self.assertFalse(self.app.save.called)
  1460. def test_524_vm_volume_clone_invlid_token(self):
  1461. self.setup_for_clone()
  1462. with self.assertRaises(AssertionError):
  1463. self.call_mgmt_func(b'admin.vm.volume.CloneTo',
  1464. b'test-vm1', b'private', b'no-such-token')
  1465. self.assertNotIn('init_volume().import_volume',
  1466. map(operator.itemgetter(0), self.pool.mock_calls))
  1467. self.assertFalse(self.app.save.called)
  1468. def test_530_tag_list(self):
  1469. self.vm.tags.add('tag1')
  1470. self.vm.tags.add('tag2')
  1471. value = self.call_mgmt_func(b'admin.vm.tag.List', b'test-vm1')
  1472. self.assertEqual(value, 'tag1\ntag2\n')
  1473. self.assertFalse(self.app.save.called)
  1474. def test_540_tag_get(self):
  1475. self.vm.tags.add('tag1')
  1476. value = self.call_mgmt_func(b'admin.vm.tag.Get', b'test-vm1',
  1477. b'tag1')
  1478. self.assertEqual(value, '1')
  1479. self.assertFalse(self.app.save.called)
  1480. def test_541_tag_get_absent(self):
  1481. value = self.call_mgmt_func(b'admin.vm.tag.Get', b'test-vm1', b'tag1')
  1482. self.assertEqual(value, '0')
  1483. self.assertFalse(self.app.save.called)
  1484. def test_550_tag_remove(self):
  1485. self.vm.tags.add('tag1')
  1486. value = self.call_mgmt_func(b'admin.vm.tag.Remove', b'test-vm1',
  1487. b'tag1')
  1488. self.assertIsNone(value, None)
  1489. self.assertNotIn('tag1', self.vm.tags)
  1490. self.assertTrue(self.app.save.called)
  1491. def test_551_tag_remove_absent(self):
  1492. with self.assertRaises(qubes.exc.QubesTagNotFoundError):
  1493. self.call_mgmt_func(b'admin.vm.tag.Remove',
  1494. b'test-vm1', b'tag1')
  1495. self.assertFalse(self.app.save.called)
  1496. def test_560_tag_set(self):
  1497. value = self.call_mgmt_func(b'admin.vm.tag.Set',
  1498. b'test-vm1', b'tag1')
  1499. self.assertIsNone(value)
  1500. self.assertIn('tag1', self.vm.tags)
  1501. self.assertTrue(self.app.save.called)
  1502. def test_561_tag_set_invalid(self):
  1503. with self.assertRaises(AssertionError):
  1504. self.call_mgmt_func(b'admin.vm.tag.Set',
  1505. b'test-vm1', b'+.some-tag')
  1506. self.assertNotIn('+.some-tag', self.vm.tags)
  1507. self.assertFalse(self.app.save.called)
  1508. def test_570_firewall_get(self):
  1509. self.vm.firewall.save = unittest.mock.Mock()
  1510. value = self.call_mgmt_func(b'admin.vm.firewall.Get',
  1511. b'test-vm1', b'')
  1512. self.assertEqual(value, 'action=accept\n')
  1513. self.assertFalse(self.vm.firewall.save.called)
  1514. self.assertFalse(self.app.save.called)
  1515. def test_571_firewall_get_non_default(self):
  1516. self.vm.firewall.save = unittest.mock.Mock()
  1517. self.vm.firewall.rules = [
  1518. qubes.firewall.Rule(action='accept', proto='tcp',
  1519. dstports='1-1024'),
  1520. qubes.firewall.Rule(action='drop', proto='icmp',
  1521. comment='No ICMP'),
  1522. qubes.firewall.Rule(action='drop', proto='udp',
  1523. expire='1499450306'),
  1524. qubes.firewall.Rule(action='accept'),
  1525. ]
  1526. value = self.call_mgmt_func(b'admin.vm.firewall.Get',
  1527. b'test-vm1', b'')
  1528. self.assertEqual(value,
  1529. 'action=accept proto=tcp dstports=1-1024\n'
  1530. 'action=drop proto=icmp comment=No ICMP\n'
  1531. 'action=drop expire=1499450306 proto=udp\n'
  1532. 'action=accept\n')
  1533. self.assertFalse(self.vm.firewall.save.called)
  1534. self.assertFalse(self.app.save.called)
  1535. def test_580_firewall_set_simple(self):
  1536. self.vm.firewall.save = unittest.mock.Mock()
  1537. value = self.call_mgmt_func(b'admin.vm.firewall.Set',
  1538. b'test-vm1', b'', b'action=accept\n')
  1539. self.assertEqual(self.vm.firewall.rules,
  1540. ['action=accept'])
  1541. self.assertTrue(self.vm.firewall.save.called)
  1542. self.assertFalse(self.app.save.called)
  1543. def test_581_firewall_set_multi(self):
  1544. self.vm.firewall.save = unittest.mock.Mock()
  1545. rules = [
  1546. qubes.firewall.Rule(action='accept', proto='tcp',
  1547. dstports='1-1024'),
  1548. qubes.firewall.Rule(action='drop', proto='icmp',
  1549. comment='No ICMP'),
  1550. qubes.firewall.Rule(action='drop', proto='udp',
  1551. expire='1499450306'),
  1552. qubes.firewall.Rule(action='accept'),
  1553. ]
  1554. rules_txt = (
  1555. 'action=accept proto=tcp dstports=1-1024\n'
  1556. 'action=drop proto=icmp comment=No ICMP\n'
  1557. 'action=drop expire=1499450306 proto=udp\n'
  1558. 'action=accept\n')
  1559. value = self.call_mgmt_func(b'admin.vm.firewall.Set',
  1560. b'test-vm1', b'', rules_txt.encode())
  1561. self.assertEqual(self.vm.firewall.rules, rules)
  1562. self.assertTrue(self.vm.firewall.save.called)
  1563. self.assertFalse(self.app.save.called)
  1564. def test_582_firewall_set_invalid(self):
  1565. self.vm.firewall.save = unittest.mock.Mock()
  1566. rules_txt = (
  1567. 'action=accept protoxyz=tcp dst4=127.0.0.1\n'
  1568. 'action=drop\n')
  1569. with self.assertRaises(ValueError):
  1570. self.call_mgmt_func(b'admin.vm.firewall.Set',
  1571. b'test-vm1', b'', rules_txt.encode())
  1572. self.assertEqual(self.vm.firewall.rules,
  1573. [qubes.firewall.Rule(action='accept')])
  1574. self.assertFalse(self.vm.firewall.save.called)
  1575. self.assertFalse(self.app.save.called)
  1576. def test_583_firewall_set_invalid(self):
  1577. self.vm.firewall.save = unittest.mock.Mock()
  1578. rules_txt = (
  1579. 'proto=tcp dstports=1-1024\n'
  1580. 'action=drop\n')
  1581. with self.assertRaises(AssertionError):
  1582. self.call_mgmt_func(b'admin.vm.firewall.Set',
  1583. b'test-vm1', b'', rules_txt.encode())
  1584. self.assertEqual(self.vm.firewall.rules,
  1585. [qubes.firewall.Rule(action='accept')])
  1586. self.assertFalse(self.vm.firewall.save.called)
  1587. self.assertFalse(self.app.save.called)
  1588. def test_584_firewall_set_invalid(self):
  1589. self.vm.firewall.save = unittest.mock.Mock()
  1590. rules_txt = (
  1591. 'action=accept proto=tcp dstports=1-1024 '
  1592. 'action=drop\n')
  1593. with self.assertRaises(ValueError):
  1594. self.call_mgmt_func(b'admin.vm.firewall.Set',
  1595. b'test-vm1', b'', rules_txt.encode())
  1596. self.assertEqual(self.vm.firewall.rules,
  1597. [qubes.firewall.Rule(action='accept')])
  1598. self.assertFalse(self.vm.firewall.save.called)
  1599. self.assertFalse(self.app.save.called)
  1600. def test_585_firewall_set_invalid(self):
  1601. self.vm.firewall.save = unittest.mock.Mock()
  1602. rules_txt = (
  1603. 'action=accept dstports=1-1024 comment=ążźł\n'
  1604. 'action=drop\n')
  1605. with self.assertRaises(UnicodeDecodeError):
  1606. self.call_mgmt_func(b'admin.vm.firewall.Set',
  1607. b'test-vm1', b'', rules_txt.encode())
  1608. self.assertEqual(self.vm.firewall.rules,
  1609. [qubes.firewall.Rule(action='accept')])
  1610. self.assertFalse(self.vm.firewall.save.called)
  1611. self.assertFalse(self.app.save.called)
  1612. def test_590_firewall_reload(self):
  1613. self.vm.firewall.save = unittest.mock.Mock()
  1614. self.app.domains['test-vm1'].fire_event = self.emitter.fire_event
  1615. value = self.call_mgmt_func(b'admin.vm.firewall.Reload',
  1616. b'test-vm1', b'')
  1617. self.assertIsNone(value)
  1618. self.assertEventFired(self.emitter, 'firewall-changed')
  1619. self.assertFalse(self.vm.firewall.save.called)
  1620. self.assertFalse(self.app.save.called)
  1621. def test_600_backup_info(self):
  1622. backup_profile = (
  1623. 'include:\n'
  1624. ' - test-vm1\n'
  1625. 'destination_vm: test-vm1\n'
  1626. 'destination_path: /var/tmp\n'
  1627. 'passphrase_text: test\n'
  1628. )
  1629. expected_info = (
  1630. '------------------+--------------+--------------+\n'
  1631. ' VM | type | size |\n'
  1632. '------------------+--------------+--------------+\n'
  1633. ' test-vm1 | VM | 0 |\n'
  1634. '------------------+--------------+--------------+\n'
  1635. ' Total size: | 0 |\n'
  1636. '------------------+--------------+--------------+\n'
  1637. 'VMs not selected for backup:\n'
  1638. ' - dom0\n'
  1639. ' - test-template\n'
  1640. )
  1641. with tempfile.TemporaryDirectory() as profile_dir:
  1642. with open(os.path.join(profile_dir, 'testprofile.conf'), 'w') as \
  1643. profile_file:
  1644. profile_file.write(backup_profile)
  1645. with unittest.mock.patch('qubes.config.backup_profile_dir',
  1646. profile_dir):
  1647. result = self.call_mgmt_func(b'admin.backup.Info', b'dom0',
  1648. b'testprofile')
  1649. self.assertEqual(result, expected_info)
  1650. def test_601_backup_info_profile_missing_destination_path(self):
  1651. backup_profile = (
  1652. 'include:\n'
  1653. ' - test-vm1\n'
  1654. 'destination_vm: test-vm1\n'
  1655. 'passphrase_text: test\n'
  1656. )
  1657. with tempfile.TemporaryDirectory() as profile_dir:
  1658. with open(os.path.join(profile_dir, 'testprofile.conf'), 'w') as \
  1659. profile_file:
  1660. profile_file.write(backup_profile)
  1661. with unittest.mock.patch('qubes.config.backup_profile_dir',
  1662. profile_dir):
  1663. with self.assertRaises(qubes.exc.QubesException):
  1664. self.call_mgmt_func(b'admin.backup.Info', b'dom0',
  1665. b'testprofile')
  1666. def test_602_backup_info_profile_missing_destination_vm(self):
  1667. backup_profile = (
  1668. 'include:\n'
  1669. ' - test-vm1\n'
  1670. 'destination_path: /home/user\n'
  1671. 'passphrase_text: test\n'
  1672. )
  1673. with tempfile.TemporaryDirectory() as profile_dir:
  1674. with open(os.path.join(profile_dir, 'testprofile.conf'), 'w') as \
  1675. profile_file:
  1676. profile_file.write(backup_profile)
  1677. with unittest.mock.patch('qubes.config.backup_profile_dir',
  1678. profile_dir):
  1679. with self.assertRaises(qubes.exc.QubesException):
  1680. self.call_mgmt_func(b'admin.backup.Info', b'dom0',
  1681. b'testprofile')
  1682. def test_610_backup_cancel_not_running(self):
  1683. with self.assertRaises(qubes.exc.QubesException):
  1684. self.call_mgmt_func(b'admin.backup.Cancel', b'dom0',
  1685. b'testprofile')
  1686. @unittest.mock.patch('qubes.backup.Backup')
  1687. def test_620_backup_execute(self, mock_backup):
  1688. backup_profile = (
  1689. 'include:\n'
  1690. ' - test-vm1\n'
  1691. 'destination_vm: test-vm1\n'
  1692. 'destination_path: /home/user\n'
  1693. 'passphrase_text: test\n'
  1694. )
  1695. mock_backup.return_value.backup_do.side_effect = self.dummy_coro
  1696. with tempfile.TemporaryDirectory() as profile_dir:
  1697. with open(os.path.join(profile_dir, 'testprofile.conf'), 'w') as \
  1698. profile_file:
  1699. profile_file.write(backup_profile)
  1700. with unittest.mock.patch('qubes.config.backup_profile_dir',
  1701. profile_dir):
  1702. result = self.call_mgmt_func(b'admin.backup.Execute', b'dom0',
  1703. b'testprofile')
  1704. self.assertIsNone(result)
  1705. mock_backup.assert_called_once_with(
  1706. self.app,
  1707. {self.vm},
  1708. target_vm=self.vm,
  1709. target_dir='/home/user',
  1710. compressed=True,
  1711. passphrase='test')
  1712. mock_backup.return_value.backup_do.assert_called_once_with()
  1713. @unittest.mock.patch('qubes.backup.Backup')
  1714. def test_621_backup_execute_passphrase_service(self, mock_backup):
  1715. backup_profile = (
  1716. 'include:\n'
  1717. ' - test-vm1\n'
  1718. 'destination_vm: test-vm1\n'
  1719. 'destination_path: /home/user\n'
  1720. 'passphrase_vm: test-vm1\n'
  1721. )
  1722. @asyncio.coroutine
  1723. def service_passphrase(*args, **kwargs):
  1724. return (b'pass-from-vm', None)
  1725. mock_backup.return_value.backup_do.side_effect = self.dummy_coro
  1726. self.vm.run_service_for_stdio = unittest.mock.Mock(
  1727. side_effect=service_passphrase)
  1728. with tempfile.TemporaryDirectory() as profile_dir:
  1729. with open(os.path.join(profile_dir, 'testprofile.conf'), 'w') as \
  1730. profile_file:
  1731. profile_file.write(backup_profile)
  1732. with unittest.mock.patch('qubes.config.backup_profile_dir',
  1733. profile_dir):
  1734. result = self.call_mgmt_func(b'admin.backup.Execute', b'dom0',
  1735. b'testprofile')
  1736. self.assertIsNone(result)
  1737. mock_backup.assert_called_once_with(
  1738. self.app,
  1739. {self.vm},
  1740. target_vm=self.vm,
  1741. target_dir='/home/user',
  1742. compressed=True,
  1743. passphrase=b'pass-from-vm')
  1744. mock_backup.return_value.backup_do.assert_called_once_with()
  1745. self.vm.run_service_for_stdio.assert_called_with(
  1746. 'qubes.BackupPassphrase+testprofile')
  1747. def test_630_vm_stats(self):
  1748. send_event = unittest.mock.Mock(spec=[])
  1749. stats1 = {
  1750. 0: {
  1751. 'cpu_time': 243951379111104 // 8,
  1752. 'cpu_usage': 0,
  1753. 'memory_kb': 3733212,
  1754. },
  1755. 1: {
  1756. 'cpu_time': 2849496569205,
  1757. 'cpu_usage': 0,
  1758. 'memory_kb': 303916,
  1759. },
  1760. }
  1761. stats2 = copy.deepcopy(stats1)
  1762. stats2[0]['cpu_time'] += 100000000
  1763. stats2[0]['cpu_usage'] = 10
  1764. stats2[1]['cpu_usage'] = 5
  1765. self.app.host.get_vm_stats = unittest.mock.Mock()
  1766. self.app.host.get_vm_stats.side_effect = [
  1767. (0, stats1), (1, stats2),
  1768. ]
  1769. self.app.stats_interval = 1
  1770. mgmt_obj = qubes.api.admin.QubesAdminAPI(
  1771. self.app, b'dom0', b'admin.vm.Stats',
  1772. b'dom0', b'', send_event=send_event)
  1773. def cancel_call():
  1774. mgmt_obj.cancel()
  1775. class MockVM(object):
  1776. def __init__(self, name):
  1777. self._name = name
  1778. def name(self):
  1779. return self._name
  1780. loop = asyncio.get_event_loop()
  1781. self.app.vmm.libvirt_conn.lookupByID.side_effect = lambda xid: {
  1782. 0: MockVM('Domain-0'),
  1783. 1: MockVM('test-template'),
  1784. 2: MockVM('test-vm1')}[xid]
  1785. execute_task = asyncio.ensure_future(
  1786. mgmt_obj.execute(untrusted_payload=b''))
  1787. loop.call_later(1.1, cancel_call)
  1788. loop.run_until_complete(execute_task)
  1789. self.assertIsNone(execute_task.result())
  1790. self.assertEventFired(self.emitter,
  1791. 'admin-permission:' + 'admin.vm.Stats')
  1792. self.assertEqual(self.app.host.get_vm_stats.mock_calls, [
  1793. unittest.mock.call(None, None, only_vm=None),
  1794. unittest.mock.call(0, stats1, only_vm=None),
  1795. ])
  1796. self.assertEqual(send_event.mock_calls, [
  1797. unittest.mock.call(self.app, 'connection-established'),
  1798. unittest.mock.call('dom0', 'vm-stats',
  1799. cpu_time=stats1[0]['cpu_time'] // 1000000,
  1800. cpu_usage=stats1[0]['cpu_usage'],
  1801. memory_kb=stats1[0]['memory_kb']),
  1802. unittest.mock.call('test-template', 'vm-stats',
  1803. cpu_time=stats1[1]['cpu_time'] // 1000000,
  1804. cpu_usage=stats1[1]['cpu_usage'],
  1805. memory_kb=stats1[1]['memory_kb']),
  1806. unittest.mock.call('dom0', 'vm-stats',
  1807. cpu_time=stats2[0]['cpu_time'] // 1000000,
  1808. cpu_usage=stats2[0]['cpu_usage'],
  1809. memory_kb=stats2[0]['memory_kb']),
  1810. unittest.mock.call('test-template', 'vm-stats',
  1811. cpu_time=stats2[1]['cpu_time'] // 1000000,
  1812. cpu_usage=stats2[1]['cpu_usage'],
  1813. memory_kb=stats2[1]['memory_kb']),
  1814. ])
  1815. def test_631_vm_stats_single_vm(self):
  1816. send_event = unittest.mock.Mock(spec=[])
  1817. stats1 = {
  1818. 2: {
  1819. 'cpu_time': 2849496569205,
  1820. 'cpu_usage': 0,
  1821. 'memory_kb': 303916,
  1822. },
  1823. }
  1824. stats2 = copy.deepcopy(stats1)
  1825. stats2[2]['cpu_usage'] = 5
  1826. self.app.host.get_vm_stats = unittest.mock.Mock()
  1827. self.app.host.get_vm_stats.side_effect = [
  1828. (0, stats1), (1, stats2),
  1829. ]
  1830. self.app.stats_interval = 1
  1831. mgmt_obj = qubes.api.admin.QubesAdminAPI(
  1832. self.app, b'dom0', b'admin.vm.Stats',
  1833. b'test-vm1', b'', send_event=send_event)
  1834. def cancel_call():
  1835. mgmt_obj.cancel()
  1836. class MockVM(object):
  1837. def __init__(self, name):
  1838. self._name = name
  1839. def name(self):
  1840. return self._name
  1841. loop = asyncio.get_event_loop()
  1842. self.app.vmm.libvirt_conn.lookupByID.side_effect = lambda xid: {
  1843. 0: MockVM('Domain-0'),
  1844. 1: MockVM('test-template'),
  1845. 2: MockVM('test-vm1')}[xid]
  1846. execute_task = asyncio.ensure_future(
  1847. mgmt_obj.execute(untrusted_payload=b''))
  1848. loop.call_later(1.1, cancel_call)
  1849. loop.run_until_complete(execute_task)
  1850. self.assertIsNone(execute_task.result())
  1851. self.assertEventFired(self.emitter,
  1852. 'admin-permission:' + 'admin.vm.Stats')
  1853. self.assertEqual(self.app.host.get_vm_stats.mock_calls, [
  1854. unittest.mock.call(None, None, only_vm=self.vm),
  1855. unittest.mock.call(0, stats1, only_vm=self.vm),
  1856. ])
  1857. self.assertEqual(send_event.mock_calls, [
  1858. unittest.mock.call(self.app, 'connection-established'),
  1859. unittest.mock.call('test-vm1', 'vm-stats',
  1860. cpu_time=stats1[2]['cpu_time'] // 1000000,
  1861. cpu_usage=stats1[2]['cpu_usage'],
  1862. memory_kb=stats1[2]['memory_kb']),
  1863. unittest.mock.call('test-vm1', 'vm-stats',
  1864. cpu_time=stats2[2]['cpu_time'] // 1000000,
  1865. cpu_usage=stats2[2]['cpu_usage'],
  1866. memory_kb=stats2[2]['memory_kb']),
  1867. ])
  1868. @unittest.mock.patch('qubes.storage.Storage.create')
  1869. def test_640_vm_create_disposable(self, mock_storage):
  1870. mock_storage.side_effect = self.dummy_coro
  1871. self.vm.template_for_dispvms = True
  1872. retval = self.call_mgmt_func(b'admin.vm.CreateDisposable',
  1873. b'test-vm1')
  1874. self.assertTrue(retval.startswith('disp'))
  1875. self.assertIn(retval, self.app.domains)
  1876. dispvm = self.app.domains[retval]
  1877. self.assertEqual(dispvm.template, self.vm)
  1878. mock_storage.assert_called_once_with()
  1879. self.assertTrue(self.app.save.called)
  1880. @unittest.mock.patch('qubes.storage.Storage.create')
  1881. def test_641_vm_create_disposable_default(self, mock_storage):
  1882. mock_storage.side_effect = self.dummy_coro
  1883. self.vm.template_for_dispvms = True
  1884. self.app.default_dispvm = self.vm
  1885. retval = self.call_mgmt_func(b'admin.vm.CreateDisposable',
  1886. b'dom0')
  1887. self.assertTrue(retval.startswith('disp'))
  1888. mock_storage.assert_called_once_with()
  1889. self.assertTrue(self.app.save.called)
  1890. @unittest.mock.patch('qubes.storage.Storage.create')
  1891. def test_642_vm_create_disposable_not_allowed(self, storage_mock):
  1892. storage_mock.side_effect = self.dummy_coro
  1893. with self.assertRaises(qubes.exc.QubesException):
  1894. self.call_mgmt_func(b'admin.vm.CreateDisposable',
  1895. b'test-vm1')
  1896. self.assertFalse(self.app.save.called)
  1897. def test_650_vm_device_set_persistent_true(self):
  1898. self.vm.add_handler('device-list:testclass',
  1899. self.device_list_testclass)
  1900. self.vm.add_handler('device-list-attached:testclass',
  1901. self.device_list_attached_testclass)
  1902. with unittest.mock.patch.object(qubes.vm.qubesvm.QubesVM,
  1903. 'is_halted', lambda _: False):
  1904. value = self.call_mgmt_func(
  1905. b'admin.vm.device.testclass.Set.persistent',
  1906. b'test-vm1', b'test-vm1+1234', b'True')
  1907. self.assertIsNone(value)
  1908. dev = qubes.devices.DeviceInfo(self.vm, '1234')
  1909. self.assertIn(dev, self.vm.devices['testclass'].persistent())
  1910. self.app.save.assert_called_once_with()
  1911. def test_651_vm_device_set_persistent_false_unchanged(self):
  1912. self.vm.add_handler('device-list:testclass',
  1913. self.device_list_testclass)
  1914. self.vm.add_handler('device-list-attached:testclass',
  1915. self.device_list_attached_testclass)
  1916. with unittest.mock.patch.object(qubes.vm.qubesvm.QubesVM,
  1917. 'is_halted', lambda _: False):
  1918. value = self.call_mgmt_func(
  1919. b'admin.vm.device.testclass.Set.persistent',
  1920. b'test-vm1', b'test-vm1+1234', b'False')
  1921. self.assertIsNone(value)
  1922. dev = qubes.devices.DeviceInfo(self.vm, '1234')
  1923. self.assertNotIn(dev, self.vm.devices['testclass'].persistent())
  1924. self.app.save.assert_called_once_with()
  1925. def test_652_vm_device_set_persistent_false(self):
  1926. self.vm.add_handler('device-list:testclass',
  1927. self.device_list_testclass)
  1928. assignment = qubes.devices.DeviceAssignment(self.vm, '1234', {},
  1929. True)
  1930. self.loop.run_until_complete(
  1931. self.vm.devices['testclass'].attach(assignment))
  1932. self.vm.add_handler('device-list-attached:testclass',
  1933. self.device_list_attached_testclass)
  1934. dev = qubes.devices.DeviceInfo(self.vm, '1234')
  1935. self.assertIn(dev, self.vm.devices['testclass'].persistent())
  1936. with unittest.mock.patch.object(qubes.vm.qubesvm.QubesVM,
  1937. 'is_halted', lambda _: False):
  1938. value = self.call_mgmt_func(
  1939. b'admin.vm.device.testclass.Set.persistent',
  1940. b'test-vm1', b'test-vm1+1234', b'False')
  1941. self.assertIsNone(value)
  1942. self.assertNotIn(dev, self.vm.devices['testclass'].persistent())
  1943. self.assertIn(dev, self.vm.devices['testclass'].attached())
  1944. self.app.save.assert_called_once_with()
  1945. def test_653_vm_device_set_persistent_true_unchanged(self):
  1946. self.vm.add_handler('device-list:testclass',
  1947. self.device_list_testclass)
  1948. assignment = qubes.devices.DeviceAssignment(self.vm, '1234', {},
  1949. True)
  1950. self.loop.run_until_complete(
  1951. self.vm.devices['testclass'].attach(assignment))
  1952. self.vm.add_handler('device-list-attached:testclass',
  1953. self.device_list_attached_testclass)
  1954. with unittest.mock.patch.object(qubes.vm.qubesvm.QubesVM,
  1955. 'is_halted', lambda _: False):
  1956. value = self.call_mgmt_func(
  1957. b'admin.vm.device.testclass.Set.persistent',
  1958. b'test-vm1', b'test-vm1+1234', b'True')
  1959. self.assertIsNone(value)
  1960. dev = qubes.devices.DeviceInfo(self.vm, '1234')
  1961. self.assertIn(dev, self.vm.devices['testclass'].persistent())
  1962. self.assertIn(dev, self.vm.devices['testclass'].attached())
  1963. self.app.save.assert_called_once_with()
  1964. def test_654_vm_device_set_persistent_not_attached(self):
  1965. self.vm.add_handler('device-list:testclass',
  1966. self.device_list_testclass)
  1967. with unittest.mock.patch.object(qubes.vm.qubesvm.QubesVM,
  1968. 'is_halted', lambda _: False):
  1969. with self.assertRaises(AssertionError):
  1970. self.call_mgmt_func(
  1971. b'admin.vm.device.testclass.Set.persistent',
  1972. b'test-vm1', b'test-vm1+1234', b'True')
  1973. dev = qubes.devices.DeviceInfo(self.vm, '1234')
  1974. self.assertNotIn(dev, self.vm.devices['testclass'].persistent())
  1975. self.assertFalse(self.app.save.called)
  1976. def test_655_vm_device_set_persistent_invalid_value(self):
  1977. self.vm.add_handler('device-list:testclass',
  1978. self.device_list_testclass)
  1979. with unittest.mock.patch.object(qubes.vm.qubesvm.QubesVM,
  1980. 'is_halted', lambda _: False):
  1981. with self.assertRaises(AssertionError):
  1982. self.call_mgmt_func(
  1983. b'admin.vm.device.testclass.Set.persistent',
  1984. b'test-vm1', b'test-vm1+1234', b'maybe')
  1985. dev = qubes.devices.DeviceInfo(self.vm, '1234')
  1986. self.assertNotIn(dev, self.vm.devices['testclass'].persistent())
  1987. self.assertFalse(self.app.save.called)
  1988. def test_990_vm_unexpected_payload(self):
  1989. methods_with_no_payload = [
  1990. b'admin.vm.List',
  1991. b'admin.vm.Remove',
  1992. b'admin.vm.property.List',
  1993. b'admin.vm.property.Get',
  1994. b'admin.vm.property.Help',
  1995. b'admin.vm.property.HelpRst',
  1996. b'admin.vm.property.Reset',
  1997. b'admin.vm.feature.List',
  1998. b'admin.vm.feature.Get',
  1999. b'admin.vm.feature.CheckWithTemplate',
  2000. b'admin.vm.feature.Remove',
  2001. b'admin.vm.tag.List',
  2002. b'admin.vm.tag.Get',
  2003. b'admin.vm.tag.Remove',
  2004. b'admin.vm.tag.Set',
  2005. b'admin.vm.firewall.Get',
  2006. b'admin.vm.firewall.Reload',
  2007. b'admin.vm.device.pci.Attach',
  2008. b'admin.vm.device.pci.Detach',
  2009. b'admin.vm.device.pci.List',
  2010. b'admin.vm.device.pci.Available',
  2011. b'admin.vm.microphone.Attach',
  2012. b'admin.vm.microphone.Detach',
  2013. b'admin.vm.microphone.Status',
  2014. b'admin.vm.volume.ListSnapshots',
  2015. b'admin.vm.volume.List',
  2016. b'admin.vm.volume.Info',
  2017. b'admin.vm.Start',
  2018. b'admin.vm.Shutdown',
  2019. b'admin.vm.Pause',
  2020. b'admin.vm.Unpause',
  2021. b'admin.vm.Kill',
  2022. b'admin.Events',
  2023. b'admin.vm.feature.List',
  2024. b'admin.vm.feature.Get',
  2025. b'admin.vm.feature.Remove',
  2026. b'admin.vm.feature.CheckWithTemplate',
  2027. ]
  2028. # make sure also no methods on actual VM gets called
  2029. vm_mock = unittest.mock.MagicMock()
  2030. vm_mock.name = self.vm.name
  2031. vm_mock.qid = self.vm.qid
  2032. vm_mock.__lt__ = (lambda x, y: x.qid < y.qid)
  2033. self.app.domains._dict[self.vm.qid] = vm_mock
  2034. for method in methods_with_no_payload:
  2035. # should reject payload regardless of having argument or not
  2036. with self.subTest(method.decode('ascii')):
  2037. with self.assertRaises(AssertionError):
  2038. self.call_mgmt_func(method, b'test-vm1', b'',
  2039. b'unexpected-payload')
  2040. self.assertFalse(vm_mock.called)
  2041. self.assertFalse(self.app.save.called)
  2042. with self.subTest(method.decode('ascii') + '+arg'):
  2043. with self.assertRaises(AssertionError):
  2044. self.call_mgmt_func(method, b'test-vm1', b'some-arg',
  2045. b'unexpected-payload')
  2046. self.assertFalse(vm_mock.called)
  2047. self.assertFalse(self.app.save.called)
  2048. def test_991_vm_unexpected_argument(self):
  2049. methods_with_no_argument = [
  2050. b'admin.vm.List',
  2051. b'admin.vm.Clone',
  2052. b'admin.vm.Remove',
  2053. b'admin.vm.property.List',
  2054. b'admin.vm.feature.List',
  2055. b'admin.vm.tag.List',
  2056. b'admin.vm.firewall.Get',
  2057. b'admin.vm.firewall.Set',
  2058. b'admin.vm.firewall.Reload',
  2059. b'admin.vm.microphone.Attach',
  2060. b'admin.vm.microphone.Detach',
  2061. b'admin.vm.microphone.Status',
  2062. b'admin.vm.volume.List',
  2063. b'admin.vm.Start',
  2064. b'admin.vm.Shutdown',
  2065. b'admin.vm.Pause',
  2066. b'admin.vm.Unpause',
  2067. b'admin.vm.Kill',
  2068. b'admin.Events',
  2069. b'admin.vm.feature.List',
  2070. ]
  2071. # make sure also no methods on actual VM gets called
  2072. vm_mock = unittest.mock.MagicMock()
  2073. vm_mock.name = self.vm.name
  2074. vm_mock.qid = self.vm.qid
  2075. vm_mock.__lt__ = (lambda x, y: x.qid < y.qid)
  2076. self.app.domains._dict[self.vm.qid] = vm_mock
  2077. for method in methods_with_no_argument:
  2078. # should reject argument regardless of having payload or not
  2079. with self.subTest(method.decode('ascii')):
  2080. with self.assertRaises(AssertionError):
  2081. self.call_mgmt_func(method, b'test-vm1', b'some-arg',
  2082. b'')
  2083. self.assertFalse(vm_mock.called)
  2084. self.assertFalse(self.app.save.called)
  2085. with self.subTest(method.decode('ascii') + '+payload'):
  2086. with self.assertRaises(AssertionError):
  2087. self.call_mgmt_func(method, b'test-vm1', b'unexpected-arg',
  2088. b'some-payload')
  2089. self.assertFalse(vm_mock.called)
  2090. self.assertFalse(self.app.save.called)
  2091. def test_992_dom0_unexpected_payload(self):
  2092. methods_with_no_payload = [
  2093. b'admin.vmclass.List',
  2094. b'admin.vm.List',
  2095. b'admin.label.List',
  2096. b'admin.label.Get',
  2097. b'admin.label.Remove',
  2098. b'admin.property.List',
  2099. b'admin.property.Get',
  2100. b'admin.property.Help',
  2101. b'admin.property.HelpRst',
  2102. b'admin.property.Reset',
  2103. b'admin.pool.List',
  2104. b'admin.pool.ListDrivers',
  2105. b'admin.pool.Info',
  2106. b'admin.pool.Remove',
  2107. b'admin.backup.Execute',
  2108. b'admin.Events',
  2109. ]
  2110. # make sure also no methods on actual VM gets called
  2111. vm_mock = unittest.mock.MagicMock()
  2112. vm_mock.name = self.vm.name
  2113. vm_mock.qid = self.vm.qid
  2114. vm_mock.__lt__ = (lambda x, y: x.qid < y.qid)
  2115. self.app.domains._dict[self.vm.qid] = vm_mock
  2116. for method in methods_with_no_payload:
  2117. # should reject payload regardless of having argument or not
  2118. with self.subTest(method.decode('ascii')):
  2119. with self.assertRaises(AssertionError):
  2120. self.call_mgmt_func(method, b'dom0', b'',
  2121. b'unexpected-payload')
  2122. self.assertFalse(vm_mock.called)
  2123. self.assertFalse(self.app.save.called)
  2124. with self.subTest(method.decode('ascii') + '+arg'):
  2125. with self.assertRaises(AssertionError):
  2126. self.call_mgmt_func(method, b'dom0', b'some-arg',
  2127. b'unexpected-payload')
  2128. self.assertFalse(vm_mock.called)
  2129. self.assertFalse(self.app.save.called)
  2130. def test_993_dom0_unexpected_argument(self):
  2131. methods_with_no_argument = [
  2132. b'admin.vmclass.List',
  2133. b'admin.vm.List',
  2134. b'admin.label.List',
  2135. b'admin.property.List',
  2136. b'admin.pool.List',
  2137. b'admin.pool.ListDrivers',
  2138. b'admin.Events',
  2139. ]
  2140. # make sure also no methods on actual VM gets called
  2141. vm_mock = unittest.mock.MagicMock()
  2142. vm_mock.name = self.vm.name
  2143. vm_mock.qid = self.vm.qid
  2144. vm_mock.__lt__ = (lambda x, y: x.qid < y.qid)
  2145. self.app.domains._dict[self.vm.qid] = vm_mock
  2146. for method in methods_with_no_argument:
  2147. # should reject argument regardless of having payload or not
  2148. with self.subTest(method.decode('ascii')):
  2149. with self.assertRaises(AssertionError):
  2150. self.call_mgmt_func(method, b'dom0', b'some-arg',
  2151. b'')
  2152. self.assertFalse(vm_mock.called)
  2153. self.assertFalse(self.app.save.called)
  2154. with self.subTest(method.decode('ascii') + '+payload'):
  2155. with self.assertRaises(AssertionError):
  2156. self.call_mgmt_func(method, b'dom0', b'unexpected-arg',
  2157. b'some-payload')
  2158. self.assertFalse(vm_mock.called)
  2159. self.assertFalse(self.app.save.called)
  2160. def test_994_dom0_only_calls(self):
  2161. # TODO set some better arguments, to make sure the call was rejected
  2162. # because of invalid destination, not invalid arguments
  2163. methods_for_dom0_only = [
  2164. b'admin.vmclass.List',
  2165. b'admin.vm.Create.AppVM',
  2166. b'admin.vm.CreateInPool.AppVM',
  2167. b'admin.vm.CreateTemplate',
  2168. b'admin.label.List',
  2169. b'admin.label.Create',
  2170. b'admin.label.Get',
  2171. b'admin.label.Remove',
  2172. b'admin.property.List',
  2173. b'admin.property.Get',
  2174. b'admin.property.Set',
  2175. b'admin.property.Help',
  2176. b'admin.property.HelpRst',
  2177. b'admin.property.Reset',
  2178. b'admin.pool.List',
  2179. b'admin.pool.ListDrivers',
  2180. b'admin.pool.Info',
  2181. b'admin.pool.Add',
  2182. b'admin.pool.Remove',
  2183. b'admin.pool.volume.List',
  2184. b'admin.pool.volume.Info',
  2185. b'admin.pool.volume.ListSnapshots',
  2186. b'admin.pool.volume.Snapshot',
  2187. b'admin.pool.volume.Revert',
  2188. b'admin.pool.volume.Resize',
  2189. b'admin.backup.Execute',
  2190. b'admin.backup.Info',
  2191. b'admin.backup.Restore',
  2192. ]
  2193. # make sure also no methods on actual VM gets called
  2194. vm_mock = unittest.mock.MagicMock()
  2195. vm_mock.name = self.vm.name
  2196. vm_mock.qid = self.vm.qid
  2197. vm_mock.__lt__ = (lambda x, y: x.qid < y.qid)
  2198. self.app.domains._dict[self.vm.qid] = vm_mock
  2199. for method in methods_for_dom0_only:
  2200. # should reject call regardless of having payload or not
  2201. with self.subTest(method.decode('ascii')):
  2202. with self.assertRaises(AssertionError):
  2203. self.call_mgmt_func(method, b'test-vm1', b'',
  2204. b'')
  2205. self.assertFalse(vm_mock.called)
  2206. self.assertFalse(self.app.save.called)
  2207. with self.subTest(method.decode('ascii') + '+arg'):
  2208. with self.assertRaises(AssertionError):
  2209. self.call_mgmt_func(method, b'test-vm1', b'some-arg',
  2210. b'')
  2211. self.assertFalse(vm_mock.called)
  2212. self.assertFalse(self.app.save.called)
  2213. with self.subTest(method.decode('ascii') + '+payload'):
  2214. with self.assertRaises(AssertionError):
  2215. self.call_mgmt_func(method, b'test-vm1', b'',
  2216. b'payload')
  2217. self.assertFalse(vm_mock.called)
  2218. self.assertFalse(self.app.save.called)
  2219. with self.subTest(method.decode('ascii') + '+arg+payload'):
  2220. with self.assertRaises(AssertionError):
  2221. self.call_mgmt_func(method, b'test-vm1', b'some-arg',
  2222. b'some-payload')
  2223. self.assertFalse(vm_mock.called)
  2224. self.assertFalse(self.app.save.called)
  2225. @unittest.skip('undecided')
  2226. def test_995_vm_only_calls(self):
  2227. # XXX is it really a good idea to prevent those calls this early?
  2228. # TODO set some better arguments, to make sure the call was rejected
  2229. # because of invalid destination, not invalid arguments
  2230. methods_for_vm_only = [
  2231. b'admin.vm.Clone',
  2232. b'admin.vm.Remove',
  2233. b'admin.vm.property.List',
  2234. b'admin.vm.property.Get',
  2235. b'admin.vm.property.Set',
  2236. b'admin.vm.property.Help',
  2237. b'admin.vm.property.HelpRst',
  2238. b'admin.vm.property.Reset',
  2239. b'admin.vm.feature.List',
  2240. b'admin.vm.feature.Get',
  2241. b'admin.vm.feature.Set',
  2242. b'admin.vm.feature.CheckWithTemplate',
  2243. b'admin.vm.feature.Remove',
  2244. b'admin.vm.tag.List',
  2245. b'admin.vm.tag.Get',
  2246. b'admin.vm.tag.Remove',
  2247. b'admin.vm.tag.Set',
  2248. b'admin.vm.firewall.Get',
  2249. b'admin.vm.firewall.Set',
  2250. b'admin.vm.firewall.Reload',
  2251. b'admin.vm.device.pci.Attach',
  2252. b'admin.vm.device.pci.Detach',
  2253. b'admin.vm.device.pci.List',
  2254. b'admin.vm.device.pci.Available',
  2255. b'admin.vm.microphone.Attach',
  2256. b'admin.vm.microphone.Detach',
  2257. b'admin.vm.microphone.Status',
  2258. b'admin.vm.volume.ListSnapshots',
  2259. b'admin.vm.volume.List',
  2260. b'admin.vm.volume.Info',
  2261. b'admin.vm.volume.Revert',
  2262. b'admin.vm.volume.Resize',
  2263. b'admin.vm.Start',
  2264. b'admin.vm.Shutdown',
  2265. b'admin.vm.Pause',
  2266. b'admin.vm.Unpause',
  2267. b'admin.vm.Kill',
  2268. b'admin.vm.feature.List',
  2269. b'admin.vm.feature.Get',
  2270. b'admin.vm.feature.Set',
  2271. b'admin.vm.feature.Remove',
  2272. b'admin.vm.feature.CheckWithTemplate',
  2273. ]
  2274. # make sure also no methods on actual VM gets called
  2275. vm_mock = unittest.mock.MagicMock()
  2276. vm_mock.name = self.vm.name
  2277. vm_mock.qid = self.vm.qid
  2278. vm_mock.__lt__ = (lambda x, y: x.qid < y.qid)
  2279. self.app.domains._dict[self.vm.qid] = vm_mock
  2280. for method in methods_for_vm_only:
  2281. # should reject payload regardless of having argument or not
  2282. # should reject call regardless of having payload or not
  2283. with self.subTest(method.decode('ascii')):
  2284. with self.assertRaises(AssertionError):
  2285. self.call_mgmt_func(method, b'dom0', b'',
  2286. b'')
  2287. self.assertFalse(vm_mock.called)
  2288. self.assertFalse(self.app.save.called)
  2289. with self.subTest(method.decode('ascii') + '+arg'):
  2290. with self.assertRaises(AssertionError):
  2291. self.call_mgmt_func(method, b'dom0', b'some-arg',
  2292. b'')
  2293. self.assertFalse(vm_mock.called)
  2294. self.assertFalse(self.app.save.called)
  2295. with self.subTest(method.decode('ascii') + '+payload'):
  2296. with self.assertRaises(AssertionError):
  2297. self.call_mgmt_func(method, b'dom0', b'',
  2298. b'payload')
  2299. self.assertFalse(vm_mock.called)
  2300. self.assertFalse(self.app.save.called)
  2301. with self.subTest(method.decode('ascii') + '+arg+payload'):
  2302. with self.assertRaises(AssertionError):
  2303. self.call_mgmt_func(method, b'dom0', b'some-arg',
  2304. b'some-payload')
  2305. self.assertFalse(vm_mock.called)
  2306. self.assertFalse(self.app.save.called)