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
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@

import datetime
import json
import os
import re
from collections.abc import Mapping
from typing import (
TYPE_CHECKING,
Any,
Expand All @@ -34,9 +36,12 @@
)

import grpc # type: ignore
from google.api_core import gapic_v1
from google.api_core import client_options as client_options_lib
from google.api_core import gapic_v1, universe
from google.api_core import retry as retries
from google.api_core.datetime_helpers import DatetimeWithNanoseconds
from google.auth import compute_engine
from google.auth.credentials import AnonymousCredentials
from google.cloud._helpers import _datetime_to_pb_timestamp # type: ignore
from google.protobuf import struct_pb2
from google.protobuf.timestamp_pb2 import Timestamp # type: ignore
Expand Down Expand Up @@ -1426,3 +1431,64 @@ def _get_document_from_bundle(
return bundled_doc.snapshot
else:
return None


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], ...] = (
AnonymousCredentials,
_aio_credentials.AnonymousCredentials,
)
except ImportError: # pragma: NO COVER
_ANONYMOUS_CREDENTIAL_TYPES = (AnonymousCredentials,)


# TODO(universe-domain): Replace with
# google.api_core.universe.resolve_client_universe once minimum
# google-api-core version exceeds 2.44.0.
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."""
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__}"
)
# Strip before determine_domain so whitespace-only values raise
# EmptyUniverseError even on google-api-core==2.28.0.
env_universe = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN")
return universe.determine_domain(
options_universe.strip()
if isinstance(options_universe, str)
else options_universe,
env_universe.strip() if isinstance(env_universe, str) else env_universe,
)


# TODO(universe-domain): Replace with
# google.api_core.universe.validate_credentials_universe once minimum
# google-api-core version exceeds 2.44.0.
def _validate_credentials_universe(client_universe: str, credentials: Any) -> None:

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 a couple of sync gaps between #19252 and the proposed shared helpers in catalog.py (cl/1029785586). I recommend the following actions:

  • Mirror _validate_credentials_universe on validate_credentials_universe in catalog.py (cl/1029785586), which also exempts google.auth.aio.credentials.AnonymousCredentials (important for Firestore's AsyncClient) alongside sync AnonymousCredentials and uncached compute_engine.Credentials.
  • Replace the inline universe resolution in BaseClient.__init__ with a copy of resolve_client_universe from catalog.py (cl/1029785586) and a # TODO(universe-domain): comment so universe resolution and EmptyUniverseError/TypeError handling stay consistent across clients.
  • Because google-cloud-firestore pins google-api-core==2.28.0 in testing/constraints-3.10.txt, keep both as local # TODO(universe-domain): copies until the floor exceeds 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 6d75f72: added aio AnonymousCredentials exemption (guarded for google-auth 2.14.1) and replaced the inline resolution with a local _resolve_client_universe copy marked with TODO(universe-domain) until the google-api-core floor passes 2.44.0. Also added unit tests covering both helpers.

"""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)
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
import google.api_core.path_template
import grpc # type: ignore
from google.api_core import retry as retries
from google.api_core import universe
from google.api_core.gapic_v1 import client_info
from google.auth.credentials import AnonymousCredentials
from google.cloud.client import ClientWithProject # type: ignore
Expand Down Expand Up @@ -164,6 +165,12 @@ def __init__(
)
self._client_options = client_options

self._universe_domain = _helpers._resolve_client_universe(self._client_options)
if self._emulator_host is None:
_helpers._validate_credentials_universe(
self._universe_domain, self._credentials
)

self._database = database

def _firestore_api_helper(self, transport, client_class, client_module) -> Any:
Expand All @@ -178,6 +185,9 @@ def _firestore_api_helper(self, transport, client_class, client_module) -> Any:
if self._emulator_host is not None:
channel = self._emulator_channel(transport)
else:
_helpers._validate_credentials_universe(
self._universe_domain, self._credentials
)
channel = transport.create_channel(
self._target,
credentials=self._credentials,
Expand Down Expand Up @@ -233,9 +243,18 @@ def _target_helper(self, client_class) -> str:
return self._emulator_host
elif self._client_options and self._client_options.api_endpoint:
return self._client_options.api_endpoint
elif self._universe_domain != universe.DEFAULT_UNIVERSE:
return client_class._DEFAULT_ENDPOINT_TEMPLATE.format(
UNIVERSE_DOMAIN=self._universe_domain
)
else:
return client_class.DEFAULT_ENDPOINT

@property
def universe_domain(self) -> str:
"""The universe domain used by the client."""
return self._universe_domain

@property
def _target(self):
"""Return the target (where the API is).
Expand Down
Loading
Loading