Skip to content
Draft
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
310 changes: 251 additions & 59 deletions packages/google-api-core/google/api_core/grpc_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@

import google.auth
import google.auth.credentials
import google.auth.exceptions
import google.auth.transport.grpc
import google.auth.transport.requests
import google.protobuf
Expand Down Expand Up @@ -112,6 +113,20 @@ def _extract_direct_path_authority(target: str) -> Optional[str]:
return None


def _canonicalize_non_direct_path_target(target: str) -> str:
"""Rewrites ``-direct.googleapis.com`` targets to ``.googleapis.com`` when DirectPath is off."""
if not target.startswith("google-c2p:///"):
clean_host = _extract_target_host(target)
if clean_host.endswith("-direct.googleapis.com") and len(clean_host) > len(
"-direct.googleapis.com"
):
new_host = (
clean_host.removesuffix("-direct.googleapis.com") + ".googleapis.com"
)
return target.replace(clean_host, new_host, 1)
return target


# The list of gRPC Callable interfaces that return iterators.
_STREAM_WRAP_CLASSES = (grpc.UnaryStreamMultiCallable, grpc.StreamStreamMultiCallable)

Expand Down Expand Up @@ -272,6 +287,84 @@ def wrap_errors(callable_):
return _wrap_unary_errors(callable_)


def _create_call_credentials(
credentials=None,
credentials_file=None,
default_scopes=None,
scopes=None,
quota_project_id=None,
default_host=None,
cert_manager=None,
):
"""Resolve Google Auth credentials and wrap them in gRPC call credentials."""
if credentials_file is not None:
warnings.warn(general_helpers._CREDENTIALS_FILE_WARNING, DeprecationWarning)

if credentials and credentials_file:
raise exceptions.DuplicateCredentialArgs(
"'credentials' and 'credentials_file' are mutually exclusive."
)

if credentials_file:
credentials, _ = google.auth.load_credentials_from_file(
credentials_file, scopes=scopes, default_scopes=default_scopes
)
elif credentials:
credentials = google.auth.credentials.with_scopes_if_required(
credentials, scopes=scopes, default_scopes=default_scopes
)
else:
credentials, _ = google.auth.default(
scopes=scopes, default_scopes=default_scopes
)

if quota_project_id and isinstance(
credentials, google.auth.credentials.CredentialsWithQuotaProject
):
credentials = credentials.with_quota_project(quota_project_id)

if cert_manager is not None:
try:
request = google.auth.transport.requests.Request(cert_manager=cert_manager)
except TypeError:
request = google.auth.transport.requests.Request()
else:
request = google.auth.transport.requests.Request()

# Create the metadata plugin for inserting the authorization header.
metadata_plugin = None
if cert_manager is not None:
try:
metadata_plugin = google.auth.transport.grpc.AuthMetadataPlugin(
credentials,
request,
default_host=default_host,
suppress_metrics_header=True,
cert_manager=cert_manager,
)
except TypeError:
pass

if metadata_plugin is None:
try:
metadata_plugin = google.auth.transport.grpc.AuthMetadataPlugin(
credentials,
request,
default_host=default_host,
suppress_metrics_header=True,
)
except TypeError:
# Support older versions of google-auth that do not accept suppress_metrics_header
metadata_plugin = google.auth.transport.grpc.AuthMetadataPlugin(
credentials,
request,
default_host=default_host,
)

# Create a set of grpc.CallCredentials using the metadata plugin.
return grpc.metadata_call_credentials(metadata_plugin)


