diff --git a/instrumentation/apache-httpclient-4.0/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/apachehttpclient/v4_0/ApacheHttpClientUtils.java b/instrumentation/apache-httpclient-4.0/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/apachehttpclient/v4_0/ApacheHttpClientUtils.java index 0616241ae..ccac1ca50 100644 --- a/instrumentation/apache-httpclient-4.0/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/apachehttpclient/v4_0/ApacheHttpClientUtils.java +++ b/instrumentation/apache-httpclient-4.0/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/apachehttpclient/v4_0/ApacheHttpClientUtils.java @@ -127,6 +127,17 @@ public static void traceEntity( BoundedByteArrayOutputStream byteArrayOutputStream = BoundedBuffersFactory.createStream(charset); entity.writeTo(byteArrayOutputStream); + if (!isGzipEncoded + && HypertraceSemanticAttributes.HTTP_REQUEST_BODY.equals(bodyAttributeKey) + && ContentTypeUtils.isMultipartFormData(contentType.getValue())) { + // multipart bodies carry binary file parts: keep the raw bytes, not the decoded text + if (byteArrayOutputStream.size() > 0) { + span.setAttribute( + AttributeKey.stringKey(bodyAttributeKey.getKey() + ".base64"), + byteArrayOutputStream.toBase64()); + } + return; + } InputStream contentStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); if (isGzipEncoded) { try { diff --git a/instrumentation/apache-httpclient-4.0/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/apachehttpclient/v4_0/HttpEntityInstrumentation.java b/instrumentation/apache-httpclient-4.0/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/apachehttpclient/v4_0/HttpEntityInstrumentation.java index ce9a0abfb..d8f05a09b 100644 --- a/instrumentation/apache-httpclient-4.0/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/apachehttpclient/v4_0/HttpEntityInstrumentation.java +++ b/instrumentation/apache-httpclient-4.0/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/apachehttpclient/v4_0/HttpEntityInstrumentation.java @@ -130,7 +130,10 @@ public static void enter( Charset charset = ContentTypeCharsetUtils.toCharset(charsetStr); BoundedByteArrayOutputStream byteArrayOutputStream = - BoundedBuffersFactory.createStream((int) contentSize, charset); + BoundedBuffersFactory.createStream( + (int) contentSize, + charset, + contentTypeHeader == null ? null : contentTypeHeader.getValue()); VirtualField.find(OutputStream.class, BoundedByteArrayOutputStream.class) .set(outputStream, byteArrayOutputStream); @@ -151,8 +154,18 @@ public static void exit( BoundedByteArrayOutputStream bufferedOutStream = contextStore.get(outputStream); contextStore.set(outputStream, null); try { - String requestBody = bufferedOutStream.toStringWithSuppliedCharset(); - spanAndAttributeKey.span.setAttribute(spanAndAttributeKey.attributeKey, requestBody); + if (bufferedOutStream.isMultipartFormData()) { + // multipart bodies carry binary file parts: keep the raw bytes, not the decoded text + if (bufferedOutStream.size() > 0) { + // advice is inlined into old class files: no static interface calls (AttributeKey) + spanAndAttributeKey.span.setAttribute( + spanAndAttributeKey.attributeKey.getKey() + ".base64", + bufferedOutStream.toBase64()); + } + } else { + String requestBody = bufferedOutStream.toStringWithSuppliedCharset(); + spanAndAttributeKey.span.setAttribute(spanAndAttributeKey.attributeKey, requestBody); + } } catch (UnsupportedEncodingException e) { // should not happen, the charset has been parsed before } diff --git a/instrumentation/apache-httpclient-4.0/src/test/java/io/opentelemetry/javaagent/instrumentation/hypertrace/apachehttpclient/v4_0/ApacheHttpClientInstrumentationTest.java b/instrumentation/apache-httpclient-4.0/src/test/java/io/opentelemetry/javaagent/instrumentation/hypertrace/apachehttpclient/v4_0/ApacheHttpClientInstrumentationTest.java index e8f8dbd8a..3ba8d684a 100644 --- a/instrumentation/apache-httpclient-4.0/src/test/java/io/opentelemetry/javaagent/instrumentation/hypertrace/apachehttpclient/v4_0/ApacheHttpClientInstrumentationTest.java +++ b/instrumentation/apache-httpclient-4.0/src/test/java/io/opentelemetry/javaagent/instrumentation/hypertrace/apachehttpclient/v4_0/ApacheHttpClientInstrumentationTest.java @@ -36,6 +36,11 @@ public ApacheHttpClientInstrumentationTest() { super(true); } + @Override + protected boolean capturesMultipartAsBase64() { + return true; + } + @Override public Response doPostRequest( String uri, Map headers, String body, String contentType) throws IOException { diff --git a/instrumentation/netty/netty-4.0/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/netty/v4_0/DataCaptureUtils.java b/instrumentation/netty/netty-4.0/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/netty/v4_0/DataCaptureUtils.java index 7b4726928..00250331d 100644 --- a/instrumentation/netty/netty-4.0/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/netty/v4_0/DataCaptureUtils.java +++ b/instrumentation/netty/netty-4.0/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/netty/v4_0/DataCaptureUtils.java @@ -69,12 +69,21 @@ public static void captureBody( try { byte[] data = buffer.toByteArray(); + boolean gzip = contentEncoding != null && contentEncoding.toLowerCase().contains("gzip"); + if (buffer.isMultipartFormData() && !gzip) { + // multipart bodies carry binary file parts: keep the raw bytes, not the decoded text + if (data.length > 0) { + span.setAttribute(attributeKey.name() + ".base64", buffer.toBase64()); + } + return; + } + String body; if (charset == null) { charset = ContentTypeCharsetUtils.getDefaultCharset(); } // Decode based on content encoding - if (contentEncoding != null && contentEncoding.toLowerCase().contains("gzip")) { + if (gzip) { try (GZIPInputStream gzipStream = new GZIPInputStream(new ByteArrayInputStream(data))) { InputStreamReader reader = new InputStreamReader(gzipStream, charset); body = readInputStream(reader, charset); diff --git a/instrumentation/netty/netty-4.0/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/netty/v4_0/client/HttpClientRequestTracingHandler.java b/instrumentation/netty/netty-4.0/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/netty/v4_0/client/HttpClientRequestTracingHandler.java index bd721cb16..56b44e9b1 100644 --- a/instrumentation/netty/netty-4.0/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/netty/v4_0/client/HttpClientRequestTracingHandler.java +++ b/instrumentation/netty/netty-4.0/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/netty/v4_0/client/HttpClientRequestTracingHandler.java @@ -91,7 +91,8 @@ public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise prm) { // the buffer is used byt captureBody method Attribute bufferAttr = ctx.channel().attr(AttributeKeys.REQUEST_BODY_BUFFER); - bufferAttr.set(BoundedBuffersFactory.createStream(contentLength, charset)); + bufferAttr.set( + BoundedBuffersFactory.createStream(contentLength, charset, contentType.toString())); channel.attr(AttributeKeys.CHARSET).set(charset); } diff --git a/instrumentation/netty/netty-4.0/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/netty/v4_0/server/HttpServerRequestTracingHandler.java b/instrumentation/netty/netty-4.0/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/netty/v4_0/server/HttpServerRequestTracingHandler.java index 815a9cf64..d0191fb6d 100644 --- a/instrumentation/netty/netty-4.0/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/netty/v4_0/server/HttpServerRequestTracingHandler.java +++ b/instrumentation/netty/netty-4.0/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/netty/v4_0/server/HttpServerRequestTracingHandler.java @@ -84,7 +84,8 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) { // the buffer is used byt captureBody method Attribute bufferAttr = ctx.channel().attr(AttributeKeys.REQUEST_BODY_BUFFER); - bufferAttr.set(BoundedBuffersFactory.createStream(contentLength, charset)); + bufferAttr.set( + BoundedBuffersFactory.createStream(contentLength, charset, contentType.toString())); channel.attr(AttributeKeys.CHARSET).set(charset); } diff --git a/instrumentation/netty/netty-4.0/src/test/java/io/opentelemetry/javaagent/instrumentation/hypertrace/netty/v4_0/client/Netty40ClientInstrumentationTest.java b/instrumentation/netty/netty-4.0/src/test/java/io/opentelemetry/javaagent/instrumentation/hypertrace/netty/v4_0/client/Netty40ClientInstrumentationTest.java index 5d7badda9..b364a05e3 100644 --- a/instrumentation/netty/netty-4.0/src/test/java/io/opentelemetry/javaagent/instrumentation/hypertrace/netty/v4_0/client/Netty40ClientInstrumentationTest.java +++ b/instrumentation/netty/netty-4.0/src/test/java/io/opentelemetry/javaagent/instrumentation/hypertrace/netty/v4_0/client/Netty40ClientInstrumentationTest.java @@ -37,6 +37,11 @@ public Netty40ClientInstrumentationTest() { super(false); } + @Override + protected boolean capturesMultipartAsBase64() { + return true; + } + @Override public Response doPostRequest( String uri, Map headers, String body, String contentType) diff --git a/instrumentation/netty/netty-4.1/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/netty/v4_1/DataCaptureUtils.java b/instrumentation/netty/netty-4.1/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/netty/v4_1/DataCaptureUtils.java index 049896dce..d11d9a270 100644 --- a/instrumentation/netty/netty-4.1/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/netty/v4_1/DataCaptureUtils.java +++ b/instrumentation/netty/netty-4.1/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/netty/v4_1/DataCaptureUtils.java @@ -70,11 +70,20 @@ public static void captureBody( try { byte[] data = buffer.toByteArray(); + boolean gzip = contentEncoding != null && contentEncoding.toLowerCase().contains("gzip"); + if (buffer.isMultipartFormData() && !gzip) { + // multipart bodies carry binary file parts: keep the raw bytes, not the decoded text + if (data.length > 0) { + span.setAttribute(attributeKey.name() + ".base64", buffer.toBase64()); + } + return; + } + String body; if (charset == null) { charset = ContentTypeCharsetUtils.getDefaultCharset(); } - if (contentEncoding != null && contentEncoding.toLowerCase().contains("gzip")) { + if (gzip) { try (GZIPInputStream gzipStream = new GZIPInputStream(new ByteArrayInputStream(data))) { InputStreamReader reader = new InputStreamReader(gzipStream, charset); body = readInputStream(reader, charset); diff --git a/instrumentation/netty/netty-4.1/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/netty/v4_1/client/HttpClientRequestTracingHandler.java b/instrumentation/netty/netty-4.1/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/netty/v4_1/client/HttpClientRequestTracingHandler.java index 6f5bda18f..1d35c74ad 100644 --- a/instrumentation/netty/netty-4.1/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/netty/v4_1/client/HttpClientRequestTracingHandler.java +++ b/instrumentation/netty/netty-4.1/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/netty/v4_1/client/HttpClientRequestTracingHandler.java @@ -90,7 +90,8 @@ public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise prm) { // the buffer is used byt captureBody method Attribute bufferAttr = ctx.channel().attr(AttributeKeys.REQUEST_BODY_BUFFER); - bufferAttr.set(BoundedBuffersFactory.createStream(contentLength, charset)); + bufferAttr.set( + BoundedBuffersFactory.createStream(contentLength, charset, contentType.toString())); channel.attr(AttributeKeys.PROVIDED_CHARSET).set(charset); } diff --git a/instrumentation/netty/netty-4.1/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/netty/v4_1/server/HttpServerRequestTracingHandler.java b/instrumentation/netty/netty-4.1/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/netty/v4_1/server/HttpServerRequestTracingHandler.java index 6fce19a2b..a7f88863e 100644 --- a/instrumentation/netty/netty-4.1/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/netty/v4_1/server/HttpServerRequestTracingHandler.java +++ b/instrumentation/netty/netty-4.1/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/netty/v4_1/server/HttpServerRequestTracingHandler.java @@ -84,7 +84,8 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) { // the buffer is used byt captureBody method Attribute bufferAttr = ctx.channel().attr(AttributeKeys.REQUEST_BODY_BUFFER); - bufferAttr.set(BoundedBuffersFactory.createStream(contentLength, charset)); + bufferAttr.set( + BoundedBuffersFactory.createStream(contentLength, charset, contentType.toString())); channel.attr(AttributeKeys.PROVIDED_CHARSET).set(charset); } diff --git a/instrumentation/netty/netty-4.1/src/test/java/io/opentelemetry/javaagent/instrumentation/hypertrace/netty/v4_1/client/Netty41ClientInstrumentationTest.java b/instrumentation/netty/netty-4.1/src/test/java/io/opentelemetry/javaagent/instrumentation/hypertrace/netty/v4_1/client/Netty41ClientInstrumentationTest.java index dd3b073dd..d3eb4b848 100644 --- a/instrumentation/netty/netty-4.1/src/test/java/io/opentelemetry/javaagent/instrumentation/hypertrace/netty/v4_1/client/Netty41ClientInstrumentationTest.java +++ b/instrumentation/netty/netty-4.1/src/test/java/io/opentelemetry/javaagent/instrumentation/hypertrace/netty/v4_1/client/Netty41ClientInstrumentationTest.java @@ -37,6 +37,11 @@ public Netty41ClientInstrumentationTest() { super(false); } + @Override + protected boolean capturesMultipartAsBase64() { + return true; + } + @Override public Response doPostRequest( String uri, Map headers, String body, String contentType) diff --git a/instrumentation/okhttp/okhttp-3.0/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/okhttp/v3_0/OkHttpTracingInterceptor.java b/instrumentation/okhttp/okhttp-3.0/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/okhttp/v3_0/OkHttpTracingInterceptor.java index dfafad5d1..abc99cfd7 100644 --- a/instrumentation/okhttp/okhttp-3.0/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/okhttp/v3_0/OkHttpTracingInterceptor.java +++ b/instrumentation/okhttp/okhttp-3.0/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/okhttp/v3_0/OkHttpTracingInterceptor.java @@ -30,11 +30,14 @@ import okhttp3.Response; import okhttp3.ResponseBody; import okio.Buffer; +import okio.BufferedSink; import okio.BufferedSource; import okio.GzipSource; import okio.Okio; import org.hypertrace.agent.core.config.InstrumentationConfig; import org.hypertrace.agent.core.instrumentation.HypertraceSemanticAttributes; +import org.hypertrace.agent.core.instrumentation.buffer.BoundedBuffersFactory; +import org.hypertrace.agent.core.instrumentation.buffer.BoundedByteArrayOutputStream; import org.hypertrace.agent.core.instrumentation.utils.ContentTypeUtils; import org.hypertrace.agent.core.instrumentation.utils.ServiceNameHeaderUtils; import org.slf4j.Logger; @@ -83,6 +86,10 @@ private static void captureRequestBody(Span span, RequestBody requestBody) { return; } try { + if (ContentTypeUtils.isMultipartFormData(mediaType.toString())) { + captureMultipartRequestBody(span, requestBody); + return; + } Buffer buffer = new Buffer(); requestBody.writeTo(buffer); span.setAttribute(HypertraceSemanticAttributes.HTTP_REQUEST_BODY, buffer.readUtf8()); @@ -91,6 +98,24 @@ private static void captureRequestBody(Span span, RequestBody requestBody) { } } + /** + * Multipart bodies are file uploads and can be large, and carry binary parts: write straight into + * a bounded buffer (the rest is dropped) so memory stays capped, and capture the raw bytes as + * base64. + */ + private static void captureMultipartRequestBody(Span span, RequestBody requestBody) + throws IOException { + BoundedByteArrayOutputStream bounded = + BoundedBuffersFactory.createStream(StandardCharsets.UTF_8); + BufferedSink sink = Okio.buffer(Okio.sink(bounded)); + requestBody.writeTo(sink); + sink.flush(); + if (bounded.size() > 0) { + span.setAttribute( + HypertraceSemanticAttributes.HTTP_REQUEST_BODY.getKey() + ".base64", bounded.toBase64()); + } + } + private static Response captureResponseBody(Span span, final Response response) { if (!instrumentationConfig.httpBody().response()) { return response; diff --git a/instrumentation/okhttp/okhttp-3.0/src/test/java/io/opentelemetry/javaagent/instrumentation/hypertrace/okhttp/v3_0/OkHttpTracingInterceptorTest.java b/instrumentation/okhttp/okhttp-3.0/src/test/java/io/opentelemetry/javaagent/instrumentation/hypertrace/okhttp/v3_0/OkHttpTracingInterceptorTest.java index 6b895c565..6504decf2 100644 --- a/instrumentation/okhttp/okhttp-3.0/src/test/java/io/opentelemetry/javaagent/instrumentation/hypertrace/okhttp/v3_0/OkHttpTracingInterceptorTest.java +++ b/instrumentation/okhttp/okhttp-3.0/src/test/java/io/opentelemetry/javaagent/instrumentation/hypertrace/okhttp/v3_0/OkHttpTracingInterceptorTest.java @@ -33,6 +33,11 @@ public OkHttpTracingInterceptorTest() { super(false); } + @Override + protected boolean capturesMultipartAsBase64() { + return true; + } + @Override public Response doPostRequest( String uri, Map headersMap, String body, String contentType) diff --git a/instrumentation/servlet/servlet-3.0/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/servlet/v3_0/nowrapping/request/Utils.java b/instrumentation/servlet/servlet-3.0/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/servlet/v3_0/nowrapping/request/Utils.java index 27d412c9b..86a1f11f4 100644 --- a/instrumentation/servlet/servlet-3.0/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/servlet/v3_0/nowrapping/request/Utils.java +++ b/instrumentation/servlet/servlet-3.0/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/servlet/v3_0/nowrapping/request/Utils.java @@ -45,7 +45,8 @@ public static ByteBufferSpanPair createRequestByteBufferSpanPair( } return new ByteBufferSpanPair( span, - BoundedBuffersFactory.createStream(contentLength, charset), + BoundedBuffersFactory.createStream( + contentLength, charset, httpServletRequest.getContentType()), filter::evaluateRequestBody, headers); } diff --git a/instrumentation/servlet/servlet-5.0/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/servlet/v5_0/request/Utils.java b/instrumentation/servlet/servlet-5.0/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/servlet/v5_0/request/Utils.java index 35355db86..30d72ee79 100644 --- a/instrumentation/servlet/servlet-5.0/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/servlet/v5_0/request/Utils.java +++ b/instrumentation/servlet/servlet-5.0/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/servlet/v5_0/request/Utils.java @@ -45,7 +45,8 @@ public static ByteBufferSpanPair createRequestByteBufferSpanPair( } return new ByteBufferSpanPair( span, - BoundedBuffersFactory.createStream(contentLength, charset), + BoundedBuffersFactory.createStream( + contentLength, charset, httpServletRequest.getContentType()), filter::evaluateRequestBody, headers); } diff --git a/instrumentation/undertow/undertow-1.4/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/undertow/v1_4/utils/BodyCapturingExchangeCompletionListener.java b/instrumentation/undertow/undertow-1.4/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/undertow/v1_4/utils/BodyCapturingExchangeCompletionListener.java index 9db79425a..925203f90 100644 --- a/instrumentation/undertow/undertow-1.4/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/undertow/v1_4/utils/BodyCapturingExchangeCompletionListener.java +++ b/instrumentation/undertow/undertow-1.4/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/undertow/v1_4/utils/BodyCapturingExchangeCompletionListener.java @@ -16,6 +16,7 @@ package io.opentelemetry.javaagent.instrumentation.hypertrace.undertow.v1_4.utils; +import io.opentelemetry.api.common.AttributeKey; import io.undertow.server.ExchangeCompletionListener; import io.undertow.server.HttpServerExchange; import java.io.UnsupportedEncodingException; @@ -37,6 +38,17 @@ public BodyCapturingExchangeCompletionListener(final SpanAndBuffer spanAndBuffer @Override public void exchangeEvent(HttpServerExchange exchange, NextListener nextListener) { + if (spanAndBuffer.byteArrayBuffer.isMultipartFormData()) { + // multipart bodies carry binary file parts: keep the raw bytes, not the decoded text + if (spanAndBuffer.byteArrayBuffer.size() > 0) { + spanAndBuffer.span.setAttribute( + AttributeKey.stringKey( + HypertraceSemanticAttributes.HTTP_REQUEST_BODY.getKey() + ".base64"), + spanAndBuffer.byteArrayBuffer.toBase64()); + } + nextListener.proceed(); + return; + } final String body; try { body = spanAndBuffer.byteArrayBuffer.toStringWithSuppliedCharset(); diff --git a/instrumentation/undertow/undertow-1.4/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/undertow/v1_4/utils/Utils.java b/instrumentation/undertow/undertow-1.4/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/undertow/v1_4/utils/Utils.java index 2db70d107..709f61c2a 100644 --- a/instrumentation/undertow/undertow-1.4/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/undertow/v1_4/utils/Utils.java +++ b/instrumentation/undertow/undertow-1.4/src/main/java/io/opentelemetry/javaagent/instrumentation/hypertrace/undertow/v1_4/utils/Utils.java @@ -58,7 +58,9 @@ public static void createAndStoreBufferForSpan( final Charset charset = Charset.forName(httpServerExchange.getRequestCharset()); final BoundedByteArrayOutputStream boundedByteArrayOutputStream = BoundedBuffersFactory.createStream( - (int) httpServerExchange.getRequestContentLength(), charset); + (int) httpServerExchange.getRequestContentLength(), + charset, + httpServerExchange.getRequestHeaders().getFirst(Headers.CONTENT_TYPE)); final String contentEncoding = httpServerExchange.getRequestHeaders().getFirst(Headers.CONTENT_ENCODING); final SpanAndBuffer spanAndBuffer = diff --git a/javaagent-core/src/main/java/org/hypertrace/agent/core/instrumentation/buffer/BoundedBuffersFactory.java b/javaagent-core/src/main/java/org/hypertrace/agent/core/instrumentation/buffer/BoundedBuffersFactory.java index 8894ac1fc..db0695340 100644 --- a/javaagent-core/src/main/java/org/hypertrace/agent/core/instrumentation/buffer/BoundedBuffersFactory.java +++ b/javaagent-core/src/main/java/org/hypertrace/agent/core/instrumentation/buffer/BoundedBuffersFactory.java @@ -18,6 +18,7 @@ import java.nio.charset.Charset; import org.hypertrace.agent.core.config.InstrumentationConfig; +import org.hypertrace.agent.core.instrumentation.utils.ContentTypeUtils; public class BoundedBuffersFactory { @@ -36,6 +37,17 @@ public static BoundedByteArrayOutputStream createStream(int initialSize, Charset : new BoundedByteArrayOutputStream(MAX_SIZE, charset); } + /** + * Creates a stream for a body with the given content type. A multipart/form-data body is flagged + * so it is captured as base64 of the raw bytes. + */ + public static BoundedByteArrayOutputStream createStream( + int initialSize, Charset charset, String contentType) { + BoundedByteArrayOutputStream stream = createStream(initialSize, charset); + stream.setMultipartFormData(ContentTypeUtils.isMultipartFormData(contentType)); + return stream; + } + public static BoundedCharArrayWriter createWriter() { return new BoundedCharArrayWriter(MAX_SIZE); } diff --git a/javaagent-core/src/main/java/org/hypertrace/agent/core/instrumentation/buffer/BoundedByteArrayOutputStream.java b/javaagent-core/src/main/java/org/hypertrace/agent/core/instrumentation/buffer/BoundedByteArrayOutputStream.java index 94e33821e..8651b18ed 100644 --- a/javaagent-core/src/main/java/org/hypertrace/agent/core/instrumentation/buffer/BoundedByteArrayOutputStream.java +++ b/javaagent-core/src/main/java/org/hypertrace/agent/core/instrumentation/buffer/BoundedByteArrayOutputStream.java @@ -20,6 +20,7 @@ import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; +import java.util.Base64; /** * {@link ByteArrayOutputStream} with a bounded capacity. Write methods are no-op if the size @@ -29,6 +30,7 @@ public class BoundedByteArrayOutputStream extends ByteArrayOutputStream { private final int maxCapacity; private final Charset charset; + private volatile boolean multipartFormData; BoundedByteArrayOutputStream(int maxCapacity, Charset charset) { this.maxCapacity = maxCapacity; @@ -41,6 +43,23 @@ public class BoundedByteArrayOutputStream extends ByteArrayOutputStream { this.charset = charset; } + /** + * Whether the buffered bytes are a multipart/form-data body. Such bodies are captured as base64 + * of the raw bytes, not decoded to text. + */ + public boolean isMultipartFormData() { + return multipartFormData; + } + + public void setMultipartFormData(boolean multipartFormData) { + this.multipartFormData = multipartFormData; + } + + /** Unpadded base64 of the buffered bytes. */ + public synchronized String toBase64() { + return Base64.getEncoder().withoutPadding().encodeToString(super.toByteArray()); + } + public synchronized String toStringWithSuppliedCharset() throws UnsupportedEncodingException { return super.toString(this.charset.name()); } diff --git a/javaagent-core/src/main/java/org/hypertrace/agent/core/instrumentation/buffer/ByteBufferSpanPair.java b/javaagent-core/src/main/java/org/hypertrace/agent/core/instrumentation/buffer/ByteBufferSpanPair.java index 228527837..ddda5281c 100644 --- a/javaagent-core/src/main/java/org/hypertrace/agent/core/instrumentation/buffer/ByteBufferSpanPair.java +++ b/javaagent-core/src/main/java/org/hypertrace/agent/core/instrumentation/buffer/ByteBufferSpanPair.java @@ -28,6 +28,8 @@ public class ByteBufferSpanPair { + private static final String BASE64_ATTRIBUTE_SUFFIX = ".base64"; + public final Span span; private final BoundedByteArrayOutputStream buffer; private final Map headers; @@ -57,7 +59,16 @@ public void captureBody(AttributeKey attributeKey) { } catch (UnsupportedEncodingException e) { // ignore charset has been parsed before } - span.setAttribute(attributeKey, requestBody); + if (buffer.isMultipartFormData()) { + // multipart bodies carry binary file parts: keep the raw bytes, not the decoded text + if (buffer.size() > 0) { + span.setAttribute( + AttributeKey.stringKey(attributeKey.getKey() + BASE64_ATTRIBUTE_SUFFIX), + buffer.toBase64()); + } + } else { + span.setAttribute(attributeKey, requestBody); + } final FilterResult filterResult; filterResult = filter.apply(span, requestBody, headers); if (filterResult.shouldBlock()) { diff --git a/javaagent-core/src/main/java/org/hypertrace/agent/core/instrumentation/utils/ContentTypeUtils.java b/javaagent-core/src/main/java/org/hypertrace/agent/core/instrumentation/utils/ContentTypeUtils.java index aefc36d9a..872ca0eff 100644 --- a/javaagent-core/src/main/java/org/hypertrace/agent/core/instrumentation/utils/ContentTypeUtils.java +++ b/javaagent-core/src/main/java/org/hypertrace/agent/core/instrumentation/utils/ContentTypeUtils.java @@ -24,7 +24,9 @@ public class ContentTypeUtils { private final String[] collectableContentTypes; private static final String[] DEFAULT_CONTENT_TYPES = - new String[] {"json", "graphql", "xml", "x-www-form-urlencoded"}; + new String[] {"json", "graphql", "xml", "x-www-form-urlencoded", "multipart/form-data"}; + + private static final String MULTIPART_FORM_DATA = "multipart/form-data"; public static String[] getDefaultContentTypes() { return DEFAULT_CONTENT_TYPES; @@ -94,6 +96,17 @@ public static boolean shouldCapture(String contentType) { return getInstance().shouldCapture_(contentType); } + /** + * Returns true if the content type is multipart/form-data. These bodies carry binary file parts, + * so they are captured as base64 of the raw bytes instead of as text. + * + * @param contentType request or response content type, may be null + * @return whether the media type is multipart/form-data + */ + public static boolean isMultipartFormData(String contentType) { + return contentType != null && contentType.trim().toLowerCase().startsWith(MULTIPART_FORM_DATA); + } + public static String parseCharset(String contentType) { if (contentType == null) { return null; diff --git a/javaagent-core/src/test/java/org/hypertrace/agent/core/instrumentation/buffer/ByteBufferSpanPairTest.java b/javaagent-core/src/test/java/org/hypertrace/agent/core/instrumentation/buffer/ByteBufferSpanPairTest.java new file mode 100644 index 000000000..665b7b373 --- /dev/null +++ b/javaagent-core/src/test/java/org/hypertrace/agent/core/instrumentation/buffer/ByteBufferSpanPairTest.java @@ -0,0 +1,184 @@ +/* + * Copyright The Hypertrace Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.hypertrace.agent.core.instrumentation.buffer; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.trace.Span; +import java.lang.reflect.Proxy; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Base64; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; +import org.hypertrace.agent.core.TriFunction; +import org.hypertrace.agent.core.filter.FilterResult; +import org.hypertrace.agent.core.instrumentation.HypertraceEvaluationException; +import org.hypertrace.agent.core.instrumentation.HypertraceSemanticAttributes; +import org.hypertrace.agent.core.instrumentation.utils.ContentTypeUtils; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +class ByteBufferSpanPairTest { + + private static final String MULTIPART = "multipart/form-data; boundary=b"; + private static final FilterResult ALLOW = new FilterResult(false, 0, null); + + private final Map attributes = new HashMap<>(); + private final AtomicInteger filterCalls = new AtomicInteger(); + private final AtomicInteger filterSeenBodyLength = new AtomicInteger(-1); + + /** Minimal recording Span: javaagent-core has no OpenTelemetry SDK test dependency. */ + private Span recordingSpan() { + return (Span) + Proxy.newProxyInstance( + Span.class.getClassLoader(), + new Class[] {Span.class}, + (proxy, method, args) -> { + if (method.getName().equals("setAttribute") && args.length == 2) { + Object key = args[0]; + attributes.put( + key instanceof AttributeKey ? ((AttributeKey) key).getKey() : (String) key, + args[1]); + } + return method.getReturnType() == Span.class ? proxy : null; + }); + } + + private ByteBufferSpanPair pair( + String contentType, TriFunction, FilterResult> filter) { + // not BoundedBuffersFactory: its static init needs the agent's InstrumentationConfig + BoundedByteArrayOutputStream buffer = + new BoundedByteArrayOutputStream(1024, StandardCharsets.ISO_8859_1); + buffer.setMultipartFormData(ContentTypeUtils.isMultipartFormData(contentType)); + return new ByteBufferSpanPair(recordingSpan(), buffer, filter, new HashMap<>()); + } + + private TriFunction, FilterResult> allowAll() { + return (span, body, headers) -> { + filterCalls.incrementAndGet(); + filterSeenBodyLength.set(body.length()); + return ALLOW; + }; + } + + private static String base64(byte[] bytes) { + return Base64.getEncoder().withoutPadding().encodeToString(bytes); + } + + @Test + void multipartBodyIsCapturedAsBase64OfRawBytes() throws Exception { + // a binary file part: bytes that are not valid text in any charset + byte[] body = + concat( + "--b\r\nContent-Disposition: form-data; name=\"f\"; filename=\"a.bin\"\r\n\r\n" + .getBytes(StandardCharsets.US_ASCII), + new byte[] {0, (byte) 0xff, (byte) 0xfe, 0x1, (byte) 0x80}, + "\r\n--b--\r\n".getBytes(StandardCharsets.US_ASCII)); + ByteBufferSpanPair pair = pair(MULTIPART, allowAll()); + pair.writeToBuffer(body); + + pair.captureBody(HypertraceSemanticAttributes.HTTP_REQUEST_BODY); + + Assertions.assertEquals(base64(body), attributes.get("http.request.body.base64")); + Assertions.assertFalse(attributes.containsKey("http.request.body")); + Assertions.assertEquals(1, filterCalls.get()); + } + + @Test + void nonMultipartBodyIsStillCapturedAsText() throws Exception { + ByteBufferSpanPair pair = pair("application/json", allowAll()); + pair.writeToBuffer("{\"a\":1}".getBytes(StandardCharsets.UTF_8)); + + pair.captureBody(HypertraceSemanticAttributes.HTTP_REQUEST_BODY); + + Assertions.assertEquals("{\"a\":1}", attributes.get("http.request.body")); + Assertions.assertFalse(attributes.containsKey("http.request.body.base64")); + } + + @Test + void malformedMultipartBodiesDoNotThrowAndAreCapturedVerbatim() throws Exception { + byte[][] malformed = { + // not multipart at all + "this is not multipart".getBytes(StandardCharsets.US_ASCII), + // boundary never terminated, part truncated mid-header + "--b\r\nContent-Disposition: form-da".getBytes(StandardCharsets.US_ASCII), + // wrong boundary + "--zzz\r\n\r\nhello\r\n--zzz--".getBytes(StandardCharsets.US_ASCII), + // random binary garbage + new byte[] {(byte) 0xde, (byte) 0xad, 0, (byte) 0xbe, (byte) 0xef, (byte) 0xff}, + }; + for (byte[] body : malformed) { + attributes.clear(); + ByteBufferSpanPair pair = pair(MULTIPART, allowAll()); + pair.writeToBuffer(body); + + Assertions.assertDoesNotThrow( + () -> pair.captureBody(HypertraceSemanticAttributes.HTTP_REQUEST_BODY), + Arrays.toString(body)); + + Assertions.assertEquals(base64(body), attributes.get("http.request.body.base64")); + } + } + + @Test + void emptyMultipartBodySetsNoAttribute() { + ByteBufferSpanPair pair = pair(MULTIPART, allowAll()); + + Assertions.assertDoesNotThrow( + () -> pair.captureBody(HypertraceSemanticAttributes.HTTP_REQUEST_BODY)); + + Assertions.assertTrue(attributes.isEmpty()); + Assertions.assertEquals(1, filterCalls.get()); + } + + @Test + void multipartBodyIsStillEvaluatedAndCanBeBlocked() throws Exception { + ByteBufferSpanPair pair = + pair(MULTIPART, (span, body, headers) -> new FilterResult(true, 403, "blocked")); + pair.writeToBuffer("--b\r\n\r\nattack\r\n--b--".getBytes(StandardCharsets.US_ASCII)); + + HypertraceEvaluationException e = + Assertions.assertThrows( + HypertraceEvaluationException.class, + () -> pair.captureBody(HypertraceSemanticAttributes.HTTP_REQUEST_BODY)); + Assertions.assertEquals(403, e.getFilterResult().getBlockingStatusCode()); + } + + @Test + void multipartBodyIsTruncatedAtMaxSizeOnRawBytes() throws Exception { + BoundedByteArrayOutputStream buffer = + new BoundedByteArrayOutputStream(4, StandardCharsets.ISO_8859_1); + buffer.setMultipartFormData(true); + ByteBufferSpanPair pair = + new ByteBufferSpanPair(recordingSpan(), buffer, allowAll(), new HashMap<>()); + pair.writeToBuffer(new byte[] {1, 2, 3, 4, 5, 6}); + + pair.captureBody(HypertraceSemanticAttributes.HTTP_REQUEST_BODY); + + Assertions.assertEquals( + base64(new byte[] {1, 2, 3, 4}), attributes.get("http.request.body.base64")); + } + + private static byte[] concat(byte[]... parts) { + java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream(); + for (byte[] part : parts) { + out.write(part, 0, part.length); + } + return out.toByteArray(); + } +} diff --git a/javaagent-core/src/test/java/org/hypertrace/agent/core/instrumentation/utils/ContentTypeUtilsTest.java b/javaagent-core/src/test/java/org/hypertrace/agent/core/instrumentation/utils/ContentTypeUtilsTest.java index f43807917..a9ad286bc 100644 --- a/javaagent-core/src/test/java/org/hypertrace/agent/core/instrumentation/utils/ContentTypeUtilsTest.java +++ b/javaagent-core/src/test/java/org/hypertrace/agent/core/instrumentation/utils/ContentTypeUtilsTest.java @@ -23,7 +23,9 @@ class ContentTypeUtilsTest { @Test public void shouldCapture() { - String[] valid = {"jSoN", "graphQL", "x-www-forM-urlencoded"}; + String[] valid = { + "jSoN", "graphQL", "x-www-forM-urlencoded", "multipart/form-data; boundary=b" + }; for (String contentType : valid) { Assertions.assertTrue(ContentTypeUtils.shouldCapture(contentType), contentType); } @@ -31,14 +33,33 @@ public void shouldCapture() { @Test public void shouldNotCapture() { - String[] valid = { - "text/plain", - }; + String[] valid = {"text/plain", "multipart/mixed; boundary=b", "application/octet-stream"}; for (String contentType : valid) { Assertions.assertFalse(ContentTypeUtils.shouldCapture(contentType), contentType); } } + @Test + public void defaultContentTypesIncludeMultipartFormData() { + Assertions.assertTrue( + java.util.Arrays.asList(ContentTypeUtils.getDefaultContentTypes()) + .contains("multipart/form-data")); + } + + @Test + public void isMultipartFormData() { + Assertions.assertTrue(ContentTypeUtils.isMultipartFormData("multipart/form-data; boundary=b")); + Assertions.assertTrue(ContentTypeUtils.isMultipartFormData(" Multipart/Form-Data")); + } + + @Test + public void isNotMultipartFormData() { + String[] values = {null, "", "multipart/mixed", "application/json", "text/multipart/form-data"}; + for (String contentType : values) { + Assertions.assertFalse(ContentTypeUtils.isMultipartFormData(contentType), contentType); + } + } + @Test public void utf8Charset() { Assertions.assertEquals( diff --git a/otel-extensions/src/test/java/org/hypertrace/agent/otel/extensions/config/HypertraceConfigTest.java b/otel-extensions/src/test/java/org/hypertrace/agent/otel/extensions/config/HypertraceConfigTest.java index 4fac1c921..087a58add 100644 --- a/otel-extensions/src/test/java/org/hypertrace/agent/otel/extensions/config/HypertraceConfigTest.java +++ b/otel-extensions/src/test/java/org/hypertrace/agent/otel/extensions/config/HypertraceConfigTest.java @@ -38,7 +38,7 @@ public class HypertraceConfigTest { private static final String[] EXPECTED_CONTENT_TYPES = - new String[] {"json", "graphql", "xml", "x-www-form-urlencoded"}; + new String[] {"json", "graphql", "xml", "x-www-form-urlencoded", "multipart/form-data"}; private static final String[] EXPECTED_CONTENT_TYPES_WITH_OVERRIDES = new String[] {"foo", "bar"}; diff --git a/testing-common/src/main/java/org/hypertrace/agent/testing/AbstractHttpClientTest.java b/testing-common/src/main/java/org/hypertrace/agent/testing/AbstractHttpClientTest.java index 16e21d21c..94447c8ed 100644 --- a/testing-common/src/main/java/org/hypertrace/agent/testing/AbstractHttpClientTest.java +++ b/testing-common/src/main/java/org/hypertrace/agent/testing/AbstractHttpClientTest.java @@ -23,6 +23,8 @@ import java.io.InputStreamReader; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Base64; import java.util.Collections; import java.util.HashMap; import java.util.List; @@ -41,6 +43,7 @@ public abstract class AbstractHttpClientTest extends AbstractInstrumenterTest { private static final String GET_JSON_PATH_FORMAT = "http://localhost:%d/get_json"; private static final String GET_GZIP_FORMAT = "http://localhost:%d/gzip"; private static final String VERIFY_HEADERS_FORMAT = "http://localhost:%d/verify_headers"; + private static final int DEFAULT_BODY_MAX_SIZE_BYTES = 131072; private static final String HEADER_NAME = "headername"; private static final String HEADER_VALUE = "headerValue"; private static final Map headers; @@ -59,6 +62,15 @@ public AbstractHttpClientTest(boolean hasResponseBodySpan) { this.hasResponseBodySpan = hasResponseBodySpan; } + /** + * Whether the instrumentation under test captures multipart/form-data request bodies as base64 of + * the raw bytes ({@code http.request.body.base64}). Clients that do not yet are only checked for + * not breaking the request. + */ + protected boolean capturesMultipartAsBase64() { + return false; + } + @BeforeAll public static void startServer() throws Exception { testHttpServer.start(); @@ -218,6 +230,74 @@ public void postPlainText_echo() assertNoBodies(clientSpan); } + @Test + public void postMultipartFormData_echo() + throws TimeoutException, InterruptedException, IOException, ExecutionException { + assertMultipartEcho( + "--b\r\nContent-Disposition: form-data; name=\"note\"\r\n\r\nhello\r\n--b--\r\n"); + } + + /** Capturing must never break or alter the application's request, whatever the body is. */ + @Test + public void postMalformedMultipartFormData_echo() + throws TimeoutException, InterruptedException, IOException, ExecutionException { + assertMultipartEcho("--b\r\nContent-Disp"); + } + + /** Uploads larger than the body cap are truncated on raw bytes and must still go through. */ + @Test + public void postLargeMultipartFormData_echo() + throws TimeoutException, InterruptedException, IOException, ExecutionException { + StringBuilder body = + new StringBuilder("--b\r\nContent-Disposition: form-data; name=\"f\"\r\n\r\n"); + for (int i = 0; i < 2 * DEFAULT_BODY_MAX_SIZE_BYTES; i++) { + body.append('x'); + } + body.append("\r\n--b--\r\n"); + assertMultipartEcho(body.toString()); + } + + private void assertMultipartEcho(String body) + throws TimeoutException, InterruptedException, IOException, ExecutionException { + String uri = String.format(ECHO_PATH_FORMAT, testHttpServer.port()); + + Response response = doPostRequest(uri, headers, body, "multipart/form-data; boundary=b"); + + Assertions.assertEquals(200, response.statusCode); + Assertions.assertEquals(body, response.body); + + if (!capturesMultipartAsBase64()) { + return; + } + TEST_WRITER.waitForTraces(1); + List> traces = + TEST_WRITER.waitForSpans( + hasResponseBodySpan ? 2 : 1, + span -> + hasResponseBodySpan + ? span.getKind().equals(Span.SpanKind.SPAN_KIND_SERVER) + : !span.getKind().equals(Span.SpanKind.SPAN_KIND_CLIENT) + || span.getAttributesList().stream() + .noneMatch( + keyValue -> + keyValue.getKey().equals("http.url") + && keyValue.getValue().getStringValue().contains("/echo"))); + Assertions.assertEquals(1, traces.size()); + Span clientSpan = + traces.get(0).stream() + .filter(span -> span.getKind().equals(Span.SpanKind.SPAN_KIND_CLIENT)) + .findFirst() + .get(); + + byte[] bodyBytes = body.getBytes(StandardCharsets.UTF_8); + byte[] expectedCaptured = + Arrays.copyOf(bodyBytes, Math.min(bodyBytes.length, DEFAULT_BODY_MAX_SIZE_BYTES)); + Assertions.assertEquals( + Base64.getEncoder().withoutPadding().encodeToString(expectedCaptured), + TEST_WRITER.getAttributesMap(clientSpan).get("http.request.body.base64").getStringValue()); + Assertions.assertNull(TEST_WRITER.getAttributesMap(clientSpan).get("http.request.body")); + } + @Test public void getNoContent() throws IOException, TimeoutException, InterruptedException, ExecutionException {