Skip to content
Open
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
10 changes: 4 additions & 6 deletions packages/google-auth/google/auth/compute_engine/_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,18 +166,16 @@ def _prepare_request_for_mds(request, use_mtls=False) -> None:

Args:
request (google.auth.transport.Request): A callable used to make
HTTP requests.
HTTP requests. If mTLS is enabled, the request will have the mTLS
adapter mounted. Otherwise, there will be no change.
use_mtls (bool): Whether to use mTLS for the request.

Returns:
google.auth.transport.Request: A request object to use.
If mTLS is enabled, the request will have the mTLS adapter mounted.
Otherwise, the original request will be returned unchanged.

"""
# Only modify the request if mTLS is enabled.
if use_mtls:
# Ensure the request has a session to mount the adapter to.
if not request.session:
if not getattr(request, "session", None):
request.session = requests.Session()
Copy link
Contributor Author

@daniel-sanche daniel-sanche Mar 7, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thinking about this some more, is this safe? Should we be attaching a session to a request that wasn't designed to hold one? Or should we drop mtls in that situation?

It looks like some tests fail if we drop mtls. But We should confirm the intention before merging this


adapter = _mtls.MdsMtlsAdapter()
Expand Down
14 changes: 14 additions & 0 deletions packages/google-auth/tests/compute_engine/test__metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -955,3 +955,17 @@ def test__prepare_request_for_mds_mtls_no_session(mock_mds_mtls_adapter):
mock_session_class.assert_called_once()
mock_mds_mtls_adapter.assert_called_once()
assert request.session.mount.call_count == len(_metadata._GCE_DEFAULT_MDS_HOSTS)


@mock.patch("google.auth.compute_engine._mtls.MdsMtlsAdapter")
def test__prepare_request_for_mds_mtls_attribute_error(mock_mds_mtls_adapter):
# Regression test for https://github.com/googleapis/google-cloud-python/issues/16035
from google.auth.transport import _http_client

request = _http_client.Request()
with mock.patch("requests.Session") as mock_session_class:
_metadata._prepare_request_for_mds(request, use_mtls=True)

mock_session_class.assert_called_once()
mock_mds_mtls_adapter.assert_called_once()
assert request.session.mount.call_count == len(_metadata._GCE_DEFAULT_MDS_HOSTS)
Loading