diff --git a/packages/google-cloud-core/google/cloud/_helpers/__init__.py b/packages/google-cloud-core/google/cloud/_helpers/__init__.py index 44f0d457f895..e8f5a90be2ec 100644 --- a/packages/google-cloud-core/google/cloud/_helpers/__init__.py +++ b/packages/google-cloud-core/google/cloud/_helpers/__init__.py @@ -22,6 +22,7 @@ import calendar import datetime import http.client +import inspect import os import re from threading import local as Local @@ -545,8 +546,16 @@ def make_secure_channel(credentials, user_agent, host, extra_options=()): user_agent_option = ("grpc.primary_user_agent", user_agent) options = (user_agent_option,) + extra_options + channel_kwargs = {"options": options} + if ( + "default_host" + in inspect.signature( + google.auth.transport.grpc.secure_authorized_channel + ).parameters + ): + channel_kwargs["default_host"] = host return google.auth.transport.grpc.secure_authorized_channel( - credentials, http_request, target, options=options + credentials, http_request, target, **channel_kwargs ) diff --git a/packages/google-cloud-core/google/cloud/_http/__init__.py b/packages/google-cloud-core/google/cloud/_http/__init__.py index e4b82870a9bc..4be6aa6762b0 100644 --- a/packages/google-cloud-core/google/cloud/_http/__init__.py +++ b/packages/google-cloud-core/google/cloud/_http/__init__.py @@ -19,8 +19,9 @@ import json import os import platform -from typing import Optional, Set -from urllib.parse import urlencode +import re +from typing import NamedTuple, Optional, Set +from urllib.parse import urlencode, urlsplit import warnings # PEP 0810: Explicit Lazy Imports @@ -34,14 +35,127 @@ # imports are ignored, making their presence safe. __lazy_modules__: Set[str] = { "google.api_core.client_info", + "google.api_core.universe", + "google.auth.exceptions", "google.cloud.exceptions", "google.cloud.version", } from google.api_core.client_info import ClientInfo +from google.api_core.universe import DEFAULT_UNIVERSE, determine_domain +from google.auth.exceptions import MutualTLSChannelError from google.cloud import exceptions from google.cloud import version +try: + from google.api_core.universe import ( # type: ignore[attr-defined] + is_googleapis_host as _is_googleapis_url, + ) +except ImportError: # pragma: NO COVER + # TODO(universe-domain): Remove fallback once google-api-core >= 2.44.0. + _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 + + def _parse_target(url_or_target: str) -> Optional[_ParsedTarget]: + """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_url(url_or_target: str) -> bool: # type: ignore[misc] + """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)) + API_BASE_URL = "https://www.googleapis.com" """The base of the API call URL.""" @@ -187,6 +301,9 @@ class JSONConnection(Connection): API_BASE_URL: Optional[str] = None """The base of the API call URL.""" + DEFAULT_API_ENDPOINT_TEMPLATE: Optional[str] = None + """Template for default base URL with ``{universe_domain}`` placeholder.""" + API_BASE_MTLS_URL: Optional[str] = None """The base of the API call URL for mutual TLS.""" @@ -199,6 +316,33 @@ class JSONConnection(Connection): API_URL_TEMPLATE: Optional[str] = None """A template for the URL of a particular API call.""" + def __init__(self, client, client_info=None, api_endpoint=None): + super(JSONConnection, self).__init__(client, client_info) + # Fall back to client_options.api_endpoint recorded on the client when + # no explicit api_endpoint argument was passed to Connection.__init__. + client_api_endpoint = getattr(client, "_api_endpoint", None) + if api_endpoint is None and isinstance(client_api_endpoint, str): + api_endpoint = client_api_endpoint + self._custom_api_endpoint = bool(api_endpoint) + # Override API_BASE_URL on this instance when a custom endpoint is set + # (from either source); otherwise expand the subclass template for the + # client's resolved universe_domain. + if api_endpoint: + self.API_BASE_URL = api_endpoint + elif self.DEFAULT_API_ENDPOINT_TEMPLATE: + # Read the client's resolved universe_domain when present as a + # string, falling back to the default universe otherwise. + client_universe = getattr(client, "universe_domain", None) + if client_universe is not None and not isinstance(client_universe, str): + client_universe = None + universe_domain = determine_domain(client_universe, None).strip() + # Support both lowercase ({universe_domain}, used in veneers) and + # uppercase ({UNIVERSE_DOMAIN}, used in api_core/GAPIC) templates. + self.API_BASE_URL = self.DEFAULT_API_ENDPOINT_TEMPLATE.format( + universe_domain=universe_domain, + UNIVERSE_DOMAIN=universe_domain, + ) + def get_api_base_url_for_mtls(self, api_base_url=None): """Return the api base url for mutual TLS. @@ -221,17 +365,41 @@ def get_api_base_url_for_mtls(self, api_base_url=None): :rtype: str :returns: The api base url used for mTLS. + :raises ~google.auth.exceptions.MutualTLSChannelError: If + `GOOGLE_API_USE_MTLS_ENDPOINT=always` is set outside `googleapis.com`. + :raises ValueError: If `GOOGLE_API_USE_MTLS_ENDPOINT=always` is set when + `API_BASE_MTLS_URL` is not available. """ if api_base_url: return api_base_url + if self._custom_api_endpoint: + return self.API_BASE_URL + env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + client_universe = getattr(self._client, "universe_domain", None) + if ( + isinstance(client_universe, str) + and client_universe.lower() != DEFAULT_UNIVERSE + ): + if env == "always": + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {DEFAULT_UNIVERSE}." + ) + return self.API_BASE_URL + + # Preserve non-googleapis.com endpoints set by subclasses (e.g. emulators). + if self.API_BASE_URL and not _is_googleapis_url(self.API_BASE_URL): + return self.API_BASE_URL + if env == "always": + if not self.API_BASE_MTLS_URL: + raise ValueError("mTLS endpoint is not available.") url_to_use = self.API_BASE_MTLS_URL elif env == "never": url_to_use = self.API_BASE_URL else: - if self.ALLOW_AUTO_SWITCH_TO_MTLS_URL: + if self.ALLOW_AUTO_SWITCH_TO_MTLS_URL and self.API_BASE_MTLS_URL: url_to_use = ( self.API_BASE_MTLS_URL if self.http.is_mtls else self.API_BASE_URL ) diff --git a/packages/google-cloud-core/google/cloud/client/__init__.py b/packages/google-cloud-core/google/cloud/client/__init__.py index e10dd839ad0a..cbd81e0faef8 100644 --- a/packages/google-cloud-core/google/cloud/client/__init__.py +++ b/packages/google-cloud-core/google/cloud/client/__init__.py @@ -14,11 +14,13 @@ """Base classes for client used to interact with Google Cloud APIs.""" +from collections.abc import Mapping import io import json import os from pickle import PicklingError -from typing import Set, Tuple, Union +from typing import Any, Optional, Set, Tuple, TYPE_CHECKING, Union +from urllib.parse import urlsplit # PEP 0810: Explicit Lazy Imports # Python 3.15+ natively intercepts and defers these imports. @@ -32,8 +34,12 @@ __lazy_modules__: Set[str] = { "google.api_core.client_options", "google.api_core.exceptions", + "google.api_core.universe", "google.auth", + "google.auth.aio", + "google.auth.aio.credentials", "google.auth.api_key", + "google.auth.compute_engine", "google.auth.environment_vars", "google.auth.credentials", "google.auth.transport.requests", @@ -44,13 +50,18 @@ import google.api_core.client_options import google.api_core.exceptions +import google.api_core.universe import google.auth from google.auth import environment_vars +import google.auth.compute_engine import google.auth.credentials import google.auth.transport.requests from google.cloud._helpers import _determine_default_project from google.oauth2 import service_account +if TYPE_CHECKING: # pragma: NO COVER + from google.auth.aio import credentials as aio_credentials + try: import google.auth.api_key @@ -59,6 +70,101 @@ HAS_GOOGLE_AUTH_API_KEY = False # pragma: NO COVER # TODO: Investigate adding a test for google.auth.api_key ImportError (https://github.com/googleapis/python-cloud-core/issues/334) +try: + from google.api_core.universe import ( # type: ignore[attr-defined] + resolve_client_universe as _resolve_client_universe, + validate_credentials_universe as _validate_credentials_universe, + ) +except ImportError: # pragma: NO COVER + # TODO(universe-domain): Remove fallbacks once google-api-core >= 2.44.0. + 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], ...] = ( + google.auth.credentials.AnonymousCredentials, + _aio_credentials.AnonymousCredentials, + ) + except ImportError: # pragma: NO COVER + _ANONYMOUS_CREDENTIAL_TYPES = (google.auth.credentials.AnonymousCredentials,) + + def _resolve_client_universe( # type: ignore[misc] + client_options: Union[ + google.api_core.client_options.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, google.api_core.client_options.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__}" + ) + # .strip() is needed for google-api-core < 2.33.0, where determine_domain() + # returned whitespace-padded values unstripped. + return google.api_core.universe.determine_domain( + options_universe, + os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN"), + ).strip() + + def _validate_credentials_universe( # type: ignore[misc] + client_universe: str, + credentials: Union[ + google.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, google.auth.compute_engine.Credentials + ) and not getattr(credentials, "_universe_domain_cached", False): + return + google.api_core.universe.compare_domains(client_universe, credentials) + _GOOGLE_AUTH_CREDENTIALS_HELP = ( "This library only supports credentials from google-auth-library-python. " @@ -180,7 +286,8 @@ class Client(_ClientFactoryMixin): """ def __init__(self, credentials=None, _http=None, client_options=None): - if isinstance(client_options, dict): + self._universe_domain = _resolve_client_universe(client_options) + if isinstance(client_options, Mapping): client_options = google.api_core.client_options.from_dict(client_options) if client_options is None: client_options = google.api_core.client_options.ClientOptions() @@ -228,6 +335,16 @@ def __init__(self, credentials=None, _http=None, client_options=None): self._http_internal = _http self._client_cert_source = client_options.client_cert_source + self._api_endpoint = client_options.api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + :rtype: str + :returns: The resolved universe domain string. + """ + return self._universe_domain def __getstate__(self): """Explicitly state that clients are not pickleable.""" @@ -240,6 +357,33 @@ def __getstate__(self): ) ) + def _validate_universe_domain(self) -> bool: + """Validate that resolved credentials match the client universe domain. + + Returns: + bool: ``True`` when credentials match :attr:`universe_domain` or + validation is exempted (``None``, ``AnonymousCredentials``, or + uncached ``compute_engine.Credentials``). + + Raises: + google.api_core.universe.UniverseMismatchError: If the credentials + have an in-memory universe domain configured for a different + universe than :attr:`universe_domain`. + """ + _validate_credentials_universe(self._universe_domain, self._credentials) + return True + + def _get_default_host(self) -> Optional[str]: + """Extract the default service hostname from an attached connection.""" + connection = getattr(self, "_connection", None) + api_base_url = getattr(connection, "API_BASE_URL", None) + if not isinstance(api_base_url, str) or not api_base_url: + return None + parsed = urlsplit( + api_base_url if "://" in api_base_url else f"//{api_base_url}" + ) + return parsed.hostname + @property def _http(self): """Getter for object used for HTTP transport. @@ -248,9 +392,14 @@ def _http(self): :returns: An HTTP object. """ if self._http_internal is None: + self._validate_universe_domain() + session_kwargs = {"refresh_timeout": _CREDENTIALS_REFRESH_TIMEOUT} + default_host = self._get_default_host() + if default_host is not None: + session_kwargs["default_host"] = default_host self._http_internal = google.auth.transport.requests.AuthorizedSession( self._credentials, - refresh_timeout=_CREDENTIALS_REFRESH_TIMEOUT, + **session_kwargs, ) self._http_internal.configure_mtls_channel(self._client_cert_source) return self._http_internal diff --git a/packages/google-cloud-core/tests/unit/conftest.py b/packages/google-cloud-core/tests/unit/conftest.py new file mode 100644 index 000000000000..d32205cfade9 --- /dev/null +++ b/packages/google-cloud-core/tests/unit/conftest.py @@ -0,0 +1,22 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pytest + + +@pytest.fixture(autouse=True) +def clean_universe_env(monkeypatch: pytest.MonkeyPatch) -> None: + """Ensure ambient workstation env vars never affect unit tests.""" + monkeypatch.delenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", raising=False) + monkeypatch.delenv("GOOGLE_API_USE_MTLS_ENDPOINT", raising=False) diff --git a/packages/google-cloud-core/tests/unit/test__helpers.py b/packages/google-cloud-core/tests/unit/test__helpers.py index 2901602ab593..95140cdbc18d 100644 --- a/packages/google-cloud-core/tests/unit/test__helpers.py +++ b/packages/google-cloud-core/tests/unit/test__helpers.py @@ -720,6 +720,22 @@ def _call_fut(self, *args, **kwargs): return make_secure_channel(*args, **kwargs) + @staticmethod + def _expected_channel_kwargs(host, options): + import inspect + + import google.auth.transport.grpc + + kwargs = {"options": options} + if ( + "default_host" + in inspect.signature( + google.auth.transport.grpc.secure_authorized_channel + ).parameters + ): # pragma: NO COVER + kwargs["default_host"] = host + return kwargs + def test_it(self): import http.client @@ -740,7 +756,10 @@ def test_it(self): expected_options = (("grpc.primary_user_agent", user_agent),) secure_authorized_channel.assert_called_once_with( - credentials, mock.ANY, expected_target, options=expected_options + credentials, + mock.ANY, + expected_target, + **self._expected_channel_kwargs(host, expected_options), ) def test_extra_options(self): @@ -764,7 +783,10 @@ def test_extra_options(self): expected_options = (("grpc.primary_user_agent", user_agent), extra_options[0]) secure_authorized_channel.assert_called_once_with( - credentials, mock.ANY, expected_target, options=expected_options + credentials, + mock.ANY, + expected_target, + **self._expected_channel_kwargs(host, expected_options), ) diff --git a/packages/google-cloud-core/tests/unit/test__http.py b/packages/google-cloud-core/tests/unit/test__http.py index faee193795a7..cfa0da4e222e 100644 --- a/packages/google-cloud-core/tests/unit/test__http.py +++ b/packages/google-cloud-core/tests/unit/test__http.py @@ -170,8 +170,8 @@ def _make_one(self, *args, **kw): def _make_mock_one(self, *args, **kw): class MockConnection(self._get_target_class()): API_URL_TEMPLATE = "{api_base_url}/mock/{api_version}{path}" - API_BASE_URL = "http://mock" - API_BASE_MTLS_URL = "https://mock.mtls" + API_BASE_URL = "http://mock.googleapis.com" + API_BASE_MTLS_URL = "https://mock.mtls.googleapis.com" API_VERSION = "vMOCK" return MockConnection(*args, **kw) @@ -254,14 +254,14 @@ def test_get_api_base_url_for_mtls_env_always(self): conn = self._make_mock_one(client) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): uri = conn.get_api_base_url_for_mtls() - self.assertEqual(uri, "https://mock.mtls") + self.assertEqual(uri, "https://mock.mtls.googleapis.com") def test_get_api_base_url_for_mtls_env_never(self): client = object() conn = self._make_mock_one(client) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): uri = conn.get_api_base_url_for_mtls() - self.assertEqual(uri, "http://mock") + self.assertEqual(uri, "http://mock.googleapis.com") def test_get_api_base_url_for_mtls_env_auto(self): client = mock.Mock() @@ -272,7 +272,7 @@ def test_get_api_base_url_for_mtls_env_auto(self): # ALLOW_AUTO_SWITCH_TO_MTLS_URL is False, so use regular endpoint. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): uri = conn.get_api_base_url_for_mtls() - self.assertEqual(uri, "http://mock") + self.assertEqual(uri, "http://mock.googleapis.com") # ALLOW_AUTO_SWITCH_TO_MTLS_URL is True, so now endpoint dependes # on client._http.is_mtls @@ -280,12 +280,12 @@ def test_get_api_base_url_for_mtls_env_auto(self): with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): uri = conn.get_api_base_url_for_mtls() - self.assertEqual(uri, "http://mock") + self.assertEqual(uri, "http://mock.googleapis.com") client._http.is_mtls = True with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): uri = conn.get_api_base_url_for_mtls() - self.assertEqual(uri, "https://mock.mtls") + self.assertEqual(uri, "https://mock.mtls.googleapis.com") def test__make_request_no_data_no_content_type_no_headers(self): from google.cloud._http import CLIENT_INFO_HEADER diff --git a/packages/google-cloud-core/tests/unit/test_client.py b/packages/google-cloud-core/tests/unit/test_client.py index 943b42208aff..1d10a678055b 100644 --- a/packages/google-cloud-core/tests/unit/test_client.py +++ b/packages/google-cloud-core/tests/unit/test_client.py @@ -23,7 +23,12 @@ def _make_credentials(): import google.auth.credentials - return mock.Mock(spec=google.auth.credentials.CredentialsWithQuotaProject) + credentials = mock.Mock( + spec=google.auth.credentials.CredentialsWithQuotaProject, + universe_domain="googleapis.com", + ) + credentials.with_quota_project.return_value.universe_domain = "googleapis.com" + return credentials class Test_ClientFactoryMixin(unittest.TestCase): diff --git a/packages/google-cloud-core/tests/unit/test_universe_domain.py b/packages/google-cloud-core/tests/unit/test_universe_domain.py new file mode 100644 index 000000000000..8d08ab315953 --- /dev/null +++ b/packages/google-cloud-core/tests/unit/test_universe_domain.py @@ -0,0 +1,412 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from collections.abc import Iterator +import inspect +import types +from typing import Any +from unittest import mock +from urllib.parse import urlparse + +import pytest +import requests + +import google.api_core.client_options as client_options_lib +from google.api_core.universe import EmptyUniverseError, UniverseMismatchError +import google.auth +from google.auth import credentials as auth_credentials +import google.auth.compute_engine +from google.auth.exceptions import MutualTLSChannelError +from google.cloud import _helpers +from google.cloud import _http +from google.cloud.client import ( + _CREDENTIALS_REFRESH_TIMEOUT, + Client, + ClientWithProject, +) + +DEFAULT_PROJECT_ID = "test-proj" +DEFAULT_UNIVERSE = "googleapis.com" +CUSTOM_UNIVERSE = "apis-tpclp.goog" + + +class _FakeCredentials(auth_credentials.Credentials): + def __init__(self, universe_domain: str = DEFAULT_UNIVERSE) -> None: + super().__init__() + self._universe_domain = universe_domain + self.token = "fake-token" + + @property + def universe_domain(self) -> str: + return self._universe_domain + + def refresh(self, request: Any) -> None: # pragma: NO COVER + pass + + +def _is_googleapis_url(url: str) -> bool: + host = urlparse(url).hostname + return bool(host and (host == "googleapis.com" or host.endswith(".googleapis.com"))) + + +@pytest.fixture +def assert_no_googleapis_calls(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]: + def _guarded_send(self, request, *args, **kwargs): # pragma: NO COVER + if _is_googleapis_url(request.url): + raise ConnectionRefusedError( + f"Unexpected googleapis.com call: {request.url}" + ) + resp = requests.Response() + resp.status_code = 200 + resp._content = b"{}" + resp.headers = {"content-type": "application/json"} + resp.encoding = "utf-8" + return resp + + monkeypatch.setattr(requests.Session, "send", _guarded_send) + yield + + +class _MockServiceConnection(_http.JSONConnection): + DEFAULT_API_ENDPOINT_TEMPLATE = "https://mock.{universe_domain}" + API_BASE_MTLS_URL = "https://mock.mtls.googleapis.com" + ALLOW_AUTO_SWITCH_TO_MTLS_URL = True + API_VERSION = "v1" + API_URL_TEMPLATE = "{api_base_url}/{api_version}{path}" + + +class _NoMtlsServiceConnection(_http.JSONConnection): + DEFAULT_API_ENDPOINT_TEMPLATE = "https://nomtls.{universe_domain}" + API_BASE_MTLS_URL = None + ALLOW_AUTO_SWITCH_TO_MTLS_URL = True + API_VERSION = "v1" + API_URL_TEMPLATE = "{api_base_url}/{api_version}{path}" + + +class _MockServiceClient(ClientWithProject): + SCOPE = None + + def __init__( + self, + project=DEFAULT_PROJECT_ID, + credentials=None, + client_options=None, + _http=None, + ): + super().__init__( + project=project, + credentials=credentials, + client_options=client_options, + _http=_http, + ) + self._connection = _MockServiceConnection(self) + + +class TestClientAndConnectionUniverse: + @pytest.mark.parametrize( + ("client_options", "env_val", "expected_universe"), + [ + (None, None, DEFAULT_UNIVERSE), + ({}, None, DEFAULT_UNIVERSE), + (client_options_lib.ClientOptions(), None, DEFAULT_UNIVERSE), + (None, f" {CUSTOM_UNIVERSE} ", CUSTOM_UNIVERSE), + ({"universe_domain": CUSTOM_UNIVERSE}, None, CUSTOM_UNIVERSE), + ( + types.MappingProxyType({"universe_domain": CUSTOM_UNIVERSE}), + "other.goog", + CUSTOM_UNIVERSE, + ), + ( + client_options_lib.ClientOptions(universe_domain=CUSTOM_UNIVERSE), + "other.goog", + CUSTOM_UNIVERSE, + ), + ({"universe_domain": DEFAULT_UNIVERSE}, CUSTOM_UNIVERSE, DEFAULT_UNIVERSE), + ], + ) + def test_universe_resolution_and_routing( + self, + monkeypatch: pytest.MonkeyPatch, + assert_no_googleapis_calls: None, + client_options: Any, + env_val: str | None, + expected_universe: str, + ) -> None: + if env_val is not None: + monkeypatch.setenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", env_val) + + client = _MockServiceClient( + credentials=_FakeCredentials(expected_universe), + client_options=client_options, + ) + assert client.universe_domain == expected_universe + assert client._connection.API_BASE_URL == f"https://mock.{expected_universe}" + if expected_universe != DEFAULT_UNIVERSE: + assert client._connection.api_request("GET", "/items") == {} + + @pytest.mark.parametrize( + ("client_options", "env_val"), + [ + ({"universe_domain": ""}, None), + ({"universe_domain": ""}, CUSTOM_UNIVERSE), + (client_options_lib.ClientOptions(universe_domain=" "), None), + (None, ""), + (None, " "), + ], + ) + def test_empty_universe_raises( + self, + monkeypatch: pytest.MonkeyPatch, + client_options: Any, + env_val: str | None, + ) -> None: + if env_val is not None: + monkeypatch.setenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", env_val) + with pytest.raises(EmptyUniverseError): + _MockServiceClient( + credentials=auth_credentials.AnonymousCredentials(), + client_options=client_options, + ) + + def test_invalid_client_options_raises_type_error(self) -> None: + with pytest.raises(TypeError, match="ClientOptions instance, Mapping, or None"): + Client( + credentials=auth_credentials.AnonymousCredentials(), + client_options="invalid", + ) + + def test_credentials_universe_validation( + self, monkeypatch: pytest.MonkeyPatch, assert_no_googleapis_calls: None + ) -> None: + # Unconfigured credential mocks do not fail in __init__ when _http is unused + unconfigured_mock = mock.Mock(spec=auth_credentials.Credentials) + assert _MockServiceClient(credentials=unconfigured_mock).universe_domain == ( + DEFAULT_UNIVERSE + ) + + # Case 2a: TPC client + GDU credentials raises UniverseMismatchError on HTTP use + tpc_with_gdu_creds = _MockServiceClient( + credentials=_FakeCredentials(DEFAULT_UNIVERSE), + client_options={"universe_domain": CUSTOM_UNIVERSE}, + ) + with pytest.raises(UniverseMismatchError): + tpc_with_gdu_creds._connection.api_request("GET", "/items") + + # Case 2b: GDU client + TPC credentials raises UniverseMismatchError on HTTP use + gdu_with_tpc_creds = _MockServiceClient( + credentials=_FakeCredentials(CUSTOM_UNIVERSE) + ) + with pytest.raises(UniverseMismatchError): + _ = gdu_with_tpc_creds._http + + # ADC credentials validated on HTTP use after resolution + monkeypatch.setenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", CUSTOM_UNIVERSE) + with mock.patch.object( + google.auth, + "default", + autospec=True, + return_value=(_FakeCredentials(DEFAULT_UNIVERSE), DEFAULT_PROJECT_ID), + ): + adc_client = _MockServiceClient() + with pytest.raises(UniverseMismatchError): + _ = adc_client._http + + # Exemptions: None (when _http provided), AnonymousCredentials, uncached GCE + custom_http_client = Client( + _http=object(), client_options={"universe_domain": CUSTOM_UNIVERSE} + ) + assert custom_http_client.universe_domain == CUSTOM_UNIVERSE + assert custom_http_client._validate_universe_domain() is True + + anon_client = _MockServiceClient( + credentials=auth_credentials.AnonymousCredentials(), + client_options={"universe_domain": CUSTOM_UNIVERSE}, + ) + assert anon_client.universe_domain == CUSTOM_UNIVERSE + assert anon_client._connection.api_request("GET", "/items") == {} + + uncached_gce = google.auth.compute_engine.Credentials() + uncached_client = _MockServiceClient( + credentials=uncached_gce, + client_options={"universe_domain": CUSTOM_UNIVERSE}, + ) + assert uncached_client.universe_domain == CUSTOM_UNIVERSE + assert uncached_client._http is not None + + # Cached GCE credentials ARE validated + cached_gce = google.auth.compute_engine.Credentials(scopes=("s",)) + cached_gce._universe_domain_cached = True # type: ignore[attr-defined] + cached_gce_client = _MockServiceClient( + credentials=cached_gce, + client_options={"universe_domain": CUSTOM_UNIVERSE}, + ) + with pytest.raises(UniverseMismatchError): + _ = cached_gce_client._http + + def test_custom_api_endpoint_and_bare_client_fallbacks(self) -> None: + client = _MockServiceClient( + credentials=_FakeCredentials(CUSTOM_UNIVERSE), + client_options={ + "universe_domain": CUSTOM_UNIVERSE, + "api_endpoint": "https://custom.mock.internal:8443", + }, + ) + assert client._connection.API_BASE_URL == "https://custom.mock.internal:8443" + assert ( + _MockServiceConnection( + client, api_endpoint="https://direct.mock.internal" + ).API_BASE_URL + == "https://direct.mock.internal" + ) + assert ( + _MockServiceConnection(object()).API_BASE_URL + == "https://mock.googleapis.com" + ) + assert ( + _MockServiceConnection(mock.Mock()).API_BASE_URL + == "https://mock.googleapis.com" + ) + + def test_default_host_propagation_and_self_signed_jwt(self) -> None: + from google.auth import crypt + from google.oauth2 import service_account + + sa_kwargs: dict[str, Any] = {"always_use_jwt_access": True} + target_universe = DEFAULT_UNIVERSE + if ( + "universe_domain" + in inspect.signature(service_account.Credentials).parameters + ): # pragma: NO COVER + sa_kwargs["universe_domain"] = CUSTOM_UNIVERSE + target_universe = CUSTOM_UNIVERSE + + sa_creds = service_account.Credentials( + mock.Mock(spec=crypt.Signer), + "sa@test-proj.iam.gserviceaccount.com", + "https://oauth2.googleapis.com/token", + **sa_kwargs, + ) + client = _MockServiceClient( + credentials=sa_creds, + client_options={"universe_domain": target_universe}, + ) + assert client._http._default_host == f"mock.{target_universe}" + assert ( + client._credentials._jwt_credentials._audience + == f"https://mock.{target_universe}/" + ) + + for api_base_url, expected_host in [ + ("mock.apis-tpclp.goog:443", "mock.apis-tpclp.goog"), + ("https:///", None), + ]: + edge_client = _MockServiceClient( + credentials=auth_credentials.AnonymousCredentials() + ) + edge_client._connection.API_BASE_URL = api_base_url + with mock.patch( + "google.auth.transport.requests.AuthorizedSession" + ) as mock_session_cls: + mock_session_cls.return_value = mock.Mock() + _ = edge_client._http + expected_kwargs: dict[str, Any] = { + "refresh_timeout": _CREDENTIALS_REFRESH_TIMEOUT + } + if expected_host: + expected_kwargs["default_host"] = expected_host + mock_session_cls.assert_called_once_with( + edge_client._credentials, **expected_kwargs + ) + + def test_mtls_gating_and_fallbacks(self, monkeypatch: pytest.MonkeyPatch) -> None: + tpc_client = _MockServiceClient( + credentials=_FakeCredentials(CUSTOM_UNIVERSE), + client_options={"universe_domain": CUSTOM_UNIVERSE}, + _http=mock.Mock(is_mtls=True, spec=["is_mtls"]), + ) + monkeypatch.setenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + assert ( + tpc_client._connection.get_api_base_url_for_mtls() + == f"https://mock.{CUSTOM_UNIVERSE}" + ) + + monkeypatch.setenv("GOOGLE_API_USE_MTLS_ENDPOINT", "always") + with pytest.raises(MutualTLSChannelError): + tpc_client._connection.get_api_base_url_for_mtls() + + custom_ep_client = _MockServiceClient( + credentials=_FakeCredentials(CUSTOM_UNIVERSE), + client_options={ + "universe_domain": CUSTOM_UNIVERSE, + "api_endpoint": "https://custom.mock.internal", + }, + ) + assert ( + custom_ep_client._connection.get_api_base_url_for_mtls() + == "https://custom.mock.internal" + ) + + gdu_client = Client( + credentials=auth_credentials.AnonymousCredentials(), + _http=mock.Mock(is_mtls=True, spec=["is_mtls"]), + ) + emulator_conn = _MockServiceConnection(gdu_client) + emulator_conn.API_BASE_URL = "localhost:9023" + assert emulator_conn.get_api_base_url_for_mtls() == "localhost:9023" + + no_mtls_conn = _NoMtlsServiceConnection(gdu_client) + with pytest.raises(ValueError, match="mTLS endpoint is not available"): + no_mtls_conn.get_api_base_url_for_mtls() + monkeypatch.setenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + assert ( + no_mtls_conn.get_api_base_url_for_mtls() == "https://nomtls.googleapis.com" + ) + + +class TestMakeSecureChannelDefaultHost: + def test_forwards_or_omits_default_host_by_signature(self) -> None: + sentinel = object() + + def with_default_host( + credentials, request, target, default_host=None, **kwargs + ): + return sentinel # pragma: NO COVER + + def without_default_host(credentials, request, target, **kwargs): + return sentinel # pragma: NO COVER + + for fn, expected_extra in [ + (with_default_host, {"default_host": "datastore.apis-tpclp.goog"}), + (without_default_host, {}), + ]: + mock_fn = mock.create_autospec(fn, return_value=sentinel) + creds = object() + with mock.patch( + "google.auth.transport.grpc.secure_authorized_channel", new=mock_fn + ): + assert ( + _helpers.make_secure_channel( + creds, "agent", "datastore.apis-tpclp.goog" + ) + is sentinel + ) + mock_fn.assert_called_once_with( + creds, + mock.ANY, + "datastore.apis-tpclp.goog:443", + options=(("grpc.primary_user_agent", "agent"),), + **expected_extra, + )