diff --git a/packages/google-cloud-ndb/google/cloud/ndb/client.py b/packages/google-cloud-ndb/google/cloud/ndb/client.py index d7f70753dd19..3c27b85e7f3d 100644 --- a/packages/google-cloud-ndb/google/cloud/ndb/client.py +++ b/packages/google-cloud-ndb/google/cloud/ndb/client.py @@ -16,11 +16,15 @@ import contextlib import os +from collections.abc import Mapping import google.api_core.client_options import grpc import requests +from google.api_core import universe from google.api_core.gapic_v1 import client_info +from google.auth import compute_engine +from google.auth import credentials as auth_credentials from google.cloud.datastore_v1.services.datastore.transports import ( grpc as datastore_grpc, ) @@ -31,6 +35,18 @@ from google.cloud.ndb import context as context_module from google.cloud.ndb import key as key_module +try: + # google.auth.aio was added in google-auth 2.28.0; older supported versions + # only provide synchronous AnonymousCredentials. + from google.auth.aio import credentials as _aio_credentials + + _ANONYMOUS_CREDENTIAL_TYPES: tuple[type, ...] = ( + auth_credentials.AnonymousCredentials, + _aio_credentials.AnonymousCredentials, + ) +except ImportError: # pragma: NO COVER + _ANONYMOUS_CREDENTIAL_TYPES = (auth_credentials.AnonymousCredentials,) + _CLIENT_INFO = client_info.ClientInfo( user_agent="google-cloud-ndb/{}".format(__version__) ) @@ -38,6 +54,47 @@ DATASTORE_API_HOST = "datastore.googleapis.com" +# TODO(universe-domain): Replace with +# google.api_core.universe.resolve_client_universe once +# testing/constraints-3.10.txt exceeds google-api-core 2.44.0. +def _resolve_client_universe(client_options=None): + """Resolve a client's universe domain from ``client_options`` or the environment.""" + 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__}" + ) + return universe.determine_domain( + options_universe, + os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN"), + ).strip() + + +# TODO(universe-domain): Replace with +# google.api_core.universe.validate_credentials_universe once +# testing/constraints-3.10.txt exceeds google-api-core 2.44.0. +def _validate_credentials_universe(client_universe, credentials): + """Validate that resolved client credentials match ``client_universe``.""" + if credentials is None or isinstance(credentials, _ANONYMOUS_CREDENTIAL_TYPES): + return + # Avoid synchronous GCE metadata server HTTP calls when + # compute_engine.Credentials hasn't resolved its universe yet. + if isinstance(credentials, compute_engine.Credentials) and not getattr( + credentials, "_universe_domain_cached", False + ): + return + cred_universe = getattr(credentials, "universe_domain", universe.DEFAULT_UNIVERSE) + if not isinstance(cred_universe, str): + return + universe.compare_domains(client_universe, credentials) + + def _get_gcd_project(): """Gets the GCD application ID if it can be inferred.""" return os.getenv(environment_vars.GCD_DATASET) @@ -104,7 +161,6 @@ def __init__( database=None, ): self.namespace = namespace - self.host = os.environ.get(environment_vars.GCD_HOST, DATASTORE_API_HOST) self.client_info = _CLIENT_INFO self._client_options = client_options self.database = database @@ -114,15 +170,17 @@ def __init__( emulator = bool(os.environ.get(environment_vars.GCD_HOST)) self.secure = not emulator - # Use Datastore API host from client_options if provided, otherwise use default - api_endpoint = DATASTORE_API_HOST - if client_options is not None: - if isinstance(client_options, dict): - client_options = google.api_core.client_options.from_dict( - client_options - ) - if client_options.api_endpoint: - api_endpoint = client_options.api_endpoint + if isinstance(client_options, dict): + client_options = google.api_core.client_options.from_dict(client_options) + + universe_domain = _resolve_client_universe(client_options) + self._universe_domain = universe_domain + + # Use Datastore API host from client_options if provided, otherwise + # template using the resolved universe_domain. + api_endpoint = f"datastore.{universe_domain}" + if client_options is not None and client_options.api_endpoint: + api_endpoint = client_options.api_endpoint self.host = os.environ.get(environment_vars.GCD_HOST, api_endpoint) @@ -153,6 +211,7 @@ def __init__( ], ) else: + _validate_credentials_universe(self._universe_domain, self._credentials) user_agent = self.client_info.to_user_agent() channel = _helpers.make_secure_channel( self._credentials, user_agent, self.host @@ -238,6 +297,11 @@ def context( # Finish up any work left to do on the event loop context.eventloop.run() + @property + def universe_domain(self): + """The universe domain used by the client.""" + return self._universe_domain + @property def _http(self): """Getter for object used for HTTP transport. diff --git a/packages/google-cloud-ndb/tests/conftest.py b/packages/google-cloud-ndb/tests/conftest.py index 98163b5b15db..6bf2818e016e 100644 --- a/packages/google-cloud-ndb/tests/conftest.py +++ b/packages/google-cloud-ndb/tests/conftest.py @@ -78,6 +78,7 @@ def initialize_environment(request, environ): environ.pop(environment_vars.GCD_DATASET, None) environ.pop(environment_vars.GCD_HOST, None) environ.pop("GOOGLE_APPLICATION_CREDENTIALS", None) + environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) @pytest.fixture diff --git a/packages/google-cloud-ndb/tests/unit/test_client.py b/packages/google-cloud-ndb/tests/unit/test_client.py index 458716a813d9..b339ada6ed32 100644 --- a/packages/google-cloud-ndb/tests/unit/test_client.py +++ b/packages/google-cloud-ndb/tests/unit/test_client.py @@ -16,8 +16,9 @@ from unittest import mock import pytest +from google.api_core import universe from google.api_core.client_options import ClientOptions -from google.auth import credentials +from google.auth import compute_engine, credentials from google.cloud.datastore import _http from google.cloud import environment_vars @@ -187,3 +188,218 @@ def test_client_info(): version = agent.split("/")[1] assert version[0].isdigit() assert "." in version + + @staticmethod + @pytest.mark.parametrize( + "client_options", + [ + ClientOptions(universe_domain="my-universe.com"), + {"universe_domain": "my-universe.com"}, + ], + ) + def test_constructor_universe_domain_from_client_options(client_options): + creds = mock.Mock(spec=credentials.Credentials) + creds.universe_domain = "my-universe.com" + with mock.patch( + "google.cloud.ndb.client._helpers.make_secure_channel" + ) as make_channel: + client = client_module.Client( + project="testing", + credentials=creds, + client_options=client_options, + ) + assert client.universe_domain == "my-universe.com" + assert client.host == "datastore.my-universe.com" + assert client.secure is True + make_channel.assert_called_once_with( + creds, client.client_info.to_user_agent(), "datastore.my-universe.com" + ) + + @staticmethod + def test_constructor_universe_domain_from_env(): + creds = mock.Mock(spec=credentials.Credentials) + creds.universe_domain = "env-universe.com" + patch_environ = mock.patch.dict( + "google.cloud.ndb.client.os.environ", + {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "env-universe.com"}, + clear=True, + ) + with patch_environ: + client = client_module.Client(project="testing", credentials=creds) + assert client.universe_domain == "env-universe.com" + assert client.host == "datastore.env-universe.com" + + @staticmethod + def test_constructor_universe_domain_precedence(): + creds = mock.Mock(spec=credentials.Credentials) + creds.universe_domain = "opts-universe.com" + patch_environ = mock.patch.dict( + "google.cloud.ndb.client.os.environ", + {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "env-universe.com"}, + clear=True, + ) + with patch_environ: + client = client_module.Client( + project="testing", + credentials=creds, + client_options=ClientOptions(universe_domain="opts-universe.com"), + ) + assert client.universe_domain == "opts-universe.com" + assert client.host == "datastore.opts-universe.com" + + @staticmethod + def test_constructor_api_endpoint_overrides_universe_template(): + creds = mock.Mock(spec=credentials.Credentials) + creds.universe_domain = "my-universe.com" + client = client_module.Client( + project="testing", + credentials=creds, + client_options=ClientOptions( + universe_domain="my-universe.com", + api_endpoint="custom.endpoint.test:443", + ), + ) + assert client.universe_domain == "my-universe.com" + assert client.host == "custom.endpoint.test:443" + + @staticmethod + @pytest.mark.parametrize( + "client_options,env_universe", + [ + (ClientOptions(universe_domain=""), None), + ({"universe_domain": " "}, None), + (None, ""), + (None, " "), + ], + ) + def test_constructor_empty_universe_domain_raises(client_options, env_universe): + env = ( + {} + if env_universe is None + else {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": env_universe} + ) + patch_environ = mock.patch.dict( + "google.cloud.ndb.client.os.environ", env, clear=True + ) + with patch_environ: + with patch_credentials("testing"): + with pytest.raises(universe.EmptyUniverseError): + client_module.Client(client_options=client_options) + + @staticmethod + @pytest.mark.parametrize( + "client_options,env_universe,cred_universe", + [ + (None, None, "tpc.test"), + (ClientOptions(universe_domain="tpc.test"), None, "googleapis.com"), + (None, "tpc.test", "googleapis.com"), + ], + ) + def test_constructor_universe_mismatch_raises_before_channel( + client_options, env_universe, cred_universe + ): + creds = mock.Mock(spec=credentials.Credentials) + creds.universe_domain = cred_universe + env = ( + {} + if env_universe is None + else {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": env_universe} + ) + patch_environ = mock.patch.dict( + "google.cloud.ndb.client.os.environ", env, clear=True + ) + with ( + patch_environ, + mock.patch("google.auth.default", return_value=(creds, "testing")), + mock.patch( + "google.cloud.ndb.client._helpers.make_secure_channel" + ) as make_channel, + ): + with pytest.raises(universe.UniverseMismatchError): + client_module.Client(client_options=client_options) + make_channel.assert_not_called() + + @staticmethod + def test_constructor_emulator_exempt_from_universe_mismatch(): + creds = mock.Mock(spec=credentials.Credentials) + creds.universe_domain = "tpc.test" + patch_environ = mock.patch.dict( + "google.cloud.ndb.client.os.environ", + {"DATASTORE_EMULATOR_HOST": "localhost:8081"}, + clear=True, + ) + with patch_environ: + client = client_module.Client(project="testing", credentials=creds) + assert client.host == "localhost:8081" + assert client.secure is False + + @staticmethod + def test_constructor_anonymous_credentials_exempt_from_universe_mismatch(): + creds = credentials.AnonymousCredentials() + client = client_module.Client( + project="testing", + credentials=creds, + client_options=ClientOptions(universe_domain="tpc.test"), + ) + assert client.universe_domain == "tpc.test" + assert client.host == "datastore.tpc.test" + + @staticmethod + def test_constructor_uncached_compute_engine_credentials_exempt(): + creds = compute_engine.Credentials() + assert not getattr(creds, "_universe_domain_cached", False) + client = client_module.Client( + project="testing", + credentials=creds, + client_options=ClientOptions(universe_domain="tpc.test"), + ) + assert client.universe_domain == "tpc.test" + assert client.host == "datastore.tpc.test" + + @staticmethod + def test_constructor_cached_compute_engine_credentials_mismatch_raises(): + creds = compute_engine.Credentials() + creds._universe_domain = "googleapis.com" + creds._universe_domain_cached = True + with pytest.raises(universe.UniverseMismatchError): + client_module.Client( + project="testing", + credentials=creds, + client_options=ClientOptions(universe_domain="tpc.test"), + ) + + @staticmethod + def test_validate_credentials_universe_aio_anonymous_exempt(): + aio_credentials = pytest.importorskip("google.auth.aio.credentials") + creds = aio_credentials.AnonymousCredentials() + client_module._validate_credentials_universe("tpc.test", creds) + + @staticmethod + def test_validate_credentials_universe_missing_cache_attr_exempt(): + creds = compute_engine.Credentials.__new__(compute_engine.Credentials) + assert not hasattr(creds, "_universe_domain_cached") + client_module._validate_credentials_universe("tpc.test", creds) + + @staticmethod + @pytest.mark.parametrize( + "client_options,env_universe,expected", + [ + (None, None, "googleapis.com"), + (None, " env.test ", "env.test"), + ({"universe_domain": " dict.test "}, None, "dict.test"), + (ClientOptions(universe_domain=" opts.test "), None, "opts.test"), + ], + ) + def test_resolve_client_universe(client_options, env_universe, expected): + env = ( + {} + if env_universe is None + else {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": env_universe} + ) + with mock.patch.dict("google.cloud.ndb.client.os.environ", env, clear=True): + assert client_module._resolve_client_universe(client_options) == expected + + @staticmethod + def test_resolve_client_universe_invalid_type_raises(): + with pytest.raises(TypeError, match="client_options must be"): + client_module._resolve_client_universe("invalid")