Skip to content

Fix silent truncation at LimitReadBuffer limits and the multipart form budget - #120036

Merged
CheSema merged 17 commits into
masterfrom
bound-http-body-decompression
Sep 24, 2026
Merged

CheSema merged 17 commits into
masterfrom
bound-http-body-decompression

Conversation

@CheSema

@CheSema CheSema commented Sep 14, 2026 •

Copy link
Copy Markdown
Member

Limits that apply while a request is parsed - that is, before the query enters the process list, and
therefore before max_memory_usage applies.

LimitReadBuffer::expect_eof now rejects data past the limit. The throw was unreachable: the window
is capped at read_no_more - bytes, so bytes could never exceed the limit, and callers silently got
EOF at the limit instead - losing the rest of the stream. HTTPServerRequest and the PROXY header opt
out, because their nested stream continues with the next keep-alive request or the client handshake, so
leftover bytes there are not overflow.

expect_eof is set only where the nested stream ends at the limit. LimitedReadPacket limited the
connection rather than the packet, so the flag asked whether the client had hung up; it now wraps
MySQLPacketPayloadReadBuffer. HTTPServerRequest and the PROXY header keep it off: their socket
carries the next keep-alive request or the client handshake. The separate defect of
handshake_timeout_milliseconds not bounding a blocking read is fixed in
#121547.

http_max_multipart_form_data_size spans the form's external-table parts. It was applied per part on
a fresh LimitReadBuffer, so 1000 file parts could carry 1000 times the limit, each one materialized
into an in-memory temporary table. Fields without a filename are not counted; they keep their own
bounds, http_max_field_value_size and http_max_fields. The budget is re-checked once a part is
parsed, since the expect_eof check runs in nextImpl and a format that stops exactly at the budget
never triggers it.

An earlier revision of this pull request also capped the output of a single DEFLATE block, on the
grounds that the libdeflate decoder had to buffer one whole block. That is dropped. The same exposure
was fixed upstream in the meantime by bumping contrib/libdeflate so the streaming decoder re-takes
its resume checkpoint at every symbol boundary: the decoder no longer buffers a block, and a cap would
have rejected legitimate bodies, since a single block can span a whole stream - the shape zlib-ng emits
at level 1.

Related: #114045

Tests: 05213_http_multipart_form_data_total_size, and gtest_limit_read_buffer covering both
expect_eof settings, the nested-buffer position contracts, and the best-effort gap above.

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fixed http_max_multipart_form_data_size silently truncating oversized multipart data instead of
failing the query, and made it span a form's external-table parts instead of resetting per part.

🤖 Generated with Claude Code


Workflow [PR]
Sync PR [sync-upstream/pr/120036]

Version info

  • Merged into: 26.10.1.628-master (included in 26.10 and later)
  • Backported to: 26.9.2.36, 26.8.11.49, 26.7.14.49, 26.3.33.152

libdeflate's streaming decoder suspends only at block boundaries, so a block
larger than the output buffer has to be buffered whole before any of it is
exposed. The buffer grew without a ceiling, so a crafted single-block gzip or
zlib stream over the HTTP interface allocated one buffer of its own chosen size.
HTTP bodies are read before `ProcessList::insert` installs `max_memory_usage`,
so only the server-wide limit stood in the way, and reaching it fails other
queries.

Real encoders keep blocks three orders of magnitude below the new 64 MiB
ceiling, so only a crafted stream reaches it.
The throw was guarded by `bytes > read_no_more`, but the working buffer is
capped at `read_no_more - bytes`, and `ReadBuffer::next` only adds the consumed
part of that buffer to `bytes`. So `bytes` could never exceed the limit and the
branch was dead: every caller got EOF at the limit and silently lost the rest of
the stream. That affected `http_max_multipart_form_data_size` and the "too long
MySQL packet" guards.

Check that the nested buffer is at EOF once the limit is reached instead.
`HTTPServerRequest` no longer asks for the check: `Content-Length` already
defines where the body ends, and with keep-alive the socket holds the bytes of
the next request.
The limit was applied to each part on its own, on a fresh LimitReadBuffer per
part, so a form of 1000 parts could carry 1000 times the limit. With external
tables every part is materialized into an in-memory temporary table, and form
data is parsed before `max_memory_usage` applies.

Carry the remaining budget across parts.
@clickhouse-gh

clickhouse-gh Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [afcc81c]

Summary: ✅


AI Review

Summary

