Repository navigation
Fix silent truncation at LimitReadBuffer limits and the multipart form budget - #120036
Conversation
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.
|
Workflow [PR], commit [afcc81c] Summary: ✅
AI ReviewSummaryThis PR fixes pre-query read-limit handling in three places: Final Verdict✅ No new findings. LLVM Coverage ReportMeasured on commit afcc81c.
Changed lines: Changed C/C++ lines covered: 34/36 (94.44%) · Uncovered code |
`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.
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.
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.
Build profile diff (arm_release)Commit 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
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`.
LimitReadBuffer limits and the multipart form budget
`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.
`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.
`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.
Backport #120036 to 26.9: Fix silent truncation at `LimitReadBuffer` limits and the multipart form budget
Backport #120036 to 26.8: Fix silent truncation at `LimitReadBuffer` limits and the multipart form budget
Backport #120036 to 26.3: Fix silent truncation at `LimitReadBuffer` limits and the multipart form budget
…limits and the multipart form budget
Backport #120036 to 26.7: Fix silent truncation at `LimitReadBuffer` limits and the multipart form budget
…adBuffer` limits and the multipart form budget
…adBuffer` limits and the multipart form budget
…adBuffer` limits and the multipart form budget
Limits that apply while a request is parsed - that is, before the query enters the process list, and
therefore before
max_memory_usageapplies.LimitReadBuffer::expect_eofnow rejects data past the limit. The throw was unreachable: the windowis capped at
read_no_more - bytes, sobytescould never exceed the limit, and callers silently gotEOF at the limit instead - losing the rest of the stream.
HTTPServerRequestand the PROXY header optout, because their nested stream continues with the next keep-alive request or the client handshake, so
leftover bytes there are not overflow.
expect_eofis set only where the nested stream ends at the limit.LimitedReadPacketlimited theconnection rather than the packet, so the flag asked whether the client had hung up; it now wraps
MySQLPacketPayloadReadBuffer.HTTPServerRequestand the PROXY header keep it off: their socketcarries the next keep-alive request or the client handshake. The separate defect of
handshake_timeout_millisecondsnot bounding a blocking read is fixed in#121547.
http_max_multipart_form_data_sizespans the form's external-table parts. It was applied per part ona fresh
LimitReadBuffer, so 1000 file parts could carry 1000 times the limit, each one materializedinto an in-memory temporary table. Fields without a
filenameare not counted; they keep their ownbounds,
http_max_field_value_sizeandhttp_max_fields. The budget is re-checked once a part isparsed, since the
expect_eofcheck runs innextImpland a format that stops exactly at the budgetnever 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/libdeflateso the streaming decoder re-takesits 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, andgtest_limit_read_buffercovering bothexpect_eofsettings, the nested-buffer position contracts, and the best-effort gap above.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
http_max_multipart_form_data_sizesilently truncating oversized multipart data instead offailing 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
26.10.1.628-master(included in26.10and later)26.9.2.36,26.8.11.49,26.7.14.49,26.3.33.152