Skip to content
Open
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 @@ -16,9 +16,12 @@

from __future__ import annotations

import copy
import datetime
import json
import os
import re
from collections.abc import Mapping
from typing import (
TYPE_CHECKING,
Any,
Expand All @@ -34,9 +37,12 @@
)

import grpc # type: ignore
from google.api_core import gapic_v1
from google.api_core import client_options as client_options_lib
from google.api_core import gapic_v1, universe
from google.api_core import retry as retries
from google.api_core.datetime_helpers import DatetimeWithNanoseconds
from google.auth import compute_engine
from google.auth.credentials import AnonymousCredentials
from google.cloud._helpers import _datetime_to_pb_timestamp # type: ignore
from google.protobuf import struct_pb2
from google.protobuf.timestamp_pb2 import Timestamp # type: ignore
Expand Down Expand Up @@ -1426,3 +1432,95 @@ def _get_document_from_bundle(
return bundled_doc.snapshot
else:
return None


try:
# google.auth.aio was added in google-auth 2.28.0; older supported versions
# (down to 2.14.1) only provide synchronous AnonymousCredentials.
from google.auth.aio import credentials as _aio_credentials

_ANONYMOUS_CREDENTIAL_TYPES: tuple[type[Any], ...] = (
AnonymousCredentials,
_aio_credentials.AnonymousCredentials,
)
except ImportError: # pragma: NO COVER
_ANONYMOUS_CREDENTIAL_TYPES = (AnonymousCredentials,)


# TODO(universe-domain): Replace with
# google.api_core.universe.resolve_client_universe once minimum
# google-api-core version exceeds 2.44.0.
def _resolve_client_universe(
client_options: client_options_lib.ClientOptions | Mapping[str, Any] | None = None,
) -> str:
"""Resolve a client's universe domain from ``client_options`` or the environment."""
if client_options is None:
options_universe = None
elif isinstance(client_options, Mapping):
options_universe = client_options.get("universe_domain")
elif isinstance(client_options, client_options_lib.ClientOptions):
options_universe = client_options.universe_domain
else:
raise TypeError(
"client_options must be a ClientOptions instance, Mapping, or None; "
f"got {type(client_options).__name__}"
)
# Strip before determine_domain so surrounding whitespace is removed from
# non-empty values even on google-api-core==2.28.0.
env_universe = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN")
return universe.determine_domain(
options_universe.strip()
if isinstance(options_universe, str)
else options_universe,
env_universe.strip() if isinstance(env_universe, str) else env_universe,
)


# TODO(universe-domain): Replace with
# google.api_core.universe.validate_credentials_universe once minimum
# google-api-core version exceeds 2.44.0.
def _validate_credentials_universe(client_universe: str, credentials: Any) -> None:
Comment thread
ohmayr marked this conversation as resolved.
Resolved
"""Validate that resolved client credentials match ``client_universe``."""
if credentials is None or isinstance(credentials, _ANONYMOUS_CREDENTIAL_TYPES):
return
# Avoid synchronous GCE metadata server HTTP calls when
# compute_engine.Credentials hasn't resolved its universe yet.
if isinstance(credentials, compute_engine.Credentials) and not getattr(
credentials, "_universe_domain_cached", False
):
return
universe.compare_domains(client_universe, credentials)


def _inherit_universe_in_client_options(
parent_universe: str,
client_options: Any = None,
) -> Any:
"""Return client options carrying ``parent_universe`` without mutating input.

Clears ``credentials_file`` and ``api_key`` because credentials have
already been resolved onto the parent client or transport.
"""
if client_options is None:
return client_options_lib.ClientOptions(universe_domain=parent_universe)
if isinstance(client_options, Mapping):
opts = client_options_lib.from_dict(client_options)
opts.universe_domain = parent_universe
opts.credentials_file = None
opts.api_key = None
return opts
if isinstance(client_options, client_options_lib.ClientOptions):
needs_universe = client_options.universe_domain != parent_universe
needs_clear = (
client_options.credentials_file is not None
or client_options.api_key is not None
)
if needs_universe or needs_clear:
opts = copy.copy(client_options)
opts.universe_domain = parent_universe
opts.credentials_file = None
opts.api_key = None
return opts
return client_options
# Preserve non-ClientOptions objects (such as unittest.mock sentinels in tests).
return client_options
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
from google.api_core import gapic_v1
from google.api_core import retry_async as retries

from google.cloud.firestore_v1 import _helpers
from google.cloud.firestore_v1.async_batch import AsyncWriteBatch
from google.cloud.firestore_v1.async_collection import AsyncCollectionReference
from google.cloud.firestore_v1.async_document import (
Expand Down Expand Up @@ -118,12 +119,16 @@ def _to_sync_copy(self):
from google.cloud.firestore_v1.client import Client

if not getattr(self, "_sync_copy", None):
client_options = _helpers._inherit_universe_in_client_options(
self._universe_domain,
self._client_options,
)
self._sync_copy = Client(
project=self.project,
credentials=self._credentials,
database=self._database,
client_info=self._client_info,
client_options=self._client_options,
client_options=client_options,
)
return self._sync_copy

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
import google.api_core.path_template
import grpc # type: ignore
from google.api_core import retry as retries
from google.api_core import universe
from google.api_core.gapic_v1 import client_info
from google.auth.credentials import AnonymousCredentials
from google.cloud.client import ClientWithProject # type: ignore
Expand Down Expand Up @@ -164,6 +165,12 @@ def __init__(
)
self._client_options = client_options

self._universe_domain = _helpers._resolve_client_universe(self._client_options)
if self._emulator_host is None:
_helpers._validate_credentials_universe(
self._universe_domain, self._credentials
)

self._database = database

def _firestore_api_helper(self, transport, client_class, client_module) -> Any:
Expand All @@ -178,6 +185,9 @@ def _firestore_api_helper(self, transport, client_class, client_module) -> Any:
if self._emulator_host is not None:
channel = self._emulator_channel(transport)
else:
_helpers._validate_credentials_universe(
self._universe_domain, self._credentials
)
channel = transport.create_channel(
self._target,
credentials=self._credentials,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just below this block (base_client.py#L199-L201), self._firestore_api_internal is lazily initialized with client_options=self._client_options.

If the client was initialized via GOOGLE_CLOUD_UNIVERSE_DOMAIN with client_options=None (or without universe_domain) and GOOGLE_CLOUD_UNIVERSE_DOMAIN is unset or modified before the first RPC, FirestoreClient.__init__ re-reads os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") (services/firestore/client.py#L490-L500), causing client._firestore_api.universe_domain to drift back to "googleapis.com" (or raising EmptyUniverseError if set to "").

Repro test (fails on this branch with AssertionError: assert 'googleapis.com' == 'example.com' for {} and EmptyUniverseError for ""):

@pytest.mark.parametrize(
    "later_env",
    [
        {},
        {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": ""},
    ],
)
def test_client_firestore_api_preserves_universe_domain_after_env_change(later_env):
    from google.cloud.firestore_v1.client import Client

    creds = _make_credentials()
    creds.universe_domain = "example.com"
    with mock.patch.dict(
        "os.environ", {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "example.com"}, clear=True
    ):
        client = Client(project=PROJECT, credentials=creds)

    with mock.patch.dict("os.environ", later_env, clear=True):
        with mock.patch(
            "google.cloud.firestore_v1.services.firestore.transports.grpc."
            "FirestoreGrpcTransport.create_channel",
            return_value=mock.create_autospec(grpc.Channel, instance=True),
        ):
            api = client._firestore_api

    assert api.universe_domain == "example.com"

Propagating self._universe_domain onto a copied ClientOptions here (the same guard you added in AsyncClient._to_sync_copy(), leaving non-ClientOptions objects untouched for existing mock tests) resolves this.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated _firestore_api_helper in 3a7ec09 to pass client_options through the shared _inherit_universe_in_client_options helper so the lazy GAPIC client gets self._universe_domain and stays pinned if GOOGLE_CLOUD_UNIVERSE_DOMAIN changes later.

Expand All @@ -186,8 +196,12 @@ def _firestore_api_helper(self, transport, client_class, client_module) -> Any:

self._transport = transport(host=self._target, channel=channel)

client_options = _helpers._inherit_universe_in_client_options(
self._universe_domain,
self._client_options,
)
self._firestore_api_internal = client_class(
transport=self._transport, client_options=self._client_options
transport=self._transport, client_options=client_options
)
client_module._client_info = self._client_info

Expand Down Expand Up @@ -233,9 +247,18 @@ def _target_helper(self, client_class) -> str:
return self._emulator_host
elif self._client_options and self._client_options.api_endpoint:
return self._client_options.api_endpoint
elif self._universe_domain != universe.DEFAULT_UNIVERSE:
return client_class._DEFAULT_ENDPOINT_TEMPLATE.format(
UNIVERSE_DOMAIN=self._universe_domain
)
else:
return client_class.DEFAULT_ENDPOINT

@property
def universe_domain(self) -> str:
"""The universe domain used by the client."""
return self._universe_domain

@property
def _target(self):
"""Return the target (where the API is).
Expand Down
21 changes: 21 additions & 0 deletions packages/google-cloud-firestore/tests/unit/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# 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_domain_env(monkeypatch):
"""Isolate unit tests from workstation GOOGLE_CLOUD_UNIVERSE_DOMAIN."""
monkeypatch.delenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", raising=False)
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@
def make_test_credentials() -> google.auth.credentials.Credentials: # type: ignore
import google.auth.credentials # type: ignore

return mock.Mock(spec=google.auth.credentials.Credentials)
return mock.Mock(
spec=google.auth.credentials.Credentials, universe_domain="googleapis.com"
)


def make_client(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,9 @@ async def test_as_context_mgr_w_error():
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"
)


def _make_client(project="seventy-nine"):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,88 @@ def test_asyncclient_sync_copy():
assert client._to_sync_copy() is client._to_sync_copy()


@pytest.mark.parametrize(
"client_options,expected_target",
[
(None, "firestore.tpc.test"),
({}, "firestore.tpc.test"),
("empty_client_options", "firestore.tpc.test"),
({"api_endpoint": "custom.endpoint.test:443"}, "custom.endpoint.test:443"),
({"universe_domain": "tpc.test"}, "firestore.tpc.test"),
],
)
def test_asyncclient_sync_copy_preserves_universe_domain(
client_options, expected_target
):
from google.api_core.client_options import ClientOptions

if client_options == "empty_client_options":
client_options = ClientOptions()

creds = _make_credentials()
creds.universe_domain = "tpc.test"
with mock.patch.dict(
"os.environ", {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "tpc.test"}, clear=True
):
async_client = _make_async_client(
project=PROJECT, credentials=creds, client_options=client_options
)

with mock.patch.dict("os.environ", {}, clear=True):
sync_client = async_client._to_sync_copy()

assert sync_client.universe_domain == "tpc.test"
assert sync_client._target == expected_target
if isinstance(client_options, ClientOptions) or client_options == {
"api_endpoint": "custom.endpoint.test:443"
}:
assert async_client._client_options.universe_domain is None


@pytest.mark.parametrize(
"universe_opt",
[None, "tpc.test"],
)
def test_asyncclient_sync_copy_clears_credentials_file(universe_opt):
creds = _make_credentials()
creds.universe_domain = "tpc.test"
options = {"credentials_file": "/tmp/fake-creds.json"}
if universe_opt is not None:
options["universe_domain"] = universe_opt

with mock.patch(
"google.auth.load_credentials_from_file", return_value=(creds, PROJECT)
):
with mock.patch.dict(
"os.environ", {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "tpc.test"}, clear=True
):
async_client = _make_async_client(project=PROJECT, client_options=options)

with mock.patch.dict("os.environ", {}, clear=True):
sync_client = async_client._to_sync_copy()

assert sync_client.universe_domain == "tpc.test"
assert sync_client._credentials is async_client._credentials
assert async_client._client_options.credentials_file == "/tmp/fake-creds.json"


def test_asyncclient_sync_copy_clears_api_key():
pytest.importorskip("google.auth.api_key")
with mock.patch.dict("os.environ", {}, clear=True):
async_client = _make_async_client(
project=PROJECT,
client_options={
"api_key": "fake-api-key",
"universe_domain": "googleapis.com",
},
)
sync_client = async_client._to_sync_copy()

assert sync_client.universe_domain == "googleapis.com"
assert sync_client._credentials is async_client._credentials
assert async_client._client_options.api_key == "fake-api-key"


@pytest.mark.asyncio
async def test_asyncclient_recursive_delete():
from google.cloud.firestore_v1.types import document, firestore
Expand Down Expand Up @@ -577,7 +659,9 @@ def test_asyncclient_pipeline():
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"
)


def _make_batch_response(**kwargs):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -926,7 +926,9 @@ def test_async_transactional_factory():
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"
)


def _make_client(project="feral-tom-cat"):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,9 @@ def _value_pb(**kwargs):
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"
)


def _make_client(project="seventy-nine"):
Expand Down
Loading
Loading