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
111 changes: 60 additions & 51 deletions packages/google-api-core/google/api_core/grpc_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import collections
import functools
import os
import re
import urllib.parse
import warnings
from typing import (
Expand All @@ -38,10 +39,14 @@
import google.protobuf
import grpc

from google.api_core import exceptions, general_helpers
from google.api_core import exceptions, general_helpers, universe
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(
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 @@ -91,6 +96,15 @@ def _extract_target_host(target: str) -> str:
return 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 _extract_direct_path_authority(target: str) -> Optional[str]:
"""Extracts the canonical TLS/HTTP2 authority for a ``-direct.googleapis.com`` target."""
clean_host = _extract_target_host(target)
Expand Down Expand Up @@ -262,54 +276,14 @@ def wrap_errors(callable_):
return _wrap_unary_errors(callable_)


def _create_composite_credentials(
def _resolve_credentials(
credentials=None,
credentials_file=None,
default_scopes=None,
scopes=None,
ssl_credentials=None,
quota_project_id=None,
default_host=None,
):
"""Create the composite credentials for secure channels.

Args:
credentials (google.auth.credentials.Credentials): The credentials. If
not specified, then this function will attempt to ascertain the
credentials from the environment using :func:`google.auth.default`.
credentials_file (str): Deprecated. A file with credentials that can be loaded with
:func:`google.auth.load_credentials_from_file`. This argument is
mutually exclusive with credentials. This argument will be
removed in the next major version of `google-api-core`.

.. warning::
Important: If you accept a credential configuration (credential JSON/File/Stream)
from an external source for authentication to Google Cloud Platform, you must
validate it before providing it to any Google API or client library. Providing an
unvalidated credential configuration to Google APIs or libraries can compromise
the security of your systems and data. For more information, refer to
`Validate credential configurations from external sources`_.

.. _Validate credential configurations from external sources:

https://cloud.google.com/docs/authentication/external/externally-sourced-credentials
default_scopes (Sequence[str]): A optional list of scopes needed for this
service. These are only used when credentials are not specified and
are passed to :func:`google.auth.default`.
scopes (Sequence[str]): A optional list of scopes needed for this
service. These are only used when credentials are not specified and
are passed to :func:`google.auth.default`.
ssl_credentials (grpc.ChannelCredentials): Optional SSL channel
credentials. This can be used to specify different certificates.
quota_project_id (str): An optional project to use for billing and quota.
default_host (str): The default endpoint. e.g., "pubsub.googleapis.com".

Returns:
grpc.ChannelCredentials: The composed channel credentials object.

Raises:
google.api_core.DuplicateCredentialArgs: If both a credentials object and credentials_file are passed.
"""
"""Resolve auth credentials from explicit credentials, a file, or ADC."""
if credentials_file is not None:
warnings.warn(general_helpers._CREDENTIALS_FILE_WARNING, DeprecationWarning)

Expand All @@ -336,6 +310,15 @@ def _create_composite_credentials(
):
credentials = credentials.with_quota_project(quota_project_id)

return credentials


def _compose_channel_credentials(
credentials,
ssl_credentials=None,
default_host=None,
):
"""Compose gRPC channel credentials from resolved auth credentials."""
request = google.auth.transport.requests.Request()

# Create the metadata plugin for inserting the authorization header.
Expand Down Expand Up @@ -409,12 +392,16 @@ def _setup_direct_path_and_credentials(
library. Use 'scopes' for user-defined scopes.
default_host (str): The default endpoint. e.g., "pubsub.googleapis.com".
attempt_direct_path (Optional[bool]): If set, Direct Path will be attempted.
Ignored if ``target`` is not a ``googleapis.com`` host or the
resolved credentials' ``universe_domain`` is not ``googleapis.com``.
attempt_direct_path_xds_over_interconnect (Optional[bool]): If set,
DirectPath over Cloud Interconnect will be attempted using standard
TLS credentials and ``?force-xds`` C2P target resolution. If None
(default), the setting is resolved from the
``GOOGLE_CLOUD_ENABLE_DIRECT_PATH_XDS_OVER_INTERCONNECT``
environment variable.
environment variable. Ignored if ``target`` is not a
``googleapis.com`` host or the resolved credentials'
``universe_domain`` is not ``googleapis.com``.
kwargs: Additional key-word args passed to the channel creation function.

Returns:
Expand All @@ -425,7 +412,8 @@ def _setup_direct_path_and_credentials(
google.api_core.DuplicateCredentialArgs: If both a credentials object
and credentials_file are passed.
ValueError: If `ssl_credentials` is set and `attempt_direct_path` is
set to `True` without `attempt_direct_path_xds_over_interconnect`.
set to `True` without `attempt_direct_path_xds_over_interconnect`
in the ``googleapis.com`` universe.
"""
if attempt_direct_path or attempt_direct_path_xds_over_interconnect is not None:
use_dp_interconnect = _resolve_direct_path_interconnect(
Expand All @@ -434,6 +422,26 @@ def _setup_direct_path_and_credentials(
else:
use_dp_interconnect = False

credentials = _resolve_credentials(
credentials=credentials,
credentials_file=credentials_file,
default_scopes=default_scopes,
scopes=scopes,
quota_project_id=quota_project_id,
)

# DirectPath and DirectPath over Interconnect are only supported in the
# Google Default Universe (googleapis.com). Disable both if either the
# 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)
and getattr(credentials, "universe_domain", universe.DEFAULT_UNIVERSE)
== universe.DEFAULT_UNIVERSE
):
attempt_direct_path = False
use_dp_interconnect = False

# If `ssl_credentials` is set and `attempt_direct_path` is set to `True`,
# raise ValueError as this is not yet supported for GCE ALTS DirectPath.
# See https://github.com/googleapis/python-api-core/issues/590
Expand All @@ -443,13 +451,9 @@ def _setup_direct_path_and_credentials(
if use_dp_interconnect and ssl_credentials is None:
ssl_credentials = grpc.ssl_channel_credentials()

composite_credentials = _create_composite_credentials(
composite_credentials = _compose_channel_credentials(
credentials=credentials,
credentials_file=credentials_file,
default_scopes=default_scopes,
scopes=scopes,
ssl_credentials=ssl_credentials,
quota_project_id=quota_project_id,
default_host=default_host,
)

Expand Down Expand Up @@ -546,12 +550,17 @@ def create_channel(
`False` as the Service may not support Direct Path.
- Using `ssl_credentials` with `attempt_direct_path` set to `True` will
result in `ValueError` as this combination is not yet supported.
- Ignored if ``target`` is not a ``googleapis.com`` host or the
resolved credentials' ``universe_domain`` is not
``googleapis.com``.
attempt_direct_path_xds_over_interconnect (Optional[bool]): If set,
DirectPath over Cloud Interconnect will be attempted using standard
TLS credentials and ``?force-xds`` C2P target resolution. If None
(default), the setting is resolved from the
``GOOGLE_CLOUD_ENABLE_DIRECT_PATH_XDS_OVER_INTERCONNECT``
environment variable.
environment variable. Ignored if ``target`` is not a
``googleapis.com`` host or the resolved credentials'
``universe_domain`` is not ``googleapis.com``.

kwargs: Additional key-word args passed to
:func:`grpc.secure_channel`.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -271,12 +271,17 @@ def create_channel(
`False` as the Service may not support Direct Path.
- Using `ssl_credentials` with `attempt_direct_path` set to `True` will
result in `ValueError` as this combination is not yet supported.
- Ignored if ``target`` is not a ``googleapis.com`` host or the
resolved credentials' ``universe_domain`` is not
``googleapis.com``.
attempt_direct_path_xds_over_interconnect (Optional[bool]): If set,
DirectPath over Cloud Interconnect will be attempted using standard
TLS credentials and ``?force-xds`` C2P target resolution. If None
(default), the setting is resolved from the
``GOOGLE_CLOUD_ENABLE_DIRECT_PATH_XDS_OVER_INTERCONNECT``
environment variable.
environment variable. Ignored if ``target`` is not a
``googleapis.com`` host or the resolved credentials'
``universe_domain`` is not ``googleapis.com``.

kwargs: Additional key-word args passed to :func:`aio.secure_channel`.

Expand Down
Loading
Loading