extra.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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 os
  22. import subprocess
  23. import sys
  24. import pkg_resources
  25. import qubes.tests
  26. import qubes.vm.appvm
  27. class ProcessWrapper(object):
  28. def __init__(self, proc, loop=None):
  29. self._proc = proc
  30. self._loop = loop or asyncio.get_event_loop()
  31. def __getattr__(self, item):
  32. return getattr(self._proc, item)
  33. def __setattr__(self, key, value):
  34. if key.startswith('_'):
  35. return super(ProcessWrapper, self).__setattr__(key, value)
  36. return setattr(self._proc, key, value)
  37. def communicate(self, input=None):
  38. return self._loop.run_until_complete(self._proc.communicate(input))
  39. def wait(self):
  40. return self._loop.run_until_complete(self._proc.wait())
  41. class VMWrapper(object):
  42. '''Wrap VM object to provide stable API for basic operations'''
  43. def __init__(self, vm, loop=None):
  44. self._vm = vm
  45. self._loop = loop or asyncio.get_event_loop()
  46. def __getattr__(self, item):
  47. return getattr(self._vm, item)
  48. def __setattr__(self, key, value):
  49. if key.startswith('_'):
  50. return super(VMWrapper, self).__setattr__(key, value)
  51. return setattr(self._vm, key, value)
  52. def __str__(self):
  53. return str(self._vm)
  54. def __eq__(self, other):
  55. return self._vm == other
  56. def __hash__(self):
  57. return hash(self._vm)
  58. def start(self, start_guid=True):
  59. return self._loop.run_until_complete(
  60. self._vm.start(start_guid=start_guid))
  61. def shutdown(self):
  62. return self._loop.run_until_complete(self._vm.shutdown())
  63. def run(self, command, wait=False, user=None, passio_popen=False,
  64. passio_stderr=False, **kwargs):
  65. if wait:
  66. try:
  67. self._loop.run_until_complete(
  68. self._vm.run_for_stdio(command, user=user))
  69. except subprocess.CalledProcessError as err:
  70. return err.returncode
  71. return 0
  72. elif passio_popen:
  73. p = self._loop.run_until_complete(self._vm.run(command, user=user,
  74. stdin=subprocess.PIPE,
  75. stdout=subprocess.PIPE,
  76. stderr=subprocess.PIPE if passio_stderr else None))
  77. return ProcessWrapper(p, self._loop)
  78. else:
  79. asyncio.ensure_future(self._vm.run_for_stdio(command, user=user),
  80. loop=self._loop)
  81. def run_service(self, service, wait=True, input=None, user=None,
  82. passio_popen=False,
  83. passio_stderr=False, **kwargs):
  84. if wait:
  85. try:
  86. if isinstance(input, str):
  87. input = input.encode()
  88. self._loop.run_until_complete(
  89. self._vm.run_service_for_stdio(service,
  90. input=input, user=user))
  91. except subprocess.CalledProcessError as err:
  92. return err.returncode
  93. return 0
  94. elif passio_popen:
  95. p = self._loop.run_until_complete(self._vm.run_service(service,
  96. user=user,
  97. stdin=subprocess.PIPE,
  98. stdout=subprocess.PIPE,
  99. stderr=subprocess.PIPE if passio_stderr else None))
  100. return ProcessWrapper(p, self._loop)
  101. class ExtraTestCase(qubes.tests.SystemTestCase):
  102. template = None
  103. def setUp(self):
  104. super(ExtraTestCase, self).setUp()
  105. self.init_default_template(self.template)
  106. if self.template is not None:
  107. # also use this template for DispVMs
  108. dispvm_base = self.app.add_new_vm('AppVM',
  109. name=self.make_vm_name('dvm'),
  110. template=self.template, label='red', template_for_dispvms=True)
  111. self.loop.run_until_complete(dispvm_base.create_on_disk())
  112. self.app.default_dispvm = dispvm_base
  113. def tearDown(self):
  114. self.app.default_dispvm = None
  115. super(ExtraTestCase, self).tearDown()
  116. def create_vms(self, names):
  117. """
  118. Create AppVMs for the duration of the test. Will be automatically
  119. removed after completing the test.
  120. :param names: list of VM names to create (each of them will be
  121. prefixed with some test specific string)
  122. :return: list of created VM objects
  123. """
  124. if self.template:
  125. template = self.app.domains[self.template]
  126. else:
  127. template = self.app.default_template
  128. for vmname in names:
  129. vm = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  130. name=self.make_vm_name(vmname),
  131. template=template,
  132. label='red')
  133. self.loop.run_until_complete(vm.create_on_disk())
  134. self.app.save()
  135. # get objects after reload
  136. vms = []
  137. for vmname in names:
  138. vms.append(VMWrapper(self.app.domains[self.make_vm_name(vmname)],
  139. loop=self.loop))
  140. return vms
  141. def enable_network(self):
  142. """
  143. Enable access to the network. Must be called before creating VMs.
  144. """
  145. self.init_networking()
  146. def qrexec_policy(self, service, source, destination, allow=True):
  147. """
  148. Allow qrexec calls for duration of the test
  149. :param service: service name
  150. :param source: source VM name
  151. :param destination: destination VM name
  152. :return:
  153. """
  154. def add_remove_rule(add=True):
  155. with open('/etc/qubes-rpc/policy/{}'.format(service), 'r+') as policy:
  156. policy_rules = policy.readlines()
  157. rule = "{} {} {}\n".format(source, destination,
  158. 'allow' if allow else 'deny')
  159. if add:
  160. policy_rules.insert(0, rule)
  161. else:
  162. policy_rules.remove(rule)
  163. policy.truncate(0)
  164. policy.seek(0)
  165. policy.write(''.join(policy_rules))
  166. add_remove_rule(add=True)
  167. self.addCleanup(add_remove_rule, add=False)
  168. def load_tests(loader, tests, pattern):
  169. include_list = None
  170. if 'QUBES_TEST_EXTRA_INCLUDE' in os.environ:
  171. include_list = os.environ['QUBES_TEST_EXTRA_INCLUDE'].split()
  172. exclude_list = []
  173. if 'QUBES_TEST_EXTRA_EXCLUDE' in os.environ:
  174. exclude_list = os.environ['QUBES_TEST_EXTRA_EXCLUDE'].split()
  175. for entry in pkg_resources.iter_entry_points('qubes.tests.extra'):
  176. if include_list is not None and entry.name not in include_list:
  177. continue
  178. if entry.name in exclude_list:
  179. continue
  180. try:
  181. for test_case in entry.load()():
  182. tests.addTests(loader.loadTestsFromNames([
  183. '{}.{}'.format(test_case.__module__, test_case.__name__)]))
  184. except Exception as err: # pylint: disable=broad-except
  185. def runTest(self):
  186. raise err
  187. ExtraLoadFailure = type('ExtraLoadFailure',
  188. (qubes.tests.QubesTestCase,),
  189. {entry.name: runTest})
  190. tests.addTest(ExtraLoadFailure(entry.name))
  191. for entry in pkg_resources.iter_entry_points(
  192. 'qubes.tests.extra.for_template'):
  193. if include_list is not None and entry.name not in include_list:
  194. continue
  195. if entry.name in exclude_list:
  196. continue
  197. try:
  198. for test_case in entry.load()():
  199. tests.addTests(loader.loadTestsFromNames(
  200. qubes.tests.create_testcases_for_templates(
  201. test_case.__name__, test_case,
  202. module=sys.modules[test_case.__module__])))
  203. except Exception as err: # pylint: disable=broad-except
  204. def runTest(self):
  205. raise err
  206. ExtraForTemplateLoadFailure = type('ExtraForTemplateLoadFailure',
  207. (qubes.tests.QubesTestCase,),
  208. {entry.name: runTest})
  209. tests.addTest(ExtraForTemplateLoadFailure(entry.name))
  210. return tests