Skip to content

Instantly share code, notes, and snippets.

@Venthe
Created March 12, 2024 00:57
Show Gist options
  • Select an option

  • Save Venthe/21dff15027fa6eb329265822882cba8f to your computer and use it in GitHub Desktop.

Select an option

Save Venthe/21dff15027fa6eb329265822882cba8f to your computer and use it in GitHub Desktop.
XSSI + ByteBuddy
package eu.venthe.pipeline.orchestrator;
import eu.venthe.pipeline.gerrit.invoker.ApiClient;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.implementation.bind.annotation.AllArguments;
import net.bytebuddy.implementation.bind.annotation.Origin;
import net.bytebuddy.implementation.bind.annotation.RuntimeType;
import net.bytebuddy.matcher.ElementMatchers;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import java.lang.reflect.Method;
@Slf4j
@RequiredArgsConstructor
public class GerritXSSIRemover {
private final ApiClient originalInstance;
@RuntimeType
public Object intercept(@Origin Method method,
@AllArguments Object[] args) throws Exception {
Object result = method.invoke(originalInstance, args);
if (result instanceof ResponseEntity<?> && ((ResponseEntity<?>) result).getBody() != null && ((ResponseEntity<?>) result).getBody() instanceof String) {
ResponseEntity<String> result1 = (ResponseEntity<String>) result;
HttpStatusCode statusCode = result1.getStatusCode();
HttpHeaders headers = result1.getHeaders();
String body = result1.getBody().replaceAll("^\\)]}'", "");
return new ResponseEntity<>(body, headers, statusCode);
}
return result;
}
@SneakyThrows
public static ApiClient wrap(ApiClient apiClient) {
return new ByteBuddy()
.subclass(ApiClient.class)
.method(ElementMatchers.named("invokeAPI"))
.intercept(MethodDelegation.to(new GerritXSSIRemover(apiClient)))
.make()
.load(ApiClient.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded()
.newInstance();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment