Skip to content

Commit

Permalink
feat: wrap all python built-in exceptions into library excpetions (#1191
Browse files Browse the repository at this point in the history
)

* feat: wrap all python built-in exceptions into library excpetions

* remove wrapped StopIteration since it will never thrown
  • Loading branch information
BigTailWolf authored Dec 6, 2022
1 parent ebd49e7 commit a83af39
Show file tree
Hide file tree
Showing 19 changed files with 177 additions and 109 deletions.
4 changes: 2 additions & 2 deletions google/auth/_default.py
Original file line number Diff line number Diff line change
Expand Up @@ -434,7 +434,7 @@ def _get_impersonated_service_account_credentials(filename, info, scopes):
filename, source_credentials_info
)
else:
raise ValueError(
raise exceptions.InvalidType(
"source credential of type {} is not supported.".format(
source_credentials_type
)
Expand All @@ -443,7 +443,7 @@ def _get_impersonated_service_account_credentials(filename, info, scopes):
start_index = impersonation_url.rfind("/")
end_index = impersonation_url.find(":generateAccessToken")
if start_index == -1 or end_index == -1 or start_index > end_index:
raise ValueError(
raise exceptions.InvalidValue(
"Cannot extract target principal from {}".format(impersonation_url)
)
target_principal = impersonation_url[start_index + 1 : end_index]
Expand Down
17 changes: 11 additions & 6 deletions google/auth/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import six
from six.moves import urllib

from google.auth import exceptions

# Token server doesn't provide a new a token when doing refresh unless the
# token is expiring within 30 seconds, so refresh threshold should not be
Expand Down Expand Up @@ -51,10 +52,10 @@ def decorator(method):
Callable: the same method passed in with an updated docstring.
Raises:
ValueError: if the method already has a docstring.
google.auth.exceptions.InvalidOperation: if the method already has a docstring.
"""
if method.__doc__:
raise ValueError("Method already has a docstring.")
raise exceptions.InvalidOperation("Method already has a docstring.")

source_method = getattr(source_class, method.__name__)
method.__doc__ = source_method.__doc__
Expand Down Expand Up @@ -101,13 +102,15 @@ def to_bytes(value, encoding="utf-8"):
passed in if it started out as bytes.
Raises:
ValueError: If the value could not be converted to bytes.
google.auth.exceptions.InvalidValue: If the value could not be converted to bytes.
"""
result = value.encode(encoding) if isinstance(value, six.text_type) else value
if isinstance(result, six.binary_type):
return result
else:
raise ValueError("{0!r} could not be converted to bytes".format(value))
raise exceptions.InvalidValue(
"{0!r} could not be converted to bytes".format(value)
)


def from_bytes(value):
Expand All @@ -121,13 +124,15 @@ def from_bytes(value):
if it started out as unicode.
Raises:
ValueError: If the value could not be converted to unicode.
google.auth.exceptions.InvalidValue: If the value could not be converted to unicode.
"""
result = value.decode("utf-8") if isinstance(value, six.binary_type) else value
if isinstance(result, six.text_type):
return result
else:
raise ValueError("{0!r} could not be converted to unicode".format(value))
raise exceptions.InvalidValue(
"{0!r} could not be converted to unicode".format(value)
)


def update_query(url, params, remove=None):
Expand Down
5 changes: 3 additions & 2 deletions google/auth/_service_account_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import six

from google.auth import crypt
from google.auth import exceptions


def from_dict(data, require=None, use_rsa_signer=True):
Expand All @@ -40,15 +41,15 @@ def from_dict(data, require=None, use_rsa_signer=True):
service account file.
Raises:
ValueError: if the data was in the wrong format, or if one of the
MalformedError: if the data was in the wrong format, or if one of the
required keys is missing.
"""
keys_needed = set(require if require is not None else [])

missing = keys_needed.difference(six.iterkeys(data))

if missing:
raise ValueError(
raise exceptions.MalformedError(
"Service account info was not in the expected format, missing "
"fields {}.".format(", ".join(missing))
)
Expand Down
3 changes: 2 additions & 1 deletion google/auth/api_key.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

from google.auth import _helpers
from google.auth import credentials
from google.auth import exceptions


class Credentials(credentials.Credentials):
Expand All @@ -36,7 +37,7 @@ def __init__(self, token):
"""
super(Credentials, self).__init__()
if not token:
raise ValueError("Token must be a non-empty API key string")
raise exceptions.InvalidValue("Token must be a non-empty API key string")
self.token = token

@property
Expand Down
13 changes: 7 additions & 6 deletions google/auth/app_engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
from google.auth import _helpers
from google.auth import credentials
from google.auth import crypt
from google.auth import exceptions

# pytype: disable=import-error
try:
Expand Down Expand Up @@ -67,13 +68,13 @@ def get_project_id():
str: The project ID
Raises:
EnvironmentError: If the App Engine APIs are unavailable.
google.auth.exceptions.OSError: If the App Engine APIs are unavailable.
"""
# pylint: disable=missing-raises-doc
# Pylint rightfully thinks EnvironmentError is OSError, but doesn't
# Pylint rightfully thinks google.auth.exceptions.OSError is OSError, but doesn't
# realize it's a valid alias.
if app_identity is None:
raise EnvironmentError("The App Engine APIs are not available.")
raise exceptions.OSError("The App Engine APIs are not available.")
return app_identity.get_application_id()


Expand Down Expand Up @@ -107,13 +108,13 @@ def __init__(
and billing.
Raises:
EnvironmentError: If the App Engine APIs are unavailable.
google.auth.exceptions.OSError: If the App Engine APIs are unavailable.
"""
# pylint: disable=missing-raises-doc
# Pylint rightfully thinks EnvironmentError is OSError, but doesn't
# Pylint rightfully thinks google.auth.exceptions.OSError is OSError, but doesn't
# realize it's a valid alias.
if app_identity is None:
raise EnvironmentError("The App Engine APIs are not available.")
raise exceptions.OSError("The App Engine APIs are not available.")

super(Credentials, self).__init__()
self._scopes = scopes
Expand Down
10 changes: 6 additions & 4 deletions google/auth/aws.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ def get_request_options(
)
# Validate provided URL.
if not uri.hostname or uri.scheme != "https":
raise ValueError("Invalid AWS service URL")
raise exceptions.InvalidResource("Invalid AWS service URL")

header_map = _generate_authentication_header_map(
host=uri.hostname,
Expand Down Expand Up @@ -408,9 +408,11 @@ def __init__(
env_id, env_version = (None, None)

if env_id != "aws" or self._cred_verification_url is None:
raise ValueError("No valid AWS 'credential_source' provided")
raise exceptions.InvalidResource(
"No valid AWS 'credential_source' provided"
)
elif int(env_version or "") != 1:
raise ValueError(
raise exceptions.InvalidValue(
"aws version '{}' is not supported in the current build.".format(
env_version
)
Expand All @@ -428,7 +430,7 @@ def validate_metadata_server_url_if_any(url_string, name_of_data):
if url_string:
url = urlparse(url_string)
if url.hostname != "169.254.169.254" and url.hostname != "fd00:ec2::254":
raise ValueError(
raise exceptions.InvalidResource(
"Invalid hostname '{}' for '{}'".format(url.hostname, name_of_data)
)

Expand Down
6 changes: 3 additions & 3 deletions google/auth/compute_engine/credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ def __init__(

if use_metadata_identity_endpoint:
if token_uri or additional_claims or service_account_email or signer:
raise ValueError(
raise exceptions.MalformedError(
"If use_metadata_identity_endpoint is set, token_uri, "
"additional_claims, service_account_email, signer arguments"
" must not be set"
Expand Down Expand Up @@ -312,7 +312,7 @@ def with_token_uri(self, token_uri):
# since the signer is already instantiated,
# the request is not needed
if self._use_metadata_identity_endpoint:
raise ValueError(
raise exceptions.MalformedError(
"If use_metadata_identity_endpoint is set, token_uri" " must not be set"
)
else:
Expand Down Expand Up @@ -423,7 +423,7 @@ def sign_bytes(self, message):
Signer is not available if metadata identity endpoint is used.
"""
if self._use_metadata_identity_endpoint:
raise ValueError(
raise exceptions.InvalidOperation(
"Signer is not available if metadata identity endpoint is used"
)
return self._signer.sign(message)
Expand Down
9 changes: 5 additions & 4 deletions google/auth/credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import six

from google.auth import _helpers, environment_vars
from google.auth import exceptions


@six.add_metaclass(abc.ABCMeta)
Expand Down Expand Up @@ -190,20 +191,20 @@ def valid(self):
return True

def refresh(self, request):
"""Raises :class:`ValueError``, anonymous credentials cannot be
"""Raises :class:``InvalidOperation``, anonymous credentials cannot be
refreshed."""
raise ValueError("Anonymous credentials cannot be refreshed.")
raise exceptions.InvalidOperation("Anonymous credentials cannot be refreshed.")

def apply(self, headers, token=None):
"""Anonymous credentials do nothing to the request.
The optional ``token`` argument is not supported.
Raises:
ValueError: If a token was specified.
google.auth.exceptions.InvalidValue: If a token was specified.
"""
if token is not None:
raise ValueError("Anonymous credentials don't support tokens.")
raise exceptions.InvalidValue("Anonymous credentials don't support tokens.")

def before_request(self, request, method, url, headers):
"""Anonymous credentials do nothing to the request."""
Expand Down
7 changes: 4 additions & 3 deletions google/auth/crypt/_python_rsa.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import six

from google.auth import _helpers
from google.auth import exceptions
from google.auth.crypt import base

_POW2 = (128, 64, 32, 16, 8, 4, 2, 1)
Expand Down Expand Up @@ -101,7 +102,7 @@ def from_string(cls, public_key):
der = rsa.pem.load_pem(public_key, "CERTIFICATE")
asn1_cert, remaining = decoder.decode(der, asn1Spec=Certificate())
if remaining != b"":
raise ValueError("Unused bytes", remaining)
raise exceptions.InvalidValue("Unused bytes", remaining)

cert_info = asn1_cert["tbsCertificate"]["subjectPublicKeyInfo"]
key_bytes = _bit_list_to_bytes(cert_info["subjectPublicKey"])
Expand Down Expand Up @@ -162,12 +163,12 @@ def from_string(cls, key, key_id=None):
elif marker_id == 1:
key_info, remaining = decoder.decode(key_bytes, asn1Spec=_PKCS8_SPEC)
if remaining != b"":
raise ValueError("Unused bytes", remaining)
raise exceptions.InvalidValue("Unused bytes", remaining)
private_key_info = key_info.getComponentByName("privateKey")
private_key = rsa.key.PrivateKey.load_pkcs1(
private_key_info.asOctets(), format="DER"
)
else:
raise ValueError("No key could be detected.")
raise exceptions.MalformedError("No key could be detected.")

return cls(private_key, key_id=key_id)
3 changes: 2 additions & 1 deletion google/auth/crypt/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

import six

from google.auth import exceptions

_JSON_FILE_PRIVATE_KEY = "private_key"
_JSON_FILE_PRIVATE_KEY_ID = "private_key_id"
Expand Down Expand Up @@ -106,7 +107,7 @@ def from_service_account_info(cls, info):
ValueError: If the info is not in the expected format.
"""
if _JSON_FILE_PRIVATE_KEY not in info:
raise ValueError(
raise exceptions.MalformedError(
"The private_key field was not found in the service account " "info."
)

Expand Down
Loading

0 comments on commit a83af39

Please sign in to comment.