blob: 52c85662591f8659c23b76d22bced78a00a20bb1 [file] [edit]
# 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.
"""Universe domain compatibility helpers.
Prefers ``google.api_core.universe.resolve_client_universe`` when available
(>= 2.45.0) and falls back to a local copy for older ``google-api-core``
releases.
"""
import collections.abc
import os
from google.api_core import client_options as client_options_lib
from google.auth import credentials as google_auth_credentials
GOOGLE_CLOUD_UNIVERSE_DOMAIN = "GOOGLE_CLOUD_UNIVERSE_DOMAIN"
DEFAULT_UNIVERSE = "googleapis.com"
class APICoreVersionError(ValueError):
def __init__(self):
message = (
"google-api-core >= 2.18.0 is required to use the universe domain feature."
)
super().__init__(message)
try:
from google.api_core import universe as api_core_universe
HAS_UNIVERSE = True
except ImportError:
api_core_universe = None
HAS_UNIVERSE = False
try:
from google.auth.aio import credentials as _aio_credentials
_ANONYMOUS_CREDENTIAL_TYPES = (
google_auth_credentials.AnonymousCredentials,
_aio_credentials.AnonymousCredentials,
)
except ImportError: # pragma: NO COVER
_ANONYMOUS_CREDENTIAL_TYPES = (google_auth_credentials.AnonymousCredentials,)
try:
from google.api_core.universe import resolve_client_universe
except ImportError:
# TODO(https://github.com/googleapis/google-cloud-python/issues/19297): Replace with
# google.api_core.universe.resolve_client_universe once minimum allowed
# google-api-core version exceeds 2.44.0.
def resolve_client_universe(client_options=None):
"""Resolve a client's universe domain from ``client_options`` or the environment."""
if client_options is None:
options_universe = None
elif isinstance(client_options, collections.abc.Mapping):
options_universe = client_options.get("universe_domain")
elif isinstance(client_options, client_options_lib.ClientOptions):
# Versions of google-api-core that predate universe domains (< 2.18.0)
# have no `universe_domain` attribute on ClientOptions.
options_universe = getattr(client_options, "universe_domain", None)
else:
raise TypeError(
"client_options must be a ClientOptions instance, Mapping, or None; "
f"got {type(client_options).__name__}"
)
# Strip before checking/determine_domain so surrounding whitespace is
# removed from non-empty values even on older google-api-core releases.
stripped_options = (
options_universe.strip()
if isinstance(options_universe, str)
else options_universe
)
env_universe = os.getenv(GOOGLE_CLOUD_UNIVERSE_DOMAIN)
stripped_env = (
env_universe.strip() if isinstance(env_universe, str) else env_universe
)
if not HAS_UNIVERSE:
# Older google-api-core (< 2.18.0) cannot route to non-default
# universes; fail before any request if a universe is configured.
if stripped_options is not None or (
stripped_env is not None and stripped_env != DEFAULT_UNIVERSE
):
raise APICoreVersionError
return None
return api_core_universe.determine_domain(
stripped_options,
stripped_env,
)
def check_api_core_compatible_with_credentials_universe(credentials):
"""Raise APICoreVersionError if credentials require universe support."""
if not HAS_UNIVERSE:
credentials_universe = getattr(credentials, "universe_domain", None)
if credentials_universe and credentials_universe != DEFAULT_UNIVERSE:
raise APICoreVersionError
def validate_request_credentials_universe(client_universe, credentials):
"""Validate credentials immediately before making a network request.
Unlike ``google.api_core.universe.validate_credentials_universe`` (which
skips uncached Compute Engine credentials to avoid metadata server calls
during offline client initialization), this validates uncached Compute
Engine credentials as well before the outbound request is sent.
"""
if not HAS_UNIVERSE:
# Without google.api_core.universe (< 2.18.0), the client can only
# target the default universe; reject non-default credentials.
check_api_core_compatible_with_credentials_universe(credentials)
return
if credentials is None or isinstance(credentials, _ANONYMOUS_CREDENTIAL_TYPES):
return
# Intentionally call compare_domains directly rather than
# google.api_core.universe.validate_credentials_universe so uncached
# Compute Engine credentials are checked before attaching a token.
api_core_universe.compare_domains(client_universe, credentials)