Skip to content

Reject a Content-Length that contradicts the body - #2407

Merged
hyperxpro merged 3 commits into
AsyncHttpClient:mainfrom
mkurz:fix/caller-content-length
Nov 25, 2026
Merged

hyperxpro merged 3 commits into
AsyncHttpClient:mainfrom
mkurz:fix/caller-content-length

Conversation

@mkurz

@mkurz mkurz commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • A Content-Length header that the caller sets goes on the wire as it is. NettyRequestFactory only sets its own when there is none (if (!headers.contains(CONTENT_LENGTH))), as Content-Length request header should be honored #1440 asked. The body is then written in full, whatever the header says.
  • What happens with a wrong header, shown on main 8b81226fa with a raw socket server and Content-Length: 49:
    • A body of 84 bytes (byte[], String, InputStream or File, with and without zero-copy) sends 35 bytes after the declared body. The server parses them as the next request on the connection, here GET /smuggled HTTP/1.1, and the request itself gets a 200.
    • A body of 20 bytes leaves the server waiting for the rest until its timeout.
  • What is checked already:
  • What this adds: a request whose body has a length AHC knows up front is rejected, and not sent.
  • For comparison, Java's HttpClient refuses a Content-Length header by default ("restricted header name").

Change

For every request but a CONNECT, a caller's Content-Length header:

Otherwise the request fails with an IllegalArgumentException, for example Content-Length header 49 does not match the body's length 84, or Content-Length header [+17] is not a length. The header is never overwritten, so #1440's precedence stays.

Two places check it:

Where Bodies
NettyRequestSender.sendRequest, before a pooled connection is taken, replacing #2401's checkStreamBodyLength byte[], a list of byte[], String (its length in bytes, in the request's charset), ByteBuffer, ByteBuf, form parameters, File, FileBodyGenerator, and no body at all (length 0). Stream bodies as in #2401.
NettyRequestFactory.newNettyRequest, once the body is built Everything, against the built body's length. This is the only check for multipart bodies, whose length depends on a boundary that AHC may only pick when it builds the body, and for other BodyGenerators, whose length is the created body's. A BodyGenerator's body is closed when the check fails.

Through an HTTP proxy to an https URL, newNettyRequest runs once the tunnel's TLS handshake is done, inside a listener of the handshake future. Netty logs and discards what that listener throws, so a failed check left the request waiting for its timeout while it held the tunnel's connection. The third commit aborts the request there, as the listener already did for a failed HTTP/2 upgrade, which fails the future and closes the connection.

Unchanged:

  • A file that isn't there still fails with its own error ("is not a file or doesn't exist"), not with a length mismatch.
  • Redirects: a redirect that drops the body, or rebuilds one of known length, already removes the caller's header (Redirect30xInterceptor). A test covers a 302 after a POST.

This is a behaviour change. A request with a wrong header used to go out and might even get a 200. It now fails, and is not sent. The same goes for a Content-Length above 0 on a request without a body, and for an invalid header on a body that isn't a stream.

One Content-Length parser

The second commit moves the parsing of a Content-Length header into a new public method, HttpUtils.parseContentLength(HttpHeaders).

Tests

Test What it checks
HttpUtilsTest parseContentLength: no header, lengths with and without trailing whitespace up to Long.MAX_VALUE, nine values that are not lengths, two fields, and one past Long.MAX_VALUE, each with its message.
CallerContentLengthTest (new) Against a raw socket server, for byte[], a list of byte[], String (non-ASCII), ByteBuffer, ByteBuf, form, File, a FileBodyGenerator region and no body:
  • with its length in the header, the server gets exactly the body, and the next request on the connection is read as GET /next HTTP/1.1;
  • with a header 5 bytes longer or shorter, the request fails with the message above. It fails before it takes the pooled connection: with maxConnections 1, the next request still gets it, and the server sees only the two GETs;
  • an invalid header (17, 17, +17, -0, Arabic-Indic digits) fails as not a length.
Multipart and a BodyGenerator: a wrong header fails, and the request is not sent. A multipart body with its boundary in Content-Type and its length in the header goes out whole. The generator's body is closed.
On a pooled connection, with maxConnections 1: a BodyGenerator body with a wrong header fails, after it took the connection, and is closed. The next request opens a new connection and succeeds.
Through an HTTP proxy to an https URL, with maxConnections 1: a multipart body with a wrong header fails with the message above once the tunnel is up, instead of waiting for its timeout. The next request through the proxy opens a new connection and succeeds.
ByteBuf bodies stay the caller's: each test releases its buffer afterwards and checks that this was the last reference.
A 302 after a POST with a header: the GET that follows has no body.

Each part reverted, on main 76f24a4b0:

Reverted Result
All of it, i.e. main All 23 rejection tests fail. The request goes out: with a header too short, it gets its 200, and with one too long, the server waits for the rest until the client gives up.
The check in newNettyRequest Only the multipart and BodyGenerator tests fail.
The check in sendRequest The 21 early tests fail. The request is still refused, but only after it took the pooled connection, which #2403 then closes, so the next request has to open a new connection.
#2403's close of the polled connection The pooled BodyGenerator test fails: the next request gets TooManyConnectionsException: Too many connections: 1.

Relation to #2401, #2402 and #2403

Not covered

AI disclosure

Claude Code on behalf of Matthias Kurz. The first two commits include Co-Authored-By per AGENTS.md.

Test plan

The third commit (2da74380a):

  • CallerContentLengthTest, StreamBodyDeclaredLengthTest and BasicHttpProxyToHttpsTest on JDK 11: 60 tests, 0 failures.
  • Reverted: multipartBodyFailsTheLateCheckThroughAProxyTunnel fails with a TimeoutException, the request still waiting after 10 seconds.

