test_boto_cognitoidentity.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. # -*- coding: utf-8 -*-
  2. # Import Python libs
  3. from __future__ import absolute_import, print_function, unicode_literals
  4. import logging
  5. import random
  6. import string
  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 patch, MagicMock
  12. # Import Salt libs
  13. import salt.config
  14. import salt.loader
  15. from salt.utils.versions import LooseVersion
  16. import salt.states.boto_cognitoidentity as boto_cognitoidentity
  17. # pylint: disable=import-error,no-name-in-module
  18. from tests.unit.modules.test_boto_cognitoidentity import BotoCognitoIdentityTestCaseMixin
  19. # Import 3rd-party libs
  20. try:
  21. import boto3
  22. from botocore.exceptions import ClientError
  23. HAS_BOTO = True
  24. except ImportError:
  25. HAS_BOTO = False
  26. from salt.ext.six.moves import range
  27. # pylint: enable=import-error,no-name-in-module
  28. # the boto_cognitoidentity module relies on the connect_to_region() method
  29. # which was added in boto 2.8.0
  30. # https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12
  31. required_boto3_version = '1.2.1'
  32. region = 'us-east-1'
  33. access_key = 'GKTADJGHEIQSXMKKRBJ08H'
  34. secret_key = 'askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs'
  35. conn_parameters = {'region': region, 'key': access_key, 'keyid': secret_key, 'profile': {}}
  36. error_message = 'An error occurred (101) when calling the {0} operation: Test-defined error'
  37. error_content = {
  38. 'Error': {
  39. 'Code': 101,
  40. 'Message': "Test-defined error"
  41. }
  42. }
  43. first_pool_id = 'first_pool_id'
  44. first_pool_name = 'first_pool'
  45. second_pool_id = 'second_pool_id'
  46. second_pool_name = 'second_pool'
  47. second_pool_name_updated = 'second_pool_updated'
  48. third_pool_id = 'third_pool_id'
  49. third_pool_name = first_pool_name
  50. default_pool_name = 'default_pool_name'
  51. default_pool_id = 'default_pool_id'
  52. default_dev_provider = 'test_provider_default'
  53. identity_pools_ret = dict(IdentityPools=[dict(IdentityPoolId=first_pool_id,
  54. IdentityPoolName=first_pool_name),
  55. dict(IdentityPoolId=second_pool_id,
  56. IdentityPoolName=second_pool_name),
  57. dict(IdentityPoolId=third_pool_id,
  58. IdentityPoolName=third_pool_name)])
  59. first_pool_ret = dict(IdentityPoolId=first_pool_id,
  60. IdentityPoolName=first_pool_name,
  61. AllowUnauthenticatedIdentities=False,
  62. SupportedLoginProviders={'accounts.google.com': 'testing123',
  63. 'api.twitter.com': 'testing123',
  64. 'graph.facebook.com': 'testing123',
  65. 'www.amazon.com': 'testing123'},
  66. DeveloperProviderName='test_provider',
  67. OpenIdConnectProviderARNs=['some_provider_arn',
  68. 'another_provider_arn'])
  69. first_pool_role_ret = dict(IdentityPoolId=first_pool_id,
  70. Roles=dict(authenticated='first_pool_auth_role',
  71. unauthenticated='first_pool_unauth_role'))
  72. second_pool_ret = dict(IdentityPoolId=second_pool_id,
  73. IdentityPoolName=second_pool_name,
  74. AllowUnauthenticatedIdentities=False)
  75. second_pool_role_ret = dict(IdentityPoolId=second_pool_id,
  76. Roles=dict(authenticated='second_pool_auth_role'))
  77. second_pool_update_ret = dict(IdentityPoolId=second_pool_id,
  78. IdentityPoolName=second_pool_name,
  79. AllowUnauthenticatedIdentities=True)
  80. third_pool_ret = dict(IdentityPoolId=third_pool_id,
  81. IdentityPoolName=third_pool_name,
  82. AllowUnauthenticatedIdentities=False,
  83. DeveloperProviderName='test_provider2')
  84. third_pool_role_ret = dict(IdentityPoolId=third_pool_id)
  85. default_pool_ret = dict(IdentityPoolId=default_pool_id,
  86. IdentityPoolName=default_pool_name,
  87. AllowUnauthenticatedIdentities=False,
  88. DeveloperProviderName=default_dev_provider)
  89. default_pool_role_ret = dict(IdentityPoolId=default_pool_id)
  90. log = logging.getLogger(__name__)
  91. def _has_required_boto():
  92. '''
  93. Returns True/False boolean depending on if Boto is installed and correct
  94. version.
  95. '''
  96. if not HAS_BOTO:
  97. return False
  98. elif LooseVersion(boto3.__version__) < LooseVersion(required_boto3_version):
  99. return False
  100. else:
  101. return True
  102. class BotoCognitoIdentityStateTestCaseBase(TestCase, LoaderModuleMockMixin):
  103. conn = None
  104. def setup_loader_modules(self):
  105. ctx = {}
  106. utils = salt.loader.utils(
  107. self.opts,
  108. whitelist=['boto', 'boto3', 'args', 'systemd', 'path', 'platform', 'reg'],
  109. context=ctx)
  110. serializers = salt.loader.serializers(self.opts)
  111. self.funcs = funcs = salt.loader.minion_mods(self.opts, context=ctx, utils=utils, whitelist=['boto_cognitoidentity'])
  112. self.salt_states = salt.loader.states(opts=self.opts, functions=funcs, utils=utils, whitelist=['boto_cognitoidentity'],
  113. serializers=serializers)
  114. return {
  115. boto_cognitoidentity: {
  116. '__opts__': self.opts,
  117. '__salt__': funcs,
  118. '__utils__': utils,
  119. '__states__': self.salt_states,
  120. '__serializers__': serializers,
  121. }
  122. }
  123. @classmethod
  124. def setUpClass(cls):
  125. cls.opts = salt.config.DEFAULT_MINION_OPTS.copy()
  126. cls.opts['grains'] = salt.loader.grains(cls.opts)
  127. @classmethod
  128. def tearDownClass(cls):
  129. del cls.opts
  130. def setUp(self):
  131. self.addCleanup(delattr, self, 'funcs')
  132. self.addCleanup(delattr, self, 'salt_states')
  133. # Set up MagicMock to replace the boto3 session
  134. # connections keep getting cached from prior tests, can't find the
  135. # correct context object to clear it. So randomize the cache key, to prevent any
  136. # cache hits
  137. conn_parameters['key'] = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(50))
  138. self.patcher = patch('boto3.session.Session')
  139. self.addCleanup(self.patcher.stop)
  140. self.addCleanup(delattr, self, 'patcher')
  141. mock_session = self.patcher.start()
  142. session_instance = mock_session.return_value
  143. self.conn = MagicMock()
  144. self.addCleanup(delattr, self, 'conn')
  145. session_instance.client.return_value = self.conn
  146. @skipIf(HAS_BOTO is False, 'The boto module must be installed.')
  147. @skipIf(_has_required_boto() is False, 'The boto3 module must be greater than'
  148. ' or equal to version {0}'
  149. .format(required_boto3_version))
  150. class BotoCognitoIdentityTestCase(BotoCognitoIdentityStateTestCaseBase, BotoCognitoIdentityTestCaseMixin):
  151. '''
  152. TestCase for salt.states.boto_cognitoidentity state.module
  153. '''
  154. def _describe_identity_pool_side_effect(self, *args, **kwargs):
  155. if kwargs.get('IdentityPoolId') == first_pool_id:
  156. return first_pool_ret
  157. elif kwargs.get('IdentityPoolId') == second_pool_id:
  158. return second_pool_ret
  159. elif kwargs.get('IdentityPoolId') == third_pool_id:
  160. return third_pool_ret
  161. else:
  162. return default_pool_ret
  163. def test_present_when_failing_to_describe_identity_pools(self):
  164. '''
  165. Tests exceptions when describing identity pools
  166. '''
  167. self.conn.list_identity_pools.return_value = identity_pools_ret
  168. self.conn.describe_identity_pool.side_effect = ClientError(error_content, 'error on describe identity pool')
  169. result = self.salt_states['boto_cognitoidentity.pool_present'](
  170. name='test pool present',
  171. IdentityPoolName=first_pool_name,
  172. AuthenticatedRole='my_auth_role',
  173. **conn_parameters)
  174. self.assertEqual(result.get('result'), False)
  175. self.assertTrue('error on describe identity pool' in result.get('comment', {}))
  176. def test_present_when_multiple_pools_with_same_name_exist(self):
  177. '''
  178. Tests present on an identity pool name where it matched
  179. multiple pools. The result should fail.
  180. '''
  181. self.conn.list_identity_pools.return_value = identity_pools_ret
  182. self.conn.describe_identity_pool.side_effect = self._describe_identity_pool_side_effect
  183. result = self.salt_states['boto_cognitoidentity.pool_present'](
  184. name='test pool present',
  185. IdentityPoolName=first_pool_name,
  186. AuthenticatedRole='my_auth_role',
  187. **conn_parameters)
  188. self.assertEqual(result.get('result'), False)
  189. self.assertIn('{0}'.format([first_pool_ret, third_pool_ret]), result.get('comment', ''))
  190. def test_present_when_failing_to_create_a_new_identity_pool(self):
  191. '''
  192. Tests present on an identity pool name that doesn't exist and
  193. an error is thrown on creation.
  194. '''
  195. self.conn.list_identity_pools.return_value = identity_pools_ret
  196. self.conn.describe_identity_pool.side_effect = self._describe_identity_pool_side_effect
  197. self.conn.create_identity_pool.side_effect = ClientError(error_content, 'error on create_identity_pool')
  198. result = self.salt_states['boto_cognitoidentity.pool_present'](
  199. name='test pool present',
  200. IdentityPoolName=default_pool_name,
  201. AuthenticatedRole='my_auth_role',
  202. **conn_parameters)
  203. self.assertEqual(result.get('result'), False)
  204. self.assertTrue('error on create_identity_pool' in result.get('comment', ''))
  205. self.assertTrue(self.conn.update_identity_pool.call_count == 0)
  206. def test_present_when_failing_to_update_an_existing_identity_pool(self):
  207. '''
  208. Tests present on a unique instance of identity pool having the matching
  209. IdentityPoolName, and an error is thrown on updating the pool properties.
  210. '''
  211. self.conn.list_identity_pools.return_value = identity_pools_ret
  212. self.conn.describe_identity_pool.side_effect = self._describe_identity_pool_side_effect
  213. self.conn.update_identity_pool.side_effect = ClientError(error_content, 'error on update_identity_pool')
  214. result = self.salt_states['boto_cognitoidentity.pool_present'](
  215. name='test pool present',
  216. IdentityPoolName=second_pool_name,
  217. AuthenticatedRole='my_auth_role',
  218. AllowUnauthenticatedIdentities=True,
  219. **conn_parameters)
  220. self.assertEqual(result.get('result'), False)
  221. self.assertTrue('error on update_identity_pool' in result.get('comment', ''))
  222. self.assertTrue(self.conn.create_identity_pool.call_count == 0)
  223. def _get_identity_pool_roles_side_effect(self, *args, **kwargs):
  224. if kwargs.get('IdentityPoolId') == first_pool_id:
  225. return first_pool_role_ret
  226. elif kwargs.get('IdentityPoolId') == second_pool_id:
  227. return second_pool_role_ret
  228. elif kwargs.get('IdentityPoolId') == third_pool_id:
  229. return third_pool_role_ret
  230. else:
  231. return default_pool_role_ret
  232. def test_present_when_failing_to_get_identity_pool_roles(self):
  233. '''
  234. Tests present on a unique instance of identity pool having the matching
  235. IdentityPoolName, where update_identity_pool succeeded, but an error
  236. is thrown on getting the identity pool role prior to setting the roles.
  237. '''
  238. self.conn.list_identity_pools.return_value = identity_pools_ret
  239. self.conn.describe_identity_pool.side_effect = self._describe_identity_pool_side_effect
  240. self.conn.update_identity_pool.return_value = second_pool_update_ret
  241. self.conn.get_identity_pool_roles.side_effect = ClientError(error_content, 'error on get_identity_pool_roles')
  242. result = self.salt_states['boto_cognitoidentity.pool_present'](
  243. name='test pool present',
  244. IdentityPoolName=second_pool_name,
  245. AuthenticatedRole='my_auth_role',
  246. AllowUnauthenticatedIdentities=True,
  247. **conn_parameters)
  248. self.assertEqual(result.get('result'), False)
  249. self.assertTrue('error on get_identity_pool_roles' in result.get('comment', ''))
  250. self.assertTrue(self.conn.create_identity_pool.call_count == 0)
  251. self.assertTrue(self.conn.set_identity_pool_roles.call_count == 0)
  252. def test_present_when_failing_to_set_identity_pool_roles(self):
  253. '''
  254. Tests present on a unique instance of identity pool having the matching
  255. IdentityPoolName, where update_identity_pool succeeded, but an error
  256. is thrown on setting the identity pool role.
  257. '''
  258. self.conn.list_identity_pools.return_value = identity_pools_ret
  259. self.conn.describe_identity_pool.side_effect = self._describe_identity_pool_side_effect
  260. self.conn.update_identity_pool.return_value = second_pool_update_ret
  261. self.conn.get_identity_pool_roles.return_value = second_pool_role_ret
  262. self.conn.set_identity_pool_roles.side_effect = ClientError(error_content, 'error on set_identity_pool_roles')
  263. with patch.dict(self.funcs, {'boto_iam.describe_role': MagicMock(return_value={'arn': 'my_auth_role_arn'})}):
  264. result = self.salt_states['boto_cognitoidentity.pool_present'](
  265. name='test pool present',
  266. IdentityPoolName=second_pool_name,
  267. AuthenticatedRole='my_auth_role',
  268. AllowUnauthenticatedIdentities=True,
  269. **conn_parameters)
  270. self.assertEqual(result.get('result'), False)
  271. self.assertTrue('error on set_identity_pool_roles' in result.get('comment', ''))
  272. expected_call_args = (dict(IdentityPoolId=second_pool_id,
  273. Roles={'authenticated': 'my_auth_role_arn'}),)
  274. self.assertTrue(self.conn.set_identity_pool_roles.call_args == expected_call_args)
  275. def test_present_when_pool_name_does_not_exist(self):
  276. '''
  277. Tests the successful case of creating a new instance, and updating its
  278. roles
  279. '''
  280. self.conn.list_identity_pools.return_value = identity_pools_ret
  281. self.conn.create_identity_pool.side_effect = self._describe_identity_pool_side_effect
  282. self.conn.get_identity_pool_roles.return_value = default_pool_role_ret
  283. self.conn.set_identity_pool_roles.return_value = None
  284. with patch.dict(self.funcs, {'boto_iam.describe_role': MagicMock(return_value={'arn': 'my_auth_role_arn'})}):
  285. result = self.salt_states['boto_cognitoidentity.pool_present'](
  286. name='test pool present',
  287. IdentityPoolName=default_pool_name,
  288. AuthenticatedRole='my_auth_role',
  289. AllowUnauthenticatedIdentities=True,
  290. DeveloperProviderName=default_dev_provider,
  291. **conn_parameters)
  292. self.assertEqual(result.get('result'), True)
  293. expected_call_args = (dict(AllowUnauthenticatedIdentities=True,
  294. IdentityPoolName=default_pool_name,
  295. DeveloperProviderName=default_dev_provider,
  296. SupportedLoginProviders={},
  297. OpenIdConnectProviderARNs=[]),)
  298. self.assertTrue(self.conn.create_identity_pool.call_args == expected_call_args)
  299. expected_call_args = (dict(IdentityPoolId=default_pool_id,
  300. Roles={'authenticated': 'my_auth_role_arn'}),)
  301. self.assertTrue(self.conn.set_identity_pool_roles.call_args == expected_call_args)
  302. self.assertTrue(self.conn.update_identity_pool.call_count == 0)
  303. def test_present_when_pool_name_exists(self):
  304. '''
  305. Tests the successful case of updating a single instance with matching
  306. IdentityPoolName and its roles.
  307. '''
  308. self.conn.list_identity_pools.return_value = identity_pools_ret
  309. self.conn.describe_identity_pool.side_effect = self._describe_identity_pool_side_effect
  310. self.conn.update_identity_pool.return_value = second_pool_update_ret
  311. self.conn.get_identity_pool_roles.return_value = second_pool_role_ret
  312. self.conn.set_identity_pool_roles.return_value = None
  313. with patch.dict(self.funcs, {'boto_iam.describe_role': MagicMock(return_value={'arn': 'my_auth_role_arn'})}):
  314. result = self.salt_states['boto_cognitoidentity.pool_present'](
  315. name='test pool present',
  316. IdentityPoolName=second_pool_name,
  317. AuthenticatedRole='my_auth_role',
  318. AllowUnauthenticatedIdentities=True,
  319. **conn_parameters)
  320. self.assertEqual(result.get('result'), True)
  321. expected_call_args = (dict(AllowUnauthenticatedIdentities=True,
  322. IdentityPoolId=second_pool_id,
  323. IdentityPoolName=second_pool_name),)
  324. self.assertTrue(self.conn.update_identity_pool.call_args == expected_call_args)
  325. expected_call_args = (dict(IdentityPoolId=second_pool_id,
  326. Roles={'authenticated': 'my_auth_role_arn'}),)
  327. self.assertTrue(self.conn.set_identity_pool_roles.call_args == expected_call_args)
  328. self.assertTrue(self.conn.create_identity_pool.call_count == 0)
  329. def test_absent_when_pool_does_not_exist(self):
  330. '''
  331. Tests absent on an identity pool that does not exist.
  332. '''
  333. self.conn.list_identity_pools.return_value = identity_pools_ret
  334. result = self.salt_states['boto_cognitoidentity.pool_absent'](
  335. name='test pool absent',
  336. IdentityPoolName='no_such_pool_name',
  337. RemoveAllMatched=False,
  338. **conn_parameters)
  339. self.assertEqual(result.get('result'), True)
  340. self.assertEqual(result['changes'], {})
  341. def test_absent_when_removeallmatched_is_false_and_multiple_pools_matched(self):
  342. '''
  343. Tests absent on when RemoveAllMatched flag is false and there are multiple matches
  344. for the given pool name
  345. first_pool_name is matched to first and third pool with different id's
  346. '''
  347. self.conn.list_identity_pools.return_value = identity_pools_ret
  348. self.conn.describe_identity_pool.side_effect = self._describe_identity_pool_side_effect
  349. result = self.salt_states['boto_cognitoidentity.pool_absent'](
  350. name='test pool absent',
  351. IdentityPoolName=first_pool_name,
  352. RemoveAllMatched=False,
  353. **conn_parameters)
  354. self.assertEqual(result.get('result'), False)
  355. self.assertEqual(result['changes'], {})
  356. self.assertTrue('{0}'.format([first_pool_ret, third_pool_ret]) in result.get('comment', ''))
  357. def test_absent_when_failing_to_describe_identity_pools(self):
  358. '''
  359. Tests exceptions when describing identity pools
  360. '''
  361. self.conn.list_identity_pools.return_value = identity_pools_ret
  362. self.conn.describe_identity_pool.side_effect = ClientError(error_content, 'error on describe identity pool')
  363. result = self.salt_states['boto_cognitoidentity.pool_absent'](
  364. name='test pool absent',
  365. IdentityPoolName=first_pool_name,
  366. RemoveAllMatched=False,
  367. **conn_parameters)
  368. self.assertEqual(result.get('result'), False)
  369. self.assertTrue('error on describe identity pool' in result.get('comment', {}))
  370. def test_absent_when_erroring_on_delete_identity_pool(self):
  371. '''
  372. Tests error due to delete_identity_pools
  373. '''
  374. self.conn.list_identity_pools.return_value = identity_pools_ret
  375. self.conn.describe_identity_pool.side_effect = self._describe_identity_pool_side_effect
  376. self.conn.delete_identity_pool.side_effect = ClientError(error_content, 'error on delete identity pool')
  377. result = self.salt_states['boto_cognitoidentity.pool_absent'](
  378. name='test pool absent',
  379. IdentityPoolName=first_pool_name,
  380. RemoveAllMatched=True,
  381. **conn_parameters)
  382. self.assertEqual(result.get('result'), False)
  383. self.assertEqual(result['changes'], {})
  384. self.assertTrue('error on delete identity pool' in result.get('comment', ''))
  385. def test_absent_when_a_single_pool_exists(self):
  386. '''
  387. Tests absent succeeds on delete when a single pool matched and
  388. RemoveAllMatched is False
  389. '''
  390. self.conn.list_identity_pools.return_value = identity_pools_ret
  391. self.conn.describe_identity_pool.return_value = second_pool_ret
  392. self.conn.delete_identity_pool.return_value = None
  393. result = self.salt_states['boto_cognitoidentity.pool_absent'](
  394. name='test pool absent',
  395. IdentityPoolName=second_pool_name,
  396. RemoveAllMatched=False,
  397. **conn_parameters)
  398. self.assertEqual(result.get('result'), True)
  399. expected_changes = {'new': {'Identity Pool Id {0}'.format(second_pool_id): None},
  400. 'old': {'Identity Pool Id {0}'.format(second_pool_id): second_pool_name}}
  401. self.assertEqual(result['changes'], expected_changes)
  402. def test_absent_when_multiple_pool_exists_and_removeallmatched_flag_is_true(self):
  403. '''
  404. Tests absent succeeds on delete when a multiple pools matched and
  405. RemoveAllMatched is True
  406. first_pool_name should match to first_pool_id and third_pool_id
  407. '''
  408. self.conn.list_identity_pools.return_value = identity_pools_ret
  409. self.conn.describe_identity_pool.side_effect = self._describe_identity_pool_side_effect
  410. self.conn.delete_identity_pool.return_value = None
  411. result = self.salt_states['boto_cognitoidentity.pool_absent'](
  412. name='test pool absent',
  413. IdentityPoolName=first_pool_name,
  414. RemoveAllMatched=True,
  415. **conn_parameters)
  416. self.assertEqual(result.get('result'), True)
  417. expected_changes = {'new': {'Identity Pool Id {0}'.format(first_pool_id): None,
  418. 'Identity Pool Id {0}'.format(third_pool_id): None},
  419. 'old': {'Identity Pool Id {0}'.format(first_pool_id): first_pool_name,
  420. 'Identity Pool Id {0}'.format(third_pool_id): third_pool_name}}
  421. self.assertEqual(result['changes'], expected_changes)