extra.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. #
  2. # The Qubes OS Project, https://www.qubes-os.org/
  3. #
  4. # Copyright (C) 2016
  5. # Marek Marczykowski-Górecki <marmarek@invisiblethingslab.com>
  6. #
  7. # This library is free software; you can redistribute it and/or
  8. # modify it under the terms of the GNU Lesser General Public
  9. # License as published by the Free Software Foundation; either
  10. # version 2.1 of the License, or (at your option) any later version.
  11. #
  12. # This library is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. # Lesser General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU Lesser General Public
  18. # License along with this library; if not, see <https://www.gnu.org/licenses/>.
  19. #
  20. import asyncio
  21. import subprocess
  22. import sys
  23. import pkg_resources
  24. import qubes.tests
  25. import qubes.vm.appvm
  26. class ProcessWrapper(object):
  27. def __init__(self, proc, loop=None):
  28. self._proc = proc
  29. self._loop = loop or asyncio.get_event_loop()
  30. def __getattr__(self, item):
  31. return getattr(self._proc, item)
  32. def __setattr__(self, key, value):
  33. if key.startswith('_'):
  34. return super(ProcessWrapper, self).__setattr__(key, value)
  35. return setattr(self._proc, key, value)
  36. def communicate(self, input=None):
  37. return self._loop.run_until_complete(self._proc.communicate(input))
  38. def wait(self):
  39. return self._loop.run_until_complete(self._proc.wait())
  40. class VMWrapper(object):
  41. '''Wrap VM object to provide stable API for basic operations'''
  42. def __init__(self, vm, loop=None):
  43. self._vm = vm
  44. self._loop = loop or asyncio.get_event_loop()
  45. def __getattr__(self, item):
  46. return getattr(self._vm, item)
  47. def __setattr__(self, key, value):
  48. if key.startswith('_'):
  49. return super(VMWrapper, self).__setattr__(key, value)
  50. return setattr(self._vm, key, value)
  51. def __str__(self):
  52. return str(self._vm)
  53. def __eq__(self, other):
  54. return self._vm == other
  55. def __hash__(self):
  56. return hash(self._vm)
  57. def start(self, start_guid=True):
  58. return self._loop.run_until_complete(
  59. self._vm.start(start_guid=start_guid))
  60. def shutdown(self):
  61. return self._loop.run_until_complete(self._vm.shutdown())
  62. def run(self, command, wait=False, user=None, passio_popen=False,
  63. passio_stderr=False, **kwargs):
  64. if wait:
  65. try:
  66. self._loop.run_until_complete(
  67. self._vm.run_for_stdio(command, user=user))
  68. except subprocess.CalledProcessError as err:
  69. return err.returncode
  70. return 0
  71. elif passio_popen:
  72. p = self._loop.run_until_complete(self._vm.run(command, user=user,
  73. stdin=subprocess.PIPE,
  74. stdout=subprocess.PIPE,
  75. stderr=subprocess.PIPE if passio_stderr else None))
  76. return ProcessWrapper(p, self._loop)
  77. else:
  78. asyncio.ensure_future(self._vm.run_for_stdio(command, user=user),
  79. loop=self._loop)
  80. def run_service(self, service, wait=True, input=None, user=None,
  81. passio_popen=False,
  82. passio_stderr=False, **kwargs):
  83. if wait:
  84. try:
  85. if isinstance(input, str):
  86. input = input.encode()
  87. self._loop.run_until_complete(
  88. self._vm.run_service_for_stdio(service,
  89. input=input, user=user))
  90. except subprocess.CalledProcessError as err:
  91. return err.returncode
  92. return 0
  93. elif passio_popen:
  94. p = self._loop.run_until_complete(self._vm.run_service(service,
  95. user=user,
  96. stdin=subprocess.PIPE,
  97. stdout=subprocess.PIPE,
  98. stderr=subprocess.PIPE if passio_stderr else None))
  99. return ProcessWrapper(p, self._loop)
  100. class ExtraTestCase(qubes.tests.SystemTestCase):
  101. template = None
  102. def setUp(self):
  103. super(ExtraTestCase, self).setUp()
  104. self.init_default_template(self.template)
  105. if self.template is not None:
  106. # also use this template for DispVMs
  107. dispvm_base = self.app.add_new_vm('AppVM',
  108. name=self.make_vm_name('dvm'),
  109. template=self.template, label='red', template_for_dispvms=True)
  110. self.loop.run_until_complete(dispvm_base.create_on_disk())
  111. self.app.default_dispvm = dispvm_base
  112. def tearDown(self):
  113. self.app.default_dispvm = None
  114. super(ExtraTestCase, self).tearDown()
  115. def create_vms(self, names):
  116. """
  117. Create AppVMs for the duration of the test. Will be automatically
  118. removed after completing the test.
  119. :param names: list of VM names to create (each of them will be
  120. prefixed with some test specific string)
  121. :return: list of created VM objects
  122. """
  123. if self.template:
  124. template = self.app.domains[self.template]
  125. else:
  126. template = self.app.default_template
  127. for vmname in names:
  128. vm = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  129. name=self.make_vm_name(vmname),
  130. template=template,
  131. label='red')
  132. self.loop.run_until_complete(vm.create_on_disk())
  133. self.app.save()
  134. # get objects after reload
  135. vms = []
  136. for vmname in names:
  137. vms.append(VMWrapper(self.app.domains[self.make_vm_name(vmname)],
  138. loop=self.loop))
  139. return vms
  140. def enable_network(self):
  141. """
  142. Enable access to the network. Must be called before creating VMs.
  143. """
  144. self.init_networking()
  145. def qrexec_policy(self, service, source, destination, allow=True):
  146. """
  147. Allow qrexec calls for duration of the test
  148. :param service: service name
  149. :param source: source VM name
  150. :param destination: destination VM name
  151. :return:
  152. """
  153. def add_remove_rule(add=True):
  154. with open('/etc/qubes-rpc/policy/{}'.format(service), 'r+') as policy:
  155. policy_rules = policy.readlines()
  156. rule = "{} {} {}\n".format(source, destination,
  157. 'allow' if allow else 'deny')
  158. if add:
  159. policy_rules.insert(0, rule)
  160. else:
  161. policy_rules.remove(rule)
  162. policy.truncate(0)
  163. policy.seek(0)
  164. policy.write(''.join(policy_rules))
  165. add_remove_rule(add=True)
  166. self.addCleanup(add_remove_rule, add=False)
  167. def load_tests(loader, tests, pattern):
  168. for entry in pkg_resources.iter_entry_points('qubes.tests.extra'):
  169. try:
  170. for test_case in entry.load()():
  171. tests.addTests(loader.loadTestsFromNames([
  172. '{}.{}'.format(test_case.__module__, test_case.__name__)]))
  173. except Exception as err: # pylint: disable=broad-except
  174. def runTest(self):
  175. raise err
  176. ExtraLoadFailure = type('ExtraLoadFailure',
  177. (qubes.tests.QubesTestCase,),
  178. {entry.name: runTest})
  179. tests.addTest(ExtraLoadFailure(entry.name))
  180. for entry in pkg_resources.iter_entry_points(
  181. 'qubes.tests.extra.for_template'):
  182. try:
  183. for test_case in entry.load()():
  184. tests.addTests(loader.loadTestsFromNames(
  185. qubes.tests.create_testcases_for_templates(
  186. test_case.__name__, test_case,
  187. module=sys.modules[test_case.__module__])))
  188. except Exception as err: # pylint: disable=broad-except
  189. def runTest(self):
  190. raise err
  191. ExtraForTemplateLoadFailure = type('ExtraForTemplateLoadFailure',
  192. (qubes.tests.QubesTestCase,),
  193. {entry.name: runTest})
  194. tests.addTest(ExtraForTemplateLoadFailure(entry.name))
  195. return tests