api_admin.py 120 KB

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