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..04169c321546 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))) - ) +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: + return False + return bool(universe._GOOGLEAPIS_HOST_PATTERN.fullmatch(parsed.host)) def _extract_direct_path_authority(target: str) -> Optional[str]: @@ -435,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 ): @@ -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..ee8935b183b0 100644 --- a/packages/google-api-core/google/api_core/universe.py +++ b/packages/google-api-core/google/api_core/universe.py @@ -14,12 +14,48 @@ """Helpers for universe domain.""" -from typing import Any, Optional -from urllib.parse import urlparse, urlunparse - +import os +import re +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, NamedTuple, Optional, Union +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 +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( + 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 +233,160 @@ 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"``. + + 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: 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``, 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[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, _ANONYMOUS_CREDENTIAL_TYPES): + return + if isinstance(credentials, compute_engine.Credentials) and not getattr( + credentials, "_universe_domain_cached", False + ): + return + compare_domains(client_universe, credentials) + + +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:///``). 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: + return None + + try: + raw = urlsplit(url_or_target) + if raw.scheme in ("http", "https"): + if ( + not url_or_target[len(raw.scheme) :].startswith("://") + or "@" in raw.netloc + ): + 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 "@" 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 "", + 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 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. + + 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)) 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..5bce93bc15ad 100644 --- a/packages/google-api-core/tests/unit/test_universe.py +++ b/packages/google-api-core/tests/unit/test_universe.py @@ -12,11 +12,21 @@ # See the License for the specific language governing permissions and # limitations under the License. +import re +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 from google.api_core import universe +TPC_UNIVERSE = "apis-tpclp.goog" +ALT_UNIVERSE = "other.goog" + class _Fake_Credentials: def __init__(self, universe_domain=None): @@ -24,6 +34,30 @@ 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 + + +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" @@ -259,3 +293,447 @@ 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] + ) + + @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 + ) + + @pytest.mark.parametrize( + "client_universe", + [ + pytest.param(universe.DEFAULT_UNIVERSE, id="default_universe"), + pytest.param(TPC_UNIVERSE, id="custom_universe"), + ], + ) + def test_exempts_async_anonymous_credentials(self, client_universe): + aio_credentials = pytest.importorskip("google.auth.aio.credentials") + assert ( + universe.validate_credentials_universe( + client_universe, aio_credentials.AnonymousCredentials() + ) + is None + ) + + +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://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, + 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( + "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, + id="spoofed_userinfo_host", + ), + 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" + ), + 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