From a8ac188fcd3a34547e072a00f755f7ef7cf04c6d Mon Sep 17 00:00:00 2001 From: ohmayr Date: Wed, 25 Nov 2026 22:37:51 +0000 Subject: [PATCH] fix(auth): honor universe_domain and URL host in impersonated creds Credentials.from_impersonated_service_account_info() ignored top-level universe_domain and discarded the host from service_account_impersonation_url, causing non-default universe and regional configs to fall back to iamcredentials.googleapis.com. Credentials.sign_bytes() and IDTokenCredentials.refresh() also ignored _iam_endpoint_override. Validate explicit universe_domain values with _helpers.validate_universe_domain(), parse and validate service_account_impersonation_url (rejecting conflicting universes, non-HTTPS URLs, malformed hosts, and default-universe endpoints on non-default universes), infer non-default universes from the impersonation host when omitted, propagate the resolved universe into source credentials without mutating caller input, keep iam_endpoint_override for non-default URLs (preserving mTLS selection for the standard default URL), and honor _iam_endpoint_override in sign_bytes() and IDTokenCredentials.refresh(). Fixes: b/589828921 --- .../google/auth/impersonated_credentials.py | 215 ++++++- .../tests/test_impersonated_credentials.py | 561 ++++++++++++++++++ 2 files changed, 754 insertions(+), 22 deletions(-) diff --git a/packages/google-auth/google/auth/impersonated_credentials.py b/packages/google-auth/google/auth/impersonated_credentials.py index f9faab5e7336..4ab947e35054 100644 --- a/packages/google-auth/google/auth/impersonated_credentials.py +++ b/packages/google-auth/google/auth/impersonated_credentials.py @@ -30,6 +30,9 @@ import http.client as http_client import json import logging +import re +import urllib.parse +from collections.abc import Mapping from datetime import datetime from typing import TYPE_CHECKING, Optional @@ -63,6 +66,80 @@ "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 _is_host_in_domain(host, domain): + """Returns True if ``host`` equals ``domain`` or is a subdomain of it.""" + return host == domain or host.endswith(f".{domain}") + + +def _parse_impersonation_url(impersonation_url): + """Extracts (target_principal, hostname, inferred_universe) from an impersonation URL.""" + error_msg = "Cannot extract target principal from {}".format(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 "").rstrip(".") + _ = 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) + + match = _IAM_HOST_PATTERN.fullmatch(hostname) + inferred_universe = match.group(1) if match else None + return target_principal, hostname, inferred_universe + + +def _build_iam_endpoint( + target_principal, + universe_domain, + iam_endpoint_override, + action, +): + """Builds an IAM Credentials API URL, honoring iam_endpoint_override when set.""" + if not iam_endpoint_override: + host_prefix = iam._IAM_DOMAIN.removesuffix(credentials.DEFAULT_UNIVERSE_DOMAIN) + return ( + f"https://{host_prefix}{universe_domain}/v1/projects/-/" + f"serviceAccounts/{target_principal}:{action}" + ) + + parsed = urllib.parse.urlsplit(iam_endpoint_override) + if not parsed.scheme or not parsed.netloc: + raise exceptions.InvalidValue( + "Invalid iam_endpoint_override: {}".format(iam_endpoint_override) + ) + if parsed.path.endswith(":generateAccessToken"): + path = parsed.path[: -len(":generateAccessToken")] + f":{action}" + else: + base_path = parsed.path.rstrip("/") + path = f"{base_path}/v1/projects/-/serviceAccounts/{target_principal}:{action}" + return urllib.parse.urlunsplit(parsed._replace(path=path)) + def _make_iam_token_request( request, @@ -91,9 +168,9 @@ def _make_iam_token_request( `iamcredentials.googleapis.com` is not enabled or the `Service Account Token Creator` is not assigned """ - iam_endpoint = iam_endpoint_override or iam._IAM_ENDPOINT.replace( - credentials.DEFAULT_UNIVERSE_DOMAIN, universe_domain - ).format(principal) + iam_endpoint = iam_endpoint_override or _build_iam_endpoint( + principal, universe_domain, None, "generateAccessToken" + ) body = json.dumps(body).encode("utf-8") @@ -212,6 +289,7 @@ def __init__( quota_project_id=None, iam_endpoint_override=None, trust_boundary=None, + universe_domain=None, ): """ Args: @@ -243,10 +321,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 +350,15 @@ 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 and source_universe != universe_domain: + raise exceptions.InvalidValue( + "The impersonated credential universe domain ({}) does not " + "match the source credential universe domain ({}).".format( + universe_domain, source_universe + ) + ) + self._universe_domain = universe_domain or source_universe self._target_principal = target_principal self._target_scopes = target_scopes self._delegates = delegates @@ -382,9 +477,12 @@ def _build_regional_access_boundary_lookup_url( def sign_bytes(self, message): from google.auth.transport.requests import AuthorizedSession - iam_sign_endpoint = iam._IAM_SIGN_ENDPOINT.replace( - credentials.DEFAULT_UNIVERSE_DOMAIN, self.universe_domain - ).format(self._target_principal) + iam_sign_endpoint = _build_iam_endpoint( + self._target_principal, + self.universe_domain, + self._iam_endpoint_override, + "signBlob", + ) body = { "payload": base64.b64encode(message).decode("utf-8"), @@ -450,6 +548,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,17 +590,80 @@ 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 + ``source_credentials``, ``universe_domain``, or + ``service_account_impersonation_url``. ValueError: If the info is not in the expected format. """ source_credentials_info = info.get("source_credentials") + if not isinstance(source_credentials_info, Mapping): + raise exceptions.InvalidValue("source_credentials must be a mapping.") + + impersonation_url = info.get("service_account_impersonation_url") + target_principal, url_host, url_universe = _parse_impersonation_url( + impersonation_url + ) + + top_level_universe = info.get("universe_domain") + if top_level_universe is not None: + _helpers.validate_universe_domain(top_level_universe) + source_universe = source_credentials_info.get("universe_domain") + if source_universe is not None: + _helpers.validate_universe_domain(source_universe) + if ( + top_level_universe is not None + and source_universe is not None + and top_level_universe != source_universe + ): + raise exceptions.InvalidValue( + "Impersonated credentials universe_domain ({}) does not match " + "source_credentials universe_domain ({}).".format( + top_level_universe, source_universe + ) + ) + + explicit_universe = top_level_universe or source_universe + if explicit_universe is not None: + explicit_lower = explicit_universe.lower() + if not _is_host_in_domain(url_host, explicit_lower): + if url_universe is not None: + raise exceptions.InvalidValue( + "Impersonated credentials universe_domain ({}) does not match " + "service_account_impersonation_url host ({}).".format( + explicit_universe, url_host + ) + ) + if explicit_lower != credentials.DEFAULT_UNIVERSE_DOMAIN and ( + _is_host_in_domain(url_host, credentials.DEFAULT_UNIVERSE_DOMAIN) + ): + raise exceptions.InvalidValue( + "Non-default universe_domain ({}) cannot use default-universe " + "service_account_impersonation_url host ({}).".format( + explicit_universe, url_host + ) + ) + + resolved_universe = explicit_universe + if ( + resolved_universe is None + and url_universe is not None + and url_universe != credentials.DEFAULT_UNIVERSE_DOMAIN + ): + resolved_universe = url_universe + + if resolved_universe is not None and source_universe is None: + source_credentials_info = dict(source_credentials_info) + source_credentials_info["universe_domain"] = resolved_universe + 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 @@ -525,26 +687,33 @@ 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=resolved_universe, ) @@ -615,10 +784,12 @@ def with_quota_project(self, quota_project_id): def refresh(self, request): from google.auth.transport.requests import AuthorizedSession - iam_sign_endpoint = iam._IAM_IDTOKEN_ENDPOINT.replace( - credentials.DEFAULT_UNIVERSE_DOMAIN, + iam_sign_endpoint = _build_iam_endpoint( + self._target_credentials.signer_email, self._target_credentials.universe_domain, - ).format(self._target_credentials.signer_email) + self._target_credentials._iam_endpoint_override, + "generateIdToken", + ) body = { "audience": self._target_audience, diff --git a/packages/google-auth/tests/test_impersonated_credentials.py b/packages/google-auth/tests/test_impersonated_credentials.py index 2cfcbf150f86..4e6146c4fa40 100644 --- a/packages/google-auth/tests/test_impersonated_credentials.py +++ b/packages/google-auth/tests/test_impersonated_credentials.py @@ -1079,3 +1079,564 @@ 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" + + def _assert_refresh_and_sign_urls( + self, + creds, + mock_authorizedsession_sign, + expected_refresh_url, + expected_sign_url, + ): + 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, + ) + creds.refresh(request) + assert request.call_args[1]["url"] == expected_refresh_url + + signature = creds.sign_bytes(b"signed bytes") + assert signature == b"signature" + assert mock_authorizedsession_sign.call_args[0][2] == expected_sign_url + + def test_from_impersonated_service_account_info_default_url_preserves_mtls_path( + self, + ): + creds = ( + impersonated_credentials.Credentials.from_impersonated_service_account_info( + IMPERSONATED_SERVICE_ACCOUNT_AUTHORIZED_USER_SOURCE_INFO + ) + ) + assert creds.universe_domain == "googleapis.com" + assert creds._iam_endpoint_override is None + + def test_from_impersonated_service_account_info_top_level_universe_domain( + self, mock_authorizedsession_sign + ): + info = { + "type": "impersonated_service_account", + "universe_domain": "example.com", + "service_account_impersonation_url": ( + "https://iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/service-account-target@example.com:generateAccessToken" + ), + "source_credentials": copy.deepcopy(SERVICE_ACCOUNT_INFO), + } + + creds = ( + impersonated_credentials.Credentials.from_impersonated_service_account_info( + info, scopes=self.TARGET_SCOPES + ) + ) + + # Caller input dict must not be mutated. + assert "universe_domain" not in info["source_credentials"] + assert creds.universe_domain == "example.com" + assert creds._source_credentials.universe_domain == "example.com" + assert creds.with_quota_project("qp").universe_domain == "example.com" + assert creds.with_scopes(self.TARGET_SCOPES).universe_domain == "example.com" + + self._assert_refresh_and_sign_urls( + creds, + mock_authorizedsession_sign, + expected_refresh_url=info["service_account_impersonation_url"], + expected_sign_url=( + "https://iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/service-account-target@example.com:signBlob" + ), + ) + + @pytest.mark.parametrize( + "impersonation_url,expected_sign_url", + [ + pytest.param( + "https://iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/service-account-target@example.com:generateAccessToken", + "https://iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/service-account-target@example.com:signBlob", + id="global_custom_universe", + ), + pytest.param( + "https://iamcredentials.example.com./v1/projects/-" + "/serviceAccounts/service-account-target@example.com:generateAccessToken", + "https://iamcredentials.example.com./v1/projects/-" + "/serviceAccounts/service-account-target@example.com:signBlob", + id="trailing_dot_custom_universe", + ), + pytest.param( + "https://us-east1-iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/service-account-target@example.com:generateAccessToken", + "https://us-east1-iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/service-account-target@example.com:signBlob", + id="dash_regional_custom_universe", + ), + pytest.param( + "https://us-east1.iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/service-account-target@example.com:generateAccessToken", + "https://us-east1.iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/service-account-target@example.com:signBlob", + id="dot_regional_custom_universe", + ), + pytest.param( + "https://iamcredentials.europe-west3.rep.example.com/v1/projects/-" + "/serviceAccounts/service-account-target@example.com:generateAccessToken", + "https://iamcredentials.europe-west3.rep.example.com/v1/projects/-" + "/serviceAccounts/service-account-target@example.com:signBlob", + id="rep_custom_universe", + ), + pytest.param( + "https://iamcredentials-us-east1.p.example.com/v1/projects/-" + "/serviceAccounts/service-account-target@example.com:generateAccessToken", + "https://iamcredentials-us-east1.p.example.com/v1/projects/-" + "/serviceAccounts/service-account-target@example.com:signBlob", + id="psc_custom_universe", + ), + ], + ) + def test_from_impersonated_service_account_info_infers_universe_from_url( + self, impersonation_url, expected_sign_url, mock_authorizedsession_sign + ): + info = { + "type": "impersonated_service_account", + "service_account_impersonation_url": impersonation_url, + "source_credentials": copy.deepcopy(SERVICE_ACCOUNT_INFO), + } + + creds = ( + impersonated_credentials.Credentials.from_impersonated_service_account_info( + info, scopes=self.TARGET_SCOPES + ) + ) + + assert creds.universe_domain == "example.com" + assert creds._source_credentials.universe_domain == "example.com" + self._assert_refresh_and_sign_urls( + creds, + mock_authorizedsession_sign, + expected_refresh_url=impersonation_url, + expected_sign_url=expected_sign_url, + ) + + @pytest.mark.parametrize( + "top_level_universe,impersonation_url,expected_sign_url", + [ + pytest.param( + None, + "https://us-east1-iamcredentials.googleapis.com/v1/projects/-" + "/serviceAccounts/service-account-target@example.com:generateAccessToken", + "https://us-east1-iamcredentials.googleapis.com/v1/projects/-" + "/serviceAccounts/service-account-target@example.com:signBlob", + id="regional_default_universe", + ), + pytest.param( + "googleapis.com", + "https://iamcredentials.us-east1.rep.googleapis.com/v1/projects/-" + "/serviceAccounts/service-account-target@example.com:generateAccessToken", + "https://iamcredentials.us-east1.rep.googleapis.com/v1/projects/-" + "/serviceAccounts/service-account-target@example.com:signBlob", + id="rep_default_universe", + ), + pytest.param( + None, + "https://iamcredentials.us-east1.rep.mtls.googleapis.com/v1/projects/-" + "/serviceAccounts/service-account-target@example.com:generateAccessToken", + "https://iamcredentials.us-east1.rep.mtls.googleapis.com/v1/projects/-" + "/serviceAccounts/service-account-target@example.com:signBlob", + id="rep_mtls_default_universe", + ), + pytest.param( + None, + "https://proxy.internal/iam/v1/projects/-" + "/serviceAccounts/service-account-target@example.com:generateAccessToken", + "https://proxy.internal/iam/v1/projects/-" + "/serviceAccounts/service-account-target@example.com:signBlob", + id="custom_proxy_origin", + ), + pytest.param( + "example.com", + "https://proxy.internal/iam/v1/projects/-" + "/serviceAccounts/service-account-target@example.com:generateAccessToken", + "https://proxy.internal/iam/v1/projects/-" + "/serviceAccounts/service-account-target@example.com:signBlob", + id="custom_proxy_origin_with_non_default_universe", + ), + ], + ) + def test_from_impersonated_service_account_info_preserves_custom_origin( + self, + top_level_universe, + impersonation_url, + expected_sign_url, + mock_donor_credentials, + mock_authorizedsession_sign, + ): + info = { + "type": "impersonated_service_account", + "service_account_impersonation_url": impersonation_url, + "source_credentials": copy.deepcopy(SERVICE_ACCOUNT_INFO), + } + if top_level_universe is not None: + info["universe_domain"] = top_level_universe + + creds = ( + impersonated_credentials.Credentials.from_impersonated_service_account_info( + info, scopes=self.TARGET_SCOPES + ) + ) + + assert creds.universe_domain == (top_level_universe or "googleapis.com") + self._assert_refresh_and_sign_urls( + creds, + mock_authorizedsession_sign, + expected_refresh_url=impersonation_url, + expected_sign_url=expected_sign_url, + ) + + def test_from_impersonated_service_account_info_top_level_universe_authorized_user( + self, + ): + info = copy.deepcopy(IMPERSONATED_SERVICE_ACCOUNT_AUTHORIZED_USER_SOURCE_INFO) + info["universe_domain"] = "example.com" + info["service_account_impersonation_url"] = ( + "https://iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/service-account-target@example.com:generateAccessToken" + ) + + creds = ( + impersonated_credentials.Credentials.from_impersonated_service_account_info( + info, scopes=self.TARGET_SCOPES + ) + ) + + assert creds.universe_domain == "example.com" + assert creds._source_credentials.universe_domain == "example.com" + request = mock.create_autospec(transport.Request) + with pytest.raises(exceptions.RefreshError, match="googleapis.com"): + creds.refresh(request) + request.assert_not_called() + + @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 service_account_impersonation_url host", + id="top_level_conflicts_with_default_url", + ), + pytest.param( + "example.com", + None, + "https://iamcredentials.googleapis.com./v1/projects/-" + "/serviceAccounts/sa@example.com:generateAccessToken", + "does not match service_account_impersonation_url host", + id="trailing_dot_default_url_blocked", + ), + pytest.param( + "example.com", + "other.com", + "https://iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/sa@example.com:generateAccessToken", + "does not match source_credentials universe_domain", + id="top_level_conflicts_with_source_universe", + ), + pytest.param( + "example.com", + None, + "https://proxy.googleapis.com/v1/projects/-" + "/serviceAccounts/sa@example.com:generateAccessToken", + "cannot use default-universe service_account_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 service_account_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 service_account_impersonation_url host", + id="source_universe_conflicts_with_url_universe", + ), + pytest.param( + "", + None, + "https://iamcredentials.googleapis.com/v1/projects/-" + "/serviceAccounts/sa@example.com:generateAccessToken", + "must be a valid non-empty domain string", + id="empty_top_level_universe", + ), + pytest.param( + " example.com ", + None, + "https://iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/sa@example.com:generateAccessToken", + "must be a valid non-empty domain string", + id="whitespace_top_level_universe", + ), + pytest.param( + 123, + None, + "https://iamcredentials.googleapis.com/v1/projects/-" + "/serviceAccounts/sa@example.com:generateAccessToken", + "must be a valid non-empty domain string", + id="non_string_top_level_universe", + ), + pytest.param( + None, + "", + "https://iamcredentials.googleapis.com/v1/projects/-" + "/serviceAccounts/sa@example.com:generateAccessToken", + "must be a valid non-empty domain string", + id="empty_source_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_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 + ) + + def test_from_impersonated_service_account_info_missing_source_credentials(self): + info = copy.deepcopy(IMPERSONATED_SERVICE_ACCOUNT_AUTHORIZED_USER_SOURCE_INFO) + info["source_credentials"] = None + with pytest.raises( + exceptions.InvalidValue, match="source_credentials must be a mapping" + ): + 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 source credential 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=" ", + ) + + @pytest.mark.parametrize( + "iam_endpoint_override,expected_sign_url", + [ + pytest.param( + "https://us-east1-iamcredentials.googleapis.com/v1/projects/-" + "/serviceAccounts/impersonated@project.iam.gserviceaccount.com:generateAccessToken", + "https://us-east1-iamcredentials.googleapis.com/v1/projects/-" + "/serviceAccounts/impersonated@project.iam.gserviceaccount.com:signBlob", + id="regional_generate_access_token_override", + ), + pytest.param( + "https://iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/impersonated@project.iam.gserviceaccount.com:generateAccessToken?alt=json", + "https://iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/impersonated@project.iam.gserviceaccount.com:signBlob?alt=json", + id="custom_universe_with_query", + ), + pytest.param( + "https://iamcredentials.example.com", + "https://iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/impersonated@project.iam.gserviceaccount.com:signBlob", + id="origin_only_override", + ), + pytest.param( + "https://proxy.internal/iam/", + "https://proxy.internal/iam/v1/projects/-" + "/serviceAccounts/impersonated@project.iam.gserviceaccount.com:signBlob", + id="proxy_path_prefix_override", + ), + ], + ) + def test_sign_bytes_honors_iam_endpoint_override( + self, + iam_endpoint_override, + expected_sign_url, + mock_authorizedsession_sign, + ): + creds = self.make_credentials( + lifetime=None, iam_endpoint_override=iam_endpoint_override + ) + signature = creds.sign_bytes(b"signed bytes") + assert signature == b"signature" + mock_authorizedsession_sign.assert_called_with( + mock.ANY, + "POST", + expected_sign_url, + None, + json={"payload": "c2lnbmVkIGJ5dGVz", "delegates": []}, + headers={"Content-Type": "application/json"}, + ) + + def test_sign_bytes_rejects_schemeless_iam_endpoint_override(self): + creds = self.make_credentials( + lifetime=None, + iam_endpoint_override="us-east1-iamcredentials.googleapis.com", + ) + with pytest.raises( + exceptions.InvalidValue, match="Invalid iam_endpoint_override" + ): + creds.sign_bytes(b"signed bytes") + + def test_id_token_refresh_honors_iam_endpoint_override( + self, mock_authorizedsession_idtoken + ): + override = ( + "https://us-east1-iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/impersonated@project.iam.gserviceaccount.com:generateAccessToken" + ) + source = service_account.Credentials( + SIGNER, "some@email.com", TOKEN_URI, universe_domain="example.com" + ) + target_creds = self.make_credentials( + lifetime=None, source_credentials=source, iam_endpoint_override=override + ) + id_creds = impersonated_credentials.IDTokenCredentials( + target_creds, target_audience="https://example.com" + ) + request = mock.create_autospec(transport.Request) + + id_creds.refresh(request) + + assert id_creds.token == ID_TOKEN_DATA + assert ( + mock_authorizedsession_idtoken.call_args[0][2] + == "https://us-east1-iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/impersonated@project.iam.gserviceaccount.com:generateIdToken" + ) + + def test_build_iam_endpoint_preserves_mtls_prefix(self): + with mock.patch( + "google.auth.iam._IAM_DOMAIN", "iamcredentials.mtls.googleapis.com" + ): + url = impersonated_credentials._build_iam_endpoint( + self.TARGET_PRINCIPAL, + "example.com", + None, + "signBlob", + ) + assert ( + url == "https://iamcredentials.mtls.example.com/v1/projects/-" + "/serviceAccounts/impersonated@project.iam.gserviceaccount.com:signBlob" + )