Skip to content
Draft
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
@@ -0,0 +1,50 @@
/*
* Copyright 2026, Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

package com.google.auth.http;

import java.io.IOException;
import org.jspecify.annotations.NullMarked;

/**
* An interface for {@link HttpTransportFactory} implementations whose underlying context can be
* rebuilt dynamically (e.g. reloading mTLS certificates from disk).
*/
@NullMarked
public interface ContextRebuildableTransportFactory extends HttpTransportFactory {

/**
* Rebuilds the underlying transport context (such as reloading a KeyStore or SSLSocketFactory).
*
* @throws IOException if rebuilding the context fails
*/
void rebuildContext() throws IOException;
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,18 @@

import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.core.InternalApi;
import com.google.auth.http.HttpTransportFactory;
import com.google.auth.http.ContextRebuildableTransportFactory;
import com.google.common.annotations.VisibleForTesting;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.util.Objects;
import javax.net.ssl.SSLSocketFactory;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;

/**
* An HttpTransportFactory that creates {@link NetHttpTransport} instances configured for mTLS
Expand All @@ -49,8 +56,10 @@
*/
@NullMarked
@InternalApi
public class MtlsHttpTransportFactory implements HttpTransportFactory {
private final KeyStore mtlsKeyStore;
public class MtlsHttpTransportFactory implements ContextRebuildableTransportFactory {
@Nullable private final MtlsProvider mtlsProvider;
private volatile KeyStore mtlsKeyStore;
private final DelegatingSSLSocketFactory sslSocketFactory;

/**
* Constructs a factory for mTLS transports.
Expand All @@ -61,17 +70,121 @@ public class MtlsHttpTransportFactory implements HttpTransportFactory {
*/
public MtlsHttpTransportFactory(KeyStore mtlsKeyStore) {
this.mtlsKeyStore = Objects.requireNonNull(mtlsKeyStore, "mtlsKeyStore cannot be null");
this.mtlsProvider = null;
try {
this.sslSocketFactory = new DelegatingSSLSocketFactory(buildSslSocketFactory(mtlsKeyStore));
} catch (GeneralSecurityException e) {
throw new RuntimeException("Failed to initialize mTLS transport.", e);
}
}

@Override
public NetHttpTransport create() {
/**
* Constructs a factory for mTLS transports using an {@link MtlsProvider}.
*
* @param mtlsProvider The {@link MtlsProvider} providing the client's KeyStore.
* @throws CertificateSourceUnavailableException if the certificate source is unavailable
* @throws IOException if a general I/O error occurs while creating the KeyStore
*/
public MtlsHttpTransportFactory(MtlsProvider mtlsProvider)
throws CertificateSourceUnavailableException, IOException {
this.mtlsProvider = Objects.requireNonNull(mtlsProvider, "mtlsProvider cannot be null");
this.mtlsKeyStore = mtlsProvider.getKeyStore();
try {
// Build the mTLS transport using the provided KeyStore.
return new NetHttpTransport.Builder().trustCertificates(null, mtlsKeyStore, "").build();
this.sslSocketFactory =
new DelegatingSSLSocketFactory(buildSslSocketFactory(this.mtlsKeyStore));
} 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);
}
}

private static SSLSocketFactory buildSslSocketFactory(KeyStore keyStore)
throws GeneralSecurityException {
return new NetHttpTransport.Builder()
.trustCertificates(null, keyStore, "")
.getSslSocketFactory();
}

/**
* Reloads the KeyStore from the underlying MtlsProvider if configured and rebuilds the SSL socket
* factory.
*
* @throws IOException if an I/O error occurs while reloading the KeyStore
*/
public synchronized void rebuildContext() throws IOException {
if (this.mtlsProvider != null) {
try {
this.mtlsKeyStore = this.mtlsProvider.getKeyStore();
this.sslSocketFactory.setDelegate(buildSslSocketFactory(this.mtlsKeyStore));
} catch (CertificateSourceUnavailableException e) {
throw new IOException("Failed to reload KeyStore from MtlsProvider.", e);
} catch (GeneralSecurityException e) {
throw new IOException("Failed to rebuild SSLSocketFactory.", e);
}
}
}

@VisibleForTesting
KeyStore getKeyStore() {
return mtlsKeyStore;
}

@Override
public NetHttpTransport create() {
return new NetHttpTransport.Builder().setSslSocketFactory(sslSocketFactory).build();
}

private static class DelegatingSSLSocketFactory extends SSLSocketFactory {
private volatile SSLSocketFactory delegate;

DelegatingSSLSocketFactory(SSLSocketFactory initialDelegate) {
this.delegate = initialDelegate;
}

void setDelegate(SSLSocketFactory newDelegate) {
this.delegate = newDelegate;
}

@Override
public String[] getDefaultCipherSuites() {
return delegate.getDefaultCipherSuites();
}

@Override
public String[] getSupportedCipherSuites() {
return delegate.getSupportedCipherSuites();
}

@Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose)
throws IOException {
return delegate.createSocket(s, host, port, autoClose);
}

@Override
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
return delegate.createSocket(host, port);
}

@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort)
throws IOException, UnknownHostException {
return delegate.createSocket(host, port, localHost, localPort);
}

@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
return delegate.createSocket(host, port);
}

@Override
public Socket createSocket(
InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
return delegate.createSocket(address, port, localAddress, localPort);
}

@Override
public Socket createSocket() throws IOException {
return delegate.createSocket();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,13 @@
import static com.google.common.base.Preconditions.checkNotNull;

import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpUnsuccessfulResponseHandler;
import com.google.api.client.json.GenericJson;
import com.google.api.client.util.Data;
import com.google.auth.RequestMetadataCallback;
import com.google.auth.http.ContextRebuildableTransportFactory;
import com.google.auth.http.HttpTransportFactory;
import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
Expand Down Expand Up @@ -431,6 +435,7 @@ static ExternalAccountCredentials fromJson(
Map<String, Object> json, HttpTransportFactory transportFactory) {
String audience = (String) json.get("audience");
String subjectTokenType = (String) json.get("subject_token_type");
String actorTokenType = (String) json.get("actor_token_type");
String tokenUrl = (String) json.get("token_url");

Map<String, Object> credentialSourceMap = (Map<String, Object>) json.get("credential_source");
Expand Down Expand Up @@ -487,6 +492,7 @@ static ExternalAccountCredentials fromJson(
.setHttpTransportFactory(transportFactory)
.setAudience(audience)
.setSubjectTokenType(subjectTokenType)
.setActorTokenType(actorTokenType)
.setTokenUrl(tokenUrl)
.setTokenInfoUrl(tokenInfoUrl)
.setCredentialSource(new IdentityPoolCredentialSource(credentialSourceMap))
Expand Down Expand Up @@ -564,6 +570,29 @@ protected AccessToken exchangeExternalCredentialForAccessToken(
requestHandler.setInternalOptions(stsTokenExchangeRequest.getInternalOptions());
}

requestHandler.setUnsuccessfulResponseHandler(
new HttpUnsuccessfulResponseHandler() {
boolean retried = false;

@Override
public boolean handleResponse(
HttpRequest request, HttpResponse response, boolean supportsRetry)
throws IOException {
if (response.getStatusCode() != 401) {
return false;
}
if (!(transportFactory instanceof ContextRebuildableTransportFactory)) {
return false;
}
if (retried) {
return false;
}
((ContextRebuildableTransportFactory) transportFactory).rebuildContext();
retried = true;
return true;
}
});

StsTokenExchangeResponse response = requestHandler.build().exchangeToken();
return response.getAccessToken();
}
Expand Down

This file was deleted.

Loading
Loading