diff --git a/sdk-platform-java/java-core/google-cloud-core-grpc/src/main/java/com/google/cloud/grpc/GrpcTransportOptions.java b/sdk-platform-java/java-core/google-cloud-core-grpc/src/main/java/com/google/cloud/grpc/GrpcTransportOptions.java index 4db83253a3a1..a488efdb0f3c 100644 --- a/sdk-platform-java/java-core/google-cloud-core-grpc/src/main/java/com/google/cloud/grpc/GrpcTransportOptions.java +++ b/sdk-platform-java/java-core/google-cloud-core-grpc/src/main/java/com/google/cloud/grpc/GrpcTransportOptions.java @@ -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() { diff --git a/sdk-platform-java/java-core/google-cloud-core-grpc/src/test/java/com/google/cloud/grpc/GrpcTransportOptionsTest.java b/sdk-platform-java/java-core/google-cloud-core-grpc/src/test/java/com/google/cloud/grpc/GrpcTransportOptionsTest.java index a112dd5e0741..5cb93c3602f6 100644 --- a/sdk-platform-java/java-core/google-cloud-core-grpc/src/test/java/com/google/cloud/grpc/GrpcTransportOptionsTest.java +++ b/sdk-platform-java/java-core/google-cloud-core-grpc/src/test/java/com/google/cloud/grpc/GrpcTransportOptionsTest.java @@ -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; @@ -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); + } } diff --git a/sdk-platform-java/java-core/google-cloud-core-http/src/main/java/com/google/cloud/http/HttpTransportOptions.java b/sdk-platform-java/java-core/google-cloud-core-http/src/main/java/com/google/cloud/http/HttpTransportOptions.java index 34e5aacdd090..76f36aeebeec 100644 --- a/sdk-platform-java/java-core/google-cloud-core-http/src/main/java/com/google/cloud/http/HttpTransportOptions.java +++ b/sdk-platform-java/java-core/google-cloud-core-http/src/main/java/com/google/cloud/http/HttpTransportOptions.java @@ -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() { diff --git a/sdk-platform-java/java-core/google-cloud-core-http/src/test/java/com/google/cloud/http/HttpTransportOptionsTest.java b/sdk-platform-java/java-core/google-cloud-core-http/src/test/java/com/google/cloud/http/HttpTransportOptionsTest.java index b39ae1584e34..0a4c2c4d60ca 100644 --- a/sdk-platform-java/java-core/google-cloud-core-http/src/test/java/com/google/cloud/http/HttpTransportOptionsTest.java +++ b/sdk-platform-java/java-core/google-cloud-core-http/src/test/java/com/google/cloud/http/HttpTransportOptionsTest.java @@ -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; @@ -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); + } } diff --git a/sdk-platform-java/java-core/google-cloud-core/src/main/java/com/google/cloud/ServiceOptions.java b/sdk-platform-java/java-core/google-cloud-core/src/main/java/com/google/cloud/ServiceOptions.java index 9d59ca11a5bf..9935e384206b 100644 --- a/sdk-platform-java/java-core/google-cloud-core/src/main/java/com/google/cloud/ServiceOptions.java +++ b/sdk-platform-java/java-core/google-cloud-core/src/main/java/com/google/cloud/ServiceOptions.java @@ -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; @@ -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(); @@ -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 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 newInstance(String className, Class expected) + 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 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); } } diff --git a/sdk-platform-java/java-core/google-cloud-core/src/test/java/com/google/cloud/ServiceOptionsTest.java b/sdk-platform-java/java-core/google-cloud-core/src/test/java/com/google/cloud/ServiceOptionsTest.java index b469827f9849..e5e6ff3dfb7f 100644 --- a/sdk-platform-java/java-core/google-cloud-core/src/test/java/com/google/cloud/ServiceOptionsTest.java +++ b/sdk-platform-java/java-core/google-cloud-core/src/test/java/com/google/cloud/ServiceOptionsTest.java @@ -38,6 +38,7 @@ 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; @@ -45,12 +46,16 @@ 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; @@ -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 headers) throws Exception { HttpTransport mockHttpTransport =