Skip to content

GH-55669: [C++][IPC] Validate buffer bounds and replace raw pointer arithmetic in MessageDecoder - #55671

Open
Awesome06 wants to merge 7 commits into
apache:mainfrom
Awesome06:gh-55669-ipc-buffer-bounds
Open

Awesome06 wants to merge 7 commits into
apache:mainfrom
Awesome06:gh-55669-ipc-buffer-bounds

Conversation

@Awesome06

@Awesome06 Awesome06 commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Rationale for this change

In arrow::ipc::MessageDecoderImpl, chunk reassembly relied on unchecked pointer arithmetic (memcpy(out + offset, ...)) during streaming message reconstruction. In addition, MessageDecoder::Consume(data, size) did not validate that size >= 0, which could construct invalid negative-sized Buffer instances and corrupt internal chunk accounting. FlatBuffers tensor metadata decoders called .size() directly on tensor->shape() without verifying that the optional vector was non-null, and IPC readers lacked opt-in limits to constrain untrusted metadata sizes, body lengths, or decompression expansion ratios.

What changes are included in this PR?

  • Replaces raw pointer arithmetic in MessageDecoderImpl::ConsumeDataChunks with std::span and checked addition via ::arrow::internal::AddWithOverflow.
  • Enforces validation in MessageDecoder::Consume rejecting size < 0 at the public API entry point.
  • Fixes potential use-after-free on EOS in MessageDecoderImpl when a listener resets or destroys the decoder during OnEOS.
  • Adds CHECK_FLATBUFFERS_NOT_NULL guards for tensor->shape(), dimension elements, and custom metadata pairs in metadata_internal.cc.
  • Adds max_metadata_length, max_body_length, and max_decompression_ratio to IpcReadOptions (defaulting to -1 for unlimited / backwards compatibility), alongside Validate(), CheckMetadataLength(), and CheckBodyLength() helpers.
  • Enforces max_decompression_ratio in DecompressBuffer using MultiplyWithOverflow and slices compressed payloads using std::span.
  • Plumbs IpcReadOptions and limit checks through MessageDecoder, MessageReader, ReadMessage, ReadMessageAsync, and RecordBatchFileReader (including file footers, pre-buffered block ranges, and custom message reader streams).

Are these changes tested?

Yes. Existing IPC streaming and file tests pass. New deterministic unit tests were added in cpp/src/arrow/ipc/read_write_test.cc:

  • TestMessageDecoderBounds.MalformedOrExceededHeaders
  • TestStreamReaderLimits.MaxBodyLengthExceeded
  • TestStreamReaderLimits.CustomMessageReaderLimitsExceeded
  • TestFileReaderLimits.MaxMetadataLengthExceeded
  • TestFileReaderLimits.MaxBodyLengthExceeded
  • TestIpcReadOptions.NegativeLimitsInvalid
  • TestDecompressBufferLimits.Limits
  • TestMetadataBounds.EmptyOrInvalidTensorMetadata

Are there any user-facing changes?

No breaking changes. Users can optionally configure max_metadata_length, max_body_length, and max_decompression_ratio on IpcReadOptions when reading IPC streams or files.

Was AI used for this PR?

In accordance to the AI generation guidelines, please disclose below whether and how AI was used in this PR.

PR code and description written by:

  • Human
  • AI

Reviewed before submission by:

  • Human
  • AI
  • Not reviewed

…in MessageDecoder

* Replace raw pointer arithmetic and unchecked memcpy offsets in MessageDecoderImpl with std::span and AddWithOverflow

* Enforce validation against negative data size in MessageDecoder::Consume

* Add opt-in max_metadata_length, max_body_length, and max_decompression_ratio ceilings to IpcReadOptions (defaulting to unlimited: -1)

* Use CHECK_FLATBUFFERS_NOT_NULL guards in Tensor metadata decoders

* Add deterministic unit tests covering negative sizes, opt-in limits, and decompression bounds in read_write_test
Copilot AI lite review requested due to automatic review settings November 18, 2026 13:09

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The change still has an unresolved critical gap where configured IPC size limits are ignored on file-reader paths, plus a decompression-ratio boundary bug that allows unlimited expansion when set to zero.

2 open issues
What changed in this PR

