diff --git a/packages/google-cloud-bigtable/google/cloud/bigtable/client.py b/packages/google-cloud-bigtable/google/cloud/bigtable/client.py index 602997d000a4..6f4bf573950a 100644 --- a/packages/google-cloud-bigtable/google/cloud/bigtable/client.py +++ b/packages/google-cloud-bigtable/google/cloud/bigtable/client.py @@ -33,6 +33,7 @@ import warnings import grpc # type: ignore +from google.api_core import universe from google.api_core.gapic_v1 import client_info as client_info_lib from google.auth.credentials import AnonymousCredentials # type: ignore from google.cloud.client import ClientWithProject # type: ignore @@ -40,6 +41,7 @@ from google.cloud import bigtable, bigtable_admin_v2 from google.cloud.bigtable.cluster import _CLUSTER_NAME_RE, Cluster +from google.cloud.bigtable.data._helpers import _validate_credentials_universe from google.cloud.bigtable.instance import Instance from google.cloud.bigtable_admin_v2.services.bigtable_instance_admin.transports import ( BigtableInstanceAdminGrpcTransport, @@ -82,6 +84,57 @@ def inner(self): return inner +def _get_client_option(options, name): + """Read an attribute or dict key from ``options`` if present.""" + if isinstance(options, dict): + return options.get(name) + return getattr(options, name, None) + + +def _inherit_admin_client_options( + client_options, admin_client_options, universe_domain_env +): + """Return ``admin_client_options``, with the endpoint settings it does not + set filled in. Neither options argument is modified. + + - ``universe_domain`` falls back to ``client_options``, then to + ``universe_domain_env`` (the ``GOOGLE_CLOUD_UNIVERSE_DOMAIN`` environment + variable). If neither sets one, it is left unset. + - ``api_endpoint`` falls back to ``client_options`` only when + ``admin_client_options`` sets neither ``api_endpoint`` nor + ``universe_domain``, so a ``client_options`` endpoint never overrides a + universe chosen for admin operations. + """ + inherited = {} + # A universe set in admin_client_options stands on its own. Inheriting an + # api_endpoint from client_options would override it. + if _get_client_option(admin_client_options, "universe_domain") is None: + # Universe: client_options, then the environment variable. With + # neither, it stays unset and the admin clients apply their default. + universe_domain = _get_client_option(client_options, "universe_domain") + if universe_domain is None: + universe_domain = universe_domain_env + if universe_domain is not None: + inherited["universe_domain"] = universe_domain + # Endpoint: client_options, unless admin_client_options sets its own. + client_endpoint = _get_client_option(client_options, "api_endpoint") + if client_endpoint and not _get_client_option( + admin_client_options, "api_endpoint" + ): + inherited["api_endpoint"] = client_endpoint + if not inherited: + # Nothing to add: use the options exactly as they were passed in. + return admin_client_options + # Add the inherited settings to a copy, so the caller's object is not + # modified. A dict stays a dict. + if admin_client_options is None or isinstance(admin_client_options, dict): + return {**(admin_client_options or {}), **inherited} + admin_client_options = copy.copy(admin_client_options) + for name, value in inherited.items(): + setattr(admin_client_options, name, value) + return admin_client_options + + class Client(ClientWithProject): """Client for interacting with Google Cloud Bigtable API. @@ -120,13 +173,19 @@ class Client(ClientWithProject): :type client_options: :class:`~google.api_core.client_options.ClientOptions` or :class:`dict` :param client_options: (Optional) Client options used to set user options - on the client. API Endpoint should be set through client_options. + on the client. The credential settings, ``api_endpoint`` and + ``universe_domain`` set here are used for both data and admin + operations, unless ``admin_client_options`` overrides the last two + for admin operations. :type admin_client_options: :class:`~google.api_core.client_options.ClientOptions` or :class:`dict` - :param admin_client_options: (Optional) Client options used to set user - options on the client. API Endpoint for admin operations should be set - through admin_client_options. + :param admin_client_options: (Optional) Overrides the ``api_endpoint`` + and ``universe_domain`` from ``client_options`` for admin operations + only. Data and admin operations are served by separate APIs, so use + this when admin operations need a different endpoint than data + operations. If neither is set here, the values from + ``client_options`` are used. :type channel: :instance: grpc.Channel :param channel (grpc.Channel): (Optional) DEPRECATED: @@ -183,7 +242,11 @@ def __init__( ) self._client_options = client_options - self._admin_client_options = admin_client_options + self._admin_client_options = _inherit_admin_client_options( + client_options, + admin_client_options, + os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN"), + ) self._channel = channel self.SCOPE = self._get_scopes() super(Client, self).__init__( @@ -225,13 +288,38 @@ def _emulator_channel(self, transport, options): channel_fn = grpc.insecure_channel return channel_fn(self._emulator_host, options=options) + def _resolve_admin_endpoint(self, client_class): + """Resolve the target host for GAPIC admin channels. + + Uses ``admin_client_options`` as resolved when the client was + constructed (see ``_inherit_admin_client_options``), so the + ``GOOGLE_CLOUD_UNIVERSE_DOMAIN`` environment variable is not read + again here. If no ``universe_domain`` is set there, the default + ``googleapis.com`` is used. + + An explicit ``api_endpoint`` overrides ``universe_domain`` without + comparing hostnames, matching GAPIC behavior for regional, proxy, or + PSC endpoints. ``universe_domain`` is still validated first so an empty + string raises ``EmptyUniverseError`` even when ``api_endpoint`` is set. + """ + universe_domain = universe.determine_domain( + _get_client_option(self._admin_client_options, "universe_domain"), None + ) + _validate_credentials_universe(universe_domain, self._credentials) + api_endpoint = _get_client_option(self._admin_client_options, "api_endpoint") + if api_endpoint: + return api_endpoint + if universe_domain == universe.DEFAULT_UNIVERSE: + return client_class.DEFAULT_ENDPOINT + return client_class._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + def _create_gapic_client_channel(self, client_class, grpc_transport): if self._emulator_host is not None: api_endpoint = self._emulator_host - elif self._client_options and self._client_options.api_endpoint: - api_endpoint = self._client_options.api_endpoint else: - api_endpoint = client_class.DEFAULT_ENDPOINT + api_endpoint = self._resolve_admin_endpoint(client_class) if self._emulator_host is not None: channel = self._emulator_channel( diff --git a/packages/google-cloud-bigtable/google/cloud/bigtable/data/_async/client.py b/packages/google-cloud-bigtable/google/cloud/bigtable/data/_async/client.py index 38792623749f..d435f0bb033d 100644 --- a/packages/google-cloud-bigtable/google/cloud/bigtable/data/_async/client.py +++ b/packages/google-cloud-bigtable/google/cloud/bigtable/data/_async/client.py @@ -38,6 +38,7 @@ import google.auth.credentials from google.api_core import client_options as client_options_lib from google.api_core import retry as retries +from google.api_core import universe from google.api_core.exceptions import ( Aborted, Cancelled, @@ -61,6 +62,7 @@ _get_retryable_errors, _get_timeouts, _retry_exception_factory, + _validate_credentials_universe, _validate_timeouts, _WarmedInstanceKey, ) @@ -253,6 +255,14 @@ def __init__( project=project, client_options=client_options, ) + if self._emulator_host is None: + client_universe = universe.determine_domain( + client_options.universe_domain if client_options else None, + os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN"), + ) + _validate_credentials_universe( + client_universe, getattr(self, "_credentials", None) + ) self._gapic_client = GapicClient( credentials=credentials, client_options=client_options, @@ -261,33 +271,34 @@ def __init__( *args, **kwargs, channel=self._build_grpc_channel ), ) - if ( - credentials - and hasattr(credentials, "universe_domain") - and credentials.universe_domain != self.universe_domain - and self._emulator_host is None - ): - # validate that the universe domain of the credentials matches the - # universe domain configured in client_options - raise ValueError( - f"The configured universe domain ({self.universe_domain}) does " - "not match the universe domain found in the credentials " - f"({self._credentials.universe_domain}). If you haven't " - "configured the universe domain explicitly, `googleapis.com` " - "is the default." - ) self._is_closed = CrossSync.Event() # Private argument, for internal use only self._disable_background_refresh = bool( kwargs.get("_disable_background_refresh", False) ) handlers: list[MetricsHandler] = [] - if self._emulator_host is None: + has_custom_endpoint = bool(client_options and client_options.api_endpoint) + if ( + self._emulator_host is None + and not isinstance( + self._credentials, google.auth.credentials.AnonymousCredentials + ) + and not has_custom_endpoint + ): try: - # create a metrics exporter using the same client configuration + # Pass only universe_domain and client_cert_source so + # Bigtable-specific options (such as scopes or api_audience) are + # not sent to Cloud Monitoring. exporter = BigtableMetricsExporter( credentials=self._credentials, - client_options=client_options, + client_options=client_options_lib.ClientOptions( + universe_domain=self.universe_domain, + client_cert_source=( + client_options.client_cert_source + if client_options + else None + ), + ), ) handlers.append( GoogleCloudMetricsHandler( diff --git a/packages/google-cloud-bigtable/google/cloud/bigtable/data/_helpers.py b/packages/google-cloud-bigtable/google/cloud/bigtable/data/_helpers.py index 7550862dbd7a..b517ed3e2fb8 100644 --- a/packages/google-cloud-bigtable/google/cloud/bigtable/data/_helpers.py +++ b/packages/google-cloud-bigtable/google/cloud/bigtable/data/_helpers.py @@ -32,7 +32,10 @@ from google.api_core import exceptions as core_exceptions from google.api_core import retry as retries +from google.api_core import universe from google.api_core.retry import RetryFailureReason, exponential_sleep_generator +from google.auth import compute_engine # type: ignore +from google.auth import credentials as auth_credentials # type: ignore from google.protobuf import any_pb2, message from google.rpc import code_pb2, status_pb2 @@ -476,3 +479,27 @@ def get_attempt_backoff(self, attempt_idx) -> float: if attempt_idx < 0: raise IndexError("received negative attempt number") return self.history[attempt_idx] + + +# 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: auth_credentials.Credentials | None, +) -> None: + """Validate that resolved client credentials match ``client_universe``.""" + if credentials is None or isinstance( + credentials, auth_credentials.AnonymousCredentials + ): + 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) diff --git a/packages/google-cloud-bigtable/google/cloud/bigtable/data/_sync_autogen/client.py b/packages/google-cloud-bigtable/google/cloud/bigtable/data/_sync_autogen/client.py index a485b53f78c4..9f91ab31f2f9 100644 --- a/packages/google-cloud-bigtable/google/cloud/bigtable/data/_sync_autogen/client.py +++ b/packages/google-cloud-bigtable/google/cloud/bigtable/data/_sync_autogen/client.py @@ -32,6 +32,7 @@ import google.auth.credentials from google.api_core import client_options as client_options_lib from google.api_core import retry as retries +from google.api_core import universe from google.api_core.exceptions import ( Aborted, Cancelled, @@ -55,6 +56,7 @@ _get_retryable_errors, _get_timeouts, _retry_exception_factory, + _validate_credentials_universe, _validate_timeouts, _WarmedInstanceKey, ) @@ -186,6 +188,14 @@ def __init__( project=project, client_options=client_options, ) + if self._emulator_host is None: + client_universe = universe.determine_domain( + client_options.universe_domain if client_options else None, + os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN"), + ) + _validate_credentials_universe( + client_universe, getattr(self, "_credentials", None) + ) self._gapic_client = GapicClient( credentials=credentials, client_options=client_options, @@ -194,24 +204,30 @@ def __init__( *args, **kwargs, channel=self._build_grpc_channel ), ) - if ( - credentials - and hasattr(credentials, "universe_domain") - and (credentials.universe_domain != self.universe_domain) - and (self._emulator_host is None) - ): - raise ValueError( - f"The configured universe domain ({self.universe_domain}) does not match the universe domain found in the credentials ({self._credentials.universe_domain}). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) self._is_closed = CrossSync._Sync_Impl.Event() self._disable_background_refresh = bool( kwargs.get("_disable_background_refresh", False) ) handlers: list[MetricsHandler] = [] - if self._emulator_host is None: + has_custom_endpoint = bool(client_options and client_options.api_endpoint) + if ( + self._emulator_host is None + and ( + not isinstance( + self._credentials, google.auth.credentials.AnonymousCredentials + ) + ) + and (not has_custom_endpoint) + ): try: exporter = BigtableMetricsExporter( - credentials=self._credentials, client_options=client_options + credentials=self._credentials, + client_options=client_options_lib.ClientOptions( + universe_domain=self.universe_domain, + client_cert_source=client_options.client_cert_source + if client_options + else None, + ), ) handlers.append( GoogleCloudMetricsHandler( @@ -1424,9 +1440,7 @@ def mutate_row( def execute_rpc(): return self.client._gapic_client.mutate_row( - request=request, - timeout=next(attempt_timeout_gen), - retry=None, + request=request, timeout=next(attempt_timeout_gen), retry=None ) return tracked_retry( diff --git a/packages/google-cloud-bigtable/tests/unit/data/_async/test_client.py b/packages/google-cloud-bigtable/tests/unit/data/_async/test_client.py index 3eaffac1e639..10f1265a6ab3 100644 --- a/packages/google-cloud-bigtable/tests/unit/data/_async/test_client.py +++ b/packages/google-cloud-bigtable/tests/unit/data/_async/test_client.py @@ -22,6 +22,7 @@ from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.auth.credentials import AnonymousCredentials +from google.oauth2 import credentials as oauth2_credentials from google.cloud.bigtable.data import TABLE_DEFAULT, mutations from google.cloud.bigtable.data._cross_sync import CrossSync @@ -102,6 +103,19 @@ def mock_metrics_batch_write(): yield +class _StubCredentials(oauth2_credentials.Credentials): + """Non-anonymous credential stub with a read-only ``universe_domain`` + property across all supported ``google-auth`` versions.""" + + def __init__(self, universe_domain: str = "googleapis.com"): + super().__init__("token") + self._test_universe_domain = universe_domain + + @property + def universe_domain(self) -> str: + return self._test_universe_domain + + @CrossSync.convert_class( sync_name="TestBigtableDataClient", add_mapping_for_name="TestBigtableDataClient", @@ -126,7 +140,7 @@ def _make_client(cls, *args, use_emulator=True, use_mtls="auto", **kwargs): warnings.filterwarnings("ignore", category=RuntimeWarning) else: # set some default values - kwargs["credentials"] = kwargs.get("credentials", AnonymousCredentials()) + kwargs["credentials"] = kwargs.get("credentials", _StubCredentials()) kwargs["project"] = kwargs.get("project", "project-id") if use_mtls is not None: env_mask["GOOGLE_API_USE_MTLS_ENDPOINT"] = use_mtls @@ -142,7 +156,7 @@ async def test_ctor(self): ) expected_project = "project-id" - expected_credentials = AnonymousCredentials() + expected_credentials = _StubCredentials() client = self._make_client( project="project-id", credentials=expected_credentials, @@ -289,22 +303,35 @@ async def test_ctor_dict_options(self): async def test_metrics_exporter_init_shares_arguments( self, exporter_mock_sync, exporter_mock_async ): - expected_credentials = AnonymousCredentials() + import os + + expected_credentials = _StubCredentials() expected_project = "custom_project" - expected_options = client_options.ClientOptions() - expected_options.credentials_file = None - expected_options.quota_project_id = None + cert_source = mock.Mock() + input_options = client_options.ClientOptions( + client_cert_source=cert_source, + api_audience="https://bigtable.googleapis.com/", + ) mock_called = exporter_mock_async if CrossSync.is_async else exporter_mock_sync - async with self._make_client( - project=expected_project, - credentials=expected_credentials, - client_options=expected_options, - use_emulator=False, + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"} ): - mock_called.assert_called_once_with( + async with self._make_client( + project=expected_project, credentials=expected_credentials, - client_options=expected_options, - ) + client_options=input_options, + use_emulator=False, + ) as client: + mock_called.assert_called_once() + call_kwargs = mock_called.call_args.kwargs + assert call_kwargs["credentials"] == client._credentials + exporter_options = call_kwargs["client_options"] + assert isinstance(exporter_options, client_options.ClientOptions) + assert exporter_options is not input_options + assert exporter_options.universe_domain == "googleapis.com" + assert exporter_options.client_cert_source is cert_source + assert exporter_options.api_endpoint is None + assert exporter_options.api_audience is None @CrossSync.pytest @mock.patch( @@ -1298,8 +1325,7 @@ async def test_configured_universe_domain_matches_GDU(self): @CrossSync.pytest async def test_credential_universe_domain_matches_GDU(self): """Test with credentials""" - creds = AnonymousCredentials() - creds._universe_domain = "googleapis.com" + creds = _StubCredentials("googleapis.com") async with self._make_client(project="project_id", credentials=creds) as client: assert client.universe_domain == "googleapis.com" @@ -1318,13 +1344,9 @@ async def test_configured_universe_domain_mismatched_credentials(self): """Test that configured universe domain errors with mismatched universe domain credentials. """ - creds = AnonymousCredentials() - universe_exists = hasattr(creds, "universe_domain") - if not universe_exists: - pytest.skip("Skip test for older versions of google-auth") universe_domain = "test-universe.test" options = client_options.ClientOptions(universe_domain=universe_domain) - creds._universe_domain = "different-universe" + creds = _StubCredentials("different-universe") with pytest.raises(ValueError) as exc: self._make_client( project="project_id", @@ -1342,6 +1364,103 @@ async def test_configured_universe_domain_mismatched_credentials(self): ) assert exc.value.args[0] == err_msg + @CrossSync.pytest + async def test_metrics_exporter_uses_universe_domain(self): + """BigtableMetricsExporter should stay enabled in custom universes and target monitoring.{universe_domain}.""" + import os + + universe_domain = "custom-universe.test" + creds = _StubCredentials(universe_domain) + options = client_options.ClientOptions(universe_domain=universe_domain) + async with self._make_client( + project="project_id", + credentials=creds, + client_options=options, + use_emulator=False, + use_mtls="never", + ) as client: + assert client.universe_domain == universe_domain + assert client.api_endpoint == f"bigtable.{universe_domain}" + assert len(client._metrics.handlers) == 1 + exporter = client._metrics.handlers[0]._exporter + assert exporter.client.universe_domain == universe_domain + assert exporter.client.api_endpoint == f"monitoring.{universe_domain}" + + with mock.patch.dict( + os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": universe_domain} + ): + async with self._make_client( + project="project_id", + credentials=creds, + use_emulator=False, + use_mtls="never", + ) as client: + assert client.universe_domain == universe_domain + assert client.api_endpoint == f"bigtable.{universe_domain}" + assert len(client._metrics.handlers) == 1 + exporter = client._metrics.handlers[0]._exporter + assert exporter.client.universe_domain == universe_domain + assert exporter.client.api_endpoint == f"monitoring.{universe_domain}" + + @CrossSync.pytest + async def test_metrics_exporter_disabled_with_anonymous_credentials(self): + """BigtableMetricsExporter should be disabled when AnonymousCredentials are used.""" + with ( + mock.patch( + "google.cloud.bigtable.data._async.client.BigtableMetricsExporter" + ) as exporter_mock_async, + mock.patch( + "google.cloud.bigtable.data._sync_autogen.client.BigtableMetricsExporter" + ) as exporter_mock_sync, + ): + async with self._make_client( + project="project_id", + credentials=AnonymousCredentials(), + use_emulator=False, + use_mtls="never", + ) as client: + assert len(client._metrics.handlers) == 0 + exporter_mock_async.assert_not_called() + exporter_mock_sync.assert_not_called() + + @CrossSync.pytest + async def test_metrics_exporter_disabled_with_custom_api_endpoint(self): + """BigtableMetricsExporter should be disabled when a custom api_endpoint is set.""" + universe_domain = "custom-universe.test" + cases = [ + ( + _StubCredentials(), + client_options.ClientOptions(api_endpoint="bigtable.custom.local:443"), + ), + ( + _StubCredentials(universe_domain), + client_options.ClientOptions( + api_endpoint="bigtable.custom.local:443", + universe_domain=universe_domain, + ), + ), + ] + with ( + mock.patch( + "google.cloud.bigtable.data._async.client.BigtableMetricsExporter" + ) as exporter_mock_async, + mock.patch( + "google.cloud.bigtable.data._sync_autogen.client.BigtableMetricsExporter" + ) as exporter_mock_sync, + ): + for creds, options in cases: + async with self._make_client( + project="project_id", + credentials=creds, + client_options=options, + use_emulator=False, + use_mtls="never", + ) as client: + assert client.api_endpoint == "bigtable.custom.local:443" + assert len(client._metrics.handlers) == 0 + exporter_mock_async.assert_not_called() + exporter_mock_sync.assert_not_called() + @CrossSync.pytest async def test_configured_universe_domain_matches_credentials(self): """Test that configured universe domain succeeds with matching universe @@ -1349,8 +1468,7 @@ async def test_configured_universe_domain_matches_credentials(self): """ universe_domain = "test-universe.test" options = client_options.ClientOptions(universe_domain=universe_domain) - creds = AnonymousCredentials() - creds._universe_domain = universe_domain + creds = _StubCredentials(universe_domain) async with self._make_client( project="project_id", credentials=creds, @@ -1360,6 +1478,80 @@ async def test_configured_universe_domain_matches_credentials(self): assert client.universe_domain == universe_domain assert client.api_endpoint == f"bigtable.{universe_domain}" + @CrossSync.pytest + async def test_adc_credentials_universe_mismatch(self): + """Resolved ADC credentials must be validated against client universe_domain before opening a channel.""" + import os + + from google.api_core.universe import UniverseMismatchError + + # Case 1: TPC ADC credentials with default (GDU) client + with ( + mock.patch( + "google.auth.default", + return_value=(_StubCredentials("tpc.test"), "project_id"), + ), + mock.patch.object(CrossSync.GapicClient, "__init__") as gapic_init, + ): + with pytest.raises(UniverseMismatchError): + self._make_client( + project="project_id", + credentials=None, + use_emulator=False, + use_mtls="never", + ) + gapic_init.assert_not_called() + + # Case 2: GDU ADC credentials with GOOGLE_CLOUD_UNIVERSE_DOMAIN="tpc.test" + with ( + mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "tpc.test"}), + mock.patch( + "google.auth.default", + return_value=(_StubCredentials("googleapis.com"), "project_id"), + ), + mock.patch.object(CrossSync.GapicClient, "__init__") as gapic_init, + ): + with pytest.raises(UniverseMismatchError): + self._make_client( + project="project_id", + credentials=None, + use_emulator=False, + use_mtls="never", + ) + gapic_init.assert_not_called() + + @CrossSync.pytest + async def test_anonymous_credentials_allowed_in_custom_universe(self): + """AnonymousCredentials should be exempted from universe validation in custom universes.""" + universe_domain = "tpc.test" + options = client_options.ClientOptions(universe_domain=universe_domain) + async with self._make_client( + project="project_id", + credentials=AnonymousCredentials(), + client_options=options, + use_emulator=False, + use_mtls="never", + ) as client: + assert client.universe_domain == universe_domain + assert len(client._metrics.handlers) == 0 + + @CrossSync.pytest + async def test_uncached_compute_engine_credentials_skip_validation(self): + """Uncached compute_engine.Credentials should not trigger synchronous MDS requests.""" + from google.auth import compute_engine + + creds = compute_engine.Credentials() + options = client_options.ClientOptions(universe_domain="tpc.test") + async with self._make_client( + project="project_id", + credentials=creds, + client_options=options, + use_emulator=False, + use_mtls="never", + ) as client: + assert client.universe_domain == "tpc.test" + assert not getattr(creds, "_universe_domain_cached", False) + @CrossSync.convert_class("TestTable", add_mapping_for_name="TestTable") class TestTableAsync: diff --git a/packages/google-cloud-bigtable/tests/unit/data/_sync_autogen/test_client.py b/packages/google-cloud-bigtable/tests/unit/data/_sync_autogen/test_client.py index 76910fea8852..9f04fa02b754 100644 --- a/packages/google-cloud-bigtable/tests/unit/data/_sync_autogen/test_client.py +++ b/packages/google-cloud-bigtable/tests/unit/data/_sync_autogen/test_client.py @@ -25,6 +25,7 @@ from google.api_core import client_options, grpc_helpers from google.api_core import exceptions as core_exceptions from google.auth.credentials import AnonymousCredentials +from google.oauth2 import credentials as oauth2_credentials from google.cloud.bigtable.data import TABLE_DEFAULT, mutations from google.cloud.bigtable.data._cross_sync import CrossSync @@ -82,6 +83,19 @@ def mock_metrics_batch_write(): yield +class _StubCredentials(oauth2_credentials.Credentials): + """Non-anonymous credential stub with a read-only ``universe_domain`` + property across all supported ``google-auth`` versions.""" + + def __init__(self, universe_domain: str = "googleapis.com"): + super().__init__("token") + self._test_universe_domain = universe_domain + + @property + def universe_domain(self) -> str: + return self._test_universe_domain + + @CrossSync._Sync_Impl.add_mapping_decorator("TestBigtableDataClient") class TestBigtableDataClient: @staticmethod @@ -99,7 +113,7 @@ def _make_client(cls, *args, use_emulator=True, use_mtls="auto", **kwargs): warnings.filterwarnings("ignore", category=RuntimeWarning) else: - kwargs["credentials"] = kwargs.get("credentials", AnonymousCredentials()) + kwargs["credentials"] = kwargs.get("credentials", _StubCredentials()) kwargs["project"] = kwargs.get("project", "project-id") if use_mtls is not None: env_mask["GOOGLE_API_USE_MTLS_ENDPOINT"] = use_mtls @@ -114,7 +128,7 @@ def test_ctor(self): ) expected_project = "project-id" - expected_credentials = AnonymousCredentials() + expected_credentials = _StubCredentials() client = self._make_client( project="project-id", credentials=expected_credentials, use_emulator=False ) @@ -250,23 +264,37 @@ def test_ctor_dict_options(self): def test_metrics_exporter_init_shares_arguments( self, exporter_mock_sync, exporter_mock_async ): - expected_credentials = AnonymousCredentials() + import os + + expected_credentials = _StubCredentials() expected_project = "custom_project" - expected_options = client_options.ClientOptions() - expected_options.credentials_file = None - expected_options.quota_project_id = None + cert_source = mock.Mock() + input_options = client_options.ClientOptions( + client_cert_source=cert_source, + api_audience="https://bigtable.googleapis.com/", + ) mock_called = ( exporter_mock_async if CrossSync._Sync_Impl.is_async else exporter_mock_sync ) - with self._make_client( - project=expected_project, - credentials=expected_credentials, - client_options=expected_options, - use_emulator=False, + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"} ): - mock_called.assert_called_once_with( - credentials=expected_credentials, client_options=expected_options - ) + with self._make_client( + project=expected_project, + credentials=expected_credentials, + client_options=input_options, + use_emulator=False, + ) as client: + mock_called.assert_called_once() + call_kwargs = mock_called.call_args.kwargs + assert call_kwargs["credentials"] == client._credentials + exporter_options = call_kwargs["client_options"] + assert isinstance(exporter_options, client_options.ClientOptions) + assert exporter_options is not input_options + assert exporter_options.universe_domain == "googleapis.com" + assert exporter_options.client_cert_source is cert_source + assert exporter_options.api_endpoint is None + assert exporter_options.api_audience is None @mock.patch( "google.cloud.bigtable.data._async.client.BigtableMetricsExporter", @@ -1081,8 +1109,7 @@ def test_configured_universe_domain_matches_GDU(self): def test_credential_universe_domain_matches_GDU(self): """Test with credentials""" - creds = AnonymousCredentials() - creds._universe_domain = "googleapis.com" + creds = _StubCredentials("googleapis.com") with self._make_client(project="project_id", credentials=creds) as client: assert client.universe_domain == "googleapis.com" @@ -1098,13 +1125,9 @@ def test_anomynous_credential_universe_domain(self): def test_configured_universe_domain_mismatched_credentials(self): """Test that configured universe domain errors with mismatched universe domain credentials.""" - creds = AnonymousCredentials() - universe_exists = hasattr(creds, "universe_domain") - if not universe_exists: - pytest.skip("Skip test for older versions of google-auth") universe_domain = "test-universe.test" options = client_options.ClientOptions(universe_domain=universe_domain) - creds._universe_domain = "different-universe" + creds = _StubCredentials("different-universe") with pytest.raises(ValueError) as exc: self._make_client( project="project_id", @@ -1116,13 +1139,105 @@ def test_configured_universe_domain_mismatched_credentials(self): err_msg = f"The configured universe domain ({universe_domain}) does not match the universe domain found in the credentials ({creds.universe_domain}). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." assert exc.value.args[0] == err_msg + def test_metrics_exporter_uses_universe_domain(self): + """BigtableMetricsExporter should stay enabled in custom universes and target monitoring.{universe_domain}.""" + import os + + universe_domain = "custom-universe.test" + creds = _StubCredentials(universe_domain) + options = client_options.ClientOptions(universe_domain=universe_domain) + with self._make_client( + project="project_id", + credentials=creds, + client_options=options, + use_emulator=False, + use_mtls="never", + ) as client: + assert client.universe_domain == universe_domain + assert client.api_endpoint == f"bigtable.{universe_domain}" + assert len(client._metrics.handlers) == 1 + exporter = client._metrics.handlers[0]._exporter + assert exporter.client.universe_domain == universe_domain + assert exporter.client.api_endpoint == f"monitoring.{universe_domain}" + with mock.patch.dict( + os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": universe_domain} + ): + with self._make_client( + project="project_id", + credentials=creds, + use_emulator=False, + use_mtls="never", + ) as client: + assert client.universe_domain == universe_domain + assert client.api_endpoint == f"bigtable.{universe_domain}" + assert len(client._metrics.handlers) == 1 + exporter = client._metrics.handlers[0]._exporter + assert exporter.client.universe_domain == universe_domain + assert exporter.client.api_endpoint == f"monitoring.{universe_domain}" + + def test_metrics_exporter_disabled_with_anonymous_credentials(self): + """BigtableMetricsExporter should be disabled when AnonymousCredentials are used.""" + with ( + mock.patch( + "google.cloud.bigtable.data._async.client.BigtableMetricsExporter" + ) as exporter_mock_async, + mock.patch( + "google.cloud.bigtable.data._sync_autogen.client.BigtableMetricsExporter" + ) as exporter_mock_sync, + ): + with self._make_client( + project="project_id", + credentials=AnonymousCredentials(), + use_emulator=False, + use_mtls="never", + ) as client: + assert len(client._metrics.handlers) == 0 + exporter_mock_async.assert_not_called() + exporter_mock_sync.assert_not_called() + + def test_metrics_exporter_disabled_with_custom_api_endpoint(self): + """BigtableMetricsExporter should be disabled when a custom api_endpoint is set.""" + universe_domain = "custom-universe.test" + cases = [ + ( + _StubCredentials(), + client_options.ClientOptions(api_endpoint="bigtable.custom.local:443"), + ), + ( + _StubCredentials(universe_domain), + client_options.ClientOptions( + api_endpoint="bigtable.custom.local:443", + universe_domain=universe_domain, + ), + ), + ] + with ( + mock.patch( + "google.cloud.bigtable.data._async.client.BigtableMetricsExporter" + ) as exporter_mock_async, + mock.patch( + "google.cloud.bigtable.data._sync_autogen.client.BigtableMetricsExporter" + ) as exporter_mock_sync, + ): + for creds, options in cases: + with self._make_client( + project="project_id", + credentials=creds, + client_options=options, + use_emulator=False, + use_mtls="never", + ) as client: + assert client.api_endpoint == "bigtable.custom.local:443" + assert len(client._metrics.handlers) == 0 + exporter_mock_async.assert_not_called() + exporter_mock_sync.assert_not_called() + def test_configured_universe_domain_matches_credentials(self): """Test that configured universe domain succeeds with matching universe domain credentials.""" universe_domain = "test-universe.test" options = client_options.ClientOptions(universe_domain=universe_domain) - creds = AnonymousCredentials() - creds._universe_domain = universe_domain + creds = _StubCredentials(universe_domain) with self._make_client( project="project_id", credentials=creds, @@ -1132,6 +1247,78 @@ def test_configured_universe_domain_matches_credentials(self): assert client.universe_domain == universe_domain assert client.api_endpoint == f"bigtable.{universe_domain}" + def test_adc_credentials_universe_mismatch(self): + """Resolved ADC credentials must be validated against client universe_domain before opening a channel.""" + import os + + from google.api_core.universe import UniverseMismatchError + + with ( + mock.patch( + "google.auth.default", + return_value=(_StubCredentials("tpc.test"), "project_id"), + ), + mock.patch.object( + CrossSync._Sync_Impl.GapicClient, "__init__" + ) as gapic_init, + ): + with pytest.raises(UniverseMismatchError): + self._make_client( + project="project_id", + credentials=None, + use_emulator=False, + use_mtls="never", + ) + gapic_init.assert_not_called() + with ( + mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "tpc.test"}), + mock.patch( + "google.auth.default", + return_value=(_StubCredentials("googleapis.com"), "project_id"), + ), + mock.patch.object( + CrossSync._Sync_Impl.GapicClient, "__init__" + ) as gapic_init, + ): + with pytest.raises(UniverseMismatchError): + self._make_client( + project="project_id", + credentials=None, + use_emulator=False, + use_mtls="never", + ) + gapic_init.assert_not_called() + + def test_anonymous_credentials_allowed_in_custom_universe(self): + """AnonymousCredentials should be exempted from universe validation in custom universes.""" + universe_domain = "tpc.test" + options = client_options.ClientOptions(universe_domain=universe_domain) + with self._make_client( + project="project_id", + credentials=AnonymousCredentials(), + client_options=options, + use_emulator=False, + use_mtls="never", + ) as client: + assert client.universe_domain == universe_domain + assert len(client._metrics.handlers) == 0 + + def test_uncached_compute_engine_credentials_skip_validation(self): + """Uncached compute_engine.Credentials should not trigger synchronous MDS requests.""" + from google.auth import compute_engine + + creds = compute_engine.Credentials() + options = client_options.ClientOptions(universe_domain="tpc.test") + with self._make_client( + project="project_id", + credentials=creds, + client_options=options, + use_emulator=False, + use_mtls="never", + ) as client: + assert client.universe_domain == "tpc.test" + assert not getattr(creds, "_universe_domain_cached", False) + @CrossSync._Sync_Impl.add_mapping_decorator("TestTable") class TestTable: @@ -2788,10 +2975,7 @@ def test_mutate_row_attempt_timeout_per_retry(self): ] mutation = mutations.DeleteAllFromRow() table.mutate_row( - "row_key", - mutation, - operation_timeout=10.0, - attempt_timeout=5.0, + "row_key", mutation, operation_timeout=10.0, attempt_timeout=5.0 ) mock_timeout_gen.assert_called_once_with(5.0, 10.0) assert mock_gapic.call_count == 2 diff --git a/packages/google-cloud-bigtable/tests/unit/data/test__helpers.py b/packages/google-cloud-bigtable/tests/unit/data/test__helpers.py index 418fe4e28c16..db53858c5503 100644 --- a/packages/google-cloud-bigtable/tests/unit/data/test__helpers.py +++ b/packages/google-cloud-bigtable/tests/unit/data/test__helpers.py @@ -576,3 +576,41 @@ def test_set_next_replacement(self, mock_uniform): generator.set_next(88) assert next(generator) == 88 assert next(generator) == 1 + + +class TestValidateCredentialsUniverse: + def test_exempts_none_and_anonymous(self): + from google.auth.credentials import AnonymousCredentials + + assert _helpers._validate_credentials_universe("googleapis.com", None) is None + assert _helpers._validate_credentials_universe("tpc.test", None) is None + assert ( + _helpers._validate_credentials_universe("tpc.test", AnonymousCredentials()) + is None + ) + + def test_exempts_uncached_compute_engine_credentials(self): + from google.auth import compute_engine + + creds = compute_engine.Credentials() + assert _helpers._validate_credentials_universe("tpc.test", creds) is None + assert not getattr(creds, "_universe_domain_cached", False) + + def test_validates_cached_compute_engine_credentials(self): + from google.api_core.universe import UniverseMismatchError + from google.auth import compute_engine + + class _CachedGCECredentials(compute_engine.Credentials): + @property + def universe_domain(self): + return "tpc.test" + + creds = _CachedGCECredentials() + creds._universe_domain_cached = True + assert _helpers._validate_credentials_universe("tpc.test", creds) is None + with pytest.raises(UniverseMismatchError): + _helpers._validate_credentials_universe("googleapis.com", creds) + + def test_exempts_non_string_universe_attribute(self): + creds = mock.Mock() + assert _helpers._validate_credentials_universe("tpc.test", creds) is None diff --git a/packages/google-cloud-bigtable/tests/unit/v2_client/_testing.py b/packages/google-cloud-bigtable/tests/unit/v2_client/_testing.py index e3da99269c9a..b5c7f25dad3f 100644 --- a/packages/google-cloud-bigtable/tests/unit/v2_client/_testing.py +++ b/packages/google-cloud-bigtable/tests/unit/v2_client/_testing.py @@ -25,7 +25,7 @@ def __init__(self, *results): self.method_calls = [] -def _make_credentials(): +def _make_credentials(universe_domain=None): import google.auth.credentials from google.cloud.bigtable_v2 import BigtableClient @@ -41,7 +41,11 @@ class _CredentialsWithScopesAndQuotaProject( # Needed to mock universe domain and quota project for new data client tests credentials_with_scopes = mock.Mock(spec=_CredentialsWithScopesAndQuotaProject) - credentials_with_scopes.universe_domain = BigtableClient._DEFAULT_UNIVERSE + credentials_with_scopes.universe_domain = ( + universe_domain + if universe_domain is not None + else BigtableClient._DEFAULT_UNIVERSE + ) credentials_with_scopes.with_quota_project.return_value = credentials_with_scopes credentials.with_scopes.return_value = credentials_with_scopes diff --git a/packages/google-cloud-bigtable/tests/unit/v2_client/test_client.py b/packages/google-cloud-bigtable/tests/unit/v2_client/test_client.py index 611fce696b3b..a80d6ec562f0 100644 --- a/packages/google-cloud-bigtable/tests/unit/v2_client/test_client.py +++ b/packages/google-cloud-bigtable/tests/unit/v2_client/test_client.py @@ -15,6 +15,7 @@ import mock import pytest +from google.api_core.client_options import ClientOptions from ._testing import _make_credentials @@ -321,7 +322,7 @@ def _create_gapic_client_channel_helper(endpoint=None, emulator_host=None): client = _make_client(project=PROJECT, credentials=credentials) if endpoint is not None: - client._client_options = mock.Mock( + client._admin_client_options = mock.Mock( spec=["api_endpoint"], api_endpoint=endpoint, ) @@ -381,6 +382,326 @@ def test_client__create_gapic_client_channel_w_endpoint_w_emulator_host(): _create_gapic_client_channel_helper(endpoint=endpoint, emulator_host=host) +@pytest.mark.parametrize( + "client_options,admin_client_options,env_universe,expected_host,expected_universe", + [ + (None, None, None, "bigtableadmin.googleapis.com:443", "googleapis.com"), + # universe_domain via client_options or admin_client_options (dict or ClientOptions) + ( + {"universe_domain": "tpc.test"}, + None, + None, + "bigtableadmin.tpc.test:443", + "tpc.test", + ), + ( + None, + {"universe_domain": "tpc.test"}, + None, + "bigtableadmin.tpc.test:443", + "tpc.test", + ), + ( + {"universe_domain": "tpc.test"}, + {"universe_domain": "other.test"}, + None, + "bigtableadmin.other.test:443", + "other.test", + ), + # GOOGLE_CLOUD_UNIVERSE_DOMAIN used when no option sets universe_domain + (None, None, "tpc.test", "bigtableadmin.tpc.test:443", "tpc.test"), + ( + {"universe_domain": "tpc.test"}, + None, + "other.test", + "bigtableadmin.tpc.test:443", + "tpc.test", + ), + ( + None, + {"universe_domain": "tpc.test"}, + "other.test", + "bigtableadmin.tpc.test:443", + "tpc.test", + ), + ( + {"universe_domain": "googleapis.com"}, + None, + "tpc.test", + "bigtableadmin.googleapis.com:443", + "googleapis.com", + ), + ( + None, + {"universe_domain": "googleapis.com"}, + "tpc.test", + "bigtableadmin.googleapis.com:443", + "googleapis.com", + ), + # explicit api_endpoint takes precedence over universe_domain within the same tier, + # while admin_client_options takes precedence over client_options + ( + {"api_endpoint": "custom.test:443"}, + None, + None, + "custom.test:443", + "googleapis.com", + ), + ( + {"api_endpoint": "custom.test:443", "universe_domain": "tpc.test"}, + None, + None, + "custom.test:443", + "tpc.test", + ), + ( + {"api_endpoint": "custom.test:443"}, + None, + "tpc.test", + "custom.test:443", + "tpc.test", + ), + ( + {"api_endpoint": "custom.test:443"}, + {"api_endpoint": "admin.custom.test:443"}, + None, + "admin.custom.test:443", + "googleapis.com", + ), + ( + {"universe_domain": "tpc.test"}, + {"api_endpoint": "admin.custom.test:443"}, + None, + "admin.custom.test:443", + "tpc.test", + ), + ( + {"api_endpoint": "data.custom.test:443"}, + {"universe_domain": "tpc.test"}, + None, + "bigtableadmin.tpc.test:443", + "tpc.test", + ), + ( + {"api_endpoint": "data.custom.test:443"}, + {"universe_domain": "googleapis.com"}, + None, + "bigtableadmin.googleapis.com:443", + "googleapis.com", + ), + ], +) +def test_client_admin_clients_endpoint( + client_options, admin_client_options, env_universe, expected_host, expected_universe +): + import os + + from google.api_core.client_options import from_dict + + for as_client_options in (False, True): + co = ( + from_dict(client_options) + if (as_client_options and client_options) + else client_options + ) + aco = ( + from_dict(admin_client_options) + if (as_client_options and admin_client_options) + else admin_client_options + ) + with mock.patch.dict(os.environ, {}, clear=False): + if env_universe is None: + os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) + else: + os.environ["GOOGLE_CLOUD_UNIVERSE_DOMAIN"] = env_universe + client = _make_client( + project=PROJECT, + credentials=_make_credentials(universe_domain=expected_universe), + admin=True, + client_options=co, + admin_client_options=aco, + ) + for admin_client in ( + client.table_admin_client, + client.instance_admin_client, + ): + assert admin_client.transport.host == expected_host + assert admin_client.api_endpoint == expected_host + assert admin_client.universe_domain == expected_universe + + +@pytest.mark.parametrize( + "admin_client_options", + [ + {"api_endpoint": "admin.custom.test:443"}, + ClientOptions(api_endpoint="admin.custom.test:443"), + ], +) +def test_client_admin_clients_inherit_universe_wo_mutating_options( + admin_client_options, +): + client = _make_client( + project=PROJECT, + credentials=_make_credentials(universe_domain="tpc.test"), + admin=True, + client_options={"universe_domain": "tpc.test"}, + admin_client_options=admin_client_options, + ) + assert client.table_admin_client.universe_domain == "tpc.test" + assert client.instance_admin_client.universe_domain == "tpc.test" + # the options object passed in by the caller is left untouched + if isinstance(admin_client_options, dict): + assert admin_client_options == {"api_endpoint": "admin.custom.test:443"} + else: + assert admin_client_options.universe_domain is None + + +@pytest.mark.parametrize( + "admin_client_options", + [ + None, + {"quota_project_id": "QUOTA-PROJECT"}, + ClientOptions(quota_project_id="QUOTA-PROJECT"), + ], +) +def test_client_admin_client_options_unchanged_wo_inherited_settings( + admin_client_options, +): + import os + + with mock.patch.dict(os.environ, {}, clear=False): + os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) + client = _make_client( + project=PROJECT, + credentials=_make_credentials(), + admin=True, + admin_client_options=admin_client_options, + ) + + # no universe or endpoint is configured anywhere, so the admin clients get + # the options as given and apply their own defaults + assert client._admin_client_options is admin_client_options + + +@pytest.mark.parametrize( + "env_at_construction,env_at_first_use,expected_universe", + [ + # set after the client is constructed: not used + (None, "tpc.test", "googleapis.com"), + # removed after the client is constructed: still used + ("tpc.test", None, "tpc.test"), + # changed after the client is constructed: the original value is used + ("tpc.test", "other.test", "tpc.test"), + ], +) +def test_client_admin_clients_universe_env_read_at_construction( + env_at_construction, env_at_first_use, expected_universe +): + import os + + def set_env(value): + if value is None: + os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) + else: + os.environ["GOOGLE_CLOUD_UNIVERSE_DOMAIN"] = value + + with mock.patch.dict(os.environ, {}, clear=False): + set_env(env_at_construction) + client = _make_client( + project=PROJECT, + credentials=_make_credentials(universe_domain=expected_universe), + admin=True, + ) + set_env(env_at_first_use) + + expected_host = f"bigtableadmin.{expected_universe}:443" + assert client.table_admin_client.transport.host == expected_host + assert client.instance_admin_client.transport.host == expected_host + + +@pytest.mark.parametrize( + "client_options,admin_client_options,env_universe", + [ + ({"universe_domain": ""}, None, None), + (None, {"universe_domain": ""}, None), + (None, None, ""), + ({"universe_domain": "", "api_endpoint": "custom.test:443"}, None, None), + (None, {"universe_domain": "", "api_endpoint": "admin.custom.test:443"}, None), + ({"api_endpoint": "custom.test:443"}, None, ""), + ], +) +def test_client_admin_clients_w_empty_universe_domain( + client_options, admin_client_options, env_universe +): + import os + + from google.api_core.universe import EmptyUniverseError + + with mock.patch.dict(os.environ, {}, clear=False): + if env_universe is None: + os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) + else: + os.environ["GOOGLE_CLOUD_UNIVERSE_DOMAIN"] = env_universe + client = _make_client( + project=PROJECT, + credentials=_make_credentials(), + admin=True, + client_options=client_options, + admin_client_options=admin_client_options, + ) + with pytest.raises(EmptyUniverseError): + _ = client.table_admin_client + with pytest.raises(EmptyUniverseError): + _ = client.instance_admin_client + + +@pytest.mark.parametrize( + "cred_universe,client_options,admin_client_options,env_universe", + [ + ("tpc.test", None, None, None), + ("googleapis.com", {"universe_domain": "tpc.test"}, None, None), + ("googleapis.com", None, {"universe_domain": "tpc.test"}, None), + ("googleapis.com", None, None, "tpc.test"), + ], +) +def test_client_admin_clients_mismatched_credentials_universe( + cred_universe, client_options, admin_client_options, env_universe +): + import os + + from google.api_core.universe import UniverseMismatchError + + with mock.patch.dict(os.environ, {}, clear=False): + if env_universe is None: + os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) + else: + os.environ["GOOGLE_CLOUD_UNIVERSE_DOMAIN"] = env_universe + client = _make_client( + project=PROJECT, + credentials=_make_credentials(universe_domain=cred_universe), + admin=True, + client_options=client_options, + admin_client_options=admin_client_options, + ) + with pytest.raises(UniverseMismatchError): + _ = client.table_admin_client + with pytest.raises(UniverseMismatchError): + _ = client.instance_admin_client + + +def test_client_admin_clients_anonymous_credentials_in_custom_universe(): + from google.auth.credentials import AnonymousCredentials + + client = _make_client( + project=PROJECT, + credentials=AnonymousCredentials(), + admin=True, + client_options={"universe_domain": "tpc.test"}, + ) + assert client.table_admin_client.transport.host == "bigtableadmin.tpc.test:443" + assert client.instance_admin_client.transport.host == "bigtableadmin.tpc.test:443" + + def test_client_project_path(): credentials = _make_credentials() project = "PROJECT"