Repository navigation
Reject a Content-Length that contradicts the body - #2407
Merged
Merged
Conversation
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
approved these changes
Nov 25, 2026
30 of 31 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Content-Lengthheader that the caller sets goes on the wire as it is.NettyRequestFactoryonly 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.main8b81226fawith a raw socket server andContent-Length: 49:byte[],String,InputStreamorFile, with and without zero-copy) sends 35 bytes after the declared body. The server parses them as the next request on the connection, hereGET /smuggled HTTP/1.1, and the request itself gets a 200.BodyGeneratorhands out at the header, and fails it if it ends before.HttpClientrefuses aContent-Lengthheader by default ("restricted header name").Change
For every request but a
CONNECT, a caller'sContent-Lengthheader:Otherwise the request fails with an
IllegalArgumentException, for exampleContent-Length header 49 does not match the body's length 84, orContent-Length header [+17] is not a length. The header is never overwritten, so #1440's precedence stays.Two places check it:
NettyRequestSender.sendRequest, before a pooled connection is taken, replacing #2401'scheckStreamBodyLengthbyte[], a list ofbyte[],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 builtBodyGenerators, whose length is the created body's. ABodyGenerator's body is closed when the check fails.Through an HTTP proxy to an
httpsURL,newNettyRequestruns 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:
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-Lengthabove 0 on a request without a body, and for an invalid header on a body that isn't a stream.One
Content-LengthparserThe second commit moves the parsing of a
Content-Lengthheader into a new public method,HttpUtils.parseContentLength(HttpHeaders).16, 16. RFC 9110 section 8.6 lets a recipient accept and normalise such a list, but a sender must not send it.NettyRequestFactory, for a caller's header, from Stop stream bodies at their declared length #2401;NettyBodyBody, for the header on the wire, from Fail InputStreamBodyGenerator's body on read errors and stop it at its length #2402.Content-Length header [x] is not a length;Content-Length header [x] is longer than AHC supports, pastLong.MAX_VALUE.NettyBodyBodysaid "not a length" before;Tests
HttpUtilsTestparseContentLength: no header, lengths with and without trailing whitespace up toLong.MAX_VALUE, nine values that are not lengths, two fields, and one pastLong.MAX_VALUE, each with its message.CallerContentLengthTest(new)byte[], a list ofbyte[],String(non-ASCII),ByteBuffer,ByteBuf, form,File, aFileBodyGeneratorregion 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
- with a header 5 bytes longer or shorter, the request fails with the message above. It fails before it takes the pooled connection: with
- an invalid header (
Multipart and aGET /next HTTP/1.1;maxConnections1, the next request still gets it, and the server sees only the two GETs;17, 17,+17,-0, Arabic-Indic digits) fails as not a length.BodyGenerator: a wrong header fails, and the request is not sent. A multipart body with its boundary inContent-Typeand its length in the header goes out whole. The generator's body is closed.On a pooled connection, with
maxConnections1: aBodyGeneratorbody 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
httpsURL, withmaxConnections1: 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.ByteBufbodies 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
main76f24a4b0:mainnewNettyRequestBodyGeneratortests fail.sendRequestBodyGeneratortest fails: the next request getsTooManyConnectionsException: Too many connections: 1.Relation to #2401, #2402 and #2403
BodyGeneratorbody or a multipart body of unknown length, and one that ends before the header fails. This PR rejects a known length that contradicts the header, and the request is not sent.BodyGeneratorbody is checked once it is built, and on a pooled connection that is after the connection was taken.bodyGeneratorFailingTheCheckOnAPooledConnectionLeavesTheLimitFree: withmaxConnections1, the next request opens a new connection and succeeds. Before Close a pooled connection when building the request fails #2403, it gotTooManyConnectionsException.mainnow, and the branch is rebased onto it without conflicts.Not covered
BodyGeneratorwithout a length, or a multipart body with anInputStreamPartwithout one. Its length is enforced while it is written: by Stop stream bodies at their declared length #2401 for stream bodies, and by Fail InputStreamBodyGenerator's body on read errors and stop it at its length #2402 for the others.Transfer-Encodingheader that the caller sets.AI disclosure
Claude Code on behalf of Matthias Kurz. The first two commits include
Co-Authored-ByperAGENTS.md.Test plan
The third commit (
2da74380a):CallerContentLengthTest,StreamBodyDeclaredLengthTestandBasicHttpProxyToHttpsTeston JDK 11: 60 tests, 0 failures.multipartBodyFailsTheLateCheckThroughAProxyTunnelfails with aTimeoutException, the request still waiting after 10 seconds.The final tree (
846bd2b70onmain322666a10, byte-identical to a local build ofmain76f24a4b0merged with the earlier branch, #2404 and #2405):./mvnw -B -ntp -Dgpg.skip=true clean installon JDK 11: 2,393 tests, 0 failures, 22 skipped; Revapi passed. Docker was not running, so the 22 skipped include the Testcontainers proxy tests.main672321768(7e88a169f):clean verifyon 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.confhad nosearch .then, soAddressResolverGroupTestpassed without Give the DNS test resolver no search domains #2405.Earlier local revisions (not pushed), before the rebase. Both commits (
53d68f01eon #2402;53d68f01ediffers from the verified0238963d0only in the javadoc ofparseContentLength):./mvnw -B -ntp -Dgpg.skip=true clean verifyon JDK 11: 2,393 tests, 0 failures, 22 skipped; Revapi passed, with the new publicHttpUtils.parseContentLength. Docker was not running, so the 22 skipped include the Testcontainers proxy tests.HttpUtilsTest,InputStreamBodyGeneratorTestandBodyChunkedInputTest: 361 tests, 0 failures, 2 skipped (both inAuthTimeoutTest).StreamBodyDeclaredLengthTestfrom Stop stream bodies at their declared length #2401 fail, as they do onmain.Earlier local revisions, the first commit alone (
119a6fcadonmain76f24a4b0):./mvnw -B -ntp -Dgpg.skip=true clean verifyon 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.unknownHostWithDnsResolverGroupFailsfails on a machine withsearch .in/etc/resolv.conf, as it does onmain.CallerContentLengthTest,StreamBodyDeclaredLengthTest,AuthTimeoutTest,BasicHttpTest,BodyDeferringAsyncHandlerTest,RedirectBodyTest,PostRedirectGetTest,PostWithQueryStringTest,ParamEncodingTest,RedirectConnectionUsageTest,Http2ConformanceRegressionTest,ConnectionPoolTest,MultipartBodyTest,MultipartUploadTest,PutFileTest,ZeroCopyFileTest,Expect100ContinueTest,Http2StreamingBodyFlowControlTest,BasicHttp2TestandRetryRequestTest: 304 tests, 0 failures, 2 skipped (both inAuthTimeoutTest), on JDK 11.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.StreamBodyDeclaredLengthTestfrom Stop stream bodies at their declared length #2401 fail, as they do onmain.CallerContentLengthTest(35 tests) 5 runs with the default transport and 5 with io_uring, 0 failures.43771d0fc) and Keep file bodies at the length they announce #2404 (58f462845):InputStreamBodyGeneratorTest,BodyChunkedInputTestandFilePartChangeTest: 344 tests, 0 failures, 2 skipped (the same two);clean verifywith-Dmaven.test.failure.ignore=true, without Give the DNS test resolver no search domains #2405: 2,387 tests, 1 failure, theAddressResolverGroupTestone above. Not a green build.