This is an automated email from the ASF dual-hosted git repository.
garydgregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-lang.git
The following commit(s) were added to refs/heads/master by this push:
new 1c27f93c1 Fix class loader resolution when cloning dynamic proxies
(#1868)
1c27f93c1 is described below
commit 1c27f93c1dab1f6d4b33b7e0134d8ff04acee020
Author: Amar Ghugare <[email protected]>
AuthorDate: Mon Nov 16 03:03:24 2026 +0530
Fix class loader resolution when cloning dynamic proxies (#1868)
* Fix class loader resolution when cloning dynamic proxies
Resolve proxy interfaces with the configured class loader and fall back
to the thread context loader, matching ordinary class resolution.
Preserve non-public interface loader constraints and translate invalid
proxy definitions into ClassNotFoundException.
Cover custom and context loaders, proxy interface identity, normal
application proxies, null loaders and invalid interface combinations.
* Reuse original proxy classes when cloning
Record proxy classes during serialization and associate each descriptor
with its original class through an annotation index. Resolve cloned
proxy descriptors directly, avoiding interface lookups and fallback
retries while preserving defining class loaders.
Cover zero interface lookups, proxies from distinct loaders with the
same interface names, proxy class objects and shared references. Retain
controls for serialization failures and ordinary proxy cloning.
---
.../apache/commons/lang3/SerializationUtils.java | 44 +++++-
.../commons/lang3/SerializationUtilsTest.java | 173 +++++++++++++++++++++
2 files changed, 210 insertions(+), 7 deletions(-)
diff --git a/src/main/java/org/apache/commons/lang3/SerializationUtils.java
b/src/main/java/org/apache/commons/lang3/SerializationUtils.java
index deafc0622..0d0396130 100644
--- a/src/main/java/org/apache/commons/lang3/SerializationUtils.java
+++ b/src/main/java/org/apache/commons/lang3/SerializationUtils.java
@@ -27,6 +27,8 @@
import java.io.ObjectStreamClass;
import java.io.OutputStream;
import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
import java.util.Objects;
/**
@@ -56,12 +58,17 @@
public class SerializationUtils {
/**
- * Custom specialization of the standard JDK {@link ObjectInputStream}
that uses a custom {@link ClassLoader} to resolve a class. If the specified
- * {@link ClassLoader} is not able to resolve the class, the context
classloader of the current thread will be used. This way, the standard
deserialization
+ * Custom specialization of the standard JDK {@link ObjectInputStream}
that uses a custom {@link ClassLoader} to resolve classes.
+ * If the specified {@link ClassLoader} cannot resolve a class, the
context classloader of the current thread will be used.
+ * This way, the standard deserialization
* also works in web application containers and application servers,
regardless of which {@link ClassLoader} loaded the class that encapsulates
* serialization/deserialization.
*
* <p>
+ * Proxy classes are recorded during serialization and reused directly to
preserve their defining class loaders without looking up their interfaces.
+ * </p>
+ *
+ * <p>
* For more in-depth information about the problem for which this class
here is a workaround, see the JIRA issue LANG-626.
* </p>
*/
@@ -69,17 +76,21 @@ static final class ClassLoaderAwareObjectInputStream
extends ObjectInputStream {
private final ClassLoader classLoader;
+ private final List<Class<?>> proxyClasses;
+
/**
* Constructs a new instance.
*
- * @param in The {@link InputStream}.
- * @param classLoader classloader to use
+ * @param in The {@link InputStream}.
+ * @param classLoader The class loader to use.
+ * @param proxyClasses The proxy classes recorded while serializing
the original object.
* @throws IOException Thrown if an I/O error occurs while reading
stream header.
* @see java.io.ObjectInputStream
*/
- ClassLoaderAwareObjectInputStream(final InputStream in, final
ClassLoader classLoader) throws IOException {
+ ClassLoaderAwareObjectInputStream(final InputStream in, final
ClassLoader classLoader, final List<Class<?>> proxyClasses) throws IOException {
super(in);
this.classLoader = classLoader;
+ this.proxyClasses = proxyClasses;
}
/**
@@ -107,6 +118,11 @@ protected Class<?> resolveClass(final ObjectStreamClass
desc) throws IOException
}
}
}
+
+ @Override
+ protected Class<?> resolveProxyClass(final String[] interfaces) throws
IOException {
+ return proxyClasses.get(readInt());
+ }
}
/**
@@ -127,9 +143,23 @@ public static <T extends Serializable> T clone(final T
object) {
if (object == null) {
return null;
}
- final ByteArrayInputStream bais = new
ByteArrayInputStream(serialize(object));
+ final ByteArrayOutputStream baos = new ByteArrayOutputStream(512);
+ final List<Class<?>> proxyClasses = new ArrayList<>();
+ try (ObjectOutputStream out = new ObjectOutputStream(baos) {
+ @Override
+ protected void annotateProxyClass(final Class<?> proxyClass)
throws IOException {
+ // Pair the descriptor with its original class, even when
another loader defines the same interface names.
+ writeInt(proxyClasses.size());
+ proxyClasses.add(proxyClass);
+ }
+ }) {
+ out.writeObject(object);
+ } catch (final IOException ex) {
+ throw new SerializationException(ex);
+ }
+ final ByteArrayInputStream bais = new
ByteArrayInputStream(baos.toByteArray());
final Class<T> cls = ObjectUtils.getClass(object);
- try (ClassLoaderAwareObjectInputStream in = new
ClassLoaderAwareObjectInputStream(bais, cls.getClassLoader())) {
+ try (ClassLoaderAwareObjectInputStream in = new
ClassLoaderAwareObjectInputStream(bais, cls.getClassLoader(), proxyClasses)) {
// When we serialize and deserialize an object, it is reasonable
to assume the deserialized object is of the
// same type as the original serialized object
return (T) in.readObject();
diff --git a/src/test/java/org/apache/commons/lang3/SerializationUtilsTest.java
b/src/test/java/org/apache/commons/lang3/SerializationUtilsTest.java
index 0702f41f1..b6f9100b4 100644
--- a/src/test/java/org/apache/commons/lang3/SerializationUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/SerializationUtilsTest.java
@@ -38,12 +38,21 @@
import java.io.OutputStream;
import java.io.Serializable;
import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
+import java.lang.reflect.Proxy;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.util.ArrayList;
import java.util.HashMap;
import java.util.function.Supplier;
+import org.apache.commons.lang3.reflect.testbed.Bar;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
final class ClassNotFoundSerialization implements Serializable {
@@ -63,6 +72,27 @@ interface SerializableSupplier<T> extends Supplier<T>,
Serializable {
*/
public class SerializationUtilsTest extends AbstractLangTest {
+ public static final class ProxyHolder implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ public final Serializable value;
+
+ public ProxyHolder(final Serializable value) {
+ this.value = value;
+ }
+ }
+
+ private static final class SerializableInvocationHandler implements
InvocationHandler, Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public Object invoke(final Object proxy, final Method method, final
Object[] args) {
+ return "test";
+ }
+ }
+
static final String CLASS_NOT_FOUND_MESSAGE =
"ClassNotFoundSerialization.readObject fake exception";
protected static final String SERIALIZE_IO_EXCEPTION_MESSAGE = "Anonymous
OutputStream I/O exception";
@@ -117,12 +147,155 @@ void testClone() {
assertEquals(iMap, testMap);
}
+ @Test
+ void testCloneClassNotFound() {
+ final SerializationException ex =
assertThrows(SerializationException.class, () -> SerializationUtils.clone(new
ClassNotFoundSerialization()));
+ assertInstanceOf(ClassNotFoundException.class, ex.getCause());
+ assertEquals(CLASS_NOT_FOUND_MESSAGE, ex.getCause().getMessage());
+ }
+
@Test
void testCloneNull() {
final Object test = SerializationUtils.clone(null);
assertNull(test);
}
+ @ParameterizedTest
+ @ValueSource(strings = { "org.apache.commons.lang3.reflect.testbed.Bar",
"org.apache.commons.lang3.SerializableSupplier" })
+ void testCloneProxyWithCustomClassLoader(final String interfaceName)
throws Exception {
+ try (URLClassLoader loader = new URLClassLoader(new URL[] {
getClass().getProtectionDomain().getCodeSource().getLocation() }, null)) {
+ final Class<?> proxyInterface = Class.forName(interfaceName,
false, loader);
+ final Serializable proxy = (Serializable)
Proxy.newProxyInstance(loader, new Class<?>[] { proxyInterface }, new
SerializableInvocationHandler());
+ final Serializable clone = SerializationUtils.clone(proxy);
+ assertNotSame(proxy, clone);
+ assertSame(proxy.getClass(), clone.getClass());
+ assertTrue(proxyInterface.isInstance(clone));
+ assertNotSame(Proxy.getInvocationHandler(proxy),
Proxy.getInvocationHandler(clone));
+ assertEquals("test", clone.toString());
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = { "org.apache.commons.lang3.reflect.testbed.Bar",
"org.apache.commons.lang3.SerializableSupplier" })
+ void testCloneProxyWithContextClassLoader(final String interfaceName)
throws Exception {
+ final Thread thread = Thread.currentThread();
+ final ClassLoader originalLoader = thread.getContextClassLoader();
+ try (URLClassLoader loader = new URLClassLoader(new URL[] {
getClass().getProtectionDomain().getCodeSource().getLocation() }, null)) {
+ final Class<?> proxyInterface = Class.forName(interfaceName,
false, loader);
+ final Serializable proxy = (Serializable)
Proxy.newProxyInstance(loader, new Class<?>[] { proxyInterface }, new
SerializableInvocationHandler());
+ final ArrayList<Serializable> holder = new ArrayList<>();
+ holder.add(proxy);
+ thread.setContextClassLoader(loader);
+ final Serializable clone = SerializationUtils.clone(holder).get(0);
+ assertNotSame(proxy, clone);
+ assertSame(proxy.getClass(), clone.getClass());
+ assertEquals("test", clone.toString());
+ } finally {
+ thread.setContextClassLoader(originalLoader);
+ }
+ }
+
+ @Test
+ void testCloneProxyWithDefaultClassLoader() {
+ final Serializable proxy = (Serializable)
Proxy.newProxyInstance(getClass().getClassLoader(), new Class<?>[] {
SerializableSupplier.class },
+ new SerializableInvocationHandler());
+ final SerializableSupplier<?> clone = (SerializableSupplier<?>)
SerializationUtils.clone(proxy);
+ assertNotSame(proxy, clone);
+ assertEquals("test", clone.get());
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = { "org.apache.commons.lang3.reflect.testbed.Bar",
"org.apache.commons.lang3.SerializableSupplier" })
+ void testCloneProxiesFromDifferentClassLoaders(final String interfaceName)
throws Exception {
+ final URL[] urls = {
getClass().getProtectionDomain().getCodeSource().getLocation() };
+ try (URLClassLoader first = new URLClassLoader(urls, null);
+ URLClassLoader second = new URLClassLoader(urls, null)) {
+ final Serializable firstProxy = (Serializable)
Proxy.newProxyInstance(first,
+ new Class<?>[] { Class.forName(interfaceName, false,
first) }, new SerializableInvocationHandler());
+ final Serializable secondProxy = (Serializable)
Proxy.newProxyInstance(second,
+ new Class<?>[] { Class.forName(interfaceName, false,
second) }, new SerializableInvocationHandler());
+ final ArrayList<Serializable> values = new ArrayList<>();
+ values.add(firstProxy.getClass());
+ values.add(firstProxy);
+ values.add(secondProxy);
+ values.add(firstProxy);
+ values.add(secondProxy.getClass());
+ final ArrayList<Serializable> clone =
SerializationUtils.clone(values);
+ assertSame(firstProxy.getClass(), clone.get(0));
+ assertNotSame(firstProxy, clone.get(1));
+ assertNotSame(secondProxy, clone.get(2));
+ assertSame(firstProxy.getClass(), clone.get(1).getClass());
+ assertSame(secondProxy.getClass(), clone.get(2).getClass());
+ assertSame(clone.get(1), clone.get(3));
+ assertSame(secondProxy.getClass(), clone.get(4));
+ assertEquals("test", clone.get(1).toString());
+ assertEquals("test", clone.get(2).toString());
+ }
+ }
+
+ @Test
+ void testCloneProxyDoesNotLookUpInterfaces() throws Exception {
+ final int[] interfaceLookups = { 0 };
+ final URL[] urls = {
getClass().getProtectionDomain().getCodeSource().getLocation() };
+ final ClassLoader applicationLoader = getClass().getClassLoader();
+ final Thread thread = Thread.currentThread();
+ final ClassLoader originalLoader = thread.getContextClassLoader();
+ try (URLClassLoader loader = new URLClassLoader(urls,
applicationLoader) {
+ @Override
+ protected Class<?> loadClass(final String name, final boolean
resolve) throws ClassNotFoundException {
+ if (name.equals(Bar.class.getName())) {
+ interfaceLookups[0]++;
+ throw new ClassNotFoundException(name);
+ }
+ if (name.equals(ProxyHolder.class.getName())) {
+ Class<?> cls = findLoadedClass(name);
+ if (cls == null) {
+ cls = findClass(name);
+ }
+ if (resolve) {
+ resolveClass(cls);
+ }
+ return cls;
+ }
+ return super.loadClass(name, resolve);
+ }
+ }) {
+ final Serializable proxy = (Serializable)
Proxy.newProxyInstance(applicationLoader, new Class<?>[] { Bar.class },
+ new SerializableInvocationHandler());
+ final Class<?> holderClass =
Class.forName(ProxyHolder.class.getName(), true, loader);
+ final Serializable holder = (Serializable)
holderClass.getConstructor(Serializable.class).newInstance(proxy);
+ thread.setContextClassLoader(applicationLoader);
+ final Serializable clone = SerializationUtils.clone(holder);
+ final Object clonedProxy =
holderClass.getField("value").get(clone);
+ assertSame(proxy.getClass(), clonedProxy.getClass());
+ assertNotSame(proxy, clonedProxy);
+ assertEquals("test", clonedProxy.toString());
+ assertEquals(0, interfaceLookups[0]);
+ } finally {
+ thread.setContextClassLoader(originalLoader);
+ }
+ }
+
+ @Test
+ void testCloneProxyWithPublicInterfaces() {
+ final Serializable proxy = (Serializable)
Proxy.newProxyInstance(getClass().getClassLoader(),
+ new Class<?>[] { Supplier.class, Serializable.class }, new
SerializableInvocationHandler());
+ final Supplier<?> clone = (Supplier<?>)
SerializationUtils.clone(proxy);
+ assertNotSame(proxy, clone);
+ assertSame(proxy.getClass(), clone.getClass());
+ assertEquals("test", clone.get());
+ }
+
+ @Test
+ void testCloneProxyWithNoInterfaces() {
+ final Serializable proxy = (Serializable)
Proxy.newProxyInstance(getClass().getClassLoader(), new Class<?>[0], new
SerializableInvocationHandler());
+ final Serializable clone = SerializationUtils.clone(proxy);
+ assertNotSame(proxy, clone);
+ assertSame(proxy.getClass(), clone.getClass());
+ assertNotSame(Proxy.getInvocationHandler(proxy),
Proxy.getInvocationHandler(clone));
+ assertEquals("test", clone.toString());
+ }
+
@Test
void testCloneSerializableSupplier() {
final SerializableSupplier<String> supplier = () -> "test";