1313See the License for the specific language governing permissions and
1414limitations under the License.
1515"""
16+
1617# file containing all mocks used for Cloud SQL Python Connector unit tests
1718
1819import datetime
1920import json
2021import ssl
2122from tempfile import TemporaryDirectory
22- from typing import Any , Callable , Dict , Optional , Tuple
23+ from typing import Any , Callable , Dict , Literal , Optional , Tuple
2324
2425from aiohttp import web
2526from cryptography import x509
2829from cryptography .hazmat .primitives import serialization
2930from cryptography .hazmat .primitives .asymmetric import rsa
3031from cryptography .x509 .oid import NameOID
32+ from google .auth import _helpers
3133from google .auth .credentials import Credentials
34+ from google .auth .credentials import TokenState
3235
3336from google .cloud .sql .connector .connector import _DEFAULT_UNIVERSE_DOMAIN
3437from google .cloud .sql .connector .utils import generate_keys
@@ -48,7 +51,7 @@ def __class__(self) -> Credentials:
4851 # set class type to google auth Credentials
4952 return Credentials
5053
51- def refresh (self , request : Callable ) -> None :
54+ def refresh (self , _ : Callable ) -> None :
5255 """Refreshes the access token."""
5356 self .token = "12345"
5457 self .expiry = datetime .datetime .now (datetime .timezone .utc ) + datetime .timedelta (
@@ -75,13 +78,33 @@ def universe_domain(self) -> str:
7578 return self ._universe_domain
7679
7780 @property
78- def valid (self ) -> bool :
79- """Checks the validity of the credentials.
80-
81- This is True if the credentials have a token and the token
82- is not expired.
81+ def token_state (
82+ self ,
83+ ) -> Literal [TokenState .FRESH , TokenState .STALE , TokenState .INVALID ]:
8384 """
84- return self .token is not None and not self .expired
85+ Tracks the state of a token.
86+ FRESH: The token is valid. It is not expired or close to expired, or the token has no expiry.
87+ STALE: The token is close to expired, and should be refreshed. The token can be used normally.
88+ INVALID: The token is expired or invalid. The token cannot be used for a normal operation.
89+ """
90+ if self .token is None :
91+ return TokenState .INVALID
92+
93+ # Credentials that can't expire are always treated as fresh.
94+ if self .expiry is None :
95+ return TokenState .FRESH
96+
97+ expired = datetime .datetime .now (datetime .timezone .utc ) >= self .expiry
98+ if expired :
99+ return TokenState .INVALID
100+
101+ is_stale = datetime .datetime .now (datetime .timezone .utc ) >= (
102+ self .expiry - _helpers .REFRESH_THRESHOLD
103+ )
104+ if is_stale :
105+ return TokenState .STALE
106+
107+ return TokenState .FRESH
85108
86109
87110def generate_cert (
0 commit comments