|
| 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