fix(auth): only trigger mTLS certificate rotation on mTLS endpoints - #17928
fix(auth): only trigger mTLS certificate rotation on mTLS endpoints#17928attharva-24 wants to merge 3 commits into
Conversation
There was a problem hiding this comment.
Code Review
This pull request restricts mTLS certificate rotation on 401 Unauthorized responses to only occur when the request URL matches specific mTLS prefixes (such as mtls.googleapis.com or mtls.sandbox.googleapis.com), and updates the test suite to verify this behavior. The feedback suggests optimizing the URL prefix check by using a generator expression inside the any() function to allow short-circuiting instead of evaluating a full list comprehension.
| if response.status_code == http_client.UNAUTHORIZED: | ||
| if self.is_mtls: | ||
| MTLS_URL_PREFIXES = ["mtls.googleapis.com", "mtls.sandbox.googleapis.com"] | ||
| use_mtls = self.is_mtls and any([prefix in url for prefix in MTLS_URL_PREFIXES]) |
There was a problem hiding this comment.
Using a list comprehension inside any() creates a temporary list in memory and evaluates all elements, defeating the short-circuiting behavior of any(). Using a generator expression instead allows any() to short-circuit as soon as a match is found, which is more efficient.
| use_mtls = self.is_mtls and any([prefix in url for prefix in MTLS_URL_PREFIXES]) | |
| use_mtls = self.is_mtls and any(prefix in url for prefix in MTLS_URL_PREFIXES) |
There was a problem hiding this comment.
Seems like a fair optimization to use
Description
In
AuthorizedSession.requestwithin therequeststransport, a401 Unauthorizedresponse triggered the mTLS client certificate rotation check regardless of whether the endpoint was actually an mTLS URL.For sessions configured with mTLS support, calling standard, non-mTLS endpoints (like standard
googleapis.comURLs) would trigger unnecessary certificate parsing, disk reads, and adapter reconfiguration upon token expiration.This PR adds a URL verification check (matching the behavior in
urllib3.py) to ensure certificate rotation is only triggered on requests sent to designated mTLS endpoints (mtls.googleapis.comormtls.sandbox.googleapis.com).Tests
test_cert_rotation_skipped_on_non_mtls_urlintests/transport/test_requests.pyto verify that rotation is skipped on non-mTLS URLs.