api_admin.py 105 KB

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