def _create_composite_credentials(
credentials=None,
credentials_file=None,
Expand Down Expand Up @@ -320,52 +413,14 @@ def _create_composite_credentials(
Raises:
google.api_core.DuplicateCredentialArgs: If both a credentials object and credentials_file are passed.
"""
if credentials_file is not None:
warnings.warn(general_helpers._CREDENTIALS_FILE_WARNING, DeprecationWarning)

if credentials and credentials_file:
raise exceptions.DuplicateCredentialArgs(
"'credentials' and 'credentials_file' are mutually exclusive."
)

if credentials_file:
credentials, _ = google.auth.load_credentials_from_file(
credentials_file, scopes=scopes, default_scopes=default_scopes
)
elif credentials:
credentials = google.auth.credentials.with_scopes_if_required(
credentials, scopes=scopes, default_scopes=default_scopes
)
else:
credentials, _ = google.auth.default(
scopes=scopes, default_scopes=default_scopes
)

if quota_project_id and isinstance(
credentials, google.auth.credentials.CredentialsWithQuotaProject
):
credentials = credentials.with_quota_project(quota_project_id)

request = google.auth.transport.requests.Request()

# Create the metadata plugin for inserting the authorization header.
try:
metadata_plugin = google.auth.transport.grpc.AuthMetadataPlugin(
credentials,
request,
default_host=default_host,
suppress_metrics_header=True,
)
except TypeError:
# Support older versions of google-auth that do not accept suppress_metrics_header
metadata_plugin = google.auth.transport.grpc.AuthMetadataPlugin(
credentials,
request,
default_host=default_host,
)

# Create a set of grpc.CallCredentials using the metadata plugin.
google_auth_credentials = grpc.metadata_call_credentials(metadata_plugin)
google_auth_credentials = _create_call_credentials(
credentials=credentials,
credentials_file=credentials_file,
default_scopes=default_scopes,
scopes=scopes,
quota_project_id=quota_project_id,
default_host=default_host,
)

# if `ssl_credentials` is set, use `grpc.composite_channel_credentials` instead of
# `grpc.compute_engine_channel_credentials` as the former supports passing
Expand Down Expand Up @@ -481,19 +536,94 @@ def _setup_direct_path_and_credentials(
target,
attempt_direct_path_xds_over_interconnect=use_dp_interconnect,
)
elif not target.startswith("google-c2p:///"):
clean_host = _extract_target_host(target)
if clean_host.endswith("-direct.googleapis.com") and len(clean_host) > len(
"-direct.googleapis.com"
):
new_host = (
clean_host.removesuffix("-direct.googleapis.com") + ".googleapis.com"
)
target = target.replace(clean_host, new_host, 1)
else:
target = _canonicalize_non_direct_path_target(target)

return target, composite_credentials, kwargs


def _should_use_client_cert() -> bool:
"""Return whether ambient mTLS client certificates are enabled in google-auth."""
try:
from google.auth.transport.mtls import should_use_client_cert
except ImportError:
return False
return bool(should_use_client_cert())


def _get_mtls_cert_manager_class():
"""Return google-auth's ``_MtlsCertManager`` class if installed, else ``None``."""
try:
from google.auth.transport._mtls_helper import _MtlsCertManager
except ImportError:
return None
return _MtlsCertManager


def _fallback_mtls_ssl_credentials(
client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]],
) -> Optional[grpc.ChannelCredentials]:
"""Build static SSL credentials when google-auth lacks ``_MtlsCertManager``."""
ssl_credentials = None
if client_cert_source is not None:
cert, key = client_cert_source()
ssl_credentials = grpc.ssl_channel_credentials(
certificate_chain=cert, private_key=key
)
else:
ssl_creds = google.auth.transport.grpc.SslCredentials()
if ssl_creds.is_mtls:
ssl_credentials = ssl_creds.ssl_credentials
if ssl_credentials is not None:
_LOGGER.warning(
"mTLS certificate rotation is unavailable with the installed "
"version of google-auth. Upgrade google-auth to enable automatic "
"client certificate rotation."
)
return ssl_credentials


def _create_rotating_channel(
target,
cert_manager,
credentials=None,
credentials_file=None,
scopes=None,
default_scopes=None,
quota_project_id=None,
default_host=None,
compression=None,
**kwargs,
) -> "_RotatingGrpcChannel":
"""Create a channel that rebuilds itself with the manager's current certificate."""
google_auth_credentials = _create_call_credentials(
credentials=credentials,
credentials_file=credentials_file,
default_scopes=default_scopes,
scopes=scopes,
quota_project_id=quota_project_id,
default_host=default_host,
cert_manager=cert_manager,
)
target = _canonicalize_non_direct_path_target(target)

