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

kou pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/arrow.git


The following commit(s) were added to refs/heads/main by this push:
     new 7299fdccf5a GH-54025: [C++][Engine] Validate Substrait emit 
output_mapping indices (#53521)
7299fdccf5a is described below

commit 7299fdccf5add00e845c20cba48cce75b43bec5e
Author: Nayana-Naik73 <[email protected]>
AuthorDate: Sun Nov 8 06:52:21 2026 +0530

    GH-54025: [C++][Engine] Validate Substrait emit output_mapping indices 
(#53521)
    
    ### Rationale for this change
    
    While reading the Substrait relation conversion I noticed that 
`GetEmitInfo` and `ProcessEmitProject` take the `emit.output_mapping` values 
straight from the plan and use them to index `input_schema->field(map_id)` and 
the project expression vector, with no range check. `Schema::field` only has 
debug assertions, so a deserialised plan carrying an out-of-bounds or negative 
mapping index reads past the end of those vectors (and in the project case 
moves an out-of-bounds `compute::Expres [...]
    
    ### What changes are included in this PR?
    
    A range check on `map_id` in both `GetEmitInfo` and `ProcessEmitProject` 
that returns `Status::Invalid` for negative or out-of-bounds indices, matching 
the existing check in `ProcessExtensionEmit`. For a ProjectRel the emit input 
schema and the project expression vector are the same length by construction 
(input columns are prefixed as passthrough refs), so the single `num_fields()` 
bound covers both accesses.
    
    ### Are these changes tested?
    
    Yes. Added ReadRelWithOutOfBoundsEmit and ProjectRelWithOutOfBoundsEmit to 
serde_test.cc, which deserialise plans with negative and out-of-range 
outputMapping indices through the generic emit path (ReadRel) and the 
ProjectRel path and expect Status::Invalid. Without the fix both tests hit the 
Schema::field DCHECK in a debug build. The existing emit round-trip tests still 
cover the valid-index path.
    
    ### Are there any user-facing changes?
    
    Deserialising a Substrait plan whose emit `output_mapping` contains a 
negative or out-of-range index now returns `Status::Invalid` rather than 
reading out of bounds. Valid plans are unaffected.
    
    **This PR contains a "Critical Fix".** It prevents an out-of-bounds read 
(and an out-of-bounds object move) when converting an untrusted Substrait plan 
with a malformed emit `output_mapping`.
    
    ### Was AI used for this PR?
    
    In accordance to the [AI generation 
guidelines](https://arrow.apache.org/docs/dev/developers/overview.html#ai-generated-code),
 please disclose below whether and how AI was used in this PR.
    
    **PR code and description written by:**
    
    - [ ] Human
    - [x] AI
    
    **Reviewed before submission by:**
    
    - [x] Human
    - [ ] AI
    - [ ] Not reviewed
    
    * GitHub Issue: #54025
    
    Authored-by: Nayana Naik <[email protected]>
    Signed-off-by: Sutou Kouhei <[email protected]>
---
 .../arrow/engine/substrait/relation_internal.cc    |  6 ++
 cpp/src/arrow/engine/substrait/serde_test.cc       | 68 ++++++++++++++++++++++
 2 files changed, 74 insertions(+)

diff --git a/cpp/src/arrow/engine/substrait/relation_internal.cc 
b/cpp/src/arrow/engine/substrait/relation_internal.cc
index d8d77fa800c..55ca899680e 100644
--- a/cpp/src/arrow/engine/substrait/relation_internal.cc
+++ b/cpp/src/arrow/engine/substrait/relation_internal.cc
@@ -85,6 +85,9 @@ Result<EmitInfo> GetEmitInfo(const RelMessage& rel,
   FieldVector emit_fields(emit_size);
   for (int i = 0; i < emit_size; i++) {
     int32_t map_id = emit.output_mapping(i);
+    if (map_id < 0 || map_id >= input_schema->num_fields()) {
+      return Status::Invalid("Out of bounds emit index ", map_id);
+    }
     proj_field_refs[i] = compute::field_ref(FieldRef(map_id));
     emit_fields[i] = input_schema->field(map_id);
   }
@@ -111,6 +114,9 @@ Result<DeclarationInfo> ProcessEmitProject(
         std::vector<compute::Expression> emit_proj_exprs(emit_size);
         for (int i = 0; i < emit_size; i++) {
           int32_t map_id = emit.output_mapping(i);
+          if (map_id < 0 || map_id >= input_schema->num_fields()) {
+            return Status::Invalid("Out of bounds emit index ", map_id);
+          }
           emit_fields[i] = input_schema->field(map_id);
           emit_proj_exprs[i] = std::move(proj_options.expressions[map_id]);
         }
diff --git a/cpp/src/arrow/engine/substrait/serde_test.cc 
b/cpp/src/arrow/engine/substrait/serde_test.cc
index 31187637983..8c3f5ca6987 100644
--- a/cpp/src/arrow/engine/substrait/serde_test.cc
+++ b/cpp/src/arrow/engine/substrait/serde_test.cc
@@ -3147,6 +3147,74 @@ TEST(SubstraitRoundTrip, ReadRelWithEmit) {
                        /*include_columns=*/{}, conversion_options);
 }
 
+void CheckInvalidEmitIndex(const std::string& rel_json) {
+  std::string substrait_json = R"({
+  "version": { "major_number": 9999, "minor_number": 9999, "patch_number": 
9999 },
+  "relations": [{
+    "rel": )" + rel_json + R"(
+  }]
+  })";
+
+  ASSERT_OK_AND_ASSIGN(auto buf,
+                       internal::SubstraitFromJSON("Plan", substrait_json,
+                                                   
/*ignore_unknown_fields=*/false));
+  auto dummy_schema =
+      schema({field("A", int32()), field("B", int32()), field("C", int32())});
+  ConversionOptions conversion_options;
+  conversion_options.named_table_provider =
+      AlwaysProvideSameTable(TableFromJSON(dummy_schema, {"[[1, 2, 3]]"}));
+  std::shared_ptr<ExtensionIdRegistry> sp_ext_id_reg = 
MakeExtensionIdRegistry();
+  ExtensionIdRegistry* ext_id_reg = sp_ext_id_reg.get();
+  ExtensionSet ext_set(ext_id_reg);
+  EXPECT_THAT(
+      DeserializePlans(
+          *buf, [] { return kNullConsumer; }, ext_id_reg, &ext_set, 
conversion_options),
+      Raises(StatusCode::Invalid, HasSubstr("Out of bounds emit index")));
+}
+
+TEST(Substrait, ReadRelWithOutOfBoundsEmit) {
+  for (const char* mapping : {"[0, 3]", "[-1, 1]"}) {
+    ARROW_SCOPED_TRACE("outputMapping: ", mapping);
+    CheckInvalidEmitIndex(R"({
+      "read": {
+        "common": {"emit": {"outputMapping": )" +
+                          std::string(mapping) + R"(}},
+        "base_schema": {
+          "names": ["A", "B", "C"],
+          "struct": {"types": [{"i32": {}}, {"i32": {}}, {"i32": {}}]}
+        },
+        "namedTable": {"names": ["A"]}
+      }
+    })");
+  }
+}
+
+TEST(Substrait, ProjectRelWithOutOfBoundsEmit) {
+  // The project emits the 3 input fields plus 1 expression, so 4 is out of 
range
+  for (const char* mapping : {"[0, 4]", "[-1, 3]"}) {
+    ARROW_SCOPED_TRACE("outputMapping: ", mapping);
+    CheckInvalidEmitIndex(R"({
+      "project": {
+        "common": {"emit": {"outputMapping": )" +
+                          std::string(mapping) + R"(}},
+        "expressions": [
+          {"selection": {"directReference": {"structField": {"field": 0}},
+                         "rootReference": {}}}
+        ],
+        "input": {
+          "read": {
+            "base_schema": {
+              "names": ["A", "B", "C"],
+              "struct": {"types": [{"i32": {}}, {"i32": {}}, {"i32": {}}]}
+            },
+            "namedTable": {"names": ["A"]}
+          }
+        }
+      }
+    })");
+  }
+}
+
 TEST(SubstraitRoundTrip, FilterRelWithEmit) {
   auto dummy_schema = schema({field("A", int32()), field("B", int32()),
                               field("C", int32()), field("D", int32())});

Reply via email to