Repository navigation
Conversation
There was a problem hiding this comment.
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.
| cert_obj = _agent_identity_utils.parse_certificate(cert_bytes) | ||
| fingerprint = _agent_identity_utils.calculate_certificate_fingerprint(cert_obj) | ||
|
|
||
| return cert_bytes, key_bytes, fingerprint |
There was a problem hiding this comment.
_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.
There was a problem hiding this comment.
_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.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| return False | ||
| if isinstance(caught_exc, exceptions.ClientCertError): | ||
| raise | ||
| raise exceptions.ClientCertError(caught_exc) from caught_exc |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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``). |
There was a problem hiding this comment.
Nit: The docstring only covers a failure on the first load. After that, a failed reload returns False and keeps the old cert.
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
Nit: This only checks the exception type. Removing the isinstance(caught_exc, exceptions.ClientCertError) pass-through still passes all 23 tests.
There was a problem hiding this comment.
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() |
There was a problem hiding this comment.
Nit: barrier.wait() and t.join() have no timeout, so a deadlock in refresh() hangs the run and the test never fails.
There was a problem hiding this comment.
Done, added timeout=5 and assert not t.is_alive() to all barrier waits and thread joins in TestMtlsCertManager.
| cert_obj = _agent_identity_utils.parse_certificate(cert_bytes) | ||
| fingerprint = _agent_identity_utils.calculate_certificate_fingerprint(cert_obj) | ||
|
|
||
| return cert_bytes, key_bytes, fingerprint |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
…and cert source callback out of pickles
… lock and it fails without it
… in _MtlsCertManager tests
… add missing edge cases
ce82fa1 to
0029884
Compare
Adds
_MtlsCertManageringoogle.auth.transport._mtls_helperto 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
_MtlsCertManagerintorequests.Requestand Compute Engine bound-token refreshes,AuthMetadataPlugin,google.api_core.grpc_helpers.create_channel, andgapic-generatorso 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.