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
89 changes: 54 additions & 35 deletions packages/google-auth/google/auth/aio/transport/sessions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
)
Comment thread
parthea marked this conversation as resolved.
Resolved
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
Expand Down
18 changes: 15 additions & 3 deletions packages/google-auth/google/auth/transport/_aiohttp_requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Comment thread
parthea marked this conversation as resolved.
Resolved

_LOGGER = logging.getLogger(__name__)

Expand Down Expand Up @@ -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
)
Comment thread
parthea marked this conversation as resolved.
Resolved
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

Expand Down
9 changes: 8 additions & 1 deletion packages/google-auth/google/auth/transport/requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Comment thread
parthea marked this conversation as resolved.
Resolved
remaining_time = guard.remaining_timeout

# Recurse. Pass in the original headers, not our modified set, but
Expand Down
9 changes: 8 additions & 1 deletion packages/google-auth/google/auth/transport/urllib3.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Comment thread
parthea marked this conversation as resolved.
Resolved

# Recurse. Pass in the original headers, not our modified set.
return self.urlopen(
Expand Down
24 changes: 22 additions & 2 deletions packages/google-auth/google/oauth2/service_account.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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)
Expand Down
43 changes: 43 additions & 0 deletions packages/google-auth/tests/oauth2/test_service_account.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
[
Expand Down
61 changes: 60 additions & 1 deletion packages/google-auth/tests/transport/aio/test_sessions.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
# limitations under the License.

import asyncio
import datetime
import http.client as http_client
import json
import threading
Expand All @@ -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,
Expand Down Expand Up @@ -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,
"[email protected]",
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."""
Expand Down
Loading
Loading