10000 feat: wrap all python built-in exceptions into library excpetions (#1… · TJB-1/google-auth-library-python@a83af39 · GitHub
[go: up one dir, main page]

Skip to content

Commit a83af39

Browse files
authored
feat: wrap all python built-in exceptions into library excpetions (googleapis#1191)
* feat: wrap all python built-in exceptions into library excpetions * remove wrapped StopIteration since it will never thrown
1 parent ebd49e7 commit a83af39

19 files changed

+177
-109
lines changed

google/auth/_default.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -434,7 +434,7 @@ def _get_impersonated_service_account_credentials(filename, info, scopes):
434434
filename, source_credentials_info
435435
)
436436
else:
437-
raise ValueError(
437+
raise exceptions.InvalidType(
438438
"source credential of type {} is not supported.".format(
439439
source_credentials_type
440440
)
@@ -443,7 +443,7 @@ def _get_impersonated_service_account_credentials(filename, info, scopes):
443443
start_index = impersonation_url.rfind("/")
444444
end_index = impersonation_url.find(":generateAccessToken")
445445
if start_index == -1 or end_index == -1 or start_index > end_index:
446-
raise ValueError(
446+
raise exceptions.InvalidValue(
447447
"Cannot extract target principal from {}".format(impersonation_url)
448448
)
449449
target_principal = impersonation_url[start_index + 1 : end_index]

google/auth/_helpers.py

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
import six
2323
from six.moves import urllib
2424

25+
from google.auth import exceptions
2526

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

5960
source_method = getattr(source_class, method.__name__)
6061
method.__doc__ = source_method.__doc__
@@ -101,13 +102,15 @@ def to_bytes(value, encoding="utf-8"):
101102
passed in if it started out as bytes.
102103
103104
Raises:
104-
ValueError: If the value could not be converted to bytes.
105+
google.auth.exceptions.InvalidValue: If the value could not be converted to bytes.
105106
"""
106107
result = value.encode(encoding) if isinstance(value, six.text_type) else value
107108
if isinstance(result, six.binary_type):
108109
return result
109110
else:
110-
raise ValueError("{0!r} could not be converted to bytes".format(value))
111+
raise exceptions.InvalidValue(
112+
"{0!r} could not be converted to bytes".format(value)
113+
)
111114

112115

113116
def from_bytes(value):
@@ -121,13 +124,15 @@ def from_bytes(value):
121124
if it started out as unicode.
122125
123126
Raises:
124-
ValueError: If the value could not be converted to unicode.
127+
google.auth.exceptions.InvalidValue: If the value could not be converted to unicode.
125128
"""
126129
result = value.decode("utf-8") if isinstance(value, six.binary_type) else value
127130
if isinstance(result, six.text_type):
128131
return result
129132
else:
130-
raise ValueError("{0!r} could not be converted to unicode".format(value))
133+
raise exceptions.InvalidValue(
134+
"{0!r} could not be converted to unicode".format(value)
135+
)
131136

132137

133138
def update_query(url, params, remove=None):

google/auth/_service_account_info.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
import six
2121

2222
from google.auth import crypt
23+
from google.auth import exceptions
2324

2425

2526
def from_dict(data, require=None, use_rsa_signer=True):
@@ -40,15 +41,15 @@ def from_dict(data, require=None, use_rsa_signer=True):
4041
service account file.
4142
4243
Raises:
43-
ValueError: if the data was in the wrong format, or if one of the
44+
MalformedError: if the data was in the wrong format, or if one of the
4445
required keys is missing.
4546
"""
4647
keys_needed = set(require if require is not None else [])
4748

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

5051
if missing:
51-
raise ValueError(
52+
raise exceptions.MalformedError(
5253
"Service account info was not in the expected format, missing "
5354
"fields {}.".format(", ".join(missing))
5455
)

google/auth/api_key.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020

2121
from google.auth import _helpers
2222
from google.auth import credentials
23+
from google.auth import exceptions
2324

2425

2526
class Credentials(credentials.Credentials):
@@ -36,7 +37,7 @@ def __init__(self, token):
3637
"""
3738
super(Credentials, self).__init__()
3839
if not token:
39-
raise ValueError("Token must be a non-empty API key string")
40+
raise exceptions.InvalidValue("Token must be a non-empty API key string")
4041
self.token = token
4142

4243
@property

google/auth/app_engine.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
from google.auth import _helpers
2828
from google.auth import credentials
2929
from google.auth import crypt
30+
from google.auth import exceptions
3031

3132
# pytype: disable=import-error
3233
try:
@@ -67,13 +68,13 @@ def get_project_id():
6768
str: The project ID
6869
6970
Raises:
70-
EnvironmentError: If the App Engine APIs are unavailable.
71+
google.auth.exceptions.OSError: If the App Engine APIs are unavailable.
7172
"""
7273
# pylint: disable=missing-raises-doc
73-
# Pylint rightfully thinks EnvironmentError is OSError, but doesn't
74+
# Pylint rightfully thinks google.auth.exceptions.OSError is OSError, but doesn't
7475
# realize it's a valid alias.
7576
if app_identity is None:
76-
raise EnvironmentError("The App Engine APIs are not available.")
77+
raise exceptions.OSError("The App Engine APIs are not available.")
7778
return app_identity.get_application_id()
7879

7980

@@ -107,13 +108,13 @@ def __init__(
107108
and billing.
108109
109110
Raises:
110-
EnvironmentError: If the App Engine APIs are unavailable.
111+
google.auth.exceptions.OSError: If the App Engine APIs are unavailable.
111112
"""
112113
# pylint: disable=missing-raises-doc
113-
# Pylint rightfully thinks EnvironmentError is OSError, but doesn't
114+
# Pylint rightfully thinks google.auth.exceptions.OSError is OSError, but doesn't
114115
# realize it's a valid alias.
115116
if app_identity is None:
116-
raise EnvironmentError("The App Engine APIs are not available.")
117+
raise exceptions.OSError("The App Engine APIs are not available.")
117118

118119
super(Credentials, self).__init__()
119120
self._scopes = scopes

google/auth/aws.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ def get_request_options(
123123
)
124124
# Validate provided URL.
125125
if not uri.hostname or uri.scheme != "https":
126-
raise ValueError("Invalid AWS service URL")
126+
raise exceptions.InvalidResource("Invalid AWS service URL")
127127

128128
header_map = _generate_authentication_header_map(
129129
host=uri.hostname,
@@ -408,9 +408,11 @@ def __init__(
408408
env_id, env_version = (None, None)
409409

410410
if env_id != "aws" or self._cred_verification_url is None:
411-
raise ValueError("No valid AWS 'credential_source' provided")
411+
raise exceptions.InvalidResource(
412+
"No valid AWS 'credential_source' provided"
413+
)
412414
elif int(env_version or "") != 1:
413-
raise ValueError(
415+
raise exceptions.InvalidValue(
414416
"aws version '{}' is not supported in the current build.".format(
415417
env_version
416418
)
@@ -428,7 +430,7 @@ def validate_metadata_server_url_if_any(url_string, name_of_data):
428430
if url_string:
429431
url = urlparse(url_string)
430432
if url.hostname != "169.254.169.254" and url.hostname != "fd00:ec2::254":
431-
raise ValueError(
433+
raise exceptions.InvalidResource(
432434
"Invalid hostname '{}' for '{}'".format(url.hostname, name_of_data)
433435
)
434436

google/auth/compute_engine/credentials.py

Lines changed: 3 additions & 3 deletions
Original file line numberD F438 iff line numberDiff line change
@@ -221,7 +221,7 @@ def __init__(
221221

222222
if use_metadata_identity_endpoint:
223223
if token_uri or additional_claims or service_account_email or signer:
224-
raise ValueError(
224+
raise exceptions.MalformedError(
225225
"If use_metadata_identity_endpoint is set, token_uri, "
226226
"additional_claims, service_account_email, signer arguments"
227227
" must not be set"
@@ -312,7 +312,7 @@ def with_token_uri(self, token_uri):
312312
# since the signer is already instantiated,
313313
# the request is not needed
314314
if self._use_metadata_identity_endpoint:
315-
raise ValueError(
315+
raise exceptions.MalformedError(
316316
"If use_metadata_identity_endpoint is set, token_uri" " must not be set"
317317
)
318318
else:
@@ -423,7 +423,7 @@ def sign_bytes(self, message):
423423
Signer is not available if metadata identity endpoint is used.
424424
"""
425425
if self._use_metadata_identity_endpoint:
426-
raise ValueError(
426+
raise exceptions.InvalidOperation(
427427
"Signer is not available if metadata identity endpoint is used"
428428
)
429429
return self._signer.sign(message)

google/auth/credentials.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
import six
2222

2323
from google.auth import _helpers, environment_vars
24+
from google.auth import exceptions
2425

2526

2627
@six.add_metaclass(abc.ABCMeta)
@@ -190,20 +191,20 @@ def valid(self):
190191
return True
191192

192193
def refresh(self, request):
193-
"""Raises :class:`ValueError``, anonymous credentials cannot be
194+
"""Raises :class:``InvalidOperation``, anonymous credentials cannot be
194195
refreshed."""
195-
raise ValueError("Anonymous credentials cannot be refreshed.")
196+
raise exceptions.InvalidOperation("Anonymous credentials cannot be refreshed.")
196197

197198
def apply(self, headers, token=None):
198199
"""Anonymous credentials do nothing to the request.
199200
200201
The optional ``token`` argument is not supported.
201202
202203
Raises:
203-
ValueError: If a token was specified.
204+
google.auth.exceptions.InvalidValue: If a token was specified.
204205
"""
205206
if token is not None:
206-
raise ValueError("Anonymous credentials don't support tokens.")
207+
raise exceptions.InvalidValue("Anonymous credentials don't support tokens.")
207208

208209
def before_request(self, request, method, url, headers):
209210
"""Anonymous credentials do nothing to the request."""

google/auth/crypt/_python_rsa.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
import six
3030

3131
from google.auth import _helpers
32+
from google.auth import exceptions
3233
from google.auth.crypt import base
3334

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

106107
cert_info = asn1_cert["tbsCertificate"]["subjectPublicKeyInfo"]
107108
key_bytes = _bit_list_to_bytes(cert_info["subjectPublicKey"])
@@ -162,12 +163,12 @@ def from_string(cls, key, key_id=None):
162163
elif marker_id == 1:
163164
key_info, remaining = decoder.decode(key_bytes, asn1Spec=_PKCS8_SPEC)
164165
if remaining != b"":
165-
raise ValueError("Unused bytes", remaining)
166+
raise exceptions.InvalidValue("Unused bytes", remaining)
166167
private_key_info = key_info.getComponentByName("privateKey")
167168
private_key = rsa.key.PrivateKey.load_pkcs1(
168169
private_key_info.asOctets(), format="DER"
169170
)
170171
else:
171-
raise ValueError("No key could be detected.")
172+
raise exceptions.MalformedError("No key could be detected.")
172173

173174
return cls(private_key, key_id=key_id)

google/auth/crypt/base.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020

2121
import six
2222

23+
from google.auth import exceptions
2324

2425
_JSON_FILE_PRIVATE_KEY = "private_key"
2526
_JSON_FILE_PRIVATE_KEY_ID = "private_key_id"
@@ -106,7 +107,7 @@ def from_service_account_info(cls, info):
106107
ValueError: If the info is not in the expected format.
107108
"""
108109
if _JSON_FILE_PRIVATE_KEY not in info:
109-
raise ValueError(
110+
raise exceptions.MalformedError(
110111
"The private_key field was not found in the service account " "info."
111112
)
112113

0 commit comments

Comments
 (0)
0