Skip to content

feat(auth): add _MtlsCertManager for mTLS client certificate rotation - #18925

Open
nbayati wants to merge 16 commits into
mainfrom
grpc_phase1_pr1
Open

nbayati wants to merge 16 commits into
mainfrom
grpc_phase1_pr1

Conversation

@nbayati

@nbayati nbayati commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Adds _MtlsCertManager in google.auth.transport._mtls_helper to track the active mTLS client certificate, private key, leaf certificate SHA-256 fingerprint, and generation counter across certificate reloads.

This is the first change in the gRPC mTLS client certificate rotation series. Subsequent PRs wire _MtlsCertManager into requests.Request and Compute Engine bound-token refreshes, AuthMetadataPlugin, google.api_core.grpc_helpers.create_channel, and gapic-generator so that TLS channel credentials and certificate-bound token refreshes stay on the same certificate generation.

This is PR1 from go/cert-rotation-python-auth phase 1.

@nbayati
nbayati requested review from a team as code owners October 30, 2026 06:25

@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 _MtlsCertManager, a thread-safe manager for handling mTLS client certificates, tracking their generation, and managing reloading. It also adds comprehensive unit tests for this new class. The feedback suggests catching all standard exceptions (Exception) during certificate reloads rather than a specific subset, ensuring that unexpected errors from custom certificate sources do not crash the application and are instead gracefully handled as transient reload errors.

@lsirac lsirac added the do not merge Indicates a pull request not ready for merge, due to either quality or timing. label Nov 7, 2026
Comment on lines +1040 to +1043
cert_obj = _agent_identity_utils.parse_certificate(cert_bytes)
fingerprint = _agent_identity_utils.calculate_certificate_fingerprint(cert_obj)

return cert_bytes, key_bytes, fingerprint

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.

_load_cert_and_fingerprint parses cert_bytes here, but never parses key_bytes or checks that it matches cert_obj. #19043 only runs inside _read_cert_and_key_files, so client_cert_source callbacks, GKE credential bundles, and SecureConnect bypass it. Even on workload files with #19043, an unparseable or encrypted key makes _has_cert_key_mismatch return False, which overwrites the working snapshot and latches _cert_fingerprint to the new cert so _key stays broken after a valid key file arrives.

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.

_MtlsCertManager already picks up #19043 automatically on separate workload files (both through default discovery and through mtls.default_client_cert_source() used by generated GAPIC clients).
For the other paths, GKE's bundle is a single file read in one pass, SecureConnect isn't used by GCE/Cloud Run/GKE and is not in the scope of this design, and our managed runtimes write PEM files without passphrase encryption. I think custom client_cert_source callbacks are responsible for returning a valid matching pair, and if we want to add key-cert matching check for them in the future, it'd be out of scope for this PR.

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.

Following up on the callback case. I gave refresh() a cert with the wrong key and it stored the pair and returned True. Every RPC on that channel then fails with UNAVAILABLE, not UNAUTHENTICATED. Does the reload on UNAUTHENTICATED ever run in that case?

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.

You're right that UNAVAILABLE won't trigger the UNAUTHENTICATED reload, so a custom callback returning a mismatched pair fails the same way it does today without the manager. With key_bytes now part of change detection (see the other thread), the stale key no longer stays latched: a later reload, such as the one on token refresh, will pick up the matching key once the callback returns it. I'd still like to leave cert/key match validation for custom callbacks out of this PR.

raise
raise exceptions.ClientCertError(caught_exc) from caught_exc

changed = cert_bytes is not None and fingerprint != self._cert_fingerprint

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.

Should changed check cert_bytes != self._cert or key_bytes != self._key instead of only the leaf fingerprint? Right now if a PEM bundle renews an intermediate CA while keeping the same leaf cert, or updates key_bytes for the same leaf, refresh() returns False and keeps serving the stale 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.

Bumping this one, I tried the key case. If a reload reads the new cert with the old key, the next reload with the right key returns False and the old key stays until the cert rotates again.

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, changed now compares both cert_bytes and key_bytes against the cached snapshot so intermediate chain and key updates for the same leaf both advance generation_id, and I added a test covering both cases.

@nbayati
nbayati requested a review from lsirac November 17, 2026 07:24
return False
if isinstance(caught_exc, exceptions.ClientCertError):
raise
raise exceptions.ClientCertError(caught_exc) from caught_exc

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 the first load this turns MutualTLSChannelError and any error from a custom callback into ClientCertError. Generated clients call the callback directly today, so users get their own exception back. Is that change intended once create_channel goes through the manager?

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.

