blob: f61ccdfec208f3ec5bfbe6ebcd469ea969330141 [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 Monteirofa01d5f2017-04-01 06:18:25 +010016import sys
17import testtools
DavidPurcell029d8c32017-01-06 15:27:41 -050018import time
Felipe Monteiro34a138c2017-03-02 17:01:37 -050019
Rajiv Kumar645dfc92017-01-19 13:48:27 +053020from oslo_log import log as logging
Felipe Monteirofa01d5f2017-04-01 06:18:25 +010021import oslo_utils.uuidutils as uuid_utils
22import six
23
24from tempest import config
DavidPurcell029d8c32017-01-06 15:27:41 -050025
Felipe Monteiro34a138c2017-03-02 17:01:37 -050026from patrole_tempest_plugin import rbac_exceptions
DavidPurcell029d8c32017-01-06 15:27:41 -050027
DavidPurcell029d8c32017-01-06 15:27:41 -050028CONF = config.CONF
Felipe Monteiro34a138c2017-03-02 17:01:37 -050029LOG = logging.getLogger(__name__)
DavidPurcell029d8c32017-01-06 15:27:41 -050030
31
32class Singleton(type):
33 _instances = {}
34
35 def __call__(cls, *args, **kwargs):
36 if cls not in cls._instances:
37 cls._instances[cls] = super(Singleton, cls).__call__(*args,
38 **kwargs)
39 return cls._instances[cls]
40
41
42@six.add_metaclass(Singleton)
43class RbacUtils(object):
DavidPurcell029d8c32017-01-06 15:27:41 -050044
Felipe Monteirofa01d5f2017-04-01 06:18:25 +010045 # References the last value of `switch_to_rbac_role` that was passed to
46 # `switch_role`. Used for ensuring that `switch_role` is correctly used
47 # in a test file, so that false positives are prevented. The key used
48 # to index into the dictionary is the class name, which is unique.
49 switch_role_history = {}
50 admin_role_id = None
51 rbac_role_id = None
DavidPurcell029d8c32017-01-06 15:27:41 -050052
Felipe Monteirofa01d5f2017-04-01 06:18:25 +010053 def switch_role(self, test_obj, switchToRbacRole=False):
54 self.user_id = test_obj.auth_provider.credentials.user_id
55 self.project_id = test_obj.auth_provider.credentials.tenant_id
56 self.token = test_obj.auth_provider.get_token()
57 self.identity_version = test_obj.get_identity_version()
DavidPurcell029d8c32017-01-06 15:27:41 -050058
Felipe Monteirofa01d5f2017-04-01 06:18:25 +010059 if self.identity_version.endswith('v3'):
60 self.roles_client = test_obj.os_admin.roles_v3_client
61 else:
62 self.roles_client = test_obj.os_admin.roles_client
63
DavidPurcell029d8c32017-01-06 15:27:41 -050064 LOG.debug('Switching role to: %s', switchToRbacRole)
DavidPurcell029d8c32017-01-06 15:27:41 -050065
66 try:
Felipe Monteirofa01d5f2017-04-01 06:18:25 +010067 if not self.admin_role_id or not self.rbac_role_id:
68 self._get_roles()
DavidPurcell029d8c32017-01-06 15:27:41 -050069
Felipe Monteirofa01d5f2017-04-01 06:18:25 +010070 rbac_utils._validate_switch_role(self, test_obj, switchToRbacRole)
DavidPurcell029d8c32017-01-06 15:27:41 -050071
72 if switchToRbacRole:
Felipe Monteirofa01d5f2017-04-01 06:18:25 +010073 self._add_role_to_user(self.rbac_role_id)
DavidPurcell029d8c32017-01-06 15:27:41 -050074 else:
Felipe Monteirofa01d5f2017-04-01 06:18:25 +010075 self._add_role_to_user(self.admin_role_id)
DavidPurcell029d8c32017-01-06 15:27:41 -050076 except Exception as exp:
77 LOG.error(exp)
78 raise
Felipe Monteiro34a138c2017-03-02 17:01:37 -050079 finally:
Felipe Monteiro23923f02017-03-17 02:15:07 +000080 # NOTE(felipemonteiro): These two comments below are copied from
81 # tempest.api.identity.v2/v3.test_users.
82 #
83 # Reset auth again to verify the password restore does work.
84 # Clear auth restores the original credentials and deletes
85 # cached auth data.
86 test_obj.auth_provider.clear_auth()
87 # Fernet tokens are not subsecond aware and Keystone should only be
88 # precise to the second. Sleep to ensure we are passing the second
Rick Bartra89f498f2017-03-20 15:54:45 -040089 # boundary before attempting to authenticate. If token is of type
90 # uuid, then do not sleep.
Felipe Monteirofa01d5f2017-04-01 06:18:25 +010091 if not uuid_utils.is_uuid_like(self.token):
Rick Bartra89f498f2017-03-20 15:54:45 -040092 time.sleep(1)
Felipe Monteiro23923f02017-03-17 02:15:07 +000093 test_obj.auth_provider.set_auth()
Felipe Monteiro34a138c2017-03-02 17:01:37 -050094
Felipe Monteirofa01d5f2017-04-01 06:18:25 +010095 def _add_role_to_user(self, role_id):
96 role_already_present = self._clear_user_roles(role_id)
97 if role_already_present:
98 return
99
100 self.roles_client.create_user_role_on_project(
101 self.project_id, self.user_id, role_id)
102
103 def _clear_user_roles(self, role_id):
104 roles = self.roles_client.list_user_roles_on_project(
105 self.project_id, self.user_id)['roles']
106
107 # If the user already has the role that is required, return early.
108 role_ids = [role['id'] for role in roles]
109 if role_ids == [role_id]:
110 return True
Felipe Monteirob3b7bc82017-03-03 15:58:15 -0500111
112 for role in roles:
Felipe Monteirofa01d5f2017-04-01 06:18:25 +0100113 self.roles_client.delete_role_from_user_on_project(
114 self.project_id, self.user_id, role['id'])
115
116 return False
117
118 def _validate_switch_role(self, test_obj, switchToRbacRole):
119 """Validates that the rbac role passed to `switch_role` is legal.
120
121 Throws an error for the following improper usages of `switch_role`:
122 * `switch_role` is not called with a boolean value
123 * `switch_role` is never called in a test file, except in tearDown
124 * `switch_role` is called with the same boolean value twice
125 """
126 if not isinstance(switchToRbacRole, bool):
127 raise rbac_exceptions.RbacResourceSetupFailed(
128 'switchToRbacRole must be a boolean value.')
129
130 key = test_obj.__name__ if isinstance(test_obj, type) else \
131 test_obj.__class__.__name__
132 self.switch_role_history.setdefault(key, None)
133
134 if self.switch_role_history[key] == switchToRbacRole:
135 # If the test was skipped, then this is a legitimate use case,
136 # so do not throw an exception.
137 exc_value = sys.exc_info()[1]
138 if not isinstance(exc_value, testtools.TestCase.skipException):
139 self.switch_role_history[key] = False
140 error_message = '`switchToRbacRole` must not be called with '\
141 'the same bool value twice. Make sure that you included '\
142 'a rbac_utils.switch_role method call inside the test.'
143 LOG.error(error_message)
144 raise rbac_exceptions.RbacResourceSetupFailed(error_message)
145 else:
146 self.switch_role_history[key] = switchToRbacRole
147
148 def _get_roles(self):
149 available_roles = self.roles_client.list_roles()
150 admin_role_id = rbac_role_id = None
151
152 for role in available_roles['roles']:
153 if role['name'] == CONF.rbac.rbac_test_role:
154 rbac_role_id = role['id']
155 if role['name'] == 'admin':
156 admin_role_id = role['id']
157
158 if not admin_role_id or not rbac_role_id:
159 msg = "Role with name 'admin' does not exist in the system."\
160 if not admin_role_id else "Role defined by rbac_test_role "\
161 "does not exist in the system."
162 raise rbac_exceptions.RbacResourceSetupFailed(msg)
163
164 self.admin_role_id = admin_role_id
165 self.rbac_role_id = rbac_role_id
Felipe Monteirob3b7bc82017-03-03 15:58:15 -0500166
Felipe Monteiro34a138c2017-03-02 17:01:37 -0500167rbac_utils = RbacUtils