api_admin.py 130 KB

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