Skip to content

Commit 02bc6cb

Browse files
committed
feat(runtimeconfig): support custom universe domains in Client and Connection
1 parent a04f559 commit 02bc6cb

7 files changed

Lines changed: 283 additions & 25 deletions

File tree

‎packages/google-cloud-runtimeconfig/google/cloud/runtimeconfig/_http.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,10 +30,10 @@ class Connection(_http.JSONConnection):
3030
"""
3131

3232
DEFAULT_API_ENDPOINT = "https://runtimeconfig.googleapis.com"
33+
DEFAULT_API_ENDPOINT_TEMPLATE = "https://runtimeconfig.{universe_domain}"
3334

34-
def __init__(self, client, client_info=None, api_endpoint=DEFAULT_API_ENDPOINT):
35-
super(Connection, self).__init__(client, client_info)
36-
self.API_BASE_URL = api_endpoint
35+
def __init__(self, client, client_info=None, api_endpoint=None):
36+
super(Connection, self).__init__(client, client_info, api_endpoint=api_endpoint)
3737
self._client_info.gapic_version = __version__
3838
self._client_info.client_library_version = __version__
3939

‎packages/google-cloud-runtimeconfig/google/cloud/runtimeconfig/client.py‎

Lines changed: 12 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,10 @@
1414

1515
"""Client for interacting with the Google Cloud RuntimeConfig API."""
1616

17-
import google.api_core.client_options
18-
from google.cloud.client import ClientWithProject
17+
from google.cloud.client import (
18+
ClientWithProject,
19+
_validate_credentials_universe,
20+
)
1921

2022
from google.cloud.runtimeconfig._http import Connection
2123
from google.cloud.runtimeconfig.config import Config
@@ -53,7 +55,8 @@ class Client(ClientWithProject):
5355
:type client_options: :class:`~google.api_core.client_options.ClientOptions`
5456
or :class:`dict`
5557
:param client_options: (Optional) Client options used to set user options
56-
on the client. API Endpoint should be set through client_options.
58+
on the client. A non-default universe domain or API endpoint should be
59+
set through client_options.
5760
"""
5861

5962
SCOPE = ("https://www.googleapis.com/auth/cloudruntimeconfig",)
@@ -68,20 +71,13 @@ def __init__(
6871
client_options=None,
6972
):
7073
super(Client, self).__init__(
71-
project=project, credentials=credentials, _http=_http
74+
project=project,
75+
credentials=credentials,
76+
client_options=client_options,
77+
_http=_http,
7278
)
73-
74-
kw_args = {"client_info": client_info}
75-
if client_options:
76-
if isinstance(client_options, dict):
77-
client_options = google.api_core.client_options.from_dict(
78-
client_options
79-
)
80-
if client_options.api_endpoint:
81-
api_endpoint = client_options.api_endpoint
82-
kw_args["api_endpoint"] = api_endpoint
83-
84-
self._connection = Connection(self, **kw_args)
79+
_validate_credentials_universe(self._universe_domain, self._credentials)
80+
self._connection = Connection(self, client_info=client_info)
8581

