Skip to content

Make body length 64-bit; bound getContent() at the array ceiling - #3102

Open
predic8 wants to merge 2 commits into
masterfrom
fix/body-length-long-overflow
Open

Make body length 64-bit; bound getContent() at the array ceiling#3102
predic8 wants to merge 2 commits into
masterfrom
fix/body-length-long-overflow

Conversation

@predic8

@predic8 predic8 commented Jul 20, 2026

Copy link
Copy Markdown
Member

Problem

An HTTP message body's length was reported by an int getLength(): Body/ChunkedBody/Http2Body cast (int) streamedLength and AbstractBody summed chunk lengths into an int. For a body ≥ 2 GB this silently overflowed to a negative value (exactly 2^31 bytes → Integer.MIN_VALUE = -2147483648).

Since #3039 tightened Header.getContentLength() to reject non-numeric/negative Content-Length values, that overflowed length — once written via setContentLength() — throws MalformedHeaderException during response construction:

MalformedHeaderException: Invalid Content-Length header value: "-2147483648".
  at Header.getContentLength(Header.java:371)
  at Message.isBodyEmpty(Message.java:326)
  at ReturnInterceptor.getOrCreateResponse(ReturnInterceptor.java:96)

triggered by ReturnInterceptor.createResponseFromRequestsetContentLength(body.getLength()).

The wire/streaming path is already 64-bit clean (Header content-length and Body(in, long length) use long; writeStreamed streams >2 GB without buffering). Only the reported length API and the getContent() materialization broke. getContent() returns a single byte[], which a JVM cannot size beyond ~Integer.MAX_VALUE — a hard limit, so full-body materialization is inherently a small-message operation.

Changes

  • getLength() returns long across AbstractBody, Body, ChunkedBody, EmptyBody, the SSE StreamingBody, and HTTP/2 Http2Body (its streamedLength field widened too). Removes the (int) truncations, so >2 GB bodies stream through with a correct Content-Length.
  • getContent() is bounded: it throws the new BodyTooLargeException before allocating when the length exceeds MAX_ARRAY_LENGTH (Integer.MAX_VALUE - 8), instead of overflowing / NegativeArraySizeException / OOM. Same guard on ChunkedBody.getRawLength(). getContentAsStream() is unaffected (it wraps the chunk list, never one giant array).
  • BodyTooLargeException extends ReadingBodyException (unchecked), so existing catch (ReadingBodyException) handling keeps working while the subtype stays distinguishable.
  • Narrowing consumers fixed: Message.estimateHeapSize() clamps; two out.write(getContent(), 0, getLength()) sites use the array's own .length.

Accepted limitations

  • Transforming (not just forwarding) a >2 GB body remains impossible — inherent to the byte[] cap. Such interceptors now fail cleanly with BodyTooLargeException rather than corrupting the Content-Length.
  • Hard ceiling only (no configurable soft limit): a sub-2 GB body still buffers fully into heap when materialized, and an unknown-length/chunked body can OOM during read before the ceiling guard fires.

Tests

  • New BodyTest.getContentThrowsWhenBodyExceedsArrayLimit and BodyTest.largeBodyLengthRoundTripsThroughContentLength (the latter reproduces the overflow → MalformedHeaderException path at the length-API/header round-trip level).
  • Green: BodyTest (11), ChunkedBodyTest (35), HeaderTest (100), ReturnInterceptorTest (4), BodyDoesntThrowIOExceptionTest (1, confirms the new unchecked exception respects the no-checked-IOException body contract).

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes

    • Improved handling of very large request and response bodies.
    • Prevented oversized bodies from being loaded into memory as a single array.
    • Added clearer errors when body content exceeds the supported in-memory limit.
    • Preserved accurate body lengths beyond the previous integer range.
    • Improved large and chunked message processing without length overflow.
  • Tests

    • Added coverage for oversized bodies and large content-length values.
    • Updated length handling tests for large and streamed content.

Body length was reported by an int getLength(): Body/ChunkedBody/Http2Body
cast (int)streamedLength and AbstractBody summed chunk lengths as int. For a
body >= 2 GB this silently overflowed to a negative value (exactly 2^31 bytes
-> Integer.MIN_VALUE). Since #3039 tightened Header.getContentLength() to
reject negative/non-numeric values, that overflowed length written via
setContentLength() then threw MalformedHeaderException during response
construction (e.g. ReturnInterceptor.createResponseFromRequest).

