api_admin.py 133 KB

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