Skip to content
Closed
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
21 changes: 21 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,8 +75,29 @@ 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
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks like credentials_async.Credentials.before_request calls through to service_account_async.refresh, which calls _make_authorization_grant_assertion, which uses a hard-coded _GOOGLE_OAUTH2_TOKEN_ENDPOINT. I think we need to add extra self-signed JWT/non-default universe protections here

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks like credentials_async.Credentials.before_request calls through to service_account_async.refresh, which calls _make_authorization_grant_assertion, which uses a hard-coded _GOOGLE_OAUTH2_TOKEN_ENDPOINT. I think we need to add extra self-signed JWT/non-default universe protections here

Fixed in b44cb15. I've pushed a commit to secure this path by extracting the validation and refresh rules into a shared _try_refresh_self_signed_jwt(request) helper.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Update: this PR has been split into a 3-PR stack, and this fix (sharing _try_refresh_self_signed_jwt(request) across both sync service_account.Credentials and async _service_account_async.Credentials) now lives in #19279.

return

token = self._get_self_signed_jwt_for_audience(request, audience)
self.apply(headers, token=token)

@_helpers.copy_docstring(credentials_async.Credentials)
async def refresh(self, request):
# Enforce the same self-signed JWT and non-default universe rules as
# the sync path before falling back to jwt_grant (which targets
# oauth2.googleapis.com). This is synchronous because
# jwt.Credentials.refresh() only signs locally and performs no I/O.
if self._try_refresh_self_signed_jwt(request):
return

assertion = self._make_authorization_grant_assertion()
access_token, expiry, _ = await _client_async.jwt_grant(
request, self._token_uri, assertion
Expand Down
163 changes: 147 additions & 16 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
)
Comment thread
parthea marked this conversation as resolved.
Resolved

@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,32 +470,131 @@ def _metric_header_for_usage(self):
return metrics.CRED_TYPE_SA_JWT
return metrics.CRED_TYPE_SA_ASSERTION

@_helpers.copy_docstring(credentials.CredentialsWithRegionalAccessBoundary)
def _perform_refresh_token(self, request):
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

parsed = urllib.parse.urlsplit(url)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we handle IPv6 addresses for emulators, etc, which may contain [] brackets?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch — urllib.parse.urlsplit(url).hostname strips the brackets from IPv6 literals, so formatting https://{host}/ directly would produce an invalid URI.

This is fixed in #19280 (PR 2 of the split stack): _derive_self_signed_jwt_audience() now re-wraps IPv6 hosts in brackets (if ":" in host: host = f"[{host}]") and catches ValueError from malformed bracketed URLs so they cleanly return None.

if not parsed.hostname:
# Return None for relative or malformed URLs so before_request falls
# through to _perform_refresh_token() rather than guessing an
# audience.
return None

return "https://{}/".format(parsed.hostname)
Comment thread
parthea marked this conversation as resolved.
Resolved

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.

Returns:
bool: ``True`` if a self-signed JWT was refreshed and stored on
``self.token`` and ``self.expiry``; ``False`` if the caller
should fall back to the OAuth 2.0 assertion grant.

Raises:
google.auth.exceptions.RefreshError: If a non-default universe
domain cannot use a self-signed JWT.
"""
if self._always_use_jwt_access and not self._jwt_credentials:
# If self signed jwt should be used but jwt credential is not
# created, try to create one with scopes
self._create_self_signed_jwt(None)

if (
self._universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN
and self._subject
):
raise exceptions.RefreshError(
"domain wide delegation is not supported for non-default universe domain"
)
if self._universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN:
if self._subject:
raise exceptions.RefreshError(
"domain wide delegation is not supported for non-default universe domain"
)
if not self._use_self_signed_jwt():
raise exceptions.RefreshError(
"self-signed JWT credentials could not be created for "
"non-default universe domain without scopes or audience"
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My understanding is that AuthorizedSession will try to refresh a token if it hits an UNAUTHORIZED 401 error. Wouldn't these exceptions swallow that error?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch — yes, on a 401 retry the HTTP transports previously called URL-less credentials.refresh(), which raised RefreshError for unscoped non-default-universe credentials using URL-derived self-signed JWTs.

This PR has been split into a 3-PR stack, and this issue is fixed in #19282: I added service_account.Credentials._refresh_self_signed_jwt_for_url(request, url) and updated requests.AuthorizedSession, urllib3.AuthorizedHttp, aiohttp.AuthorizedSession, and aio.transport.sessions.AsyncAuthorizedSession (via _SyncCredentialsAdapter) to refresh the cached URL-derived JWT for the request URL on 401 instead of falling back to URL-less refresh().


if self._use_self_signed_jwt():
self._jwt_credentials.refresh(request)
self.token = self._jwt_credentials.token.decode()
self.expiry = self._jwt_credentials.expiry
else:
assertion = self._make_authorization_grant_assertion()
access_token, expiry, _ = _client.jwt_grant(
request, self._token_uri, assertion
)
self.token = access_token
self.expiry = expiry
return True

return False

@_helpers.copy_docstring(credentials.CredentialsWithRegionalAccessBoundary)
def _perform_refresh_token(self, request):
if self._try_refresh_self_signed_jwt(request):
return

assertion = self._make_authorization_grant_assertion()
access_token, expiry, _ = _client.jwt_grant(request, self._token_uri, assertion)
self.token = access_token
self.expiry = expiry

def _create_self_signed_jwt(self, audience):
"""Create a self-signed JWT from the credentials if requirements are met.
Expand Down
Loading
Loading