This is an automated email from the ASF dual-hosted git repository.
github-merge-queue[bot] pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/arrow-rs.git
The following commit(s) were added to refs/heads/main by this push:
new 5681d12c23 fix: check small-crate length and offset arithmetic (#12340)
5681d12c23 is described below
commit 5681d12c23b1e41ee4d3a724e92acb6ce17377d6
Author: RIchard Baah <[email protected]>
AuthorDate: Fri Nov 20 06:07:08 2026 +0000
fix: check small-crate length and offset arithmetic (#12340)
# Which issue does this PR close?
- Part of #12325.
# Rationale for this change
Several small support crates trust externally supplied lengths, offsets,
or counts before narrowing them or using them for allocation. Oversized
inputs can wrap, panic, or request an invalid capacity instead of
returning an error.
# What changes are included in this PR?
- `arrow-integration-testing` converts batch row counts to `i64` and
uses checked addition for `FlightInfo.total_records`.
- `arrow-csv` checks decoder buffer-size arithmetic before resizing.
- `arrow-integration-test` checks narrow JSON integers, offsets, view
ranges, fixed-size binary capacity, and Decimal256 width.
- `arrow-pyarrow` uses fallible reservation for Python iterable length
hints.
This completes the overflow audit for these four small crates.
# Are these changes tested?
The existing crate tests cover the affected decoding and conversion
paths. The new checks are direct checked arithmetic and checked
conversions, so this PR does not add synthetic maximum-size fixtures.
# Are there any significant user-facing changes?
Yes. Invalid or oversized integration JSON that previously truncated
values or panicked now returns `ParseError` or `JsonError`.
---
arrow-csv/src/reader/records.rs | 35 +++++-
arrow-integration-test/src/datatype.rs | 11 +-
arrow-integration-test/src/lib.rs | 120 ++++++++++++++-------
.../flight_server_scenarios/integration_test.rs | 14 ++-
arrow-pyarrow/src/lib.rs | 8 +-
5 files changed, 138 insertions(+), 50 deletions(-)
diff --git a/arrow-csv/src/reader/records.rs b/arrow-csv/src/reader/records.rs
index 1c74201212..72466e5570 100644
--- a/arrow-csv/src/reader/records.rs
+++ b/arrow-csv/src/reader/records.rs
@@ -84,8 +84,26 @@ impl RecordDecoder {
}
// Reserve sufficient capacity in offsets
- self.offsets
- .resize(self.offsets_len + to_read * self.num_columns, 0);
+ let offsets_capacity = to_read
+ .checked_mul(self.num_columns)
+ .and_then(|capacity| self.offsets_len.checked_add(capacity))
+ .ok_or_else(|| ArrowError::CsvError("CSV decoder capacity
overflow".to_string()))?;
+
+ // Validate both allocation layouts before modifying either buffer
+ let data_capacity = to_read
+ .checked_mul(self.num_columns)
+ .and_then(|capacity| capacity.checked_mul(AVERAGE_FIELD_SIZE))
+ .map(|capacity| capacity.max(MIN_CAPACITY))
+ .and_then(|capacity| self.data_len.checked_add(capacity))
+ .ok_or_else(|| ArrowError::CsvError("CSV decoder capacity
overflow".to_string()))?;
+ if std::alloc::Layout::array::<usize>(offsets_capacity).is_err()
+ || std::alloc::Layout::array::<u8>(data_capacity).is_err()
+ {
+ return Err(ArrowError::CsvError(
+ "CSV decoder capacity overflow".to_string(),
+ ));
+ }
+ self.offsets.resize(offsets_capacity, 0);
// The current offset into `input`
let mut input_offset = 0;
@@ -96,9 +114,18 @@ impl RecordDecoder {
loop {
// Reserve necessary space in output data based on best estimate
let remaining_rows = to_read - read;
- let capacity = remaining_rows * self.num_columns *
AVERAGE_FIELD_SIZE;
+ let capacity = remaining_rows
+ .checked_mul(self.num_columns)
+ .and_then(|capacity| capacity.checked_mul(AVERAGE_FIELD_SIZE))
+ .ok_or_else(|| ArrowError::CsvError("CSV decoder capacity
overflow".to_string()))?;
let estimated_data = capacity.max(MIN_CAPACITY);
- self.data.resize(self.data_len + estimated_data, 0);
+ let data_capacity = self
+ .data_len
+ .checked_add(estimated_data)
+ .ok_or_else(|| ArrowError::CsvError("CSV decoder capacity
overflow".to_string()))?;
+ std::alloc::Layout::array::<u8>(data_capacity)
+ .map_err(|_| ArrowError::CsvError("CSV decoder capacity
overflow".to_string()))?;
+ self.data.resize(data_capacity, 0);
// Try to read a record
loop {
diff --git a/arrow-integration-test/src/datatype.rs
b/arrow-integration-test/src/datatype.rs
index 2979e6d7b4..3d67824f25 100644
--- a/arrow-integration-test/src/datatype.rs
+++ b/arrow-integration-test/src/datatype.rs
@@ -7,7 +7,7 @@ use arrow::error::{ArrowError, Result};
use std::sync::Arc;
/// Read a JSON number as an integer of type `T`.
-fn json_int<T: TryFrom<i64>>(what: &str, value: &serde_json::Value) ->
Result<T> {
+pub(crate) fn json_int<T: TryFrom<i64>>(what: &str, value: &serde_json::Value)
-> Result<T> {
let int = value
.as_i64()
.ok_or_else(|| ArrowError::ParseError(format!("Expecting {what} to be
an integer")))?;
@@ -15,6 +15,15 @@ fn json_int<T: TryFrom<i64>>(what: &str, value:
&serde_json::Value) -> Result<T>
.map_err(|_| ArrowError::ParseError(format!("{what} is out of range
for its type: {int}")))
}
+/// Read a JSON number as an unsigned integer of type `T`.
+pub(crate) fn json_uint<T: TryFrom<u64>>(what: &str, value:
&serde_json::Value) -> Result<T> {
+ let int = value
+ .as_u64()
+ .ok_or_else(|| ArrowError::ParseError(format!("Expecting {what} to be
an integer")))?;
+ T::try_from(int)
+ .map_err(|_| ArrowError::ParseError(format!("{what} is out of range
for its type: {int}")))
+}
+
/// Parse a data type from a JSON representation.
pub fn data_type_from_json(json: &serde_json::Value) -> Result<DataType> {
use serde_json::Value;
diff --git a/arrow-integration-test/src/lib.rs
b/arrow-integration-test/src/lib.rs
index 5e6e634d60..c7d5c5570d 100644
--- a/arrow-integration-test/src/lib.rs
+++ b/arrow-integration-test/src/lib.rs
@@ -48,6 +48,8 @@ mod datatype;
mod field;
mod schema;
+use datatype::{json_int, json_uint};
+
pub use datatype::*;
pub use field::*;
pub use schema::*;
@@ -369,9 +371,7 @@ pub fn array_from_json(
.zip(json_col.data.unwrap())
{
match is_valid {
- 1 => b.append_value(value.as_i64().ok_or_else(|| {
- ArrowError::JsonError(format!("Unable to get {value:?}
as int64"))
- })? as i8),
+ 1 => b.append_value(json_int("int8 value", &value)?),
_ => b.append_null(),
}
}
@@ -387,7 +387,7 @@ pub fn array_from_json(
.zip(json_col.data.unwrap())
{
match is_valid {
- 1 => b.append_value(value.as_i64().unwrap() as i16),
+ 1 => b.append_value(json_int("int16 value", &value)?),
_ => b.append_null(),
}
}
@@ -403,7 +403,7 @@ pub fn array_from_json(
.zip(json_col.data.unwrap())
{
match is_valid {
- 1 => b.append_value(value.as_i64().unwrap() as i32),
+ 1 => b.append_value(json_int("int32 value", &value)?),
_ => b.append_null(),
}
}
@@ -420,7 +420,7 @@ pub fn array_from_json(
.zip(json_col.data.unwrap())
{
match is_valid {
- 1 => b.append_value(value.as_i64().unwrap() as i32),
+ 1 => b.append_value(json_int("year-month interval",
&value)?),
_ => b.append_null(),
}
}
@@ -469,17 +469,9 @@ pub fn array_from_json(
DataType::Interval(IntervalUnit::DayTime) => {
let days = map.get("days").unwrap();
let milliseconds =
map.get("milliseconds").unwrap();
-
- match (days, milliseconds) {
- (Value::Number(d), Value::Number(m))
=> {
- let days = d.as_i64().unwrap() as
_;
- let millis = m.as_i64().unwrap()
as _;
- IntervalDayTime::new(days, millis)
- }
- _ => {
- panic!("Unable to parse {value:?}
as interval daytime")
- }
- }
+ let days = json_int("interval days",
days)?;
+ let millis = json_int("interval
milliseconds", milliseconds)?;
+ IntervalDayTime::new(days, millis)
}
_ => panic!("Unable to parse {value:?} as
interval daytime"),
}
@@ -501,7 +493,7 @@ pub fn array_from_json(
.zip(json_col.data.unwrap())
{
match is_valid {
- 1 => b.append_value(value.as_u64().unwrap() as u8),
+ 1 => b.append_value(json_uint("uint8 value", &value)?),
_ => b.append_null(),
}
}
@@ -517,7 +509,7 @@ pub fn array_from_json(
.zip(json_col.data.unwrap())
{
match is_valid {
- 1 => b.append_value(value.as_u64().unwrap() as u16),
+ 1 => b.append_value(json_uint("uint16 value", &value)?),
_ => b.append_null(),
}
}
@@ -533,7 +525,7 @@ pub fn array_from_json(
.zip(json_col.data.unwrap())
{
match is_valid {
- 1 => b.append_value(value.as_u64().unwrap() as u32),
+ 1 => b.append_value(json_uint("uint32 value", &value)?),
_ => b.append_null(),
}
}
@@ -590,8 +582,14 @@ pub fn array_from_json(
Value::Number(days),
Value::Number(nanoseconds),
) => {
- let months = months.as_i64().unwrap() as
i32;
- let days = days.as_i64().unwrap() as i32;
+ let months = json_int(
+ "month-day-nano interval months",
+ &Value::Number(months.clone()),
+ )?;
+ let days = json_int(
+ "month-day-nano interval days",
+ &Value::Number(days.clone()),
+ )?;
let nanoseconds =
nanoseconds.as_i64().unwrap();
IntervalMonthDayNano::new(months, days,
nanoseconds)
}
@@ -710,6 +708,15 @@ pub fn array_from_json(
Ok(Arc::new(b.finish()))
}
DataType::FixedSizeBinary(len) => {
+ let byte_width = usize::try_from(*len).map_err(|_| {
+ ArrowError::JsonError("FixedSizeBinary byte width must be
non-negative".to_string())
+ })?;
+ let capacity =
json_col.count.checked_mul(byte_width).ok_or_else(|| {
+ ArrowError::JsonError("FixedSizeBinary capacity
overflow".to_string())
+ })?;
+ std::alloc::Layout::array::<u8>(capacity).map_err(|_| {
+ ArrowError::JsonError("FixedSizeBinary capacity
overflow".to_string())
+ })?;
let mut b = FixedSizeBinaryBuilder::with_capacity(json_col.count,
*len);
for (is_valid, value) in json_col
.validity
@@ -736,8 +743,8 @@ pub fn array_from_json(
.offset
.unwrap()
.iter()
- .map(|v| v.as_i64().unwrap() as i32)
- .collect();
+ .map(|v| json_int("list offset", v))
+ .collect::<Result<_>>()?;
let list_data = ArrayData::builder(field.data_type().clone())
.len(json_col.count)
.offset(0)
@@ -780,14 +787,14 @@ pub fn array_from_json(
.offset
.unwrap()
.iter()
- .map(|v| v.as_i64().unwrap() as i32)
- .collect();
+ .map(|v| json_int("list view offset", v))
+ .collect::<Result<_>>()?;
let sizes: Vec<i32> = json_col
.size
.unwrap()
.iter()
- .map(|v| v.as_i64().unwrap() as i32)
- .collect();
+ .map(|v| json_int("list view size", v))
+ .collect::<Result<_>>()?;
let list_data = ArrayData::builder(field.data_type().clone())
.len(json_col.count)
.add_buffer(Buffer::from(offsets.to_byte_slice()))
@@ -962,6 +969,11 @@ pub fn array_from_json(
} else {
[0_u8; 32]
};
+ if integer_bytes.len() > bytes.len() {
+ return Err(ArrowError::JsonError(
+ "Decimal256 value exceeds 256
bits".to_string(),
+ ));
+ }
bytes[0..integer_bytes.len()].copy_from_slice(integer_bytes.as_slice());
b.append_value(i256::from_le_bytes(bytes));
}
@@ -980,8 +992,8 @@ pub fn array_from_json(
.offset
.unwrap()
.iter()
- .map(|v| v.as_i64().unwrap() as i32)
- .collect();
+ .map(|v| json_int("map offset", v))
+ .collect::<Result<_>>()?;
let array_data = ArrayData::builder(field.data_type().clone())
.len(json_col.count)
.add_buffer(Buffer::from(offsets.to_byte_slice()))
@@ -1002,7 +1014,13 @@ pub fn array_from_json(
let offset: Option<ScalarBuffer<i32>> = json_col
.offset
- .map(|offsets| offsets.iter().map(|v| v.as_i64().unwrap() as
i32).collect());
+ .map(|offsets| {
+ offsets
+ .iter()
+ .map(|v| json_int("union offset", v))
+ .collect::<Result<_>>()
+ })
+ .transpose()?;
let mut children = Vec::with_capacity(fields.len());
for ((_, field), col) in
fields.iter().zip(json_col.children.unwrap()) {
@@ -1028,16 +1046,26 @@ pub fn array_from_json(
builder.append_null();
} else {
let view_obj = view.as_object().unwrap();
- let size = view_obj["SIZE"].as_u64().unwrap() as usize;
+ let size: usize = json_uint("view size",
&view_obj["SIZE"])?;
// Check for INLINED key presence - inlined if SIZE <= 12
if let Some(inlined) = view_obj.get("INLINED") {
builder.append_value(inlined.as_str().unwrap());
} else {
// Reference to variadic buffer
- let buffer_index =
view_obj["BUFFER_INDEX"].as_u64().unwrap() as usize;
- let offset = view_obj["OFFSET"].as_u64().unwrap() as
usize;
- let buffer_data =
hex::decode(&variadic_buffers[buffer_index]).unwrap();
- let s =
std::str::from_utf8(&buffer_data[offset..offset + size]).unwrap();
+ let buffer_index: usize =
+ json_uint("view buffer index",
&view_obj["BUFFER_INDEX"])?;
+ let offset: usize = json_uint("view offset",
&view_obj["OFFSET"])?;
+ let end = offset.checked_add(size).ok_or_else(|| {
+ ArrowError::JsonError("View offset
overflow".to_string())
+ })?;
+ let buffer =
variadic_buffers.get(buffer_index).ok_or_else(|| {
+ ArrowError::JsonError("View buffer index out of
bounds".to_string())
+ })?;
+ let buffer_data = hex::decode(buffer).unwrap();
+ let data = buffer_data.get(offset..end).ok_or_else(|| {
+ ArrowError::JsonError("View range out of
bounds".to_string())
+ })?;
+ let s = std::str::from_utf8(data).unwrap();
builder.append_value(s);
}
}
@@ -1058,17 +1086,27 @@ pub fn array_from_json(
builder.append_null();
} else {
let view_obj = view.as_object().unwrap();
- let size = view_obj["SIZE"].as_u64().unwrap() as usize;
+ let size: usize = json_uint("view size",
&view_obj["SIZE"])?;
// Check for INLINED key presence - inlined if SIZE <= 12
if let Some(inlined) = view_obj.get("INLINED") {
let data =
hex::decode(inlined.as_str().unwrap()).unwrap();
builder.append_value(&data);
} else {
// Reference to variadic buffer
- let buffer_index =
view_obj["BUFFER_INDEX"].as_u64().unwrap() as usize;
- let offset = view_obj["OFFSET"].as_u64().unwrap() as
usize;
- let buffer_data =
hex::decode(&variadic_buffers[buffer_index]).unwrap();
- builder.append_value(&buffer_data[offset..offset +
size]);
+ let buffer_index: usize =
+ json_uint("view buffer index",
&view_obj["BUFFER_INDEX"])?;
+ let offset: usize = json_uint("view offset",
&view_obj["OFFSET"])?;
+ let end = offset.checked_add(size).ok_or_else(|| {
+ ArrowError::JsonError("View offset
overflow".to_string())
+ })?;
+ let buffer =
variadic_buffers.get(buffer_index).ok_or_else(|| {
+ ArrowError::JsonError("View buffer index out of
bounds".to_string())
+ })?;
+ let buffer_data = hex::decode(buffer).unwrap();
+ let data = buffer_data.get(offset..end).ok_or_else(|| {
+ ArrowError::JsonError("View range out of
bounds".to_string())
+ })?;
+ builder.append_value(data);
}
}
}
diff --git
a/arrow-integration-testing/src/flight_server_scenarios/integration_test.rs
b/arrow-integration-testing/src/flight_server_scenarios/integration_test.rs
index 526632f024..2ff0c54790 100644
--- a/arrow-integration-testing/src/flight_server_scenarios/integration_test.rs
+++ b/arrow-integration-testing/src/flight_server_scenarios/integration_test.rs
@@ -60,6 +60,16 @@ struct IntegrationDataset {
chunks: Vec<RecordBatch>,
}
+fn total_record_count(chunks: &[RecordBatch]) -> Result<i64, Status> {
+ chunks.iter().try_fold(0_i64, |total, chunk| {
+ let rows = i64::try_from(chunk.num_rows())
+ .map_err(|_| Status::out_of_range("Flight record count exceeds
i64::MAX"))?;
+ total
+ .checked_add(rows)
+ .ok_or_else(|| Status::out_of_range("Flight record count exceeds
i64::MAX"))
+ })
+}
+
/// Flight service implementation for integration testing
#[derive(Clone, Default)]
pub struct FlightServiceImpl {
@@ -190,7 +200,7 @@ impl FlightService for FlightServiceImpl {
let endpoint = self.endpoint_from_path(&path[0]);
- let total_records: usize = flight.chunks.iter().map(|chunk|
chunk.num_rows()).sum();
+ let total_records = total_record_count(&flight.chunks)?;
let options = arrow::ipc::writer::IpcWriteOptions::default();
let message = SchemaAsIpc::new(&flight.schema, &options)
@@ -205,7 +215,7 @@ impl FlightService for FlightServiceImpl {
schema,
flight_descriptor: Some(descriptor.clone()),
endpoint: vec![endpoint],
- total_records: total_records as i64,
+ total_records,
total_bytes: -1,
ordered: false,
app_metadata: vec![].into(),
diff --git a/arrow-pyarrow/src/lib.rs b/arrow-pyarrow/src/lib.rs
index 150338920c..09d03a6d63 100644
--- a/arrow-pyarrow/src/lib.rs
+++ b/arrow-pyarrow/src/lib.rs
@@ -77,7 +77,7 @@ use arrow_array::{
};
use arrow_data::ArrayData;
use arrow_schema::{ArrowError, DataType, Field, Schema, SchemaRef};
-use pyo3::exceptions::{PyTypeError, PyValueError};
+use pyo3::exceptions::{PyMemoryError, PyTypeError, PyValueError};
use pyo3::ffi::Py_uintptr_t;
use pyo3::prelude::*;
use pyo3::sync::PyOnceLock;
@@ -390,7 +390,11 @@ impl<T: FromPyArrow> FromPyArrow for Vec<T> {
);
fn from_pyarrow_bound(value: &Bound<PyAny>) -> PyResult<Self> {
- let mut v = Vec::with_capacity(value.len().unwrap_or(0));
+ let mut v = Vec::new();
+ if let Ok(len) = value.len() {
+ v.try_reserve(len)
+ .map_err(|e| PyMemoryError::new_err(e.to_string()))?;
+ }
for item in value.try_iter()? {
v.push(T::from_pyarrow_bound(&item?)?);
}