Merge "Straighten up exceptions imports"

This commit is contained in:
Jenkins 2015-10-16 19:19:23 +00:00 committed by Gerrit Code Review
commit de6b98fd5c
3 changed files with 59 additions and 53 deletions

View File

@ -215,7 +215,7 @@ from keystoneclient import adapter
from keystoneclient import auth from keystoneclient import auth
from keystoneclient.common import cms from keystoneclient.common import cms
from keystoneclient import discover from keystoneclient import discover
from keystoneclient import exceptions from keystoneclient import exceptions as ksc_exceptions
from keystoneclient import session from keystoneclient import session
from oslo_config import cfg from oslo_config import cfg
from oslo_serialization import jsonutils from oslo_serialization import jsonutils
@ -226,7 +226,7 @@ import webob.dec
from keystonemiddleware.auth_token import _auth from keystonemiddleware.auth_token import _auth
from keystonemiddleware.auth_token import _base from keystonemiddleware.auth_token import _base
from keystonemiddleware.auth_token import _cache from keystonemiddleware.auth_token import _cache
from keystonemiddleware.auth_token import _exceptions as exc from keystonemiddleware.auth_token import _exceptions as ksm_exceptions
from keystonemiddleware.auth_token import _identity from keystonemiddleware.auth_token import _identity
from keystonemiddleware.auth_token import _request from keystonemiddleware.auth_token import _request
from keystonemiddleware.auth_token import _revocations from keystonemiddleware.auth_token import _revocations
@ -416,7 +416,7 @@ def _conf_values_type_convert(conf):
# This option is not known to auth_token. # This option is not known to auth_token.
pass pass
except ValueError as e: except ValueError as e:
raise exc.ConfigurationError( raise ksm_exceptions.ConfigurationError(
_('Unable to convert the value of %(key)s option into correct ' _('Unable to convert the value of %(key)s option into correct '
'type: %(ex)s') % {'key': k, 'ex': e}) 'type: %(ex)s') % {'key': k, 'ex': e})
opts[dest] = v opts[dest] = v
@ -480,7 +480,7 @@ class _BaseAuthProtocol(object):
data, user_auth_ref = self._do_fetch_token(request.user_token) data, user_auth_ref = self._do_fetch_token(request.user_token)
self._validate_token(user_auth_ref) self._validate_token(user_auth_ref)
self._confirm_token_bind(user_auth_ref, request) self._confirm_token_bind(user_auth_ref, request)
except exc.InvalidToken: except ksm_exceptions.InvalidToken:
self.log.info(_LI('Invalid user token')) self.log.info(_LI('Invalid user token'))
request.user_token_valid = False request.user_token_valid = False
else: else:
@ -493,7 +493,7 @@ class _BaseAuthProtocol(object):
_, serv_auth_ref = self._do_fetch_token(request.service_token) _, serv_auth_ref = self._do_fetch_token(request.service_token)
self._validate_token(serv_auth_ref) self._validate_token(serv_auth_ref)
self._confirm_token_bind(serv_auth_ref, request) self._confirm_token_bind(serv_auth_ref, request)
except exc.InvalidToken: except ksm_exceptions.InvalidToken:
self.log.info(_LI('Invalid service token')) self.log.info(_LI('Invalid service token'))
request.service_token_valid = False request.service_token_valid = False
else: else:
@ -512,7 +512,7 @@ class _BaseAuthProtocol(object):
""" """
# 0 seconds of validity means it is invalid right now # 0 seconds of validity means it is invalid right now
if auth_ref.will_expire_soon(stale_duration=0): if auth_ref.will_expire_soon(stale_duration=0):
raise exc.InvalidToken(_('Token authorization failed')) raise ksm_exceptions.InvalidToken(_('Token authorization failed'))
def _do_fetch_token(self, token): def _do_fetch_token(self, token):
"""Helper method to fetch a token and convert it into an AccessInfo""" """Helper method to fetch a token and convert it into an AccessInfo"""
@ -522,7 +522,7 @@ class _BaseAuthProtocol(object):
return data, access.AccessInfo.factory(body=data, auth_token=token) return data, access.AccessInfo.factory(body=data, auth_token=token)
except Exception: except Exception:
self.log.warning(_LW('Invalid token contents.'), exc_info=True) self.log.warning(_LW('Invalid token contents.'), exc_info=True)
raise exc.InvalidToken(_('Token authorization failed')) raise ksm_exceptions.InvalidToken(_('Token authorization failed'))
def _fetch_token(self, token): def _fetch_token(self, token):
"""Fetch the token data based on the value in the header. """Fetch the token data based on the value in the header.
@ -555,7 +555,7 @@ class _BaseAuthProtocol(object):
if msg is False: if msg is False:
msg = _('Token authorization failed') msg = _('Token authorization failed')
raise exc.InvalidToken(msg) raise ksm_exceptions.InvalidToken(msg)
def _confirm_token_bind(self, auth_ref, req): def _confirm_token_bind(self, auth_ref, req):
if self._enforce_token_bind == _BIND_MODE.DISABLED: if self._enforce_token_bind == _BIND_MODE.DISABLED:
@ -848,11 +848,13 @@ class AuthProtocol(_BaseAuthProtocol):
self._token_cache.store(token_hashes[0], data) self._token_cache.store(token_hashes[0], data)
except (exceptions.ConnectionRefused, exceptions.RequestTimeout, except (ksc_exceptions.ConnectionRefused,
exc.RevocationListError, exc.ServiceError) as e: ksc_exceptions.RequestTimeout,
ksm_exceptions.RevocationListError,
ksm_exceptions.ServiceError) as e:
self.log.critical(_LC('Unable to validate token: %s'), e) self.log.critical(_LC('Unable to validate token: %s'), e)
raise webob.exc.HTTPServiceUnavailable() raise webob.exc.HTTPServiceUnavailable()
except exc.InvalidToken: except ksm_exceptions.InvalidToken:
self.log.debug('Token validation failure.', exc_info=True) self.log.debug('Token validation failure.', exc_info=True)
if token_hashes: if token_hashes:
self._token_cache.store_invalid(token_hashes[0]) self._token_cache.store_invalid(token_hashes[0])
@ -873,10 +875,10 @@ class AuthProtocol(_BaseAuthProtocol):
else: else:
# Can't do offline validation for this type of token. # Can't do offline validation for this type of token.
return return
except exceptions.CertificateConfigError: except ksc_exceptions.CertificateConfigError:
self.log.warning(_LW('Fetch certificate config failed, ' self.log.warning(_LW('Fetch certificate config failed, '
'fallback to online validation.')) 'fallback to online validation.'))
except exc.RevocationListError: except ksm_exceptions.RevocationListError:
self.log.warning(_LW('Fetch revocation list failed, ' self.log.warning(_LW('Fetch revocation list failed, '
'fallback to online validation.')) 'fallback to online validation.'))
else: else:
@ -888,7 +890,7 @@ class AuthProtocol(_BaseAuthProtocol):
if auth_ref.version == 'v2.0' and not auth_ref.project_id: if auth_ref.version == 'v2.0' and not auth_ref.project_id:
msg = _('Unable to determine service tenancy.') msg = _('Unable to determine service tenancy.')
raise exc.InvalidToken(msg) raise ksm_exceptions.InvalidToken(msg)
def _cms_verify(self, data, inform=cms.PKI_ASN1_FORM): def _cms_verify(self, data, inform=cms.PKI_ASN1_FORM):
"""Verifies the signature of the provided data's IAW CMS syntax. """Verifies the signature of the provided data's IAW CMS syntax.
@ -905,14 +907,15 @@ class AuthProtocol(_BaseAuthProtocol):
return cms.cms_verify(data, signing_cert_path, return cms.cms_verify(data, signing_cert_path,
signing_ca_path, signing_ca_path,
inform=inform).decode('utf-8') inform=inform).decode('utf-8')
except (exceptions.CMSError, except (ksc_exceptions.CMSError,
cms.subprocess.CalledProcessError) as err: cms.subprocess.CalledProcessError) as err:
self.log.warning(_LW('Verify error: %s'), err) self.log.warning(_LW('Verify error: %s'), err)
raise exc.InvalidToken(_('Token authorization failed')) msg = _('Token authorization failed')
raise ksm_exceptions.InvalidToken(msg)
try: try:
return verify() return verify()
except exceptions.CertificateConfigError: except ksc_exceptions.CertificateConfigError:
# the certs might be missing; unconditionally fetch to avoid racing # the certs might be missing; unconditionally fetch to avoid racing
self._fetch_signing_cert() self._fetch_signing_cert()
self._fetch_ca_cert() self._fetch_ca_cert()
@ -920,7 +923,7 @@ class AuthProtocol(_BaseAuthProtocol):
try: try:
# retry with certs in place # retry with certs in place
return verify() return verify()
except exceptions.CertificateConfigError as err: except ksc_exceptions.CertificateConfigError as err:
# if this is still occurring, something else is wrong and we # if this is still occurring, something else is wrong and we
# need err.output to identify the problem # need err.output to identify the problem
self.log.error(_LE('CMS Verify output: %s'), err.output) self.log.error(_LE('CMS Verify output: %s'), err.output)
@ -942,7 +945,7 @@ class AuthProtocol(_BaseAuthProtocol):
# TypeError If the signed_text is not zlib compressed # TypeError If the signed_text is not zlib compressed
# binascii.Error if signed_text has incorrect base64 padding (py34) # binascii.Error if signed_text has incorrect base64 padding (py34)
except (TypeError, binascii.Error): except (TypeError, binascii.Error):
raise exc.InvalidToken(signed_text) raise ksm_exceptions.InvalidToken(signed_text)
def _fetch_signing_cert(self): def _fetch_signing_cert(self):
self._signing_directory.write_file( self._signing_directory.write_file(
@ -1105,7 +1108,7 @@ def app_factory(global_conf, **local_conf):
# NOTE(jamielennox): Maintained here for public API compatibility. # NOTE(jamielennox): Maintained here for public API compatibility.
InvalidToken = exc.InvalidToken InvalidToken = ksm_exceptions.InvalidToken
ServiceError = exc.ServiceError ServiceError = ksm_exceptions.ServiceError
ConfigurationError = exc.ConfigurationError ConfigurationError = ksm_exceptions.ConfigurationError
RevocationListError = exc.RevocationListError RevocationListError = ksm_exceptions.RevocationListError

View File

@ -14,13 +14,13 @@ import functools
from keystoneclient import auth from keystoneclient import auth
from keystoneclient import discover from keystoneclient import discover
from keystoneclient import exceptions from keystoneclient import exceptions as ksc_exceptions
from keystoneclient.v2_0 import client as v2_client from keystoneclient.v2_0 import client as v2_client
from keystoneclient.v3 import client as v3_client from keystoneclient.v3 import client as v3_client
from six.moves import urllib from six.moves import urllib
from keystonemiddleware.auth_token import _auth from keystonemiddleware.auth_token import _auth
from keystonemiddleware.auth_token import _exceptions as exc from keystonemiddleware.auth_token import _exceptions as ksm_exceptions
from keystonemiddleware.i18n import _, _LE, _LI, _LW from keystonemiddleware.i18n import _, _LE, _LI, _LW
@ -29,8 +29,8 @@ def _convert_fetch_cert_exception(fetch_cert):
def wrapper(self): def wrapper(self):
try: try:
text = fetch_cert(self) text = fetch_cert(self)
except exceptions.HTTPError as e: except ksc_exceptions.HTTPError as e:
raise exceptions.CertificateConfigError(e.details) raise ksc_exceptions.CertificateConfigError(e.details)
return text return text
return wrapper return wrapper
@ -77,7 +77,7 @@ class _V2RequestStrategy(_RequestStrategy):
if not auth_ref: if not auth_ref:
msg = _('Failed to fetch token data from identity server') msg = _('Failed to fetch token data from identity server')
raise exc.InvalidToken(msg) raise ksm_exceptions.InvalidToken(msg)
return {'access': auth_ref} return {'access': auth_ref}
@ -106,7 +106,7 @@ class _V3RequestStrategy(_RequestStrategy):
if not auth_ref: if not auth_ref:
msg = _('Failed to fetch token data from identity server') msg = _('Failed to fetch token data from identity server')
raise exc.InvalidToken(msg) raise ksm_exceptions.InvalidToken(msg)
return {'token': auth_ref} return {'token': auth_ref}
@ -194,7 +194,7 @@ class IdentityServer(object):
', '.join(versions)) ', '.join(versions))
msg = _('No compatible apis supported by server') msg = _('No compatible apis supported by server')
raise exc.ServiceError(msg) raise ksm_exceptions.ServiceError(msg)
def verify_token(self, user_token, retry=True): def verify_token(self, user_token, retry=True):
"""Authenticate user token with identity server. """Authenticate user token with identity server.
@ -211,11 +211,11 @@ class IdentityServer(object):
""" """
try: try:
auth_ref = self._request_strategy.verify_token(user_token) auth_ref = self._request_strategy.verify_token(user_token)
except exceptions.NotFound as e: except ksc_exceptions.NotFound as e:
self._LOG.warning(_LW('Authorization failed for token')) self._LOG.warning(_LW('Authorization failed for token'))
self._LOG.warning(_LW('Identity response: %s'), e.response.text) self._LOG.warning(_LW('Identity response: %s'), e.response.text)
raise exc.InvalidToken(_('Token authorization failed')) raise ksm_exceptions.InvalidToken(_('Token authorization failed'))
except exceptions.Unauthorized as e: except ksc_exceptions.Unauthorized as e:
self._LOG.info(_LI('Identity server rejected authorization')) self._LOG.info(_LI('Identity server rejected authorization'))
self._LOG.warning(_LW('Identity response: %s'), e.response.text) self._LOG.warning(_LW('Identity response: %s'), e.response.text)
if retry: if retry:
@ -223,26 +223,26 @@ class IdentityServer(object):
return self.verify_token(user_token, False) return self.verify_token(user_token, False)
msg = _('Identity server rejected authorization necessary to ' msg = _('Identity server rejected authorization necessary to '
'fetch token data') 'fetch token data')
raise exc.ServiceError(msg) raise ksm_exceptions.ServiceError(msg)
except exceptions.HttpError as e: except ksc_exceptions.HttpError as e:
self._LOG.error( self._LOG.error(
_LE('Bad response code while validating token: %s'), _LE('Bad response code while validating token: %s'),
e.http_status) e.http_status)
self._LOG.warning(_LW('Identity response: %s'), e.response.text) self._LOG.warning(_LW('Identity response: %s'), e.response.text)
msg = _('Failed to fetch token data from identity server') msg = _('Failed to fetch token data from identity server')
raise exc.ServiceError(msg) raise ksm_exceptions.ServiceError(msg)
else: else:
return auth_ref return auth_ref
def fetch_revocation_list(self): def fetch_revocation_list(self):
try: try:
data = self._request_strategy.fetch_revocation_list() data = self._request_strategy.fetch_revocation_list()
except exceptions.HTTPError as e: except ksc_exceptions.HTTPError as e:
msg = _('Failed to fetch token revocation list: %d') msg = _('Failed to fetch token revocation list: %d')
raise exc.RevocationListError(msg % e.http_status) raise ksm_exceptions.RevocationListError(msg % e.http_status)
if 'signed' not in data: if 'signed' not in data:
msg = _('Revocation list improperly formatted.') msg = _('Revocation list improperly formatted.')
raise exc.RevocationListError(msg) raise ksm_exceptions.RevocationListError(msg)
return data['signed'] return data['signed']
def fetch_signing_cert(self): def fetch_signing_cert(self):

