Skip to content
Merged
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
73 changes: 23 additions & 50 deletions packages/google-api-core/google/api_core/grpc_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@
import collections
import functools
import os
import re
import urllib.parse
import warnings
from typing import (
Callable,
Expand All @@ -43,10 +41,6 @@
from google.api_core._feature_gating_helpers import _strtobool

_DIRECT_PATH_INTERCONNECT_ENV = "GOOGLE_CLOUD_ENABLE_DIRECT_PATH_XDS_OVER_INTERCONNECT"
_GOOGLEAPIS_HOST_PATTERN = re.compile(

@chalmerlowe chalmerlowe Nov 25, 2026 •

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.

Note

NOTE TO REVIEWERS:
Several items from this file are moved to the universe.py file due to their close association with trying to manage universe_domain issues.

rf"^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)*{re.escape(universe.DEFAULT_UNIVERSE)}$",
re.IGNORECASE,
)


def _resolve_direct_path_interconnect(
Expand Down Expand Up @@ -85,24 +79,16 @@ def _resolve_direct_path_interconnect(

def _extract_target_host(target: str) -> str:
"""Extracts the host from a target URI or address."""
stripped_target = target
for prefix in ("google-c2p:///", "dns:///", "https://", "http://"):
if target.startswith(prefix):
stripped_target = target.removeprefix(prefix)
break
try:
return urllib.parse.urlsplit(f"//{stripped_target}").hostname or target
except ValueError:
return target
parsed = universe._parse_target(target)
return parsed.host if parsed is not None else target


def _is_googleapis_host(target: str) -> bool:
"""Returns True if ``target`` resolves to a ``googleapis.com`` host."""
return (
"@" not in target
and "#" not in target
and bool(_GOOGLEAPIS_HOST_PATTERN.fullmatch(_extract_target_host(target)))
)
def _is_direct_path_googleapis_target(target: str) -> bool:
"""Returns True if ``target`` is a DirectPath-eligible ``googleapis.com`` host."""
parsed = universe._parse_target(target)
if parsed is None or parsed.authority:
return False
return bool(universe._GOOGLEAPIS_HOST_PATTERN.fullmatch(parsed.host))


def _extract_direct_path_authority(target: str) -> Optional[str]:
Expand Down Expand Up @@ -435,7 +421,7 @@ def _setup_direct_path_and_credentials(
# target host or the resolved credential universe_domain is non-GDU.
if attempt_direct_path or use_dp_interconnect:
if not (
_is_googleapis_host(target)
_is_direct_path_googleapis_target(target)
and getattr(credentials, "universe_domain", universe.DEFAULT_UNIVERSE)
== universe.DEFAULT_UNIVERSE
):
Expand Down Expand Up @@ -475,7 +461,7 @@ def _setup_direct_path_and_credentials(
target,
attempt_direct_path_xds_over_interconnect=use_dp_interconnect,
)
elif not target.startswith("google-c2p:///"):
elif not target.lower().startswith("google-c2p:///"):
clean_host = _extract_target_host(target)
if clean_host.endswith("-direct.googleapis.com") and len(clean_host) > len(
"-direct.googleapis.com"
Expand Down Expand Up @@ -614,34 +600,21 @@ def _modify_target_for_direct_path(
original target may already denote Direct Path.
"""

# Strip standard URI scheme prefixes ("dns:///", "https://", "http://") if
# `attempt_direct_path` is enabled, as the Direct Path prefix `google-c2p:///`
# will be used instead.
for scheme_prefix in ("dns:///", "https://", "http://"):
if target.startswith(scheme_prefix):
target = target.removeprefix(scheme_prefix)
break

direct_path_separator = ":///"
if direct_path_separator not in target:
if "?" in target:
host_part, query_part = target.split("?", 1)
target_without_port = host_part.split("/")[0].split(":")[0]
target = (
f"google-c2p{direct_path_separator}{target_without_port}?{query_part}"
)
else:
target_without_port = target.split("/")[0].split(":")[0]
# Modify the target to use Direct Path by adding the `google-c2p:///` prefix
target = f"google-c2p{direct_path_separator}{target_without_port}"
parsed = universe._parse_target(target)
if parsed is None or parsed.authority:
return target

if attempt_direct_path_xds_over_interconnect and target.startswith(
"google-c2p:///"
query = parsed.query
if attempt_direct_path_xds_over_interconnect and "force-xds" not in query.split(
"&"
):
if "force-xds" not in target:
separator = "&" if "?" in target else "?"
target = f"{target}{separator}force-xds"
return target
query = f"{query}&force-xds" if query else "force-xds"

return (
f"google-c2p:///{parsed.host}?{query}"
if query
else f"google-c2p:///{parsed.host}"
)


def apply_channel_interceptors(
Expand Down
199 changes: 196 additions & 3 deletions packages/google-api-core/google/api_core/universe.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,48 @@

"""Helpers for universe domain."""

from typing import Any, Optional
from urllib.parse import urlparse, urlunparse

import os
import re
from collections.abc import Mapping
from typing import TYPE_CHECKING, Any, NamedTuple, Optional, Union
from urllib.parse import urlparse, urlsplit, urlunparse

from google.auth import compute_engine
from google.auth import credentials as auth_credentials
from google.auth.exceptions import MutualTLSChannelError # type: ignore

from google.api_core import client_options as client_options_lib

if TYPE_CHECKING: # pragma: NO COVER
from google.auth.aio import credentials as aio_credentials

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], ...] = (
auth_credentials.AnonymousCredentials,
_aio_credentials.AnonymousCredentials,
)
except ImportError: # pragma: NO COVER
_ANONYMOUS_CREDENTIAL_TYPES = (auth_credentials.AnonymousCredentials,)

DEFAULT_UNIVERSE = "googleapis.com"
UNIVERSE_DOMAIN_ENV = "GOOGLE_CLOUD_UNIVERSE_DOMAIN"
_GOOGLEAPIS_HOST_PATTERN = re.compile(
rf"^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)*{re.escape(DEFAULT_UNIVERSE)}$",
re.IGNORECASE,
)


class _ParsedTarget(NamedTuple):
"""Normalized components of an HTTP(S) URL or gRPC target string."""

scheme: str
authority: str
host: str
query: str


class EmptyUniverseError(ValueError):
Expand Down Expand Up @@ -197,3 +233,160 @@ def get_api_endpoint(
return default_mtls_endpoint
else:
return default_endpoint_template.format(UNIVERSE_DOMAIN=universe_domain)


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.

Follows AIP-4113 precedence: ``client_options.universe_domain``, then
``GOOGLE_CLOUD_UNIVERSE_DOMAIN``, then ``"googleapis.com"``.

Args:
client_options (Optional[Union[google.api_core.client_options.ClientOptions, Mapping[str, Any]]]):
Optional ``ClientOptions`` instance or mapping passed to
``Client.__init__``. If ``None``, falls back to
``GOOGLE_CLOUD_UNIVERSE_DOMAIN`` and then ``"googleapis.com"``.

Returns:
str: The resolved universe domain string.

Raises:
EmptyUniverseError: If the configured universe domain is an empty string.
TypeError: If ``client_options`` is not a ``ClientOptions`` instance,
``Mapping``, or ``None``.
"""
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__}"
)
return determine_domain(
options_universe,
os.getenv(UNIVERSE_DOMAIN_ENV),
)


def validate_credentials_universe(
client_universe: str,
credentials: Union[
auth_credentials.Credentials, "aio_credentials.Credentials", None
],
) -> None:
"""Validate that resolved client credentials match ``client_universe``.

Call on ``self._credentials`` after ``super().__init__()`` or Application
Default Credentials resolution rather than on the raw constructor
``credentials`` argument (which is ``None`` before ADC loads), and never
inside ``Credentials.before_request()``. Exempts ``None``, synchronous and
asynchronous ``AnonymousCredentials``, and ``compute_engine.Credentials``
whose universe domain is not yet cached in memory (avoiding synchronous
Metadata Server HTTP requests during client initialization).

Args:
client_universe (str): Resolved universe domain of the client.
credentials (Optional[Union[google.auth.credentials.Credentials, google.auth.aio.credentials.Credentials]]):
Resolved credentials bound to the client, or ``None`` (in which case
validation is skipped).

Raises:
UniverseMismatchError: If ``credentials`` has an in-memory universe
domain configured for a different universe than ``client_universe``.
"""
if credentials is None or isinstance(credentials, _ANONYMOUS_CREDENTIAL_TYPES):
return
if isinstance(credentials, compute_engine.Credentials) and not getattr(
credentials, "_universe_domain_cached", False
):
return
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.

compare_domains sometimes makes a network request to the metadata server to find the credential's universe_domain. My understanding is that this was showing up noisily in logs, so compare_domains was currently removed from use (there's an internal bug I'll send you over chat)

We may want to have this auto-pass for now, with a TODO explaining the situation. Or skip validation for credential types that need to talk to MDS. Or we could leave this level of validation out of scope for now

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.

It looks like google.auth.compute_engine.Credentials is the only one with this problem, so maybe we should just handle that as a special case with a comment here

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.

@daniel-sanche
Great catch! Checked across google-auth and yes, compute_engine.Credentials (credentials.py:249-264) is the one credential class whose .universe_domain property triggers a Metadata Server HTTP lookup when _universe_domain_cached is False.

Went with your middle option in cef786d723c: validate_credentials_universe now skips uncached compute_engine.Credentials (avoiding MDS network requests during client init) while still validating all in-memory credentials:

  • service_account
  • external_account
  • jwt
  • oauth2
  • explicitly configured compute_engine.Credentials

That also gives handwritten veneers (like storage/grpc_client.py, which currently calls raw compare_domains) a single shared MDS-safe helper to call.

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.

Sounds good, thanks!



def _parse_target(url_or_target: str) -> _ParsedTarget | None:
"""Parse an HTTP(S) URL or gRPC target into normalized components.

Uses :func:`urllib.parse.urlsplit` for case-insensitive RFC 3986 scheme and
port validation while normalizing scheme-less ``host:port`` targets and gRPC
path-style schemes (``dns:`` and ``google-c2p:///``). Rejects userinfo
(``@`` in authority/netloc) while allowing ``@`` in HTTP(S) paths and
queries (such as service account email endpoints). Returns ``None`` for
empty, non-string, userinfo- or fragment-containing, unknown-scheme, or
malformed inputs.
"""
if not isinstance(url_or_target, str) or not url_or_target or "#" in url_or_target:
return None

try:
raw = urlsplit(url_or_target)
if raw.scheme in ("http", "https"):
if (
not url_or_target[len(raw.scheme) :].startswith("://")
or "@" in raw.netloc
):
return None
_ = raw.port
if not raw.hostname:
return None
return _ParsedTarget(raw.scheme, "", raw.hostname, raw.query)

if raw.scheme == "google-c2p":
if not url_or_target[len(raw.scheme) :].startswith(":///"):
return None
endpoint = raw.path.removeprefix("/")
authority = ""
query = raw.query
elif raw.scheme == "dns":
_ = raw.port
endpoint = raw.path.removeprefix("/")
authority = raw.netloc
query = raw.query
elif "://" in url_or_target:
return None
else:
endpoint = url_or_target
authority = ""
query = ""

inner = urlsplit(f"//{endpoint}")
_ = inner.port
if "@" in authority or "@" in inner.netloc or inner.path or not inner.hostname:
return None
return _ParsedTarget(
raw.scheme if raw.scheme in ("google-c2p", "dns") else "",
authority,
inner.hostname,
query or inner.query,
)
except ValueError:
return None


def is_googleapis_host(url_or_target: str) -> bool:
Comment thread
daniel-sanche marked this conversation as resolved.
Resolved
Comment thread
daniel-sanche marked this conversation as resolved.
Resolved
"""Return True if an HTTP(S) URL or gRPC target resolves to ``googleapis.com``.

Matches ``googleapis.com`` and ``*.googleapis.com`` across ``https://`` URLs,
``host:port`` gRPC targets, ``google-c2p:///`` DirectPath targets, and
``dns:///`` or ``dns://authority/`` targets while rejecting userinfo in the
authority/netloc (``@``), fragments (``#``), unknown schemes, malformed
ports, and spoofed suffixes. Intended for gating default-universe-only
features (such as DirectPath, mTLS endpoint switching, or built-in Cloud
Monitoring metrics); do not use to test equality against a single default
service host because regional (``*.rep.googleapis.com``) and Private Service
Connect (``*.p.googleapis.com``) endpoints also match ``*.googleapis.com``.

Args:
url_or_target (str): HTTP(S) URL or gRPC target string to inspect.

Returns:
bool: True if the target hostname is ``googleapis.com`` or a valid
subdomain of ``googleapis.com``; False otherwise.
"""
parsed = _parse_target(url_or_target)
return bool(parsed and _GOOGLEAPIS_HOST_PATTERN.fullmatch(parsed.host))
8 changes: 8 additions & 0 deletions packages/google-api-core/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@

import pytest

from google.api_core import universe


@pytest.fixture(scope="session", autouse=True)
def mock_mtls_env():
Expand All @@ -34,6 +36,12 @@ def mock_mtls_env():
yield


@pytest.fixture(autouse=True)
def clean_universe_env(monkeypatch):
"""Autouse fixture to isolate unit tests from workstation GOOGLE_CLOUD_UNIVERSE_DOMAIN."""
monkeypatch.delenv(universe.UNIVERSE_DOMAIN_ENV, raising=False)


@pytest.fixture
def mock_otel(monkeypatch):
"""Provides a mocked OpenTelemetry environment with tracing enabled."""
Expand Down
Loading
Loading