Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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__

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@

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

import google.api_core.client_options
from google.cloud.client import ClientWithProject

from google.cloud.runtimeconfig._http import Connection
Expand Down Expand Up @@ -53,7 +52,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",)
Expand All @@ -68,20 +68,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)
self._validate_universe_domain()
self._connection = Connection(self, client_info=client_info)

def config(self, config_name):
"""Factory constructor for config object.
Expand Down
5 changes: 1 addition & 4 deletions packages/google-cloud-runtimeconfig/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
22 changes: 22 additions & 0 deletions packages/google-cloud-runtimeconfig/tests/unit/conftest.py
Original file line number Diff line number Diff line change
@@ -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)
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
Original file line number Diff line number Diff line change
@@ -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()
Loading