From 7a30b38bfdc29044f97b52e70794d86bd7ab325c Mon Sep 17 00:00:00 2001 From: ohmayr Date: Wed, 25 Nov 2026 23:49:03 +0000 Subject: [PATCH 1/3] 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 69f91b96008839e66245a5948723ef704fb73621 Mon Sep 17 00:00:00 2001 From: ohmayr Date: Wed, 25 Nov 2026 23:50:36 +0000 Subject: [PATCH 2/3] fix(auth): validate and use service_account_impersonation_url host Credentials.from_impersonated_service_account_info() sliced the target principal out of service_account_impersonation_url and discarded the URL's host and origin. Impersonated configs targeting a regional, custom-universe, or proxy endpoint therefore fell back to iamcredentials.googleapis.com and could bypass universe consistency checks. Validate service_account_impersonation_url with _parse_impersonation_url() and extract Google IAM Credentials host universes with _extract_universe_from_iam_host(). Reuse _helpers.compare_universe_domains() and _helpers.has_default_universe_host() to enforce host-vs-universe consistency, infer non-default universes when omitted, and pass iam_endpoint_override for non-default URLs while keeping mTLS selection intact for the standard default URL. b/589828921 --- .../google/auth/impersonated_credentials.py | 115 ++++++- .../tests/test_impersonated_credentials.py | 289 ++++++++++++++++++ 2 files changed, 393 insertions(+), 11 deletions(-) diff --git a/packages/google-auth/google/auth/impersonated_credentials.py b/packages/google-auth/google/auth/impersonated_credentials.py index 7ba8d4521061..56dcb514d0aa 100644 --- a/packages/google-auth/google/auth/impersonated_credentials.py +++ b/packages/google-auth/google/auth/impersonated_credentials.py @@ -30,6 +30,8 @@ import http.client as http_client import json import logging +import re +import urllib.parse from datetime import datetime from typing import TYPE_CHECKING, Optional @@ -63,6 +65,60 @@ "external_account_authorized_user" ) +_DNS_LABEL = r"[a-z0-9](?:[a-z0-9-]*[a-z0-9])?" +_IAM_HOST_PATTERN = re.compile( + rf"^(?:{_DNS_LABEL}[.-])?iamcredentials" + rf"(?:-{_DNS_LABEL}\.p|\.p|\.{_DNS_LABEL}\.rep(?:\.mtls)?|\.mtls)?" + rf"\.({_DNS_LABEL}(?:\.{_DNS_LABEL})+)$" +) + + +def _extract_universe_from_iam_host(hostname): + """Extracts the universe domain from a Google IAM Credentials hostname. + + Recognizes standard global, regional (``-iamcredentials.`` or + ``.iamcredentials.``), REP + (``iamcredentials..rep[.mtls].``), PSC + (``iamcredentials[-].p.``), and mTLS + (``iamcredentials.mtls.``) hostnames. Returns ``None`` for custom + proxy hostnames. + """ + match = _IAM_HOST_PATTERN.fullmatch(hostname.lower()) + return match.group(1) if match else None + + +def _parse_impersonation_url(impersonation_url): + """Validates an impersonation URL and extracts ``(target_principal, hostname)``.""" + error_msg = f"Cannot extract target principal from {impersonation_url}" + if ( + not isinstance(impersonation_url, str) + or "#" in impersonation_url + or any(ch.isspace() or ord(ch) < 0x20 for ch in impersonation_url) + ): + raise exceptions.InvalidValue(error_msg) + try: + parsed = urllib.parse.urlsplit(impersonation_url) + hostname = (parsed.hostname or "").removesuffix(".") + _ = parsed.port + except ValueError as exc: + raise exceptions.InvalidValue(error_msg) from exc + + start_index = parsed.path.rfind("/") + if ( + parsed.scheme != "https" + or not hostname + or "@" in parsed.netloc + or not parsed.path.endswith(":generateAccessToken") + or start_index == -1 + ): + raise exceptions.InvalidValue(error_msg) + + target_principal = parsed.path[start_index + 1 : -len(":generateAccessToken")] + if not target_principal: + raise exceptions.InvalidValue(error_msg) + + return target_principal, hostname + def _make_iam_token_request( request, @@ -511,7 +567,36 @@ def from_impersonated_service_account_info(cls, info, scopes=None): """ source_credentials_info = info.get("source_credentials") + impersonation_url = info.get("service_account_impersonation_url") + target_principal, url_host = _parse_impersonation_url(impersonation_url) + url_universe = _extract_universe_from_iam_host(url_host) + universe_domain = info.get("universe_domain") + explicit_universe = ( + universe_domain + if universe_domain is not None + else source_credentials_info.get("universe_domain") + ) + if explicit_universe is not None: + _helpers.validate_universe_domain(explicit_universe) + if url_universe is not None: + _helpers.compare_universe_domains( + explicit_universe.lower(), url_universe + ) + elif ( + explicit_universe.lower() != credentials.DEFAULT_UNIVERSE_DOMAIN + and _helpers.has_default_universe_host(f"https://{url_host}") + ): + raise exceptions.InvalidValue( + f"Non-default universe domain ({explicit_universe}) cannot " + f"use default-universe impersonation URL host ({url_host})." + ) + elif ( + url_universe is not None + and url_universe != credentials.DEFAULT_UNIVERSE_DOMAIN + ): + universe_domain = url_universe + if ( universe_domain is not None and source_credentials_info.get("universe_domain") is None @@ -523,10 +608,12 @@ def from_impersonated_service_account_info(cls, info, scopes=None): source_credentials_type = source_credentials_info.get("type") if source_credentials_type == _SOURCE_CREDENTIAL_AUTHORIZED_USER_TYPE: - from google.oauth2 import credentials + from google.oauth2 import credentials as oauth2_credentials - source_credentials = credentials.Credentials.from_authorized_user_info( - source_credentials_info + source_credentials = ( + oauth2_credentials.Credentials.from_authorized_user_info( + source_credentials_info + ) ) elif source_credentials_type == _SOURCE_CREDENTIAL_SERVICE_ACCOUNT_TYPE: from google.oauth2 import service_account @@ -550,25 +637,31 @@ def from_impersonated_service_account_info(cls, info, scopes=None): ) ) - impersonation_url = info.get("service_account_impersonation_url") - start_index = impersonation_url.rfind("/") - end_index = impersonation_url.find(":generateAccessToken") - if start_index == -1 or end_index == -1 or start_index > end_index: - raise exceptions.InvalidValue( - "Cannot extract target principal from {}".format(impersonation_url) - ) - target_principal = impersonation_url[start_index + 1 : end_index] delegates = info.get("delegates") quota_project_id = info.get("quota_project_id") scopes = scopes or info.get("scopes") trust_boundary = info.get("trust_boundary") + # Leave iam_endpoint_override unset for the exact standard default URL + # so mTLS endpoint selection via iam._IAM_ENDPOINT stays intact; keep + # the override for regional, custom-universe, and proxy URLs. + default_impersonation_url = ( + "https://iamcredentials.{}/v1/projects/-/serviceAccounts/{}" + ":generateAccessToken" + ).format(credentials.DEFAULT_UNIVERSE_DOMAIN, target_principal) + iam_endpoint_override = ( + None + if impersonation_url == default_impersonation_url + else impersonation_url + ) + return cls( source_credentials, target_principal, scopes, delegates, quota_project_id=quota_project_id, + iam_endpoint_override=iam_endpoint_override, 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 ff1d137dd21e..5f2edf6abbc0 100644 --- a/packages/google-auth/tests/test_impersonated_credentials.py +++ b/packages/google-auth/tests/test_impersonated_credentials.py @@ -1247,3 +1247,292 @@ def test_constructor_universe_domain_validation(self): target_scopes=self.TARGET_SCOPES, universe_domain=" ", ) + + def _refresh_impersonated_and_get_url(self, creds): + 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) + return request.call_args[1]["url"] + + def test_from_impersonated_service_account_info_default_url_preserves_mtls_path( + self, + ): + info = copy.deepcopy(IMPERSONATED_SERVICE_ACCOUNT_AUTHORIZED_USER_SOURCE_INFO) + creds = ( + impersonated_credentials.Credentials.from_impersonated_service_account_info( + info + ) + ) + assert creds.universe_domain == "googleapis.com" + assert creds._iam_endpoint_override is None + assert ( + self._refresh_impersonated_and_get_url(creds) + == info["service_account_impersonation_url"] + ) + + @pytest.mark.parametrize( + "impersonation_url,expected_universe", + [ + pytest.param( + "https://iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/some@email.com:generateAccessToken", + "example.com", + id="global_custom_universe", + ), + pytest.param( + "https://iamcredentials.example.com./v1/projects/-" + "/serviceAccounts/some@email.com:generateAccessToken", + "example.com", + id="trailing_dot_custom_universe", + ), + pytest.param( + "https://us-east1-iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/some@email.com:generateAccessToken", + "example.com", + id="dash_regional_custom_universe", + ), + pytest.param( + "https://us-east1.iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/some@email.com:generateAccessToken", + "example.com", + id="dot_regional_custom_universe", + ), + pytest.param( + "https://iamcredentials.us-east1.rep.example.com/v1/projects/-" + "/serviceAccounts/some@email.com:generateAccessToken", + "example.com", + id="rep_custom_universe", + ), + pytest.param( + "https://iamcredentials-ep1.p.example.com/v1/projects/-" + "/serviceAccounts/some@email.com:generateAccessToken", + "example.com", + id="psc_custom_universe", + ), + pytest.param( + "https://iamcredentials.mtls.example.com/v1/projects/-" + "/serviceAccounts/some@email.com:generateAccessToken", + "example.com", + id="mtls_custom_universe", + ), + ], + ) + def test_from_impersonated_service_account_info_infers_universe_from_url( + self, impersonation_url, expected_universe + ): + info = copy.deepcopy(IMPERSONATED_SERVICE_ACCOUNT_AUTHORIZED_USER_SOURCE_INFO) + info["service_account_impersonation_url"] = impersonation_url + + creds = ( + impersonated_credentials.Credentials.from_impersonated_service_account_info( + info + ) + ) + assert creds.universe_domain == expected_universe + assert creds._source_credentials.universe_domain == expected_universe + assert creds._iam_endpoint_override == impersonation_url + assert self._refresh_impersonated_and_get_url(creds) == impersonation_url + + @pytest.mark.parametrize( + "top_level_universe,impersonation_url,expected_universe", + [ + pytest.param( + None, + "https://us-east1-iamcredentials.googleapis.com/v1/projects/-" + "/serviceAccounts/some@email.com:generateAccessToken", + "googleapis.com", + id="regional_default_universe", + ), + pytest.param( + "googleapis.com", + "https://iamcredentials.us-east1.rep.mtls.googleapis.com/v1/projects/-" + "/serviceAccounts/some@email.com:generateAccessToken", + "googleapis.com", + id="rep_mtls_default_universe", + ), + pytest.param( + None, + "https://proxy.internal.corp/v1/projects/-" + "/serviceAccounts/some@email.com:generateAccessToken", + "googleapis.com", + id="custom_proxy_with_omitted_universe", + ), + pytest.param( + "googleapis.com", + "https://proxy.internal.corp/v1/projects/-" + "/serviceAccounts/some@email.com:generateAccessToken", + "googleapis.com", + id="custom_proxy_with_default_universe", + ), + pytest.param( + "example.com", + "https://proxy.internal.corp/v1/projects/-" + "/serviceAccounts/some@email.com:generateAccessToken", + "example.com", + id="custom_proxy_with_non_default_universe", + ), + ], + ) + def test_from_impersonated_service_account_info_preserves_custom_origin( + self, top_level_universe, impersonation_url, expected_universe + ): + info = copy.deepcopy(IMPERSONATED_SERVICE_ACCOUNT_AUTHORIZED_USER_SOURCE_INFO) + if top_level_universe is not None: + info["universe_domain"] = top_level_universe + info["service_account_impersonation_url"] = impersonation_url + + creds = ( + impersonated_credentials.Credentials.from_impersonated_service_account_info( + info + ) + ) + assert creds.universe_domain == expected_universe + assert creds._iam_endpoint_override == impersonation_url + assert self._refresh_impersonated_and_get_url(creds) == impersonation_url + + @pytest.mark.parametrize( + "top_level_universe,source_universe,impersonation_url,expected_match", + [ + pytest.param( + "example.com", + None, + "https://iamcredentials.googleapis.com/v1/projects/-" + "/serviceAccounts/sa@example.com:generateAccessToken", + "does not match the expected universe domain", + id="non_default_universe_with_default_iam_url", + ), + pytest.param( + "example.com", + None, + "https://iamcredentials.googleapis.com./v1/projects/-" + "/serviceAccounts/sa@example.com:generateAccessToken", + "does not match the expected universe domain", + id="non_default_universe_with_trailing_dot_default_iam_url", + ), + pytest.param( + "example.com", + None, + "https://proxy.googleapis.com/v1/projects/-" + "/serviceAccounts/sa@example.com:generateAccessToken", + "cannot use default-universe impersonation URL host", + id="non_default_universe_with_googleapis_proxy_url", + ), + pytest.param( + "example.com", + None, + "https://proxy.googleapis.com./v1/projects/-" + "/serviceAccounts/sa@example.com:generateAccessToken", + "cannot use default-universe impersonation URL host", + id="non_default_universe_with_trailing_dot_googleapis_proxy", + ), + pytest.param( + None, + "googleapis.com", + "https://iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/sa@example.com:generateAccessToken", + "does not match the expected universe domain", + id="source_universe_conflicts_with_url_universe", + ), + pytest.param( + None, + None, + None, + "Cannot extract target principal", + id="missing_impersonation_url", + ), + pytest.param( + None, + None, + "https://[invalid/v1/projects/-/serviceAccounts/sa@example.com:generateAccessToken", + "Cannot extract target principal", + id="malformed_ipv6_impersonation_url", + ), + pytest.param( + None, + None, + "https://iamcredentials.googleapis.com:notaport/v1/projects/-" + "/serviceAccounts/sa@example.com:generateAccessToken", + "Cannot extract target principal", + id="invalid_port_impersonation_url", + ), + pytest.param( + None, + None, + "http://iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/sa@example.com:generateAccessToken", + "Cannot extract target principal", + id="plaintext_http_impersonation_url", + ), + pytest.param( + None, + None, + "https://evil.com@iamcredentials.googleapis.com/v1/projects/-" + "/serviceAccounts/sa@example.com:generateAccessToken", + "Cannot extract target principal", + id="userinfo_in_impersonation_url", + ), + pytest.param( + None, + None, + "https://iamcredentials.googleapis.com/v1/projects/-" + "/serviceAccounts/sa@example.com:generateAccessToken#frag", + "Cannot extract target principal", + id="fragment_in_impersonation_url", + ), + pytest.param( + None, + None, + "https://iamcredentials.googleapis.com/v1/projects/-" + "/serviceAccounts/sa@example.com:generateAccessToken\t", + "Cannot extract target principal", + id="whitespace_in_impersonation_url", + ), + pytest.param( + None, + None, + "https://iamcredentials.googleapis.com/v1/projects/-" + "/serviceAccounts/sa@example.com:generateAccessToken:extra", + "Cannot extract target principal", + id="trailing_junk_after_action", + ), + pytest.param( + None, + None, + "https://iamcredentials.googleapis.com/v1/projects/-" + "/serviceAccounts/:generateAccessToken", + "Cannot extract target principal", + id="empty_target_principal_in_url", + ), + pytest.param( + None, + None, + "https://./v1/projects/-/serviceAccounts/sa@example.com:generateAccessToken", + "Cannot extract target principal", + id="dot_only_host_in_url", + ), + ], + ) + def test_from_impersonated_service_account_info_url_validation_errors( + self, top_level_universe, source_universe, impersonation_url, 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 + info["service_account_impersonation_url"] = impersonation_url + + with pytest.raises(exceptions.InvalidValue, match=expected_match): + impersonated_credentials.Credentials.from_impersonated_service_account_info( + info + ) From e9f028f4f34537ecb31c7463973d28681a93c16a Mon Sep 17 00:00:00 2001 From: ohmayr Date: Fri, 27 Nov 2026 16:06:12 +0000 Subject: [PATCH 3/3] fix(auth): validate missing source_credentials in impersonated loader --- .../google/auth/impersonated_credentials.py | 9 ++++++--- .../tests/test_impersonated_credentials.py | 18 ++++++++++++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/packages/google-auth/google/auth/impersonated_credentials.py b/packages/google-auth/google/auth/impersonated_credentials.py index 56dcb514d0aa..bca2599e5d2b 100644 --- a/packages/google-auth/google/auth/impersonated_credentials.py +++ b/packages/google-auth/google/auth/impersonated_credentials.py @@ -26,6 +26,7 @@ """ import base64 +import collections.abc import copy import http.client as http_client import json @@ -567,6 +568,10 @@ def from_impersonated_service_account_info(cls, info, scopes=None): """ source_credentials_info = info.get("source_credentials") + if not isinstance(source_credentials_info, collections.abc.Mapping): + raise exceptions.InvalidValue( + "The 'source_credentials' field is required in the impersonated service account info." + ) impersonation_url = info.get("service_account_impersonation_url") target_principal, url_host = _parse_impersonation_url(impersonation_url) url_universe = _extract_universe_from_iam_host(url_host) @@ -580,9 +585,7 @@ def from_impersonated_service_account_info(cls, info, scopes=None): if explicit_universe is not None: _helpers.validate_universe_domain(explicit_universe) if url_universe is not None: - _helpers.compare_universe_domains( - explicit_universe.lower(), url_universe - ) + _helpers.compare_universe_domains(explicit_universe, url_universe) elif ( explicit_universe.lower() != credentials.DEFAULT_UNIVERSE_DOMAIN and _helpers.has_default_universe_host(f"https://{url_host}") diff --git a/packages/google-auth/tests/test_impersonated_credentials.py b/packages/google-auth/tests/test_impersonated_credentials.py index 5f2edf6abbc0..2f02f1f90247 100644 --- a/packages/google-auth/tests/test_impersonated_credentials.py +++ b/packages/google-auth/tests/test_impersonated_credentials.py @@ -1536,3 +1536,21 @@ def test_from_impersonated_service_account_info_url_validation_errors( impersonated_credentials.Credentials.from_impersonated_service_account_info( info ) + + @pytest.mark.parametrize("source_credentials_value", [None, "invalid"]) + def test_from_impersonated_service_account_info_missing_source_credentials( + self, source_credentials_value + ): + info = copy.deepcopy(IMPERSONATED_SERVICE_ACCOUNT_AUTHORIZED_USER_SOURCE_INFO) + if source_credentials_value is None: + info.pop("source_credentials", None) + else: + info["source_credentials"] = source_credentials_value + + with pytest.raises( + exceptions.InvalidValue, + match="The 'source_credentials' field is required", + ): + impersonated_credentials.Credentials.from_impersonated_service_account_info( + info + )