api_admin.py 115 KB

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