|
| 1 | +# Copyright 2026 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +""" |
| 16 | +Helper functions for mTLS in async for discovery of certs. |
| 17 | +""" |
| 18 | + |
| 19 | +import asyncio |
| 20 | +import logging |
| 21 | + |
| 22 | +from google.auth import exceptions |
| 23 | +import google.auth.transport._mtls_helper |
| 24 | +import google.auth.transport.mtls |
| 25 | + |
| 26 | +_LOGGER = logging.getLogger(__name__) |
| 27 | + |
| 28 | + |
| 29 | +async def _run_in_executor(func, *args): |
| 30 | + """Run a blocking function in an executor to avoid blocking the event loop. |
| 31 | +
|
| 32 | + This implements the non-blocking execution strategy for disk I/O operations. |
| 33 | + """ |
| 34 | + try: |
| 35 | + # For python versions 3.9 and newer versions |
| 36 | + return await asyncio.to_thread(func, *args) |
| 37 | + except AttributeError: |
| 38 | + # Fallback for older Python versions |
| 39 | + loop = asyncio.get_running_loop() |
| 40 | + return await loop.run_in_executor(None, func, *args) |
| 41 | + |
| 42 | + |
| 43 | +def default_client_cert_source(): |
| 44 | + """Get a callback which returns the default client SSL credentials. |
| 45 | +
|
| 46 | + Returns: |
| 47 | + Awaitable[Callable[[], [bytes, bytes]]]: A callback which returns the default |
| 48 | + client certificate bytes and private key bytes, both in PEM format. |
| 49 | +
|
| 50 | + Raises: |
| 51 | + google.auth.exceptions.DefaultClientCertSourceError: If the default |
| 52 | + client SSL credentials don't exist or are malformed. |
| 53 | + """ |
| 54 | + if not google.auth.transport.mtls.has_default_client_cert_source( |
| 55 | + include_context_aware=False |
| 56 | + ): |
| 57 | + raise exceptions.MutualTLSChannelError( |
| 58 | + "Default client cert source doesn't exist" |
| 59 | + ) |
| 60 | + |
| 61 | + async def callback(): |
| 62 | + try: |
| 63 | + _, cert_bytes, key_bytes = await get_client_cert_and_key() |
| 64 | + except (OSError, RuntimeError, ValueError) as caught_exc: |
| 65 | + new_exc = exceptions.MutualTLSChannelError(caught_exc) |
| 66 | + raise new_exc from caught_exc |
| 67 | + |
| 68 | + return cert_bytes, key_bytes |
| 69 | + |
| 70 | + return callback |
| 71 | + |
| 72 | + |
| 73 | +async def get_client_ssl_credentials( |
| 74 | + certificate_config_path=None, |
| 75 | +): |
| 76 | + """Returns the client side certificate, private key and passphrase. |
| 77 | +
|
| 78 | + We look for certificates and keys with the following order of priority: |
| 79 | + 1. Certificate and key specified by certificate_config.json. |
| 80 | + Currently, only X.509 workload certificates are supported. |
| 81 | +
|
| 82 | + Args: |
| 83 | + certificate_config_path (str): The certificate_config.json file path. |
| 84 | +
|
| 85 | + Returns: |
| 86 | + Tuple[bool, bytes, bytes, bytes]: |
| 87 | + A boolean indicating if cert, key and passphrase are obtained, the |
| 88 | + cert bytes and key bytes both in PEM format, and passphrase bytes. |
| 89 | +
|
| 90 | + Raises: |
| 91 | + google.auth.exceptions.ClientCertError: if problems occurs when getting |
| 92 | + the cert, key and passphrase. |
| 93 | + """ |
| 94 | + |
| 95 | + # Attempt to retrieve X.509 Workload cert and key. |
| 96 | + cert, key = await _run_in_executor( |
| 97 | + google.auth.transport._mtls_helper._get_workload_cert_and_key, |
| 98 | + certificate_config_path, |
| 99 | + False, |
| 100 | + ) |
| 101 | + |
| 102 | + if cert and key: |
| 103 | + return True, cert, key, None |
| 104 | + |
| 105 | + return False, None, None, None |
| 106 | + |
| 107 | + |
| 108 | +async def get_client_cert_and_key(client_cert_callback=None): |
| 109 | + """Returns the client side certificate and private key. The function first |
| 110 | + tries to get certificate and key from client_cert_callback; if the callback |
| 111 | + is None or doesn't provide certificate and key, the function tries application |
| 112 | + default SSL credentials. |
| 113 | +
|
| 114 | + Args: |
| 115 | + client_cert_callback (Optional[Callable[[], (bytes, bytes)]]): An |
| 116 | + optional callback which returns client certificate bytes and private |
| 117 | + key bytes both in PEM format. |
| 118 | +
|
| 119 | + Returns: |
| 120 | + Tuple[bool, bytes, bytes]: |
| 121 | + A boolean indicating if cert and key are obtained, the cert bytes |
| 122 | + and key bytes both in PEM format. |
| 123 | +
|
| 124 | + Raises: |
| 125 | + google.auth.exceptions.ClientCertError: if problems occurs when getting |
| 126 | + the cert and key. |
| 127 | + """ |
| 128 | + if client_cert_callback: |
| 129 | + result = client_cert_callback() |
| 130 | + try: |
| 131 | + cert, key = await result |
| 132 | + except TypeError: |
| 133 | + cert, key = result |
| 134 | + return True, cert, key |
| 135 | + |
| 136 | + has_cert, cert, key, _ = await get_client_ssl_credentials() |
| 137 | + return has_cert, cert, key |
0 commit comments