Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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.
*
* <p>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.
*
* <p><b>Warning:</b> This class is considered internal and is not intended for direct use by
* library consumers. Its API and behavior may change without notice.
Expand All @@ -58,6 +67,8 @@
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() ==
Expand Down Expand Up @@ -92,12 +103,12 @@
* deserialization), with an empty KeyStore, or with a KeyStore containing only trusted CA
* certificates (without a private key entry and certificate chain) will return {@code false}.
*/
public boolean hasKeyStore() {

Check warning on line 106 in google-auth-library-java/oauth2_http/java/com/google/auth/mtls/MtlsHttpTransportFactory.java

View workflow job for this annotation

GitHub Actions / bom-content-test

Check warning on line 106 in google-auth-library-java/oauth2_http/java/com/google/auth/mtls/MtlsHttpTransportFactory.java

View workflow job for this annotation

GitHub Actions / BomContentAssertionsTest (Test for assertion logic in BomContentTest)

return this.hasKeyStore;
}

/** Returns the {@link KeyStore} used by this factory, or {@code null} if none was configured. */
public @Nullable KeyStore getKeyStore() {

Check warning on line 111 in google-auth-library-java/oauth2_http/java/com/google/auth/mtls/MtlsHttpTransportFactory.java

View workflow job for this annotation

GitHub Actions / bom-content-test

Check warning on line 111 in google-auth-library-java/oauth2_http/java/com/google/auth/mtls/MtlsHttpTransportFactory.java

View workflow job for this annotation

GitHub Actions / BomContentAssertionsTest (Test for assertion logic in BomContentTest)

return this.mtlsKeyStore;
}

Expand Down Expand Up @@ -125,15 +136,37 @@
}
}

/**
* 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();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand All @@ -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}. */
Expand All @@ -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.
*
* <p>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. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<KeyStore, HttpTransportFactory> mtlsTransportFactoryProvider =
MtlsHttpTransportFactory::new;
// Overrides the per-CertInfo mTLS transport factory in tests; null uses CertInfo's shared
// MtlsHttpTransportFactory.
private static volatile @Nullable Function<KeyStore, HttpTransportFactory>
mtlsTransportFactoryProvider;

/**
* The credentials, transport and endpoint domain to use for one IAM Credentials call.
Expand Down Expand Up @@ -244,25 +244,28 @@ private static boolean isSameBoundToken(
}

@VisibleForTesting
static void setMtlsTransportFactoryProvider(Function<KeyStore, HttpTransportFactory> provider) {
static void setMtlsTransportFactoryProvider(
@Nullable Function<KeyStore, HttpTransportFactory> 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<KeyStore, HttpTransportFactory> mtlsTransportFactory)
@Nullable Function<KeyStore, HttpTransportFactory> mtlsTransportFactory)
throws IOException {
IamCallTarget defaultTarget =
new IamCallTarget(authCredentials, transportFactory, universeDomain, /* usesMtls= */ false);
Expand All @@ -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
Expand All @@ -293,7 +304,7 @@ static IamCallTarget resolveBoundTokenCallTarget(
pinnedTokenCredentials.refresh();
return new IamCallTarget(
pinnedTokenCredentials,
mtlsTransportFactory.apply(keyStore),
resolvedTransportFactory,
MTLS_DOMAIN_PREFIX + universeDomain,
/* usesMtls= */ true);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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 {
Expand Down Expand Up @@ -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<Future<NetHttpTransport>> 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<NetHttpTransport> 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());
}
}
Loading
Loading