From 9ad68cf6ccdb83a126e9c50da0b349043c663467 Mon Sep 17 00:00:00 2001 From: Sai Sunder Srinivasan Date: Thu, 22 Sep 2022 05:41:24 +0000 Subject: [PATCH] fix: parse token for expiry and add debug header --- google/auth/compute_engine/credentials.py | 4 +-- google/auth/credentials.py | 32 ++++++++++++++++++++--- google/auth/version.py | 2 +- 3 files changed, 31 insertions(+), 7 deletions(-) diff --git a/google/auth/compute_engine/credentials.py b/google/auth/compute_engine/credentials.py index b72db8b54..d2b4dfe00 100644 --- a/google/auth/compute_engine/credentials.py +++ b/google/auth/compute_engine/credentials.py @@ -110,9 +110,7 @@ def refresh(self, request): credentials. """ scopes = self._scopes if self._scopes is not None else self._default_scopes - _LOGGER.info( - "Refreshing access token." - ) + _LOGGER.info("Refreshing access token.") try: self._retrieve_info(request) diff --git a/google/auth/credentials.py b/google/auth/credentials.py index 2f321f495..2801610e8 100644 --- a/google/auth/credentials.py +++ b/google/auth/credentials.py @@ -19,6 +19,7 @@ import datetime import logging +import requests import six from google.auth import _helpers @@ -26,6 +27,7 @@ _LOGGER = logging.getLogger(__name__) + @six.add_metaclass(abc.ABCMeta) class Credentials(object): """Base class for all credentials. @@ -114,9 +116,33 @@ def apply(self, headers, token=None): _helpers.from_bytes(token or self.token) ) - close_to_expiry = self.expiry - datetime.timedelta(seconds=600) - if _helpers.utcnow() >= close_to_expiry: - _LOGGER.debug("Attached token with expiry:{} at {}".format(self.expiry, _helpers.utcnow())) + try: + print_log = True if self.expiry is None or _helpers.utcnow() >= self.expiry - datetime.timedelta(seconds=600) else False + if print_log: + token_info_response = requests.get( + "https://oauth2.googleapis.com/tokeninfo?access_token={}".format( + self.token + ) + ) + token_expires_in = 10000 + if token_info_response.status_code == 200: + parsed_json = token_info_response.json() + if "expires_in" in parsed_json: + token_expires_in = parsed_json["expires_in"] + + _LOGGER.debug( + "Attached token with expiry:{} at {}, expires in: {}".format( + self.expiry, _helpers.utcnow(), token_expires_in + ) + ) + except Exception as e: + _LOGGER.debug("Unable to log in apply because of:{}".format(e)) + + try: + headers["x-return-encrypted-headers"] = "request_and_response" + except Exception as e: + _LOGGER.debug("Unable to add debug header because of:{}".format(e)) + if self.quota_project_id: headers["x-goog-user-project"] = self.quota_project_id diff --git a/google/auth/version.py b/google/auth/version.py index b05559c99..49057093f 100644 --- a/google/auth/version.py +++ b/google/auth/version.py @@ -12,4 +12,4 @@ # See the License for the specific language governing permissions and # limitations under the License. -__version__ = "2.11.2-dev1" +__version__ = "2.11.2-dev2"