|
| 1 | +package dev.aikido.agent.wrappers.spring; |
| 2 | + |
| 3 | +import dev.aikido.agent.wrappers.Wrapper; |
| 4 | +import dev.aikido.agent_api.collectors.WebRequestCollector; |
| 5 | +import dev.aikido.agent_api.collectors.WebResponseCollector; |
| 6 | +import dev.aikido.agent_api.context.ContextObject; |
| 7 | +import dev.aikido.agent_api.context.SpringWebfluxContextObject; |
| 8 | +import dev.aikido.agent_api.helpers.logging.LogManager; |
| 9 | +import dev.aikido.agent_api.helpers.logging.Logger; |
| 10 | +import net.bytebuddy.asm.Advice; |
| 11 | +import net.bytebuddy.description.method.MethodDescription; |
| 12 | +import net.bytebuddy.description.type.TypeDescription; |
| 13 | +import net.bytebuddy.matcher.ElementMatcher; |
| 14 | +import org.springframework.core.io.buffer.DataBuffer; |
| 15 | +import org.springframework.core.io.buffer.DataBufferFactory; |
| 16 | +import org.springframework.http.HttpCookie; |
| 17 | +import org.springframework.http.server.reactive.ServerHttpRequest; |
| 18 | +import org.springframework.http.server.reactive.ServerHttpResponse; |
| 19 | +import reactor.core.publisher.Mono; |
| 20 | + |
| 21 | +import java.lang.reflect.Executable; |
| 22 | +import java.nio.charset.StandardCharsets; |
| 23 | +import java.util.*; |
| 24 | +import java.util.stream.Collectors; |
| 25 | + |
| 26 | +import static net.bytebuddy.implementation.bytecode.assign.Assigner.Typing.DYNAMIC; |
| 27 | +import static net.bytebuddy.matcher.ElementMatchers.*; |
| 28 | + |
| 29 | +/** |
| 30 | + * Wraps handle() function on HttpWebHandlerAdapter for Spring Webflux. |
| 31 | + * Creates context object, writes a response (e.g. ip blocking), and reports status code. |
| 32 | + * [github link](https://github.com/spring-projects/spring-framework/blob/7405e2069098400a01ee1e84ce72c45c6498b28d/spring-web/src/main/java/org/springframework/web/server/adapter/HttpWebHandlerAdapter.java#L269) |
| 33 | + */ |
| 34 | +public class SpringWebfluxWrapper implements Wrapper { |
| 35 | + public static final Logger logger = LogManager.getLogger(SpringWebfluxWrapper.class); |
| 36 | + |
| 37 | + @Override |
| 38 | + public String getName() { |
| 39 | + return SpringWebfluxAdvice.class.getName(); |
| 40 | + } |
| 41 | + |
| 42 | + @Override |
| 43 | + public ElementMatcher<? super MethodDescription> getMatcher() { |
| 44 | + |
| 45 | + return isDeclaredBy(getTypeMatcher()).and(named("handle")) |
| 46 | + .and(takesArgument(0, nameContains("ServerHttpRequest"))) |
| 47 | + .and(takesArgument(1, nameContains("ServerHttpResponse"))); |
| 48 | + } |
| 49 | + |
| 50 | + @Override |
| 51 | + public ElementMatcher<? super TypeDescription> getTypeMatcher() { |
| 52 | + return nameContainsIgnoreCase("org.springframework.web.server.adapter.HttpWebHandlerAdapter"); |
| 53 | + } |
| 54 | + |
| 55 | + public record SkipOnWrapper(Mono<Void> newReturnValue) { |
| 56 | + } |
| 57 | + |
| 58 | + public static class SpringWebfluxAdvice { |
| 59 | + @Advice.OnMethodEnter(skipOn = SkipOnWrapper.class, suppress = Throwable.class) |
| 60 | + public static Object onEnter( |
| 61 | + @Advice.Origin Executable method, |
| 62 | + @Advice.Argument(value = 0, typing = DYNAMIC, optional = true) ServerHttpRequest req, |
| 63 | + @Advice.Argument(value = 1, typing = DYNAMIC, optional = true) ServerHttpResponse res |
| 64 | + ) { |
| 65 | + if (req == null) { |
| 66 | + return null; |
| 67 | + } |
| 68 | + // Extract headers & query parameters : |
| 69 | + Set<Map.Entry<String, List<String>>> headerEntries = req.getHeaders().entrySet(); |
| 70 | + Map<String, List<String>> query = req.getQueryParams(); |
| 71 | + |
| 72 | + // Extract cookies : |
| 73 | + HashMap<String, List<String>> cookieMap = new HashMap<>(); |
| 74 | + for (Map.Entry<String, List<HttpCookie>> entry : req.getCookies().entrySet()) { |
| 75 | + List<String> values = entry.getValue().stream().map(HttpCookie::getValue).collect(Collectors.toList()); |
| 76 | + cookieMap.put(entry.getKey(), values); |
| 77 | + } |
| 78 | + |
| 79 | + // Create context object : |
| 80 | + ContextObject context = new SpringWebfluxContextObject( |
| 81 | + req.getMethod().toString(), req.getURI().toString(), |
| 82 | + Objects.requireNonNull(req.getRemoteAddress()), |
| 83 | + cookieMap, query, req.getHeaders().toSingleValueMap() |
| 84 | + ); |
| 85 | + |
| 86 | + // If the request gets blocked (e.g. IP Blocking), write a response here : |
| 87 | + WebRequestCollector.Res zenResponse = WebRequestCollector.report(context); |
| 88 | + if (zenResponse != null && res != null) { |
| 89 | + // Write message : |
| 90 | + DataBufferFactory dataBufferFactory = res.bufferFactory(); |
| 91 | + DataBuffer dataBuffer = dataBufferFactory.wrap(zenResponse.msg().getBytes(StandardCharsets.UTF_8)); |
| 92 | + |
| 93 | + res.setRawStatusCode(zenResponse.status()); // Set status code |
| 94 | + return new SkipOnWrapper(res.writeWith(Mono.just(dataBuffer))); |
| 95 | + } |
| 96 | + |
| 97 | + return res; // Return to analyze status code in OnMethodExit. |
| 98 | + } |
| 99 | + |
| 100 | + /** onExit() |
| 101 | + * We can use @Advice.Return to overwrite the returned value of handle(...) i.e. to block requests. |
| 102 | + */ |
| 103 | + @Advice.OnMethodExit(onThrowable = Throwable.class, suppress = Throwable.class) |
| 104 | + public static void onExit( |
| 105 | + @Advice.Enter Object enterResult, |
| 106 | + @Advice.Return(readOnly = false) Mono<Void> returnValue |
| 107 | + ) { |
| 108 | + // enterResult can be two things : Either the SkipOnWrapper or the ServerHttpResponse |
| 109 | + // ServerHttpResponse -> Extract status code. |
| 110 | + // SkipOnWrapper -> we blocked a request (e.g. IP Blocking), and are returning the value below |
| 111 | + if (enterResult instanceof SkipOnWrapper wrapper && wrapper.newReturnValue() != null) { |
| 112 | + returnValue = wrapper.newReturnValue(); |
| 113 | + } else if (enterResult instanceof ServerHttpResponse res) { |
| 114 | + // Report status code of response : |
| 115 | + Integer statusCode = res.getRawStatusCode(); |
| 116 | + if (statusCode != null) { |
| 117 | + WebResponseCollector.report(statusCode); |
| 118 | + } |
| 119 | + } |
| 120 | + } |
| 121 | + } |
| 122 | + |
| 123 | +} |
0 commit comments