def setUp(self): super(PolicyTypeControllerRBACTestCase, self).setUp() self.models = self.fixtures_loader.save_fixtures_to_db(fixtures_pack=FIXTURES_PACK, fixtures_dict=TEST_FIXTURES) file_name = 'fake_policy_type_1.yaml' PolicyTypeControllerRBACTestCase.POLICY_TYPE_1 = self.fixtures_loader.load_fixtures( fixtures_pack=FIXTURES_PACK, fixtures_dict={'policytypes': [file_name]})['policytypes'][file_name] file_name = 'fake_policy_type_2.yaml' PolicyTypeControllerRBACTestCase.POLICY_TYPE_2 = self.fixtures_loader.load_fixtures( fixtures_pack=FIXTURES_PACK, fixtures_dict={'policytypes': [file_name]})['policytypes'][file_name] # Insert mock users, roles and assignments # Users user_1_db = UserDB(name='policy_type_list') user_1_db = User.add_or_update(user_1_db) self.users['policy_type_list'] = user_1_db user_2_db = UserDB(name='policy_type_view') user_2_db = User.add_or_update(user_2_db) self.users['policy_type_view'] = user_2_db # Roles # policy_type_list grant_db = PermissionGrantDB(resource_uid=None, resource_type=ResourceType.POLICY_TYPE, permission_types=[PermissionType.POLICY_TYPE_LIST]) grant_db = PermissionGrant.add_or_update(grant_db) permission_grants = [str(grant_db.id)] role_1_db = RoleDB(name='policy_type_list', permission_grants=permission_grants) role_1_db = Role.add_or_update(role_1_db) self.roles['policy_type_list'] = role_1_db # policy_type_view on timer 1 policy_type_uid = self.models['policytypes']['fake_policy_type_1.yaml'].get_uid() grant_db = PermissionGrantDB(resource_uid=policy_type_uid, resource_type=ResourceType.POLICY_TYPE, permission_types=[PermissionType.POLICY_TYPE_VIEW]) grant_db = PermissionGrant.add_or_update(grant_db) permission_grants = [str(grant_db.id)] role_1_db = RoleDB(name='policy_type_view', permission_grants=permission_grants) role_1_db = Role.add_or_update(role_1_db) self.roles['policy_type_view'] = role_1_db # Role assignments role_assignment_db = UserRoleAssignmentDB( user=self.users['policy_type_list'].name, role=self.roles['policy_type_list'].name, source='assignments/%s.yaml' % self.users['policy_type_list'].name) UserRoleAssignment.add_or_update(role_assignment_db) role_assignment_db = UserRoleAssignmentDB( user=self.users['policy_type_view'].name, role=self.roles['policy_type_view'].name, source='assignments/%s.yaml' % self.users['policy_type_view'].name) UserRoleAssignment.add_or_update(role_assignment_db)
def setUp(self): super(APIControllerWithRBACTestCase, self).setUp() self.users = {} self.roles = {} # Run RBAC migrations run_all_rbac_migrations() # Insert mock users with default role assignments role_names = [SystemRole.SYSTEM_ADMIN, SystemRole.ADMIN, SystemRole.OBSERVER] for role_name in role_names: user_db = UserDB(name=role_name) user_db = User.add_or_update(user_db) self.users[role_name] = user_db role_assignment_db = UserRoleAssignmentDB( user=user_db.name, role=role_name) UserRoleAssignment.add_or_update(role_assignment_db) # Insert a user with no permissions and role assignments user_1_db = UserDB(name='no_permissions') user_1_db = User.add_or_update(user_1_db) self.users['no_permissions'] = user_1_db
def setUp(self): super(KeyValuesControllerRBACTestCase, self).setUp() self.kvps = {} # Insert mock users user_1_db = UserDB(name='user1') user_1_db = User.add_or_update(user_1_db) self.users['user_1'] = user_1_db user_2_db = UserDB(name='user2') user_2_db = User.add_or_update(user_2_db) self.users['user_2'] = user_2_db # Insert mock kvp objects kvp_api = KeyValuePairSetAPI(name='test_system_scope', value='value1', scope=FULL_SYSTEM_SCOPE) kvp_db = KeyValuePairSetAPI.to_model(kvp_api) kvp_db = KeyValuePair.add_or_update(kvp_db) kvp_db = KeyValuePairAPI.from_model(kvp_db) self.kvps['kvp_1'] = kvp_db kvp_api = KeyValuePairSetAPI(name='test_system_scope_secret', value='value_secret', scope=FULL_SYSTEM_SCOPE, secret=True) kvp_db = KeyValuePairSetAPI.to_model(kvp_api) kvp_db = KeyValuePair.add_or_update(kvp_db) kvp_db = KeyValuePairAPI.from_model(kvp_db) self.kvps['kvp_2'] = kvp_db name = get_key_reference(scope=FULL_USER_SCOPE, name='test_user_scope_1', user='******') kvp_db = KeyValuePairDB(name=name, value='valueu12', scope=FULL_USER_SCOPE) kvp_db = KeyValuePair.add_or_update(kvp_db) kvp_db = KeyValuePairAPI.from_model(kvp_db) self.kvps['kvp_3'] = kvp_db name = get_key_reference(scope=FULL_USER_SCOPE, name='test_user_scope_2', user='******') kvp_api = KeyValuePairSetAPI(name=name, value='user_secret', scope=FULL_USER_SCOPE, secret=True) kvp_db = KeyValuePairSetAPI.to_model(kvp_api) kvp_db = KeyValuePair.add_or_update(kvp_db) kvp_db = KeyValuePairAPI.from_model(kvp_db) self.kvps['kvp_4'] = kvp_db name = get_key_reference(scope=FULL_USER_SCOPE, name='test_user_scope_3', user='******') kvp_db = KeyValuePairDB(name=name, value='valueu21', scope=FULL_USER_SCOPE) kvp_db = KeyValuePair.add_or_update(kvp_db) kvp_db = KeyValuePairAPI.from_model(kvp_db) self.kvps['kvp_5'] = kvp_db self.system_scoped_items_count = 2 self.user_scoped_items_count = 3 self.user_scoped_items_per_user_count = { 'user1': 2, 'user2': 1 }
def _get_username_for_request(self, username, request): impersonate_user = getattr(request, 'user', None) if impersonate_user is not None: # check this is a service account try: if not User.get_by_name(username).is_service: message = "Current user is not a service and cannot " \ "request impersonated tokens" abort_request(status_code=http_client.BAD_REQUEST, message=message) return username = impersonate_user except (UserNotFoundError, StackStormDBObjectNotFoundError): message = "Could not locate user %s" % \ (impersonate_user) abort_request(status_code=http_client.BAD_REQUEST, message=message) return else: impersonate_user = getattr(request, 'impersonate_user', None) nickname_origin = getattr(request, 'nickname_origin', None) if impersonate_user is not None: try: # check this is a service account if not User.get_by_name(username).is_service: raise NotServiceUserError() username = User.get_by_nickname(impersonate_user, nickname_origin).name except NotServiceUserError: message = "Current user is not a service and cannot " \ "request impersonated tokens" abort_request(status_code=http_client.BAD_REQUEST, message=message) return except (UserNotFoundError, StackStormDBObjectNotFoundError): message = "Could not locate user %s@%s" % \ (impersonate_user, nickname_origin) abort_request(status_code=http_client.BAD_REQUEST, message=message) return except NoNicknameOriginProvidedError: message = "Nickname origin is not provided for nickname '%s'" % \ impersonate_user abort_request(status_code=http_client.BAD_REQUEST, message=message) return except AmbiguousUserError: message = "%s@%s matched more than one username" % \ (impersonate_user, nickname_origin) abort_request(status_code=http_client.BAD_REQUEST, message=message) return return username
def setUp(self): super(RunnerPermissionsResolverTestCase, self).setUp() # Create some mock users user_1_db = UserDB(name='custom_role_runner_view_grant') user_1_db = User.add_or_update(user_1_db) self.users['custom_role_runner_view_grant'] = user_1_db user_2_db = UserDB(name='custom_role_runner_modify_grant') user_2_db = User.add_or_update(user_2_db) self.users['custom_role_runner_modify_grant'] = user_2_db # Create some mock resources on which permissions can be granted runner_1_db = RunnerTypeDB(name='runner_1') self.resources['runner_1'] = runner_1_db runner_2_db = RunnerTypeDB(name='runner_2') self.resources['runner_2'] = runner_2_db # Create some mock roles with associated permission grants # Custom role - "runner_view" grant on runner_1 grant_db = PermissionGrantDB(resource_uid=self.resources['runner_1'].get_uid(), resource_type=ResourceType.RUNNER, permission_types=[PermissionType.RUNNER_VIEW]) grant_db = PermissionGrant.add_or_update(grant_db) permission_grants = [str(grant_db.id)] role_db = RoleDB(name='custom_role_runner_view_grant', permission_grants=permission_grants) role_db = Role.add_or_update(role_db) self.roles['custom_role_runner_view_grant'] = role_db # Custom role - "runner_modify" grant on runner_2 grant_db = PermissionGrantDB(resource_uid=self.resources['runner_2'].get_uid(), resource_type=ResourceType.RUNNER, permission_types=[PermissionType.RUNNER_MODIFY]) grant_db = PermissionGrant.add_or_update(grant_db) permission_grants = [str(grant_db.id)] role_db = RoleDB(name='custom_role_runner_modify_grant', permission_grants=permission_grants) role_db = Role.add_or_update(role_db) self.roles['custom_role_runner_modify_grant'] = role_db # Create some mock role assignments user_db = self.users['custom_role_runner_view_grant'] role_assignment_db = UserRoleAssignmentDB( user=user_db.name, role=self.roles['custom_role_runner_view_grant'].name) UserRoleAssignment.add_or_update(role_assignment_db) user_db = self.users['custom_role_runner_modify_grant'] role_assignment_db = UserRoleAssignmentDB( user=user_db.name, role=self.roles['custom_role_runner_modify_grant'].name) UserRoleAssignment.add_or_update(role_assignment_db)
def create_token(username, ttl=None, metadata=None, add_missing_user=True, service=False): """ :param username: Username of the user to create the token for. If the account for this user doesn't exist yet it will be created. :type username: ``str`` :param ttl: Token TTL (in seconds). :type ttl: ``int`` :param metadata: Optional metadata to associate with the token. :type metadata: ``dict`` :param add_missing_user: Add the user given by `username` if they don't exist :type add_missing_user: ``bool`` :param service: True if this is a service (non-user) token. :type service: ``bool`` """ if ttl: # Note: We allow arbitrary large TTLs for service tokens. if not service and ttl > cfg.CONF.auth.token_ttl: msg = ('TTL specified %s is greater than max allowed %s.' % (ttl, cfg.CONF.auth.token_ttl)) raise TTLTooLargeException(msg) else: ttl = cfg.CONF.auth.token_ttl if username: try: User.get_by_name(username) except: if add_missing_user: user_db = UserDB(name=username) User.add_or_update(user_db) extra = {'username': username, 'user': user_db} LOG.audit('Registered new user "%s".' % (username), extra=extra) else: raise UserNotFoundError() token = uuid.uuid4().hex expiry = date_utils.get_datetime_utc_now() + datetime.timedelta(seconds=ttl) token = TokenDB(user=username, token=token, expiry=expiry, metadata=metadata, service=service) Token.add_or_update(token) username_string = username if username else 'an anonymous user' token_expire_string = isotime.format(expiry, offset=False) extra = {'username': username, 'token_expiration': token_expire_string} LOG.audit('Access granted to "%s" with the token set to expire at "%s".' % (username_string, token_expire_string), extra=extra) return token
def setUp(self): super(KeyValuesControllerRBACTestCase, self).setUp() self.kvps = {} # Insert mock users user_1_db = UserDB(name="user1") user_1_db = User.add_or_update(user_1_db) self.users["user_1"] = user_1_db user_2_db = UserDB(name="user2") user_2_db = User.add_or_update(user_2_db) self.users["user_2"] = user_2_db # Insert mock kvp objects kvp_api = KeyValuePairSetAPI(name="test_system_scope", value="value1", scope=FULL_SYSTEM_SCOPE) kvp_db = KeyValuePairSetAPI.to_model(kvp_api) kvp_db = KeyValuePair.add_or_update(kvp_db) kvp_db = KeyValuePairAPI.from_model(kvp_db) self.kvps["kvp_1"] = kvp_db kvp_api = KeyValuePairSetAPI( name="test_system_scope_secret", value="value_secret", scope=FULL_SYSTEM_SCOPE, secret=True ) kvp_db = KeyValuePairSetAPI.to_model(kvp_api) kvp_db = KeyValuePair.add_or_update(kvp_db) kvp_db = KeyValuePairAPI.from_model(kvp_db) self.kvps["kvp_2"] = kvp_db name = get_key_reference(scope=FULL_USER_SCOPE, name="test_user_scope_1", user="******") kvp_db = KeyValuePairDB(name=name, value="valueu12", scope=FULL_USER_SCOPE) kvp_db = KeyValuePair.add_or_update(kvp_db) kvp_db = KeyValuePairAPI.from_model(kvp_db) self.kvps["kvp_3"] = kvp_db name = get_key_reference(scope=FULL_USER_SCOPE, name="test_user_scope_2", user="******") kvp_api = KeyValuePairSetAPI(name=name, value="user_secret", scope=FULL_USER_SCOPE, secret=True) kvp_db = KeyValuePairSetAPI.to_model(kvp_api) kvp_db = KeyValuePair.add_or_update(kvp_db) kvp_db = KeyValuePairAPI.from_model(kvp_db) self.kvps["kvp_4"] = kvp_db name = get_key_reference(scope=FULL_USER_SCOPE, name="test_user_scope_3", user="******") kvp_db = KeyValuePairDB(name=name, value="valueu21", scope=FULL_USER_SCOPE) kvp_db = KeyValuePair.add_or_update(kvp_db) kvp_db = KeyValuePairAPI.from_model(kvp_db) self.kvps["kvp_5"] = kvp_db self.system_scoped_items_count = 2 self.user_scoped_items_count = 3 self.user_scoped_items_per_user_count = {"user1": 2, "user2": 1}
def post(self, api_key_api, requester_user): """ Create a new entry. """ permission_type = PermissionType.API_KEY_CREATE rbac_utils = get_rbac_backend().get_utils_class() rbac_utils.assert_user_has_resource_api_permission(user_db=requester_user, resource_api=api_key_api, permission_type=permission_type) api_key_db = None api_key = None try: if not getattr(api_key_api, 'user', None): if requester_user: api_key_api.user = requester_user.name else: api_key_api.user = cfg.CONF.system_user.user try: User.get_by_name(api_key_api.user) except StackStormDBObjectNotFoundError: user_db = UserDB(name=api_key_api.user) User.add_or_update(user_db) extra = {'username': api_key_api.user, 'user': user_db} LOG.audit('Registered new user "%s".' % (api_key_api.user), extra=extra) # If key_hash is provided use that and do not create a new key. The assumption # is user already has the original api-key if not getattr(api_key_api, 'key_hash', None): api_key, api_key_hash = auth_util.generate_api_key_and_hash() # store key_hash in DB api_key_api.key_hash = api_key_hash api_key_db = ApiKey.add_or_update(ApiKeyAPI.to_model(api_key_api)) except (ValidationError, ValueError) as e: LOG.exception('Validation failed for api_key data=%s.', api_key_api) abort(http_client.BAD_REQUEST, six.text_type(e)) extra = {'api_key_db': api_key_db} LOG.audit('ApiKey created. ApiKey.id=%s' % (api_key_db.id), extra=extra) api_key_create_response_api = ApiKeyCreateResponseAPI.from_model(api_key_db) # Return real api_key back to user. A one-way hash of the api_key is stored in the DB # only the real value only returned at create time. Also, no masking of key here since # the user needs to see this value atleast once. api_key_create_response_api.key = api_key return Response(json=api_key_create_response_api, status=http_client.CREATED)
def setUp(self): super(WebhookControllerRBACTestCase, self).setUp() # Insert mock users, roles and assignments # Users user_1_db = UserDB(name='webhook_list') user_1_db = User.add_or_update(user_1_db) self.users['webhook_list'] = user_1_db user_2_db = UserDB(name='webhook_view') user_2_db = User.add_or_update(user_2_db) self.users['webhook_view'] = user_2_db # Roles # webhook_list grant_db = PermissionGrantDB(resource_uid=None, resource_type=ResourceType.WEBHOOK, permission_types=[PermissionType.WEBHOOK_LIST]) grant_db = PermissionGrant.add_or_update(grant_db) permission_grants = [str(grant_db.id)] role_1_db = RoleDB(name='webhook_list', permission_grants=permission_grants) role_1_db = Role.add_or_update(role_1_db) self.roles['webhook_list'] = role_1_db # webhook_view on webhook 1 (git) name = 'git' webhook_db = WebhookDB(name=name) webhook_uid = webhook_db.get_uid() grant_db = PermissionGrantDB(resource_uid=webhook_uid, resource_type=ResourceType.WEBHOOK, permission_types=[PermissionType.WEBHOOK_VIEW]) grant_db = PermissionGrant.add_or_update(grant_db) permission_grants = [str(grant_db.id)] role_1_db = RoleDB(name='webhook_view', permission_grants=permission_grants) role_1_db = Role.add_or_update(role_1_db) self.roles['webhook_view'] = role_1_db # Role assignments role_assignment_db = UserRoleAssignmentDB( user=self.users['webhook_list'].name, role=self.roles['webhook_list'].name, source='assignments/%s.yaml' % self.users['webhook_list'].name) UserRoleAssignment.add_or_update(role_assignment_db) role_assignment_db = UserRoleAssignmentDB( user=self.users['webhook_view'].name, role=self.roles['webhook_view'].name, source='assignments/%s.yaml' % self.users['webhook_view'].name) UserRoleAssignment.add_or_update(role_assignment_db)
def setUp(self): super(RBACDefinitionsDBSyncerTestCase, self).setUp() self.roles = {} self.users = {} # Insert some mock users user_1_db = UserDB(name='user_1') user_1_db = User.add_or_update(user_1_db) self.users['user_1'] = user_1_db user_2_db = UserDB(name='user_2') user_2_db = User.add_or_update(user_2_db) self.users['user_2'] = user_2_db
def setUp(self): super(ExecutionViewsFiltersControllerRBACTestCase, self).setUp() # Insert mock users, roles and assignments # Users user_1_db = UserDB(name='execution_views_filters_list') user_1_db = User.add_or_update(user_1_db) self.users['execution_views_filters_list'] = user_1_db # Roles # trace_list permission_types = [PermissionType.EXECUTION_VIEWS_FILTERS_LIST] grant_db = PermissionGrantDB(resource_uid=None, resource_type=ResourceType.EXECUTION, permission_types=permission_types) grant_db = PermissionGrant.add_or_update(grant_db) permission_grants = [str(grant_db.id)] role_1_db = RoleDB(name='execution_views_filters_list', permission_grants=permission_grants) role_1_db = Role.add_or_update(role_1_db) self.roles['execution_views_filters_list'] = role_1_db # Role assignments role_assignment_db = UserRoleAssignmentDB( user=self.users['execution_views_filters_list'].name, role=self.roles['execution_views_filters_list'].name, source='assignments/%s.yaml' % self.users['execution_views_filters_list'].name) UserRoleAssignment.add_or_update(role_assignment_db)
def sync_users_role_assignments(self, role_assignment_apis): """ Synchronize role assignments for all the users in the database. :param role_assignment_apis: Role assignments API objects for the assignments loaded from the files. :type role_assignment_apis: ``list`` of :class:`UserRoleAssignmentFileFormatAPI` :return: Dictionary with created and removed role assignments for each user. :rtype: ``dict`` """ LOG.info('Synchronizing users role assignments...') user_dbs = User.get_all() username_to_user_db_map = dict([(user_db.name, user_db) for user_db in user_dbs]) results = {} for role_assignment_api in role_assignment_apis: username = role_assignment_api.username user_db = username_to_user_db_map.get(username, None) if not user_db: LOG.debug(('Skipping role assignments for user "%s" which doesn\'t exist in the ' 'database' % (username))) continue role_assignment_dbs = rbac_services.get_role_assignments_for_user(user_db=user_db) result = self._sync_user_role_assignments(user_db=user_db, role_assignment_dbs=role_assignment_dbs, role_assignment_api=role_assignment_api) results[username] = result LOG.info('User role assignments synchronized') return results
def setUp(self): super(RBACRoleAssignmentsControllerRBACTestCase, self).setUp() # Insert mock users, roles and assignments self.role_assignments = {} # Users user_1_db = UserDB(name='user_foo') user_1_db = User.add_or_update(user_1_db) self.users['user_foo'] = user_1_db # Roles role_1_db = RoleDB(name='user_foo', permission_grants=[]) role_1_db = Role.add_or_update(role_1_db) self.roles['user_foo'] = role_1_db # Role assignments role_assignment_db = UserRoleAssignmentDB( user=self.users['user_foo'].name, role=self.roles['user_foo'].name, source='assignments/%s.yaml' % self.users['user_foo'].name) UserRoleAssignment.add_or_update(role_assignment_db) self.role_assignments['assignment_one'] = role_assignment_db role_assignment_db = UserRoleAssignmentDB( user='******', role=self.roles['user_foo'].name, source='assignments/user_bar.yaml') UserRoleAssignment.add_or_update(role_assignment_db) self.role_assignments['assignment_two'] = role_assignment_db
def sync_users_role_assignments(self, role_assignment_apis): """ Synchronize role assignments for all the users in the database. :param role_assignment_apis: Role assignments API objects for the assignments loaded from the files. :type role_assignment_apis: ``list`` of :class:`UserRoleAssignmentFileFormatAPI` :return: Dictionary with created and removed role assignments for each user. :rtype: ``dict`` """ LOG.info("Synchronizing users role assignments...") username_to_role_assignment_map = dict([(api.username, api) for api in role_assignment_apis]) user_dbs = User.get_all() results = {} for user_db in user_dbs: username = user_db.name role_assignment_api = username_to_role_assignment_map.get(username, None) role_assignment_dbs = rbac_services.get_role_assignments_for_user(user_db=user_db) result = self._sync_user_role_assignments( user_db=user_db, role_assignment_dbs=role_assignment_dbs, role_assignment_api=role_assignment_api ) results[username] = result LOG.info("User role assignments synchronized") return results
def setUp(self): super(TestRbacController, self).setUp() permissions = [ PermissionType.RULE_CREATE, PermissionType.RULE_VIEW, PermissionType.RULE_MODIFY, PermissionType.RULE_DELETE ] for name in permissions: user_db = UserDB(name=name) user_db = User.add_or_update(user_db) self.users[name] = user_db # Roles # action_create grant on parent pack grant_db = PermissionGrantDB(resource_uid='pack:examples', resource_type=ResourceType.PACK, permission_types=[name]) grant_db = PermissionGrant.add_or_update(grant_db) grant_2_db = PermissionGrantDB( resource_uid='action:wolfpack:action-1', resource_type=ResourceType.ACTION, permission_types=[PermissionType.ACTION_EXECUTE]) grant_2_db = PermissionGrant.add_or_update(grant_2_db) permission_grants = [str(grant_db.id), str(grant_2_db.id)] role_db = RoleDB(name=name, permission_grants=permission_grants) role_db = Role.add_or_update(role_db) self.roles[name] = role_db # Role assignments role_assignment_db = UserRoleAssignmentDB(user=user_db.name, role=role_db.name) UserRoleAssignment.add_or_update(role_assignment_db)
def test_sync_assignments_user_doesnt_exist_in_db(self): # Make sure that the assignments for the users which don't exist in the db are still saved syncer = RBACDefinitionsDBSyncer() self._insert_mock_roles() username = '******' # Initial state, no roles user_db = UserDB(name=username) self.assertEqual(len(User.query(name=username)), 0) role_dbs = get_roles_for_user(user_db=user_db) self.assertItemsEqual(role_dbs, []) # Do the sync with two roles defined api = UserRoleAssignmentFileFormatAPI( username=user_db.name, roles=['role_1', 'role_2'], file_path='assignments/foobar.yaml') syncer.sync_users_role_assignments(role_assignment_apis=[api]) role_dbs = get_roles_for_user(user_db=user_db) self.assertEqual(len(role_dbs), 2) self.assertEqual(role_dbs[0], self.roles['role_1']) self.assertEqual(role_dbs[1], self.roles['role_2'])
def test_grant_and_revoke_role(self): user_db = UserDB(name='test-user-1') user_db = User.add_or_update(user_db) # Initial state, no roles role_dbs = rbac_services.get_roles_for_user(user_db=user_db) self.assertItemsEqual(role_dbs, []) role_dbs = user_db.get_roles() self.assertItemsEqual(role_dbs, []) # Assign a role, should have one role assigned rbac_services.assign_role_to_user(role_db=self.roles['custom_role_1'], user_db=user_db) role_dbs = rbac_services.get_roles_for_user(user_db=user_db) self.assertItemsEqual(role_dbs, [self.roles['custom_role_1']]) role_dbs = user_db.get_roles() self.assertItemsEqual(role_dbs, [self.roles['custom_role_1']]) # Revoke previously assigned role, should have no roles again rbac_services.revoke_role_from_user(role_db=self.roles['custom_role_1'], user_db=user_db) role_dbs = rbac_services.get_roles_for_user(user_db=user_db) self.assertItemsEqual(role_dbs, []) role_dbs = user_db.get_roles() self.assertItemsEqual(role_dbs, [])
def setUp(self): super(ActionControllerRBACTestCase, self).setUp() self.fixtures_loader.save_fixtures_to_db(fixtures_pack=FIXTURES_PACK, fixtures_dict=TEST_FIXTURES) file_name = 'action1.yaml' ActionControllerRBACTestCase.ACTION_1 = self.fixtures_loader.load_fixtures( fixtures_pack=FIXTURES_PACK, fixtures_dict={'actions': [file_name]})['actions'][file_name] # Insert mock users, roles and assignments # Users user_2_db = UserDB(name='action_create') user_2_db = User.add_or_update(user_2_db) self.users['action_create'] = user_2_db # Roles # action_create grant on parent pack grant_db = PermissionGrantDB(resource_uid='pack:examples', resource_type=ResourceType.PACK, permission_types=[PermissionType.ACTION_CREATE]) grant_db = PermissionGrant.add_or_update(grant_db) permission_grants = [str(grant_db.id)] role_1_db = RoleDB(name='action_create', permission_grants=permission_grants) role_1_db = Role.add_or_update(role_1_db) self.roles['action_create'] = role_1_db # Role assignments user_db = self.users['action_create'] role_assignment_db = UserRoleAssignmentDB( user=user_db.name, role=self.roles['action_create'].name) UserRoleAssignment.add_or_update(role_assignment_db)
def setUp(self): super(ActionControllerRBACTestCase, self).setUp() self.fixtures_loader.save_fixtures_to_db(fixtures_pack=FIXTURES_PACK, fixtures_dict=TEST_FIXTURES) file_name = 'action1.yaml' ActionControllerRBACTestCase.ACTION_1 = self.fixtures_loader.load_fixtures( fixtures_pack=FIXTURES_PACK, fixtures_dict={'actions': [file_name]})['actions'][file_name] # Insert mock users, roles and assignments # Users user_2_db = UserDB(name='action_create') user_2_db = User.add_or_update(user_2_db) self.users['action_create'] = user_2_db # Roles # action_create grant on parent pack grant_db = PermissionGrantDB( resource_uid='pack:examples', resource_type=ResourceType.PACK, permission_types=[PermissionType.ACTION_CREATE]) grant_db = PermissionGrant.add_or_update(grant_db) permission_grants = [str(grant_db.id)] role_1_db = RoleDB(name='action_create', permission_grants=permission_grants) role_1_db = Role.add_or_update(role_1_db) self.roles['action_create'] = role_1_db # Role assignments user_db = self.users['action_create'] role_assignment_db = UserRoleAssignmentDB( user=user_db.name, role=self.roles['action_create'].name) UserRoleAssignment.add_or_update(role_assignment_db)
def setUp(self): super(WebhookPermissionsResolverTestCase, self).setUp() # Create some mock users user_1_db = UserDB(name='custom_role_webhook_grant') user_1_db = User.add_or_update(user_1_db) self.users['custom_role_webhook_grant'] = user_1_db # Create some mock resources on which permissions can be granted webhook_1_db = WebhookDB(name='st2/') self.resources['webhook_1'] = webhook_1_db # Create some mock roles with associated permission grants # Custom role - "webhook_send" grant on webhook_1 grant_db = PermissionGrantDB(resource_uid=self.resources['webhook_1'].get_uid(), resource_type=ResourceType.WEBHOOK, permission_types=[PermissionType.WEBHOOK_SEND]) grant_db = PermissionGrant.add_or_update(grant_db) permission_grants = [str(grant_db.id)] role_db = RoleDB(name='custom_role_webhook_grant', permission_grants=permission_grants) role_db = Role.add_or_update(role_db) self.roles['custom_role_webhook_grant'] = role_db # Create some mock role assignments user_db = self.users['custom_role_webhook_grant'] role_assignment_db = UserRoleAssignmentDB( user=user_db.name, role=self.roles['custom_role_webhook_grant'].name, source='assignments/%s.yaml' % user_db.name) UserRoleAssignment.add_or_update(role_assignment_db)
def test_logging_profiling_is_disabled(self, mock_log): disable_profiling() queryset = User.query(name__in=['test1', 'test2'], order_by=['+aa', '-bb'], limit=1) result = log_query_and_profile_data_for_queryset(queryset=queryset) self.assertEqual(queryset, result) call_args_list = mock_log.debug.call_args_list self.assertItemsEqual(call_args_list, [])
def test_assign_role_to_user_ignore_already_exists_error(self): user_db = UserDB(name='test-user-10') user_db = User.add_or_update(user_db) role_assignment_db_1 = rbac_service.assign_role_to_user( role_db=self.roles['custom_role_1'], user_db=user_db, source='assignments/%s_10.yaml' % user_db.name) # 1. Without ignore errors self.assertRaises(StackStormDBObjectConflictError, rbac_service.assign_role_to_user, role_db=self.roles['custom_role_1'], user_db=user_db, source='assignments/%s_10.yaml' % user_db.name) # 2. With ignore errors role_assignment_db_2 = rbac_service.assign_role_to_user( role_db=self.roles['custom_role_1'], user_db=user_db, source='assignments/%s_10.yaml' % user_db.name, ignore_already_exists_error=True) self.assertEqual(role_assignment_db_1, role_assignment_db_2) self.assertEqual(role_assignment_db_1.id, role_assignment_db_2.id) self.assertEqual(role_assignment_db_1.user, role_assignment_db_2.user) self.assertEqual(role_assignment_db_1.role, role_assignment_db_2.role)
def setUp(self): super(ActionExecutionRBACControllerTestCase, self).setUp() self.fixtures_loader.save_fixtures_to_db(fixtures_pack=FIXTURES_PACK, fixtures_dict=TEST_FIXTURES) # Insert mock users, roles and assignments # Users user_1_db = UserDB(name='multiple_roles') user_1_db = User.add_or_update(user_1_db) self.users['multiple_roles'] = user_1_db # Roles roles = ['role_1', 'role_2', 'role_3'] for role in roles: role_db = RoleDB(name=role) Role.add_or_update(role_db) # Role assignments user_db = self.users['multiple_roles'] role_assignment_db = UserRoleAssignmentDB( user=user_db.name, role='admin') UserRoleAssignment.add_or_update(role_assignment_db) for role in roles: role_assignment_db = UserRoleAssignmentDB( user=user_db.name, role=role) UserRoleAssignment.add_or_update(role_assignment_db)
def test_grant_and_revoke_role(self): user_db = UserDB(name='test-user-1') user_db = User.add_or_update(user_db) # Initial state, no roles role_dbs = rbac_services.get_roles_for_user(user_db=user_db) self.assertItemsEqual(role_dbs, []) role_dbs = user_db.get_roles() self.assertItemsEqual(role_dbs, []) # Assign a role, should have one role assigned rbac_services.assign_role_to_user(role_db=self.roles['custom_role_1'], user_db=user_db, source='assignments/%s.yaml' % user_db.name) role_dbs = rbac_services.get_roles_for_user(user_db=user_db) self.assertItemsEqual(role_dbs, [self.roles['custom_role_1']]) role_dbs = user_db.get_roles() self.assertItemsEqual(role_dbs, [self.roles['custom_role_1']]) # Revoke previously assigned role, should have no roles again rbac_services.revoke_role_from_user( role_db=self.roles['custom_role_1'], user_db=user_db) role_dbs = rbac_services.get_roles_for_user(user_db=user_db) self.assertItemsEqual(role_dbs, []) role_dbs = user_db.get_roles() self.assertItemsEqual(role_dbs, [])
def put(self, api_key_api, api_key_id_or_key, requester_user): api_key_db = ApiKey.get_by_key_or_id(api_key_id_or_key) permission_type = PermissionType.API_KEY_MODIFY rbac_utils = get_rbac_backend().get_utils_class() rbac_utils.assert_user_has_resource_db_permission( user_db=requester_user, resource_db=api_key_db, permission_type=permission_type, ) old_api_key_db = api_key_db api_key_db = ApiKeyAPI.to_model(api_key_api) try: User.get_by_name(api_key_api.user) except StackStormDBObjectNotFoundError: user_db = UserDB(name=api_key_api.user) User.add_or_update(user_db) extra = {"username": api_key_api.user, "user": user_db} LOG.audit('Registered new user "%s".' % (api_key_api.user), extra=extra) # Passing in key_hash as MASKED_ATTRIBUTE_VALUE is expected since we do not # leak it out therefore it is expected we get the same value back. Interpret # this special code and empty value as no-change if api_key_db.key_hash == MASKED_ATTRIBUTE_VALUE or not api_key_db.key_hash: api_key_db.key_hash = old_api_key_db.key_hash # Rather than silently ignore any update to key_hash it is better to explicitly # disallow and notify user. if old_api_key_db.key_hash != api_key_db.key_hash: raise ValueError("Update of key_hash is not allowed.") api_key_db.id = old_api_key_db.id api_key_db = ApiKey.add_or_update(api_key_db) extra = { "old_api_key_db": old_api_key_db, "new_api_key_db": api_key_db } LOG.audit("API Key updated. ApiKey.id=%s." % (api_key_db.id), extra=extra) api_key_api = ApiKeyAPI.from_model(api_key_db) return api_key_api
def _insert_mock_data(self): # Insert some mock users user_1_db = UserDB(name='user_1') user_1_db = User.add_or_update(user_1_db) self.users['user_1'] = user_1_db user_2_db = UserDB(name='user_2') user_2_db = User.add_or_update(user_2_db) self.users['user_2'] = user_2_db user_3_db = UserDB(name='user_3') user_3_db = User.add_or_update(user_3_db) self.users['user_3'] = user_3_db user_5_db = UserDB(name='user_5') user_5_db = User.add_or_update(user_5_db) self.users['user_5'] = user_5_db
def create_token(username, ttl=None, metadata=None): """ :param username: Username of the user to create the token for. If the account for this user doesn't exist yet it will be created. :type username: ``str`` :param ttl: Token TTL (in seconds). :type ttl: ``int`` :param metadata: Optional metadata to associate with the token. :type metadata: ``dict`` """ if ttl: if ttl > cfg.CONF.auth.token_ttl: msg = 'TTL specified %s is greater than max allowed %s.' % ( ttl, cfg.CONF.auth.token_ttl ) raise TTLTooLargeException(msg) else: ttl = cfg.CONF.auth.token_ttl if username: try: User.get_by_name(username) except: user = UserDB(name=username) User.add_or_update(user) extra = {'username': username, 'user': user} LOG.audit('Registered new user "%s".' % (username), extra=extra) token = uuid.uuid4().hex expiry = datetime.datetime.utcnow() + datetime.timedelta(seconds=ttl) expiry = isotime.add_utc_tz(expiry) token = TokenDB(user=username, token=token, expiry=expiry, metadata=metadata) Token.add_or_update(token) username_string = username if username else 'an anonymous user' token_expire_string = isotime.format(expiry, offset=False) extra = {'username': username, 'token_expiration': token_expire_string} LOG.audit('Access granted to "%s" with the token set to expire at "%s".' % (username_string, token_expire_string), extra=extra) return token
def post(self, api_key_api, requester_user): """ Create a new entry. """ permission_type = PermissionType.API_KEY_CREATE rbac_utils.assert_user_has_resource_api_permission(user_db=requester_user, resource_api=api_key_api, permission_type=permission_type) api_key_db = None api_key = None try: if not getattr(api_key_api, 'user', None): api_key_api.user = requester_user.name or cfg.CONF.system_user.user try: User.get_by_name(api_key_api.user) except StackStormDBObjectNotFoundError: user_db = UserDB(name=api_key_api.user) User.add_or_update(user_db) extra = {'username': api_key_api.user, 'user': user_db} LOG.audit('Registered new user "%s".' % (api_key_api.user), extra=extra) # If key_hash is provided use that and do not create a new key. The assumption # is user already has the original api-key if not getattr(api_key_api, 'key_hash', None): api_key, api_key_hash = auth_util.generate_api_key_and_hash() # store key_hash in DB api_key_api.key_hash = api_key_hash api_key_db = ApiKey.add_or_update(ApiKeyAPI.to_model(api_key_api)) except (ValidationError, ValueError) as e: LOG.exception('Validation failed for api_key data=%s.', api_key_api) abort(http_client.BAD_REQUEST, str(e)) extra = {'api_key_db': api_key_db} LOG.audit('ApiKey created. ApiKey.id=%s' % (api_key_db.id), extra=extra) api_key_create_response_api = ApiKeyCreateResponseAPI.from_model(api_key_db) # Return real api_key back to user. A one-way hash of the api_key is stored in the DB # only the real value only returned at create time. Also, no masking of key here since # the user needs to see this value atleast once. api_key_create_response_api.key = api_key return Response(json=api_key_create_response_api, status=http_client.CREATED)
def setUp(self): super(AuthHandlerRBACRoleSyncTestCase, self).setUp() cfg.CONF.set_override(group='auth', name='backend', override='mock') cfg.CONF.set_override(group='rbac', name='backend', override='default') self.users = {} self.roles = {} self.role_assignments = {} # Insert some mock users user_1_db = UserDB(name='auser') user_1_db = User.add_or_update(user_1_db) self.users['user_1'] = user_1_db user_2_db = UserDB(name='buser') user_2_db = User.add_or_update(user_2_db) self.users['user_2'] = user_2_db # Insert mock local role assignments role_db = rbac_service.create_role(name='mock_local_role_1') user_db = self.users['user_1'] source = 'assignments/%s.yaml' % user_db.name role_assignment_db_1 = rbac_service.assign_role_to_user( role_db=role_db, user_db=user_db, source=source, is_remote=False) self.roles['mock_local_role_1'] = role_db self.role_assignments['assignment_1'] = role_assignment_db_1 role_db = rbac_service.create_role(name='mock_local_role_2') user_db = self.users['user_1'] source = 'assignments/%s.yaml' % user_db.name role_assignment_db_2 = rbac_service.assign_role_to_user( role_db=role_db, user_db=user_db, source=source, is_remote=False) self.roles['mock_local_role_2'] = role_db self.role_assignments['assignment_2'] = role_assignment_db_2 role_db = rbac_service.create_role(name='mock_role_3') self.roles['mock_role_3'] = role_db role_db = rbac_service.create_role(name='mock_role_4') self.roles['mock_role_4'] = role_db role_db = rbac_service.create_role(name='mock_role_5') self.roles['mock_role_5'] = role_db
def setUp(self): super(AuthHandlerGroupToRoleTestCase, self).setUp() cfg.CONF.auth.backend = 'mock' self.users = {} self.roles = {} self.role_assignments = {} # Insert some mock users user_1_db = UserDB(name='auser') user_1_db = User.add_or_update(user_1_db) self.users['user_1'] = user_1_db user_2_db = UserDB(name='buser') user_2_db = User.add_or_update(user_2_db) self.users['user_2'] = user_2_db # Insert mock local role assignments role_db = create_role(name='mock_local_role_1') user_db = self.users['user_1'] source = 'assignments/%s.yaml' % user_db.name role_assignment_db_1 = assign_role_to_user( role_db=role_db, user_db=user_db, source=source, is_remote=False) self.roles['mock_local_role_1'] = role_db self.role_assignments['assignment_1'] = role_assignment_db_1 role_db = create_role(name='mock_local_role_2') user_db = self.users['user_1'] source = 'assignments/%s.yaml' % user_db.name role_assignment_db_2 = assign_role_to_user( role_db=role_db, user_db=user_db, source=source, is_remote=False) self.roles['mock_local_role_2'] = role_db self.role_assignments['assignment_2'] = role_assignment_db_2 role_db = create_role(name='mock_role_3') self.roles['mock_role_3'] = role_db role_db = create_role(name='mock_role_4') self.roles['mock_role_4'] = role_db role_db = create_role(name='mock_role_5') self.roles['mock_role_5'] = role_db
def create_token(username, ttl=None, metadata=None): """ :param username: Username of the user to create the token for. If the account for this user doesn't exist yet it will be created. :type username: ``str`` :param ttl: Token TTL (in seconds). :type ttl: ``int`` :param metadata: Optional metadata to associate with the token. :type metadata: ``dict`` """ if ttl: if ttl > cfg.CONF.auth.token_ttl: msg = 'TTL specified %s is greater than max allowed %s.' % ( ttl, cfg.CONF.auth.token_ttl ) raise TTLTooLargeException(msg) else: ttl = cfg.CONF.auth.token_ttl if username: try: User.get_by_name(username) except: user = UserDB(name=username) User.add_or_update(user) extra = {'username': username, 'user': user} LOG.audit('Registered new user "%s".' % (username), extra=extra) token = uuid.uuid4().hex expiry = date_utils.get_datetime_utc_now() + datetime.timedelta(seconds=ttl) token = TokenDB(user=username, token=token, expiry=expiry, metadata=metadata) Token.add_or_update(token) username_string = username if username else 'an anonymous user' token_expire_string = isotime.format(expiry, offset=False) extra = {'username': username, 'token_expiration': token_expire_string} LOG.audit('Access granted to "%s" with the token set to expire at "%s".' % (username_string, token_expire_string), extra=extra) return token
def setUp(self): super(HandlerTestCase, self).setUp() cfg.CONF.auth.backend = 'mock' self.users = {} self.roles = {} self.role_assignments = {} # Insert some mock users user_1_db = UserDB(name='auser') user_1_db = User.add_or_update(user_1_db) self.users['user_1'] = user_1_db user_2_db = UserDB(name='buser') user_2_db = User.add_or_update(user_2_db) self.users['user_2'] = user_2_db # Insert mock local role assignments role_db = create_role(name='mock_local_role_1') user_db = self.users['user_1'] source = 'assignments/%s.yaml' % user_db.name role_assignment_db_1 = assign_role_to_user( role_db=role_db, user_db=user_db, source=source, is_remote=False) self.roles['mock_local_role_1'] = role_db self.role_assignments['assignment_1'] = role_assignment_db_1 role_db = create_role(name='mock_local_role_2') user_db = self.users['user_1'] source = 'assignments/%s.yaml' % user_db.name role_assignment_db_2 = assign_role_to_user( role_db=role_db, user_db=user_db, source=source, is_remote=False) self.roles['mock_local_role_2'] = role_db self.role_assignments['assignment_2'] = role_assignment_db_2 role_db = create_role(name='mock_role_3') self.roles['mock_role_3'] = role_db role_db = create_role(name='mock_role_4') self.roles['mock_role_4'] = role_db role_db = create_role(name='mock_role_5') self.roles['mock_role_5'] = role_db
def setUp(self): super(RBACServicesTestCase, self).setUp() # TODO: Share mocks self.users = {} self.roles = {} self.resources = {} # Create some mock users user_1_db = UserDB(name='admin') user_1_db = User.add_or_update(user_1_db) self.users['admin'] = user_1_db user_2_db = UserDB(name='observer') user_2_db = User.add_or_update(user_2_db) self.users['observer'] = user_2_db user_3_db = UserDB(name='no_roles') user_3_db = User.add_or_update(user_3_db) self.users['no_roles'] = user_3_db user_4_db = UserDB(name='custom_role') user_4_db = User.add_or_update(user_4_db) self.users['1_custom_role'] = user_4_db # Create some mock roles role_1_db = rbac_services.create_role(name='custom_role_1') role_2_db = rbac_services.create_role(name='custom_role_2', description='custom role 2') self.roles['custom_role_1'] = role_1_db self.roles['custom_role_2'] = role_2_db # Create some mock role assignments role_assignment_1 = UserRoleAssignmentDB( user=self.users['1_custom_role'].name, role=self.roles['custom_role_1'].name) role_assignment_1 = UserRoleAssignment.add_or_update(role_assignment_1) # Create some mock resources on which permissions can be granted rule_1_db = RuleDB(pack='test1', name='rule1', ref='test1.rule1') rule_1_db = Rule.add_or_update(rule_1_db) self.resources['rule_1'] = rule_1_db
def sync_users_role_assignments(self, role_assignment_apis): """ Synchronize role assignments for all the users in the database. :param role_assignment_apis: Role assignments API objects for the assignments loaded from the files. :type role_assignment_apis: ``list`` of :class:`UserRoleAssignmentFileFormatAPI` :return: Dictionary with created and removed role assignments for each user. :rtype: ``dict`` """ LOG.info('Synchronizing users role assignments...') user_dbs = User.get_all() username_to_user_db_map = dict([(user_db.name, user_db) for user_db in user_dbs]) username_to_role_assignment_api_map = dict([ (role_assignment_api.username, role_assignment_api) for role_assignment_api in role_assignment_apis ]) # Note: We process assignments for all the users (ones specified in the assignment files # and ones which are in the databse). We want to make sure assignments are correctly # deleted from the databse for users which existing in the databse, but have no assignment # file on disk. all_usernames = (username_to_user_db_map.keys() + username_to_role_assignment_api_map.keys()) all_usernames = list(set(all_usernames)) results = {} for username in all_usernames: role_assignment_api = username_to_role_assignment_api_map.get( username, None) user_db = username_to_user_db_map.get(username, None) if not user_db: # Note: We allow assignments to be created for the users which don't exist in the # DB yet because user creation in StackStorm is lazy (we only create UserDB) object # when user first logs in. user_db = UserDB(name=username) LOG.debug(( 'User "%s" doesn\'t exist in the DB, creating assignment anyway' % (username))) role_assignment_dbs = rbac_services.get_role_assignments_for_user( user_db=user_db, include_remote=False) result = self._sync_user_role_assignments( user_db=user_db, role_assignment_dbs=role_assignment_dbs, role_assignment_api=role_assignment_api) results[username] = result LOG.info('User role assignments synchronized') return results
def setUp(self): super(RBACServicesTestCase, self).setUp() # TODO: Share mocks self.users = {} self.roles = {} self.resources = {} # Create some mock users user_1_db = UserDB(name='admin') user_1_db = User.add_or_update(user_1_db) self.users['admin'] = user_1_db user_2_db = UserDB(name='observer') user_2_db = User.add_or_update(user_2_db) self.users['observer'] = user_2_db user_3_db = UserDB(name='no_roles') user_3_db = User.add_or_update(user_3_db) self.users['no_roles'] = user_3_db user_4_db = UserDB(name='custom_role') user_4_db = User.add_or_update(user_4_db) self.users['1_custom_role'] = user_4_db # Create some mock roles role_1_db = rbac_services.create_role(name='custom_role_1') role_2_db = rbac_services.create_role(name='custom_role_2', description='custom role 2') self.roles['custom_role_1'] = role_1_db self.roles['custom_role_2'] = role_2_db # Create some mock role assignments role_assignment_1 = UserRoleAssignmentDB(user=self.users['1_custom_role'].name, role=self.roles['custom_role_1'].name) role_assignment_1 = UserRoleAssignment.add_or_update(role_assignment_1) # Create some mock resources on which permissions can be granted rule_1_db = RuleDB(pack='test1', name='rule1', ref='test1.rule1') rule_1_db = Rule.add_or_update(rule_1_db) self.resources['rule_1'] = rule_1_db
def test_admin_permissions_for_user_scoped_kvps(self): resolver = KeyValuePermissionsResolver() admin_user_db = self.users["admin"] # Setup users. No explicit grant, role, and assignment records should be # required for user to access their KVPs user_1_db = UserDB(name="user105") user_1_db = User.add_or_update(user_1_db) self.users[user_1_db.name] = user_1_db # Insert user scoped key value pairs for user1. key_1_name = "mykey5" key_1_ref = get_key_reference(FULL_USER_SCOPE, key_1_name, user_1_db.name) kvp_1_db = KeyValuePairDB( uid="%s:%s:%s" % (ResourceType.KEY_VALUE_PAIR, FULL_USER_SCOPE, key_1_ref), scope=FULL_USER_SCOPE, name=key_1_ref, value="myval5", ) kvp_1_db = KeyValuePair.add_or_update(kvp_1_db) self.resources[kvp_1_db.uid] = kvp_1_db # Admin user should have general list permissions on user1's kvps. self.assertUserHasResourceDbPermission( resolver=resolver, user_db=admin_user_db, resource_db=KeyValuePairDB(scope="%s:%s" % (FULL_USER_SCOPE, user_1_db.name)), permission_type=PermissionType.KEY_VALUE_PAIR_LIST, ) # Admin user should have all permissions to another user1's kvp. self.assertUserHasResourceDbPermission( resolver=resolver, user_db=admin_user_db, resource_db=kvp_1_db, permission_type=PermissionType.KEY_VALUE_PAIR_ALL, ) self.assertUserHasResourceDbPermissions( resolver=resolver, user_db=admin_user_db, resource_db=kvp_1_db, permission_types=self.read_permission_types, ) self.assertUserHasResourceDbPermissions( resolver=resolver, user_db=admin_user_db, resource_db=kvp_1_db, permission_types=self.write_permission_types, )
def _insert_common_mock_users(self): # Insert common mock users user_1_db = UserDB(name='admin') user_1_db = User.add_or_update(user_1_db) self.users['admin'] = user_1_db user_2_db = UserDB(name='observer') user_2_db = User.add_or_update(user_2_db) self.users['observer'] = user_2_db user_3_db = UserDB(name='no_roles') user_3_db = User.add_or_update(user_3_db) self.users['no_roles'] = user_3_db user_4_db = UserDB(name='1_custom_role_no_permissions') user_4_db = User.add_or_update(user_4_db) self.users['1_custom_role_no_permissions'] = user_4_db user_5_db = UserDB(name='1_role_pack_grant') user_5_db = User.add_or_update(user_5_db) self.users['custom_role_pack_grant'] = user_5_db
def _insert_common_mock_users(self): # Insert common mock users user_1_db = UserDB(name="admin") user_1_db = User.add_or_update(user_1_db) self.users["admin"] = user_1_db user_2_db = UserDB(name="observer") user_2_db = User.add_or_update(user_2_db) self.users["observer"] = user_2_db user_3_db = UserDB(name="no_roles") user_3_db = User.add_or_update(user_3_db) self.users["no_roles"] = user_3_db user_4_db = UserDB(name="1_custom_role_no_permissions") user_4_db = User.add_or_update(user_4_db) self.users["1_custom_role_no_permissions"] = user_4_db user_5_db = UserDB(name="1_role_pack_grant") user_5_db = User.add_or_update(user_5_db) self.users["custom_role_pack_grant"] = user_5_db
def _insert_mock_data(self): # Insert some mock users user_1_db = UserDB(name='user_1') user_1_db = User.add_or_update(user_1_db) self.users['user_1'] = user_1_db user_2_db = UserDB(name='user_2') user_2_db = User.add_or_update(user_2_db) self.users['user_2'] = user_2_db user_3_db = UserDB(name='user_3') user_3_db = User.add_or_update(user_3_db) self.users['user_3'] = user_3_db user_5_db = UserDB(name='user_5') user_5_db = User.add_or_update(user_5_db) self.users['user_5'] = user_5_db user_6_db = UserDB(name='user_6') user_6_db = User.add_or_update(user_6_db) self.users['user_6'] = user_6_db
def put(self, api_key_api, api_key_id_or_key, requester_user): api_key_db = ApiKey.get_by_key_or_id(api_key_id_or_key) permission_type = PermissionType.API_KEY_MODIFY rbac_utils = get_rbac_backend().get_utils_class() rbac_utils.assert_user_has_resource_db_permission(user_db=requester_user, resource_db=api_key_db, permission_type=permission_type) old_api_key_db = api_key_db api_key_db = ApiKeyAPI.to_model(api_key_api) try: User.get_by_name(api_key_api.user) except StackStormDBObjectNotFoundError: user_db = UserDB(name=api_key_api.user) User.add_or_update(user_db) extra = {'username': api_key_api.user, 'user': user_db} LOG.audit('Registered new user "%s".' % (api_key_api.user), extra=extra) # Passing in key_hash as MASKED_ATTRIBUTE_VALUE is expected since we do not # leak it out therefore it is expected we get the same value back. Interpret # this special code and empty value as no-change if api_key_db.key_hash == MASKED_ATTRIBUTE_VALUE or not api_key_db.key_hash: api_key_db.key_hash = old_api_key_db.key_hash # Rather than silently ignore any update to key_hash it is better to explicitly # disallow and notify user. if old_api_key_db.key_hash != api_key_db.key_hash: raise ValueError('Update of key_hash is not allowed.') api_key_db.id = old_api_key_db.id api_key_db = ApiKey.add_or_update(api_key_db) extra = {'old_api_key_db': old_api_key_db, 'new_api_key_db': api_key_db} LOG.audit('API Key updated. ApiKey.id=%s.' % (api_key_db.id), extra=extra) api_key_api = ApiKeyAPI.from_model(api_key_db) return api_key_api
def _validate_creds_and_get_user(request): """ Validate one of token or api_key provided either in headers or query parameters. Will returnt the User :rtype: :class:`UserDB` """ headers = request.headers query_string = request.query_string query_params = dict(urlparse.parse_qsl(query_string)) token_in_headers = headers.get(HEADER_ATTRIBUTE_NAME, None) token_in_query_params = query_params.get(QUERY_PARAM_ATTRIBUTE_NAME, None) api_key_in_headers = headers.get(HEADER_API_KEY_ATTRIBUTE_NAME, None) api_key_in_query_params = query_params.get( QUERY_PARAM_API_KEY_ATTRIBUTE_NAME, None) if ((token_in_headers or token_in_query_params) and (api_key_in_headers or api_key_in_query_params)): raise auth_exceptions.MultipleAuthSourcesError( 'Only one of Token or API key expected.') user = None if token_in_headers or token_in_query_params: token_db = auth_utils.validate_token_and_source( token_in_headers=token_in_headers, token_in_query_params=token_in_query_params) user = token_db.user elif api_key_in_headers or api_key_in_query_params: api_key_db = auth_utils.validate_api_key_and_source( api_key_in_headers=api_key_in_headers, api_key_query_params=api_key_in_query_params) user = api_key_db.user else: raise auth_exceptions.NoAuthSourceProvidedError( 'One of Token or API key required.') if not user: LOG.warn('User not found for supplied token or api-key.') return None try: return User.get(user) except StackStormDBObjectNotFoundError: # User doesn't exist - we should probably also invalidate token/apikey if # this happens. LOG.warn('User %s not found.', user) return None
def setUp(self): super(BaseAPIControllerWithRBACTestCase, self).setUp() self.users = {} self.roles = {} # Run RBAC migrations run_all_rbac_migrations() # Insert mock users with default role assignments role_names = [ SystemRole.SYSTEM_ADMIN, SystemRole.ADMIN, SystemRole.OBSERVER ] for role_name in role_names: user_db = UserDB(name=role_name) user_db = User.add_or_update(user_db) self.users[role_name] = user_db role_assignment_db = UserRoleAssignmentDB( user=user_db.name, role=role_name, source='assignments/%s.yaml' % user_db.name) UserRoleAssignment.add_or_update(role_assignment_db) # Insert a user with no permissions and role assignments user_1_db = UserDB(name='no_permissions') user_1_db = User.add_or_update(user_1_db) self.users['no_permissions'] = user_1_db # Insert special system user user_2_db = UserDB(name='system_user') user_2_db = User.add_or_update(user_2_db) self.users['system_user'] = user_2_db role_assignment_db = UserRoleAssignmentDB( user=user_2_db.name, role=SystemRole.ADMIN, source='assignments/%s.yaml' % user_2_db.name) UserRoleAssignment.add_or_update(role_assignment_db)
def _validate_creds_and_get_user(request): """ Validate one of token or api_key provided either in headers or query parameters. Will returnt the User :rtype: :class:`UserDB` """ headers = request.headers query_string = request.query_string query_params = dict(urlparse.parse_qsl(query_string)) token_in_headers = headers.get(HEADER_ATTRIBUTE_NAME, None) token_in_query_params = query_params.get(QUERY_PARAM_ATTRIBUTE_NAME, None) api_key_in_headers = headers.get(HEADER_API_KEY_ATTRIBUTE_NAME, None) api_key_in_query_params = query_params.get(QUERY_PARAM_API_KEY_ATTRIBUTE_NAME, None) if ((token_in_headers or token_in_query_params) and (api_key_in_headers or api_key_in_query_params)): raise auth_exceptions.MultipleAuthSourcesError( 'Only one of Token or API key expected.') user = None if token_in_headers or token_in_query_params: token_db = auth_utils.validate_token_and_source( token_in_headers=token_in_headers, token_in_query_params=token_in_query_params) user = token_db.user elif api_key_in_headers or api_key_in_query_params: api_key_db = auth_utils.validate_api_key_and_source( api_key_in_headers=api_key_in_headers, api_key_query_params=api_key_in_query_params) user = api_key_db.user else: raise auth_exceptions.NoAuthSourceProvidedError('One of Token or API key required.') if not user: LOG.warn('User not found for supplied token or api-key.') return None try: return User.get(user) except StackStormDBObjectNotFoundError: # User doesn't exist - we should probably also invalidate token/apikey if # this happens. LOG.warn('User %s not found.', user) return None
def test_logging_profiling_is_enabled(self, mock_log): enable_profiling() queryset = User.query(name__in=['test1', 'test2'], order_by=['+aa', '-bb'], limit=1) result = log_query_and_profile_data_for_queryset(queryset=queryset) call_args_list = mock_log.debug.call_args_list call_args = call_args_list[0][0] call_kwargs = call_args_list[0][1] expected_result = ("db.user_d_b.find({'name': {'$in': ['test1', 'test2']}})" ".sort({aa: 1, bb: -1}).limit(1);") self.assertEqual(queryset, result) self.assertTrue(expected_result in call_args[0]) self.assertTrue('mongo_query' in call_kwargs['extra']) self.assertTrue('mongo_shell_query' in call_kwargs['extra'])
def setUp(self): super(APIControllersRBACTestCase, self).setUp() # Register packs if self.register_packs: self._register_packs() self.users = {} # Users user_1_db = UserDB(name="no_permissions") user_1_db = User.add_or_update(user_1_db) self.users["no_permissions"] = user_1_db # Insert mock objects - those objects are used to test get one, edit and delete operations self.models = self.fixtures_loader.save_fixtures_to_db(fixtures_pack=FIXTURES_PACK, fixtures_dict=TEST_FIXTURES)
def setUp(self): super(APIControllersRBACTestCase, self).setUp() # Register packs if self.register_packs: self._register_packs() self.users = {} # Users user_1_db = UserDB(name='no_permissions') user_1_db = User.add_or_update(user_1_db) self.users['no_permissions'] = user_1_db # Insert mock objects - those objects are used to test get one, edit and delete operations self.models = self.fixtures_loader.save_fixtures_to_db( fixtures_pack=FIXTURES_PACK, fixtures_dict=TEST_FIXTURES)
def setUp(self): super(ActionViewsControllerRBACTestCase, self).setUp() self.models = self.fixtures_loader.save_fixtures_to_db( fixtures_pack=FIXTURES_PACK, fixtures_dict=TEST_FIXTURES) file_name = 'a1.yaml' ActionViewsControllerRBACTestCase.ACTION_1 = self.fixtures_loader.load_fixtures( fixtures_pack=FIXTURES_PACK, fixtures_dict={'actions': [file_name]})['actions'][file_name] file_name = 'a2.yaml' ActionViewsControllerRBACTestCase.ACTION_1 = self.fixtures_loader.load_fixtures( fixtures_pack=FIXTURES_PACK, fixtures_dict={'actions': [file_name]})['actions'][file_name] # Insert mock users, roles and assignments # Users user_2_db = UserDB(name='action_view_a1') user_2_db = User.add_or_update(user_2_db) self.users['action_view_a1'] = user_2_db # Roles # action_view on a1 action_uid = self.models['actions']['a1.yaml'].get_uid() grant_db = PermissionGrantDB( resource_uid=action_uid, resource_type=ResourceType.ACTION, permission_types=[PermissionType.ACTION_VIEW]) grant_db = PermissionGrant.add_or_update(grant_db) permission_grants = [str(grant_db.id)] role_1_db = RoleDB(name='action_view_a1', permission_grants=permission_grants) role_1_db = Role.add_or_update(role_1_db) self.roles['action_view_a1'] = role_1_db # Role assignments role_assignment_db = UserRoleAssignmentDB( user=self.users['action_view_a1'].name, role=self.roles['action_view_a1'].name, source='assignments/%s.yaml' % self.users['action_view_a1'].name) UserRoleAssignment.add_or_update(role_assignment_db)
def sync_users_role_assignments(self, role_assignment_apis): """ Synchronize role assignments for all the users in the database. :param role_assignment_apis: Role assignments API objects for the assignments loaded from the files. :type role_assignment_apis: ``list`` of :class:`UserRoleAssignmentFileFormatAPI` :return: Dictionary with created and removed role assignments for each user. :rtype: ``dict`` """ LOG.info('Synchronizing users role assignments...') user_dbs = User.get_all() username_to_user_db_map = dict([(user_db.name, user_db) for user_db in user_dbs]) results = {} for role_assignment_api in role_assignment_apis: username = role_assignment_api.username user_db = username_to_user_db_map.get(username, None) if not user_db: # Note: We allow assignments to be created for the users which don't exist in the # DB yet because user creation in StackStorm is lazy (we only create UserDB) object # when user first logs in. user_db = UserDB(name=username) LOG.debug(( 'User "%s" doesn\'t exist in the DB, creating assignment anyway' % (username))) role_assignment_dbs = rbac_services.get_role_assignments_for_user( user_db=user_db) result = self._sync_user_role_assignments( user_db=user_db, role_assignment_dbs=role_assignment_dbs, role_assignment_api=role_assignment_api) results[username] = result LOG.info('User role assignments synchronized') return results
def setUp(self): super(RBACControllerTestCase, self).setUp() permissions = [PermissionType.RULE_CREATE, PermissionType.RULE_VIEW, PermissionType.RULE_MODIFY, PermissionType.RULE_DELETE] for name in permissions: user_db = UserDB(name=name) user_db = User.add_or_update(user_db) self.users[name] = user_db # Roles # action_create grant on parent pack grant_db = PermissionGrantDB(resource_uid='pack:examples', resource_type=ResourceType.PACK, permission_types=[name]) grant_db = PermissionGrant.add_or_update(grant_db) grant_2_db = PermissionGrantDB(resource_uid='action:wolfpack:action-1', resource_type=ResourceType.ACTION, permission_types=[PermissionType.ACTION_EXECUTE]) grant_2_db = PermissionGrant.add_or_update(grant_2_db) permission_grants = [str(grant_db.id), str(grant_2_db.id)] role_db = RoleDB(name=name, permission_grants=permission_grants) role_db = Role.add_or_update(role_db) self.roles[name] = role_db # Role assignments role_assignment_db = UserRoleAssignmentDB( user=user_db.name, role=role_db.name, source='assignments/%s.yaml' % user_db.name) UserRoleAssignment.add_or_update(role_assignment_db) role_assignment_db = UserRoleAssignmentDB( user='******', role='role_two', source='assignments/user_two.yaml', is_remote=True) UserRoleAssignment.add_or_update(role_assignment_db)
def setUp(self): super(ActionViewsControllerRBACTestCase, self).setUp() self.models = self.fixtures_loader.save_fixtures_to_db(fixtures_pack=FIXTURES_PACK, fixtures_dict=TEST_FIXTURES) file_name = 'a1.yaml' ActionViewsControllerRBACTestCase.ACTION_1 = self.fixtures_loader.load_fixtures( fixtures_pack=FIXTURES_PACK, fixtures_dict={'actions': [file_name]})['actions'][file_name] file_name = 'a2.yaml' ActionViewsControllerRBACTestCase.ACTION_1 = self.fixtures_loader.load_fixtures( fixtures_pack=FIXTURES_PACK, fixtures_dict={'actions': [file_name]})['actions'][file_name] # Insert mock users, roles and assignments # Users user_2_db = UserDB(name='action_view_a1') user_2_db = User.add_or_update(user_2_db) self.users['action_view_a1'] = user_2_db # Roles # action_view on a1 action_uid = self.models['actions']['a1.yaml'].get_uid() grant_db = PermissionGrantDB(resource_uid=action_uid, resource_type=ResourceType.ACTION, permission_types=[PermissionType.ACTION_VIEW]) grant_db = PermissionGrant.add_or_update(grant_db) permission_grants = [str(grant_db.id)] role_1_db = RoleDB(name='action_view_a1', permission_grants=permission_grants) role_1_db = Role.add_or_update(role_1_db) self.roles['action_view_a1'] = role_1_db # Role assignments role_assignment_db = UserRoleAssignmentDB( user=self.users['action_view_a1'].name, role=self.roles['action_view_a1'].name, source='assignments/%s.yaml' % self.users['action_view_a1'].name) UserRoleAssignment.add_or_update(role_assignment_db)
def before(self, state): # OPTIONS requests doesn't need to be authenticated if state.request.method == 'OPTIONS': return token_db = self._validate_token(request=state.request) try: user_db = User.get(token_db.user) except ValueError: # User doesn't exist - we should probably also invalidate token if # this happens user_db = None # Store token and related user object in the context # Note: We also store token outside of auth dict for backward compatibility state.request.context['token'] = token_db state.request.context['auth'] = {'token': token_db, 'user': user_db} if QUERY_PARAM_ATTRIBUTE_NAME in state.arguments.keywords: del state.arguments.keywords[QUERY_PARAM_ATTRIBUTE_NAME]
def sync_users_role_assignments(self, role_assignment_apis): """ Synchronize role assignments for all the users in the database. :param role_assignment_apis: Role assignments API objects for the assignments loaded from the files. :type role_assignment_apis: ``list`` of :class:`UserRoleAssignmentFileFormatAPI` :return: Dictionary with created and removed role assignments for each user. :rtype: ``dict`` """ LOG.info('Synchronizing users role assignments...') user_dbs = User.get_all() username_to_user_db_map = dict([(user_db.name, user_db) for user_db in user_dbs]) results = {} for role_assignment_api in role_assignment_apis: username = role_assignment_api.username user_db = username_to_user_db_map.get(username, None) if not user_db: LOG.debug(( 'Skipping role assignments for user "%s" which doesn\'t exist in the ' 'database' % (username))) continue role_assignment_dbs = rbac_services.get_role_assignments_for_user( user_db=user_db) result = self._sync_user_role_assignments( user_db=user_db, role_assignment_dbs=role_assignment_dbs, role_assignment_api=role_assignment_api) results[username] = result LOG.info('User role assignments synchronized') return results
def sync_users_role_assignments(self, role_assignment_apis): """ Synchronize role assignments for all the users in the database. :param role_assignment_apis: Role assignments API objects for the assignments loaded from the files. :type role_assignment_apis: ``list`` of :class:`UserRoleAssignmentFileFormatAPI` :return: Dictionary with created and removed role assignments for each user. :rtype: ``dict`` """ assert isinstance(role_assignment_apis, (list, tuple)) LOG.info('Synchronizing users role assignments...') # Note: We exclude remote assignments because sync tool is not supposed to manipulate # remote assignments role_assignment_dbs = rbac_services.get_all_role_assignments( include_remote=False) user_dbs = User.get_all() username_to_user_db_map = dict([(user_db.name, user_db) for user_db in user_dbs]) username_to_role_assignment_apis_map = defaultdict(list) username_to_role_assignment_dbs_map = defaultdict(list) for role_assignment_api in role_assignment_apis: username = role_assignment_api.username username_to_role_assignment_apis_map[username].append( role_assignment_api) for role_assignment_db in role_assignment_dbs: username = role_assignment_db.user username_to_role_assignment_dbs_map[username].append( role_assignment_db) # Note: We process assignments for all the users (ones specified in the assignment files # and ones which are in the database). We want to make sure assignments are correctly # deleted from the database for users which existing in the database, but have no # assignment file on disk and for assignments for users which don't exist in the database. all_usernames = (list(username_to_user_db_map.keys()) + list(username_to_role_assignment_apis_map.keys()) + list(username_to_role_assignment_dbs_map.keys())) all_usernames = list(set(all_usernames)) results = {} for username in all_usernames: user_db = username_to_user_db_map.get(username, None) if not user_db: # Note: We allow assignments to be created for the users which don't exist in the # DB yet because user creation in StackStorm is lazy (we only create UserDB) object # when user first logs in. user_db = UserDB(name=username) LOG.debug(( 'User "%s" doesn\'t exist in the DB, creating assignment anyway' % (username))) role_assignment_apis = username_to_role_assignment_apis_map.get( username, []) role_assignment_dbs = username_to_role_assignment_dbs_map.get( username, []) # Additional safety assert to ensure we don't accidentally manipulate remote # assignments for role_assignment_db in role_assignment_dbs: assert role_assignment_db.is_remote is False result = self._sync_user_role_assignments( user_db=user_db, role_assignment_dbs=role_assignment_dbs, role_assignment_apis=role_assignment_apis) results[username] = result LOG.info('User role assignments synchronized') return results
def setUp(self): super(ExecutionPermissionsResolverTestCase, self).setUp() # Create some mock users user_1_db = UserDB(name='custom_role_unrelated_pack_action_grant') user_1_db = User.add_or_update(user_1_db) self.users['custom_role_unrelated_pack_action_grant'] = user_1_db user_2_db = UserDB( name='custom_role_pack_action_grant_unrelated_permission') user_2_db = User.add_or_update(user_2_db) self.users[ 'custom_role_pack_action_grant_unrelated_permission'] = user_2_db user_3_db = UserDB(name='custom_role_pack_action_view_grant') user_3_db = User.add_or_update(user_3_db) self.users['custom_role_pack_action_view_grant'] = user_3_db user_4_db = UserDB(name='custom_role_action_view_grant') user_4_db = User.add_or_update(user_4_db) self.users['custom_role_action_view_grant'] = user_4_db user_5_db = UserDB(name='custom_role_pack_action_execute_grant') user_5_db = User.add_or_update(user_5_db) self.users['custom_role_pack_action_execute_grant'] = user_5_db user_6_db = UserDB(name='custom_role_action_execute_grant') user_6_db = User.add_or_update(user_6_db) self.users['custom_role_action_execute_grant'] = user_6_db user_7_db = UserDB(name='custom_role_pack_action_all_grant') user_7_db = User.add_or_update(user_7_db) self.users['custom_role_pack_action_all_grant'] = user_7_db user_8_db = UserDB(name='custom_role_action_all_grant') user_8_db = User.add_or_update(user_8_db) self.users['custom_role_action_all_grant'] = user_8_db user_9_db = UserDB(name='custom_role_execution_list_grant') user_9_db = User.add_or_update(user_5_db) self.users['custom_role_execution_list_grant'] = user_9_db # Create some mock resources on which permissions can be granted action_1_db = ActionDB(pack='test_pack_2', name='action1', entry_point='', runner_type={'name': 'run-local'}) action_1_db = Action.add_or_update(action_1_db) self.resources['action_1'] = action_1_db runner = {'name': 'run-python'} liveaction = {'action': 'test_pack_2.action1'} status = action_constants.LIVEACTION_STATUS_REQUESTED action = {'uid': action_1_db.get_uid(), 'pack': 'test_pack_2'} exec_1_db = ActionExecutionDB(action=action, runner=runner, liveaction=liveaction, status=status) exec_1_db = ActionExecution.add_or_update(exec_1_db) self.resources['exec_1'] = exec_1_db # Create some mock roles with associated permission grants # Custom role - one grant to an unrelated pack grant_db = PermissionGrantDB( resource_uid=self.resources['pack_1'].get_uid(), resource_type=ResourceType.PACK, permission_types=[PermissionType.ACTION_VIEW]) grant_db = PermissionGrant.add_or_update(grant_db) permission_grants = [str(grant_db.id)] role_db = RoleDB(name='custom_role_unrelated_pack_action_grant', permission_grants=permission_grants) role_db = Role.add_or_update(role_db) self.roles['custom_role_unrelated_pack_action_grant'] = role_db # Custom role - one grant of unrelated permission type to parent action pack grant_db = PermissionGrantDB( resource_uid=self.resources['pack_2'].get_uid(), resource_type=ResourceType.PACK, permission_types=[PermissionType.RULE_VIEW]) grant_db = PermissionGrant.add_or_update(grant_db) permission_grants = [str(grant_db.id)] role_db = RoleDB( name='custom_role_pack_action_grant_unrelated_permission', permission_grants=permission_grants) role_db = Role.add_or_update(role_db) self.roles[ 'custom_role_pack_action_grant_unrelated_permission'] = role_db # Custom role - one grant of "action_view" to the parent pack of the action the execution # belongs to grant_db = PermissionGrantDB( resource_uid=self.resources['pack_2'].get_uid(), resource_type=ResourceType.PACK, permission_types=[PermissionType.ACTION_VIEW]) grant_db = PermissionGrant.add_or_update(grant_db) permission_grants = [str(grant_db.id)] role_db = RoleDB(name='custom_role_pack_action_view_grant', permission_grants=permission_grants) role_db = Role.add_or_update(role_db) self.roles['custom_role_pack_action_view_grant'] = role_db # Custom role - one grant of "action_view" to the action the execution belongs to grant_db = PermissionGrantDB( resource_uid=self.resources['action_1'].get_uid(), resource_type=ResourceType.ACTION, permission_types=[PermissionType.ACTION_VIEW]) grant_db = PermissionGrant.add_or_update(grant_db) permission_grants = [str(grant_db.id)] role_db = RoleDB(name='custom_role_action_view_grant', permission_grants=permission_grants) role_db = Role.add_or_update(role_db) self.roles['custom_role_action_view_grant'] = role_db # Custom role - one grant of "action_execute" to the parent pack of the action the # execution belongs to grant_db = PermissionGrantDB( resource_uid=self.resources['pack_2'].get_uid(), resource_type=ResourceType.PACK, permission_types=[PermissionType.ACTION_EXECUTE]) grant_db = PermissionGrant.add_or_update(grant_db) permission_grants = [str(grant_db.id)] role_db = RoleDB(name='custom_role_pack_action_execute_grant', permission_grants=permission_grants) role_db = Role.add_or_update(role_db) self.roles['custom_role_pack_action_execute_grant'] = role_db # Custom role - one grant of "action_execute" to the the action the execution belongs to grant_db = PermissionGrantDB( resource_uid=self.resources['action_1'].get_uid(), resource_type=ResourceType.ACTION, permission_types=[PermissionType.ACTION_EXECUTE]) grant_db = PermissionGrant.add_or_update(grant_db) permission_grants = [str(grant_db.id)] role_db = RoleDB(name='custom_role_action_execute_grant', permission_grants=permission_grants) role_db = Role.add_or_update(role_db) self.roles['custom_role_action_execute_grant'] = role_db # Custom role - "action_all" grant on a parent action pack the execution belongs to grant_db = PermissionGrantDB( resource_uid=self.resources['pack_2'].get_uid(), resource_type=ResourceType.PACK, permission_types=[PermissionType.ACTION_ALL]) grant_db = PermissionGrant.add_or_update(grant_db) permission_grants = [str(grant_db.id)] role_4_db = RoleDB(name='custom_role_pack_action_all_grant', permission_grants=permission_grants) role_4_db = Role.add_or_update(role_4_db) self.roles['custom_role_pack_action_all_grant'] = role_4_db # Custom role - "action_all" grant on action the execution belongs to grant_db = PermissionGrantDB( resource_uid=self.resources['action_1'].get_uid(), resource_type=ResourceType.ACTION, permission_types=[PermissionType.ACTION_ALL]) grant_db = PermissionGrant.add_or_update(grant_db) permission_grants = [str(grant_db.id)] role_4_db = RoleDB(name='custom_role_action_all_grant', permission_grants=permission_grants) role_4_db = Role.add_or_update(role_4_db) self.roles['custom_role_action_all_grant'] = role_4_db # Custom role - "execution_list" grant grant_db = PermissionGrantDB( resource_uid=None, resource_type=None, permission_types=[PermissionType.EXECUTION_LIST]) grant_db = PermissionGrant.add_or_update(grant_db) permission_grants = [str(grant_db.id)] role_5_db = RoleDB(name='custom_role_execution_list_grant', permission_grants=permission_grants) role_5_db = Role.add_or_update(role_5_db) self.roles['custom_role_execution_list_grant'] = role_5_db # Create some mock role assignments user_db = self.users['custom_role_unrelated_pack_action_grant'] role_assignment_db = UserRoleAssignmentDB( user=user_db.name, role=self.roles['custom_role_unrelated_pack_action_grant'].name, source='assignments/%s.yaml' % user_db.name) UserRoleAssignment.add_or_update(role_assignment_db) user_db = self.users[ 'custom_role_pack_action_grant_unrelated_permission'] role_assignment_db = UserRoleAssignmentDB( user=user_db.name, role=self. roles['custom_role_pack_action_grant_unrelated_permission'].name, source='assignments/%s.yaml' % user_db.name) UserRoleAssignment.add_or_update(role_assignment_db) user_db = self.users['custom_role_pack_action_view_grant'] role_assignment_db = UserRoleAssignmentDB( user=user_db.name, role=self.roles['custom_role_pack_action_view_grant'].name, source='assignments/%s.yaml' % user_db.name) UserRoleAssignment.add_or_update(role_assignment_db) user_db = self.users['custom_role_action_view_grant'] role_assignment_db = UserRoleAssignmentDB( user=user_db.name, role=self.roles['custom_role_action_view_grant'].name, source='assignments/%s.yaml' % user_db.name) UserRoleAssignment.add_or_update(role_assignment_db) user_db = self.users['custom_role_pack_action_execute_grant'] role_assignment_db = UserRoleAssignmentDB( user=user_db.name, role=self.roles['custom_role_pack_action_execute_grant'].name, source='assignments/%s.yaml' % user_db.name) UserRoleAssignment.add_or_update(role_assignment_db) user_db = self.users['custom_role_action_execute_grant'] role_assignment_db = UserRoleAssignmentDB( user=user_db.name, role=self.roles['custom_role_action_execute_grant'].name, source='assignments/%s.yaml' % user_db.name) UserRoleAssignment.add_or_update(role_assignment_db) user_db = self.users['custom_role_pack_action_all_grant'] role_assignment_db = UserRoleAssignmentDB( user=user_db.name, role=self.roles['custom_role_pack_action_all_grant'].name, source='assignments/%s.yaml' % user_db.name) UserRoleAssignment.add_or_update(role_assignment_db) user_db = self.users['custom_role_action_all_grant'] role_assignment_db = UserRoleAssignmentDB( user=user_db.name, role=self.roles['custom_role_action_all_grant'].name, source='assignments/%s.yaml' % user_db.name) UserRoleAssignment.add_or_update(role_assignment_db) user_db = self.users['custom_role_execution_list_grant'] role_assignment_db = UserRoleAssignmentDB( user=user_db.name, role=self.roles['custom_role_execution_list_grant'].name, source='assignments/%s.yaml' % user_db.name) UserRoleAssignment.add_or_update(role_assignment_db)