Repository navigation
perf(auth): reuse NetHttpTransport per certificate snapshot for mTLS IAM calls (stacked on #15027) - #15216
Draft
macastelaz wants to merge 10 commits into
Draft
perf(auth): reuse NetHttpTransport per certificate snapshot for mTLS IAM calls (stacked on #15027)#15216macastelaz wants to merge 10 commits into
macastelaz wants to merge 10 commits into
Conversation
…thout a body IamUtils.sign() and IamUtils.getIdToken() parse the JSON body of every 4xx response. HttpURLConnection discards the body of a 401 response to a request sent in streaming mode (NetHttpTransport sends every POST with content in streaming mode), so the response has no content and parseAs() throws a NullPointerException. Callers such as ImpersonatedCredentials.sign(), ImpersonatedCredentials.idTokenWithAudience() and ComputeEngineCredentials.sign() then surface a bare NPE instead of the 401. Use the HTTP status message when the error response has no content, so these calls fail with an IOException (or SigningException) that includes the status code.
- Fall back to the status message when the 4xx body is empty but not null (the JSON parser throws IllegalArgumentException: no JSON input found). - Treat an empty reason phrase like a missing one. - Tests: empty-string body, missing reason phrase, sign() with a JSON body, and an IAM-shaped 401 (Bearer challenge) for getIdToken that asserts no credential refresh.
… agent identity tokens On GKE and Cloud Run workloads with an agent identity, ComputeEngineCredentials requests access tokens that are bound to the workload certificate. A bound token is accepted only over mTLS, presenting that certificate, to the mTLS endpoint. ImpersonatedCredentials (generateAccessToken, signBlob, generateIdToken) and ComputeEngineCredentials.sign() sent the token to the plain iamcredentials.googleapis.com host without a client certificate, so they failed with 401. - AgentIdentityUtils.CertInfo now also holds a KeyStore built from the same certificate chain and private key that were loaded and verified together. - ComputeEngineCredentials returns a package-private BoundAccessToken that records the CertInfo the token was bound to. It serializes as a plain AccessToken. - IamUtils.resolveCallTarget() sends calls authenticated with a bound token to iamcredentials.mtls.googleapis.com over an MtlsHttpTransportFactory with that KeyStore, authenticated with exactly that token, so the presented certificate always matches the token. Calls with a custom IAM endpoint, a custom transport factory, a non-default universe, or an unbound token are unchanged. - ImpersonatedCredentials and ComputeEngineCredentials.sign() use it.
- Building the mTLS key store can no longer fail token binding: unparsable and duplicate extra certificates are skipped (as in MtlsKeyStoreUtils), PKCS12 is used if JKS is unavailable, and any remaining failure leaves the key store unset (IAM calls then use the default endpoint). - BoundAccessToken serializes as an expired AccessToken, so deserialized credentials mint a new bound token on first use instead of sending a bound token without its certificate. - sign() and idTokenWithAudience() use the mTLS endpoint even when iamEndpointOverride is set; the override only ever applied to generateAccessToken. - Look up the universe domain before the source refresh in ImpersonatedCredentials.refreshAccessToken so its errors keep their type. - Tests: call-site routing for ImpersonatedCredentials (generateAccessToken, signBlob, generateIdToken, endpoint override) and ComputeEngineCredentials.sign through a test-only mTLS transport factory provider; key store contents; chain with extra certificates; credential serialization round trip.
Avoids a refresh on first use. Adds a test that the pinned credentials start with the bound token and keep it after a refresh.
…bound tokens - Populate PinnedTokenCredentials via an in-memory refresh() after construction instead of Builder.setAccessToken(token), so GoogleCredentials attaches the x-goog-user-project header via getAdditionalHeaders() while still starting with the bound token cached. - Disable HttpCredentialsAdapter's 401 retry handler when authenticating IAM generateAccessToken or generateIdToken calls with PinnedTokenCredentials, preventing 10 futile retries with the same pinned token on a 401. - Store usesMtls explicitly on IamCallTarget, reuse OAuth2Utils.PEM_CERT_PATTERN in AgentIdentityUtils.buildKeyStore, and match MtlsKeyStoreUtils by skipping null returns or RuntimeExceptions from CertificateFactory.generateCertificate on extra chain blocks. - Expand unit tests in IamMtlsRoutingTest, IamUtilsTest, and ComputeEngineCredentialsTest to cover quotaProjectId preservation, 401 fail-fast behavior across all 4 call sites, DefaultHttpTransportFactory endpoint-override routing, idTokenWithAudience with iamEndpointOverride, cold-start token refresh, certificate rotation isolation, and multi-certificate chain retention.
Contributor
|
Warning Gemini encountered an error creating the review. You can try again by commenting |
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Summary
In #15027, each bound-token IAM Credentials call (
ImpersonatedCredentials.refreshAccessToken(),sign(),idTokenWithAudience(), andComputeEngineCredentials.sign()) instantiates a freshMtlsHttpTransportFactory(keyStore)and builds a newNetHttpTransport(SSLContext+SSLSocketFactory). Compared to the unbound path—which shares a singleNetHttpTransportviaOAuth2Utils.DefaultHttpTransportFactory—that prevents TLS session resumption and HTTP keep-alive connection reuse across repeated calls (for example, signing URLs in a loop).This change caches the
NetHttpTransportlazily insideMtlsHttpTransportFactoryand holds oneMtlsHttpTransportFactoryper verifiedAgentIdentityUtils.CertInfosnapshot so repeated IAM calls bound to the same certificate reuse the sameNetHttpTransport, while certificate rotation automatically switches subsequent calls to a new transport without disturbing in-flight calls.Changes
MtlsHttpTransportFactory: Lazily caches the builtNetHttpTransport(private transient volatile @Nullable NetHttpTransport cachedTransport) using double-checked locking with a privatetransientlock (transportLock, restored inreadObject) increate().NetHttpTransportis immutable and thread-safe (and itsshutdown()is a no-op), matchingOAuth2Utils.DefaultHttpTransportFactory.cachedTransporttransientpreservesSerializablecompatibility (serialVersionUID = 1L) so a fresh transport is lazily created after deserialization.NetHttpTransportcreation are not cached.MtlsHttpTransportFactory(such as Workload Identity FederationIdentityPoolCredentials) also benefit from reusing the transport across calls sharing a factory instance.AgentIdentityUtils.CertInfo: Holds aprivate final @Nullable MtlsHttpTransportFactory mtlsTransportFactoryinitialized whenkeyStore != null, exposed via package-privategetMtlsTransportFactory().MtlsHttpTransportFactory.create()initializesSSLContext/NetHttpTransportlazily, non-IAM workloads that only loadCertInfofor token binding pay no eagerSSLContextconstruction cost.AgentIdentityCacheUtilsreuses the sameCertInfowhile the certificate/key files on disk are unchanged, repeated IAM calls (including across token refreshes) reuse the sameNetHttpTransport, and certificate rotation produces a newCertInfowith a newMtlsHttpTransportFactorywhile any in-flightIamCallTargetretains the previous snapshot's transport.IamUtils: UsescertInfo.getMtlsTransportFactory()by default inresolveBoundTokenCallTarget()when no test override is installed (mtlsTransportFactoryProviderdefaults tonull).Testing
Unit tests
MtlsHttpTransportFactoryTest:create_reusesSameNetHttpTransportInstancecreate_concurrentCalls_returnSameNetHttpTransportInstance(8 concurrent threads verify a singleNetHttpTransportinstance is built and returned)create_uninitializedKeyStore_throwsAndDoesNotCacheFailureserialization_roundTripAfterCreate_succeedsAndCachesNewTransportIamUtilsTest:certInfo_withoutKeyStore_hasNullMtlsTransportFactoryresolveCallTarget_repeatedCallsWithSameCertInfo_reusesTransportFactoryAndTransportresolveBoundTokenCallTarget_nullOverrideUsesCertInfoFactory_providerReturningNullUsesDefaultresolveCallTarget_certificateRotation_usesNewTransportFactoryAndTransport(verifies unchanged-cert token refreshes reuse the cached factory/transport, real on-disk rotation without clearing static caches switches to a new factory/transport, and in-flight targets retain the pre-rotation transport)refreshAndResolveRetryTarget_tokenRefreshReusesTransport_certRotationReplacesTransport(verifies 401 retry reuses the transport when only the token changes and switches to the new transport when the on-disk certificate rotates)fmt:format, Checkstyle (0 violations), Java 8animal-sniffer, and the fulloauth2_httptest suite locally: 1,380 tests, 0 failures, 2 skipped.Live GKE A/B verification (agent-identity pod)
Ran an apples-to-apples A/B benchmark in the same GKE agent-identity pod comparing #15027 (
fd149da8b56), this PR, and the unbound control (GOOGLE_API_ENABLE_RUNTIME_BOUND_TOKEN=false, sharingOAuth2Utils.HTTP_TRANSPORT) across two alternating rounds of 20 consecutiveImpersonatedCredentials.sign()calls + 10 consecutiveImpersonatedCredentials.idTokenWithAudience()calls (with MDS pre-warmed and no debug logging), plus a separate-Djavax.net.debug=ssl:handshakeprobe across 10 consecutive IAM calls (5sign()+ 5idTokenWithAudience()):TLS handshakes (10 consecutive IAM calls: 5
sign()+ 5idTokenWithAudience()):ClientHelloServerHelloclient CertificateVerify(mTLS)fd149da8b56)HTTP_TRANSPORT)Steady-state latency (2 alternating rounds in the same pod, no SSL debug logging):
sign()calls 2–20 total (R1 / R2)sign()calls 2–20 avg (R1 / R2)sign()calls 2–20 median (R1 / R2)idToken()calls 2–10 avg (R1 / R2)idToken()calls 2–10 median (R1 / R2)fd149da8b56)HTTP_TRANSPORT)sign()drops by ~50% (109–113ms → 56.6ms avg), matching the unbound baseline (56.2–66.3ms), and mTLS handshakes drop from 10 to 1 across 10 consecutive IAM calls.ImpersonatedCredentials.refreshAccessToken(),sign(),idTokenWithAudience(), stale-token and wrong-cert-mismatch 401 recovery (including swapping from the wrong cert's transport to the real cert's transport when MDS returns the same token string),sign()401 no-retry,x-goog-user-projectover mTLS, serialization round-trip, andPinnedTokenCredentialsnon-serializability all pass.