Skip to content
Merged
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 @@ -197,7 +197,7 @@ public boolean equals(Object obj) {

private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException {
input.defaultReadObject();
executorFactory = ServiceOptions.newInstance(executorFactoryClassName);
executorFactory = ServiceOptions.newInstance(executorFactoryClassName, ExecutorFactory.class);
}

public static Builder newBuilder() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,13 @@
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;

import com.google.cloud.ServiceOptions;
import com.google.cloud.grpc.GrpcTransportOptions.DefaultExecutorFactory;
import com.google.cloud.grpc.GrpcTransportOptions.ExecutorFactory;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.concurrent.ScheduledExecutorService;
import org.easymock.EasyMock;
import org.junit.jupiter.api.Test;
Expand Down Expand Up @@ -67,4 +72,26 @@ void testDefaultExecutorFactory() {
ScheduledExecutorService executorService = executorFactory.get();
assertSame(executorService, executorFactory.get());
}

@Test
void testSerializationRoundTrip() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
oos.writeObject(DEFAULT_OPTIONS);
}
GrpcTransportOptions deserialized;
try (ObjectInputStream ois =
new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()))) {
deserialized = (GrpcTransportOptions) ois.readObject();
}
assertEquals(DEFAULT_OPTIONS, deserialized);
assertTrue(deserialized.getExecutorFactory() instanceof DefaultExecutorFactory);
}

@Test
@SuppressWarnings("deprecation")
void testDeprecatedNewInstance_executorFactory() throws Exception {
Object instance = ServiceOptions.newInstance(DefaultExecutorFactory.class.getName());
assertTrue(instance instanceof DefaultExecutorFactory);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,8 @@ public boolean equals(Object obj) {

private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException {
input.defaultReadObject();
httpTransportFactory = ServiceOptions.newInstance(httpTransportFactoryClassName);
httpTransportFactory =
ServiceOptions.newInstance(httpTransportFactoryClassName, HttpTransportFactory.class);
}

public static Builder newBuilder() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,11 @@
import com.google.cloud.TransportOptions;
import com.google.cloud.http.HttpTransportOptions.DefaultHttpTransportFactory;
import com.google.cloud.spi.ServiceRpcFactory;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Set;
import java.util.regex.Pattern;
Expand Down Expand Up @@ -364,4 +368,19 @@ public int hashCode() {
return baseHashCode();
}
}

@Test
void testSerializationRoundTrip() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
oos.writeObject(DEFAULT_OPTIONS);
}
HttpTransportOptions deserialized;
try (ObjectInputStream ois =
new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()))) {
deserialized = (HttpTransportOptions) ois.readObject();
}
assertEquals(DEFAULT_OPTIONS, deserialized);
assertTrue(deserialized.getHttpTransportFactory() instanceof DefaultHttpTransportFactory);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
import com.google.api.gax.tracing.ApiTracerFactory;
import com.google.auth.ApiKeyCredentials;
import com.google.auth.Credentials;
import com.google.auth.http.HttpTransportFactory;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.auth.oauth2.QuotaProjectIdProvider;
import com.google.auth.oauth2.ServiceAccountCredentials;
Expand Down Expand Up @@ -87,6 +88,8 @@ public abstract class ServiceOptions<
private static final String DEFAULT_HOST = "https://www.googleapis.com";
private static final String LEGACY_PROJECT_ENV_NAME = "GCLOUD_PROJECT";
private static final String PROJECT_ENV_NAME = "GOOGLE_CLOUD_PROJECT";
private static final String GRPC_EXECUTOR_FACTORY_CLASS_NAME =
"com.google.cloud.grpc.GrpcTransportOptions$ExecutorFactory";

