From 8ddd9bb9920727a5a3b12c77637529281d6b55aa Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Wed, 25 Nov 2026 11:53:53 -0500 Subject: [PATCH 1/4] test(api_core): add unit tests for shared universe_domain helpers --- packages/google-api-core/tests/conftest.py | 8 + .../tests/unit/test_grpc_helpers.py | 62 +- .../tests/unit/test_universe.py | 793 ++++++++++++++++++ 3 files changed, 822 insertions(+), 41 deletions(-) diff --git a/packages/google-api-core/tests/conftest.py b/packages/google-api-core/tests/conftest.py index b32d696bb58d..73962b17aed0 100644 --- a/packages/google-api-core/tests/conftest.py +++ b/packages/google-api-core/tests/conftest.py @@ -20,6 +20,8 @@ import pytest +from google.api_core import universe + @pytest.fixture(scope="session", autouse=True) def mock_mtls_env(): @@ -34,6 +36,12 @@ def mock_mtls_env(): yield +@pytest.fixture(autouse=True) +def clean_universe_env(monkeypatch): + """Autouse fixture to isolate unit tests from workstation GOOGLE_CLOUD_UNIVERSE_DOMAIN.""" + monkeypatch.delenv(universe.UNIVERSE_DOMAIN_ENV, raising=False) + + @pytest.fixture def mock_otel(monkeypatch): """Provides a mocked OpenTelemetry environment with tracing enabled.""" diff --git a/packages/google-api-core/tests/unit/test_grpc_helpers.py b/packages/google-api-core/tests/unit/test_grpc_helpers.py index 5e063fe92d58..593b2dfd7301 100644 --- a/packages/google-api-core/tests/unit/test_grpc_helpers.py +++ b/packages/google-api-core/tests/unit/test_grpc_helpers.py @@ -1173,6 +1173,26 @@ def test__extract_target_host(target, expected_host): True, "google-c2p:///storage-direct.googleapis.com?foo=bar&force-xds", ), + ( + "dns:storage-direct.googleapis.com:443", + False, + "google-c2p:///storage-direct.googleapis.com", + ), + ( + "HTTPS://storage-direct.googleapis.com:443/v1", + True, + "google-c2p:///storage-direct.googleapis.com?force-xds", + ), + ( + "dns://8.8.8.8/storage-direct.googleapis.com:443", + True, + "dns://8.8.8.8/storage-direct.googleapis.com:443", + ), + ( + "another-c2p:///storage-direct.googleapis.com", + True, + "another-c2p:///storage-direct.googleapis.com", + ), ], ) def test__modify_target_for_direct_path_interconnect( @@ -1464,47 +1484,6 @@ def test_create_channel_interconnect_gated_by_attempt_direct_path( ) -@pytest.mark.parametrize( - "target,expected", - [ - ("storage.googleapis.com:443", True), - ("storage.googleapis.com", True), - ("googleapis.com:443", True), - ("googleapis.com", True), - ("storage-direct.googleapis.com:443", True), - ("us-east1-pubsub.googleapis.com:443", True), - ("storage.mtls.googleapis.com:443", True), - ("storage.mtls.sandbox.googleapis.com:443", True), - ("a.googleapis.com:443", True), - ("STORAGE.GOOGLEAPIS.COM:443", True), - ("dns:///storage.googleapis.com:443", True), - ("https://storage.googleapis.com:443/v1", True), - ("http://storage.googleapis.com:443", True), - ("google-c2p:///storage-direct.googleapis.com?force-xds", True), - ("storage.universe.domain:443", False), - ("dns:///storage.universe.domain:443", False), - ("https://storage.universe.domain:443", False), - ("google-c2p:///storage.universe.domain", False), - ("evilgoogleapis.com:443", False), - ("storage.googleapis.com.universe.domain:443", False), - (".googleapis.com:443", False), - ("-direct.googleapis.com:443", False), - ("storage-.googleapis.com:443", False), - ("a..b.googleapis.com:443", False), - ("https://?.googleapis.com", False), - ("[invalid.googleapis.com", False), - ("user@storage.googleapis.com:443", False), - ("storage.universe.domain:443@storage.googleapis.com", False), - ("storage.googleapis.com#universe.domain", False), - ("another-c2p:///storage.googleapis.com", False), - ("[::1]:8080", False), - ("", False), - ], -) -def test__is_googleapis_host(target, expected): - assert grpc_helpers._is_googleapis_host(target) is expected - - @mock.patch("grpc.compute_engine_channel_credentials") @mock.patch("grpc.metadata_call_credentials") @mock.patch("google.auth.transport.grpc.AuthMetadataPlugin") @@ -1554,6 +1533,7 @@ def test__compose_channel_credentials_legacy_auth_metadata_plugin( [ "storage.universe.domain:443", "dns:///storage.universe.domain:443", + "dns://8.8.8.8/storage.googleapis.com:443", "evilgoogleapis.com:443", "storage.googleapis.com.universe.domain:443", ], diff --git a/packages/google-api-core/tests/unit/test_universe.py b/packages/google-api-core/tests/unit/test_universe.py index 84d271d5115b..5157771833ec 100644 --- a/packages/google-api-core/tests/unit/test_universe.py +++ b/packages/google-api-core/tests/unit/test_universe.py @@ -12,11 +12,27 @@ # See the License for the specific language governing permissions and # limitations under the License. +import re +import types + import pytest +from google.auth import credentials as auth_credentials from google.auth.exceptions import MutualTLSChannelError +from google.api_core import client_options as client_options_lib from google.api_core import universe +from ..helpers import warn_deprecated_credentials_file + +TPC_UNIVERSE = "apis-tpclp.goog" +ALT_UNIVERSE = "other.goog" +CHILD_UNIVERSE = "child.goog" +PARENT_ENDPOINT = "parent.custom.test:443" +CHILD_ENDPOINT = "child.custom.test:443" +TEST_QUOTA_PROJECT = "qp-1" +TEST_API_KEY = "secret-key" +TEST_CREDENTIALS_FILE = "/path/to/creds.json" + class _Fake_Credentials: def __init__(self, universe_domain=None): @@ -24,6 +40,19 @@ def __init__(self, universe_domain=None): self.universe_domain = universe_domain +class _StubCredentials(auth_credentials.Credentials): + def __init__(self, universe_domain: str = universe.DEFAULT_UNIVERSE): + super().__init__() + self._test_universe_domain = universe_domain + + @property + def universe_domain(self) -> str: + return self._test_universe_domain + + def refresh(self, request): # pragma: NO COVER + pass + + def test_determine_domain(): domain_client = "foo.com" domain_env = "bar.com" @@ -259,3 +288,767 @@ def test_get_api_endpoint( ) == expected ) + + +class TestResolveClientUniverse: + def test_default_argument_omitted(self): + assert universe.resolve_client_universe() == universe.DEFAULT_UNIVERSE + + @pytest.mark.parametrize( + ("client_options", "env_val", "expected"), + [ + pytest.param(None, None, universe.DEFAULT_UNIVERSE, id="default_none"), + pytest.param({}, None, universe.DEFAULT_UNIVERSE, id="empty_dict"), + pytest.param( + client_options_lib.ClientOptions(), + None, + universe.DEFAULT_UNIVERSE, + id="empty_client_options", + ), + pytest.param( + None, + TPC_UNIVERSE, + TPC_UNIVERSE, + id="env_var_fallback", + ), + pytest.param( + {"universe_domain": None}, + f" {TPC_UNIVERSE} ", + TPC_UNIVERSE, + id="dict_none_falls_back_to_stripped_env", + ), + pytest.param( + {"universe_domain": TPC_UNIVERSE}, + None, + TPC_UNIVERSE, + id="dict_explicit", + ), + pytest.param( + types.MappingProxyType({"universe_domain": TPC_UNIVERSE}), + ALT_UNIVERSE, + TPC_UNIVERSE, + id="mapping_proxy_overrides_env", + ), + pytest.param( + client_options_lib.ClientOptions(universe_domain=TPC_UNIVERSE), + ALT_UNIVERSE, + TPC_UNIVERSE, + id="client_options_overrides_env", + ), + pytest.param( + {"universe_domain": universe.DEFAULT_UNIVERSE}, + TPC_UNIVERSE, + universe.DEFAULT_UNIVERSE, + id="explicit_gdu_overrides_tpc_env", + ), + ], + ) + def test_precedence(self, monkeypatch, client_options, env_val, expected): + if env_val is not None: + monkeypatch.setenv(universe.UNIVERSE_DOMAIN_ENV, env_val) + + assert universe.resolve_client_universe(client_options) == expected + + @pytest.mark.parametrize( + ("client_options", "env_val"), + [ + pytest.param({"universe_domain": ""}, None, id="empty_in_dict"), + pytest.param( + {"universe_domain": ""}, + TPC_UNIVERSE, + id="empty_in_dict_not_masked_by_env", + ), + pytest.param( + client_options_lib.ClientOptions(universe_domain=" "), + None, + id="whitespace_in_client_options", + ), + pytest.param(None, "", id="empty_in_env"), + pytest.param(None, " ", id="whitespace_in_env"), + ], + ) + def test_empty_raises(self, monkeypatch, client_options, env_val): + if env_val is not None: + monkeypatch.setenv(universe.UNIVERSE_DOMAIN_ENV, env_val) + + with pytest.raises( + universe.EmptyUniverseError, + match="Universe Domain cannot be an empty string", + ): + universe.resolve_client_universe(client_options) + + def test_invalid_client_options_type_raises_type_error(self): + with pytest.raises(TypeError, match="ClientOptions instance, Mapping, or None"): + # Pass an invalid str on purpose to verify runtime TypeError handling; + # mypy flags the intentional type mismatch without this ignore. + universe.resolve_client_universe("invalid") # type: ignore[arg-type] + + +class TestValidateCredentialsUniverse: + @pytest.mark.parametrize( + ("client_universe", "credentials"), + [ + pytest.param( + universe.DEFAULT_UNIVERSE, + None, + id="none_in_default_universe", + ), + pytest.param(TPC_UNIVERSE, None, id="none_in_custom_universe"), + pytest.param( + universe.DEFAULT_UNIVERSE, + auth_credentials.AnonymousCredentials(), + id="anonymous_in_default_universe", + ), + pytest.param( + TPC_UNIVERSE, + auth_credentials.AnonymousCredentials(), + id="anonymous_in_custom_universe", + ), + ], + ) + def test_exempts_none_and_anonymous(self, client_universe, credentials): + assert ( + universe.validate_credentials_universe(client_universe, credentials) is None + ) + + @pytest.mark.parametrize( + ("client_universe", "credentials"), + [ + pytest.param( + universe.DEFAULT_UNIVERSE, + _StubCredentials(universe.DEFAULT_UNIVERSE), + id="default_universe", + ), + pytest.param( + TPC_UNIVERSE, + _StubCredentials(TPC_UNIVERSE), + id="custom_universe", + ), + pytest.param( + universe.DEFAULT_UNIVERSE, + _Fake_Credentials(), + id="legacy_credentials_without_attr_default_to_gdu", + ), + ], + ) + def test_matching_universes_succeed(self, client_universe, credentials): + assert ( + universe.validate_credentials_universe(client_universe, credentials) is None + ) + + @pytest.mark.parametrize( + ("client_universe", "cred_universe"), + [ + pytest.param( + universe.DEFAULT_UNIVERSE, + TPC_UNIVERSE, + id="gdu_vs_tpc", + ), + pytest.param( + TPC_UNIVERSE, + universe.DEFAULT_UNIVERSE, + id="tpc_vs_gdu", + ), + pytest.param( + TPC_UNIVERSE, + ALT_UNIVERSE, + id="tpc_vs_other_tpc", + ), + ], + ) + def test_mismatch_raises(self, client_universe, cred_universe): + creds = _StubCredentials(cred_universe) + expected_pattern = ( + rf"configured universe domain \({re.escape(client_universe)}\)" + rf".*credentials \({re.escape(cred_universe)}\)" + ) + + with pytest.raises(universe.UniverseMismatchError, match=expected_pattern): + universe.validate_credentials_universe(client_universe, creds) + + def test_legacy_credentials_without_universe_attr_mismatch_custom_universe(self): + with pytest.raises( + universe.UniverseMismatchError, + match=r"configured universe domain \(apis-tpclp\.goog\).*credentials \(googleapis\.com\)", + ): + # Verify runtime getattr fallback for legacy custom credential objects; + # mypy expects google.auth.credentials.Credentials. + universe.validate_credentials_universe( + TPC_UNIVERSE, + _Fake_Credentials(), # type: ignore[arg-type] + ) + + +class TestInheritUniverseInClientOptions: + @pytest.mark.parametrize( + "env_val", + [ + pytest.param(None, id="env_unset"), + pytest.param(universe.DEFAULT_UNIVERSE, id="env_matches_gdu"), + pytest.param(f" {universe.DEFAULT_UNIVERSE} ", id="env_padded_gdu"), + ], + ) + def test_none_options_in_default_universe_returns_none(self, monkeypatch, env_val): + if env_val is not None: + monkeypatch.setenv(universe.UNIVERSE_DOMAIN_ENV, env_val) + + assert ( + universe.inherit_universe_in_client_options(universe.DEFAULT_UNIVERSE, None) + is None + ) + + @pytest.mark.parametrize( + ("parent_universe", "env_val", "expected_universe"), + [ + pytest.param( + TPC_UNIVERSE, + None, + TPC_UNIVERSE, + id="custom_parent_creates_options", + ), + pytest.param( + universe.DEFAULT_UNIVERSE, + TPC_UNIVERSE, + universe.DEFAULT_UNIVERSE, + id="explicit_gdu_parent_overrides_tpc_env", + ), + pytest.param( + universe.DEFAULT_UNIVERSE, + "", + universe.DEFAULT_UNIVERSE, + id="explicit_gdu_parent_overrides_empty_env", + ), + pytest.param( + universe.DEFAULT_UNIVERSE, + " ", + universe.DEFAULT_UNIVERSE, + id="explicit_gdu_parent_overrides_whitespace_env", + ), + ], + ) + def test_none_options_propagates_universe( + self, monkeypatch, parent_universe, env_val, expected_universe + ): + if env_val is not None: + monkeypatch.setenv(universe.UNIVERSE_DOMAIN_ENV, env_val) + + opts = universe.inherit_universe_in_client_options(parent_universe, None) + + assert opts is not None + assert opts.universe_domain == expected_universe + + @pytest.mark.parametrize( + ("parent_universe", "input_dict", "expected_universe"), + [ + pytest.param( + TPC_UNIVERSE, + {"quota_project_id": TEST_QUOTA_PROJECT}, + TPC_UNIVERSE, + id="custom_parent_inherits_onto_unset_mapping", + ), + pytest.param( + universe.DEFAULT_UNIVERSE, + {"quota_project_id": TEST_QUOTA_PROJECT}, + None, + id="default_parent_leaves_unset_mapping_none", + ), + pytest.param( + TPC_UNIVERSE, + { + "quota_project_id": TEST_QUOTA_PROJECT, + "universe_domain": CHILD_UNIVERSE, + }, + CHILD_UNIVERSE, + id="preserves_explicit_child_universe", + ), + pytest.param( + TPC_UNIVERSE, + {"quota_project_id": TEST_QUOTA_PROJECT, "universe_domain": ""}, + "", + id="preserves_explicit_empty_string_in_mapping", + ), + ], + ) + def test_mapping_options_universe_inheritance( + self, parent_universe, input_dict, expected_universe + ): + caller_dict = dict(input_dict) + + opts = universe.inherit_universe_in_client_options(parent_universe, caller_dict) + + assert opts is not None + assert opts.universe_domain == expected_universe + assert opts.quota_project_id == TEST_QUOTA_PROJECT + assert caller_dict == input_dict + + @pytest.mark.parametrize( + "cred_entry", + [ + pytest.param( + {"credentials_file": TEST_CREDENTIALS_FILE}, + id="clears_credentials_file", + ), + pytest.param({"api_key": TEST_API_KEY}, id="clears_api_key"), + ], + ) + def test_mapping_clears_credentials_when_requested(self, cred_entry): + caller_dict = {"universe_domain": CHILD_UNIVERSE, **cred_entry} + + opts = universe.inherit_universe_in_client_options( + TPC_UNIVERSE, + caller_dict, + clear_credentials=True, + ) + + assert opts is not None + assert opts.universe_domain == CHILD_UNIVERSE + assert opts.credentials_file is None + assert opts.api_key is None + assert caller_dict == {"universe_domain": CHILD_UNIVERSE, **cred_entry} + + def test_mapping_preserves_credentials_when_clear_credentials_false(self): + opts = universe.inherit_universe_in_client_options( + TPC_UNIVERSE, + { + "credentials_file": TEST_CREDENTIALS_FILE, + "api_key": TEST_API_KEY, + }, + clear_credentials=False, + ) + + assert opts is not None + assert opts.universe_domain == TPC_UNIVERSE + assert opts.credentials_file == TEST_CREDENTIALS_FILE + assert opts.api_key == TEST_API_KEY + + @pytest.mark.parametrize( + ("parent_universe", "initial_universe", "clear_credentials"), + [ + pytest.param( + universe.DEFAULT_UNIVERSE, + None, + False, + id="default_parent_unset_child", + ), + pytest.param( + universe.DEFAULT_UNIVERSE, + None, + True, + id="clear_credentials_without_creds_set", + ), + pytest.param( + TPC_UNIVERSE, + CHILD_UNIVERSE, + False, + id="explicit_child_universe_preserved", + ), + pytest.param( + TPC_UNIVERSE, + "", + False, + id="explicit_empty_child_universe_preserved", + ), + ], + ) + def test_client_options_obj_no_changes_returns_same_instance( + self, parent_universe, initial_universe, clear_credentials + ): + original = client_options_lib.ClientOptions( + universe_domain=initial_universe, + quota_project_id=TEST_QUOTA_PROJECT, + ) + + result = universe.inherit_universe_in_client_options( + parent_universe, + original, + clear_credentials=clear_credentials, + ) + + assert result is original + assert result.universe_domain == initial_universe + + def test_client_options_obj_inherits_via_shallow_copy(self): + original = client_options_lib.ClientOptions( + quota_project_id=TEST_QUOTA_PROJECT, + api_key=TEST_API_KEY, + ) + + result = universe.inherit_universe_in_client_options(TPC_UNIVERSE, original) + + assert result is not original + assert result is not None + assert result.universe_domain == TPC_UNIVERSE + assert result.quota_project_id == TEST_QUOTA_PROJECT + assert result.api_key == TEST_API_KEY + assert original.universe_domain is None + + @pytest.mark.parametrize( + ("initial_universe", "expected_universe"), + [ + pytest.param(CHILD_UNIVERSE, CHILD_UNIVERSE, id="clear_api_key_only"), + pytest.param(None, TPC_UNIVERSE, id="inherit_universe_and_clear_api_key"), + ], + ) + def test_client_options_obj_clears_api_key( + self, initial_universe, expected_universe + ): + original = client_options_lib.ClientOptions( + universe_domain=initial_universe, + api_key=TEST_API_KEY, + ) + + result = universe.inherit_universe_in_client_options( + TPC_UNIVERSE, + original, + clear_credentials=True, + ) + + assert result is not original + assert result is not None + assert result.universe_domain == expected_universe + assert result.api_key is None + assert original.universe_domain == initial_universe + assert original.api_key == TEST_API_KEY + + def test_client_options_obj_clears_credentials_file(self): + with warn_deprecated_credentials_file(): + original = client_options_lib.ClientOptions( + credentials_file=TEST_CREDENTIALS_FILE, + ) + + result = universe.inherit_universe_in_client_options( + TPC_UNIVERSE, + original, + clear_credentials=True, + ) + + assert result is not original + assert result is not None + assert result.universe_domain == TPC_UNIVERSE + assert result.credentials_file is None + assert original.credentials_file == TEST_CREDENTIALS_FILE + + @pytest.mark.parametrize( + ("parent_universe", "expected_universe"), + [ + pytest.param(universe.DEFAULT_UNIVERSE, None, id="default_parent"), + pytest.param(TPC_UNIVERSE, TPC_UNIVERSE, id="custom_parent"), + ], + ) + def test_none_options_inherits_parent_api_endpoint( + self, parent_universe, expected_universe + ): + opts = universe.inherit_universe_in_client_options( + parent_universe, + None, + parent_api_endpoint=PARENT_ENDPOINT, + ) + + assert opts is not None + assert opts.api_endpoint == PARENT_ENDPOINT + assert opts.universe_domain == expected_universe + + @pytest.mark.parametrize( + ("child_dict", "expected_endpoint", "expected_universe"), + [ + pytest.param( + {"quota_project_id": TEST_QUOTA_PROJECT}, + PARENT_ENDPOINT, + TPC_UNIVERSE, + id="unset_child_inherits_parent_endpoint_and_universe", + ), + pytest.param( + {"api_endpoint": CHILD_ENDPOINT}, + CHILD_ENDPOINT, + TPC_UNIVERSE, + id="explicit_child_endpoint_wins_and_inherits_universe", + ), + pytest.param( + {"universe_domain": CHILD_UNIVERSE}, + None, + CHILD_UNIVERSE, + id="explicit_child_universe_blocks_parent_endpoint", + ), + pytest.param( + {"universe_domain": universe.DEFAULT_UNIVERSE}, + None, + universe.DEFAULT_UNIVERSE, + id="explicit_gdu_child_universe_blocks_parent_endpoint", + ), + ], + ) + def test_mapping_parent_api_endpoint_precedence( + self, child_dict, expected_endpoint, expected_universe + ): + caller_dict = dict(child_dict) + + opts = universe.inherit_universe_in_client_options( + TPC_UNIVERSE, + caller_dict, + parent_api_endpoint=PARENT_ENDPOINT, + ) + + assert opts is not None + assert opts.api_endpoint == expected_endpoint + assert opts.universe_domain == expected_universe + assert caller_dict == child_dict + + @pytest.mark.parametrize( + ( + "parent_universe", + "child_endpoint", + "child_universe", + "expected_endpoint", + "expected_universe", + "expect_same_instance", + ), + [ + pytest.param( + universe.DEFAULT_UNIVERSE, + None, + None, + PARENT_ENDPOINT, + None, + False, + id="default_parent_copies_only_parent_endpoint", + ), + pytest.param( + TPC_UNIVERSE, + None, + None, + PARENT_ENDPOINT, + TPC_UNIVERSE, + False, + id="custom_parent_copies_both_endpoint_and_universe", + ), + pytest.param( + TPC_UNIVERSE, + CHILD_ENDPOINT, + None, + CHILD_ENDPOINT, + TPC_UNIVERSE, + False, + id="child_endpoint_preserved_while_universe_inherited", + ), + pytest.param( + TPC_UNIVERSE, + None, + CHILD_UNIVERSE, + None, + CHILD_UNIVERSE, + True, + id="child_universe_blocks_parent_endpoint_returns_same_obj", + ), + pytest.param( + universe.DEFAULT_UNIVERSE, + CHILD_ENDPOINT, + None, + CHILD_ENDPOINT, + None, + True, + id="default_parent_with_child_endpoint_returns_same_obj", + ), + ], + ) + def test_client_options_obj_parent_api_endpoint_precedence( + self, + parent_universe, + child_endpoint, + child_universe, + expected_endpoint, + expected_universe, + expect_same_instance, + ): + original = client_options_lib.ClientOptions( + api_endpoint=child_endpoint, + universe_domain=child_universe, + ) + + result = universe.inherit_universe_in_client_options( + parent_universe, + original, + parent_api_endpoint=PARENT_ENDPOINT, + ) + + assert result is not None + assert (result is original) is expect_same_instance + assert result.api_endpoint == expected_endpoint + assert result.universe_domain == expected_universe + assert original.api_endpoint == child_endpoint + assert original.universe_domain == child_universe + + def test_invalid_client_options_type_raises_type_error(self): + with pytest.raises(TypeError, match="ClientOptions instance, Mapping, or None"): + # Pass an invalid str on purpose to verify runtime TypeError handling; + # mypy flags the intentional type mismatch without this ignore. + universe.inherit_universe_in_client_options( + universe.DEFAULT_UNIVERSE, + "invalid", # type: ignore[arg-type] + ) + + +class TestIsGoogleapisHost: + @pytest.mark.parametrize( + ("target", "expected"), + [ + pytest.param("storage.googleapis.com:443", True, id="grpc_host_port"), + pytest.param("storage.googleapis.com", True, id="bare_service_host"), + pytest.param("googleapis.com:443", True, id="root_domain_port"), + pytest.param("googleapis.com", True, id="root_domain"), + pytest.param( + "storage-direct.googleapis.com:443", True, id="directpath_host" + ), + pytest.param("us-east1-pubsub.googleapis.com:443", True, id="zonal_host"), + pytest.param("storage.mtls.googleapis.com:443", True, id="mtls_host"), + pytest.param( + "storage.mtls.sandbox.googleapis.com:443", + True, + id="mtls_sandbox_host", + ), + pytest.param( + "us-central1-bigquery.rep.googleapis.com", True, id="rep_host" + ), + pytest.param("bigquery-psc.p.googleapis.com", True, id="psc_host"), + pytest.param("oauth2.googleapis.com:443", True, id="label_trailing_digit"), + pytest.param("3p.googleapis.com:443", True, id="label_leading_digit"), + pytest.param("STORAGE.GOOGLEAPIS.COM:443", True, id="uppercase_host"), + pytest.param( + "dns:///storage.googleapis.com:443", True, id="dns_triple_slash" + ), + pytest.param( + "DNS:///storage.googleapis.com:443", + True, + id="uppercase_dns_triple_slash", + ), + pytest.param("dns:storage.googleapis.com:443", True, id="dns_no_slash"), + pytest.param( + "dns://8.8.8.8/storage.googleapis.com:443", + True, + id="dns_with_authority", + ), + pytest.param( + "https://storage.googleapis.com:443/v1?alt=json", + True, + id="https_url_with_path_and_query", + ), + pytest.param( + "HTTPS://storage.googleapis.com:443/v1", + True, + id="uppercase_https_url", + ), + pytest.param("http://storage.googleapis.com:443", True, id="http_url"), + pytest.param( + "google-c2p:///storage-direct.googleapis.com?force-xds", + True, + id="google_c2p_directpath", + ), + pytest.param( + "GOOGLE-C2P:///storage-direct.googleapis.com?force-xds", + True, + id="uppercase_google_c2p_directpath", + ), + pytest.param("storage.apis-tpclp.goog:443", False, id="tpc_host_port"), + pytest.param( + "dns:///storage.apis-tpclp.goog:443", False, id="dns_tpc_triple_slash" + ), + pytest.param( + "dns://8.8.8.8/storage.apis-tpclp.goog:443", + False, + id="dns_tpc_with_authority", + ), + pytest.param("dns://8.8.8.8", False, id="dns_authority_without_target"), + pytest.param( + "dns://storage.googleapis.com:443", + False, + id="dns_googleapis_authority_without_target", + ), + pytest.param( + "dns://storage.googleapis.com/storage.apis-tpclp.goog:443", + False, + id="dns_googleapis_authority_with_tpc_target", + ), + pytest.param( + "dns:////storage.googleapis.com:443", + False, + id="dns_quad_slash_extra_path", + ), + pytest.param( + "https://storage.apis-tpclp.goog:443/v1", False, id="https_tpc_url" + ), + pytest.param( + "http:storage.googleapis.com", + False, + id="http_scheme_missing_slashes", + ), + pytest.param( + "google-c2p:///storage.apis-tpclp.goog", False, id="c2p_tpc_target" + ), + pytest.param( + "google-c2p://storage.googleapis.com", + False, + id="c2p_double_slash_authority", + ), + pytest.param( + "google-c2p:storage.googleapis.com", + False, + id="c2p_no_slashes", + ), + pytest.param("evilgoogleapis.com:443", False, id="missing_dot_boundary"), + pytest.param( + "storage.googleapis.com.example.com:443", + False, + id="spoofed_trailing_suffix", + ), + pytest.param( + "storage.googleapis.com:evil.com", + False, + id="invalid_non_numeric_port", + ), + pytest.param( + "storage.googleapis.com:443:80", + False, + id="double_port_suffix", + ), + pytest.param( + "storage.googleapis.com:443/evil.com", + False, + id="non_http_path_segment", + ), + pytest.param(".googleapis.com:443", False, id="leading_dot_label"), + pytest.param("-direct.googleapis.com:443", False, id="leading_hyphen"), + pytest.param("storage-.googleapis.com:443", False, id="trailing_hyphen"), + pytest.param("a..b.googleapis.com:443", False, id="empty_middle_label"), + pytest.param("https://?.googleapis.com", False, id="query_before_host"), + pytest.param( + "https://[invalid.googleapis.com", False, id="malformed_https_ipv6" + ), + pytest.param("[invalid.googleapis.com", False, id="malformed_bare_ipv6"), + pytest.param("user@storage.googleapis.com:443", False, id="userinfo_at"), + pytest.param( + "storage.example.com:443@storage.googleapis.com", + False, + id="spoofed_userinfo_host", + ), + pytest.param( + "storage.googleapis.com#example.com", False, id="fragment_hash" + ), + pytest.param( + "another-c2p:///storage.googleapis.com", False, id="unknown_scheme" + ), + pytest.param("http://localhost:8080", False, id="localhost_emulator"), + pytest.param("[::1]:8080", False, id="ipv6_loopback"), + pytest.param("", False, id="empty_string"), + # Verify runtime guard returns False if None is passed dynamically; + # mypy expects str for url_or_target. + pytest.param(None, False, id="none_input"), # type: ignore[arg-type] + # Verify runtime isinstance(str) guard rejects truthy non-str inputs; + # mypy expects str for url_or_target. + pytest.param( + b"storage.googleapis.com:443", # type: ignore[arg-type] + False, + id="bytes_input", + ), + ], + ) + def test_is_googleapis_host(self, target, expected): + assert universe.is_googleapis_host(target) is expected From 168fa15fc5eac8afd212bd4667a935b3c1474a3b Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Wed, 25 Nov 2026 11:53:55 -0500 Subject: [PATCH 2/4] feat(api_core): add shared universe_domain client and host helpers --- .../google/api_core/grpc_helpers.py | 69 ++--- .../google/api_core/universe.py | 284 +++++++++++++++++- 2 files changed, 302 insertions(+), 51 deletions(-) diff --git a/packages/google-api-core/google/api_core/grpc_helpers.py b/packages/google-api-core/google/api_core/grpc_helpers.py index 51bf772c79f0..192a2c1c111f 100644 --- a/packages/google-api-core/google/api_core/grpc_helpers.py +++ b/packages/google-api-core/google/api_core/grpc_helpers.py @@ -17,8 +17,6 @@ import collections import functools import os -import re -import urllib.parse import warnings from typing import ( Callable, @@ -43,10 +41,6 @@ from google.api_core._feature_gating_helpers import _strtobool _DIRECT_PATH_INTERCONNECT_ENV = "GOOGLE_CLOUD_ENABLE_DIRECT_PATH_XDS_OVER_INTERCONNECT" -_GOOGLEAPIS_HOST_PATTERN = re.compile( - rf"^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)*{re.escape(universe.DEFAULT_UNIVERSE)}$", - re.IGNORECASE, -) def _resolve_direct_path_interconnect( @@ -85,24 +79,16 @@ def _resolve_direct_path_interconnect( def _extract_target_host(target: str) -> str: """Extracts the host from a target URI or address.""" - stripped_target = target - for prefix in ("google-c2p:///", "dns:///", "https://", "http://"): - if target.startswith(prefix): - stripped_target = target.removeprefix(prefix) - break - try: - return urllib.parse.urlsplit(f"//{stripped_target}").hostname or target - except ValueError: - return target + parsed = universe._parse_target(target) + return parsed.host if parsed is not None else target def _is_googleapis_host(target: str) -> bool: - """Returns True if ``target`` resolves to a ``googleapis.com`` host.""" - return ( - "@" not in target - and "#" not in target - and bool(_GOOGLEAPIS_HOST_PATTERN.fullmatch(_extract_target_host(target))) - ) + """Returns True if ``target`` is a DirectPath-eligible ``googleapis.com`` host.""" + parsed = universe._parse_target(target) + if parsed is None or parsed.authority: + return False + return bool(universe._GOOGLEAPIS_HOST_PATTERN.fullmatch(parsed.host)) def _extract_direct_path_authority(target: str) -> Optional[str]: @@ -475,7 +461,7 @@ def _setup_direct_path_and_credentials( target, attempt_direct_path_xds_over_interconnect=use_dp_interconnect, ) - elif not target.startswith("google-c2p:///"): + elif not target.lower().startswith("google-c2p:///"): clean_host = _extract_target_host(target) if clean_host.endswith("-direct.googleapis.com") and len(clean_host) > len( "-direct.googleapis.com" @@ -614,34 +600,21 @@ def _modify_target_for_direct_path( original target may already denote Direct Path. """ - # Strip standard URI scheme prefixes ("dns:///", "https://", "http://") if - # `attempt_direct_path` is enabled, as the Direct Path prefix `google-c2p:///` - # will be used instead. - for scheme_prefix in ("dns:///", "https://", "http://"): - if target.startswith(scheme_prefix): - target = target.removeprefix(scheme_prefix) - break - - direct_path_separator = ":///" - if direct_path_separator not in target: - if "?" in target: - host_part, query_part = target.split("?", 1) - target_without_port = host_part.split("/")[0].split(":")[0] - target = ( - f"google-c2p{direct_path_separator}{target_without_port}?{query_part}" - ) - else: - target_without_port = target.split("/")[0].split(":")[0] - # Modify the target to use Direct Path by adding the `google-c2p:///` prefix - target = f"google-c2p{direct_path_separator}{target_without_port}" + parsed = universe._parse_target(target) + if parsed is None or parsed.authority: + return target - if attempt_direct_path_xds_over_interconnect and target.startswith( - "google-c2p:///" + query = parsed.query + if attempt_direct_path_xds_over_interconnect and "force-xds" not in query.split( + "&" ): - if "force-xds" not in target: - separator = "&" if "?" in target else "?" - target = f"{target}{separator}force-xds" - return target + query = f"{query}&force-xds" if query else "force-xds" + + return ( + f"google-c2p:///{parsed.host}?{query}" + if query + else f"google-c2p:///{parsed.host}" + ) def apply_channel_interceptors( diff --git a/packages/google-api-core/google/api_core/universe.py b/packages/google-api-core/google/api_core/universe.py index 58eb2d26f7c9..8329b2865da6 100644 --- a/packages/google-api-core/google/api_core/universe.py +++ b/packages/google-api-core/google/api_core/universe.py @@ -14,12 +14,33 @@ """Helpers for universe domain.""" -from typing import Any, Optional -from urllib.parse import urlparse, urlunparse - +import copy +import os +import re +from collections.abc import Mapping +from typing import Any, NamedTuple, Optional +from urllib.parse import urlparse, urlsplit, urlunparse + +from google.auth import credentials as auth_credentials from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.api_core import client_options as client_options_lib + DEFAULT_UNIVERSE = "googleapis.com" +UNIVERSE_DOMAIN_ENV = "GOOGLE_CLOUD_UNIVERSE_DOMAIN" +_GOOGLEAPIS_HOST_PATTERN = re.compile( + rf"^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)*{re.escape(DEFAULT_UNIVERSE)}$", + re.IGNORECASE, +) + + +class _ParsedTarget(NamedTuple): + """Normalized components of an HTTP(S) URL or gRPC target string.""" + + scheme: str + authority: str + host: str + query: str class EmptyUniverseError(ValueError): @@ -197,3 +218,260 @@ def get_api_endpoint( return default_mtls_endpoint else: return default_endpoint_template.format(UNIVERSE_DOMAIN=universe_domain) + + +def resolve_client_universe( + client_options: client_options_lib.ClientOptions | Mapping[str, Any] | None = None, +) -> str: + """Resolve a client's universe domain from ``client_options`` or the environment. + + Follows AIP-4113 precedence: ``client_options.universe_domain``, then + ``GOOGLE_CLOUD_UNIVERSE_DOMAIN``, then ``"googleapis.com"``. To propagate an + already-resolved parent universe onto a child client's options, use + :func:`inherit_universe_in_client_options` instead. + + Args: + client_options (Optional[Union[google.api_core.client_options.ClientOptions, Mapping[str, Any]]]): + Optional ``ClientOptions`` instance or mapping passed to + ``Client.__init__``. If ``None``, falls back to + ``GOOGLE_CLOUD_UNIVERSE_DOMAIN`` and then ``"googleapis.com"``. + + Returns: + str: The resolved universe domain string. + + Raises: + EmptyUniverseError: If the configured universe domain is an empty string. + TypeError: If ``client_options`` is not a ``ClientOptions`` instance, + ``Mapping``, or ``None``. + """ + if client_options is None: + options_universe = None + elif isinstance(client_options, Mapping): + options_universe = client_options.get("universe_domain") + elif isinstance(client_options, client_options_lib.ClientOptions): + options_universe = client_options.universe_domain + else: + raise TypeError( + "client_options must be a ClientOptions instance, Mapping, or None; " + f"got {type(client_options).__name__}" + ) + return determine_domain( + options_universe, + os.getenv(UNIVERSE_DOMAIN_ENV), + ) + + +def validate_credentials_universe( + client_universe: str, + credentials: auth_credentials.Credentials | None, +) -> None: + """Validate that resolved client credentials match ``client_universe``. + + Call on ``self._credentials`` after ``super().__init__()`` or Application + Default Credentials resolution rather than on the raw constructor + ``credentials`` argument (which is ``None`` before ADC loads), and never + inside ``Credentials.before_request()``. Exempts ``None`` and + ``AnonymousCredentials`` for local emulator workflows. + + Args: + client_universe (str): Resolved universe domain of the client. + credentials (Optional[google.auth.credentials.Credentials]): Resolved + credentials bound to the client, or ``None`` (in which case + validation is skipped). + + Raises: + UniverseMismatchError: If ``credentials`` is configured for a different + universe than ``client_universe``. + """ + if credentials is None or isinstance( + credentials, auth_credentials.AnonymousCredentials + ): + return + compare_domains(client_universe, credentials) + + +def inherit_universe_in_client_options( + parent_universe: str, + client_options: client_options_lib.ClientOptions | Mapping[str, Any] | None = None, + *, + parent_api_endpoint: str | None = None, + clear_credentials: bool = False, +) -> client_options_lib.ClientOptions | None: + """Inherit ``parent_universe`` onto child ``client_options`` when unset. + + Caller-supplied mappings and ``ClientOptions`` instances are never mutated, + and an explicit ``universe_domain`` already set on ``client_options`` is + always preserved. Also stamps explicit ``"googleapis.com"`` when + ``GOOGLE_CLOUD_UNIVERSE_DOMAIN`` is set in ``os.environ`` to a different + universe so child clients do not drift from an explicitly configured parent. + + When ``parent_api_endpoint`` is provided (for child clients that share the + same API endpoint family as the parent), it is inherited onto + ``api_endpoint`` only when both ``api_endpoint`` and ``universe_domain`` are + unset on ``client_options``: + + 1. ``client_options.api_endpoint`` + 2. ``client_options.universe_domain`` (blocks ``parent_api_endpoint``) + 3. ``parent_api_endpoint`` + 4. ``parent_universe`` + + Args: + parent_universe (str): Resolved universe domain of the parent client. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, Mapping[str, Any]]]): + Optional child ``ClientOptions`` instance or mapping. If ``None``, + a new ``ClientOptions`` is created when propagation is required; + otherwise ``None`` is returned. + parent_api_endpoint (Optional[str]): Optional parent ``api_endpoint`` + override to inherit when the child targets the same API host family + and sets neither ``api_endpoint`` nor ``universe_domain``. Leave + ``None`` when the child targets a different API service. + clear_credentials (bool): Set to ``True`` when forwarding parent + ``client_options`` alongside already-resolved + ``credentials=self._credentials`` or a pre-built ``transport`` so + leftover ``credentials_file`` or ``api_key`` fields do not trigger + GAPIC ``DuplicateCredentialArgs`` or ``ValueError``. + + Returns: + Optional[google.api_core.client_options.ClientOptions]: Updated + ``ClientOptions`` instance, or ``None`` when ``client_options`` is + ``None`` and default resolution already matches the parent. + + Raises: + TypeError: If ``client_options`` is not a ``ClientOptions`` instance, + ``Mapping``, or ``None``. + """ + env_universe = os.getenv(UNIVERSE_DOMAIN_ENV) + should_propagate = parent_universe != DEFAULT_UNIVERSE or ( + env_universe is not None and env_universe.strip() != parent_universe + ) + has_parent_endpoint = bool(parent_api_endpoint) + if client_options is None: + if should_propagate or has_parent_endpoint: + return client_options_lib.ClientOptions( + api_endpoint=parent_api_endpoint if has_parent_endpoint else None, + universe_domain=parent_universe if should_propagate else None, + ) + return None + if isinstance(client_options, Mapping): + opts = client_options_lib.from_dict(client_options) + needs_endpoint = ( + has_parent_endpoint + and not opts.api_endpoint + and opts.universe_domain is None + ) + if opts.universe_domain is None and should_propagate: + opts.universe_domain = parent_universe + if needs_endpoint: + opts.api_endpoint = parent_api_endpoint + if clear_credentials: + opts.credentials_file = None + opts.api_key = None + return opts + if isinstance(client_options, client_options_lib.ClientOptions): + needs_universe = client_options.universe_domain is None and should_propagate + needs_endpoint = ( + has_parent_endpoint + and not client_options.api_endpoint + and client_options.universe_domain is None + ) + needs_cred_clear = clear_credentials and bool( + client_options.credentials_file or client_options.api_key + ) + if needs_universe or needs_endpoint or needs_cred_clear: + opts = copy.copy(client_options) + if needs_universe: + opts.universe_domain = parent_universe + if needs_endpoint: + opts.api_endpoint = parent_api_endpoint + if needs_cred_clear: + opts.credentials_file = None + opts.api_key = None + return opts + return client_options + raise TypeError( + "client_options must be a ClientOptions instance, Mapping, or None; " + f"got {type(client_options).__name__}" + ) + + +def _parse_target(url_or_target: str) -> _ParsedTarget | None: + """Parse an HTTP(S) URL or gRPC target into normalized components. + + Uses :func:`urllib.parse.urlsplit` for case-insensitive RFC 3986 scheme and + port validation while normalizing scheme-less ``host:port`` targets and gRPC + path-style schemes (``dns:`` and ``google-c2p:///``). Returns ``None`` for + empty, non-string, userinfo/fragment-containing, unknown-scheme, or + malformed inputs. + """ + if ( + not isinstance(url_or_target, str) + or not url_or_target + or "@" in url_or_target + or "#" in url_or_target + ): + return None + + try: + raw = urlsplit(url_or_target) + if raw.scheme in ("http", "https"): + if not url_or_target[len(raw.scheme) :].startswith("://"): + return None + _ = raw.port + if not raw.hostname: + return None + return _ParsedTarget(raw.scheme, "", raw.hostname, raw.query) + + if raw.scheme == "google-c2p": + if not url_or_target[len(raw.scheme) :].startswith(":///"): + return None + endpoint = raw.path.removeprefix("/") + authority = "" + query = raw.query + elif raw.scheme == "dns": + _ = raw.port + endpoint = raw.path.removeprefix("/") + authority = raw.netloc + query = raw.query + elif "://" in url_or_target: + return None + else: + endpoint = url_or_target + authority = "" + query = "" + + inner = urlsplit(f"//{endpoint}") + _ = inner.port + if inner.path or not inner.hostname: + return None + return _ParsedTarget( + raw.scheme if raw.scheme in ("google-c2p", "dns") else "", + authority, + inner.hostname, + query or inner.query, + ) + except ValueError: + return None + + +def is_googleapis_host(url_or_target: str) -> bool: + """Return True if an HTTP(S) URL or gRPC target resolves to ``googleapis.com``. + + Matches ``googleapis.com`` and ``*.googleapis.com`` across ``https://`` URLs, + ``host:port`` gRPC targets, ``google-c2p:///`` DirectPath targets, and + ``dns:///`` or ``dns://authority/`` targets while rejecting userinfo/fragment + characters (``@``, ``#``), unknown schemes, malformed ports, and spoofed + suffixes. Intended for gating default-universe-only features (such as + DirectPath, mTLS endpoint switching, or built-in Cloud Monitoring metrics); + do not use to test equality against a single default service host because + regional (``*.rep.googleapis.com``) and Private Service Connect + (``*.p.googleapis.com``) endpoints also match ``*.googleapis.com``. + + Args: + url_or_target (str): HTTP(S) URL or gRPC target string to inspect. + + Returns: + bool: True if the target hostname is ``googleapis.com`` or a valid + subdomain of ``googleapis.com``; False otherwise. + """ + parsed = _parse_target(url_or_target) + return bool(parsed and _GOOGLEAPIS_HOST_PATTERN.fullmatch(parsed.host)) From cef786d723c071bc33f2969b211133680bb2a1d1 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Wed, 25 Nov 2026 14:57:12 -0500 Subject: [PATCH 3/4] fix(api_core): skip uncached compute_engine MDS lookup in validate_credentials_universe --- .../google/api_core/universe.py | 15 +++++-- .../tests/unit/test_universe.py | 45 +++++++++++++++++++ 2 files changed, 56 insertions(+), 4 deletions(-) diff --git a/packages/google-api-core/google/api_core/universe.py b/packages/google-api-core/google/api_core/universe.py index 8329b2865da6..5840c64b18cf 100644 --- a/packages/google-api-core/google/api_core/universe.py +++ b/packages/google-api-core/google/api_core/universe.py @@ -21,6 +21,7 @@ from typing import Any, NamedTuple, Optional from urllib.parse import urlparse, urlsplit, urlunparse +from google.auth import compute_engine from google.auth import credentials as auth_credentials from google.auth.exceptions import MutualTLSChannelError # type: ignore @@ -270,8 +271,10 @@ def validate_credentials_universe( Call on ``self._credentials`` after ``super().__init__()`` or Application Default Credentials resolution rather than on the raw constructor ``credentials`` argument (which is ``None`` before ADC loads), and never - inside ``Credentials.before_request()``. Exempts ``None`` and - ``AnonymousCredentials`` for local emulator workflows. + inside ``Credentials.before_request()``. Exempts ``None``, + ``AnonymousCredentials``, and ``compute_engine.Credentials`` whose universe + domain is not yet cached in memory (avoiding synchronous Metadata Server + HTTP requests during client initialization). Args: client_universe (str): Resolved universe domain of the client. @@ -280,13 +283,17 @@ def validate_credentials_universe( validation is skipped). Raises: - UniverseMismatchError: If ``credentials`` is configured for a different - universe than ``client_universe``. + UniverseMismatchError: If ``credentials`` has an in-memory universe + domain configured for a different universe than ``client_universe``. """ if credentials is None or isinstance( credentials, auth_credentials.AnonymousCredentials ): return + if isinstance(credentials, compute_engine.Credentials) and not getattr( + credentials, "_universe_domain_cached", False + ): + return compare_domains(client_universe, credentials) diff --git a/packages/google-api-core/tests/unit/test_universe.py b/packages/google-api-core/tests/unit/test_universe.py index 5157771833ec..20ad729b6f4c 100644 --- a/packages/google-api-core/tests/unit/test_universe.py +++ b/packages/google-api-core/tests/unit/test_universe.py @@ -16,7 +16,9 @@ import types import pytest +from google.auth import compute_engine from google.auth import credentials as auth_credentials +from google.auth.compute_engine import _metadata as compute_engine_metadata from google.auth.exceptions import MutualTLSChannelError from google.api_core import client_options as client_options_lib @@ -53,6 +55,17 @@ def refresh(self, request): # pragma: NO COVER pass +class _CachedComputeEngineCredentials(compute_engine.Credentials): + def __init__(self, universe_domain: str = universe.DEFAULT_UNIVERSE): + super().__init__() + self._test_universe_domain = universe_domain + self._universe_domain_cached = True + + @property + def universe_domain(self) -> str: + return self._test_universe_domain + + def test_determine_domain(): domain_client = "foo.com" domain_env = "bar.com" @@ -478,6 +491,38 @@ def test_legacy_credentials_without_universe_attr_mismatch_custom_universe(self) _Fake_Credentials(), # type: ignore[arg-type] ) + @pytest.mark.parametrize( + "client_universe", + [ + pytest.param(universe.DEFAULT_UNIVERSE, id="default_universe"), + pytest.param(TPC_UNIVERSE, id="custom_universe"), + ], + ) + def test_skips_uncached_compute_engine_credentials_without_mds_request( + self, monkeypatch, client_universe + ): + def _fail_mds_call(*args, **kwargs): # pragma: NO COVER + raise AssertionError("Unexpected Metadata Server request") + + monkeypatch.setattr(compute_engine_metadata, "get", _fail_mds_call) + creds = compute_engine.Credentials() + + assert universe.validate_credentials_universe(client_universe, creds) is None + + def test_validates_cached_compute_engine_credentials(self): + matching_creds = _CachedComputeEngineCredentials(TPC_UNIVERSE) + assert ( + universe.validate_credentials_universe(TPC_UNIVERSE, matching_creds) is None + ) + + with pytest.raises( + universe.UniverseMismatchError, + match=r"configured universe domain \(googleapis\.com\).*credentials \(apis-tpclp\.goog\)", + ): + universe.validate_credentials_universe( + universe.DEFAULT_UNIVERSE, matching_creds + ) + class TestInheritUniverseInClientOptions: @pytest.mark.parametrize( From 4aad3884a1691ff392ac29246462eda2c22d90d8 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Wed, 25 Nov 2026 16:32:55 -0500 Subject: [PATCH 4/4] fix(api_core): address review feedback on universe_domain helpers --- .../google/api_core/grpc_helpers.py | 4 +- .../google/api_core/universe.py | 180 ++----- .../tests/unit/test_universe.py | 456 ++---------------- 3 files changed, 94 insertions(+), 546 deletions(-) diff --git a/packages/google-api-core/google/api_core/grpc_helpers.py b/packages/google-api-core/google/api_core/grpc_helpers.py index 192a2c1c111f..04169c321546 100644 --- a/packages/google-api-core/google/api_core/grpc_helpers.py +++ b/packages/google-api-core/google/api_core/grpc_helpers.py @@ -83,7 +83,7 @@ def _extract_target_host(target: str) -> str: return parsed.host if parsed is not None else target -def _is_googleapis_host(target: str) -> bool: +def _is_direct_path_googleapis_target(target: str) -> bool: """Returns True if ``target`` is a DirectPath-eligible ``googleapis.com`` host.""" parsed = universe._parse_target(target) if parsed is None or parsed.authority: @@ -421,7 +421,7 @@ def _setup_direct_path_and_credentials( # target host or the resolved credential universe_domain is non-GDU. if attempt_direct_path or use_dp_interconnect: if not ( - _is_googleapis_host(target) + _is_direct_path_googleapis_target(target) and getattr(credentials, "universe_domain", universe.DEFAULT_UNIVERSE) == universe.DEFAULT_UNIVERSE ): diff --git a/packages/google-api-core/google/api_core/universe.py b/packages/google-api-core/google/api_core/universe.py index 5840c64b18cf..ee8935b183b0 100644 --- a/packages/google-api-core/google/api_core/universe.py +++ b/packages/google-api-core/google/api_core/universe.py @@ -14,11 +14,10 @@ """Helpers for universe domain.""" -import copy import os import re from collections.abc import Mapping -from typing import Any, NamedTuple, Optional +from typing import TYPE_CHECKING, Any, NamedTuple, Optional, Union from urllib.parse import urlparse, urlsplit, urlunparse from google.auth import compute_engine @@ -27,6 +26,21 @@ from google.api_core import client_options as client_options_lib +if TYPE_CHECKING: # pragma: NO COVER + from google.auth.aio import credentials as aio_credentials + +try: + # google.auth.aio was added in google-auth 2.28.0; older supported versions + # (down to 2.14.1) only provide synchronous AnonymousCredentials. + from google.auth.aio import credentials as _aio_credentials + + _ANONYMOUS_CREDENTIAL_TYPES: tuple[type[Any], ...] = ( + auth_credentials.AnonymousCredentials, + _aio_credentials.AnonymousCredentials, + ) +except ImportError: # pragma: NO COVER + _ANONYMOUS_CREDENTIAL_TYPES = (auth_credentials.AnonymousCredentials,) + DEFAULT_UNIVERSE = "googleapis.com" UNIVERSE_DOMAIN_ENV = "GOOGLE_CLOUD_UNIVERSE_DOMAIN" _GOOGLEAPIS_HOST_PATTERN = re.compile( @@ -227,9 +241,7 @@ def resolve_client_universe( """Resolve a client's universe domain from ``client_options`` or the environment. Follows AIP-4113 precedence: ``client_options.universe_domain``, then - ``GOOGLE_CLOUD_UNIVERSE_DOMAIN``, then ``"googleapis.com"``. To propagate an - already-resolved parent universe onto a child client's options, use - :func:`inherit_universe_in_client_options` instead. + ``GOOGLE_CLOUD_UNIVERSE_DOMAIN``, then ``"googleapis.com"``. Args: client_options (Optional[Union[google.api_core.client_options.ClientOptions, Mapping[str, Any]]]): @@ -264,31 +276,31 @@ def resolve_client_universe( def validate_credentials_universe( client_universe: str, - credentials: auth_credentials.Credentials | None, + credentials: Union[ + auth_credentials.Credentials, "aio_credentials.Credentials", None + ], ) -> None: """Validate that resolved client credentials match ``client_universe``. Call on ``self._credentials`` after ``super().__init__()`` or Application Default Credentials resolution rather than on the raw constructor ``credentials`` argument (which is ``None`` before ADC loads), and never - inside ``Credentials.before_request()``. Exempts ``None``, - ``AnonymousCredentials``, and ``compute_engine.Credentials`` whose universe - domain is not yet cached in memory (avoiding synchronous Metadata Server - HTTP requests during client initialization). + inside ``Credentials.before_request()``. Exempts ``None``, synchronous and + asynchronous ``AnonymousCredentials``, and ``compute_engine.Credentials`` + whose universe domain is not yet cached in memory (avoiding synchronous + Metadata Server HTTP requests during client initialization). Args: client_universe (str): Resolved universe domain of the client. - credentials (Optional[google.auth.credentials.Credentials]): Resolved - credentials bound to the client, or ``None`` (in which case + credentials (Optional[Union[google.auth.credentials.Credentials, google.auth.aio.credentials.Credentials]]): + Resolved credentials bound to the client, or ``None`` (in which case validation is skipped). Raises: UniverseMismatchError: If ``credentials`` has an in-memory universe domain configured for a different universe than ``client_universe``. """ - if credentials is None or isinstance( - credentials, auth_credentials.AnonymousCredentials - ): + if credentials is None or isinstance(credentials, _ANONYMOUS_CREDENTIAL_TYPES): return if isinstance(credentials, compute_engine.Credentials) and not getattr( credentials, "_universe_domain_cached", False @@ -297,131 +309,27 @@ def validate_credentials_universe( compare_domains(client_universe, credentials) -def inherit_universe_in_client_options( - parent_universe: str, - client_options: client_options_lib.ClientOptions | Mapping[str, Any] | None = None, - *, - parent_api_endpoint: str | None = None, - clear_credentials: bool = False, -) -> client_options_lib.ClientOptions | None: - """Inherit ``parent_universe`` onto child ``client_options`` when unset. - - Caller-supplied mappings and ``ClientOptions`` instances are never mutated, - and an explicit ``universe_domain`` already set on ``client_options`` is - always preserved. Also stamps explicit ``"googleapis.com"`` when - ``GOOGLE_CLOUD_UNIVERSE_DOMAIN`` is set in ``os.environ`` to a different - universe so child clients do not drift from an explicitly configured parent. - - When ``parent_api_endpoint`` is provided (for child clients that share the - same API endpoint family as the parent), it is inherited onto - ``api_endpoint`` only when both ``api_endpoint`` and ``universe_domain`` are - unset on ``client_options``: - - 1. ``client_options.api_endpoint`` - 2. ``client_options.universe_domain`` (blocks ``parent_api_endpoint``) - 3. ``parent_api_endpoint`` - 4. ``parent_universe`` - - Args: - parent_universe (str): Resolved universe domain of the parent client. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, Mapping[str, Any]]]): - Optional child ``ClientOptions`` instance or mapping. If ``None``, - a new ``ClientOptions`` is created when propagation is required; - otherwise ``None`` is returned. - parent_api_endpoint (Optional[str]): Optional parent ``api_endpoint`` - override to inherit when the child targets the same API host family - and sets neither ``api_endpoint`` nor ``universe_domain``. Leave - ``None`` when the child targets a different API service. - clear_credentials (bool): Set to ``True`` when forwarding parent - ``client_options`` alongside already-resolved - ``credentials=self._credentials`` or a pre-built ``transport`` so - leftover ``credentials_file`` or ``api_key`` fields do not trigger - GAPIC ``DuplicateCredentialArgs`` or ``ValueError``. - - Returns: - Optional[google.api_core.client_options.ClientOptions]: Updated - ``ClientOptions`` instance, or ``None`` when ``client_options`` is - ``None`` and default resolution already matches the parent. - - Raises: - TypeError: If ``client_options`` is not a ``ClientOptions`` instance, - ``Mapping``, or ``None``. - """ - env_universe = os.getenv(UNIVERSE_DOMAIN_ENV) - should_propagate = parent_universe != DEFAULT_UNIVERSE or ( - env_universe is not None and env_universe.strip() != parent_universe - ) - has_parent_endpoint = bool(parent_api_endpoint) - if client_options is None: - if should_propagate or has_parent_endpoint: - return client_options_lib.ClientOptions( - api_endpoint=parent_api_endpoint if has_parent_endpoint else None, - universe_domain=parent_universe if should_propagate else None, - ) - return None - if isinstance(client_options, Mapping): - opts = client_options_lib.from_dict(client_options) - needs_endpoint = ( - has_parent_endpoint - and not opts.api_endpoint - and opts.universe_domain is None - ) - if opts.universe_domain is None and should_propagate: - opts.universe_domain = parent_universe - if needs_endpoint: - opts.api_endpoint = parent_api_endpoint - if clear_credentials: - opts.credentials_file = None - opts.api_key = None - return opts - if isinstance(client_options, client_options_lib.ClientOptions): - needs_universe = client_options.universe_domain is None and should_propagate - needs_endpoint = ( - has_parent_endpoint - and not client_options.api_endpoint - and client_options.universe_domain is None - ) - needs_cred_clear = clear_credentials and bool( - client_options.credentials_file or client_options.api_key - ) - if needs_universe or needs_endpoint or needs_cred_clear: - opts = copy.copy(client_options) - if needs_universe: - opts.universe_domain = parent_universe - if needs_endpoint: - opts.api_endpoint = parent_api_endpoint - if needs_cred_clear: - opts.credentials_file = None - opts.api_key = None - return opts - return client_options - raise TypeError( - "client_options must be a ClientOptions instance, Mapping, or None; " - f"got {type(client_options).__name__}" - ) - - def _parse_target(url_or_target: str) -> _ParsedTarget | None: """Parse an HTTP(S) URL or gRPC target into normalized components. Uses :func:`urllib.parse.urlsplit` for case-insensitive RFC 3986 scheme and port validation while normalizing scheme-less ``host:port`` targets and gRPC - path-style schemes (``dns:`` and ``google-c2p:///``). Returns ``None`` for - empty, non-string, userinfo/fragment-containing, unknown-scheme, or + path-style schemes (``dns:`` and ``google-c2p:///``). Rejects userinfo + (``@`` in authority/netloc) while allowing ``@`` in HTTP(S) paths and + queries (such as service account email endpoints). Returns ``None`` for + empty, non-string, userinfo- or fragment-containing, unknown-scheme, or malformed inputs. """ - if ( - not isinstance(url_or_target, str) - or not url_or_target - or "@" in url_or_target - or "#" in url_or_target - ): + if not isinstance(url_or_target, str) or not url_or_target or "#" in url_or_target: return None try: raw = urlsplit(url_or_target) if raw.scheme in ("http", "https"): - if not url_or_target[len(raw.scheme) :].startswith("://"): + if ( + not url_or_target[len(raw.scheme) :].startswith("://") + or "@" in raw.netloc + ): return None _ = raw.port if not raw.hostname: @@ -448,7 +356,7 @@ def _parse_target(url_or_target: str) -> _ParsedTarget | None: inner = urlsplit(f"//{endpoint}") _ = inner.port - if inner.path or not inner.hostname: + if "@" in authority or "@" in inner.netloc or inner.path or not inner.hostname: return None return _ParsedTarget( raw.scheme if raw.scheme in ("google-c2p", "dns") else "", @@ -465,13 +373,13 @@ def is_googleapis_host(url_or_target: str) -> bool: Matches ``googleapis.com`` and ``*.googleapis.com`` across ``https://`` URLs, ``host:port`` gRPC targets, ``google-c2p:///`` DirectPath targets, and - ``dns:///`` or ``dns://authority/`` targets while rejecting userinfo/fragment - characters (``@``, ``#``), unknown schemes, malformed ports, and spoofed - suffixes. Intended for gating default-universe-only features (such as - DirectPath, mTLS endpoint switching, or built-in Cloud Monitoring metrics); - do not use to test equality against a single default service host because - regional (``*.rep.googleapis.com``) and Private Service Connect - (``*.p.googleapis.com``) endpoints also match ``*.googleapis.com``. + ``dns:///`` or ``dns://authority/`` targets while rejecting userinfo in the + authority/netloc (``@``), fragments (``#``), unknown schemes, malformed + ports, and spoofed suffixes. Intended for gating default-universe-only + features (such as DirectPath, mTLS endpoint switching, or built-in Cloud + Monitoring metrics); do not use to test equality against a single default + service host because regional (``*.rep.googleapis.com``) and Private Service + Connect (``*.p.googleapis.com``) endpoints also match ``*.googleapis.com``. Args: url_or_target (str): HTTP(S) URL or gRPC target string to inspect. diff --git a/packages/google-api-core/tests/unit/test_universe.py b/packages/google-api-core/tests/unit/test_universe.py index 20ad729b6f4c..5bce93bc15ad 100644 --- a/packages/google-api-core/tests/unit/test_universe.py +++ b/packages/google-api-core/tests/unit/test_universe.py @@ -24,16 +24,8 @@ from google.api_core import client_options as client_options_lib from google.api_core import universe -from ..helpers import warn_deprecated_credentials_file - TPC_UNIVERSE = "apis-tpclp.goog" ALT_UNIVERSE = "other.goog" -CHILD_UNIVERSE = "child.goog" -PARENT_ENDPOINT = "parent.custom.test:443" -CHILD_ENDPOINT = "child.custom.test:443" -TEST_QUOTA_PROJECT = "qp-1" -TEST_API_KEY = "secret-key" -TEST_CREDENTIALS_FILE = "/path/to/creds.json" class _Fake_Credentials: @@ -523,414 +515,22 @@ def test_validates_cached_compute_engine_credentials(self): universe.DEFAULT_UNIVERSE, matching_creds ) - -class TestInheritUniverseInClientOptions: @pytest.mark.parametrize( - "env_val", + "client_universe", [ - pytest.param(None, id="env_unset"), - pytest.param(universe.DEFAULT_UNIVERSE, id="env_matches_gdu"), - pytest.param(f" {universe.DEFAULT_UNIVERSE} ", id="env_padded_gdu"), + pytest.param(universe.DEFAULT_UNIVERSE, id="default_universe"), + pytest.param(TPC_UNIVERSE, id="custom_universe"), ], ) - def test_none_options_in_default_universe_returns_none(self, monkeypatch, env_val): - if env_val is not None: - monkeypatch.setenv(universe.UNIVERSE_DOMAIN_ENV, env_val) - + def test_exempts_async_anonymous_credentials(self, client_universe): + aio_credentials = pytest.importorskip("google.auth.aio.credentials") assert ( - universe.inherit_universe_in_client_options(universe.DEFAULT_UNIVERSE, None) - is None - ) - - @pytest.mark.parametrize( - ("parent_universe", "env_val", "expected_universe"), - [ - pytest.param( - TPC_UNIVERSE, - None, - TPC_UNIVERSE, - id="custom_parent_creates_options", - ), - pytest.param( - universe.DEFAULT_UNIVERSE, - TPC_UNIVERSE, - universe.DEFAULT_UNIVERSE, - id="explicit_gdu_parent_overrides_tpc_env", - ), - pytest.param( - universe.DEFAULT_UNIVERSE, - "", - universe.DEFAULT_UNIVERSE, - id="explicit_gdu_parent_overrides_empty_env", - ), - pytest.param( - universe.DEFAULT_UNIVERSE, - " ", - universe.DEFAULT_UNIVERSE, - id="explicit_gdu_parent_overrides_whitespace_env", - ), - ], - ) - def test_none_options_propagates_universe( - self, monkeypatch, parent_universe, env_val, expected_universe - ): - if env_val is not None: - monkeypatch.setenv(universe.UNIVERSE_DOMAIN_ENV, env_val) - - opts = universe.inherit_universe_in_client_options(parent_universe, None) - - assert opts is not None - assert opts.universe_domain == expected_universe - - @pytest.mark.parametrize( - ("parent_universe", "input_dict", "expected_universe"), - [ - pytest.param( - TPC_UNIVERSE, - {"quota_project_id": TEST_QUOTA_PROJECT}, - TPC_UNIVERSE, - id="custom_parent_inherits_onto_unset_mapping", - ), - pytest.param( - universe.DEFAULT_UNIVERSE, - {"quota_project_id": TEST_QUOTA_PROJECT}, - None, - id="default_parent_leaves_unset_mapping_none", - ), - pytest.param( - TPC_UNIVERSE, - { - "quota_project_id": TEST_QUOTA_PROJECT, - "universe_domain": CHILD_UNIVERSE, - }, - CHILD_UNIVERSE, - id="preserves_explicit_child_universe", - ), - pytest.param( - TPC_UNIVERSE, - {"quota_project_id": TEST_QUOTA_PROJECT, "universe_domain": ""}, - "", - id="preserves_explicit_empty_string_in_mapping", - ), - ], - ) - def test_mapping_options_universe_inheritance( - self, parent_universe, input_dict, expected_universe - ): - caller_dict = dict(input_dict) - - opts = universe.inherit_universe_in_client_options(parent_universe, caller_dict) - - assert opts is not None - assert opts.universe_domain == expected_universe - assert opts.quota_project_id == TEST_QUOTA_PROJECT - assert caller_dict == input_dict - - @pytest.mark.parametrize( - "cred_entry", - [ - pytest.param( - {"credentials_file": TEST_CREDENTIALS_FILE}, - id="clears_credentials_file", - ), - pytest.param({"api_key": TEST_API_KEY}, id="clears_api_key"), - ], - ) - def test_mapping_clears_credentials_when_requested(self, cred_entry): - caller_dict = {"universe_domain": CHILD_UNIVERSE, **cred_entry} - - opts = universe.inherit_universe_in_client_options( - TPC_UNIVERSE, - caller_dict, - clear_credentials=True, - ) - - assert opts is not None - assert opts.universe_domain == CHILD_UNIVERSE - assert opts.credentials_file is None - assert opts.api_key is None - assert caller_dict == {"universe_domain": CHILD_UNIVERSE, **cred_entry} - - def test_mapping_preserves_credentials_when_clear_credentials_false(self): - opts = universe.inherit_universe_in_client_options( - TPC_UNIVERSE, - { - "credentials_file": TEST_CREDENTIALS_FILE, - "api_key": TEST_API_KEY, - }, - clear_credentials=False, - ) - - assert opts is not None - assert opts.universe_domain == TPC_UNIVERSE - assert opts.credentials_file == TEST_CREDENTIALS_FILE - assert opts.api_key == TEST_API_KEY - - @pytest.mark.parametrize( - ("parent_universe", "initial_universe", "clear_credentials"), - [ - pytest.param( - universe.DEFAULT_UNIVERSE, - None, - False, - id="default_parent_unset_child", - ), - pytest.param( - universe.DEFAULT_UNIVERSE, - None, - True, - id="clear_credentials_without_creds_set", - ), - pytest.param( - TPC_UNIVERSE, - CHILD_UNIVERSE, - False, - id="explicit_child_universe_preserved", - ), - pytest.param( - TPC_UNIVERSE, - "", - False, - id="explicit_empty_child_universe_preserved", - ), - ], - ) - def test_client_options_obj_no_changes_returns_same_instance( - self, parent_universe, initial_universe, clear_credentials - ): - original = client_options_lib.ClientOptions( - universe_domain=initial_universe, - quota_project_id=TEST_QUOTA_PROJECT, - ) - - result = universe.inherit_universe_in_client_options( - parent_universe, - original, - clear_credentials=clear_credentials, - ) - - assert result is original - assert result.universe_domain == initial_universe - - def test_client_options_obj_inherits_via_shallow_copy(self): - original = client_options_lib.ClientOptions( - quota_project_id=TEST_QUOTA_PROJECT, - api_key=TEST_API_KEY, - ) - - result = universe.inherit_universe_in_client_options(TPC_UNIVERSE, original) - - assert result is not original - assert result is not None - assert result.universe_domain == TPC_UNIVERSE - assert result.quota_project_id == TEST_QUOTA_PROJECT - assert result.api_key == TEST_API_KEY - assert original.universe_domain is None - - @pytest.mark.parametrize( - ("initial_universe", "expected_universe"), - [ - pytest.param(CHILD_UNIVERSE, CHILD_UNIVERSE, id="clear_api_key_only"), - pytest.param(None, TPC_UNIVERSE, id="inherit_universe_and_clear_api_key"), - ], - ) - def test_client_options_obj_clears_api_key( - self, initial_universe, expected_universe - ): - original = client_options_lib.ClientOptions( - universe_domain=initial_universe, - api_key=TEST_API_KEY, - ) - - result = universe.inherit_universe_in_client_options( - TPC_UNIVERSE, - original, - clear_credentials=True, - ) - - assert result is not original - assert result is not None - assert result.universe_domain == expected_universe - assert result.api_key is None - assert original.universe_domain == initial_universe - assert original.api_key == TEST_API_KEY - - def test_client_options_obj_clears_credentials_file(self): - with warn_deprecated_credentials_file(): - original = client_options_lib.ClientOptions( - credentials_file=TEST_CREDENTIALS_FILE, + universe.validate_credentials_universe( + client_universe, aio_credentials.AnonymousCredentials() ) - - result = universe.inherit_universe_in_client_options( - TPC_UNIVERSE, - original, - clear_credentials=True, - ) - - assert result is not original - assert result is not None - assert result.universe_domain == TPC_UNIVERSE - assert result.credentials_file is None - assert original.credentials_file == TEST_CREDENTIALS_FILE - - @pytest.mark.parametrize( - ("parent_universe", "expected_universe"), - [ - pytest.param(universe.DEFAULT_UNIVERSE, None, id="default_parent"), - pytest.param(TPC_UNIVERSE, TPC_UNIVERSE, id="custom_parent"), - ], - ) - def test_none_options_inherits_parent_api_endpoint( - self, parent_universe, expected_universe - ): - opts = universe.inherit_universe_in_client_options( - parent_universe, - None, - parent_api_endpoint=PARENT_ENDPOINT, - ) - - assert opts is not None - assert opts.api_endpoint == PARENT_ENDPOINT - assert opts.universe_domain == expected_universe - - @pytest.mark.parametrize( - ("child_dict", "expected_endpoint", "expected_universe"), - [ - pytest.param( - {"quota_project_id": TEST_QUOTA_PROJECT}, - PARENT_ENDPOINT, - TPC_UNIVERSE, - id="unset_child_inherits_parent_endpoint_and_universe", - ), - pytest.param( - {"api_endpoint": CHILD_ENDPOINT}, - CHILD_ENDPOINT, - TPC_UNIVERSE, - id="explicit_child_endpoint_wins_and_inherits_universe", - ), - pytest.param( - {"universe_domain": CHILD_UNIVERSE}, - None, - CHILD_UNIVERSE, - id="explicit_child_universe_blocks_parent_endpoint", - ), - pytest.param( - {"universe_domain": universe.DEFAULT_UNIVERSE}, - None, - universe.DEFAULT_UNIVERSE, - id="explicit_gdu_child_universe_blocks_parent_endpoint", - ), - ], - ) - def test_mapping_parent_api_endpoint_precedence( - self, child_dict, expected_endpoint, expected_universe - ): - caller_dict = dict(child_dict) - - opts = universe.inherit_universe_in_client_options( - TPC_UNIVERSE, - caller_dict, - parent_api_endpoint=PARENT_ENDPOINT, - ) - - assert opts is not None - assert opts.api_endpoint == expected_endpoint - assert opts.universe_domain == expected_universe - assert caller_dict == child_dict - - @pytest.mark.parametrize( - ( - "parent_universe", - "child_endpoint", - "child_universe", - "expected_endpoint", - "expected_universe", - "expect_same_instance", - ), - [ - pytest.param( - universe.DEFAULT_UNIVERSE, - None, - None, - PARENT_ENDPOINT, - None, - False, - id="default_parent_copies_only_parent_endpoint", - ), - pytest.param( - TPC_UNIVERSE, - None, - None, - PARENT_ENDPOINT, - TPC_UNIVERSE, - False, - id="custom_parent_copies_both_endpoint_and_universe", - ), - pytest.param( - TPC_UNIVERSE, - CHILD_ENDPOINT, - None, - CHILD_ENDPOINT, - TPC_UNIVERSE, - False, - id="child_endpoint_preserved_while_universe_inherited", - ), - pytest.param( - TPC_UNIVERSE, - None, - CHILD_UNIVERSE, - None, - CHILD_UNIVERSE, - True, - id="child_universe_blocks_parent_endpoint_returns_same_obj", - ), - pytest.param( - universe.DEFAULT_UNIVERSE, - CHILD_ENDPOINT, - None, - CHILD_ENDPOINT, - None, - True, - id="default_parent_with_child_endpoint_returns_same_obj", - ), - ], - ) - def test_client_options_obj_parent_api_endpoint_precedence( - self, - parent_universe, - child_endpoint, - child_universe, - expected_endpoint, - expected_universe, - expect_same_instance, - ): - original = client_options_lib.ClientOptions( - api_endpoint=child_endpoint, - universe_domain=child_universe, - ) - - result = universe.inherit_universe_in_client_options( - parent_universe, - original, - parent_api_endpoint=PARENT_ENDPOINT, + is None ) - assert result is not None - assert (result is original) is expect_same_instance - assert result.api_endpoint == expected_endpoint - assert result.universe_domain == expected_universe - assert original.api_endpoint == child_endpoint - assert original.universe_domain == child_universe - - def test_invalid_client_options_type_raises_type_error(self): - with pytest.raises(TypeError, match="ClientOptions instance, Mapping, or None"): - # Pass an invalid str on purpose to verify runtime TypeError handling; - # mypy flags the intentional type mismatch without this ignore. - universe.inherit_universe_in_client_options( - universe.DEFAULT_UNIVERSE, - "invalid", # type: ignore[arg-type] - ) - class TestIsGoogleapisHost: @pytest.mark.parametrize( @@ -976,6 +576,16 @@ class TestIsGoogleapisHost: True, id="https_url_with_path_and_query", ), + pytest.param( + "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/my-sa@my-project.iam.gserviceaccount.com:generateAccessToken", + True, + id="https_service_account_email_in_path", + ), + pytest.param( + "https://storage.googleapis.com/v1/b?user=sa@example.com", + True, + id="https_at_in_query", + ), pytest.param( "HTTPS://storage.googleapis.com:443/v1", True, @@ -1069,6 +679,31 @@ class TestIsGoogleapisHost: ), pytest.param("[invalid.googleapis.com", False, id="malformed_bare_ipv6"), pytest.param("user@storage.googleapis.com:443", False, id="userinfo_at"), + pytest.param( + "https://user@storage.googleapis.com:443/v1", + False, + id="https_userinfo_at", + ), + pytest.param( + "https://storage.example.com:443@storage.googleapis.com/v1", + False, + id="https_spoofed_userinfo_host", + ), + pytest.param( + "dns://user@8.8.8.8/storage.googleapis.com:443", + False, + id="dns_authority_userinfo_at", + ), + pytest.param( + "dns:///user@storage.googleapis.com:443", + False, + id="dns_target_userinfo_at", + ), + pytest.param( + "google-c2p:///user@storage-direct.googleapis.com", + False, + id="c2p_userinfo_at", + ), pytest.param( "storage.example.com:443@storage.googleapis.com", False, @@ -1077,6 +712,11 @@ class TestIsGoogleapisHost: pytest.param( "storage.googleapis.com#example.com", False, id="fragment_hash" ), + pytest.param( + "https://storage.googleapis.com/v1#fragment", + False, + id="https_fragment_hash", + ), pytest.param( "another-c2p:///storage.googleapis.com", False, id="unknown_scheme" ),