def test_launch_instance(self): policy.check((), IsA(http.HttpRequest)).MultipleTimes().AndReturn(True) api.trove.datastore_flavors(IsA(http.HttpRequest), IsA(six.string_types), IsA(six.string_types)).\ MultipleTimes().AndReturn(self.flavors.list()) api.trove.backup_list(IsA(http.HttpRequest)).AndReturn( self.database_backups.list()) api.trove.configuration_list(IsA(http.HttpRequest)).AndReturn([]) api.trove.instance_list(IsA(http.HttpRequest)).AndReturn( self.databases.list()) # Mock datastores api.trove.datastore_list(IsA(http.HttpRequest)).AndReturn( self.datastores.list()) # Mock datastore versions api.trove.datastore_version_list(IsA(http.HttpRequest), IsA(str)).\ MultipleTimes().AndReturn(self.datastore_versions.list()) dash_api.cinder.volume_type_list(IsA(http.HttpRequest)).AndReturn([]) dash_api.neutron.network_list(IsA(http.HttpRequest), tenant_id=self.tenant.id, shared=False).AndReturn( self.networks.list()[:1]) dash_api.neutron.network_list(IsA(http.HttpRequest), shared=True).AndReturn( self.networks.list()[1:]) dash_api.nova.availability_zone_list(IsA(http.HttpRequest)) \ .AndReturn(self.availability_zones.list()) self.mox.ReplayAll() res = self.client.get(LAUNCH_URL) self.assertTemplateUsed(res, 'project/databases/launch.html')
def test_launch_backup(self): policy.check((), IsA(http.HttpRequest)).MultipleTimes().AndReturn(True) api.trove.instance_list(IsA(http.HttpRequest))\ .AndReturn(self.databases.list()) api.trove.backup_list(IsA(http.HttpRequest)) \ .AndReturn(self.database_backups.list()) database = self.databases.first() backupName = "NewBackup" backupDesc = "Backup Description" api.trove.backup_create(IsA(http.HttpRequest), backupName, database.id, backupDesc, "") self.mox.ReplayAll() post = { 'name': backupName, 'instance': database.id, 'description': backupDesc, 'parent': "" } res = self.client.post(BACKUP_URL, post) self.assertNoFormErrors(res) self.assertRedirectsNoFollow(res, INDEX_URL)
def test_launch_backup(self): policy.check((), IsA(http.HttpRequest)).MultipleTimes().AndReturn(True) api.trove.instance_list(IsA(http.HttpRequest))\ .AndReturn(self.databases.list()) api.trove.backup_list(IsA(http.HttpRequest)) \ .AndReturn(self.database_backups.list()) database = self.databases.first() backupName = "NewBackup" backupDesc = "Backup Description" api.trove.backup_create( IsA(http.HttpRequest), backupName, database.id, backupDesc, "") self.mox.ReplayAll() post = { 'name': backupName, 'instance': database.id, 'description': backupDesc, 'parent': "" } res = self.client.post(BACKUP_URL, post) self.assertNoFormErrors(res) self.assertRedirectsNoFollow(res, INDEX_URL)
def test_launch_backup_exception(self): policy.check((), IsA(http.HttpRequest)).MultipleTimes().AndReturn(True) api.trove.instance_list(IsA(http.HttpRequest))\ .AndRaise(self.exceptions.trove) api.trove.backup_list(IsA(http.HttpRequest)) \ .AndReturn(self.database_backups.list()) self.mox.ReplayAll() res = self.client.get(BACKUP_URL) self.assertMessageCount(res, error=1) self.assertTemplateUsed(res, 'project/database_backups/backup.html')
def test_restore_backup(self): policy.check((), IsA(http.HttpRequest)).MultipleTimes().AndReturn(True) backup = self.database_backups.first() api.trove.backup_get(IsA(http.HttpRequest), IsA(six.text_type)) \ .AndReturn(self.database_backups.first()) api.trove.backup_list(IsA(http.HttpRequest)).AndReturn( self.database_backups.list()) api.trove.configuration_list(IsA(http.HttpRequest)) \ .AndReturn(self.database_configurations.list()) api.trove.datastore_flavors(IsA(http.HttpRequest), IsA(six.string_types), IsA(six.string_types)) \ .AndReturn(self.flavors.list()) api.trove.datastore_list(IsA(http.HttpRequest)) \ .AndReturn(self.datastores.list()) api.trove.datastore_version_list(IsA(http.HttpRequest), backup.datastore['type']) \ .AndReturn(self.datastore_versions.list()) api.trove.instance_list(IsA(http.HttpRequest), marker=None) \ .AndReturn(common.Paginated(self.databases.list())) dash_api.cinder.volume_type_list(IsA(http.HttpRequest)).AndReturn([]) dash_api.neutron.network_list(IsA(http.HttpRequest), tenant_id=self.tenant.id, shared=False).\ AndReturn(self.networks.list()[:1]) dash_api.nova.availability_zone_list(IsA(http.HttpRequest)) \ .AndReturn(self.availability_zones.list()) self.mox.ReplayAll() url = RESTORE_URL + '?backup=%s' % self.database_backups.first().id res = self.client.get(url) self.assertTemplateUsed(res, 'project/databases/launch.html') set_instance_detail_step = \ [step for step in res.context_data['workflow'].steps if isinstance(step, create_instance.SetInstanceDetails)][0] fields = set_instance_detail_step.action.fields self.assertTrue(len(fields['datastore'].choices), 1) text = 'mysql - 5.6' choice = fields['datastore'].choices[0] self.assertTrue(choice[0], common_utils.hexlify(text)) self.assertTrue(choice[1], text) advanced_step = [ step for step in res.context_data['workflow'].steps if isinstance(step, create_instance.Advanced) ][0] fields = advanced_step.action.fields self.assertTrue(len(fields['initial_state'].choices), 1) choice = fields['initial_state'].choices[0] self.assertTrue(choice[0], 'backup') self.assertTrue(choice[1], _('Restore from Backup'))
def test_check_identity_rule_not_found_true(self): policy.reset() value = policy.check((("identity", "i_dont_exist"),), request=self.request) # this should succeed because the default check for # identity is admin_required self.assertTrue(value)
def test_check_identity_rule_not_found_false(self): policy.reset() value = policy.check((("identity", "i_dont_exist"), ), request=self.request) # this should fail because the default check for # identity is admin_required self.assertFalse(value)
def get_rules(self, request): # Verify that the user attempting this is authorized to do so. if not verify.check((("identity", "identity:get_policy"), ), request): resp = HttpResponse() resp.status_code = 404 # 404 due to 401 foring system logout. return resp # Ensure that existing rules are up to date enforcer = generator._get_enforcer("keystone") enforcer.load_rules() # Create a dictionary of the existing rules current_rules_list = [ policy.RuleDefault(name, default.check_str) for name, default in enforcer.file_rules.items() ] registered_rules_list = [ policy.RuleDefault(name, default.check_str) for name, default in enforcer.registered_rules.items() if name not in enforcer.file_rules ] all_rules_dict = {'rules': current_rules_list + registered_rules_list} # Create a rules list rules = [] # Loop through all the rules and append them to the rules list for rule in generator._sort_and_format_by_section(all_rules_dict, include_help=False): rules.append(Policy().from_line(rule.rstrip()).to_json()) return rules
def check(actions, request, target=None): import inspect from horizon import Dashboard as dashboard frame = None try: # Get a caller frame frame = inspect.stack()[2][0] arginfo = inspect.getargvalues(frame) called_obj = arginfo.locals['self'] if 'self' in arginfo.locals else None # Check calld class is dashboard if called_obj and isinstance(called_obj, dashboard): roles = request.user.roles role_name_list = [role['name'] for role in request.user.roles] my_roles = set(role_name_list) admin_roles = set(OPENSTACK_KEYSTONE_ADMIN_ROLES) return 0 < len(my_roles & admin_roles) finally: if frame: del frame # Note(Itxaka): This is to prevent circular dependencies and apps not ready # If you do django imports in your settings, you are gonna have a bad time from openstack_auth import policy return policy.check(actions, request, target)
def set_rules(self, request): # Verify that the user attempting this is authorized to do so. if not verify.check( (("identity", "identity:modify_policy"), ), request): resp = HttpResponse() resp.status_code = 404 # 404 due to 401 foring system logout. return resp # Test the parsing of the new rules before proceeding for early failure new_rules = request.DATA for new_rule in new_rules: try: self.test_parsing(new_rule['rule']) except ValueError as e: resp = HttpResponse() resp.status_code = 400 resp.content = str(e) return resp # Ensure that existing rules are up to date enforcer = generator._get_enforcer("keystone") enforcer.load_rules() # Create a dict of the existing rules current_rules_list = [ policy.RuleDefault(name, default.check_str) for name, default in enforcer.file_rules.items() ] current_rules_dict = {'rules': current_rules_list} # Create a new rules dictionary new_rules_dict = dict() # Loop through the existing rules for rule in sorted(current_rules_dict.keys()): rule_defaults = current_rules_dict[rule] for rule_default in rule_defaults: # add the rules to the new rules dictionary new_rules_dict[rule_default.name] = rule_default.check_str # Loop through the new rules sent in the request for new_rule in new_rules: # Create an identifier using the rule's project and target new_rule_id = self.get_identifier(new_rule['project'], new_rule['target']) # Add/Update the new rule in the new rules dictionary new_rules_dict[new_rule_id] = new_rule['rule'] # Write the new rules dict to the policy file with open('/etc/keystone/policy.json', 'w') as policyfile: json.dump(new_rules_dict, policyfile, sort_keys=True, indent=4, separators=(',', ': ')) # Return 200 OK, everything went well. resp = HttpResponse() resp.status_code = 200 return resp
def test_compound_check_false(self): policy.reset() value = policy.check(( ("identity", "admin_required"), ("identity", "identity:default"), ), request=self.request) self.assertFalse(value)
def _gather_steps(self): ordered_step_classes = self._order_steps() for default_step in self.default_steps: self.register(default_step) self._registry[default_step] = default_step(self) self._ordered_steps = [] for step_class in ordered_step_classes: cls = self._registry[step_class] if (has_permissions(self.request.user, cls) and policy.check(cls.policy_rules, self.request)): self._ordered_steps.append(cls)
def get_rule(self, request, project, target): # Verify that the user attempting this is authorized to do so. if not verify.check((("identity", "identity:get_policy"), ), request): resp = HttpResponse() resp.status_code = 404 # 404 due to 401 foring system logout. return resp # Get the current rules from the policy file rules = self.get_rules(request) # Get the requested rule's identifier rule_id = self.get_identifier(project, target) # Prepare a response variable response = "" # Loop through the retrieved rules for rule in rules: # Find the requested rule by its identifier if rule_id in rule: # Set the found rule as the response response = Policy().from_line(rule.rstrip()).to_json() return response
def check(actions, request, target=None): # Note(Itxaka): This is to prevent circular dependencies and apps not ready # If you do django imports in your settings, you are gonna have a bad time from openstack_auth import policy return policy.check(actions, request, target=None)
def test_create_simple_instance_exception(self): policy.check((), IsA(http.HttpRequest)).MultipleTimes().AndReturn(True) trove_exception = self.exceptions.nova api.trove.datastore_flavors(IsA(http.HttpRequest), IsA(six.string_types), IsA(six.string_types)).\ MultipleTimes().AndReturn(self.flavors.list()) api.trove.backup_list(IsA(http.HttpRequest)).AndReturn( self.database_backups.list()) api.trove.instance_list(IsA(http.HttpRequest)).AndReturn( self.databases.list()) # Mock datastores api.trove.datastore_list(IsA(http.HttpRequest))\ .AndReturn(self.datastores.list()) # Mock datastore versions api.trove.datastore_version_list(IsA(http.HttpRequest), IsA(str))\ .MultipleTimes().AndReturn(self.datastore_versions.list()) dash_api.cinder.volume_type_list(IsA(http.HttpRequest)).AndReturn([]) dash_api.neutron.network_list(IsA(http.HttpRequest), tenant_id=self.tenant.id, shared=False).AndReturn( self.networks.list()[:1]) dash_api.neutron.network_list(IsA(http.HttpRequest), shared=True).AndReturn( self.networks.list()[1:]) nics = [{"net-id": self.networks.first().id, "v4-fixed-ip": ''}] datastore = 'mysql' datastore_version = '5.5' field_name = self._build_flavor_widget_name(datastore, datastore_version) dash_api.nova.availability_zone_list(IsA(http.HttpRequest)) \ .AndReturn(self.availability_zones.list()) # Actual create database call api.trove.instance_create( IsA(http.HttpRequest), IsA(six.text_type), IsA(int), IsA(six.text_type), databases=None, datastore=datastore, datastore_version=datastore_version, restore_point=None, replica_of=None, configuration=None, users=None, nics=nics, replica_count=None, volume_type=None, locality=None, availability_zone=IsA(six.text_type) ).AndRaise(trove_exception) self.mox.ReplayAll() post = { 'name': "MyDB", 'volume': '1', 'flavor': 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'datastore': field_name, field_name: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'network': self.networks.first().id, 'volume_type': 'no_type' } res = self.client.post(LAUNCH_URL, post) self.assertRedirectsNoFollow(res, INDEX_URL)
def test_check_nova_context_is_admin_false(self): policy.reset() value = policy.check((("compute", "context_is_admin"), ), request=self.request) self.assertFalse(value)
def test_scope_not_found(self): policy.reset() value = policy.check((("dummy", "default"), ), request=self.request) self.assertTrue(value)
def test_check_admin_required_true(self): policy.reset() value = policy.check((("identity", "admin_required"), ), request=self.request) self.assertTrue(value)
def test_compound_check_true(self): policy.reset() value = policy.check((("identity", "admin_required"), ("identity", "identity:default"),), request=self.request) self.assertTrue(value)
def test_check_nova_context_is_admin_true(self): policy.reset() value = policy.check((("compute", "context_is_admin"),), request=self.request) self.assertTrue(value)
def test_scope_not_found(self): policy.reset() value = policy.check((("dummy", "default"),), request=self.request) self.assertTrue(value)
def test_check_admin_required_false(self): policy.reset() value = policy.check((("identity", "admin_required"),), request=self.request) self.assertFalse(value)
def test_check_any_admin_required_true(self): policy.reset() value = policy.check((("identity", "admin_or_cloud_admin"),), request=self.request) self.assertTrue(value)
def test_check_domain_admin_required_true(self): policy.reset() value = policy.check(( ("identity", "admin_and_matching_domain_id"),), request=self.request) self.assertTrue(value)