blob: 268673673cdd7c9108f0710d32cfd54d52f52259 [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 Monteirofd1db982017-04-13 21:19:41 +010043 def __init__(self, project_id, user_id, service=None, path=None,
44 extra_target_data={}):
Felipe Monteiro322c5b62017-02-26 02:44:21 +000045 """Initialization of Rbac Policy Parser.
DavidPurcell029d8c32017-01-06 15:27:41 -050046
Felipe Monteiro9c978502017-01-27 17:07:54 -050047 Parses a policy file to create a dictionary, mapping policy actions to
48 roles. If a policy file does not exist, checks whether the policy file
49 is registered as a namespace under oslo.policy.policies. Nova, for
50 example, doesn't use a policy.json file by default; its policy is
51 implemented in code and registered as 'nova' under
52 oslo.policy.policies.
53
54 If the policy file is not found in either place, raises an exception.
55
56 Additionally, if the policy file exists in both code and as a
57 policy.json (for example, by creating a custom nova policy.json file),
58 the custom policy file over the default policy implementation is
59 prioritized.
Felipe Monteirob0595652017-01-23 16:51:58 -050060
Felipe Monteirofd1db982017-04-13 21:19:41 +010061 :param project_id: type uuid
Felipe Monteiro889264e2017-03-01 17:19:35 -050062 :param user_id: type uuid
DavidPurcell029d8c32017-01-06 15:27:41 -050063 :param service: type string
64 :param path: type string
65 """
Felipe Monteiroae2ebab2017-03-23 22:49:06 +000066
Rick Bartra503c5572017-03-09 13:49:58 -050067 # First check if the service is valid
68 service = service.lower().strip() if service else None
69 self.admin_mgr = credentials.AdminManager()
70 services = self.admin_mgr.identity_services_v3_client.\
71 list_services()['services']
72 service_names = [s['name'] for s in services]
73 if not service or not any(service in name for name in service_names):
74 LOG.debug(str(service) + " is NOT a valid service.")
75 raise rbac_exceptions.RbacInvalidService
76
Felipe Monteiroae2ebab2017-03-23 22:49:06 +000077 # Use default path in /etc/<service_name/policy.json if no path
78 # is provided.
79 self.path = path or os.path.join('/etc', service, 'policy.json')
80 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 Monteirob0595652017-01-23 16:51:58 -050086 def allowed(self, rule_name, role):
Felipe Monteiro9c978502017-01-27 17:07:54 -050087 is_admin_context = self._is_admin_context(role)
Felipe Monteirob0595652017-01-23 16:51:58 -050088 is_allowed = self._allowed(
Felipe Monteiro9c978502017-01-27 17:07:54 -050089 access=self._get_access_token(role),
Felipe Monteirob0595652017-01-23 16:51:58 -050090 apply_rule=rule_name,
Felipe Monteiro9c978502017-01-27 17:07:54 -050091 is_admin=is_admin_context)
Felipe Monteiro9c978502017-01-27 17:07:54 -050092 return is_allowed
DavidPurcell029d8c32017-01-06 15:27:41 -050093
Felipe Monteiroae2ebab2017-03-23 22:49:06 +000094 def _get_policy_data(self, service):
95 file_policy_data = {}
96 mgr_policy_data = {}
97 policy_data = {}
98
99 # Check whether policy file exists.
100 if os.path.isfile(self.path):
101 with open(self.path, 'r') as policy_file:
102 file_policy_data = policy_file.read()
103 try:
104 file_policy_data = json.loads(file_policy_data)
105 except ValueError:
Joseph Abade7df9c42017-04-18 16:38:50 -0400106 file_policy_data = None
Felipe Monteiroae2ebab2017-03-23 22:49:06 +0000107
108 # Check whether policy actions are defined in code. Nova and Keystone,
109 # for example, define their default policy actions in code.
110 mgr = stevedore.named.NamedExtensionManager(
111 'oslo.policy.policies',
112 names=[service],
113 on_load_failure_callback=None,
114 invoke_on_load=True,
115 warn_on_missing_entrypoint=False)
116
117 if mgr:
118 policy_generator = {policy.name: policy.obj for policy in mgr}
119 if policy_generator and service in policy_generator:
120 for rule in policy_generator[service]:
121 mgr_policy_data[rule.name] = str(rule.check)
122
123 # If data from both file and code exist, combine both together.
124 if file_policy_data and mgr_policy_data:
125 # Add the policy actions from code first.
126 for action, rule in mgr_policy_data.items():
127 policy_data[action] = rule
128 # Overwrite with any custom policy actions defined in policy.json.
129 for action, rule in file_policy_data.items():
130 policy_data[action] = rule
131 elif file_policy_data:
132 policy_data = file_policy_data
133 elif mgr_policy_data:
134 policy_data = mgr_policy_data
135 else:
136 error_message = 'Policy file for {0} service neither found in '\
137 'code nor at {1}.'.format(service, self.path)
138 raise rbac_exceptions.RbacParsingException(error_message)
139
140 try:
141 policy_data = json.dumps(policy_data)
142 except ValueError:
143 error_message = 'Policy file for {0} service is invalid.'.format(
144 service)
145 raise rbac_exceptions.RbacParsingException(error_message)
146
147 return policy_data
148
Felipe Monteiro9c978502017-01-27 17:07:54 -0500149 def _is_admin_context(self, role):
150 """Checks whether a role has admin context.
151
152 If context_is_admin is contained in the policy file, then checks
153 whether the given role is contained in context_is_admin. If it is not
154 in the policy file, then default to context_is_admin: admin.
155 """
156 if 'context_is_admin' in self.rules.keys():
157 return self._allowed(
158 access=self._get_access_token(role),
159 apply_rule='context_is_admin')
160 return role == 'admin'
DavidPurcell029d8c32017-01-06 15:27:41 -0500161
Felipe Monteirob0595652017-01-23 16:51:58 -0500162 def _get_access_token(self, role):
163 access_token = {
164 "token": {
165 "roles": [
166 {
167 "name": role
168 }
169 ],
Felipe Monteirofd1db982017-04-13 21:19:41 +0100170 "project_id": self.project_id,
171 "tenant_id": self.project_id,
Felipe Monteiro889264e2017-03-01 17:19:35 -0500172 "user_id": self.user_id
Felipe Monteirob0595652017-01-23 16:51:58 -0500173 }
174 }
175 return access_token
DavidPurcell029d8c32017-01-06 15:27:41 -0500176
Felipe Monteiro9c978502017-01-27 17:07:54 -0500177 def _allowed(self, access, apply_rule, is_admin=False):
Felipe Monteirob0595652017-01-23 16:51:58 -0500178 """Checks if a given rule in a policy is allowed with given access.
DavidPurcell029d8c32017-01-06 15:27:41 -0500179
Felipe Monteirob0595652017-01-23 16:51:58 -0500180 Adapted from oslo_policy.shell.
DavidPurcell029d8c32017-01-06 15:27:41 -0500181
Felipe Monteirob0595652017-01-23 16:51:58 -0500182 :param access: type dict: dictionary from ``_get_access_token``
183 :param apply_rule: type string: rule to be checked
184 :param is_admin: type bool: whether admin context is used
DavidPurcell029d8c32017-01-06 15:27:41 -0500185 """
Felipe Monteirob0595652017-01-23 16:51:58 -0500186 access_data = copy.copy(access['token'])
187 access_data['roles'] = [role['name'] for role in access_data['roles']]
Felipe Monteirob0595652017-01-23 16:51:58 -0500188 access_data['is_admin'] = is_admin
Felipe Monteiro9c978502017-01-27 17:07:54 -0500189 # TODO(felipemonteiro): Dynamically calculate is_admin_project rather
190 # than hard-coding it to True. is_admin_project cannot be determined
191 # from the role, but rather from project and domain names. See
192 # _populate_is_admin_project in keystone.token.providers.common
193 # for more information.
194 access_data['is_admin_project'] = True
DavidPurcell029d8c32017-01-06 15:27:41 -0500195
Felipe Monteirob0595652017-01-23 16:51:58 -0500196 class Object(object):
197 pass
198 o = Object()
Felipe Monteiro9c978502017-01-27 17:07:54 -0500199 o.rules = self.rules
DavidPurcell029d8c32017-01-06 15:27:41 -0500200
Felipe Monteiro9fc782e2017-02-01 15:38:46 -0500201 target = {"project_id": access_data['project_id'],
202 "tenant_id": access_data['project_id'],
Felipe Monteiro889264e2017-03-01 17:19:35 -0500203 "network:tenant_id": access_data['project_id'],
204 "user_id": access_data['user_id']}
Felipe Monteirofd1db982017-04-13 21:19:41 +0100205 if self.extra_target_data:
206 target.update(self.extra_target_data)
Felipe Monteirob0595652017-01-23 16:51:58 -0500207
Felipe Monteiro9c978502017-01-27 17:07:54 -0500208 result = self._try_rule(apply_rule, target, access_data, o)
Felipe Monteirob0595652017-01-23 16:51:58 -0500209 return result
210
Felipe Monteiro9c978502017-01-27 17:07:54 -0500211 def _try_rule(self, apply_rule, target, access_data, o):
Samantha Blanco0d880082017-03-23 18:14:37 -0400212 if apply_rule not in self.rules:
Felipe Monteiro48c913d2017-03-15 12:07:48 -0400213 message = "Policy action: {0} not found in policy file: {1}."\
214 .format(apply_rule, self.path)
215 LOG.debug(message)
216 raise rbac_exceptions.RbacParsingException(message)
Samantha Blanco0d880082017-03-23 18:14:37 -0400217 else:
218 rule = self.rules[apply_rule]
219 return rule(target, access_data, o)