diff --git a/packages/google-auth/google/auth/aio/transport/sessions.py b/packages/google-auth/google/auth/aio/transport/sessions.py index c4ee482895e9..7e30f15b9444 100644 --- a/packages/google-auth/google/auth/aio/transport/sessions.py +++ b/packages/google-auth/google/auth/aio/transport/sessions.py @@ -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, diff --git a/packages/google-auth/google/oauth2/_service_account_async.py b/packages/google-auth/google/oauth2/_service_account_async.py index 50ba8e82530c..f5335fb20e74 100644 --- a/packages/google-auth/google/oauth2/_service_account_async.py +++ b/packages/google-auth/google/oauth2/_service_account_async.py @@ -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 + ) + 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 diff --git a/packages/google-auth/google/oauth2/service_account.py b/packages/google-auth/google/oauth2/service_account.py index 6744e6f14d9b..9b91ef871766 100644 --- a/packages/google-auth/google/oauth2/service_account.py +++ b/packages/google-auth/google/oauth2/service_account.py @@ -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, @@ -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" @@ -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 @@ -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 + ) + @classmethod def _from_signer_and_info(cls, signer, info, **kwargs): """Creates a Credentials instance from a signer and service account @@ -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) + 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) + + 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" + ) 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. diff --git a/packages/google-auth/tests/oauth2/test_service_account.py b/packages/google-auth/tests/oauth2/test_service_account.py index 84074ec37b9a..3f113cb22d2c 100644 --- a/packages/google-auth/tests/oauth2/test_service_account.py +++ b/packages/google-auth/tests/oauth2/test_service_account.py @@ -12,9 +12,11 @@ # See the License for the specific language governing permissions and # limitations under the License. +import concurrent.futures import datetime import json import os +import pickle from unittest import mock import pytest # type: ignore @@ -677,6 +679,392 @@ def test_refresh_non_gdu_domain_wide_delegation_not_supported(self): credentials.refresh(None) assert excinfo.match("domain wide delegation is not supported") + def test_refresh_unscoped_non_default_universe_domain_requires_self_signed_jwt( + self, + ): + """Unscoped non-default universe refresh raises RefreshError without audience.""" + credentials = service_account.Credentials( + SIGNER, + self.SERVICE_ACCOUNT_EMAIL, + service_account._GOOGLE_OAUTH2_TOKEN_ENDPOINT, + scopes=None, + default_scopes=None, + universe_domain=FAKE_UNIVERSE_DOMAIN, + ) + request = mock.create_autospec(transport.Request, instance=True) + response = mock.create_autospec(transport.Response, instance=True) + response.status = 200 + response.data = json.dumps( + { + "access_token": "token", + "expires_in": 3600, + "token_type": "Bearer", + } + ).encode("utf-8") + request.return_value = response + + assert credentials._always_use_jwt_access + assert credentials._jwt_credentials is None + + with pytest.raises(exceptions.RefreshError): + credentials.refresh(request) + + request.assert_not_called() + + def test_before_request_unscoped_non_default_universe_domain_derives_audience(self): + """Unscoped non-default universe before_request derives audience from URL.""" + credentials = service_account.Credentials( + SIGNER, + self.SERVICE_ACCOUNT_EMAIL, + service_account._GOOGLE_OAUTH2_TOKEN_ENDPOINT, + scopes=None, + default_scopes=None, + universe_domain=FAKE_UNIVERSE_DOMAIN, + ) + request = mock.create_autospec(transport.Request, instance=True) + response = mock.create_autospec(transport.Response, instance=True) + response.status = 200 + response.data = json.dumps( + { + "access_token": "token", + "expires_in": 3600, + "token_type": "Bearer", + } + ).encode("utf-8") + request.return_value = response + + headers = {} + credentials.before_request( + request, + "GET", + f"https://storage.{FAKE_UNIVERSE_DOMAIN}/storage/v1/b?alt=json", + headers, + ) + + request.assert_not_called() + assert credentials._jwt_credentials is None + assert credentials.token is None + assert headers["authorization"].startswith("Bearer ") + first_token = headers["authorization"].split(" ", 1)[1] + payload = jwt.decode(first_token, PUBLIC_CERT_BYTES) + assert payload["iss"] == self.SERVICE_ACCOUNT_EMAIL + assert payload["aud"] == f"https://storage.{FAKE_UNIVERSE_DOMAIN}/" + + # A subsequent request to the same host reuses the cached token. + same_host_headers = {} + credentials.before_request( + request, + "GET", + f"https://storage.{FAKE_UNIVERSE_DOMAIN}/storage/v1/o", + same_host_headers, + ) + assert same_host_headers["authorization"] == f"Bearer {first_token}" + + # A subsequent request to a different host derives and caches its own + # audience without evicting the first host's cached token. + other_host_headers = {} + credentials.before_request( + request, + "GET", + f"https://pubsub.{FAKE_UNIVERSE_DOMAIN}/v1/projects/p/topics", + other_host_headers, + ) + request.assert_not_called() + second_token = other_host_headers["authorization"].split(" ", 1)[1] + second_payload = jwt.decode(second_token, PUBLIC_CERT_BYTES) + assert second_payload["aud"] == f"https://pubsub.{FAKE_UNIVERSE_DOMAIN}/" + + # Alternating back to the first host reuses the cached token (no thrashing). + return_host_headers = {} + credentials.before_request( + request, + "GET", + f"https://storage.{FAKE_UNIVERSE_DOMAIN}/storage/v1/b", + return_host_headers, + ) + assert return_host_headers["authorization"] == f"Bearer {first_token}" + + # Expiring the cached entry causes a fresh token to be minted. + cached_jwt_creds = credentials._url_jwt_credentials_cache[ + f"https://storage.{FAKE_UNIVERSE_DOMAIN}/" + ] + cached_jwt_creds.expiry = _helpers.utcnow() - datetime.timedelta(seconds=10) + with mock.patch.object( + cached_jwt_creds, "refresh", wraps=cached_jwt_creds.refresh + ) as refresh_spy: + refreshed_headers = {} + credentials.before_request( + request, + "GET", + f"https://storage.{FAKE_UNIVERSE_DOMAIN}/storage/v1/b", + refreshed_headers, + ) + refresh_spy.assert_called_once_with(request) + refreshed_payload = jwt.decode( + refreshed_headers["authorization"].split(" ", 1)[1], PUBLIC_CERT_BYTES + ) + assert refreshed_payload["aud"] == f"https://storage.{FAKE_UNIVERSE_DOMAIN}/" + + def test_before_request_unscoped_non_default_universe_domain_without_hostname(self): + """Unscoped non-default universe before_request fails if URL has no host.""" + credentials = service_account.Credentials( + SIGNER, + self.SERVICE_ACCOUNT_EMAIL, + service_account._GOOGLE_OAUTH2_TOKEN_ENDPOINT, + scopes=None, + default_scopes=None, + universe_domain=FAKE_UNIVERSE_DOMAIN, + ) + request = mock.create_autospec(transport.Request, instance=True) + response = mock.create_autospec(transport.Response, instance=True) + response.status = 200 + response.data = json.dumps( + { + "access_token": "token", + "expires_in": 3600, + "token_type": "Bearer", + } + ).encode("utf-8") + request.return_value = response + + with pytest.raises(exceptions.RefreshError): + credentials.before_request(request, "GET", "/storage/v1/b", {}) + + request.assert_not_called() + + def test_before_request_scoped_non_default_universe_domain_uses_scopes(self): + """Scoped non-default universe before_request keeps scope-based self-signed JWT.""" + credentials = service_account.Credentials( + SIGNER, + self.SERVICE_ACCOUNT_EMAIL, + service_account._GOOGLE_OAUTH2_TOKEN_ENDPOINT, + scopes=["https://www.googleapis.com/auth/cloud-platform"], + universe_domain=FAKE_UNIVERSE_DOMAIN, + ) + request = mock.create_autospec(transport.Request, instance=True) + + headers = {} + credentials.before_request( + request, + "GET", + f"https://storage.{FAKE_UNIVERSE_DOMAIN}/storage/v1/b", + headers, + ) + + request.assert_not_called() + token = headers["authorization"].split(" ", 1)[1] + payload = jwt.decode(token, PUBLIC_CERT_BYTES) + assert payload["scope"] == "https://www.googleapis.com/auth/cloud-platform" + assert "aud" not in payload + assert not credentials._url_jwt_credentials_cache + + def test_before_request_preserves_explicit_jwt_audience(self): + """Explicitly configured JWT audience is not overwritten by request URLs.""" + credentials = service_account.Credentials( + SIGNER, + self.SERVICE_ACCOUNT_EMAIL, + service_account._GOOGLE_OAUTH2_TOKEN_ENDPOINT, + universe_domain=FAKE_UNIVERSE_DOMAIN, + ) + explicit_audience = f"https://compute.{FAKE_UNIVERSE_DOMAIN}/" + credentials._create_self_signed_jwt(explicit_audience) + request = mock.create_autospec(transport.Request, instance=True) + + headers = {} + credentials.before_request( + request, + "GET", + f"https://us-central1-compute.{FAKE_UNIVERSE_DOMAIN}/v1/projects", + headers, + ) + + request.assert_not_called() + token = headers["authorization"].split(" ", 1)[1] + payload = jwt.decode(token, PUBLIC_CERT_BYTES) + assert payload["aud"] == explicit_audience + assert not credentials._url_jwt_credentials_cache + + def test_before_request_default_scopes_non_default_universe_domain_uses_default_scopes( + self, + ): + """Default-scoped non-default universe before_request keeps default scopes.""" + credentials = service_account.Credentials( + SIGNER, + self.SERVICE_ACCOUNT_EMAIL, + service_account._GOOGLE_OAUTH2_TOKEN_ENDPOINT, + scopes=None, + default_scopes=["https://www.googleapis.com/auth/cloud-platform"], + universe_domain=FAKE_UNIVERSE_DOMAIN, + ) + request = mock.create_autospec(transport.Request, instance=True) + + headers = {} + credentials.before_request( + request, + "GET", + f"https://us-central1-aiplatform.{FAKE_UNIVERSE_DOMAIN}/v1/projects", + headers, + ) + + request.assert_not_called() + token = headers["authorization"].split(" ", 1)[1] + payload = jwt.decode(token, PUBLIC_CERT_BYTES) + assert payload["scope"] == "https://www.googleapis.com/auth/cloud-platform" + assert "aud" not in payload + assert not credentials._url_jwt_credentials_cache + + @mock.patch("google.oauth2._client.jwt_grant", autospec=True) + def test_before_request_preserves_subject_credentials_without_deriving_url_audience( + self, jwt_grant + ): + """Domain-wide delegation credentials do not derive URL audiences or drop tokens.""" + jwt_grant.return_value = ( + "oauth-token", + _helpers.utcnow() + datetime.timedelta(seconds=500), + {}, + ) + credentials = service_account.Credentials( + SIGNER, + self.SERVICE_ACCOUNT_EMAIL, + service_account._GOOGLE_OAUTH2_TOKEN_ENDPOINT, + always_use_jwt_access=True, + subject="user@example.com", + ) + request = mock.create_autospec(transport.Request, instance=True) + + first_headers = {} + credentials.before_request( + request, "GET", "https://storage.googleapis.com/storage/v1/b", first_headers + ) + second_headers = {} + credentials.before_request( + request, "GET", "https://pubsub.googleapis.com/v1/topics", second_headers + ) + + assert jwt_grant.call_count == 1 + assert credentials._jwt_credentials is None + assert not credentials._url_jwt_credentials_cache + assert first_headers["authorization"] == "Bearer oauth-token" + assert second_headers["authorization"] == "Bearer oauth-token" + + def test_create_self_signed_jwt_none_preserves_url_derivation(self): + """No-op _create_self_signed_jwt(None) keeps URL derivation active.""" + 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) + + first_headers = {} + credentials.before_request( + request, + "GET", + f"https://storage.{FAKE_UNIVERSE_DOMAIN}/storage/v1/b", + first_headers, + ) + + # Calling _create_self_signed_jwt(None) is a no-op and keeps URL + # derivation working for other hosts. + credentials._create_self_signed_jwt(None) + + second_headers = {} + credentials.before_request( + request, + "GET", + f"https://pubsub.{FAKE_UNIVERSE_DOMAIN}/v1/projects/p/topics", + second_headers, + ) + second_payload = jwt.decode( + second_headers["authorization"].split(" ", 1)[1], PUBLIC_CERT_BYTES + ) + assert second_payload["aud"] == f"https://pubsub.{FAKE_UNIVERSE_DOMAIN}/" + + # Passing an explicit audience pins it so later URLs do not override it. + explicit_audience = f"https://compute.{FAKE_UNIVERSE_DOMAIN}/" + credentials._create_self_signed_jwt(explicit_audience) + + third_headers = {} + credentials.before_request( + request, + "GET", + f"https://storage.{FAKE_UNIVERSE_DOMAIN}/storage/v1/b", + third_headers, + ) + third_payload = jwt.decode( + third_headers["authorization"].split(" ", 1)[1], PUBLIC_CERT_BYTES + ) + assert third_payload["aud"] == explicit_audience + + def test_before_request_concurrent_multi_host_thread_safe(self): + """Concurrent multi-host before_request calls get matching per-host JWTs.""" + 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) + hosts = [ + f"storage.{FAKE_UNIVERSE_DOMAIN}", + f"pubsub.{FAKE_UNIVERSE_DOMAIN}", + f"compute.{FAKE_UNIVERSE_DOMAIN}", + ] + + def call_before_request(host): + headers = {} + credentials.before_request(request, "GET", f"https://{host}/v1/x", headers) + payload = jwt.decode( + headers["authorization"].split(" ", 1)[1], PUBLIC_CERT_BYTES + ) + return host, payload["aud"] + + with concurrent.futures.ThreadPoolExecutor(max_workers=6) as executor: + futures = [ + executor.submit(call_before_request, hosts[i % len(hosts)]) + for i in range(30) + ] + results = [f.result() for f in futures] + + request.assert_not_called() + for host, aud in results: + assert aud == f"https://{host}/" + + def test_pickle_roundtrip_with_url_jwt_cache(self): + """Credentials with populated URL JWT cache can be pickled and unpickled.""" + 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) + credentials.before_request( + request, + "GET", + f"https://storage.{FAKE_UNIVERSE_DOMAIN}/storage/v1/b", + {}, + ) + assert f"https://storage.{FAKE_UNIVERSE_DOMAIN}/" in ( + credentials._url_jwt_credentials_cache + ) + + restored = pickle.loads(pickle.dumps(credentials)) + assert not restored._url_jwt_credentials_cache + + headers = {} + restored.before_request( + request, + "GET", + f"https://pubsub.{FAKE_UNIVERSE_DOMAIN}/v1/projects/p/topics", + headers, + ) + payload = jwt.decode( + headers["authorization"].split(" ", 1)[1], PUBLIC_CERT_BYTES + ) + assert payload["aud"] == f"https://pubsub.{FAKE_UNIVERSE_DOMAIN}/" + class TestIDTokenCredentials(object): SERVICE_ACCOUNT_EMAIL = "service-account@example.com" diff --git a/packages/google-auth/tests/transport/aio/test_sessions.py b/packages/google-auth/tests/transport/aio/test_sessions.py index 8cbfa59d5683..8590abc69ae2 100644 --- a/packages/google-auth/tests/transport/aio/test_sessions.py +++ b/packages/google-auth/tests/transport/aio/test_sessions.py @@ -14,6 +14,7 @@ import asyncio import http.client as http_client +import json import threading from typing import AsyncGenerator from unittest.mock import AsyncMock, Mock, patch @@ -23,6 +24,7 @@ import google.auth.credentials import google.auth.transport.requests +from google.auth import crypt, jwt from google.auth.aio.credentials import AnonymousCredentials, Credentials from google.auth.aio.transport import ( _DEFAULT_TIMEOUT_SECONDS, @@ -327,6 +329,81 @@ async def test_constructor_no_auth_request_does_not_mutate_service_account(self) sync_credentials._create_self_signed_jwt.assert_not_called() + @pytest.mark.asyncio + async def test_request_non_default_universe_domain_service_account(self): + """AsyncAuthorizedSession mints a URL-audience JWT for unscoped service account.""" + 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", + ) + ok_response = MockResponse(status_code=http_client.OK) + auth_request = AsyncMock(return_value=ok_response) + + mock_sync_request = Mock() + mock_token_response = Mock() + mock_token_response.status = http_client.OK + mock_token_response.data = json.dumps( + {"access_token": "token", "expires_in": 3600} + ).encode("utf-8") + mock_sync_request.return_value = mock_token_response + mock_sync_request.session = Mock() + + target_url = "https://storage.universe.foo/storage/v1/b" + other_url = "https://pubsub.universe.foo/v1/projects/p/topics" + with patch( + "google.auth.transport.requests.Request", return_value=mock_sync_request + ): + authed_session = sessions.AsyncAuthorizedSession( + sync_credentials, auth_request=auth_request + ) + responses = await asyncio.gather( + authed_session.request("GET", target_url), + authed_session.request("GET", other_url), + authed_session.request("GET", target_url), + ) + await authed_session.close() + + assert all(r is ok_response for r in responses) + mock_sync_request.assert_not_called() + assert auth_request.call_count == 3 + tokens_by_url = {} + for call in auth_request.call_args_list: + req_url = call.args[0] + sent_headers = call.args[3] + assert sent_headers["authorization"].startswith("Bearer ") + token = sent_headers["authorization"].split(" ", 1)[1] + payload = jwt.decode(token, pytest.public_cert_bytes) + expected_aud = ( + "https://storage.universe.foo/" + if req_url == target_url + else "https://pubsub.universe.foo/" + ) + assert payload["aud"] == expected_aud + tokens_by_url.setdefault(req_url, set()).add(token) + # 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_with_mock_service_account_credentials_still_refreshes(self): + """Mocked service_account.Credentials still refreshes when invalid.""" + sync_credentials = Mock(spec=service_account.Credentials) + sync_credentials.valid = False + ok_response = MockResponse(status_code=http_client.OK) + auth_request = AsyncMock(return_value=ok_response) + + authed_session = sessions.AsyncAuthorizedSession( + sync_credentials, auth_request=auth_request + ) + response = await authed_session.request("GET", self.TEST_URL) + await authed_session.close() + + assert response is ok_response + sync_credentials.refresh.assert_called_once() + sync_credentials.before_request.assert_called_once() + @pytest.mark.asyncio async def test_request_default_auth_request_success(self): with aioresponses() as m: diff --git a/packages/google-auth/tests/transport/test_grpc.py b/packages/google-auth/tests/transport/test_grpc.py index f5f1354f9bfa..958207eb66af 100644 --- a/packages/google-auth/tests/transport/test_grpc.py +++ b/packages/google-auth/tests/transport/test_grpc.py @@ -14,6 +14,7 @@ import datetime import importlib +import json import os import time import warnings @@ -21,7 +22,15 @@ import pytest # type: ignore -from google.auth import _helpers, credentials, environment_vars, exceptions, transport +from google.auth import ( + _helpers, + credentials, + crypt, + environment_vars, + exceptions, + jwt, + transport, +) from google.oauth2 import service_account try: @@ -131,6 +140,53 @@ def test__get_authorization_headers_with_service_account_and_default_host(self): "https://{}/".format(default_host) ) + def test__get_authorization_headers_non_default_universe_domain_without_default_host( + self, + ): + """AuthMetadataPlugin derives JWT aud from service_url without default_host.""" + signer = crypt.RSASigner.from_string(PRIVATE_KEY_BYTES, "1") + creds = service_account.Credentials( + signer, + "service-account@example.com", + service_account._GOOGLE_OAUTH2_TOKEN_ENDPOINT, + universe_domain="universe.foo", + ) + request = mock.create_autospec(transport.Request, instance=True) + token_response = mock.create_autospec(transport.Response, instance=True) + token_response.status = 200 + token_response.data = json.dumps( + {"access_token": "token", "expires_in": 3600} + ).encode("utf-8") + request.return_value = token_response + + plugin = google.auth.transport.grpc.AuthMetadataPlugin(creds, request) + context = mock.create_autospec(grpc.AuthMetadataContext, instance=True) + context.method_name = "methodName" + context.service_url = "https://pubsub.universe.foo/google.pubsub.v1.Publisher" + + headers = dict(plugin._get_authorization_headers(context)) + + request.assert_not_called() + assert headers["authorization"].startswith("Bearer ") + payload = jwt.decode( + headers["authorization"].split(" ", 1)[1], PUBLIC_CERT_BYTES + ) + assert payload["aud"] == "https://pubsub.universe.foo/" + + # A subsequent RPC to a different host updates the derived audience even + # though AuthMetadataPlugin calls _create_self_signed_jwt(None) each call. + other_context = mock.create_autospec(grpc.AuthMetadataContext, instance=True) + other_context.method_name = "otherMethod" + other_context.service_url = ( + "https://storage.universe.foo/google.storage.v2.Storage" + ) + other_headers = dict(plugin._get_authorization_headers(other_context)) + request.assert_not_called() + other_payload = jwt.decode( + other_headers["authorization"].split(" ", 1)[1], PUBLIC_CERT_BYTES + ) + assert other_payload["aud"] == "https://storage.universe.foo/" + def test_suppress_metrics_header(self): credentials = mock.create_autospec(service_account.Credentials) @@ -468,6 +524,53 @@ def test_secure_authorized_channel_with_default_host( f"https://{default_host}/" ) + def test_secure_authorized_channel_non_default_universe_domain_service_account( + self, + secure_channel, + ssl_channel_credentials, + metadata_call_credentials, + composite_channel_credentials, + get_client_ssl_credentials, + ): + """secure_authorized_channel mints a self-signed JWT for unscoped service account.""" + signer = crypt.RSASigner.from_string(PRIVATE_KEY_BYTES, "1") + creds = service_account.Credentials( + signer, + "service-account@example.com", + service_account._GOOGLE_OAUTH2_TOKEN_ENDPOINT, + universe_domain="universe.foo", + ) + request = mock.create_autospec(transport.Request, instance=True) + token_response = mock.create_autospec(transport.Response, instance=True) + token_response.status = 200 + token_response.data = json.dumps( + {"access_token": "token", "expires_in": 3600} + ).encode("utf-8") + request.return_value = token_response + + google.auth.transport.grpc.secure_authorized_channel( + creds, + request, + "pubsub.universe.foo:443", + ssl_credentials=mock.Mock(), + ) + + auth_plugin = metadata_call_credentials.call_args[0][0] + assert isinstance(auth_plugin, google.auth.transport.grpc.AuthMetadataPlugin) + + context = mock.create_autospec(grpc.AuthMetadataContext, instance=True) + context.method_name = "methodName" + context.service_url = "https://pubsub.universe.foo/google.pubsub.v1.Publisher" + + headers = dict(auth_plugin._get_authorization_headers(context)) + + request.assert_not_called() + assert headers["authorization"].startswith("Bearer ") + payload = jwt.decode( + headers["authorization"].split(" ", 1)[1], PUBLIC_CERT_BYTES + ) + assert payload["aud"] == "https://pubsub.universe.foo/" + @mock.patch("grpc.ssl_channel_credentials", autospec=True) @mock.patch( diff --git a/packages/google-auth/tests/transport/test_requests.py b/packages/google-auth/tests/transport/test_requests.py index 05afe93ee767..38cc09a64db9 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 environment_vars, exceptions +from google.auth import crypt, environment_vars, exceptions, jwt from google.oauth2 import service_account from tests.transport import compliance @@ -750,6 +750,46 @@ def test_authorized_session_with_default_host(self): "https://{}/".format(default_host) ) + def test_authorized_session_non_default_universe_domain_without_default_host(self): + """AuthorizedSession derives JWT audience from URL if default_host is unset.""" + 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", + ) + 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 + + target_url = "https://storage.universe.foo/storage/v1/b" + response = make_response() + adapter = AdapterStub([response]) + + authed_session = google.auth.transport.requests.AuthorizedSession( + credentials, auth_request=auth_request + ) + authed_session.mount("https://", adapter) + + result = authed_session.request("GET", target_url) + + assert result == response + auth_request.assert_not_called() + assert len(adapter.requests) == 1 + auth_header = adapter.requests[0].headers["authorization"] + assert auth_header.startswith("Bearer ") + payload = jwt.decode(auth_header.split(" ", 1)[1], pytest.public_cert_bytes) + assert payload["aud"] == "https://storage.universe.foo/" + 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 2abc39c7c10f..d36d271b347a 100644 --- a/packages/google-auth/tests/transport/test_urllib3.py +++ b/packages/google-auth/tests/transport/test_urllib3.py @@ -13,6 +13,7 @@ # limitations under the License. import http.client as http_client +import json import os import threading from unittest import mock @@ -23,7 +24,7 @@ import google.auth.credentials import google.auth.transport._mtls_helper import google.auth.transport.urllib3 -from google.auth import environment_vars, exceptions +from google.auth import crypt, environment_vars, exceptions, jwt from google.oauth2 import service_account from tests.transport import compliance @@ -191,6 +192,39 @@ def test_urlopen_with_default_host(self): "https://{}/".format(default_host) ) + def test_authorized_http_non_default_universe_domain_without_default_host(self): + """AuthorizedHttp derives JWT audience from URL if default_host is unset.""" + 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", + ) + response = ResponseStub() + http = HttpStub([response]) + http.request = mock.Mock( + return_value=ResponseStub( + data=json.dumps({"access_token": "token", "expires_in": 3600}).encode( + "utf-8" + ) + ) + ) + + authed_http = google.auth.transport.urllib3.AuthorizedHttp( + credentials, http=http + ) + target_url = "https://storage.universe.foo/storage/v1/b" + result = authed_http.urlopen("GET", target_url) + + assert result == response + http.request.assert_not_called() + assert len(http.requests) == 1 + auth_header = http.requests[0][3]["authorization"] + assert auth_header.startswith("Bearer ") + payload = jwt.decode(auth_header.split(" ", 1)[1], pytest.public_cert_bytes) + assert payload["aud"] == "https://storage.universe.foo/" + 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/oauth2/test_service_account_async.py b/packages/google-auth/tests_async/oauth2/test_service_account_async.py index d3606c9641e0..3f4b4bc1c42d 100644 --- a/packages/google-auth/tests_async/oauth2/test_service_account_async.py +++ b/packages/google-auth/tests_async/oauth2/test_service_account_async.py @@ -17,7 +17,7 @@ import pytest # type: ignore -from google.auth import _helpers, crypt, environment_vars, jwt, transport +from google.auth import _helpers, crypt, environment_vars, exceptions, jwt, transport from google.oauth2 import _service_account_async as service_account from tests.oauth2 import test_service_account @@ -231,6 +231,187 @@ async def test_before_request_refreshes(self, jwt_grant): # Credentials should now be valid. assert credentials.valid + @mock.patch("google.oauth2._client_async.jwt_grant", autospec=True) + @pytest.mark.asyncio + async def test_before_request_unscoped_non_default_universe_domain_derives_audience( + self, jwt_grant + ): + """Async unscoped non-default universe before_request derives URL audience.""" + credentials = service_account.Credentials( + test_service_account.SIGNER, + self.SERVICE_ACCOUNT_EMAIL, + self.TOKEN_URI, + universe_domain="universe.foo", + ) + request = mock.create_autospec(transport.Request, instance=True) + headers = {} + + await credentials.before_request( + request, "GET", "https://storage.universe.foo/storage/v1/b", headers + ) + + jwt_grant.assert_not_called() + assert headers["authorization"].startswith("Bearer ") + payload = jwt.decode( + headers["authorization"].split(" ", 1)[1], + test_service_account.PUBLIC_CERT_BYTES, + ) + assert payload["iss"] == self.SERVICE_ACCOUNT_EMAIL + assert payload["aud"] == "https://storage.universe.foo/" + + @mock.patch("google.oauth2._client_async.jwt_grant", autospec=True) + @pytest.mark.asyncio + async def test_refresh_unscoped_non_default_universe_domain_requires_self_signed_jwt( + self, jwt_grant + ): + """Async unscoped non-default universe refresh raises RefreshError.""" + jwt_grant.return_value = ( + "token", + _helpers.utcnow() + datetime.timedelta(seconds=500), + {}, + ) + credentials = service_account.Credentials( + test_service_account.SIGNER, + self.SERVICE_ACCOUNT_EMAIL, + self.TOKEN_URI, + universe_domain="universe.foo", + ) + request = mock.create_autospec(transport.Request, instance=True) + + with pytest.raises( + exceptions.RefreshError, + match="self-signed JWT credentials could not be created", + ): + await credentials.refresh(request) + + jwt_grant.assert_not_called() + + @mock.patch("google.oauth2._client_async.jwt_grant", autospec=True) + @pytest.mark.asyncio + async def test_before_request_unscoped_non_default_universe_domain_without_hostname( + self, jwt_grant + ): + """Async unscoped non-default universe fails if URL has no hostname.""" + jwt_grant.return_value = ( + "token", + _helpers.utcnow() + datetime.timedelta(seconds=500), + {}, + ) + credentials = service_account.Credentials( + test_service_account.SIGNER, + self.SERVICE_ACCOUNT_EMAIL, + self.TOKEN_URI, + universe_domain="universe.foo", + ) + request = mock.create_autospec(transport.Request, instance=True) + + with pytest.raises( + exceptions.RefreshError, + match="self-signed JWT credentials could not be created", + ): + await credentials.before_request(request, "GET", "/storage/v1/b", {}) + + jwt_grant.assert_not_called() + + @mock.patch("google.oauth2._client_async.jwt_grant", autospec=True) + @pytest.mark.asyncio + async def test_refresh_non_gdu_domain_wide_delegation_not_supported( + self, jwt_grant + ): + """Async non-default universe rejects domain-wide delegation.""" + jwt_grant.return_value = ( + "token", + _helpers.utcnow() + datetime.timedelta(seconds=500), + {}, + ) + credentials = service_account.Credentials( + test_service_account.SIGNER, + self.SERVICE_ACCOUNT_EMAIL, + self.TOKEN_URI, + subject="user@example.com", + universe_domain="universe.foo", + ) + request = mock.create_autospec(transport.Request, instance=True) + + with pytest.raises( + exceptions.RefreshError, + match="domain wide delegation is not supported", + ): + await credentials.refresh(request) + + jwt_grant.assert_not_called() + + @mock.patch("google.oauth2._client_async.jwt_grant", autospec=True) + @pytest.mark.asyncio + async def test_before_request_scoped_non_default_universe_domain_uses_scopes( + self, jwt_grant + ): + """Async scoped non-default universe before_request uses scope-based JWT.""" + jwt_grant.return_value = ( + "token", + _helpers.utcnow() + datetime.timedelta(seconds=500), + {}, + ) + credentials = service_account.Credentials( + test_service_account.SIGNER, + self.SERVICE_ACCOUNT_EMAIL, + self.TOKEN_URI, + scopes=["https://www.googleapis.com/auth/cloud-platform"], + universe_domain="universe.foo", + ) + request = mock.create_autospec(transport.Request, instance=True) + headers = {} + + await credentials.before_request( + request, "GET", "https://storage.universe.foo/storage/v1/b", headers + ) + + jwt_grant.assert_not_called() + assert headers["authorization"].startswith("Bearer ") + payload = jwt.decode( + headers["authorization"].split(" ", 1)[1], + test_service_account.PUBLIC_CERT_BYTES, + ) + assert payload["scope"] == "https://www.googleapis.com/auth/cloud-platform" + assert "aud" not in payload + assert not credentials._url_jwt_credentials_cache + + @mock.patch("google.oauth2._client_async.jwt_grant", autospec=True) + @pytest.mark.asyncio + async def test_before_request_preserves_explicit_jwt_audience(self, jwt_grant): + """Async before_request uses explicit self-signed JWT audience without jwt_grant.""" + jwt_grant.return_value = ( + "token", + _helpers.utcnow() + datetime.timedelta(seconds=500), + {}, + ) + credentials = service_account.Credentials( + test_service_account.SIGNER, + self.SERVICE_ACCOUNT_EMAIL, + self.TOKEN_URI, + universe_domain="universe.foo", + ) + explicit_audience = "https://compute.universe.foo/" + credentials._create_self_signed_jwt(explicit_audience) + request = mock.create_autospec(transport.Request, instance=True) + headers = {} + + await credentials.before_request( + request, + "GET", + "https://us-central1-compute.universe.foo/v1/projects", + headers, + ) + + jwt_grant.assert_not_called() + assert headers["authorization"].startswith("Bearer ") + payload = jwt.decode( + headers["authorization"].split(" ", 1)[1], + test_service_account.PUBLIC_CERT_BYTES, + ) + assert payload["aud"] == explicit_audience + assert not credentials._url_jwt_credentials_cache + @pytest.mark.asyncio async def test_before_request_triggers_rab_refresh(self, monkeypatch): monkeypatch.setenv(