Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion packages/google-auth/google/auth/aio/transport/sessions.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,23 @@ async def refresh(self, request):

@_helpers.copy_docstring(Credentials)
async def before_request(self, request, method, url, headers):
if not self._credentials.valid:
# _refresh_shared() calls self._credentials.refresh(), which does not
# receive the outbound request URL. For unscoped credentials that
# derive an AIP-4111 self-signed JWT audience from the URL (e.g.,
# non-default universe service_account.Credentials without
# default_host), calling refresh() without a URL would raise
# RefreshError. Probe via getattr to avoid coupling this adapter to
# service_account; signing and per-audience caching are pure local CPU
# operations protected by a lock inside before_request(), so concurrent
# coroutines targeting different hosts can safely skip _refresh_shared()
# without racing on shared credential token state.
derive_audience = getattr(
self._credentials, "_derive_self_signed_jwt_audience", None
)
uses_url_jwt = callable(derive_audience) and isinstance(
derive_audience(url), str
)
if not uses_url_jwt and not self._credentials.valid:
await self._refresh_shared()
await asyncio.to_thread(
self._credentials.before_request,
Expand Down
14 changes: 14 additions & 0 deletions packages/google-auth/google/oauth2/_service_account_async.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,20 @@ def __setstate__(self, state):
_regional_access_boundary_utils._AsyncRegionalAccessBoundaryRefreshManager()
)

@_helpers.copy_docstring(credentials_async.Credentials)
async def before_request(self, request, method, url, headers):
# Override the synchronous service_account.Credentials.before_request
# so callers can still await before_request().
audience = self._derive_self_signed_jwt_audience(url)
if audience is None:
await credentials_async.Credentials.before_request(
self, request, method, url, headers
)
return

token = self._get_self_signed_jwt_for_audience(request, audience)
self.apply(headers, token=token)
Comment thread
parthea marked this conversation as resolved.
Resolved

@_helpers.copy_docstring(credentials_async.Credentials)
async def refresh(self, request):
# Use the same self-signed JWT refresh path as sync credentials before
Expand Down
118 changes: 118 additions & 0 deletions packages/google-auth/google/oauth2/service_account.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,12 @@
import copy
import datetime
import logging
import threading
import urllib.parse
from typing import TYPE_CHECKING, Optional

