Skip to content

Commit 5fcfa0f

Browse files
committed
feat(dns): support custom universe domains in Client and Connection
1 parent f4e6e85 commit 5fcfa0f

7 files changed

Lines changed: 266 additions & 23 deletions

File tree

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

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

3131
DEFAULT_API_ENDPOINT = "https://dns.googleapis.com"
32+
DEFAULT_API_ENDPOINT_TEMPLATE = "https://dns.{universe_domain}"
3233

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

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

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,11 @@
1414

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

17-
from google.api_core import client_options as client_options_mod
1817
from google.api_core import page_iterator
19-
from google.cloud.client import ClientWithProject
18+
from google.cloud.client import (
19+
ClientWithProject,
20+
_validate_credentials_universe,
21+
)
2022

2123
from google.cloud.dns._http import Connection
2224
from google.cloud.dns.zone import ManagedZone
@@ -55,7 +57,8 @@ class Client(ClientWithProject):
5557
:type client_options: :class:`~google.api_core.client_options.ClientOptions`
5658
or :class:`dict`
5759
:param client_options: (Optional) Client options used to set user options
58-
on the client. API Endpoint should be set through client_options.
60+
on the client. A non-default universe domain or API endpoint should be
61+
set through client_options.
5962
"""
6063

6164
SCOPE = ("https://www.googleapis.com/auth/ndev.clouddns.readwrite",)
@@ -70,18 +73,13 @@ def __init__(
7073
client_options=None,
7174
):
7275
super(Client, self).__init__(
73-
project=project, credentials=credentials, _http=_http
76+
project=project,
77+
credentials=credentials,
78+
client_options=client_options,
79+
_http=_http,
7480
)
75-
76-
kwargs = {"client_info": client_info}
77-
if client_options:
78-
if isinstance(client_options, dict):
79-
client_options = client_options_mod.from_dict(client_options)
80-
81-
if client_options.api_endpoint:
82-
kwargs["api_endpoint"] = client_options.api_endpoint
83-
84-
self._connection = Connection(self, **kwargs)
81+
_validate_credentials_universe(self._universe_domain, self._credentials)
82+
self._connection = Connection(self, client_info=client_info)
8583

8684
def quotas(self):
8785
"""Return DNS quotas for the project associated with this client.

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

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,10 +38,7 @@
3838
# 'Development Status :: 5 - Production/Stable'
3939
release_status = "Development Status :: 3 - Alpha"
4040
dependencies = [
41-
# NOTE: Maintainers, please do not require google-cloud-core>=2.x.x
42-
# Until this issue is closed
43-
# https://github.com/googleapis/google-cloud-python/issues/10566
44-
"google-cloud-core >= 1.4.4, < 3.0.0",
41+
"google-cloud-core >= 2.9.0, < 3.0.0",
4542
]
4643
extras = {}
4744

‎packages/google-cloud-dns/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-dns/tests/unit/test_client.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,9 @@
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, universe_domain="googleapis.com"
25+
)
2426

2527

