Repository navigation
Fix buffer overflows on data from external servers - #115706
Conversation
|
Workflow [PR], commit [192b935] Summary: ✅
AI ReviewSummaryThis PR substantially hardens Azure/S3 object reads, copies, and backup paths against malformed external responses and mid-read object replacement, and the latest S3 Findings
Final VerdictChanges requested: the new generation-pinning contract is still incomplete for archive-backed LLVM Coverage ReportMeasured on commit 192b935.
Changed lines: Changed C/C++ lines covered: 3536/3856 (91.70%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes54 object files changed (+415.60 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units366 translation units recompiled, 2434 s compile time in total, 366 of them have a recent master baseline. Median compile-time ratio to the baselines is ×0.93 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio. |
… tests Address review: `ReadBufferFromAzureBlobStorage::readBigAt` returned the requested size even when the endpoint kept returning short responses and the retry budget was exhausted, so callers could use uninitialized data. Return the number of bytes actually copied instead. Extract `copyFromAzureBodyStream` and `parseMySQLBitValue` and cover both fixes with unit tests: an endpoint returning more data than requested, a short response, and an oversized MySQL `BIT` payload.
…-buffer-overflows
`ReadBufferFromAzureBlobStorage::initialize` derived `total_size` from `BodyStream::Length`, which is the `Content-Length` chosen by the remote endpoint. With `read_until_position = 100`, `offset = 0` and a 64-byte reading buffer, an endpoint that answers the 100-byte ranged request with `Content-Length = 128` made `nextImpl` hand out 64 bytes twice and only trip the right-bound check on the following call, so 28 bytes from outside the requested range had already escaped into the caller. With a reading buffer larger than the range, all 28 escape in a single call. Derive the bound of the current download from `read_until_position`, which is set locally by the caller, instead of trusting the length of the response. The size of the blob from the same response is not used for this: it comes from the same untrusted place, and an endpoint that answers a ranged request with `200 OK` would make it truncate a legitimate read. Fold the tests of `copyFromAzureBodyStream` into a new `src/Disks/tests/gtest_azure_read_buffer.cpp` and add regressions that drive `nextImpl` through `setReadUntilPosition` against a fake Azure HTTP transport whose response is longer than the requested range. Without the change they fail with `Attempt to read beyond right offset (128 > 99)`.
`ETag` is an optional response header, and `Azure::ETag::ToString` calls `AZURE_ASSERT_MSG`, which aborts the process - in release builds too, because that macro is not compiled out with `NDEBUG`. `setMetadataFromResponse` called it unconditionally on the response of every `Download`, both on the sequential path and in `readBigAt`, so an endpoint that answers without an `ETag` took the server down. Found while writing the regression for the ranged-read bound: a mocked response without that header aborted the unit test binary with `SIGABRT`.
| /// The endpoint kept returning short responses. Report how much was actually copied: | ||
| /// the caller must not treat the tail of its buffer as initialized. | ||
| LOG_DEBUG(log, "AzureBlobStorage readBigAt for file {} got only {} bytes out of {} requested after {} attempts", | ||
| path, initial_n - n, initial_n, max_single_download_retries); | ||
| } |
There was a problem hiding this comment.
Maybe we should throw error (like UNEXPECTED_END_OF_FILE) here or increase level of log to warning. wdyt ?
There was a problem hiding this comment.
🕵 I took the second half of your suggestion and raised it to LOG_WARNING (it went in with 8329b8c, which touches the same file - the commit message only mentions the ETag work). Exhausting the retry budget against an endpoint that keeps answering short is not a normal condition and should be visible without turning up the log level of the whole server.
I did not make it throw, and I would rather leave that to you to overrule if you disagree. readBigAt is documented in SeekableReadBuffer as "Stops either after n bytes, or at end of file, or on exception. Returns number of bytes read", so a short return is the documented end-of-file signal, and the callers that cannot accept one already convert it into UNEXPECTED_END_OF_FILE themselves - see CachedInMemoryReadBufferFromFile, which compares the result against the requested size and throws exactly that. Throwing inside readBigAt would duplicate that error and take the choice away from callers that legitimately read up to the end of the file. What this pull request fixes is the previous behaviour of returning initial_n unconditionally, which told the caller that bytes it never received were initialized.
`parseMySQLBitValue` copied the payload into the object representation of the result and reversed it only on a little-endian host. On a big-endian host a value shorter than 8 bytes therefore stayed left-aligned: `"\x01\x02"` read back as `0x0102000000000000` instead of `0x0102`, a wrong result for every `MYSQL_TYPE_BIT` column on the big-endian targets we build for. Assemble the integer by shifting instead, which needs no byte order at all. The unit test now covers every width from 0 to 8 bytes; its expectations are numbers rather than byte patterns, so they hold on a host of either endianness.
…d` path `Azure::ETag::ToString` aborts the process when the tag is absent, in release builds too, because `AZURE_ASSERT_MSG` expands to `std::abort` under `NDEBUG`. Guarding it in `ReadBufferFromAzureBlobStorage::setMetadataFromResponse` left three call sites that take the same untrusted value straight from a response: `AzureObjectStorage::getObjectMetadata` on the answer to `GetProperties`, and the two listing paths (`listObjects` and the iterator) on the `Etag` element of every blob in the answer to `ListBlobs`. All three are reachable outside the read-buffer flow, so an Azure-compatible endpoint that omits the optional tag could still take the server down. Put the guard in one place, `AzureBlobStorage::getETagOrEmpty`, and route all four call sites through it. There is no unguarded `Azure::ETag::ToString` left in the tree. `src/Disks/tests/gtest_azure_object_storage_metadata.cpp` drives `getObjectMetadata`, `listObjects` and `iterate` against a fake Azure HTTP transport that answers without an `ETag`.
The transport policy of the Azure SDK buffers the body of every response it does not stream, by calling `ReadToEnd` on the body stream unconditionally. A response constructed without one therefore dereferences a null pointer, which is what the answer to the HEAD request of `GetProperties` did: the test crashed before it ever reached the `ETag` conversion it was meant to cover. Serve every response, including the empty body of the HEAD, from a body stream that owns its data.
The AI review on #115706 found two remaining gaps in the Azure hardening: - `getTotalSizeOfCurrentDownload` shrank the bound of a right-bounded read to the remote `Content-Length`, so a short `206` response moved the end of the file before the locally requested `read_until_position`, breaking the `supportsRightBoundedReads` promise. The local bound is now authoritative: on a premature end of the response, `nextImpl` reopens the download at the current offset, and throws `UNEXPECTED_END_OF_FILE` once the retry budget is exhausted, instead of silently reporting a truncated file. - `copyFromAzureBodyStream` capped the copy by the reported `Content-Length`, so an endpoint under-reporting it truncated a `readBigAt` even when the bytes were already in the response body. The size of the destination is the only bound needed: `ReadToCount` stops at the actual end of the body. The unit tests now drive the reader through a range-aware fake transport: `ShortRangeResponse` asserts that a bounded read reassembles the full range through reopens, the new `TruncatedBlob` asserts the exception when the blob really ends before the bound, and the new `LengthSmallerThanData` pins down that a lying short `Content-Length` does not truncate the copy. Co-Authored-By: Claude Fable 5 <[email protected]>
…-buffer-overflows
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115706&sha=439fb44121b960987a8ab86ba3fa2d9e46e1d1f1&name_0=PR&name_1=Fast%20test%20%28arm_darwin%29 — |
|
The fix is already open: #113605 ( One correction to the diagnosis: this is disk, not memory. The only failing leaf in the report you linked is on runner What #113605 changes: |
…null `memcpy` in the test `supportsReadAt` advertises positioned reads on a buffer on which nothing has been read yet, but `readBigAt` dereferenced `blob_client`, which is only created by the sequential path and by `tryGetFileSize`. It is also called concurrently on the same buffer, so it must not create the shared member either: it now uses a call-local `BlobClient` when the shared one does not exist. `AzureReadUntilPosition.TruncatedBlob` failed under UBSan because the fake transport served an empty response body, and `memcpy` was then called with a null source pointer.
…-buffer-overflows
|
Sent as #120303. I took the caller-side retry policy rather than teaching One thing I did not expect: the retry budget was not the only reason the log held nothing but dots. The child's stdout is a block-buffered pipe ( |
…llision-114847 Master landed ClickHouse#115706, which pins an S3Queue read, copy and delete to the generation of the SOURCE that was ingested. This branch guards the DESTINATION of a move. The two overlap, so the merge is not textual: - `copyS3File` and `copyAzureBlobStorageFile` keep master's positional `src_etag` / `src_version_id` and its `String` return; `S3CopyFileSettings` loses `source_if_match` and `source_version_id`, which said the same thing, and keeps the destination guard and the header and tag restatement the guard forces. `makeCopySource` goes, master has `copySource()`. - `deleteFileFromS3` takes master's `etag_to_match` and then this branch's `version_id`. They are different operations: `If-Match` refuses a delete of a newer generation, a version id removes one named version and leaves no delete marker. Passing a version id in master's slot would have sent it as an `ETag`. - The Azure read-and-write fallback is pinned to `src_etag` by master, so the refusal this branch raised there is gone. - A source that is no longer the ingested generation now raises `FILE_CHANGED_DURING_READ` or `S3_OBJECT_CHANGED_DURING_READ` and is rethrown once the batch is done, so the file is not committed and the newer generation is read later. This branch logged it and committed the file, which left that generation in the bucket unread. `MoveResult::SourceRewritten` goes with it, and `removeCopiedSource` drops its head-then-delete check, which master's `If-Match` makes atomic. - The queue source takes master's `ProcessedFile`, which carries the size as well as the `ETag`, and its fail-closed refusal to read a file whose generation the listing did not report. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ails, and skip if it is unavailable `LogCluster.select` returned None for every kind of read failure and printed only the last response's text, so its one caller could say no more than "CI logs cluster query failed: <SQL>" and the reader had to open the job log to find that the endpoint had answered `Code: 241 ... (MEMORY_LIMIT_EXCEEDED)`. One shape was worse than a bad message. A failure raised after the status line is already on the wire arrives in the body, in an `exception` field next to the rows produced before it, and `response.ok` is true. Against a stub endpoint answering `200` with that field and an empty `data`, master's `has_pr_data` gets `[]`, the job posts "No arm_release build profile data for commit ..." and completes OK: a failed read is a green check. `select` now classifies every response with one module-level predicate - a body that is a JSON object with a non-empty `exception`, otherwise a status that is not ok - retries such an in-band failure like a 5xx, and raises `ReadFailure` with the status and the cluster's own error. `Db.query` keeps no failure branch. A cluster that cannot answer at all is not the commit's fault, so when every observed failure was a `>= 500` or a `requests` timeout, `select` raises `TransientReadFailure` and the job is SKIPPED with a pinned comment saying the comparison did not run. One non-5xx refusal, a probe answering something other than `1`, or a comment that did not post keeps the check red, so a 403 is still a failure. The skip is not cached: the verdict is the cluster's health, which no digest input captures, and a cached success would turn one pressure spike into a permanent skip. The readiness probe is classified the same way. It used to return a bare False after printing `No connection to LogCluster` with neither status nor body, so a run that failed there was red with nothing to attribute it to; it now prints both, and a `>= 500` or a timeout there is transient like the read itself. Requested in ClickHouse#115706 (comment) and ClickHouse#118708 (review) . Supersedes ClickHouse#120121 , closed in favour of this one. Co-Authored-By: Claude Opus 5 <[email protected]>
…collision-114847 Master reverted ClickHouse#115706, which this PR is built on. The revert is kept everywhere (backups, plain_rewritable, the Azure read buffer, MySQLSource, their tests), while the S3/Azure copy-and-delete generation pinning this PR needs is carried by the PR itself. Resolved: AzureObjectStorage.cpp, S3ObjectStorage.cpp, gtest_azure_read_buffer.cpp, copyAzureBlobStorageFile.cpp, copyS3File.cpp, deleteFileFromS3.{cpp,h}, getObjectInfo.cpp, ObjectStorageQueuePostProcessor.{cpp,h}. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01ScfL2iRpXjAYmAMoDLCmqY
`ReadBufferFromAzureBlobStorage::setReadUntilPosition` only recorded the new bound and marked the download as not initialized, leaving the working buffer as it was. When the bound was lowered below the end of the buffered bytes, those bytes were still handed out past the bound, and the next download was then opened where the previous response ended rather than at the bound, so the following `nextImpl` failed with the logical error `Attempt to read beyond right offset (100 > 39)`. Formats that adjust the bound mid-read (Parquet, Arrow, ORC through `AsynchronousBoundedReadBuffer`) are the callers. The buffered bytes that lie past a lowered bound are now cut off the working buffer, and the next download, if any, starts at the bound. Buffered bytes within the new bound are kept, so raising the bound goes on reopening the download after them, as before, without downloading them again. Setting the bound that is already in effect no longer drops the download. The download itself is always reopened under a changed bound, since the current one was requested under the previous bound. `src/Disks/tests/gtest_azure_read_buffer_right_bound_change.cpp` lowers the bound below already buffered bytes (fails with the logical error without the change), raises it after some bytes were consumed, and sets the same bound twice, checking the bytes delivered, the final position, and the offsets the fake endpoint was asked for. This is one of the independent parts of #115706, which was reverted in #120419.
…ure copy `BlobProperties::CopySource` and `CopyStatusDescription` are `Nullable` in the Azure SDK, and `Nullable::Value()` of an empty one calls `std::abort` in a release build (`AZURE_ASSERT_MSG` expands to a bare `std::abort` under `NDEBUG`). The completion of an asynchronous native copy (`StartCopyFromUri` polled to the end) logged `CopySource.Value()` and reported `CopyStatusDescription.Value()`, and the properties it polls come from the remote endpoint, which is under no obligation to send either header. The log names `src_blob` instead, and the failure message says `<none>` for a missing description. `src/IO/tests/gtest_azure_copy_blob_optional_properties.cpp` drives the asynchronous copy against a fake Azure HTTP transport that reports the copy as completed without `x-ms-copy-source`. Without the change, the unit test binary dies with `SIGABRT`. This is one of the independent parts of ClickHouse#115706, which was reverted in ClickHouse#120419.
…ails, and skip if it is unavailable `LogCluster.select` returned None for every kind of read failure and printed only the last response's text, so its one caller could say no more than "CI logs cluster query failed: <SQL>" and the reader had to open the job log to find that the endpoint had answered `Code: 241 ... (MEMORY_LIMIT_EXCEEDED)`. One shape was worse than a bad message. A failure raised after the status line is already on the wire arrives in the body, in an `exception` field next to the rows produced before it, and `response.ok` is true. Against a stub endpoint answering `200` with that field and an empty `data`, master's `has_pr_data` gets `[]`, the job posts "No arm_release build profile data for commit ..." and completes OK: a failed read is a green check. `select` now classifies every response with one module-level predicate - a body that is a JSON object with a non-empty `exception`, otherwise a status that is not ok - and raises `ReadFailure` with the status and the cluster's own error. `Db.query` keeps no failure branch. A cluster that could not serve the read is not the commit's fault, so in that case `select` raises `TransientReadFailure` and the job is SKIPPED with a pinned comment saying the comparison did not run. Three observations mean the read was not served: a `>= 500`, a `requests` timeout, and an error the server reports after it has already committed an ok status, which is the condition a `>= 500` reports when it happens before the status goes out. The two are the same event seen at different points of one answer, so they are classified alike. Anything else keeps the check red: a 403 or any other refusal (an `exception` field does not make one transient, the committed ok status does), a probe answering something other than `1`, a non-timeout connection failure, or a comment that did not post. One such observation is enough, which is why the classification needs no more than the one flag that records it. The skip is not cached: the verdict is the cluster's health, which no digest input captures, and a cached success would turn one pressure spike into a permanent skip. The readiness probe is classified the same way. It used to return a bare False after printing `No connection to LogCluster` with neither status nor body, so a run that failed there was red with nothing to attribute it to; it now prints both, and a `>= 500` or a timeout there is transient like the read itself. Requested in ClickHouse#115706 (comment) , ClickHouse#118708 (review) and ClickHouse#118708 (comment) . Supersedes ClickHouse#120121 , closed in favour of this one. Co-Authored-By: Claude Opus 5 <[email protected]>
The `ignore_range` mode of the fake endpoint - answering every request with `200 OK` and the blob from byte 0, the way a proxy that does not understand ranges does - and the `HTTP_RANGE_NOT_SATISFIABLE` and `LOGICAL_ERROR` error codes are left over from #115706, where the check of the range an endpoint returns lived in the same change as the premature end. No test here uses them. That check is #120955, and it brings its own range-ignoring endpoint in `src/Disks/tests/gtest_azure_read_buffer_range_check.cpp`. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…equested one A successful `Download` is not enough to trust the body: an endpoint, or a proxy in front of it, that ignores the requested range answers `200 OK` with the whole object from byte 0, and the reader consumed that body as if it started at the requested offset - both on the sequential path (after a seek or on a reopen) and in `readBigAt`. The caller then got the wrong bytes under the right offsets, which is silent data corruption. The start of the returned range (`Content-Range`, which the SDK reports as 0 for a `200 OK` response) is now checked against the requested offset before the body is read, and a mismatch is `HTTP_RANGE_NOT_SATISFIABLE`. A full-object response is accepted exactly when the request started at 0, where it is a correct answer, the same as in `ReadWriteBufferFromHTTP`. `src/Disks/tests/gtest_azure_read_buffer_range_check.cpp` drives a positioned read and a sequential read after a seek against a fake endpoint that ignores ranges, and a read at offset 0 and a well-behaved endpoint as controls. This is one of the independent parts of ClickHouse#115706, which was reverted in ClickHouse#120419.
…hin one storage `IObjectStorage::copyObjectToAnotherObjectStorage` handled the case where the destination storage is the same instance by calling `copyObject`, and then fell through to the generic path, which read the source and wrote the destination a second time through buffers. The object ended up correct, but every such copy transferred the data twice: natively, and then once more over the network through the server. Return after the native copy. The default implementation is reached by every object storage that does not override the method (Azure, Local, Web, HDFS, and S3 for a cross-storage copy, which forwards to it), through `DiskObjectStorageTransaction` and `BlobCopierThread`. `src/Disks/tests/gtest_copy_object_to_another_object_storage.cpp` copies an object within one local object storage and counts the reads and writes: exactly one of each. This is one of the independent parts of ClickHouse#115706, which was reverted in ClickHouse#120419.
`ReadBufferFromAzureBlobStorage::nextImpl` took the end of the response body as the end of the data. For a read with a right bound that is wrong: the bound is set locally by the caller, and every layer above the buffer takes it as the length of the data, so an endpoint or a proxy that caps its responses - or a blob that is shorter than the size it was listed with - silently truncated the file at the end of the first response. A response that ends before the bound is now a premature end: the download is reopened at the offset the read has reached and counted against `max_single_read_retries`, and when the endpoint keeps ending its responses before the bound the read fails with `UNEXPECTED_END_OF_FILE` instead of returning truncated data. A read without a right bound keeps its behaviour. The amount left of the current download is measured per attempt, so a reopened download is read from where it was reopened. `src/Disks/tests/gtest_azure_read_buffer_premature_end.cpp` reassembles a 100-byte blob from an endpoint that caps every response to 40 bytes, fails on a blob truncated at 40 bytes after the retries are spent, and checks that an exact response and an unbounded read are not reopened. This is one of the independent parts of ClickHouse#115706, which was reverted in ClickHouse#120419.
…the response length `ReadBufferFromAzureBlobStorage::initialize` derived `total_size` from `BodyStream::Length`, which is the `Content-Length` chosen by the remote endpoint. With `read_until_position = 100`, `offset = 0` and a 64-byte reading buffer, an endpoint that answers the 100-byte ranged request with `Content-Length = 128` made `nextImpl` hand out 64 bytes twice and only trip the right-bound check on the following call, so 28 bytes from outside the requested range had already escaped into the caller. With a reading buffer larger than the range, all 28 escape in a single call. Derive the bound of the current download from `read_until_position`, which is set locally by the caller, and let the length of the response only shorten it. The size of the blob from the same response is not used for this: it comes from the same untrusted place, and an endpoint that answers a ranged request with `200 OK` would make it truncate a legitimate read. `src/Disks/tests/gtest_azure_read_buffer.cpp` gains regressions that drive `nextImpl` through `setReadUntilPosition` against a fake Azure HTTP transport whose response is longer than the requested range, with a reading buffer both smaller and larger than the range. Without the change they fail with `Attempt to read beyond right offset (128 > 99)`. This is one of the independent parts of ClickHouse#115706, which was reverted in ClickHouse#120419. The positioned read path, `readBigAt`, was fixed separately in ClickHouse#119054.
`ReadBufferFromAzureBlobStorage::setReadUntilPosition` only recorded the new bound and marked the download as not initialized, but left the working buffer as it was. The bytes that the current response had already delivered were still handed out - past a lowered bound too - and the next download was then opened where the previous response ended rather than where the reader was, so the following `nextImpl` failed with the logical error `Attempt to read beyond right offset`, whether the bound was lowered or raised. Setting the bound that was already in effect did the same, because it also dropped the download. A change of the right bound is now a new logical read, the same way a seek is: the working buffer is dropped, the position is kept, and the download is reopened at the position under the new bound. Setting the bound that is already in effect does nothing, so a caller that sets it repeatedly does not reopen the download. `setReadUntilEnd` uses the same path. `src/Disks/tests/gtest_azure_read_buffer_right_bound_change.cpp` lowers the bound below already buffered bytes, raises it after some were consumed, and sets the same bound twice, checking the bytes delivered, the final position, and the offsets the endpoint was asked for. This is one of the independent parts of ClickHouse#115706, which was reverted in ClickHouse#120419.
Places where data that comes from an external server was used without checking it against what was
requested locally:
ReadBufferFromAzureBlobStorage::readBigAtrequestsnbytes and copiesbody_stream->Length()bytes into a buffer that has room for
n. The length is theContent-Lengthof the response, soan endpoint that returns more data than the requested range overflows the buffer. The S3
implementation caps the copy at
n; do the same here.BITfield copiesvalue.size()bytes into aUInt64on the stack. Thelength comes from the MySQL wire protocol, while a
BITvalue holds at most 64 bits.initializederivedtotal_sizefromBodyStream::Length, so withread_until_position = 100,offset = 0and a 64-byte buffer, an endpoint answering the 100-byte ranged request withContent-Length = 128delivered 28 bytes from outside the requested range to the caller beforethe right-bound check tripped on the following call. The bound is now derived from
read_until_position, which is set locally.ETagis an optional response header, andAzure::ETag::ToStringaborts the process when thetag is absent - in release builds too, because
AZURE_ASSERT_MSGexpands to a barestd::abortunder
NDEBUG, dropping the message with it. Three call sites converted it unconditionally on avalue taken straight from a response:
setMetadataFromResponseon the details of everyDownload,AzureObjectStorage::getObjectMetadataon the answer toGetProperties, and bothlisting paths (
listObjectsand the async iterator) on theEtagelement of every blob in theanswer to
ListBlobs. All of them are reachable by an endpoint that simply omits the header, andall but the first are outside the read-buffer flow. The guard now lives in one place,
AzureBlobStorage::getETagOrEmpty, and every call site goes through it; no unguardedAzure::ETag::ToStringis left in the tree.Additionally,
readBigAtreported the full requested size even when the endpoint kept returningshort responses and the retry budget was exhausted, so callers could use uninitialized data; it
now returns the number of bytes actually copied, and says so at warning level. It does not throw:
readBigAtis documented to stop at the end of the file and return the number of bytes read, andthe callers that cannot accept a short read (
CachedInMemoryReadBufferFromFile, for one) alreadyturn it into
UNEXPECTED_END_OF_FILEthemselves.parseMySQLBitValuealso decoded shortBITpayloads incorrectly on a big-endian host: the byteswere written into the object representation of the result and reversed only on a little-endian one,
so a value shorter than 8 bytes stayed left-aligned and
"\x01\x02"read back as0x0102000000000000instead of0x0102. It is now assembled by shifting, which needs no byteorder at all.
Beyond the overflows, the Azure read and copy paths trusted the endpoint about where an object
ends and about which generation of it they were talking to:
read_until_positionwhen the caller set one,otherwise the size the object had when it was listed or headed. That size is not an optional
hint: it is the length of the file for every layer above the buffer -
ReadBufferFromRemoteFSGatherlays the next object of a file out right behind it,AsynchronousBoundedReadBuffertakes it as its own right bound,ReaderExecutorclamps objectreads to it, and both caches address the data inside a file of that length - so the buffer ends
the read there as well, and an endpoint that answers with more cannot push the excess under
offsets that belong to something else. It is also the size the buffer reports:
getFileSizeanswers with it without a
HEAD, so a wrapper that sizes itself before it reads (the page cache,CachedInMemoryReadBufferFromFile) cannot learn the length of a newer generation at the key andexpect bytes the buffer ends before. Where neither is available, reaching the
Content-Rangetotal of a response is treated as a question rather than an answer: the download is reopened at
that offset and the end of the file is reported only if the fresh response delivers nothing
either, or if the endpoint refuses the range with
416, which is how a real one answers a rangepast the end of a blob. An endpoint that caps an open-ended
GETtherefore cannot truncate thefile silently.
Download,a retry, and a reopen after a premature end of the response - carries
If-Matchon thegeneration selected at read setup, and the
ETagof every response is compared with it, so ablob overwritten in place mid-read raises
FILE_CHANGED_DURING_READinstead of handing thecaller bytes stitched together from two objects. The offset of the returned
Content-Rangeischecked against the requested one, so an endpoint that ignores the range cannot deliver the wrong
bytes under the right offsets.
x-ms-source-if-match, the read-and-write fallback pins its reads, and aDELETEthat follows acopy removes only the generation that was copied. The paths that copy-then-delete - the
after_processingstep ofObjectStorageQueue, theMOVEandunlinkoperations of aplain_rewritabledisk, and backups - name the generation once and use it for every request, andrefuse to act at all when the endpoint will not name one, rather than acting blind. The one
one shape that cannot be pinned is a
plain_rewritablemove or hard link whose endpoint names nogeneration in its response to the copy to the destination: the operation is refused before the
source is deleted, and its rollback does not delete the destination either - a delete by key alone
could take away a generation another writer has put there since - but leaves the blob the copy
wrote at its key and logs it.
loadrebuilds a directory from the blobs under its key, so thatblob comes back as the uncommitted file on the next start until it is removed by hand; that is
the fail-closed side of the trade, a copy of the source left behind rather than a blob deleted blind.
The generation the copy wrote is named by the response to the copy itself:
IObjectStorage::copyObjectreturns theETagthe endpoint reported for the object it created(
CopyObject/PutObject/CompleteMultipartUploadon S3,Copy Blob From URL/Put Blob/Put Block Liston Azure; an asynchronous Azure copy is trusted only when the destinationproperties report the copy that was started as the one that wrote the blob), and
nameTheGenerationThatWasJustWrittenmakes no request of its own. NoHEADof the destinationfollows the copy, so a writer that replaces the destination right after it cannot have its
generation bound to the operation: the rollback delete carries the copy's
ETagand is refused.copyS3FileandcopyS3FileRangecarry the
ETagof the selected generation asx-amz-copy-source-if-matchon theCopyObjectand on every
UploadPartCopy, and map a412toS3_OBJECT_CHANGED_DURING_READbefore any otherroute is tried. The S3 backup writer (
copyFileFromDisk,copyFile) and reader name thegeneration of the source with one
HeadObject, check the measured size against the file beingbacked up or against the backup metadata (a restore of a backup file replaced by a longer object
is refused rather than restored as its first bytes or copied whole), and use it for the native
copy and for the pinned
ReadBufferFromS3of the fallback; theafter_processingmove and delete of
ObjectStorageQueuepin their copy and their delete to the generation thelisting reported, pin the read that ingests the file to that same generation whatever
s3_validate_etag_on_readsays (as they do on Azure), and aS3_OBJECT_CHANGED_DURING_READanywhere in the post-processing aborts the batch likeFILE_CHANGED_DURING_READdoes on Azure.s3_validate_etag_on_read = 0opts the S3 backupcopies out of the pinning only, as it does every other S3 read, and not out of the size check;
with the pinning off, though, the check holds for the object at the
HeadObjectonly, and asame-key replacement between that
HeadObjectand theGETorCopyObjectis not caught,because the read carries no generation to refuse it by - that window is what opting out gives
up, for backups as anywhere else, while the replacement that is already there when the restore
or backup starts is still refused. A backup opened as
S3('...?versionId=...')is read at thatversion, and the native copy of a restore to an S3 disk addresses the same version
(
bucket/key?versionId=...on theCopyObjectand on everyUploadPartCopy), so it cannotrestore the latest version of the key in place of the selected one.
The read-and-write fallback of the backup writer reads through the disk (so it honours
read_from_filesystem_cache) for every disk whose object keys are generated and neverrewritten in place, and checks after the buffer is built that the file still names the object
that was measured (a file rewritten in between names a new key, and is refused with
S3_OBJECT_CHANGED_DURING_READ); only aplain/plain_rewritabledisk gets the direct readpinned with
If-Match. Aplain_rewritablemove or hard link names the generation of itssource on Azure and on S3 (
pinToTheGenerationThatIsThereNow), copies exactly that one, andrefuses a source generation whose size is not the one the metadata records for the file
(
refuseAGenerationOfAnotherSize), so a target can never be recorded with the size of ageneration it did not copy. The S3 delete is pinned too: S3 evaluates
If-Matchon aDeleteObjectand theETagelement of every object of aDeleteObjectson general purposebuckets, so the delete that follows a copy (
plain_rewritableunlink,moveand hard link, theafter_processingmove ofObjectStorageQueue), the rollback deletes of a move and a hard link,and
after_processing = 'delete'carry the generation that was copied or ingested and are refusedwith
FILE_CHANGED_DURING_READwhen another writer has replaced it; a batch deletes every objectit can before it reports the replaced one. An S3-compatible endpoint that ignores
If-Matchon aDELETEdeletes by key, as it did before the header was sent. The rollback of aplain_rewritableunlinkormovewhose delete already went through restores the blob it savedaside without writing over a key that another writer has recreated since, on Azure and on S3
alike (
restoreTheSavedBlobWithoutWritingOver): the saved blob is read pinned to its generationand put back with a create-if-absent write (
If-None-Match: *), and a refused restore leaves thesaved blob in the bucket at its temporary key rather than being retried blind.
src/Disks/tests/gtest_azure_read_buffer.cppdrives the reader, the copies, the deletes, the queuepost-processing and the
plain_rewritablemove operations against a fake Azure HTTP transport thatmisbehaves in each of the ways above - a response longer than the requested range, a response
shorter than it, a
Content-Rangetotal that under-reports or shrinks, a range refused with416,a
HEADwithout anETagor with a404, an ignored range, and an overwrite placed at an exactpoint of a request sequence.
src/Disks/tests/gtest_azure_object_storage_metadata.cppcoversgetObjectMetadata,listObjectsanditerateagainst an endpoint that omits the header;src/Processors/tests/gtest_mysql_bit_value.cppcovers theBITpayload at every width from 0 to8 bytes, with expectations written as numbers so that they hold on a host of either endianness.
src/IO/tests/gtest_writebuffer_s3.cppdrives the pinned S3 copies and deletes, and theplain_rewritablemove and hard-link operations on S3, against an S3 mock that keeps ageneration per object, keeps versions of a key, and evaluates
x-amz-copy-source-if-match,?versionId=on a copy source,If-MatchonDeleteObjectand the
ETagelement ofDeleteObjects;05211_s3_backup_native_copy_etagbacks a table on an S3 disk up to S3 with a failpoint that makes the pinned copy carry a generation
the source never had, and
05210_s3_backup_plain_read_etag/05194_s3_backup_archive_reopen_etagdo the same for the reads of a backup;
05212_s3_backup_restore_replaced_filereplaces a data fileinside an S3 backup with a longer object and asserts that both the buffered restore and the native
copy of the restore refuse it;
05213_s3_backup_archive_without_etagmakesHeadObjectreport noETag(failpoints3_head_omit_etag) and asserts that the restore of an archive is refused up front,because its reopens could not be pinned to one generation.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix buffer overflows and a server abort on malformed responses from external servers: an Azure Blob Storage endpoint that returns more data than was requested or omits the
ETagheader, and a MySQL server that returns an oversizedBITvalue. Azure reads, copies and deletes, and S3 copies made by backups and byS3Queuepost-processing, are now pinned to the object generation they selected, so an object overwritten in place is reported instead of silently mixing two generations. Also fix the decoding of a MySQLBITvalue shorter than 8 bytes on big-endian hosts.Workflow [PR]
Sync PR [sync-upstream/pr/115706]
Version info
26.9.1.1544(included in26.9and later)