1
0

test_vault.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. # -*- coding: utf-8 -*-
  2. '''
  3. Unit tests for the Vault runner
  4. '''
  5. # Import Python Libs
  6. from __future__ import absolute_import, print_function, unicode_literals
  7. import logging
  8. # Import Salt Testing Libs
  9. from tests.support.mixins import LoaderModuleMockMixin
  10. from tests.support.unit import skipIf, TestCase
  11. from tests.support.mock import (
  12. MagicMock,
  13. Mock,
  14. patch,
  15. NO_MOCK,
  16. NO_MOCK_REASON,
  17. ANY,
  18. call
  19. )
  20. # Import salt libs
  21. from salt.ext import six
  22. import salt.runners.vault as vault
  23. log = logging.getLogger(__name__)
  24. class VaultTest(TestCase, LoaderModuleMockMixin):
  25. '''
  26. Tests for the runner module of the Vault integration
  27. '''
  28. def setup_loader_modules(self):
  29. return {vault: {}}
  30. def setUp(self):
  31. self.grains = {
  32. 'id': 'test-minion',
  33. 'roles': ['web', 'database'],
  34. 'aux': ['foo', 'bar'],
  35. 'deep': {
  36. 'foo': {
  37. 'bar': {
  38. 'baz': [
  39. 'hello',
  40. 'world'
  41. ]
  42. }
  43. }
  44. },
  45. 'mixedcase': 'UP-low-UP'
  46. }
  47. def tearDown(self):
  48. del self.grains
  49. def test_pattern_list_expander(self):
  50. '''
  51. Ensure _expand_pattern_lists works as intended:
  52. - Expand list-valued patterns
  53. - Do not change non-list-valued tokens
  54. '''
  55. cases = {
  56. 'no-tokens-to-replace': ['no-tokens-to-replace'],
  57. 'single-dict:{minion}': ['single-dict:{minion}'],
  58. 'single-list:{grains[roles]}': ['single-list:web', 'single-list:database'],
  59. 'multiple-lists:{grains[roles]}+{grains[aux]}': [
  60. 'multiple-lists:web+foo',
  61. 'multiple-lists:web+bar',
  62. 'multiple-lists:database+foo',
  63. 'multiple-lists:database+bar',
  64. ],
  65. 'single-list-with-dicts:{grains[id]}+{grains[roles]}+{grains[id]}': [
  66. 'single-list-with-dicts:{grains[id]}+web+{grains[id]}',
  67. 'single-list-with-dicts:{grains[id]}+database+{grains[id]}'
  68. ],
  69. 'deeply-nested-list:{grains[deep][foo][bar][baz]}': [
  70. 'deeply-nested-list:hello',
  71. 'deeply-nested-list:world'
  72. ]
  73. }
  74. # The mappings dict is assembled in _get_policies, so emulate here
  75. mappings = {'minion': self.grains['id'], 'grains': self.grains}
  76. for case, correct_output in six.iteritems(cases):
  77. output = vault._expand_pattern_lists(case, **mappings) # pylint: disable=protected-access
  78. diff = set(output).symmetric_difference(set(correct_output))
  79. if diff:
  80. log.debug('Test %s failed', case)
  81. log.debug('Expected:\n\t%s\nGot\n\t%s', output, correct_output)
  82. log.debug('Difference:\n\t%s', diff)
  83. self.assertEqual(output, correct_output)
  84. def test_get_policies_for_nonexisting_minions(self):
  85. minion_id = 'salt_master'
  86. # For non-existing minions, or the master-minion, grains will be None
  87. cases = {
  88. 'no-tokens-to-replace': ['no-tokens-to-replace'],
  89. 'single-dict:{minion}': ['single-dict:{0}'.format(minion_id)],
  90. 'single-list:{grains[roles]}': []
  91. }
  92. with patch('salt.utils.minions.get_minion_data',
  93. MagicMock(return_value=(None, None, None))):
  94. for case, correct_output in six.iteritems(cases):
  95. test_config = {'policies': [case]}
  96. output = vault._get_policies(minion_id, test_config) # pylint: disable=protected-access
  97. diff = set(output).symmetric_difference(set(correct_output))
  98. if diff:
  99. log.debug('Test %s failed', case)
  100. log.debug('Expected:\n\t%s\nGot\n\t%s', output, correct_output)
  101. log.debug('Difference:\n\t%s', diff)
  102. self.assertEqual(output, correct_output)
  103. @skipIf(NO_MOCK, NO_MOCK_REASON)
  104. def test_get_policies(self):
  105. '''
  106. Ensure _get_policies works as intended, including expansion of lists
  107. '''
  108. cases = {
  109. 'no-tokens-to-replace': ['no-tokens-to-replace'],
  110. 'single-dict:{minion}': ['single-dict:test-minion'],
  111. 'single-list:{grains[roles]}': ['single-list:web', 'single-list:database'],
  112. 'multiple-lists:{grains[roles]}+{grains[aux]}': [
  113. 'multiple-lists:web+foo',
  114. 'multiple-lists:web+bar',
  115. 'multiple-lists:database+foo',
  116. 'multiple-lists:database+bar',
  117. ],
  118. 'single-list-with-dicts:{grains[id]}+{grains[roles]}+{grains[id]}': [
  119. 'single-list-with-dicts:test-minion+web+test-minion',
  120. 'single-list-with-dicts:test-minion+database+test-minion'
  121. ],
  122. 'deeply-nested-list:{grains[deep][foo][bar][baz]}': [
  123. 'deeply-nested-list:hello',
  124. 'deeply-nested-list:world'
  125. ],
  126. 'should-not-cause-an-exception,but-result-empty:{foo}': [],
  127. 'Case-Should-Be-Lowered:{grains[mixedcase]}': [
  128. 'case-should-be-lowered:up-low-up'
  129. ]
  130. }
  131. with patch('salt.utils.minions.get_minion_data',
  132. MagicMock(return_value=(None, self.grains, None))):
  133. for case, correct_output in six.iteritems(cases):
  134. test_config = {'policies': [case]}
  135. output = vault._get_policies('test-minion', test_config) # pylint: disable=protected-access
  136. diff = set(output).symmetric_difference(set(correct_output))
  137. if diff:
  138. log.debug('Test %s failed', case)
  139. log.debug('Expected:\n\t%s\nGot\n\t%s', output, correct_output)
  140. log.debug('Difference:\n\t%s', diff)
  141. self.assertEqual(output, correct_output)
  142. def test_get_token_create_url(self):
  143. '''
  144. Ensure _get_token_create_url parses config correctly
  145. '''
  146. self.assertEqual(vault._get_token_create_url( # pylint: disable=protected-access
  147. {"url": "http://127.0.0.1"}),
  148. "http://127.0.0.1/v1/auth/token/create")
  149. self.assertEqual(vault._get_token_create_url( # pylint: disable=protected-access
  150. {"url": "https://127.0.0.1/"}),
  151. "https://127.0.0.1/v1/auth/token/create")
  152. self.assertEqual(vault._get_token_create_url( # pylint: disable=protected-access
  153. {"url": "http://127.0.0.1:8200", "role_name": "therole"}),
  154. "http://127.0.0.1:8200/v1/auth/token/create/therole")
  155. self.assertEqual(vault._get_token_create_url( # pylint: disable=protected-access
  156. {"url": "https://127.0.0.1/test", "role_name": "therole"}),
  157. "https://127.0.0.1/test/v1/auth/token/create/therole")
  158. def _mock_json_response(data, status_code=200, reason=""):
  159. '''
  160. Mock helper for http response
  161. '''
  162. response = MagicMock()
  163. response.json = MagicMock(return_value=data)
  164. response.status_code = status_code
  165. response.reason = reason
  166. return Mock(return_value=response)
  167. class VaultTokenAuthTest(TestCase, LoaderModuleMockMixin):
  168. '''
  169. Tests for the runner module of the Vault with token setup
  170. '''
  171. def setup_loader_modules(self):
  172. return {
  173. vault: {
  174. '__opts__': {
  175. 'vault': {
  176. 'url': "http://127.0.0.1",
  177. "auth": {
  178. 'token': 'test',
  179. 'method': 'token'
  180. }
  181. }
  182. }
  183. }
  184. }
  185. @patch('salt.runners.vault._validate_signature', MagicMock(return_value=None))
  186. @patch('salt.runners.vault._get_token_create_url', MagicMock(return_value="http://fake_url"))
  187. def test_generate_token(self):
  188. '''
  189. Basic tests for test_generate_token: all exits
  190. '''
  191. mock = _mock_json_response({'auth': {'client_token': 'test'}})
  192. with patch('requests.post', mock):
  193. result = vault.generate_token('test-minion', 'signature')
  194. log.debug('generate_token result: %s', result)
  195. self.assertTrue(isinstance(result, dict))
  196. self.assertFalse('error' in result)
  197. self.assertTrue('token' in result)
  198. self.assertEqual(result['token'], 'test')
  199. mock.assert_called_with("http://fake_url", headers=ANY, json=ANY, verify=ANY)
  200. mock = _mock_json_response({}, status_code=403, reason="no reason")
  201. with patch('requests.post', mock):
  202. result = vault.generate_token('test-minion', 'signature')
  203. self.assertTrue(isinstance(result, dict))
  204. self.assertTrue('error' in result)
  205. self.assertEqual(result['error'], "no reason")
  206. with patch('salt.runners.vault._get_policies', MagicMock(return_value=[])):
  207. result = vault.generate_token('test-minion', 'signature')
  208. self.assertTrue(isinstance(result, dict))
  209. self.assertTrue('error' in result)
  210. self.assertEqual(result['error'], 'No policies matched minion')
  211. with patch('requests.post',
  212. MagicMock(side_effect=Exception('Test Exception Reason'))):
  213. result = vault.generate_token('test-minion', 'signature')
  214. self.assertTrue(isinstance(result, dict))
  215. self.assertTrue('error' in result)
  216. self.assertEqual(result['error'], 'Test Exception Reason')
  217. class VaultAppRoleAuthTest(TestCase, LoaderModuleMockMixin):
  218. '''
  219. Tests for the runner module of the Vault with approle setup
  220. '''
  221. def setup_loader_modules(self):
  222. return {
  223. vault: {
  224. '__opts__': {
  225. 'vault': {
  226. 'url': "http://127.0.0.1",
  227. "auth": {
  228. 'method': 'approle',
  229. 'role_id': 'role',
  230. 'secret_id': 'secret'
  231. }
  232. }
  233. }
  234. }
  235. }
  236. @patch('salt.runners.vault._validate_signature', MagicMock(return_value=None))
  237. @patch('salt.runners.vault._get_token_create_url', MagicMock(return_value="http://fake_url"))
  238. def test_generate_token(self):
  239. '''
  240. Basic test for test_generate_token with approle (two vault calls)
  241. '''
  242. mock = _mock_json_response({'auth': {'client_token': 'test'}})
  243. with patch('requests.post', mock):
  244. result = vault.generate_token('test-minion', 'signature')
  245. log.debug('generate_token result: %s', result)
  246. self.assertTrue(isinstance(result, dict))
  247. self.assertFalse('error' in result)
  248. self.assertTrue('token' in result)
  249. self.assertEqual(result['token'], 'test')
  250. calls = [
  251. call("http://127.0.0.1/v1/auth/approle/login", json=ANY, verify=ANY),
  252. call("http://fake_url", headers=ANY, json=ANY, verify=ANY)
  253. ]
  254. mock.assert_has_calls(calls)