2628
class TestClient(unittest.TestCase):
Lines changed: 224 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,224 @@
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 dns
32+
33+
DEFAULT_PROJECT_ID = "test-proj"
34+
DEFAULT_UNIVERSE = "googleapis.com"
35+
CUSTOM_UNIVERSE = "apis-tpclp.goog"
36+
37+
38+
class FakeScopedQuotaCredentials(
39+
auth_credentials.Scoped, auth_credentials.CredentialsWithQuotaProject
40+
):
41+
"""Fake Credentials supporting scopes, quota project, and universe_domain."""
42+
43+
def __init__(
44+
self,
45+
universe_domain: str = DEFAULT_UNIVERSE,
46+
quota_project_id: str | None = None,
47+
scopes: tuple[str, ...] | None = None,
48+
) -> None:
49+
super().__init__()
50+
self._universe_domain = universe_domain
51+
self._quota_project_id = quota_project_id
52+
self._scopes = scopes
53+
self.token = "fake-token"
54+
55+
@property
56+
def universe_domain(self) -> str:
57+
return self._universe_domain
58+
59+
@property
60+
def requires_scopes(self) -> bool:
61+
return False
62+
63+
def refresh(self, request: Any) -> None: # pragma: NO COVER
64+
self.token = "fake-token"
65+
66+
def with_scopes(
67+
self, scopes: Any, default_scopes: Any = None
68+
) -> FakeScopedQuotaCredentials: # pragma: NO COVER
69+
return FakeScopedQuotaCredentials(
70+
universe_domain=self._universe_domain,
71+
quota_project_id=self._quota_project_id,
72+
scopes=tuple(scopes or default_scopes or ()),
73+
)
74+
75+
def with_quota_project(
76+
self, quota_project_id: str | None
77+
) -> FakeScopedQuotaCredentials: # pragma: NO COVER
78+
return FakeScopedQuotaCredentials(
79+
universe_domain=self._universe_domain,
80+
quota_project_id=quota_project_id,
81+
scopes=self._scopes,
82+
)
83+
84+
85+
def _is_googleapis_host(url: str) -> bool:
86+
host = urlparse(url).hostname
87+
return bool(host and (host == "googleapis.com" or host.endswith(".googleapis.com")))
88+
89+
90+
@pytest.fixture
91+
def captured_requests(monkeypatch: pytest.MonkeyPatch) -> Iterator[list[str]]:
92+
seen_urls: list[str] = []
93+
94+
def _guarded_send(self, request, *args, **kwargs):
95+
if _is_googleapis_host(request.url): # pragma: NO COVER
96+
raise ConnectionRefusedError(
97+
f"Unexpected googleapis.com call: {request.url}"
98+
)
99+
seen_urls.append(request.url)
100+
resp = requests.Response()
101+
resp.status_code = 200
102+
resp._content = b'{"quota": {"managedZones": 10}}'
103+
resp.headers = {"content-type": "application/json"}
104+
resp.encoding = "utf-8"
105+
return resp
106+
107+
monkeypatch.setattr(requests.Session, "send", _guarded_send)
108+
yield seen_urls
109+
110+
111+
class TestDnsUniverseDomain:
112+
@pytest.mark.parametrize(
113+
"client_options",
114+
[
115+
{"universe_domain": CUSTOM_UNIVERSE},
116+
MappingProxyType({"universe_domain": CUSTOM_UNIVERSE}),
117+
client_options_lib.ClientOptions(universe_domain=CUSTOM_UNIVERSE),
118+
],
119+
)
120+
def test_custom_universe_routing_and_default_host(
121+
self, captured_requests: list[str], client_options: Any
122+
) -> None:
123+
creds = FakeScopedQuotaCredentials(CUSTOM_UNIVERSE)
124+
client = dns.Client(
125+
project=DEFAULT_PROJECT_ID,
126+
credentials=creds,
127+
client_options=client_options,
128+
)
129+
130+
assert client.universe_domain == CUSTOM_UNIVERSE
131+
assert client._connection.API_BASE_URL == f"https://dns.{CUSTOM_UNIVERSE}"
132+
assert client.quotas() == {"managedZones": 10}
133+
assert captured_requests == [
134+
f"https://dns.{CUSTOM_UNIVERSE}/dns/v1/projects/{DEFAULT_PROJECT_ID}?prettyPrint=false"
135+
]
136+
assert client._http._default_host == f"dns.{CUSTOM_UNIVERSE}"
137+
138+
def test_env_var_universe_with_adc(
139+
self, monkeypatch: pytest.MonkeyPatch, captured_requests: list[str]
140+
) -> None:
141+
monkeypatch.setenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", CUSTOM_UNIVERSE)
142+
adc_creds = FakeScopedQuotaCredentials(CUSTOM_UNIVERSE)
143+
144+
with mock.patch.object(
145+
google.auth,
146+
"default",
147+
autospec=True,
148+
return_value=(adc_creds, DEFAULT_PROJECT_ID),
149+
):
150+
client = dns.Client(project=DEFAULT_PROJECT_ID)
151+
152+
assert client.universe_domain == CUSTOM_UNIVERSE
153+
assert client._connection.API_BASE_URL == f"https://dns.{CUSTOM_UNIVERSE}"
154+
assert client.quotas() == {"managedZones": 10}
155+
assert len(captured_requests) == 1
156+
157+
def test_universe_validation_and_empty_errors(
158+
self, monkeypatch: pytest.MonkeyPatch
159+
) -> None:
160+
with pytest.raises(UniverseMismatchError):
161+
dns.Client(
162+
project=DEFAULT_PROJECT_ID,
163+
credentials=FakeScopedQuotaCredentials(DEFAULT_UNIVERSE),
164+
client_options={"universe_domain": CUSTOM_UNIVERSE},
165+
)
166+
167+
with pytest.raises(UniverseMismatchError):
168+
dns.Client(
169+
project=DEFAULT_PROJECT_ID,
170+
credentials=FakeScopedQuotaCredentials(CUSTOM_UNIVERSE),
171+
)
172+
173+
with pytest.raises(EmptyUniverseError):
174+
dns.Client(
175+
project=DEFAULT_PROJECT_ID,
176+
credentials=auth_credentials.AnonymousCredentials(),
177+
client_options={"universe_domain": ""},
178+
)
179+
180+
monkeypatch.setenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", "")
181+
with pytest.raises(EmptyUniverseError):
182+
dns.Client(
183+
project=DEFAULT_PROJECT_ID,
184+
credentials=auth_credentials.AnonymousCredentials(),
185+
)
186+
187+
def test_anonymous_credentials_and_api_endpoint_precedence(
188+
self, monkeypatch: pytest.MonkeyPatch, captured_requests: list[str]
189+
) -> None:
190+
monkeypatch.setenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", "env.goog")
191+
anon_client = dns.Client(
192+
project=DEFAULT_PROJECT_ID,
193+
credentials=auth_credentials.AnonymousCredentials(),
194+
client_options={
195+
"universe_domain": CUSTOM_UNIVERSE,
196+
"api_endpoint": "https://custom-dns.internal:8443",
197+
},
198+
)
199+
assert anon_client.universe_domain == CUSTOM_UNIVERSE
200+
assert (
201+
anon_client._connection.API_BASE_URL == "https://custom-dns.internal:8443"
202+
)
203+
assert anon_client.quotas() == {"managedZones": 10}
204+
assert captured_requests == [
205+
f"https://custom-dns.internal:8443/dns/v1/projects/{DEFAULT_PROJECT_ID}?prettyPrint=false"
206+
]
207+
208+
def test_mtls_always_gating(self, monkeypatch: pytest.MonkeyPatch) -> None:
209+
monkeypatch.setenv("GOOGLE_API_USE_MTLS_ENDPOINT", "always")
210+
211+
tpc_client = dns.Client(
212+
project=DEFAULT_PROJECT_ID,
213+
credentials=FakeScopedQuotaCredentials(CUSTOM_UNIVERSE),
214+
client_options={"universe_domain": CUSTOM_UNIVERSE},
215+
)
216+
with pytest.raises(MutualTLSChannelError):
217+
tpc_client._connection.get_api_base_url_for_mtls()
218+
219+
gdu_client = dns.Client(
220+
project=DEFAULT_PROJECT_ID,
221+
credentials=FakeScopedQuotaCredentials(DEFAULT_UNIVERSE),
222+
)
223+
with pytest.raises(ValueError, match="mTLS endpoint is not available"):
224+
gdu_client._connection.get_api_base_url_for_mtls()

0 commit comments

Comments
 (0)