Copilot commented on code in PR #3862:
URL: https://github.com/apache/avro/pull/3862#discussion_r3567381488


##########
lang/ruby/lib/avro/io.rb:
##########
@@ -481,11 +546,14 @@ def skip_union(writers_schema, decoder)
       end

Review Comment:
   DatumReader#skip_union indexes `writers_schema.schemas` with the decoded 
branch index without bounds checking. Since Ruby allows negative indexing, 
malformed data (e.g., -1) can silently select the wrong branch and skip the 
wrong amount, desynchronizing the decoder. Add the same bounds check used in 
read_union and raise AvroError on invalid indices.



##########
lang/ruby/lib/avro/io.rb:
##########
@@ -103,10 +120,43 @@ def read_string
       end
 
       def read(len)
-        # Read n bytes
+        # Read n bytes. Reject a declared length that exceeds the bytes
+        # actually remaining before allocating for it, to guard against an
+        # out-of-memory attack from a malicious or truncated input. The check
+        # is only applied to larger reads; smaller reads and stream readers 
that
+        # cannot report their size fall back to reading directly.
+        if len < 0
+          # A negative length would make IO#read return the rest of the stream,
+          # which bypasses the size check and can allocate without bound.
+          raise AvroError, "Cannot read a negative number of bytes: #{len}"
+        end
+        if len > MAX_UNCHECKED_READ
+          remaining = bytes_remaining
+          if remaining && len > remaining
+            raise AvroError, "Cannot read #{len} bytes, only #{remaining} 
remaining"
+          end
+        end
         @reader.read(len)
       end

Review Comment:
   BinaryDecoder#read can return a short string (or nil) when the underlying IO 
is truncated or performs partial reads. For bytes/string/fixed, that would 
silently accept corrupted/truncated data and can undermine the intended “reject 
before allocating” hardening for lengths <= MAX_UNCHECKED_READ. Consider 
raising when fewer than `len` bytes are actually read.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to