From 95abb825281d87cd7d612ead3cfd2e5d5c4c49a1 Mon Sep 17 00:00:00 2001 From: Daniel Sanche Date: Thu, 26 Nov 2026 00:50:11 -0700 Subject: [PATCH 1/2] feat(runtimeconfig): support custom universe domains in Client and Connection --- .../google/cloud/runtimeconfig/_http.py | 6 +- .../google/cloud/runtimeconfig/client.py | 28 +- packages/google-cloud-runtimeconfig/setup.py | 5 +- .../testing/constraints-3.10.txt | 2 +- .../tests/unit/conftest.py | 22 ++ .../tests/unit/test_client.py | 5 +- .../tests/unit/test_universe_domain.py | 240 ++++++++++++++++++ 7 files changed, 283 insertions(+), 25 deletions(-) create mode 100644 packages/google-cloud-runtimeconfig/tests/unit/conftest.py create mode 100644 packages/google-cloud-runtimeconfig/tests/unit/test_universe_domain.py diff --git a/packages/google-cloud-runtimeconfig/google/cloud/runtimeconfig/_http.py b/packages/google-cloud-runtimeconfig/google/cloud/runtimeconfig/_http.py index dc77833bc545..38c5d6182a2e 100644 --- a/packages/google-cloud-runtimeconfig/google/cloud/runtimeconfig/_http.py +++ b/packages/google-cloud-runtimeconfig/google/cloud/runtimeconfig/_http.py @@ -30,10 +30,10 @@ class Connection(_http.JSONConnection): """ DEFAULT_API_ENDPOINT = "https://runtimeconfig.googleapis.com" + DEFAULT_API_ENDPOINT_TEMPLATE = "https://runtimeconfig.{universe_domain}" - def __init__(self, client, client_info=None, api_endpoint=DEFAULT_API_ENDPOINT): - super(Connection, self).__init__(client, client_info) - self.API_BASE_URL = api_endpoint + def __init__(self, client, client_info=None, api_endpoint=None): + super(Connection, self).__init__(client, client_info, api_endpoint=api_endpoint) self._client_info.gapic_version = __version__ self._client_info.client_library_version = __version__ diff --git a/packages/google-cloud-runtimeconfig/google/cloud/runtimeconfig/client.py b/packages/google-cloud-runtimeconfig/google/cloud/runtimeconfig/client.py index a50727dc0647..07047022d89c 100644 --- a/packages/google-cloud-runtimeconfig/google/cloud/runtimeconfig/client.py +++ b/packages/google-cloud-runtimeconfig/google/cloud/runtimeconfig/client.py @@ -14,8 +14,10 @@ """Client for interacting with the Google Cloud RuntimeConfig API.""" -import google.api_core.client_options -from google.cloud.client import ClientWithProject +from google.cloud.client import ( + ClientWithProject, + _validate_credentials_universe, +) from google.cloud.runtimeconfig._http import Connection from google.cloud.runtimeconfig.config import Config @@ -53,7 +55,8 @@ class Client(ClientWithProject): :type client_options: :class:`~google.api_core.client_options.ClientOptions` or :class:`dict` :param client_options: (Optional) Client options used to set user options - on the client. API Endpoint should be set through client_options. + on the client. A non-default universe domain or API endpoint should be + set through client_options. """ SCOPE = ("https://www.googleapis.com/auth/cloudruntimeconfig",) @@ -68,20 +71,13 @@ def __init__( client_options=None, ): super(Client, self).__init__( - project=project, credentials=credentials, _http=_http + project=project, + credentials=credentials, + client_options=client_options, + _http=_http, ) - - kw_args = {"client_info": client_info} - if client_options: - if isinstance(client_options, dict): - client_options = google.api_core.client_options.from_dict( - client_options - ) - if client_options.api_endpoint: - api_endpoint = client_options.api_endpoint - kw_args["api_endpoint"] = api_endpoint - - self._connection = Connection(self, **kw_args) + _validate_credentials_universe(self._universe_domain, self._credentials) + self._connection = Connection(self, client_info=client_info) def config(self, config_name): """Factory constructor for config object. diff --git a/packages/google-cloud-runtimeconfig/setup.py b/packages/google-cloud-runtimeconfig/setup.py index b46ef501aae0..d3dc017f4699 100644 --- a/packages/google-cloud-runtimeconfig/setup.py +++ b/packages/google-cloud-runtimeconfig/setup.py @@ -34,10 +34,7 @@ # 'Development Status :: 5 - Production/Stable' release_status = "Development Status :: 4 - Beta" dependencies = [ - # NOTE: Maintainers, please do not require google-cloud-core>=2.x.x - # Until this issue is closed - # https://github.com/googleapis/google-cloud-python/issues/10566 - "google-cloud-core >= 1.4.4, < 3.0.0", + "google-cloud-core >= 2.9.0, < 3.0.0", ] extras = {} diff --git a/packages/google-cloud-runtimeconfig/testing/constraints-3.10.txt b/packages/google-cloud-runtimeconfig/testing/constraints-3.10.txt index 327aaf29bca7..dc16663f0753 100644 --- a/packages/google-cloud-runtimeconfig/testing/constraints-3.10.txt +++ b/packages/google-cloud-runtimeconfig/testing/constraints-3.10.txt @@ -5,4 +5,4 @@ # # e.g., if setup.py has "foo >= 1.14.0, < 2.0.0dev", # Then this file should have foo==1.14.0 -google-cloud-core==1.4.4 +google-cloud-core==2.9.0 diff --git a/packages/google-cloud-runtimeconfig/tests/unit/conftest.py b/packages/google-cloud-runtimeconfig/tests/unit/conftest.py new file mode 100644 index 000000000000..d32205cfade9 --- /dev/null +++ b/packages/google-cloud-runtimeconfig/tests/unit/conftest.py @@ -0,0 +1,22 @@ +# 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 pytest + + +@pytest.fixture(autouse=True) +def clean_universe_env(monkeypatch: pytest.MonkeyPatch) -> None: + """Ensure ambient workstation env vars never affect unit tests.""" + monkeypatch.delenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", raising=False) + monkeypatch.delenv("GOOGLE_API_USE_MTLS_ENDPOINT", raising=False) diff --git a/packages/google-cloud-runtimeconfig/tests/unit/test_client.py b/packages/google-cloud-runtimeconfig/tests/unit/test_client.py index 2d1e0f69a30f..305cd3bb15b9 100644 --- a/packages/google-cloud-runtimeconfig/tests/unit/test_client.py +++ b/packages/google-cloud-runtimeconfig/tests/unit/test_client.py @@ -20,7 +20,10 @@ def _make_credentials(): import google.auth.credentials - return mock.Mock(spec=google.auth.credentials.Credentials) + return mock.Mock( + spec=google.auth.credentials.Credentials, + universe_domain="googleapis.com", + ) class TestClient(unittest.TestCase): diff --git a/packages/google-cloud-runtimeconfig/tests/unit/test_universe_domain.py b/packages/google-cloud-runtimeconfig/tests/unit/test_universe_domain.py new file mode 100644 index 000000000000..e24dfb0a7330 --- /dev/null +++ b/packages/google-cloud-runtimeconfig/tests/unit/test_universe_domain.py @@ -0,0 +1,240 @@ +# 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 __future__ import annotations + +from collections.abc import Iterator +from types import MappingProxyType +from typing import Any +from unittest import mock +from urllib.parse import urlparse + +import google.auth +import pytest +import requests +from google.api_core import client_options as client_options_lib +from google.api_core.universe import EmptyUniverseError, UniverseMismatchError +from google.auth import credentials as auth_credentials +from google.auth.exceptions import MutualTLSChannelError + +from google.cloud import runtimeconfig + +DEFAULT_PROJECT_ID = "test-proj" +DEFAULT_CONFIG_NAME = "my-cfg" +DEFAULT_UNIVERSE = "googleapis.com" +CUSTOM_UNIVERSE = "apis-tpclp.goog" + + +class FakeScopedQuotaCredentials( + auth_credentials.Scoped, auth_credentials.CredentialsWithQuotaProject +): + """Fake Credentials supporting scopes, quota project, and universe_domain.""" + + def __init__( + self, + universe_domain: str = DEFAULT_UNIVERSE, + quota_project_id: str | None = None, + scopes: tuple[str, ...] | None = None, + ) -> None: + super().__init__() + self._universe_domain = universe_domain + self._quota_project_id = quota_project_id + self._scopes = scopes + self.token = "fake-token" + + @property + def universe_domain(self) -> str: + return self._universe_domain + + @property + def requires_scopes(self) -> bool: + return False + + def refresh(self, request: Any) -> None: # pragma: NO COVER + self.token = "fake-token" + + def with_scopes( + self, scopes: Any, default_scopes: Any = None + ) -> FakeScopedQuotaCredentials: # pragma: NO COVER + return FakeScopedQuotaCredentials( + universe_domain=self._universe_domain, + quota_project_id=self._quota_project_id, + scopes=tuple(scopes or default_scopes or ()), + ) + + def with_quota_project( + self, quota_project_id: str | None + ) -> FakeScopedQuotaCredentials: # pragma: NO COVER + return FakeScopedQuotaCredentials( + universe_domain=self._universe_domain, + quota_project_id=quota_project_id, + scopes=self._scopes, + ) + + +def _is_googleapis_host(url: str) -> bool: + host = urlparse(url).hostname + return bool(host and (host == "googleapis.com" or host.endswith(".googleapis.com"))) + + +@pytest.fixture +def captured_requests(monkeypatch: pytest.MonkeyPatch) -> Iterator[list[str]]: + seen_urls: list[str] = [] + + def _guarded_send(self, request, *args, **kwargs): + if _is_googleapis_host(request.url): # pragma: NO COVER + raise ConnectionRefusedError( + f"Unexpected googleapis.com call: {request.url}" + ) + seen_urls.append(request.url) + resp = requests.Response() + resp.status_code = 200 + resp._content = ( + b'{"name": "projects/test-proj/configs/my-cfg", "description": "desc"}' + ) + resp.headers = {"content-type": "application/json"} + resp.encoding = "utf-8" + return resp + + monkeypatch.setattr(requests.Session, "send", _guarded_send) + yield seen_urls + + +class TestRuntimeConfigUniverseDomain: + @pytest.mark.parametrize( + "client_options", + [ + {"universe_domain": CUSTOM_UNIVERSE}, + MappingProxyType({"universe_domain": CUSTOM_UNIVERSE}), + client_options_lib.ClientOptions(universe_domain=CUSTOM_UNIVERSE), + ], + ) + def test_custom_universe_routing_and_default_host( + self, captured_requests: list[str], client_options: Any + ) -> None: + creds = FakeScopedQuotaCredentials(CUSTOM_UNIVERSE) + client = runtimeconfig.Client( + project=DEFAULT_PROJECT_ID, + credentials=creds, + client_options=client_options, + ) + + assert client.universe_domain == CUSTOM_UNIVERSE + assert ( + client._connection.API_BASE_URL + == f"https://runtimeconfig.{CUSTOM_UNIVERSE}" + ) + cfg = client.config(DEFAULT_CONFIG_NAME) + cfg.reload() + assert cfg.description == "desc" + assert captured_requests == [ + f"https://runtimeconfig.{CUSTOM_UNIVERSE}/v1beta1/projects/{DEFAULT_PROJECT_ID}/configs/{DEFAULT_CONFIG_NAME}?prettyPrint=false" + ] + assert client._http._default_host == f"runtimeconfig.{CUSTOM_UNIVERSE}" + + def test_env_var_universe_with_adc( + self, monkeypatch: pytest.MonkeyPatch, captured_requests: list[str] + ) -> None: + monkeypatch.setenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", CUSTOM_UNIVERSE) + adc_creds = FakeScopedQuotaCredentials(CUSTOM_UNIVERSE) + + with mock.patch.object( + google.auth, + "default", + autospec=True, + return_value=(adc_creds, DEFAULT_PROJECT_ID), + ): + client = runtimeconfig.Client(project=DEFAULT_PROJECT_ID) + + assert client.universe_domain == CUSTOM_UNIVERSE + assert ( + client._connection.API_BASE_URL + == f"https://runtimeconfig.{CUSTOM_UNIVERSE}" + ) + cfg = client.config(DEFAULT_CONFIG_NAME) + cfg.reload() + assert cfg.description == "desc" + assert len(captured_requests) == 1 + + def test_universe_validation_and_empty_errors( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + with pytest.raises(UniverseMismatchError): + runtimeconfig.Client( + project=DEFAULT_PROJECT_ID, + credentials=FakeScopedQuotaCredentials(DEFAULT_UNIVERSE), + client_options={"universe_domain": CUSTOM_UNIVERSE}, + ) + + with pytest.raises(UniverseMismatchError): + runtimeconfig.Client( + project=DEFAULT_PROJECT_ID, + credentials=FakeScopedQuotaCredentials(CUSTOM_UNIVERSE), + ) + + with pytest.raises(EmptyUniverseError): + runtimeconfig.Client( + project=DEFAULT_PROJECT_ID, + credentials=auth_credentials.AnonymousCredentials(), + client_options={"universe_domain": ""}, + ) + + monkeypatch.setenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", "") + with pytest.raises(EmptyUniverseError): + runtimeconfig.Client( + project=DEFAULT_PROJECT_ID, + credentials=auth_credentials.AnonymousCredentials(), + ) + + def test_anonymous_credentials_and_api_endpoint_precedence( + self, monkeypatch: pytest.MonkeyPatch, captured_requests: list[str] + ) -> None: + monkeypatch.setenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", "env.goog") + anon_client = runtimeconfig.Client( + project=DEFAULT_PROJECT_ID, + credentials=auth_credentials.AnonymousCredentials(), + client_options={ + "universe_domain": CUSTOM_UNIVERSE, + "api_endpoint": "https://custom-runtimeconfig.internal:8443", + }, + ) + assert anon_client.universe_domain == CUSTOM_UNIVERSE + assert ( + anon_client._connection.API_BASE_URL + == "https://custom-runtimeconfig.internal:8443" + ) + cfg = anon_client.config(DEFAULT_CONFIG_NAME) + cfg.reload() + assert cfg.description == "desc" + assert captured_requests == [ + f"https://custom-runtimeconfig.internal:8443/v1beta1/projects/{DEFAULT_PROJECT_ID}/configs/{DEFAULT_CONFIG_NAME}?prettyPrint=false" + ] + + def test_mtls_always_gating(self, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("GOOGLE_API_USE_MTLS_ENDPOINT", "always") + + tpc_client = runtimeconfig.Client( + project=DEFAULT_PROJECT_ID, + credentials=FakeScopedQuotaCredentials(CUSTOM_UNIVERSE), + client_options={"universe_domain": CUSTOM_UNIVERSE}, + ) + with pytest.raises(MutualTLSChannelError): + tpc_client._connection.get_api_base_url_for_mtls() + + gdu_client = runtimeconfig.Client( + project=DEFAULT_PROJECT_ID, + credentials=FakeScopedQuotaCredentials(DEFAULT_UNIVERSE), + ) + with pytest.raises(ValueError, match="mTLS endpoint is not available"): + gdu_client._connection.get_api_base_url_for_mtls() From f142c7fecf5e33e8474fe626a27da1d339a655aa Mon Sep 17 00:00:00 2001 From: Daniel Sanche Date: Mon, 30 Nov 2026 13:35:18 -0700 Subject: [PATCH 2/2] use Client._validate_universe_domain --- .../google/cloud/runtimeconfig/client.py | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/packages/google-cloud-runtimeconfig/google/cloud/runtimeconfig/client.py b/packages/google-cloud-runtimeconfig/google/cloud/runtimeconfig/client.py index 07047022d89c..81b0d8abb766 100644 --- a/packages/google-cloud-runtimeconfig/google/cloud/runtimeconfig/client.py +++ b/packages/google-cloud-runtimeconfig/google/cloud/runtimeconfig/client.py @@ -14,10 +14,7 @@ """Client for interacting with the Google Cloud RuntimeConfig API.""" -from google.cloud.client import ( - ClientWithProject, - _validate_credentials_universe, -) +from google.cloud.client import ClientWithProject from google.cloud.runtimeconfig._http import Connection from google.cloud.runtimeconfig.config import Config @@ -76,7 +73,7 @@ def __init__( client_options=client_options, _http=_http, ) - _validate_credentials_universe(self._universe_domain, self._credentials) + self._validate_universe_domain() self._connection = Connection(self, client_info=client_info) def config(self, config_name):