def authenticate(self): if self.auth_strategy != 'keystone': raise exceptions.Unauthorized(message=_('Unknown auth strategy')) if self.tenant_id: body = { 'auth': { 'passwordCredentials': { 'username': self.username, 'password': self.password, }, 'tenantId': self.tenant_id, }, } else: body = { 'auth': { 'passwordCredentials': { 'username': self.username, 'password': self.password, }, 'tenantName': self.tenant_name, }, } token_url = self.auth_url + "/tokens" # Make sure we follow redirects when trying to reach Keystone tmp_follow_all_redirects = self.follow_all_redirects self.follow_all_redirects = True try: resp, resp_body = self._cs_request(token_url, "POST", body=json.dumps(body), content_type="application/json") finally: self.follow_all_redirects = tmp_follow_all_redirects status_code = self.get_status_code(resp) if status_code != 200: if not _logger.isEnabledFor(logging.DEBUG): utils.http_log_req(_logger, ["POST"], { 'body': json.dumps(body), 'content_type': "application/json" }, force_logging=True) raise exceptions.Unauthorized(message=resp_body) if resp_body: try: resp_body = json.loads(resp_body) except ValueError: pass else: resp_body = None self._extract_service_catalog(resp_body)
def authenticate(self): if self.auth_strategy != 'keystone': err_msg = _('Unknown auth strategy: %s') % self.auth_strategy raise exceptions.Unauthorized(message=err_msg) if self.tenant_id: body = { 'auth': { 'passwordCredentials': { 'username': self.username, 'password': self.password, }, 'tenantId': self.tenant_id, }, } else: body = { 'auth': { 'passwordCredentials': { 'username': self.username, 'password': self.password, }, 'tenantName': self.tenant_name, }, } if self.auth_url is None: raise exceptions.NoAuthURLProvided() token_url = self.auth_url + "/tokens" # Make sure we follow redirects when trying to reach Keystone tmp_follow_all_redirects = self.follow_all_redirects self.follow_all_redirects = True try: resp, resp_body = self._cs_request(token_url, "POST", body=json.dumps(body), content_type="application/json") finally: self.follow_all_redirects = tmp_follow_all_redirects status_code = self.get_status_code(resp) if status_code != 200: raise exceptions.Unauthorized(message=resp_body) if resp_body: try: resp_body = json.loads(resp_body) except ValueError: pass else: resp_body = None self._extract_service_catalog(resp_body)
def _cs_request(self, *args, **kwargs): kargs = {} kargs.setdefault('headers', kwargs.get('headers', {})) kargs['headers']['User-Agent'] = self.USER_AGENT if 'content_type' in kwargs: kargs['headers']['Content-Type'] = kwargs['content_type'] kargs['headers']['Accept'] = kwargs['content_type'] else: kargs['headers']['Content-Type'] = self.content_type kargs['headers']['Accept'] = self.content_type if 'body' in kwargs: kargs['body'] = kwargs['body'] args = utils.safe_encode_list(args) kargs = utils.safe_encode_dict(kargs) utils.http_log_req(_logger, args, kargs) try: resp, body = self.request(*args, **kargs) except Exception as e: # Wrap the low-level connection error (socket timeout, redirect # limit, decompression error, etc) into our custom high-level # connection exception (it is excepted in the upper layers of code) raise exceptions.ConnectionFailed(reason=e) utils.http_log_resp(_logger, resp, body) status_code = self.get_status_code(resp) if status_code == 401: raise exceptions.Unauthorized(message=body) elif status_code == 403: raise exceptions.Forbidden(message=body) return resp, body
def get_neutron_client(context, admin=False): global _ADMIN_AUTH global _SESSION auth_plugin = None if not _SESSION: _SESSION = ks_loading.load_session_from_conf_options( CONF, NEUTRON_GROUP) if admin or (context.is_admin and not context.auth_token): if not _ADMIN_AUTH: _ADMIN_AUTH = _load_auth_plugin(CONF) auth_plugin = _ADMIN_AUTH elif context.auth_token: auth_plugin = context.get_auth_plugin() if not auth_plugin: # We did not get a user token and we should not be using # an admin token so log an error raise neutron_client_exc.Unauthorized() return clientv20.Client(session=_SESSION, auth=auth_plugin, endpoint_override=CONF.neutron.url, region_name=CONF.neutron.region_name)
def _cs_request(self, *args, **kwargs): kargs = {} kargs.setdefault('headers', kwargs.get('headers', {})) kargs['headers']['User-Agent'] = self.USER_AGENT if 'body' in kwargs: kargs['body'] = kwargs['body'] if self.log_credentials: log_kargs = kargs else: log_kargs = self._strip_credentials(kargs) utils.http_log_req(_logger, args, log_kargs) try: resp, body = self.request(*args, **kargs) except requests.exceptions.SSLError as e: raise exceptions.SslCertificateValidationError(reason=e) except Exception as e: # Wrap the low-level connection error (socket timeout, redirect # limit, decompression error, etc) into our custom high-level # connection exception (it is excepted in the upper layers of code) _logger.debug("throwing ConnectionFailed : %s", e) raise exceptions.ConnectionFailed(reason=e) utils.http_log_resp(_logger, resp, body) if resp.status_code == 401: raise exceptions.Unauthorized(message=body) return resp, body
def get_client(context, admin=False): # NOTE(dprince): In the case where no auth_token is present # we allow use of neutron admin tenant credentials if # it is an admin context. # This is to support some services (metadata API) where # an admin context is used without an auth token. if admin or (context.is_admin and not context.auth_token): # NOTE(dims): We need to use admin token, let us cache a # thread local copy for re-using this client # multiple times and to avoid excessive calls # to neutron to fetch tokens. Some of the hackiness in this code # will go away once BP auth-plugins is implemented. # That blue print will ensure that tokens can be shared # across clients as well if not hasattr(local.strong_store, 'neutron_client'): local.strong_store.neutron_client = _get_client(token=None) return local.strong_store.neutron_client # We got a user token that we can use that as-is if context.auth_token: token = context.auth_token return _get_client(token=token) # We did not get a user token and we should not be using # an admin token so log an error raise exceptions.Unauthorized()
def _authenticate_keystone(self): if self.user_id: creds = {'userId': self.user_id, 'password': self.password} else: creds = {'username': self.username, 'password': self.password} if self.project_id: body = {'auth': {'passwordCredentials': creds, 'tenantId': self.project_id, }, } else: body = {'auth': {'passwordCredentials': creds, 'tenantName': self.project_name, }, } if self.auth_url is None: raise exceptions.NoAuthURLProvided() token_url = self.auth_url + "/tokens" resp, resp_body = self._cs_request(token_url, "POST", body=json.dumps(body), content_type="application/json", allow_redirects=True) if resp.status_code != 200: raise exceptions.Unauthorized(message=resp_body) if resp_body: try: resp_body = json.loads(resp_body) except ValueError: pass else: resp_body = None self._extract_service_catalog(resp_body)
def get_client(self, context): if context.is_admin: token = None elif not context.auth_token: raise neutron_client_exc.Unauthorized() else: token = context.auth_token return self._get_client(token=token)
def _load_auth_plugin(conf): auth_plugin = ks_loading.load_auth_from_conf_options(conf, NEUTRON_GROUP) if auth_plugin: return auth_plugin err_msg = _('Unknown auth type: %s') % conf.neutron.auth_type raise neutron_client_exc.Unauthorized(message=err_msg)
def authenticate(self): if self.auth_strategy == 'keystone': self._authenticate_keystone() elif self.auth_strategy == 'noauth': self._authenticate_noauth() else: err_msg = _('Unknown auth strategy: %s') % self.auth_strategy raise exceptions.Unauthorized(message=err_msg)
def get_client(context, admin=False): if admin or context.is_admin: token = None elif not context.auth_token: raise exceptions.Unauthorized() else: token = context.auth_token return _get_client(token=token)
def _cs_request(self, *args, **kwargs): kargs = {} kargs.setdefault('headers', kwargs.get('headers', {})) kargs['headers']['User-Agent'] = self.USER_AGENT if 'content_type' in kwargs: kargs['headers']['Content-Type'] = kwargs['content_type'] kargs['headers']['Accept'] = kwargs['content_type'] else: kargs['headers']['Content-Type'] = self.content_type kargs['headers']['Accept'] = self.content_type if 'body' in kwargs: kargs['body'] = kwargs['body'] args = utils.safe_encode_list(args) kargs = utils.safe_encode_dict(kargs) if self.log_credentials: log_kargs = kargs else: log_kargs = self._strip_credentials(kargs) utils.http_log_req(_logger, args, log_kargs) try: resp, body = self.request(*args, **kargs) except httplib2.SSLHandshakeError as e: if not _logger.isEnabledFor(logging.DEBUG): utils.http_log_req(_logger, args, log_kargs, force_logging=True) raise exceptions.SslCertificateValidationError(reason=e) except Exception as e: if not _logger.isEnabledFor(logging.DEBUG): utils.http_log_req(_logger, args, log_kargs, force_logging=True) # Wrap the low-level connection error (socket timeout, redirect # limit, decompression error, etc) into our custom high-level # connection exception (it is excepted in the upper layers of code) _logger.debug("throwing ConnectionFailed : %s", e) raise exceptions.ConnectionFailed(reason=e) finally: # Temporary Fix for gate failures. RPC calls and HTTP requests # seem to be stepping on each other resulting in bogus fd's being # picked up for making http requests self.connections.clear() utils.http_log_resp(_logger, resp, body) status_code = self.get_status_code(resp) if status_code == 401: raise exceptions.Unauthorized(message=body) elif status_code == 403: raise exceptions.Forbidden(message=body) return resp, body
def test_create_network_unauthorized(self): docker_network_id = hashlib.sha256(utils.getrandbits(256)).hexdigest() self._create_network_with_exception(docker_network_id, exceptions.Unauthorized()) response = self._invoke_create_request(docker_network_id) self.assertEqual(401, response.status_code) decoded_json = jsonutils.loads(response.data) self.assertIn('Err', decoded_json) self.assertEqual({'Err': exceptions.Unauthorized.message}, decoded_json)
def _extract_service_catalog(self, body): """Set the client's service catalog from the response data.""" self.service_catalog = ServiceCatalog(body) try: sc = self.service_catalog.get_token() self.auth_token = sc['id'] self.auth_tenant_id = sc.get('tenant_id') self.auth_user_id = sc.get('user_id') except KeyError: raise exceptions.Unauthorized() self.endpoint_url = self.service_catalog.url_for( attr='region', filter_value=self.region_name, endpoint_type=self.endpoint_type)
def get_client(context, admin=False): if admin or (context.is_admin and not context.auth_token): with lockutils.lock('neutron_admin_auth_token_lock'): orig_token = AdminTokenStore.get().admin_auth_token client = _get_client(orig_token, admin=True) return ClientWrapper(client) # We got a user token that we can use as-is if context.auth_token: token = context.auth_token return _get_client(token=token) # We did not get a user token and we should not be using # an admin token so log an error raise neutron_client_exc.Unauthorized()
def get_client(context, admin=False): # NOTE(dprince): In the case where no auth_token is present # we allow use of neutron admin tenant credentials if # it is an admin context. # This is to support some services (metadata API) where # an admin context is used without an auth token. if admin or (context.is_admin and not context.auth_token): with lockutils.lock('neutron_admin_auth_token_lock'): orig_token = AdminTokenStore.get().admin_auth_token client = _get_client(orig_token, admin=True) return ClientWrapper(client) # We got a user token that we can use that as-is if context.auth_token: token = context.auth_token return _get_client(token=token) # We did not get a user token and we should not be using # an admin token so log an error raise exceptions.Unauthorized()
def _cs_request(self, *args, **kwargs): kargs = {} kargs.setdefault('headers', kwargs.get('headers', {})) kargs['headers']['User-Agent'] = USER_AGENT if 'body' in kwargs: kargs['body'] = kwargs['body'] if self.log_credentials: log_kargs = kargs else: log_kargs = self._strip_credentials(kargs) utils.http_log_req(_logger, args, log_kargs) try: resp, body = self.request(*args, **kargs) except requests.exceptions.SSLError as e: raise exceptions.SslCertificateValidationError(reason=str(e)) except Exception as e: # Wrap the low-level connection error (socket timeout, redirect # limit, decompression error, etc) into our custom high-level # connection exception (it is excepted in the upper layers of code) _logger.debug("throwing ConnectionFailed : %s", e) raise exceptions.ConnectionFailed(reason=str(e)) utils.http_log_resp(_logger, resp, body) # log request-id for each api call request_id = resp.headers.get('x-openstack-request-id') if request_id: _logger.debug( '%(method)s call to neutron for ' '%(url)s used request id ' '%(response_request_id)s', { 'method': resp.request.method, 'url': resp.url, 'response_request_id': request_id }) if resp.status_code == 401: raise exceptions.Unauthorized(message=body) return resp, body
def _authenticate(cls, auth_url): """Authenticate against noauth or the Rackspace auth service.""" if cls.auth_strategy == 'noauth': if not cls.endpoint_url: message = ('For "noauth" authentication strategy, the endpoint ' 'must be specified either in the constructor or ' 'using --os-url') raise exceptions.Unauthorized(message=message) else: return None if not auth_url: raise exceptions.NoAuthURLProvided() body = { "auth": { "RAX-KSKEY:apiKeyCredentials": { "username": cls.username, "apiKey": cls.password }, } } token_url = cls.auth_url + "/tokens" resp, resp_body = cls._cs_request(token_url, "POST", body=json.dumps(body), content_type="application/json", allow_redirects=True) if resp_body: try: resp_body = json.loads(resp_body) except ValueError: pass else: resp_body = None return resp_body
def _authenticate_noauth(self): if not self.endpoint_url: message = _('For "noauth" authentication strategy, the endpoint ' 'must be specified either in the constructor or ' 'using --os-url') raise exceptions.Unauthorized(message=message)