Skip to content

Commit bc6c1e8

Browse files
committed
lint
1 parent 08baabf commit bc6c1e8

File tree

1 file changed

+47
-19
lines changed

1 file changed

+47
-19
lines changed

packages/toolbox-core/src/toolbox_core/auth_methods.py

Lines changed: 47 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -33,33 +33,41 @@
3333
tools = await toolbox.load_toolset()
3434
"""
3535

36+
import asyncio
3637
from datetime import datetime, timedelta, timezone
3738
from typing import Any, Dict
39+
3840
import google.auth
3941
from google.auth.exceptions import GoogleAuthError
40-
from google.auth.transport.requests import Request, AuthorizedSession
42+
from google.auth.transport.requests import AuthorizedSession, Request
4143
from google.oauth2 import id_token
42-
import asyncio
4344

4445
# --- Constants ---
4546
BEARER_TOKEN_PREFIX = "Bearer "
4647
CACHE_REFRESH_MARGIN = timedelta(seconds=60)
4748

48-
_token_cache: Dict[str, Any] = {"token": None, "expires_at": datetime.min.replace(tzinfo=timezone.utc)}
49+
_token_cache: Dict[str, Any] = {
50+
"token": None,
51+
"expires_at": datetime.min.replace(tzinfo=timezone.utc),
52+
}
53+
4954

5055
def _is_token_valid() -> bool:
5156
"""Checks if the cached token exists and is not nearing expiry."""
5257
if not _token_cache["token"]:
5358
return False
54-
return datetime.now(timezone.utc) < (_token_cache["expires_at"] - CACHE_REFRESH_MARGIN)
59+
return datetime.now(timezone.utc) < (
60+
_token_cache["expires_at"] - CACHE_REFRESH_MARGIN
61+
)
62+
5563

5664
def _update_cache(new_token: str) -> None:
5765
"""
5866
Validates a new token, extracts its expiry, and updates the cache.
59-
67+
6068
Args:
6169
new_token: The new JWT ID token string.
62-
70+
6371
Raises:
6472
ValueError: If the token is invalid or its expiry cannot be determined.
6573
"""
@@ -68,13 +76,15 @@ def _update_cache(new_token: str) -> None:
6876
# signature and claims against Google's public keys.
6977
# It's a synchronous, CPU-bound operation, safe for async contexts.
7078
claims = id_token.verify_oauth2_token(new_token, Request())
71-
79+
7280
expiry_timestamp = claims.get("exp")
7381
if not expiry_timestamp:
7482
raise ValueError("Token does not contain an 'exp' claim.")
75-
83+
7684
_token_cache["token"] = new_token
77-
_token_cache["expires_at"] = datetime.fromtimestamp(expiry_timestamp, tz=timezone.utc)
85+
_token_cache["expires_at"] = datetime.fromtimestamp(
86+
expiry_timestamp, tz=timezone.utc
87+
)
7888

7989
except (ValueError, GoogleAuthError) as e:
8090
# Clear cache on failure to prevent using a stale or invalid token
@@ -83,13 +93,12 @@ def _update_cache(new_token: str) -> None:
8393
raise ValueError(f"Failed to validate and cache the new token: {e}") from e
8494

8595

86-
# --- Public API Functions ---
87-
8896
def get_google_id_token(audience: str) -> str:
8997
"""
9098
Synchronously fetches a Google ID token for a specific audience.
91-
92-
This function uses Application Default Credentials and caches the token in memory.
99+
This function uses Application Default Credentials for local systems
100+
and standard google auth libraries for Google Cloud environments.
101+
It caches the token in memory.
93102
94103
Args:
95104
audience: The audience for the ID token (e.g., a service URL or client ID).
@@ -103,7 +112,7 @@ def get_google_id_token(audience: str) -> str:
103112
"""
104113
if _is_token_valid():
105114
return BEARER_TOKEN_PREFIX + _token_cache["token"]
106-
115+
107116
# Get local user credentials
108117
credentials, _ = google.auth.default()
109118
session = AuthorizedSession(credentials)
@@ -122,10 +131,29 @@ def get_google_id_token(audience: str) -> str:
122131
new_token = id_token.fetch_id_token(request, audience)
123132
_update_cache(new_token)
124133
return BEARER_TOKEN_PREFIX + _token_cache["token"]
125-
134+
126135
except GoogleAuthError as e:
127-
raise GoogleAuthError(f"Failed to fetch Google ID token for audience '{audience}': {e}") from e
128-
136+
raise GoogleAuthError(
137+
f"Failed to fetch Google ID token for audience '{audience}': {e}"
138+
) from e
139+
140+
129141
async def aget_google_id_token(audience: str) -> str:
130-
token = await asyncio.to_thread(get_google_id_token, audience)
131-
return token
142+
"""
143+
Asynchronously fetches a Google ID token for a specific audience.
144+
This function uses Application Default Credentials for local systems
145+
and standard google auth libraries for Google Cloud environments.
146+
It caches the token in memory.
147+
148+
Args:
149+
audience: The audience for the ID token (e.g., a service URL or client ID).
150+
151+
Returns:
152+
A string in the format "Bearer <google_id_token>".
153+
154+
Raises:
155+
GoogleAuthError: If fetching credentials or the token fails.
156+
ValueError: If the fetched token is invalid.
157+
"""
158+
token = await asyncio.to_thread(get_google_id_token, audience)
159+
return token

0 commit comments

Comments
 (0)