blob: 9a9f864e06c28daba48f9e2292a88a18cb2a0384 [file] [log] [blame]
DavidPurcellb25f93d2017-01-27 12:46:27 -05001# Copyright 2017 AT&T Corporation.
DavidPurcell029d8c32017-01-06 15:27:41 -05002# All Rights Reserved.
3#
4# Licensed under the Apache License, Version 2.0 (the "License"); you may
5# not use this file except in compliance with the License. You may obtain
6# a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13# License for the specific language governing permissions and limitations
14# under the License.
15
Felipe Monteiro10e82fd2017-11-21 01:47:20 +000016from contextlib import contextmanager
DavidPurcell029d8c32017-01-06 15:27:41 -050017import time
Felipe Monteiro34a138c2017-03-02 17:01:37 -050018
Rajiv Kumar645dfc92017-01-19 13:48:27 +053019from oslo_log import log as logging
Felipe Monteiro83903412018-07-09 16:33:55 +010020from oslo_log import versionutils
Felipe Monteiro2693bf72017-08-12 22:56:47 +010021from oslo_utils import excutils
Felipe Monteirofa01d5f2017-04-01 06:18:25 +010022
Felipe Monteiro3e14f472017-08-17 23:02:11 +010023from tempest import clients
Felipe Monteiroe7e552e2017-05-02 17:04:12 +010024from tempest.common import credentials_factory as credentials
Felipe Monteirofa01d5f2017-04-01 06:18:25 +010025from tempest import config
DavidPurcell029d8c32017-01-06 15:27:41 -050026
Felipe Monteiro34a138c2017-03-02 17:01:37 -050027from patrole_tempest_plugin import rbac_exceptions
DavidPurcell029d8c32017-01-06 15:27:41 -050028
DavidPurcell029d8c32017-01-06 15:27:41 -050029CONF = config.CONF
Felipe Monteiro34a138c2017-03-02 17:01:37 -050030LOG = logging.getLogger(__name__)
DavidPurcell029d8c32017-01-06 15:27:41 -050031
32
DavidPurcell029d8c32017-01-06 15:27:41 -050033class RbacUtils(object):
Felipe Monteiro10e82fd2017-11-21 01:47:20 +000034 """Utility class responsible for switching ``os_primary`` role.
Felipe Monteiroe8d93e02017-07-19 20:52:20 +010035
36 This class is responsible for overriding the value of the primary Tempest
Felipe Monteiro10e82fd2017-11-21 01:47:20 +000037 credential's role (i.e. ``os_primary`` role). By doing so, it is possible
38 to seamlessly swap between admin credentials, needed for setup and clean
39 up, and primary credentials, needed to perform the API call which does
Felipe Monteiroe8d93e02017-07-19 20:52:20 +010040 policy enforcement. The primary credentials always cycle between roles
Felipe Monteiro10e82fd2017-11-21 01:47:20 +000041 defined by ``CONF.identity.admin_role`` and
42 ``CONF.patrole.rbac_test_role``.
Felipe Monteiroe8d93e02017-07-19 20:52:20 +010043 """
DavidPurcell029d8c32017-01-06 15:27:41 -050044
Felipe Monteirob35de582017-05-05 00:16:53 +010045 def __init__(self, test_obj):
Felipe Monteiroe8d93e02017-07-19 20:52:20 +010046 """Constructor for ``RbacUtils``.
47
Felipe Monteiro2693bf72017-08-12 22:56:47 +010048 :param test_obj: An instance of `tempest.test.BaseTestCase`.
Felipe Monteiroe8d93e02017-07-19 20:52:20 +010049 """
Felipe Monteiroe8d93e02017-07-19 20:52:20 +010050 # Intialize the admin roles_client to perform role switching.
Felipe Monteiro3e14f472017-08-17 23:02:11 +010051 admin_mgr = clients.Manager(
52 credentials.get_configured_admin_credentials())
Felipe Monteiroe8d93e02017-07-19 20:52:20 +010053 if test_obj.get_identity_version() == 'v3':
Felipe Monteiro3e14f472017-08-17 23:02:11 +010054 admin_roles_client = admin_mgr.roles_v3_client
Felipe Monteiroe8d93e02017-07-19 20:52:20 +010055 else:
Felipe Monteiro3e14f472017-08-17 23:02:11 +010056 admin_roles_client = admin_mgr.roles_client
Felipe Monteiroe8d93e02017-07-19 20:52:20 +010057
58 self.admin_roles_client = admin_roles_client
Felipe Monteiro10e82fd2017-11-21 01:47:20 +000059 self._override_role(test_obj, False)
Felipe Monteirob35de582017-05-05 00:16:53 +010060
Felipe Monteirofa01d5f2017-04-01 06:18:25 +010061 admin_role_id = None
62 rbac_role_id = None
DavidPurcell029d8c32017-01-06 15:27:41 -050063
Felipe Monteiro10e82fd2017-11-21 01:47:20 +000064 @contextmanager
65 def override_role(self, test_obj):
66 """Override the role used by ``os_primary`` Tempest credentials.
67
68 Temporarily change the role used by ``os_primary`` credentials to:
Masayuki Igawa80b9aab2018-01-09 17:00:45 +090069
70 * ``[patrole] rbac_test_role`` before test execution
71 * ``[identity] admin_role`` after test execution
Felipe Monteiro10e82fd2017-11-21 01:47:20 +000072
73 Automatically switches to admin role after test execution.
74
75 :param test_obj: Instance of ``tempest.test.BaseTestCase``.
76 :returns: None
77
78 .. warning::
79
80 This function can alter user roles for pre-provisioned credentials.
81 Work is underway to safely clean up after this function.
82
83 Example::
84
85 @rbac_rule_validation.action(service='test',
86 rule='a:test:rule')
87 def test_foo(self):
88 # Allocate test-level resources here.
89 with self.rbac_utils.override_role(self):
melissaml7cd21612018-05-23 21:00:50 +080090 # The role for `os_primary` has now been overridden. Within
Felipe Monteiro10e82fd2017-11-21 01:47:20 +000091 # this block, call the API endpoint that enforces the
92 # expected policy specified by "rule" in the decorator.
93 self.foo_service.bar_api_call()
94 # The role is switched back to admin automatically. Note that
95 # if the API call above threw an exception, any code below this
96 # point in the test is not executed.
97 """
98 self._override_role(test_obj, True)
99 try:
100 # Execute the test.
101 yield
102 finally:
103 # This code block is always executed, no matter the result of the
104 # test. Automatically switch back to the admin role for test clean
105 # up.
106 self._override_role(test_obj, False)
107
Felipe Monteiro10e82fd2017-11-21 01:47:20 +0000108 def _override_role(self, test_obj, toggle_rbac_role=False):
109 """Private helper for overriding ``os_primary`` Tempest credentials.
110
Felipe Monteiro07a1c172017-12-10 04:26:08 +0000111 :param test_obj: instance of :py:class:`tempest.test.BaseTestCase`
Felipe Monteiro10e82fd2017-11-21 01:47:20 +0000112 :param toggle_rbac_role: Boolean value that controls the role that
113 overrides default role of ``os_primary`` credentials.
114 * If True: role is set to ``[patrole] rbac_test_role``
115 * If False: role is set to ``[identity] admin_role``
116 """
Felipe Monteiroe8d93e02017-07-19 20:52:20 +0100117 self.user_id = test_obj.os_primary.credentials.user_id
118 self.project_id = test_obj.os_primary.credentials.tenant_id
119 self.token = test_obj.os_primary.auth_provider.get_token()
DavidPurcell029d8c32017-01-06 15:27:41 -0500120
Felipe Monteiro10e82fd2017-11-21 01:47:20 +0000121 LOG.debug('Overriding role to: %s.', toggle_rbac_role)
Felipe Monteiro2693bf72017-08-12 22:56:47 +0100122 role_already_present = False
123
DavidPurcell029d8c32017-01-06 15:27:41 -0500124 try:
Felipe Monteiro2693bf72017-08-12 22:56:47 +0100125 if not all([self.admin_role_id, self.rbac_role_id]):
126 self._get_roles_by_name()
DavidPurcell029d8c32017-01-06 15:27:41 -0500127
Felipe Monteiro2693bf72017-08-12 22:56:47 +0100128 target_role = (
129 self.rbac_role_id if toggle_rbac_role else self.admin_role_id)
130 role_already_present = self._list_and_clear_user_roles_on_project(
131 target_role)
132
Felipe Monteiro10e82fd2017-11-21 01:47:20 +0000133 # Do not override roles if `target_role` already exists.
Felipe Monteiro2693bf72017-08-12 22:56:47 +0100134 if not role_already_present:
135 self._create_user_role_on_project(target_role)
DavidPurcell029d8c32017-01-06 15:27:41 -0500136 except Exception as exp:
Felipe Monteiro2693bf72017-08-12 22:56:47 +0100137 with excutils.save_and_reraise_exception():
138 LOG.exception(exp)
Felipe Monteiro34a138c2017-03-02 17:01:37 -0500139 finally:
Mykola Yakovliev1d829782018-08-03 14:37:37 -0500140 auth_providers = test_obj.get_auth_providers()
141 for provider in auth_providers:
142 provider.clear_auth()
Felipe Monteiro7be94e82017-07-26 02:17:08 +0100143 # Fernet tokens are not subsecond aware so sleep to ensure we are
144 # passing the second boundary before attempting to authenticate.
Felipe Monteiro2693bf72017-08-12 22:56:47 +0100145 # Only sleep if a token revocation occurred as a result of role
Felipe Monteiro10e82fd2017-11-21 01:47:20 +0000146 # overriding. This will optimize test runtime in the case where
Felipe Monteirob58c1192017-11-20 01:50:24 +0000147 # ``[identity] admin_role`` == ``[patrole] rbac_test_role``.
Felipe Monteiro2693bf72017-08-12 22:56:47 +0100148 if not role_already_present:
Rick Bartra89f498f2017-03-20 15:54:45 -0400149 time.sleep(1)
Mykola Yakovliev1d829782018-08-03 14:37:37 -0500150
151 for provider in auth_providers:
152 provider.set_auth()
Felipe Monteiro34a138c2017-03-02 17:01:37 -0500153
Felipe Monteiro2693bf72017-08-12 22:56:47 +0100154 def _get_roles_by_name(self):
Felipe Monteiro2fc29292018-06-15 18:26:27 -0400155 available_roles = self.admin_roles_client.list_roles()['roles']
156 role_map = {r['name']: r['id'] for r in available_roles}
157 LOG.debug('Available roles: %s', list(role_map.keys()))
Felipe Monteirofa01d5f2017-04-01 06:18:25 +0100158
Felipe Monteiro2fc29292018-06-15 18:26:27 -0400159 admin_role_id = role_map.get(CONF.identity.admin_role)
160 rbac_role_id = role_map.get(CONF.patrole.rbac_test_role)
Felipe Monteiro2693bf72017-08-12 22:56:47 +0100161
162 if not all([admin_role_id, rbac_role_id]):
Felipe Monteiro2fc29292018-06-15 18:26:27 -0400163 missing_roles = []
164 msg = ("Could not find `[patrole] rbac_test_role` or "
165 "`[identity] admin_role`, both of which are required for "
166 "RBAC testing.")
167 if not admin_role_id:
168 missing_roles.append(CONF.identity.admin_role)
169 if not rbac_role_id:
170 missing_roles.append(CONF.patrole.rbac_test_role)
171 msg += " Following roles were not found: %s." % (
172 ", ".join(missing_roles))
173 msg += " Available roles: %s." % ", ".join(list(role_map.keys()))
Felipe Monteiro2693bf72017-08-12 22:56:47 +0100174 raise rbac_exceptions.RbacResourceSetupFailed(msg)
175
176 self.admin_role_id = admin_role_id
177 self.rbac_role_id = rbac_role_id
178
179 def _create_user_role_on_project(self, role_id):
Felipe Monteiroe8d93e02017-07-19 20:52:20 +0100180 self.admin_roles_client.create_user_role_on_project(
Felipe Monteirofa01d5f2017-04-01 06:18:25 +0100181 self.project_id, self.user_id, role_id)
182
Felipe Monteiro2693bf72017-08-12 22:56:47 +0100183 def _list_and_clear_user_roles_on_project(self, role_id):
Felipe Monteiroe8d93e02017-07-19 20:52:20 +0100184 roles = self.admin_roles_client.list_user_roles_on_project(
Felipe Monteirofa01d5f2017-04-01 06:18:25 +0100185 self.project_id, self.user_id)['roles']
Felipe Monteirofa01d5f2017-04-01 06:18:25 +0100186 role_ids = [role['id'] for role in roles]
Felipe Monteiro2693bf72017-08-12 22:56:47 +0100187
188 # NOTE(felipemonteiro): We do not use ``role_id in role_ids`` here to
189 # avoid over-permission errors: if the current list of roles on the
190 # project includes "admin" and "Member", and we are switching to the
191 # "Member" role, then we must delete the "admin" role. Thus, we only
192 # return early if the user's roles on the project are an exact match.
193 if [role_id] == role_ids:
Felipe Monteirofa01d5f2017-04-01 06:18:25 +0100194 return True
Felipe Monteirob3b7bc82017-03-03 15:58:15 -0500195
196 for role in roles:
Felipe Monteiroe8d93e02017-07-19 20:52:20 +0100197 self.admin_roles_client.delete_role_from_user_on_project(
Felipe Monteirofa01d5f2017-04-01 06:18:25 +0100198 self.project_id, self.user_id, role['id'])
199
200 return False
201
Felipe Monteiro17e9b492017-05-27 05:45:20 +0100202
Felipe Monteiro07a1c172017-12-10 04:26:08 +0000203class RbacUtilsMixin(object):
204 """Mixin class to be used alongside an instance of
205 :py:class:`tempest.test.BaseTestCase`.
206
207 Should be used to perform Patrole class setup for a base RBAC class. Child
208 classes should not use this mixin.
209
210 Example::
211
212 class BaseRbacTest(rbac_utils.RbacUtilsMixin, base.BaseV2ComputeTest):
213
214 @classmethod
215 def skip_checks(cls):
216 super(BaseRbacTest, cls).skip_checks()
217 cls.skip_rbac_checks()
218
219 @classmethod
220 def setup_clients(cls):
221 super(BaseRbacTest, cls).setup_clients()
222 cls.setup_rbac_utils()
223 """
224
225 @classmethod
Mykola Yakovliev1d829782018-08-03 14:37:37 -0500226 def get_auth_providers(cls):
227 """Returns list of auth_providers used within test.
228
229 Tests may redefine this method to include their own or third party
230 client auth_providers.
231 """
232 return [cls.os_primary.auth_provider]
233
234 @classmethod
Felipe Monteiro07a1c172017-12-10 04:26:08 +0000235 def skip_rbac_checks(cls):
236 if not CONF.patrole.enable_rbac:
Felipe Monteiro83903412018-07-09 16:33:55 +0100237 deprecation_msg = ("The `[patrole].enable_rbac` option is "
238 "deprecated and will be removed in the S "
239 "release. Patrole tests will always be enabled "
240 "following installation of the Patrole Tempest "
241 "plugin. Use a regex to skip tests.")
242 versionutils.report_deprecated_feature(LOG, deprecation_msg)
Felipe Monteiro07a1c172017-12-10 04:26:08 +0000243 raise cls.skipException(
Felipe Monteirod7371992018-04-25 16:57:09 +0100244 'Patrole testing not enabled so skipping %s.' % cls.__name__)
Felipe Monteiro07a1c172017-12-10 04:26:08 +0000245
246 @classmethod
247 def setup_rbac_utils(cls):
248 cls.rbac_utils = RbacUtils(cls)
249
250
Felipe Monteiro8a043fb2017-08-06 06:29:05 +0100251def is_admin():
252 """Verifies whether the current test role equals the admin role.
253
254 :returns: True if ``rbac_test_role`` is the admin role.
255 """
Felipe Monteiro2fc29292018-06-15 18:26:27 -0400256 # TODO(felipemonteiro): Make this more robust via a context is admin
257 # lookup.
Felipe Monteirof6eb8622017-08-06 06:08:02 +0100258 return CONF.patrole.rbac_test_role == CONF.identity.admin_role