View File

@ -25,7 +25,7 @@ import uuid
import fixtures import fixtures
from keystoneclient import auth from keystoneclient import auth
from keystoneclient.common import cms from keystoneclient.common import cms
from keystoneclient import exceptions from keystoneclient import exceptions as ksc_exceptions
from keystoneclient import fixture from keystoneclient import fixture
from keystoneclient import session from keystoneclient import session
import mock import mock
@ -42,7 +42,7 @@ import webob.dec
from keystonemiddleware import auth_token from keystonemiddleware import auth_token
from keystonemiddleware.auth_token import _base from keystonemiddleware.auth_token import _base
from keystonemiddleware.auth_token import _exceptions as exc from keystonemiddleware.auth_token import _exceptions as ksm_exceptions
from keystonemiddleware.auth_token import _revocations from keystonemiddleware.auth_token import _revocations
from keystonemiddleware.openstack.common import memorycache from keystonemiddleware.openstack.common import memorycache
from keystonemiddleware.tests.unit.auth_token import base from keystonemiddleware.tests.unit.auth_token import base
@ -512,7 +512,7 @@ class GeneralAuthTokenMiddlewareTest(BaseAuthTokenMiddlewareTest,
conf = { conf = {
'include_service_catalog': '123', 'include_service_catalog': '123',
} }
self.assertRaises(exc.ConfigurationError, self.assertRaises(ksm_exceptions.ConfigurationError,
auth_token.AuthProtocol, self.fake_app, conf) auth_token.AuthProtocol, self.fake_app, conf)
def test_auth_region_name(self): def test_auth_region_name(self):
@ -656,7 +656,7 @@ class CommonAuthTokenMiddlewareTest(object):
# test the case where that retrieval fails # test the case where that retrieval fails
self.middleware._revocations._fetched_time = datetime.datetime.min self.middleware._revocations._fetched_time = datetime.datetime.min
with mock.patch.object(self.middleware._revocations, '_fetch', with mock.patch.object(self.middleware._revocations, '_fetch',
side_effect=exc.RevocationListError): side_effect=ksm_exceptions.RevocationListError):
self.call_middleware(headers={'X-Auth-Token': token}, self.call_middleware(headers={'X-Auth-Token': token},
expected_status=503) expected_status=503)
@ -797,7 +797,7 @@ class CommonAuthTokenMiddlewareTest(object):
def test_verify_signed_token_raises_exception_for_revoked_token(self): def test_verify_signed_token_raises_exception_for_revoked_token(self):
self.middleware._revocations._list = ( self.middleware._revocations._list = (
self.get_revocation_list_json()) self.get_revocation_list_json())
self.assertRaises(exc.InvalidToken, self.assertRaises(ksm_exceptions.InvalidToken,
self.middleware._verify_signed_token, self.middleware._verify_signed_token,
self.token_dict['revoked_token'], self.token_dict['revoked_token'],
[self.token_dict['revoked_token_hash']]) [self.token_dict['revoked_token_hash']])
@ -807,7 +807,7 @@ class CommonAuthTokenMiddlewareTest(object):
self.set_middleware() self.set_middleware()
self.middleware._revocations._list = ( self.middleware._revocations._list = (
self.get_revocation_list_json(mode='sha256')) self.get_revocation_list_json(mode='sha256'))
self.assertRaises(exc.InvalidToken, self.assertRaises(ksm_exceptions.InvalidToken,
self.middleware._verify_signed_token, self.middleware._verify_signed_token,
self.token_dict['revoked_token'], self.token_dict['revoked_token'],
[self.token_dict['revoked_token_hash_sha256'], [self.token_dict['revoked_token_hash_sha256'],
@ -816,7 +816,7 @@ class CommonAuthTokenMiddlewareTest(object):
def test_verify_signed_token_raises_exception_for_revoked_pkiz_token(self): def test_verify_signed_token_raises_exception_for_revoked_pkiz_token(self):
self.middleware._revocations._list = ( self.middleware._revocations._list = (
self.examples.REVOKED_TOKEN_PKIZ_LIST_JSON) self.examples.REVOKED_TOKEN_PKIZ_LIST_JSON)
self.assertRaises(exc.InvalidToken, self.assertRaises(ksm_exceptions.InvalidToken,
self.middleware._verify_pkiz_token, self.middleware._verify_pkiz_token,
self.token_dict['revoked_token_pkiz'], self.token_dict['revoked_token_pkiz'],
[self.token_dict['revoked_token_pkiz_hash']]) [self.token_dict['revoked_token_pkiz_hash']])
@ -912,7 +912,7 @@ class CommonAuthTokenMiddlewareTest(object):
def test_invalid_revocation_list_raises_error(self): def test_invalid_revocation_list_raises_error(self):
self.requests_mock.get(self.revocation_url, json={}) self.requests_mock.get(self.revocation_url, json={})
self.assertRaises(exc.RevocationListError, self.assertRaises(ksm_exceptions.RevocationListError,
self.middleware._revocations._fetch) self.middleware._revocations._fetch)
def test_fetch_revocation_list(self): def test_fetch_revocation_list(self):
@ -983,7 +983,8 @@ class CommonAuthTokenMiddlewareTest(object):
token = 'invalid-token' token = 'invalid-token'
self.call_middleware(headers={'X-Auth-Token': token}, self.call_middleware(headers={'X-Auth-Token': token},
expected_status=401) expected_status=401)
self.assertRaises(exc.InvalidToken, self._get_cached_token, token) self.assertRaises(ksm_exceptions.InvalidToken,
self._get_cached_token, token)
def test_memcache_set_expired(self, extra_conf={}, extra_environ={}): def test_memcache_set_expired(self, extra_conf={}, extra_environ={}):
token_cache_time = 10 token_cache_time = 10
@ -1319,7 +1320,7 @@ class V2CertDownloadMiddlewareTest(BaseAuthTokenMiddlewareTest,
status_code=404) status_code=404)
self.requests_mock.get('%s%s' % (BASE_URI, self.signing_path), self.requests_mock.get('%s%s' % (BASE_URI, self.signing_path),
status_code=404) status_code=404)
self.assertRaises(exceptions.CertificateConfigError, self.assertRaises(ksc_exceptions.CertificateConfigError,
self.middleware._verify_signed_token, self.middleware._verify_signed_token,
self.examples.SIGNED_TOKEN_SCOPED, self.examples.SIGNED_TOKEN_SCOPED,
[self.examples.SIGNED_TOKEN_SCOPED_HASH]) [self.examples.SIGNED_TOKEN_SCOPED_HASH])
@ -1411,7 +1412,7 @@ class V3CertDownloadMiddlewareTest(V2CertDownloadMiddlewareTest):
def network_error_response(request, context): def network_error_response(request, context):
raise exceptions.ConnectionRefused("Network connection refused.") raise ksc_exceptions.ConnectionRefused("Network connection refused.")
class v2AuthTokenMiddlewareTest(BaseAuthTokenMiddlewareTest, class v2AuthTokenMiddlewareTest(BaseAuthTokenMiddlewareTest,
@ -1680,7 +1681,8 @@ class v3AuthTokenMiddlewareTest(BaseAuthTokenMiddlewareTest,
self.assertEqual(auth_id, FAKE_ADMIN_TOKEN_ID) self.assertEqual(auth_id, FAKE_ADMIN_TOKEN_ID)
if token_id == ERROR_TOKEN: if token_id == ERROR_TOKEN:
raise exceptions.ConnectionRefused("Network connection refused.") msg = "Network connection refused."
raise ksc_exceptions.ConnectionRefused(msg)
try: try:
response = self.examples.JSON_TOKEN_RESPONSES[token_id] response = self.examples.JSON_TOKEN_RESPONSES[token_id]
@ -2131,7 +2133,8 @@ class v3CompositeAuthTests(BaseAuthTokenMiddlewareTest,
response = "" response = ""
if token_id == ERROR_TOKEN: if token_id == ERROR_TOKEN:
raise exceptions.ConnectionRefused("Network connection refused.") msg = "Network connection refused."
raise ksc_exceptions.ConnectionRefused(msg)
try: try:
response = self.examples.JSON_TOKEN_RESPONSES[token_id] response = self.examples.JSON_TOKEN_RESPONSES[token_id]
@ -2281,7 +2284,7 @@ class AuthProtocolLoadingTests(BaseAuthTokenMiddlewareTest):
group=_base.AUTHTOKEN_GROUP) group=_base.AUTHTOKEN_GROUP)
self.assertRaises( self.assertRaises(
exceptions.NoMatchingPlugin, ksc_exceptions.NoMatchingPlugin,
self.create_simple_middleware) self.create_simple_middleware)
def test_plugin_loading_mixed_opts(self): def test_plugin_loading_mixed_opts(self):