From bad53cad2261ad6aca161371ff36b54dd868936d Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Tue, 24 Nov 2026 15:50:24 +0000 Subject: [PATCH 01/17] fix(auth): preserve universe_domain and JWT state in service_account credentials --- .../google/oauth2/service_account.py | 51 ++++- .../tests/oauth2/test_service_account.py | 199 +++++++++++++++++- 2 files changed, 241 insertions(+), 9 deletions(-) diff --git a/packages/google-auth/google/oauth2/service_account.py b/packages/google-auth/google/oauth2/service_account.py index 6744e6f14d9b..97267dc59b56 100644 --- a/packages/google-auth/google/oauth2/service_account.py +++ b/packages/google-auth/google/oauth2/service_account.py @@ -101,6 +101,7 @@ class Credentials( credentials.Scoped, credentials.CredentialsWithQuotaProject, credentials.CredentialsWithTokenUri, + credentials.CredentialsWithUniverseDomain, credentials.CredentialsWithRegionalAccessBoundary, ): """Service account credentials @@ -196,7 +197,9 @@ def __init__( self._always_use_jwt_access = always_use_jwt_access self._universe_domain = universe_domain or credentials.DEFAULT_UNIVERSE_DOMAIN - if universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN: + # Check the normalized universe domain so None or "" falls back to the + # default universe domain without forcing self-signed JWT access. + if self._universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN: self._always_use_jwt_access = True self._jwt_credentials = None @@ -224,14 +227,17 @@ def _from_signer_and_info(cls, signer, info, **kwargs): Raises: ValueError: If the info is not in the expected format. """ + # Respect an explicit universe_domain kwarg from the caller instead of + # letting a missing, null, or empty JSON value overwrite it. + if "universe_domain" not in kwargs: + kwargs["universe_domain"] = ( + info.get("universe_domain") or credentials.DEFAULT_UNIVERSE_DOMAIN + ) return cls( signer, service_account_email=info["client_email"], token_uri=info["token_uri"], project_id=info.get("project_id"), - universe_domain=info.get( - "universe_domain", credentials.DEFAULT_UNIVERSE_DOMAIN - ), trust_boundary=info.get("trust_boundary"), **kwargs, ) @@ -309,6 +315,10 @@ def _make_copy(self): trust_boundary=self._trust_boundary, ) cred._cred_file_path = self._cred_file_path + # Clone cached self-signed JWT credentials so audience-bound copies keep + # their audience without sharing mutable token state with the original. + if self._jwt_credentials is not None: + cred._jwt_credentials = self._jwt_credentials.with_claims() self._copy_regional_access_boundary_manager(cred) return cred @@ -317,6 +327,8 @@ def with_scopes(self, scopes, default_scopes=None): cred = self._make_copy() cred._scopes = scopes cred._default_scopes = default_scopes + # Clear cached JWT credentials so subsequent refreshes reflect the new scopes. + cred._jwt_credentials = None return cred def with_always_use_jwt_access(self, always_use_jwt_access): @@ -341,14 +353,19 @@ def with_always_use_jwt_access(self, always_use_jwt_access): "always_use_jwt_access should be True for non-default universe domain" ) cred._always_use_jwt_access = always_use_jwt_access + if not always_use_jwt_access: + # Drop cached self-signed JWT credentials when opting out of JWT access. + cred._jwt_credentials = None return cred @_helpers.copy_docstring(credentials.CredentialsWithUniverseDomain) def with_universe_domain(self, universe_domain): cred = self._make_copy() - cred._universe_domain = universe_domain - if universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN: + cred._universe_domain = universe_domain or credentials.DEFAULT_UNIVERSE_DOMAIN + if cred._universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN: cred._always_use_jwt_access = True + # Clear cached JWT credentials since audience/universe metadata may change. + cred._jwt_credentials = None return cred def with_subject(self, subject): @@ -560,6 +577,7 @@ class IDTokenCredentials( credentials.Signing, credentials.CredentialsWithQuotaProject, credentials.CredentialsWithTokenUri, + credentials.CredentialsWithUniverseDomain, ): """Open ID Connect ID Token-based service account credentials. @@ -679,8 +697,12 @@ def _from_signer_and_info(cls, signer, info, **kwargs): """ kwargs.setdefault("service_account_email", info["client_email"]) kwargs.setdefault("token_uri", info["token_uri"]) - if "universe_domain" in info: - kwargs["universe_domain"] = info["universe_domain"] + # Respect an explicit universe_domain kwarg from the caller instead of + # letting a missing, null, or empty JSON value overwrite it. + if "universe_domain" not in kwargs: + kwargs["universe_domain"] = ( + info.get("universe_domain") or credentials.DEFAULT_UNIVERSE_DOMAIN + ) return cls(signer, **kwargs) @classmethod @@ -791,6 +813,19 @@ def with_token_uri(self, token_uri): cred._token_uri = token_uri return cred + @_helpers.copy_docstring(credentials.CredentialsWithUniverseDomain) + def with_universe_domain(self, universe_domain): + cred = self._make_copy() + cred._universe_domain = universe_domain or credentials.DEFAULT_UNIVERSE_DOMAIN + # Rebuild the IAM generateIdToken URL for the updated universe domain. + cred._iam_id_token_endpoint = iam._IAM_IDTOKEN_ENDPOINT.replace( + "googleapis.com", cred._universe_domain + ) + # Non-default universe domains require the IAM generateIdToken endpoint. + if cred._universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN: + cred._use_iam_endpoint = True + return cred + def _make_authorization_grant_assertion(self): """Create the OAuth 2.0 assertion. diff --git a/packages/google-auth/tests/oauth2/test_service_account.py b/packages/google-auth/tests/oauth2/test_service_account.py index 84074ec37b9a..958496f66e44 100644 --- a/packages/google-auth/tests/oauth2/test_service_account.py +++ b/packages/google-auth/tests/oauth2/test_service_account.py @@ -20,7 +20,10 @@ import pytest # type: ignore from google.auth import _helpers, crypt, exceptions, iam, jwt, transport -from google.auth.credentials import DEFAULT_UNIVERSE_DOMAIN +from google.auth.credentials import ( + DEFAULT_UNIVERSE_DOMAIN, + CredentialsWithUniverseDomain, +) from google.oauth2 import service_account DATA_DIR = os.path.join(os.path.dirname(__file__), "..", "data") @@ -90,12 +93,100 @@ def test__make_copy_get_cred_info(self): cred_copy = credentials._make_copy() assert cred_copy._cred_file_path == "/path/to/file" + def test__make_copy_preserves_jwt_credentials(self): + """Copying audience-bound credentials preserves self-signed JWT state.""" + credentials = self.make_credentials(universe_domain=FAKE_UNIVERSE_DOMAIN) + audience = f"https://compute.{FAKE_UNIVERSE_DOMAIN}/" + credentials._create_self_signed_jwt(audience) + + assert credentials._jwt_credentials is not None + assert credentials._jwt_credentials._audience == audience + + copied = credentials.with_quota_project("quota-project-123") + + assert copied._jwt_credentials is not None + assert copied._jwt_credentials is not credentials._jwt_credentials + assert copied._jwt_credentials._audience == audience + + request = mock.create_autospec(transport.Request, instance=True) + copied.refresh(request) + + request.assert_not_called() + payload = jwt.decode(copied.token, PUBLIC_CERT_BYTES) + assert payload["aud"] == audience + + def test_with_scopes_clears_jwt_credentials(self): + """with_scopes clears cached self-signed JWT credentials so new scopes apply.""" + credentials = self.make_credentials(universe_domain=FAKE_UNIVERSE_DOMAIN) + credentials._create_self_signed_jwt(f"https://compute.{FAKE_UNIVERSE_DOMAIN}/") + assert credentials._jwt_credentials is not None + + scoped = credentials.with_scopes( + ["https://www.googleapis.com/auth/cloud-platform"] + ) + assert scoped._jwt_credentials is None + + request = mock.create_autospec(transport.Request, instance=True) + scoped.refresh(request) + + request.assert_not_called() + payload = jwt.decode(scoped.token, PUBLIC_CERT_BYTES) + assert payload["scope"] == "https://www.googleapis.com/auth/cloud-platform" + assert "aud" not in payload + + def test_with_always_use_jwt_access_false_clears_jwt_credentials(self): + """Disabling always_use_jwt_access clears cached self-signed JWT credentials.""" + credentials = self.make_credentials().with_always_use_jwt_access(True) + credentials._create_self_signed_jwt("https://compute.googleapis.com/") + assert credentials._jwt_credentials is not None + + updated = credentials.with_always_use_jwt_access(False) + assert not updated._always_use_jwt_access + assert updated._jwt_credentials is None + + def test_with_universe_domain_clears_jwt_credentials(self): + """with_universe_domain clears cached self-signed JWT credentials.""" + credentials = self.make_credentials(universe_domain=FAKE_UNIVERSE_DOMAIN) + credentials._create_self_signed_jwt(f"https://compute.{FAKE_UNIVERSE_DOMAIN}/") + assert credentials._jwt_credentials is not None + + updated = credentials.with_universe_domain("other.universe.foo") + assert updated.universe_domain == "other.universe.foo" + assert updated._jwt_credentials is None + + @pytest.mark.parametrize("universe_domain", [None, ""]) + def test_with_universe_domain_empty_or_none_defaults(self, universe_domain): + """with_universe_domain normalizes None or empty string to the default domain.""" + credentials = self.make_credentials() + updated = credentials.with_universe_domain(universe_domain) + assert updated.universe_domain == DEFAULT_UNIVERSE_DOMAIN + assert not updated._always_use_jwt_access + + def test_inherits_credentials_with_universe_domain(self): + """Credentials implements the CredentialsWithUniverseDomain interface.""" + credentials = self.make_credentials() + assert isinstance(credentials, CredentialsWithUniverseDomain) + def test_constructor_no_universe_domain(self): credentials = service_account.Credentials( SIGNER, self.SERVICE_ACCOUNT_EMAIL, self.TOKEN_URI, universe_domain=None ) assert credentials.universe_domain == DEFAULT_UNIVERSE_DOMAIN + @pytest.mark.parametrize("universe_domain", [None, ""]) + def test_constructor_empty_or_none_universe_domain_jwt_access( + self, universe_domain + ): + """None or empty universe_domain defaults without forcing JWT access.""" + credentials = service_account.Credentials( + SIGNER, + self.SERVICE_ACCOUNT_EMAIL, + self.TOKEN_URI, + universe_domain=universe_domain, + ) + assert credentials.universe_domain == DEFAULT_UNIVERSE_DOMAIN + assert not credentials._always_use_jwt_access + def test_from_service_account_info(self): credentials = service_account.Credentials.from_service_account_info( SERVICE_ACCOUNT_INFO @@ -115,6 +206,36 @@ def test_from_service_account_info_non_gdu(self): assert credentials.universe_domain == FAKE_UNIVERSE_DOMAIN assert credentials._always_use_jwt_access + @pytest.mark.parametrize("info_universe_domain", [None, ""]) + def test_from_service_account_info_explicit_universe_domain_preserved( + self, info_universe_domain + ): + """Explicit universe_domain kwarg is not overridden by empty JSON values.""" + info = SERVICE_ACCOUNT_INFO.copy() + info["universe_domain"] = info_universe_domain + + credentials = service_account.Credentials.from_service_account_info( + info, universe_domain=FAKE_UNIVERSE_DOMAIN + ) + + assert credentials.universe_domain == FAKE_UNIVERSE_DOMAIN + assert credentials._always_use_jwt_access + + @pytest.mark.parametrize("explicit_universe_domain", [None, ""]) + def test_from_service_account_info_explicit_empty_universe_domain_overrides_info( + self, explicit_universe_domain + ): + """Explicit None or empty universe_domain kwarg overrides the JSON value.""" + info = SERVICE_ACCOUNT_INFO.copy() + info["universe_domain"] = FAKE_UNIVERSE_DOMAIN + + credentials = service_account.Credentials.from_service_account_info( + info, universe_domain=explicit_universe_domain + ) + + assert credentials.universe_domain == DEFAULT_UNIVERSE_DOMAIN + assert not credentials._always_use_jwt_access + def test_from_service_account_info_args(self): info = SERVICE_ACCOUNT_INFO.copy() scopes = ["email", "profile"] @@ -703,6 +824,11 @@ def test_constructor_no_universe_domain(self): ) assert credentials._universe_domain == DEFAULT_UNIVERSE_DOMAIN + def test_inherits_credentials_with_universe_domain(self): + """IDTokenCredentials implements the CredentialsWithUniverseDomain interface.""" + credentials = self.make_credentials() + assert isinstance(credentials, CredentialsWithUniverseDomain) + def test_from_service_account_info(self): credentials = service_account.IDTokenCredentials.from_service_account_info( SERVICE_ACCOUNT_INFO, target_audience=self.TARGET_AUDIENCE @@ -730,6 +856,56 @@ def test_from_service_account_info_non_gdu(self): assert credentials._target_audience == self.TARGET_AUDIENCE assert credentials._use_iam_endpoint + @pytest.mark.parametrize("info_universe_domain", [None, ""]) + @mock.patch( + "google.oauth2._client.call_iam_generate_id_token_endpoint", autospec=True + ) + @mock.patch("google.oauth2._client.id_token_jwt_grant", autospec=True) + def test_from_service_account_info_explicit_universe_domain_preserved( + self, + id_token_jwt_grant, + call_iam_generate_id_token_endpoint, + info_universe_domain, + ): + """Explicit universe_domain kwarg wins over null or empty JSON values.""" + info = SERVICE_ACCOUNT_INFO.copy() + info["universe_domain"] = info_universe_domain + expiry = _helpers.utcnow() + datetime.timedelta(seconds=500) + call_iam_generate_id_token_endpoint.return_value = ("id_token", expiry) + id_token_jwt_grant.return_value = ("id_token", expiry, {}) + + credentials = service_account.IDTokenCredentials.from_service_account_info( + info, + target_audience=self.TARGET_AUDIENCE, + universe_domain=FAKE_UNIVERSE_DOMAIN, + ) + + assert credentials.universe_domain == FAKE_UNIVERSE_DOMAIN + assert credentials._use_iam_endpoint is True + + request = mock.create_autospec(transport.Request, instance=True) + credentials.refresh(request) + + call_iam_generate_id_token_endpoint.assert_called_once() + id_token_jwt_grant.assert_not_called() + + @pytest.mark.parametrize("explicit_universe_domain", [None, ""]) + def test_from_service_account_info_explicit_empty_universe_domain_overrides_info( + self, explicit_universe_domain + ): + """Explicit None or empty universe_domain kwarg overrides the JSON value.""" + info = SERVICE_ACCOUNT_INFO.copy() + info["universe_domain"] = FAKE_UNIVERSE_DOMAIN + + credentials = service_account.IDTokenCredentials.from_service_account_info( + info, + target_audience=self.TARGET_AUDIENCE, + universe_domain=explicit_universe_domain, + ) + + assert credentials.universe_domain == DEFAULT_UNIVERSE_DOMAIN + assert not credentials._use_iam_endpoint + def test_from_service_account_file(self): info = SERVICE_ACCOUNT_INFO.copy() @@ -807,6 +983,27 @@ def test_with_token_uri(self): creds_with_new_token_uri = credentials.with_token_uri(new_token_uri) assert creds_with_new_token_uri._token_uri == new_token_uri + def test_with_universe_domain(self): + """with_universe_domain updates domain, IAM endpoint, and IAM flow flag.""" + credentials = self.make_credentials() + + non_default = credentials.with_universe_domain(FAKE_UNIVERSE_DOMAIN) + assert non_default.universe_domain == FAKE_UNIVERSE_DOMAIN + assert non_default._use_iam_endpoint is True + assert non_default._iam_id_token_endpoint == iam._IAM_IDTOKEN_ENDPOINT.replace( + "googleapis.com", FAKE_UNIVERSE_DOMAIN + ) + + default = credentials.with_universe_domain(DEFAULT_UNIVERSE_DOMAIN) + assert default.universe_domain == DEFAULT_UNIVERSE_DOMAIN + assert default._use_iam_endpoint is False + assert default._iam_id_token_endpoint == iam._IAM_IDTOKEN_ENDPOINT + + normalized = credentials.with_universe_domain(None) + assert normalized.universe_domain == DEFAULT_UNIVERSE_DOMAIN + assert normalized._use_iam_endpoint is False + assert normalized._iam_id_token_endpoint == iam._IAM_IDTOKEN_ENDPOINT + def test__make_authorization_grant_assertion(self): credentials = self.make_credentials() token = credentials._make_authorization_grant_assertion() From 6da80c88b4c4b325f7ff5e29ee4a94f00f88a675 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Tue, 24 Nov 2026 16:04:42 +0000 Subject: [PATCH 02/17] fix(auth): clear cached JWT credentials in Credentials.with_subject --- packages/google-auth/google/oauth2/service_account.py | 3 +++ .../google-auth/tests/oauth2/test_service_account.py | 10 ++++++++++ 2 files changed, 13 insertions(+) diff --git a/packages/google-auth/google/oauth2/service_account.py b/packages/google-auth/google/oauth2/service_account.py index 97267dc59b56..102f370eb544 100644 --- a/packages/google-auth/google/oauth2/service_account.py +++ b/packages/google-auth/google/oauth2/service_account.py @@ -380,6 +380,9 @@ def with_subject(self, subject): """ cred = self._make_copy() cred._subject = subject + # Clear cached JWT credentials since subject delegation does not use + # self-signed JWTs. + cred._jwt_credentials = None return cred def with_claims(self, additional_claims): diff --git a/packages/google-auth/tests/oauth2/test_service_account.py b/packages/google-auth/tests/oauth2/test_service_account.py index 958496f66e44..a6f0245a9ec6 100644 --- a/packages/google-auth/tests/oauth2/test_service_account.py +++ b/packages/google-auth/tests/oauth2/test_service_account.py @@ -154,6 +154,16 @@ def test_with_universe_domain_clears_jwt_credentials(self): assert updated.universe_domain == "other.universe.foo" assert updated._jwt_credentials is None + def test_with_subject_clears_jwt_credentials(self): + """with_subject clears cached self-signed JWT credentials.""" + credentials = self.make_credentials() + credentials._create_self_signed_jwt("https://compute.googleapis.com/") + assert credentials._jwt_credentials is not None + + delegated = credentials.with_subject("user@example.com") + assert delegated._subject == "user@example.com" + assert delegated._jwt_credentials is None + @pytest.mark.parametrize("universe_domain", [None, ""]) def test_with_universe_domain_empty_or_none_defaults(self, universe_domain): """with_universe_domain normalizes None or empty string to the default domain.""" From d2b6e6322cfd2df320f588aa317aa9da2348bc6b Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Tue, 24 Nov 2026 16:05:43 +0000 Subject: [PATCH 03/17] fix(auth): reset _use_iam_endpoint in IDTokenCredentials.with_universe_domain --- packages/google-auth/google/oauth2/service_account.py | 5 +++-- packages/google-auth/tests/oauth2/test_service_account.py | 4 ++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/packages/google-auth/google/oauth2/service_account.py b/packages/google-auth/google/oauth2/service_account.py index 102f370eb544..5947aea4e7c1 100644 --- a/packages/google-auth/google/oauth2/service_account.py +++ b/packages/google-auth/google/oauth2/service_account.py @@ -825,8 +825,9 @@ def with_universe_domain(self, universe_domain): "googleapis.com", cred._universe_domain ) # Non-default universe domains require the IAM generateIdToken endpoint. - if cred._universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN: - cred._use_iam_endpoint = True + cred._use_iam_endpoint = ( + cred._universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN + ) return cred def _make_authorization_grant_assertion(self): diff --git a/packages/google-auth/tests/oauth2/test_service_account.py b/packages/google-auth/tests/oauth2/test_service_account.py index a6f0245a9ec6..066e6850448b 100644 --- a/packages/google-auth/tests/oauth2/test_service_account.py +++ b/packages/google-auth/tests/oauth2/test_service_account.py @@ -1004,12 +1004,12 @@ def test_with_universe_domain(self): "googleapis.com", FAKE_UNIVERSE_DOMAIN ) - default = credentials.with_universe_domain(DEFAULT_UNIVERSE_DOMAIN) + default = non_default.with_universe_domain(DEFAULT_UNIVERSE_DOMAIN) assert default.universe_domain == DEFAULT_UNIVERSE_DOMAIN assert default._use_iam_endpoint is False assert default._iam_id_token_endpoint == iam._IAM_IDTOKEN_ENDPOINT - normalized = credentials.with_universe_domain(None) + normalized = non_default.with_universe_domain(None) assert normalized.universe_domain == DEFAULT_UNIVERSE_DOMAIN assert normalized._use_iam_endpoint is False assert normalized._iam_id_token_endpoint == iam._IAM_IDTOKEN_ENDPOINT From ecc966bd4ea80fd31fcbaf77f43f6dc65d08378b Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Wed, 25 Nov 2026 16:54:47 +0000 Subject: [PATCH 04/17] address review feedback --- .../google/oauth2/service_account.py | 17 +++- .../tests/oauth2/test_service_account.py | 97 +++++++++++++++---- 2 files changed, 93 insertions(+), 21 deletions(-) diff --git a/packages/google-auth/google/oauth2/service_account.py b/packages/google-auth/google/oauth2/service_account.py index 5947aea4e7c1..5c8f3f7f44f4 100644 --- a/packages/google-auth/google/oauth2/service_account.py +++ b/packages/google-auth/google/oauth2/service_account.py @@ -96,6 +96,17 @@ _GOOGLE_OAUTH2_TOKEN_ENDPOINT = "https://oauth2.googleapis.com/token" +def _validate_universe_domain(universe_domain): + """Validates that the universe domain is non-empty. + + Raises: + ValueError: If the universe domain is an empty string + or contains only blank spaces. + """ + if universe_domain is not None and not str(universe_domain).strip(): + raise ValueError("Universe Domain cannot be an empty string.") + + class Credentials( credentials.Signing, credentials.Scoped, @@ -195,9 +206,10 @@ def __init__( self._quota_project_id = quota_project_id self._token_uri = token_uri self._always_use_jwt_access = always_use_jwt_access + _validate_universe_domain(universe_domain) self._universe_domain = universe_domain or credentials.DEFAULT_UNIVERSE_DOMAIN - # Check the normalized universe domain so None or "" falls back to the + # Check the normalized universe domain so None falls back to the # default universe domain without forcing self-signed JWT access. if self._universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN: self._always_use_jwt_access = True @@ -360,6 +372,7 @@ def with_always_use_jwt_access(self, always_use_jwt_access): @_helpers.copy_docstring(credentials.CredentialsWithUniverseDomain) def with_universe_domain(self, universe_domain): + _validate_universe_domain(universe_domain) cred = self._make_copy() cred._universe_domain = universe_domain or credentials.DEFAULT_UNIVERSE_DOMAIN if cred._universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN: @@ -666,6 +679,7 @@ def __init__( self._quota_project_id = quota_project_id self._use_iam_endpoint = False + _validate_universe_domain(universe_domain) if not universe_domain: self._universe_domain = credentials.DEFAULT_UNIVERSE_DOMAIN else: @@ -818,6 +832,7 @@ def with_token_uri(self, token_uri): @_helpers.copy_docstring(credentials.CredentialsWithUniverseDomain) def with_universe_domain(self, universe_domain): + _validate_universe_domain(universe_domain) cred = self._make_copy() cred._universe_domain = universe_domain or credentials.DEFAULT_UNIVERSE_DOMAIN # Rebuild the IAM generateIdToken URL for the updated universe domain. diff --git a/packages/google-auth/tests/oauth2/test_service_account.py b/packages/google-auth/tests/oauth2/test_service_account.py index 066e6850448b..302b7290cad2 100644 --- a/packages/google-auth/tests/oauth2/test_service_account.py +++ b/packages/google-auth/tests/oauth2/test_service_account.py @@ -164,14 +164,22 @@ def test_with_subject_clears_jwt_credentials(self): assert delegated._subject == "user@example.com" assert delegated._jwt_credentials is None - @pytest.mark.parametrize("universe_domain", [None, ""]) - def test_with_universe_domain_empty_or_none_defaults(self, universe_domain): - """with_universe_domain normalizes None or empty string to the default domain.""" + def test_with_universe_domain_none_defaults(self): + """with_universe_domain normalizes None to the default domain.""" credentials = self.make_credentials() - updated = credentials.with_universe_domain(universe_domain) + updated = credentials.with_universe_domain(None) assert updated.universe_domain == DEFAULT_UNIVERSE_DOMAIN assert not updated._always_use_jwt_access + @pytest.mark.parametrize("empty_ud", ["", " "]) + def test_with_universe_domain_empty_string_raises(self, empty_ud): + """Explicitly passing an empty or whitespace universe domain raises ValueError.""" + credentials = self.make_credentials() + with pytest.raises( + ValueError, match="Universe Domain cannot be an empty string" + ): + credentials.with_universe_domain(empty_ud) + def test_inherits_credentials_with_universe_domain(self): """Credentials implements the CredentialsWithUniverseDomain interface.""" credentials = self.make_credentials() @@ -183,20 +191,30 @@ def test_constructor_no_universe_domain(self): ) assert credentials.universe_domain == DEFAULT_UNIVERSE_DOMAIN - @pytest.mark.parametrize("universe_domain", [None, ""]) - def test_constructor_empty_or_none_universe_domain_jwt_access( - self, universe_domain - ): - """None or empty universe_domain defaults without forcing JWT access.""" + def test_constructor_none_universe_domain_jwt_access(self): + """None universe_domain defaults without forcing JWT access.""" credentials = service_account.Credentials( SIGNER, self.SERVICE_ACCOUNT_EMAIL, self.TOKEN_URI, - universe_domain=universe_domain, + universe_domain=None, ) assert credentials.universe_domain == DEFAULT_UNIVERSE_DOMAIN assert not credentials._always_use_jwt_access + @pytest.mark.parametrize("empty_ud", ["", " "]) + def test_constructor_empty_universe_domain_raises(self, empty_ud): + """Empty or whitespace universe_domain in constructor raises ValueError.""" + with pytest.raises( + ValueError, match="Universe Domain cannot be an empty string" + ): + service_account.Credentials( + SIGNER, + self.SERVICE_ACCOUNT_EMAIL, + self.TOKEN_URI, + universe_domain=empty_ud, + ) + def test_from_service_account_info(self): credentials = service_account.Credentials.from_service_account_info( SERVICE_ACCOUNT_INFO @@ -231,21 +249,35 @@ def test_from_service_account_info_explicit_universe_domain_preserved( assert credentials.universe_domain == FAKE_UNIVERSE_DOMAIN assert credentials._always_use_jwt_access - @pytest.mark.parametrize("explicit_universe_domain", [None, ""]) - def test_from_service_account_info_explicit_empty_universe_domain_overrides_info( - self, explicit_universe_domain + def test_from_service_account_info_explicit_none_universe_domain_overrides_info( + self, ): - """Explicit None or empty universe_domain kwarg overrides the JSON value.""" + """Explicit None universe_domain kwarg overrides the JSON value and defaults.""" info = SERVICE_ACCOUNT_INFO.copy() info["universe_domain"] = FAKE_UNIVERSE_DOMAIN credentials = service_account.Credentials.from_service_account_info( - info, universe_domain=explicit_universe_domain + info, universe_domain=None ) assert credentials.universe_domain == DEFAULT_UNIVERSE_DOMAIN assert not credentials._always_use_jwt_access + @pytest.mark.parametrize("empty_ud", ["", " "]) + def test_from_service_account_info_explicit_empty_universe_domain_raises( + self, empty_ud + ): + """Explicit empty or whitespace universe_domain kwarg raises ValueError.""" + info = SERVICE_ACCOUNT_INFO.copy() + info["universe_domain"] = FAKE_UNIVERSE_DOMAIN + + with pytest.raises( + ValueError, match="Universe Domain cannot be an empty string" + ): + service_account.Credentials.from_service_account_info( + info, universe_domain=empty_ud + ) + def test_from_service_account_info_args(self): info = SERVICE_ACCOUNT_INFO.copy() scopes = ["email", "profile"] @@ -899,23 +931,39 @@ def test_from_service_account_info_explicit_universe_domain_preserved( call_iam_generate_id_token_endpoint.assert_called_once() id_token_jwt_grant.assert_not_called() - @pytest.mark.parametrize("explicit_universe_domain", [None, ""]) - def test_from_service_account_info_explicit_empty_universe_domain_overrides_info( - self, explicit_universe_domain + def test_from_service_account_info_explicit_none_universe_domain_overrides_info( + self, ): - """Explicit None or empty universe_domain kwarg overrides the JSON value.""" + """Explicit None universe_domain kwarg overrides the JSON value and defaults.""" info = SERVICE_ACCOUNT_INFO.copy() info["universe_domain"] = FAKE_UNIVERSE_DOMAIN credentials = service_account.IDTokenCredentials.from_service_account_info( info, target_audience=self.TARGET_AUDIENCE, - universe_domain=explicit_universe_domain, + universe_domain=None, ) assert credentials.universe_domain == DEFAULT_UNIVERSE_DOMAIN assert not credentials._use_iam_endpoint + @pytest.mark.parametrize("empty_ud", ["", " "]) + def test_id_token_from_service_account_info_explicit_empty_universe_domain_raises( + self, empty_ud + ): + """Explicit empty or whitespace universe_domain kwarg raises ValueError.""" + info = SERVICE_ACCOUNT_INFO.copy() + info["universe_domain"] = FAKE_UNIVERSE_DOMAIN + + with pytest.raises( + ValueError, match="Universe Domain cannot be an empty string" + ): + service_account.IDTokenCredentials.from_service_account_info( + info, + target_audience=self.TARGET_AUDIENCE, + universe_domain=empty_ud, + ) + def test_from_service_account_file(self): info = SERVICE_ACCOUNT_INFO.copy() @@ -1133,3 +1181,12 @@ def test_before_request_refreshes(self, id_token_jwt_grant): # Credentials should now be valid. assert credentials.valid + + @pytest.mark.parametrize("empty_ud", ["", " "]) + def test_id_token_with_universe_domain_empty_string_raises(self, empty_ud): + """Explicitly passing an empty or whitespace universe domain raises ValueError.""" + credentials = self.make_credentials() + with pytest.raises( + ValueError, match="Universe Domain cannot be an empty string" + ): + credentials.with_universe_domain(empty_ud) From 61b1ee9707564ae204b17cccd10d99c553dae262 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Wed, 25 Nov 2026 17:24:42 +0000 Subject: [PATCH 05/17] add test --- .../google-auth/tests/oauth2/test_service_account.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/packages/google-auth/tests/oauth2/test_service_account.py b/packages/google-auth/tests/oauth2/test_service_account.py index 302b7290cad2..a0bc4c0c80b5 100644 --- a/packages/google-auth/tests/oauth2/test_service_account.py +++ b/packages/google-auth/tests/oauth2/test_service_account.py @@ -144,6 +144,17 @@ def test_with_always_use_jwt_access_false_clears_jwt_credentials(self): assert not updated._always_use_jwt_access assert updated._jwt_credentials is None + def test_with_universe_domain_resets_always_use_jwt_access(self): + """Transitioning from non-default back to default domain resets always_use_jwt_access.""" + creds = self.make_credentials() + assert not creds._always_use_jwt_access + + non_default = creds.with_universe_domain("custom.universe.domain") + assert non_default._always_use_jwt_access is True + + back_to_default = non_default.with_universe_domain(DEFAULT_UNIVERSE_DOMAIN) + assert back_to_default._always_use_jwt_access is False + def test_with_universe_domain_clears_jwt_credentials(self): """with_universe_domain clears cached self-signed JWT credentials.""" credentials = self.make_credentials(universe_domain=FAKE_UNIVERSE_DOMAIN) From 7928eab5dd1bd353ca45ea779f2bbb4e0558a753 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Wed, 25 Nov 2026 17:25:05 +0000 Subject: [PATCH 06/17] address review feedback --- packages/google-auth/google/oauth2/service_account.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/google-auth/google/oauth2/service_account.py b/packages/google-auth/google/oauth2/service_account.py index 5c8f3f7f44f4..7d3012ea1367 100644 --- a/packages/google-auth/google/oauth2/service_account.py +++ b/packages/google-auth/google/oauth2/service_account.py @@ -375,8 +375,9 @@ def with_universe_domain(self, universe_domain): _validate_universe_domain(universe_domain) cred = self._make_copy() cred._universe_domain = universe_domain or credentials.DEFAULT_UNIVERSE_DOMAIN - if cred._universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN: - cred._always_use_jwt_access = True + cred._always_use_jwt_access = ( + cred._universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN + ) # Clear cached JWT credentials since audience/universe metadata may change. cred._jwt_credentials = None return cred From fa569a53d0f6b389062cc178d308e19227b133e0 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Wed, 25 Nov 2026 17:28:41 +0000 Subject: [PATCH 07/17] Address review feedback --- packages/google-auth/google/oauth2/service_account.py | 3 +++ .../google-auth/tests/oauth2/test_service_account.py | 10 ++++++++++ 2 files changed, 13 insertions(+) diff --git a/packages/google-auth/google/oauth2/service_account.py b/packages/google-auth/google/oauth2/service_account.py index 7d3012ea1367..6685c9d5d553 100644 --- a/packages/google-auth/google/oauth2/service_account.py +++ b/packages/google-auth/google/oauth2/service_account.py @@ -380,6 +380,9 @@ def with_universe_domain(self, universe_domain): ) # Clear cached JWT credentials since audience/universe metadata may change. cred._jwt_credentials = None + # RAB state is only valid for the default universe domain. + if cred._universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN: + cred._rab_manager._data = None return cred def with_subject(self, subject): diff --git a/packages/google-auth/tests/oauth2/test_service_account.py b/packages/google-auth/tests/oauth2/test_service_account.py index a0bc4c0c80b5..ef625b16ee14 100644 --- a/packages/google-auth/tests/oauth2/test_service_account.py +++ b/packages/google-auth/tests/oauth2/test_service_account.py @@ -155,6 +155,16 @@ def test_with_universe_domain_resets_always_use_jwt_access(self): back_to_default = non_default.with_universe_domain(DEFAULT_UNIVERSE_DOMAIN) assert back_to_default._always_use_jwt_access is False + + def test_with_universe_domain_clears_rab_state_for_non_default_domain(self): + """Switching to a non-default universe domain clears cached RAB data.""" + creds = self.make_credentials() + creds._rab_manager._data = mock.Mock() + + custom_creds = creds.with_universe_domain("custom.universe.domain") + assert custom_creds._rab_manager._data is None + + def test_with_universe_domain_clears_jwt_credentials(self): """with_universe_domain clears cached self-signed JWT credentials.""" credentials = self.make_credentials(universe_domain=FAKE_UNIVERSE_DOMAIN) From 89b8d8b280f96e050d0f4a412fe5a2aa43e587b2 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Wed, 25 Nov 2026 17:35:20 +0000 Subject: [PATCH 08/17] lint --- packages/google-auth/tests/oauth2/test_service_account.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/packages/google-auth/tests/oauth2/test_service_account.py b/packages/google-auth/tests/oauth2/test_service_account.py index ef625b16ee14..bd6864c43d42 100644 --- a/packages/google-auth/tests/oauth2/test_service_account.py +++ b/packages/google-auth/tests/oauth2/test_service_account.py @@ -155,7 +155,6 @@ def test_with_universe_domain_resets_always_use_jwt_access(self): back_to_default = non_default.with_universe_domain(DEFAULT_UNIVERSE_DOMAIN) assert back_to_default._always_use_jwt_access is False - def test_with_universe_domain_clears_rab_state_for_non_default_domain(self): """Switching to a non-default universe domain clears cached RAB data.""" creds = self.make_credentials() @@ -164,7 +163,6 @@ def test_with_universe_domain_clears_rab_state_for_non_default_domain(self): custom_creds = creds.with_universe_domain("custom.universe.domain") assert custom_creds._rab_manager._data is None - def test_with_universe_domain_clears_jwt_credentials(self): """with_universe_domain clears cached self-signed JWT credentials.""" credentials = self.make_credentials(universe_domain=FAKE_UNIVERSE_DOMAIN) From 5b5e06e8ad623b472e237c8ded98b761f2779cfa Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Wed, 25 Nov 2026 17:44:32 +0000 Subject: [PATCH 09/17] address review feedback --- packages/google-auth/google/auth/jwt.py | 5 +---- packages/google-auth/google/oauth2/credentials.py | 12 ++++++++++++ .../google-auth/google/oauth2/service_account.py | 3 +-- 3 files changed, 14 insertions(+), 6 deletions(-) diff --git a/packages/google-auth/google/auth/jwt.py b/packages/google-auth/google/auth/jwt.py index 827d893bd14f..fc4aae6994d2 100644 --- a/packages/google-auth/google/auth/jwt.py +++ b/packages/google-auth/google/auth/jwt.py @@ -616,10 +616,7 @@ def with_universe_domain(self, universe_domain): quota_project_id=self._quota_project_id, 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) + self._update_regional_access_boundary_for_universe(cred, cred.universe_domain) return cred def _make_jwt(self): diff --git a/packages/google-auth/google/oauth2/credentials.py b/packages/google-auth/google/oauth2/credentials.py index cff8647d3bd9..6b2f4c377a5e 100644 --- a/packages/google-auth/google/oauth2/credentials.py +++ b/packages/google-auth/google/oauth2/credentials.py @@ -379,6 +379,18 @@ def _is_regional_access_boundary_lookup_required(self): """OAuth 2.0 credentials do not support independent lookup.""" return False + def _update_regional_access_boundary_for_universe( + self, target_credentials, universe_domain + ): + """Updates or resets the Regional Access Boundary (RAB) state for a target domain. + + RAB state is only preserved when the target is the default Google domain. + """ + if universe_domain == credentials.DEFAULT_UNIVERSE_DOMAIN: + self._copy_regional_access_boundary_manager(target_credentials) + else: + target_credentials._rab_manager._data = None + def _perform_refresh_token(self, request): if self._universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN: raise exceptions.RefreshError( diff --git a/packages/google-auth/google/oauth2/service_account.py b/packages/google-auth/google/oauth2/service_account.py index 6685c9d5d553..7ab23f8004f4 100644 --- a/packages/google-auth/google/oauth2/service_account.py +++ b/packages/google-auth/google/oauth2/service_account.py @@ -381,8 +381,7 @@ def with_universe_domain(self, universe_domain): # Clear cached JWT credentials since audience/universe metadata may change. cred._jwt_credentials = None # RAB state is only valid for the default universe domain. - if cred._universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN: - cred._rab_manager._data = None + self._update_regional_access_boundary_for_universe(cred, cred._universe_domain) return cred def with_subject(self, subject): From 08aae82fa359ce2d4b64ac142de9fb4fb979ec00 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Wed, 25 Nov 2026 17:56:19 +0000 Subject: [PATCH 10/17] address review feedback; fix build --- .../google-auth/google/auth/credentials.py | 12 +++++++++++ .../google-auth/google/oauth2/credentials.py | 12 ----------- .../google/oauth2/service_account.py | 20 ++++++++----------- .../tests/oauth2/test_service_account.py | 12 +++++++++++ 4 files changed, 32 insertions(+), 24 deletions(-) diff --git a/packages/google-auth/google/auth/credentials.py b/packages/google-auth/google/auth/credentials.py index 607d56654b45..e3901cad5b81 100644 --- a/packages/google-auth/google/auth/credentials.py +++ b/packages/google-auth/google/auth/credentials.py @@ -408,6 +408,18 @@ def _copy_regional_access_boundary_manager(self, target): self._rab_manager._use_blocking_regional_access_boundary_lookup ) + def _update_regional_access_boundary_for_universe( + self, target_credentials, universe_domain + ): + """Updates or resets the Regional Access Boundary (RAB) state for a target domain. + + RAB state is only preserved when the target is the default Google domain. + """ + if universe_domain == DEFAULT_UNIVERSE_DOMAIN: + self._copy_regional_access_boundary_manager(target_credentials) + else: + target_credentials._rab_manager._data = None + def _set_regional_access_boundary(self, initial_boundary): """Applies the regional_access_boundary provided via the initial_boundary on these credentials. This is intended for internal use only as an invalid diff --git a/packages/google-auth/google/oauth2/credentials.py b/packages/google-auth/google/oauth2/credentials.py index 6b2f4c377a5e..cff8647d3bd9 100644 --- a/packages/google-auth/google/oauth2/credentials.py +++ b/packages/google-auth/google/oauth2/credentials.py @@ -379,18 +379,6 @@ def _is_regional_access_boundary_lookup_required(self): """OAuth 2.0 credentials do not support independent lookup.""" return False - def _update_regional_access_boundary_for_universe( - self, target_credentials, universe_domain - ): - """Updates or resets the Regional Access Boundary (RAB) state for a target domain. - - RAB state is only preserved when the target is the default Google domain. - """ - if universe_domain == credentials.DEFAULT_UNIVERSE_DOMAIN: - self._copy_regional_access_boundary_manager(target_credentials) - else: - target_credentials._rab_manager._data = None - def _perform_refresh_token(self, request): if self._universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN: raise exceptions.RefreshError( diff --git a/packages/google-auth/google/oauth2/service_account.py b/packages/google-auth/google/oauth2/service_account.py index 7ab23f8004f4..e694bb07a7ee 100644 --- a/packages/google-auth/google/oauth2/service_account.py +++ b/packages/google-auth/google/oauth2/service_account.py @@ -239,12 +239,10 @@ def _from_signer_and_info(cls, signer, info, **kwargs): Raises: ValueError: If the info is not in the expected format. """ - # Respect an explicit universe_domain kwarg from the caller instead of - # letting a missing, null, or empty JSON value overwrite it. - if "universe_domain" not in kwargs: - kwargs["universe_domain"] = ( - info.get("universe_domain") or credentials.DEFAULT_UNIVERSE_DOMAIN - ) + # Respect an explicit universe_domain kwarg from the caller, otherwise + # only forward from info if present and non-empty. + if "universe_domain" not in kwargs and info.get("universe_domain"): + kwargs["universe_domain"] = info["universe_domain"] return cls( signer, service_account_email=info["client_email"], @@ -717,12 +715,10 @@ def _from_signer_and_info(cls, signer, info, **kwargs): """ kwargs.setdefault("service_account_email", info["client_email"]) kwargs.setdefault("token_uri", info["token_uri"]) - # Respect an explicit universe_domain kwarg from the caller instead of - # letting a missing, null, or empty JSON value overwrite it. - if "universe_domain" not in kwargs: - kwargs["universe_domain"] = ( - info.get("universe_domain") or credentials.DEFAULT_UNIVERSE_DOMAIN - ) + # Respect an explicit universe_domain kwarg from the caller, otherwise + # only forward from info if present and non-empty. Let cls() handle fallback. + if "universe_domain" not in kwargs and info.get("universe_domain"): + kwargs["universe_domain"] = info["universe_domain"] return cls(signer, **kwargs) @classmethod diff --git a/packages/google-auth/tests/oauth2/test_service_account.py b/packages/google-auth/tests/oauth2/test_service_account.py index bd6864c43d42..55aa19b6f878 100644 --- a/packages/google-auth/tests/oauth2/test_service_account.py +++ b/packages/google-auth/tests/oauth2/test_service_account.py @@ -1209,3 +1209,15 @@ def test_id_token_with_universe_domain_empty_string_raises(self, empty_ud): ValueError, match="Universe Domain cannot be an empty string" ): credentials.with_universe_domain(empty_ud) + + def test_from_service_account_info_does_not_inject_default_into_kwargs(self): + """Factory does not inject DEFAULT_UNIVERSE_DOMAIN when key is absent from info.""" + info = SERVICE_ACCOUNT_INFO.copy() + info.pop("universe_domain", None) + + with mock.patch.object( + service_account.Credentials, "__init__", return_value=None + ) as mock_init: + service_account.Credentials.from_service_account_info(info) + _, kwargs = mock_init.call_args + assert "universe_domain" not in kwargs From 922b93dff9fc27ba4e9e41a245adf8f45186d78d Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Wed, 25 Nov 2026 18:15:52 +0000 Subject: [PATCH 11/17] address review feedback; fix build --- .../google-auth/google/auth/credentials.py | 9 ++++----- .../google/oauth2/service_account.py | 18 +++++++++++------- .../tests/oauth2/test_service_account.py | 9 +++++++++ 3 files changed, 24 insertions(+), 12 deletions(-) diff --git a/packages/google-auth/google/auth/credentials.py b/packages/google-auth/google/auth/credentials.py index e3901cad5b81..4b0381807a8f 100644 --- a/packages/google-auth/google/auth/credentials.py +++ b/packages/google-auth/google/auth/credentials.py @@ -411,14 +411,13 @@ def _copy_regional_access_boundary_manager(self, target): def _update_regional_access_boundary_for_universe( self, target_credentials, universe_domain ): - """Updates or resets the Regional Access Boundary (RAB) state for a target domain. - - RAB state is only preserved when the target is the default Google domain. - """ + """Updates or resets Regional Access Boundary state for a target domain.""" if universe_domain == DEFAULT_UNIVERSE_DOMAIN: self._copy_regional_access_boundary_manager(target_credentials) else: - target_credentials._rab_manager._data = None + target_credentials._rab_manager = ( + _regional_access_boundary_utils._RegionalAccessBoundaryManager() + ) def _set_regional_access_boundary(self, initial_boundary): """Applies the regional_access_boundary provided via the initial_boundary on these diff --git a/packages/google-auth/google/oauth2/service_account.py b/packages/google-auth/google/oauth2/service_account.py index e694bb07a7ee..c5ea62f717ef 100644 --- a/packages/google-auth/google/oauth2/service_account.py +++ b/packages/google-auth/google/oauth2/service_account.py @@ -94,6 +94,13 @@ _DEFAULT_TOKEN_LIFETIME_SECS = 3600 # 1 hour in seconds _GOOGLE_OAUTH2_TOKEN_ENDPOINT = "https://oauth2.googleapis.com/token" +# The double curly braces `{{}}` escape the inner service account email placeholder. +# When this template is formatted via `.format(universe_domain=...)`, python evaluates +# `{{}}` down to a single `{}` which is populated with the email downstream in `_client.py`. +_IAM_IDTOKEN_ENDPOINT_TEMPLATE = ( + "https://iamcredentials.{universe_domain}/v1/projects/-/" + "serviceAccounts/{{}}:generateIdToken" +) def _validate_universe_domain(universe_domain): @@ -685,10 +692,9 @@ def __init__( self._universe_domain = credentials.DEFAULT_UNIVERSE_DOMAIN else: self._universe_domain = universe_domain - self._iam_id_token_endpoint = iam._IAM_IDTOKEN_ENDPOINT.replace( - "googleapis.com", self._universe_domain + self._iam_id_token_endpoint = _IAM_IDTOKEN_ENDPOINT_TEMPLATE.format( + universe_domain=self._universe_domain ) - if self._universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN: self._use_iam_endpoint = True @@ -834,11 +840,9 @@ def with_universe_domain(self, universe_domain): _validate_universe_domain(universe_domain) cred = self._make_copy() cred._universe_domain = universe_domain or credentials.DEFAULT_UNIVERSE_DOMAIN - # Rebuild the IAM generateIdToken URL for the updated universe domain. - cred._iam_id_token_endpoint = iam._IAM_IDTOKEN_ENDPOINT.replace( - "googleapis.com", cred._universe_domain + cred._iam_id_token_endpoint = _IAM_IDTOKEN_ENDPOINT_TEMPLATE.format( + universe_domain=cred._universe_domain ) - # Non-default universe domains require the IAM generateIdToken endpoint. cred._use_iam_endpoint = ( cred._universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN ) diff --git a/packages/google-auth/tests/oauth2/test_service_account.py b/packages/google-auth/tests/oauth2/test_service_account.py index 55aa19b6f878..c91a4300fcd2 100644 --- a/packages/google-auth/tests/oauth2/test_service_account.py +++ b/packages/google-auth/tests/oauth2/test_service_account.py @@ -1210,6 +1210,15 @@ def test_id_token_with_universe_domain_empty_string_raises(self, empty_ud): ): credentials.with_universe_domain(empty_ud) + def test_id_token_credentials_universe_domain_substring_safety(self): + """Universe domains containing 'googleapis.com' as a substring do not corrupt endpoint.""" + tricky_ud = "googleapis.com.custom.internal" + creds = self.make_credentials() + updated = creds.with_universe_domain(tricky_ud) + + expected = f"https://iamcredentials.{tricky_ud}/v1/projects/-/serviceAccounts/{{}}:generateIdToken" + assert updated._iam_id_token_endpoint == expected + def test_from_service_account_info_does_not_inject_default_into_kwargs(self): """Factory does not inject DEFAULT_UNIVERSE_DOMAIN when key is absent from info.""" info = SERVICE_ACCOUNT_INFO.copy() From bb28bdb0162d41202bace0d85bb45018bf2b0fb6 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Wed, 25 Nov 2026 19:03:25 +0000 Subject: [PATCH 12/17] address review feedback --- .../auth/_regional_access_boundary_utils.py | 9 ++++ .../google-auth/google/auth/credentials.py | 11 +++-- .../google/oauth2/service_account.py | 1 - .../oauth2/test_service_account_async.py | 45 ++++++++++++++++++- 4 files changed, 58 insertions(+), 8 deletions(-) diff --git a/packages/google-auth/google/auth/_regional_access_boundary_utils.py b/packages/google-auth/google/auth/_regional_access_boundary_utils.py index 0034bf381012..d0d31b843941 100644 --- a/packages/google-auth/google/auth/_regional_access_boundary_utils.py +++ b/packages/google-auth/google/auth/_regional_access_boundary_utils.py @@ -359,6 +359,15 @@ def process_regional_access_boundary_info(self, regional_access_boundary_info): # Perform the atomic swap of the state object. self._data = updated_data + def clear_data(self): + """Clears cached Regional Access Boundary location data.""" + self._data = _RegionalAccessBoundaryData( + encoded_locations=None, + expiry=None, + cooldown_expiry=None, + cooldown_duration=DEFAULT_REGIONAL_ACCESS_BOUNDARY_COOLDOWN, + ) + class _RegionalAccessBoundaryRefreshThread(threading.Thread): """Thread for background refreshing of the Regional Access Boundary.""" diff --git a/packages/google-auth/google/auth/credentials.py b/packages/google-auth/google/auth/credentials.py index 4b0381807a8f..25da25f0c224 100644 --- a/packages/google-auth/google/auth/credentials.py +++ b/packages/google-auth/google/auth/credentials.py @@ -412,12 +412,11 @@ def _update_regional_access_boundary_for_universe( self, target_credentials, universe_domain ): """Updates or resets Regional Access Boundary state for a target domain.""" - if universe_domain == DEFAULT_UNIVERSE_DOMAIN: - self._copy_regional_access_boundary_manager(target_credentials) - else: - target_credentials._rab_manager = ( - _regional_access_boundary_utils._RegionalAccessBoundaryManager() - ) + self._copy_regional_access_boundary_manager(target_credentials) + # RAB state is only valid for the default universe domain, so don't + # carry cached RAB data over when using a non-default universe domain. + if universe_domain != DEFAULT_UNIVERSE_DOMAIN: + target_credentials._rab_manager.clear_data() def _set_regional_access_boundary(self, initial_boundary): """Applies the regional_access_boundary provided via the initial_boundary on these diff --git a/packages/google-auth/google/oauth2/service_account.py b/packages/google-auth/google/oauth2/service_account.py index c5ea62f717ef..b79e6c4104be 100644 --- a/packages/google-auth/google/oauth2/service_account.py +++ b/packages/google-auth/google/oauth2/service_account.py @@ -81,7 +81,6 @@ _service_account_info, credentials, exceptions, - iam, jwt, metrics, ) 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..e9ab8636be27 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,16 @@ import pytest # type: ignore -from google.auth import _helpers, crypt, environment_vars, jwt, transport +from google.auth import _credentials_async as credentials_async +from google.auth import ( + _helpers, + _regional_access_boundary_utils, + crypt, + environment_vars, + jwt, + transport, +) +from google.auth.credentials import DEFAULT_UNIVERSE_DOMAIN from google.oauth2 import _service_account_async as service_account from tests.oauth2 import test_service_account @@ -385,6 +394,40 @@ def test_unpickle_old_credentials_without_rab(self): _regional_access_boundary_utils._AsyncRegionalAccessBoundaryRefreshManager, ) + def test_with_universe_domain(self): + """Async credentials cleanly inherit and process with_universe_domain copying.""" + credentials = self.make_credentials() + + # 1. Assert that the original instance is indeed an async credential object + assert isinstance(credentials, credentials_async.Credentials) + assert credentials.universe_domain == DEFAULT_UNIVERSE_DOMAIN + assert not credentials._always_use_jwt_access + + # Transition to custom universe + custom_creds = credentials.with_universe_domain("custom.universe.domain") + + # 2. Assert that the copy retains async inheritance and subclass identity + assert isinstance(custom_creds, service_account.Credentials) + assert isinstance(custom_creds, credentials_async.Credentials) + assert custom_creds.universe_domain == "custom.universe.domain" + assert custom_creds._always_use_jwt_access is True + + # 3. Explicitly verify that its RAB manager retains the asynchronous refresh worker implementation + assert isinstance( + custom_creds._rab_manager.refresh_manager, + _regional_access_boundary_utils._AsyncRegionalAccessBoundaryRefreshManager, + ) + assert custom_creds._rab_manager._data.encoded_locations is None + + # Transition back to GDU + back_to_gdu = custom_creds.with_universe_domain(DEFAULT_UNIVERSE_DOMAIN) + + # 4. Confirm async credentials class is preserved on the return transition + assert isinstance(back_to_gdu, service_account.Credentials) + assert isinstance(back_to_gdu, credentials_async.Credentials) + assert back_to_gdu.universe_domain == DEFAULT_UNIVERSE_DOMAIN + assert back_to_gdu._always_use_jwt_access is False + class TestIDTokenCredentials(object): SERVICE_ACCOUNT_EMAIL = "service-account@example.com" From 66d06e7ce80f00fc739f84b6a58c7213c78f0bff Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Wed, 25 Nov 2026 21:36:03 +0000 Subject: [PATCH 13/17] clean up --- packages/google-auth/google/auth/_helpers.py | 20 +++ .../auth/_regional_access_boundary_utils.py | 13 +- .../google-auth/google/auth/credentials.py | 11 +- packages/google-auth/google/auth/iam.py | 21 +++ packages/google-auth/google/auth/jwt.py | 33 ++-- .../google/oauth2/service_account.py | 74 ++++----- .../tests/oauth2/test_service_account.py | 144 +++++++++++++----- packages/google-auth/tests/test__helpers.py | 31 +++- packages/google-auth/tests/test_iam.py | 15 ++ .../oauth2/test_service_account_async.py | 91 +++++++++-- 10 files changed, 322 insertions(+), 131 deletions(-) diff --git a/packages/google-auth/google/auth/_helpers.py b/packages/google-auth/google/auth/_helpers.py index 568def959d5a..063c34c550a6 100644 --- a/packages/google-auth/google/auth/_helpers.py +++ b/packages/google-auth/google/auth/_helpers.py @@ -533,3 +533,23 @@ def response_log(logger: logging.Logger, response: Any) -> None: if is_logging_enabled(logger): json_response = _parse_response(response) _response_log_base(logger, json_response) + + +def validate_universe_domain( + universe_domain: Optional[str], *, allow_none: bool = False +) -> None: + """Validates that ``universe_domain`` is a non-empty string. + + Args: + universe_domain (Optional[str]): The universe domain to validate. + allow_none (bool): Whether ``None`` is permitted (allowing fallback + to the default universe domain). Defaults to ``False``. + + Raises: + google.auth.exceptions.InvalidValue: If ``universe_domain`` is not a + non-empty string (or is ``None`` when ``allow_none=False``). + """ + if universe_domain is None and allow_none: + return + if not isinstance(universe_domain, str) or not universe_domain.strip(): + raise exceptions.InvalidValue("Universe domain cannot be empty.") diff --git a/packages/google-auth/google/auth/_regional_access_boundary_utils.py b/packages/google-auth/google/auth/_regional_access_boundary_utils.py index d0d31b843941..89858165433b 100644 --- a/packages/google-auth/google/auth/_regional_access_boundary_utils.py +++ b/packages/google-auth/google/auth/_regional_access_boundary_utils.py @@ -361,12 +361,13 @@ def process_regional_access_boundary_info(self, regional_access_boundary_info): def clear_data(self): """Clears cached Regional Access Boundary location data.""" - self._data = _RegionalAccessBoundaryData( - encoded_locations=None, - expiry=None, - cooldown_expiry=None, - cooldown_duration=DEFAULT_REGIONAL_ACCESS_BOUNDARY_COOLDOWN, - ) + with self._update_lock: + self._data = _RegionalAccessBoundaryData( + encoded_locations=None, + expiry=None, + cooldown_expiry=None, + cooldown_duration=DEFAULT_REGIONAL_ACCESS_BOUNDARY_COOLDOWN, + ) class _RegionalAccessBoundaryRefreshThread(threading.Thread): diff --git a/packages/google-auth/google/auth/credentials.py b/packages/google-auth/google/auth/credentials.py index 25da25f0c224..7a76f74f742b 100644 --- a/packages/google-auth/google/auth/credentials.py +++ b/packages/google-auth/google/auth/credentials.py @@ -411,11 +411,12 @@ def _copy_regional_access_boundary_manager(self, target): def _update_regional_access_boundary_for_universe( self, target_credentials, universe_domain ): - """Updates or resets Regional Access Boundary state for a target domain.""" - self._copy_regional_access_boundary_manager(target_credentials) - # RAB state is only valid for the default universe domain, so don't - # carry cached RAB data over when using a non-default universe domain. - if universe_domain != DEFAULT_UNIVERSE_DOMAIN: + """Copies RAB state for the default universe domain or clears it otherwise.""" + # RAB state is only valid for the default universe domain, so only copy + # cached RAB state/config when targeting the default universe domain. + if universe_domain == DEFAULT_UNIVERSE_DOMAIN: + self._copy_regional_access_boundary_manager(target_credentials) + else: target_credentials._rab_manager.clear_data() def _set_regional_access_boundary(self, initial_boundary): diff --git a/packages/google-auth/google/auth/iam.py b/packages/google-auth/google/auth/iam.py index 46ae558c5198..d8024e6c0056 100644 --- a/packages/google-auth/google/auth/iam.py +++ b/packages/google-auth/google/auth/iam.py @@ -54,6 +54,27 @@ _IAM_SIGN_ENDPOINT = _IAM_BASE_URL + ":signBlob" _IAM_SIGNJWT_ENDPOINT = _IAM_BASE_URL + ":signJwt" _IAM_IDTOKEN_ENDPOINT = _IAM_BASE_URL + ":generateIdToken" +# Template for non-default universe domains; double braces escape the service +# account email placeholder so .format(universe_domain=...) leaves `{}` intact +# for downstream email formatting. +_IAM_IDTOKEN_ENDPOINT_TEMPLATE = ( + "https://iamcredentials.{universe_domain}/v1/projects/-/" + "serviceAccounts/{{}}:generateIdToken" +) + + +def _get_iam_idtoken_endpoint( + universe_domain: str = credentials.DEFAULT_UNIVERSE_DOMAIN, +) -> str: + """Returns the IAM generateIdToken endpoint template for ``universe_domain``. + + Uses ``_IAM_IDTOKEN_ENDPOINT`` (which respects mTLS configuration) for the + default universe domain, and formats ``_IAM_IDTOKEN_ENDPOINT_TEMPLATE`` for + non-default universe domains. + """ + if universe_domain == credentials.DEFAULT_UNIVERSE_DOMAIN: + return _IAM_IDTOKEN_ENDPOINT + return _IAM_IDTOKEN_ENDPOINT_TEMPLATE.format(universe_domain=universe_domain) class Signer(crypt.Signer): diff --git a/packages/google-auth/google/auth/jwt.py b/packages/google-auth/google/auth/jwt.py index fc4aae6994d2..4e4e94842733 100644 --- a/packages/google-auth/google/auth/jwt.py +++ b/packages/google-auth/google/auth/jwt.py @@ -75,17 +75,6 @@ _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. @@ -539,17 +528,15 @@ def from_signing_credentials(cls, credentials, 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, - google.auth.credentials.CredentialsWithRegionalAccessBoundary, - ) - and jwt_creds.universe_domain - == google.auth.credentials.DEFAULT_UNIVERSE_DOMAIN + # empty RAB state so a default-universe boundary is never sent to + # another universe. + if isinstance( + credentials, + google.auth.credentials.CredentialsWithRegionalAccessBoundary, ): - credentials._copy_regional_access_boundary_manager(jwt_creds) + credentials._update_regional_access_boundary_for_universe( + jwt_creds, jwt_creds.universe_domain + ) return jwt_creds @@ -605,7 +592,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) + _helpers.validate_universe_domain(universe_domain) cred = self.__class__( self._signer, issuer=self._issuer, @@ -896,7 +883,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) + _helpers.validate_universe_domain(universe_domain) return self.__class__( self._signer, issuer=self._issuer, diff --git a/packages/google-auth/google/oauth2/service_account.py b/packages/google-auth/google/oauth2/service_account.py index b79e6c4104be..c95bb60280d9 100644 --- a/packages/google-auth/google/oauth2/service_account.py +++ b/packages/google-auth/google/oauth2/service_account.py @@ -81,6 +81,7 @@ _service_account_info, credentials, exceptions, + iam, jwt, metrics, ) @@ -93,24 +94,6 @@ _DEFAULT_TOKEN_LIFETIME_SECS = 3600 # 1 hour in seconds _GOOGLE_OAUTH2_TOKEN_ENDPOINT = "https://oauth2.googleapis.com/token" -# The double curly braces `{{}}` escape the inner service account email placeholder. -# When this template is formatted via `.format(universe_domain=...)`, python evaluates -# `{{}}` down to a single `{}` which is populated with the email downstream in `_client.py`. -_IAM_IDTOKEN_ENDPOINT_TEMPLATE = ( - "https://iamcredentials.{universe_domain}/v1/projects/-/" - "serviceAccounts/{{}}:generateIdToken" -) - - -def _validate_universe_domain(universe_domain): - """Validates that the universe domain is non-empty. - - Raises: - ValueError: If the universe domain is an empty string - or contains only blank spaces. - """ - if universe_domain is not None and not str(universe_domain).strip(): - raise ValueError("Universe Domain cannot be an empty string.") class Credentials( @@ -211,8 +194,9 @@ def __init__( self._project_id = project_id self._quota_project_id = quota_project_id self._token_uri = token_uri + self._explicit_always_use_jwt_access = bool(always_use_jwt_access) self._always_use_jwt_access = always_use_jwt_access - _validate_universe_domain(universe_domain) + _helpers.validate_universe_domain(universe_domain, allow_none=True) self._universe_domain = universe_domain or credentials.DEFAULT_UNIVERSE_DOMAIN # Check the normalized universe domain so None falls back to the @@ -245,9 +229,10 @@ def _from_signer_and_info(cls, signer, info, **kwargs): Raises: ValueError: If the info is not in the expected format. """ - # Respect an explicit universe_domain kwarg from the caller, otherwise - # only forward from info if present and non-empty. - if "universe_domain" not in kwargs and info.get("universe_domain"): + # Respect an explicit universe_domain kwarg from the caller; otherwise + # forward from info whenever present and not None so empty strings still + # fail validation while omitted/null values let cls() apply its default. + if "universe_domain" not in kwargs and info.get("universe_domain") is not None: kwargs["universe_domain"] = info["universe_domain"] return cls( signer, @@ -315,7 +300,7 @@ def requires_scopes(self): """ return True if not self._scopes else False - def _make_copy(self): + def _make_copy(self, *, _copy_rab=True): cred = self.__class__( self._signer, service_account_email=self._service_account_email, @@ -326,7 +311,9 @@ def _make_copy(self): project_id=self._project_id, quota_project_id=self._quota_project_id, additional_claims=self._additional_claims.copy(), - always_use_jwt_access=self._always_use_jwt_access, + always_use_jwt_access=getattr( + self, "_explicit_always_use_jwt_access", self._always_use_jwt_access + ), universe_domain=self._universe_domain, trust_boundary=self._trust_boundary, ) @@ -335,7 +322,8 @@ def _make_copy(self): # their audience without sharing mutable token state with the original. if self._jwt_credentials is not None: cred._jwt_credentials = self._jwt_credentials.with_claims() - self._copy_regional_access_boundary_manager(cred) + if _copy_rab: + self._copy_regional_access_boundary_manager(cred) return cred @_helpers.copy_docstring(credentials.Scoped) @@ -368,6 +356,7 @@ def with_always_use_jwt_access(self, always_use_jwt_access): raise exceptions.InvalidValue( "always_use_jwt_access should be True for non-default universe domain" ) + cred._explicit_always_use_jwt_access = bool(always_use_jwt_access) cred._always_use_jwt_access = always_use_jwt_access if not always_use_jwt_access: # Drop cached self-signed JWT credentials when opting out of JWT access. @@ -376,11 +365,12 @@ def with_always_use_jwt_access(self, always_use_jwt_access): @_helpers.copy_docstring(credentials.CredentialsWithUniverseDomain) def with_universe_domain(self, universe_domain): - _validate_universe_domain(universe_domain) - cred = self._make_copy() - cred._universe_domain = universe_domain or credentials.DEFAULT_UNIVERSE_DOMAIN + _helpers.validate_universe_domain(universe_domain) + cred = self._make_copy(_copy_rab=False) + cred._universe_domain = universe_domain cred._always_use_jwt_access = ( - cred._universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN + getattr(cred, "_explicit_always_use_jwt_access", False) + or cred._universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN ) # Clear cached JWT credentials since audience/universe metadata may change. cred._jwt_credentials = None @@ -686,13 +676,10 @@ def __init__( self._quota_project_id = quota_project_id self._use_iam_endpoint = False - _validate_universe_domain(universe_domain) - if not universe_domain: - self._universe_domain = credentials.DEFAULT_UNIVERSE_DOMAIN - else: - self._universe_domain = universe_domain - self._iam_id_token_endpoint = _IAM_IDTOKEN_ENDPOINT_TEMPLATE.format( - universe_domain=self._universe_domain + _helpers.validate_universe_domain(universe_domain, allow_none=True) + self._universe_domain = universe_domain or credentials.DEFAULT_UNIVERSE_DOMAIN + self._iam_id_token_endpoint = iam._get_iam_idtoken_endpoint( + self._universe_domain ) if self._universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN: self._use_iam_endpoint = True @@ -720,9 +707,10 @@ def _from_signer_and_info(cls, signer, info, **kwargs): """ kwargs.setdefault("service_account_email", info["client_email"]) kwargs.setdefault("token_uri", info["token_uri"]) - # Respect an explicit universe_domain kwarg from the caller, otherwise - # only forward from info if present and non-empty. Let cls() handle fallback. - if "universe_domain" not in kwargs and info.get("universe_domain"): + # Respect an explicit universe_domain kwarg from the caller; otherwise + # forward from info whenever present and not None so empty strings still + # fail validation while omitted/null values let cls() apply its default. + if "universe_domain" not in kwargs and info.get("universe_domain") is not None: kwargs["universe_domain"] = info["universe_domain"] return cls(signer, **kwargs) @@ -836,11 +824,11 @@ def with_token_uri(self, token_uri): @_helpers.copy_docstring(credentials.CredentialsWithUniverseDomain) def with_universe_domain(self, universe_domain): - _validate_universe_domain(universe_domain) + _helpers.validate_universe_domain(universe_domain) cred = self._make_copy() - cred._universe_domain = universe_domain or credentials.DEFAULT_UNIVERSE_DOMAIN - cred._iam_id_token_endpoint = _IAM_IDTOKEN_ENDPOINT_TEMPLATE.format( - universe_domain=cred._universe_domain + cred._universe_domain = universe_domain + cred._iam_id_token_endpoint = iam._get_iam_idtoken_endpoint( + cred._universe_domain ) cred._use_iam_endpoint = ( cred._universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN diff --git a/packages/google-auth/tests/oauth2/test_service_account.py b/packages/google-auth/tests/oauth2/test_service_account.py index c91a4300fcd2..2e79c365d8bb 100644 --- a/packages/google-auth/tests/oauth2/test_service_account.py +++ b/packages/google-auth/tests/oauth2/test_service_account.py @@ -19,7 +19,15 @@ import pytest # type: ignore -from google.auth import _helpers, crypt, exceptions, iam, jwt, transport +from google.auth import ( + _helpers, + _regional_access_boundary_utils, + crypt, + exceptions, + iam, + jwt, + transport, +) from google.auth.credentials import ( DEFAULT_UNIVERSE_DOMAIN, CredentialsWithUniverseDomain, @@ -107,6 +115,7 @@ def test__make_copy_preserves_jwt_credentials(self): assert copied._jwt_credentials is not None assert copied._jwt_credentials is not credentials._jwt_credentials assert copied._jwt_credentials._audience == audience + assert copied._jwt_credentials.universe_domain == FAKE_UNIVERSE_DOMAIN request = mock.create_autospec(transport.Request, instance=True) copied.refresh(request) @@ -155,13 +164,40 @@ def test_with_universe_domain_resets_always_use_jwt_access(self): back_to_default = non_default.with_universe_domain(DEFAULT_UNIVERSE_DOMAIN) assert back_to_default._always_use_jwt_access is False + # Explicit always_use_jwt_access=True opt-in is preserved across transitions. + explicit_jwt_creds = creds.with_always_use_jwt_access(True) + assert explicit_jwt_creds._always_use_jwt_access is True + explicit_roundtrip = explicit_jwt_creds.with_universe_domain( + "custom.universe.domain" + ).with_universe_domain(DEFAULT_UNIVERSE_DOMAIN) + assert explicit_roundtrip._always_use_jwt_access is True + def test_with_universe_domain_clears_rab_state_for_non_default_domain(self): """Switching to a non-default universe domain clears cached RAB data.""" + fake_rab_encoded_locations = "0xA30" creds = self.make_credentials() - creds._rab_manager._data = mock.Mock() + creds._rab_manager._data = _regional_access_boundary_utils._RegionalAccessBoundaryData( + encoded_locations=fake_rab_encoded_locations, + expiry=_helpers.utcnow() + datetime.timedelta(hours=1), + cooldown_expiry=None, + cooldown_duration=_regional_access_boundary_utils.DEFAULT_REGIONAL_ACCESS_BOUNDARY_COOLDOWN, + ) + assert creds._rab_manager._data.encoded_locations == fake_rab_encoded_locations + + # Switching to a non-default domain clears the boundary custom_creds = creds.with_universe_domain("custom.universe.domain") - assert custom_creds._rab_manager._data is None + assert custom_creds._rab_manager._data.encoded_locations is None + assert custom_creds._rab_manager._data.expiry is None + assert custom_creds._rab_manager is not creds._rab_manager + + # Switching within the default domain preserves the boundary + default_creds = creds.with_universe_domain(DEFAULT_UNIVERSE_DOMAIN) + assert ( + default_creds._rab_manager._data.encoded_locations + == fake_rab_encoded_locations + ) + assert default_creds._rab_manager is not creds._rab_manager def test_with_universe_domain_clears_jwt_credentials(self): """with_universe_domain clears cached self-signed JWT credentials.""" @@ -183,21 +219,14 @@ def test_with_subject_clears_jwt_credentials(self): assert delegated._subject == "user@example.com" assert delegated._jwt_credentials is None - def test_with_universe_domain_none_defaults(self): - """with_universe_domain normalizes None to the default domain.""" - credentials = self.make_credentials() - updated = credentials.with_universe_domain(None) - assert updated.universe_domain == DEFAULT_UNIVERSE_DOMAIN - assert not updated._always_use_jwt_access - - @pytest.mark.parametrize("empty_ud", ["", " "]) - def test_with_universe_domain_empty_string_raises(self, empty_ud): - """Explicitly passing an empty or whitespace universe domain raises ValueError.""" + @pytest.mark.parametrize("invalid_ud", [None, "", " ", 123]) + def test_with_universe_domain_invalid_raises(self, invalid_ud): + """Explicitly passing None, empty, whitespace, or non-str raises InvalidValue.""" credentials = self.make_credentials() with pytest.raises( - ValueError, match="Universe Domain cannot be an empty string" + exceptions.InvalidValue, match="Universe domain cannot be empty." ): - credentials.with_universe_domain(empty_ud) + credentials.with_universe_domain(invalid_ud) def test_inherits_credentials_with_universe_domain(self): """Credentials implements the CredentialsWithUniverseDomain interface.""" @@ -221,17 +250,17 @@ def test_constructor_none_universe_domain_jwt_access(self): assert credentials.universe_domain == DEFAULT_UNIVERSE_DOMAIN assert not credentials._always_use_jwt_access - @pytest.mark.parametrize("empty_ud", ["", " "]) - def test_constructor_empty_universe_domain_raises(self, empty_ud): - """Empty or whitespace universe_domain in constructor raises ValueError.""" + @pytest.mark.parametrize("invalid_ud", ["", " ", 123]) + def test_constructor_empty_universe_domain_raises(self, invalid_ud): + """Empty, whitespace, or non-str universe_domain in constructor raises.""" with pytest.raises( - ValueError, match="Universe Domain cannot be an empty string" + exceptions.InvalidValue, match="Universe domain cannot be empty." ): service_account.Credentials( SIGNER, self.SERVICE_ACCOUNT_EMAIL, self.TOKEN_URI, - universe_domain=empty_ud, + universe_domain=invalid_ud, ) def test_from_service_account_info(self): @@ -286,17 +315,42 @@ def test_from_service_account_info_explicit_none_universe_domain_overrides_info( def test_from_service_account_info_explicit_empty_universe_domain_raises( self, empty_ud ): - """Explicit empty or whitespace universe_domain kwarg raises ValueError.""" + """Explicit empty or whitespace universe_domain kwarg raises InvalidValue.""" info = SERVICE_ACCOUNT_INFO.copy() info["universe_domain"] = FAKE_UNIVERSE_DOMAIN with pytest.raises( - ValueError, match="Universe Domain cannot be an empty string" + exceptions.InvalidValue, match="Universe domain cannot be empty." ): service_account.Credentials.from_service_account_info( info, universe_domain=empty_ud ) + @pytest.mark.parametrize("empty_ud", ["", " "]) + def test_from_service_account_info_empty_universe_domain_in_json_raises( + self, empty_ud + ): + """Empty or whitespace universe_domain in JSON raises InvalidValue.""" + info = SERVICE_ACCOUNT_INFO.copy() + info["universe_domain"] = empty_ud + + with pytest.raises( + exceptions.InvalidValue, match="Universe domain cannot be empty." + ): + service_account.Credentials.from_service_account_info(info) + + def test_from_service_account_info_does_not_inject_default_into_kwargs(self): + """Factory does not inject DEFAULT_UNIVERSE_DOMAIN when key is absent from info.""" + info = SERVICE_ACCOUNT_INFO.copy() + info.pop("universe_domain", None) + + with mock.patch.object( + service_account.Credentials, "__init__", return_value=None + ) as mock_init: + service_account.Credentials.from_service_account_info(info) + _, kwargs = mock_init.call_args + assert "universe_domain" not in kwargs + def test_from_service_account_info_args(self): info = SERVICE_ACCOUNT_INFO.copy() scopes = ["email", "profile"] @@ -970,12 +1024,12 @@ def test_from_service_account_info_explicit_none_universe_domain_overrides_info( def test_id_token_from_service_account_info_explicit_empty_universe_domain_raises( self, empty_ud ): - """Explicit empty or whitespace universe_domain kwarg raises ValueError.""" + """Explicit empty or whitespace universe_domain kwarg raises InvalidValue.""" info = SERVICE_ACCOUNT_INFO.copy() info["universe_domain"] = FAKE_UNIVERSE_DOMAIN with pytest.raises( - ValueError, match="Universe Domain cannot be an empty string" + exceptions.InvalidValue, match="Universe domain cannot be empty." ): service_account.IDTokenCredentials.from_service_account_info( info, @@ -983,6 +1037,21 @@ def test_id_token_from_service_account_info_explicit_empty_universe_domain_raise universe_domain=empty_ud, ) + @pytest.mark.parametrize("empty_ud", ["", " "]) + def test_id_token_from_service_account_info_empty_universe_domain_in_json_raises( + self, empty_ud + ): + """Empty or whitespace universe_domain in JSON raises InvalidValue.""" + info = SERVICE_ACCOUNT_INFO.copy() + info["universe_domain"] = empty_ud + + with pytest.raises( + exceptions.InvalidValue, match="Universe domain cannot be empty." + ): + service_account.IDTokenCredentials.from_service_account_info( + info, target_audience=self.TARGET_AUDIENCE + ) + def test_from_service_account_file(self): info = SERVICE_ACCOUNT_INFO.copy() @@ -1067,20 +1136,14 @@ def test_with_universe_domain(self): non_default = credentials.with_universe_domain(FAKE_UNIVERSE_DOMAIN) assert non_default.universe_domain == FAKE_UNIVERSE_DOMAIN assert non_default._use_iam_endpoint is True - assert non_default._iam_id_token_endpoint == iam._IAM_IDTOKEN_ENDPOINT.replace( - "googleapis.com", FAKE_UNIVERSE_DOMAIN - ) + expected_endpoint = f"https://iamcredentials.{FAKE_UNIVERSE_DOMAIN}/v1/projects/-/serviceAccounts/{{}}:generateIdToken" + assert non_default._iam_id_token_endpoint == expected_endpoint default = non_default.with_universe_domain(DEFAULT_UNIVERSE_DOMAIN) assert default.universe_domain == DEFAULT_UNIVERSE_DOMAIN assert default._use_iam_endpoint is False assert default._iam_id_token_endpoint == iam._IAM_IDTOKEN_ENDPOINT - normalized = non_default.with_universe_domain(None) - assert normalized.universe_domain == DEFAULT_UNIVERSE_DOMAIN - assert normalized._use_iam_endpoint is False - assert normalized._iam_id_token_endpoint == iam._IAM_IDTOKEN_ENDPOINT - def test__make_authorization_grant_assertion(self): credentials = self.make_credentials() token = credentials._make_authorization_grant_assertion() @@ -1201,14 +1264,14 @@ def test_before_request_refreshes(self, id_token_jwt_grant): # Credentials should now be valid. assert credentials.valid - @pytest.mark.parametrize("empty_ud", ["", " "]) - def test_id_token_with_universe_domain_empty_string_raises(self, empty_ud): - """Explicitly passing an empty or whitespace universe domain raises ValueError.""" + @pytest.mark.parametrize("invalid_ud", [None, "", " ", 123]) + def test_id_token_with_universe_domain_invalid_raises(self, invalid_ud): + """Explicitly passing None, empty, whitespace, or non-str raises InvalidValue.""" credentials = self.make_credentials() with pytest.raises( - ValueError, match="Universe Domain cannot be an empty string" + exceptions.InvalidValue, match="Universe domain cannot be empty." ): - credentials.with_universe_domain(empty_ud) + credentials.with_universe_domain(invalid_ud) def test_id_token_credentials_universe_domain_substring_safety(self): """Universe domains containing 'googleapis.com' as a substring do not corrupt endpoint.""" @@ -1218,6 +1281,7 @@ def test_id_token_credentials_universe_domain_substring_safety(self): expected = f"https://iamcredentials.{tricky_ud}/v1/projects/-/serviceAccounts/{{}}:generateIdToken" assert updated._iam_id_token_endpoint == expected + assert updated._use_iam_endpoint is True def test_from_service_account_info_does_not_inject_default_into_kwargs(self): """Factory does not inject DEFAULT_UNIVERSE_DOMAIN when key is absent from info.""" @@ -1225,8 +1289,10 @@ def test_from_service_account_info_does_not_inject_default_into_kwargs(self): info.pop("universe_domain", None) with mock.patch.object( - service_account.Credentials, "__init__", return_value=None + service_account.IDTokenCredentials, "__init__", return_value=None ) as mock_init: - service_account.Credentials.from_service_account_info(info) + service_account.IDTokenCredentials.from_service_account_info( + info, target_audience=self.TARGET_AUDIENCE + ) _, kwargs = mock_init.call_args assert "universe_domain" not in kwargs diff --git a/packages/google-auth/tests/test__helpers.py b/packages/google-auth/tests/test__helpers.py index 5755e2a357d2..9807df369ff2 100644 --- a/packages/google-auth/tests/test__helpers.py +++ b/packages/google-auth/tests/test__helpers.py @@ -20,7 +20,7 @@ import pytest # type: ignore -from google.auth import _helpers +from google.auth import _helpers, exceptions # _MOCK_BASE_LOGGER_NAME is the base logger namespace used for testing. _MOCK_BASE_LOGGER_NAME = "foogle" @@ -652,6 +652,35 @@ def test_parse_response_none(): assert _helpers._parse_response(None) is None +@pytest.mark.parametrize("invalid_ud", [None, "", " ", "\t", "\n", 123, []]) +def test_validate_universe_domain_invalid_raises(invalid_ud): + with pytest.raises( + exceptions.InvalidValue, match="Universe domain cannot be empty." + ): + _helpers.validate_universe_domain(invalid_ud) + + +@pytest.mark.parametrize("invalid_ud", ["", " ", "\t", "\n", 123, []]) +def test_validate_universe_domain_allow_none_still_rejects_empty_and_non_str( + invalid_ud, +): + with pytest.raises( + exceptions.InvalidValue, match="Universe domain cannot be empty." + ): + _helpers.validate_universe_domain(invalid_ud, allow_none=True) + + +@pytest.mark.parametrize("valid_ud", ["googleapis.com", "myuniverse.goog"]) +def test_validate_universe_domain_valid(valid_ud): + # Does not raise with default allow_none=False or allow_none=True + _helpers.validate_universe_domain(valid_ud) + _helpers.validate_universe_domain(valid_ud, allow_none=True) + + +def test_validate_universe_domain_allow_none_accepts_none(): + _helpers.validate_universe_domain(None, allow_none=True) + + class TestUtcFromTimestamp: """Tests for the utcfromtimestamp utility function.""" diff --git a/packages/google-auth/tests/test_iam.py b/packages/google-auth/tests/test_iam.py index 51e045e9864d..6cf66a11bb8a 100644 --- a/packages/google-auth/tests/test_iam.py +++ b/packages/google-auth/tests/test_iam.py @@ -110,3 +110,18 @@ def test_sign_bytes_retryable_failure(self, mock_time): with pytest.raises(exceptions.TransportError): signer.sign("123") request.call_count == 3 + + +def test__get_iam_idtoken_endpoint(): + assert ( + iam._get_iam_idtoken_endpoint(google.auth.credentials.DEFAULT_UNIVERSE_DOMAIN) + == iam._IAM_IDTOKEN_ENDPOINT + ) + assert ( + iam._get_iam_idtoken_endpoint("universe.foo") + == "https://iamcredentials.universe.foo/v1/projects/-/serviceAccounts/{}:generateIdToken" + ) + assert ( + iam._get_iam_idtoken_endpoint("googleapis.com.custom.internal") + == "https://iamcredentials.googleapis.com.custom.internal/v1/projects/-/serviceAccounts/{}:generateIdToken" + ) 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 e9ab8636be27..fabd1fe98ba1 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 @@ -23,10 +23,15 @@ _regional_access_boundary_utils, crypt, environment_vars, + exceptions, + iam, jwt, transport, ) -from google.auth.credentials import DEFAULT_UNIVERSE_DOMAIN +from google.auth.credentials import ( + DEFAULT_UNIVERSE_DOMAIN, + CredentialsWithUniverseDomain, +) from google.oauth2 import _service_account_async as service_account from tests.oauth2 import test_service_account @@ -396,37 +401,67 @@ def test_unpickle_old_credentials_without_rab(self): def test_with_universe_domain(self): """Async credentials cleanly inherit and process with_universe_domain copying.""" + fake_rab_encoded_locations = "0xA30" credentials = self.make_credentials() - # 1. Assert that the original instance is indeed an async credential object + credentials._rab_manager._data = _regional_access_boundary_utils._RegionalAccessBoundaryData( + encoded_locations=fake_rab_encoded_locations, + expiry=_helpers.utcnow() + datetime.timedelta(hours=1), + cooldown_expiry=None, + cooldown_duration=_regional_access_boundary_utils.DEFAULT_REGIONAL_ACCESS_BOUNDARY_COOLDOWN, + ) + + # 1. Assert that the original instance is an async credential object assert isinstance(credentials, credentials_async.Credentials) + assert isinstance(credentials, CredentialsWithUniverseDomain) assert credentials.universe_domain == DEFAULT_UNIVERSE_DOMAIN assert not credentials._always_use_jwt_access + assert ( + credentials._rab_manager._data.encoded_locations + == fake_rab_encoded_locations + ) - # Transition to custom universe - custom_creds = credentials.with_universe_domain("custom.universe.domain") + # 2. Staying within the default universe preserves RAB state and async refresh manager + same_default = credentials.with_universe_domain(DEFAULT_UNIVERSE_DOMAIN) + assert isinstance(same_default, service_account.Credentials) + assert isinstance(same_default, credentials_async.Credentials) + assert ( + same_default._rab_manager._data.encoded_locations + == fake_rab_encoded_locations + ) + assert isinstance( + same_default._rab_manager.refresh_manager, + _regional_access_boundary_utils._AsyncRegionalAccessBoundaryRefreshManager, + ) - # 2. Assert that the copy retains async inheritance and subclass identity + # 3. Transitioning to a custom universe clears RAB data while retaining async refresh manager + custom_creds = credentials.with_universe_domain("custom.universe.domain") assert isinstance(custom_creds, service_account.Credentials) assert isinstance(custom_creds, credentials_async.Credentials) assert custom_creds.universe_domain == "custom.universe.domain" assert custom_creds._always_use_jwt_access is True - - # 3. Explicitly verify that its RAB manager retains the asynchronous refresh worker implementation assert isinstance( custom_creds._rab_manager.refresh_manager, _regional_access_boundary_utils._AsyncRegionalAccessBoundaryRefreshManager, ) assert custom_creds._rab_manager._data.encoded_locations is None + assert custom_creds._rab_manager._data.expiry is None - # Transition back to GDU - back_to_gdu = custom_creds.with_universe_domain(DEFAULT_UNIVERSE_DOMAIN) + # 4. Transitioning back to the default universe resets _always_use_jwt_access + # and keeps cleared RAB state (requiring a fresh lookup). + back_to_default = custom_creds.with_universe_domain(DEFAULT_UNIVERSE_DOMAIN) + assert isinstance(back_to_default, service_account.Credentials) + assert isinstance(back_to_default, credentials_async.Credentials) + assert back_to_default.universe_domain == DEFAULT_UNIVERSE_DOMAIN + assert back_to_default._always_use_jwt_access is False + assert back_to_default._rab_manager._data.encoded_locations is None - # 4. Confirm async credentials class is preserved on the return transition - assert isinstance(back_to_gdu, service_account.Credentials) - assert isinstance(back_to_gdu, credentials_async.Credentials) - assert back_to_gdu.universe_domain == DEFAULT_UNIVERSE_DOMAIN - assert back_to_gdu._always_use_jwt_access is False + # 5. Reject None or empty universe domain + for invalid_ud in (None, "", " "): + with pytest.raises( + exceptions.InvalidValue, match="Universe domain cannot be empty." + ): + credentials.with_universe_domain(invalid_ud) class TestIDTokenCredentials(object): @@ -508,6 +543,34 @@ def test_with_quota_project(self): new_credentials = credentials.with_quota_project("project-foo") assert new_credentials._quota_project_id == "project-foo" + def test_with_universe_domain(self): + """Async IDTokenCredentials inherits CredentialsWithUniverseDomain.""" + credentials = self.make_credentials() + assert isinstance(credentials, CredentialsWithUniverseDomain) + assert isinstance(credentials, credentials_async.Credentials) + + custom = credentials.with_universe_domain("custom.universe.domain") + assert isinstance(custom, service_account.IDTokenCredentials) + assert isinstance(custom, credentials_async.Credentials) + assert custom.universe_domain == "custom.universe.domain" + assert custom._use_iam_endpoint is True + assert ( + custom._iam_id_token_endpoint + == "https://iamcredentials.custom.universe.domain/v1/projects/-/serviceAccounts/{}:generateIdToken" + ) + + default = custom.with_universe_domain(DEFAULT_UNIVERSE_DOMAIN) + assert isinstance(default, service_account.IDTokenCredentials) + assert default.universe_domain == DEFAULT_UNIVERSE_DOMAIN + assert default._use_iam_endpoint is False + assert default._iam_id_token_endpoint == iam._IAM_IDTOKEN_ENDPOINT + + for invalid_ud in (None, "", " "): + with pytest.raises( + exceptions.InvalidValue, match="Universe domain cannot be empty." + ): + credentials.with_universe_domain(invalid_ud) + def test__make_authorization_grant_assertion(self): credentials = self.make_credentials() token = credentials._make_authorization_grant_assertion() From 82901e902aea8348bff4e46c4d22e2a7dc04b8cc Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Thu, 26 Nov 2026 19:01:30 +0000 Subject: [PATCH 14/17] clean up --- packages/google-auth/google/auth/_helpers.py | 20 ------------- .../google/oauth2/service_account.py | 6 ++-- packages/google-auth/tests/test__helpers.py | 29 ------------------- 3 files changed, 4 insertions(+), 51 deletions(-) diff --git a/packages/google-auth/google/auth/_helpers.py b/packages/google-auth/google/auth/_helpers.py index 2fda5843ca85..5599f2004f85 100644 --- a/packages/google-auth/google/auth/_helpers.py +++ b/packages/google-auth/google/auth/_helpers.py @@ -584,23 +584,3 @@ def response_log(logger: logging.Logger, response: Any) -> None: if is_logging_enabled(logger): json_response = _parse_response(response) _response_log_base(logger, json_response) - - -def validate_universe_domain( - universe_domain: Optional[str], *, allow_none: bool = False -) -> None: - """Validates that ``universe_domain`` is a non-empty string. - - Args: - universe_domain (Optional[str]): The universe domain to validate. - allow_none (bool): Whether ``None`` is permitted (allowing fallback - to the default universe domain). Defaults to ``False``. - - Raises: - google.auth.exceptions.InvalidValue: If ``universe_domain`` is not a - non-empty string (or is ``None`` when ``allow_none=False``). - """ - if universe_domain is None and allow_none: - return - if not isinstance(universe_domain, str) or not universe_domain.strip(): - raise exceptions.InvalidValue("Universe domain cannot be empty.") diff --git a/packages/google-auth/google/oauth2/service_account.py b/packages/google-auth/google/oauth2/service_account.py index c95bb60280d9..ef2e21c132d5 100644 --- a/packages/google-auth/google/oauth2/service_account.py +++ b/packages/google-auth/google/oauth2/service_account.py @@ -196,7 +196,8 @@ def __init__( self._token_uri = token_uri self._explicit_always_use_jwt_access = bool(always_use_jwt_access) self._always_use_jwt_access = always_use_jwt_access - _helpers.validate_universe_domain(universe_domain, allow_none=True) + if universe_domain is not None: + _helpers.validate_universe_domain(universe_domain) self._universe_domain = universe_domain or credentials.DEFAULT_UNIVERSE_DOMAIN # Check the normalized universe domain so None falls back to the @@ -676,7 +677,8 @@ def __init__( self._quota_project_id = quota_project_id self._use_iam_endpoint = False - _helpers.validate_universe_domain(universe_domain, allow_none=True) + if universe_domain is not None: + _helpers.validate_universe_domain(universe_domain) self._universe_domain = universe_domain or credentials.DEFAULT_UNIVERSE_DOMAIN self._iam_id_token_endpoint = iam._get_iam_idtoken_endpoint( self._universe_domain diff --git a/packages/google-auth/tests/test__helpers.py b/packages/google-auth/tests/test__helpers.py index 8980692e4f87..41fd4befb71c 100644 --- a/packages/google-auth/tests/test__helpers.py +++ b/packages/google-auth/tests/test__helpers.py @@ -652,35 +652,6 @@ def test_parse_response_none(): assert _helpers._parse_response(None) is None -@pytest.mark.parametrize("invalid_ud", [None, "", " ", "\t", "\n", 123, []]) -def test_validate_universe_domain_invalid_raises(invalid_ud): - with pytest.raises( - exceptions.InvalidValue, match="Universe domain cannot be empty." - ): - _helpers.validate_universe_domain(invalid_ud) - - -@pytest.mark.parametrize("invalid_ud", ["", " ", "\t", "\n", 123, []]) -def test_validate_universe_domain_allow_none_still_rejects_empty_and_non_str( - invalid_ud, -): - with pytest.raises( - exceptions.InvalidValue, match="Universe domain cannot be empty." - ): - _helpers.validate_universe_domain(invalid_ud, allow_none=True) - - -@pytest.mark.parametrize("valid_ud", ["googleapis.com", "myuniverse.goog"]) -def test_validate_universe_domain_valid(valid_ud): - # Does not raise with default allow_none=False or allow_none=True - _helpers.validate_universe_domain(valid_ud) - _helpers.validate_universe_domain(valid_ud, allow_none=True) - - -def test_validate_universe_domain_allow_none_accepts_none(): - _helpers.validate_universe_domain(None, allow_none=True) - - class TestUtcFromTimestamp: """Tests for the utcfromtimestamp utility function.""" From ed4ba4b8eb7ef8c2c48cb665d67046c879c05b18 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Thu, 26 Nov 2026 19:22:42 +0000 Subject: [PATCH 15/17] work in progress --- .../tests/oauth2/test_service_account.py | 21 ++++++++++++------- .../oauth2/test_service_account_async.py | 6 ++++-- 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/packages/google-auth/tests/oauth2/test_service_account.py b/packages/google-auth/tests/oauth2/test_service_account.py index 2e79c365d8bb..e9efbd79fdf2 100644 --- a/packages/google-auth/tests/oauth2/test_service_account.py +++ b/packages/google-auth/tests/oauth2/test_service_account.py @@ -224,7 +224,8 @@ def test_with_universe_domain_invalid_raises(self, invalid_ud): """Explicitly passing None, empty, whitespace, or non-str raises InvalidValue.""" credentials = self.make_credentials() with pytest.raises( - exceptions.InvalidValue, match="Universe domain cannot be empty." + exceptions.InvalidValue, + match="Universe domain must be a valid non-empty domain string.", ): credentials.with_universe_domain(invalid_ud) @@ -254,7 +255,8 @@ def test_constructor_none_universe_domain_jwt_access(self): def test_constructor_empty_universe_domain_raises(self, invalid_ud): """Empty, whitespace, or non-str universe_domain in constructor raises.""" with pytest.raises( - exceptions.InvalidValue, match="Universe domain cannot be empty." + exceptions.InvalidValue, + match="Universe domain must be a valid non-empty domain string.", ): service_account.Credentials( SIGNER, @@ -320,7 +322,8 @@ def test_from_service_account_info_explicit_empty_universe_domain_raises( info["universe_domain"] = FAKE_UNIVERSE_DOMAIN with pytest.raises( - exceptions.InvalidValue, match="Universe domain cannot be empty." + exceptions.InvalidValue, + match="Universe domain must be a valid non-empty domain string.", ): service_account.Credentials.from_service_account_info( info, universe_domain=empty_ud @@ -335,7 +338,8 @@ def test_from_service_account_info_empty_universe_domain_in_json_raises( info["universe_domain"] = empty_ud with pytest.raises( - exceptions.InvalidValue, match="Universe domain cannot be empty." + exceptions.InvalidValue, + match="Universe domain must be a valid non-empty domain string.", ): service_account.Credentials.from_service_account_info(info) @@ -1029,7 +1033,8 @@ def test_id_token_from_service_account_info_explicit_empty_universe_domain_raise info["universe_domain"] = FAKE_UNIVERSE_DOMAIN with pytest.raises( - exceptions.InvalidValue, match="Universe domain cannot be empty." + exceptions.InvalidValue, + match="Universe domain must be a valid non-empty domain string.", ): service_account.IDTokenCredentials.from_service_account_info( info, @@ -1046,7 +1051,8 @@ def test_id_token_from_service_account_info_empty_universe_domain_in_json_raises info["universe_domain"] = empty_ud with pytest.raises( - exceptions.InvalidValue, match="Universe domain cannot be empty." + exceptions.InvalidValue, + match="Universe domain must be a valid non-empty domain string.", ): service_account.IDTokenCredentials.from_service_account_info( info, target_audience=self.TARGET_AUDIENCE @@ -1269,7 +1275,8 @@ def test_id_token_with_universe_domain_invalid_raises(self, invalid_ud): """Explicitly passing None, empty, whitespace, or non-str raises InvalidValue.""" credentials = self.make_credentials() with pytest.raises( - exceptions.InvalidValue, match="Universe domain cannot be empty." + exceptions.InvalidValue, + match="Universe domain must be a valid non-empty domain string.", ): credentials.with_universe_domain(invalid_ud) 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 fabd1fe98ba1..5a31e3943975 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 @@ -459,7 +459,8 @@ def test_with_universe_domain(self): # 5. Reject None or empty universe domain for invalid_ud in (None, "", " "): with pytest.raises( - exceptions.InvalidValue, match="Universe domain cannot be empty." + exceptions.InvalidValue, + match="Universe domain must be a valid non-empty domain string.", ): credentials.with_universe_domain(invalid_ud) @@ -567,7 +568,8 @@ def test_with_universe_domain(self): for invalid_ud in (None, "", " "): with pytest.raises( - exceptions.InvalidValue, match="Universe domain cannot be empty." + exceptions.InvalidValue, + match="Universe domain must be a valid non-empty domain string.", ): credentials.with_universe_domain(invalid_ud) From 1d35469a311b9f2a7c71f5f8d843240ebc0cbc18 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Thu, 26 Nov 2026 19:24:24 +0000 Subject: [PATCH 16/17] fix(auth): clear cached jwt_credentials on with_claims in service_account --- .../google-auth/google/oauth2/service_account.py | 2 ++ .../google-auth/tests/oauth2/test_service_account.py | 12 ++++++++++++ 2 files changed, 14 insertions(+) diff --git a/packages/google-auth/google/oauth2/service_account.py b/packages/google-auth/google/oauth2/service_account.py index ef2e21c132d5..43c51cd0bc79 100644 --- a/packages/google-auth/google/oauth2/service_account.py +++ b/packages/google-auth/google/oauth2/service_account.py @@ -412,6 +412,8 @@ def with_claims(self, additional_claims): new_additional_claims.update(additional_claims or {}) cred = self._make_copy() cred._additional_claims = new_additional_claims + # Clear cached JWT credentials so they regenerate with the new claims + cred._jwt_credentials = None return cred @_helpers.copy_docstring(credentials.CredentialsWithQuotaProject) diff --git a/packages/google-auth/tests/oauth2/test_service_account.py b/packages/google-auth/tests/oauth2/test_service_account.py index e9efbd79fdf2..3bab54ef9022 100644 --- a/packages/google-auth/tests/oauth2/test_service_account.py +++ b/packages/google-auth/tests/oauth2/test_service_account.py @@ -917,6 +917,18 @@ 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_with_claims_clears_jwt_credentials(self): + """with_claims clears cached self-signed JWT credentials so stale JWT state is not reused.""" + credentials = self.make_credentials(universe_domain=FAKE_UNIVERSE_DOMAIN) + credentials._create_self_signed_jwt(f"https://compute.{FAKE_UNIVERSE_DOMAIN}/") + assert credentials._jwt_credentials is not None + + updated = credentials.with_claims({"custom_key": "custom_val"}) + + # FAILS WITHOUT FIX: + # _make_copy() cloned _jwt_credentials, so updated._jwt_credentials is not None. + assert updated._jwt_credentials is None + class TestIDTokenCredentials(object): SERVICE_ACCOUNT_EMAIL = "service-account@example.com" From a12460a9b2be99e302ba51dd0fe87700c9299831 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Thu, 26 Nov 2026 19:34:07 +0000 Subject: [PATCH 17/17] work in progress --- packages/google-auth/google/auth/credentials.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/google-auth/google/auth/credentials.py b/packages/google-auth/google/auth/credentials.py index 7a76f74f742b..9abbaee41874 100644 --- a/packages/google-auth/google/auth/credentials.py +++ b/packages/google-auth/google/auth/credentials.py @@ -417,7 +417,9 @@ def _update_regional_access_boundary_for_universe( if universe_domain == DEFAULT_UNIVERSE_DOMAIN: self._copy_regional_access_boundary_manager(target_credentials) else: - target_credentials._rab_manager.clear_data() + rab_manager = getattr(target_credentials, "_rab_manager", None) + if rab_manager is not None: + rab_manager.clear_data() def _set_regional_access_boundary(self, initial_boundary): """Applies the regional_access_boundary provided via the initial_boundary on these