Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ public ApacheHttpClientInstrumentationTest() {
super(true);
}

@Override
protected boolean capturesMultipartAsBase64() {
return true;
}

@Override
public Response doPostRequest(
String uri, Map<String, String> headers, String body, String contentType) throws IOException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,8 @@ public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise prm) {
// the buffer is used byt captureBody method
Attribute<BoundedByteArrayOutputStream> 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);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,8 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) {
// the buffer is used byt captureBody method
Attribute<BoundedByteArrayOutputStream> 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);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ public Netty40ClientInstrumentationTest() {
super(false);
}

@Override
protected boolean capturesMultipartAsBase64() {
return true;
}

@Override
public Response doPostRequest(
String uri, Map<String, String> headers, String body, String contentType)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,8 @@ public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise prm) {
// the buffer is used byt captureBody method
Attribute<BoundedByteArrayOutputStream> 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);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,8 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) {
// the buffer is used byt captureBody method
Attribute<BoundedByteArrayOutputStream> 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);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ public Netty41ClientInstrumentationTest() {
super(false);
}

@Override
protected boolean capturesMultipartAsBase64() {
return true;
}

@Override
public Response doPostRequest(
String uri, Map<String, String> headers, String body, String contentType)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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());
Expand All @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ public OkHttpTracingInterceptorTest() {
super(false);
}

@Override
protected boolean capturesMultipartAsBase64() {
return true;
}

@Override
public Response doPostRequest(
String uri, Map<String, String> headersMap, String body, String contentType)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {

Expand All @@ -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);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -29,6 +30,7 @@ public class BoundedByteArrayOutputStream extends ByteArrayOutputStream {

private final int maxCapacity;
private final Charset charset;
private volatile boolean multipartFormData;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This class can be accessed by multiple threads?


BoundedByteArrayOutputStream(int maxCapacity, Charset charset) {
this.maxCapacity = maxCapacity;
Expand All @@ -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());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<String, String> headers;
Expand Down Expand Up @@ -57,7 +59,16 @@ public void captureBody(AttributeKey<String> 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()) {
Expand Down
Loading