Skip to content

Commit da6f264

Browse files
committed
✨ Add Fixed Unsafe Reflection
1 parent ce2d467 commit da6f264

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

pom.xml

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,11 @@
2828
<artifactId>jakarta.ws.rs-api</artifactId>
2929
<version>3.1.0</version>
3030
</dependency>
31+
<dependency>
32+
<groupId>io.github.pixee</groupId>
33+
<artifactId>java-security-toolkit</artifactId>
34+
<version>1.1.2</version>
35+
</dependency>
3136
</dependencies>
3237
</dependencyManagement>
3338

@@ -36,6 +41,10 @@
3641
<groupId>jakarta.ws.rs</groupId>
3742
<artifactId>jakarta.ws.rs-api</artifactId>
3843
</dependency>
44+
<dependency>
45+
<groupId>io.github.pixee</groupId>
46+
<artifactId>java-security-toolkit</artifactId>
47+
</dependency>
3948
<dependency>
4049
<groupId>org.junit.jupiter</groupId>
4150
<artifactId>junit-jupiter-api</artifactId>
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package com.acme.reflection;
2+
3+
import io.github.pixee.security.Reflection;
4+
import jakarta.ws.rs.GET;
5+
import jakarta.ws.rs.Path;
6+
import jakarta.ws.rs.QueryParam;
7+
import java.lang.reflect.Constructor;
8+
import java.lang.reflect.InvocationTargetException;
9+
10+
/** {@link UnsafeReflection}, but with the expected hardening against unsafe reflection. */
11+
@Path("/unsafe-reflection-fixed")
12+
public class UnsafeReflectionFixed {
13+
14+
@GET
15+
public String hello(@QueryParam("translator") final String translationStrategy) {
16+
final var translator = loadTranslatorByName(translationStrategy);
17+
return translator.translate("Hello, world!");
18+
}
19+
20+
private static TranslatorStrategy loadTranslatorByName(final String translationStrategy) {
21+
final Class<?> translatorClazz;
22+
try {
23+
translatorClazz = Reflection.loadAndVerify("com.acme." + translationStrategy);
24+
} catch (ClassNotFoundException e) {
25+
throw new IllegalArgumentException("Invalid translator: " + translationStrategy, e);
26+
}
27+
if (TranslatorStrategy.class.isAssignableFrom(translatorClazz)) {
28+
throw new IllegalArgumentException("Invalid translator: " + translationStrategy);
29+
}
30+
final Constructor<?> translatorCtor;
31+
try {
32+
translatorCtor = translatorClazz.getConstructor();
33+
} catch (NoSuchMethodException e) {
34+
throw new IllegalStateException(
35+
"Translator " + translationStrategy + " is missing a no-args constructor", e);
36+
}
37+
final TranslatorStrategy translator;
38+
try {
39+
translator = (TranslatorStrategy) translatorCtor.newInstance();
40+
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
41+
throw new IllegalStateException("Failed to initialize translator " + translationStrategy, e);
42+
}
43+
return translator;
44+
}
45+
}

0 commit comments

Comments
 (0)