From 7a30b38bfdc29044f97b52e70794d86bd7ab325c Mon Sep 17 00:00:00 2001 From: ohmayr Date: Wed, 25 Nov 2026 23:49:03 +0000 Subject: [PATCH 1/2] fix(auth): propagate top-level universe_domain in impersonated creds Credentials.from_impersonated_service_account_info() ignored a top-level universe_domain field and delegated _universe_domain solely to source_credentials. When source_credentials omitted universe_domain, impersonated credentials defaulted to googleapis.com and sent source tokens to iamcredentials.googleapis.com. Add an optional universe_domain parameter to Credentials.__init__() (validated via _helpers.validate_universe_domain() and compared against source_credentials.universe_domain via _helpers.compare_universe_domains()), forward it in _make_copy(), and propagate top-level universe_domain into a shallow copy of source_credentials_info in from_impersonated_service_account_info() without mutating caller input. b/589828921 --- .../google/auth/impersonated_credentials.py | 30 +++- .../tests/test_impersonated_credentials.py | 168 ++++++++++++++++++ 2 files changed, 196 insertions(+), 2 deletions(-) diff --git a/packages/google-auth/google/auth/impersonated_credentials.py b/packages/google-auth/google/auth/impersonated_credentials.py index f9faab5e7336..7ba8d4521061 100644 --- a/packages/google-auth/google/auth/impersonated_credentials.py +++ b/packages/google-auth/google/auth/impersonated_credentials.py @@ -212,6 +212,7 @@ def __init__( quota_project_id=None, iam_endpoint_override=None, trust_boundary=None, + universe_domain=None, ): """ Args: @@ -243,10 +244,19 @@ def __init__( if you wish to impersonate as a user. This feature is useful when using domain wide delegation. trust_boundary (Mapping[str,str]): A credential trust boundary. + universe_domain (Optional[str]): The universe domain value. If + provided, it must match ``source_credentials.universe_domain``. + + Raises: + InvalidValue: If ``universe_domain`` is invalid or does not match + ``source_credentials.universe_domain``. """ super(Credentials, self).__init__() + if universe_domain is not None: + _helpers.validate_universe_domain(universe_domain) + self._source_credentials = copy.copy(source_credentials) # Service account source credentials must have the _IAM_SCOPE # added to refresh correctly. User credentials cannot have @@ -263,7 +273,10 @@ def __init__( ): self._source_credentials._create_self_signed_jwt(None) - self._universe_domain = source_credentials.universe_domain + source_universe = self._source_credentials.universe_domain + if universe_domain is not None: + _helpers.compare_universe_domains(universe_domain, source_universe) + self._universe_domain = source_universe self._target_principal = target_principal self._target_scopes = target_scopes self._delegates = delegates @@ -450,6 +463,7 @@ def _make_copy(self): quota_project_id=self._quota_project_id, iam_endpoint_override=self._iam_endpoint_override, trust_boundary=self._trust_boundary, + universe_domain=self._universe_domain, ) cred._cred_file_path = self._cred_file_path self._copy_regional_access_boundary_manager(cred) @@ -491,11 +505,22 @@ def from_impersonated_service_account_info(cls, info, scopes=None): Raises: InvalidType: If the info["source_credentials"] are not a supported impersonation type - InvalidValue: If the info["service_account_impersonation_url"] is not in the expected format. + InvalidValue: If ``info`` has an invalid or conflicting + ``universe_domain`` or ``service_account_impersonation_url``. ValueError: If the info is not in the expected format. """ source_credentials_info = info.get("source_credentials") + universe_domain = info.get("universe_domain") + if ( + universe_domain is not None + and source_credentials_info.get("universe_domain") is None + ): + source_credentials_info = { + **source_credentials_info, + "universe_domain": universe_domain, + } + source_credentials_type = source_credentials_info.get("type") if source_credentials_type == _SOURCE_CREDENTIAL_AUTHORIZED_USER_TYPE: from google.oauth2 import credentials @@ -545,6 +570,7 @@ def from_impersonated_service_account_info(cls, info, scopes=None): delegates, quota_project_id=quota_project_id, trust_boundary=trust_boundary, + universe_domain=universe_domain, ) diff --git a/packages/google-auth/tests/test_impersonated_credentials.py b/packages/google-auth/tests/test_impersonated_credentials.py index 2cfcbf150f86..ff1d137dd21e 100644 --- a/packages/google-auth/tests/test_impersonated_credentials.py +++ b/packages/google-auth/tests/test_impersonated_credentials.py @@ -1079,3 +1079,171 @@ def test_sign_jwt_request_invalid_response_error(self): == "Unable to acquire impersonated credentials: No signed JWT in response." ) assert excinfo.value.args[1] == "invalid_data" + + @pytest.mark.parametrize( + "source_info", + [ + pytest.param( + IMPERSONATED_SERVICE_ACCOUNT_AUTHORIZED_USER_SOURCE_INFO[ + "source_credentials" + ], + id="authorized_user_source", + ), + pytest.param( + SERVICE_ACCOUNT_INFO, + id="service_account_source", + ), + ], + ) + def test_from_impersonated_service_account_info_top_level_universe_domain( + self, source_info + ): + info = copy.deepcopy(IMPERSONATED_SERVICE_ACCOUNT_AUTHORIZED_USER_SOURCE_INFO) + info["source_credentials"] = copy.deepcopy(source_info) + info["universe_domain"] = "example.com" + info["service_account_impersonation_url"] = ( + "https://iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/some@email.com:generateAccessToken" + ) + original_source = copy.deepcopy(info["source_credentials"]) + + creds = ( + impersonated_credentials.Credentials.from_impersonated_service_account_info( + info + ) + ) + + assert creds.universe_domain == "example.com" + assert creds._source_credentials.universe_domain == "example.com" + # Caller's source_credentials dict must not be mutated. + assert info["source_credentials"] == original_source + assert creds.with_quota_project("qp").universe_domain == "example.com" + + expire_time = ( + _helpers.utcnow().replace(microsecond=0) + datetime.timedelta(seconds=500) + ).isoformat("T") + "Z" + request = self.make_request( + data=json.dumps({"accessToken": "token", "expireTime": expire_time}), + status=http_client.OK, + ) + with mock.patch.object(creds._source_credentials, "refresh"): + creds._source_credentials.token = "source-token" + creds._source_credentials.expiry = _helpers.utcnow() + datetime.timedelta( + seconds=500 + ) + creds.refresh(request) + + assert ( + request.call_args[1]["url"] == "https://iamcredentials.example.com" + "/v1/projects/-/serviceAccounts/some@email.com:generateAccessToken" + ) + + def test_from_impersonated_service_account_info_matching_universes(self): + info = copy.deepcopy(IMPERSONATED_SERVICE_ACCOUNT_AUTHORIZED_USER_SOURCE_INFO) + info["universe_domain"] = "example.com" + info["source_credentials"]["universe_domain"] = "example.com" + info["service_account_impersonation_url"] = ( + "https://iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/some@email.com:generateAccessToken" + ) + + creds = ( + impersonated_credentials.Credentials.from_impersonated_service_account_info( + info + ) + ) + assert creds.universe_domain == "example.com" + assert creds._source_credentials.universe_domain == "example.com" + + def test_from_impersonated_service_account_info_source_only_universe(self): + info = copy.deepcopy(IMPERSONATED_SERVICE_ACCOUNT_AUTHORIZED_USER_SOURCE_INFO) + info["source_credentials"]["universe_domain"] = "example.com" + info["service_account_impersonation_url"] = ( + "https://iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/some@email.com:generateAccessToken" + ) + + creds = ( + impersonated_credentials.Credentials.from_impersonated_service_account_info( + info + ) + ) + assert creds.universe_domain == "example.com" + assert creds._source_credentials.universe_domain == "example.com" + + @pytest.mark.parametrize( + "top_level_universe,source_universe,expected_match", + [ + pytest.param( + "googleapis.com", + "other.com", + "does not match the expected universe domain", + id="top_level_conflicts_with_source", + ), + pytest.param( + "", + None, + "must be a valid non-empty domain string", + id="empty_top_level_universe", + ), + pytest.param( + " example.com ", + None, + "must be a valid non-empty domain string", + id="whitespace_top_level_universe", + ), + pytest.param( + 123, + None, + "must be a valid non-empty domain string", + id="non_string_top_level_universe", + ), + ], + ) + def test_from_impersonated_service_account_info_universe_validation_errors( + self, top_level_universe, source_universe, expected_match + ): + info = copy.deepcopy(IMPERSONATED_SERVICE_ACCOUNT_AUTHORIZED_USER_SOURCE_INFO) + if top_level_universe is not None: + info["universe_domain"] = top_level_universe + if source_universe is not None: + info["source_credentials"]["universe_domain"] = source_universe + + with pytest.raises(exceptions.InvalidValue, match=expected_match): + impersonated_credentials.Credentials.from_impersonated_service_account_info( + info + ) + + def test_constructor_universe_domain_validation(self): + source = service_account.Credentials( + SIGNER, "some@email.com", TOKEN_URI, universe_domain="example.com" + ) + creds = impersonated_credentials.Credentials( + source_credentials=source, + target_principal=self.TARGET_PRINCIPAL, + target_scopes=self.TARGET_SCOPES, + universe_domain="example.com", + ) + assert creds.universe_domain == "example.com" + + with pytest.raises( + exceptions.InvalidValue, + match="does not match the expected universe domain", + ): + impersonated_credentials.Credentials( + source_credentials=source, + target_principal=self.TARGET_PRINCIPAL, + target_scopes=self.TARGET_SCOPES, + universe_domain="other.com", + ) + + with pytest.raises( + exceptions.InvalidValue, + match="must be a valid non-empty domain string", + ): + impersonated_credentials.Credentials( + source_credentials=source, + target_principal=self.TARGET_PRINCIPAL, + target_scopes=self.TARGET_SCOPES, + universe_domain=" ", + ) From dde1e837c56116e560d7d2a61296506fb8f7c055 Mon Sep 17 00:00:00 2001 From: ohmayr Date: Mon, 30 Nov 2026 21:54:36 +0000 Subject: [PATCH 2/2] fix(auth): validate source universe_domain in impersonated creds Validate source_credentials.universe_domain in Credentials.__init__ even when universe_domain is omitted, defaulting explicit None or missing attributes to DEFAULT_UNIVERSE_DOMAIN without coercing empty strings. Validate nested source_credentials["universe_domain"] in from_impersonated_service_account_info before constructing source credentials, document the early universe_domain validation check, and add external_account_authorized_user propagation test coverage. --- .../google/auth/impersonated_credentials.py | 16 ++-- .../tests/test_impersonated_credentials.py | 81 +++++++++++++++++++ 2 files changed, 92 insertions(+), 5 deletions(-) diff --git a/packages/google-auth/google/auth/impersonated_credentials.py b/packages/google-auth/google/auth/impersonated_credentials.py index 7ba8d4521061..76fbacf750c3 100644 --- a/packages/google-auth/google/auth/impersonated_credentials.py +++ b/packages/google-auth/google/auth/impersonated_credentials.py @@ -254,6 +254,8 @@ def __init__( super(Credentials, self).__init__() + # Validate early to fail fast before cloning/scoping source_credentials + # or triggering a metadata lookup on uncached compute_engine.Credentials. if universe_domain is not None: _helpers.validate_universe_domain(universe_domain) @@ -273,9 +275,13 @@ def __init__( ): self._source_credentials._create_self_signed_jwt(None) - source_universe = self._source_credentials.universe_domain + source_universe = getattr(self._source_credentials, "universe_domain", None) + if source_universe is None: + source_universe = credentials.DEFAULT_UNIVERSE_DOMAIN if universe_domain is not None: _helpers.compare_universe_domains(universe_domain, source_universe) + else: + _helpers.validate_universe_domain(source_universe) self._universe_domain = source_universe self._target_principal = target_principal self._target_scopes = target_scopes @@ -512,10 +518,10 @@ def from_impersonated_service_account_info(cls, info, scopes=None): source_credentials_info = info.get("source_credentials") universe_domain = info.get("universe_domain") - if ( - universe_domain is not None - and source_credentials_info.get("universe_domain") is None - ): + source_universe_domain = source_credentials_info.get("universe_domain") + if source_universe_domain is not None: + _helpers.validate_universe_domain(source_universe_domain) + elif universe_domain is not None: source_credentials_info = { **source_credentials_info, "universe_domain": universe_domain, diff --git a/packages/google-auth/tests/test_impersonated_credentials.py b/packages/google-auth/tests/test_impersonated_credentials.py index ff1d137dd21e..777a2d3dd523 100644 --- a/packages/google-auth/tests/test_impersonated_credentials.py +++ b/packages/google-auth/tests/test_impersonated_credentials.py @@ -22,6 +22,7 @@ import pytest # type: ignore from google.auth import _helpers, crypt, exceptions, impersonated_credentials, transport +from google.auth import credentials as auth_credentials from google.auth.impersonated_credentials import Credentials from google.oauth2 import credentials, service_account @@ -31,6 +32,9 @@ PRIVATE_KEY_BYTES = fh.read() SERVICE_ACCOUNT_JSON_FILE = os.path.join(DATA_DIR, "service_account.json") +EXTERNAL_ACCOUNT_AUTHORIZED_USER_JSON_FILE = os.path.join( + DATA_DIR, "external_account_authorized_user.json" +) IMPERSONATED_SERVICE_ACCOUNT_AUTHORIZED_USER_SOURCE_FILE = os.path.join( DATA_DIR, "impersonated_service_account_authorized_user_source.json" ) @@ -48,6 +52,9 @@ with open(SERVICE_ACCOUNT_JSON_FILE, "rb") as fh: SERVICE_ACCOUNT_INFO = json.load(fh) +with open(EXTERNAL_ACCOUNT_AUTHORIZED_USER_JSON_FILE, "rb") as fh: + EXTERNAL_ACCOUNT_AUTHORIZED_USER_INFO = json.load(fh) + with open(IMPERSONATED_SERVICE_ACCOUNT_AUTHORIZED_USER_SOURCE_FILE, "rb") as fh: IMPERSONATED_SERVICE_ACCOUNT_AUTHORIZED_USER_SOURCE_INFO = json.load(fh) @@ -1093,6 +1100,10 @@ def test_sign_jwt_request_invalid_response_error(self): SERVICE_ACCOUNT_INFO, id="service_account_source", ), + pytest.param( + EXTERNAL_ACCOUNT_AUTHORIZED_USER_INFO, + id="external_account_authorized_user_source", + ), ], ) def test_from_impersonated_service_account_info_top_level_universe_domain( @@ -1247,3 +1258,73 @@ def test_constructor_universe_domain_validation(self): target_scopes=self.TARGET_SCOPES, universe_domain=" ", ) + + @pytest.mark.parametrize( + "top_level_universe,source_universe", + [ + pytest.param(None, "", id="empty_source_universe"), + pytest.param("googleapis.com", "", id="default_top_level_empty_source"), + pytest.param("example.com", "", id="custom_top_level_empty_source"), + pytest.param(None, " ", id="whitespace_source_universe"), + pytest.param( + None, "googleapis.com@testdomain.com", id="userinfo_injection_source" + ), + pytest.param(None, 123, id="non_string_source_universe"), + ], + ) + def test_from_impersonated_service_account_info_invalid_source_universe_domain( + self, top_level_universe, source_universe + ): + info = copy.deepcopy(IMPERSONATED_SERVICE_ACCOUNT_AUTHORIZED_USER_SOURCE_INFO) + if top_level_universe is None: + info.pop("universe_domain", None) + else: + info["universe_domain"] = top_level_universe + info["source_credentials"]["universe_domain"] = source_universe + + with pytest.raises( + exceptions.InvalidValue, + match="must be a valid non-empty domain string", + ): + impersonated_credentials.Credentials.from_impersonated_service_account_info( + info + ) + + @pytest.mark.parametrize( + "invalid_source_universe", + [ + pytest.param(" ", id="whitespace"), + pytest.param("googleapis.com@testdomain.com", id="userinfo_injection"), + ], + ) + def test_constructor_invalid_source_universe_domain_when_universe_omitted( + self, invalid_source_universe + ): + source = service_account.Credentials( + SIGNER, "some@email.com", TOKEN_URI, universe_domain=invalid_source_universe + ) + + with pytest.raises( + exceptions.InvalidValue, + match="must be a valid non-empty domain string", + ): + impersonated_credentials.Credentials( + source_credentials=source, + target_principal=self.TARGET_PRINCIPAL, + target_scopes=self.TARGET_SCOPES, + ) + + def test_impersonated_credentials_source_universe_none_defaults_to_default_universe( + self, + ): + source = mock.Mock(spec=["universe_domain", "refresh", "apply", "token_state"]) + source.universe_domain = None + source.token_state = auth_credentials.TokenState.FRESH + + creds = impersonated_credentials.Credentials( + source_credentials=source, + target_principal=self.TARGET_PRINCIPAL, + target_scopes=self.TARGET_SCOPES, + ) + + assert creds.universe_domain == auth_credentials.DEFAULT_UNIVERSE_DOMAIN