From b98170c0f03fd9749ed002ec26c586fe60cf720e Mon Sep 17 00:00:00 2001 From: Daniel Sanche Date: Sat, 21 Nov 2026 17:03:20 -0700 Subject: [PATCH 1/9] disable client side metrics outside default universe --- .../cloud/bigtable/data/_async/client.py | 8 ++- .../bigtable/data/_sync_autogen/client.py | 8 ++- .../tests/unit/data/_async/test_client.py | 69 +++++++++++++++++++ .../unit/data/_sync_autogen/test_client.py | 66 ++++++++++++++++++ 4 files changed, 149 insertions(+), 2 deletions(-) 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..bfa006ca7506 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, @@ -282,7 +283,12 @@ def __init__( 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 self.universe_domain == universe.DEFAULT_UNIVERSE + and not has_custom_endpoint + ): try: # create a metrics exporter using the same client configuration exporter = BigtableMetricsExporter( 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..2d3d74aa6a32 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, @@ -208,7 +209,12 @@ def __init__( 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 self.universe_domain == universe.DEFAULT_UNIVERSE + and (not has_custom_endpoint) + ): try: exporter = BigtableMetricsExporter( credentials=self._credentials, client_options=client_options 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..3695f1c85485 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 @@ -1342,6 +1342,75 @@ async def test_configured_universe_domain_mismatched_credentials(self): ) assert exc.value.args[0] == err_msg + @CrossSync.pytest + async def test_metrics_exporter_disabled_outside_gdu(self): + """BigtableMetricsExporter should be disabled when universe_domain != googleapis.com.""" + import os + + universe_domain = "custom-universe.test" + creds = AnonymousCredentials() + creds._universe_domain = universe_domain + options = client_options.ClientOptions(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, + ): + 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) == 0 + exporter_mock_async.assert_not_called() + exporter_mock_sync.assert_not_called() + + 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) == 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.""" + options = client_options.ClientOptions(api_endpoint="bigtable.custom.local:443") + 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(), + 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 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..dcca7366cd0e 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 @@ -1116,6 +1116,72 @@ 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_disabled_outside_gdu(self): + """BigtableMetricsExporter should be disabled when universe_domain != googleapis.com.""" + import os + + universe_domain = "custom-universe.test" + creds = AnonymousCredentials() + creds._universe_domain = universe_domain + options = client_options.ClientOptions(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, + ): + 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) == 0 + exporter_mock_async.assert_not_called() + exporter_mock_sync.assert_not_called() + 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) == 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.""" + options = client_options.ClientOptions(api_endpoint="bigtable.custom.local:443") + 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(), + 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.""" From 2a81ac7b9e80224c5af5737f5d68628e3f99c83c Mon Sep 17 00:00:00 2001 From: Daniel Sanche Date: Mon, 23 Nov 2026 20:24:27 -0700 Subject: [PATCH 2/9] use universe_domain in legacy client --- .../google/cloud/bigtable/client.py | 61 ++++++- .../tests/unit/v2_client/test_client.py | 152 ++++++++++++++++++ 2 files changed, 209 insertions(+), 4 deletions(-) diff --git a/packages/google-cloud-bigtable/google/cloud/bigtable/client.py b/packages/google-cloud-bigtable/google/cloud/bigtable/client.py index 602997d000a4..d31ca950d413 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 @@ -82,6 +83,13 @@ 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) + + class Client(ClientWithProject): """Client for interacting with Google Cloud Bigtable API. @@ -121,12 +129,16 @@ class Client(ClientWithProject): 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. + ``api_endpoint`` and ``universe_domain`` also apply to admin + operations, unless ``admin_client_options`` sets either one. :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. + through admin_client_options. If neither ``api_endpoint`` nor + ``universe_domain`` is set, admin operations fall back to the values + from ``client_options``. :type channel: :instance: grpc.Channel :param channel (grpc.Channel): (Optional) DEPRECATED: @@ -225,13 +237,54 @@ 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. + + Precedence order: + 1. ``admin_client_options.api_endpoint`` + 2. ``admin_client_options.universe_domain`` + 3. ``client_options.api_endpoint`` + 4. ``client_options.universe_domain`` + 5. ``GOOGLE_CLOUD_UNIVERSE_DOMAIN`` environment variable + 6. ``client_class.DEFAULT_ENDPOINT`` (``googleapis.com``) + + Within the same options object (or against the environment variable), + 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. + """ + admin_universe = _get_client_option( + self._admin_client_options, "universe_domain" + ) + client_universe = _get_client_option(self._client_options, "universe_domain") + configured_universe = ( + admin_universe if admin_universe is not None else client_universe + ) + universe_domain = universe.determine_domain( + configured_universe, os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + ) + + admin_endpoint = _get_client_option(self._admin_client_options, "api_endpoint") + if admin_endpoint: + return admin_endpoint + + if admin_universe is None: + client_endpoint = _get_client_option(self._client_options, "api_endpoint") + if client_endpoint: + return client_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/tests/unit/v2_client/test_client.py b/packages/google-cloud-bigtable/tests/unit/v2_client/test_client.py index 611fce696b3b..0bf66ed80b56 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 @@ -381,6 +381,158 @@ 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", + [ + (None, None, None, "bigtableadmin.googleapis.com:443"), + # universe_domain via client_options or admin_client_options (dict or ClientOptions) + ({"universe_domain": "tpc.test"}, None, None, "bigtableadmin.tpc.test:443"), + (None, {"universe_domain": "tpc.test"}, None, "bigtableadmin.tpc.test:443"), + ( + {"universe_domain": "tpc.test"}, + {"universe_domain": "other.test"}, + None, + "bigtableadmin.other.test:443", + ), + # GOOGLE_CLOUD_UNIVERSE_DOMAIN used when no option sets universe_domain + (None, None, "tpc.test", "bigtableadmin.tpc.test:443"), + ( + {"universe_domain": "tpc.test"}, + None, + "other.test", + "bigtableadmin.tpc.test:443", + ), + ( + None, + {"universe_domain": "tpc.test"}, + "other.test", + "bigtableadmin.tpc.test:443", + ), + # 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"), + ( + {"api_endpoint": "custom.test:443", "universe_domain": "tpc.test"}, + None, + None, + "custom.test:443", + ), + ({"api_endpoint": "custom.test:443"}, None, "tpc.test", "custom.test:443"), + ( + {"api_endpoint": "custom.test:443"}, + {"api_endpoint": "admin.custom.test:443"}, + None, + "admin.custom.test:443", + ), + ( + {"universe_domain": "tpc.test"}, + {"api_endpoint": "admin.custom.test:443"}, + None, + "admin.custom.test:443", + ), + ( + {"api_endpoint": "data.custom.test:443"}, + {"universe_domain": "tpc.test"}, + None, + "bigtableadmin.tpc.test:443", + ), + ( + {"api_endpoint": "data.custom.test:443"}, + {"universe_domain": "googleapis.com"}, + None, + "bigtableadmin.googleapis.com:443", + ), + ], +) +def test_client_admin_clients_endpoint( + client_options, admin_client_options, env_universe, expected_host +): + 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(), + 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 + + +def test_client_admin_clients_w_universe_env_set_after_construction(): + 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 + ) + os.environ["GOOGLE_CLOUD_UNIVERSE_DOMAIN"] = "tpc.test" + + expected_host = "bigtableadmin.tpc.test: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 + + def test_client_project_path(): credentials = _make_credentials() project = "PROJECT" From c76f12443657854e5596d7a0c9919edb44bc1933 Mon Sep 17 00:00:00 2001 From: Daniel Sanche Date: Mon, 23 Nov 2026 21:01:07 -0700 Subject: [PATCH 3/9] pass through universe into admin_client_options --- .../google/cloud/bigtable/client.py | 20 ++++- .../tests/unit/v2_client/test_client.py | 73 +++++++++++++++++-- 2 files changed, 83 insertions(+), 10 deletions(-) diff --git a/packages/google-cloud-bigtable/google/cloud/bigtable/client.py b/packages/google-cloud-bigtable/google/cloud/bigtable/client.py index d31ca950d413..d1686fc89c45 100644 --- a/packages/google-cloud-bigtable/google/cloud/bigtable/client.py +++ b/packages/google-cloud-bigtable/google/cloud/bigtable/client.py @@ -280,6 +280,22 @@ def _resolve_admin_endpoint(self, client_class): UNIVERSE_DOMAIN=universe_domain ) + def _resolve_admin_client_options(self): + """Return ``admin_client_options``, inheriting ``universe_domain`` from + ``client_options`` if unset so admin clients report the right universe.""" + admin_options = self._admin_client_options + client_universe = _get_client_option(self._client_options, "universe_domain") + if ( + not client_universe + or _get_client_option(admin_options, "universe_domain") is not None + ): + return admin_options + if admin_options is None or isinstance(admin_options, dict): + return {**(admin_options or {}), "universe_domain": client_universe} + admin_options = copy.copy(admin_options) + admin_options.universe_domain = client_universe + return admin_options + def _create_gapic_client_channel(self, client_class, grpc_transport): if self._emulator_host is not None: api_endpoint = self._emulator_host @@ -371,7 +387,7 @@ def table_admin_client(self): ) klass = _create_gapic_client( bigtable_admin_v2.BaseBigtableTableAdminClient, - client_options=self._admin_client_options, + client_options=self._resolve_admin_client_options(), transport=transport, ) self._table_admin_client = klass(self) @@ -408,7 +424,7 @@ def instance_admin_client(self): ) klass = _create_gapic_client( bigtable_admin_v2.BigtableInstanceAdminClient, - client_options=self._admin_client_options, + client_options=self._resolve_admin_client_options(), transport=transport, ) self._instance_admin_client = klass(self) 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 0bf66ed80b56..aab7740928e7 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 @@ -382,70 +382,102 @@ def test_client__create_gapic_client_channel_w_endpoint_w_emulator_host(): @pytest.mark.parametrize( - "client_options,admin_client_options,env_universe,expected_host", + "client_options,admin_client_options,env_universe,expected_host,expected_universe", [ - (None, None, None, "bigtableadmin.googleapis.com:443"), + (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"), - (None, {"universe_domain": "tpc.test"}, None, "bigtableadmin.tpc.test:443"), + ( + {"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"), + (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", ), # 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"), + ( + {"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"}, None, "tpc.test", "custom.test:443"), ( {"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 + client_options, admin_client_options, env_universe, expected_host, expected_universe ): import os @@ -480,6 +512,31 @@ def test_client_admin_clients_endpoint( ): assert admin_client.transport.host == expected_host assert admin_client.api_endpoint == expected_host + assert admin_client.universe_domain == expected_universe + + +def test_client_admin_clients_inherit_universe_wo_mutating_options(): + from google.api_core.client_options import ClientOptions + + for admin_client_options in ( + {"api_endpoint": "admin.custom.test:443"}, + ClientOptions(api_endpoint="admin.custom.test:443"), + ): + client = _make_client( + project=PROJECT, + credentials=_make_credentials(), + 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 + assert client._admin_client_options is admin_client_options + 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 def test_client_admin_clients_w_universe_env_set_after_construction(): From 6cda2e625b094e802b9b5f87879e404a4fe1d3eb Mon Sep 17 00:00:00 2001 From: Daniel Sanche Date: Mon, 23 Nov 2026 21:07:42 -0700 Subject: [PATCH 4/9] updated docstring --- .../google/cloud/bigtable/client.py | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/packages/google-cloud-bigtable/google/cloud/bigtable/client.py b/packages/google-cloud-bigtable/google/cloud/bigtable/client.py index d1686fc89c45..5dc825773cae 100644 --- a/packages/google-cloud-bigtable/google/cloud/bigtable/client.py +++ b/packages/google-cloud-bigtable/google/cloud/bigtable/client.py @@ -128,17 +128,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. - ``api_endpoint`` and ``universe_domain`` also apply to admin - operations, unless ``admin_client_options`` sets either one. + 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. If neither ``api_endpoint`` nor - ``universe_domain`` is set, admin operations fall back to the values - from ``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: From 01a4f5a46eaaa7bb8570efb054425bfb4c8ab3d3 Mon Sep 17 00:00:00 2001 From: Daniel Sanche Date: Mon, 23 Nov 2026 21:08:20 -0700 Subject: [PATCH 5/9] updated test --- .../tests/unit/v2_client/test_client.py | 44 ++++++++++--------- 1 file changed, 24 insertions(+), 20 deletions(-) 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 aab7740928e7..5901ec14877c 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 @@ -515,28 +516,31 @@ def test_client_admin_clients_endpoint( assert admin_client.universe_domain == expected_universe -def test_client_admin_clients_inherit_universe_wo_mutating_options(): - from google.api_core.client_options import ClientOptions - - for admin_client_options in ( +@pytest.mark.parametrize( + "admin_client_options", + [ {"api_endpoint": "admin.custom.test:443"}, ClientOptions(api_endpoint="admin.custom.test:443"), - ): - client = _make_client( - project=PROJECT, - credentials=_make_credentials(), - 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 - assert client._admin_client_options is admin_client_options - 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 + ], +) +def test_client_admin_clients_inherit_universe_wo_mutating_options( + admin_client_options, +): + client = _make_client( + project=PROJECT, + credentials=_make_credentials(), + 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 + assert client._admin_client_options is admin_client_options + 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 def test_client_admin_clients_w_universe_env_set_after_construction(): From 2cc35ef09a58624bb1ae41e4a13fbcbfe753f062 Mon Sep 17 00:00:00 2001 From: Daniel Sanche Date: Tue, 24 Nov 2026 16:40:07 -0700 Subject: [PATCH 6/9] improved legacy client logic --- .../google/cloud/bigtable/client.py | 107 ++++++++++-------- .../tests/unit/v2_client/test_client.py | 55 ++++++++- 2 files changed, 111 insertions(+), 51 deletions(-) diff --git a/packages/google-cloud-bigtable/google/cloud/bigtable/client.py b/packages/google-cloud-bigtable/google/cloud/bigtable/client.py index 5dc825773cae..cb5f27495604 100644 --- a/packages/google-cloud-bigtable/google/cloud/bigtable/client.py +++ b/packages/google-cloud-bigtable/google/cloud/bigtable/client.py @@ -90,6 +90,50 @@ def _get_client_option(options, 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. @@ -197,7 +241,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__( @@ -242,62 +290,29 @@ def _emulator_channel(self, transport, options): def _resolve_admin_endpoint(self, client_class): """Resolve the target host for GAPIC admin channels. - Precedence order: - 1. ``admin_client_options.api_endpoint`` - 2. ``admin_client_options.universe_domain`` - 3. ``client_options.api_endpoint`` - 4. ``client_options.universe_domain`` - 5. ``GOOGLE_CLOUD_UNIVERSE_DOMAIN`` environment variable - 6. ``client_class.DEFAULT_ENDPOINT`` (``googleapis.com``) + 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. - Within the same options object (or against the environment variable), - an explicit ``api_endpoint`` overrides ``universe_domain`` without + 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. """ - admin_universe = _get_client_option( - self._admin_client_options, "universe_domain" - ) - client_universe = _get_client_option(self._client_options, "universe_domain") - configured_universe = ( - admin_universe if admin_universe is not None else client_universe - ) universe_domain = universe.determine_domain( - configured_universe, os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + _get_client_option(self._admin_client_options, "universe_domain"), None ) - - admin_endpoint = _get_client_option(self._admin_client_options, "api_endpoint") - if admin_endpoint: - return admin_endpoint - - if admin_universe is None: - client_endpoint = _get_client_option(self._client_options, "api_endpoint") - if client_endpoint: - return client_endpoint - + 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 _resolve_admin_client_options(self): - """Return ``admin_client_options``, inheriting ``universe_domain`` from - ``client_options`` if unset so admin clients report the right universe.""" - admin_options = self._admin_client_options - client_universe = _get_client_option(self._client_options, "universe_domain") - if ( - not client_universe - or _get_client_option(admin_options, "universe_domain") is not None - ): - return admin_options - if admin_options is None or isinstance(admin_options, dict): - return {**(admin_options or {}), "universe_domain": client_universe} - admin_options = copy.copy(admin_options) - admin_options.universe_domain = client_universe - return admin_options - def _create_gapic_client_channel(self, client_class, grpc_transport): if self._emulator_host is not None: api_endpoint = self._emulator_host @@ -389,7 +404,7 @@ def table_admin_client(self): ) klass = _create_gapic_client( bigtable_admin_v2.BaseBigtableTableAdminClient, - client_options=self._resolve_admin_client_options(), + client_options=self._admin_client_options, transport=transport, ) self._table_admin_client = klass(self) @@ -426,7 +441,7 @@ def instance_admin_client(self): ) klass = _create_gapic_client( bigtable_admin_v2.BigtableInstanceAdminClient, - client_options=self._resolve_admin_client_options(), + client_options=self._admin_client_options, transport=transport, ) self._instance_admin_client = klass(self) 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 5901ec14877c..5be61e8b2c0d 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 @@ -322,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, ) @@ -536,24 +536,69 @@ def test_client_admin_clients_inherit_universe_wo_mutating_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 - assert client._admin_client_options is admin_client_options 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 -def test_client_admin_clients_w_universe_env_set_after_construction(): +@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(), admin=True ) - os.environ["GOOGLE_CLOUD_UNIVERSE_DOMAIN"] = "tpc.test" + set_env(env_at_first_use) - expected_host = "bigtableadmin.tpc.test:443" + 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 From b3a756c1b00682592da13f7d49d00ea963636aa9 Mon Sep 17 00:00:00 2001 From: Daniel Sanche Date: Wed, 25 Nov 2026 10:15:16 -0700 Subject: [PATCH 7/9] re-enable csm --- .../cloud/bigtable/data/_async/client.py | 18 ++- .../bigtable/data/_sync_autogen/client.py | 19 ++- .../tests/unit/data/_async/test_client.py | 143 +++++++++++------ .../unit/data/_sync_autogen/test_client.py | 146 ++++++++++++------ 4 files changed, 217 insertions(+), 109 deletions(-) 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 bfa006ca7506..0e470a46e33d 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,7 +38,6 @@ 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, @@ -286,14 +285,25 @@ def __init__( has_custom_endpoint = bool(client_options and client_options.api_endpoint) if ( self._emulator_host is None - and self.universe_domain == universe.DEFAULT_UNIVERSE + 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/_sync_autogen/client.py b/packages/google-cloud-bigtable/google/cloud/bigtable/data/_sync_autogen/client.py index 2d3d74aa6a32..435c65969788 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,7 +32,6 @@ 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, @@ -212,12 +211,22 @@ def __init__( has_custom_endpoint = bool(client_options and client_options.api_endpoint) if ( self._emulator_host is None - and self.universe_domain == universe.DEFAULT_UNIVERSE + 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( @@ -1430,9 +1439,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 3695f1c85485..fc27451e60be 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 @@ -126,7 +127,9 @@ 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", oauth2_credentials.Credentials("token") + ) kwargs["project"] = kwargs.get("project", "project-id") if use_mtls is not None: env_mask["GOOGLE_API_USE_MTLS_ENDPOINT"] = use_mtls @@ -142,7 +145,7 @@ async def test_ctor(self): ) expected_project = "project-id" - expected_credentials = AnonymousCredentials() + expected_credentials = oauth2_credentials.Credentials("token") client = self._make_client( project="project-id", credentials=expected_credentials, @@ -289,22 +292,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 = oauth2_credentials.Credentials("token") 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( @@ -1343,54 +1359,47 @@ async def test_configured_universe_domain_mismatched_credentials(self): assert exc.value.args[0] == err_msg @CrossSync.pytest - async def test_metrics_exporter_disabled_outside_gdu(self): - """BigtableMetricsExporter should be disabled when universe_domain != googleapis.com.""" + 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 = AnonymousCredentials() + creds = oauth2_credentials.Credentials("token") creds._universe_domain = universe_domain options = client_options.ClientOptions(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, + 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, - 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) == 0 - exporter_mock_async.assert_not_called() - exporter_mock_sync.assert_not_called() - - 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) == 0 - exporter_mock_async.assert_not_called() - exporter_mock_sync.assert_not_called() + 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_custom_api_endpoint(self): - """BigtableMetricsExporter should be disabled when a custom api_endpoint is set.""" - options = client_options.ClientOptions(api_endpoint="bigtable.custom.local:443") + 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" @@ -1402,15 +1411,53 @@ async def test_metrics_exporter_disabled_with_custom_api_endpoint(self): async with self._make_client( project="project_id", credentials=AnonymousCredentials(), - 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_metrics_exporter_disabled_with_custom_api_endpoint(self): + """BigtableMetricsExporter should be disabled when a custom api_endpoint is set.""" + universe_domain = "custom-universe.test" + tpc_creds = oauth2_credentials.Credentials("token") + tpc_creds._universe_domain = universe_domain + cases = [ + ( + oauth2_credentials.Credentials("token"), + client_options.ClientOptions(api_endpoint="bigtable.custom.local:443"), + ), + ( + tpc_creds, + 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 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 dcca7366cd0e..db7b83c7982b 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 @@ -99,7 +100,9 @@ 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", oauth2_credentials.Credentials("token") + ) kwargs["project"] = kwargs.get("project", "project-id") if use_mtls is not None: env_mask["GOOGLE_API_USE_MTLS_ENDPOINT"] = use_mtls @@ -114,7 +117,7 @@ def test_ctor(self): ) expected_project = "project-id" - expected_credentials = AnonymousCredentials() + expected_credentials = oauth2_credentials.Credentials("token") client = self._make_client( project="project-id", credentials=expected_credentials, use_emulator=False ) @@ -250,23 +253,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 = oauth2_credentials.Credentials("token") 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", @@ -1116,52 +1133,45 @@ 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_disabled_outside_gdu(self): - """BigtableMetricsExporter should be disabled when universe_domain != googleapis.com.""" + 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 = AnonymousCredentials() + creds = oauth2_credentials.Credentials("token") creds._universe_domain = universe_domain options = client_options.ClientOptions(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, + 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, - 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) == 0 - exporter_mock_async.assert_not_called() - exporter_mock_sync.assert_not_called() - 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) == 0 - exporter_mock_async.assert_not_called() - exporter_mock_sync.assert_not_called() + 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_custom_api_endpoint(self): - """BigtableMetricsExporter should be disabled when a custom api_endpoint is set.""" - options = client_options.ClientOptions(api_endpoint="bigtable.custom.local:443") + 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" @@ -1173,15 +1183,52 @@ def test_metrics_exporter_disabled_with_custom_api_endpoint(self): with self._make_client( project="project_id", credentials=AnonymousCredentials(), - 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_metrics_exporter_disabled_with_custom_api_endpoint(self): + """BigtableMetricsExporter should be disabled when a custom api_endpoint is set.""" + universe_domain = "custom-universe.test" + tpc_creds = oauth2_credentials.Credentials("token") + tpc_creds._universe_domain = universe_domain + cases = [ + ( + oauth2_credentials.Credentials("token"), + client_options.ClientOptions(api_endpoint="bigtable.custom.local:443"), + ), + ( + tpc_creds, + 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.""" @@ -2854,10 +2901,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 From 8d9715b8a379c015b19f8409e76f4bc9beb96f94 Mon Sep 17 00:00:00 2001 From: Daniel Sanche Date: Wed, 25 Nov 2026 15:45:27 -0700 Subject: [PATCH 8/9] update tests --- .../tests/unit/data/_async/test_client.py | 42 ++++++++++--------- .../unit/data/_sync_autogen/test_client.py | 42 ++++++++++--------- .../tests/unit/v2_client/test_client.py | 14 +++++++ 3 files changed, 58 insertions(+), 40 deletions(-) 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 fc27451e60be..ef070d4c28bc 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 @@ -103,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", @@ -127,9 +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", oauth2_credentials.Credentials("token") - ) + 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 @@ -145,7 +156,7 @@ async def test_ctor(self): ) expected_project = "project-id" - expected_credentials = oauth2_credentials.Credentials("token") + expected_credentials = _StubCredentials() client = self._make_client( project="project-id", credentials=expected_credentials, @@ -294,7 +305,7 @@ async def test_metrics_exporter_init_shares_arguments( ): import os - expected_credentials = oauth2_credentials.Credentials("token") + expected_credentials = _StubCredentials() expected_project = "custom_project" cert_source = mock.Mock() input_options = client_options.ClientOptions( @@ -1314,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" @@ -1334,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", @@ -1364,8 +1370,7 @@ async def test_metrics_exporter_uses_universe_domain(self): import os universe_domain = "custom-universe.test" - creds = oauth2_credentials.Credentials("token") - creds._universe_domain = universe_domain + creds = _StubCredentials(universe_domain) options = client_options.ClientOptions(universe_domain=universe_domain) async with self._make_client( project="project_id", @@ -1422,15 +1427,13 @@ async def test_metrics_exporter_disabled_with_anonymous_credentials(self): 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" - tpc_creds = oauth2_credentials.Credentials("token") - tpc_creds._universe_domain = universe_domain cases = [ ( - oauth2_credentials.Credentials("token"), + _StubCredentials(), client_options.ClientOptions(api_endpoint="bigtable.custom.local:443"), ), ( - tpc_creds, + _StubCredentials(universe_domain), client_options.ClientOptions( api_endpoint="bigtable.custom.local:443", universe_domain=universe_domain, @@ -1465,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, 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 db7b83c7982b..aaca8c3d049e 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 @@ -83,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 @@ -100,9 +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", oauth2_credentials.Credentials("token") - ) + 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 @@ -117,7 +128,7 @@ def test_ctor(self): ) expected_project = "project-id" - expected_credentials = oauth2_credentials.Credentials("token") + expected_credentials = _StubCredentials() client = self._make_client( project="project-id", credentials=expected_credentials, use_emulator=False ) @@ -255,7 +266,7 @@ def test_metrics_exporter_init_shares_arguments( ): import os - expected_credentials = oauth2_credentials.Credentials("token") + expected_credentials = _StubCredentials() expected_project = "custom_project" cert_source = mock.Mock() input_options = client_options.ClientOptions( @@ -1098,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" @@ -1115,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", @@ -1138,8 +1144,7 @@ def test_metrics_exporter_uses_universe_domain(self): import os universe_domain = "custom-universe.test" - creds = oauth2_credentials.Credentials("token") - creds._universe_domain = universe_domain + creds = _StubCredentials(universe_domain) options = client_options.ClientOptions(universe_domain=universe_domain) with self._make_client( project="project_id", @@ -1193,15 +1198,13 @@ def test_metrics_exporter_disabled_with_anonymous_credentials(self): 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" - tpc_creds = oauth2_credentials.Credentials("token") - tpc_creds._universe_domain = universe_domain cases = [ ( - oauth2_credentials.Credentials("token"), + _StubCredentials(), client_options.ClientOptions(api_endpoint="bigtable.custom.local:443"), ), ( - tpc_creds, + _StubCredentials(universe_domain), client_options.ClientOptions( api_endpoint="bigtable.custom.local:443", universe_domain=universe_domain, @@ -1234,8 +1237,7 @@ def test_configured_universe_domain_matches_credentials(self): 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, 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 5be61e8b2c0d..eb9ade102ad6 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 @@ -424,6 +424,20 @@ def test_client__create_gapic_client_channel_w_endpoint_w_emulator_host(): "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 ( From f6568d0092864534e0d961d0c912dc2169e3c56d Mon Sep 17 00:00:00 2001 From: Daniel Sanche Date: Wed, 25 Nov 2026 17:42:53 -0700 Subject: [PATCH 9/9] added universe validation --- .../google/cloud/bigtable/client.py | 2 + .../cloud/bigtable/data/_async/client.py | 25 +++---- .../google/cloud/bigtable/data/_helpers.py | 27 +++++++ .../bigtable/data/_sync_autogen/client.py | 19 ++--- .../tests/unit/data/_async/test_client.py | 74 +++++++++++++++++++ .../unit/data/_sync_autogen/test_client.py | 72 ++++++++++++++++++ .../tests/unit/data/test__helpers.py | 38 ++++++++++ .../tests/unit/v2_client/_testing.py | 8 +- .../tests/unit/v2_client/test_client.py | 55 +++++++++++++- 9 files changed, 291 insertions(+), 29 deletions(-) diff --git a/packages/google-cloud-bigtable/google/cloud/bigtable/client.py b/packages/google-cloud-bigtable/google/cloud/bigtable/client.py index cb5f27495604..6f4bf573950a 100644 --- a/packages/google-cloud-bigtable/google/cloud/bigtable/client.py +++ b/packages/google-cloud-bigtable/google/cloud/bigtable/client.py @@ -41,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, @@ -304,6 +305,7 @@ def _resolve_admin_endpoint(self, client_class): 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 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 0e470a46e33d..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,21 +271,6 @@ 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( 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 435c65969788..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,15 +204,6 @@ 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) 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 ef070d4c28bc..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 @@ -1478,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 aaca8c3d049e..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 @@ -1247,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: 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 eb9ade102ad6..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 @@ -516,7 +516,7 @@ def test_client_admin_clients_endpoint( os.environ["GOOGLE_CLOUD_UNIVERSE_DOMAIN"] = env_universe client = _make_client( project=PROJECT, - credentials=_make_credentials(), + credentials=_make_credentials(universe_domain=expected_universe), admin=True, client_options=co, admin_client_options=aco, @@ -542,7 +542,7 @@ def test_client_admin_clients_inherit_universe_wo_mutating_options( ): client = _make_client( project=PROJECT, - credentials=_make_credentials(), + credentials=_make_credentials(universe_domain="tpc.test"), admin=True, client_options={"universe_domain": "tpc.test"}, admin_client_options=admin_client_options, @@ -608,7 +608,9 @@ def set_env(value): with mock.patch.dict(os.environ, {}, clear=False): set_env(env_at_construction) client = _make_client( - project=PROJECT, credentials=_make_credentials(), admin=True + project=PROJECT, + credentials=_make_credentials(universe_domain=expected_universe), + admin=True, ) set_env(env_at_first_use) @@ -653,6 +655,53 @@ def test_client_admin_clients_w_empty_universe_domain( _ = 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"