Repository navigation
fix(ndb): resolve universe_domain and validate credentials in Client #19251
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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,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): | ||
| """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) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There are two critical issues with this line:\n\n1. Incorrect Argument: 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 )
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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) | ||
|
|
@@ -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. | ||
|
|
||
There was a problem hiding this comment.
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
#19251and the proposed shared helpers incatalog.py(cl/1029785586). I recommend the following actions:_validate_credentials_universeto mirrorvalidate_credentials_universeincatalog.py(cl/1029785586), specifically usingnot getattr(credentials, "_universe_domain_cached", False)and exemptinggoogle.auth.aio.credentials.AnonymousCredentials.Client.__init__with a copy ofresolve_client_universefromcatalog.py(cl/1029785586) and a# TODO(universe-domain):comment.Why: Checking
getattr(..., "_universe_domain_cached", None) is Falsemisses oldergoogle-authversions where_universe_domain_cachedis absent, andresolve_client_universeadds consistentEmptyUniverseErrorhandling for empty/whitespace values. Keep both as local# TODO(universe-domain):copies untiltesting/constraints-3.10.txtexceedsgoogle-api-core2.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.
There was a problem hiding this comment.
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.