chore: blacken (#375)
diff --git a/google/oauth2/_client.py b/google/oauth2/_client.py
index eac01b7..996f9b7 100644
--- a/google/oauth2/_client.py
+++ b/google/oauth2/_client.py
@@ -34,9 +34,9 @@
from google.auth import exceptions
from google.auth import jwt
-_URLENCODED_CONTENT_TYPE = 'application/x-www-form-urlencoded'
-_JWT_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:jwt-bearer'
-_REFRESH_GRANT_TYPE = 'refresh_token'
+_URLENCODED_CONTENT_TYPE = "application/x-www-form-urlencoded"
+_JWT_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer"
+_REFRESH_GRANT_TYPE = "refresh_token"
def _handle_error_response(response_body):
@@ -50,15 +50,14 @@
"""
try:
error_data = json.loads(response_body)
- error_details = '{}: {}'.format(
- error_data['error'],
- error_data.get('error_description'))
+ error_details = "{}: {}".format(
+ error_data["error"], error_data.get("error_description")
+ )
# If no details could be extracted, use the response data.
except (KeyError, ValueError):
error_details = response_body
- raise exceptions.RefreshError(
- error_details, response_body)
+ raise exceptions.RefreshError(error_details, response_body)
def _parse_expiry(response_data):
@@ -71,11 +70,10 @@
Optional[datetime]: The expiration or ``None`` if no expiration was
specified.
"""
- expires_in = response_data.get('expires_in', None)
+ expires_in = response_data.get("expires_in", None)
if expires_in is not None:
- return _helpers.utcnow() + datetime.timedelta(
- seconds=expires_in)
+ return _helpers.utcnow() + datetime.timedelta(seconds=expires_in)
else:
return None
@@ -98,24 +96,20 @@
an error.
"""
body = urllib.parse.urlencode(body)
- headers = {
- 'content-type': _URLENCODED_CONTENT_TYPE,
- }
+ headers = {"content-type": _URLENCODED_CONTENT_TYPE}
retry = 0
# retry to fetch token for maximum of two times if any internal failure
# occurs.
while True:
- response = request(
- method='POST', url=token_uri, headers=headers, body=body)
- response_body = response.data.decode('utf-8')
+ response = request(method="POST", url=token_uri, headers=headers, body=body)
+ response_body = response.data.decode("utf-8")
if response.status == http_client.OK:
break
else:
- error_desc = json.loads(
- response_body).get('error_description') or ''
- if error_desc == 'internal_failure' and retry < 1:
+ error_desc = json.loads(response_body).get("error_description") or ""
+ if error_desc == "internal_failure" and retry < 1:
retry += 1
continue
_handle_error_response(response_body)
@@ -147,18 +141,14 @@
.. _rfc7523 section 4: https://tools.ietf.org/html/rfc7523#section-4
"""
- body = {
- 'assertion': assertion,
- 'grant_type': _JWT_GRANT_TYPE,
- }
+ body = {"assertion": assertion, "grant_type": _JWT_GRANT_TYPE}
response_data = _token_endpoint_request(request, token_uri, body)
try:
- access_token = response_data['access_token']
+ access_token = response_data["access_token"]
except KeyError as caught_exc:
- new_exc = exceptions.RefreshError(
- 'No access token in response.', response_data)
+ new_exc = exceptions.RefreshError("No access token in response.", response_data)
six.raise_from(new_exc, caught_exc)
expiry = _parse_expiry(response_data)
@@ -191,28 +181,25 @@
google.auth.exceptions.RefreshError: If the token endpoint returned
an error.
"""
- body = {
- 'assertion': assertion,
- 'grant_type': _JWT_GRANT_TYPE,
- }
+ body = {"assertion": assertion, "grant_type": _JWT_GRANT_TYPE}
response_data = _token_endpoint_request(request, token_uri, body)
try:
- id_token = response_data['id_token']
+ id_token = response_data["id_token"]
except KeyError as caught_exc:
- new_exc = exceptions.RefreshError(
- 'No ID token in response.', response_data)
+ new_exc = exceptions.RefreshError("No ID token in response.", response_data)
six.raise_from(new_exc, caught_exc)
payload = jwt.decode(id_token, verify=False)
- expiry = datetime.datetime.utcfromtimestamp(payload['exp'])
+ expiry = datetime.datetime.utcfromtimestamp(payload["exp"])
return id_token, expiry, response_data
-def refresh_grant(request, token_uri, refresh_token, client_id, client_secret,
- scopes=None):
+def refresh_grant(
+ request, token_uri, refresh_token, client_id, client_secret, scopes=None
+):
"""Implements the OAuth 2.0 refresh token grant.
For more details, see `rfc678 section 6`_.
@@ -243,24 +230,23 @@
.. _rfc6748 section 6: https://tools.ietf.org/html/rfc6749#section-6
"""
body = {
- 'grant_type': _REFRESH_GRANT_TYPE,
- 'client_id': client_id,
- 'client_secret': client_secret,
- 'refresh_token': refresh_token,
+ "grant_type": _REFRESH_GRANT_TYPE,
+ "client_id": client_id,
+ "client_secret": client_secret,
+ "refresh_token": refresh_token,
}
if scopes:
- body['scope'] = ' '.join(scopes)
+ body["scope"] = " ".join(scopes)
response_data = _token_endpoint_request(request, token_uri, body)
try:
- access_token = response_data['access_token']
+ access_token = response_data["access_token"]
except KeyError as caught_exc:
- new_exc = exceptions.RefreshError(
- 'No access token in response.', response_data)
+ new_exc = exceptions.RefreshError("No access token in response.", response_data)
six.raise_from(new_exc, caught_exc)
- refresh_token = response_data.get('refresh_token', refresh_token)
+ refresh_token = response_data.get("refresh_token", refresh_token)
expiry = _parse_expiry(response_data)
return access_token, refresh_token, expiry, response_data
diff --git a/google/oauth2/credentials.py b/google/oauth2/credentials.py
index 9e11416..676a432 100644
--- a/google/oauth2/credentials.py
+++ b/google/oauth2/credentials.py
@@ -43,15 +43,22 @@
# The Google OAuth 2.0 token endpoint. Used for authorized user credentials.
-_GOOGLE_OAUTH2_TOKEN_ENDPOINT = 'https://oauth2.googleapis.com/token'
+_GOOGLE_OAUTH2_TOKEN_ENDPOINT = "https://oauth2.googleapis.com/token"
class Credentials(credentials.ReadOnlyScoped, credentials.Credentials):
"""Credentials using OAuth 2.0 access and refresh tokens."""
- def __init__(self, token, refresh_token=None, id_token=None,
- token_uri=None, client_id=None, client_secret=None,
- scopes=None):
+ def __init__(
+ self,
+ token,
+ refresh_token=None,
+ id_token=None,
+ token_uri=None,
+ client_id=None,
+ client_secret=None,
+ scopes=None,
+ ):
"""
Args:
token (Optional(str)): The OAuth 2.0 access token. Can be None
@@ -124,35 +131,43 @@
@_helpers.copy_docstring(credentials.Credentials)
def refresh(self, request):
- if (self._refresh_token is None or
- self._token_uri is None or
- self._client_id is None or
- self._client_secret is None):
+ if (
+ self._refresh_token is None
+ or self._token_uri is None
+ or self._client_id is None
+ or self._client_secret is None
+ ):
raise exceptions.RefreshError(
- 'The credentials do not contain the necessary fields need to '
- 'refresh the access token. You must specify refresh_token, '
- 'token_uri, client_id, and client_secret.')
+ "The credentials do not contain the necessary fields need to "
+ "refresh the access token. You must specify refresh_token, "
+ "token_uri, client_id, and client_secret."
+ )
- access_token, refresh_token, expiry, grant_response = (
- _client.refresh_grant(
- request, self._token_uri, self._refresh_token, self._client_id,
- self._client_secret, self._scopes))
+ access_token, refresh_token, expiry, grant_response = _client.refresh_grant(
+ request,
+ self._token_uri,
+ self._refresh_token,
+ self._client_id,
+ self._client_secret,
+ self._scopes,
+ )
self.token = access_token
self.expiry = expiry
self._refresh_token = refresh_token
- self._id_token = grant_response.get('id_token')
+ self._id_token = grant_response.get("id_token")
- if self._scopes and 'scopes' in grant_response:
+ if self._scopes and "scopes" in grant_response:
requested_scopes = frozenset(self._scopes)
- granted_scopes = frozenset(grant_response['scopes'].split())
- scopes_requested_but_not_granted = (
- requested_scopes - granted_scopes)
+ granted_scopes = frozenset(grant_response["scopes"].split())
+ scopes_requested_but_not_granted = requested_scopes - granted_scopes
if scopes_requested_but_not_granted:
raise exceptions.RefreshError(
- 'Not all requested scopes were granted by the '
- 'authorization server, missing scopes {}.'.format(
- ', '.join(scopes_requested_but_not_granted)))
+ "Not all requested scopes were granted by the "
+ "authorization server, missing scopes {}.".format(
+ ", ".join(scopes_requested_but_not_granted)
+ )
+ )
@classmethod
def from_authorized_user_info(cls, info, scopes=None):
@@ -171,21 +186,23 @@
Raises:
ValueError: If the info is not in the expected format.
"""
- keys_needed = set(('refresh_token', 'client_id', 'client_secret'))
+ keys_needed = set(("refresh_token", "client_id", "client_secret"))
missing = keys_needed.difference(six.iterkeys(info))
if missing:
raise ValueError(
- 'Authorized user info was not in the expected format, missing '
- 'fields {}.'.format(', '.join(missing)))
+ "Authorized user info was not in the expected format, missing "
+ "fields {}.".format(", ".join(missing))
+ )
return cls(
None, # No access token, must be refreshed.
- refresh_token=info['refresh_token'],
+ refresh_token=info["refresh_token"],
token_uri=_GOOGLE_OAUTH2_TOKEN_ENDPOINT,
scopes=scopes,
- client_id=info['client_id'],
- client_secret=info['client_secret'])
+ client_id=info["client_id"],
+ client_secret=info["client_secret"],
+ )
@classmethod
def from_authorized_user_file(cls, filename, scopes=None):
@@ -203,6 +220,6 @@
Raises:
ValueError: If the file is not in the expected format.
"""
- with io.open(filename, 'r', encoding='utf-8') as json_file:
+ with io.open(filename, "r", encoding="utf-8") as json_file:
data = json.load(json_file)
return cls.from_authorized_user_info(data, scopes)
diff --git a/google/oauth2/id_token.py b/google/oauth2/id_token.py
index 208ab62..bc48445 100644
--- a/google/oauth2/id_token.py
+++ b/google/oauth2/id_token.py
@@ -67,13 +67,14 @@
# The URL that provides public certificates for verifying ID tokens issued
# by Google's OAuth 2.0 authorization server.
-_GOOGLE_OAUTH2_CERTS_URL = 'https://www.googleapis.com/oauth2/v1/certs'
+_GOOGLE_OAUTH2_CERTS_URL = "https://www.googleapis.com/oauth2/v1/certs"
# The URL that provides public certificates for verifying ID tokens issued
# by Firebase and the Google APIs infrastructure
_GOOGLE_APIS_CERTS_URL = (
- 'https://www.googleapis.com/robot/v1/metadata/x509'
- '/securetoken@system.gserviceaccount.com')
+ "https://www.googleapis.com/robot/v1/metadata/x509"
+ "/securetoken@system.gserviceaccount.com"
+)
def _fetch_certs(request, certs_url):
@@ -91,17 +92,17 @@
Mapping[str, str]: A mapping of public key ID to x.509 certificate
data.
"""
- response = request(certs_url, method='GET')
+ response = request(certs_url, method="GET")
if response.status != http_client.OK:
raise exceptions.TransportError(
- 'Could not fetch certificates at {}'.format(certs_url))
+ "Could not fetch certificates at {}".format(certs_url)
+ )
- return json.loads(response.data.decode('utf-8'))
+ return json.loads(response.data.decode("utf-8"))
-def verify_token(id_token, request, audience=None,
- certs_url=_GOOGLE_OAUTH2_CERTS_URL):
+def verify_token(id_token, request, audience=None, certs_url=_GOOGLE_OAUTH2_CERTS_URL):
"""Verifies an ID token and returns the decoded token.
Args:
@@ -137,8 +138,8 @@
Mapping[str, Any]: The decoded token.
"""
return verify_token(
- id_token, request, audience=audience,
- certs_url=_GOOGLE_OAUTH2_CERTS_URL)
+ id_token, request, audience=audience, certs_url=_GOOGLE_OAUTH2_CERTS_URL
+ )
def verify_firebase_token(id_token, request, audience=None):
@@ -156,4 +157,5 @@
Mapping[str, Any]: The decoded token.
"""
return verify_token(
- id_token, request, audience=audience, certs_url=_GOOGLE_APIS_CERTS_URL)
+ id_token, request, audience=audience, certs_url=_GOOGLE_APIS_CERTS_URL
+ )
diff --git a/google/oauth2/service_account.py b/google/oauth2/service_account.py
index c60c565..17fdd51 100644
--- a/google/oauth2/service_account.py
+++ b/google/oauth2/service_account.py
@@ -82,9 +82,7 @@
_DEFAULT_TOKEN_LIFETIME_SECS = 3600 # 1 hour in seconds
-class Credentials(credentials.Signing,
- credentials.Scoped,
- credentials.Credentials):
+class Credentials(credentials.Signing, credentials.Scoped, credentials.Credentials):
"""Service account credentials
Usually, you'll create these credentials with one of the helper
@@ -116,8 +114,16 @@
delegated_credentials = credentials.with_subject(subject)
"""
- def __init__(self, signer, service_account_email, token_uri, scopes=None,
- subject=None, project_id=None, additional_claims=None):
+ def __init__(
+ self,
+ signer,
+ service_account_email,
+ token_uri,
+ scopes=None,
+ subject=None,
+ project_id=None,
+ additional_claims=None,
+ ):
"""
Args:
signer (google.auth.crypt.Signer): The signer used to sign JWTs.
@@ -169,9 +175,11 @@
"""
return cls(
signer,
- service_account_email=info['client_email'],
- token_uri=info['token_uri'],
- project_id=info.get('project_id'), **kwargs)
+ service_account_email=info["client_email"],
+ token_uri=info["token_uri"],
+ project_id=info.get("project_id"),
+ **kwargs
+ )
@classmethod
def from_service_account_info(cls, info, **kwargs):
@@ -190,7 +198,8 @@
ValueError: If the info is not in the expected format.
"""
signer = _service_account_info.from_dict(
- info, require=['client_email', 'token_uri'])
+ info, require=["client_email", "token_uri"]
+ )
return cls._from_signer_and_info(signer, info, **kwargs)
@classmethod
@@ -206,7 +215,8 @@
credentials.
"""
info, signer = _service_account_info.from_filename(
- filename, require=['client_email', 'token_uri'])
+ filename, require=["client_email", "token_uri"]
+ )
return cls._from_signer_and_info(signer, info, **kwargs)
@property
@@ -237,7 +247,8 @@
token_uri=self._token_uri,
subject=self._subject,
project_id=self._project_id,
- additional_claims=self._additional_claims.copy())
+ additional_claims=self._additional_claims.copy(),
+ )
def with_subject(self, subject):
"""Create a copy of these credentials with the specified subject.
@@ -256,7 +267,8 @@
token_uri=self._token_uri,
subject=subject,
project_id=self._project_id,
- additional_claims=self._additional_claims.copy())
+ additional_claims=self._additional_claims.copy(),
+ )
def with_claims(self, additional_claims):
"""Returns a copy of these credentials with modified claims.
@@ -280,7 +292,8 @@
token_uri=self._token_uri,
subject=self._subject,
project_id=self._project_id,
- additional_claims=new_additional_claims)
+ additional_claims=new_additional_claims,
+ )
def _make_authorization_grant_assertion(self):
"""Create the OAuth 2.0 assertion.
@@ -296,20 +309,20 @@
expiry = now + lifetime
payload = {
- 'iat': _helpers.datetime_to_secs(now),
- 'exp': _helpers.datetime_to_secs(expiry),
+ "iat": _helpers.datetime_to_secs(now),
+ "exp": _helpers.datetime_to_secs(expiry),
# The issuer must be the service account email.
- 'iss': self._service_account_email,
+ "iss": self._service_account_email,
# The audience must be the auth token endpoint's URI
- 'aud': self._token_uri,
- 'scope': _helpers.scopes_to_string(self._scopes or ())
+ "aud": self._token_uri,
+ "scope": _helpers.scopes_to_string(self._scopes or ()),
}
payload.update(self._additional_claims)
# The subject can be a user email for domain-wide delegation.
if self._subject:
- payload.setdefault('sub', self._subject)
+ payload.setdefault("sub", self._subject)
token = jwt.encode(self._signer, payload)
@@ -318,8 +331,7 @@
@_helpers.copy_docstring(credentials.Credentials)
def refresh(self, request):
assertion = self._make_authorization_grant_assertion()
- access_token, expiry, _ = _client.jwt_grant(
- request, self._token_uri, assertion)
+ access_token, expiry, _ = _client.jwt_grant(request, self._token_uri, assertion)
self.token = access_token
self.expiry = expiry
@@ -379,8 +391,15 @@
delegated_credentials = credentials.with_subject(subject)
"""
- def __init__(self, signer, service_account_email, token_uri,
- target_audience, additional_claims=None):
+
+ def __init__(
+ self,
+ signer,
+ service_account_email,
+ token_uri,
+ target_audience,
+ additional_claims=None,
+ ):
"""
Args:
signer (google.auth.crypt.Signer): The signer used to sign JWTs.
@@ -424,8 +443,8 @@
Raises:
ValueError: If the info is not in the expected format.
"""
- kwargs.setdefault('service_account_email', info['client_email'])
- kwargs.setdefault('token_uri', info['token_uri'])
+ kwargs.setdefault("service_account_email", info["client_email"])
+ kwargs.setdefault("token_uri", info["token_uri"])
return cls(signer, **kwargs)
@classmethod
@@ -445,7 +464,8 @@
ValueError: If the info is not in the expected format.
"""
signer = _service_account_info.from_dict(
- info, require=['client_email', 'token_uri'])
+ info, require=["client_email", "token_uri"]
+ )
return cls._from_signer_and_info(signer, info, **kwargs)
@classmethod
@@ -461,7 +481,8 @@
credentials.
"""
info, signer = _service_account_info.from_filename(
- filename, require=['client_email', 'token_uri'])
+ filename, require=["client_email", "token_uri"]
+ )
return cls._from_signer_and_info(signer, info, **kwargs)
def with_target_audience(self, target_audience):
@@ -481,7 +502,8 @@
service_account_email=self._service_account_email,
token_uri=self._token_uri,
target_audience=target_audience,
- additional_claims=self._additional_claims.copy())
+ additional_claims=self._additional_claims.copy(),
+ )
def _make_authorization_grant_assertion(self):
"""Create the OAuth 2.0 assertion.
@@ -497,15 +519,15 @@
expiry = now + lifetime
payload = {
- 'iat': _helpers.datetime_to_secs(now),
- 'exp': _helpers.datetime_to_secs(expiry),
+ "iat": _helpers.datetime_to_secs(now),
+ "exp": _helpers.datetime_to_secs(expiry),
# The issuer must be the service account email.
- 'iss': self.service_account_email,
+ "iss": self.service_account_email,
# The audience must be the auth token endpoint's URI
- 'aud': self._token_uri,
+ "aud": self._token_uri,
# The target audience specifies which service the ID token is
# intended for.
- 'target_audience': self._target_audience
+ "target_audience": self._target_audience,
}
payload.update(self._additional_claims)
@@ -518,7 +540,8 @@
def refresh(self, request):
assertion = self._make_authorization_grant_assertion()
access_token, expiry, _ = _client.id_token_jwt_grant(
- request, self._token_uri, assertion)
+ request, self._token_uri, assertion
+ )
self.token = access_token
self.expiry = expiry