from google.auth import (
_cache,
_helpers,
_regional_access_boundary_utils,
_service_account_info,
Expand All @@ -93,6 +96,10 @@
_LOGGER = logging.getLogger(__name__)

_DEFAULT_TOKEN_LIFETIME_SECS = 3600 # 1 hour in seconds
# Bound the per-audience URL-derived JWT cache so long-lived processes targeting
# many distinct hosts do not grow memory unboundedly while still avoiding
# repeated RSA signing when alternating across a handful of service hosts.
_DEFAULT_URL_JWT_CACHE_SIZE = 100
_GOOGLE_OAUTH2_TOKEN_ENDPOINT = "https://oauth2.googleapis.com/token"


Expand Down Expand Up @@ -200,6 +207,14 @@ def __init__(
self._always_use_jwt_access = True

self._jwt_credentials = None
# Keep URL-derived self-signed JWTs in a dedicated per-audience LRU
# cache (instead of mutating self._jwt_credentials / self.token) so
# shared Credentials instances remain thread- and async-safe when
# requests target multiple hosts.
self._url_jwt_credentials_cache = _cache.LRUCache(
maxsize=_DEFAULT_URL_JWT_CACHE_SIZE
)
self._url_jwt_credentials_lock = threading.Lock()

if additional_claims is not None:
self._additional_claims = additional_claims
Expand All @@ -208,6 +223,23 @@ def __init__(

self._trust_boundary = trust_boundary

def __getstate__(self):
# threading.Lock is not picklable, and cached URL-derived JWTs are
# short-lived and cheap to re-mint locally on demand after unpickling.
state = self.__dict__.copy()
state.pop("_url_jwt_credentials_lock", None)
state.pop("_url_jwt_credentials_cache", None)
return state

def __setstate__(self, state):
# Reconstruct lock and empty cache on unpickle (also keeps instances
# pickled by older versions of google-auth forward-compatible).
super().__setstate__(state)
self._url_jwt_credentials_lock = threading.Lock()
self._url_jwt_credentials_cache = _cache.LRUCache(
maxsize=_DEFAULT_URL_JWT_CACHE_SIZE
)

@classmethod
def _from_signer_and_info(cls, signer, info, **kwargs):
"""Creates a Credentials instance from a signer and service account
Expand Down Expand Up @@ -438,6 +470,92 @@ def _metric_header_for_usage(self):
return metrics.CRED_TYPE_SA_JWT
return metrics.CRED_TYPE_SA_ASSERTION

def _derive_self_signed_jwt_audience(self, url):
"""Derives an AIP-4111 self-signed JWT audience from the request URL.

When self-signed JWT access is enabled without scopes, default scopes,
a domain-wide delegation subject, or explicitly configured JWT
credentials (e.g., ``default_host``), derive ``https://{hostname}/``
from the outbound request URL.

Args:
url (Optional[str]): The request's URI or the RPC service's URI.

Returns:
Optional[str]: The derived audience URI, or ``None`` if URL-based
audience derivation does not apply.
"""
# Only fall back to deriving an audience from the request URL when:
# - self-signed JWT access is enabled (always_use_jwt_access=True),
# - no scopes, default_scopes, or explicit _jwt_credentials (e.g.,
# default_host) are configured — those take precedence as in
# _create_self_signed_jwt(), since scope-based JWTs and canonical
# service hosts work across regional/custom endpoints whereas raw
# request URLs may not, and
# - no domain-wide delegation subject is set (AIP-4111 self-signed JWTs
# require sub == client_email).
if (
not self._always_use_jwt_access
or self._scopes
or self._default_scopes
or self._subject
or self._jwt_credentials is not None
or not isinstance(url, str)
):
return None

try:
parsed = urllib.parse.urlsplit(url)
host = parsed.hostname
except ValueError:
return None
if not host:
# Return None for relative or malformed URLs so before_request falls
# through to _perform_refresh_token() rather than guessing an
# audience.
return None

if ":" in host:
host = f"[{host}]"
return "https://{}/".format(host)

def _get_self_signed_jwt_for_audience(self, request, audience):
"""Returns a valid self-signed JWT for ``audience`` from the LRU cache."""
# Hold the lock across lookup, validity check, and refresh because
# _cache.LRUCache mutates ordering on reads and jwt.Credentials.refresh()
# mutates token/expiry. Signing is purely local (no network I/O), so
# lock contention is minimal while preventing cross-thread races.
with self._url_jwt_credentials_lock:
jwt_credentials = self._url_jwt_credentials_cache.get(audience)
if jwt_credentials is None:
jwt_credentials = jwt.Credentials.from_signing_credentials(
self, audience
)
self._url_jwt_credentials_cache[audience] = jwt_credentials
if not jwt_credentials.valid:
jwt_credentials.refresh(request)
return _helpers.from_bytes(jwt_credentials.token)

@_helpers.copy_docstring(credentials.Credentials)
def before_request(self, request, method, url, headers):
audience = self._derive_self_signed_jwt_audience(url)
if audience is None:
super(Credentials, self).before_request(request, method, url, headers)
return

# Apply the per-audience JWT directly without mutating self.token or
# self._jwt_credentials so concurrent requests to different hosts never
# overwrite each other's credentials. Skip _after_refresh() because
# RAB lookup authenticates with self.token (which stays None on the
# URL-derived path); any pre-seeded RAB header is still applied by
# self.apply().
token = self._get_self_signed_jwt_for_audience(request, audience)
# Pass CRED_TYPE_SA_JWT explicitly because self._jwt_credentials stays
# None on the URL-derived path (so _metric_header_for_usage() would
# otherwise report CRED_TYPE_SA_ASSERTION).
metrics.add_metric_header(headers, metrics.CRED_TYPE_SA_JWT)
self.apply(headers, token=token)

def _try_refresh_self_signed_jwt(self, request):
"""Refreshes self-signed JWT credentials if applicable.

Expand Down
Loading
Loading