This PR hardens C++ IPC decoding against malformed or oversized input by validating message lengths, protecting chunk reassembly, checking FlatBuffers fields, and adding configurable decompression and allocation limits.

Changes:

  • Adds bounds validation for decoder input, metadata, body lengths, and chunk copying.
  • Adds null checks for tensor and custom metadata FlatBuffers fields.
  • Adds configurable metadata, body, and decompression-ratio limits to IpcReadOptions, with associated tests.
File Description
cpp/​src/​arrow/​ipc/​reader.cc Adds decompression-ratio validation and propagates read options to streaming decoding.
cpp/​src/​arrow/​ipc/​reader_internal.h Exposes the internal decompression helper declaration.
cpp/​src/​arrow/​ipc/​read_write_test.cc Adds tests for decoder bounds, metadata validation, body limits, and decompression limits.
cpp/​src/​arrow/​ipc/​options.h Adds configurable IPC metadata, body, and decompression limits.
cpp/​src/​arrow/​ipc/​metadata_internal.cc Validates required FlatBuffers tensor and custom metadata fields.
cpp/​src/​arrow/​ipc/​message.h Adds MessageDecoder constructors accepting IpcReadOptions.
cpp/​src/​arrow/​ipc/​message.cc Validates input sizes and message lengths, uses spans for chunk copying, and enforces decoder limits.

Review effort: Lite

Comment thread cpp/src/arrow/ipc/options.h Resolved
Comment thread cpp/src/arrow/ipc/reader.cc Resolved
…r and enforce reader limits

* Avoid use-after-free in MessageDecoderImpl when listener OnEOS resets the decoder
* Early exit when data span is fully consumed before trailing member dereferences
* Wire IpcReadOptions through ReadMessage, MessageReader, and RecordBatchFileReader
* Add block bounds validation and test coverage for IPC reader limits
Copilot AI lite review requested due to automatic review settings November 18, 2026 16:19

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Approval is blocked by two active moderate issues: invalid negative length limits can disable IPC protections, and file-footer metadata is not covered by the configured metadata bound.

3 open issues
1 resolved since last review

Review effort: Lite

Comment thread cpp/src/arrow/ipc/options.h Resolved
Comment thread cpp/src/arrow/ipc/reader.cc Resolved
…force file footer bound

* Add IpcReadOptions::Validate() to reject negative values below -1
* Wire options validation to stream and file reader entry points
* Enforce max_metadata_length against footer_length in ReadFooterAsync
* Add tests for footer bounds, negative options validation, and decoder rejection
Copilot AI lite review requested due to automatic review settings November 18, 2026 18:45

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The supplied MessageReader path bypasses the new metadata and body size limits, leaving custom readers such as Flight’s vulnerable to unbounded message decoding.

2 open issues
1 resolved since last review

Review effort: Lite

… MessageReader streams

* Validate metadata and body lengths in StreamDecoderInternal::OnMessageDecoded
* Protect custom MessageReader pathways against unbounded allocations
* Add unit test coverage with MockCustomMessageReader
Copilot AI lite review requested due to automatic review settings November 18, 2026 19:11

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Human assessment is needed because the change is unusually complex and a critical hidden issue indicates untrusted input can trigger oversized prebuffer reads before configured limits are enforced.

2 open issues

Review effort: Lite

Copilot AI lite review requested due to automatic review settings November 18, 2026 19:33

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Human assessment is needed because moderate and critical findings indicate the hardening may still permit allocation denial-of-service and allow the advertised body-length limit to be bypassed on a public reader path.

No open issues 🎉

2 resolved since last review

Review effort: Lite

…ds tests

Consolidate repeated IPC metadata and body length validations into IpcReadOptions, fix coalescing in generator limits test, and deduplicate bounds test cases.

- Add CheckMetadataLength and CheckBodyLength helper methods to IpcReadOptions to centralize limit validation and error message formatting.
- Replace repetitive validation blocks across message.cc and reader.cc with IpcReadOptions check methods.
- Update TestFileReaderLimits.GeneratorCoalesceBlockLimitsExceeded to use NoZeroCopyBufferReader to trigger coalesced range validation.
- Consolidate bounds and limits tests in read_write_test.cc to reduce boilerplate and eliminate redundant test coverage.
Copilot AI lite review requested due to automatic review settings November 19, 2026 12:01

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Active moderate and critical issues remain: unbounded metadata reservation, acceptance of negative body lengths, and bypassable size limits in direct record-batch APIs.

