From 8808918355959b3dafb8b7dad365dc1288d34f9f Mon Sep 17 00:00:00 2001 From: Heba Alazzeh Date: Thu, 16 Jul 2026 14:54:01 +0000 Subject: [PATCH 1/5] feat(api-core): move universe and endpoint routing logic to gapic_v1 public helpers Introduces routing module containing get_api_endpoint, get_default_mtls_endpoint, and get_universe_domain helpers. Exposes the module as public in gapic_v1. --- .../google/api_core/gapic_v1/__init__.py | 4 +- .../google/api_core/gapic_v1/routing.py | 101 ++++++++++ packages/google-api-core/noxfile.py | 2 +- packages/google-api-core/tests/conftest.py | 31 ++++ .../tests/unit/gapic/test_routing.py | 175 ++++++++++++++++++ .../google-api-core/tests/unit/test_bidi.py | 5 +- 6 files changed, 313 insertions(+), 5 deletions(-) create mode 100644 packages/google-api-core/google/api_core/gapic_v1/routing.py create mode 100644 packages/google-api-core/tests/conftest.py create mode 100644 packages/google-api-core/tests/unit/gapic/test_routing.py diff --git a/packages/google-api-core/google/api_core/gapic_v1/__init__.py b/packages/google-api-core/google/api_core/gapic_v1/__init__.py index 48a27ec21d24..dd17bfd55975 100644 --- a/packages/google-api-core/google/api_core/gapic_v1/__init__.py +++ b/packages/google-api-core/google/api_core/gapic_v1/__init__.py @@ -25,9 +25,10 @@ # Older Python versions safely ignore this variable. __lazy_modules__: Set[str] = { "google.api_core.gapic_v1.client_info", + "google.api_core.gapic_v1.routing", "google.api_core.gapic_v1.routing_header", } -__all__ = ["client_info", "routing_header"] +__all__ = ["client_info", "routing", "routing_header"] if _has_grpc: __lazy_modules__.update( @@ -41,6 +42,7 @@ from google.api_core.gapic_v1 import ( # noqa: E402 client_info, + routing, routing_header, ) diff --git a/packages/google-api-core/google/api_core/gapic_v1/routing.py b/packages/google-api-core/google/api_core/gapic_v1/routing.py new file mode 100644 index 000000000000..f2e98acc8a1c --- /dev/null +++ b/packages/google-api-core/google/api_core/gapic_v1/routing.py @@ -0,0 +1,101 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +"""Helpers for routing and endpoint resolution.""" + +import re +from typing import Any, Optional + +from google.auth.exceptions import MutualTLSChannelError # type: ignore + +_MTLS_ENDPOINT_RE = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?" + r"(?P\.googleapis\.com)?" +) + + +def get_default_mtls_endpoint(api_endpoint: Optional[str]) -> Optional[str]: + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + Optional[str]: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + m = _MTLS_ENDPOINT_RE.match(api_endpoint) + if m is None: + # Could not parse api_endpoint; return as-is. + return api_endpoint + + name, mtls_group, sandbox, googledomain = m.groups() + if mtls_group or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + +def get_api_endpoint( + api_override: Optional[str], + client_cert_source: Optional[Any], + universe_domain: str, + use_mtls_endpoint: str, + default_universe: str, + default_mtls_endpoint: Optional[str], + default_endpoint_template: Optional[str], +) -> Optional[str]: + """Return the API endpoint used by the client.""" + if api_override is not None: + return api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + if universe_domain.lower() != default_universe.lower(): + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {default_universe}." + ) + return default_mtls_endpoint + else: + return ( + default_endpoint_template.format(UNIVERSE_DOMAIN=universe_domain) + if default_endpoint_template + else None + ) + + +def get_universe_domain( + client_universe_domain: Optional[str], + universe_domain_env: Optional[str], + default_universe: str, +) -> str: + """Return the universe domain used by the client.""" + universe_domain = default_universe + if client_universe_domain is not None: + universe_domain = client_universe_domain.strip() + elif universe_domain_env is not None: + universe_domain = universe_domain_env.strip() + if not universe_domain: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain diff --git a/packages/google-api-core/noxfile.py b/packages/google-api-core/noxfile.py index 0bad668a80dd..3cbebbaa84d2 100644 --- a/packages/google-api-core/noxfile.py +++ b/packages/google-api-core/noxfile.py @@ -350,7 +350,7 @@ def prerelease_deps(session): @nox.session(python=DEFAULT_PYTHON_VERSION) def core_deps_from_source(session): """Run the test suite installing dependencies from source.""" - default(session, prerelease=True) + default(session, install_deps_from_source=True) @nox.session(python=DEFAULT_PYTHON_VERSION) diff --git a/packages/google-api-core/tests/conftest.py b/packages/google-api-core/tests/conftest.py new file mode 100644 index 000000000000..1872207be107 --- /dev/null +++ b/packages/google-api-core/tests/conftest.py @@ -0,0 +1,31 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +from unittest import mock +import pytest + + +@pytest.fixture(scope="session", autouse=True) +def mock_mtls_env(): + """Autouse session-scoped fixture to isolate unit tests from workstation mTLS environments.""" + with mock.patch.dict( + os.environ, + { + "GOOGLE_API_USE_CLIENT_CERTIFICATE": "false", + "CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE": "false", + }, + ): + yield diff --git a/packages/google-api-core/tests/unit/gapic/test_routing.py b/packages/google-api-core/tests/unit/gapic/test_routing.py new file mode 100644 index 000000000000..1200f2589133 --- /dev/null +++ b/packages/google-api-core/tests/unit/gapic/test_routing.py @@ -0,0 +1,175 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from unittest import mock + +import pytest + +from google.auth.exceptions import MutualTLSChannelError + +from google.api_core.gapic_v1.routing import ( + get_api_endpoint, + get_default_mtls_endpoint, + get_universe_domain, +) + + +def test_get_default_mtls_endpoint(): + # Test valid API endpoints + assert get_default_mtls_endpoint("foo.googleapis.com") == "foo.mtls.googleapis.com" + assert ( + get_default_mtls_endpoint("foo.sandbox.googleapis.com") + == "foo.mtls.sandbox.googleapis.com" + ) + + # Test endpoints that shouldn't be converted + assert ( + get_default_mtls_endpoint("foo.mtls.googleapis.com") + == "foo.mtls.googleapis.com" + ) + assert get_default_mtls_endpoint("foo.com") == "foo.com" + + # Test empty/None endpoints + assert get_default_mtls_endpoint("") == "" + assert get_default_mtls_endpoint(None) is None + + +def test_get_api_endpoint_override(): + # If api_override is provided, it should be returned + # regardless of other args + endpoint = get_api_endpoint( + api_override="custom.endpoint.com", + client_cert_source=None, + universe_domain="googleapis.com", + use_mtls_endpoint="auto", + default_universe="googleapis.com", + default_mtls_endpoint="foo.mtls.googleapis.com", + default_endpoint_template="foo.{UNIVERSE_DOMAIN}", + ) + assert endpoint == "custom.endpoint.com" + + +def test_get_api_endpoint_mtls_always(): + # use_mtls_endpoint == "always" should use the default mtls endpoint + endpoint = get_api_endpoint( + api_override=None, + client_cert_source=None, + universe_domain="googleapis.com", + use_mtls_endpoint="always", + default_universe="googleapis.com", + default_mtls_endpoint="foo.mtls.googleapis.com", + default_endpoint_template="foo.{UNIVERSE_DOMAIN}", + ) + assert endpoint == "foo.mtls.googleapis.com" + + +def test_get_api_endpoint_mtls_auto_with_cert(): + # "auto" with client_cert_source should use mtls + endpoint = get_api_endpoint( + api_override=None, + client_cert_source=mock.Mock(), + universe_domain="googleapis.com", + use_mtls_endpoint="auto", + default_universe="googleapis.com", + default_mtls_endpoint="foo.mtls.googleapis.com", + default_endpoint_template="foo.{UNIVERSE_DOMAIN}", + ) + assert endpoint == "foo.mtls.googleapis.com" + + +def test_get_api_endpoint_mtls_auto_no_cert(): + # "auto" without client_cert_source should use the default template + endpoint = get_api_endpoint( + api_override=None, + client_cert_source=None, + universe_domain="googleapis.com", + use_mtls_endpoint="auto", + default_universe="googleapis.com", + default_mtls_endpoint="foo.mtls.googleapis.com", + default_endpoint_template="foo.{UNIVERSE_DOMAIN}", + ) + assert endpoint == "foo.googleapis.com" + + +def test_get_api_endpoint_mtls_universe_mismatch(): + # mTLS is only supported in the default universe + with pytest.raises(MutualTLSChannelError, match="mTLS is not supported"): + get_api_endpoint( + api_override=None, + client_cert_source=mock.Mock(), + universe_domain="custom-universe.com", + use_mtls_endpoint="auto", + default_universe="googleapis.com", + default_mtls_endpoint="foo.mtls.googleapis.com", + default_endpoint_template="foo.{UNIVERSE_DOMAIN}", + ) + + +def test_get_api_endpoint_mtls_case_insensitive(): + # mTLS universe check should be case insensitive + endpoint = get_api_endpoint( + api_override=None, + client_cert_source=mock.Mock(), + universe_domain="GOOGLEAPIS.COM", + use_mtls_endpoint="auto", + default_universe="googleapis.com", + default_mtls_endpoint="foo.mtls.googleapis.com", + default_endpoint_template="foo.{UNIVERSE_DOMAIN}", + ) + assert endpoint == "foo.mtls.googleapis.com" + + +def test_get_universe_domain(): + # client_universe_domain takes precedence + assert ( + get_universe_domain("client.com", "env.com", "default.com") # noqa: E501 + == "client.com" + ) + + # env takes precedence over default + assert ( + get_universe_domain(None, "env.com", "default.com") == "env.com" # noqa: E501 + ) + + # fallback to default + assert get_universe_domain(None, None, "default.com") == "default.com" # noqa: E501 + + +def test_get_universe_domain_strip(): + # check that whitespace is stripped + assert ( + get_universe_domain(" client.com ", "env.com", "default.com") == "client.com" + ) + assert get_universe_domain(None, " env.com ", "default.com") == "env.com" + + +def test_get_universe_domain_empty(): + with pytest.raises(ValueError, match="cannot be an empty string"): + get_universe_domain("", None, "default.com") + with pytest.raises(ValueError, match="cannot be an empty string"): + get_universe_domain(" ", None, "default.com") + + +def test_get_api_endpoint_none_template(): + endpoint = get_api_endpoint( + api_override=None, + client_cert_source=None, + universe_domain="googleapis.com", + use_mtls_endpoint="never", + default_universe="googleapis.com", + default_mtls_endpoint=None, + default_endpoint_template=None, + ) + assert endpoint is None diff --git a/packages/google-api-core/tests/unit/test_bidi.py b/packages/google-api-core/tests/unit/test_bidi.py index 4a8eb74fac94..0f4810cb0a12 100644 --- a/packages/google-api-core/tests/unit/test_bidi.py +++ b/packages/google-api-core/tests/unit/test_bidi.py @@ -31,8 +31,7 @@ except ImportError: # pragma: NO COVER pytest.skip("No GRPC", allow_module_level=True) -from google.api_core import bidi -from google.api_core import exceptions +from google.api_core import bidi, exceptions class Test_RequestQueueGenerator(object): @@ -195,7 +194,7 @@ def test_delays_entry_attempts_above_threshold(self): # (NOTE: not using assert all(...), b/c the coverage check would complain) for i, entry in enumerate(entries): if i != 3: - assert entry["reported_wait"] == 0.0 + assert entry["reported_wait"] < 0.01 # The delayed entry is expected to have been delayed for a significant # chunk of the full second, and the actual and reported delay times From 3c47f56582f7e3c8780ee5fad9d8ac06d1626d57 Mon Sep 17 00:00:00 2001 From: Heba Alazzeh Date: Thu, 16 Jul 2026 19:20:20 +0000 Subject: [PATCH 2/5] refactor(api-core): revert unrelated changes in noxfile and test_bidi --- packages/google-api-core/noxfile.py | 2 +- packages/google-api-core/tests/unit/test_bidi.py | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/google-api-core/noxfile.py b/packages/google-api-core/noxfile.py index 3cbebbaa84d2..0bad668a80dd 100644 --- a/packages/google-api-core/noxfile.py +++ b/packages/google-api-core/noxfile.py @@ -350,7 +350,7 @@ def prerelease_deps(session): @nox.session(python=DEFAULT_PYTHON_VERSION) def core_deps_from_source(session): """Run the test suite installing dependencies from source.""" - default(session, install_deps_from_source=True) + default(session, prerelease=True) @nox.session(python=DEFAULT_PYTHON_VERSION) diff --git a/packages/google-api-core/tests/unit/test_bidi.py b/packages/google-api-core/tests/unit/test_bidi.py index 0f4810cb0a12..4a8eb74fac94 100644 --- a/packages/google-api-core/tests/unit/test_bidi.py +++ b/packages/google-api-core/tests/unit/test_bidi.py @@ -31,7 +31,8 @@ except ImportError: # pragma: NO COVER pytest.skip("No GRPC", allow_module_level=True) -from google.api_core import bidi, exceptions +from google.api_core import bidi +from google.api_core import exceptions class Test_RequestQueueGenerator(object): @@ -194,7 +195,7 @@ def test_delays_entry_attempts_above_threshold(self): # (NOTE: not using assert all(...), b/c the coverage check would complain) for i, entry in enumerate(entries): if i != 3: - assert entry["reported_wait"] < 0.01 + assert entry["reported_wait"] == 0.0 # The delayed entry is expected to have been delayed for a significant # chunk of the full second, and the actual and reported delay times From f953c809e54d78c7ae01671d80f4d742353bc2e6 Mon Sep 17 00:00:00 2001 From: Heba Alazzeh Date: Thu, 16 Jul 2026 19:28:08 +0000 Subject: [PATCH 3/5] refactor(api-core): update routing tests to match generator's test template precisely --- .../tests/unit/gapic/test_routing.py | 232 ++++++++++-------- 1 file changed, 123 insertions(+), 109 deletions(-) diff --git a/packages/google-api-core/tests/unit/gapic/test_routing.py b/packages/google-api-core/tests/unit/gapic/test_routing.py index 1200f2589133..76fb5e2d6c8d 100644 --- a/packages/google-api-core/tests/unit/gapic/test_routing.py +++ b/packages/google-api-core/tests/unit/gapic/test_routing.py @@ -26,6 +26,12 @@ ) +class MockClient: + _DEFAULT_UNIVERSE = "googleapis.com" + DEFAULT_MTLS_ENDPOINT = "foo.mtls.googleapis.com" + _DEFAULT_ENDPOINT_TEMPLATE = "foo.{UNIVERSE_DOMAIN}" + + def test_get_default_mtls_endpoint(): # Test valid API endpoints assert get_default_mtls_endpoint("foo.googleapis.com") == "foo.mtls.googleapis.com" @@ -46,130 +52,138 @@ def test_get_default_mtls_endpoint(): assert get_default_mtls_endpoint(None) is None -def test_get_api_endpoint_override(): - # If api_override is provided, it should be returned - # regardless of other args - endpoint = get_api_endpoint( - api_override="custom.endpoint.com", - client_cert_source=None, - universe_domain="googleapis.com", - use_mtls_endpoint="auto", - default_universe="googleapis.com", - default_mtls_endpoint="foo.mtls.googleapis.com", - default_endpoint_template="foo.{UNIVERSE_DOMAIN}", +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = MockClient._DEFAULT_UNIVERSE + default_endpoint = MockClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe ) - assert endpoint == "custom.endpoint.com" - - -def test_get_api_endpoint_mtls_always(): - # use_mtls_endpoint == "always" should use the default mtls endpoint - endpoint = get_api_endpoint( - api_override=None, - client_cert_source=None, - universe_domain="googleapis.com", - use_mtls_endpoint="always", - default_universe="googleapis.com", - default_mtls_endpoint="foo.mtls.googleapis.com", - default_endpoint_template="foo.{UNIVERSE_DOMAIN}", + mock_universe = "bar.com" + mock_endpoint = MockClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe ) - assert endpoint == "foo.mtls.googleapis.com" - - -def test_get_api_endpoint_mtls_auto_with_cert(): - # "auto" with client_cert_source should use mtls - endpoint = get_api_endpoint( - api_override=None, - client_cert_source=mock.Mock(), - universe_domain="googleapis.com", - use_mtls_endpoint="auto", - default_universe="googleapis.com", - default_mtls_endpoint="foo.mtls.googleapis.com", - default_endpoint_template="foo.{UNIVERSE_DOMAIN}", + + assert ( + get_api_endpoint( + api_override, + mock_client_cert_source, + default_universe, + "always", + MockClient._DEFAULT_UNIVERSE, + MockClient.DEFAULT_MTLS_ENDPOINT, + MockClient._DEFAULT_ENDPOINT_TEMPLATE, + ) + == api_override ) - assert endpoint == "foo.mtls.googleapis.com" - - -def test_get_api_endpoint_mtls_auto_no_cert(): - # "auto" without client_cert_source should use the default template - endpoint = get_api_endpoint( - api_override=None, - client_cert_source=None, - universe_domain="googleapis.com", - use_mtls_endpoint="auto", - default_universe="googleapis.com", - default_mtls_endpoint="foo.mtls.googleapis.com", - default_endpoint_template="foo.{UNIVERSE_DOMAIN}", + assert ( + get_api_endpoint( + None, + mock_client_cert_source, + default_universe, + "auto", + MockClient._DEFAULT_UNIVERSE, + MockClient.DEFAULT_MTLS_ENDPOINT, + MockClient._DEFAULT_ENDPOINT_TEMPLATE, + ) + == MockClient.DEFAULT_MTLS_ENDPOINT ) - assert endpoint == "foo.googleapis.com" - - -def test_get_api_endpoint_mtls_universe_mismatch(): - # mTLS is only supported in the default universe - with pytest.raises(MutualTLSChannelError, match="mTLS is not supported"): + assert ( get_api_endpoint( - api_override=None, - client_cert_source=mock.Mock(), - universe_domain="custom-universe.com", - use_mtls_endpoint="auto", - default_universe="googleapis.com", - default_mtls_endpoint="foo.mtls.googleapis.com", - default_endpoint_template="foo.{UNIVERSE_DOMAIN}", + None, + None, + default_universe, + "auto", + MockClient._DEFAULT_UNIVERSE, + MockClient.DEFAULT_MTLS_ENDPOINT, + MockClient._DEFAULT_ENDPOINT_TEMPLATE, ) - - -def test_get_api_endpoint_mtls_case_insensitive(): - # mTLS universe check should be case insensitive - endpoint = get_api_endpoint( - api_override=None, - client_cert_source=mock.Mock(), - universe_domain="GOOGLEAPIS.COM", - use_mtls_endpoint="auto", - default_universe="googleapis.com", - default_mtls_endpoint="foo.mtls.googleapis.com", - default_endpoint_template="foo.{UNIVERSE_DOMAIN}", + == default_endpoint ) - assert endpoint == "foo.mtls.googleapis.com" - - -def test_get_universe_domain(): - # client_universe_domain takes precedence assert ( - get_universe_domain("client.com", "env.com", "default.com") # noqa: E501 - == "client.com" + get_api_endpoint( + None, + None, + default_universe, + "always", + MockClient._DEFAULT_UNIVERSE, + MockClient.DEFAULT_MTLS_ENDPOINT, + MockClient._DEFAULT_ENDPOINT_TEMPLATE, + ) + == MockClient.DEFAULT_MTLS_ENDPOINT ) - - # env takes precedence over default assert ( - get_universe_domain(None, "env.com", "default.com") == "env.com" # noqa: E501 + get_api_endpoint( + None, + mock_client_cert_source, + default_universe, + "always", + MockClient._DEFAULT_UNIVERSE, + MockClient.DEFAULT_MTLS_ENDPOINT, + MockClient._DEFAULT_ENDPOINT_TEMPLATE, + ) + == MockClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + get_api_endpoint( + None, + None, + mock_universe, + "never", + MockClient._DEFAULT_UNIVERSE, + MockClient.DEFAULT_MTLS_ENDPOINT, + MockClient._DEFAULT_ENDPOINT_TEMPLATE, + ) + == mock_endpoint ) - - # fallback to default - assert get_universe_domain(None, None, "default.com") == "default.com" # noqa: E501 - - -def test_get_universe_domain_strip(): - # check that whitespace is stripped assert ( - get_universe_domain(" client.com ", "env.com", "default.com") == "client.com" + get_api_endpoint( + None, + None, + default_universe, + "never", + MockClient._DEFAULT_UNIVERSE, + MockClient.DEFAULT_MTLS_ENDPOINT, + MockClient._DEFAULT_ENDPOINT_TEMPLATE, + ) + == default_endpoint ) - assert get_universe_domain(None, " env.com ", "default.com") == "env.com" + with pytest.raises(MutualTLSChannelError) as excinfo: + get_api_endpoint( + None, + mock_client_cert_source, + mock_universe, + "auto", + MockClient._DEFAULT_UNIVERSE, + MockClient.DEFAULT_MTLS_ENDPOINT, + MockClient._DEFAULT_ENDPOINT_TEMPLATE, + ) + assert ( + str(excinfo.value) + == "mTLS is not supported in any universe other than googleapis.com." + ) -def test_get_universe_domain_empty(): - with pytest.raises(ValueError, match="cannot be an empty string"): - get_universe_domain("", None, "default.com") - with pytest.raises(ValueError, match="cannot be an empty string"): - get_universe_domain(" ", None, "default.com") +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" -def test_get_api_endpoint_none_template(): - endpoint = get_api_endpoint( - api_override=None, - client_cert_source=None, - universe_domain="googleapis.com", - use_mtls_endpoint="never", - default_universe="googleapis.com", - default_mtls_endpoint=None, - default_endpoint_template=None, + assert ( + get_universe_domain( + client_universe_domain, universe_domain_env, MockClient._DEFAULT_UNIVERSE + ) + == client_universe_domain ) - assert endpoint is None + assert ( + get_universe_domain(None, universe_domain_env, MockClient._DEFAULT_UNIVERSE) + == universe_domain_env + ) + assert ( + get_universe_domain(None, None, MockClient._DEFAULT_UNIVERSE) + == MockClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + get_universe_domain("", None, MockClient._DEFAULT_UNIVERSE) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." From 0fe63b534dd5633be4623382824b3890a36356be Mon Sep 17 00:00:00 2001 From: Heba Alazzeh Date: Thu, 16 Jul 2026 19:38:58 +0000 Subject: [PATCH 4/5] fix(api-core): update get_default_mtls_endpoint to use robust string slicing --- .../google/api_core/gapic_v1/routing.py | 28 ++++++------------- 1 file changed, 8 insertions(+), 20 deletions(-) diff --git a/packages/google-api-core/google/api_core/gapic_v1/routing.py b/packages/google-api-core/google/api_core/gapic_v1/routing.py index f2e98acc8a1c..be094a7d455e 100644 --- a/packages/google-api-core/google/api_core/gapic_v1/routing.py +++ b/packages/google-api-core/google/api_core/gapic_v1/routing.py @@ -16,16 +16,10 @@ """Helpers for routing and endpoint resolution.""" -import re from typing import Any, Optional from google.auth.exceptions import MutualTLSChannelError # type: ignore -_MTLS_ENDPOINT_RE = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?" - r"(?P\.googleapis\.com)?" -) - def get_default_mtls_endpoint(api_endpoint: Optional[str]) -> Optional[str]: """Converts api endpoint to mTLS endpoint. @@ -37,24 +31,18 @@ def get_default_mtls_endpoint(api_endpoint: Optional[str]) -> Optional[str]: Returns: Optional[str]: converted mTLS api endpoint. """ - if not api_endpoint: + if not api_endpoint or ".mtls." in api_endpoint: return api_endpoint - m = _MTLS_ENDPOINT_RE.match(api_endpoint) - if m is None: - # Could not parse api_endpoint; return as-is. - return api_endpoint + if api_endpoint.endswith(".sandbox.googleapis.com"): + # len(".sandbox.googleapis.com") == 23 + return api_endpoint[:-23] + ".mtls.sandbox.googleapis.com" - name, mtls_group, sandbox, googledomain = m.groups() - if mtls_group or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) + if api_endpoint.endswith(".googleapis.com"): + # len(".googleapis.com") == 15 + return api_endpoint[:-15] + ".mtls.googleapis.com" - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + return api_endpoint def get_api_endpoint( From 2d0808b205a9b3f4bc97c6ae94364df29ef9eb34 Mon Sep 17 00:00:00 2001 From: Heba Alazzeh Date: Thu, 16 Jul 2026 23:11:31 +0000 Subject: [PATCH 5/5] docs(api-core): address routing review feedback on docstrings, types, and variables --- .../google/api_core/gapic_v1/routing.py | 57 +++++++++++++++---- .../tests/unit/gapic/test_routing.py | 12 ++++ 2 files changed, 59 insertions(+), 10 deletions(-) diff --git a/packages/google-api-core/google/api_core/gapic_v1/routing.py b/packages/google-api-core/google/api_core/gapic_v1/routing.py index be094a7d455e..2ba3af412cd6 100644 --- a/packages/google-api-core/google/api_core/gapic_v1/routing.py +++ b/packages/google-api-core/google/api_core/gapic_v1/routing.py @@ -26,8 +26,10 @@ def get_default_mtls_endpoint(api_endpoint: Optional[str]) -> Optional[str]: Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: api_endpoint (Optional[str]): the api endpoint to convert. + Returns: Optional[str]: converted mTLS api endpoint. """ @@ -52,9 +54,30 @@ def get_api_endpoint( use_mtls_endpoint: str, default_universe: str, default_mtls_endpoint: Optional[str], - default_endpoint_template: Optional[str], -) -> Optional[str]: - """Return the API endpoint used by the client.""" + default_endpoint_template: str, +) -> str: + """Return the API endpoint used by the client. + + Args: + api_override (Optional[str]): The API endpoint override. If specified, + this is always returned. + client_cert_source (Optional[Any]): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint. Possible values + are "always", "auto", or "never". + default_universe (str): The default universe domain. + default_mtls_endpoint (Optional[str]): The default mTLS endpoint. + default_endpoint_template (str): The default endpoint template containing + a placeholder `{UNIVERSE_DOMAIN}`. + + Returns: + str: The API endpoint to be used by the client. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mTLS is requested but + not supported in the configured universe domain. + ValueError: If mTLS is requested but no mTLS endpoint is available. + """ if api_override is not None: return api_override elif use_mtls_endpoint == "always" or ( @@ -64,13 +87,11 @@ def get_api_endpoint( raise MutualTLSChannelError( f"mTLS is not supported in any universe other than {default_universe}." ) + if not default_mtls_endpoint: + raise ValueError("mTLS endpoint is not available.") return default_mtls_endpoint else: - return ( - default_endpoint_template.format(UNIVERSE_DOMAIN=universe_domain) - if default_endpoint_template - else None - ) + return default_endpoint_template.format(UNIVERSE_DOMAIN=universe_domain) def get_universe_domain( @@ -78,12 +99,28 @@ def get_universe_domain( universe_domain_env: Optional[str], default_universe: str, ) -> str: - """Return the universe domain used by the client.""" - universe_domain = default_universe + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured + via client options. + universe_domain_env (Optional[str]): The universe domain configured + via environment variable. + default_universe (str): The default universe domain. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the resolved universe domain is an empty string. + """ if client_universe_domain is not None: universe_domain = client_universe_domain.strip() elif universe_domain_env is not None: universe_domain = universe_domain_env.strip() + else: + universe_domain = default_universe + if not universe_domain: raise ValueError("Universe Domain cannot be an empty string.") return universe_domain diff --git a/packages/google-api-core/tests/unit/gapic/test_routing.py b/packages/google-api-core/tests/unit/gapic/test_routing.py index 76fb5e2d6c8d..0fcf3131fa69 100644 --- a/packages/google-api-core/tests/unit/gapic/test_routing.py +++ b/packages/google-api-core/tests/unit/gapic/test_routing.py @@ -164,6 +164,18 @@ def test__get_api_endpoint(): == "mTLS is not supported in any universe other than googleapis.com." ) + with pytest.raises(ValueError) as excinfo: + get_api_endpoint( + None, + mock_client_cert_source, + default_universe, + "always", + MockClient._DEFAULT_UNIVERSE, + None, + MockClient._DEFAULT_ENDPOINT_TEMPLATE, + ) + assert str(excinfo.value) == "mTLS endpoint is not available." + def test__get_universe_domain(): client_universe_domain = "foo.com"