Skip to content

Feature/issue99 request body size limit filter#114

Open
MartinStenhagen wants to merge 11 commits intomainfrom
feature/issue99-request-body-size-limit-filter
Open

Feature/issue99 request body size limit filter#114
MartinStenhagen wants to merge 11 commits intomainfrom
feature/issue99-request-body-size-limit-filter

Conversation

@MartinStenhagen
Copy link

@MartinStenhagen MartinStenhagen commented Feb 27, 2026

Resolves #99

Summary by CodeRabbit

  • New Features
    • Request body size limiting added: oversized submissions are rejected with a 413 Payload Too Large. Configurable max size (default 1 MB) and toggleable on/off; checks both declared and actual body size.
  • Tests
    • Added unit tests validating limit enforcement, header handling, UTF-8 byte counting, and edge cases.

@coderabbitai
Copy link

coderabbitai bot commented Feb 27, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 715913e and fd96cdb.

📒 Files selected for processing (2)
  • src/main/java/org/example/ConnectionHandler.java
  • src/main/java/org/example/filter/MaxRequestBodySizeFilter.java
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/java/org/example/filter/MaxRequestBodySizeFilter.java

📝 Walkthrough

Walkthrough

Adds a configurable maximum request body size feature: new MaxRequestBodySizeFilter enforces a configured byte limit (via Content-Length or actual UTF-8 body bytes) and returns HTTP 413 when exceeded. AppConfig gains MaxRequestBodyConfig; ConnectionHandler wires the filter into the pipeline and treats 413 as an immediate error response.

Changes

Cohort / File(s) Summary
Configuration & Constants
src/main/java/org/example/config/AppConfig.java, src/main/resources/application.yml, src/main/java/org/example/http/HttpResponseBuilder.java
Added MaxRequestBodyConfig to AppConfig (enabled, maxBytes) and defaults/apply logic; enabled config added to application.yml; introduced SC_PAYLOAD_TOO_LARGE = 413 and reason phrase.
Filter Implementation
src/main/java/org/example/filter/MaxRequestBodySizeFilter.java
New MaxRequestBodySizeFilter class implementing Filter; validates request size via Content-Length or UTF‑8 body byte count; rejects with 413 when over limit; includes helper methods and defensive checks.
Integration / Connection Handling
src/main/java/org/example/ConnectionHandler.java
Wired MaxRequestBodySizeFilter into buildFilters() when enabled; adjusted HttpRequest body arg from "" to null; updated error handling in runConnectionHandler() to short-circuit on 413 alongside 400/403.
Tests
src/test/java/org/example/filter/MaxRequestBodySizeTest.java
New unit tests covering allowed/rejected sizes, header case-insensitivity, invalid headers, UTF‑8 byte counting, and constructor validation.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant ConnectionHandler
    participant MaxRequestBodySizeFilter
    participant FilterChain
    participant HttpResponseBuilder

    Client->>ConnectionHandler: send HTTP request (headers + optional body)
    ConnectionHandler->>MaxRequestBodySizeFilter: invoke doFilter(request, response, chain)
    MaxRequestBodySizeFilter->>MaxRequestBodySizeFilter: check method mayHaveBody()
    alt Content-Length present
        MaxRequestBodySizeFilter->>MaxRequestBodySizeFilter: parse header as long
        alt header > maxBytes
            MaxRequestBodySizeFilter->>HttpResponseBuilder: set status 413 + body
            MaxRequestBodySizeFilter->>ConnectionHandler: short-circuit response
            ConnectionHandler->>Client: write/flush 413 response
        else header within limit
            MaxRequestBodySizeFilter->>FilterChain: chain.doFilter(request, response)
            FilterChain->>ConnectionHandler: continue processing
        end
    else no Content-Length
        MaxRequestBodySizeFilter->>MaxRequestBodySizeFilter: measure UTF-8 byte length of body
        alt body bytes > maxBytes
            MaxRequestBodySizeFilter->>HttpResponseBuilder: set status 413 + body
            MaxRequestBodySizeFilter->>ConnectionHandler: short-circuit response
            ConnectionHandler->>Client: write/flush 413 response
        else
            MaxRequestBodySizeFilter->>FilterChain: chain.doFilter(request, response)
            FilterChain->>ConnectionHandler: continue processing
        end
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • Feature/27 ipfilter #70: Adds a new Filter and AppConfig entry and modifies ConnectionHandler/filter integration similarly.

Suggested reviewers

  • gvaguirres
  • eeebbaandersson

Poem

🐇 I counted bytes from dusk till dawn,
Guarding gates where requests are drawn.
If bodies grow beyond the cap,
I thump my foot — a 413 slap! 🥕

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically describes the main change: adding a request body size limit filter feature.
Linked Issues check ✅ Passed The PR implements all requirements from issue #99: a configurable filter that enforces maximum request body size and returns HTTP 413 Payload Too Large when exceeded.
Out of Scope Changes check ✅ Passed All changes are directly related to implementing the request body size limit filter feature specified in issue #99; no unrelated modifications detected.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/issue99-request-body-size-limit-filter

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/main/java/org/example/ConnectionHandler.java`:
- Around line 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.

In `@src/main/java/org/example/filter/MaxRequestBodySizeFilter.java`:
- Line 95: In MaxRequestBodySizeFilter locate the response.setBody call that
builds the rejection message (the one using contentLength and maxBytes) and
insert a space before the "bytes" token so the message reads "...: X bytes (max
Y)" instead of "...: Xbytes"; update the string concatenation in that
response.setBody invocation to include the space between the size value and
"bytes".

ℹ️ Review info

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 80ffccf and 715913e.

📒 Files selected for processing (6)
  • src/main/java/org/example/ConnectionHandler.java
  • src/main/java/org/example/config/AppConfig.java
  • src/main/java/org/example/filter/MaxRequestBodySizeFilter.java
  • src/main/java/org/example/http/HttpResponseBuilder.java
  • src/main/resources/application.yml
  • src/test/java/org/example/filter/MaxRequestBodySizeTest.java

Comment on lines +44 to +47
AppConfig.MaxRequestBodyConfig maxBodyConfig = config.maxRequestBody();
if (Boolean.TRUE.equals(maxBodyConfig.enabled())) {
list.add(new MaxRequestBodySizeFilter(maxBodyConfig.maxBytes()));
}
Copy link

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.

Changed body from "" to null in ConnectionHandler to not give impressionthat body exists.

Fixed this line:
response.setBody("Payload too large: " + contentLength + " bytes (max " + maxBytes + ")");

Added
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Request Body Size Limit

1 participant