The wire/streaming path is already 64-bit clean (Header content-length and
Body(in, long length) use long, writeStreamed streams >2 GB fine); only the
reported length API and getContent() materialization broke.

- getLength() returns long across AbstractBody, Body, ChunkedBody, EmptyBody,
  the SSE StreamingBody and HTTP/2 Http2Body (streamedLength field widened),
  removing the (int) truncations.
- getContent() throws the new BodyTooLargeException before allocating when the
  length exceeds MAX_ARRAY_LENGTH (Integer.MAX_VALUE - 8) instead of
  overflowing/OOMing; same guard on ChunkedBody.getRawLength(). A single byte[]
  cannot hold more than ~2 GB, so full-body materialization stays small-message
  only. getContentAsStream() is unaffected (wraps the chunk list).
- BodyTooLargeException extends ReadingBodyException so existing body-error
  handling keeps working while the subtype stays distinguishable.
- Narrowing consumers fixed: Message.estimateHeapSize() clamps; two
  out.write(getContent(), 0, getLength()) sites use the array's own length.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Jul 20, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 2edb45a4-00f2-40a2-ad62-3a80a1c78854

📥 Commits

Reviewing files that changed from the base of the PR and between cdb5189 and 1272ffb.

📒 Files selected for processing (11)
  • core/src/main/java/com/predic8/membrane/core/http/AbstractBody.java
  • core/src/main/java/com/predic8/membrane/core/http/Body.java
  • core/src/main/java/com/predic8/membrane/core/http/BodyTooLargeException.java
  • core/src/main/java/com/predic8/membrane/core/http/ChunkedBody.java
  • core/src/main/java/com/predic8/membrane/core/http/EmptyBody.java
  • core/src/main/java/com/predic8/membrane/core/http/Message.java
  • core/src/main/java/com/predic8/membrane/core/interceptor/sse/ServerSentEventsDemoStreamInterceptor.java
  • core/src/main/java/com/predic8/membrane/core/transport/http2/StreamInfo.java
  • core/src/test/java/com/predic8/membrane/core/http/BodyTest.java
  • core/src/test/java/com/predic8/membrane/core/interceptor/beautifier/BeautifierInterceptorTest.java
  • core/src/test/java/com/predic8/membrane/integration/withoutinternet/LimitedMemoryExchangeStoreIntegrationTest.java

📝 Walkthrough

Walkthrough

Body length APIs now preserve values above Integer.MAX_VALUE, while buffering rejects bodies exceeding the maximum array size. Body implementations, heap estimation, HTTP/2 streaming, and related unit and integration tests were updated accordingly.

Changes

Body length safety

Layer / File(s) Summary
Buffering limit and length contract
core/src/main/java/com/predic8/membrane/core/http/AbstractBody.java, core/src/main/java/com/predic8/membrane/core/http/BodyTooLargeException.java
getLength() returns long, and getContent() rejects bodies exceeding MAX_ARRAY_LENGTH with BodyTooLargeException.
Body implementations and length propagation
core/src/main/java/com/predic8/membrane/core/http/*Body.java, core/src/main/java/com/predic8/membrane/core/http/Message.java, core/src/main/java/com/predic8/membrane/core/interceptor/sse/..., core/src/main/java/com/predic8/membrane/core/transport/http2/StreamInfo.java
Streamed lengths use long, already-read writes use actual array lengths, chunked lengths enforce the array limit, and heap-size estimates are capped.
Large-body regression coverage
core/src/test/java/com/predic8/membrane/core/http/BodyTest.java, core/src/test/java/com/predic8/membrane/core/interceptor/beautifier/BeautifierInterceptorTest.java, core/src/test/java/com/predic8/membrane/integration/withoutinternet/LimitedMemoryExchangeStoreIntegrationTest.java
Tests cover oversized buffering, large content lengths, long body-length assertions, and updated integration proxy wiring.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related PRs

Suggested reviewers: rrayst

Poem

I’m a rabbit with bytes in my burrow,
Long lengths now hop without sorrow.
Huge bodies meet a neat array gate,
Chunked streams keep their proper weight.
Tests guard each leap and flow—
Safe buffering makes carrots grow!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 4.35% 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 accurately captures the main change: widening body length to 64-bit and enforcing a ceiling on getContent() allocation.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/body-length-long-overflow

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.

@membrane-ci-server

Copy link
Copy Markdown

This pull request needs "/ok-to-test" from an authorized committer.

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.

1 participant