private static final RetrySettings DEFAULT_RETRY_SETTINGS =
getDefaultRetrySettingsBuilder().build();
Expand Down Expand Up @@ -784,16 +787,57 @@ protected boolean baseEquals(ServiceOptions<?, ?> other) {

private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException {
input.defaultReadObject();
serviceFactory = newInstance(serviceFactoryClassName);
serviceRpcFactory = newInstance(serviceRpcFactoryClassName);
serviceFactory = newInstance(serviceFactoryClassName, ServiceFactory.class);
serviceRpcFactory = newInstance(serviceRpcFactoryClassName, ServiceRpcFactory.class);
}

@SuppressWarnings("unchecked")
/**
* @deprecated Use {@link #newInstance(String, Class)} instead to validate the expected type.
*/
@Deprecated
@InternalApi
public static <T> T newInstance(String className) throws IOException, ClassNotFoundException {
ClassLoader classLoader = ServiceOptions.class.getClassLoader();
// Avoid running static initializers before verifying the class type.
Class<?> clazz = Class.forName(className, false, classLoader);
if (!isAllowedFactoryClass(clazz, classLoader)) {
throw new IOException("Class " + className + " is not an allowed factory type");
}
return instantiate(clazz);
}

@InternalApi
public static <T> T newInstance(String className, Class<?> expected)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you think we can mark the other newInstance() variant (the one without the expected class) as obsolete and tell any users to use this variant instead for security (I doubt we have any public users of this, but just in case)?

I think this is probably the best practice to reduce any attack vectors.

@whowes whowes Nov 30, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added @Deprecated to the single-arg newInstance() with a pointer to use the new 2-arg version. IMO it makes more sense than @ObsoleteApi for @InternalApi methods.

After thinking about it some more I also opted to harden the deprecated version by checking that the class is assignable to a small allowlist (the factory interfaces used by the existing internal callers). I think the only reason to keep it around is for possible version skew effects, and after some soak time I think we'll be able to safely remove it.

throws IOException, ClassNotFoundException {
// Avoid running static initializers before verifying the class type.
Class<?> clazz = Class.forName(className, false, ServiceOptions.class.getClassLoader());
if (!expected.isAssignableFrom(clazz)) {
throw new IOException("Class " + className + " is not assignable to " + expected.getName());
}
return instantiate(clazz);
}

private static boolean isAllowedFactoryClass(Class<?> clazz, ClassLoader classLoader) {
if (ServiceFactory.class.isAssignableFrom(clazz)
|| ServiceRpcFactory.class.isAssignableFrom(clazz)
|| HttpTransportFactory.class.isAssignableFrom(clazz)) {
return true;
}
// google-cloud-core-grpc depends on google-cloud-core, so resolve ExecutorFactory by name.
try {
Class<?> executorFactory =
Class.forName(GRPC_EXECUTOR_FACTORY_CLASS_NAME, false, classLoader);
return executorFactory.isAssignableFrom(clazz);
} catch (ClassNotFoundException e) {
return false;
}
}

@SuppressWarnings("unchecked")
private static <T> T instantiate(Class<?> clazz) throws IOException {
try {
return (T) Class.forName(className).newInstance();
} catch (InstantiationException | IllegalAccessException e) {
return (T) clazz.getDeclaredConstructor().newInstance();
} catch (ReflectiveOperationException e) {
throw new IOException(e);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,19 +38,24 @@
import com.google.api.core.ApiClock;
import com.google.api.core.CurrentMillisClock;
import com.google.auth.ApiKeyCredentials;
import com.google.auth.http.HttpTransportFactory;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.auth.oauth2.ServiceAccountCredentials;
import com.google.cloud.spi.ServiceRpcFactory;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import com.google.common.io.Files;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Pattern;
import org.junit.jupiter.api.Test;

Expand Down Expand Up @@ -758,6 +763,102 @@ void testGetScopedCredentials_useJwtAccessWithScope_overridesCredentials() {
assertThat(((ServiceAccountCredentials) scoped).getUseJwtAccessWithScope()).isFalse();
}

private static final AtomicBoolean DISALLOWED_CLASS_INITIALIZED = new AtomicBoolean(false);

public static class DisallowedClass {
static {
DISALLOWED_CLASS_INITIALIZED.set(true);
}
}

public static class PublicTestServiceFactory implements TestServiceFactory {
@Override
public TestService create(TestServiceOptions options) {
return new TestServiceImpl(options);
}
}

public static class PublicTestServiceRpcFactory implements TestServiceRpcFactory {
@Override
public TestServiceRpc create(TestServiceOptions options) {
return new DefaultTestServiceRpc(options);
}
}

public static class PublicTestHttpTransportFactory implements HttpTransportFactory {
@Override
public HttpTransport create() {
return new MockHttpTransport();
}
}

private static class SerializableTransportOptions implements TransportOptions {
private static final long serialVersionUID = 1L;
}

@Test
void testNewInstance_disallowedClassDoesNotInitialize() {
IOException exception =
assertThrows(
IOException.class,
() ->
ServiceOptions.newInstance(DisallowedClass.class.getName(), ServiceFactory.class));
assertThat(exception).hasMessageThat().contains("is not assignable to");
assertThat(DISALLOWED_CLASS_INITIALIZED.get()).isFalse();
}

@Test
@SuppressWarnings("deprecation")
void testNewInstance_deprecated_disallowedClassDoesNotInitialize() {
IOException exception =
assertThrows(
IOException.class, () -> ServiceOptions.newInstance(DisallowedClass.class.getName()));
assertThat(exception).hasMessageThat().contains("is not an allowed factory type");
assertThat(DISALLOWED_CLASS_INITIALIZED.get()).isFalse();
}

@Test
@SuppressWarnings("deprecation")
void testNewInstance_deprecated_allowedFactoryTypes() throws Exception {
Object serviceFactory = ServiceOptions.newInstance(PublicTestServiceFactory.class.getName());
assertThat(serviceFactory).isInstanceOf(PublicTestServiceFactory.class);

Object serviceRpcFactory =
ServiceOptions.newInstance(PublicTestServiceRpcFactory.class.getName());
assertThat(serviceRpcFactory).isInstanceOf(PublicTestServiceRpcFactory.class);

Object httpTransportFactory =
ServiceOptions.newInstance(PublicTestHttpTransportFactory.class.getName());
assertThat(httpTransportFactory).isInstanceOf(PublicTestHttpTransportFactory.class);
}

@Test
void testReadObject_validSerializationRoundTrip() throws Exception {
TestServiceOptions options =
TestServiceOptions.newBuilder()
.setProjectId("project-id")
.setCredentials(NoCredentials.getInstance())
.setClock(CurrentMillisClock.getDefaultClock())
.setServiceFactory(new PublicTestServiceFactory())
.setServiceRpcFactory(new PublicTestServiceRpcFactory())
.setTransportOptions(new SerializableTransportOptions())
.build();

ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
oos.writeObject(options);
}
TestServiceOptions deserialized;
try (ObjectInputStream ois =
new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()))) {
deserialized = (TestServiceOptions) ois.readObject();
}

assertThat(deserialized).isEqualTo(options);
assertThat(deserialized.getService()).isInstanceOf(TestServiceImpl.class);
assertThat(deserialized.getRpc()).isInstanceOf(DefaultTestServiceRpc.class);
}

private HttpResponse createHttpResponseWithHeader(final Multimap<String, String> headers)
throws Exception {
HttpTransport mockHttpTransport =
Expand Down
Loading