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

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


The following commit(s) were added to refs/heads/main by this push:
     new 75ac84b2 fix(parquet/file): reject encrypted row group and column 
ordinals above 32767 (#1645)
75ac84b2 is described below

commit 75ac84b21d37f36519d469b69103767284aba7cf
Author: Harrison Crosse <[email protected]>
AuthorDate: Fri Nov 20 12:29:54 2026 -0500

    fix(parquet/file): reject encrypted row group and column ordinals above 
32767 (#1645)
    
    ### Rationale for this change
    
    arrow-go writes encrypted row group and column ordinals above 32767 that
    Arrow C++ refuses to read, and arrow-go's own reader also rejects those
    columns.
    
    ### What changes are included in this PR?
    
    `AppendRowGroupChecked` and `AppendBufferedRowGroupChecked` refuse the
    32769th encrypted row group and leave the writer usable, so `Close`
    still writes a valid file with the first 32768 row groups as Arrow C++
    does. `pqarrow`'s `FileWriter.WriteTable` closes on error, so it now
    leaves that file and returns the error.
    
    `NewParquetWriterWithError` rejects encrypted columns at index 32768 or
    above before writing. Unencrypted files and columns are not limited. The
    reader is unchanged.
    
    ### Are these changes tested?
    
    Yes. I added tests for rejecting ordinals above the limit, closing after
    rejection, the 32768 boundary and unencrypted controls.
    
    ### Are there any user-facing changes?
    
    Yes. Encrypted row group and column ordinals above 32767 are rejected.
    Writes of more than 32768 encrypted row groups, which arrow-go could
    previously read back itself, now fail instead of writing wrapped
    ordinals. There is no API change.
    
    Closes #1644.
---
 parquet/file/file_writer.go      |  42 ++++++++++--
 parquet/file/file_writer_test.go | 145 +++++++++++++++++++++++++++++++++++++++
 2 files changed, 182 insertions(+), 5 deletions(-)

diff --git a/parquet/file/file_writer.go b/parquet/file/file_writer.go
index c82bbfbd..d07d08b9 100644
--- a/parquet/file/file_writer.go
+++ b/parquet/file/file_writer.go
@@ -21,6 +21,7 @@ import (
        "errors"
        "fmt"
        "io"
+       "math"
 
        "github.com/apache/arrow-go/v18/parquet"
        "github.com/apache/arrow-go/v18/parquet/internal/encryption"
@@ -97,7 +98,8 @@ func NewParquetWriter(w io.Writer, sc *schema.GroupNode, opts 
...WriteOption) *W
 // An error is returned if the initial write of the parquet magic header to
 // the underlying sink fails or short-writes, which can happen when the
 // sink is a flaky or network-attached writer (for example, a cloud-storage
-// upload writer).
+// upload writer). An error is also returned if the file is encrypted and
+// an encrypted column has an index above 32767.
 func NewParquetWriterWithError(w io.Writer, sc *schema.GroupNode, opts 
...WriteOption) (*Writer, error) {
        config := &writerConfig{}
        for _, o := range opts {
@@ -180,11 +182,13 @@ func (fw *Writer) AppendBufferedRowGroup() 
BufferedRowGroupWriter {
 }
 
 // AppendBufferedRowGroupChecked is the error-returning form of
-// AppendBufferedRowGroup.
+// AppendBufferedRowGroup. An encrypted file cannot have more than 32768 row
+// groups. Appending another returns an error and leaves the writer usable, so
+// it can still be closed.
 func (fw *Writer) AppendBufferedRowGroupChecked() (BufferedRowGroupWriter, 
error) {
        rgw, err := fw.appendRowGroup(true)
        if err != nil {
-               return nil, fw.recordError(err)
+               return nil, fw.recordAppendError(err)
        }
        return rgw, nil
 }
@@ -206,11 +210,13 @@ func (fw *Writer) AppendRowGroup() SerialRowGroupWriter {
        return rgw
 }
 
-// AppendRowGroupChecked is the error-returning form of AppendRowGroup.
+// AppendRowGroupChecked is the error-returning form of AppendRowGroup. An
+// encrypted file cannot have more than 32768 row groups. Appending another
+// returns an error and leaves the writer usable, so it can still be closed.
 func (fw *Writer) AppendRowGroupChecked() (SerialRowGroupWriter, error) {
        rgw, err := fw.appendRowGroup(false)
        if err != nil {
-               return nil, fw.recordError(err)
+               return nil, fw.recordAppendError(err)
        }
        return rgw, nil
 }
@@ -220,6 +226,13 @@ func (fw *Writer) appendRowGroup(buffered bool) 
(*rowGroupWriter, error) {
                return nil, fw.writeErr
        }
 
+       // The module AAD stores row group ordinals as two byte signed integers.
+       // The open row group must stay open here, because Close closes it and
+       // closing it twice would count its rows twice.
+       if fw.fileEncryptor != nil && fw.rowGroups > math.MaxInt16 {
+               return nil, errEncryptedRowGroupLimit
+       }
+
        if fw.rowGroupWriter != nil {
                if err := fw.rowGroupWriter.Close(); err != nil {
                        return nil, err
@@ -266,6 +279,14 @@ func (fw *Writer) startFile() error {
                        }
                }
 
+               // The module AAD stores column ordinals as two byte signed 
integers,
+               // and the reader refuses an encrypted column above index 32767.
+               for i := math.MaxInt16 + 1; i < fw.Schema.NumColumns(); i++ {
+                       if path := fw.Schema.Column(i).Path(); 
encryptionProps.ColumnEncryptionProperties(path) != nil {
+                               return fmt.Errorf("parquet: cannot encrypt 
column %q at index %d, encrypted columns must have an index of at most %d", 
path, i, math.MaxInt16)
+                       }
+               }
+
                fw.fileEncryptor = encryption.NewFileEncryptor(encryptionProps, 
fw.props.Allocator())
                fw.metadata.SetFileEncryptor(fw.fileEncryptor)
                if encryptionProps.EncryptedFooter() {
@@ -327,6 +348,17 @@ func (fw *Writer) AppendKeyValueMetadata(key string, value 
string) error {
        return fw.metadata.AppendKeyValueMetadata(key, value)
 }
 
+var errEncryptedRowGroupLimit = errors.New("parquet: encrypted files cannot 
have more than 32768 row groups")
+
+// recordAppendError does not record the row group limit, which refuses the
+// append without invalidating the row groups already written.
+func (fw *Writer) recordAppendError(err error) error {
+       if errors.Is(err, errEncryptedRowGroupLimit) {
+               return err
+       }
+       return fw.recordError(err)
+}
+
 func (fw *Writer) recordError(err error) error {
        if fw.writeErr == nil {
                fw.writeErr = err
diff --git a/parquet/file/file_writer_test.go b/parquet/file/file_writer_test.go
index a111a468..a7097715 100644
--- a/parquet/file/file_writer_test.go
+++ b/parquet/file/file_writer_test.go
@@ -1676,6 +1676,151 @@ func TestPqarrowNewFileWriter_PropagatesShortWrite(t 
*testing.T) {
        require.Contains(t, err.Error(), "short write of magic number")
 }
 
+const (
+       encryptedOrdinalLimit = math.MaxInt16 + 1
+       ordinalLimitKey       = "0123456789012345"
+)
+
+func encryptionOpt(columns ...string) parquet.WriterProperty {
+       var opts []parquet.EncryptOption
+       if len(columns) > 0 {
+               cols := parquet.ColumnPathToEncryptionPropsMap{}
+               for _, c := range columns {
+                       cols[c] = parquet.NewColumnEncryptionProperties(c)
+               }
+               opts = append(opts, parquet.WithEncryptedColumns(cols))
+       }
+       return 
parquet.WithEncryptionProperties(parquet.NewFileEncryptionProperties(ordinalLimitKey,
 opts...))
+}
+
+func newWideSchema(t *testing.T, n int) *schema.GroupNode {
+       t.Helper()
+       fields := make(schema.FieldList, n)
+       for i := range fields {
+               fields[i] = schema.NewInt32Node("c"+strconv.Itoa(i), 
parquet.Repetitions.Required, -1)
+       }
+       sc, err := schema.NewGroupNode("schema", parquet.Repetitions.Required, 
fields, -1)
+       require.NoError(t, err)
+       return sc
+}
+
+func TestEncryptedRowGroupLimit(t *testing.T) {
+       sc := newSingleColumnSchema(t)
+
+       for _, buffered := range []bool{false, true} {
+               name := "serial row group after the limit is refused and Close 
writes the rest"
+               if buffered {
+                       name = "buffered row group after the limit is refused 
and Close writes the rest"
+               }
+               t.Run(name, func(t *testing.T) {
+                       mem := 
memory.NewCheckedAllocator(memory.DefaultAllocator)
+                       props := 
parquet.NewWriterProperties(parquet.WithAllocator(mem),
+                               parquet.WithDataPageSize(1), 
parquet.WithBatchSize(1), encryptionOpt())
+                       var buf bytes.Buffer
+                       w, err := file.NewParquetWriterWithError(&buf, sc, 
file.WithWriterProps(props))
+                       require.NoError(t, err)
+
+                       for range encryptedOrdinalLimit - 1 {
+                               rgw, err := w.AppendRowGroupChecked()
+                               require.NoError(t, err)
+                               cw, err := rgw.NextColumn()
+                               require.NoError(t, err)
+                               _, err = 
cw.(*file.Int32ColumnChunkWriter).WriteBatch([]int32{1}, nil, nil)
+                               require.NoError(t, err)
+                       }
+
+                       // The last allowed row group holds flushed pages and a 
dictionary
+                       // that only Close releases.
+                       var cw file.ColumnChunkWriter
+                       if buffered {
+                               rgw, err := w.AppendBufferedRowGroupChecked()
+                               require.NoError(t, err)
+                               cw, err = rgw.Column(0)
+                               require.NoError(t, err)
+                       } else {
+                               rgw, err := w.AppendRowGroupChecked()
+                               require.NoError(t, err)
+                               cw, err = rgw.NextColumn()
+                               require.NoError(t, err)
+                       }
+                       _, err = 
cw.(*file.Int32ColumnChunkWriter).WriteBatch([]int32{1, 2, 3}, nil, nil)
+                       require.NoError(t, err)
+
+                       if buffered {
+                               _, err = w.AppendBufferedRowGroupChecked()
+                       } else {
+                               _, err = w.AppendRowGroupChecked()
+                       }
+                       require.ErrorContains(t, err, "more than 32768 row 
groups")
+                       require.Equal(t, encryptedOrdinalLimit, 
w.NumRowGroups())
+
+                       require.NoError(t, w.Close())
+                       assert.Equal(t, encryptedOrdinalLimit+2, w.NumRows())
+                       mem.AssertSize(t, 0)
+
+                       rp := parquet.NewReaderProperties(nil)
+                       rp.FileDecryptProps = 
parquet.NewFileDecryptionProperties(parquet.WithFooterKey(ordinalLimitKey))
+                       r, err := 
file.NewParquetReader(bytes.NewReader(buf.Bytes()), file.WithReadProps(rp))
+                       require.NoError(t, err)
+                       assert.Equal(t, encryptedOrdinalLimit, r.NumRowGroups())
+                       assert.EqualValues(t, encryptedOrdinalLimit+2, 
r.NumRows())
+               })
+       }
+
+       t.Run("unencrypted files are not limited", func(t *testing.T) {
+               props := 
parquet.NewWriterProperties(parquet.WithDictionaryDefault(false))
+               w, err := file.NewParquetWriterWithError(io.Discard, sc, 
file.WithWriterProps(props))
+               require.NoError(t, err)
+               for range encryptedOrdinalLimit + 1 {
+                       rgw, err := w.AppendRowGroupChecked()
+                       require.NoError(t, err)
+                       cw, err := rgw.NextColumn()
+                       require.NoError(t, err)
+                       _, err = 
cw.(*file.Int32ColumnChunkWriter).WriteBatch([]int32{1}, nil, nil)
+                       require.NoError(t, err)
+               }
+               require.NoError(t, w.Close())
+       })
+}
+
+func TestEncryptedColumnLimit(t *testing.T) {
+       newWriter := func(w io.Writer, columns int, opts 
...parquet.WriterProperty) (*file.Writer, error) {
+               return file.NewParquetWriterWithError(w, newWideSchema(t, 
columns),
+                       
file.WithWriterProps(parquet.NewWriterProperties(opts...)))
+       }
+
+       t.Run("last allowed encrypted column is accepted", func(t *testing.T) {
+               w, err := newWriter(io.Discard, encryptedOrdinalLimit, 
encryptionOpt())
+               require.NoError(t, err)
+               require.NoError(t, w.Close())
+       })
+
+       t.Run("encrypted column after the limit is rejected before any write", 
func(t *testing.T) {
+               var buf bytes.Buffer
+               w, err := newWriter(&buf, encryptedOrdinalLimit+1, 
encryptionOpt())
+               require.ErrorContains(t, err, "cannot encrypt column")
+               require.Nil(t, w)
+               require.Zero(t, buf.Len())
+       })
+
+       t.Run("only the encrypted columns are checked", func(t *testing.T) {
+               w, err := newWriter(io.Discard, encryptedOrdinalLimit+1, 
encryptionOpt("c0"))
+               require.NoError(t, err)
+               require.NoError(t, w.Close())
+       })
+
+       t.Run("unencrypted files are not limited", func(t *testing.T) {
+               w, err := newWriter(io.Discard, encryptedOrdinalLimit+1)
+               require.NoError(t, err)
+               require.NoError(t, w.Close())
+       })
+
+       t.Run("an encrypted column inside the wide range is rejected", func(t 
*testing.T) {
+               _, err := newWriter(io.Discard, encryptedOrdinalLimit+3, 
encryptionOpt("c32769"))
+               require.ErrorContains(t, err, `cannot encrypt column "c32769"`)
+       })
+}
+
 type byteLimitSink struct {
        buf   bytes.Buffer
        limit int

Reply via email to