This is an automated email from the ASF dual-hosted git repository.

github-merge-queue[bot] pushed a commit to branch 
gh-readonly-queue/main/pr-12142-0ada6ff1ae5f500efd51757993abbfa9fa558a53
in repository https://gitbox.apache.org/repos/asf/arrow-rs.git

commit df096d7cf042b645a7e35759ca865bedbd98ea92
Author: Ed Seidl <[email protected]>
AuthorDate: Fri Nov 13 22:09:20 2026 +0000

    fix(parquet): Harden Thrift decoding of binary lengths and collection 
counts (#12142)
    
    # Which issue does this PR close?
    
    - Closes #11954
    - Closes #12100
    
    # Rationale for this change
    
    There are some bits of the Thrift decoder that can either over-allocate
    or silently return corrupt data when given malformed input. I'm choosing
    to address them as a single PR to keep performance issues at a minimum.
    
    # What changes are included in this PR?
    
    - Bound binary lengths to i32::MAX, cap the initial allocation for
    streamed binary payloads, and reject truncated payloads instead of
    returning partial data.
    - Validate schema child counts against the remaining schema elements and
    offset-index page-location counts against the remaining input before
    reserving capacity.
    
    # Are these changes tested?
    
    Yes
    
    # Are there any significant user-facing changes?
    
    No
    
    # AI disclosure
    
    An AI agent was used in the development and testing of this PR.
---
 parquet/src/file/metadata/thrift/mod.rs     |  15 ++++
 parquet/src/file/page_index/offset_index.rs |  51 ++++++++++++-
 parquet/src/parquet_thrift.rs               | 112 ++++++++++++++++++++++++++--
 parquet/src/schema/types.rs                 |  43 ++++++++++-
 4 files changed, 211 insertions(+), 10 deletions(-)

diff --git a/parquet/src/file/metadata/thrift/mod.rs 
b/parquet/src/file/metadata/thrift/mod.rs
index 15f93ba0c6..0b3eac2be7 100644
--- a/parquet/src/file/metadata/thrift/mod.rs
+++ b/parquet/src/file/metadata/thrift/mod.rs
@@ -2094,6 +2094,21 @@ pub(crate) mod tests {
         );
     }
 
