GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(auth): verify workload cert and key match, retrying mid-rotation reads by nbayati · Pull Request #19043 · googleapis/google-cloud-python

Conversation

@nbayati

@nbayati nbayati commented Nov 11, 2026

Copy link
Copy Markdown
Contributor

When the workload certificate and private key are separate files, re-read both (up to 3 attempts, 100ms apart) if the private key does not match the leaf certificate's public key, and raise ClientCertError if the mismatch persists. Keys or certificates that cannot be parsed (e.g. passphrase- encrypted keys) skip the check and keep the existing behavior.

fixes b/545786900

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

gemini-code-assist[bot] reacted with eyes emoji
All reactions
  • 👀 1 reaction
@nbayati
fix(auth): verify workload cert and key match, retrying mid-rotation …
e0c26de
…reads

When the workload certificate and private key are separate files, re-read
both (up to 3 attempts, 100ms apart) if the private key does not match the
leaf certificate's public key, and raise ClientCertError if the mismatch
persists. Keys or certificates that cannot be parsed (e.g. passphrase-
encrypted keys) skip the check and keep the existing behavior.
@nbayati
nbayati requested review from a team as code owners November 11, 2026 01:51
@nbayati nbayati mentioned this pull request Nov 11, 2026
feat(auth): add _MtlsCertManager for mTLS client certificate rotation #18925
Open
gemini-code-assist[bot]
gemini-code-assist Bot reviewed Nov 11, 2026
View reviewed changes

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a retry mechanism when reading certificate and private key files in _read_cert_and_key_files. If a mismatch is detected between the private key and the leaf certificate's public key (which can happen during disk rotation), the files are re-read up to 3 times with a 100ms delay. A helper function _has_cert_key_mismatch is added to verify the match, and corresponding unit tests are implemented to cover various scenarios including successful matches, mismatches, rotation recovery, and uninspectable pairs. No review comments were provided, so there is no feedback to address.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@nbayati
nbayati requested a review from macastelaz November 11, 2026 01:52
macastelaz
macastelaz reviewed Nov 11, 2026
View reviewed changes

@macastelaz macastelaz left a comment

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

Behaviour change worth stating in the description: on the 401 path a persistent mismatch is not raised to the caller.

Before this change, a mismatched pair on disk was returned, the fingerprint differed, reconfiguration failed in load_cert_chain, and the request raised MutualTLSChannelError("Failed to reconfigure mTLS channel") with no token refresh.

Now the new ClientCertError is caught by the existing "failed to check" handlers in _reconfigure_mtls_channel_if_cert_changed (requests and urllib3) and in the aio AsyncAuthorizedSession.request. A warning is logged, the token is refreshed, and the request is retried on the old channel, about 0.2 s later per 401.

That is arguably the better outcome, and nothing is cached so the next 401 re-checks. But the description says "raise ClientCertError if the mismatch persists", which is not what a 401-path caller sees. A caller-level test for this path would be a nice addition.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
Comment thread packages/google-auth/google/auth/transport/_mtls_helper.py
Comment on lines +628 to +630
key_public_key = serialization.load_pem_private_key(
key, password=None
).public_key()

@macastelaz macastelaz Nov 11, 2026

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

This loads the private key with full RSA validation on every call of _read_cert_and_key_files, including the success path. That validation is expensive, holds the GIL, and doesn't act as a gate here.

Cost (cryptography 46.0.7, OpenSSL 3.6.5, per check): RSA-2048 ~41 ms, RSA-4096 ~286 ms, EC P-256 ~0.06 ms. Agent-identity pools are fixed to ECDSA P-256, but RSA keys are documented for this path: the X.509 Workload Identity Federation setup guide generates rsa:2048 keys, and managed workload identity pools accept keyAlgorithm: RSA_2048/3072/4096. For those users the cost is paid on every configure_mtls_channel, every 401 on an mTLS endpoint (an ordinary expired-token 401 with an unchanged RSA-2048 pair went from ~1 ms to ~44 ms), and every SslCredentials.ssl_credentials access. Because the GIL is held, the aio transport's asyncio.to_thread hand-off doesn't protect the event loop (~42 ms stall per call in my test).

Not a gate: if validation fails, the ValueError is caught below and treated as "can't inspect, skip the check". I built an RSA key with valid n/e and corrupted private values: paired with an unrelated certificate, this function reports no mismatch and the mismatched pair is returned. ssl.load_cert_chain also accepts that key, so the TLS layer never ran this validation before this change either.

Since only the public half is compared, suggest skipping the validation where the installed library supports it (needs import inspect):

# Only the key's public half is compared, so skip RSA private-key validation
# where supported: it is slow (~40 ms for RSA-2048) and the TLS layer does not
# perform it either.
try:
    _SKIP_RSA_VALIDATION_SUPPORTED = (
        "unsafe_skip_rsa_key_validation"
        in inspect.signature(serialization.load_pem_private_key).parameters
    )
except (TypeError, ValueError):
    _SKIP_RSA_VALIDATION_SUPPORTED = False
_KEY_MATCH_LOAD_KWARGS = (
    {"unsafe_skip_rsa_key_validation": True} if _SKIP_RSA_VALIDATION_SUPPORTED else {}
)
...
        key_public_key = serialization.load_pem_private_key(
            key, password=None, **_KEY_MATCH_LOAD_KWARGS
        ).public_key()

I applied this to a copy of the branch:

  • The seven new tests still pass.
  • Matching and mismatched RSA/EC pairs, the two-certificate chain, a mismatch that heals after one sleep, encrypted keys and garbage bodies behave exactly as before.
  • The corrupted-key mismatch is now caught.
  • An RSA-2048 check drops from ~41 ms to ~0.03 ms.

The try/except matters because load_pem_private_key is a compiled function whose inspectable signature depends on how the library was built; without it, a version where inspect.signature raises would fail at import. Older cryptography versions without the option, or where its signature can't be inspected, keep today's behaviour. If you'd rather avoid the unsafe_ option, reading n/e with pyasn1 (already a dependency) also works, at ~0.1–0.2 ms per check.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
Comment thread packages/google-auth/google/auth/transport/_mtls_helper.py
Comment on lines +600 to +601
if attempt:
time.sleep(_CERT_KEY_MATCH_RETRY_INTERVAL)
cert_data = _read_cert_file(cert_path)
key_data = _read_key_file(key_path)

@macastelaz macastelaz Nov 11, 2026

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

The retry only covers "both files parse but the keys differ". These two reads are outside any try, so an OSError or the PEM-format ClientCertError from _extract_cert_chain / _extract_private_key leaves the loop on the first attempt with no sleep and no re-read.

A rotator that truncates and rewrites in place, or unlinks and recreates, produces an empty, partial, or missing file in the same window that produces a mismatched pair. I reproduced each of those states against this function: all raise immediately, even when the file would be valid again by the first sleep. Rotators that swap atomically never hit this.

Not a regression, but the docstring justifies the loop by rotation, so it seems worth covering. Sketch (I ran this against the branch for healing, permanent-failure and mixed cases):

last_exc = None
for attempt in range(_CERT_KEY_MATCH_MAX_ATTEMPTS):
    if attempt:
        time.sleep(_CERT_KEY_MATCH_RETRY_INTERVAL)
    try:
        cert_data = _read_cert_file(cert_path)
        key_data = _read_key_file(key_path)
    except (OSError, exceptions.ClientCertError) as exc:
        last_exc = exc
        continue
    last_exc = None
    if not _has_cert_key_mismatch(cert_data, key_data):
        return cert_data, key_data
    ...

if last_exc is not None:
    raise last_exc
raise exceptions.ClientCertError(...)

Trade-off: a permanently missing or malformed file then takes 0.2 s to raise. The existing failure tests in TestReadCertAndKeyFile (test_no_cert_file, test_no_key_file, test_invalid_cert_file, test_invalid_key_file, test_multiple_keys_raises_error, test_truncated_multi_cert_raises_error) would still pass but each sleep for real unless time.sleep is patched.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
Comment thread packages/google-auth/tests/transport/test__mtls_helper.py
Comment on lines +858 to +860
mock_sleep.side_effect = lambda _: key_file.write_bytes(
pytest.private_key_bytes
)

@macastelaz macastelaz Nov 11, 2026

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

This only rewrites the key file during the wait, so nothing pins that the certificate is re-read too. Hoisting _read_cert_file(cert_path) out of the loop still passes all seven new cases (I checked by mutation).

Rotation can land in either order. Suggest parametrizing on which file catches up, or adding a sibling case: start with a stale certificate and the new key, and have the side effect write the matching certificate to cert.pem.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
Comment thread packages/google-auth/google/auth/transport/_mtls_helper.py
key_public_key = serialization.load_pem_private_key(
key, password=None
).public_key()
except (ValueError, TypeError, UnsupportedAlgorithm):

@macastelaz macastelaz Nov 11, 2026

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

x509.InvalidVersion derives from Exception only, so it is not caught here. A certificate with an invalid version field makes this function raise instead of returning False as the docstring says, while ssl.load_cert_chain accepts the same pair. Unlikely in practice, but a one-token fix:

Suggested change
except (ValueError, TypeError, UnsupportedAlgorithm):
except (ValueError, TypeError, UnsupportedAlgorithm, x509.InvalidVersion):

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

@macastelaz macastelaz macastelaz left review comments
+1 more reviewer
@gemini-code-assist gemini-code-assist[bot] gemini-code-assist[bot] left review comments
Reviewers whose approvals may not affect merge requirements

At least 1 approving review is required to merge this pull request.

Uh oh!

There was an error while loading. Please reload this page.

Assignees

No one assigned

Labels

None yet

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

Uh oh!

There was an error while loading. Please reload this page.

2 participants

@nbayati @macastelaz
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.