def channel_factory() -> grpc.Channel:
cert_bytes, key_bytes, _ = cert_manager.get_credential_snapshot()
ssl_credentials = grpc.ssl_channel_credentials(
certificate_chain=cert_bytes, private_key=key_bytes
)
return grpc.secure_channel(
target,
grpc.composite_channel_credentials(
ssl_credentials, google_auth_credentials
),
compression=compression,
**kwargs,
)

return _RotatingGrpcChannel(channel_factory, cert_manager=cert_manager)


def create_channel(
target,
credentials=None,
Expand All @@ -506,6 +636,8 @@ def create_channel(
compression=None,
attempt_direct_path: Optional[bool] = False,
attempt_direct_path_xds_over_interconnect: Optional[bool] = None,
client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
support_mtls_channel_rotation: bool = True,
**kwargs,
):
"""Create a secure channel with credentials.
Expand Down Expand Up @@ -554,14 +686,26 @@ def create_channel(
- If the request causes a `ServiceUnavailable` response, it is recommended
that the client repeat the request with `attempt_direct_path` set to
`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.
- Using `ssl_credentials` or `client_cert_source` with
`attempt_direct_path` set to `True` will result in `ValueError` as
this combination is not yet supported.
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.
client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): Optional
callback returning ``(cert_bytes, key_bytes)`` in PEM format for mutual
TLS. Ignored when ``ssl_credentials`` is explicitly provided or
DirectPath over Cloud Interconnect is enabled. When both
``ssl_credentials`` and ``client_cert_source`` are ``None`` and
``support_mtls_channel_rotation`` is ``True``, client certificates may
still be loaded from the environment if enabled in ``google-auth``.
support_mtls_channel_rotation (bool): Whether to wrap mutual TLS channels
for automatic client certificate rotation. Defaults to ``True``. Set to
``False`` to bypass the rotation wrapper and return a plain
:class:`grpc.Channel`.

kwargs: Additional key-word args passed to
:func:`grpc.secure_channel`.
Expand All @@ -572,9 +716,57 @@ def create_channel(
Raises:
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`.
google.auth.exceptions.MutualTLSChannelError: If loading or validating
the initial client certificate fails (exceptions raised directly by
a caller-supplied ``client_cert_source`` propagate unchanged).
ValueError: If `ssl_credentials` or `client_cert_source` is set and
`attempt_direct_path` is set to `True` without
`attempt_direct_path_xds_over_interconnect`.
"""
use_dp_interconnect = (
_resolve_direct_path_interconnect(attempt_direct_path_xds_over_interconnect)
if attempt_direct_path or attempt_direct_path_xds_over_interconnect is not None
else False
)

if attempt_direct_path and not use_dp_interconnect:
if not ssl_credentials and client_cert_source is not None:
raise ValueError(
"Using client_cert_source with Direct Path is not supported"
)
elif not use_dp_interconnect and ssl_credentials is None:
if not support_mtls_channel_rotation:
if client_cert_source is not None:
cert, key = client_cert_source()
ssl_credentials = grpc.ssl_channel_credentials(
certificate_chain=cert, private_key=key
)
elif client_cert_source is not None or _should_use_client_cert():
cert_manager_cls = _get_mtls_cert_manager_class()
if cert_manager_cls is None:
ssl_credentials = _fallback_mtls_ssl_credentials(client_cert_source)
else:
cert_manager = cert_manager_cls(client_cert_source=client_cert_source)
try:
cert_manager.refresh()
except google.auth.exceptions.ClientCertError as exc:
raise google.auth.exceptions.MutualTLSChannelError(exc) from exc

# With ambient discovery and no default certificate on disk,
# fall through to a plain TLS channel.
if cert_manager.generation_id > 0:
return _create_rotating_channel(
target,
cert_manager,
credentials=credentials,
credentials_file=credentials_file,
scopes=scopes,
default_scopes=default_scopes,
quota_project_id=quota_project_id,
default_host=default_host,
compression=compression,
**kwargs,
)

target, composite_credentials, kwargs = _setup_direct_path_and_credentials(
target=target,
Expand Down
Loading
Loading