test_vault.py 11 KB

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