1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.bcel.util;
21
22 import static org.junit.jupiter.api.Assertions.assertNull;
23 import static org.junit.jupiter.api.Assertions.assertThrows;
24
25 import java.io.ByteArrayInputStream;
26 import java.io.InputStream;
27
28 import org.apache.bcel.Const;
29 import org.apache.bcel.generic.ClassGen;
30 import org.junit.jupiter.api.Test;
31
32
33
34
35
36
37
38 class RepositoryNameMismatchTest {
39
40 private static byte[] classBytes(final String className) {
41 return new ClassGen(className, "java.lang.Object", className + ".java", Const.ACC_PUBLIC, null).getJavaClass().getBytes();
42 }
43
44 @Test
45 void testClassLoaderRepositoryRejectsMismatchedName() {
46 final byte[] bytes = classBytes("evil.Squatter");
47 final ClassLoader loader = new ClassLoader(getClass().getClassLoader()) {
48 @Override
49 public InputStream getResourceAsStream(final String name) {
50 return "victim/Innocent.class".equals(name) ? new ByteArrayInputStream(bytes) : super.getResourceAsStream(name);
51 }
52 };
53 final ClassLoaderRepository repository = new ClassLoaderRepository(loader);
54 assertThrows(ClassNotFoundException.class, () -> repository.loadClass("victim.Innocent"));
55 assertNull(repository.findClass("evil.Squatter"), "mismatched class must not be cached under its declared name");
56 assertNull(repository.findClass("victim.Innocent"), "mismatched class must not be cached under the requested name");
57 }
58 }