|
| 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