api_admin.py 119 KB

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