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
10 changes: 8 additions & 2 deletions src/main/java/org/example/ConnectionHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import org.example.config.AppConfig;
import org.example.filter.IpFilter;
import org.example.filter.MaxRequestBodySizeFilter;
import org.example.httpparser.HttpParser;
import org.example.httpparser.HttpRequest;
import java.util.ArrayList;
Expand Down Expand Up @@ -40,6 +41,10 @@ private List<Filter> buildFilters() {
if (Boolean.TRUE.equals(ipFilterConfig.enabled())) {
list.add(createIpFilterFromConfig(ipFilterConfig));
}
AppConfig.MaxRequestBodyConfig maxBodyConfig = config.maxRequestBody();
if (Boolean.TRUE.equals(maxBodyConfig.enabled())) {
list.add(new MaxRequestBodySizeFilter(maxBodyConfig.maxBytes()));
}
Comment on lines +44 to +47

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Filter integration currently bypasses parsed-body enforcement.

MaxRequestBodySizeFilter is added here, but in this execution path HttpRequest is constructed with an empty body on Line 71. That means the filter’s fallback byte-length check never runs, so enforcement is effectively limited to the declared Content-Length header only.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/main/java/org/example/ConnectionHandler.java` around lines 44 - 47, The
MaxRequestBodySizeFilter is never able to enforce actual byte-size because
ConnectionHandler constructs the HttpRequest with an empty body before filters
run; fix by ensuring the raw request body bytes are available to the filter:
either run MaxRequestBodySizeFilter before building the HttpRequest or construct
the HttpRequest with the actual body stream/byte[] (instead of an empty body) so
MaxRequestBodySizeFilter can inspect the bytes; update the ConnectionHandler
code path that creates the HttpRequest and the filter registration
(AppConfig.MaxRequestBodyConfig / MaxRequestBodySizeFilter) so the filter
receives the raw body (or a reusable InputStream/byte supplier) prior to any
parsing or consumption.

// Add more filters here...
return list;
}
Expand All @@ -63,7 +68,7 @@ public void runConnectionHandler() throws IOException {
parser.getUri(),
parser.getVersion(),
parser.getHeadersMap(),
""
null
);

String clientIp = client.getInetAddress().getHostAddress();
Expand All @@ -73,7 +78,8 @@ public void runConnectionHandler() throws IOException {

int statusCode = response.getStatusCode();
if (statusCode == HttpResponseBuilder.SC_FORBIDDEN ||
statusCode == HttpResponseBuilder.SC_BAD_REQUEST) {
statusCode == HttpResponseBuilder.SC_BAD_REQUEST ||
statusCode == HttpResponseBuilder.SC_PAYLOAD_TOO_LARGE) {
byte[] responseBytes = response.build();
client.getOutputStream().write(responseBytes);
client.getOutputStream().flush();
Expand Down
35 changes: 31 additions & 4 deletions src/main/java/org/example/config/AppConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,27 @@
public record AppConfig(
@JsonProperty("server") ServerConfig server,
@JsonProperty("logging") LoggingConfig logging,
@JsonProperty("ipFilter") IpFilterConfig ipFilter
@JsonProperty("ipFilter") IpFilterConfig ipFilter,
@JsonProperty("maxRequestBody") MaxRequestBodyConfig maxRequestBody

) {
public static AppConfig defaults() {
return new AppConfig(
ServerConfig.defaults(),
LoggingConfig.defaults(),
IpFilterConfig.defaults()
IpFilterConfig.defaults(),
MaxRequestBodyConfig.defaults()
);
}

public AppConfig withDefaultsApplied() {
ServerConfig serverConfig = (server == null ? ServerConfig.defaults() : server.withDefaultsApplied());
LoggingConfig loggingConfig = (logging == null ? LoggingConfig.defaults() : logging.withDefaultsApplied());
IpFilterConfig ipFilterConfig = (ipFilter == null ? IpFilterConfig.defaults() : ipFilter.withDefaultsApplied()); // ← LÄGG TILL
return new AppConfig(serverConfig, loggingConfig, ipFilterConfig); // ← UPPDATERA DENNA RAD
IpFilterConfig ipFilterConfig = (ipFilter == null ? IpFilterConfig.defaults() : ipFilter.withDefaultsApplied());
MaxRequestBodyConfig maxRequestBodyConfig =
(maxRequestBody == null ? MaxRequestBodyConfig.defaults() : maxRequestBody.withDefaultsApplied());

return new AppConfig(serverConfig, loggingConfig, ipFilterConfig, maxRequestBodyConfig);
}

@JsonIgnoreProperties(ignoreUnknown = true)
Expand Down Expand Up @@ -76,4 +82,25 @@ public IpFilterConfig withDefaultsApplied() {
return new IpFilterConfig(e, m, blocked, allowed);
}
}

@JsonIgnoreProperties(ignoreUnknown = true)
public record MaxRequestBodyConfig(
@JsonProperty("enabled") Boolean enabled,
@JsonProperty("maxBytes") Long maxBytes
) {
public static MaxRequestBodyConfig defaults() {
return new MaxRequestBodyConfig(false, 1_048_576L);
}

public MaxRequestBodyConfig withDefaultsApplied() {
Boolean enabledFlag = (enabled == null) ? false : enabled;
long limit = (maxBytes == null) ? 1_048_576L : maxBytes;

if (limit < 0) {
throw new IllegalArgumentException("maxRequestBody.maxBytes must be >= 0");
}

return new MaxRequestBodyConfig(enabledFlag, limit);
}
}
}
97 changes: 97 additions & 0 deletions src/main/java/org/example/filter/MaxRequestBodySizeFilter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
package org.example.filter;


import org.example.http.HttpResponseBuilder;
import org.example.httpparser.HttpRequest;

import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
* A filter that rejects requests with bodies larger than a configured byte limit.
* It primarily uses the Content-Length header (when present), and can also validate
* a parsed request body if available.
*/
public class MaxRequestBodySizeFilter implements Filter {

private final long maxBytes;

public MaxRequestBodySizeFilter(long maxBytes) {
if (maxBytes < 0) {
throw new IllegalArgumentException("maxBytes must be >= 0");
}
this.maxBytes = maxBytes;
}
@Override
public void init() {

}

@Override
public void doFilter(HttpRequest request, HttpResponseBuilder response, FilterChain chain) {

if (!mayHaveBody(request.getMethod())) {
chain.doFilter(request, response);
return;
}

Long contentLength = getHeaderAsLong(request.getHeaders(), "Content-Length");

if (contentLength != null && contentLength > maxBytes) {
reject(response, contentLength);
return;
}

// fallback: if a body has already been parsed, validate it as well
String body = request.getBody();
if (body != null && !body.isEmpty()) {
int bodySizeInBytes = body.getBytes(StandardCharsets.UTF_8).length;
if (bodySizeInBytes > maxBytes) {
reject(response, (long) bodySizeInBytes);
return;
}
}
chain.doFilter(request, response);
}

@Override
public void destroy() {

}

private boolean mayHaveBody(String method) {
if (method == null) {
return false;
}
String normalizedMethod = method.trim().toUpperCase();
return normalizedMethod.equals("POST") || normalizedMethod.equals("PUT") || normalizedMethod.equals("PATCH");
}

private Long getHeaderAsLong(Map<String, String> headers, String headerName) {
if (headers == null || headerName == null) {
return null;
}
String rawHeaderValue = null;
for (Map.Entry<String, String> headerEntry : headers.entrySet()) {
String currentHeaderName = headerEntry.getKey();
if (currentHeaderName.equalsIgnoreCase(headerName)) {
rawHeaderValue = headerEntry.getValue();
break;
}
}
if (rawHeaderValue == null) {
return null;
}
try {
long parsedContentLength = Long.parseLong(rawHeaderValue.trim());
return parsedContentLength < 0 ? null : parsedContentLength;
} catch (NumberFormatException ex) {
return null;
}
}

private void reject(HttpResponseBuilder response, Long contentLength) {
response.setStatusCode(HttpResponseBuilder.SC_PAYLOAD_TOO_LARGE);
response.setBody("Payload too large: " + contentLength + " bytes (max " + maxBytes + ")");
}
}
4 changes: 3 additions & 1 deletion src/main/java/org/example/http/HttpResponseBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ public class HttpResponseBuilder {
public static final int SC_UNAUTHORIZED = 401;
public static final int SC_FORBIDDEN = 403;
public static final int SC_NOT_FOUND = 404;
public static final int SC_PAYLOAD_TOO_LARGE = 413;

// SERVER ERROR
public static final int SC_INTERNAL_SERVER_ERROR = 500;
Expand Down Expand Up @@ -60,7 +61,8 @@ public class HttpResponseBuilder {
Map.entry(SC_INTERNAL_SERVER_ERROR, "Internal Server Error"),
Map.entry(SC_BAD_GATEWAY, "Bad Gateway"),
Map.entry(SC_SERVICE_UNAVAILABLE, "Service Unavailable"),
Map.entry(SC_GATEWAY_TIMEOUT, "Gateway Timeout")
Map.entry(SC_GATEWAY_TIMEOUT, "Gateway Timeout"),
Map.entry(SC_PAYLOAD_TOO_LARGE, "Payload Too Large")
);

public void setStatusCode(int statusCode) {
Expand Down
4 changes: 4 additions & 0 deletions src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,7 @@ ipFilter:
mode: "BLOCKLIST"
blockedIps: [ ]
allowedIps: [ ]

maxRequestBody:
enabled: true
maxBytes: 1048576
128 changes: 128 additions & 0 deletions src/test/java/org/example/filter/MaxRequestBodySizeTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
package org.example.filter;

import org.example.http.HttpResponseBuilder;
import org.example.httpparser.HttpRequest;
import org.junit.jupiter.api.Test;

import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

import static org.junit.jupiter.api.Assertions.*;

class MaxRequestBodySizeFilterTest {

private static FilterChain spyChain(AtomicBoolean called) {
return (req, resp) -> called.set(true);
}

@Test
void getRequest_shouldPassThrough() {
MaxRequestBodySizeFilter filter = new MaxRequestBodySizeFilter(10);

HttpRequest request = new HttpRequest("GET", "/", "HTTP/1.1", Map.of(), null);
HttpResponseBuilder response = new HttpResponseBuilder();
AtomicBoolean chainCalled = new AtomicBoolean(false);

filter.doFilter(request, response, spyChain(chainCalled));

assertTrue(chainCalled.get());
assertEquals(HttpResponseBuilder.SC_OK, response.getStatusCode());
}

@Test
void postWithTooLargeContentLength_shouldRejectWith413() {
MaxRequestBodySizeFilter filter = new MaxRequestBodySizeFilter(10);

HttpRequest request = new HttpRequest(
"POST", "/upload", "HTTP/1.1",
Map.of("Content-Length", "11"),
null
);
HttpResponseBuilder response = new HttpResponseBuilder();
AtomicBoolean chainCalled = new AtomicBoolean(false);

filter.doFilter(request, response, spyChain(chainCalled));

assertFalse(chainCalled.get());
assertEquals(HttpResponseBuilder.SC_PAYLOAD_TOO_LARGE, response.getStatusCode());
assertTrue(response.getBody().startsWith("Payload too large:"), "body should explain rejection");
}

@Test
void postWithContentLengthEqualToMax_shouldPassThrough() {
MaxRequestBodySizeFilter filter = new MaxRequestBodySizeFilter(10);

HttpRequest request = new HttpRequest(
"POST", "/upload", "HTTP/1.1",
Map.of("Content-Length", "10"),
null
);
HttpResponseBuilder response = new HttpResponseBuilder();
AtomicBoolean chainCalled = new AtomicBoolean(false);

filter.doFilter(request, response, spyChain(chainCalled));

assertTrue(chainCalled.get());
assertEquals(HttpResponseBuilder.SC_OK, response.getStatusCode());
}

@Test
void invalidContentLength_shouldBeIgnoredAndPassThrough() {
MaxRequestBodySizeFilter filter = new MaxRequestBodySizeFilter(10);

HttpRequest request = new HttpRequest(
"POST", "/upload", "HTTP/1.1",
Map.of("Content-Length", "abc"),
null
);
HttpResponseBuilder response = new HttpResponseBuilder();
AtomicBoolean chainCalled = new AtomicBoolean(false);

filter.doFilter(request, response, spyChain(chainCalled));

assertTrue(chainCalled.get());
assertEquals(HttpResponseBuilder.SC_OK, response.getStatusCode());
}

@Test
void contentLengthHeaderName_shouldBeCaseInsensitive() {
MaxRequestBodySizeFilter filter = new MaxRequestBodySizeFilter(10);

HttpRequest request = new HttpRequest(
"POST", "/upload", "HTTP/1.1",
Map.of("content-length", "11"), // lowercase key
null
);
HttpResponseBuilder response = new HttpResponseBuilder();
AtomicBoolean chainCalled = new AtomicBoolean(false);

filter.doFilter(request, response, spyChain(chainCalled));

assertFalse(chainCalled.get());
assertEquals(HttpResponseBuilder.SC_PAYLOAD_TOO_LARGE, response.getStatusCode());
}

@Test
void bodyFallback_shouldCountUtf8Bytes() {
// "€" is 3 bytes in UTF-8
MaxRequestBodySizeFilter filter = new MaxRequestBodySizeFilter(2);

HttpRequest request = new HttpRequest(
"POST", "/upload", "HTTP/1.1",
Map.of(), // no Content-Length
"€"
);
HttpResponseBuilder response = new HttpResponseBuilder();
AtomicBoolean chainCalled = new AtomicBoolean(false);

filter.doFilter(request, response, spyChain(chainCalled));

assertFalse(chainCalled.get());
assertEquals(HttpResponseBuilder.SC_PAYLOAD_TOO_LARGE, response.getStatusCode());
}

@Test
void negativeMaxBytes_shouldThrow() {
assertThrows(IllegalArgumentException.class, () -> new MaxRequestBodySizeFilter(-1));
}
}