diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/mtls/MtlsHttpTransportFactory.java b/google-auth-library-java/oauth2_http/java/com/google/auth/mtls/MtlsHttpTransportFactory.java index 8f7fd6f198aa..e3b834109ecd 100644 --- a/google-auth-library-java/oauth2_http/java/com/google/auth/mtls/MtlsHttpTransportFactory.java +++ b/google-auth-library-java/oauth2_http/java/com/google/auth/mtls/MtlsHttpTransportFactory.java @@ -34,6 +34,8 @@ import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.core.InternalApi; import com.google.auth.http.HttpTransportFactory; +import java.io.IOException; +import java.io.ObjectInputStream; import java.io.Serializable; import java.security.GeneralSecurityException; import java.security.KeyStore; @@ -45,9 +47,16 @@ import org.jspecify.annotations.Nullable; /** - * An HttpTransportFactory that creates {@link NetHttpTransport} instances configured for mTLS - * (mutual TLS) using a specific {@link KeyStore} containing the client's certificate and private - * key. + * An HttpTransportFactory that lazily creates and caches a {@link NetHttpTransport} instance + * configured for mTLS (mutual TLS) using a specific {@link KeyStore} containing the client's + * certificate and private key. + * + *

Repeated {@link #create()} calls on the same factory instance reuse the same {@link + * NetHttpTransport} so connections share the same {@link javax.net.ssl.SSLContext} and {@link + * javax.net.ssl.SSLSocketFactory} for TLS session resumption and HTTP keep-alive reuse. Callers + * rotating client certificates must construct a new {@link MtlsHttpTransportFactory} with the + * updated {@link KeyStore}. The cached transport is {@code transient} and is lazily recreated after + * deserialization. * *

Warning: This class is considered internal and is not intended for direct use by * library consumers. Its API and behavior may change without notice. @@ -58,6 +67,8 @@ public class MtlsHttpTransportFactory implements HttpTransportFactory, Serializa private static final long serialVersionUID = 1L; private final transient @Nullable KeyStore mtlsKeyStore; private final transient boolean hasKeyStore; + private transient volatile Object transportLock = new Object(); + private transient volatile @Nullable NetHttpTransport cachedTransport; /** * Default no-arg constructor creating an instance without a KeyStore ({@code hasKeyStore() == @@ -125,15 +136,37 @@ private static boolean checkHasKeyStore(@Nullable KeyStore keyStore) { } } + /** + * Returns the lazily initialized {@link NetHttpTransport} for this factory, creating it once on + * first call and reusing the same immutable instance on subsequent calls. + */ @Override public NetHttpTransport create() { - try { - // Build the mTLS transport using the provided KeyStore. - return new NetHttpTransport.Builder().trustCertificates(null, mtlsKeyStore, "").build(); - } catch (GeneralSecurityException e) { - // Wrap the checked exception in a RuntimeException because the HttpTransportFactory - // interface's create() method doesn't allow throwing checked exceptions. - throw new RuntimeException("Failed to initialize mTLS transport.", e); + NetHttpTransport transport = cachedTransport; + if (transport != null) { + return transport; } + synchronized (transportLock) { + transport = cachedTransport; + if (transport == null) { + try { + // Build the mTLS transport once per factory so repeated calls share the same + // SSLContext and SSLSocketFactory for TLS session resumption and keep-alive reuse. + transport = + new NetHttpTransport.Builder().trustCertificates(null, mtlsKeyStore, "").build(); + } catch (GeneralSecurityException e) { + // Wrap the checked exception in a RuntimeException because the HttpTransportFactory + // interface's create() method doesn't allow throwing checked exceptions. + throw new RuntimeException("Failed to initialize mTLS transport.", e); + } + cachedTransport = transport; + } + } + return transport; + } + + private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { + in.defaultReadObject(); + this.transportLock = new Object(); } } diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/AgentIdentityUtils.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/AgentIdentityUtils.java index 39b7cbc7a4d1..60e5504d074b 100644 --- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/AgentIdentityUtils.java +++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/AgentIdentityUtils.java @@ -32,6 +32,7 @@ import com.google.api.client.json.GenericJson; import com.google.api.client.json.JsonObjectParser; +import com.google.auth.mtls.MtlsHttpTransportFactory; import com.google.auth.mtls.MtlsUtils; import com.google.auth.oauth2.AgentIdentityCacheUtils.CachedAgentIdentityInfo; import com.google.auth.oauth2.AgentIdentityCacheUtils.FileMetadata; @@ -169,6 +170,7 @@ static class CertInfo { private final X509Certificate certificate; private final String certContent; private final @Nullable KeyStore keyStore; + private final @Nullable MtlsHttpTransportFactory mtlsTransportFactory; CertInfo(final X509Certificate certificate, final String certContent) { this(certificate, certContent, null); @@ -181,6 +183,7 @@ static class CertInfo { this.certificate = certificate; this.certContent = certContent; this.keyStore = keyStore; + this.mtlsTransportFactory = keyStore != null ? new MtlsHttpTransportFactory(keyStore) : null; } /** Returns the parsed {@link X509Certificate}. */ @@ -200,6 +203,18 @@ String getCertContent() { @Nullable KeyStore getKeyStore() { return keyStore; } + + /** + * Returns the shared {@link MtlsHttpTransportFactory} for this certificate snapshot, or {@code + * null} if no {@link KeyStore} is available. + * + *

The underlying {@link com.google.api.client.http.javanet.NetHttpTransport} is created + * lazily on first use and reused across calls bound to this snapshot for TLS session resumption + * and HTTP keep-alive reuse, and is replaced automatically on rotation. + */ + @Nullable MtlsHttpTransportFactory getMtlsTransportFactory() { + return mtlsTransportFactory; + } } /** Holds the resolved filesystem paths for the certificate and private key. */ diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/IamUtils.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/IamUtils.java index 342567a030a7..e6bedf12ec1e 100644 --- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/IamUtils.java +++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/IamUtils.java @@ -49,7 +49,6 @@ import com.google.auth.ServiceAccountSigner; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.http.HttpTransportFactory; -import com.google.auth.mtls.MtlsHttpTransportFactory; import com.google.auth.oauth2.MetricsUtils.RequestType; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Strings; @@ -99,9 +98,10 @@ class IamUtils { // for example iamcredentials.mtls.googleapis.com. private static final String MTLS_DOMAIN_PREFIX = "mtls."; - // Creates the mTLS transport factory for a bound token's key store. Replaced only in tests. - private static volatile Function mtlsTransportFactoryProvider = - MtlsHttpTransportFactory::new; + // Overrides the per-CertInfo mTLS transport factory in tests; null uses CertInfo's shared + // MtlsHttpTransportFactory. + private static volatile @Nullable Function + mtlsTransportFactoryProvider; /** * The credentials, transport and endpoint domain to use for one IAM Credentials call. @@ -244,25 +244,28 @@ private static boolean isSameBoundToken( } @VisibleForTesting - static void setMtlsTransportFactoryProvider(Function provider) { + static void setMtlsTransportFactoryProvider( + @Nullable Function provider) { mtlsTransportFactoryProvider = provider; } @VisibleForTesting static void resetForTest() { - mtlsTransportFactoryProvider = MtlsHttpTransportFactory::new; + mtlsTransportFactoryProvider = null; } /** - * Like {@link #resolveCallTarget}, without the transport check, and with the mTLS transport - * factory supplied by the caller. + * Like {@link #resolveCallTarget}, without the transport check, and with an optional mTLS + * transport factory override supplied by the caller (when {@code null}, uses the shared {@link + * com.google.auth.mtls.MtlsHttpTransportFactory} on the token's {@link + * AgentIdentityUtils.CertInfo}). */ @VisibleForTesting static IamCallTarget resolveBoundTokenCallTarget( Credentials authCredentials, HttpTransportFactory transportFactory, String universeDomain, - Function mtlsTransportFactory) + @Nullable Function mtlsTransportFactory) throws IOException { IamCallTarget defaultTarget = new IamCallTarget(authCredentials, transportFactory, universeDomain, /* usesMtls= */ false); @@ -279,10 +282,18 @@ static IamCallTarget resolveBoundTokenCallTarget( return defaultTarget; } BoundAccessToken boundToken = (BoundAccessToken) token; - KeyStore keyStore = boundToken.getCertInfo().getKeyStore(); + AgentIdentityUtils.CertInfo certInfo = boundToken.getCertInfo(); + KeyStore keyStore = certInfo.getKeyStore(); if (keyStore == null) { return defaultTarget; } + HttpTransportFactory resolvedTransportFactory = + mtlsTransportFactory != null + ? mtlsTransportFactory.apply(keyStore) + : certInfo.getMtlsTransportFactory(); + if (resolvedTransportFactory == null) { + return defaultTarget; + } // Authenticate with exactly this token: the source credentials could otherwise refresh and // attach a token bound to a different certificate. Calling refresh() populates OAuthValue in // memory via getAdditionalHeaders() after quotaProjectId is initialized, so x-goog-user-project @@ -293,7 +304,7 @@ static IamCallTarget resolveBoundTokenCallTarget( pinnedTokenCredentials.refresh(); return new IamCallTarget( pinnedTokenCredentials, - mtlsTransportFactory.apply(keyStore), + resolvedTransportFactory, MTLS_DOMAIN_PREFIX + universeDomain, /* usesMtls= */ true); } diff --git a/google-auth-library-java/oauth2_http/javatests/com/google/auth/mtls/MtlsHttpTransportFactoryTest.java b/google-auth-library-java/oauth2_http/javatests/com/google/auth/mtls/MtlsHttpTransportFactoryTest.java index c7c447bbe229..cd37237aeff9 100644 --- a/google-auth-library-java/oauth2_http/javatests/com/google/auth/mtls/MtlsHttpTransportFactoryTest.java +++ b/google-auth-library-java/oauth2_http/javatests/com/google/auth/mtls/MtlsHttpTransportFactoryTest.java @@ -34,6 +34,9 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -47,10 +50,18 @@ import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.SequenceInputStream; +import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.cert.Certificate; import java.security.cert.CertificateFactory; +import java.util.ArrayList; import java.util.Enumeration; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.Test; class MtlsHttpTransportFactoryTest { @@ -175,4 +186,98 @@ void hasKeyStore_cachesStateAtConstructionTime() throws Exception { // hasKeyStore() should still return the cached true value evaluated at construction assertTrue(factory.hasKeyStore()); } + + private static KeyStore loadTestMtlsKeyStore() throws Exception { + try (InputStream certStream = new FileInputStream(new File(TEST_CERT_PATH)); + InputStream keyStream = new FileInputStream(new File(TEST_KEY_PATH)); + InputStream combined = new SequenceInputStream(certStream, keyStream)) { + return SecurityUtils.createMtlsKeyStore(combined); + } + } + + @Test + void create_reusesSameNetHttpTransportInstance() throws Exception { + MtlsHttpTransportFactory factory = new MtlsHttpTransportFactory(loadTestMtlsKeyStore()); + + NetHttpTransport first = factory.create(); + NetHttpTransport second = factory.create(); + + assertNotNull(first); + assertSame(first, second); + } + + @Test + void create_concurrentCalls_returnSameNetHttpTransportInstance() throws Exception { + MtlsHttpTransportFactory factory = new MtlsHttpTransportFactory(loadTestMtlsKeyStore()); + int threadCount = 8; + ExecutorService executor = Executors.newFixedThreadPool(threadCount); + CountDownLatch readyLatch = new CountDownLatch(threadCount); + CountDownLatch startLatch = new CountDownLatch(1); + try { + List> futures = new ArrayList<>(); + for (int i = 0; i < threadCount; i++) { + futures.add( + executor.submit( + () -> { + readyLatch.countDown(); + assertTrue(startLatch.await(10, TimeUnit.SECONDS)); + return factory.create(); + })); + } + assertTrue(readyLatch.await(10, TimeUnit.SECONDS)); + startLatch.countDown(); + + NetHttpTransport first = futures.get(0).get(30, TimeUnit.SECONDS); + assertNotNull(first); + for (Future future : futures) { + assertSame(first, future.get(30, TimeUnit.SECONDS)); + } + } finally { + executor.shutdownNow(); + executor.awaitTermination(5, TimeUnit.SECONDS); + } + } + + @Test + void create_uninitializedKeyStore_throwsAndDoesNotCacheFailure() throws Exception { + KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); + MtlsHttpTransportFactory factory = new MtlsHttpTransportFactory(keyStore); + + RuntimeException exception = assertThrows(RuntimeException.class, factory::create); + assertTrue(exception.getCause() instanceof GeneralSecurityException); + + keyStore.load(null, null); + NetHttpTransport first = factory.create(); + NetHttpTransport second = factory.create(); + assertNotNull(first); + assertSame(first, second); + } + + @Test + void serialization_roundTripAfterCreate_succeedsAndCachesNewTransport() throws Exception { + MtlsHttpTransportFactory factory = new MtlsHttpTransportFactory(loadTestMtlsKeyStore()); + NetHttpTransport beforeSerialization = factory.create(); + assertNotNull(beforeSerialization); + assertTrue(beforeSerialization.isMtls()); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + try (ObjectOutputStream oos = new ObjectOutputStream(baos)) { + oos.writeObject(factory); + } + + MtlsHttpTransportFactory deserialized; + try (ObjectInputStream ois = + new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()))) { + deserialized = (MtlsHttpTransportFactory) ois.readObject(); + } + + assertNotNull(deserialized); + assertFalse(deserialized.hasKeyStore()); + assertNull(deserialized.getKeyStore()); + NetHttpTransport afterDeserialization = deserialized.create(); + assertNotNull(afterDeserialization); + assertFalse(afterDeserialization.isMtls()); + assertNotSame(beforeSerialization, afterDeserialization); + assertSame(afterDeserialization, deserialized.create()); + } } diff --git a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java index 99f0b78c6f2e..76908c12f448 100644 --- a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java +++ b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java @@ -41,6 +41,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.api.client.http.HttpStatusCodes; +import com.google.api.client.http.HttpTransport; import com.google.api.client.http.LowLevelHttpRequest; import com.google.api.client.http.LowLevelHttpResponse; import com.google.api.client.json.GenericJson; @@ -65,6 +66,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; import java.security.KeyStore; import java.util.Collections; import java.util.Date; @@ -73,6 +75,7 @@ import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -104,6 +107,12 @@ void setup() throws IOException { Mockito.when(credentials.getUniverseDomain()).thenReturn("googleapis.com"); } + @AfterEach + void tearDown() { + IamUtils.resetForTest(); + AgentIdentityUtils.resetForTest(); + } + @Test void sign_success_noRetry() { byte[] expectedSignature = {0xD, 0xE, 0xA, 0xD}; @@ -1098,4 +1107,247 @@ void resolveCallTarget_pinnedTokenCredentials_isNotSerializable() throws Excepti assertThrows(NotSerializableException.class, () -> out.writeObject(target.credentials)); } } + + @Test + void certInfo_withoutKeyStore_hasNullMtlsTransportFactory() throws Exception { + AgentIdentityUtils.CertInfo loaded = loadAgentCertInfo(); + assertNotNull(loaded.getMtlsTransportFactory()); + assertSame(loaded.getKeyStore(), loaded.getMtlsTransportFactory().getKeyStore()); + + AgentIdentityUtils.CertInfo withoutKey = + new AgentIdentityUtils.CertInfo(loaded.getCertificate(), loaded.getCertContent()); + assertNull(withoutKey.getMtlsTransportFactory()); + } + + @Test + void resolveCallTarget_repeatedCallsWithSameCertInfo_reusesTransportFactoryAndTransport() + throws Exception { + AgentIdentityUtils.CertInfo certInfo = loadAgentCertInfo(); + ComputeEngineCredentials source1 = + computeEngineCredentialsWithToken( + new BoundAccessToken("bound-token-1", oneHourFromNow(), certInfo)); + ComputeEngineCredentials source2 = + computeEngineCredentialsWithToken( + new BoundAccessToken("bound-token-2", oneHourFromNow(), certInfo)); + + IamUtils.IamCallTarget target1 = + IamUtils.resolveCallTarget( + source1, OAuth2Utils.HTTP_TRANSPORT_FACTORY, Credentials.GOOGLE_DEFAULT_UNIVERSE); + IamUtils.IamCallTarget target2 = + IamUtils.resolveCallTarget( + source1, OAuth2Utils.HTTP_TRANSPORT_FACTORY, Credentials.GOOGLE_DEFAULT_UNIVERSE); + IamUtils.IamCallTarget target3 = + IamUtils.resolveCallTarget( + source2, OAuth2Utils.HTTP_TRANSPORT_FACTORY, Credentials.GOOGLE_DEFAULT_UNIVERSE); + + assertSame(certInfo.getMtlsTransportFactory(), target1.transportFactory); + assertSame(target1.transportFactory, target2.transportFactory); + assertSame(target1.transportFactory, target3.transportFactory); + + HttpTransport transport1 = target1.transportFactory.create(); + assertNotNull(transport1); + assertSame(transport1, target2.transportFactory.create()); + assertSame(transport1, target3.transportFactory.create()); + } + + @Test + void + resolveBoundTokenCallTarget_nullOverrideUsesCertInfoFactory_providerReturningNullUsesDefault() + throws Exception { + AgentIdentityUtils.CertInfo certInfo = loadAgentCertInfo(); + ComputeEngineCredentials source = + computeEngineCredentialsWithToken( + new BoundAccessToken("bound-token", oneHourFromNow(), certInfo)); + HttpTransportFactory defaultFactory = MockHttpTransport::new; + + IamUtils.IamCallTarget defaultMtlsTarget = + IamUtils.resolveBoundTokenCallTarget( + source, defaultFactory, Credentials.GOOGLE_DEFAULT_UNIVERSE, null); + assertTrue(defaultMtlsTarget.usesMtls()); + assertSame(certInfo.getMtlsTransportFactory(), defaultMtlsTarget.transportFactory); + + IamUtils.IamCallTarget nullProviderTarget = + IamUtils.resolveBoundTokenCallTarget( + source, defaultFactory, Credentials.GOOGLE_DEFAULT_UNIVERSE, keyStore -> null); + assertFalse(nullProviderTarget.usesMtls()); + assertSame(source, nullProviderTarget.credentials); + assertSame(defaultFactory, nullProviderTarget.transportFactory); + assertEquals(Credentials.GOOGLE_DEFAULT_UNIVERSE, nullProviderTarget.endpointDomain); + } + + private static Path configureMutableAgentCertEnv( + Path tempDir, String initialCertResource, String keyResource) throws Exception { + Path certFile = tempDir.resolve("cert.pem"); + Path keyFile = tempDir.resolve("key.pem"); + Files.copy( + Paths.get(IamUtilsTest.class.getResource(initialCertResource).toURI()), + certFile, + StandardCopyOption.REPLACE_EXISTING); + Files.copy( + Paths.get(IamUtilsTest.class.getResource(keyResource).toURI()), + keyFile, + StandardCopyOption.REPLACE_EXISTING); + + Path configPath = tempDir.resolve("certificate_config.json"); + Map workload = new HashMap<>(); + workload.put("cert_path", certFile.toString()); + workload.put("key_path", keyFile.toString()); + Map certConfigs = new HashMap<>(); + certConfigs.put("workload", workload); + Map config = new HashMap<>(); + config.put("cert_configs", certConfigs); + Files.write( + configPath, OAuth2Utils.JSON_FACTORY.toString(config).getBytes(StandardCharsets.UTF_8)); + + TestEnvironmentProvider envProvider = new TestEnvironmentProvider(); + envProvider.setEnv(AgentIdentityUtils.GOOGLE_API_CERTIFICATE_CONFIG, configPath.toString()); + AgentIdentityUtils.resetForTest(); + AgentIdentityUtils.setEnvironmentProvider(envProvider); + AgentIdentityUtils.setPropertyProvider(new TestPropertyProvider()); + AgentIdentityUtils.setWellKnownDir(tempDir.resolve("no-spiffe").toString()); + return certFile; + } + + private static void rotateCertFileInPlace(Path certFile, String rotatedCertResource) + throws Exception { + Path tmpCert = certFile.resolveSibling("cert.pem.tmp"); + Files.copy( + Paths.get(IamUtilsTest.class.getResource(rotatedCertResource).toURI()), + tmpCert, + StandardCopyOption.REPLACE_EXISTING); + Files.move(tmpCert, certFile, StandardCopyOption.REPLACE_EXISTING); + } + + @Test + void resolveCallTarget_certificateRotation_usesNewTransportFactoryAndTransport( + @TempDir Path tempDir) throws Exception { + Path certFile = + configureMutableAgentCertEnv( + tempDir, "/agent/agent_spiffe_cert.pem", "/agent/agent_spiffe_key.pem"); + AtomicReference nextToken = new AtomicReference<>("bound-token-a1"); + AtomicInteger metadataRequests = new AtomicInteger(); + MockHttpTransport metadataTransport = newMetadataTokenTransport(nextToken, metadataRequests); + ComputeEngineCredentials source = + ComputeEngineCredentials.newBuilder() + .setHttpTransportFactory(() -> metadataTransport) + .setUniverseDomain(Credentials.GOOGLE_DEFAULT_UNIVERSE) + .build(); + + IamUtils.IamCallTarget targetA1 = + IamUtils.resolveCallTarget( + source, OAuth2Utils.HTTP_TRANSPORT_FACTORY, Credentials.GOOGLE_DEFAULT_UNIVERSE); + assertEquals(1, metadataRequests.get()); + assertTrue(targetA1.usesMtls()); + assertTrue(targetA1.transportFactory instanceof MtlsHttpTransportFactory); + assertEquals( + 1, + ((MtlsHttpTransportFactory) targetA1.transportFactory) + .getKeyStore() + .getCertificateChain("alias") + .length); + HttpTransport transportA = targetA1.transportFactory.create(); + assertNotNull(transportA); + + // Refresh the access token while the on-disk certificate is unchanged: CertInfo cache hit + // must keep reusing the same MtlsHttpTransportFactory and NetHttpTransport. + nextToken.set("bound-token-a2"); + source.refresh(); + IamUtils.IamCallTarget targetA2 = + IamUtils.resolveCallTarget( + source, OAuth2Utils.HTTP_TRANSPORT_FACTORY, Credentials.GOOGLE_DEFAULT_UNIVERSE); + assertEquals(2, metadataRequests.get()); + assertTrue(targetA2.usesMtls()); + assertSame(targetA1.transportFactory, targetA2.transportFactory); + assertSame(transportA, targetA2.transportFactory.create()); + + // Rotate the certificate file on disk without clearing AgentIdentityUtils static caches. + rotateCertFileInPlace(certFile, "/agent/agent_spiffe_cert_chain.pem"); + nextToken.set("bound-token-b"); + source.refresh(); + + IamUtils.IamCallTarget targetB1 = + IamUtils.resolveCallTarget( + source, OAuth2Utils.HTTP_TRANSPORT_FACTORY, Credentials.GOOGLE_DEFAULT_UNIVERSE); + IamUtils.IamCallTarget targetB2 = + IamUtils.resolveCallTarget( + source, OAuth2Utils.HTTP_TRANSPORT_FACTORY, Credentials.GOOGLE_DEFAULT_UNIVERSE); + + assertEquals(3, metadataRequests.get()); + assertTrue(targetB1.usesMtls()); + assertTrue(targetB1.transportFactory instanceof MtlsHttpTransportFactory); + assertEquals( + 2, + ((MtlsHttpTransportFactory) targetB1.transportFactory) + .getKeyStore() + .getCertificateChain("alias") + .length); + assertNotSame(targetA1.transportFactory, targetB1.transportFactory); + assertSame(targetB1.transportFactory, targetB2.transportFactory); + HttpTransport transportB = targetB1.transportFactory.create(); + assertNotNull(transportB); + assertNotSame(transportA, transportB); + assertSame(transportB, targetB2.transportFactory.create()); + // Any in-flight target from before rotation keeps using Cert A's transport. + assertSame(transportA, targetA1.transportFactory.create()); + } + + @Test + void refreshAndResolveRetryTarget_tokenRefreshReusesTransport_certRotationReplacesTransport( + @TempDir Path tempDir) throws Exception { + Path certFile = + configureMutableAgentCertEnv( + tempDir, "/agent/agent_spiffe_cert.pem", "/agent/agent_spiffe_key.pem"); + AtomicReference nextToken = new AtomicReference<>("bound-token-1"); + AtomicInteger metadataRequests = new AtomicInteger(); + MockHttpTransport metadataTransport = newMetadataTokenTransport(nextToken, metadataRequests); + ComputeEngineCredentials source = + ComputeEngineCredentials.newBuilder() + .setHttpTransportFactory(() -> metadataTransport) + .setUniverseDomain(Credentials.GOOGLE_DEFAULT_UNIVERSE) + .build(); + + IamUtils.IamCallTarget initialTarget = + IamUtils.resolveCallTarget( + source, OAuth2Utils.HTTP_TRANSPORT_FACTORY, Credentials.GOOGLE_DEFAULT_UNIVERSE); + assertTrue(initialTarget.usesMtls()); + HttpTransport transportA = initialTarget.transportFactory.create(); + assertNotNull(transportA); + + // 401 retry when only the token changes (same on-disk cert) reuses the cached transport. + nextToken.set("bound-token-2"); + IamUtils.IamCallTarget tokenOnlyRetry = + IamUtils.refreshAndResolveRetryTarget( + source, + OAuth2Utils.HTTP_TRANSPORT_FACTORY, + Credentials.GOOGLE_DEFAULT_UNIVERSE, + initialTarget); + assertNotNull(tokenOnlyRetry); + assertTrue(tokenOnlyRetry.usesMtls()); + assertEquals(2, metadataRequests.get()); + assertSame(initialTarget.transportFactory, tokenOnlyRetry.transportFactory); + assertSame(transportA, tokenOnlyRetry.transportFactory.create()); + + // 401 retry after on-disk certificate rotation switches to the new CertInfo's transport. + rotateCertFileInPlace(certFile, "/agent/agent_spiffe_cert_chain.pem"); + nextToken.set("bound-token-3"); + IamUtils.IamCallTarget rotatedRetry = + IamUtils.refreshAndResolveRetryTarget( + source, + OAuth2Utils.HTTP_TRANSPORT_FACTORY, + Credentials.GOOGLE_DEFAULT_UNIVERSE, + tokenOnlyRetry); + assertNotNull(rotatedRetry); + assertTrue(rotatedRetry.usesMtls()); + assertEquals(3, metadataRequests.get()); + assertNotSame(initialTarget.transportFactory, rotatedRetry.transportFactory); + HttpTransport transportB = rotatedRetry.transportFactory.create(); + assertNotNull(transportB); + assertNotSame(transportA, transportB); + assertEquals( + 2, + ((MtlsHttpTransportFactory) rotatedRetry.transportFactory) + .getKeyStore() + .getCertificateChain("alias") + .length); + } }