Skip to content

Commit 633ab62

Browse files
feat: Auto enable mTLS when supported certificates are detected
Signed-off-by: Radhika Agrawal <agrawalradhika@google.com>
1 parent 9340408 commit 633ab62

File tree

2 files changed

+19
-11
lines changed

2 files changed

+19
-11
lines changed

google/api_core/operations_v1/abstract_operations_base_client.py

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -300,16 +300,20 @@ def __init__(
300300
client_options = client_options_lib.ClientOptions()
301301

302302
# Create SSL credentials for mutual TLS if needed.
303-
use_client_cert = os.getenv(
304-
"GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"
305-
).lower()
306-
if use_client_cert not in ("true", "false"):
307-
raise ValueError(
308-
"Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
309-
)
303+
if hasattr(mtls, "should_use_client_cert"):
304+
use_client_cert = mtls.should_use_client_cert()
305+
else:
306+
# if unsupported, fallback to reading from env var
307+
use_client_cert_str = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower()
308+
if use_client_cert_str not in ("true", "false"):
309+
raise ValueError(
310+
"Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be"
311+
" either `true` or `false`"
312+
)
313+
use_client_cert = use_client_cert_str == "true"
310314
client_cert_source_func = None
311315
is_mtls = False
312-
if use_client_cert == "true":
316+
if use_client_cert:
313317
if client_options.client_cert_source:
314318
is_mtls = True
315319
client_cert_source_func = client_options.client_cert_source

tests/unit/operations_v1/test_operations_rest_client.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -346,12 +346,16 @@ def test_operations_client_client_options(
346346
with pytest.raises(MutualTLSChannelError):
347347
client = client_class()
348348

349-
# Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value.
349+
# Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value and
350+
# should_use_client_cert is unavailable.
350351
with mock.patch.dict(
351352
os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}
352353
):
353-
with pytest.raises(ValueError):
354-
client = client_class()
354+
if hasattr(google.auth.transport.mtls, "should_use_client_cert"):
355+
pytest.skip(
356+
"The should_use_client_cert function is available in this "
357+
"version of google-auth. Skipping this test."
358+
)
355359

356360
# Check the case quota_project_id is provided
357361
options = client_options.ClientOptions(quota_project_id="octopus")

0 commit comments

Comments
 (0)