From 0a9e4e5209d975b477fb98cd29529cc57938ebc8 Mon Sep 17 00:00:00 2001 From: Negar Bayati Date: Thu, 19 Nov 2026 07:03:06 +0000 Subject: [PATCH 1/6] fix(auth): support universe_domain in jwt and _jwt_async credentials Add `universe_domain` support and implement `CredentialsWithUniverseDomain` (`with_universe_domain()`) on `google.auth.jwt.Credentials`, `google.auth.jwt.OnDemandCredentials`, and their `google.auth._jwt_async` subclasses, matching the other credential types in `google-auth`. `universe_domain` is read from service account key info/files and signing credentials (defaulting to `googleapis.com` when omitted, such as in direct constructor calls) and preserved across credential cloning methods, while keeping Regional Access Boundary state scoped to the default universe domain. --- packages/google-auth/google/auth/jwt.py | 80 +++- packages/google-auth/tests/test_jwt.py | 414 +++++++++++++++++- .../google-auth/tests_async/test_jwt_async.py | 136 +++++- 3 files changed, 621 insertions(+), 9 deletions(-) diff --git a/packages/google-auth/google/auth/jwt.py b/packages/google-auth/google/auth/jwt.py index 4f256b79cddc..84eec88e50d8 100644 --- a/packages/google-auth/google/auth/jwt.py +++ b/packages/google-auth/google/auth/jwt.py @@ -333,6 +333,7 @@ def decode(token, certs=None, verify=True, audience=None, clock_skew_in_seconds= class Credentials( google.auth.credentials.Signing, google.auth.credentials.CredentialsWithQuotaProject, + google.auth.credentials.CredentialsWithUniverseDomain, google.auth.credentials.CredentialsWithRegionalAccessBoundary, ): """Credentials that use a JWT as the bearer token. @@ -393,6 +394,7 @@ def __init__( additional_claims=None, token_lifetime=_DEFAULT_TOKEN_LIFETIME_SECS, quota_project_id=None, + universe_domain=google.auth.credentials.DEFAULT_UNIVERSE_DOMAIN, ): """ Args: @@ -407,6 +409,8 @@ def __init__( which the token is valid. Defaults to 1 hour. quota_project_id (Optional[str]): The project ID used for quota and billing. + universe_domain (Optional[str]): The universe domain. The default + universe domain is googleapis.com. """ super(Credentials, self).__init__() self._signer = signer @@ -415,6 +419,9 @@ def __init__( self._audience = audience self._token_lifetime = token_lifetime self._quota_project_id = quota_project_id + self._universe_domain = ( + universe_domain or google.auth.credentials.DEFAULT_UNIVERSE_DOMAIN + ) if additional_claims is None: additional_claims = {} @@ -439,6 +446,10 @@ def _from_signer_and_info(cls, signer, info, **kwargs): """ kwargs.setdefault("subject", info["client_email"]) kwargs.setdefault("issuer", info["client_email"]) + if not kwargs.get("universe_domain"): + kwargs["universe_domain"] = info.get( + "universe_domain", google.auth.credentials.DEFAULT_UNIVERSE_DOMAIN + ) return cls(signer, **kwargs) @classmethod @@ -506,11 +517,21 @@ def from_signing_credentials(cls, credentials, audience, **kwargs): """ kwargs.setdefault("issuer", credentials.signer_email) kwargs.setdefault("subject", credentials.signer_email) + if not kwargs.get("universe_domain"): + kwargs["universe_domain"] = getattr( + credentials, + "universe_domain", + google.auth.credentials.DEFAULT_UNIVERSE_DOMAIN, + ) jwt_creds = cls(credentials.signer, audience=audience, **kwargs) - if isinstance( - credentials, - google.auth.credentials.CredentialsWithRegionalAccessBoundary, + if ( + isinstance( + credentials, + google.auth.credentials.CredentialsWithRegionalAccessBoundary, + ) + and jwt_creds.universe_domain + == google.auth.credentials.DEFAULT_UNIVERSE_DOMAIN ): credentials._copy_regional_access_boundary_manager(jwt_creds) @@ -545,6 +566,7 @@ def with_claims( audience=audience if audience is not None else self._audience, additional_claims=new_additional_claims, quota_project_id=self._quota_project_id, + universe_domain=self._universe_domain, ) self._copy_regional_access_boundary_manager(cred) return cred @@ -558,10 +580,27 @@ def with_quota_project(self, quota_project_id): audience=self._audience, additional_claims=self._additional_claims, quota_project_id=quota_project_id, + universe_domain=self._universe_domain, ) self._copy_regional_access_boundary_manager(cred) return cred + @_helpers.copy_docstring(google.auth.credentials.CredentialsWithUniverseDomain) + def with_universe_domain(self, universe_domain): + cred = self.__class__( + self._signer, + issuer=self._issuer, + subject=self._subject, + audience=self._audience, + additional_claims=self._additional_claims, + token_lifetime=self._token_lifetime, + quota_project_id=self._quota_project_id, + universe_domain=universe_domain, + ) + if cred.universe_domain == google.auth.credentials.DEFAULT_UNIVERSE_DOMAIN: + self._copy_regional_access_boundary_manager(cred) + return cred + def _make_jwt(self): """Make a signed JWT. @@ -637,7 +676,9 @@ def additional_claims(self): class OnDemandCredentials( - google.auth.credentials.Signing, google.auth.credentials.CredentialsWithQuotaProject + google.auth.credentials.Signing, + google.auth.credentials.CredentialsWithQuotaProject, + google.auth.credentials.CredentialsWithUniverseDomain, ): """On-demand JWT credentials. @@ -665,6 +706,7 @@ def __init__( token_lifetime=_DEFAULT_TOKEN_LIFETIME_SECS, max_cache_size=_DEFAULT_MAX_CACHE_SIZE, quota_project_id=None, + universe_domain=google.auth.credentials.DEFAULT_UNIVERSE_DOMAIN, ): """ Args: @@ -679,6 +721,8 @@ def __init__( cache. Tokens are cached using :class:`google.auth._cache.LRUCache`. quota_project_id (Optional[str]): The project ID used for quota and billing. + universe_domain (Optional[str]): The universe domain. The default + universe domain is googleapis.com. """ super(OnDemandCredentials, self).__init__() @@ -687,6 +731,9 @@ def __init__( self._subject = subject self._token_lifetime = token_lifetime self._quota_project_id = quota_project_id + self._universe_domain = ( + universe_domain or google.auth.credentials.DEFAULT_UNIVERSE_DOMAIN + ) if additional_claims is None: additional_claims = {} @@ -712,6 +759,10 @@ def _from_signer_and_info(cls, signer, info, **kwargs): """ kwargs.setdefault("subject", info["client_email"]) kwargs.setdefault("issuer", info["client_email"]) + if not kwargs.get("universe_domain"): + kwargs["universe_domain"] = info.get( + "universe_domain", google.auth.credentials.DEFAULT_UNIVERSE_DOMAIN + ) return cls(signer, **kwargs) @classmethod @@ -775,6 +826,12 @@ def from_signing_credentials(cls, credentials, **kwargs): """ kwargs.setdefault("issuer", credentials.signer_email) kwargs.setdefault("subject", credentials.signer_email) + if not kwargs.get("universe_domain"): + kwargs["universe_domain"] = getattr( + credentials, + "universe_domain", + google.auth.credentials.DEFAULT_UNIVERSE_DOMAIN, + ) return cls(credentials.signer, **kwargs) def with_claims(self, issuer=None, subject=None, additional_claims=None): @@ -802,6 +859,7 @@ def with_claims(self, issuer=None, subject=None, additional_claims=None): additional_claims=new_additional_claims, max_cache_size=self._cache.maxsize, quota_project_id=self._quota_project_id, + universe_domain=self._universe_domain, ) @_helpers.copy_docstring(google.auth.credentials.CredentialsWithQuotaProject) @@ -813,6 +871,20 @@ def with_quota_project(self, quota_project_id): additional_claims=self._additional_claims, max_cache_size=self._cache.maxsize, quota_project_id=quota_project_id, + universe_domain=self._universe_domain, + ) + + @_helpers.copy_docstring(google.auth.credentials.CredentialsWithUniverseDomain) + def with_universe_domain(self, universe_domain): + return self.__class__( + self._signer, + issuer=self._issuer, + subject=self._subject, + additional_claims=self._additional_claims, + token_lifetime=self._token_lifetime, + max_cache_size=self._cache.maxsize, + quota_project_id=self._quota_project_id, + universe_domain=universe_domain, ) @property diff --git a/packages/google-auth/tests/test_jwt.py b/packages/google-auth/tests/test_jwt.py index ffc3fe5a0112..4c79e55b48c3 100644 --- a/packages/google-auth/tests/test_jwt.py +++ b/packages/google-auth/tests/test_jwt.py @@ -14,15 +14,31 @@ import base64 import datetime +import http.client as http_client import json import os +import urllib.parse from unittest import mock import pytest # type: ignore -from google.auth import _helpers, crypt, exceptions, jwt +from google.auth import ( + _helpers, + crypt, + exceptions, + iam, + impersonated_credentials, + jwt, + transport, +) +from google.auth import ( + credentials as auth_credentials, +) +from google.auth.transport import _mtls_helper +from google.oauth2 import service_account DATA_DIR = os.path.join(os.path.dirname(__file__), "data") +FAKE_UNIVERSE_DOMAIN = "fake_universe_domain" with open(os.path.join(DATA_DIR, "privatekey.pem"), "rb") as fh: PRIVATE_KEY_BYTES = fh.read() @@ -454,6 +470,29 @@ def test_from_service_account_info(self): assert credentials._issuer == info["client_email"] assert credentials._subject == info["client_email"] assert credentials._audience == self.AUDIENCE + assert credentials.universe_domain == auth_credentials.DEFAULT_UNIVERSE_DOMAIN + + def test_from_service_account_info_universe_domain(self): + info = {**SERVICE_ACCOUNT_INFO, "universe_domain": FAKE_UNIVERSE_DOMAIN} + + credentials = jwt.Credentials.from_service_account_info( + info, audience=self.AUDIENCE + ) + assert credentials.universe_domain == FAKE_UNIVERSE_DOMAIN + + override_credentials = jwt.Credentials.from_service_account_info( + info, audience=self.AUDIENCE, universe_domain="override.domain" + ) + assert override_credentials.universe_domain == "override.domain" + + @pytest.mark.parametrize("empty_universe", [None, ""]) + def test_from_service_account_info_empty_universe_kwarg(self, empty_universe): + info = {**SERVICE_ACCOUNT_INFO, "universe_domain": FAKE_UNIVERSE_DOMAIN} + + credentials = jwt.Credentials.from_service_account_info( + info, audience=self.AUDIENCE, universe_domain=empty_universe + ) + assert credentials.universe_domain == FAKE_UNIVERSE_DOMAIN def test_from_service_account_info_args(self): info = SERVICE_ACCOUNT_INFO.copy() @@ -482,6 +521,17 @@ def test_from_service_account_file(self): assert credentials._issuer == info["client_email"] assert credentials._subject == info["client_email"] assert credentials._audience == self.AUDIENCE + assert credentials.universe_domain == auth_credentials.DEFAULT_UNIVERSE_DOMAIN + + def test_from_service_account_file_universe_domain(self, tmp_path): + info = {**SERVICE_ACCOUNT_INFO, "universe_domain": FAKE_UNIVERSE_DOMAIN} + key_file = tmp_path / "service_account_non_default.json" + key_file.write_text(json.dumps(info), encoding="utf-8") + + credentials = jwt.Credentials.from_service_account_file( + str(key_file), audience=self.AUDIENCE + ) + assert credentials.universe_domain == FAKE_UNIVERSE_DOMAIN def test_from_service_account_file_args(self): info = SERVICE_ACCOUNT_INFO.copy() @@ -517,6 +567,24 @@ def test_default_state(self): assert not self.credentials.valid # Expiration hasn't been set yet assert not self.credentials.expired + assert ( + self.credentials.universe_domain == auth_credentials.DEFAULT_UNIVERSE_DOMAIN + ) + assert self.credentials._is_regional_access_boundary_lookup_required() is True + assert isinstance( + self.credentials, auth_credentials.CredentialsWithUniverseDomain + ) + + @pytest.mark.parametrize("empty_universe", [None, ""]) + def test_constructor_empty_universe_domain(self, signer, empty_universe): + credentials = jwt.Credentials( + signer, + self.SERVICE_ACCOUNT_EMAIL, + self.SERVICE_ACCOUNT_EMAIL, + self.AUDIENCE, + universe_domain=empty_universe, + ) + assert credentials.universe_domain == auth_credentials.DEFAULT_UNIVERSE_DOMAIN def test_with_claims(self): new_audience = "new_audience" @@ -528,6 +596,12 @@ def test_with_claims(self): assert new_credentials._audience == new_audience assert new_credentials._additional_claims == self.credentials._additional_claims assert new_credentials._quota_project_id == self.credentials._quota_project_id + assert ( + self.credentials.with_universe_domain(FAKE_UNIVERSE_DOMAIN) + .with_claims(audience=new_audience) + .universe_domain + == FAKE_UNIVERSE_DOMAIN + ) def test__make_jwt_without_audience(self): cred = jwt.Credentials.from_service_account_info( @@ -552,6 +626,12 @@ def test_with_quota_project(self): assert new_credentials._additional_claims == self.credentials._additional_claims assert new_credentials.additional_claims == self.credentials._additional_claims assert new_credentials._quota_project_id == quota_project_id + assert ( + self.credentials.with_universe_domain(FAKE_UNIVERSE_DOMAIN) + .with_quota_project(quota_project_id) + .universe_domain + == FAKE_UNIVERSE_DOMAIN + ) def test_sign_bytes(self): to_sign = b"123" @@ -669,8 +749,6 @@ def test_cloning_retains_rab_manager_data(self): assert cloned_quota._rab_manager is not self.credentials._rab_manager def test_from_signing_credentials_copies_rab_state(self): - from google.oauth2 import service_account - sa_creds = service_account.Credentials.from_service_account_info( SERVICE_ACCOUNT_INFO ) @@ -681,6 +759,224 @@ def test_from_signing_credentials_copies_rab_state(self): assert jwt_creds._rab_manager._data == mock.sentinel.rab_data assert jwt_creds._rab_manager is not sa_creds._rab_manager + def test_from_signing_credentials_universe_domain(self): + sa_creds = service_account.Credentials.from_service_account_info( + {**SERVICE_ACCOUNT_INFO, "universe_domain": FAKE_UNIVERSE_DOMAIN} + ) + jwt_creds = jwt.Credentials.from_signing_credentials( + sa_creds, audience=self.AUDIENCE + ) + assert jwt_creds.universe_domain == FAKE_UNIVERSE_DOMAIN + + override_creds = jwt.Credentials.from_signing_credentials( + sa_creds, audience=self.AUDIENCE, universe_domain="override.domain" + ) + assert override_creds.universe_domain == "override.domain" + + bare_signing = mock.create_autospec(auth_credentials.Signing, instance=True) + bare_signing.signer = self.credentials.signer + bare_signing.signer_email = self.SERVICE_ACCOUNT_EMAIL + fallback_creds = jwt.Credentials.from_signing_credentials( + bare_signing, audience=self.AUDIENCE + ) + assert ( + fallback_creds.universe_domain == auth_credentials.DEFAULT_UNIVERSE_DOMAIN + ) + + @pytest.mark.parametrize("empty_universe", [None, ""]) + def test_from_signing_credentials_empty_universe_kwarg(self, empty_universe): + sa_creds = service_account.Credentials.from_service_account_info( + {**SERVICE_ACCOUNT_INFO, "universe_domain": FAKE_UNIVERSE_DOMAIN} + ) + jwt_creds = jwt.Credentials.from_signing_credentials( + sa_creds, audience=self.AUDIENCE, universe_domain=empty_universe + ) + assert jwt_creds.universe_domain == FAKE_UNIVERSE_DOMAIN + + def test_with_universe_domain(self, signer): + self.credentials._rab_manager._data = mock.sentinel.rab_data + + gdu_copy = self.credentials.with_universe_domain( + auth_credentials.DEFAULT_UNIVERSE_DOMAIN + ) + assert gdu_copy.universe_domain == auth_credentials.DEFAULT_UNIVERSE_DOMAIN + assert gdu_copy._rab_manager._data == mock.sentinel.rab_data + assert gdu_copy._rab_manager is not self.credentials._rab_manager + + non_default = self.credentials.with_universe_domain(FAKE_UNIVERSE_DOMAIN) + assert isinstance(non_default, jwt.Credentials) + assert non_default.universe_domain == FAKE_UNIVERSE_DOMAIN + assert non_default._rab_manager._data.encoded_locations is None + assert non_default._rab_manager._data.expiry is None + assert non_default._rab_manager is not self.credentials._rab_manager + + reset_default = non_default.with_universe_domain( + auth_credentials.DEFAULT_UNIVERSE_DOMAIN + ) + assert reset_default.universe_domain == auth_credentials.DEFAULT_UNIVERSE_DOMAIN + + custom_lifetime_creds = jwt.Credentials( + signer, + self.SERVICE_ACCOUNT_EMAIL, + self.SERVICE_ACCOUNT_EMAIL, + self.AUDIENCE, + token_lifetime=600, + ) + assert ( + custom_lifetime_creds.with_universe_domain( + FAKE_UNIVERSE_DOMAIN + )._token_lifetime + == 600 + ) + + def test_before_request_with_universe_domain_clears_cached_rab(self): + self.credentials._set_regional_access_boundary( + { + "encodedLocations": "0xA30", + "expiry": _helpers.utcnow() + datetime.timedelta(hours=1), + } + ) + non_default = self.credentials.with_universe_domain(FAKE_UNIVERSE_DOMAIN) + non_default._set_blocking_regional_access_boundary_lookup() + + request = mock.create_autospec(transport.Request, instance=True) + headers = {} + non_default.before_request( + request, + "GET", + f"https://pubsub.{FAKE_UNIVERSE_DOMAIN}/v1/projects/p/topics", + headers, + ) + + assert "authorization" in headers + assert "x-allowed-locations" not in headers + request.assert_not_called() + + def test_before_request_from_signing_credentials_override_clears_cached_rab(self): + gdu_sa_creds = service_account.Credentials.from_service_account_info( + SERVICE_ACCOUNT_INFO + ) + gdu_sa_creds._set_regional_access_boundary( + { + "encodedLocations": "0xA30", + "expiry": _helpers.utcnow() + datetime.timedelta(hours=1), + } + ) + jwt_creds = jwt.Credentials.from_signing_credentials( + gdu_sa_creds, audience=self.AUDIENCE, universe_domain=FAKE_UNIVERSE_DOMAIN + ) + assert jwt_creds._rab_manager._data.encoded_locations is None + assert jwt_creds._rab_manager._data.expiry is None + + jwt_creds._set_blocking_regional_access_boundary_lookup() + request = mock.create_autospec(transport.Request, instance=True) + headers = {} + jwt_creds.before_request( + request, + "GET", + f"https://pubsub.{FAKE_UNIVERSE_DOMAIN}/v1/projects/p/topics", + headers, + ) + + assert "authorization" in headers + assert "x-allowed-locations" not in headers + request.assert_not_called() + + def test_before_request_non_default_universe_skips_rab_lookup(self, signer): + credentials = jwt.Credentials( + signer, + self.SERVICE_ACCOUNT_EMAIL, + self.SERVICE_ACCOUNT_EMAIL, + self.AUDIENCE, + universe_domain=FAKE_UNIVERSE_DOMAIN, + ) + credentials._set_blocking_regional_access_boundary_lookup() + assert credentials._is_regional_access_boundary_lookup_required() is False + + request = mock.create_autospec(transport.Request, instance=True) + headers = {} + credentials.before_request( + request, + "GET", + f"https://pubsub.{FAKE_UNIVERSE_DOMAIN}/v1/projects/p/topics", + headers, + ) + + assert "authorization" in headers + assert "x-allowed-locations" not in headers + request.assert_not_called() + + def test_before_request_default_universe_performs_rab_lookup(self, monkeypatch): + monkeypatch.setattr(_mtls_helper, "check_use_client_cert", lambda: False) + self.credentials._set_blocking_regional_access_boundary_lookup() + + response = mock.create_autospec(transport.Response, instance=True) + response.status = http_client.OK + response.data = json.dumps( + {"locations": ["us-central1"], "encodedLocations": "0xA30"} + ).encode("utf-8") + request = mock.create_autospec( + transport.Request, instance=True, return_value=response + ) + + headers = {} + self.credentials.before_request( + request, + "GET", + "https://pubsub.googleapis.com/v1/projects/p/topics", + headers, + ) + + assert "authorization" in headers + assert headers["x-allowed-locations"] == "0xA30" + request.assert_called_once() + + def test_impersonated_credentials_with_non_default_jwt_source( + self, signer, monkeypatch + ): + monkeypatch.setattr( + iam, + "_IAM_ENDPOINT", + "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/{}:generateAccessToken", + ) + source_credentials = jwt.Credentials( + signer, + self.SERVICE_ACCOUNT_EMAIL, + self.SERVICE_ACCOUNT_EMAIL, + audience=f"https://iamcredentials.{FAKE_UNIVERSE_DOMAIN}/", + universe_domain=FAKE_UNIVERSE_DOMAIN, + ) + source_credentials._set_blocking_regional_access_boundary_lookup() + + impersonated = impersonated_credentials.Credentials( + source_credentials=source_credentials, + target_principal="target@project.iam.gserviceaccount.com", + target_scopes=["https://www.googleapis.com/auth/cloud-platform"], + ) + assert impersonated.universe_domain == FAKE_UNIVERSE_DOMAIN + + expire_time = ( + _helpers.utcnow().replace(microsecond=0) + datetime.timedelta(seconds=500) + ).isoformat("T") + "Z" + response = mock.create_autospec(transport.Response, instance=True) + response.status = http_client.OK + response.data = json.dumps( + {"accessToken": "imp-token", "expireTime": expire_time} + ).encode("utf-8") + request = mock.create_autospec( + transport.Request, instance=True, return_value=response + ) + + impersonated.refresh(request) + + assert impersonated.token == "imp-token" + request.assert_called_once() + called_url = request.call_args.kwargs["url"] + assert ( + urllib.parse.urlsplit(called_url).hostname + == f"iamcredentials.{FAKE_UNIVERSE_DOMAIN}" + ) + class TestOnDemandCredentials(object): SERVICE_ACCOUNT_EMAIL = "service-account@example.com" @@ -706,6 +1002,27 @@ def test_from_service_account_info(self): assert credentials._signer.key_id == info["private_key_id"] assert credentials._issuer == info["client_email"] assert credentials._subject == info["client_email"] + assert credentials.universe_domain == auth_credentials.DEFAULT_UNIVERSE_DOMAIN + + def test_from_service_account_info_universe_domain(self): + info = {**SERVICE_ACCOUNT_INFO, "universe_domain": FAKE_UNIVERSE_DOMAIN} + + credentials = jwt.OnDemandCredentials.from_service_account_info(info) + assert credentials.universe_domain == FAKE_UNIVERSE_DOMAIN + + override_credentials = jwt.OnDemandCredentials.from_service_account_info( + info, universe_domain="override.domain" + ) + assert override_credentials.universe_domain == "override.domain" + + @pytest.mark.parametrize("empty_universe", [None, ""]) + def test_from_service_account_info_empty_universe_kwarg(self, empty_universe): + info = {**SERVICE_ACCOUNT_INFO, "universe_domain": FAKE_UNIVERSE_DOMAIN} + + credentials = jwt.OnDemandCredentials.from_service_account_info( + info, universe_domain=empty_universe + ) + assert credentials.universe_domain == FAKE_UNIVERSE_DOMAIN def test_from_service_account_info_args(self): info = SERVICE_ACCOUNT_INFO.copy() @@ -729,6 +1046,15 @@ def test_from_service_account_file(self): assert credentials._signer.key_id == info["private_key_id"] assert credentials._issuer == info["client_email"] assert credentials._subject == info["client_email"] + assert credentials.universe_domain == auth_credentials.DEFAULT_UNIVERSE_DOMAIN + + def test_from_service_account_file_universe_domain(self, tmp_path): + info = {**SERVICE_ACCOUNT_INFO, "universe_domain": FAKE_UNIVERSE_DOMAIN} + key_file = tmp_path / "service_account_non_default.json" + key_file.write_text(json.dumps(info), encoding="utf-8") + + credentials = jwt.OnDemandCredentials.from_service_account_file(str(key_file)) + assert credentials.universe_domain == FAKE_UNIVERSE_DOMAIN def test_from_service_account_file_args(self): info = SERVICE_ACCOUNT_INFO.copy() @@ -755,11 +1081,81 @@ def test_from_signing_credentials(self): assert jwt_from_signing._issuer == jwt_from_info._issuer assert jwt_from_signing._subject == jwt_from_info._subject + def test_from_signing_credentials_universe_domain(self): + sa_creds = service_account.Credentials.from_service_account_info( + {**SERVICE_ACCOUNT_INFO, "universe_domain": FAKE_UNIVERSE_DOMAIN} + ) + jwt_creds = jwt.OnDemandCredentials.from_signing_credentials(sa_creds) + assert isinstance(jwt_creds, jwt.OnDemandCredentials) + assert jwt_creds.universe_domain == FAKE_UNIVERSE_DOMAIN + + override_creds = jwt.OnDemandCredentials.from_signing_credentials( + sa_creds, universe_domain="override.domain" + ) + assert override_creds.universe_domain == "override.domain" + + bare_signing = mock.create_autospec(auth_credentials.Signing, instance=True) + bare_signing.signer = self.credentials.signer + bare_signing.signer_email = self.SERVICE_ACCOUNT_EMAIL + fallback_creds = jwt.OnDemandCredentials.from_signing_credentials(bare_signing) + assert ( + fallback_creds.universe_domain == auth_credentials.DEFAULT_UNIVERSE_DOMAIN + ) + + @pytest.mark.parametrize("empty_universe", [None, ""]) + def test_from_signing_credentials_empty_universe_kwarg(self, empty_universe): + sa_creds = service_account.Credentials.from_service_account_info( + {**SERVICE_ACCOUNT_INFO, "universe_domain": FAKE_UNIVERSE_DOMAIN} + ) + jwt_creds = jwt.OnDemandCredentials.from_signing_credentials( + sa_creds, universe_domain=empty_universe + ) + assert jwt_creds.universe_domain == FAKE_UNIVERSE_DOMAIN + def test_default_state(self): # Credentials are *always* valid. assert self.credentials.valid # Credentials *never* expire. assert not self.credentials.expired + assert ( + self.credentials.universe_domain == auth_credentials.DEFAULT_UNIVERSE_DOMAIN + ) + assert isinstance( + self.credentials, auth_credentials.CredentialsWithUniverseDomain + ) + + @pytest.mark.parametrize("empty_universe", [None, ""]) + def test_constructor_empty_universe_domain(self, signer, empty_universe): + credentials = jwt.OnDemandCredentials( + signer, + self.SERVICE_ACCOUNT_EMAIL, + self.SERVICE_ACCOUNT_EMAIL, + universe_domain=empty_universe, + ) + assert credentials.universe_domain == auth_credentials.DEFAULT_UNIVERSE_DOMAIN + + def test_with_universe_domain(self, signer): + non_default = self.credentials.with_universe_domain(FAKE_UNIVERSE_DOMAIN) + assert isinstance(non_default, jwt.OnDemandCredentials) + assert non_default.universe_domain == FAKE_UNIVERSE_DOMAIN + + reset_default = non_default.with_universe_domain( + auth_credentials.DEFAULT_UNIVERSE_DOMAIN + ) + assert reset_default.universe_domain == auth_credentials.DEFAULT_UNIVERSE_DOMAIN + + custom_lifetime_creds = jwt.OnDemandCredentials( + signer, + self.SERVICE_ACCOUNT_EMAIL, + self.SERVICE_ACCOUNT_EMAIL, + token_lifetime=600, + ) + assert ( + custom_lifetime_creds.with_universe_domain( + FAKE_UNIVERSE_DOMAIN + )._token_lifetime + == 600 + ) def test_with_claims(self): new_claims = {"meep": "moop"} @@ -769,6 +1165,12 @@ def test_with_claims(self): assert new_credentials._issuer == self.credentials._issuer assert new_credentials._subject == self.credentials._subject assert new_credentials._additional_claims == new_claims + assert ( + self.credentials.with_universe_domain(FAKE_UNIVERSE_DOMAIN) + .with_claims(additional_claims=new_claims) + .universe_domain + == FAKE_UNIVERSE_DOMAIN + ) def test_with_quota_project(self): quota_project_id = "project-foo" @@ -779,6 +1181,12 @@ def test_with_quota_project(self): assert new_credentials._subject == self.credentials._subject assert new_credentials._additional_claims == self.credentials._additional_claims assert new_credentials._quota_project_id == quota_project_id + assert ( + self.credentials.with_universe_domain(FAKE_UNIVERSE_DOMAIN) + .with_quota_project(quota_project_id) + .universe_domain + == FAKE_UNIVERSE_DOMAIN + ) def test_sign_bytes(self): to_sign = b"123" diff --git a/packages/google-auth/tests_async/test_jwt_async.py b/packages/google-auth/tests_async/test_jwt_async.py index 22ee7c26ff13..7dee2e6e9241 100644 --- a/packages/google-auth/tests_async/test_jwt_async.py +++ b/packages/google-auth/tests_async/test_jwt_async.py @@ -13,13 +13,27 @@ # limitations under the License. import datetime +import http.client as http_client import json from unittest import mock import pytest # type: ignore -from google.auth import _jwt_async as jwt_async -from google.auth import crypt, exceptions +from google.auth import ( + _helpers, + _regional_access_boundary_utils, + crypt, + exceptions, +) +from google.auth import ( + _jwt_async as jwt_async, +) +from google.auth import ( + credentials as auth_credentials, +) +from google.auth.aio import transport as aio_transport +from google.auth.transport import _mtls_helper +from google.oauth2 import service_account from tests import test_jwt @@ -119,6 +133,44 @@ def test_default_state(self): assert not self.credentials.valid # Expiration hasn't been set yet assert not self.credentials.expired + assert ( + self.credentials.universe_domain == auth_credentials.DEFAULT_UNIVERSE_DOMAIN + ) + assert isinstance( + self.credentials, auth_credentials.CredentialsWithUniverseDomain + ) + + def test_universe_domain(self): + info = { + **test_jwt.SERVICE_ACCOUNT_INFO, + "universe_domain": test_jwt.FAKE_UNIVERSE_DOMAIN, + } + from_info = jwt_async.Credentials.from_service_account_info( + info, audience=self.AUDIENCE + ) + assert isinstance(from_info, jwt_async.Credentials) + assert from_info.universe_domain == test_jwt.FAKE_UNIVERSE_DOMAIN + + sa_creds = service_account.Credentials.from_service_account_info(info) + from_signing = jwt_async.Credentials.from_signing_credentials( + sa_creds, audience=self.AUDIENCE + ) + assert isinstance(from_signing, jwt_async.Credentials) + assert from_signing.universe_domain == test_jwt.FAKE_UNIVERSE_DOMAIN + + self.credentials._rab_manager._data = mock.sentinel.rab_data + non_default = self.credentials.with_universe_domain( + test_jwt.FAKE_UNIVERSE_DOMAIN + ) + assert isinstance(non_default, jwt_async.Credentials) + assert non_default.universe_domain == test_jwt.FAKE_UNIVERSE_DOMAIN + assert non_default._rab_manager._data.encoded_locations is None + assert non_default._rab_manager._data.expiry is None + assert non_default._rab_manager is not self.credentials._rab_manager + assert isinstance( + non_default._rab_manager.refresh_manager, + _regional_access_boundary_utils._AsyncRegionalAccessBoundaryRefreshManager, + ) def test_with_claims(self): new_audience = "new_audience" @@ -244,6 +296,60 @@ async def test_before_request_refreshes(self): ) assert self.credentials.valid + @pytest.mark.asyncio + async def test_before_request_default_universe_performs_rab_lookup( + self, monkeypatch + ): + monkeypatch.setattr(_mtls_helper, "check_use_client_cert", lambda: False) + self.credentials._set_blocking_regional_access_boundary_lookup() + + response = mock.AsyncMock(spec=aio_transport.Response) + response.status_code = http_client.OK + response.read = mock.AsyncMock( + return_value=json.dumps( + {"locations": ["us-central1"], "encodedLocations": "0xA30"} + ).encode("utf-8") + ) + request = mock.AsyncMock(spec=aio_transport.Request, return_value=response) + + headers = {} + await self.credentials.before_request( + request, + "GET", + "https://pubsub.googleapis.com/v1/projects/p/topics", + headers, + ) + + assert "authorization" in headers + assert headers["x-allowed-locations"] == "0xA30" + request.assert_awaited_once() + + @pytest.mark.asyncio + async def test_before_request_with_universe_domain_clears_cached_rab(self): + self.credentials._set_regional_access_boundary( + { + "encodedLocations": "0xA30", + "expiry": _helpers.utcnow() + datetime.timedelta(hours=1), + } + ) + non_default = self.credentials.with_universe_domain( + test_jwt.FAKE_UNIVERSE_DOMAIN + ) + non_default._set_blocking_regional_access_boundary_lookup() + + request = mock.AsyncMock(spec=aio_transport.Request) + headers = {} + await non_default.before_request( + request, + "GET", + f"https://pubsub.{test_jwt.FAKE_UNIVERSE_DOMAIN}/v1/projects/p/topics", + headers, + ) + + assert "authorization" in headers + assert "x-allowed-locations" not in headers + request.assert_not_called() + class TestOnDemandCredentials(object): SERVICE_ACCOUNT_EMAIL = "service-account@example.com" @@ -323,6 +429,32 @@ def test_default_state(self): assert self.credentials.valid # Credentials *never* expire. assert not self.credentials.expired + assert ( + self.credentials.universe_domain == auth_credentials.DEFAULT_UNIVERSE_DOMAIN + ) + assert isinstance( + self.credentials, auth_credentials.CredentialsWithUniverseDomain + ) + + def test_universe_domain(self): + info = { + **test_jwt.SERVICE_ACCOUNT_INFO, + "universe_domain": test_jwt.FAKE_UNIVERSE_DOMAIN, + } + from_info = jwt_async.OnDemandCredentials.from_service_account_info(info) + assert isinstance(from_info, jwt_async.OnDemandCredentials) + assert from_info.universe_domain == test_jwt.FAKE_UNIVERSE_DOMAIN + + sa_creds = service_account.Credentials.from_service_account_info(info) + from_signing = jwt_async.OnDemandCredentials.from_signing_credentials(sa_creds) + assert isinstance(from_signing, jwt_async.OnDemandCredentials) + assert from_signing.universe_domain == test_jwt.FAKE_UNIVERSE_DOMAIN + + non_default = self.credentials.with_universe_domain( + test_jwt.FAKE_UNIVERSE_DOMAIN + ) + assert isinstance(non_default, jwt_async.OnDemandCredentials) + assert non_default.universe_domain == test_jwt.FAKE_UNIVERSE_DOMAIN def test_with_claims(self): new_claims = {"meep": "moop"} From 34ecfd37f341ac39e29ff8ad2908b654e997c0bc Mon Sep 17 00:00:00 2001 From: Negar Bayati Date: Sat, 21 Nov 2026 00:45:01 +0000 Subject: [PATCH 2/6] test(auth): enable RAB env var in jwt before_request tests --- packages/google-auth/tests/test_jwt.py | 29 +++++++++++++++---- .../google-auth/tests_async/test_jwt_async.py | 13 ++++++++- 2 files changed, 36 insertions(+), 6 deletions(-) diff --git a/packages/google-auth/tests/test_jwt.py b/packages/google-auth/tests/test_jwt.py index 4c79e55b48c3..811e7f61601f 100644 --- a/packages/google-auth/tests/test_jwt.py +++ b/packages/google-auth/tests/test_jwt.py @@ -25,6 +25,7 @@ from google.auth import ( _helpers, crypt, + environment_vars, exceptions, iam, impersonated_credentials, @@ -570,7 +571,6 @@ def test_default_state(self): assert ( self.credentials.universe_domain == auth_credentials.DEFAULT_UNIVERSE_DOMAIN ) - assert self.credentials._is_regional_access_boundary_lookup_required() is True assert isinstance( self.credentials, auth_credentials.CredentialsWithUniverseDomain ) @@ -829,7 +829,11 @@ def test_with_universe_domain(self, signer): == 600 ) - def test_before_request_with_universe_domain_clears_cached_rab(self): + def test_before_request_with_universe_domain_clears_cached_rab(self, monkeypatch): + monkeypatch.setenv( + environment_vars.GOOGLE_SDK_EXPERIMENTAL_PYTHON_REGIONAL_ACCESS_BOUNDARY_LOOKUP_ENABLED, + "true", + ) self.credentials._set_regional_access_boundary( { "encodedLocations": "0xA30", @@ -852,7 +856,13 @@ def test_before_request_with_universe_domain_clears_cached_rab(self): assert "x-allowed-locations" not in headers request.assert_not_called() - def test_before_request_from_signing_credentials_override_clears_cached_rab(self): + def test_before_request_from_signing_credentials_override_clears_cached_rab( + self, monkeypatch + ): + monkeypatch.setenv( + environment_vars.GOOGLE_SDK_EXPERIMENTAL_PYTHON_REGIONAL_ACCESS_BOUNDARY_LOOKUP_ENABLED, + "true", + ) gdu_sa_creds = service_account.Credentials.from_service_account_info( SERVICE_ACCOUNT_INFO ) @@ -882,7 +892,13 @@ def test_before_request_from_signing_credentials_override_clears_cached_rab(self assert "x-allowed-locations" not in headers request.assert_not_called() - def test_before_request_non_default_universe_skips_rab_lookup(self, signer): + def test_before_request_non_default_universe_skips_rab_lookup( + self, signer, monkeypatch + ): + monkeypatch.setenv( + environment_vars.GOOGLE_SDK_EXPERIMENTAL_PYTHON_REGIONAL_ACCESS_BOUNDARY_LOOKUP_ENABLED, + "true", + ) credentials = jwt.Credentials( signer, self.SERVICE_ACCOUNT_EMAIL, @@ -907,6 +923,10 @@ def test_before_request_non_default_universe_skips_rab_lookup(self, signer): request.assert_not_called() def test_before_request_default_universe_performs_rab_lookup(self, monkeypatch): + monkeypatch.setenv( + environment_vars.GOOGLE_SDK_EXPERIMENTAL_PYTHON_REGIONAL_ACCESS_BOUNDARY_LOOKUP_ENABLED, + "true", + ) monkeypatch.setattr(_mtls_helper, "check_use_client_cert", lambda: False) self.credentials._set_blocking_regional_access_boundary_lookup() @@ -946,7 +966,6 @@ def test_impersonated_credentials_with_non_default_jwt_source( audience=f"https://iamcredentials.{FAKE_UNIVERSE_DOMAIN}/", universe_domain=FAKE_UNIVERSE_DOMAIN, ) - source_credentials._set_blocking_regional_access_boundary_lookup() impersonated = impersonated_credentials.Credentials( source_credentials=source_credentials, diff --git a/packages/google-auth/tests_async/test_jwt_async.py b/packages/google-auth/tests_async/test_jwt_async.py index 7dee2e6e9241..5b2784069bd8 100644 --- a/packages/google-auth/tests_async/test_jwt_async.py +++ b/packages/google-auth/tests_async/test_jwt_async.py @@ -23,6 +23,7 @@ _helpers, _regional_access_boundary_utils, crypt, + environment_vars, exceptions, ) from google.auth import ( @@ -300,6 +301,10 @@ async def test_before_request_refreshes(self): async def test_before_request_default_universe_performs_rab_lookup( self, monkeypatch ): + monkeypatch.setenv( + environment_vars.GOOGLE_SDK_EXPERIMENTAL_PYTHON_REGIONAL_ACCESS_BOUNDARY_LOOKUP_ENABLED, + "true", + ) monkeypatch.setattr(_mtls_helper, "check_use_client_cert", lambda: False) self.credentials._set_blocking_regional_access_boundary_lookup() @@ -325,7 +330,13 @@ async def test_before_request_default_universe_performs_rab_lookup( request.assert_awaited_once() @pytest.mark.asyncio - async def test_before_request_with_universe_domain_clears_cached_rab(self): + async def test_before_request_with_universe_domain_clears_cached_rab( + self, monkeypatch + ): + monkeypatch.setenv( + environment_vars.GOOGLE_SDK_EXPERIMENTAL_PYTHON_REGIONAL_ACCESS_BOUNDARY_LOOKUP_ENABLED, + "true", + ) self.credentials._set_regional_access_boundary( { "encodedLocations": "0xA30", From ee688af262e3a58459b417e8ca5cf04201f81faa Mon Sep 17 00:00:00 2001 From: Negar Bayati Date: Sat, 21 Nov 2026 00:57:14 +0000 Subject: [PATCH 3/6] fix(auth): preserve token_lifetime when cloning JWT credentials --- packages/google-auth/google/auth/jwt.py | 4 +++ packages/google-auth/tests/test_jwt.py | 44 +++++++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/packages/google-auth/google/auth/jwt.py b/packages/google-auth/google/auth/jwt.py index 84eec88e50d8..bcf3c6e8a597 100644 --- a/packages/google-auth/google/auth/jwt.py +++ b/packages/google-auth/google/auth/jwt.py @@ -565,6 +565,7 @@ def with_claims( subject=subject if subject is not None else self._subject, audience=audience if audience is not None else self._audience, additional_claims=new_additional_claims, + token_lifetime=self._token_lifetime, quota_project_id=self._quota_project_id, universe_domain=self._universe_domain, ) @@ -579,6 +580,7 @@ def with_quota_project(self, quota_project_id): subject=self._subject, audience=self._audience, additional_claims=self._additional_claims, + token_lifetime=self._token_lifetime, quota_project_id=quota_project_id, universe_domain=self._universe_domain, ) @@ -857,6 +859,7 @@ def with_claims(self, issuer=None, subject=None, additional_claims=None): issuer=issuer if issuer is not None else self._issuer, subject=subject if subject is not None else self._subject, additional_claims=new_additional_claims, + token_lifetime=self._token_lifetime, max_cache_size=self._cache.maxsize, quota_project_id=self._quota_project_id, universe_domain=self._universe_domain, @@ -869,6 +872,7 @@ def with_quota_project(self, quota_project_id): issuer=self._issuer, subject=self._subject, additional_claims=self._additional_claims, + token_lifetime=self._token_lifetime, max_cache_size=self._cache.maxsize, quota_project_id=quota_project_id, universe_domain=self._universe_domain, diff --git a/packages/google-auth/tests/test_jwt.py b/packages/google-auth/tests/test_jwt.py index 811e7f61601f..9de7d08b1903 100644 --- a/packages/google-auth/tests/test_jwt.py +++ b/packages/google-auth/tests/test_jwt.py @@ -602,6 +602,17 @@ def test_with_claims(self): .universe_domain == FAKE_UNIVERSE_DOMAIN ) + custom_lifetime_creds = jwt.Credentials( + self.credentials.signer, + self.SERVICE_ACCOUNT_EMAIL, + self.SERVICE_ACCOUNT_EMAIL, + self.AUDIENCE, + token_lifetime=600, + ) + assert ( + custom_lifetime_creds.with_claims(audience=new_audience)._token_lifetime + == 600 + ) def test__make_jwt_without_audience(self): cred = jwt.Credentials.from_service_account_info( @@ -632,6 +643,17 @@ def test_with_quota_project(self): .universe_domain == FAKE_UNIVERSE_DOMAIN ) + custom_lifetime_creds = jwt.Credentials( + self.credentials.signer, + self.SERVICE_ACCOUNT_EMAIL, + self.SERVICE_ACCOUNT_EMAIL, + self.AUDIENCE, + token_lifetime=600, + ) + assert ( + custom_lifetime_creds.with_quota_project(quota_project_id)._token_lifetime + == 600 + ) def test_sign_bytes(self): to_sign = b"123" @@ -1190,6 +1212,18 @@ def test_with_claims(self): .universe_domain == FAKE_UNIVERSE_DOMAIN ) + custom_lifetime_creds = jwt.OnDemandCredentials( + self.credentials.signer, + self.SERVICE_ACCOUNT_EMAIL, + self.SERVICE_ACCOUNT_EMAIL, + token_lifetime=600, + ) + assert ( + custom_lifetime_creds.with_claims( + additional_claims=new_claims + )._token_lifetime + == 600 + ) def test_with_quota_project(self): quota_project_id = "project-foo" @@ -1206,6 +1240,16 @@ def test_with_quota_project(self): .universe_domain == FAKE_UNIVERSE_DOMAIN ) + custom_lifetime_creds = jwt.OnDemandCredentials( + self.credentials.signer, + self.SERVICE_ACCOUNT_EMAIL, + self.SERVICE_ACCOUNT_EMAIL, + token_lifetime=600, + ) + assert ( + custom_lifetime_creds.with_quota_project(quota_project_id)._token_lifetime + == 600 + ) def test_sign_bytes(self): to_sign = b"123" From 6983e0d029d261c7588b3c9243de077d68872f1b Mon Sep 17 00:00:00 2001 From: Negar Bayati Date: Sat, 21 Nov 2026 01:17:04 +0000 Subject: [PATCH 4/6] fix(auth): avoid default universe fallback in jwt with_universe_domain and document RAB scoping --- packages/google-auth/google/auth/jwt.py | 14 +++++++++++--- packages/google-auth/tests/test_jwt.py | 14 ++++++++++++++ 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/packages/google-auth/google/auth/jwt.py b/packages/google-auth/google/auth/jwt.py index bcf3c6e8a597..6b1e11595f73 100644 --- a/packages/google-auth/google/auth/jwt.py +++ b/packages/google-auth/google/auth/jwt.py @@ -525,6 +525,11 @@ def from_signing_credentials(cls, credentials, audience, **kwargs): ) jwt_creds = cls(credentials.signer, audience=audience, **kwargs) + # Regional Access Boundary (RAB) only applies to the default universe + # domain. Reuse the source credentials' cached RAB state only when the + # new credentials stay in the default universe; otherwise start with + # empty RAB state so a googleapis.com boundary is never sent to another + # universe. if ( isinstance( credentials, @@ -597,8 +602,10 @@ def with_universe_domain(self, universe_domain): additional_claims=self._additional_claims, token_lifetime=self._token_lifetime, quota_project_id=self._quota_project_id, - universe_domain=universe_domain, ) + cred._universe_domain = universe_domain + # RAB state is only valid for the default universe domain, so don't + # carry cached RAB data over when switching to another universe. if cred.universe_domain == google.auth.credentials.DEFAULT_UNIVERSE_DOMAIN: self._copy_regional_access_boundary_manager(cred) return cred @@ -880,7 +887,7 @@ def with_quota_project(self, quota_project_id): @_helpers.copy_docstring(google.auth.credentials.CredentialsWithUniverseDomain) def with_universe_domain(self, universe_domain): - return self.__class__( + cred = self.__class__( self._signer, issuer=self._issuer, subject=self._subject, @@ -888,8 +895,9 @@ def with_universe_domain(self, universe_domain): token_lifetime=self._token_lifetime, max_cache_size=self._cache.maxsize, quota_project_id=self._quota_project_id, - universe_domain=universe_domain, ) + cred._universe_domain = universe_domain + return cred @property def valid(self): diff --git a/packages/google-auth/tests/test_jwt.py b/packages/google-auth/tests/test_jwt.py index 9de7d08b1903..577517d1e3a2 100644 --- a/packages/google-auth/tests/test_jwt.py +++ b/packages/google-auth/tests/test_jwt.py @@ -851,6 +851,15 @@ def test_with_universe_domain(self, signer): == 600 ) + @pytest.mark.parametrize("empty_universe", [None, ""]) + def test_with_universe_domain_falsy(self, empty_universe): + self.credentials._rab_manager._data = mock.sentinel.rab_data + + cred = self.credentials.with_universe_domain(empty_universe) + assert cred.universe_domain == empty_universe + assert cred._rab_manager._data.encoded_locations is None + assert cred._rab_manager._data.expiry is None + def test_before_request_with_universe_domain_clears_cached_rab(self, monkeypatch): monkeypatch.setenv( environment_vars.GOOGLE_SDK_EXPERIMENTAL_PYTHON_REGIONAL_ACCESS_BOUNDARY_LOOKUP_ENABLED, @@ -1198,6 +1207,11 @@ def test_with_universe_domain(self, signer): == 600 ) + @pytest.mark.parametrize("empty_universe", [None, ""]) + def test_with_universe_domain_falsy(self, empty_universe): + cred = self.credentials.with_universe_domain(empty_universe) + assert cred.universe_domain == empty_universe + def test_with_claims(self): new_claims = {"meep": "moop"} new_credentials = self.credentials.with_claims(additional_claims=new_claims) From f4c06f9d70d01920f541d712eaab01d3cc367c79 Mon Sep 17 00:00:00 2001 From: Negar Bayati Date: Sat, 21 Nov 2026 01:24:36 +0000 Subject: [PATCH 5/6] test(auth): verify cloned fields and async RAB state in jwt universe_domain tests --- packages/google-auth/tests/test_jwt.py | 48 ++++++++++++------- .../google-auth/tests_async/test_jwt_async.py | 30 ++++++++++++ 2 files changed, 60 insertions(+), 18 deletions(-) diff --git a/packages/google-auth/tests/test_jwt.py b/packages/google-auth/tests/test_jwt.py index 577517d1e3a2..7480a49f7514 100644 --- a/packages/google-auth/tests/test_jwt.py +++ b/packages/google-auth/tests/test_jwt.py @@ -837,19 +837,24 @@ def test_with_universe_domain(self, signer): ) assert reset_default.universe_domain == auth_credentials.DEFAULT_UNIVERSE_DOMAIN - custom_lifetime_creds = jwt.Credentials( + custom_creds = jwt.Credentials( signer, self.SERVICE_ACCOUNT_EMAIL, - self.SERVICE_ACCOUNT_EMAIL, + self.SUBJECT, self.AUDIENCE, + additional_claims=self.ADDITIONAL_CLAIMS, token_lifetime=600, - ) - assert ( - custom_lifetime_creds.with_universe_domain( - FAKE_UNIVERSE_DOMAIN - )._token_lifetime - == 600 - ) + quota_project_id="project-foo", + ) + cloned = custom_creds.with_universe_domain(FAKE_UNIVERSE_DOMAIN) + assert cloned._signer == custom_creds._signer + assert cloned._issuer == custom_creds._issuer + assert cloned._subject == self.SUBJECT + assert cloned._audience == self.AUDIENCE + assert cloned._additional_claims == self.ADDITIONAL_CLAIMS + assert cloned._token_lifetime == 600 + assert cloned._quota_project_id == "project-foo" + assert cloned.universe_domain == FAKE_UNIVERSE_DOMAIN @pytest.mark.parametrize("empty_universe", [None, ""]) def test_with_universe_domain_falsy(self, empty_universe): @@ -1194,18 +1199,25 @@ def test_with_universe_domain(self, signer): ) assert reset_default.universe_domain == auth_credentials.DEFAULT_UNIVERSE_DOMAIN - custom_lifetime_creds = jwt.OnDemandCredentials( + custom_creds = jwt.OnDemandCredentials( signer, self.SERVICE_ACCOUNT_EMAIL, - self.SERVICE_ACCOUNT_EMAIL, + self.SUBJECT, + additional_claims=self.ADDITIONAL_CLAIMS, token_lifetime=600, - ) - assert ( - custom_lifetime_creds.with_universe_domain( - FAKE_UNIVERSE_DOMAIN - )._token_lifetime - == 600 - ) + max_cache_size=2, + quota_project_id="project-foo", + ) + cloned = custom_creds.with_universe_domain(FAKE_UNIVERSE_DOMAIN) + assert cloned._signer == custom_creds._signer + assert cloned._issuer == custom_creds._issuer + assert cloned._subject == self.SUBJECT + assert cloned._additional_claims == self.ADDITIONAL_CLAIMS + assert cloned._token_lifetime == 600 + assert cloned._cache.maxsize == 2 + assert cloned._cache is not custom_creds._cache + assert cloned._quota_project_id == "project-foo" + assert cloned.universe_domain == FAKE_UNIVERSE_DOMAIN @pytest.mark.parametrize("empty_universe", [None, ""]) def test_with_universe_domain_falsy(self, empty_universe): diff --git a/packages/google-auth/tests_async/test_jwt_async.py b/packages/google-auth/tests_async/test_jwt_async.py index 5b2784069bd8..287d688c9443 100644 --- a/packages/google-auth/tests_async/test_jwt_async.py +++ b/packages/google-auth/tests_async/test_jwt_async.py @@ -159,7 +159,37 @@ def test_universe_domain(self): assert isinstance(from_signing, jwt_async.Credentials) assert from_signing.universe_domain == test_jwt.FAKE_UNIVERSE_DOMAIN + gdu_sa_creds = service_account.Credentials.from_service_account_info( + test_jwt.SERVICE_ACCOUNT_INFO + ) + gdu_sa_creds._rab_manager._data = mock.sentinel.rab_data + from_gdu_signing = jwt_async.Credentials.from_signing_credentials( + gdu_sa_creds, audience=self.AUDIENCE + ) + assert isinstance(from_gdu_signing, jwt_async.Credentials) + assert ( + from_gdu_signing.universe_domain == auth_credentials.DEFAULT_UNIVERSE_DOMAIN + ) + assert from_gdu_signing._rab_manager._data == mock.sentinel.rab_data + assert from_gdu_signing._rab_manager is not gdu_sa_creds._rab_manager + assert isinstance( + from_gdu_signing._rab_manager.refresh_manager, + _regional_access_boundary_utils._AsyncRegionalAccessBoundaryRefreshManager, + ) + self.credentials._rab_manager._data = mock.sentinel.rab_data + gdu_copy = self.credentials.with_universe_domain( + auth_credentials.DEFAULT_UNIVERSE_DOMAIN + ) + assert isinstance(gdu_copy, jwt_async.Credentials) + assert gdu_copy.universe_domain == auth_credentials.DEFAULT_UNIVERSE_DOMAIN + assert gdu_copy._rab_manager._data == mock.sentinel.rab_data + assert gdu_copy._rab_manager is not self.credentials._rab_manager + assert isinstance( + gdu_copy._rab_manager.refresh_manager, + _regional_access_boundary_utils._AsyncRegionalAccessBoundaryRefreshManager, + ) + non_default = self.credentials.with_universe_domain( test_jwt.FAKE_UNIVERSE_DOMAIN ) From fef3fc61ba772e908c0c1a5e62f2659e17e0b4fe Mon Sep 17 00:00:00 2001 From: Negar Bayati Date: Sat, 21 Nov 2026 02:53:33 +0000 Subject: [PATCH 6/6] fix(auth): raise on empty universe domain in jwt with_universe_domain --- packages/google-auth/google/auth/jwt.py | 20 ++++++++++++++++---- packages/google-auth/tests/test_jwt.py | 20 ++++++++------------ 2 files changed, 24 insertions(+), 16 deletions(-) diff --git a/packages/google-auth/google/auth/jwt.py b/packages/google-auth/google/auth/jwt.py index 6b1e11595f73..827d893bd14f 100644 --- a/packages/google-auth/google/auth/jwt.py +++ b/packages/google-auth/google/auth/jwt.py @@ -75,6 +75,17 @@ _ALGORITHM_TO_VERIFIER_CLASS["ES384"] = es.EsVerifier # type: ignore +def _validate_universe_domain(universe_domain): + """Raises if the universe domain passed to ``with_universe_domain`` is empty. + + Raises: + google.auth.exceptions.InvalidValue: If the universe domain is None, + empty, or whitespace-only. + """ + if not universe_domain or not universe_domain.strip(): + raise exceptions.InvalidValue("Universe domain cannot be empty.") + + def encode(signer, payload, header=None, key_id=None): """Make a signed JWT. @@ -594,6 +605,7 @@ def with_quota_project(self, quota_project_id): @_helpers.copy_docstring(google.auth.credentials.CredentialsWithUniverseDomain) def with_universe_domain(self, universe_domain): + _validate_universe_domain(universe_domain) cred = self.__class__( self._signer, issuer=self._issuer, @@ -602,8 +614,8 @@ def with_universe_domain(self, universe_domain): additional_claims=self._additional_claims, token_lifetime=self._token_lifetime, quota_project_id=self._quota_project_id, + universe_domain=universe_domain, ) - cred._universe_domain = universe_domain # RAB state is only valid for the default universe domain, so don't # carry cached RAB data over when switching to another universe. if cred.universe_domain == google.auth.credentials.DEFAULT_UNIVERSE_DOMAIN: @@ -887,7 +899,8 @@ def with_quota_project(self, quota_project_id): @_helpers.copy_docstring(google.auth.credentials.CredentialsWithUniverseDomain) def with_universe_domain(self, universe_domain): - cred = self.__class__( + _validate_universe_domain(universe_domain) + return self.__class__( self._signer, issuer=self._issuer, subject=self._subject, @@ -895,9 +908,8 @@ def with_universe_domain(self, universe_domain): token_lifetime=self._token_lifetime, max_cache_size=self._cache.maxsize, quota_project_id=self._quota_project_id, + universe_domain=universe_domain, ) - cred._universe_domain = universe_domain - return cred @property def valid(self): diff --git a/packages/google-auth/tests/test_jwt.py b/packages/google-auth/tests/test_jwt.py index 7480a49f7514..7347dab47818 100644 --- a/packages/google-auth/tests/test_jwt.py +++ b/packages/google-auth/tests/test_jwt.py @@ -856,14 +856,10 @@ def test_with_universe_domain(self, signer): assert cloned._quota_project_id == "project-foo" assert cloned.universe_domain == FAKE_UNIVERSE_DOMAIN - @pytest.mark.parametrize("empty_universe", [None, ""]) - def test_with_universe_domain_falsy(self, empty_universe): - self.credentials._rab_manager._data = mock.sentinel.rab_data - - cred = self.credentials.with_universe_domain(empty_universe) - assert cred.universe_domain == empty_universe - assert cred._rab_manager._data.encoded_locations is None - assert cred._rab_manager._data.expiry is None + @pytest.mark.parametrize("empty_universe", [None, "", " "]) + def test_with_universe_domain_empty_raises(self, empty_universe): + with pytest.raises(exceptions.InvalidValue): + self.credentials.with_universe_domain(empty_universe) def test_before_request_with_universe_domain_clears_cached_rab(self, monkeypatch): monkeypatch.setenv( @@ -1219,10 +1215,10 @@ def test_with_universe_domain(self, signer): assert cloned._quota_project_id == "project-foo" assert cloned.universe_domain == FAKE_UNIVERSE_DOMAIN - @pytest.mark.parametrize("empty_universe", [None, ""]) - def test_with_universe_domain_falsy(self, empty_universe): - cred = self.credentials.with_universe_domain(empty_universe) - assert cred.universe_domain == empty_universe + @pytest.mark.parametrize("empty_universe", [None, "", " "]) + def test_with_universe_domain_empty_raises(self, empty_universe): + with pytest.raises(exceptions.InvalidValue): + self.credentials.with_universe_domain(empty_universe) def test_with_claims(self): new_claims = {"meep": "moop"}