api_admin.py 119 KB

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