3 open issues

Review effort: Lite

Comment thread cpp/src/arrow/ipc/options.cc Resolved
Comment thread cpp/src/arrow/ipc/reader.cc Resolved
Comment thread cpp/src/arrow/ipc/metadata_internal.cc Resolved
@Mr-Nobody-Anonymous

Mr-Nobody-Anonymous commented Nov 19, 2026 •

Copy link
Copy Markdown

Hi @Awesome06,

Thank you for this valuable hardening work on the IPC decoder and message boundaries.

I noticed the CI build failed across the C++ matrix on read_write_test.cc:3579 with the following compilation error:
error: unable to deduce 'std::initializer_list<auto>&&' from '{(&options.arrow::ipc::IpcReadOptions::max_metadata_length), (&options.arrow::ipc::IpcReadOptions::max_body_length), (&options.arrow::ipc::IpcReadOptions::max_decompression_ratio)}' note: deduced conflicting types for parameter 'auto' ('long int*' and 'int32_t*' {aka 'int*'})

The root cause is that max_metadata_length and max_body_length are int64_t*, whereas max_decompression_ratio is int32_t*. Because the braced initializer list contains mixed pointer types, template type deduction fails.

I investigated this and prepared a patch that addresses both this build failure and the active review findings:

  1. Build Failure in Test:
  • Separated the int64_t* fields (max_metadata_length, max_body_length) from int32_t* (max_decompression_ratio) in TEST(TestIpcReadOptions, NegativeLimitsInvalid).
  1. Negative Body and Metadata Length Rejection:
  • Added validation in IpcReadOptions::CheckMetadataLength and IpcReadOptions::CheckBodyLength (as well as CheckBodyLength in message.cc) to reject negative lengths directly before checking limits or performing arithmetic.
  1. Limit Enforcement in Direct RecordBatch Entry Points:
  • Moved options.Validate(), CheckMetadataLength(), and CheckBodyLength() into the shared ReadRecordBatchInternal function in cpp/src/arrow/ipc/reader.cc so that direct calls like ReadRecordBatch(metadata, ...) and ReadRecordBatch(message, ...) respect the configured limits.
  1. Unconditional Metadata Allocation:
  • Removed metadata->reserve(fb_metadata->size()) in GetKeyValueMetadata in cpp/src/arrow/ipc/metadata_internal.cc to prevent untrusted FlatBuffers custom metadata from triggering premature large vector allocations.
  1. Added Unit Tests:
  • Added tests verifying that negative lengths are rejected and that direct ReadRecordBatch calls enforce metadata and body length limits.

To make it as easy as possible to integrate, I have opened a pull request against your branch:
Awesome06#1

You can also inspect the fix branch directly here:
https://github.com/Mr-Nobody-Anonymous/arrow/tree/fix-pr-55671-ipc-bounds

Please feel free to merge or adapt any of these changes if they are helpful.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota.

@Awesome06
Awesome06 force-pushed the gh-55669-ipc-buffer-bounds branch from e8322e2 to 51bdf54 Compare November 20, 2026 08:27
Copilot AI lite review requested due to automatic review settings November 20, 2026 08:27

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota.

@Awesome06

Awesome06 commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor Author

Hi @Mr-Nobody-Anonymous,

Thanks for reviewing and pointing out the template deduction conflict on line 3579. I have resolved the test pointer separation directly on this branch with clean clang-format compliance.

Regarding the additional changes (such as the FlatBuffers metadata->reserve adjustment in metadata_internal.cc and ReadRecordBatchInternal validations), I am keeping this PR strictly focused on the MessageDecoder buffer bounds validation and raw pointer arithmetic replacement originally specified in GH-55669. Those broader cleanups would be better suited for a distinct follow-up issue so maintainers have a clean, isolated diff to review.

I also noticed you opened a duplicate PR (#55687) incorporating my commits. Since this PR is actively maintained and passing tests, please close #55687 so we do not split the maintainers' review queue.

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants