Repository navigation
Conversation
|
Warning Gemini encountered an error creating the review. You can try again by commenting |
|
/gemini review |
There was a problem hiding this comment.
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.
d8b046b to
7e7e32a
Compare
|
/gemini review |
There was a problem hiding this comment.
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.
7e7e32a to
03acad2
Compare
|
/gemini review |
There was a problem hiding this comment.
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.
03acad2 to
47786ec
Compare
| raise exceptions.RefreshError( | ||
| "self-signed JWT credentials could not be created for " | ||
| "non-default universe domain without scopes or audience" | ||
| ) |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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 | ||
| ) |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
It looks like
credentials_async.Credentials.before_requestcalls through toservice_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.
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
Should we handle IPv6 addresses for emulators, etc, which may contain [] brackets?
There was a problem hiding this comment.
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.
|
This PR has been split into a 3-PR stack that also addresses all review feedback from @daniel-sanche:
Closing this PR in favor of the stack above. |
Improve self-signed JWT handling for
google.oauth2.service_account.Credentialswhen operating in a non-defaultuniverse_domainwithout explicit scopes ordefault_host:service_account.Credentials.before_request()(andgoogle.oauth2._service_account_async.Credentials.before_request()to keepbefore_request()awaitable on async credentials) to derivehttps://{hostname}/from the outbound request URL when_always_use_jwt_accessis enabled and neitherscopes,default_scopes,subject, nor explicit_jwt_credentials(e.g.,default_host) are configured. Cache per-audiencejwt.Credentialsin a bounded, lock-protected_cache.LRUCache(with__getstate__/__setstate__support for pickling/deepcopy) and apply tokens directly viaapply(headers, token=token)so shared credentials remain thread- and async-safe across multiple hosts without cache thrashing.RefreshErrorinservice_account.Credentials._perform_refresh_token()when operating in a non-defaultuniverse_domainwithout scopes or an audience_SyncCredentialsAdapter: Skip the URL-less_refresh_shared()call in_SyncCredentialsAdapter.before_request()when wrapped synchronous credentials derive a URL-scoped self-signed JWT, lettingbefore_request()handle local signing and per-audience caching safely across concurrent coroutines.service_account.Credentials(including alternating-host cache reuse, expiry re-minting, concurrent multi-threaded calls,default_scopes, domain-wide delegationsubject, and pickle round-tripping),_service_account_async.Credentials,requests.AuthorizedSession,urllib3.AuthorizedHttp,grpc.AuthMetadataPlugin,grpc.secure_authorized_channel, and concurrentaio.transport.sessions.AsyncAuthorizedSessionrequests.