Skip to content

fix(firestore): resolve universe_domain and validate credentials - #19252

Open
ohmayr wants to merge 6 commits into
mainfrom
smallpr/b-588887079-firestore-universe-domain
Open

ohmayr wants to merge 6 commits into
mainfrom
smallpr/b-588887079-firestore-universe-domain

Conversation

@ohmayr

@ohmayr ohmayr commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Context & Problem

Both synchronous Client and asynchronous AsyncClient in google-cloud-firestore ignored client_options.universe_domain and GOOGLE_CLOUD_UNIVERSE_DOMAIN, hardcoding firestore.googleapis.com and opening a gRPC channel without validating credential universe parity.

Summary of Changes

  • Resolve universe_domain in BaseClient.init via local _resolve_client_universe (mirroring google.api_core.universe.resolve_client_universe) and expose client.universe_domain.
  • Template non-default endpoints from client_class._DEFAULT_ENDPOINT_TEMPLATE in BaseClient._target_helper when FIRESTORE_EMULATOR_HOST and client_options.api_endpoint are unset.
  • Validate credential universe parity via _validate_credentials_universe in BaseClient.init and before transport.create_channel in _firestore_api_helper (exempting emulator mode, sync and async AnonymousCredentials, uncached compute_engine.Credentials, and unconfigured unittest.mock / mock.mock credentials while failing closed for real credentials with non-string universe_domain values).
  • Preserve the resolved universe_domain when AsyncClient._to_sync_copy() lazily creates its synchronous Client so later GOOGLE_CLOUD_UNIVERSE_DOMAIN changes cannot drift bulk_writer() or recursive_delete().
  • Add unit tests in test_base_client.py and test_async_client.py covering Client and AsyncClient universe resolution, endpoint precedence, empty universe errors, mismatch errors before channel creation, mutated credentials, _to_sync_copy() preservation, and exemptions.

Behavior Note

Callers in a non-default universe who previously set only client_options.api_endpoint without setting client_options.universe_domain or GOOGLE_CLOUD_UNIVERSE_DOMAIN will now receive UniverseMismatchError at client initialization. Set client_options.universe_domain or GOOGLE_CLOUD_UNIVERSE_DOMAIN when connecting to a non-default universe.

Why This Approach

Resolving universe_domain and validating credentials inside BaseClient fixes both sync Client and AsyncClient (including _to_sync_copy) in one place while keeping google-cloud-firestore's google-api-core >= 2.28.0 lower bound. We considered waiting for google.api_core.universe.validate_credentials_universe (> 2.44.0) or google-cloud-core (#19231), but mirroring _resolve_client_universe and _validate_credentials_universe locally with TODO(universe-domain) markers matches sibling PR #19251 and works immediately without bumping dependency floors.

Intentionally Out of Scope

  • Bumping google-api-core or google-cloud-core minimum versions in setup.py.
  • Changing generated GAPIC client code or re-enabling GAPIC _validate_universe_domain (tracked in b/349488459).
  • Modifying firestore_admin_v1, which is pure GAPIC and already handles universe_domain.

Verification

nox -s lint, mypy-3.14, unit-3.14, unit-3.10 (lower-bound constraints: google-api-core==2.28.0, google-auth==2.14.1, google-cloud-core==2.0.0), and cover (100% diff coverage) all passed locally.

Fixes: b/588887079

@gemini-code-assist gemini-code-assist Bot left a comment

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.

Code Review

This pull request introduces universe domain validation to the Firestore base client, ensuring that client credentials match the resolved universe domain. It adds the _validate_credentials_universe helper, updates client initialization and API helpers to perform validation, and adjusts endpoint targeting for non-default universes. Comprehensive unit tests have also been added. However, a critical bug was identified in _validate_credentials_universe where universe.compare_domains is called with the credentials object instead of the resolved cred_universe string, which will lead to an AttributeError at runtime.

@ohmayr ohmayr changed the title fix(firestore): respect universe_domain and validate credentials fix(firestore): resolve universe_domain and validate credentials Nov 27, 2026
Resolve universe_domain on BaseClient from client_options or
GOOGLE_CLOUD_UNIVERSE_DOMAIN, format the default endpoint template for
non-default universes, and validate credentials against the resolved
universe before opening a gRPC channel.

