blob: bb34f6c20dc35a606828a0acc29515bf22ccc946 [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 copy
Felipe Monteiroae2ebab2017-03-23 22:49:06 +000017import json
DavidPurcell029d8c32017-01-06 15:27:41 -050018import os
19
Felipe Monteiroae2ebab2017-03-23 22:49:06 +000020from oslo_config import cfg
DavidPurcell029d8c32017-01-06 15:27:41 -050021from oslo_log import log as logging
DavidPurcell029d8c32017-01-06 15:27:41 -050022from oslo_policy import policy
Felipe Monteiroae2ebab2017-03-23 22:49:06 +000023import stevedore
DavidPurcell029d8c32017-01-06 15:27:41 -050024
Rick Bartra503c5572017-03-09 13:49:58 -050025from tempest.common import credentials_factory as credentials
26
Felipe Monteirob0595652017-01-23 16:51:58 -050027from patrole_tempest_plugin import rbac_exceptions
DavidPurcell029d8c32017-01-06 15:27:41 -050028
Felipe Monteiroae2ebab2017-03-23 22:49:06 +000029CONF = cfg.CONF
DavidPurcell029d8c32017-01-06 15:27:41 -050030LOG = logging.getLogger(__name__)
31
DavidPurcell029d8c32017-01-06 15:27:41 -050032
Felipe Monteiro322c5b62017-02-26 02:44:21 +000033class RbacPolicyParser(object):
DavidPurcell029d8c32017-01-06 15:27:41 -050034 """A class for parsing policy rules into lists of allowed roles.
35
36 RBAC testing requires that each rule in a policy file be broken up into
37 the roles that constitute it. This class automates that process.
Felipe Monteirob0595652017-01-23 16:51:58 -050038
39 The list of roles per rule can be reverse-engineered by checking, for
40 each role, whether a given rule is allowed using oslo policy.
DavidPurcell029d8c32017-01-06 15:27:41 -050041 """
42
Felipe Monteiro0854ded2017-05-05 16:30:55 +010043 def __init__(self, project_id, user_id, service, extra_target_data=None):
Felipe Monteiro322c5b62017-02-26 02:44:21 +000044 """Initialization of Rbac Policy Parser.
DavidPurcell029d8c32017-01-06 15:27:41 -050045
Felipe Monteiro9c978502017-01-27 17:07:54 -050046 Parses a policy file to create a dictionary, mapping policy actions to
47 roles. If a policy file does not exist, checks whether the policy file
48 is registered as a namespace under oslo.policy.policies. Nova, for
49 example, doesn't use a policy.json file by default; its policy is
50 implemented in code and registered as 'nova' under
51 oslo.policy.policies.
52
53 If the policy file is not found in either place, raises an exception.
54
55 Additionally, if the policy file exists in both code and as a
56 policy.json (for example, by creating a custom nova policy.json file),
57 the custom policy file over the default policy implementation is
58 prioritized.
Felipe Monteirob0595652017-01-23 16:51:58 -050059
Felipe Monteirofd1db982017-04-13 21:19:41 +010060 :param project_id: type uuid
Felipe Monteiro889264e2017-03-01 17:19:35 -050061 :param user_id: type uuid
DavidPurcell029d8c32017-01-06 15:27:41 -050062 :param service: type string
63 :param path: type string
64 """
Felipe Monteiroae2ebab2017-03-23 22:49:06 +000065
Felipe Monteiro0854ded2017-05-05 16:30:55 +010066 if extra_target_data is None:
67 extra_target_data = {}
68
Felipe Monteirod9607c42017-06-12 19:28:45 +010069 # First check if the service is valid.
70 self.validate_service(service)
Rick Bartra503c5572017-03-09 13:49:58 -050071
Felipe Monteiroae2ebab2017-03-23 22:49:06 +000072 # Use default path in /etc/<service_name/policy.json if no path
73 # is provided.
Samantha Blanco85f79d72017-04-21 11:09:14 -040074 path = getattr(CONF.rbac, '%s_policy_file' % str(service), None)
75 if not path:
76 LOG.info("No config option found for %s,"
Felipe Monteiro4bf66a22017-05-07 14:44:21 +010077 " using default path", str(service))
Samantha Blanco85f79d72017-04-21 11:09:14 -040078 path = os.path.join('/etc', service, 'policy.json')
79 self.path = path
Felipe Monteiroae2ebab2017-03-23 22:49:06 +000080 self.rules = policy.Rules.load(self._get_policy_data(service),
81 'default')
Felipe Monteirofd1db982017-04-13 21:19:41 +010082 self.project_id = project_id
Felipe Monteiro889264e2017-03-01 17:19:35 -050083 self.user_id = user_id
Felipe Monteirofd1db982017-04-13 21:19:41 +010084 self.extra_target_data = extra_target_data
DavidPurcell029d8c32017-01-06 15:27:41 -050085
Felipe Monteirod9607c42017-06-12 19:28:45 +010086 @classmethod
87 def validate_service(cls, service):
88 """Validate whether the service passed to ``init`` exists."""
89 service = service.lower().strip() if service else None
90
91 # Cache the list of available services in memory to avoid needlessly
92 # doing an API call every time.
93 if not hasattr(cls, 'available_services'):
94 admin_mgr = credentials.AdminManager()
95 services = admin_mgr.identity_services_v3_client.\
96 list_services()['services']
97 cls.available_services = [s['name'] for s in services]
98
99 if not service or service not in cls.available_services:
100 LOG.debug("%s is NOT a valid service.", service)
101 raise rbac_exceptions.RbacInvalidService(
102 "%s is NOT a valid service." % service)
103
Felipe Monteirob0595652017-01-23 16:51:58 -0500104 def allowed(self, rule_name, role):
Felipe Monteiro9c978502017-01-27 17:07:54 -0500105 is_admin_context = self._is_admin_context(role)
Felipe Monteirob0595652017-01-23 16:51:58 -0500106 is_allowed = self._allowed(
Felipe Monteiro9c978502017-01-27 17:07:54 -0500107 access=self._get_access_token(role),
Felipe Monteirob0595652017-01-23 16:51:58 -0500108 apply_rule=rule_name,
Felipe Monteiro9c978502017-01-27 17:07:54 -0500109 is_admin=is_admin_context)
Felipe Monteiro9c978502017-01-27 17:07:54 -0500110 return is_allowed
DavidPurcell029d8c32017-01-06 15:27:41 -0500111
Felipe Monteiroae2ebab2017-03-23 22:49:06 +0000112 def _get_policy_data(self, service):
113 file_policy_data = {}
114 mgr_policy_data = {}
115 policy_data = {}
116
117 # Check whether policy file exists.
118 if os.path.isfile(self.path):
Felipe Monteiroae2ebab2017-03-23 22:49:06 +0000119 try:
Samantha Blanco85f79d72017-04-21 11:09:14 -0400120 with open(self.path, 'r') as policy_file:
121 file_policy_data = policy_file.read()
Felipe Monteiroae2ebab2017-03-23 22:49:06 +0000122 file_policy_data = json.loads(file_policy_data)
Samantha Blanco85f79d72017-04-21 11:09:14 -0400123 except (IOError, ValueError) as e:
124 msg = "Failed to read policy file for service. "
125 if isinstance(e, IOError):
126 msg += "Please check that policy path exists."
127 else:
128 msg += "JSON may be improperly formatted."
129 LOG.debug(msg)
130 file_policy_data = {}
Felipe Monteiroae2ebab2017-03-23 22:49:06 +0000131
132 # Check whether policy actions are defined in code. Nova and Keystone,
133 # for example, define their default policy actions in code.
134 mgr = stevedore.named.NamedExtensionManager(
135 'oslo.policy.policies',
136 names=[service],
137 on_load_failure_callback=None,
138 invoke_on_load=True,
139 warn_on_missing_entrypoint=False)
140
141 if mgr:
142 policy_generator = {policy.name: policy.obj for policy in mgr}
143 if policy_generator and service in policy_generator:
144 for rule in policy_generator[service]:
145 mgr_policy_data[rule.name] = str(rule.check)
146
147 # If data from both file and code exist, combine both together.
148 if file_policy_data and mgr_policy_data:
149 # Add the policy actions from code first.
150 for action, rule in mgr_policy_data.items():
151 policy_data[action] = rule
152 # Overwrite with any custom policy actions defined in policy.json.
153 for action, rule in file_policy_data.items():
154 policy_data[action] = rule
155 elif file_policy_data:
156 policy_data = file_policy_data
157 elif mgr_policy_data:
158 policy_data = mgr_policy_data
159 else:
160 error_message = 'Policy file for {0} service neither found in '\
161 'code nor at {1}.'.format(service, self.path)
162 raise rbac_exceptions.RbacParsingException(error_message)
163
164 try:
165 policy_data = json.dumps(policy_data)
166 except ValueError:
167 error_message = 'Policy file for {0} service is invalid.'.format(
168 service)
169 raise rbac_exceptions.RbacParsingException(error_message)
170
171 return policy_data
172
Felipe Monteiro9c978502017-01-27 17:07:54 -0500173 def _is_admin_context(self, role):
174 """Checks whether a role has admin context.
175
176 If context_is_admin is contained in the policy file, then checks
177 whether the given role is contained in context_is_admin. If it is not
178 in the policy file, then default to context_is_admin: admin.
179 """
180 if 'context_is_admin' in self.rules.keys():
181 return self._allowed(
182 access=self._get_access_token(role),
183 apply_rule='context_is_admin')
Felipe Monteirof6b69e22017-05-04 21:55:04 +0100184 return role == CONF.identity.admin_role
DavidPurcell029d8c32017-01-06 15:27:41 -0500185
Felipe Monteirob0595652017-01-23 16:51:58 -0500186 def _get_access_token(self, role):
187 access_token = {
188 "token": {
189 "roles": [
190 {
191 "name": role
192 }
193 ],
Felipe Monteirofd1db982017-04-13 21:19:41 +0100194 "project_id": self.project_id,
195 "tenant_id": self.project_id,
Felipe Monteiro889264e2017-03-01 17:19:35 -0500196 "user_id": self.user_id
Felipe Monteirob0595652017-01-23 16:51:58 -0500197 }
198 }
199 return access_token
DavidPurcell029d8c32017-01-06 15:27:41 -0500200
Felipe Monteiro9c978502017-01-27 17:07:54 -0500201 def _allowed(self, access, apply_rule, is_admin=False):
Felipe Monteirob0595652017-01-23 16:51:58 -0500202 """Checks if a given rule in a policy is allowed with given access.
DavidPurcell029d8c32017-01-06 15:27:41 -0500203
Felipe Monteirob0595652017-01-23 16:51:58 -0500204 Adapted from oslo_policy.shell.
DavidPurcell029d8c32017-01-06 15:27:41 -0500205
Felipe Monteirob0595652017-01-23 16:51:58 -0500206 :param access: type dict: dictionary from ``_get_access_token``
207 :param apply_rule: type string: rule to be checked
208 :param is_admin: type bool: whether admin context is used
DavidPurcell029d8c32017-01-06 15:27:41 -0500209 """
Felipe Monteirob0595652017-01-23 16:51:58 -0500210 access_data = copy.copy(access['token'])
211 access_data['roles'] = [role['name'] for role in access_data['roles']]
Felipe Monteirob0595652017-01-23 16:51:58 -0500212 access_data['is_admin'] = is_admin
Felipe Monteiro9c978502017-01-27 17:07:54 -0500213 # TODO(felipemonteiro): Dynamically calculate is_admin_project rather
214 # than hard-coding it to True. is_admin_project cannot be determined
215 # from the role, but rather from project and domain names. See
216 # _populate_is_admin_project in keystone.token.providers.common
217 # for more information.
218 access_data['is_admin_project'] = True
DavidPurcell029d8c32017-01-06 15:27:41 -0500219
Felipe Monteirob0595652017-01-23 16:51:58 -0500220 class Object(object):
221 pass
222 o = Object()
Felipe Monteiro9c978502017-01-27 17:07:54 -0500223 o.rules = self.rules
DavidPurcell029d8c32017-01-06 15:27:41 -0500224
Felipe Monteiro9fc782e2017-02-01 15:38:46 -0500225 target = {"project_id": access_data['project_id'],
226 "tenant_id": access_data['project_id'],
Felipe Monteiro889264e2017-03-01 17:19:35 -0500227 "network:tenant_id": access_data['project_id'],
228 "user_id": access_data['user_id']}
Felipe Monteirofd1db982017-04-13 21:19:41 +0100229 if self.extra_target_data:
230 target.update(self.extra_target_data)
Felipe Monteirob0595652017-01-23 16:51:58 -0500231
Felipe Monteiro9c978502017-01-27 17:07:54 -0500232 result = self._try_rule(apply_rule, target, access_data, o)
Felipe Monteirob0595652017-01-23 16:51:58 -0500233 return result
234
Felipe Monteiro9c978502017-01-27 17:07:54 -0500235 def _try_rule(self, apply_rule, target, access_data, o):
Samantha Blanco0d880082017-03-23 18:14:37 -0400236 if apply_rule not in self.rules:
Felipe Monteiro48c913d2017-03-15 12:07:48 -0400237 message = "Policy action: {0} not found in policy file: {1}."\
238 .format(apply_rule, self.path)
239 LOG.debug(message)
240 raise rbac_exceptions.RbacParsingException(message)
Samantha Blanco0d880082017-03-23 18:14:37 -0400241 else:
242 rule = self.rules[apply_rule]
243 return rule(target, access_data, o)