+    #[test]
+    fn metadata_schema_huge_child_count_is_rejected() {
+        // File version 1, one schema element named "r" with i32::MAX children.
+        let data = [
+            0x15, 0x02, 0x19, 0x1c, 0x48, 0x01, 0x72, 0x15, 0xfe, 0xff, 0xff, 
0xff, 0x0f, 0x00,
+        ];
+        let err = super::parquet_metadata_from_bytes(&data, None)
+            .unwrap_err()
+            .to_string();
+        assert!(
+            err.contains("Schema children count 2147483647 exceeds remaining 
schema elements 0"),
+            "{err}"
+        );
+    }
+
     /// Test row group on-wire size validation.
     #[test]
     fn row_group_count_exceeding_remaining_input_is_rejected() {
diff --git a/parquet/src/file/page_index/offset_index.rs 
b/parquet/src/file/page_index/offset_index.rs
index d710093703..8b5b0da8f6 100644
--- a/parquet/src/file/page_index/offset_index.rs
+++ b/parquet/src/file/page_index/offset_index.rs
@@ -10,7 +10,7 @@ use std::io::Write;
 
 use crate::parquet_thrift::{
     ElementType, FieldType, ReadThrift, ThriftCompactInputProtocol, 
ThriftCompactOutputProtocol,
-    WriteThrift, WriteThriftField, read_thrift_vec, validate_list_type,
+    WriteThrift, WriteThriftField, check_list_size, read_thrift_vec, 
validate_list_type,
 };
 use crate::{
     errors::{ParquetError, Result},
@@ -78,7 +78,10 @@ impl OffsetIndexMetaData {
         // we have to do this manually because we want to use the fast 
PageLocation decoder
         let list_ident = prot.read_list_begin()?;
         validate_list_type(ElementType::Struct, &list_ident)?;
-        let mut page_locations = Vec::with_capacity(list_ident.size as usize);
+        // list_ident.size is already guaranteed to fit in i32 by 
read_list_begin()
+        let size = list_ident.size as usize;
+        check_list_size(prot.remaining_bytes(), size)?;
+        let mut page_locations = Vec::with_capacity(size);
         for _ in 0..list_ident.size {
             page_locations.push(read_page_location(prot)?);
         }
@@ -155,7 +158,49 @@ fn read_page_location<'a, R: 
ThriftCompactInputProtocol<'a>>(prot: &mut R) -> Re
 #[cfg(test)]
 mod tests {
     use super::*;
-    use crate::parquet_thrift::tests::test_roundtrip;
+    use crate::file::page_index::index_reader::decode_offset_index;
+    use crate::parquet_thrift::{ThriftSliceInputProtocol, 
tests::test_roundtrip};
+
+    #[test]
+    fn test_offset_idx_rejects_count_exceeding_remaining_input() {
+        // Field 1: list<struct> declaring 4096 entries, with no payload.
+        let data = [0x19, 0xfc, 0x80, 0x20];
+        let mut prot = ThriftSliceInputProtocol::new(&data);
+        let err = OffsetIndexMetaData::try_from_fast(&mut prot).unwrap_err();
+        assert!(
+            err.to_string()
+                .contains("Thrift list size 4096 exceeds remaining input 
length 0"),
+            "{err}"
+        );
+        assert!(decode_offset_index(&data).is_err());
+    }
+
+    #[test]
+    fn test_offset_idx_fast_path_roundtrip() {
+        for page_locations in [
+            Vec::new(),
+            vec![PageLocation {
+                offset: 0,
+                compressed_page_size: 10,
+                first_row_index: 0,
+            }],
+        ] {
+            let index = OffsetIndexMetaData {
+                page_locations,
+                unencoded_byte_array_data_bytes: None,
+            };
+            let mut data = Vec::new();
+            index
+                .write_thrift(&mut ThriftCompactOutputProtocol::new(&mut data))
+                .unwrap();
+            let mut prot = ThriftSliceInputProtocol::new(&data);
+            assert_eq!(
+                OffsetIndexMetaData::try_from_fast(&mut prot).unwrap(),
+                index
+            );
+            assert_eq!(decode_offset_index(&data).unwrap(), index);
+        }
+    }
 
     #[test]
     fn test_offset_idx_roundtrip() {
diff --git a/parquet/src/parquet_thrift.rs b/parquet/src/parquet_thrift.rs
index aa41b32588..91402b84d0 100644
--- a/parquet/src/parquet_thrift.rs
+++ b/parquet/src/parquet_thrift.rs
@@ -311,6 +311,11 @@ pub(crate) trait ThriftCompactInputProtocol<'a> {
         }
     }
 
+    /// Read a binary length, bounded to the signed 32-bit range used by Java 
and C++ Thrift.
+    fn read_binary_len(&mut self) -> ThriftProtocolResult<usize> {
+        Ok(i32::try_from(self.read_vlq()?)? as usize)
+    }
+
     /// Read a zig-zag encoded signed varint from the input.
     fn read_zig_zag(&mut self) -> ThriftProtocolResult<i64> {
         let val = self.read_vlq()?;
@@ -461,7 +466,7 @@ pub(crate) trait ThriftCompactInputProtocol<'a> {
     ///
     /// [binary]: 
https://github.com/apache/thrift/blob/master/doc/specs/thrift-compact-protocol.md#binary-encoding
     fn skip_binary(&mut self) -> ThriftProtocolResult<()> {
-        let len = usize::try_from(self.read_vlq()?)?;
+        let len = self.read_binary_len()?;
         self.skip_bytes(len)
     }
 
@@ -600,7 +605,7 @@ impl<'b, 'a: 'b> ThriftCompactInputProtocol<'b> for 
ThriftSliceInputProtocol<'a>
     }
 
     fn read_bytes(&mut self) -> ThriftProtocolResult<&'b [u8]> {
-        let len = self.read_vlq()? as usize;
+        let len = self.read_binary_len()?;
         let ret = self.buf.get(..len).ok_or(ThriftProtocolError::Eof)?;
         self.buf = &self.buf[len..];
         Ok(ret)
@@ -658,9 +663,12 @@ impl<'a, R: Read> ThriftCompactInputProtocol<'a> for 
ThriftReadInputProtocol<R>
     }
 
     fn read_bytes_owned(&mut self) -> ThriftProtocolResult<Vec<u8>> {
-        let len = self.read_vlq()? as usize;
-        let mut v = Vec::with_capacity(len);
-        std::io::copy(&mut self.reader.by_ref().take(len as u64), &mut v)?;
+        let len = self.read_binary_len()?;
+        let mut v = Vec::with_capacity(len.min(8 * 1024));
+        let copied = std::io::copy(&mut self.reader.by_ref().take(len as u64), 
&mut v)?;
+        if copied != len as u64 {
+            return Err(ThriftProtocolError::Eof);
+        }
         Ok(v)
     }
 
@@ -1194,6 +1202,7 @@ pub(crate) mod tests {
 
     use super::*;
     use std::fmt::Debug;
+    use std::io::{ErrorKind, Result as IoResult};
 
     pub(crate) fn test_roundtrip<T>(val: T)
     where
@@ -1210,6 +1219,99 @@ pub(crate) mod tests {
         assert_eq!(val, read_val);
     }
 
+    #[test]
+    fn test_binary_length_bound() {
+        let oversized = [0x80, 0x80, 0x80, 0x80, 8]; // i32::MAX + 1
+        let maximum = [0xff, 0xff, 0xff, 0xff, 7]; // i32::MAX, no payload
+        for bytes in [&oversized, &maximum] {
+            let check = |result: ThriftProtocolResult<()>| {
+                if bytes == &oversized {
+                    assert!(matches!(result, 
Err(ThriftProtocolError::IntegerOverflow)));
+                } else {
+                    assert!(matches!(result, Err(ThriftProtocolError::Eof)));
+                }
+            };
+            check(
+                ThriftSliceInputProtocol::new(bytes)
+                    .read_bytes()
+                    .map(|_| ()),
+            );
+            check(
+                ThriftSliceInputProtocol::new(bytes)
+                    .read_bytes_owned()
+                    .map(|_| ()),
+            );
+            check(ThriftSliceInputProtocol::new(bytes).skip_binary());
+            check(
+                ThriftReadInputProtocol::new(bytes.as_slice())
+                    .read_bytes_owned()
+                    .map(|_| ()),
+            );
+            
check(ThriftReadInputProtocol::new(bytes.as_slice()).skip_binary());
+        }
+    }
+
+    struct FragmentedReader<'a>(&'a [u8]);
+
+    impl Read for FragmentedReader<'_> {
+        fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> {
+            let len = buf.len().min(2);
+            self.0.read(&mut buf[..len])
+        }
+    }
+
+    #[test]
+    fn test_read_bytes_owned_complete_and_fragmented() {
+        let large_payload = vec![7; 16 * 1024];
+        for payload in [b"".as_slice(), b"abcde".as_slice(), &large_payload] {
+            let mut data = Vec::new();
+            ThriftCompactOutputProtocol::new(&mut data)
+                .write_bytes(payload)
+                .unwrap();
+            data.push(42);
+            let mut slice = ThriftSliceInputProtocol::new(&data);
+            let mut stream = ThriftReadInputProtocol::new(data.as_slice());
+            let mut fragmented = 
ThriftReadInputProtocol::new(FragmentedReader(&data));
+            assert_eq!(slice.read_bytes_owned().unwrap(), payload);
+            assert_eq!(stream.read_bytes_owned().unwrap(), payload);
+            assert_eq!(fragmented.read_bytes_owned().unwrap(), payload);
+            assert_eq!(slice.read_byte().unwrap(), 42);
+            assert_eq!(stream.read_byte().unwrap(), 42);
+            assert_eq!(fragmented.read_byte().unwrap(), 42);
+        }
+    }
+
+    #[test]
+    fn test_read_bytes_owned_truncated_payload() {
+        for len in [5, 1024 * 1024, i32::MAX as u64] {
+            let mut data = Vec::new();
+            ThriftCompactOutputProtocol::new(&mut data)
+                .write_vlq(len)
+                .unwrap();
+            data.extend_from_slice(b"abc");
+            let mut stream = 
ThriftReadInputProtocol::new(FragmentedReader(&data));
+            assert!(matches!(
+                stream.read_bytes_owned(),
+                Err(ThriftProtocolError::Eof)
+            ));
+        }
+    }
+
+    #[test]
+    fn test_read_bytes_owned_preserves_io_error() {
+        struct FailingReader;
+        impl Read for FailingReader {
+            fn read(&mut self, _: &mut [u8]) -> IoResult<usize> {
+                Err(Error::new(ErrorKind::PermissionDenied, "payload error"))
+            }
+        }
+        let reader = b"\x05ab".as_slice().chain(FailingReader);
+        let mut stream = ThriftReadInputProtocol::new(reader);
+        assert!(
+            matches!(stream.read_bytes_owned(), 
Err(ThriftProtocolError::IO(e)) if e.kind() == ErrorKind::PermissionDenied)
+        );
+    }
+
     #[test]
     fn test_enum_roundtrip() {
         test_roundtrip(Type::BOOLEAN);
diff --git a/parquet/src/schema/types.rs b/parquet/src/schema/types.rs
index 2c078a7515..743ade871c 100644
--- a/parquet/src/schema/types.rs
+++ b/parquet/src/schema/types.rs
@@ -1519,9 +1519,17 @@ fn schema_from_array_helper(
         Some(n) => {
             let repetition = element.repetition_type;
 
-            let mut fields = Vec::with_capacity(usize::try_from(n)?);
+            let num_children = usize::try_from(n)?;
+            if num_children > elements.len() {
+                return Err(general_err!(
+                    "Schema children count {} exceeds remaining schema 
elements {}",
+                    num_children,
+                    elements.len()
+                ));
+            }
+            let mut fields = Vec::with_capacity(num_children);
             let mut next_index = index + 1;
-            for _ in 0..n {
+            for _ in 0..num_children {
                 let child_result = schema_from_array_helper(elements, 
num_elements, next_index)?;
                 next_index = child_result.0;
                 fields.push(child_result.1);
@@ -2811,6 +2819,37 @@ mod tests {
         assert!(result.is_err());
     }
 
+    #[test]
+    fn test_parquet_schema_from_array_rejects_huge_num_children() {
+        let schema = Arc::new(parse_message_type("message schema 
{}").unwrap());
+        let mut buf = schema_to_buf(&schema).unwrap();
+        let mut elements = buf_to_schema_list(&mut buf).unwrap();
+        elements[0].num_children = Some(i32::MAX);
+        let err = parquet_schema_from_array(elements).unwrap_err().to_string();
+        assert!(
+            err.contains("Schema children count 2147483647 exceeds remaining 
schema elements 0"),
+            "{err}"
+        );
+    }
+
+    #[test]
+    fn 
test_parquet_schema_from_array_rejects_children_exceeding_remaining_elements() {
+        let schema = Arc::new(
+            parse_message_type("message schema { REQUIRED group nested { 
REQUIRED INT32 leaf; } }")
+                .unwrap(),
+        );
+        let mut buf = schema_to_buf(&schema).unwrap();
+        let mut elements = buf_to_schema_list(&mut buf).unwrap();
+        // Two children fit in the original three-element array, but only one
+        // element remains after consuming the root and nested group.
+        elements[1].num_children = Some(2);
+        let err = parquet_schema_from_array(elements).unwrap_err().to_string();
+        assert!(
+            err.contains("Schema children count 2 exceeds remaining schema 
elements 1"),
+            "{err}"
+        );
+    }
+
     #[test]
     fn test_parquet_schema_from_array_rejects_negative_num_children() {
         let elements = vec![SchemaElement {

Reply via email to