def create(self, request, body=None): """Creates a new instance of the requested entity""" body = self._prepare_request_body(request.context, body, True, allow_bulk=True) action = "create_%s" % self._resource # Check authz try: if self._collection in body: # Have to account for bulk create for item in body[self._collection]: self._validate_network_tenant_ownership( request, item[self._resource], ) policy.enforce( request.context, action, item[self._resource], ) else: self._validate_network_tenant_ownership( request, body[self._resource] ) policy.enforce(request.context, action, body[self._resource]) except exceptions.PolicyNotAuthorized: raise webob.exc.HTTPForbidden() obj_creator = getattr(self._plugin, action) kwargs = {self._resource: body} obj = obj_creator(request.context, **kwargs) return {self._resource: self._view(obj)}
def index(self, request, **kwargs): plugin = manager.QuantumManager.get_plugin() policy.enforce(request.context, "get_%s" % L3_ROUTERS, {}, plugin=plugin) return plugin.list_routers_on_l3_agent(request.context, kwargs['agent_id'])
def delete(self, request, id, **kwargs): """Deletes the specified entity""" notifier_api.notify(request.context, self._publisher_id, self._resource + '.delete.start', notifier_api.INFO, {self._resource + '_id': id}) action = self._plugin_handlers[self.DELETE] # Check authz parent_id = kwargs.get(self._parent_id_name) obj = self._item(request, id, parent_id=parent_id) try: policy.enforce(request.context, action, obj, plugin=self._plugin) except exceptions.PolicyNotAuthorized: # To avoid giving away information, pretend that it # doesn't exist raise webob.exc.HTTPNotFound() obj_deleter = getattr(self._plugin, action) obj_deleter(request.context, id, **kwargs) notifier_api.notify(request.context, self._publisher_id, self._resource + '.delete.end', notifier_api.INFO, {self._resource + '_id': id})
def remove_router_interface(self, context, router_id, interface_info): # make sure router exists router = self._get_router(context, router_id) try: policy.enforce(context, "extension:router:remove_router_interface", self._make_router_dict(router)) except q_exc.PolicyNotAuthorized: raise l3.RouterNotFound(router_id=router_id) if not interface_info: msg = _("Either subnet_id or port_id must be specified") raise q_exc.BadRequest(resource="router", msg=msg) if "port_id" in interface_info: port_id = interface_info["port_id"] port_db = self._get_port(context, port_id) if not (port_db["device_owner"] == DEVICE_OWNER_ROUTER_INTF and port_db["device_id"] == router_id): raise l3.RouterInterfaceNotFound(router_id=router_id, port_id=port_id) if "subnet_id" in interface_info: port_subnet_id = port_db["fixed_ips"][0]["subnet_id"] if port_subnet_id != interface_info["subnet_id"]: raise q_exc.SubnetMismatchForPort(port_id=port_id, subnet_id=interface_info["subnet_id"]) subnet_id = port_db["fixed_ips"][0]["subnet_id"] self._confirm_router_interface_not_in_use(context, router_id, subnet_id) _network_id = port_db["network_id"] self.delete_port(context, port_db["id"], l3_port_check=False) elif "subnet_id" in interface_info: subnet_id = interface_info["subnet_id"] self._confirm_router_interface_not_in_use(context, router_id, subnet_id) subnet = self._get_subnet(context, subnet_id) found = False try: rport_qry = context.session.query(models_v2.Port) ports = rport_qry.filter_by( device_id=router_id, device_owner=DEVICE_OWNER_ROUTER_INTF, network_id=subnet["network_id"] ).all() for p in ports: if p["fixed_ips"][0]["subnet_id"] == subnet_id: port_id = p["id"] _network_id = p["network_id"] self.delete_port(context, p["id"], l3_port_check=False) found = True break except exc.NoResultFound: pass if not found: raise l3.RouterInterfaceNotFoundForSubnet(router_id=router_id, subnet_id=subnet_id) routers = self.get_sync_data(context.elevated(), [router_id]) l3_rpc_agent_api.L3AgentNotify.routers_updated( context, routers, "remove_router_interface", {"network_id": _network_id, "subnet_id": subnet_id} ) notifier_api.notify( context, notifier_api.publisher_id("network"), "router.interface.delete", notifier_api.CONF.default_notification_level, {"router.interface": {"port_id": port_id, "subnet_id": subnet_id}}, )
def delete(self, request, id, **kwargs): plugin = manager.QuantumManager.get_plugin() policy.enforce(request.context, "delete_%s" % L3_ROUTER, {}) return plugin.remove_router_from_l3_agent( request.context, kwargs['agent_id'], id)
def index(self, request, **kwargs): plugin = manager.QuantumManager.get_plugin() policy.enforce(request.context, "get_%s" % DHCP_AGENTS, {}) return plugin.list_dhcp_agents_hosting_network( request.context, kwargs['network_id'])
def index(self, request, **kwargs): plugin = manager.QuantumManager.get_plugin() policy.enforce(request.context, "get_%s" % L3_ROUTERS, {}) return plugin.list_routers_on_l3_agent( request.context, kwargs['agent_id'])
def delete(self, request, id): """Deletes the specified entity""" notifier_api.notify(request.context, self._publisher_id, self._resource + '.delete.start', notifier_api.INFO, {self._resource + '_id': id}) action = "delete_%s" % self._resource # Check authz obj = self._item(request, id) try: policy.enforce(request.context, action, obj, plugin=self._plugin) except exceptions.PolicyNotAuthorized: # To avoid giving away information, pretend that it # doesn't exist raise webob.exc.HTTPNotFound() obj_deleter = getattr(self._plugin, action) obj_deleter(request.context, id) notifier_api.notify(request.context, self._publisher_id, self._resource + '.delete.end', notifier_api.INFO, {self._resource + '_id': id})
def delete(self, request, id, **kwargs): plugin = manager.QuantumManager.get_plugin() policy.enforce(request.context, "delete_%s" % DHCP_NET, {}) return plugin.remove_network_from_dhcp_agent( request.context, kwargs['agent_id'], id)
def create(self, request, body, **kwargs): plugin = manager.QuantumManager.get_plugin() policy.enforce(request.context, "create_%s" % DHCP_NET, {}) return plugin.add_network_to_dhcp_agent( request.context, kwargs['agent_id'], body['network_id'])
def index(self, request, **kwargs): plugin = manager.QuantumManager.get_plugin() policy.enforce(request.context, "get_%s" % DHCP_NETS, {}) return plugin.list_networks_on_dhcp_agent( request.context, kwargs['agent_id'])
def create(self, request, body=None): """Creates a new instance of the requested entity""" body = self._prepare_request_body(request.context, body, True, allow_bulk=True) action = "create_%s" % self._resource # Check authz try: if self._collection in body: # Have to account for bulk create for item in body[self._collection]: policy.enforce(request.context, action, item[self._resource]) else: policy.enforce(request.context, action, body[self._resource]) except exceptions.PolicyNotAuthorized: raise webob.exc.HTTPForbidden() obj_creator = getattr(self._plugin, action) kwargs = {self._resource: body} obj = obj_creator(request.context, **kwargs) return {self._resource: self._view(obj)}
def update(self, request, id, body=None): """Updates the specified entity's attributes""" payload = body.copy() payload['id'] = id notifier_api.notify(request.context, self._publisher_id, self._resource + '.update.start', notifier_api.INFO, payload) body = self._prepare_request_body(request.context, body, False) action = "update_%s" % self._resource # Check authz orig_obj = self._item(request, id)[self._resource] try: policy.enforce(request.context, action, orig_obj) except exceptions.PolicyNotAuthorized: # To avoid giving away information, pretend that it # doesn't exist raise webob.exc.HTTPNotFound() obj_updater = getattr(self._plugin, action) kwargs = {self._resource: body} obj = obj_updater(request.context, id, **kwargs) result = {self._resource: self._view(obj)} notifier_api.notify(request.context, self._publisher_id, self._resource + '.update.end', notifier_api.INFO, result) return result
def delete(self, request, id, **kwargs): plugin = manager.QuantumManager.get_plugin() policy.enforce(request.context, "delete_%s" % DHCP_NET, {}, plugin=plugin) return plugin.remove_network_from_dhcp_agent(request.context, kwargs['agent_id'], id)
def index(self, request, **kwargs): plugin = manager.QuantumManager.get_plugin() policy.enforce(request.context, "get_%s" % L3_AGENTS, {}, plugin=plugin) return plugin.list_l3_agents_hosting_router(request.context, kwargs['router_id'])
def delete(self, request, id, **kwargs): plugin = manager.QuantumManager.get_plugin() policy.enforce(request.context, "delete_%s" % L3_ROUTER, {}, plugin=plugin) return plugin.remove_router_from_l3_agent(request.context, kwargs['agent_id'], id)
def index(self, request, **kwargs): plugin = manager.QuantumManager.get_plugin() policy.enforce(request.context, "get_%s" % DHCP_NETS, {}, plugin=plugin) return plugin.list_networks_on_dhcp_agent(request.context, kwargs['agent_id'])
def index(self, request, **kwargs): plugin = manager.QuantumManager.get_plugin() policy.enforce(request.context, "get_%s" % DHCP_AGENTS, {}, plugin=plugin) return plugin.list_dhcp_agents_hosting_network(request.context, kwargs['network_id'])
def index(self, request, **kwargs): plugin = manager.QuantumManager.get_plugin() policy.enforce(request.context, "get_%s" % L3_AGENTS, {}) return plugin.list_l3_agents_hosting_router( request.context, kwargs['router_id'])
def delete(self, request, id, **kwargs): """Deletes the specified entity.""" notifier_api.notify(request.context, self._publisher_id, self._resource + '.delete.start', notifier_api.CONF.default_notification_level, {self._resource + '_id': id}) action = self._plugin_handlers[self.DELETE] # Check authz parent_id = kwargs.get(self._parent_id_name) obj = self._item(request, id, parent_id=parent_id) try: policy.enforce(request.context, action, obj) except exceptions.PolicyNotAuthorized: # To avoid giving away information, pretend that it # doesn't exist raise webob.exc.HTTPNotFound() obj_deleter = getattr(self._plugin, action) obj_deleter(request.context, id, **kwargs) notifier_method = self._resource + '.delete.end' notifier_api.notify(request.context, self._publisher_id, notifier_method, notifier_api.CONF.default_notification_level, {self._resource + '_id': id}) result = {self._resource: self._view(request.context, obj)} self._send_dhcp_notification(request.context, result, notifier_method)
def delete(self, request, id, **kwargs): """Deletes the specified entity""" notifier_api.notify(request.context, self._publisher_id, self._resource + '.delete.start', notifier_api.CONF.default_notification_level, {self._resource + '_id': id}) action = self._plugin_handlers[self.DELETE] # Check authz parent_id = kwargs.get(self._parent_id_name) obj = self._item(request, id, parent_id=parent_id) try: policy.enforce(request.context, action, obj, plugin=self._plugin) except exceptions.PolicyNotAuthorized: # To avoid giving away information, pretend that it # doesn't exist raise webob.exc.HTTPNotFound() obj_deleter = getattr(self._plugin, action) obj_deleter(request.context, id, **kwargs) notifier_method = self._resource + '.delete.end' notifier_api.notify(request.context, self._publisher_id, notifier_method, notifier_api.CONF.default_notification_level, {self._resource + '_id': id}) result = {self._resource: self._view(obj)} self._send_dhcp_notification(request.context, result, notifier_method)
def test_templatized_enforcement(self): target_mine = {'tenant_id': 'fake'} target_not_mine = {'tenant_id': 'another'} action = "example:my_file" policy.enforce(self.context, action, target_mine) self.assertRaises(exceptions.PolicyNotAuthorized, policy.enforce, self.context, action, target_not_mine)
def delete(self, request, id): """Deletes the specified entity""" notifier_api.notify(request.context, self._publisher_id, self._resource + '.delete.start', notifier_api.INFO, {self._resource + '_id': id}) action = "delete_%s" % self._resource # Check authz obj = self._item(request, id)[self._resource] try: policy.enforce(request.context, action, obj) except exceptions.PolicyNotAuthorized: # To avoid giving away information, pretend that it # doesn't exist raise webob.exc.HTTPNotFound() obj_deleter = getattr(self._plugin, action) obj_deleter(request.context, id) notifier_api.notify(request.context, self._publisher_id, self._resource + '.delete.end', notifier_api.INFO, {self._resource + '_id': id})
def add_router_interface(self, context, router_id, interface_info): # make sure router exists router = self._get_router(context, router_id) if not interface_info: msg = "Either subnet_id or port_id must be specified" raise q_exc.BadRequest(resource='router', msg=msg) try: policy.enforce(context, "extension:router:add_router_interface", self._make_router_dict(router)) except q_exc.PolicyNotAuthorized: raise l3.RouterNotFound(router_id=router_id) if 'port_id' in interface_info: if 'subnet_id' in interface_info: msg = "cannot specify both subnet-id and port-id" raise q_exc.BadRequest(resource='router', msg=msg) port = self._get_port(context, interface_info['port_id']) if port['device_id']: raise q_exc.PortInUse(net_id=port['network_id'], port_id=port['id'], device_id=port['device_id']) fixed_ips = [ip for ip in port['fixed_ips']] if len(fixed_ips) != 1: msg = 'Router port must have exactly one fixed IP' raise q_exc.BadRequest(resource='router', msg=msg) self._check_for_dup_router_subnet(context, router_id, port['network_id'], fixed_ips[0]['subnet_id']) port.update({'device_id': router_id, 'device_owner': DEVICE_OWNER_ROUTER_INTF}) elif 'subnet_id' in interface_info: subnet_id = interface_info['subnet_id'] subnet = self._get_subnet(context, subnet_id) # Ensure the subnet has a gateway if not subnet['gateway_ip']: msg = 'Subnet for router interface must have a gateway IP' raise q_exc.BadRequest(resource='router', msg=msg) self._check_for_dup_router_subnet(context, router_id, subnet['network_id'], subnet_id) fixed_ip = {'ip_address': subnet['gateway_ip'], 'subnet_id': subnet['id']} port = self.create_port(context, { 'port': {'tenant_id': subnet['tenant_id'], 'network_id': subnet['network_id'], 'fixed_ips': [fixed_ip], 'mac_address': attributes.ATTR_NOT_SPECIFIED, 'admin_state_up': True, 'device_id': router_id, 'device_owner': DEVICE_OWNER_ROUTER_INTF, 'name': ''}}) routers = self.get_sync_data(context.elevated(), [router_id]) l3_rpc_agent_api.L3AgentNofity.routers_updated(context, routers) return {'port_id': port['id'], 'subnet_id': port['fixed_ips'][0]['subnet_id']}
def create(self, request, body, **kwargs): plugin = manager.QuantumManager.get_plugin() policy.enforce(request.context, "create_%s" % DHCP_NET, {}, plugin=plugin) return plugin.add_network_to_dhcp_agent(request.context, kwargs['agent_id'], body['network_id'])
def test_ignore_case_role_check(self): lowercase_action = "example:lowercase_admin" uppercase_action = "example:uppercase_admin" # NOTE(dprince) we mix case in the Admin role here to ensure # case is ignored admin_context = context.Context("admin", "fake", roles=["AdMiN"]) policy.enforce(admin_context, lowercase_action, self.target) policy.enforce(admin_context, uppercase_action, self.target)
def create(self, request, body, **kwargs): plugin = manager.QuantumManager.get_plugin() policy.enforce(request.context, "create_%s" % L3_ROUTER, {}, plugin=plugin) return plugin.add_router_to_l3_agent(request.context, kwargs['agent_id'], body['router_id'])
def test_ignore_case_role_check(self): lowercase_action = "example:lowercase_admin" uppercase_action = "example:uppercase_admin" # NOTE(dprince) we mix case in the Admin role here to ensure # case is ignored admin_context = context.Context('admin', 'fake', roles=['AdMiN']) policy.enforce(admin_context, lowercase_action, self.target) policy.enforce(admin_context, uppercase_action, self.target)
def remove_router_interface(self, context, router_id, interface_info): # make sure router exists router = self._get_router(context, router_id) try: policy.enforce(context, "extension:router:remove_router_interface", self._make_router_dict(router)) except q_exc.PolicyNotAuthorized: raise l3.RouterNotFound(router_id=router_id) if not interface_info: msg = "Either subnet_id or port_id must be specified" raise q_exc.BadRequest(resource='router', msg=msg) if 'port_id' in interface_info: port_id = interface_info['port_id'] port_db = self._get_port(context, port_id) if not (port_db['device_owner'] == DEVICE_OWNER_ROUTER_INTF and port_db['device_id'] == router_id): raise l3.RouterInterfaceNotFound(router_id=router_id, port_id=port_id) if 'subnet_id' in interface_info: port_subnet_id = port_db['fixed_ips'][0]['subnet_id'] if port_subnet_id != interface_info['subnet_id']: raise q_exc.SubnetMismatchForPort( port_id=port_id, subnet_id=interface_info['subnet_id']) self._confirm_router_interface_not_in_use( context, router_id, port_db['fixed_ips'][0]['subnet_id']) self.delete_port(context, port_db['id'], l3_port_check=False) elif 'subnet_id' in interface_info: subnet_id = interface_info['subnet_id'] self._confirm_router_interface_not_in_use(context, router_id, subnet_id) subnet = self._get_subnet(context, subnet_id) found = False try: rport_qry = context.session.query(models_v2.Port) ports = rport_qry.filter_by( device_id=router_id, device_owner=DEVICE_OWNER_ROUTER_INTF, network_id=subnet['network_id']).all() for p in ports: if p['fixed_ips'][0]['subnet_id'] == subnet_id: self.delete_port(context, p['id'], l3_port_check=False) found = True break except exc.NoResultFound: pass if not found: raise l3.RouterInterfaceNotFoundForSubnet(router_id=router_id, subnet_id=subnet_id) routers = self.get_sync_data(context.elevated(), [router_id]) l3_rpc_agent_api.L3AgentNofity.routers_updated(context, routers)
def add_router_interface(self, context, router_id, interface_info): # make sure router exists router = self._get_router(context, router_id) if not interface_info: msg = "Either subnet_id or port_id must be specified" raise q_exc.BadRequest(resource='router', msg=msg) try: policy.enforce(context, "extension:router:add_router_interface", self._make_router_dict(router)) except q_exc.PolicyNotAuthorized: raise l3.RouterNotFound(router_id=router_id) if 'port_id' in interface_info: if 'subnet_id' in interface_info: msg = "cannot specify both subnet-id and port-id" raise q_exc.BadRequest(resource='router', msg=msg) port = self._get_port(context, interface_info['port_id']) if port['device_id']: raise q_exc.PortInUse(net_id=port['network_id'], port_id=port['id'], device_id=port['device_id']) fixed_ips = [ip for ip in port['fixed_ips']] if len(fixed_ips) != 1: msg = 'Router port must have exactly one fixed IP' raise q_exc.BadRequest(resource='router', msg=msg) self._check_for_dup_router_subnet(context, router_id, port['network_id'], fixed_ips[0]['subnet_id']) with context.session.begin(subtransactions=True): port.update({'device_id': router_id, 'device_owner': DEVICE_OWNER_ROUTER_INTF}) elif 'subnet_id' in interface_info: subnet_id = interface_info['subnet_id'] subnet = self._get_subnet(context, subnet_id) # Ensure the subnet has a gateway if not subnet['gateway_ip']: msg = 'Subnet for router interface must have a gateway IP' raise q_exc.BadRequest(resource='router', msg=msg) self._check_for_dup_router_subnet(context, router_id, subnet['network_id'], subnet_id) fixed_ip = {'ip_address': subnet['gateway_ip'], 'subnet_id': subnet['id']} port = self.create_port(context, { 'port': {'tenant_id': subnet['tenant_id'], 'network_id': subnet['network_id'], 'fixed_ips': [fixed_ip], 'mac_address': attributes.ATTR_NOT_SPECIFIED, 'admin_state_up': True, 'device_id': router_id, 'device_owner': DEVICE_OWNER_ROUTER_INTF, 'name': ''}}) return {'port_id': port['id'], 'subnet_id': port['fixed_ips'][0]['subnet_id']}
def create(self, request, body, **kwargs): plugin = manager.QuantumManager.get_plugin() policy.enforce(request.context, "create_%s" % L3_ROUTER, {}) return plugin.add_router_to_l3_agent( request.context, kwargs['agent_id'], body['router_id'])
def update(self, request, id, body=None, **kwargs): """Updates the specified entity's attributes""" parent_id = kwargs.get(self._parent_id_name) try: payload = body.copy() except AttributeError: msg = _("Invalid format: %s") % request.body raise exceptions.BadRequest(resource='body', msg=msg) payload['id'] = id notifier_api.notify(request.context, self._publisher_id, self._resource + '.update.start', notifier_api.CONF.default_notification_level, payload) body = Controller.prepare_request_body(request.context, body, False, self._resource, self._attr_info, allow_bulk=self._allow_bulk) action = self._plugin_handlers[self.UPDATE] # Load object to check authz # but pass only attributes in the original body and required # by the policy engine to the policy 'brain' field_list = [ name for (name, value) in self._attr_info.iteritems() if ('required_by_policy' in value and value['required_by_policy'] or 'default' not in value) ] orig_obj = self._item(request, id, field_list=field_list, parent_id=parent_id) orig_obj.update(body[self._resource]) try: policy.enforce(request.context, action, orig_obj, plugin=self._plugin) except exceptions.PolicyNotAuthorized: # To avoid giving away information, pretend that it # doesn't exist raise webob.exc.HTTPNotFound() obj_updater = getattr(self._plugin, action) kwargs = {self._resource: body} if parent_id: kwargs[self._parent_id_name] = parent_id obj = obj_updater(request.context, id, **kwargs) result = {self._resource: self._view(obj)} notifier_method = self._resource + '.update.end' notifier_api.notify(request.context, self._publisher_id, notifier_method, notifier_api.CONF.default_notification_level, result) self._send_dhcp_notification(request.context, result, notifier_method) return result
def remove_router_interface(self, context, router_id, interface_info): # make sure router exists router = self._get_router(context, router_id) try: policy.enforce(context, "extension:router:remove_router_interface", self._make_router_dict(router)) except q_exc.PolicyNotAuthorized: raise l3.RouterNotFound(router_id=router_id) if not interface_info: msg = "Either subnet_id or port_id must be specified" raise q_exc.BadRequest(resource='router', msg=msg) if 'port_id' in interface_info: port_id = interface_info['port_id'] port_db = self._get_port(context, port_id) if not (port_db['device_owner'] == DEVICE_OWNER_ROUTER_INTF and port_db['device_id'] == router_id): raise w_exc.HTTPNotFound("Router %(router_id)s does not have " " an interface with id %(port_id)s" % locals()) if 'subnet_id' in interface_info: port_subnet_id = port_db['fixed_ips'][0]['subnet_id'] if port_subnet_id != interface_info['subnet_id']: raise w_exc.HTTPConflict("subnet_id %s on port does not " "match requested one (%s)" % (port_subnet_id, interface_info['subnet_id'])) if port_db['device_id'] != router_id: raise w_exc.HTTPConflict("port_id %s not used by router" % port_db['id']) self.delete_port(context, port_db['id'], l3_port_check=False) elif 'subnet_id' in interface_info: subnet_id = interface_info['subnet_id'] subnet = self._get_subnet(context, subnet_id) found = False try: rport_qry = context.session.query(models_v2.Port) ports = rport_qry.filter_by( device_id=router_id, device_owner=DEVICE_OWNER_ROUTER_INTF, network_id=subnet['network_id']).all() for p in ports: if p['fixed_ips'][0]['subnet_id'] == subnet_id: self.delete_port(context, p['id'], l3_port_check=False) found = True break except exc.NoResultFound: pass if not found: raise w_exc.HTTPNotFound("Router %(router_id)s has no " "interface on subnet %(subnet_id)s" % locals())
def create(self, request, body=None): """Creates a new instance of the requested entity""" notifier_api.notify(request.context, self._publisher_id, self._resource + '.create.start', notifier_api.INFO, body) body = self._prepare_request_body(request.context, body, True, allow_bulk=True) action = "create_%s" % self._resource # Check authz try: if self._collection in body: # Have to account for bulk create for item in body[self._collection]: self._validate_network_tenant_ownership( request, item[self._resource], ) policy.enforce( request.context, action, item[self._resource], ) count = QUOTAS.count(request.context, self._resource, self._plugin, self._collection, item[self._resource]['tenant_id']) kwargs = {self._resource: count + 1} QUOTAS.limit_check(request.context, **kwargs) else: self._validate_network_tenant_ownership( request, body[self._resource] ) policy.enforce(request.context, action, body[self._resource]) count = QUOTAS.count(request.context, self._resource, self._plugin, self._collection, body[self._resource]['tenant_id']) kwargs = {self._resource: count + 1} QUOTAS.limit_check(request.context, **kwargs) except exceptions.PolicyNotAuthorized: raise webob.exc.HTTPForbidden() obj_creator = getattr(self._plugin, action) kwargs = {self._resource: body} obj = obj_creator(request.context, **kwargs) result = {self._resource: self._view(obj)} notifier_api.notify(request.context, self._publisher_id, self._resource + '.create.end', notifier_api.INFO, result) return result
def update(self, request, id, body=None, **kwargs): """Updates the specified entity's attributes.""" parent_id = kwargs.get(self._parent_id_name) try: payload = body.copy() except AttributeError: msg = _("Invalid format: %s") % request.body raise exceptions.BadRequest(resource='body', msg=msg) payload['id'] = id notifier_api.notify(request.context, self._publisher_id, self._resource + '.update.start', notifier_api.CONF.default_notification_level, payload) body = Controller.prepare_request_body(request.context, body, False, self._resource, self._attr_info, allow_bulk=self._allow_bulk) action = self._plugin_handlers[self.UPDATE] # Load object to check authz # but pass only attributes in the original body and required # by the policy engine to the policy 'brain' field_list = [name for (name, value) in self._attr_info.iteritems() if ('required_by_policy' in value and value['required_by_policy'] or 'default' not in value)] orig_obj = self._item(request, id, field_list=field_list, parent_id=parent_id) orig_obj.update(body[self._resource]) try: policy.enforce(request.context, action, orig_obj, plugin=self._plugin) except exceptions.PolicyNotAuthorized: # To avoid giving away information, pretend that it # doesn't exist raise webob.exc.HTTPNotFound() obj_updater = getattr(self._plugin, action) kwargs = {self._resource: body} if parent_id: kwargs[self._parent_id_name] = parent_id obj = obj_updater(request.context, id, **kwargs) result = {self._resource: self._view(request.context, obj)} notifier_method = self._resource + '.update.end' notifier_api.notify(request.context, self._publisher_id, notifier_method, notifier_api.CONF.default_notification_level, result) self._send_dhcp_notification(request.context, result, notifier_method) return result
def _item(self, request, id, do_authz=False, field_list=None): """Retrieves and formats a single element of the requested entity""" kwargs = {'fields': field_list} action = "get_%s" % self._resource obj_getter = getattr(self._plugin, action) obj = obj_getter(request.context, id, **kwargs) # Check authz # FIXME(salvatore-orlando): obj_getter might return references to # other resources. Must check authZ on them too. if do_authz: policy.enforce(request.context, action, obj, plugin=self._plugin) return obj
def _item(self, request, id, do_authz=False): """Retrieves and formats a single element of the requested entity""" kwargs = {"verbose": verbose(request), "fields": fields(request)} action = "get_%s" % self._resource obj_getter = getattr(self._plugin, action) obj = obj_getter(request.context, id, **kwargs) # Check authz if do_authz: policy.enforce(request.context, action, obj) return {self._resource: self._view(obj)}
def _item(self, request, id, do_authz=False): """Retrieves and formats a single element of the requested entity""" kwargs = {'verbose': verbose(request), 'fields': fields(request)} action = "get_%s" % self._resource obj_getter = getattr(self._plugin, action) obj = obj_getter(request.context, id, **kwargs) # Check authz if do_authz: policy.enforce(request.context, action, obj) return {self._resource: self._view(obj)}
def delete(self, request, id): """Deletes the specified entity""" action = "delete_%s" % self._resource # Check authz obj = self._item(request, id) try: policy.enforce(request.context, action, obj) except exceptions.PolicyNotAuthorized: # To avoid giving away information, pretend that it # doesn't exist raise webob.exc.HTTPNotFound() obj_deleter = getattr(self._plugin, action) obj_deleter(request.context, id)
def delete(self, request, id): """Deletes the specified entity""" action = "delete_%s" % self._resource # Check authz obj = self._item(request, id)[self._resource] try: policy.enforce(request.context, action, obj) except exceptions.PolicyNotAuthorized: # To avoid giving away information, pretend that it # doesn't exist raise webob.exc.HTTPNotFound() obj_deleter = getattr(self._plugin, action) obj_deleter(request.context, id)
def test_nonadmin_read_on_shared_returns_200(self): action = "get_network" user_context = context.Context('', "user", roles=['user']) # 420 is the int value of the bitmask for rw-r--r-- target = {'tenant_id': 'the_owner', 'shared': True} result = policy.enforce(user_context, action, target, None) self.assertEqual(result, None)
def test_modified_policy_reloads(self): def fake_find_config_file(_1, _2): return self.tempdir.join("policy") with mock.patch.object(quantum.common.utils, "find_config_file", new=fake_find_config_file): tmpfilename = fake_find_config_file(None, None) action = "example:test" with open(tmpfilename, "w") as policyfile: policyfile.write("""{"example:test": ""}""") policy.enforce(self.context, action, self.target) with open(tmpfilename, "w") as policyfile: policyfile.write("""{"example:test": "!"}""") # NOTE(vish): reset stored policy cache so we don't have to # sleep(1) policy._POLICY_CACHE = {} self.assertRaises(exceptions.PolicyNotAuthorized, policy.enforce, self.context, action, self.target)
def _item(self, request, id, do_authz=False): """Retrieves and formats a single element of the requested entity""" # NOTE(salvatore-orlando): The following ensures that fields which # are needed for authZ policy validation are not stripped away by the # plugin before returning. field_list, added_fields = self._do_field_list(fields(request)) kwargs = {'verbose': verbose(request), 'fields': field_list} action = "get_%s" % self._resource obj_getter = getattr(self._plugin, action) obj = obj_getter(request.context, id, **kwargs) # Check authz if do_authz: policy.enforce(request.context, action, obj) return {self._resource: self._view(obj, fields_to_strip=added_fields)}
def _test_action_on_attr(self, context, action, attr, value, exception=None): action = "%s_network" % action target = {"tenant_id": "the_owner", attr: value} if exception: self.assertRaises(exception, policy.enforce, context, action, target, None) else: result = policy.enforce(context, action, target, None) self.assertEqual(result, True)
def delete_site_from_user(self,context,id,body,**kwargs): #return None action = "users:delete_site_from_user" try: if policy.enforce(context, action, body['user']) == False: raise webob.exc.HTTPNotFound() except exceptions.PolicyNotAuthorized: raise webob.exc.HTTPNotFound() return super(HuaWeiQuantumPlugin,self).release_site_from_tenant(context,id,body,**kwargs)
def update(self, request, id, body=None): """Updates the specified entity's attributes""" body = self._prepare_request_body(request.context, body, False) action = "update_%s" % self._resource # Check authz orig_obj = self._item(request, id) try: policy.enforce(request.context, action, orig_obj) except exceptions.PolicyNotAuthorized: # To avoid giving away information, pretend that it # doesn't exist raise webob.exc.HTTPNotFound() obj_updater = getattr(self._plugin, action) kwargs = {self._resource: body} obj = obj_updater(request.context, id, **kwargs) return {self._resource: self._view(obj)}
def test_enforce_parentresource_owner(self): def fakegetnetwork(*args, **kwargs): return {'tenant_id': 'fake'} action = "create_port:mac" with mock.patch.object(self.plugin, 'get_network', new=fakegetnetwork): target = {'network_id': 'whatever'} result = policy.enforce(self.context, action, target, self.plugin) self.assertTrue(result)
def test_enforce_http_true(self): def fakeurlopen(url, post_data): return StringIO.StringIO("True") with mock.patch.object(urllib2, 'urlopen', new=fakeurlopen): action = "example:get_http" target = {} result = policy.enforce(self.context, action, target) self.assertEqual(result, True)
def _handle_action(request, id, **kwargs): arg_list = [request.context, id] # Fetch the resource and verify if the user can access it try: resource = self._item(request, id, True) except exceptions.PolicyNotAuthorized: raise webob.exc.HTTPNotFound() body = kwargs.pop('body', None) # Explicit comparison with None to distinguish from {} if body is not None: arg_list.append(body) # TODO(salvatore-orlando): bp/make-authz-ortogonal # The body of the action request should be included # in the info passed to the policy engine # It is ok to raise a 403 because accessibility to the # object was checked earlier in this method policy.enforce(request.context, name, resource) return getattr(self._plugin, name)(*arg_list, **kwargs)
def test_enforce_parentresource_owner(self): def fakegetnetwork(*args, **kwargs): return {"tenant_id": "fake"} action = "create_port:mac" with mock.patch.object(self.plugin, "get_network", new=fakegetnetwork): target = {"network_id": "whatever"} result = policy.enforce(self.context, action, target, self.plugin) self.assertTrue(result)
def _test_action_on_attr(self, context, action, attr, value, exception=None): action = "%s_network" % action target = {'tenant_id': 'the_owner', attr: value} if exception: self.assertRaises(exception, policy.enforce, context, action, target, None) else: result = policy.enforce(context, action, target, None) self.assertEqual(result, True)
def update(self, request, id, body=None): """Updates the specified entity's attributes""" payload = body.copy() payload['id'] = id notifier_api.notify(request.context, self._publisher_id, self._resource + '.update.start', notifier_api.INFO, payload) body = Controller.prepare_request_body(request.context, body, False, self._resource, self._attr_info, allow_bulk=self._allow_bulk) action = "update_%s" % self._resource # Load object to check authz # but pass only attributes in the original body and required # by the policy engine to the policy 'brain' field_list = [ name for (name, value) in self._attr_info.iteritems() if ('required_by_policy' in value and value['required_by_policy'] or not 'default' in value) ] orig_obj = self._item(request, id, field_list=field_list) orig_obj.update(body) try: policy.enforce(request.context, action, orig_obj, plugin=self._plugin) except exceptions.PolicyNotAuthorized: # To avoid giving away information, pretend that it # doesn't exist raise webob.exc.HTTPNotFound() obj_updater = getattr(self._plugin, action) kwargs = {self._resource: body} obj = obj_updater(request.context, id, **kwargs) result = {self._resource: self._view(obj)} notifier_api.notify(request.context, self._publisher_id, self._resource + '.update.end', notifier_api.INFO, result) return result
def test_modified_policy_reloads(self): def fake_find_config_file(_1, _2): return self.tempdir.join('policy') with mock.patch.object(quantum.common.utils, 'find_config_file', new=fake_find_config_file): tmpfilename = fake_find_config_file(None, None) action = "example:test" with open(tmpfilename, "w") as policyfile: policyfile.write("""{"example:test": ""}""") policy.enforce(self.context, action, self.target) with open(tmpfilename, "w") as policyfile: policyfile.write("""{"example:test": "!"}""") # NOTE(vish): reset stored policy cache so we don't have to # sleep(1) policy._POLICY_CACHE = {} self.assertRaises(exceptions.PolicyNotAuthorized, policy.enforce, self.context, action, self.target)
def test_enforce_tenant_id_check_parent_resource(self): def fakegetnetwork(*args, **kwargs): return {'tenant_id': 'fake'} action = "create_port:mac" with mock.patch.object(manager.QuantumManager.get_instance().plugin, 'get_network', new=fakegetnetwork): target = {'network_id': 'whatever'} result = policy.enforce(self.context, action, target) self.assertTrue(result)
def test_enforce_tenant_id_check_parent_resource_bw_compatibility(self): def fakegetnetwork(*args, **kwargs): return {'tenant_id': 'fake'} del self.rules['admin_or_network_owner'] self.rules['admin_or_network_owner'] = common_policy.parse_rule( "role:admin or tenant_id:%(network_tenant_id)s") action = "create_port:mac" with mock.patch.object(manager.QuantumManager.get_instance().plugin, 'get_network', new=fakegetnetwork): target = {'network_id': 'whatever'} result = policy.enforce(self.context, action, target) self.assertTrue(result)