def test_non_admin_cannot_add_provider_sg_rule(self): provider_secgroup = self._create_provider_security_group() pvd_sg_id = provider_secgroup['security_group']['id'] data = {'security_group_rule': {'security_group_id': pvd_sg_id, 'direction': 'ingress', 'protocol': 'tcp', 'ethertype': 'IPv4', 'tenant_id': self._tenant_id}} req = self.new_create_request( 'security-group-rules', data) req.environ['neutron.context'] = context.Context('', self._tenant_id) res = req.get_response(self.ext_api) self.assertEqual(webob.exc.HTTPForbidden.code, res.status_int)
def test_show_quotas_with_admin(self): project_id = 'project_id1' env = { 'neutron.context': context.Context('', project_id + '2', is_admin=True) } res = self.api.get(_get_path('quotas', id=project_id, fmt=self.fmt), extra_environ=env) self.assertEqual(200, res.status_int) quota = self.deserialize(res) self.assertEqual(qconf.DEFAULT_QUOTA_NETWORK, quota['quota']['network']) self.assertEqual(qconf.DEFAULT_QUOTA_SUBNET, quota['quota']['subnet']) self.assertEqual(qconf.DEFAULT_QUOTA_PORT, quota['quota']['port'])
def _create_address_group(self, **kwargs): address_group = {'address_group': {}} for k, v in kwargs.items(): if k != 'addresses': v = str(v) address_group['address_group'][k] = v req = self.new_create_request('address-groups', address_group) neutron_context = context.Context( '', kwargs.get('tenant_id', self._tenant_id)) req.environ['neutron.context'] = neutron_context res = req.get_response(self.ext_api) if res.status_int >= webob.exc.HTTPClientError.code: raise webob.exc.HTTPClientError(code=res.status_int) return res
def test_proper_load_order(self): """ Verifies that loading policies by way of admin context after populating extensions and extending the resource map results in networks with router:external are visible to regular tenants. """ policy.reset() extension_manager = extensions.ExtensionManager(self.extension_path) extension_manager.extend_resources(self.api_version, attributes.RESOURCES) policy.init() admin_context = context.get_admin_context() tenant_context = context.Context('test_user', 'test_tenant_id', False) self.assertTrue(self._check_external_router_policy(admin_context)) self.assertTrue(self._check_external_router_policy(tenant_context))
def test_neutron_context_create(self): ctx = context.Context('user_id', 'tenant_id') self.assertEqual('user_id', ctx.user_id) self.assertEqual('tenant_id', ctx.project_id) self.assertEqual('tenant_id', ctx.tenant_id) request_id = ctx.request_id if isinstance(request_id, bytes): request_id = request_id.decode('utf-8') self.assertThat(request_id, matchers.StartsWith('req-')) self.assertEqual('user_id', ctx.user) self.assertEqual('tenant_id', ctx.tenant) self.assertIsNone(ctx.user_name) self.assertIsNone(ctx.tenant_name) self.assertIsNone(ctx.project_name) self.assertIsNone(ctx.auth_token)
def test_premature_loading(self): """Test premature policy loading Verifies that loading policies by way of admin context before populating extensions and extending the resource map results in networks with router:external is true being invisible to regular tenants. """ extension_manager = extensions.ExtensionManager(self.extension_path) admin_context = context.get_admin_context() tenant_context = context.Context('test_user', 'test_tenant_id', False) extension_manager.extend_resources(self.api_version, attributes.RESOURCES) self.assertTrue(self._check_external_router_policy(admin_context)) self.assertFalse(self._check_external_router_policy(tenant_context))
def test_non_admin_cannot_delete_provider_sg_and_admin_can(self): provider_secgroup = self._create_provider_security_group() pvd_sg_id = provider_secgroup['security_group']['id'] # Try deleting the request as the normal tenant returns forbidden # as a tenant is not allowed to delete this. ctx = context.Context('', self._tenant_id) self._delete('security-groups', pvd_sg_id, expected_code=webob.exc.HTTPForbidden.code, neutron_context=ctx) # can be deleted though as admin self._delete('security-groups', pvd_sg_id, expected_code=webob.exc.HTTPNoContent.code)
def setUp(self, plugin=None): if not plugin: plugin = ('neutron.tests.unit.extensions.test_floatingip_pools.' 'TestFloatingIPPoolsIntPlugin') # for these tests we need to enable overlapping ips cfg.CONF.set_default('allow_overlapping_ips', True) cfg.CONF.set_default('max_routes', 3) ext_mgr = FloatingIPPoolsTestExtensionManager() super(test_l3.L3BaseForIntTests, self).setUp( plugin=plugin, ext_mgr=ext_mgr) self.setup_notification_driver() self.ctxt = context.Context('fake_user', 'fake_tenant') self.admin_ctxt = self.ctxt.elevated()
def test_delete_quotas_with_admin(self): project_id = 'project_id1' env = { 'neutron.context': context.Context('', project_id + '2', is_admin=True) } # Create a quota to ensure we have something to delete quotas = {'quota': {'network': 100}} self.api.put(_get_path('quotas', id=project_id, fmt=self.fmt), self.serialize(quotas), extra_environ=env) res = self.api.delete(_get_path('quotas', id=project_id, fmt=self.fmt), extra_environ=env) self.assertEqual(204, res.status_int)
def get_instances_with_cached_ips(project_id='fake', user_id='fake'): """Kludge the cache into instance(s) without having to create DB entries """ user_id = user_id project_id = project_id no_context = nova_context.RequestContext(user_id, project_id, is_admin=True) ne_context = neutron_context.Context(user_id, project_id, is_admin=True) def _info_cache_for(instance, ip): info_cache = dict(test_instance_info_cache.fake_info_cache, network_info=_get_fake_cache(ip), instance_uuid=instance['uuid']) if isinstance(instance, obj_base.NovaObject): _info_cache = objects.InstanceInfoCache(no_context) objects.InstanceInfoCache._from_db_object(no_context, _info_cache, info_cache) info_cache = _info_cache instance['info_cache'] = info_cache instances = [] ports = [] tradeoff = int(parsed_args.trade_off) * 4 runtime = int(parsed_args.runtime) for m in xrange(0, runtime): for j in xrange(0 + tradeoff, 4 + tradeoff): ip_str = '192.168.' + str(j) + '.' for i in xrange(1, 251): ip = ip_str + str(i) name_str = 'perfomance_test_' + str(i) updates = { 'id': i + 250 * j * m, 'name': name_str, 'project_id': project_id, 'user_id': user_id } instance = fake_instance_obj(no_context, **updates) _info_cache_for(instance, ip) instances.append(instance) port = _create_port(ne_context, instance.uuid, ip_address=ip) ports.append(port) return instances, ports
def _create_local_ip(self, **kwargs): kwargs.setdefault('project_id', self._tenant_id) local_ip = {'local_ip': {}} for k, v in kwargs.items(): local_ip['local_ip'][k] = v req = self.new_create_request('local-ips', local_ip) neutron_context = context.Context('', kwargs.get('project_id', self._tenant_id), is_admin=True) req.environ['neutron.context'] = neutron_context res = req.get_response(self.ext_api) if res.status_int >= webob.exc.HTTPClientError.code: raise webob.exc.HTTPClientError(code=res.status_int) return self.deserialize(self.fmt, res)
def test_update_firewall_group_with_port_on_different_project(self): ctx = context.Context('not_admin', 'fake_project_id_1') with self.firewall_group(ctx=ctx) as firewall_group: with self.port(tenant_id='fake_project_id_2') as port: data = { 'firewall_group': { 'ports': [port['port']['id']], }, } req = self.new_update_request( 'firewall_groups', data, firewall_group['firewall_group']['id'], ) res = req.get_response(self.ext_api) self.assertEqual(webob.exc.HTTPConflict.code, res.status_int)
def test_req_context_header(self): sp = directory.get_plugin().servers ncontext = context.Context('uid', 'tid') sp.set_context(ncontext) with mock.patch(HTTPCON) as conmock: rv = conmock.return_value rv.getresponse.return_value.getheader.return_value = 'HASHHEADER' sp.rest_action('GET', '/') callheaders = rv.request.mock_calls[0][1][3] self.assertIn(servermanager.REQ_CONTEXT_HEADER, callheaders) ctxdct = ncontext.to_dict() # auth token is not included ctxdct.pop('auth_token') self.assertEqual( ctxdct, jsonutils.loads(callheaders[servermanager.REQ_CONTEXT_HEADER]))
def setUp(self): super(NetworkRBACTestCase, self).setUp() cfg.CONF.set_override('notify_nova_on_port_status_changes', False) DB_PLUGIN_KLASS = 'neutron.plugins.ml2.plugin.Ml2Plugin' self.setup_coreplugin(DB_PLUGIN_KLASS) self.plugin = ml2_plugin.Ml2Plugin() self.cxt = context.Context(user_id=None, tenant_id=None, is_admin=True, overwrite=False) self.tenant_1 = uuidutils.generate_uuid() self.tenant_2 = uuidutils.generate_uuid() self.network_id = uuidutils.generate_uuid() self.subnet_1_id = uuidutils.generate_uuid() self.subnet_2_id = uuidutils.generate_uuid() self.port_id = uuidutils.generate_uuid()
def test_show_default_quotas_with_owner_tenant(self): tenant_id = 'tenant_id1' env = { 'neutron.context': context.Context('', tenant_id, is_admin=False) } res = self.api.get(_get_path('quotas', id=tenant_id, action=DEFAULT_QUOTAS_ACTION, fmt=self.fmt), extra_environ=env) self.assertEqual(200, res.status_int) quota = self.deserialize(res) self.assertEqual(qconf.DEFAULT_QUOTA_NETWORK, quota['quota']['network']) self.assertEqual(qconf.DEFAULT_QUOTA_SUBNET, quota['quota']['subnet']) self.assertEqual(qconf.DEFAULT_QUOTA_PORT, quota['quota']['port'])
def test_update_port_security_off_shared_network(self): with self.network(shared=True) as net: with self.subnet(network=net): res = self._create_port('json', net['network']['id'], tenant_id='not_network_owner', set_context=True) port = self.deserialize('json', res) # remove security group on port update_port = {'port': {ext_sg.SECURITYGROUPS: None, psec.PORTSECURITY: False}} req = self.new_update_request('ports', update_port, port['port']['id']) req.environ['neutron.context'] = context.Context( '', 'not_network_owner') res = req.get_response(self.api) self.assertEqual(exc.HTTPForbidden.code, res.status_int)
def setUp(self): super(NeutronPolicyTestCase, self).setUp() # Add Fake resources to RESOURCE_ATTRIBUTE_MAP attributes.RESOURCES.update(FAKE_RESOURCES) self._set_rules() self.patcher = mock.patch.object(neutron.policy, 'init', new=self.fakepolicyinit) self.patcher.start() policy.refresh() self.addCleanup(policy.refresh) self.context = context.Context('fake', 'fake', roles=['user']) plugin_klass = importutils.import_class( "neutron.db.db_base_plugin_v2.NeutronDbPluginV2") directory.add_plugin(plugin_constants.CORE, plugin_klass())
def _create_metering_label(self, fmt, name, description, **kwargs): data = {'metering_label': {'name': name, 'tenant_id': kwargs.get('tenant_id', 'test-tenant'), 'shared': kwargs.get('shared', False), 'description': description}} req = self.new_create_request('metering-labels', data, fmt) if kwargs.get('set_context') and 'tenant_id' in kwargs: # create a specific auth context for this request req.environ['neutron.context'] = ( context.Context('', kwargs['tenant_id'], is_admin=kwargs.get('is_admin', True))) return req.get_response(self.ext_api)
def setUp(self): super(IpamTestCase, self).setUp() cfg.CONF.set_override('notify_nova_on_port_status_changes', False) DB_PLUGIN_KLASS = 'neutron.db.db_base_plugin_v2.NeutronDbPluginV2' self.setup_coreplugin(DB_PLUGIN_KLASS) self.plugin = base_plugin.NeutronDbPluginV2() self.cxt = context.Context(user_id=None, tenant_id=None, is_admin=True, overwrite=False) self.tenant_id = uuidutils.generate_uuid() self.network_id = uuidutils.generate_uuid() self.subnet_id = uuidutils.generate_uuid() self.port_id = uuidutils.generate_uuid() self._create_network() self._create_subnet()
def _test_update_address_group(self, addr_group_id, data, expected=None, tenant_id=None): update_req = self.new_update_request('address-groups', data, addr_group_id) update_req.environ['neutron.context'] = context.Context( '', tenant_id or self._tenant_id) update_res = update_req.get_response(self.ext_api) if expected: addr_group = self.deserialize(self.fmt, update_res) self._compare_resource(addr_group, expected, 'address_group') return addr_group return update_res
def test_list_availability_zones(self): self._register_azs() helpers.set_agent_admin_state(self.agent3['id'], admin_state_up=False) helpers.set_agent_admin_state(self.agent4['id'], admin_state_up=False) expected = [ {'name': 'nova1', 'resource': 'network', 'state': 'available'}, {'name': 'nova2', 'resource': 'network', 'state': 'available'}, {'name': 'nova2', 'resource': 'router', 'state': 'available'}, {'name': 'nova3', 'resource': 'router', 'state': 'unavailable'}] res = self._list('availability_zones') azs = res['availability_zones'] self.assertItemsEqual(expected, azs) # not admin case ctx = context.Context('', 'noadmin') res = self._list('availability_zones', neutron_context=ctx) azs = res['availability_zones'] self.assertItemsEqual(expected, azs)
def setUp(self): super(TestDriverValidation, self).setUp() self.context = n_ctx.Context('some_user', 'some_tenant') self.service_plugin = mock.Mock() driver = mock.Mock() driver.service_plugin = self.service_plugin with mock.patch("neutron_lib.plugins.directory.get_plugin"): self.validator = ipsec_validator.IPsecV3Validator(driver) self.validator._l3_plugin = mock.Mock() self.validator._core_plugin = mock.Mock() self.vpn_service = { 'router_id': 'dummy_router', 'subnet_id': 'dummy_subnet' } self.peer_address = '10.10.10.10' self.peer_cidr = '10.10.11.0/20'
def _create_metering_label_rule(self, fmt, metering_label_id, direction, remote_ip_prefix, excluded, **kwargs): data = {'metering_label_rule': {'metering_label_id': metering_label_id, 'tenant_id': kwargs.get('tenant_id', 'test-tenant'), 'direction': direction, 'excluded': excluded, 'remote_ip_prefix': remote_ip_prefix}} req = self.new_create_request('metering-label-rules', data, fmt) if kwargs.get('set_context') and 'tenant_id' in kwargs: # create a specific auth context for this request req.environ['neutron.context'] = ( context.Context('', kwargs['tenant_id'])) return req.get_response(self.ext_api)
def _test_update_address_scope(self, addr_scope_id, data, admin=False, expected=None, tenant_id=None): update_req = self.new_update_request('address-scopes', data, addr_scope_id) update_req.environ['neutron.context'] = context.Context( '', tenant_id or self._tenant_id, is_admin=admin) update_res = update_req.get_response(self.ext_api) if expected: addr_scope = self.deserialize(self.fmt, update_res) self._compare_resource(addr_scope, expected, 'address_scope') return addr_scope return update_res
def test_port_vnic_type(self): vnic_arg = {portbindings.VNIC_TYPE: self.vnic_type} with self.port(name='name', arg_list=(portbindings.VNIC_TYPE,), **vnic_arg) as port: port_id = port['port']['id'] # Check a response of create_port self._check_response_portbindings_vnic_type(port['port']) # Check a response of get_port ctx = context.get_admin_context() port = self._show('ports', port_id, neutron_context=ctx)['port'] self._check_response_portbindings_vnic_type(port) # By default user is admin - now test non admin user ctx = context.Context(user_id=None, tenant_id=self._tenant_id, is_admin=False) non_admin_port = self._show( 'ports', port_id, neutron_context=ctx)['port'] self._check_response_portbindings_vnic_type(non_admin_port)
def test_port_vif_host(self): host_arg = {portbindings.HOST_ID: self.hostname} with self.port(name='name', arg_list=(portbindings.HOST_ID,), **host_arg) as port: port_id = port['port']['id'] # Check a response of create_port self._check_response_portbindings_host(port['port']) # Check a response of get_port ctx = context.get_admin_context() port = self._show('ports', port_id, neutron_context=ctx)['port'] self._check_response_portbindings_host(port) # By default user is admin - now test non admin user ctx = context.Context(user_id=None, tenant_id=self._tenant_id, is_admin=False) non_admin_port = self._show( 'ports', port_id, neutron_context=ctx)['port'] self._check_response_no_portbindings_host(non_admin_port)
def test_get_firewall_for_tenant_without_rules(self): tenant_id = 'test-tenant' ctx = context.Context('', tenant_id) with self.firewall_policy(tenant_id=tenant_id) as fwp: fwp_id = fwp['firewall_policy']['id'] attrs = self._get_test_firewall_attrs() attrs['firewall_policy_id'] = fwp_id with self.firewall(firewall_policy_id=fwp_id, tenant_id=tenant_id, admin_state_up=test_db_firewall.ADMIN_STATE_UP ) as fw: # router_ids is not present in the firewall db # but is added in the get_firewalls override by plugin fw_list = [fw['firewall']] f = self.callbacks.get_firewalls_for_tenant_without_rules res = f(ctx, host='dummy') for fw in res: del fw['shared'] self.assertEqual(fw_list, res)
def setUp(self): super(TestPlugin, self).setUp() self.setup_coreplugin(load_plugins=False) mock.patch('neutron.objects.db.api.create_object').start() mock.patch('neutron.objects.db.api.update_object').start() mock.patch('neutron.objects.db.api.delete_object').start() mock.patch('neutron.objects.db.api.get_object').start() self.cl_plugin = plugin.ClassificationPlugin() self.ctxt = context.Context('fake_user', 'fake_tenant') mock.patch.object(self.ctxt.session, 'refresh').start() mock.patch.object(self.ctxt.session, 'expunge').start() mock.patch('neutron_classifier.objects.classifications').start() self._generate_test_classifications()
def _process_router_update(self, updated_router): """If a new or existing router in the local namespace is updated, queries the plugin to get the firewall groups for the project in question and then sees if the router has any ports for any firewall group that is configured for that project. If so, installs firewall group rules on the requested ports on this router. """ LOG.debug("Process router update, router_id: %s tenant: %s.", updated_router['id'], updated_router['tenant_id']) router_id = updated_router['id'] if not self.agent_api.is_router_in_namespace(router_id): return # Get the firewall groups for the new router's project. # NOTE: Vernacular move from "tenant" to "project" doesn't yet appear # as a key in router or firewall group objects. ctx = context.Context('', updated_router['tenant_id']) fwg_list = self.fwplugin_rpc.get_firewall_groups_for_project(ctx) if nl_constants.INTERFACE_KEY not in updated_router: return # Apply a firewall group, as requested, to ports on the new router. all_router_ports = set( p['id'] for p in updated_router[nl_constants.INTERFACE_KEY] ) processed_ports = set() for firewall_group in fwg_list: if not self._has_port_insertion_fields(firewall_group): continue ports_to_process = (set(firewall_group['add-port-ids'] + firewall_group['del-port-ids']) & all_router_ports) # A port can have at most one firewall group. port_ids_to_exclude = ports_to_process & processed_ports if port_ids_to_exclude: LOG.warning("Port(s) %s is associated with " "more than one firewall group(s).", port_ids_to_exclude) ports_to_process -= port_ids_to_exclude self._invoke_driver_for_sync_from_plugin( ctx, ports_to_process, firewall_group) processed_ports |= ports_to_process
def setUp(self): super(TestDriverBase, self).setUp() self.driver = FakeDriver.create() self.rule_data = { 'minimum_bandwidth_rule': { 'id': uuidutils.generate_uuid(), 'min_kbps': 100, 'direction': constants.EGRESS_DIRECTION }, 'dscp_marking_rule': { 'id': uuidutils.generate_uuid(), 'dscp_mark': 16 } } ctxt = context.Context('fake_user', 'fake_tenant') self.minimum_bandwidth_rule = rule_object.QosMinimumBandwidthRule( ctxt, **self.rule_data['minimum_bandwidth_rule']) self.dscp_rule = rule_object.QosDscpMarkingRule( ctxt, **self.rule_data['dscp_marking_rule'])