Repository navigation
Conversation
There was a problem hiding this comment.
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.
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
3ae9f3d to
20a1ae2
Compare
parthea
left a comment
There was a problem hiding this comment.
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.
| # 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) |
There was a problem hiding this comment.
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_domaintwice on real credentials (once here and again insideuniverse.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.
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| 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, | ||
| ) |
There was a problem hiding this comment.
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().
There was a problem hiding this comment.
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.
| 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, | ||
| ) |
There was a problem hiding this comment.
Two test suggestions:
- Env hermeticity (fails today when
GOOGLE_CLOUD_UNIVERSE_DOMAINis set in the shell): Without anautousefixture clearingGOOGLE_CLOUD_UNIVERSE_DOMAINin a unitconftest.py(as in fix(ndb): resolve universe_domain and validate credentials in Client #19251), existing tests that don't clearos.environfail when the variable is set in the runner environment — for example:fails withGOOGLE_CLOUD_UNIVERSE_DOMAIN=example.com pytest tests/unit/v1/test_base_client.py -k test_baseclient__target_helper_wo_client_options
AssertionError: assert <Mock name='mock._DEFAULT_ENDPOINT_TEMPLATE.format()'> == 'https://api.example.com/firestore'. - Conformance / regression guards (these pass today on this branch, worth adding to lock in behavior):
- An ADC (
credentials=None, patchinggoogle.auth.default) mismatch test to confirmBaseClient.__init__validates resolvedself._credentialsaftersuper().__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.Credentialssubclass (in addition tomock.Mock(spec=...)) and assertingclient.universe_domainis read-only (AttributeErroron assignment), plus including an emptyClientOptions()case intest_asyncclient_sync_copy_preserves_universe_domain.
- An ADC (
There was a problem hiding this comment.
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.
|
@parthea Addressed all four comments in 3a7ec09: removed the mock check from |
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.
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
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
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