Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 74 additions & 10 deletions packages/google-cloud-ndb/google/cloud/ndb/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)
Expand All @@ -31,13 +35,66 @@
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__)
)

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):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SYNC WARNING:

I noticed two sync gaps between #19251 and the proposed shared helpers in catalog.py (cl/1029785586). I recommend the following actions:

  • Update _validate_credentials_universe to mirror validate_credentials_universe in catalog.py (cl/1029785586), specifically using not getattr(credentials, "_universe_domain_cached", False) and exempting google.auth.aio.credentials.AnonymousCredentials.
  • Replace the inline universe resolution in Client.__init__ with a copy of resolve_client_universe from catalog.py (cl/1029785586) and a # TODO(universe-domain): comment.

Why: Checking getattr(..., "_universe_domain_cached", None) is False misses older google-auth versions where _universe_domain_cached is absent, and resolve_client_universe adds consistent EmptyUniverseError handling for empty/whitespace values. Keep both as local # TODO(universe-domain): copies until testing/constraints-3.10.txt exceeds google-api-core 2.44.0.

I know that you have better context on this than I do, so if any of these suggestions are wrong, please leave a comment here. Gemini will pick them up and learn from them during the next sync sweep.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated both helpers in 55a8eb2 to mirror validate_credentials_universe (using not getattr(..., "_universe_domain_cached", False) and exempting aio AnonymousCredentials) and resolve_client_universe with TODO(universe-domain) comments and unit tests. Kept the non-string cred_universe guard for existing ndb mock credentials and .strip() for google-api-core 2.28.0 compatibility.

"""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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

There are two critical issues with this line:\n\n1. Incorrect Argument: universe.compare_domains expects two domain strings, but credentials (a Credentials object) is passed instead of cred_universe. This will raise an AttributeError at runtime (e.g., 'Credentials' object has no attribute 'strip') when real credentials are used.\n2. Ignored Return Value: universe.compare_domains returns a boolean and does not raise an exception on mismatch. The return value must be checked, and universe.UniverseMismatchError should be raised if it returns False.

    if not universe.compare_domains(client_universe, cred_universe):\n        raise universe.UniverseMismatchError(\n            f"The client universe {client_universe} does not match the credentials universe {cred_universe}."\n        )

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

google.api_core.universe.compare_domains(client_universe, credentials) actually takes the credentials object (it reads credentials.universe_domain internally via getattr) and raises UniverseMismatchError directly on mismatch rather than returning False. Passing the cred_universe string instead would break mismatch detection since getattr on a str would always fall back to DEFAULT_UNIVERSE, so the current call is intentional.



def _get_gcd_project():
"""Gets the GCD application ID if it can be inferred."""
return os.getenv(environment_vars.GCD_DATASET)
Expand Down Expand Up @@ -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
Expand All @@ -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)

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
1 change: 1 addition & 0 deletions packages/google-cloud-ndb/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
218 changes: 217 additions & 1 deletion packages/google-cloud-ndb/tests/unit/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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")
Loading