The final tree (846bd2b70 on main 322666a10, byte-identical to a local build of main 76f24a4b0 merged with the earlier branch, #2404 and #2405):

  • ./mvnw -B -ntp -Dgpg.skip=true clean install on JDK 11: 2,393 tests, 0 failures, 22 skipped; Revapi passed. Docker was not running, so the 22 skipped include the Testcontainers proxy tests.
  • Before Give the DNS test resolver no search domains #2405 was merged, the same two commits on main 672321768 (7e88a169f): clean verify on JDK 11, 2,393 tests, 0 failures, 22 skipped; Revapi passed ("API checks completed without failures", against 3.0.14). This machine's /etc/resolv.conf had no search . then, so AddressResolverGroupTest passed without Give the DNS test resolver no search domains #2405.

Earlier local revisions (not pushed), before the rebase. Both commits (53d68f01e on #2402; 53d68f01e differs from the verified 0238963d0 only in the javadoc of parseContentLength):

  • Merged with Give the DNS test resolver no search domains #2405 and Keep file bodies at the length they announce #2404: ./mvnw -B -ntp -Dgpg.skip=true clean verify on JDK 11: 2,393 tests, 0 failures, 22 skipped; Revapi passed, with the new public HttpUtils.parseContentLength. Docker was not running, so the 22 skipped include the Testcontainers proxy tests.
  • Focused tests: the classes below plus HttpUtilsTest, InputStreamBodyGeneratorTest and BodyChunkedInputTest: 361 tests, 0 failures, 2 skipped (both in AuthTimeoutTest).

Earlier local revisions, the first commit alone (119a6fcad on main 76f24a4b0):

  • ./mvnw -B -ntp -Dgpg.skip=true clean verify on JDK 11, with the DNS test fix (Give the DNS test resolver no search domains #2405) merged in: 2,353 tests, 0 failures, 22 skipped; Revapi passed. Docker was not running, so the 22 skipped include the Testcontainers proxy tests. Without that fix, AddressResolverGroupTest.unknownHostWithDnsResolverGroupFails fails on a machine with search . in /etc/resolv.conf, as it does on main.
  • Each part reverted: as described above.
  • Focused tests: CallerContentLengthTest, StreamBodyDeclaredLengthTest, AuthTimeoutTest, BasicHttpTest, BodyDeferringAsyncHandlerTest, RedirectBodyTest, PostRedirectGetTest, PostWithQueryStringTest, ParamEncodingTest, RedirectConnectionUsageTest, Http2ConformanceRegressionTest, ConnectionPoolTest, MultipartBodyTest, MultipartUploadTest, PutFileTest, ZeroCopyFileTest, Expect100ContinueTest, Http2StreamingBodyFlowControlTest, BasicHttp2Test and RetryRequestTest: 304 tests, 0 failures, 2 skipped (both in AuthTimeoutTest), on JDK 11.
    • The version before the pooled test, 96496a76f: 303 tests, 0 failures, 2 skipped (the same two), on JDK 11, 17, 21 and 25, and on JDK 11 with NIO selected explicitly.
    • With io_uring, only the four short-stream tests of StreamBodyDeclaredLengthTest from Stop stream bodies at their declared length #2401 fail, as they do on main.
  • Repeats: CallerContentLengthTest (35 tests) 5 runs with the default transport and 5 with io_uring, 0 failures.
  • Merged with Fail InputStreamBodyGenerator's body on read errors and stop it at its length #2402 (43771d0fc) and Keep file bodies at the length they announce #2404 (58f462845):
    • those focused tests plus InputStreamBodyGeneratorTest, BodyChunkedInputTest and FilePartChangeTest: 344 tests, 0 failures, 2 skipped (the same two);
    • clean verify with -Dmaven.test.failure.ignore=true, without Give the DNS test resolver no search domains #2405: 2,387 tests, 1 failure, the AddressResolverGroupTest one above. Not a green build.

mkurz and others added 3 commits November 25, 2026 19:22
A Content-Length header that the caller sets goes on the wire as it
is, and the body is then written in full, whatever the header says. A
header shorter than the body leaves the rest of the body to be read as
the start of the next request on the connection, and a longer one
makes the server wait for bytes that never come. AsyncHttpClient#2401 checks the
header for stream bodies only.

The header must now be a length for every body, and match the body's
where AHC knows that:

- byte[], String, ByteBuffer, ByteBuf, form, File and
  FileBodyGenerator bodies, and no body at all, are checked before a
  pooled connection is taken, as stream bodies already are;
- multipart and other BodyGenerator bodies only have their length once
  they are built, so they are checked then, and a BodyGenerator's body
  is closed.

A body of unknown length is sent with the header as before. A redirect
that drops or rebuilds the body already drops the header.

Claude Code on behalf of Matthias Kurz

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
NettyRequestFactory parsed a caller's Content-Length header, and
NettyBodyBody parsed the Content-Length on the wire again, each with
its own copy of the rules and messages: a length past Long.MAX_VALUE
was "longer than AHC supports" in one and "not a length" in the
other, and a stream body's error added "for an InputStream body".

HttpUtils.parseContentLength now does it for both, with one set of
messages. The request factory rejects a caller's header that is not a
length before any body is written, so NettyBodyBody only reads valid
ones.

Claude Code on behalf of Matthias Kurz

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@hyperxpro
hyperxpro merged commit 2229e96 into AsyncHttpClient:main Nov 25, 2026
13 checks passed
@mkurz
mkurz deleted the fix/caller-content-length branch November 25, 2026 20:41
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.

2 participants