api_admin.py 123 KB

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