8682
def config(self, config_name):
8783
"""Factory constructor for config object.

‎packages/google-cloud-runtimeconfig/setup.py‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,10 +34,7 @@
3434
# 'Development Status :: 5 - Production/Stable'
3535
release_status = "Development Status :: 4 - Beta"
3636
dependencies = [
37-
# NOTE: Maintainers, please do not require google-cloud-core>=2.x.x
38-
# Until this issue is closed
39-
# https://github.com/googleapis/google-cloud-python/issues/10566
40-
"google-cloud-core >= 1.4.4, < 3.0.0",
37+
"google-cloud-core >= 2.9.0, < 3.0.0",
4138
]
4239
extras = {}
4340

‎packages/google-cloud-runtimeconfig/testing/constraints-3.10.txt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,4 @@
55
#
66
# e.g., if setup.py has "foo >= 1.14.0, < 2.0.0dev",
77
# Then this file should have foo==1.14.0
8-
google-cloud-core==1.4.4
8+
google-cloud-core==2.9.0
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# Copyright 2026 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
import pytest
16+
17+
18+
@pytest.fixture(autouse=True)
19+
def clean_universe_env(monkeypatch: pytest.MonkeyPatch) -> None:
20+
"""Ensure ambient workstation env vars never affect unit tests."""
21+
monkeypatch.delenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", raising=False)
22+
monkeypatch.delenv("GOOGLE_API_USE_MTLS_ENDPOINT", raising=False)

‎packages/google-cloud-runtimeconfig/tests/unit/test_client.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,10 @@
2020
def _make_credentials():
2121
import google.auth.credentials
2222

23-
return mock.Mock(spec=google.auth.credentials.Credentials)
23+
return mock.Mock(
24+
spec=google.auth.credentials.Credentials,
25+
universe_domain="googleapis.com",
26+
)
2427

2528

2629
class TestClient(unittest.TestCase):
Lines changed: 240 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,240 @@
1+
# Copyright 2026 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
from __future__ import annotations
16+
17+
from collections.abc import Iterator
18+
from types import MappingProxyType
19+
from typing import Any
20+
from unittest import mock
21+
from urllib.parse import urlparse
22+
23+
import google.auth
24+
import pytest
25+
import requests
26+
from google.api_core import client_options as client_options_lib
27+
from google.api_core.universe import EmptyUniverseError, UniverseMismatchError
28+
from google.auth import credentials as auth_credentials
29+
from google.auth.exceptions import MutualTLSChannelError
30+
31+
from google.cloud import runtimeconfig
32+
33+
DEFAULT_PROJECT_ID = "test-proj"
34+
DEFAULT_CONFIG_NAME = "my-cfg"
35+
DEFAULT_UNIVERSE = "googleapis.com"
36+
CUSTOM_UNIVERSE = "apis-tpclp.goog"
37+
38+
39+
class FakeScopedQuotaCredentials(
40+
auth_credentials.Scoped, auth_credentials.CredentialsWithQuotaProject
41+
):
42+
"""Fake Credentials supporting scopes, quota project, and universe_domain."""
43+
44+
def __init__(
45+
self,
46+
universe_domain: str = DEFAULT_UNIVERSE,
47+
quota_project_id: str | None = None,
48+
scopes: tuple[str, ...] | None = None,
49+
) -> None:
50+
super().__init__()
51+
self._universe_domain = universe_domain
52+
self._quota_project_id = quota_project_id
53+
self._scopes = scopes
54+
self.token = "fake-token"
55+
56+
@property
57+
def universe_domain(self) -> str:
58+
return self._universe_domain
59+
60+
@property
61+
def requires_scopes(self) -> bool:
62+
return False
63+
64+
def refresh(self, request: Any) -> None: # pragma: NO COVER
65+
self.token = "fake-token"
66+
67+
def with_scopes(
68+
self, scopes: Any, default_scopes: Any = None
69+
) -> FakeScopedQuotaCredentials: # pragma: NO COVER
70+
return FakeScopedQuotaCredentials(
71+
universe_domain=self._universe_domain,
72+
quota_project_id=self._quota_project_id,
73+
scopes=tuple(scopes or default_scopes or ()),
74+
)
75+
76+
def with_quota_project(
77+
self, quota_project_id: str | None
78+
) -> FakeScopedQuotaCredentials: # pragma: NO COVER
79+
return FakeScopedQuotaCredentials(
80+
universe_domain=self._universe_domain,
81+
quota_project_id=quota_project_id,
82+
scopes=self._scopes,
83+
)
84+
85+
86+
def _is_googleapis_host(url: str) -> bool:
87+
host = urlparse(url).hostname
88+
return bool(host and (host == "googleapis.com" or host.endswith(".googleapis.com")))
89+
90+
91+
@pytest.fixture
92+
def captured_requests(monkeypatch: pytest.MonkeyPatch) -> Iterator[list[str]]:
93+
seen_urls: list[str] = []
94+
95+
def _guarded_send(self, request, *args, **kwargs):
96+
if _is_googleapis_host(request.url): # pragma: NO COVER
97+
raise ConnectionRefusedError(
98+
f"Unexpected googleapis.com call: {request.url}"
99+
)
100+
seen_urls.append(request.url)
101+
resp = requests.Response()
102+
resp.status_code = 200
103+
resp._content = (
104+
b'{"name": "projects/test-proj/configs/my-cfg", "description": "desc"}'
105+
)
106+
resp.headers = {"content-type": "application/json"}
107+
resp.encoding = "utf-8"
108+
return resp
109+
110+
monkeypatch.setattr(requests.Session, "send", _guarded_send)
111+
yield seen_urls
112+
113+
114+
class TestRuntimeConfigUniverseDomain:
115+
@pytest.mark.parametrize(
116+
"client_options",
117+
[
118+
{"universe_domain": CUSTOM_UNIVERSE},
119+
MappingProxyType({"universe_domain": CUSTOM_UNIVERSE}),
120+
client_options_lib.ClientOptions(universe_domain=CUSTOM_UNIVERSE),
121+
],
122+
)
123+
def test_custom_universe_routing_and_default_host(
124+
self, captured_requests: list[str], client_options: Any
125+
) -> None:
126+
creds = FakeScopedQuotaCredentials(CUSTOM_UNIVERSE)
127+
client = runtimeconfig.Client(
128+
project=DEFAULT_PROJECT_ID,
129+
credentials=creds,
130+
client_options=client_options,
131+
)
132+
133+
assert client.universe_domain == CUSTOM_UNIVERSE
134+
assert (
135+
client._connection.API_BASE_URL
136+
== f"https://runtimeconfig.{CUSTOM_UNIVERSE}"
137+
)
138+
cfg = client.config(DEFAULT_CONFIG_NAME)
139+
cfg.reload()
140+
assert cfg.description == "desc"
141+
assert captured_requests == [
142+
f"https://runtimeconfig.{CUSTOM_UNIVERSE}/v1beta1/projects/{DEFAULT_PROJECT_ID}/configs/{DEFAULT_CONFIG_NAME}?prettyPrint=false"
143+
]
144+
assert client._http._default_host == f"runtimeconfig.{CUSTOM_UNIVERSE}"
145+
146+
def test_env_var_universe_with_adc(
147+
self, monkeypatch: pytest.MonkeyPatch, captured_requests: list[str]
148+
) -> None:
149+
monkeypatch.setenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", CUSTOM_UNIVERSE)
150+
adc_creds = FakeScopedQuotaCredentials(CUSTOM_UNIVERSE)
151+
152+
with mock.patch.object(
153+
google.auth,
154+
"default",
155+
autospec=True,
156+
return_value=(adc_creds, DEFAULT_PROJECT_ID),
157+
):
158+
client = runtimeconfig.Client(project=DEFAULT_PROJECT_ID)
159+
160+
assert client.universe_domain == CUSTOM_UNIVERSE
161+
assert (
162+
client._connection.API_BASE_URL
163+
== f"https://runtimeconfig.{CUSTOM_UNIVERSE}"
164+
)
165+
cfg = client.config(DEFAULT_CONFIG_NAME)
166+
cfg.reload()
167+
assert cfg.description == "desc"
168+
assert len(captured_requests) == 1
169+
170+
def test_universe_validation_and_empty_errors(
171+
self, monkeypatch: pytest.MonkeyPatch
172+
) -> None:
173+
with pytest.raises(UniverseMismatchError):
174+
runtimeconfig.Client(
175+
project=DEFAULT_PROJECT_ID,
176+
credentials=FakeScopedQuotaCredentials(DEFAULT_UNIVERSE),
177+
client_options={"universe_domain": CUSTOM_UNIVERSE},
178+
)
179+
180+
with pytest.raises(UniverseMismatchError):
181+
runtimeconfig.Client(
182+
project=DEFAULT_PROJECT_ID,
183+
credentials=FakeScopedQuotaCredentials(CUSTOM_UNIVERSE),
184+
)
185+
186+
with pytest.raises(EmptyUniverseError):
187+
runtimeconfig.Client(
188+
project=DEFAULT_PROJECT_ID,
189+
credentials=auth_credentials.AnonymousCredentials(),
190+
client_options={"universe_domain": ""},
191+
)
192+
193+
monkeypatch.setenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", "")
194+
with pytest.raises(EmptyUniverseError):
195+
runtimeconfig.Client(
196+
project=DEFAULT_PROJECT_ID,
197+
credentials=auth_credentials.AnonymousCredentials(),
198+
)
199+
200+
def test_anonymous_credentials_and_api_endpoint_precedence(
201+
self, monkeypatch: pytest.MonkeyPatch, captured_requests: list[str]
202+
) -> None:
203+
monkeypatch.setenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", "env.goog")
204+
anon_client = runtimeconfig.Client(
205+
project=DEFAULT_PROJECT_ID,
206+
credentials=auth_credentials.AnonymousCredentials(),
207+
client_options={
208+
"universe_domain": CUSTOM_UNIVERSE,
209+
"api_endpoint": "https://custom-runtimeconfig.internal:8443",
210+
},
211+
)
212+
assert anon_client.universe_domain == CUSTOM_UNIVERSE
213+
assert (
214+
anon_client._connection.API_BASE_URL
215+
== "https://custom-runtimeconfig.internal:8443"
216+
)
217+
cfg = anon_client.config(DEFAULT_CONFIG_NAME)
218+
cfg.reload()
219+
assert cfg.description == "desc"
220+
assert captured_requests == [
221+
f"https://custom-runtimeconfig.internal:8443/v1beta1/projects/{DEFAULT_PROJECT_ID}/configs/{DEFAULT_CONFIG_NAME}?prettyPrint=false"
222+
]
223+
224+
def test_mtls_always_gating(self, monkeypatch: pytest.MonkeyPatch) -> None:
225+
monkeypatch.setenv("GOOGLE_API_USE_MTLS_ENDPOINT", "always")
226+
227+
tpc_client = runtimeconfig.Client(
228+
project=DEFAULT_PROJECT_ID,
229+
credentials=FakeScopedQuotaCredentials(CUSTOM_UNIVERSE),
230+
client_options={"universe_domain": CUSTOM_UNIVERSE},
231+
)
232+
with pytest.raises(MutualTLSChannelError):
233+
tpc_client._connection.get_api_base_url_for_mtls()
234+
235+
gdu_client = runtimeconfig.Client(
236+
project=DEFAULT_PROJECT_ID,
237+
credentials=FakeScopedQuotaCredentials(DEFAULT_UNIVERSE),
238+
)
239+
with pytest.raises(ValueError, match="mTLS endpoint is not available"):
240+
gdu_client._connection.get_api_base_url_for_mtls()

0 commit comments

Comments
 (0)