Fixes: b/588887079
@ohmayr
ohmayr force-pushed the smallpr/b-588887079-firestore-universe-domain branch from 3ae9f3d to 20a1ae2 Compare November 27, 2026 18:51
@ohmayr
ohmayr marked this pull request as ready for review December 2, 2026 20:24
@ohmayr
ohmayr requested a review from a team as a code owner December 2, 2026 20:24
@parthea parthea self-assigned this Dec 2, 2026

@parthea parthea left a comment

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.

Thanks for the clean fix covering both Client and AsyncClient while keeping the google-api-core==2.28.0 / google-auth==2.14.1 floors intact (nice catch on stripping whitespace before determine_domain for 2.28.0 compatibility, and on guarding uncached compute_engine.Credentials so initialization does not trigger metadata server calls). I left a few inline comments on aligning _validate_credentials_universe with google.api_core.universe.validate_credentials_universe (#19211), propagating self._universe_domain into lazy GAPIC initialization, clearing credentials_file/api_key in _to_sync_copy(), and closing a couple of test coverage gaps.

Comment on lines +1491 to +1500
# Skip unconfigured mock credentials while failing closed for real
# credentials with non-string values. TODO(universe-domain): set
# universe_domain on mock creds before swapping to validate_credentials_universe.
cred_universe = getattr(credentials, "universe_domain", universe.DEFAULT_UNIVERSE)
if any(
cls.__module__ in ("unittest.mock", "mock.mock")
for cls in type(cred_universe).__mro__
):
return
universe.compare_domains(client_universe, 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.

I recommend removing this unittest.mock / mock.mock check from production code and instead configuring universe_domain = "googleapis.com" on the mocked credentials in the unit tests (or using a lightweight concrete fake credentials class as in #19199):

  • It adds test-only logic to production code and reads credentials.universe_domain twice on real credentials (once here and again inside universe.compare_domains).
  • google.api_core.universe.validate_credentials_universe (feat(api_core): add shared universe_domain client and host helpers #19211) does not include a mock check, so keeping this here means the # TODO(universe-domain) replacement will not be a drop-in swap later.

There are only ~14 mock.Mock(spec=...) credential sites across packages/google-cloud-firestore/tests/unit/v1/ (mostly _make_credentials() helpers), so updating the tests directly should be straightforward.

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.

Removed the mock check from _validate_credentials_universe in 3a7ec09 so it matches google.api_core.universe.validate_credentials_universe directly, and set universe_domain="googleapis.com" on the mocked credentials across tests/unit/v1/.

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

Comment on lines 123 to 137
client_options = self._client_options
if not client_options:
client_options = client_options_lib.ClientOptions(
universe_domain=self._universe_domain
)
elif getattr(client_options, "universe_domain", None) is None:
client_options = copy.copy(client_options)
client_options.universe_domain = self._universe_domain
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,
)

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.

If AsyncClient was initialized with client_options={"credentials_file": ...} or {"api_key": ...}, google.cloud.client.Client.__init__ resolves self._credentials while self._client_options still retains credentials_file / api_key. Passing both credentials=self._credentials and client_options=client_options to Client(...) here then raises DuplicateCredentialArgs (including when client_options.universe_domain is already set and the elif branch does not copy client_options).

Repro test (fails on this branch with google.api_core.exceptions.DuplicateCredentialArgs: 'credentials' and 'client_options.credentials_file' are mutually exclusive., and similarly for api_key):

def test_asyncclient_sync_copy_with_credentials_file():
    from google.cloud.firestore_v1.async_client import AsyncClient

    creds = _make_credentials()
    creds.universe_domain = "example.com"
    with mock.patch.dict("os.environ", {}, clear=True):
        with mock.patch(
            "google.auth.load_credentials_from_file",
            return_value=(creds, PROJECT),
        ):
            async_client = AsyncClient(
                project=PROJECT,
                client_options={
                    "credentials_file": "/fake/service-account.json",
                    "universe_domain": "example.com",
                },
            )
        sync_client = async_client._to_sync_copy()

    assert sync_client.universe_domain == "example.com"
    assert sync_client._target == "firestore.example.com"

Copying client_options and clearing credentials_file = None and api_key = None whenever present (matching _inherit_universe_in_client_options(..., clear_credentials=True) in #19199) fixes this and can be shared with BaseClient._firestore_api_helper().

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 _to_sync_copy() in 3a7ec09 to use the same _inherit_universe_in_client_options helper, which copies ClientOptions and clears credentials_file and api_key without mutating self._client_options. Added unit tests covering both.

Comment on lines +490 to +514
def test_baseclient_universe_mismatch_raises_before_channel(
client_options, env_universe, cred_universe
):
from google.api_core import universe

from google.cloud.firestore_v1.async_client import AsyncClient
from google.cloud.firestore_v1.client import Client

credentials = _make_credentials()
credentials.universe_domain = cred_universe
env = {} if env_universe is None else {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": env_universe}

with mock.patch.dict("os.environ", env, clear=True):
with pytest.raises(universe.UniverseMismatchError):
Client(
project=PROJECT,
credentials=credentials,
client_options=client_options,
)
with pytest.raises(universe.UniverseMismatchError):
AsyncClient(
project=PROJECT,
credentials=credentials,
client_options=client_options,
)

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.

Two test suggestions:

  1. Env hermeticity (fails today when GOOGLE_CLOUD_UNIVERSE_DOMAIN is set in the shell): Without an autouse fixture clearing GOOGLE_CLOUD_UNIVERSE_DOMAIN in a unit conftest.py (as in fix(ndb): resolve universe_domain and validate credentials in Client #19251), existing tests that don't clear os.environ fail when the variable is set in the runner environment — for example:
    GOOGLE_CLOUD_UNIVERSE_DOMAIN=example.com pytest tests/unit/v1/test_base_client.py -k test_baseclient__target_helper_wo_client_options
    fails with AssertionError: assert <Mock name='mock._DEFAULT_ENDPOINT_TEMPLATE.format()'> == 'https://api.example.com/firestore'.
  2. Conformance / regression guards (these pass today on this branch, worth adding to lock in behavior):
    • An ADC (credentials=None, patching google.auth.default) mismatch test to confirm BaseClient.__init__ validates resolved self._credentials after super().__init__() rather than the raw constructor argument:
      def test_client_adc_universe_mismatch_raises():
          from google.api_core import universe
          from google.cloud.firestore_v1.client import Client
      
          adc_creds = _make_credentials()
          adc_creds.universe_domain = "example.com"
          with mock.patch.dict("os.environ", {}, clear=True):
              with mock.patch("google.auth.default", return_value=(adc_creds, PROJECT)):
                  with pytest.raises(universe.UniverseMismatchError):
                      Client(project=PROJECT)
    • Covering at least one mismatch with a concrete google.auth.credentials.Credentials subclass (in addition to mock.Mock(spec=...)) and asserting client.universe_domain is read-only (AttributeError on assignment), plus including an empty ClientOptions() case in test_asyncclient_sync_copy_preserves_universe_domain.

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.

Added tests/unit/conftest.py in 3a7ec09 to clear GOOGLE_CLOUD_UNIVERSE_DOMAIN for each test, plus tests for ADC mismatch, concrete Credentials subclass mismatch, read-only client.universe_domain, and empty ClientOptions() in _to_sync_copy().

Remove the unittest.mock guard from _validate_credentials_universe and
set universe_domain on mocked unit-test credentials, propagate
universe_domain via a shared _inherit_universe_in_client_options helper
in _firestore_api_helper and _to_sync_copy (clearing credentials_file
and api_key), and add conftest.py env cleanup plus regression tests.
@ohmayr

ohmayr commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

@parthea Addressed all four comments in 3a7ec09: removed the mock check from _validate_credentials_universe and updated the unit test mocks, added a shared _inherit_universe_in_client_options helper for both _firestore_api_helper and _to_sync_copy (propagating universe_domain and clearing credentials_file/api_key), and added conftest.py plus the requested regression tests.

FirestoreGrpcTransport.__init__ calls google.auth.default() when no
credentials are passed to the transport constructor, causing
test_baseclient__firestore_api_helper_propagates_universe_domain to fail
with DefaultCredentialsError in CI environments without ADC.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants