Skip to content

fix(auth): verify workload cert and key match, retrying mid-rotation reads - #19043

Open
nbayati wants to merge 8 commits into
mainfrom
cert_key_mismatch_retry
Open

nbayati wants to merge 8 commits into
mainfrom
cert_key_mismatch_retry

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

…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.

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

Copy link
Copy Markdown
Contributor

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.

@nbayati
nbayati requested a review from macastelaz November 11, 2026 01:52

@macastelaz macastelaz left a comment

Copy link
Copy Markdown
Contributor

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.

Comment on lines +628 to +630
key_public_key = serialization.load_pem_private_key(
key, password=None
).public_key()

Copy link
Copy Markdown
Contributor

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done. Put the signature check in a small helper so the older-version and missing-signature fallbacks can be unit-tested directly without reloading the module, and added a test for the corrupted-RSA mismatch case.

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)

Copy link
Copy Markdown
Contributor

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done. Patched time.sleep on the existing failure tests (including test_requests.py) and added recovery and mixed-sequence cases.

Comment on lines +858 to +860
mock_sleep.side_effect = lambda _: key_file.write_bytes(
pytest.private_key_bytes
)

Copy link
Copy Markdown
Contributor

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done, parametrized the recovery test to cover both the key and certificate catching up.

key_public_key = serialization.load_pem_private_key(
key, password=None
).public_key()
except (ValueError, TypeError, UnsupportedAlgorithm):

Copy link
Copy Markdown
Contributor

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):

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done!

@macastelaz macastelaz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM! Thanks for addressing all of the feedback.

One non-blocking note before merging: could you update the PR description so the squash-merge commit message reflects the current behavior — specifically (1) that on the 401 reload path a persistent mismatch logs a warning, refreshes the token, and retries on the existing channel rather than raising ClientCertError to the caller, and (2) that _read_cert_and_key_files also retries transient OSError / PEM-format errors across the 3 attempts and skips RSA private-key validation where supported?

assert result.status_code == http_client.OK
credentials.refresh.assert_called_once()
assert authed_session._cached_cert == pytest.public_cert_bytes
assert authed_session.get_adapter(self.MTLS_TEST_URL) is adapter

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Optional non-blocking nit: configure_mtls_channel() replaces the "https://" adapter, so because adapter is mounted at the longer self.MTLS_TEST_URL prefix, get_adapter(self.MTLS_TEST_URL) stays adapter even if "https://" were replaced. Capturing https_adapter = authed_session.adapters["https://"] before the request and asserting authed_session.adapters["https://"] is https_adapter would verify the "https://" mount directly.

@nbayati
nbayati requested a review from lsirac December 1, 2026 18:41
from typing import Generator, List, Optional, Tuple, Union, cast
from urllib.parse import urlsplit

from cryptography import x509

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Moving cryptography to a top-level import breaks gcloud when it runs on a system Python without cryptography installed. gcloud imports _mtls_helper on every API command and keeps cryptography optional, so those commands will crash on startup with ModuleNotFoundError. Can we keep the cryptography imports inside the helper functions instead?

"""
for attempt in range(_CERT_KEY_MATCH_MAX_ATTEMPTS):
if attempt:
time.sleep(_CERT_KEY_MATCH_RETRY_INTERVAL)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

On a 401, AuthorizedSession and AuthorizedHttp hold _mtls_reauth_lock while calling this function and only skip re-checking if the cached cert changed. When the cert and key stay mismatched or missing, the cached cert never changes, so concurrent threads queue up and each one sleeps 0.2s inside the lock. Ten threads hitting 401 at once stall for 2 seconds total and can trip TimeoutGuard instead of failing fast.

"""
for attempt in range(_CERT_KEY_MATCH_MAX_ATTEMPTS):
if attempt:
time.sleep(_CERT_KEY_MATCH_RETRY_INTERVAL)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

In aio/transport/mtls.py, get_client_cert_and_key runs synchronous client_cert_callback functions directly on the asyncio event loop instead of in an executor. Async callers like python-genai pass the sync mtls.default_client_cert_source there, so adding time.sleep here freezes the entire event loop for 200ms on a mismatch or missing file. Should the async helper offload sync callbacks to an executor?

if attempt:
time.sleep(_CERT_KEY_MATCH_RETRY_INTERVAL)
try:
cert_data = _read_cert_file(cert_path)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

When cert_path and key_path point to the same combined PEM bundle file, _read_cert_file and _read_key_file open it twice. If an encrypted bundle rotates between the two opens, the mismatch check gets skipped and this returns the old cert paired with the new key.

_CERT_KEY_MATCH_MAX_ATTEMPTS,
)

raise exceptions.ClientCertError(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

One wrinkle on the 401 trade-off from the earlier review. If the cert file updates to a new cert before the key file catches up and the mismatch lasts past 200ms, catching ClientCertError lets credentials.refresh() run while the TLS channel stays on the old cert. For bound tokens, that refresh reads the new cert file alone and caches a token bound to the new cert, so the retry sends a new-cert token over the old-cert channel and fails with 401 again. Is that intended?

key_public_key = serialization.load_pem_private_key(
key, password=None, **_KEY_MATCH_LOAD_KWARGS
).public_key()
except (ValueError, TypeError, UnsupportedAlgorithm, x509.InvalidVersion):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nit: load_pem_private_key raises cryptography.exceptions.InternalError on some malformed keys, like a truncated PKCS#8 Ed25519 key, or when another library leaves an error on the OpenSSL stack. InternalError inherits directly from Exception, so it misses this catch and escapes callers that only handle ClientCertError, OSError, or ValueError.

except (ValueError, TypeError, UnsupportedAlgorithm, x509.InvalidVersion):
return False

return cert_public_key.public_bytes(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nit: public_bytes runs outside the try block, so any InternalError or UnsupportedAlgorithm raised while serializing a public key skips the fallback here and escapes callers instead of leaving validation to the TLS layer.

@pytest.mark.parametrize(
"cert_name, key_name",
[
("public_cert.pem", "privatekey.pem"),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nit: Both fixtures here contain a single certificate, so nothing tests that a valid multi-cert chain passes when the leaf matches the key and an intermediate cert does not. Can we add a matching leaf plus intermediate case?

key_file.write_bytes(fh.read())

target_file = key_file if lagging_file == "key" else cert_file
mock_sleep.side_effect = lambda _: target_file.write_bytes(rotated_bytes)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nit: Every recovery test in this class passes after the first sleep, so nothing checks that the third read attempt runs. If the loop stopped after two attempts with a trailing sleep, the whole suite would still pass.

cert_file = tmp_path / "cert.pem"
key_file = tmp_path / "key.pem"
cert_file.write_bytes(cert_bytes)
key_file.write_bytes(pytest.private_key_bytes)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nit: This writes the matching key for the mutated certificate, so the test passes even if the check runs instead of being skipped. Should this pair with a mismatched key instead so it proves the check was skipped?

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants