From efc6d0192f5a243e60798c20525c12b95aca5cdd Mon Sep 17 00:00:00 2001 From: Negar Bayati Date: Fri, 27 Nov 2026 00:39:01 +0000 Subject: [PATCH] feat(google-api-core): wire mTLS certificate rotation into create_channel create_channel now accepts client_cert_source and returns a _RotatingGrpcChannel backed by google-auth's _MtlsCertManager when mTLS is active, so channels pick up rotated client certificates without recreating the client. The manager is shared with AuthMetadataPlugin and its Request so tokens and the TLS connection use the same certificate. DirectPath, explicit ssl_credentials, and support_mtls_channel_rotation=False keep the existing unwrapped channel. Older google-auth releases without _MtlsCertManager fall back to static SSL credentials and log a warning when mTLS is active. --- .../google/api_core/grpc_helpers.py | 310 +++++++++--- .../tests/unit/test_grpc_helpers.py | 444 ++++++++++++++++++ 2 files changed, 695 insertions(+), 59 deletions(-) diff --git a/packages/google-api-core/google/api_core/grpc_helpers.py b/packages/google-api-core/google/api_core/grpc_helpers.py index 0c3483c1c4ab..376a6a721e92 100644 --- a/packages/google-api-core/google/api_core/grpc_helpers.py +++ b/packages/google-api-core/google/api_core/grpc_helpers.py @@ -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 @@ -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) @@ -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, @@ -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 @@ -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, @@ -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. @@ -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`. @@ -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, diff --git a/packages/google-api-core/tests/unit/test_grpc_helpers.py b/packages/google-api-core/tests/unit/test_grpc_helpers.py index 4e1fc8e9202a..cafed7630e31 100644 --- a/packages/google-api-core/tests/unit/test_grpc_helpers.py +++ b/packages/google-api-core/tests/unit/test_grpc_helpers.py @@ -13,8 +13,10 @@ # limitations under the License. import copy +import datetime import gc import inspect +import logging import threading import time import weakref @@ -31,10 +33,25 @@ pytest.skip("No GRPC", allow_module_level=True) import google.auth.credentials +import google.auth.exceptions +import google.auth.transport._mtls_helper +import google.auth.transport.requests from google.longrunning import operations_pb2 from google.api_core import exceptions, grpc_helpers +try: + from cryptography import x509 + from cryptography.hazmat.primitives import hashes, serialization + from cryptography.hazmat.primitives.asymmetric import ec + from cryptography.x509.oid import NameOID +except ImportError: # pragma: NO COVER + x509 = None # type: ignore[assignment] + +_REAL_MTLS_CERT_MANAGER = getattr( + google.auth.transport._mtls_helper, "_MtlsCertManager", None +) + def test__patch_callable_name(): callable = mock.Mock(spec=["__class__"]) @@ -2320,3 +2337,430 @@ def test_getattr_without_init_raises_attribute_error(self): ) with pytest.raises(AttributeError): uninitialized.custom_attr + + +def _generate_self_signed_pem_pair(): + """Generate an ephemeral self-signed ECDSA cert/key PEM pair in memory.""" + key = ec.generate_private_key(ec.SECP256R1()) + subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "test-client")]) + now = datetime.datetime.now(datetime.timezone.utc) + cert = ( + x509.CertificateBuilder() + .subject_name(subject) + .issuer_name(subject) + .public_key(key.public_key()) + .serial_number(x509.random_serial_number()) + .not_valid_before(now - datetime.timedelta(minutes=1)) + .not_valid_after(now + datetime.timedelta(hours=1)) + .sign(key, hashes.SHA256()) + ) + cert_pem = cert.public_bytes(serialization.Encoding.PEM) + key_pem = key.private_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PrivateFormat.PKCS8, + encryption_algorithm=serialization.NoEncryption(), + ) + return cert_pem, key_pem + + +class _FakeMtlsCertManager: + """Stands in for google-auth's _MtlsCertManager on releases that lack it.""" + + # Returned by default discovery when client_cert_source is None. + default_cert_source = None + + def __init__(self, client_cert_source=None): + self.client_cert_source = client_cert_source + self.generation_id = 0 + self._cert_and_key = (None, None) + + def get_credential_snapshot(self): + return (*self._cert_and_key, self.generation_id) + + def refresh(self): + source = self.client_cert_source or type(self).default_cert_source + if source is None: + return False + self._cert_and_key = source() + self.generation_id += 1 + return True + + +@pytest.fixture +def fake_cert_manager(monkeypatch): + monkeypatch.setattr( + "google.auth.transport._mtls_helper._MtlsCertManager", + _FakeMtlsCertManager, + raising=False, + ) + return _FakeMtlsCertManager + + +@pytest.fixture +def ambient_mtls(): + # create=True: older google-auth releases lack should_use_client_cert. + with mock.patch( + "google.auth.transport.mtls.should_use_client_cert", + return_value=True, + create=True, + ) as should_use_client_cert: + yield should_use_client_cert + + +class TestCreateChannelMtlsRotation: + @pytest.mark.parametrize( + "ssl_credentials,support_rotation,message", + [ + (None, True, "Using client_cert_source with Direct Path"), + (None, False, "Using client_cert_source with Direct Path"), + (mock.sentinel.ssl_credentials, True, "Using ssl_credentials with Direct"), + ], + ) + def test_direct_path_rejects_mtls_arguments( + self, ssl_credentials, support_rotation, message + ): + cert_source = mock.Mock() + with pytest.raises(ValueError, match=message): + grpc_helpers.create_channel( + "example.com:443", + ssl_credentials=ssl_credentials, + attempt_direct_path=True, + client_cert_source=cert_source, + support_mtls_channel_rotation=support_rotation, + ) + cert_source.assert_not_called() + + def test_direct_path_ignores_ambient_mtls(self, ambient_mtls): + with mock.patch("grpc.secure_channel") as secure_channel: + channel = grpc_helpers.create_channel( + "example.com:443", + credentials=mock.sentinel.credentials, + attempt_direct_path=True, + ) + + assert channel is secure_channel.return_value + ambient_mtls.assert_not_called() + + def test_direct_path_interconnect_ignores_client_cert_source(self): + cert_source = mock.Mock() + with mock.patch("grpc.secure_channel") as secure_channel: + channel = grpc_helpers.create_channel( + "storage-direct.googleapis.com:443", + credentials=mock.sentinel.credentials, + attempt_direct_path_xds_over_interconnect=True, + client_cert_source=cert_source, + ) + + assert channel is secure_channel.return_value + cert_source.assert_not_called() + + def test_explicit_ssl_credentials_ignore_client_cert_source(self): + cert_source = mock.Mock() + with ( + mock.patch("grpc.composite_channel_credentials") as composite, + mock.patch("grpc.secure_channel") as secure_channel, + ): + channel = grpc_helpers.create_channel( + "example.com:443", + credentials=mock.sentinel.credentials, + ssl_credentials=mock.sentinel.ssl_credentials, + client_cert_source=cert_source, + ) + + assert channel is secure_channel.return_value + cert_source.assert_not_called() + composite.assert_called_once_with(mock.sentinel.ssl_credentials, mock.ANY) + + def test_rotation_opt_out_uses_static_client_cert(self): + cert_source = mock.Mock(return_value=(b"cert", b"key")) + with ( + mock.patch("grpc.ssl_channel_credentials") as ssl_creds, + mock.patch("grpc.composite_channel_credentials") as composite, + mock.patch("grpc.secure_channel") as secure_channel, + ): + channel = grpc_helpers.create_channel( + "example.com:443", + credentials=mock.sentinel.credentials, + client_cert_source=cert_source, + support_mtls_channel_rotation=False, + ) + + assert channel is secure_channel.return_value + ssl_creds.assert_called_once_with(certificate_chain=b"cert", private_key=b"key") + composite.assert_called_once_with(ssl_creds.return_value, mock.ANY) + + def test_rotation_opt_out_ignores_ambient_mtls(self, ambient_mtls): + with ( + mock.patch("grpc.compute_engine_channel_credentials") as plain_tls, + mock.patch("grpc.secure_channel") as secure_channel, + ): + channel = grpc_helpers.create_channel( + "example.com:443", + credentials=mock.sentinel.credentials, + support_mtls_channel_rotation=False, + ) + + assert channel is secure_channel.return_value + ambient_mtls.assert_not_called() + plain_tls.assert_called_once_with(mock.ANY) + + def test_missing_should_use_client_cert_means_no_mtls(self, monkeypatch): + monkeypatch.delattr( + "google.auth.transport.mtls.should_use_client_cert", raising=False + ) + with ( + mock.patch("grpc.compute_engine_channel_credentials") as plain_tls, + mock.patch("grpc.secure_channel") as secure_channel, + ): + channel = grpc_helpers.create_channel( + "example.com:443", credentials=mock.sentinel.credentials + ) + + assert channel is secure_channel.return_value + plain_tls.assert_called_once_with(mock.ANY) + + def test_old_google_auth_uses_static_client_cert(self, monkeypatch, caplog): + monkeypatch.delattr( + "google.auth.transport._mtls_helper._MtlsCertManager", raising=False + ) + cert_source = mock.Mock(return_value=(b"cert", b"key")) + with ( + mock.patch("grpc.ssl_channel_credentials") as ssl_creds, + mock.patch("grpc.composite_channel_credentials") as composite, + mock.patch("grpc.secure_channel") as secure_channel, + caplog.at_level(logging.WARNING, logger="google.api_core.grpc_helpers"), + ): + channel = grpc_helpers.create_channel( + "example.com:443", + credentials=mock.sentinel.credentials, + client_cert_source=cert_source, + ) + + assert channel is secure_channel.return_value + ssl_creds.assert_called_once_with(certificate_chain=b"cert", private_key=b"key") + composite.assert_called_once_with(ssl_creds.return_value, mock.ANY) + assert "Upgrade google-auth" in caplog.text + + @pytest.mark.parametrize( + "is_mtls,channel_credentials_factory,warning_count", + [ + (True, "grpc.composite_channel_credentials", 1), + (False, "grpc.compute_engine_channel_credentials", 0), + ], + ) + def test_old_google_auth_ambient_mtls( + self, + ambient_mtls, + monkeypatch, + caplog, + is_mtls, + channel_credentials_factory, + warning_count, + ): + monkeypatch.delattr( + "google.auth.transport._mtls_helper._MtlsCertManager", raising=False + ) + with ( + mock.patch( + "google.auth.transport.grpc.SslCredentials", + return_value=mock.Mock(is_mtls=is_mtls), + ), + mock.patch(channel_credentials_factory) as channel_credentials, + mock.patch("grpc.secure_channel") as secure_channel, + caplog.at_level(logging.WARNING, logger="google.api_core.grpc_helpers"), + ): + grpc_helpers.create_channel( + "example.com:443", credentials=mock.sentinel.credentials + ) + + secure_channel.assert_called_once_with( + "example.com:443", channel_credentials.return_value, compression=None + ) + assert caplog.text.count("Upgrade google-auth") == warning_count + + def test_rotating_channel_rebuilds_with_current_cert(self, fake_cert_manager): + certs = iter([(b"cert1", b"key1"), (b"cert2", b"key2")]) + generation_at_plugin_init = [] + + def record_generation(*args, cert_manager, **kwargs): + generation_at_plugin_init.append(cert_manager.generation_id) + return mock.DEFAULT + + with ( + mock.patch( + "google.auth.transport.grpc.AuthMetadataPlugin", + side_effect=record_generation, + ) as plugin, + mock.patch("grpc.metadata_call_credentials") as call_creds, + mock.patch("grpc.ssl_channel_credentials") as ssl_creds, + mock.patch("grpc.composite_channel_credentials") as composite, + mock.patch( + "grpc.secure_channel", + side_effect=[mock.sentinel.channel1, mock.sentinel.channel2], + ) as secure_channel, + ): + channel = grpc_helpers.create_channel( + "storage-direct.googleapis.com:443", + credentials=mock.sentinel.credentials, + compression=grpc.Compression.Gzip, + client_cert_source=lambda: next(certs), + options=(("grpc.keepalive_time_ms", 1000),), + ) + cert_manager = channel._cert_manager + cert_manager.refresh() + channel.swap_channel() + + assert isinstance(channel, grpc_helpers._RotatingGrpcChannel) + assert channel.channel is mock.sentinel.channel2 + # The first certificate is loaded before AuthMetadataPlugin is built. + assert generation_at_plugin_init == [1] + assert plugin.call_args.kwargs["cert_manager"] is cert_manager + assert ssl_creds.call_args_list == [ + mock.call(certificate_chain=b"cert1", private_key=b"key1"), + mock.call(certificate_chain=b"cert2", private_key=b"key2"), + ] + # Every rebuilt channel reuses the same call credentials. + call_creds.assert_called_once_with(plugin.return_value) + assert ( + composite.call_args_list + == [mock.call(ssl_creds.return_value, call_creds.return_value)] * 2 + ) + assert ( + secure_channel.call_args_list + == [ + mock.call( + "storage.googleapis.com:443", + composite.return_value, + compression=grpc.Compression.Gzip, + options=(("grpc.keepalive_time_ms", 1000),), + ) + ] + * 2 + ) + + def test_ambient_mtls_uses_default_cert( + self, ambient_mtls, fake_cert_manager, monkeypatch + ): + monkeypatch.setattr( + fake_cert_manager, "default_cert_source", lambda: (b"cert", b"key") + ) + with ( + mock.patch("google.auth.transport.grpc.AuthMetadataPlugin"), + mock.patch("grpc.metadata_call_credentials"), + mock.patch("grpc.ssl_channel_credentials") as ssl_creds, + mock.patch("grpc.composite_channel_credentials"), + mock.patch("grpc.secure_channel"), + ): + channel = grpc_helpers.create_channel( + "example.com:443", credentials=mock.sentinel.credentials + ) + + assert isinstance(channel, grpc_helpers._RotatingGrpcChannel) + assert channel._cert_manager.client_cert_source is None + ssl_creds.assert_called_once_with(certificate_chain=b"cert", private_key=b"key") + + def test_ambient_mtls_without_default_cert_uses_plain_tls( + self, ambient_mtls, fake_cert_manager + ): + with ( + mock.patch("grpc.compute_engine_channel_credentials") as plain_tls, + mock.patch("grpc.secure_channel") as secure_channel, + ): + channel = grpc_helpers.create_channel( + "example.com:443", credentials=mock.sentinel.credentials + ) + + assert channel is secure_channel.return_value + plain_tls.assert_called_once_with(mock.ANY) + + def test_initial_client_cert_error_raises_mutual_tls_channel_error( + self, fake_cert_manager + ): + error = google.auth.exceptions.ClientCertError("broken cert") + with pytest.raises( + google.auth.exceptions.MutualTLSChannelError, match="broken cert" + ) as exc_info: + grpc_helpers.create_channel( + "example.com:443", + credentials=mock.sentinel.credentials, + client_cert_source=mock.Mock(side_effect=error), + ) + assert exc_info.value.__cause__ is error + + @pytest.mark.parametrize( + "request_kwargs,plugin_kwargs", + [ + # Request and AuthMetadataPlugin both accept cert_manager. + ( + {"cert_manager"}, + {"default_host", "suppress_metrics_header", "cert_manager"}, + ), + # Only Request accepts cert_manager. + ({"cert_manager"}, {"default_host", "suppress_metrics_header"}), + # Neither accepts cert_manager or suppress_metrics_header. + (set(), {"default_host"}), + ], + ) + def test_falls_back_when_google_auth_rejects_keyword( + self, fake_cert_manager, request_kwargs, plugin_kwargs + ): + def accepting(supported_kwargs, result): + def factory(*args, **kwargs): + if not kwargs.keys() <= supported_kwargs: + raise TypeError("unexpected keyword argument") + return result + + return factory + + with ( + mock.patch( + "google.auth.transport.requests.Request", + side_effect=accepting(request_kwargs, mock.sentinel.request), + ) as request, + mock.patch( + "google.auth.transport.grpc.AuthMetadataPlugin", + side_effect=accepting(plugin_kwargs, mock.sentinel.plugin), + ) as plugin, + mock.patch("grpc.metadata_call_credentials"), + mock.patch("grpc.composite_channel_credentials"), + mock.patch("grpc.secure_channel"), + ): + grpc_helpers.create_channel( + "example.com:443", + credentials=mock.sentinel.credentials, + client_cert_source=lambda: (b"cert", b"key"), + ) + + assert set(request.call_args.kwargs) == request_kwargs + assert plugin.call_args.args == ( + mock.sentinel.credentials, + mock.sentinel.request, + ) + assert set(plugin.call_args.kwargs) == plugin_kwargs + + @pytest.mark.skipif( + _REAL_MTLS_CERT_MANAGER is None or x509 is None, + reason="requires google-auth with _MtlsCertManager and cryptography", + ) + def test_real_cert_manager_is_shared_with_request(self): + cert, key = _generate_self_signed_pem_pair() + # AuthMetadataPlugin is mocked because it does not accept cert_manager yet. + with ( + mock.patch("google.auth.transport.grpc.AuthMetadataPlugin") as plugin, + mock.patch("grpc.metadata_call_credentials"), + mock.patch("grpc.composite_channel_credentials"), + mock.patch("grpc.secure_channel"), + ): + channel = grpc_helpers.create_channel( + "example.com:443", + credentials=mock.sentinel.credentials, + client_cert_source=lambda: (cert, key), + ) + + cert_manager = channel._cert_manager + assert isinstance(cert_manager, _REAL_MTLS_CERT_MANAGER) + assert cert_manager.get_credential_snapshot() == (cert, key, 1) + request = plugin.call_args.args[1] + assert isinstance(request, google.auth.transport.requests.Request) + assert request._cert_manager is cert_manager + assert plugin.call_args.kwargs["cert_manager"] is cert_manager