Good catch! Updated _MtlsCertManager so exceptions raised by client_cert_source propagate unchanged on the initial load while default-discovery, empty-credential, and certificate-parsing errors still raise ClientCertError. Reloads after the initial load still suppress all exceptions and keep the previous certificate.

assert manager.generation_id == 1
assert 1 <= reload_source.call_count < 6

def test_mid_reload_arrival_does_not_reuse_earlier_read(self):

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.

Swapping the two early-return checks in refresh() still passes all 23 tests. Can we add a third thread that also arrives during the held reload? It should get True once the second thread loads the new cert, and with the swap it gets False.

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, added a third thread that queues during the held reload and asserted [False, True, True] with steps == [], which fails if the two early-return checks are swapped.


assert results == [False] * 6
assert manager.generation_id == 1
assert 1 <= reload_source.call_count < 6

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.

I know this got loosened after my last comment, but < 6 no longer checks what the comment at the top of the test says. If a failed first load costs one extra reload, call_count goes from 2 to 3 and this still passes.

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, synchronized the 6 worker threads at lock entry so all of them capture _reload_id before any thread runs the reload, removing the time.sleep and asserting reload_source.call_count == 1.


t2 = threading.Thread(target=worker, args=(1,))
t2.start()
time.sleep(0.02)

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.

If t2 takes more than 20ms to reach refresh(), t1 has already finished and nothing arrives mid-reload. I started t2 after t1 finished and the test still passed, including against a refresh() that bumps _reload_id after the load.

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, replaced the 20ms sleep with a lock-entry hook so the held reload is only released after both waiting threads have reached _lock.


Raises:
google.auth.exceptions.ClientCertError: If loading or parsing the
certificate fails on the initial load (``generation_id == 0``).

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: The docstring only covers a failure on the first load. After that, a failed reload returns False and keeps the old cert.

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.

Updated the refresh() docstring to document post-startup reload failure behavior as well.


# A failed first load must not stop later bursts from sharing a reload.
with pytest.raises(exceptions.ClientCertError):
manager.refresh(expected_generation=0)

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: Can we add a concurrent case for a failed first load? If I move self._completed_reload_id = self._reload_id into a finally, a thread waiting behind a failed startup load returns False with no cert, and all 23 tests pass.

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, added test_concurrent_failed_initial_load_does_not_suppress_waiter synchronizing two threads at expected_generation=0 before lock entry so moving _completed_reload_id into a finally block fails the test.

def test_initial_load_error_raises_client_cert_error(self, cert_source):
manager = _mtls_helper._MtlsCertManager(client_cert_source=cert_source)

with pytest.raises(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.

Nit: This only checks the exception type. Removing the isinstance(caught_exc, exceptions.ClientCertError) pass-through still passes all 23 tests.

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, the initial-load tests now assert exception identity (is) for both callback and default-discovery ClientCertError pass-throughs.

results = [None] * 4

def worker(idx):
barrier.wait()

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: barrier.wait() and t.join() have no timeout, so a deadlock in refresh() hangs the run and the test never fails.

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, added timeout=5 and assert not t.is_alive() to all barrier waits and thread joins in TestMtlsCertManager.

Comment on lines +1040 to +1043
cert_obj = _agent_identity_utils.parse_certificate(cert_bytes)
fingerprint = _agent_identity_utils.calculate_certificate_fingerprint(cert_obj)

return cert_bytes, key_bytes, fingerprint

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.

Following up on the callback case. I gave refresh() a cert with the wrong key and it stored the pair and returned True. Every RPC on that channel then fails with UNAVAILABLE, not UNAUTHENTICATED. Does the reload on UNAUTHENTICATED ever run in that case?

raise
raise exceptions.ClientCertError(caught_exc) from caught_exc

changed = cert_bytes is not None and fingerprint != self._cert_fingerprint

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.

Bumping this one, I tried the key case. If a reload reads the new cert with the old key, the next reload with the right key returns False and the old key stays until the cert rotates again.

Adds `_MtlsCertManager` in `google.auth.transport._mtls_helper` to track
the active mTLS client certificate, private key, leaf certificate
SHA-256 fingerprint, and generation counter across certificate reloads.

This is the first change in the gRPC mTLS client certificate rotation
series. Subsequent PRs wire `_MtlsCertManager` into `requests.Request`
and Compute Engine bound-token refreshes, `AuthMetadataPlugin`,
`google.api_core.grpc_helpers.create_channel`, and `gapic-generator` so
that TLS channel credentials and certificate-bound token refreshes stay
on the same certificate generation.

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

do not merge Indicates a pull request not ready for merge, due to either quality or timing.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants