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
11 changes: 10 additions & 1 deletion packages/google-cloud-core/google/cloud/_helpers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import calendar
import datetime
import http.client
import inspect
import os
import re
from threading import local as Local
Expand Down Expand Up @@ -545,8 +546,16 @@ def make_secure_channel(credentials, user_agent, host, extra_options=()):

user_agent_option = ("grpc.primary_user_agent", user_agent)
options = (user_agent_option,) + extra_options
channel_kwargs = {"options": options}
if (
"default_host"
in inspect.signature(
google.auth.transport.grpc.secure_authorized_channel
).parameters
):
channel_kwargs["default_host"] = host
return google.auth.transport.grpc.secure_authorized_channel(
credentials, http_request, target, options=options
credentials, http_request, target, **channel_kwargs
)


Expand Down
174 changes: 171 additions & 3 deletions packages/google-cloud-core/google/cloud/_http/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,9 @@
import json
import os
import platform
from typing import Optional, Set
from urllib.parse import urlencode
import re
from typing import NamedTuple, Optional, Set
from urllib.parse import urlencode, urlsplit
import warnings

# PEP 0810: Explicit Lazy Imports
Expand All @@ -34,14 +35,127 @@
# imports are ignored, making their presence safe.
__lazy_modules__: Set[str] = {
"google.api_core.client_info",
"google.api_core.universe",
"google.auth.exceptions",
"google.cloud.exceptions",
"google.cloud.version",
}

from google.api_core.client_info import ClientInfo
from google.api_core.universe import DEFAULT_UNIVERSE, determine_domain
from google.auth.exceptions import MutualTLSChannelError
from google.cloud import exceptions
from google.cloud import version

try:
from google.api_core.universe import ( # type: ignore[attr-defined]
is_googleapis_host as _is_googleapis_url,
)
except ImportError: # pragma: NO COVER
# TODO(universe-domain): Remove fallback once google-api-core >= 2.44.0.
_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

def _parse_target(url_or_target: str) -> Optional[_ParsedTarget]:
"""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_url(url_or_target: str) -> bool: # type: ignore[misc]
"""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))


API_BASE_URL = "https://www.googleapis.com"
"""The base of the API call URL."""
Expand Down Expand Up @@ -187,6 +301,9 @@ class JSONConnection(Connection):
API_BASE_URL: Optional[str] = None
"""The base of the API call URL."""

DEFAULT_API_ENDPOINT_TEMPLATE: Optional[str] = None
"""Template for default base URL with ``{universe_domain}`` placeholder."""

API_BASE_MTLS_URL: Optional[str] = None
"""The base of the API call URL for mutual TLS."""

Expand All @@ -199,6 +316,33 @@ class JSONConnection(Connection):
API_URL_TEMPLATE: Optional[str] = None
"""A template for the URL of a particular API call."""

def __init__(self, client, client_info=None, api_endpoint=None):
super(JSONConnection, self).__init__(client, client_info)
# Fall back to client_options.api_endpoint recorded on the client when
# no explicit api_endpoint argument was passed to Connection.__init__.
client_api_endpoint = getattr(client, "_api_endpoint", None)
if api_endpoint is None and isinstance(client_api_endpoint, str):
api_endpoint = client_api_endpoint
self._custom_api_endpoint = bool(api_endpoint)
# Override API_BASE_URL on this instance when a custom endpoint is set
# (from either source); otherwise expand the subclass template for the
# client's resolved universe_domain.
if api_endpoint:
self.API_BASE_URL = api_endpoint
elif self.DEFAULT_API_ENDPOINT_TEMPLATE:
# Read the client's resolved universe_domain when present as a
# string, falling back to the default universe otherwise.
client_universe = getattr(client, "universe_domain", None)
if client_universe is not None and not isinstance(client_universe, str):
client_universe = None
universe_domain = determine_domain(client_universe, None).strip()
# Support both lowercase ({universe_domain}, used in veneers) and
# uppercase ({UNIVERSE_DOMAIN}, used in api_core/GAPIC) templates.
self.API_BASE_URL = self.DEFAULT_API_ENDPOINT_TEMPLATE.format(
universe_domain=universe_domain,
UNIVERSE_DOMAIN=universe_domain,
)

def get_api_base_url_for_mtls(self, api_base_url=None):
"""Return the api base url for mutual TLS.

Expand All @@ -221,17 +365,41 @@ def get_api_base_url_for_mtls(self, api_base_url=None):

:rtype: str
:returns: The api base url used for mTLS.
:raises ~google.auth.exceptions.MutualTLSChannelError: If
`GOOGLE_API_USE_MTLS_ENDPOINT=always` is set outside `googleapis.com`.
:raises ValueError: If `GOOGLE_API_USE_MTLS_ENDPOINT=always` is set when
`API_BASE_MTLS_URL` is not available.
"""
if api_base_url:
return api_base_url

if self._custom_api_endpoint:
return self.API_BASE_URL

env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto")
client_universe = getattr(self._client, "universe_domain", None)
if (
isinstance(client_universe, str)
and client_universe.lower() != DEFAULT_UNIVERSE
):
if env == "always":
raise MutualTLSChannelError(
f"mTLS is not supported in any universe other than {DEFAULT_UNIVERSE}."
)
return self.API_BASE_URL

# Preserve non-googleapis.com endpoints set by subclasses (e.g. emulators).
if self.API_BASE_URL and not _is_googleapis_url(self.API_BASE_URL):
return self.API_BASE_URL

if env == "always":
if not self.API_BASE_MTLS_URL:
raise ValueError("mTLS endpoint is not available.")
url_to_use = self.API_BASE_MTLS_URL
elif env == "never":
url_to_use = self.API_BASE_URL
else:
if self.ALLOW_AUTO_SWITCH_TO_MTLS_URL:
if self.ALLOW_AUTO_SWITCH_TO_MTLS_URL and self.API_BASE_MTLS_URL:
url_to_use = (
self.API_BASE_MTLS_URL if self.http.is_mtls else self.API_BASE_URL
)
Expand Down
Loading
Loading