From 1ab11e68f5575d8d2195e2a78f595d779284fa8d Mon Sep 17 00:00:00 2001 From: Eno Compton Date: Mon, 22 Jul 2024 11:18:03 -0600 Subject: [PATCH] fix: refresh token prior to metadata exchange (#351) In heavy usage, there can be cases where the client does not refresh the token but then the token expires prior to the metadata exchange. This commit ensures that the token is always fresh before proceeding to the metadata exchange. Fixes #346 --- google/cloud/alloydb/connector/connector.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/google/cloud/alloydb/connector/connector.py b/google/cloud/alloydb/connector/connector.py index 1cd20b1d..8b714263 100644 --- a/google/cloud/alloydb/connector/connector.py +++ b/google/cloud/alloydb/connector/connector.py @@ -23,7 +23,9 @@ from typing import Any, Dict, Optional, Type, TYPE_CHECKING, Union from google.auth import default +from google.auth.credentials import TokenState from google.auth.credentials import with_scopes_if_required +from google.auth.transport import requests from google.cloud.alloydb.connector.client import AlloyDBClient from google.cloud.alloydb.connector.enums import IPTypes @@ -258,6 +260,10 @@ def metadata_exchange( if enable_iam_auth: auth_type = connectorspb.MetadataExchangeRequest.AUTO_IAM + # Ensure the credentials are in fact valid before proceeding. + if not self._credentials.token_state == TokenState.FRESH: + self._credentials.refresh(requests.Request()) + # form metadata exchange request req = connectorspb.MetadataExchangeRequest( user_agent=f"{self._client._user_agent}", # type: ignore