blob: 540d006aa497cd8ef097a3c9e126df1663bd3f4f [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 Monteirob0595652017-01-23 16:51:58 -050016import logging
Felipe Monteiro8eda8cc2017-03-22 14:15:14 +000017import sys
Felipe Monteiro78fc4892017-04-12 21:33:39 +010018import testtools
Felipe Monteiro8eda8cc2017-03-22 14:15:14 +000019
20import six
Felipe Monteirob0595652017-01-23 16:51:58 -050021
DavidPurcell029d8c32017-01-06 15:27:41 -050022from tempest import config
23from tempest.lib import exceptions
raiesmh088590c0c2017-03-14 18:06:52 +053024from tempest import test
DavidPurcell029d8c32017-01-06 15:27:41 -050025
Felipe Monteiro88a5bab2017-08-31 04:00:32 +010026from patrole_tempest_plugin import policy_authority
DavidPurcell029d8c32017-01-06 15:27:41 -050027from patrole_tempest_plugin import rbac_exceptions
Felipe Monteiro8a043fb2017-08-06 06:29:05 +010028from patrole_tempest_plugin import rbac_utils
Rick Bartraed950052017-06-29 17:20:33 -040029from patrole_tempest_plugin import requirements_authority
DavidPurcell029d8c32017-01-06 15:27:41 -050030
31CONF = config.CONF
32LOG = logging.getLogger(__name__)
33
Felipe Monteiro973a1bc2017-06-14 21:23:54 +010034_SUPPORTED_ERROR_CODES = [403, 404]
35
Sean Pryor7f8993f2017-08-14 12:53:17 -040036RBACLOG = logging.getLogger('rbac_reporting')
37
DavidPurcell029d8c32017-01-06 15:27:41 -050038
Felipe Monteiroe7e552e2017-05-02 17:04:12 +010039def action(service, rule='', admin_only=False, expected_error_code=403,
Felipe Monteiro0854ded2017-05-05 16:30:55 +010040 extra_target_data=None):
Felipe Monteirof2b58d72017-08-31 22:40:36 +010041 """A decorator for verifying OpenStack policy enforcement.
Felipe Monteirod5d76b82017-03-20 23:18:50 +000042
Felipe Monteiro01d633b2017-08-16 20:17:26 +010043 A decorator which allows for positive and negative RBAC testing. Given:
Rick Bartraed950052017-06-29 17:20:33 -040044
Felipe Monteiro01d633b2017-08-16 20:17:26 +010045 * an OpenStack service,
46 * a policy action (``rule``) enforced by that service, and
47 * the test role defined by ``[patrole] rbac_test_role``
Felipe Monteirod5d76b82017-03-20 23:18:50 +000048
Felipe Monteiro01d633b2017-08-16 20:17:26 +010049 determines whether the test role has sufficient permissions to perform an
50 API call that enforces the ``rule``.
Felipe Monteirod5d76b82017-03-20 23:18:50 +000051
Felipe Monteiro01d633b2017-08-16 20:17:26 +010052 This decorator should only be applied to an instance or subclass of
Felipe Monteirof2b58d72017-08-31 22:40:36 +010053 ``tempest.test.BaseTestCase``.
Felipe Monteiro01d633b2017-08-16 20:17:26 +010054
55 The result from ``_is_authorized`` is used to determine the *expected*
56 test result. The *actual* test result is determined by running the
57 Tempest test this decorator applies to.
58
59 Below are the following possibilities from comparing the *expected* and
60 *actual* results:
61
62 1) If *expected* is True and the test passes (*actual*), this is a success.
63 2) If *expected* is True and the test fails (*actual*), this results in a
64 `Forbidden` exception failure.
65 3) If *expected* is False and the test passes (*actual*), this results in
66 an `OverPermission` exception failure.
67 4) If *expected* is False and the test fails (*actual*), this is a success.
68
69 As such, negative and positive testing can be applied using this decorator.
70
Felipe Monteirof2b58d72017-08-31 22:40:36 +010071 :param service: An OpenStack service. Examples: "nova" or "neutron".
Felipe Monteiro01d633b2017-08-16 20:17:26 +010072 :param rule: A policy action defined in a policy.json file (or in
73 code).
74
75 .. note::
76
77 Patrole currently only supports custom JSON policy files.
78
Felipe Monteirof2b58d72017-08-31 22:40:36 +010079 :param admin_only: Skips over ``oslo.policy`` check because the policy
80 action defined by ``rule`` is not enforced by the service's policy
Felipe Monteiro01d633b2017-08-16 20:17:26 +010081 enforcement engine. For example, Keystone v2 performs an admin check
Felipe Monteirof2b58d72017-08-31 22:40:36 +010082 for most of its endpoints. If True, ``rule`` is effectively ignored.
Felipe Monteirod5d76b82017-03-20 23:18:50 +000083 :param expected_error_code: Overrides default value of 403 (Forbidden)
Felipe Monteiro973a1bc2017-06-14 21:23:54 +010084 with endpoint-specific error code. Currently only supports 403 and 404.
85 Support for 404 is needed because some services, like Neutron,
86 intentionally throw a 404 for security reasons.
Felipe Monteirod5d76b82017-03-20 23:18:50 +000087
Felipe Monteiro01d633b2017-08-16 20:17:26 +010088 .. warning::
89
90 A 404 should not be provided *unless* the endpoint masks a
Felipe Monteirof2b58d72017-08-31 22:40:36 +010091 ``Forbidden`` exception as a ``NotFound`` exception.
Felipe Monteiro01d633b2017-08-16 20:17:26 +010092
Felipe Monteirof2b58d72017-08-31 22:40:36 +010093 :param extra_target_data: Dictionary, keyed with ``oslo.policy`` generic
Felipe Monteiro01d633b2017-08-16 20:17:26 +010094 check names, whose values are string literals that reference nested
Felipe Monteirof2b58d72017-08-31 22:40:36 +010095 ``tempest.test.BaseTestCase`` attributes. Used by ``oslo.policy`` for
Felipe Monteiro01d633b2017-08-16 20:17:26 +010096 performing matching against attributes that are sent along with the API
97 calls. Example::
98
99 extra_target_data={
100 "target.token.user_id":
101 "os_alt.auth_provider.credentials.user_id"
102 })
103
Felipe Monteirof2b58d72017-08-31 22:40:36 +0100104 :raises NotFound: If ``service`` is invalid.
Felipe Monteiro01d633b2017-08-16 20:17:26 +0100105 :raises Forbidden: For item (2) above.
106 :raises RbacOverPermission: For item (3) above.
107
108 Examples::
109
110 @rbac_rule_validation.action(
111 service="nova", rule="os_compute_api:os-agents")
112 def test_list_agents_rbac(self):
Felipe Monteirof2b58d72017-08-31 22:40:36 +0100113 # The call to `switch_role` is mandatory.
Felipe Monteiro01d633b2017-08-16 20:17:26 +0100114 self.rbac_utils.switch_role(self, toggle_rbac_role=True)
115 self.agents_client.list_agents()
Felipe Monteirod5d76b82017-03-20 23:18:50 +0000116 """
Felipe Monteiro0854ded2017-05-05 16:30:55 +0100117
118 if extra_target_data is None:
119 extra_target_data = {}
120
Sean Pryor7f8993f2017-08-14 12:53:17 -0400121 def decorator(test_func):
Felipe Monteirof6eb8622017-08-06 06:08:02 +0100122 role = CONF.patrole.rbac_test_role
Felipe Monteiro78fc4892017-04-12 21:33:39 +0100123
DavidPurcell029d8c32017-01-06 15:27:41 -0500124 def wrapper(*args, **kwargs):
Felipe Monteiro78fc4892017-04-12 21:33:39 +0100125 if args and isinstance(args[0], test.BaseTestCase):
126 test_obj = args[0]
127 else:
128 raise rbac_exceptions.RbacResourceSetupFailed(
129 '`rbac_rule_validation` decorator can only be applied to '
130 'an instance of `tempest.test.BaseTestCase`.')
raiesmh088590c0c2017-03-14 18:06:52 +0530131
Sean Pryor7f8993f2017-08-14 12:53:17 -0400132 allowed = _is_authorized(test_obj, service, rule,
133 extra_target_data, admin_only)
Felipe Monteirod5d76b82017-03-20 23:18:50 +0000134
Rick Bartra12998942017-03-17 17:35:45 -0400135 expected_exception, irregular_msg = _get_exception_type(
136 expected_error_code)
DavidPurcell029d8c32017-01-06 15:27:41 -0500137
Sean Pryor7f8993f2017-08-14 12:53:17 -0400138 test_status = 'Allowed'
139
DavidPurcell029d8c32017-01-06 15:27:41 -0500140 try:
Sean Pryor7f8993f2017-08-14 12:53:17 -0400141 test_func(*args, **kwargs)
Rick Bartra503c5572017-03-09 13:49:58 -0500142 except rbac_exceptions.RbacInvalidService as e:
Felipe Monteiro48c913d2017-03-15 12:07:48 -0400143 msg = ("%s is not a valid service." % service)
Sean Pryor7f8993f2017-08-14 12:53:17 -0400144 test_status = ('Error, %s' % (msg))
Felipe Monteiro48c913d2017-03-15 12:07:48 -0400145 LOG.error(msg)
146 raise exceptions.NotFound(
Felipe Monteiro78fc4892017-04-12 21:33:39 +0100147 "%s RbacInvalidService was: %s" % (msg, e))
Samantha Blanco36bea052017-07-19 12:01:59 -0400148 except (expected_exception,
149 rbac_exceptions.RbacConflictingPolicies,
150 rbac_exceptions.RbacMalformedResponse) as e:
Sean Pryor7f8993f2017-08-14 12:53:17 -0400151 test_status = 'Denied'
Felipe Monteiro8eda8cc2017-03-22 14:15:14 +0000152 if irregular_msg:
153 LOG.warning(irregular_msg.format(rule, service))
DavidPurcell029d8c32017-01-06 15:27:41 -0500154 if allowed:
155 msg = ("Role %s was not allowed to perform %s." %
Felipe Monteiro78fc4892017-04-12 21:33:39 +0100156 (role, rule))
DavidPurcell029d8c32017-01-06 15:27:41 -0500157 LOG.error(msg)
158 raise exceptions.Forbidden(
Felipe Monteiro4bf66a22017-05-07 14:44:21 +0100159 "%s Exception was: %s" % (msg, e))
Felipe Monteiro8eda8cc2017-03-22 14:15:14 +0000160 except Exception as e:
161 exc_info = sys.exc_info()
162 error_details = exc_info[1].__str__()
Felipe Monteiro5ed98d72017-09-01 20:30:25 +0100163 msg = ("An unexpected exception has occurred during test: %s. "
Sean Pryor7f8993f2017-08-14 12:53:17 -0400164 "Exception was: %s"
165 % (test_func.__name__, error_details))
166 test_status = ('Error, %s' % (error_details))
Felipe Monteiro8eda8cc2017-03-22 14:15:14 +0000167 LOG.error(msg)
168 six.reraise(exc_info[0], exc_info[0](msg), exc_info[2])
DavidPurcell029d8c32017-01-06 15:27:41 -0500169 else:
170 if not allowed:
Felipe Monteiro4bf66a22017-05-07 14:44:21 +0100171 LOG.error("Role %s was allowed to perform %s",
Felipe Monteiroe52cbc62017-05-24 17:48:59 +0100172 role, rule)
DavidPurcell029d8c32017-01-06 15:27:41 -0500173 raise rbac_exceptions.RbacOverPermission(
174 "OverPermission: Role %s was allowed to perform %s" %
Felipe Monteiro78fc4892017-04-12 21:33:39 +0100175 (role, rule))
raiesmh088590c0c2017-03-14 18:06:52 +0530176 finally:
Felipe Monteiro78fc4892017-04-12 21:33:39 +0100177 test_obj.rbac_utils.switch_role(test_obj,
178 toggle_rbac_role=False)
Sean Pryor7f8993f2017-08-14 12:53:17 -0400179 if CONF.patrole_log.enable_reporting:
180 RBACLOG.info(
181 "[Service]: %s, [Test]: %s, [Rule]: %s, "
182 "[Expected]: %s, [Actual]: %s",
183 service, test_func.__name__, rule,
184 "Allowed" if allowed else "Denied",
185 test_status)
Felipe Monteiro78fc4892017-04-12 21:33:39 +0100186
187 _wrapper = testtools.testcase.attr(role)(wrapper)
188 return _wrapper
DavidPurcell029d8c32017-01-06 15:27:41 -0500189 return decorator
Rick Bartra12998942017-03-17 17:35:45 -0400190
191
Sean Pryor7f8993f2017-08-14 12:53:17 -0400192def _is_authorized(test_obj, service, rule, extra_target_data, admin_only):
Felipe Monteirodea13842017-07-05 04:11:18 +0100193 """Validates whether current RBAC role has permission to do policy action.
194
Felipe Monteirof2b58d72017-08-31 22:40:36 +0100195 :param test_obj: An instance or subclass of ``tempest.test.BaseTestCase``.
Felipe Monteiro01d633b2017-08-16 20:17:26 +0100196 :param service: The OpenStack service that enforces ``rule``.
197 :param rule: The name of the policy action. Examples include
198 "identity:create_user" or "os_compute_api:os-agents".
Felipe Monteirof2b58d72017-08-31 22:40:36 +0100199 :param extra_target_data: Dictionary, keyed with ``oslo.policy`` generic
Felipe Monteiro01d633b2017-08-16 20:17:26 +0100200 check names, whose values are string literals that reference nested
Felipe Monteirof2b58d72017-08-31 22:40:36 +0100201 ``tempest.test.BaseTestCase`` attributes. Used by ``oslo.policy`` for
Felipe Monteiro01d633b2017-08-16 20:17:26 +0100202 performing matching against attributes that are sent along with the API
203 calls.
Felipe Monteirof2b58d72017-08-31 22:40:36 +0100204 :param admin_only: Skips over ``oslo.policy`` check because the policy
205 action defined by ``rule`` is not enforced by the service's policy
Sean Pryor7f8993f2017-08-14 12:53:17 -0400206 enforcement engine. For example, Keystone v2 performs an admin check
Felipe Monteirof2b58d72017-08-31 22:40:36 +0100207 for most of its endpoints. If True, ``rule`` is effectively ignored.
Sean Pryor7f8993f2017-08-14 12:53:17 -0400208
Felipe Monteiro01d633b2017-08-16 20:17:26 +0100209 :returns: True if the current RBAC role can perform the policy action,
210 else False.
Sean Pryor7f8993f2017-08-14 12:53:17 -0400211
Felipe Monteiro01d633b2017-08-16 20:17:26 +0100212 :raises RbacResourceSetupFailed: If `project_id` or `user_id` are missing
213 from the `auth_provider` attribute in `test_obj`.
214 :raises RbacParsingException: if ``[patrole] strict_policy_check`` is True
215 and the ``rule`` does not exist in the system.
216 :raises skipException: If ``[patrole] strict_policy_check`` is False and
217 the ``rule`` does not exist in the system.
Felipe Monteirodea13842017-07-05 04:11:18 +0100218 """
Sean Pryor7f8993f2017-08-14 12:53:17 -0400219
220 if admin_only:
221 LOG.info("As admin_only is True, only admin role should be "
222 "allowed to perform the API. Skipping oslo.policy "
223 "check for policy action {0}.".format(rule))
224 return rbac_utils.is_admin()
225
Felipe Monteiro78fc4892017-04-12 21:33:39 +0100226 try:
Felipe Monteiroe8d93e02017-07-19 20:52:20 +0100227 project_id = test_obj.os_primary.credentials.project_id
228 user_id = test_obj.os_primary.credentials.user_id
Felipe Monteiro78fc4892017-04-12 21:33:39 +0100229 except AttributeError as e:
Felipe Monteiroe8d93e02017-07-19 20:52:20 +0100230 msg = ("{0}: project_id or user_id not found in os_primary.credentials"
231 .format(e))
Felipe Monteiro78fc4892017-04-12 21:33:39 +0100232 LOG.error(msg)
233 raise rbac_exceptions.RbacResourceSetupFailed(msg)
234
235 try:
Felipe Monteirof6eb8622017-08-06 06:08:02 +0100236 role = CONF.patrole.rbac_test_role
Felipe Monteiro88a5bab2017-08-31 04:00:32 +0100237 # Test RBAC against custom requirements. Otherwise use oslo.policy.
Felipe Monteirof6eb8622017-08-06 06:08:02 +0100238 if CONF.patrole.test_custom_requirements:
Rick Bartraed950052017-06-29 17:20:33 -0400239 authority = requirements_authority.RequirementsAuthority(
Felipe Monteirof6eb8622017-08-06 06:08:02 +0100240 CONF.patrole.custom_requirements_file, service)
Rick Bartraed950052017-06-29 17:20:33 -0400241 else:
242 formatted_target_data = _format_extra_target_data(
243 test_obj, extra_target_data)
Felipe Monteiro88a5bab2017-08-31 04:00:32 +0100244 authority = policy_authority.PolicyAuthority(
Rick Bartraed950052017-06-29 17:20:33 -0400245 project_id, user_id, service,
246 extra_target_data=formatted_target_data)
Felipe Monteiro01d633b2017-08-16 20:17:26 +0100247 is_allowed = authority.allowed(rule, role)
Felipe Monteiro78fc4892017-04-12 21:33:39 +0100248
249 if is_allowed:
Felipe Monteiro01d633b2017-08-16 20:17:26 +0100250 LOG.debug("[Action]: %s, [Role]: %s is allowed!", rule,
Felipe Monteiro78fc4892017-04-12 21:33:39 +0100251 role)
252 else:
253 LOG.debug("[Action]: %s, [Role]: %s is NOT allowed!",
Felipe Monteiro01d633b2017-08-16 20:17:26 +0100254 rule, role)
Felipe Monteiro78fc4892017-04-12 21:33:39 +0100255 return is_allowed
256 except rbac_exceptions.RbacParsingException as e:
Felipe Monteirof6eb8622017-08-06 06:08:02 +0100257 if CONF.patrole.strict_policy_check:
Felipe Monteiro78fc4892017-04-12 21:33:39 +0100258 raise e
259 else:
260 raise testtools.TestCase.skipException(str(e))
261 return False
262
263
Felipe Monteiro973a1bc2017-06-14 21:23:54 +0100264def _get_exception_type(expected_error_code=403):
265 """Dynamically calculate the expected exception to be caught.
266
267 Dynamically calculate the expected exception to be caught by the test case.
Felipe Monteirof2b58d72017-08-31 22:40:36 +0100268 Only ``Forbidden`` and ``NotFound`` exceptions are permitted. ``NotFound``
269 is supported because Neutron, for security reasons, masks ``Forbidden``
270 exceptions as ``NotFound`` exceptions.
Felipe Monteiro973a1bc2017-06-14 21:23:54 +0100271
272 :param expected_error_code: the integer representation of the expected
Felipe Monteirof2b58d72017-08-31 22:40:36 +0100273 exception to be caught. Must be contained in
274 ``_SUPPORTED_ERROR_CODES``.
Felipe Monteiro973a1bc2017-06-14 21:23:54 +0100275 :returns: tuple of the exception type corresponding to
Felipe Monteirof2b58d72017-08-31 22:40:36 +0100276 ``expected_error_code`` and a message explaining that a non-Forbidden
Felipe Monteiro973a1bc2017-06-14 21:23:54 +0100277 exception was expected, if applicable.
278 """
Rick Bartra12998942017-03-17 17:35:45 -0400279 expected_exception = None
280 irregular_msg = None
Felipe Monteiro973a1bc2017-06-14 21:23:54 +0100281
282 if not isinstance(expected_error_code, six.integer_types) \
Sean Pryor7f8993f2017-08-14 12:53:17 -0400283 or expected_error_code not in _SUPPORTED_ERROR_CODES:
Felipe Monteiro973a1bc2017-06-14 21:23:54 +0100284 msg = ("Please pass an expected error code. Currently "
285 "supported codes: {0}".format(_SUPPORTED_ERROR_CODES))
286 LOG.error(msg)
287 raise rbac_exceptions.RbacInvalidErrorCode(msg)
Felipe Monteiro78fc4892017-04-12 21:33:39 +0100288
Rick Bartra12998942017-03-17 17:35:45 -0400289 if expected_error_code == 403:
290 expected_exception = exceptions.Forbidden
291 elif expected_error_code == 404:
292 expected_exception = exceptions.NotFound
293 irregular_msg = ("NotFound exception was caught for policy action "
294 "{0}. The service {1} throws a 404 instead of a 403, "
295 "which is irregular.")
Rick Bartra12998942017-03-17 17:35:45 -0400296
297 return expected_exception, irregular_msg
Felipe Monteirofd1db982017-04-13 21:19:41 +0100298
299
300def _format_extra_target_data(test_obj, extra_target_data):
301 """Formats the "extra_target_data" dictionary with correct test data.
302
303 Before being formatted, "extra_target_data" is a dictionary that maps a
Felipe Monteiro01d633b2017-08-16 20:17:26 +0100304 policy string like "trust.trustor_user_id" to a nested list of
Felipe Monteirof2b58d72017-08-31 22:40:36 +0100305 ``tempest.test.BaseTestCase`` attributes. For example, the attribute list
306 in:
Felipe Monteirofd1db982017-04-13 21:19:41 +0100307
308 "trust.trustor_user_id": "os.auth_provider.credentials.user_id"
309
Felipe Monteiro01d633b2017-08-16 20:17:26 +0100310 is parsed by iteratively calling ``getattr`` until the value of "user_id"
Felipe Monteirofd1db982017-04-13 21:19:41 +0100311 is resolved. The resulting dictionary returns:
312
Felipe Monteiro01d633b2017-08-16 20:17:26 +0100313 "trust.trustor_user_id": "the user_id of the `os_primary` credential"
Felipe Monteirofd1db982017-04-13 21:19:41 +0100314
Felipe Monteirof2b58d72017-08-31 22:40:36 +0100315 :param test_obj: An instance or subclass of ``tempest.test.BaseTestCase``.
316 :param extra_target_data: Dictionary, keyed with ``oslo.policy`` generic
Felipe Monteiro01d633b2017-08-16 20:17:26 +0100317 check names, whose values are string literals that reference nested
Felipe Monteirof2b58d72017-08-31 22:40:36 +0100318 ``tempest.test.BaseTestCase`` attributes. Used by ``oslo.policy`` for
Felipe Monteiro01d633b2017-08-16 20:17:26 +0100319 performing matching against attributes that are sent along with the API
320 calls.
321 :returns: Dictionary containing additional object data needed by
Felipe Monteirof2b58d72017-08-31 22:40:36 +0100322 ``oslo.policy`` to validate generic checks.
Felipe Monteirofd1db982017-04-13 21:19:41 +0100323 """
324 attr_value = test_obj
325 formatted_target_data = {}
326
327 for user_attribute, attr_string in extra_target_data.items():
328 attrs = attr_string.split('.')
329 for attr in attrs:
330 attr_value = getattr(attr_value, attr)
331 formatted_target_data[user_attribute] = attr_value
332
333 return formatted_target_data