Skip to content

fix(auth): derive AIP-4111 JWT audience from URL for non-default universe domains - #19196

Closed
parthea wants to merge 3 commits into
mainfrom
fix/auth-sa-jwt-url-audience
Closed

parthea wants to merge 3 commits into
mainfrom
fix/auth-sa-jwt-url-audience

Conversation

@parthea

@parthea parthea commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Improve self-signed JWT handling for google.oauth2.service_account.Credentials when operating in a non-default universe_domain without explicit scopes or default_host:

  • Derive and cache AIP-4111 audiences per host: Override service_account.Credentials.before_request() (and google.oauth2._service_account_async.Credentials.before_request() to keep before_request() awaitable on async credentials) to derive https://{hostname}/ from the outbound request URL when _always_use_jwt_access is enabled and neither scopes, default_scopes, subject, nor explicit _jwt_credentials (e.g., default_host) are configured. Cache per-audience jwt.Credentials in a bounded, lock-protected _cache.LRUCache (with __getstate__/__setstate__ support for pickling/deepcopy) and apply tokens directly via apply(headers, token=token) so shared credentials remain thread- and async-safe across multiple hosts without cache thrashing.
  • Require self-signed JWTs in non-default universe domains: Raise RefreshError in service_account.Credentials._perform_refresh_token() when operating in a non-default universe_domain without scopes or an audience
  • Handle URL-derived JWTs in _SyncCredentialsAdapter: Skip the URL-less _refresh_shared() call in _SyncCredentialsAdapter.before_request() when wrapped synchronous credentials derive a URL-scoped self-signed JWT, letting before_request() handle local signing and per-audience caching safely across concurrent coroutines.
  • Add unit tests: Cover service_account.Credentials (including alternating-host cache reuse, expiry re-minting, concurrent multi-threaded calls, default_scopes, domain-wide delegation subject, and pickle round-tripping), _service_account_async.Credentials, requests.AuthorizedSession, urllib3.AuthorizedHttp, grpc.AuthMetadataPlugin, grpc.secure_authorized_channel, and concurrent aio.transport.sessions.AsyncAuthorizedSession requests.

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

Gemini encountered an error creating the review. You can try again by commenting /gemini review.

@parthea

parthea commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

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.

Code Review

This pull request introduces support for deriving a self-signed JWT audience from the outbound request URL when using unscoped service account credentials in a non-default universe domain. While this aligns with AIP-4111, the current implementation of storing and mutating the derived audience on the shared Credentials instance introduces severe concurrency risks. Specifically, concurrent requests to different hosts in both multi-threaded and asynchronous environments can lead to race conditions where incorrect tokens are applied, causing authentication failures. Additionally, alternating requests to different hosts will cause cache thrashing and high CPU overhead due to constant JWT re-signing. It is highly recommended to document these limitations or implement proper synchronization and caching mechanisms.

@parthea
parthea force-pushed the fix/auth-sa-jwt-url-audience branch from d8b046b to 7e7e32a Compare November 24, 2026 19:16
@parthea

parthea commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

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.

Code Review

This pull request implements AIP-4111 self-signed JWT audience derivation from request URLs for unscoped service account credentials, enabling thread-safe caching of these JWTs using an LRU cache. The feedback identifies several key improvements: resolving a potential AttributeError in setstate by updating self.dict directly instead of calling super().setstate, defensively checking if the audience derivation helper is callable, appending non-standard ports to the derived audience to fully comply with AIP-4111, and using _helpers.from_bytes instead of .decode() to safely handle token types.

@parthea
parthea force-pushed the fix/auth-sa-jwt-url-audience branch from 7e7e32a to 03acad2 Compare November 24, 2026 19:40
@parthea

parthea commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

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.

Code Review

This pull request introduces support for deriving AIP-4111 self-signed JWT audiences from request URLs for unscoped service account credentials in non-default universe domains. It implements a thread-safe, bounded LRU cache to store these per-audience JWTs, ensuring that concurrent requests targeting different hosts do not overwrite each other's credentials. The changes span both synchronous and asynchronous service account implementations, with corresponding updates to transport sessions (including gRPC, requests, urllib3, and aio) and comprehensive test coverage. I have no feedback to provide as there are no review comments.

@parthea
parthea force-pushed the fix/auth-sa-jwt-url-audience branch from 03acad2 to 47786ec Compare November 24, 2026 19:45
@parthea
parthea marked this pull request as ready for review November 24, 2026 20:23
@parthea
parthea requested review from a team as code owners November 24, 2026 20:23
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 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 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.

@parthea

parthea commented Nov 30, 2026

Copy link
Copy Markdown
Contributor Author

This PR has been split into a 3-PR stack that also addresses all review feedback from @daniel-sanche:

  1. fix(auth): enforce self-signed JWT rules for non-default universe in service_account refresh #19279 — enforce self-signed JWT rules for non-default universe in service_account refresh (sync + async)
  2. fix(auth): derive AIP-4111 JWT audience from URL for unscoped service_account credentials #19280 — derive AIP-4111 JWT audience from URL for unscoped service_account credentials (including IPv6 bracket handling)
  3. fix(auth): refresh URL-derived self-signed JWTs on 401 across HTTP transports #19282 — refresh URL-derived self-signed JWTs on 401 across HTTP transports

Closing this PR in favor of the stack above.

@parthea parthea closed this Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants