Skip to content

perf(auth): reuse NetHttpTransport per certificate snapshot for mTLS IAM calls (stacked on #15027) - #15216

Draft
macastelaz wants to merge 10 commits into
googleapis:mainfrom
macastelaz:impersonated-agent-identity-mtls-transport-reuse
Draft

macastelaz wants to merge 10 commits into
googleapis:mainfrom
macastelaz:impersonated-agent-identity-mtls-transport-reuse

Conversation

@macastelaz

Copy link
Copy Markdown
Contributor

Stacked on #15027 — implements Option 2 from the transport reuse discussion on #15027. Currently drafted against main (containing #15027's commits as ancestors); once #15027 merges I will rebase onto main and mark this ready for review. To review only this PR's incremental diff on top of #15027, see commit ff8ee6566d9 or the compare view.

Summary

In #15027, each bound-token IAM Credentials call (ImpersonatedCredentials.refreshAccessToken(), sign(), idTokenWithAudience(), and ComputeEngineCredentials.sign()) instantiates a fresh MtlsHttpTransportFactory(keyStore) and builds a new NetHttpTransport (SSLContext + SSLSocketFactory). Compared to the unbound path—which shares a single NetHttpTransport via OAuth2Utils.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 NetHttpTransport lazily inside MtlsHttpTransportFactory and holds one MtlsHttpTransportFactory per verified AgentIdentityUtils.CertInfo snapshot so repeated IAM calls bound to the same certificate reuse the same NetHttpTransport, while certificate rotation automatically switches subsequent calls to a new transport without disturbing in-flight calls.

Changes

  • MtlsHttpTransportFactory: Lazily caches the built NetHttpTransport (private transient volatile @Nullable NetHttpTransport cachedTransport) using double-checked locking with a private transient lock (transportLock, restored in readObject) in create().
    • NetHttpTransport is immutable and thread-safe (and its shutdown() is a no-op), matching OAuth2Utils.DefaultHttpTransportFactory.
    • Marking cachedTransport transient preserves Serializable compatibility (serialVersionUID = 1L) so a fresh transport is lazily created after deserialization.
    • Failures during NetHttpTransport creation are not cached.
    • Other callers using MtlsHttpTransportFactory (such as Workload Identity Federation IdentityPoolCredentials) also benefit from reusing the transport across calls sharing a factory instance.
  • AgentIdentityUtils.CertInfo: Holds a private final @Nullable MtlsHttpTransportFactory mtlsTransportFactory initialized when keyStore != null, exposed via package-private getMtlsTransportFactory().
    • Because MtlsHttpTransportFactory.create() initializes SSLContext / NetHttpTransport lazily, non-IAM workloads that only load CertInfo for token binding pay no eager SSLContext construction cost.
    • Because AgentIdentityCacheUtils reuses the same CertInfo while the certificate/key files on disk are unchanged, repeated IAM calls (including across token refreshes) reuse the same NetHttpTransport, and certificate rotation produces a new CertInfo with a new MtlsHttpTransportFactory while any in-flight IamCallTarget retains the previous snapshot's transport.
  • IamUtils: Uses certInfo.getMtlsTransportFactory() by default in resolveBoundTokenCallTarget() when no test override is installed (mtlsTransportFactoryProvider defaults to null).

Testing

Unit tests

  • Added unit tests in MtlsHttpTransportFactoryTest:
    • create_reusesSameNetHttpTransportInstance
    • create_concurrentCalls_returnSameNetHttpTransportInstance (8 concurrent threads verify a single NetHttpTransport instance is built and returned)
    • create_uninitializedKeyStore_throwsAndDoesNotCacheFailure
    • serialization_roundTripAfterCreate_succeedsAndCachesNewTransport
  • Added unit tests in IamUtilsTest:
    • certInfo_withoutKeyStore_hasNullMtlsTransportFactory
    • resolveCallTarget_repeatedCallsWithSameCertInfo_reusesTransportFactoryAndTransport
    • resolveBoundTokenCallTarget_nullOverrideUsesCertInfoFactory_providerReturningNullUsesDefault
    • resolveCallTarget_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)
  • Ran fmt:format, Checkstyle (0 violations), Java 8 animal-sniffer, and the full oauth2_http test 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, sharing OAuth2Utils.HTTP_TRANSPORT) across two alternating rounds of 20 consecutive ImpersonatedCredentials.sign() calls + 10 consecutive ImpersonatedCredentials.idTokenWithAudience() calls (with MDS pre-warmed and no debug logging), plus a separate -Djavax.net.debug=ssl:handshake probe across 10 consecutive IAM calls (5 sign() + 5 idTokenWithAudience()):

TLS handshakes (10 consecutive IAM calls: 5 sign() + 5 idTokenWithAudience()):

Variant ClientHello ServerHello client CertificateVerify (mTLS)
#15027 (fd149da8b56) 10 10 10
This PR (Option 2) 1 1 1
Unbound control (HTTP_TRANSPORT) 1 1 0

Steady-state latency (2 alternating rounds in the same pod, no SSL debug logging):

Variant 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)
#15027 (fd149da8b56) 2154.2ms / 2072.7ms 113.4ms / 109.1ms 108.7ms / 95.7ms 89.9ms / 72.9ms 86.3ms / 76.9ms
This PR (Option 2) 1075.3ms / 1075.7ms 56.6ms / 56.6ms 60.8ms / 59.0ms 59.4ms / 58.4ms 61.8ms / 61.1ms
Unbound control (HTTP_TRANSPORT) 1259.4ms / 1068.7ms 66.3ms / 56.2ms 70.7ms / 57.6ms 61.7ms / 54.7ms 60.5ms / 58.1ms
  • Latency parity achieved: steady-state 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.
  • Full live functional smoke test on this PR's jar: 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-project over mTLS, serialization round-trip, and PinnedTokenCredentials non-serializability all pass.

…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.
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

Gemini encountered an error creating the review. You can try again by commenting /gemini review.

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.

1 participant