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
@@ -1,5 +1,6 @@
package com.getyourguide.openapi.validation.factory;

import com.getyourguide.openapi.validation.filter.BoundedContentCachingResponseWrapper;
import com.getyourguide.openapi.validation.filter.MultiReadContentCachingRequestWrapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
Expand All @@ -8,6 +9,8 @@
import org.springframework.web.util.WebUtils;

public class ContentCachingWrapperFactory {
public static final int DEFAULT_RESPONSE_CACHE_LIMIT_BYTES = 100 * 1024 * 1024;

public MultiReadContentCachingRequestWrapper buildContentCachingRequestWrapper(HttpServletRequest request) {
if (request instanceof MultiReadContentCachingRequestWrapper) {
return (MultiReadContentCachingRequestWrapper) request;
Expand All @@ -22,7 +25,7 @@ public ContentCachingResponseWrapper buildContentCachingResponseWrapper(HttpServ
return cachingResponse;
}

return new ContentCachingResponseWrapper(response);
return new BoundedContentCachingResponseWrapper(response, DEFAULT_RESPONSE_CACHE_LIMIT_BYTES);
}

@Nullable
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,250 @@
package com.getyourguide.openapi.validation.filter;

import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.WriteListener;
import jakarta.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UncheckedIOException;
import java.io.Writer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import org.springframework.http.HttpHeaders;
import org.springframework.web.util.ContentCachingResponseWrapper;

/**
* Caches a response body up to a fixed limit. Once the limit is exceeded, it writes the cached bytes and all
* subsequent bytes directly to the underlying response.
*/
public class BoundedContentCachingResponseWrapper extends ContentCachingResponseWrapper {
private final int cacheLimitBytes;
private final ByteArrayOutputStream content = new ByteArrayOutputStream();

private ServletOutputStream outputStream;
private PrintWriter writer;
private ResettableWriter writerDelegate;
private boolean contentOverflowed;
private boolean bodyCopied;

public BoundedContentCachingResponseWrapper(HttpServletResponse response, int cacheLimitBytes) {
super(response);
if (cacheLimitBytes < 1) {
throw new IllegalArgumentException("cacheLimitBytes must be positive");
}
this.cacheLimitBytes = cacheLimitBytes;
}

public boolean isContentOverflowed() {
return contentOverflowed;
}

public void flushContent() {
flushWriter();
}

@Override
public ServletOutputStream getOutputStream() {
if (writer != null) {
throw new IllegalStateException(
"This response is already being written as text. Continue using getWriter() instead of getOutputStream()."
);
}
if (outputStream == null) {
outputStream = new ResponseServletOutputStream();
}
return outputStream;
}

@Override
public PrintWriter getWriter() {
if (writer != null) {
return writer;
}
if (outputStream != null) {
throw new IllegalStateException(
"This response is already being written as bytes. Continue using getOutputStream() instead of getWriter()."
);
}
var encoding = getCharacterEncoding();
var charset = encoding != null ? Charset.forName(encoding) : StandardCharsets.ISO_8859_1;
outputStream = getOutputStream();
writerDelegate = new ResettableWriter(outputStream, charset);
writer = new PrintWriter(writerDelegate);
return writer;
}

@Override
public void flushBuffer() throws IOException {
if (writer != null) {
writer.flush();
}
if (contentOverflowed) {
getNativeResponse().flushBuffer();
}
}

public byte[] getContentAsByteArray() {
flushWriter();
return content.toByteArray();
}

public ByteArrayInputStream getContentInputStream() {
return new ByteArrayInputStream(getContentAsByteArray());
}

public int getContentSize() {
flushWriter();
return content.size();
}

public void copyBodyToResponse() throws IOException {
flushWriter();
if (bodyCopied) {
return;
}
if (!contentOverflowed && content.size() > 0) {
var response = getNativeResponse();
if (!response.isCommitted() && response.getHeader(HttpHeaders.TRANSFER_ENCODING) == null) {
response.setContentLength(content.size());
}
getDelegateOutputStream().write(content.toByteArray());
content.reset();
}
bodyCopied = true;
}

@Override
public void resetBuffer() {
clearContent();
getNativeResponse().resetBuffer();
}

@Override
public void reset() {
clearContent();
getNativeResponse().reset();
}

@Override
public void sendError(int status) throws IOException {
resetBuffer();
getNativeResponse().sendError(status);
}

@Override
public void sendError(int status, String message) throws IOException {
resetBuffer();
getNativeResponse().sendError(status, message);
}

@Override
public void sendRedirect(String location) throws IOException {
resetBuffer();
getNativeResponse().sendRedirect(location);
}

private void clearContent() {
if (writerDelegate != null) {
writerDelegate.reset();
}
content.reset();
contentOverflowed = false;
bodyCopied = false;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

private HttpServletResponse getNativeResponse() {
return (HttpServletResponse) getResponse();
}

private ServletOutputStream getDelegateOutputStream() throws IOException {
return getNativeResponse().getOutputStream();
}

private void flushWriter() {
if (writer != null) {
writer.flush();
}
}

private void write(byte[] bytes, int offset, int length) throws IOException {
if (contentOverflowed) {
getDelegateOutputStream().write(bytes, offset, length);
return;
}

if (length <= cacheLimitBytes - content.size()) {
content.write(bytes, offset, length);
return;
}

contentOverflowed = true;
var responseOutputStream = getDelegateOutputStream();
content.writeTo(responseOutputStream);
content.reset();
responseOutputStream.write(bytes, offset, length);
}

private class ResponseServletOutputStream extends ServletOutputStream {
@Override
public boolean isReady() {
try {
return getDelegateOutputStream().isReady();
} catch (IOException exception) {
throw new UncheckedIOException(exception);
}
}

@Override
public void setWriteListener(WriteListener writeListener) {
try {
getDelegateOutputStream().setWriteListener(writeListener);
} catch (IOException exception) {
throw new UncheckedIOException(exception);
}
}

@Override
public void write(int value) throws IOException {
write(new byte[] {(byte) value});
}

@Override
public void write(byte[] bytes, int offset, int length) throws IOException {
BoundedContentCachingResponseWrapper.this.write(bytes, offset, length);
}
}

private static class ResettableWriter extends Writer {
private final ServletOutputStream outputStream;
private final Charset charset;
private OutputStreamWriter delegate;

private ResettableWriter(ServletOutputStream outputStream, Charset charset) {
this.outputStream = outputStream;
this.charset = charset;
this.delegate = new OutputStreamWriter(outputStream, charset);
}

@Override
public void write(char[] characters, int offset, int length) throws IOException {
delegate.write(characters, offset, length);
}

@Override
public void flush() throws IOException {
delegate.flush();
}

@Override
public void close() throws IOException {
delegate.close();
}

private void reset() {
delegate = new OutputStreamWriter(outputStream, charset);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,13 @@ private void validateResponse(
var responseMetaData = metaDataFactory.buildResponseMetaData(response, exception);
var responseToUse = contentCachingWrapperFactory.getCachingResponse(response);
if (responseToUse != null) {
if (responseToUse instanceof BoundedContentCachingResponseWrapper boundedResponse) {
boundedResponse.flushContent();
if (boundedResponse.isContentOverflowed()) {
log.debug("Skipping validation because the response body exceeded the cache limit");
return;
}
}
var violations = validateResponse(
request,
responseToUse,
Expand Down
Loading