chore: blacken (#375)
diff --git a/google/auth/__init__.py b/google/auth/__init__.py
index 65e1395..5f78cd1 100644
--- a/google/auth/__init__.py
+++ b/google/auth/__init__.py
@@ -19,9 +19,7 @@
from google.auth._default import default
-__all__ = [
- 'default',
-]
+__all__ = ["default"]
# Set default logging handler to avoid "No handler found" warnings.
diff --git a/google/auth/_cloud_sdk.py b/google/auth/_cloud_sdk.py
index 0d4b222..61ffd4f 100644
--- a/google/auth/_cloud_sdk.py
+++ b/google/auth/_cloud_sdk.py
@@ -23,20 +23,21 @@
# The ~/.config subdirectory containing gcloud credentials.
-_CONFIG_DIRECTORY = 'gcloud'
+_CONFIG_DIRECTORY = "gcloud"
# Windows systems store config at %APPDATA%\gcloud
-_WINDOWS_CONFIG_ROOT_ENV_VAR = 'APPDATA'
+_WINDOWS_CONFIG_ROOT_ENV_VAR = "APPDATA"
# The name of the file in the Cloud SDK config that contains default
# credentials.
-_CREDENTIALS_FILENAME = 'application_default_credentials.json'
+_CREDENTIALS_FILENAME = "application_default_credentials.json"
# The name of the Cloud SDK shell script
-_CLOUD_SDK_POSIX_COMMAND = 'gcloud'
-_CLOUD_SDK_WINDOWS_COMMAND = 'gcloud.cmd'
+_CLOUD_SDK_POSIX_COMMAND = "gcloud"
+_CLOUD_SDK_WINDOWS_COMMAND = "gcloud.cmd"
# The command to get the Cloud SDK configuration
-_CLOUD_SDK_CONFIG_COMMAND = ('config', 'config-helper', '--format', 'json')
+_CLOUD_SDK_CONFIG_COMMAND = ("config", "config-helper", "--format", "json")
# Cloud SDK's application-default client ID
CLOUD_SDK_CLIENT_ID = (
- '764086051850-6qr4p6gpi6hn506pt8ejuq83di341hur.apps.googleusercontent.com')
+ "764086051850-6qr4p6gpi6hn506pt8ejuq83di341hur.apps.googleusercontent.com"
+)
def get_config_path():
@@ -52,21 +53,19 @@
pass
# Non-windows systems store this at ~/.config/gcloud
- if os.name != 'nt':
- return os.path.join(
- os.path.expanduser('~'), '.config', _CONFIG_DIRECTORY)
+ if os.name != "nt":
+ return os.path.join(os.path.expanduser("~"), ".config", _CONFIG_DIRECTORY)
# Windows systems store config at %APPDATA%\gcloud
else:
try:
return os.path.join(
- os.environ[_WINDOWS_CONFIG_ROOT_ENV_VAR],
- _CONFIG_DIRECTORY)
+ os.environ[_WINDOWS_CONFIG_ROOT_ENV_VAR], _CONFIG_DIRECTORY
+ )
except KeyError:
# This should never happen unless someone is really
# messing with things, but we'll cover the case anyway.
- drive = os.environ.get('SystemDrive', 'C:')
- return os.path.join(
- drive, '\\', _CONFIG_DIRECTORY)
+ drive = os.environ.get("SystemDrive", "C:")
+ return os.path.join(drive, "\\", _CONFIG_DIRECTORY)
def get_application_default_credentials_path():
@@ -93,8 +92,7 @@
Raises:
ValueError: if the info is in the wrong format or missing data.
"""
- return google.oauth2.credentials.Credentials.from_authorized_user_info(
- info)
+ return google.oauth2.credentials.Credentials.from_authorized_user_info(info)
def get_project_id():
@@ -103,24 +101,24 @@
Returns:
Optional[str]: The project ID.
"""
- if os.name == 'nt':
+ if os.name == "nt":
command = _CLOUD_SDK_WINDOWS_COMMAND
else:
command = _CLOUD_SDK_POSIX_COMMAND
try:
output = subprocess.check_output(
- (command,) + _CLOUD_SDK_CONFIG_COMMAND,
- stderr=subprocess.STDOUT)
+ (command,) + _CLOUD_SDK_CONFIG_COMMAND, stderr=subprocess.STDOUT
+ )
except (subprocess.CalledProcessError, OSError, IOError):
return None
try:
- configuration = json.loads(output.decode('utf-8'))
+ configuration = json.loads(output.decode("utf-8"))
except ValueError:
return None
try:
- return configuration['configuration']['properties']['core']['project']
+ return configuration["configuration"]["properties"]["core"]["project"]
except KeyError:
return None
diff --git a/google/auth/_default.py b/google/auth/_default.py
index 27de58d..32e81ba 100644
--- a/google/auth/_default.py
+++ b/google/auth/_default.py
@@ -32,8 +32,8 @@
_LOGGER = logging.getLogger(__name__)
# Valid types accepted for file-based credentials.
-_AUTHORIZED_USER_TYPE = 'authorized_user'
-_SERVICE_ACCOUNT_TYPE = 'service_account'
+_AUTHORIZED_USER_TYPE = "authorized_user"
+_SERVICE_ACCOUNT_TYPE = "service_account"
_VALID_TYPES = (_AUTHORIZED_USER_TYPE, _SERVICE_ACCOUNT_TYPE)
# Help message when no credentials can be found.
@@ -42,7 +42,9 @@
explicitly create credentials and re-run the application. For more \
information, please see \
https://cloud.google.com/docs/authentication/getting-started
-""".format(env=environment_vars.CREDENTIALS).strip()
+""".format(
+ env=environment_vars.CREDENTIALS
+).strip()
# Warning when using Cloud SDK user credentials
_CLOUD_SDK_CREDENTIALS_WARNING = """\
@@ -62,6 +64,7 @@
quota. If this is the case, warn about it.
"""
from google.auth import _cloud_sdk
+
if credentials.client_id == _cloud_sdk.CLOUD_SDK_CLIENT_ID:
warnings.warn(_CLOUD_SDK_CREDENTIALS_WARNING)
@@ -86,20 +89,21 @@
"""
if not os.path.exists(filename):
raise exceptions.DefaultCredentialsError(
- 'File {} was not found.'.format(filename))
+ "File {} was not found.".format(filename)
+ )
- with io.open(filename, 'r') as file_obj:
+ with io.open(filename, "r") as file_obj:
try:
info = json.load(file_obj)
except ValueError as caught_exc:
new_exc = exceptions.DefaultCredentialsError(
- 'File {} is not a valid json file.'.format(filename),
- caught_exc)
+ "File {} is not a valid json file.".format(filename), caught_exc
+ )
six.raise_from(new_exc, caught_exc)
# The type key should indicate that the file is either a service account
# credentials file or an authorized user credentials file.
- credential_type = info.get('type')
+ credential_type = info.get("type")
if credential_type == _AUTHORIZED_USER_TYPE:
from google.auth import _cloud_sdk
@@ -107,8 +111,7 @@
try:
credentials = _cloud_sdk.load_authorized_user_credentials(info)
except ValueError as caught_exc:
- msg = 'Failed to load authorized user credentials from {}'.format(
- filename)
+ msg = "Failed to load authorized user credentials from {}".format(filename)
new_exc = exceptions.DefaultCredentialsError(msg, caught_exc)
six.raise_from(new_exc, caught_exc)
# Authorized user credentials do not contain the project ID.
@@ -119,20 +122,20 @@
from google.oauth2 import service_account
try:
- credentials = (
- service_account.Credentials.from_service_account_info(info))
+ credentials = service_account.Credentials.from_service_account_info(info)
except ValueError as caught_exc:
- msg = 'Failed to load service account credentials from {}'.format(
- filename)
+ msg = "Failed to load service account credentials from {}".format(filename)
new_exc = exceptions.DefaultCredentialsError(msg, caught_exc)
six.raise_from(new_exc, caught_exc)
- return credentials, info.get('project_id')
+ return credentials, info.get("project_id")
else:
raise exceptions.DefaultCredentialsError(
- 'The file {file} does not have a valid type. '
- 'Type is {type}, expected one of {valid_types}.'.format(
- file=filename, type=credential_type, valid_types=_VALID_TYPES))
+ "The file {file} does not have a valid type. "
+ "Type is {type}, expected one of {valid_types}.".format(
+ file=filename, type=credential_type, valid_types=_VALID_TYPES
+ )
+ )
def _get_gcloud_sdk_credentials():
@@ -140,14 +143,12 @@
from google.auth import _cloud_sdk
# Check if application default credentials exist.
- credentials_filename = (
- _cloud_sdk.get_application_default_credentials_path())
+ credentials_filename = _cloud_sdk.get_application_default_credentials_path()
if not os.path.isfile(credentials_filename):
return None, None
- credentials, project_id = _load_credentials_from_file(
- credentials_filename)
+ credentials, project_id = _load_credentials_from_file(credentials_filename)
if not project_id:
project_id = _cloud_sdk.get_project_id()
@@ -162,7 +163,8 @@
if explicit_file is not None:
credentials, project_id = _load_credentials_from_file(
- os.environ[environment_vars.CREDENTIALS])
+ os.environ[environment_vars.CREDENTIALS]
+ )
return credentials, project_id
@@ -292,14 +294,15 @@
from google.auth.credentials import with_scopes_if_required
explicit_project_id = os.environ.get(
- environment_vars.PROJECT,
- os.environ.get(environment_vars.LEGACY_PROJECT))
+ environment_vars.PROJECT, os.environ.get(environment_vars.LEGACY_PROJECT)
+ )
checkers = (
_get_explicit_environ_credentials,
_get_gcloud_sdk_credentials,
_get_gae_credentials,
- lambda: _get_gce_credentials(request))
+ lambda: _get_gce_credentials(request),
+ )
for checker in checkers:
credentials, project_id = checker()
@@ -308,10 +311,11 @@
effective_project_id = explicit_project_id or project_id
if not effective_project_id:
_LOGGER.warning(
- 'No project ID could be determined. Consider running '
- '`gcloud config set project` or setting the %s '
- 'environment variable',
- environment_vars.PROJECT)
+ "No project ID could be determined. Consider running "
+ "`gcloud config set project` or setting the %s "
+ "environment variable",
+ environment_vars.PROJECT,
+ )
return credentials, effective_project_id
raise exceptions.DefaultCredentialsError(_HELP_MESSAGE)
diff --git a/google/auth/_helpers.py b/google/auth/_helpers.py
index b32801a..ecb88ff 100644
--- a/google/auth/_helpers.py
+++ b/google/auth/_helpers.py
@@ -36,6 +36,7 @@
Callable: A decorator that will copy the docstring of the same
named method in the source class to the decorated method.
"""
+
def decorator(method):
"""Decorator implementation.
@@ -49,12 +50,13 @@
ValueError: if the method already has a docstring.
"""
if method.__doc__:
- raise ValueError('Method already has a docstring.')
+ raise ValueError("Method already has a docstring.")
source_method = getattr(source_class, method.__name__)
method.__doc__ = source_method.__doc__
return method
+
return decorator
@@ -79,7 +81,7 @@
return calendar.timegm(value.utctimetuple())
-def to_bytes(value, encoding='utf-8'):
+def to_bytes(value, encoding="utf-8"):
"""Converts a string value to bytes, if necessary.
Unfortunately, ``six.b`` is insufficient for this task since in
@@ -97,12 +99,11 @@
Raises:
ValueError: If the value could not be converted to bytes.
"""
- result = (value.encode(encoding)
- if isinstance(value, six.text_type) else value)
+ 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 ValueError("{0!r} could not be converted to bytes".format(value))
def from_bytes(value):
@@ -118,13 +119,11 @@
Raises:
ValueError: If the value could not be converted to unicode.
"""
- result = (value.decode('utf-8')
- if isinstance(value, six.binary_type) else value)
+ 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 ValueError("{0!r} could not be converted to unicode".format(value))
def update_query(url, params, remove=None):
@@ -163,9 +162,8 @@
query_params.update(params)
# Remove any values specified in remove.
query_params = {
- key: value for key, value
- in six.iteritems(query_params)
- if key not in remove}
+ key: value for key, value in six.iteritems(query_params) if key not in remove
+ }
# Re-encoded the query string.
new_query = urllib.parse.urlencode(query_params, doseq=True)
# Unsplit the url.
@@ -183,7 +181,7 @@
Returns:
str: The scopes formatted as a single string.
"""
- return ' '.join(scopes)
+ return " ".join(scopes)
def string_to_scopes(scopes):
@@ -198,7 +196,7 @@
if not scopes:
return []
- return scopes.split(' ')
+ return scopes.split(" ")
def padded_urlsafe_b64decode(value):
@@ -213,7 +211,7 @@
bytes: The decoded value
"""
b64string = to_bytes(value)
- padded = b64string + b'=' * (-len(b64string) % 4)
+ padded = b64string + b"=" * (-len(b64string) % 4)
return base64.urlsafe_b64decode(padded)
@@ -231,4 +229,4 @@
Returns:
Union[str|bytes]: The encoded value
"""
- return base64.urlsafe_b64encode(value).rstrip(b'=')
+ return base64.urlsafe_b64encode(value).rstrip(b"=")
diff --git a/google/auth/_oauth2client.py b/google/auth/_oauth2client.py
index afe7dc4..b14a382 100644
--- a/google/auth/_oauth2client.py
+++ b/google/auth/_oauth2client.py
@@ -34,18 +34,17 @@
import oauth2client.contrib.gce
import oauth2client.service_account
except ImportError as caught_exc:
- six.raise_from(
- ImportError('oauth2client is not installed.'), caught_exc)
+ six.raise_from(ImportError("oauth2client is not installed."), caught_exc)
try:
import oauth2client.contrib.appengine # pytype: disable=import-error
+
_HAS_APPENGINE = True
except ImportError:
_HAS_APPENGINE = False
-_CONVERT_ERROR_TMPL = (
- 'Unable to convert {} to a google-auth credentials class.')
+_CONVERT_ERROR_TMPL = "Unable to convert {} to a google-auth credentials class."
def _convert_oauth2_credentials(credentials):
@@ -65,7 +64,8 @@
token_uri=credentials.token_uri,
client_id=credentials.client_id,
client_secret=credentials.client_secret,
- scopes=credentials.scopes)
+ scopes=credentials.scopes,
+ )
new_credentials._expires = credentials.token_expiry
@@ -85,9 +85,8 @@
google.oauth2.service_account.Credentials: The converted credentials.
"""
info = credentials.serialization_data.copy()
- info['token_uri'] = credentials.token_uri
- return google.oauth2.service_account.Credentials.from_service_account_info(
- info)
+ info["token_uri"] = credentials.token_uri
+ return google.oauth2.service_account.Credentials.from_service_account_info(info)
def _convert_gce_app_assertion_credentials(credentials):
@@ -101,7 +100,8 @@
google.oauth2.service_account.Credentials: The converted credentials.
"""
return google.auth.compute_engine.Credentials(
- service_account_email=credentials.service_account_email)
+ service_account_email=credentials.service_account_email
+ )
def _convert_appengine_app_assertion_credentials(credentials):
@@ -117,24 +117,22 @@
# pylint: disable=invalid-name
return google.auth.app_engine.Credentials(
scopes=_helpers.string_to_scopes(credentials.scope),
- service_account_id=credentials.service_account_id)
+ service_account_id=credentials.service_account_id,
+ )
_CLASS_CONVERSION_MAP = {
oauth2client.client.OAuth2Credentials: _convert_oauth2_credentials,
oauth2client.client.GoogleCredentials: _convert_oauth2_credentials,
- oauth2client.service_account.ServiceAccountCredentials:
- _convert_service_account_credentials,
- oauth2client.service_account._JWTAccessCredentials:
- _convert_service_account_credentials,
- oauth2client.contrib.gce.AppAssertionCredentials:
- _convert_gce_app_assertion_credentials,
+ oauth2client.service_account.ServiceAccountCredentials: _convert_service_account_credentials,
+ oauth2client.service_account._JWTAccessCredentials: _convert_service_account_credentials,
+ oauth2client.contrib.gce.AppAssertionCredentials: _convert_gce_app_assertion_credentials,
}
if _HAS_APPENGINE:
_CLASS_CONVERSION_MAP[
- oauth2client.contrib.appengine.AppAssertionCredentials] = (
- _convert_appengine_app_assertion_credentials)
+ oauth2client.contrib.appengine.AppAssertionCredentials
+ ] = _convert_appengine_app_assertion_credentials
def convert(credentials):
diff --git a/google/auth/_service_account_info.py b/google/auth/_service_account_info.py
index dd39ea7..790be92 100644
--- a/google/auth/_service_account_info.py
+++ b/google/auth/_service_account_info.py
@@ -47,8 +47,9 @@
if missing:
raise ValueError(
- 'Service account info was not in the expected format, missing '
- 'fields {}.'.format(', '.join(missing)))
+ "Service account info was not in the expected format, missing "
+ "fields {}.".format(", ".join(missing))
+ )
# Create a signer.
signer = crypt.RSASigner.from_service_account_info(data)
@@ -68,6 +69,6 @@
Tuple[ Mapping[str, str], google.auth.crypt.Signer ]: The verified
info and a signer instance.
"""
- 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 data, from_dict(data, require=require)
diff --git a/google/auth/app_engine.py b/google/auth/app_engine.py
index 91ba842..aec86a6 100644
--- a/google/auth/app_engine.py
+++ b/google/auth/app_engine.py
@@ -73,13 +73,11 @@
# Pylint rightfully thinks EnvironmentError 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 EnvironmentError("The App Engine APIs are not available.")
return app_identity.get_application_id()
-class Credentials(credentials.Scoped, credentials.Signing,
- credentials.Credentials):
+class Credentials(credentials.Scoped, credentials.Signing, credentials.Credentials):
"""App Engine standard environment credentials.
These credentials use the App Engine App Identity API to obtain access
@@ -103,8 +101,7 @@
# Pylint rightfully thinks EnvironmentError 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 EnvironmentError("The App Engine APIs are not available.")
super(Credentials, self).__init__()
self._scopes = scopes
@@ -115,7 +112,8 @@
def refresh(self, request):
# pylint: disable=unused-argument
token, ttl = app_identity.get_access_token(
- self._scopes, self._service_account_id)
+ self._scopes, self._service_account_id
+ )
expiry = datetime.datetime.utcfromtimestamp(ttl)
self.token, self.expiry = token, expiry
@@ -139,7 +137,8 @@
@_helpers.copy_docstring(credentials.Scoped)
def with_scopes(self, scopes):
return self.__class__(
- scopes=scopes, service_account_id=self._service_account_id)
+ scopes=scopes, service_account_id=self._service_account_id
+ )
@_helpers.copy_docstring(credentials.Signing)
def sign_bytes(self, message):
diff --git a/google/auth/compute_engine/__init__.py b/google/auth/compute_engine/__init__.py
index ca31b46..461f104 100644
--- a/google/auth/compute_engine/__init__.py
+++ b/google/auth/compute_engine/__init__.py
@@ -18,7 +18,4 @@
from google.auth.compute_engine.credentials import IDTokenCredentials
-__all__ = [
- 'Credentials',
- 'IDTokenCredentials',
-]
+__all__ = ["Credentials", "IDTokenCredentials"]
diff --git a/google/auth/compute_engine/_metadata.py b/google/auth/compute_engine/_metadata.py
index d8004bb..f4fae72 100644
--- a/google/auth/compute_engine/_metadata.py
+++ b/google/auth/compute_engine/_metadata.py
@@ -32,21 +32,23 @@
_LOGGER = logging.getLogger(__name__)
-_METADATA_ROOT = 'http://{}/computeMetadata/v1/'.format(
- os.getenv(environment_vars.GCE_METADATA_ROOT, 'metadata.google.internal'))
+_METADATA_ROOT = "http://{}/computeMetadata/v1/".format(
+ os.getenv(environment_vars.GCE_METADATA_ROOT, "metadata.google.internal")
+)
# This is used to ping the metadata server, it avoids the cost of a DNS
# lookup.
-_METADATA_IP_ROOT = 'http://{}'.format(
- os.getenv(environment_vars.GCE_METADATA_IP, '169.254.169.254'))
-_METADATA_FLAVOR_HEADER = 'metadata-flavor'
-_METADATA_FLAVOR_VALUE = 'Google'
+_METADATA_IP_ROOT = "http://{}".format(
+ os.getenv(environment_vars.GCE_METADATA_IP, "169.254.169.254")
+)
+_METADATA_FLAVOR_HEADER = "metadata-flavor"
+_METADATA_FLAVOR_VALUE = "Google"
_METADATA_HEADERS = {_METADATA_FLAVOR_HEADER: _METADATA_FLAVOR_VALUE}
# Timeout in seconds to wait for the GCE metadata server when detecting the
# GCE environment.
try:
- _METADATA_DEFAULT_TIMEOUT = int(os.getenv('GCE_METADATA_TIMEOUT', 3))
+ _METADATA_DEFAULT_TIMEOUT = int(os.getenv("GCE_METADATA_TIMEOUT", 3))
except ValueError: # pragma: NO COVER
_METADATA_DEFAULT_TIMEOUT = 3
@@ -74,16 +76,24 @@
while retries < retry_count:
try:
response = request(
- url=_METADATA_IP_ROOT, method='GET', headers=_METADATA_HEADERS,
- timeout=timeout)
+ url=_METADATA_IP_ROOT,
+ method="GET",
+ headers=_METADATA_HEADERS,
+ timeout=timeout,
+ )
metadata_flavor = response.headers.get(_METADATA_FLAVOR_HEADER)
- return (response.status == http_client.OK and
- metadata_flavor == _METADATA_FLAVOR_VALUE)
+ return (
+ response.status == http_client.OK
+ and metadata_flavor == _METADATA_FLAVOR_VALUE
+ )
except exceptions.TransportError:
- _LOGGER.info('Compute Engine Metadata server unavailable on'
- 'attempt %s of %s', retries+1, retry_count)
+ _LOGGER.info(
+ "Compute Engine Metadata server unavailable on" "attempt %s of %s",
+ retries + 1,
+ retry_count,
+ )
retries += 1
return False
@@ -115,29 +125,33 @@
query_params = {}
if recursive:
- query_params['recursive'] = 'true'
+ query_params["recursive"] = "true"
url = _helpers.update_query(base_url, query_params)
- response = request(url=url, method='GET', headers=_METADATA_HEADERS)
+ response = request(url=url, method="GET", headers=_METADATA_HEADERS)
if response.status == http_client.OK:
content = _helpers.from_bytes(response.data)
- if response.headers['content-type'] == 'application/json':
+ if response.headers["content-type"] == "application/json":
try:
return json.loads(content)
except ValueError as caught_exc:
new_exc = exceptions.TransportError(
- 'Received invalid JSON from the Google Compute Engine'
- 'metadata service: {:.20}'.format(content))
+ "Received invalid JSON from the Google Compute Engine"
+ "metadata service: {:.20}".format(content)
+ )
six.raise_from(new_exc, caught_exc)
else:
return content
else:
raise exceptions.TransportError(
- 'Failed to retrieve {} from the Google Compute Engine'
- 'metadata service. Status: {} Response:\n{}'.format(
- url, response.status, response.data), response)
+ "Failed to retrieve {} from the Google Compute Engine"
+ "metadata service. Status: {} Response:\n{}".format(
+ url, response.status, response.data
+ ),
+ response,
+ )
def get_project_id(request):
@@ -154,10 +168,10 @@
google.auth.exceptions.TransportError: if an error occurred while
retrieving metadata.
"""
- return get(request, 'project/project-id')
+ return get(request, "project/project-id")
-def get_service_account_info(request, service_account='default'):
+def get_service_account_info(request, service_account="default"):
"""Get information about a service account from the metadata server.
Args:
@@ -182,11 +196,12 @@
"""
return get(
request,
- 'instance/service-accounts/{0}/'.format(service_account),
- recursive=True)
+ "instance/service-accounts/{0}/".format(service_account),
+ recursive=True,
+ )
-def get_service_account_token(request, service_account='default'):
+def get_service_account_token(request, service_account="default"):
"""Get the OAuth 2.0 access token for a service account.
Args:
@@ -204,8 +219,9 @@
retrieving metadata.
"""
token_json = get(
- request,
- 'instance/service-accounts/{0}/token'.format(service_account))
+ request, "instance/service-accounts/{0}/token".format(service_account)
+ )
token_expiry = _helpers.utcnow() + datetime.timedelta(
- seconds=token_json['expires_in'])
- return token_json['access_token'], token_expiry
+ seconds=token_json["expires_in"]
+ )
+ return token_json["access_token"], token_expiry
diff --git a/google/auth/compute_engine/credentials.py b/google/auth/compute_engine/credentials.py
index d9c6e26..eeb92f5 100644
--- a/google/auth/compute_engine/credentials.py
+++ b/google/auth/compute_engine/credentials.py
@@ -54,7 +54,7 @@
https://cloud.google.com/compute/docs/authentication#using
"""
- def __init__(self, service_account_email='default'):
+ def __init__(self, service_account_email="default"):
"""
Args:
service_account_email (str): The service account email to use, or
@@ -74,11 +74,11 @@
HTTP requests.
"""
info = _metadata.get_service_account_info(
- request,
- service_account=self._service_account_email)
+ request, service_account=self._service_account_email
+ )
- self._service_account_email = info['email']
- self._scopes = info['scopes']
+ self._service_account_email = info["email"]
+ self._scopes = info["scopes"]
def refresh(self, request):
"""Refresh the access token and scopes.
@@ -95,8 +95,8 @@
try:
self._retrieve_info(request)
self.token, self.expiry = _metadata.get_service_account_token(
- request,
- service_account=self._service_account_email)
+ request, service_account=self._service_account_email
+ )
except exceptions.TransportError as caught_exc:
new_exc = exceptions.RefreshError(caught_exc)
six.raise_from(new_exc, caught_exc)
@@ -117,7 +117,7 @@
_DEFAULT_TOKEN_LIFETIME_SECS = 3600 # 1 hour in seconds
-_DEFAULT_TOKEN_URI = 'https://www.googleapis.com/oauth2/v4/token'
+_DEFAULT_TOKEN_URI = "https://www.googleapis.com/oauth2/v4/token"
class IDTokenCredentials(credentials.Credentials, credentials.Signing):
@@ -128,10 +128,15 @@
In order for this to work, the GCE instance must have been started with
a service account that has access to the IAM Cloud API.
"""
- def __init__(self, request, target_audience,
- token_uri=_DEFAULT_TOKEN_URI,
- additional_claims=None,
- service_account_email=None):
+
+ def __init__(
+ self,
+ request,
+ target_audience,
+ token_uri=_DEFAULT_TOKEN_URI,
+ additional_claims=None,
+ service_account_email=None,
+ ):
"""
Args:
request (google.auth.transport.Request): The object used to make
@@ -150,13 +155,14 @@
if service_account_email is None:
sa_info = _metadata.get_service_account_info(request)
- service_account_email = sa_info['email']
+ service_account_email = sa_info["email"]
self._service_account_email = service_account_email
self._signer = iam.Signer(
request=request,
credentials=Credentials(),
- service_account_email=service_account_email)
+ service_account_email=service_account_email,
+ )
self._token_uri = token_uri
self._target_audience = target_audience
@@ -181,7 +187,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.
@@ -195,15 +202,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)
@@ -216,7 +223,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
diff --git a/google/auth/credentials.py b/google/auth/credentials.py
index 8ff1f02..81bbd03 100644
--- a/google/auth/credentials.py
+++ b/google/auth/credentials.py
@@ -41,6 +41,7 @@
construction. Some classes will provide mechanisms to copy the credentials
with modifications such as :meth:`ScopedCredentials.with_scopes`.
"""
+
def __init__(self):
self.token = None
"""str: The bearer token that can be used in HTTP headers to make
@@ -88,7 +89,7 @@
"""
# pylint: disable=missing-raises-doc
# (pylint doesn't recognize that this is abstract)
- raise NotImplementedError('Refresh must be implemented')
+ raise NotImplementedError("Refresh must be implemented")
def apply(self, headers, token=None):
"""Apply the token to the authentication header.
@@ -98,8 +99,9 @@
token (Optional[str]): If specified, overrides the current access
token.
"""
- headers['authorization'] = 'Bearer {}'.format(
- _helpers.from_bytes(token or self.token))
+ headers["authorization"] = "Bearer {}".format(
+ _helpers.from_bytes(token or self.token)
+ )
def before_request(self, request, method, url, headers):
"""Performs credential-specific before request logic.
@@ -189,6 +191,7 @@
.. _RFC6749 Section 3.3: https://tools.ietf.org/html/rfc6749#section-3.3
"""
+
def __init__(self):
super(ReadOnlyScoped, self).__init__()
self._scopes = None
@@ -247,6 +250,7 @@
.. _RFC6749 Section 3.3: https://tools.ietf.org/html/rfc6749#section-3.3
"""
+
@abc.abstractmethod
def with_scopes(self, scopes):
"""Create a copy of these credentials with the specified scopes.
@@ -260,7 +264,7 @@
This can be avoided by checking :attr:`requires_scopes` before
calling this method.
"""
- raise NotImplementedError('This class does not require scoping.')
+ raise NotImplementedError("This class does not require scoping.")
def with_scopes_if_required(credentials, scopes):
@@ -305,18 +309,18 @@
"""
# pylint: disable=missing-raises-doc,redundant-returns-doc
# (pylint doesn't recognize that this is abstract)
- raise NotImplementedError('Sign bytes must be implemented.')
+ raise NotImplementedError("Sign bytes must be implemented.")
@abc.abstractproperty
def signer_email(self):
"""Optional[str]: An email address that identifies the signer."""
# pylint: disable=missing-raises-doc
# (pylint doesn't recognize that this is abstract)
- raise NotImplementedError('Signer email must be implemented.')
+ raise NotImplementedError("Signer email must be implemented.")
@abc.abstractproperty
def signer(self):
"""google.auth.crypt.Signer: The signer used to sign bytes."""
# pylint: disable=missing-raises-doc
# (pylint doesn't recognize that this is abstract)
- raise NotImplementedError('Signer must be implemented.')
+ raise NotImplementedError("Signer must be implemented.")
diff --git a/google/auth/crypt/__init__.py b/google/auth/crypt/__init__.py
index 7baa206..bf66e71 100644
--- a/google/auth/crypt/__init__.py
+++ b/google/auth/crypt/__init__.py
@@ -39,12 +39,7 @@
from google.auth.crypt import rsa
-__all__ = [
- 'RSASigner',
- 'RSAVerifier',
- 'Signer',
- 'Verifier',
-]
+__all__ = ["RSASigner", "RSAVerifier", "Signer", "Verifier"]
# Aliases to maintain the v1.0.0 interface, as the crypt module was split
# into submodules.
diff --git a/google/auth/crypt/_cryptography_rsa.py b/google/auth/crypt/_cryptography_rsa.py
index 87076b0..285cf5c 100644
--- a/google/auth/crypt/_cryptography_rsa.py
+++ b/google/auth/crypt/_cryptography_rsa.py
@@ -31,18 +31,18 @@
from google.auth.crypt import base
_IMPORT_ERROR_MSG = (
- 'cryptography>=1.4.0 is required to use cryptography-based RSA '
- 'implementation.')
+ "cryptography>=1.4.0 is required to use cryptography-based RSA " "implementation."
+)
try: # pragma: NO COVER
- release = pkg_resources.get_distribution('cryptography').parsed_version
- if release < pkg_resources.parse_version('1.4.0'):
+ release = pkg_resources.get_distribution("cryptography").parsed_version
+ if release < pkg_resources.parse_version("1.4.0"):
raise ImportError(_IMPORT_ERROR_MSG)
except pkg_resources.DistributionNotFound: # pragma: NO COVER
raise ImportError(_IMPORT_ERROR_MSG)
-_CERTIFICATE_MARKER = b'-----BEGIN CERTIFICATE-----'
+_CERTIFICATE_MARKER = b"-----BEGIN CERTIFICATE-----"
_BACKEND = backends.default_backend()
_PADDING = padding.PKCS1v15()
_SHA256 = hashes.SHA256()
@@ -88,12 +88,12 @@
if _CERTIFICATE_MARKER in public_key_data:
cert = cryptography.x509.load_pem_x509_certificate(
- public_key_data, _BACKEND)
+ public_key_data, _BACKEND
+ )
pubkey = cert.public_key()
else:
- pubkey = serialization.load_pem_public_key(
- public_key_data, _BACKEND)
+ pubkey = serialization.load_pem_public_key(public_key_data, _BACKEND)
return cls(pubkey)
@@ -122,8 +122,7 @@
@_helpers.copy_docstring(base.Signer)
def sign(self, message):
message = _helpers.to_bytes(message)
- return self._key.sign(
- message, _PADDING, _SHA256)
+ return self._key.sign(message, _PADDING, _SHA256)
@classmethod
def from_string(cls, key, key_id=None):
@@ -145,5 +144,6 @@
"""
key = _helpers.to_bytes(key)
private_key = serialization.load_pem_private_key(
- key, password=None, backend=_BACKEND)
+ key, password=None, backend=_BACKEND
+ )
return cls(private_key, key_id=key_id)
diff --git a/google/auth/crypt/_python_rsa.py b/google/auth/crypt/_python_rsa.py
index 44aa791..d53991c 100644
--- a/google/auth/crypt/_python_rsa.py
+++ b/google/auth/crypt/_python_rsa.py
@@ -32,11 +32,9 @@
from google.auth.crypt import base
_POW2 = (128, 64, 32, 16, 8, 4, 2, 1)
-_CERTIFICATE_MARKER = b'-----BEGIN CERTIFICATE-----'
-_PKCS1_MARKER = ('-----BEGIN RSA PRIVATE KEY-----',
- '-----END RSA PRIVATE KEY-----')
-_PKCS8_MARKER = ('-----BEGIN PRIVATE KEY-----',
- '-----END PRIVATE KEY-----')
+_CERTIFICATE_MARKER = b"-----BEGIN CERTIFICATE-----"
+_PKCS1_MARKER = ("-----BEGIN RSA PRIVATE KEY-----", "-----END RSA PRIVATE KEY-----")
+_PKCS8_MARKER = ("-----BEGIN PRIVATE KEY-----", "-----END PRIVATE KEY-----")
_PKCS8_SPEC = PrivateKeyInfo()
@@ -55,9 +53,8 @@
num_bits = len(bit_list)
byte_vals = bytearray()
for start in six.moves.xrange(0, num_bits, 8):
- curr_bits = bit_list[start:start + 8]
- char_val = sum(
- val * digit for val, digit in six.moves.zip(_POW2, curr_bits))
+ curr_bits = bit_list[start : start + 8]
+ char_val = sum(val * digit for val, digit in six.moves.zip(_POW2, curr_bits))
byte_vals.append(char_val)
return bytes(byte_vals)
@@ -101,16 +98,16 @@
# If this is a certificate, extract the public key info.
if is_x509_cert:
- der = rsa.pem.load_pem(public_key, 'CERTIFICATE')
+ der = rsa.pem.load_pem(public_key, "CERTIFICATE")
asn1_cert, remaining = decoder.decode(der, asn1Spec=Certificate())
- if remaining != b'':
- raise ValueError('Unused bytes', remaining)
+ if remaining != b"":
+ raise ValueError("Unused bytes", remaining)
- cert_info = asn1_cert['tbsCertificate']['subjectPublicKeyInfo']
- key_bytes = _bit_list_to_bytes(cert_info['subjectPublicKey'])
- pubkey = rsa.PublicKey.load_pkcs1(key_bytes, 'DER')
+ cert_info = asn1_cert["tbsCertificate"]["subjectPublicKeyInfo"]
+ key_bytes = _bit_list_to_bytes(cert_info["subjectPublicKey"])
+ pubkey = rsa.PublicKey.load_pkcs1(key_bytes, "DER")
else:
- pubkey = rsa.PublicKey.load_pkcs1(public_key, 'PEM')
+ pubkey = rsa.PublicKey.load_pkcs1(public_key, "PEM")
return cls(pubkey)
@@ -136,7 +133,7 @@
@_helpers.copy_docstring(base.Signer)
def sign(self, message):
message = _helpers.to_bytes(message)
- return rsa.pkcs1.sign(message, self._key, 'SHA-256')
+ return rsa.pkcs1.sign(message, self._key, "SHA-256")
@classmethod
def from_string(cls, key, key_id=None):
@@ -155,22 +152,22 @@
"""
key = _helpers.from_bytes(key) # PEM expects str in Python 3
marker_id, key_bytes = pem.readPemBlocksFromFile(
- six.StringIO(key), _PKCS1_MARKER, _PKCS8_MARKER)
+ six.StringIO(key), _PKCS1_MARKER, _PKCS8_MARKER
+ )
# Key is in pkcs1 format.
if marker_id == 0:
- private_key = rsa.key.PrivateKey.load_pkcs1(
- key_bytes, format='DER')
+ private_key = rsa.key.PrivateKey.load_pkcs1(key_bytes, format="DER")
# Key is in pkcs8.
elif marker_id == 1:
- key_info, remaining = decoder.decode(
- key_bytes, asn1Spec=_PKCS8_SPEC)
- if remaining != b'':
- raise ValueError('Unused bytes', remaining)
- private_key_info = key_info.getComponentByName('privateKey')
+ key_info, remaining = decoder.decode(key_bytes, asn1Spec=_PKCS8_SPEC)
+ if remaining != b"":
+ raise ValueError("Unused bytes", remaining)
+ private_key_info = key_info.getComponentByName("privateKey")
private_key = rsa.key.PrivateKey.load_pkcs1(
- private_key_info.asOctets(), format='DER')
+ private_key_info.asOctets(), format="DER"
+ )
else:
- raise ValueError('No key could be detected.')
+ raise ValueError("No key could be detected.")
return cls(private_key, key_id=key_id)
diff --git a/google/auth/crypt/base.py b/google/auth/crypt/base.py
index c6c0427..ceb6e9c 100644
--- a/google/auth/crypt/base.py
+++ b/google/auth/crypt/base.py
@@ -21,8 +21,8 @@
import six
-_JSON_FILE_PRIVATE_KEY = 'private_key'
-_JSON_FILE_PRIVATE_KEY_ID = 'private_key_id'
+_JSON_FILE_PRIVATE_KEY = "private_key"
+_JSON_FILE_PRIVATE_KEY_ID = "private_key_id"
@six.add_metaclass(abc.ABCMeta)
@@ -43,7 +43,7 @@
"""
# pylint: disable=missing-raises-doc,redundant-returns-doc
# (pylint doesn't recognize that this is abstract)
- raise NotImplementedError('Verify must be implemented')
+ raise NotImplementedError("Verify must be implemented")
@six.add_metaclass(abc.ABCMeta)
@@ -53,7 +53,7 @@
@abc.abstractproperty
def key_id(self):
"""Optional[str]: The key ID used to identify this private key."""
- raise NotImplementedError('Key id must be implemented')
+ raise NotImplementedError("Key id must be implemented")
@abc.abstractmethod
def sign(self, message):
@@ -67,7 +67,7 @@
"""
# pylint: disable=missing-raises-doc,redundant-returns-doc
# (pylint doesn't recognize that this is abstract)
- raise NotImplementedError('Sign must be implemented')
+ raise NotImplementedError("Sign must be implemented")
@six.add_metaclass(abc.ABCMeta)
@@ -88,7 +88,7 @@
Raises:
ValueError: If the key cannot be parsed.
"""
- raise NotImplementedError('from_string must be implemented')
+ raise NotImplementedError("from_string must be implemented")
@classmethod
def from_service_account_info(cls, info):
@@ -107,12 +107,12 @@
"""
if _JSON_FILE_PRIVATE_KEY not in info:
raise ValueError(
- 'The private_key field was not found in the service account '
- 'info.')
+ "The private_key field was not found in the service account " "info."
+ )
return cls.from_string(
- info[_JSON_FILE_PRIVATE_KEY],
- info.get(_JSON_FILE_PRIVATE_KEY_ID))
+ info[_JSON_FILE_PRIVATE_KEY], info.get(_JSON_FILE_PRIVATE_KEY_ID)
+ )
@classmethod
def from_service_account_file(cls, filename):
@@ -125,7 +125,7 @@
Returns:
google.auth.crypt.Signer: The constructed signer.
"""
- 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_service_account_info(data)
diff --git a/google/auth/environment_vars.py b/google/auth/environment_vars.py
index 0110e6a..96d2ffc 100644
--- a/google/auth/environment_vars.py
+++ b/google/auth/environment_vars.py
@@ -15,35 +15,35 @@
"""Environment variables used by :mod:`google.auth`."""
-PROJECT = 'GOOGLE_CLOUD_PROJECT'
+PROJECT = "GOOGLE_CLOUD_PROJECT"
"""Environment variable defining default project.
This used by :func:`google.auth.default` to explicitly set a project ID. This
environment variable is also used by the Google Cloud Python Library.
"""
-LEGACY_PROJECT = 'GCLOUD_PROJECT'
+LEGACY_PROJECT = "GCLOUD_PROJECT"
"""Previously used environment variable defining the default project.
This environment variable is used instead of the current one in some
situations (such as Google App Engine).
"""
-CREDENTIALS = 'GOOGLE_APPLICATION_CREDENTIALS'
+CREDENTIALS = "GOOGLE_APPLICATION_CREDENTIALS"
"""Environment variable defining the location of Google application default
credentials."""
# The environment variable name which can replace ~/.config if set.
-CLOUD_SDK_CONFIG_DIR = 'CLOUDSDK_CONFIG'
+CLOUD_SDK_CONFIG_DIR = "CLOUDSDK_CONFIG"
"""Environment variable defines the location of Google Cloud SDK's config
files."""
# These two variables allow for customization of the addresses used when
# contacting the GCE metadata service.
-GCE_METADATA_ROOT = 'GCE_METADATA_ROOT'
+GCE_METADATA_ROOT = "GCE_METADATA_ROOT"
"""Environment variable providing an alternate hostname or host:port to be
used for GCE metadata requests."""
-GCE_METADATA_IP = 'GCE_METADATA_IP'
+GCE_METADATA_IP = "GCE_METADATA_IP"
"""Environment variable providing an alternate ip:port to be used for ip-only
GCE metadata requests."""
diff --git a/google/auth/iam.py b/google/auth/iam.py
index e091e47..a438726 100644
--- a/google/auth/iam.py
+++ b/google/auth/iam.py
@@ -28,9 +28,8 @@
from google.auth import crypt
from google.auth import exceptions
-_IAM_API_ROOT_URI = 'https://iam.googleapis.com/v1'
-_SIGN_BLOB_URI = (
- _IAM_API_ROOT_URI + '/projects/-/serviceAccounts/{}:signBlob?alt=json')
+_IAM_API_ROOT_URI = "https://iam.googleapis.com/v1"
+_SIGN_BLOB_URI = _IAM_API_ROOT_URI + "/projects/-/serviceAccounts/{}:signBlob?alt=json"
class Signer(crypt.Signer):
@@ -68,23 +67,20 @@
"""Makes a request to the API signBlob API."""
message = _helpers.to_bytes(message)
- method = 'POST'
+ method = "POST"
url = _SIGN_BLOB_URI.format(self._service_account_email)
headers = {}
- body = json.dumps({
- 'bytesToSign': base64.b64encode(message).decode('utf-8'),
- })
+ body = json.dumps({"bytesToSign": base64.b64encode(message).decode("utf-8")})
self._credentials.before_request(self._request, method, url, headers)
- response = self._request(
- url=url, method=method, body=body, headers=headers)
+ response = self._request(url=url, method=method, body=body, headers=headers)
if response.status != http_client.OK:
raise exceptions.TransportError(
- 'Error calling the IAM signBytes API: {}'.format(
- response.data))
+ "Error calling the IAM signBytes API: {}".format(response.data)
+ )
- return json.loads(response.data.decode('utf-8'))
+ return json.loads(response.data.decode("utf-8"))
@property
def key_id(self):
@@ -99,4 +95,4 @@
@_helpers.copy_docstring(crypt.Signer)
def sign(self, message):
response = self._make_signing_request(message)
- return base64.b64decode(response['signature'])
+ return base64.b64decode(response["signature"])
diff --git a/google/auth/impersonated_credentials.py b/google/auth/impersonated_credentials.py
index bb2bbf2..70fa5dc 100644
--- a/google/auth/impersonated_credentials.py
+++ b/google/auth/impersonated_credentials.py
@@ -41,22 +41,28 @@
_DEFAULT_TOKEN_LIFETIME_SECS = 3600 # 1 hour in seconds
-_IAM_SCOPE = ['https://www.googleapis.com/auth/iam']
+_IAM_SCOPE = ["https://www.googleapis.com/auth/iam"]
-_IAM_ENDPOINT = ('https://iamcredentials.googleapis.com/v1/projects/-' +
- '/serviceAccounts/{}:generateAccessToken')
+_IAM_ENDPOINT = (
+ "https://iamcredentials.googleapis.com/v1/projects/-"
+ + "/serviceAccounts/{}:generateAccessToken"
+)
-_IAM_SIGN_ENDPOINT = ('https://iamcredentials.googleapis.com/v1/projects/-' +
- '/serviceAccounts/{}:signBlob')
+_IAM_SIGN_ENDPOINT = (
+ "https://iamcredentials.googleapis.com/v1/projects/-"
+ + "/serviceAccounts/{}:signBlob"
+)
-_IAM_IDTOKEN_ENDPOINT = ('https://iamcredentials.googleapis.com/v1/' +
- 'projects/-/serviceAccounts/{}:generateIdToken')
+_IAM_IDTOKEN_ENDPOINT = (
+ "https://iamcredentials.googleapis.com/v1/"
+ + "projects/-/serviceAccounts/{}:generateIdToken"
+)
-_REFRESH_ERROR = 'Unable to acquire impersonated credentials'
+_REFRESH_ERROR = "Unable to acquire impersonated credentials"
_DEFAULT_TOKEN_LIFETIME_SECS = 3600 # 1 hour in seconds
-_DEFAULT_TOKEN_URI = 'https://oauth2.googleapis.com/token'
+_DEFAULT_TOKEN_URI = "https://oauth2.googleapis.com/token"
def _make_iam_token_request(request, principal, headers, body):
@@ -80,34 +86,31 @@
body = json.dumps(body)
- response = request(
- url=iam_endpoint,
- method='POST',
- headers=headers,
- body=body)
+ response = request(url=iam_endpoint, method="POST", headers=headers, body=body)
- response_body = response.data.decode('utf-8')
+ response_body = response.data.decode("utf-8")
if response.status != http_client.OK:
exceptions.RefreshError(_REFRESH_ERROR, response_body)
try:
- token_response = json.loads(response.data.decode('utf-8'))
- token = token_response['accessToken']
- expiry = datetime.strptime(
- token_response['expireTime'], '%Y-%m-%dT%H:%M:%SZ')
+ token_response = json.loads(response.data.decode("utf-8"))
+ token = token_response["accessToken"]
+ expiry = datetime.strptime(token_response["expireTime"], "%Y-%m-%dT%H:%M:%SZ")
return token, expiry
except (KeyError, ValueError) as caught_exc:
new_exc = exceptions.RefreshError(
- '{}: No access token or invalid expiration in response.'.format(
- _REFRESH_ERROR),
- response_body)
+ "{}: No access token or invalid expiration in response.".format(
+ _REFRESH_ERROR
+ ),
+ response_body,
+ )
six.raise_from(new_exc, caught_exc)
-class Credentials(credentials.Credentials, credentials.Signing):
+class Credentials(credentials.Credentials, credentials.Signing):
"""This module defines impersonated credentials which are essentially
impersonated identities.
@@ -169,9 +172,14 @@
print(bucket.name)
"""
- def __init__(self, source_credentials, target_principal,
- target_scopes, delegates=None,
- lifetime=_DEFAULT_TOKEN_LIFETIME_SECS):
+ def __init__(
+ self,
+ source_credentials,
+ target_principal,
+ target_scopes,
+ delegates=None,
+ lifetime=_DEFAULT_TOKEN_LIFETIME_SECS,
+ ):
"""
Args:
source_credentials (google.auth.Credentials): The source credential
@@ -228,12 +236,10 @@
body = {
"delegates": self._delegates,
"scope": self._target_scopes,
- "lifetime": str(self._lifetime) + "s"
+ "lifetime": str(self._lifetime) + "s",
}
- headers = {
- 'Content-Type': 'application/json',
- }
+ headers = {"Content-Type": "application/json"}
# Apply the source credentials authentication info.
self._source_credentials.apply(headers)
@@ -242,29 +248,24 @@
request=request,
principal=self._target_principal,
headers=headers,
- body=body)
+ body=body,
+ )
def sign_bytes(self, message):
iam_sign_endpoint = _IAM_SIGN_ENDPOINT.format(self._target_principal)
- body = {
- "payload": base64.b64encode(message),
- "delegates": self._delegates
- }
+ body = {"payload": base64.b64encode(message), "delegates": self._delegates}
- headers = {
- 'Content-Type': 'application/json',
- }
+ headers = {"Content-Type": "application/json"}
authed_session = AuthorizedSession(self._source_credentials)
response = authed_session.post(
- url=iam_sign_endpoint,
- headers=headers,
- json=body)
+ url=iam_sign_endpoint, headers=headers, json=body
+ )
- return base64.b64decode(response.json()['signedBlob'])
+ return base64.b64decode(response.json()["signedBlob"])
@property
def signer_email(self):
@@ -283,8 +284,8 @@
"""Open ID Connect ID Token-based service account credentials.
"""
- def __init__(self, target_credentials,
- target_audience=None, include_email=False):
+
+ def __init__(self, target_credentials, target_audience=None, include_email=False):
"""
Args:
target_credentials (google.auth.Credentials): The target
@@ -294,57 +295,54 @@
"""
super(IDTokenCredentials, self).__init__()
- if not isinstance(target_credentials,
- Credentials):
- raise exceptions.GoogleAuthError("Provided Credential must be "
- "impersonated_credentials")
+ if not isinstance(target_credentials, Credentials):
+ raise exceptions.GoogleAuthError(
+ "Provided Credential must be " "impersonated_credentials"
+ )
self._target_credentials = target_credentials
self._target_audience = target_audience
self._include_email = include_email
- def from_credentials(self, target_credentials,
- target_audience=None):
+ def from_credentials(self, target_credentials, target_audience=None):
return self.__class__(
- target_credentials=self._target_credentials,
- target_audience=target_audience)
+ target_credentials=self._target_credentials, target_audience=target_audience
+ )
def with_target_audience(self, target_audience):
return self.__class__(
- target_credentials=self._target_credentials,
- target_audience=target_audience)
+ target_credentials=self._target_credentials, target_audience=target_audience
+ )
def with_include_email(self, include_email):
return self.__class__(
target_credentials=self._target_credentials,
target_audience=self._target_audience,
- include_email=include_email)
+ include_email=include_email,
+ )
@_helpers.copy_docstring(credentials.Credentials)
def refresh(self, request):
- iam_sign_endpoint = _IAM_IDTOKEN_ENDPOINT.format(self.
- _target_credentials.
- signer_email)
+ iam_sign_endpoint = _IAM_IDTOKEN_ENDPOINT.format(
+ self._target_credentials.signer_email
+ )
body = {
"audience": self._target_audience,
"delegates": self._target_credentials._delegates,
- "includeEmail": self._include_email
+ "includeEmail": self._include_email,
}
- headers = {
- 'Content-Type': 'application/json',
- }
+ headers = {"Content-Type": "application/json"}
- authed_session = AuthorizedSession(self._target_credentials.
- _source_credentials)
+ authed_session = AuthorizedSession(self._target_credentials._source_credentials)
response = authed_session.post(
url=iam_sign_endpoint,
headers=headers,
- data=json.dumps(body).encode('utf-8'))
+ data=json.dumps(body).encode("utf-8"),
+ )
- id_token = response.json()['token']
+ id_token = response.json()["token"]
self.token = id_token
- self.expiry = datetime.fromtimestamp(jwt.decode(id_token,
- verify=False)['exp'])
+ self.expiry = datetime.fromtimestamp(jwt.decode(id_token, verify=False)["exp"])
diff --git a/google/auth/jwt.py b/google/auth/jwt.py
index d63c50b..a30c575 100644
--- a/google/auth/jwt.py
+++ b/google/auth/jwt.py
@@ -79,36 +79,30 @@
if key_id is None:
key_id = signer.key_id
- header.update({'typ': 'JWT', 'alg': 'RS256'})
+ header.update({"typ": "JWT", "alg": "RS256"})
if key_id is not None:
- header['kid'] = key_id
+ header["kid"] = key_id
segments = [
- _helpers.unpadded_urlsafe_b64encode(
- json.dumps(header).encode('utf-8')
- ),
- _helpers.unpadded_urlsafe_b64encode(
- json.dumps(payload).encode('utf-8')
- ),
+ _helpers.unpadded_urlsafe_b64encode(json.dumps(header).encode("utf-8")),
+ _helpers.unpadded_urlsafe_b64encode(json.dumps(payload).encode("utf-8")),
]
- signing_input = b'.'.join(segments)
+ signing_input = b".".join(segments)
signature = signer.sign(signing_input)
- segments.append(
- _helpers.unpadded_urlsafe_b64encode(signature)
- )
+ segments.append(_helpers.unpadded_urlsafe_b64encode(signature))
- return b'.'.join(segments)
+ return b".".join(segments)
def _decode_jwt_segment(encoded_section):
"""Decodes a single JWT segment."""
section_bytes = _helpers.padded_urlsafe_b64decode(encoded_section)
try:
- return json.loads(section_bytes.decode('utf-8'))
+ return json.loads(section_bytes.decode("utf-8"))
except ValueError as caught_exc:
- new_exc = ValueError('Can\'t parse segment: {0}'.format(section_bytes))
+ new_exc = ValueError("Can't parse segment: {0}".format(section_bytes))
six.raise_from(new_exc, caught_exc)
@@ -127,12 +121,11 @@
"""
token = _helpers.to_bytes(token)
- if token.count(b'.') != 2:
- raise ValueError(
- 'Wrong number of segments in token: {0}'.format(token))
+ if token.count(b".") != 2:
+ raise ValueError("Wrong number of segments in token: {0}".format(token))
- encoded_header, encoded_payload, signature = token.split(b'.')
- signed_section = encoded_header + b'.' + encoded_payload
+ encoded_header, encoded_payload, signature = token.split(b".")
+ signed_section = encoded_header + b"." + encoded_payload
signature = _helpers.padded_urlsafe_b64decode(signature)
# Parse segments
@@ -172,26 +165,25 @@
now = _helpers.datetime_to_secs(_helpers.utcnow())
# Make sure the iat and exp claims are present.
- for key in ('iat', 'exp'):
+ for key in ("iat", "exp"):
if key not in payload:
- raise ValueError(
- 'Token does not contain required claim {}'.format(key))
+ raise ValueError("Token does not contain required claim {}".format(key))
# Make sure the token wasn't issued in the future.
- iat = payload['iat']
+ iat = payload["iat"]
# Err on the side of accepting a token that is slightly early to account
# for clock skew.
earliest = iat - _helpers.CLOCK_SKEW_SECS
if now < earliest:
- raise ValueError('Token used too early, {} < {}'.format(now, iat))
+ raise ValueError("Token used too early, {} < {}".format(now, iat))
# Make sure the token wasn't issued in the past.
- exp = payload['exp']
+ exp = payload["exp"]
# Err on the side of accepting a token that is slightly out of date
# to account for clow skew.
latest = exp + _helpers.CLOCK_SKEW_SECS
if latest < now:
- raise ValueError('Token expired, {} < {}'.format(latest, now))
+ raise ValueError("Token expired, {} < {}".format(latest, now))
def decode(token, certs=None, verify=True, audience=None):
@@ -224,11 +216,10 @@
# If certs is specified as a dictionary of key IDs to certificates, then
# use the certificate identified by the key ID in the token header.
if isinstance(certs, collections.Mapping):
- key_id = header.get('kid')
+ key_id = header.get("kid")
if key_id:
if key_id not in certs:
- raise ValueError(
- 'Certificate for key id {} not found.'.format(key_id))
+ raise ValueError("Certificate for key id {} not found.".format(key_id))
certs_to_check = [certs[key_id]]
# If there's no key id in the header, check against all of the certs.
else:
@@ -238,24 +229,25 @@
# Verify that the signature matches the message.
if not crypt.verify_signature(signed_section, signature, certs_to_check):
- raise ValueError('Could not verify token signature.')
+ raise ValueError("Could not verify token signature.")
# Verify the issued at and created times in the payload.
_verify_iat_and_exp(payload)
# Check audience.
if audience is not None:
- claim_audience = payload.get('aud')
+ claim_audience = payload.get("aud")
if audience != claim_audience:
raise ValueError(
- 'Token has wrong audience {}, expected {}'.format(
- claim_audience, audience))
+ "Token has wrong audience {}, expected {}".format(
+ claim_audience, audience
+ )
+ )
return payload
-class Credentials(google.auth.credentials.Signing,
- google.auth.credentials.Credentials):
+class Credentials(google.auth.credentials.Signing, google.auth.credentials.Credentials):
"""Credentials that use a JWT as the bearer token.
These credentials require an "audience" claim. This claim identifies the
@@ -305,9 +297,15 @@
new_credentials = credentials.with_claims(audience=new_audience)
"""
- def __init__(self, signer, issuer, subject, audience,
- additional_claims=None,
- token_lifetime=_DEFAULT_TOKEN_LIFETIME_SECS):
+ def __init__(
+ self,
+ signer,
+ issuer,
+ subject,
+ audience,
+ additional_claims=None,
+ token_lifetime=_DEFAULT_TOKEN_LIFETIME_SECS,
+ ):
"""
Args:
signer (google.auth.crypt.Signer): The signer used to sign JWTs.
@@ -348,8 +346,8 @@
Raises:
ValueError: If the info is not in the expected format.
"""
- kwargs.setdefault('subject', info['client_email'])
- kwargs.setdefault('issuer', info['client_email'])
+ kwargs.setdefault("subject", info["client_email"])
+ kwargs.setdefault("issuer", info["client_email"])
return cls(signer, **kwargs)
@classmethod
@@ -367,8 +365,7 @@
Raises:
ValueError: If the info is not in the expected format.
"""
- signer = _service_account_info.from_dict(
- info, require=['client_email'])
+ signer = _service_account_info.from_dict(info, require=["client_email"])
return cls._from_signer_and_info(signer, info, **kwargs)
@classmethod
@@ -384,7 +381,8 @@
google.auth.jwt.Credentials: The constructed credentials.
"""
info, signer = _service_account_info.from_filename(
- filename, require=['client_email'])
+ filename, require=["client_email"]
+ )
return cls._from_signer_and_info(signer, info, **kwargs)
@classmethod
@@ -415,15 +413,13 @@
Returns:
google.auth.jwt.Credentials: A new Credentials instance.
"""
- kwargs.setdefault('issuer', credentials.signer_email)
- kwargs.setdefault('subject', credentials.signer_email)
- return cls(
- credentials.signer,
- audience=audience,
- **kwargs)
+ kwargs.setdefault("issuer", credentials.signer_email)
+ kwargs.setdefault("subject", credentials.signer_email)
+ return cls(credentials.signer, audience=audience, **kwargs)
- def with_claims(self, issuer=None, subject=None, audience=None,
- additional_claims=None):
+ def with_claims(
+ self, issuer=None, subject=None, audience=None, additional_claims=None
+ ):
"""Returns a copy of these credentials with modified claims.
Args:
@@ -448,7 +444,8 @@
issuer=issuer if issuer is not None else self._issuer,
subject=subject if subject is not None else self._subject,
audience=audience if audience is not None else self._audience,
- additional_claims=new_additional_claims)
+ additional_claims=new_additional_claims,
+ )
def _make_jwt(self):
"""Make a signed JWT.
@@ -461,11 +458,11 @@
expiry = now + lifetime
payload = {
- 'iss': self._issuer,
- 'sub': self._subject,
- 'iat': _helpers.datetime_to_secs(now),
- 'exp': _helpers.datetime_to_secs(expiry),
- 'aud': self._audience,
+ "iss": self._issuer,
+ "sub": self._subject,
+ "iat": _helpers.datetime_to_secs(now),
+ "exp": _helpers.datetime_to_secs(expiry),
+ "aud": self._audience,
}
payload.update(self._additional_claims)
@@ -500,8 +497,8 @@
class OnDemandCredentials(
- google.auth.credentials.Signing,
- google.auth.credentials.Credentials):
+ google.auth.credentials.Signing, google.auth.credentials.Credentials
+):
"""On-demand JWT credentials.
Like :class:`Credentials`, this class uses a JWT as the bearer token for
@@ -519,10 +516,15 @@
.. _grpc: http://www.grpc.io/
"""
- def __init__(self, signer, issuer, subject,
- additional_claims=None,
- token_lifetime=_DEFAULT_TOKEN_LIFETIME_SECS,
- max_cache_size=_DEFAULT_MAX_CACHE_SIZE):
+ def __init__(
+ self,
+ signer,
+ issuer,
+ subject,
+ additional_claims=None,
+ token_lifetime=_DEFAULT_TOKEN_LIFETIME_SECS,
+ max_cache_size=_DEFAULT_MAX_CACHE_SIZE,
+ ):
"""
Args:
signer (google.auth.crypt.Signer): The signer used to sign JWTs.
@@ -563,8 +565,8 @@
Raises:
ValueError: If the info is not in the expected format.
"""
- kwargs.setdefault('subject', info['client_email'])
- kwargs.setdefault('issuer', info['client_email'])
+ kwargs.setdefault("subject", info["client_email"])
+ kwargs.setdefault("issuer", info["client_email"])
return cls(signer, **kwargs)
@classmethod
@@ -582,8 +584,7 @@
Raises:
ValueError: If the info is not in the expected format.
"""
- signer = _service_account_info.from_dict(
- info, require=['client_email'])
+ signer = _service_account_info.from_dict(info, require=["client_email"])
return cls._from_signer_and_info(signer, info, **kwargs)
@classmethod
@@ -599,7 +600,8 @@
google.auth.jwt.OnDemandCredentials: The constructed credentials.
"""
info, signer = _service_account_info.from_filename(
- filename, require=['client_email'])
+ filename, require=["client_email"]
+ )
return cls._from_signer_and_info(signer, info, **kwargs)
@classmethod
@@ -626,8 +628,8 @@
Returns:
google.auth.jwt.Credentials: A new Credentials instance.
"""
- kwargs.setdefault('issuer', credentials.signer_email)
- kwargs.setdefault('subject', credentials.signer_email)
+ kwargs.setdefault("issuer", credentials.signer_email)
+ kwargs.setdefault("subject", credentials.signer_email)
return cls(credentials.signer, **kwargs)
def with_claims(self, issuer=None, subject=None, additional_claims=None):
@@ -653,7 +655,8 @@
issuer=issuer if issuer is not None else self._issuer,
subject=subject if subject is not None else self._subject,
additional_claims=new_additional_claims,
- max_cache_size=self._cache.maxsize)
+ max_cache_size=self._cache.maxsize,
+ )
@property
def valid(self):
@@ -678,11 +681,11 @@
expiry = now + lifetime
payload = {
- 'iss': self._issuer,
- 'sub': self._subject,
- 'iat': _helpers.datetime_to_secs(now),
- 'exp': _helpers.datetime_to_secs(expiry),
- 'aud': audience,
+ "iss": self._issuer,
+ "sub": self._subject,
+ "iat": _helpers.datetime_to_secs(now),
+ "exp": _helpers.datetime_to_secs(expiry),
+ "aud": audience,
}
payload.update(self._additional_claims)
@@ -725,7 +728,8 @@
# pylint: disable=unused-argument
# (pylint doesn't correctly recognize overridden methods.)
raise exceptions.RefreshError(
- 'OnDemandCredentials can not be directly refreshed.')
+ "OnDemandCredentials can not be directly refreshed."
+ )
def before_request(self, request, method, url, headers):
"""Performs credential-specific before request logic.
@@ -743,7 +747,8 @@
parts = urllib.parse.urlsplit(url)
# Strip query string and fragment
audience = urllib.parse.urlunsplit(
- (parts.scheme, parts.netloc, parts.path, "", ""))
+ (parts.scheme, parts.netloc, parts.path, "", "")
+ )
token = self._get_jwt_for_audience(audience)
self.apply(headers, token=token)
diff --git a/google/auth/transport/__init__.py b/google/auth/transport/__init__.py
index d73c63c..53aa4ba 100644
--- a/google/auth/transport/__init__.py
+++ b/google/auth/transport/__init__.py
@@ -45,17 +45,17 @@
@abc.abstractproperty
def status(self):
"""int: The HTTP status code."""
- raise NotImplementedError('status must be implemented.')
+ raise NotImplementedError("status must be implemented.")
@abc.abstractproperty
def headers(self):
"""Mapping[str, str]: The HTTP response headers."""
- raise NotImplementedError('headers must be implemented.')
+ raise NotImplementedError("headers must be implemented.")
@abc.abstractproperty
def data(self):
"""bytes: The response body."""
- raise NotImplementedError('data must be implemented.')
+ raise NotImplementedError("data must be implemented.")
@six.add_metaclass(abc.ABCMeta)
@@ -69,8 +69,9 @@
"""
@abc.abstractmethod
- def __call__(self, url, method='GET', body=None, headers=None,
- timeout=None, **kwargs):
+ def __call__(
+ self, url, method="GET", body=None, headers=None, timeout=None, **kwargs
+ ):
"""Make an HTTP request.
Args:
@@ -93,4 +94,4 @@
"""
# pylint: disable=redundant-returns-doc, missing-raises-doc
# (pylint doesn't play well with abstract docstrings.)
- raise NotImplementedError('__call__ must be implemented.')
+ raise NotImplementedError("__call__ must be implemented.")
diff --git a/google/auth/transport/_http_client.py b/google/auth/transport/_http_client.py
index 08b1ab6..b52ca7b 100644
--- a/google/auth/transport/_http_client.py
+++ b/google/auth/transport/_http_client.py
@@ -33,10 +33,10 @@
Args:
response (http.client.HTTPResponse): The raw http client response.
"""
+
def __init__(self, response):
self._status = response.status
- self._headers = {
- key.lower(): value for key, value in response.getheaders()}
+ self._headers = {key.lower(): value for key, value in response.getheaders()}
self._data = response.read()
@property
@@ -55,8 +55,9 @@
class Request(transport.Request):
"""http.client transport request adapter."""
- def __call__(self, url, method='GET', body=None, headers=None,
- timeout=None, **kwargs):
+ def __call__(
+ self, url, method="GET", body=None, headers=None, timeout=None, **kwargs
+ ):
"""Make an HTTP request using http.client.
Args:
@@ -88,20 +89,21 @@
# http.client needs the host and path parts specified separately.
parts = urllib.parse.urlsplit(url)
path = urllib.parse.urlunsplit(
- ('', '', parts.path, parts.query, parts.fragment))
+ ("", "", parts.path, parts.query, parts.fragment)
+ )
- if parts.scheme != 'http':
+ if parts.scheme != "http":
raise exceptions.TransportError(
- 'http.client transport only supports the http scheme, {}'
- 'was specified'.format(parts.scheme))
+ "http.client transport only supports the http scheme, {}"
+ "was specified".format(parts.scheme)
+ )
connection = http_client.HTTPConnection(parts.netloc, timeout=timeout)
try:
- _LOGGER.debug('Making request: %s %s', method, url)
+ _LOGGER.debug("Making request: %s %s", method, url)
- connection.request(
- method, path, body=body, headers=headers, **kwargs)
+ connection.request(method, path, body=body, headers=headers, **kwargs)
response = connection.getresponse()
return Response(response)
diff --git a/google/auth/transport/grpc.py b/google/auth/transport/grpc.py
index 0d44f64..9a1bc6d 100644
--- a/google/auth/transport/grpc.py
+++ b/google/auth/transport/grpc.py
@@ -17,13 +17,14 @@
from __future__ import absolute_import
import six
+
try:
import grpc
except ImportError as caught_exc: # pragma: NO COVER
six.raise_from(
ImportError(
- 'gRPC is not installed, please install the grpcio package '
- 'to use the gRPC transport.'
+ "gRPC is not installed, please install the grpcio package "
+ "to use the gRPC transport."
),
caught_exc,
)
@@ -42,6 +43,7 @@
request (google.auth.transport.Request): A HTTP transport request
object used to refresh credentials as needed.
"""
+
def __init__(self, credentials, request):
# pylint: disable=no-value-for-parameter
# pylint doesn't realize that the super method takes no arguments
@@ -59,10 +61,8 @@
"""
headers = {}
self._credentials.before_request(
- self._request,
- context.method_name,
- context.service_url,
- headers)
+ self._request, context.method_name, context.service_url, headers
+ )
return list(six.iteritems(headers))
@@ -78,7 +78,8 @@
def secure_authorized_channel(
- credentials, request, target, ssl_credentials=None, **kwargs):
+ credentials, request, target, ssl_credentials=None, **kwargs
+):
"""Creates a secure authorized gRPC channel.
This creates a channel with SSL and :class:`AuthMetadataPlugin`. This
@@ -130,6 +131,7 @@
# Combine the ssl credentials and the authorization credentials.
composite_credentials = grpc.composite_channel_credentials(
- ssl_credentials, google_auth_credentials)
+ ssl_credentials, google_auth_credentials
+ )
return grpc.secure_channel(target, composite_credentials, **kwargs)
diff --git a/google/auth/transport/requests.py b/google/auth/transport/requests.py
index 8250c74..564a0cd 100644
--- a/google/auth/transport/requests.py
+++ b/google/auth/transport/requests.py
@@ -23,10 +23,11 @@
import requests
except ImportError as caught_exc: # pragma: NO COVER
import six
+
six.raise_from(
ImportError(
- 'The requests library is not installed, please install the '
- 'requests package to use the requests transport.'
+ "The requests library is not installed, please install the "
+ "requests package to use the requests transport."
),
caught_exc,
)
@@ -46,6 +47,7 @@
Args:
response (requests.Response): The raw Requests response.
"""
+
def __init__(self, response):
self._response = response
@@ -85,14 +87,16 @@
.. automethod:: __call__
"""
+
def __init__(self, session=None):
if not session:
session = requests.Session()
self.session = session
- def __call__(self, url, method='GET', body=None, headers=None,
- timeout=None, **kwargs):
+ def __call__(
+ self, url, method="GET", body=None, headers=None, timeout=None, **kwargs
+ ):
"""Make an HTTP request using requests.
Args:
@@ -114,10 +118,10 @@
google.auth.exceptions.TransportError: If any exception occurred.
"""
try:
- _LOGGER.debug('Making request: %s %s', method, url)
+ _LOGGER.debug("Making request: %s %s", method, url)
response = self.session.request(
- method, url, data=body, headers=headers, timeout=timeout,
- **kwargs)
+ method, url, data=body, headers=headers, timeout=timeout, **kwargs
+ )
return _Response(response)
except requests.exceptions.RequestException as caught_exc:
new_exc = exceptions.TransportError(caught_exc)
@@ -157,11 +161,15 @@
an instance of :class:`~google.auth.transport.requests.Request`
is created.
"""
- def __init__(self, credentials,
- refresh_status_codes=transport.DEFAULT_REFRESH_STATUS_CODES,
- max_refresh_attempts=transport.DEFAULT_MAX_REFRESH_ATTEMPTS,
- refresh_timeout=None,
- auth_request=None):
+
+ def __init__(
+ self,
+ credentials,
+ refresh_status_codes=transport.DEFAULT_REFRESH_STATUS_CODES,
+ max_refresh_attempts=transport.DEFAULT_MAX_REFRESH_ATTEMPTS,
+ refresh_timeout=None,
+ auth_request=None,
+ ):
super(AuthorizedSession, self).__init__()
self.credentials = credentials
self._refresh_status_codes = refresh_status_codes
@@ -194,40 +202,50 @@
# Use a kwarg for this instead of an attribute to maintain
# thread-safety.
- _credential_refresh_attempt = kwargs.pop(
- '_credential_refresh_attempt', 0)
+ _credential_refresh_attempt = kwargs.pop("_credential_refresh_attempt", 0)
# Make a copy of the headers. They will be modified by the credentials
# and we want to pass the original headers if we recurse.
request_headers = headers.copy() if headers is not None else {}
self.credentials.before_request(
- self._auth_request, method, url, request_headers)
+ self._auth_request, method, url, request_headers
+ )
response = super(AuthorizedSession, self).request(
- method, url, data=data, headers=request_headers, **kwargs)
+ method, url, data=data, headers=request_headers, **kwargs
+ )
# If the response indicated that the credentials needed to be
# refreshed, then refresh the credentials and re-attempt the
# request.
# A stored token may expire between the time it is retrieved and
# the time the request is made, so we may need to try twice.
- if (response.status_code in self._refresh_status_codes
- and _credential_refresh_attempt < self._max_refresh_attempts):
+ if (
+ response.status_code in self._refresh_status_codes
+ and _credential_refresh_attempt < self._max_refresh_attempts
+ ):
_LOGGER.info(
- 'Refreshing credentials due to a %s response. Attempt %s/%s.',
- response.status_code, _credential_refresh_attempt + 1,
- self._max_refresh_attempts)
+ "Refreshing credentials due to a %s response. Attempt %s/%s.",
+ response.status_code,
+ _credential_refresh_attempt + 1,
+ self._max_refresh_attempts,
+ )
auth_request_with_timeout = functools.partial(
- self._auth_request, timeout=self._refresh_timeout)
+ self._auth_request, timeout=self._refresh_timeout
+ )
self.credentials.refresh(auth_request_with_timeout)
# Recurse. Pass in the original headers, not our modified set.
return self.request(
- method, url, data=data, headers=headers,
+ method,
+ url,
+ data=data,
+ headers=headers,
_credential_refresh_attempt=_credential_refresh_attempt + 1,
- **kwargs)
+ **kwargs
+ )
return response
diff --git a/google/auth/transport/urllib3.py b/google/auth/transport/urllib3.py
index 37eb317..dbb186b 100644
--- a/google/auth/transport/urllib3.py
+++ b/google/auth/transport/urllib3.py
@@ -34,10 +34,11 @@
import urllib3
except ImportError as caught_exc: # pragma: NO COVER
import six
+
six.raise_from(
ImportError(
- 'The urllib3 library is not installed, please install the '
- 'urllib3 package to use the urllib3 transport.'
+ "The urllib3 library is not installed, please install the "
+ "urllib3 package to use the urllib3 transport."
),
caught_exc,
)
@@ -56,6 +57,7 @@
Args:
response (urllib3.response.HTTPResponse): The raw urllib3 response.
"""
+
def __init__(self, response):
self._response = response
@@ -97,11 +99,13 @@
.. automethod:: __call__
"""
+
def __init__(self, http):
self.http = http
- def __call__(self, url, method='GET', body=None, headers=None,
- timeout=None, **kwargs):
+ def __call__(
+ self, url, method="GET", body=None, headers=None, timeout=None, **kwargs
+ ):
"""Make an HTTP request using urllib3.
Args:
@@ -125,12 +129,13 @@
# urllib3 uses a sentinel default value for timeout, so only set it if
# specified.
if timeout is not None:
- kwargs['timeout'] = timeout
+ kwargs["timeout"] = timeout
try:
- _LOGGER.debug('Making request: %s %s', method, url)
+ _LOGGER.debug("Making request: %s %s", method, url)
response = self.http.request(
- method, url, body=body, headers=headers, **kwargs)
+ method, url, body=body, headers=headers, **kwargs
+ )
return _Response(response)
except urllib3.exceptions.HTTPError as caught_exc:
new_exc = exceptions.TransportError(caught_exc)
@@ -139,9 +144,7 @@
def _make_default_http():
if certifi is not None:
- return urllib3.PoolManager(
- cert_reqs='CERT_REQUIRED',
- ca_certs=certifi.where())
+ return urllib3.PoolManager(cert_reqs="CERT_REQUIRED", ca_certs=certifi.where())
else:
return urllib3.PoolManager()
@@ -178,9 +181,14 @@
max_refresh_attempts (int): The maximum number of times to attempt to
refresh the credentials and retry the request.
"""
- def __init__(self, credentials, http=None,
- refresh_status_codes=transport.DEFAULT_REFRESH_STATUS_CODES,
- max_refresh_attempts=transport.DEFAULT_MAX_REFRESH_ATTEMPTS):
+
+ def __init__(
+ self,
+ credentials,
+ http=None,
+ refresh_status_codes=transport.DEFAULT_REFRESH_STATUS_CODES,
+ max_refresh_attempts=transport.DEFAULT_MAX_REFRESH_ATTEMPTS,
+ ):
if http is None:
http = _make_default_http()
@@ -204,8 +212,7 @@
# Use a kwarg for this instead of an attribute to maintain
# thread-safety.
- _credential_refresh_attempt = kwargs.pop(
- '_credential_refresh_attempt', 0)
+ _credential_refresh_attempt = kwargs.pop("_credential_refresh_attempt", 0)
if headers is None:
headers = self.headers
@@ -214,11 +221,11 @@
# and we want to pass the original headers if we recurse.
request_headers = headers.copy()
- self.credentials.before_request(
- self._request, method, url, request_headers)
+ self.credentials.before_request(self._request, method, url, request_headers)
response = self.http.urlopen(
- method, url, body=body, headers=request_headers, **kwargs)
+ method, url, body=body, headers=request_headers, **kwargs
+ )
# If the response indicated that the credentials needed to be
# refreshed, then refresh the credentials and re-attempt the
@@ -227,21 +234,29 @@
# the time the request is made, so we may need to try twice.
# The reason urllib3's retries aren't used is because they
# don't allow you to modify the request headers. :/
- if (response.status in self._refresh_status_codes
- and _credential_refresh_attempt < self._max_refresh_attempts):
+ if (
+ response.status in self._refresh_status_codes
+ and _credential_refresh_attempt < self._max_refresh_attempts
+ ):
_LOGGER.info(
- 'Refreshing credentials due to a %s response. Attempt %s/%s.',
- response.status, _credential_refresh_attempt + 1,
- self._max_refresh_attempts)
+ "Refreshing credentials due to a %s response. Attempt %s/%s.",
+ response.status,
+ _credential_refresh_attempt + 1,
+ self._max_refresh_attempts,
+ )
self.credentials.refresh(self._request)
# Recurse. Pass in the original headers, not our modified set.
return self.urlopen(
- method, url, body=body, headers=headers,
+ method,
+ url,
+ body=body,
+ headers=headers,
_credential_refresh_attempt=_credential_refresh_attempt + 1,
- **kwargs)
+ **kwargs
+ )
return response