From dc73b6ee5a8b99f4d8e9f90e3ef650b3b934ddcc Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Fri, 27 Nov 2026 19:17:25 +0000 Subject: [PATCH] fix(auth): refresh URL-derived self-signed JWTs on 401 across HTTP transports --- .../google/auth/aio/transport/sessions.py | 89 +++++++++++-------- .../auth/transport/_aiohttp_requests.py | 18 +++- .../google/auth/transport/requests.py | 9 +- .../google/auth/transport/urllib3.py | 9 +- .../google/oauth2/service_account.py | 24 ++++- .../tests/oauth2/test_service_account.py | 43 +++++++++ .../tests/transport/aio/test_sessions.py | 61 ++++++++++++- .../tests/transport/test_requests.py | 78 +++++++++++++++- .../tests/transport/test_urllib3.py | 55 +++++++++++- .../transport/test_aiohttp_requests.py | 52 +++++++++++ 10 files changed, 393 insertions(+), 45 deletions(-) diff --git a/packages/google-auth/google/auth/aio/transport/sessions.py b/packages/google-auth/google/auth/aio/transport/sessions.py index 7e30f15b9444..8b5031e3d9c8 100644 --- a/packages/google-auth/google/auth/aio/transport/sessions.py +++ b/packages/google-auth/google/auth/aio/transport/sessions.py @@ -187,6 +187,15 @@ async def apply(self, headers, token=None): async def refresh(self, request): await self._refresh_shared() + async def _refresh_self_signed_jwt_for_url(self, url): + """Refreshes a URL-derived self-signed JWT if supported by wrapped credentials.""" + refresh_for_url = getattr( + self._credentials, "_refresh_self_signed_jwt_for_url", None + ) + if not callable(refresh_for_url): + return False + return await asyncio.to_thread(refresh_for_url, self._sync_request, url) is True + @_helpers.copy_docstring(Credentials) async def before_request(self, request, method, url, headers): # _refresh_shared() calls self._credentials.refresh(), which does not @@ -601,44 +610,54 @@ async def _recover_auth_state(): ) # Always increment so waiting tasks skip the check block self._mtls_check_counter += 1 - if self._refresh_lock is None: - self._refresh_lock = asyncio.Lock() - - async with self._refresh_lock: - # Check if another task already refreshed credentials while we were waiting - if self._refresh_counter > refresh_counter_at_error: - _LOGGER.debug( - "Credentials were already refreshed by a concurrent task. Skipping duplicate refresh." - ) - else: - try: - await self._credentials.refresh(self._auth_request) - except NotImplementedError: - _LOGGER.debug( - "Credentials do not implement refresh()." - ) - # A retry only helps when an mTLS reconfiguration - # occurred for this mTLS endpoint. Short-circuit on - # non-mTLS endpoints first so that a concurrent - # rotation (which bumps the session-wide counter) - # cannot trigger a spurious retry here. - if ( - not is_mtls_endpoint - or self._mtls_reconfig_counter - <= reconfig_counter_at_error - ): - return response - except ( - exceptions.RefreshError, - getattr(exceptions, "InvalidOperation", Exception), - ) as e: + refreshed_url_jwt = isinstance( + self._credentials, _SyncCredentialsAdapter + ) and await self._credentials._refresh_self_signed_jwt_for_url( + url + ) + if not refreshed_url_jwt: + if self._refresh_lock is None: + self._refresh_lock = asyncio.Lock() + + async with self._refresh_lock: + # Check if another task already refreshed credentials while we were waiting + if self._refresh_counter > refresh_counter_at_error: _LOGGER.debug( - "Credential refresh failed, returning 401 response. Error: %s", - e, + "Credentials were already refreshed by a concurrent task. Skipping duplicate refresh." ) - return response else: - self._refresh_counter += 1 + try: + await self._credentials.refresh( + self._auth_request + ) + except NotImplementedError: + _LOGGER.debug( + "Credentials do not implement refresh()." + ) + # A retry only helps when an mTLS reconfiguration + # occurred for this mTLS endpoint. Short-circuit on + # non-mTLS endpoints first so that a concurrent + # rotation (which bumps the session-wide counter) + # cannot trigger a spurious retry here. + if ( + not is_mtls_endpoint + or self._mtls_reconfig_counter + <= reconfig_counter_at_error + ): + return response + except ( + exceptions.RefreshError, + getattr( + exceptions, "InvalidOperation", Exception + ), + ) as e: + _LOGGER.debug( + "Credential refresh failed, returning 401 response. Error: %s", + e, + ) + return response + else: + self._refresh_counter += 1 if is_streaming: return response diff --git a/packages/google-auth/google/auth/transport/_aiohttp_requests.py b/packages/google-auth/google/auth/transport/_aiohttp_requests.py index 0513602bf69f..4998b48bd305 100644 --- a/packages/google-auth/google/auth/transport/_aiohttp_requests.py +++ b/packages/google-auth/google/auth/transport/_aiohttp_requests.py @@ -30,6 +30,7 @@ from google.auth import _helpers, exceptions, transport from google.auth.aio import _helpers as _helpers_async from google.auth.transport import requests +from google.oauth2 import service_account _LOGGER = logging.getLogger(__name__) @@ -462,10 +463,21 @@ async def request( with requests.TimeoutGuard( remaining_time, asyncio.TimeoutError ) as guard: - async with self._refresh_lock: - await self._loop.run_in_executor( - None, self.credentials.refresh, auth_request + refreshed_url_jwt = ( + isinstance(self.credentials, service_account.Credentials) + and await self._loop.run_in_executor( + None, + self.credentials._refresh_self_signed_jwt_for_url, + auth_request, + url, ) + is True + ) + if not refreshed_url_jwt: + async with self._refresh_lock: + await self._loop.run_in_executor( + None, self.credentials.refresh, auth_request + ) remaining_time = guard.remaining_timeout diff --git a/packages/google-auth/google/auth/transport/requests.py b/packages/google-auth/google/auth/transport/requests.py index fe62dcedf9ea..2a02cd1973fa 100644 --- a/packages/google-auth/google/auth/transport/requests.py +++ b/packages/google-auth/google/auth/transport/requests.py @@ -788,7 +788,14 @@ def request( ) with TimeoutGuard(remaining_time) as guard: - self.credentials.refresh(auth_request) + if not ( + isinstance(self.credentials, service_account.Credentials) + and self.credentials._refresh_self_signed_jwt_for_url( + auth_request, url + ) + is True + ): + self.credentials.refresh(auth_request) remaining_time = guard.remaining_timeout # Recurse. Pass in the original headers, not our modified set, but diff --git a/packages/google-auth/google/auth/transport/urllib3.py b/packages/google-auth/google/auth/transport/urllib3.py index 0659213291bb..e83f189ccd9f 100644 --- a/packages/google-auth/google/auth/transport/urllib3.py +++ b/packages/google-auth/google/auth/transport/urllib3.py @@ -453,7 +453,14 @@ def urlopen(self, method, url, body=None, headers=None, **kwargs): self._max_refresh_attempts, ) - self.credentials.refresh(self._request) + if not ( + isinstance(self.credentials, service_account.Credentials) + and self.credentials._refresh_self_signed_jwt_for_url( + self._request, url + ) + is True + ): + self.credentials.refresh(self._request) # Recurse. Pass in the original headers, not our modified set. return self.urlopen( diff --git a/packages/google-auth/google/oauth2/service_account.py b/packages/google-auth/google/oauth2/service_account.py index 8a3bdff7b573..d92a19395b29 100644 --- a/packages/google-auth/google/oauth2/service_account.py +++ b/packages/google-auth/google/oauth2/service_account.py @@ -519,7 +519,9 @@ def _derive_self_signed_jwt_audience(self, url): host = f"[{host}]" return "https://{}/".format(host) - def _get_self_signed_jwt_for_audience(self, request, audience): + def _get_self_signed_jwt_for_audience( + self, request, audience, *, force_refresh=False + ): """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() @@ -532,10 +534,28 @@ def _get_self_signed_jwt_for_audience(self, request, audience): self, audience ) self._url_jwt_credentials_cache[audience] = jwt_credentials - if not jwt_credentials.valid: + if force_refresh or not jwt_credentials.valid: jwt_credentials.refresh(request) return _helpers.from_bytes(jwt_credentials.token) + def _refresh_self_signed_jwt_for_url(self, request, url): + """Refreshes the cached URL-derived self-signed JWT for ``url`` if applicable. + + Args: + request (google.auth.transport.Request): The object used to make + HTTP requests. + url (Optional[str]): The request's URI. + + Returns: + bool: ``True`` if ``url`` uses a URL-derived self-signed JWT and + its cached token was refreshed; ``False`` otherwise. + """ + audience = self._derive_self_signed_jwt_audience(url) + if audience is None: + return False + self._get_self_signed_jwt_for_audience(request, audience, force_refresh=True) + return True + @_helpers.copy_docstring(credentials.Credentials) def before_request(self, request, method, url, headers): audience = self._derive_self_signed_jwt_audience(url) diff --git a/packages/google-auth/tests/oauth2/test_service_account.py b/packages/google-auth/tests/oauth2/test_service_account.py index b49fb6b32df6..5e3529dcbaf2 100644 --- a/packages/google-auth/tests/oauth2/test_service_account.py +++ b/packages/google-auth/tests/oauth2/test_service_account.py @@ -1070,6 +1070,49 @@ def test_pickle_roundtrip_with_url_jwt_cache(self): ) assert payload["aud"] == f"https://pubsub.{FAKE_UNIVERSE_DOMAIN}/" + def test_refresh_self_signed_jwt_for_url(self): + """_refresh_self_signed_jwt_for_url re-mints cached URL JWTs when applicable.""" + credentials = service_account.Credentials( + SIGNER, + self.SERVICE_ACCOUNT_EMAIL, + service_account._GOOGLE_OAUTH2_TOKEN_ENDPOINT, + universe_domain=FAKE_UNIVERSE_DOMAIN, + ) + request = mock.create_autospec(transport.Request, instance=True) + target_url = f"https://storage.{FAKE_UNIVERSE_DOMAIN}/storage/v1/b" + real_now = _helpers.utcnow() + past_time = real_now - datetime.timedelta(seconds=30) + + with mock.patch.object(_helpers, "utcnow", return_value=past_time): + first_headers = {} + credentials.before_request(request, "GET", target_url, first_headers) + + with mock.patch.object(_helpers, "utcnow", return_value=real_now): + assert credentials._refresh_self_signed_jwt_for_url(request, target_url) + second_headers = {} + credentials.before_request(request, "GET", target_url, second_headers) + + request.assert_not_called() + first_token = first_headers["authorization"].split(" ", 1)[1] + second_token = second_headers["authorization"].split(" ", 1)[1] + assert first_token != second_token + first_payload = jwt.decode(first_token, PUBLIC_CERT_BYTES) + second_payload = jwt.decode(second_token, PUBLIC_CERT_BYTES) + assert first_payload["aud"] == f"https://storage.{FAKE_UNIVERSE_DOMAIN}/" + assert second_payload["aud"] == f"https://storage.{FAKE_UNIVERSE_DOMAIN}/" + assert second_payload["iat"] > first_payload["iat"] + + # Relative URLs and non-URL-JWT credentials return False. + assert not credentials._refresh_self_signed_jwt_for_url( + request, "/storage/v1/b" + ) + scoped = credentials.with_scopes( + ["https://www.googleapis.com/auth/cloud-platform"] + ) + assert not scoped._refresh_self_signed_jwt_for_url(request, target_url) + default_creds = self.make_credentials() + assert not default_creds._refresh_self_signed_jwt_for_url(request, target_url) + @pytest.mark.parametrize( "url,expected", [ diff --git a/packages/google-auth/tests/transport/aio/test_sessions.py b/packages/google-auth/tests/transport/aio/test_sessions.py index 8590abc69ae2..1a7c6fec7ae2 100644 --- a/packages/google-auth/tests/transport/aio/test_sessions.py +++ b/packages/google-auth/tests/transport/aio/test_sessions.py @@ -13,6 +13,7 @@ # limitations under the License. import asyncio +import datetime import http.client as http_client import json import threading @@ -24,7 +25,7 @@ import google.auth.credentials import google.auth.transport.requests -from google.auth import crypt, jwt +from google.auth import _helpers, crypt, jwt from google.auth.aio.credentials import AnonymousCredentials, Credentials from google.auth.aio.transport import ( _DEFAULT_TIMEOUT_SECONDS, @@ -386,6 +387,64 @@ async def test_request_non_default_universe_domain_service_account(self): # Concurrent requests to the same host share the cached token. assert len(tokens_by_url[target_url]) == 1 + @pytest.mark.asyncio + async def test_request_non_default_universe_domain_service_account_401_retries( + self, + ): + """AsyncAuthorizedSession refreshes URL-derived JWT on 401 and retries.""" + signer = crypt.RSASigner.from_string(pytest.private_key_bytes, "1") + sync_credentials = service_account.Credentials( + signer, + "service-account@example.com", + service_account._GOOGLE_OAUTH2_TOKEN_ENDPOINT, + universe_domain="universe.foo", + ) + unauthorized_response = MockResponse(status_code=http_client.UNAUTHORIZED) + ok_response = MockResponse(status_code=http_client.OK) + + real_now = _helpers.utcnow() + current_time = [real_now - datetime.timedelta(seconds=30)] + responses_iter = iter([unauthorized_response, ok_response]) + + async def mock_auth_request(*args, **kwargs): + resp = next(responses_iter) + current_time[0] = real_now + return resp + + auth_request = AsyncMock(side_effect=mock_auth_request) + mock_sync_request = Mock() + mock_sync_request.session = Mock() + + target_url = "https://storage.universe.foo/storage/v1/b" + with ( + patch( + "google.auth.transport.requests.Request", + return_value=mock_sync_request, + ), + patch.object(_helpers, "utcnow", side_effect=lambda: current_time[0]), + ): + authed_session = sessions.AsyncAuthorizedSession( + sync_credentials, auth_request=auth_request + ) + response = await authed_session.request("GET", target_url) + await authed_session.close() + + assert response is ok_response + mock_sync_request.assert_not_called() + assert auth_request.call_count == 2 + first_token = ( + auth_request.call_args_list[0].args[3]["authorization"].split(" ", 1)[1] + ) + second_token = ( + auth_request.call_args_list[1].args[3]["authorization"].split(" ", 1)[1] + ) + assert first_token != second_token + first_payload = jwt.decode(first_token, pytest.public_cert_bytes) + second_payload = jwt.decode(second_token, pytest.public_cert_bytes) + assert first_payload["aud"] == "https://storage.universe.foo/" + assert second_payload["aud"] == "https://storage.universe.foo/" + assert second_payload["iat"] > first_payload["iat"] + @pytest.mark.asyncio async def test_request_with_mock_service_account_credentials_still_refreshes(self): """Mocked service_account.Credentials still refreshes when invalid.""" diff --git a/packages/google-auth/tests/transport/test_requests.py b/packages/google-auth/tests/transport/test_requests.py index 38cc09a64db9..4ed8fc38aea0 100644 --- a/packages/google-auth/tests/transport/test_requests.py +++ b/packages/google-auth/tests/transport/test_requests.py @@ -32,7 +32,7 @@ import google.auth.transport._custom_tls_signer import google.auth.transport._mtls_helper import google.auth.transport.requests -from google.auth import crypt, environment_vars, exceptions, jwt +from google.auth import _helpers, crypt, environment_vars, exceptions, jwt from google.oauth2 import service_account from tests.transport import compliance @@ -790,6 +790,82 @@ def test_authorized_session_non_default_universe_domain_without_default_host(sel payload = jwt.decode(auth_header.split(" ", 1)[1], pytest.public_cert_bytes) assert payload["aud"] == "https://storage.universe.foo/" + @pytest.mark.parametrize( + "universe_domain,always_use_jwt_access,target_url,expected_aud", + [ + ( + "universe.foo", + False, + "https://storage.universe.foo/storage/v1/b", + "https://storage.universe.foo/", + ), + ( + google.auth.credentials.DEFAULT_UNIVERSE_DOMAIN, + True, + "https://storage.googleapis.com/storage/v1/b", + "https://storage.googleapis.com/", + ), + ], + ) + def test_authorized_session_url_jwt_401_retries_with_fresh_jwt( + self, universe_domain, always_use_jwt_access, target_url, expected_aud + ): + """AuthorizedSession refreshes URL-derived JWT on 401 without calling refresh().""" + signer = crypt.RSASigner.from_string(pytest.private_key_bytes, "1") + credentials = service_account.Credentials( + signer, + "service-account@example.com", + service_account._GOOGLE_OAUTH2_TOKEN_ENDPOINT, + always_use_jwt_access=always_use_jwt_access, + universe_domain=universe_domain, + ) + auth_request = mock.create_autospec( + google.auth.transport.Request, instance=True + ) + token_response = mock.create_autospec( + google.auth.transport.Response, instance=True + ) + token_response.status = http_client.OK + token_response.data = json.dumps( + {"access_token": "token", "expires_in": 3600} + ).encode("utf-8") + auth_request.return_value = token_response + + unauthorized = make_response(status=http_client.UNAUTHORIZED) + ok_response = make_response(status=http_client.OK) + adapter = AdapterStub([unauthorized, ok_response]) + + real_now = _helpers.utcnow() + current_time = [real_now - datetime.timedelta(seconds=30)] + original_send = adapter.send + + def send_and_tick(request, **kwargs): + resp = original_send(request, **kwargs) + current_time[0] = real_now + return resp + + adapter.send = send_and_tick + + authed_session = google.auth.transport.requests.AuthorizedSession( + credentials, auth_request=auth_request + ) + authed_session.mount("https://", adapter) + + with mock.patch.object(_helpers, "utcnow", side_effect=lambda: current_time[0]): + result = authed_session.request("GET", target_url) + + assert result == ok_response + auth_request.assert_not_called() + assert len(adapter.requests) == 2 + first_token = adapter.requests[0].headers["authorization"].split(" ", 1)[1] + second_token = adapter.requests[1].headers["authorization"].split(" ", 1)[1] + assert first_token != second_token + first_payload = jwt.decode(first_token, pytest.public_cert_bytes) + second_payload = jwt.decode(second_token, pytest.public_cert_bytes) + assert first_payload["aud"] == expected_aud + assert second_payload["aud"] == expected_aud + assert second_payload["iat"] > first_payload["iat"] + def test_configure_mtls_channel_with_callback(self): mock_callback = mock.Mock() mock_callback.return_value = ( diff --git a/packages/google-auth/tests/transport/test_urllib3.py b/packages/google-auth/tests/transport/test_urllib3.py index d36d271b347a..bcc29fcdf5a4 100644 --- a/packages/google-auth/tests/transport/test_urllib3.py +++ b/packages/google-auth/tests/transport/test_urllib3.py @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +import datetime import http.client as http_client import json import os @@ -24,7 +25,7 @@ import google.auth.credentials import google.auth.transport._mtls_helper import google.auth.transport.urllib3 -from google.auth import crypt, environment_vars, exceptions, jwt +from google.auth import _helpers, crypt, environment_vars, exceptions, jwt from google.oauth2 import service_account from tests.transport import compliance @@ -225,6 +226,58 @@ def test_authorized_http_non_default_universe_domain_without_default_host(self): payload = jwt.decode(auth_header.split(" ", 1)[1], pytest.public_cert_bytes) assert payload["aud"] == "https://storage.universe.foo/" + def test_authorized_http_non_default_universe_domain_401_retries_with_fresh_jwt( + self, + ): + """AuthorizedHttp refreshes URL-derived JWT on 401 without raising RefreshError.""" + signer = crypt.RSASigner.from_string(pytest.private_key_bytes, "1") + credentials = service_account.Credentials( + signer, + "service-account@example.com", + service_account._GOOGLE_OAUTH2_TOKEN_ENDPOINT, + universe_domain="universe.foo", + ) + unauthorized = ResponseStub(status=http_client.UNAUTHORIZED) + ok_response = ResponseStub(status=http_client.OK) + http = HttpStub([unauthorized, ok_response]) + http.request = mock.Mock( + return_value=ResponseStub( + data=json.dumps({"access_token": "token", "expires_in": 3600}).encode( + "utf-8" + ) + ) + ) + + real_now = _helpers.utcnow() + current_time = [real_now - datetime.timedelta(seconds=30)] + original_urlopen = http.urlopen + + def urlopen_and_tick(*args, **kwargs): + resp = original_urlopen(*args, **kwargs) + current_time[0] = real_now + return resp + + http.urlopen = urlopen_and_tick + + authed_http = google.auth.transport.urllib3.AuthorizedHttp( + credentials, http=http + ) + target_url = "https://storage.universe.foo/storage/v1/b" + with mock.patch.object(_helpers, "utcnow", side_effect=lambda: current_time[0]): + result = authed_http.urlopen("GET", target_url) + + assert result == ok_response + http.request.assert_not_called() + assert len(http.requests) == 2 + first_token = http.requests[0][3]["authorization"].split(" ", 1)[1] + second_token = http.requests[1][3]["authorization"].split(" ", 1)[1] + assert first_token != second_token + first_payload = jwt.decode(first_token, pytest.public_cert_bytes) + second_payload = jwt.decode(second_token, pytest.public_cert_bytes) + assert first_payload["aud"] == "https://storage.universe.foo/" + assert second_payload["aud"] == "https://storage.universe.foo/" + assert second_payload["iat"] > first_payload["iat"] + def test_proxies(self): http = mock.create_autospec(urllib3.PoolManager) authed_http = google.auth.transport.urllib3.AuthorizedHttp(None, http=http) diff --git a/packages/google-auth/tests_async/transport/test_aiohttp_requests.py b/packages/google-auth/tests_async/transport/test_aiohttp_requests.py index 2071bc589f12..6ae9e1f1f60d 100644 --- a/packages/google-auth/tests_async/transport/test_aiohttp_requests.py +++ b/packages/google-auth/tests_async/transport/test_aiohttp_requests.py @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +import datetime from unittest import mock import aiohttp # type: ignore @@ -20,7 +21,10 @@ import google.auth._credentials_async import google.auth.transport._mtls_helper +from google.auth import _helpers, jwt from google.auth.transport import _aiohttp_requests as aiohttp_requests +from google.oauth2 import _service_account_async +from tests.oauth2 import test_service_account from tests_async.transport import async_compliance @@ -474,3 +478,51 @@ async def test_request_refresh(self): assert response.status == 200 await authed_session.close() + + @pytest.mark.asyncio + async def test_request_non_default_universe_domain_service_account_401_retries( + self, + ): + """Legacy aiohttp AuthorizedSession refreshes URL-derived JWT on 401.""" + credentials = _service_account_async.Credentials( + test_service_account.SIGNER, + "service-account@example.com", + _service_account_async.service_account._GOOGLE_OAUTH2_TOKEN_ENDPOINT, + universe_domain="universe.foo", + ) + target_url = "https://storage.universe.foo/storage/v1/b" + real_now = _helpers.utcnow() + current_time = [real_now - datetime.timedelta(seconds=30)] + sent_tokens = [] + + def first_callback(url, **kwargs): + sent_tokens.append(kwargs["headers"]["authorization"].split(" ", 1)[1]) + current_time[0] = real_now + return core.CallbackResult(status=401) + + def second_callback(url, **kwargs): + sent_tokens.append(kwargs["headers"]["authorization"].split(" ", 1)[1]) + return core.CallbackResult(status=200) + + with ( + mock.patch.object(_helpers, "utcnow", side_effect=lambda: current_time[0]), + aioresponses() as mocked, + ): + mocked.get(target_url, callback=first_callback) + mocked.get(target_url, callback=second_callback) + authed_session = aiohttp_requests.AuthorizedSession(credentials) + response = await authed_session.request("GET", target_url) + await authed_session.close() + + assert response.status == 200 + assert len(sent_tokens) == 2 + assert sent_tokens[0] != sent_tokens[1] + first_payload = jwt.decode( + sent_tokens[0], test_service_account.PUBLIC_CERT_BYTES + ) + second_payload = jwt.decode( + sent_tokens[1], test_service_account.PUBLIC_CERT_BYTES + ) + assert first_payload["aud"] == "https://storage.universe.foo/" + assert second_payload["aud"] == "https://storage.universe.foo/" + assert second_payload["iat"] > first_payload["iat"]