blob: c088ce7c2068182a2505e59af09780c7b143feba [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
DavidPurcell029d8c32017-01-06 15:27:41 -050026from patrole_tempest_plugin import rbac_exceptions
Felipe Monteiro78fc4892017-04-12 21:33:39 +010027from patrole_tempest_plugin import rbac_policy_parser
Rick Bartraed950052017-06-29 17:20:33 -040028from patrole_tempest_plugin import requirements_authority
DavidPurcell029d8c32017-01-06 15:27:41 -050029
30CONF = config.CONF
31LOG = logging.getLogger(__name__)
32
Felipe Monteiro973a1bc2017-06-14 21:23:54 +010033_SUPPORTED_ERROR_CODES = [403, 404]
34
DavidPurcell029d8c32017-01-06 15:27:41 -050035
Felipe Monteiroe7e552e2017-05-02 17:04:12 +010036def action(service, rule='', admin_only=False, expected_error_code=403,
Felipe Monteiro0854ded2017-05-05 16:30:55 +010037 extra_target_data=None):
Felipe Monteirod5d76b82017-03-20 23:18:50 +000038 """A decorator which does a policy check and matches it against test run.
39
40 A decorator which allows for positive and negative RBAC testing. Given
41 an OpenStack service and a policy action enforced by that service, an
42 oslo.policy lookup is performed by calling `authority.get_permission`.
Rick Bartraed950052017-06-29 17:20:33 -040043 Alternatively, the RBAC tests can run against a YAML file that defines
44 policy requirements.
45
Felipe Monteirod5d76b82017-03-20 23:18:50 +000046 The following cases are possible:
47
48 * If `allowed` is True and the test passes, this is a success.
49 * If `allowed` is True and the test fails, this is a failure.
50 * If `allowed` is False and the test passes, this is a failure.
51 * If `allowed` is False and the test fails, this is a success.
52
53 :param service: A OpenStack service: for example, "nova" or "neutron".
54 :param rule: A policy action defined in a policy.json file (or in code).
55 :param admin_only: Skips over oslo.policy check because the policy action
Felipe Monteiro973a1bc2017-06-14 21:23:54 +010056 defined by `rule` is not enforced by the service's policy enforcement
57 logic. For example, Keystone v2 performs an admin check for most of its
58 endpoints. If True, `rule` is effectively ignored.
Felipe Monteirod5d76b82017-03-20 23:18:50 +000059 :param expected_error_code: Overrides default value of 403 (Forbidden)
Felipe Monteiro973a1bc2017-06-14 21:23:54 +010060 with endpoint-specific error code. Currently only supports 403 and 404.
61 Support for 404 is needed because some services, like Neutron,
62 intentionally throw a 404 for security reasons.
Felipe Monteirod5d76b82017-03-20 23:18:50 +000063
64 :raises NotFound: if `service` is invalid or
65 if Tempest credentials cannot be found.
66 :raises Forbidden: for bullet (2) above.
67 :raises RbacOverPermission: for bullet (3) above.
68 """
Felipe Monteiro0854ded2017-05-05 16:30:55 +010069
70 if extra_target_data is None:
71 extra_target_data = {}
72
DavidPurcell029d8c32017-01-06 15:27:41 -050073 def decorator(func):
Felipe Monteiro78fc4892017-04-12 21:33:39 +010074 role = CONF.rbac.rbac_test_role
75
DavidPurcell029d8c32017-01-06 15:27:41 -050076 def wrapper(*args, **kwargs):
Felipe Monteiro78fc4892017-04-12 21:33:39 +010077 if args and isinstance(args[0], test.BaseTestCase):
78 test_obj = args[0]
79 else:
80 raise rbac_exceptions.RbacResourceSetupFailed(
81 '`rbac_rule_validation` decorator can only be applied to '
82 'an instance of `tempest.test.BaseTestCase`.')
raiesmh088590c0c2017-03-14 18:06:52 +053083
Felipe Monteirod5d76b82017-03-20 23:18:50 +000084 if admin_only:
85 LOG.info("As admin_only is True, only admin role should be "
86 "allowed to perform the API. Skipping oslo.policy "
87 "check for policy action {0}.".format(rule))
Felipe Monteiro17e9b492017-05-27 05:45:20 +010088 allowed = test_obj.rbac_utils.is_admin
Felipe Monteirod5d76b82017-03-20 23:18:50 +000089 else:
Felipe Monteiro78fc4892017-04-12 21:33:39 +010090 allowed = _is_authorized(test_obj, service, rule,
91 extra_target_data)
Felipe Monteirod5d76b82017-03-20 23:18:50 +000092
Rick Bartra12998942017-03-17 17:35:45 -040093 expected_exception, irregular_msg = _get_exception_type(
94 expected_error_code)
DavidPurcell029d8c32017-01-06 15:27:41 -050095
96 try:
Felipe Monteiro78fc4892017-04-12 21:33:39 +010097 func(*args, **kwargs)
Rick Bartra503c5572017-03-09 13:49:58 -050098 except rbac_exceptions.RbacInvalidService as e:
Felipe Monteiro48c913d2017-03-15 12:07:48 -040099 msg = ("%s is not a valid service." % service)
100 LOG.error(msg)
101 raise exceptions.NotFound(
Felipe Monteiro78fc4892017-04-12 21:33:39 +0100102 "%s RbacInvalidService was: %s" % (msg, e))
Felipe Monteiro8eda8cc2017-03-22 14:15:14 +0000103 except (expected_exception, rbac_exceptions.RbacActionFailed) as e:
104 if irregular_msg:
105 LOG.warning(irregular_msg.format(rule, service))
DavidPurcell029d8c32017-01-06 15:27:41 -0500106 if allowed:
107 msg = ("Role %s was not allowed to perform %s." %
Felipe Monteiro78fc4892017-04-12 21:33:39 +0100108 (role, rule))
DavidPurcell029d8c32017-01-06 15:27:41 -0500109 LOG.error(msg)
110 raise exceptions.Forbidden(
Felipe Monteiro4bf66a22017-05-07 14:44:21 +0100111 "%s Exception was: %s" % (msg, e))
Felipe Monteiro8eda8cc2017-03-22 14:15:14 +0000112 except Exception as e:
113 exc_info = sys.exc_info()
114 error_details = exc_info[1].__str__()
115 msg = ("%s An unexpected exception has occurred: Expected "
116 "exception was %s, which was not thrown."
117 % (error_details, expected_exception.__name__))
118 LOG.error(msg)
119 six.reraise(exc_info[0], exc_info[0](msg), exc_info[2])
DavidPurcell029d8c32017-01-06 15:27:41 -0500120 else:
121 if not allowed:
Felipe Monteiro4bf66a22017-05-07 14:44:21 +0100122 LOG.error("Role %s was allowed to perform %s",
Felipe Monteiroe52cbc62017-05-24 17:48:59 +0100123 role, rule)
DavidPurcell029d8c32017-01-06 15:27:41 -0500124 raise rbac_exceptions.RbacOverPermission(
125 "OverPermission: Role %s was allowed to perform %s" %
Felipe Monteiro78fc4892017-04-12 21:33:39 +0100126 (role, rule))
raiesmh088590c0c2017-03-14 18:06:52 +0530127 finally:
Felipe Monteiro78fc4892017-04-12 21:33:39 +0100128 test_obj.rbac_utils.switch_role(test_obj,
129 toggle_rbac_role=False)
130
131 _wrapper = testtools.testcase.attr(role)(wrapper)
132 return _wrapper
DavidPurcell029d8c32017-01-06 15:27:41 -0500133 return decorator
Rick Bartra12998942017-03-17 17:35:45 -0400134
135
Felipe Monteiro78fc4892017-04-12 21:33:39 +0100136def _is_authorized(test_obj, service, rule_name, extra_target_data):
Felipe Monteirodea13842017-07-05 04:11:18 +0100137 """Validates whether current RBAC role has permission to do policy action.
138
139 :param test_obj: type BaseTestCase (tempest base test class)
140 :param service: the OpenStack service that enforces ``rule_name``
141 :param rule_name: the name of the policy action
142 :param extra_target_data: dictionary with unresolved string literals that
143 reference nested BaseTestCase attributes
144 :returns: True if the current RBAC role can perform the policy action else
145 False
146 :raises RbacParsingException: if ``CONF.rbac.strict_policy_check`` is
147 enabled and the ``rule_name`` does not exist in the system
148 :raises skipException: if ``CONF.rbac.strict_policy_check`` is
149 disabled and the ``rule_name`` does not exist in the system
150 """
Felipe Monteiro78fc4892017-04-12 21:33:39 +0100151 try:
152 project_id = test_obj.auth_provider.credentials.project_id
153 user_id = test_obj.auth_provider.credentials.user_id
154 except AttributeError as e:
155 msg = ("{0}: project_id/user_id not found in "
156 "cls.auth_provider.credentials".format(e))
157 LOG.error(msg)
158 raise rbac_exceptions.RbacResourceSetupFailed(msg)
159
160 try:
161 role = CONF.rbac.rbac_test_role
Rick Bartraed950052017-06-29 17:20:33 -0400162 # Test RBAC against custom requirements. Otherwise use oslo.policy
163 if CONF.rbac.test_custom_requirements:
164 authority = requirements_authority.RequirementsAuthority(
165 CONF.rbac.custom_requirements_file, service)
166 else:
167 formatted_target_data = _format_extra_target_data(
168 test_obj, extra_target_data)
169 authority = rbac_policy_parser.RbacPolicyParser(
170 project_id, user_id, service,
171 extra_target_data=formatted_target_data)
172 is_allowed = authority.allowed(rule_name, role)
Felipe Monteiro78fc4892017-04-12 21:33:39 +0100173
174 if is_allowed:
175 LOG.debug("[Action]: %s, [Role]: %s is allowed!", rule_name,
176 role)
177 else:
178 LOG.debug("[Action]: %s, [Role]: %s is NOT allowed!",
179 rule_name, role)
180 return is_allowed
181 except rbac_exceptions.RbacParsingException as e:
182 if CONF.rbac.strict_policy_check:
183 raise e
184 else:
185 raise testtools.TestCase.skipException(str(e))
186 return False
187
188
Felipe Monteiro973a1bc2017-06-14 21:23:54 +0100189def _get_exception_type(expected_error_code=403):
190 """Dynamically calculate the expected exception to be caught.
191
192 Dynamically calculate the expected exception to be caught by the test case.
193 Only `Forbidden` and `NotFound` exceptions are permitted. `NotFound` is
194 supported because Neutron, for security reasons, masks `Forbidden`
195 exceptions as `NotFound` exceptions.
196
197 :param expected_error_code: the integer representation of the expected
198 exception to be caught. Must be contained in `_SUPPORTED_ERROR_CODES`.
199 :returns: tuple of the exception type corresponding to
200 `expected_error_code` and a message explaining that a non-Forbidden
201 exception was expected, if applicable.
202 """
Rick Bartra12998942017-03-17 17:35:45 -0400203 expected_exception = None
204 irregular_msg = None
Felipe Monteiro973a1bc2017-06-14 21:23:54 +0100205
206 if not isinstance(expected_error_code, six.integer_types) \
207 or expected_error_code not in _SUPPORTED_ERROR_CODES:
208 msg = ("Please pass an expected error code. Currently "
209 "supported codes: {0}".format(_SUPPORTED_ERROR_CODES))
210 LOG.error(msg)
211 raise rbac_exceptions.RbacInvalidErrorCode(msg)
Felipe Monteiro78fc4892017-04-12 21:33:39 +0100212
Rick Bartra12998942017-03-17 17:35:45 -0400213 if expected_error_code == 403:
214 expected_exception = exceptions.Forbidden
215 elif expected_error_code == 404:
216 expected_exception = exceptions.NotFound
217 irregular_msg = ("NotFound exception was caught for policy action "
218 "{0}. The service {1} throws a 404 instead of a 403, "
219 "which is irregular.")
Rick Bartra12998942017-03-17 17:35:45 -0400220
221 return expected_exception, irregular_msg
Felipe Monteirofd1db982017-04-13 21:19:41 +0100222
223
224def _format_extra_target_data(test_obj, extra_target_data):
225 """Formats the "extra_target_data" dictionary with correct test data.
226
227 Before being formatted, "extra_target_data" is a dictionary that maps a
228 policy string like "trust.trustor_user_id" to a nested list of BaseTestCase
229 attributes. For example, the attribute list in:
230
231 "trust.trustor_user_id": "os.auth_provider.credentials.user_id"
232
233 is parsed by iteratively calling `getattr` until the value of "user_id"
234 is resolved. The resulting dictionary returns:
235
236 "trust.trustor_user_id": "the user_id of the `primary` credential"
237
238 :param test_obj: type BaseTestCase (tempest base test class)
239 :param extra_target_data: dictionary with unresolved string literals that
Felipe Monteiro973a1bc2017-06-14 21:23:54 +0100240 reference nested BaseTestCase attributes
Felipe Monteirodea13842017-07-05 04:11:18 +0100241 :returns: dictionary containing additional object data needed by
242 oslo.policy to validate generic checks
Felipe Monteirofd1db982017-04-13 21:19:41 +0100243 """
244 attr_value = test_obj
245 formatted_target_data = {}
246
247 for user_attribute, attr_string in extra_target_data.items():
248 attrs = attr_string.split('.')
249 for attr in attrs:
250 attr_value = getattr(attr_value, attr)
251 formatted_target_data[user_attribute] = attr_value
252
253 return formatted_target_data