From d895f9406415e86837c93d6e9d7e4c502969de12 Mon Sep 17 00:00:00 2001 From: ohmayr Date: Tue, 24 Nov 2026 23:29:47 +0000 Subject: [PATCH 1/4] fix(auth): guard default-universe get_project_id by endpoint host External account configs that omit `universe_domain` default to `googleapis.com`. If the config points `token_url` or `service_account_impersonation_url` at another domain (such as another universe or a custom proxy), `get_project_id()` would mint a token from that endpoint and send it to `cloudresourcemanager.googleapis.com`. When `universe_domain` is `googleapis.com`, skip the Cloud Resource Manager lookup and return `None` unless `token_url` (and `service_account_impersonation_url`, when set) has a `googleapis.com` host. Configs targeting `googleapis.com` that omit `universe_domain` continue to work unchanged, as do configs that set a custom `universe_domain` explicitly. This change only addresses external_account.Credentials.get_project_id. Tracking whether universe_domain was explicitly configured (for Regional Access Boundary lookups) will be handled in a follow-up PR. b/588990592 --- .../google/auth/external_account.py | 30 ++++++++ .../tests/test_external_account.py | 72 +++++++++++++++++++ 2 files changed, 102 insertions(+) diff --git a/packages/google-auth/google/auth/external_account.py b/packages/google-auth/google/auth/external_account.py index 8832abbce29b..baf1ef372f2a 100644 --- a/packages/google-auth/google/auth/external_account.py +++ b/packages/google-auth/google/auth/external_account.py @@ -38,6 +38,7 @@ import threading from dataclasses import dataclass from typing import TYPE_CHECKING, Optional +from urllib.parse import urlparse from google.auth import ( _helpers, @@ -66,6 +67,18 @@ _DEFAULT_TOKEN_URL = "https://sts.{universe_domain}/v1/token" +def _has_default_universe_host(url): + """Checks whether a URL's host is in the default universe domain.""" + try: + host = urlparse(url).hostname + return host is not None and ( + host == credentials.DEFAULT_UNIVERSE_DOMAIN + or host.endswith(f".{credentials.DEFAULT_UNIVERSE_DOMAIN}") + ) + except (ValueError, TypeError, AttributeError): + return False + + @dataclass class SupplierContext: """A context class that contains information about the requested third party credential that is passed @@ -417,6 +430,23 @@ def get_project_id(self, request): # Scopes are required in order to retrieve a valid access token. project_number = self.project_number or self._workforce_pool_user_project if project_number and scopes: + # Avoid sending tokens minted for non-googleapis.com endpoints + # (e.g. another universe domain or custom proxy) to + # cloudresourcemanager.googleapis.com. + if self.universe_domain == credentials.DEFAULT_UNIVERSE_DOMAIN: + if not _has_default_universe_host(self._token_url): + return None + # Impersonation is optional; calling _has_default_universe_host(None) + # returns False and would block non-impersonated default-universe + # credentials. + if ( + self._service_account_impersonation_url + and not _has_default_universe_host( + self._service_account_impersonation_url + ) + ): + return None + headers = {} url = "{}{}".format(self._cloud_resource_manager_url, project_number) self.before_request(request, "GET", url, headers) diff --git a/packages/google-auth/tests/test_external_account.py b/packages/google-auth/tests/test_external_account.py index 73993fd76e50..91d451371713 100644 --- a/packages/google-auth/tests/test_external_account.py +++ b/packages/google-auth/tests/test_external_account.py @@ -2319,6 +2319,78 @@ def test_get_project_id_cloud_resource_manager_custom_universe_domain(self): ) assert crm_request_kwargs["url"] == expected_url + @pytest.mark.parametrize( + "token_url,impersonation_url", + [ + pytest.param( + "https://sts.example.com/v1/token", + None, + id="non_default_token_url", + ), + pytest.param( + "https://sts.googleapis.com/v1/token", + "https://iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/sa@p.iam.gserviceaccount.com:generateAccessToken", + id="non_default_impersonation_url", + ), + pytest.param( + "https://sts.googleapis.com.evil.com/v1/token", + None, + id="spoofed_host_suffix", + ), + pytest.param( + "https://evilgoogleapis.com/v1/token", + None, + id="missing_subdomain_dot", + ), + pytest.param(None, None, id="missing_token_url"), + pytest.param("https://[invalid/v1/token", None, id="malformed_token_url"), + ], + ) + def test_get_project_id_skips_non_default_universe_endpoints( + self, token_url, impersonation_url + ): + request = mock.create_autospec(transport.Request) + info = { + "type": "external_account", + "audience": self.AUDIENCE, + "subject_token_type": self.SUBJECT_TOKEN_TYPE, + "token_url": token_url, + "credential_source": self.CREDENTIAL_SOURCE, + } + if impersonation_url is not None: + info["service_account_impersonation_url"] = impersonation_url + credentials = CredentialsImpl.from_info(info, scopes=self.SCOPES) + + project_id = credentials.get_project_id(request) + + assert project_id is None + request.assert_not_called() + + def test_get_project_id_allows_default_universe_token_url_when_universe_omitted( + self, + ): + request = self.make_mock_request( + status=http_client.OK, + data=self.SUCCESS_RESPONSE.copy(), + cloud_resource_manager_status=http_client.OK, + cloud_resource_manager_data=self.CLOUD_RESOURCE_MANAGER_SUCCESS_RESPONSE, + ) + credentials = CredentialsImpl.from_info( + { + "type": "external_account", + "audience": self.AUDIENCE, + "subject_token_type": self.SUBJECT_TOKEN_TYPE, + "token_url": self.TOKEN_URL, + "credential_source": self.CREDENTIAL_SOURCE, + }, + scopes=self.SCOPES, + ) + + project_id = credentials.get_project_id(request) + + assert project_id == self.PROJECT_ID + def test_refresh_with_existing_impersonated_credentials(self): credentials = self.make_credentials( service_account_impersonation_url=self.SERVICE_ACCOUNT_IMPERSONATION_URL From c464fe56a2a4d56b9754d1a6aaaff126cd76994b Mon Sep 17 00:00:00 2001 From: ohmayr Date: Wed, 25 Nov 2026 11:20:43 +0000 Subject: [PATCH 2/4] fix(auth): guard get_project_id against actual CRM URL host Check `_has_default_universe_host(self._cloud_resource_manager_url)` instead of `self.universe_domain == DEFAULT_UNIVERSE_DOMAIN` in `external_account.Credentials.get_project_id()`. Because `with_universe_domain()` currently does not update `_cloud_resource_manager_url`, guarding the actual destination URL prevents non-default tokens from leaking to `cloudresourcemanager.googleapis.com` even after `with_universe_domain("example.com" / None / "")`. b/588990592 --- .../google/auth/external_account.py | 2 +- .../tests/test_external_account.py | 28 +++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/packages/google-auth/google/auth/external_account.py b/packages/google-auth/google/auth/external_account.py index baf1ef372f2a..5773d9b7d7f9 100644 --- a/packages/google-auth/google/auth/external_account.py +++ b/packages/google-auth/google/auth/external_account.py @@ -433,7 +433,7 @@ def get_project_id(self, request): # Avoid sending tokens minted for non-googleapis.com endpoints # (e.g. another universe domain or custom proxy) to # cloudresourcemanager.googleapis.com. - if self.universe_domain == credentials.DEFAULT_UNIVERSE_DOMAIN: + if _has_default_universe_host(self._cloud_resource_manager_url): if not _has_default_universe_host(self._token_url): return None # Impersonation is optional; calling _has_default_universe_host(None) diff --git a/packages/google-auth/tests/test_external_account.py b/packages/google-auth/tests/test_external_account.py index 91d451371713..de736dcf4a07 100644 --- a/packages/google-auth/tests/test_external_account.py +++ b/packages/google-auth/tests/test_external_account.py @@ -2367,6 +2367,34 @@ def test_get_project_id_skips_non_default_universe_endpoints( assert project_id is None request.assert_not_called() + @pytest.mark.parametrize( + "universe_domain", + [ + pytest.param("example.com", id="custom_universe"), + pytest.param(None, id="none_universe"), + pytest.param("", id="empty_universe"), + ], + ) + def test_get_project_id_skips_default_crm_url_after_with_universe_domain( + self, universe_domain + ): + request = mock.create_autospec(transport.Request) + credentials = CredentialsImpl.from_info( + { + "type": "external_account", + "audience": self.AUDIENCE, + "subject_token_type": self.SUBJECT_TOKEN_TYPE, + "token_url": "https://sts.example.com/v1/token", + "credential_source": self.CREDENTIAL_SOURCE, + }, + scopes=self.SCOPES, + ).with_universe_domain(universe_domain) + + project_id = credentials.get_project_id(request) + + assert project_id is None + request.assert_not_called() + def test_get_project_id_allows_default_universe_token_url_when_universe_omitted( self, ): From 5ef820bfada4bc3cf912d2796d69e033a3910d4f Mon Sep 17 00:00:00 2001 From: ohmayr Date: Wed, 25 Nov 2026 19:36:03 +0000 Subject: [PATCH 3/4] fix(auth): harden external_account default-universe host check Reject URL fragments ("#"), userinfo ("@" in netloc), and invalid DNS labels in _has_default_universe_host() to align with #19163. Check "@" on parsed.netloc rather than the raw URL so valid service_account_impersonation_url paths containing service account emails remain allowed. b/588990592 --- .../google/auth/external_account.py | 21 +++++++++++++------ .../tests/test_external_account.py | 15 +++++++++++++ 2 files changed, 30 insertions(+), 6 deletions(-) diff --git a/packages/google-auth/google/auth/external_account.py b/packages/google-auth/google/auth/external_account.py index 5773d9b7d7f9..5b568270d40b 100644 --- a/packages/google-auth/google/auth/external_account.py +++ b/packages/google-auth/google/auth/external_account.py @@ -67,15 +67,24 @@ _DEFAULT_TOKEN_URL = "https://sts.{universe_domain}/v1/token" +_DEFAULT_UNIVERSE_HOST_PATTERN = re.compile( + rf"^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)*{re.escape(credentials.DEFAULT_UNIVERSE_DOMAIN)}$" +) + + def _has_default_universe_host(url): """Checks whether a URL's host is in the default universe domain.""" + if not isinstance(url, str) or "#" in url: + return False try: - host = urlparse(url).hostname - return host is not None and ( - host == credentials.DEFAULT_UNIVERSE_DOMAIN - or host.endswith(f".{credentials.DEFAULT_UNIVERSE_DOMAIN}") - ) - except (ValueError, TypeError, AttributeError): + parsed = urlparse(url) + # Reject userinfo ("@" in netloc) without rejecting "@" in the path + # (such as service account emails in service_account_impersonation_url). + if "@" in parsed.netloc: + return False + host = parsed.hostname + return bool(host and _DEFAULT_UNIVERSE_HOST_PATTERN.fullmatch(host)) + except ValueError: return False diff --git a/packages/google-auth/tests/test_external_account.py b/packages/google-auth/tests/test_external_account.py index de736dcf4a07..c0c494e12562 100644 --- a/packages/google-auth/tests/test_external_account.py +++ b/packages/google-auth/tests/test_external_account.py @@ -2345,6 +2345,21 @@ def test_get_project_id_cloud_resource_manager_custom_universe_domain(self): ), pytest.param(None, None, id="missing_token_url"), pytest.param("https://[invalid/v1/token", None, id="malformed_token_url"), + pytest.param( + "https://evil.com\\@sts.googleapis.com/v1/token", + None, + id="userinfo_in_token_url", + ), + pytest.param( + "https://sts.googleapis.com#evil.com", + None, + id="fragment_in_token_url", + ), + pytest.param( + "https://.googleapis.com/v1/token", + None, + id="empty_label_token_url", + ), ], ) def test_get_project_id_skips_non_default_universe_endpoints( From 22e6539de4c7713481d148f44d0edaae7bad05e8 Mon Sep 17 00:00:00 2001 From: ohmayr Date: Wed, 25 Nov 2026 19:46:15 +0000 Subject: [PATCH 4/4] refactor(auth): move has_default_universe_host to _helpers Move _has_default_universe_host() from external_account.py to google.auth._helpers.has_default_universe_host() so other google-auth modules can reuse it, and add direct unit tests in test__helpers.py. b/588990592 --- packages/google-auth/google/auth/_helpers.py | 31 ++++++++++++- .../google/auth/external_account.py | 34 +++----------- packages/google-auth/tests/test__helpers.py | 45 +++++++++++++++++++ 3 files changed, 81 insertions(+), 29 deletions(-) diff --git a/packages/google-auth/google/auth/_helpers.py b/packages/google-auth/google/auth/_helpers.py index 568def959d5a..780c99c40d34 100644 --- a/packages/google-auth/google/auth/_helpers.py +++ b/packages/google-auth/google/auth/_helpers.py @@ -20,14 +20,18 @@ import hashlib import json import logging +import re import sys -import urllib +import urllib.parse from email.message import Message from typing import Any, Dict, Mapping, Optional, Union from google.auth import exceptions DEFAULT_UNIVERSE_DOMAIN = "googleapis.com" +_DEFAULT_UNIVERSE_HOST_PATTERN = re.compile( + rf"^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)*{re.escape(DEFAULT_UNIVERSE_DOMAIN)}$" +) # _BASE_LOGGER_NAME is the base logger for all google-based loggers. _BASE_LOGGER_NAME = "google" @@ -247,6 +251,31 @@ def update_query(url, params, remove=None): return urllib.parse.urlunparse(new_parts) +def has_default_universe_host(url): + """Checks whether a URL's host is in the default universe domain. + + Args: + url (Optional[str]): The URL to inspect. + + Returns: + bool: True if ``url`` has a valid ``googleapis.com`` or + ``*.googleapis.com`` host without userinfo or fragments; False + otherwise. + """ + if not isinstance(url, str) or "#" in url: + return False + try: + parsed = urllib.parse.urlparse(url) + # Reject userinfo ("@" in netloc) without rejecting "@" in the path + # (such as service account emails in service_account_impersonation_url). + if "@" in parsed.netloc: + return False + host = parsed.hostname + return bool(host and _DEFAULT_UNIVERSE_HOST_PATTERN.fullmatch(host)) + except ValueError: + return False + + def scopes_to_string(scopes): """Converts scope value to a string suitable for sending to OAuth 2.0 authorization servers. diff --git a/packages/google-auth/google/auth/external_account.py b/packages/google-auth/google/auth/external_account.py index 5b568270d40b..505f013a793e 100644 --- a/packages/google-auth/google/auth/external_account.py +++ b/packages/google-auth/google/auth/external_account.py @@ -38,7 +38,6 @@ import threading from dataclasses import dataclass from typing import TYPE_CHECKING, Optional -from urllib.parse import urlparse from google.auth import ( _helpers, @@ -67,27 +66,6 @@ _DEFAULT_TOKEN_URL = "https://sts.{universe_domain}/v1/token" -_DEFAULT_UNIVERSE_HOST_PATTERN = re.compile( - rf"^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)*{re.escape(credentials.DEFAULT_UNIVERSE_DOMAIN)}$" -) - - -def _has_default_universe_host(url): - """Checks whether a URL's host is in the default universe domain.""" - if not isinstance(url, str) or "#" in url: - return False - try: - parsed = urlparse(url) - # Reject userinfo ("@" in netloc) without rejecting "@" in the path - # (such as service account emails in service_account_impersonation_url). - if "@" in parsed.netloc: - return False - host = parsed.hostname - return bool(host and _DEFAULT_UNIVERSE_HOST_PATTERN.fullmatch(host)) - except ValueError: - return False - - @dataclass class SupplierContext: """A context class that contains information about the requested third party credential that is passed @@ -442,15 +420,15 @@ def get_project_id(self, request): # Avoid sending tokens minted for non-googleapis.com endpoints # (e.g. another universe domain or custom proxy) to # cloudresourcemanager.googleapis.com. - if _has_default_universe_host(self._cloud_resource_manager_url): - if not _has_default_universe_host(self._token_url): + if _helpers.has_default_universe_host(self._cloud_resource_manager_url): + if not _helpers.has_default_universe_host(self._token_url): return None - # Impersonation is optional; calling _has_default_universe_host(None) - # returns False and would block non-impersonated default-universe - # credentials. + # Impersonation is optional; calling + # has_default_universe_host(None) returns False and would block + # non-impersonated default-universe credentials. if ( self._service_account_impersonation_url - and not _has_default_universe_host( + and not _helpers.has_default_universe_host( self._service_account_impersonation_url ) ): diff --git a/packages/google-auth/tests/test__helpers.py b/packages/google-auth/tests/test__helpers.py index 5755e2a357d2..9b431401aca0 100644 --- a/packages/google-auth/tests/test__helpers.py +++ b/packages/google-auth/tests/test__helpers.py @@ -697,3 +697,48 @@ def test_out_of_range(self): with pytest.raises((OverflowError, OSError, ValueError)): # Large enough to fail on most systems (Year 300,000+) _helpers.utcfromtimestamp(9999999999999) + + +@pytest.mark.parametrize( + "url,expected", + [ + pytest.param("https://googleapis.com/v1/token", True, id="exact_default"), + pytest.param("https://sts.googleapis.com/v1/token", True, id="subdomain"), + pytest.param("HTTPS://STS.GOOGLEAPIS.COM/v1/token", True, id="uppercase_host"), + pytest.param( + "https://us-east1-iamcredentials.googleapis.com/v1/projects/-" + "/serviceAccounts/sa@p.iam.gserviceaccount.com:generateAccessToken", + True, + id="at_sign_in_path", + ), + pytest.param("https://sts.example.com/v1/token", False, id="other_universe"), + pytest.param( + "https://sts.googleapis.com.evil.com/v1/token", + False, + id="spoofed_suffix", + ), + pytest.param("https://evilgoogleapis.com/v1/token", False, id="missing_dot"), + pytest.param( + "https://.googleapis.com/v1/token", False, id="empty_leading_label" + ), + pytest.param( + "https://foo..googleapis.com/v1/token", False, id="empty_middle_label" + ), + pytest.param( + "https://evil.com@sts.googleapis.com/v1/token", + False, + id="userinfo_at", + ), + pytest.param( + "https://evil.com\\@sts.googleapis.com/v1/token", + False, + id="userinfo_backslash_at", + ), + pytest.param("https://sts.googleapis.com#evil.com", False, id="fragment_hash"), + pytest.param("https://[invalid/v1/token", False, id="malformed_url"), + pytest.param("", False, id="empty_string"), + pytest.param(None, False, id="none_input"), + ], +) +def test_has_default_universe_host(url, expected): + assert _helpers.has_default_universe_host(url) is expected