This PR fixes pre-query read-limit handling in three places: LimitReadBuffer::expect_eof now reports overflow instead of silently truncating when the caller actually exhausts the bounded stream, MySQL packet limiting is applied to packet payloads instead of the whole connection, and http_max_multipart_form_data_size is tracked across a form's external-table parts instead of resetting per part. After reviewing the current PR diff, the updated head code, the existing review threads, and the current all-green CI, I did not find a remaining correctness, compatibility, or coverage issue that warrants a new inline comment.

Final Verdict

✅ No new findings.

LLVM Coverage Report

Measured on commit afcc81c.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.40% 79.40% +0.00%

Changed lines: Changed C/C++ lines covered: 34/36 (94.44%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 14, 2026
`receiveProxyHeader` wraps the connection itself, and its scan loop calls `eof`
once the 107 byte limit is reached. With `expect_eof` that now probes the socket
for the client's next bytes, so a malformed maximal header would block in `recv`
instead of being reported as incomplete. The flag was dead code before, so
dropping it keeps the behaviour of that parser unchanged.

Document that `expect_eof` suits a bounded nested buffer only.
@clickhouse-gh clickhouse-gh Bot added the comp-protocols Server wire protocols + request/response handling (native TCP, HTTP, MySQL/PostgreSQL wire protoc... label Sep 14, 2026
The ceiling lives in the libdeflate decoder. Fast test configures
`ENABLE_LIBRARIES=0`, so `ENABLE_LIBDEFLATE` is off and gzip goes through zlib,
which suspends mid-block and never buffers a whole one, so the crafted stream is
decoded instead of rejected.
The `expect_eof = false` paths carry the `Content-Length` shape that
`HTTPServerRequest` relies on, so pin them: an exact fit, a short stream, an
empty stream and a zero limit, plus the two position contracts - the nested
buffer stays readable past the limit, and a partial read leaves it at the
consumed offset. A short stream under `expect_eof` is covered too, since
reaching EOF before the limit must not throw.
Comment thread src/Core/ExternalTable.cpp Resolved
Waiting on a socket belongs to the socket layer - ReadBufferFromPocoSocket
raises SOCKET_TIMEOUT and TimeoutSetter sets the deadline - so the `eof` check
cannot hang, and that was the wrong reason to give.

The real one: except for the `UNKNOWN` health check, the client sends its
handshake right after the header, so the connection does not end at the limit,
which is exactly what `expect_eof` claims. An over-long header is rejected
regardless, because it cannot carry its `\r\n` within the 107 bytes.
`expect_eof` on the limiter only fires when the format asks for a byte past the
budget, so a format that stops exactly at the budget leaves the overflow
undetected - the check lives in `nextImpl`, which runs on demand only.
Re-check the part stream once the part is parsed, which happens whatever the
format did.

Both checks stay, because they catch different truncations. Mid-record the
limiter throws while parsing, and that is what yields the size error instead of
the parse failure a truncated row would raise; at a record boundary the format
sees a clean EOF and only the check here can see the overflow.
@clickhouse-gh

clickhouse-gh Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit afcc81c05b21a7ba0ed0f7dd48ba81821450a07b was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

"the whole form" overclaimed: the budget spans the form's external-table parts,
the ones that reach `ExternalTablesHandler::handlePart`. A field without a
filename never gets there, and is bounded by `http_max_field_value_size` and
`http_max_fields` instead.
…ompression

# Conflicts:
#	src/Core/ExternalTable.cpp
@CheSema
CheSema marked this pull request as ready for review September 15, 2026 15:28
Comment thread src/Server/HTTP/HTTPServerRequest.cpp Resolved
The ceiling sat in `LibdeflateInflatingReadBuffer`, which serves every
gzip/zlib read, so it restricted existing `.gz` data read through `file`,
`url` and `s3` - and only in builds with libdeflate, since the zlib decoder
exposes output from inside a block and never buffers a whole one.

It is now a parameter of the decompression wrapper, set by the HTTP handler
and the gRPC server, where the body is read before the query owns the
allocation. Everywhere else the buffer grows as it did before, bounded by the
memory tracker alone.
…ompression

Conflict in `src/IO/LibdeflateInflatingReadBuffer.cpp`, resolved in favour of
master, which removes the reason this branch had a ceiling at all.

`edc82b0871dc` bumped `contrib/libdeflate` so the streaming decompressor
re-takes its resume checkpoint at every symbol boundary. The decoder no longer
buffers a whole DEFLATE block, so the grow path can only be reached by a single
match (258 bytes) or one stored block (64 KiB), neither of which an attacker
picks. There is nothing left for a ceiling to bound.

That also refutes the premise the ceiling was built on. A single block CAN span
a whole stream: it is what zlib-ng emits at level 1, the default of the official
.NET SDK (issue #114045). A 64 MiB ceiling would have rejected such bodies.

Dropped with it: the `max_block_output` parameter of
`LibdeflateInflatingReadBuffer`, the `max_deflate_block_output` parameter of
`wrapReadBufferWithCompressionMethod` and its callers in `HTTPHandler` and
`GRPCServer`, and the test `05212_http_gzip_single_block_limit`, whose subject
master now covers in `04836_http_gzip_single_deflate_block`.
@CheSema CheSema changed the title Bound HTTP request body decompression and multipart form size Fix silent truncation at LimitReadBuffer limits and the multipart form budget Sep 21, 2026
`LimitedReadPacket` wrapped the connection in the limiter and built the packet
framing inside it. So `expect_eof` asked whether the client had hung up, rather
than whether this packet carries more than the maximum, and the 10000-byte
budget counted packet headers too. A client that declared a longer payload and
then stalled was held for `receive_timeout` instead of being rejected.

Wrap `MySQLPacketPayloadReadBuffer` instead, which ends where the packet ends.
`readPayloadWithUnpacked` already received an unpacked payload and is unchanged.
Comment thread src/Core/ExternalTable.cpp Resolved
`handlePart` probed the nested `stream`, but `LimitReadBuffer` syncs that cursor
only in `nextImpl` or its destructor. A format that consumed exactly the remaining
budget and stopped left `stream` pointing at the start of those bytes, so the probe
counted them as pending and threw `LIMIT_EXCEEDED` on a part that fit. The same
probe reported the budget as exceeded when a format merely left trailing bytes
unread well under it.

Ask the limiter instead: `eof()` credits the consumed bytes, syncs the cursor and
runs `expect_eof` itself, with the hint that names the setting. `05213` now covers
a part that ends exactly at the budget.
@Michicosun Michicosun self-assigned this Sep 23, 2026
Comment thread src/Core/ExternalTable.cpp Resolved
Comment thread src/Core/MySQL/IMySQLReadPacket.cpp Resolved
`handlePart` asked the limiter for EOF, which returns at once while the limiter
still holds buffered bytes, so `count()` credited only the prefix the format
consumed and `HTMLForm` skipped the rest outside the limiter. A form of parts
with small parseable prefixes and large tails exceeded the budget it is supposed
to span. Drain the limiter instead: the tail counts, and a part running past the
budget trips `expect_eof` on the way.

`gtest_mysql_limited_read_packet` covers the packet-versus-connection boundary
that the re-nesting changed. A payload exactly at the limit followed by another
packet passes now and fails against the old nesting, where the 4-byte header
pushed the connection past the limit and the next packet was read as overflow.
The oversized cases pass either way, so the limit cannot go missing unnoticed.
@CheSema
CheSema added this pull request to the merge queue Sep 24, 2026
Merged via the queue into master with commit a6bd33c Sep 24, 2026
176 checks passed
@CheSema
CheSema deleted the bound-http-body-decompression branch September 24, 2026 17:53
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 24, 2026
@CheSema CheSema added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Sep 25, 2026
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 25, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 25, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 25, 2026
Backport #120036 to 26.9: Fix silent truncation at `LimitReadBuffer` limits and the multipart form budget
clickhouse-gh Bot added a commit that referenced this pull request Sep 25, 2026
Backport #120036 to 26.8: Fix silent truncation at `LimitReadBuffer` limits and the multipart form budget
PedroTadim added a commit that referenced this pull request Sep 25, 2026
Backport #120036 to 26.3: Fix silent truncation at `LimitReadBuffer` limits and the multipart form budget
clickhouse-gh Bot pushed a commit that referenced this pull request Sep 25, 2026
…limits and the multipart form budget
clickhouse-gh Bot added a commit that referenced this pull request Sep 25, 2026
Backport #120036 to 26.7: Fix silent truncation at `LimitReadBuffer` limits and the multipart form budget
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Oct 2, 2026
…adBuffer` limits and the multipart form budget
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Oct 2, 2026
…adBuffer` limits and the multipart form budget
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Oct 2, 2026
…adBuffer` limits and the multipart form budget
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-protocols Server wire protocols + request/response handling (native TCP, HTTP, MySQL/PostgreSQL wire protoc... pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants