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..89858165433b 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,16 @@ 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.""" + 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): """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 607d56654b45..9abbaee41874 100644 --- a/packages/google-auth/google/auth/credentials.py +++ b/packages/google-auth/google/auth/credentials.py @@ -408,6 +408,19 @@ 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 + ): + """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: + 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 credentials. This is intended for internal use only as an invalid 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 0c0c1f176191..4e4e94842733 100644 --- a/packages/google-auth/google/auth/jwt.py +++ b/packages/google-auth/google/auth/jwt.py @@ -528,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,10 +603,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/service_account.py b/packages/google-auth/google/oauth2/service_account.py index 6744e6f14d9b..43c51cd0bc79 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 @@ -193,10 +194,15 @@ 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 + if universe_domain is not None: + _helpers.validate_universe_domain(universe_domain) self._universe_domain = universe_domain or credentials.DEFAULT_UNIVERSE_DOMAIN - if universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN: + # 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 self._jwt_credentials = None @@ -224,14 +230,16 @@ 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 + # 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, 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, ) @@ -293,7 +301,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, @@ -304,12 +312,19 @@ 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, ) cred._cred_file_path = self._cred_file_path - self._copy_regional_access_boundary_manager(cred) + # 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() + if _copy_rab: + self._copy_regional_access_boundary_manager(cred) return cred @_helpers.copy_docstring(credentials.Scoped) @@ -317,6 +332,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): @@ -340,15 +357,26 @@ 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. + cred._jwt_credentials = None return cred @_helpers.copy_docstring(credentials.CredentialsWithUniverseDomain) def with_universe_domain(self, universe_domain): - cred = self._make_copy() + _helpers.validate_universe_domain(universe_domain) + cred = self._make_copy(_copy_rab=False) cred._universe_domain = universe_domain - if universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN: - cred._always_use_jwt_access = True + cred._always_use_jwt_access = ( + 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 + # RAB state is only valid for the default universe domain. + self._update_regional_access_boundary_for_universe(cred, cred._universe_domain) return cred def with_subject(self, subject): @@ -363,6 +391,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): @@ -381,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) @@ -560,6 +593,7 @@ class IDTokenCredentials( credentials.Signing, credentials.CredentialsWithQuotaProject, credentials.CredentialsWithTokenUri, + credentials.CredentialsWithUniverseDomain, ): """Open ID Connect ID Token-based service account credentials. @@ -645,14 +679,12 @@ def __init__( self._quota_project_id = quota_project_id self._use_iam_endpoint = False - if not universe_domain: - 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 + 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 ) - if self._universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN: self._use_iam_endpoint = True @@ -679,7 +711,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"]) - if "universe_domain" in info: + # 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) @@ -791,6 +826,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): + _helpers.validate_universe_domain(universe_domain) + cred = self._make_copy() + 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 + ) + 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..3bab54ef9022 100644 --- a/packages/google-auth/tests/oauth2/test_service_account.py +++ b/packages/google-auth/tests/oauth2/test_service_account.py @@ -19,8 +19,19 @@ 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 import ( + _helpers, + _regional_access_boundary_utils, + crypt, + exceptions, + iam, + jwt, + transport, +) +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 +101,170 @@ 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 + assert copied._jwt_credentials.universe_domain == FAKE_UNIVERSE_DOMAIN + + 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_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 + + # 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 = _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.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.""" + 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 + + 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("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( + exceptions.InvalidValue, + match="Universe domain must be a valid non-empty domain string.", + ): + credentials.with_universe_domain(invalid_ud) + + 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 + 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=None, + ) + assert credentials.universe_domain == DEFAULT_UNIVERSE_DOMAIN + assert not credentials._always_use_jwt_access + + @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( + exceptions.InvalidValue, + match="Universe domain must be a valid non-empty domain string.", + ): + service_account.Credentials( + SIGNER, + self.SERVICE_ACCOUNT_EMAIL, + self.TOKEN_URI, + universe_domain=invalid_ud, + ) + def test_from_service_account_info(self): credentials = service_account.Credentials.from_service_account_info( SERVICE_ACCOUNT_INFO @@ -115,6 +284,77 @@ 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 + + def test_from_service_account_info_explicit_none_universe_domain_overrides_info( + self, + ): + """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=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 InvalidValue.""" + info = SERVICE_ACCOUNT_INFO.copy() + info["universe_domain"] = FAKE_UNIVERSE_DOMAIN + + with pytest.raises( + 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 + ) + + @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 must be a valid non-empty domain string.", + ): + 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"] @@ -677,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" @@ -703,6 +955,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 +987,89 @@ 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() + + def test_from_service_account_info_explicit_none_universe_domain_overrides_info( + self, + ): + """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=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 InvalidValue.""" + info = SERVICE_ACCOUNT_INFO.copy() + info["universe_domain"] = FAKE_UNIVERSE_DOMAIN + + with pytest.raises( + 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, + 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 must be a valid non-empty domain string.", + ): + 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() @@ -807,6 +1147,21 @@ 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 + 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 + def test__make_authorization_grant_assertion(self): credentials = self.make_credentials() token = credentials._make_authorization_grant_assertion() @@ -926,3 +1281,37 @@ def test_before_request_refreshes(self, id_token_jwt_grant): # Credentials should now be valid. assert credentials.valid + + @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( + exceptions.InvalidValue, + match="Universe domain must be a valid non-empty domain string.", + ): + 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.""" + 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 + 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.""" + info = SERVICE_ACCOUNT_INFO.copy() + info.pop("universe_domain", None) + + with mock.patch.object( + service_account.IDTokenCredentials, "__init__", return_value=None + ) as mock_init: + 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_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 d3606c9641e0..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 @@ -17,7 +17,21 @@ 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, + exceptions, + iam, + jwt, + transport, +) +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 @@ -385,6 +399,71 @@ 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.""" + fake_rab_encoded_locations = "0xA30" + credentials = self.make_credentials() + + 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 + ) + + # 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, + ) + + # 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 + 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 + + # 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 + + # 5. Reject None or empty universe domain + for invalid_ud in (None, "", " "): + with pytest.raises( + exceptions.InvalidValue, + match="Universe domain must be a valid non-empty domain string.", + ): + credentials.with_universe_domain(invalid_ud) + class TestIDTokenCredentials(object): SERVICE_ACCOUNT_EMAIL = "service-account@example.com" @@ -465,6 +544,35 @@ 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 must be a valid non-empty domain string.", + ): + credentials.with_universe_domain(invalid_ud) + def test__make_authorization_grant_assertion(self): credentials = self.make_credentials() token = credentials._make_authorization_grant_assertion()