You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@avro.apache.org by "iemejia (via GitHub)" <gi...@apache.org> on 2026/07/11 21:20:20 UTC

[PR] AVRO-4294: [c++] Validate available bytes before allocating for length-prefixed values [avro]

iemejia opened a new pull request, #3859:
URL: https://github.com/apache/avro/pull/3859

   ## What is the purpose of the change
   
   A `bytes` or `string` value is encoded as a length prefix followed by that many bytes of data, and an `array` or `map` block is encoded as an element count followed by that many items. A malicious or truncated input can declare a very large length or count while carrying little or no actual data, which causes a correspondingly large allocation before the shortfall is noticed.
   
   This applies the equivalent of the Java SDK fix [AVRO-4241](https://issues.apache.org/jira/browse/AVRO-4241) to the C++ SDK: when the source can report how many bytes remain, a declared length (or a collection block count) that exceeds the bytes actually available is rejected before allocating for it. The collection check uses the minimum on-wire size of the element schema, so a zero-byte element type (such as `null`) is never falsely rejected. Sources that cannot report their remaining size are unaffected.
   
   Adds `remainingBytes()` to `InputStream` (default -1) overridden by the memory input streams and exposed via `StreamReader`, and `bytesRemaining()` to the `Decoder` interface, overridden by `BinaryDecoder` and forwarded by the validating and resolving decoders. `decodeString`/`decodeBytes` and `GenericReader`'s array/map decoding consult it. The collection check is skipped under schema resolution, where the datum (reader) type may be larger than the wire (writer) type.
   
   This is a sub-task of [AVRO-4292](https://issues.apache.org/jira/browse/AVRO-4292) and resolves [AVRO-4294](https://issues.apache.org/jira/browse/AVRO-4294).
   
   ## Verifying this change
   
   This change added tests and can be verified as follows:
   
   - Added `lang/c++/test/AvailableBytesTests.cc` covering over-limit `string`/`bytes`/`array`/`map` rejection, within-limit values, and an array of nulls that must not be falsely rejected.
   - Run: `cd lang/c++ && mkdir build && cd build && cmake .. && make && ctest`
   
   ## Documentation
   
   - Does this pull request introduce a new feature? (no — hardening / robustness)
   - If yes, how is the feature documented? (not applicable)
   


-- 
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: dev-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Validate available bytes before allocating for length-prefixed values [avro]

Posted by "iemejia (via GitHub)" <gi...@apache.org>.
iemejia commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3565836923


##########
lang/c++/include/avro/Stream.hh:
##########
@@ -345,6 +356,26 @@ struct StreamReader {
         return next_ != end_ || fill();
     }
 
+    /**
+     * Returns the number of bytes still available to be read: those already
+     * buffered in this reader plus whatever the underlying stream reports as
+     * remaining. Returns a negative value when the underlying stream cannot
+     * report its remaining size.
+     */
+    int64_t remainingBytes() const {
+        if (in_ == nullptr) {
+            return -1;
+        }
+        int64_t streamRemaining = in_->remainingBytes();
+        if (streamRemaining < 0) {
+            return -1;
+        }
+        // end_ - next_ is the data already buffered in this reader; it is added
+        // to what the underlying stream still has. The addition promotes the
+        // pointer difference to int64_t.
+        return (end_ - next_) + streamRemaining;
+    }

Review Comment:
   Good catch. Fixed in 83b3b7137a: the buffered-byte count is now computed as (next_ != nullptr) ? (end_ - next_) : 0, so the pointer subtraction is skipped when next_/end_ are both null (right after init()/reset(), before any fill). Added testBytesRemainingRightAfterInit that calls bytesRemaining() immediately after init() on a BinaryDecoder.



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Validate available bytes before allocating for length-prefixed values [avro]

Posted by "iemejia (via GitHub)" <gi...@apache.org>.
iemejia commented on PR #3859:
URL: https://github.com/apache/avro/pull/3859#issuecomment-4951284176

   This PR now also includes the collection block-count cap for [c++], so it is the single complete fix for collection allocation DoS in this SDK. In addition to validating available bytes before allocating length-prefixed values, it bounds the number of array/map items per block:
   
   - a heap-aware cap for zero-byte-element collections (e.g. `array<null>`), which otherwise bypass the available-bytes check because each element reads 0 bytes;
   - a structural cap for all collections;
   - bounded skip paths so projection/skip cannot loop unboundedly.
   
   With this, the standalone collection-limit change for [c++] (AVRO-4278, #3849) is redundant and is being closed as superseded by this PR.


-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Bound allocation when decoding length-prefixed values and collections [avro]

Posted by "Gerrit0 (via GitHub)" <gi...@apache.org>.
Gerrit0 commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3566478995


##########
lang/c++/impl/BinaryDecoder.cc:
##########
@@ -19,12 +19,28 @@
 #include "Decoder.hh"
 #include "Exception.hh"
 #include "Zigzag.hh"
+#include <cstdlib>
 #include <memory>
 
 namespace avro {
 
 using std::make_shared;
 
+// Structural cap on the number of elements to skip in an array or map. Mirrors
+// the read-path limit in Generic.cc; AVRO_MAX_COLLECTION_ITEMS, when a
+// non-negative integer, overrides it.
+static int64_t maxCollectionStructural() {
+    const char *env = std::getenv("AVRO_MAX_COLLECTION_ITEMS");
+    if (env != nullptr && *env != '\0') {
+        char *end = nullptr;
+        long long value = std::strtoll(env, &end, 10);
+        if (*end == '\0' && value >= 0) {
+            return static_cast<int64_t>(value);
+        }
+    }
+    return 2147483639;

Review Comment:
   This should use the named constant rather than duplicating an arbitrary number



##########
lang/c++/impl/Generic.cc:
##########
@@ -25,6 +26,86 @@ using std::ostringstream;
 using std::string;
 using std::vector;
 
+// Minimum number of bytes a single value of the given schema node can occupy on
+// the wire. Used to reject an array/map block count that could not be backed by
+// the bytes remaining. A type that can encode to zero bytes (null) returns 0,
+// which disables the collection check for it (so an array of nulls is not
+// falsely rejected). A depth limit breaks self-referencing (symbolic) schemas.
+static int64_t minBytesPerElement(const NodePtr &node, int depth) {
+    if (!node) {
+        return 0;
+    }
+    if (depth > 64) {
+        // A cyclic or pathologically deep schema. Return 1 (not 0) so the
+        // collection check stays enabled rather than being silently bypassed;
+        // a valid recursive value always encodes to at least 1 byte.
+        return 1;
+    }
+    switch (node->type()) {
+        case AVRO_NULL:
+            return 0;
+        case AVRO_FLOAT:
+            return 4;
+        case AVRO_DOUBLE:
+            return 8;
+        case AVRO_FIXED: {
+            // fixedSize() is a size_t; clamp to int64_t so a huge fixed size
+            // cannot wrap negative.
+            size_t sz = node->fixedSize();
+            return sz > static_cast<size_t>(std::numeric_limits<int64_t>::max())

Review Comment:
   This would read better as a simple `return std::min(...)`



##########
lang/c++/include/avro/Stream.hh:
##########
@@ -345,6 +356,29 @@ struct StreamReader {
         return next_ != end_ || fill();
     }
 
+    /**
+     * Returns the number of bytes still available to be read: those already
+     * buffered in this reader plus whatever the underlying stream reports as
+     * remaining. Returns a negative value when the underlying stream cannot
+     * report its remaining size.
+     */
+    int64_t remainingBytes() const {
+        if (in_ == nullptr) {
+            return -1;
+        }
+        int64_t streamRemaining = in_->remainingBytes();
+        if (streamRemaining < 0) {
+            return -1;
+        }
+        // end_ - next_ is the data already buffered in this reader; it is added
+        // to what the underlying stream still has. Guard the pointer
+        // subtraction: after init()/reset() and before any data is buffered,
+        // next_ and end_ are both null, and subtracting null pointers is
+        // undefined behavior.

Review Comment:
   This is just... not true?
   
   > [N4950](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2023/n4950.pdf)
   > 5 When two pointer expressions P and Q are subtracted, the type of the result is an implementation-defined signed integral type; this type shall be the same type that is defined as std::ptrdiff_t in the <cstddef> header (17.2.4).
   > (5.1) If P and Q both evaluate to null pointer values, the result is 0.



##########
lang/c++/impl/Generic.cc:
##########
@@ -105,7 +156,13 @@ void GenericReader::read(GenericDatum &datum, Decoder &d, bool isResolving) {
             const NodePtr &nn = v.schema()->leafAt(0);
             r.resize(0);
             size_t start = 0;
+            // Only when not resolving: the datum schema then matches the wire
+            // schema, so minBytesPerElement is a true lower bound. Under
+            // resolution the wire (writer) type may be smaller than the datum
+            // (reader) type, which would over-estimate and reject valid data.
+            int64_t minBytes = isResolving ? 0 : minBytesPerElement(nn, 0);
             for (size_t m = d.arrayStart(); m != 0; m = d.arrayNext()) {
+                ensureCollectionAvailable(d, m, minBytes);
                 r.resize(r.size() + m);

Review Comment:
   I am *extremely* suspicious of the claim that ensureCanGrow can ever fail. Is there some platform I am not considering where max_size limits would be exceeded before RAM is exhausted?
   
   C++ reference implies this won't ever happen, https://en.cppreference.com/cpp/container/vector/max_size



##########
lang/c++/include/avro/Decoder.hh:
##########
@@ -169,6 +169,14 @@ public:
     /// by the avro decoder. Similar set of problems occur if the Decoder
     /// consumes more than what it should.
     virtual void drain() = 0;
+
+    /// Returns the number of bytes that remain to be read from the underlying
+    /// stream, or a negative value when that count is not known (for example a
+    /// streaming source, or a decoder not backed by a byte stream). The default
+    /// is "unknown"; byte-stream decoders override it so a length prefix or a
+    /// collection block count that exceeds the data actually available can be
+    /// rejected before allocating for it.
+    virtual int64_t bytesRemaining() const { return -1; }

Review Comment:
   It bothers me that `bytesRemaining` and `remainingBytes` are both used for this. They seem to be defining the exact same concept.



##########
lang/c++/impl/Generic.cc:
##########
@@ -25,6 +27,151 @@ using std::ostringstream;
 using std::string;
 using std::vector;
 
+// Minimum number of bytes a single value of the given schema node can occupy on
+// the wire. Used to reject an array/map block count that could not be backed by
+// the bytes remaining. A type that can encode to zero bytes (null) returns 0,
+// which disables the collection check for it (so an array of nulls is not
+// falsely rejected). A depth limit breaks self-referencing (symbolic) schemas.
+static int64_t minBytesPerElement(const NodePtr &node, int depth) {
+    if (!node) {
+        return 0;
+    }
+    switch (node->type()) {
+        case AVRO_NULL:
+            return 0;
+        case AVRO_FLOAT:
+            return 4;
+        case AVRO_DOUBLE:
+            return 8;
+        case AVRO_FIXED: {
+            // fixedSize() is a size_t; clamp to int64_t so a huge fixed size
+            // cannot wrap negative.
+            size_t sz = node->fixedSize();
+            return sz > static_cast<size_t>(std::numeric_limits<int64_t>::max())
+                       ? std::numeric_limits<int64_t>::max()
+                       : static_cast<int64_t>(sz);
+        }
+        case AVRO_RECORD: {
+            if (depth > 64) {
+                // Purely a recursion (stack-overflow) safety net for a
+                // pathologically deep schema. A truly cyclic schema never
+                // reaches this: a self-reference is an AVRO_SYMBOLIC node,
+                // handled by the default case below (returning 1 without
+                // following the link), so recursion always terminates. This
+                // guard therefore only trips on a genuinely deep *acyclic*
+                // record, whose true minimum can still be 0 (e.g. a long chain
+                // of records whose only leaves are null). Return 0 rather than
+                // over-estimating, so a valid array/map of such elements is not
+                // falsely rejected; 0 is always a valid lower bound.
+                return 0;
+            }
+            int64_t total = 0;
+            for (size_t i = 0; i < node->leaves(); ++i) {
+                int64_t fieldMin = minBytesPerElement(node->leafAt(i), depth + 1);
+                // Saturate rather than overflow: a wrapped (negative) total
+                // would disable the collection check.
+                if (fieldMin > std::numeric_limits<int64_t>::max() - total) {
+                    return std::numeric_limits<int64_t>::max();
+                }
+                total += fieldMin;
+            }
+            return total;
+        }
+        default:
+            // boolean, int, long, bytes, string, enum, union, array, map and
+            // symbolic references all encode to at least one byte.
+            return 1;
+    }
+}
+
+// Default maximum number of zero-byte-encoded collection elements (e.g. an
+// array of nulls) to allocate from a single decode. Such elements consume no
+// input, so ensureCollectionAvailable cannot bound their count; without a cap a
+// tiny payload can declare a huge block count and exhaust memory. Overridable
+// via the AVRO_MAX_COLLECTION_ITEMS environment variable.
+static constexpr int64_t kDefaultMaxCollectionItems = 10000000;
+
+// Structural cap on the number of elements in any array or map (an overflow /
+// defense-in-depth guard), matching the historical Integer.MAX_VALUE - 8 limit.

Review Comment:
   This is a rather confusing claim for C++, where that limit has never existed.



##########
lang/c++/impl/BinaryDecoder.cc:
##########
@@ -19,12 +19,28 @@
 #include "Decoder.hh"
 #include "Exception.hh"
 #include "Zigzag.hh"
+#include <cstdlib>
 #include <memory>
 
 namespace avro {
 
 using std::make_shared;
 
+// Structural cap on the number of elements to skip in an array or map. Mirrors
+// the read-path limit in Generic.cc; AVRO_MAX_COLLECTION_ITEMS, when a
+// non-negative integer, overrides it.
+static int64_t maxCollectionStructural() {
+    const char *env = std::getenv("AVRO_MAX_COLLECTION_ITEMS");

Review Comment:
   I really don't like this. Libraries should not grab environment variables for configuration which developers of the library might not even know exist. If this option is important, I should be able to set it somehow on the decoder itself.
   
   If this is going to stay, it at the very least needs to be properly documented.



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Bound allocation when decoding length-prefixed values and collections [avro]

Posted by "iemejia (via GitHub)" <gi...@apache.org>.
iemejia commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3568112143


##########
lang/c++/include/avro/GenericDatum.hh:
##########
@@ -244,6 +244,9 @@ public:
      * \param branch The index for the selected branch.
      */
     void selectBranch(size_t branch) {
+        if (branch >= schema()->leaves()) {
+            throw Exception("Union branch index out of range: must be less than " + std::to_string(schema()->leaves()) + ", but is " + std::to_string(branch));
+        }

Review Comment:
   Fixed — decodeUnionIndex now validates the decoded long via decodeIndex(): a negative index is rejected before the size_t cast (so it can't wrap to a huge value), and selectBranch's bound against leaves() still applies.



##########
lang/c++/include/avro/GenericDatum.hh:
##########
@@ -244,6 +244,9 @@ public:
      * \param branch The index for the selected branch.
      */
     void selectBranch(size_t branch) {
+        if (branch >= schema()->leaves()) {
+            throw Exception("Union branch index out of range: must be less than " + std::to_string(schema()->leaves()) + ", but is " + std::to_string(branch));
+        }

Review Comment:
   Fixed — decodeIndex() also rejects an index beyond std::numeric_limits<size_t>::max(), so on a 32-bit build a large on-wire union index (e.g. 2^32) can't truncate into a small in-range value; it's rejected before reaching selectBranch.



##########
lang/c++/impl/Stream.cc:
##########
@@ -119,6 +130,10 @@ class MemoryInputStream2 : public InputStream {
     size_t byteCount() const final {
         return curLen_;
     }
+
+    int64_t remainingBytes() const final {
+        return static_cast<int64_t>(size_ - curLen_);
+    }

Review Comment:
   Fixed — MemoryInputStream2::remainingBytes() now computes `(int64_t)size_ - (int64_t)curLen_`, so a violated invariant can't underflow an unsigned subtraction.



##########
lang/c++/impl/Generic.cc:
##########
@@ -25,6 +29,164 @@ using std::ostringstream;
 using std::string;
 using std::vector;
 
+// Minimum number of bytes a single value of the given schema node can occupy on
+// the wire. Used to reject an array/map block count that could not be backed by
+// the bytes remaining. A type that can encode to zero bytes (null) returns 0,
+// which disables the collection check for it (so an array of nulls is not
+// falsely rejected). A depth limit breaks self-referencing (symbolic) schemas.
+static int64_t minBytesPerElement(const NodePtr &node, int depth) {
+    if (!node) {
+        return 0;
+    }
+    switch (node->type()) {
+        case AVRO_NULL:
+            return 0;
+        case AVRO_FLOAT:
+            return 4;
+        case AVRO_DOUBLE:
+            return 8;
+        case AVRO_FIXED: {
+            // fixedSize() is a size_t; clamp to int64_t so a huge fixed size
+            // cannot wrap negative.
+            return static_cast<int64_t>(std::min<uint64_t>(
+                node->fixedSize(),
+                static_cast<uint64_t>(std::numeric_limits<int64_t>::max())));
+        }
+        case AVRO_RECORD: {
+            if (depth > 64) {
+                // Purely a recursion (stack-overflow) safety net for a
+                // pathologically deep schema. A truly cyclic schema never
+                // reaches this: a self-reference is an AVRO_SYMBOLIC node,
+                // handled by the default case below (returning 1 without
+                // following the link), so recursion always terminates. This
+                // guard therefore only trips on a genuinely deep *acyclic*
+                // record, whose true minimum can still be 0 (e.g. a long chain
+                // of records whose only leaves are null). Return 0 rather than
+                // over-estimating, so a valid array/map of such elements is not
+                // falsely rejected; 0 is always a valid lower bound.
+                return 0;
+            }
+            int64_t total = 0;
+            for (size_t i = 0; i < node->leaves(); ++i) {
+                int64_t fieldMin = minBytesPerElement(node->leafAt(i), depth + 1);
+                // Saturate rather than overflow: a wrapped (negative) total
+                // would disable the collection check.
+                if (fieldMin > std::numeric_limits<int64_t>::max() - total) {
+                    return std::numeric_limits<int64_t>::max();
+                }
+                total += fieldMin;
+            }
+            return total;
+        }
+        default:
+            // boolean, int, long, bytes, string, enum, union, array, map and
+            // symbolic references all encode to at least one byte.
+            return 1;
+    }
+}
+
+// Default maximum number of zero-byte-encoded collection elements (e.g. an
+// array of nulls) to allocate from a single decode. Such elements consume no
+// input, so ensureCollectionAvailable cannot bound their count; without a cap a
+// tiny payload can declare a huge block count and exhaust memory. Overridable
+// via the AVRO_MAX_COLLECTION_ITEMS environment variable.
+static constexpr int64_t kDefaultMaxCollectionItems = 10000000;
+
+// Structural cap on the number of elements in any array or map (an overflow /
+// defense-in-depth guard). It matches the value used by the other Avro SDKs
+// (Integer.MAX_VALUE - 8); non-zero-byte elements are also bounded by the bytes
+// remaining.
+static constexpr int64_t kDefaultMaxCollectionStructural = 2147483639;
+
+// Upper bound on how many elements a collection container is grown by in a
+// single step while decoding. The container still grows to hold every element
+// that is actually read; this only prevents resizing to the full (possibly
+// attacker-declared) block count up front, before any element is decoded. That
+// matters most for stream sources, where the bytes-remaining check cannot bound
+// the declared count against the input, so a single up-front resize could
+// allocate a huge container before the truncated stream is detected.
+static constexpr size_t kMaxCollectionPrealloc = 1024;
+
+struct CollectionLimits {
+    int64_t zeroByte;
+    int64_t structural;
+};
+
+// AVRO_MAX_COLLECTION_ITEMS, when a non-negative integer, overrides both limits
+// to that value; otherwise zero-byte elements use the tighter default and all
+// collections use the structural default.
+static CollectionLimits collectionLimits() {
+    const char *env = std::getenv("AVRO_MAX_COLLECTION_ITEMS");
+    if (env != nullptr && *env != '\0') {
+        char *end = nullptr;
+        long long value = std::strtoll(env, &end, 10);
+        if (*end == '\0' && value >= 0) {
+            return {static_cast<int64_t>(value), static_cast<int64_t>(value)};
+        }
+    }
+    return {kDefaultMaxCollectionItems, kDefaultMaxCollectionStructural};

Review Comment:
   Already handled — collectionLimits() resets errno before strtoll and only accepts the value when `errno == 0`, so an ERANGE overflow (saturated LLONG_MAX) is ignored and the defaults apply (Generic.cc:122-127).



##########
lang/c++/impl/BinaryDecoder.cc:
##########
@@ -19,12 +19,36 @@
 #include "Decoder.hh"
 #include "Exception.hh"
 #include "Zigzag.hh"
+#include <cstdint>
+#include <cstdlib>
+#include <limits>
 #include <memory>
 
 namespace avro {
 
 using std::make_shared;
 
+// Structural cap on the number of elements to skip in an array or map (an
+// overflow / defense-in-depth guard). Mirrors the read-path limit in Generic.cc
+// and matches the value used by the other Avro SDKs (Integer.MAX_VALUE - 8).
+static constexpr int64_t kDefaultMaxCollectionStructural = 2147483639;
+
+// Returns the structural collection cap. It can be overridden by the
+// AVRO_MAX_COLLECTION_ITEMS environment variable (a non-negative integer),
+// matching the read path and the other SDKs so a single knob configures all of
+// them; an invalid or unset value uses the default.
+static int64_t maxCollectionStructural() {
+    const char *env = std::getenv("AVRO_MAX_COLLECTION_ITEMS");
+    if (env != nullptr && *env != '\0') {
+        char *end = nullptr;
+        long long value = std::strtoll(env, &end, 10);
+        if (*end == '\0' && value >= 0) {
+            return static_cast<int64_t>(value);
+        }
+    }
+    return kDefaultMaxCollectionStructural;
+}

Review Comment:
   Already handled — maxCollectionStructural() has the same `errno == 0` guard, so an overflowing AVRO_MAX_COLLECTION_ITEMS falls back to the default structural cap (BinaryDecoder.cc).



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Bound allocation when decoding length-prefixed values and collections [avro]

Posted by "iemejia (via GitHub)" <gi...@apache.org>.
iemejia commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3566893024


##########
lang/c++/impl/BinaryDecoder.cc:
##########
@@ -180,6 +215,18 @@ size_t BinaryDecoder::skipArray() {
             auto n = static_cast<size_t>(doDecodeLong());
             in_.skipBytes(n);
         } else {
+            // Bound the block count: skipping a huge block of zero-byte elements
+            // would otherwise loop unboundedly (a CPU exhaustion) even though it
+            // reads/allocates nothing. The decoder has no element schema here, so
+            // apply the structural cap (AVRO_MAX_COLLECTION_ITEMS, default
+            // Integer.MAX_VALUE - 8).
+            static const int64_t structural = maxCollectionStructural();

Review Comment:
   Fixed in e6a35fa802: skipArray() now reads maxCollectionStructural() on each call rather than caching it in a function-local static, so runtime env changes (and test cleanup) are honoured, matching Generic.cc.



##########
lang/c++/impl/BinaryDecoder.cc:
##########
@@ -180,6 +215,18 @@ size_t BinaryDecoder::skipArray() {
             auto n = static_cast<size_t>(doDecodeLong());
             in_.skipBytes(n);
         } else {

Review Comment:
   Fixed in e6a35fa802: skipArray() now rejects a negative block byte-size before casting to size_t / calling skipBytes(), so a negative size can't drive an unbounded skip. Added a test.



##########
lang/c++/test/AvailableBytesTests.cc:
##########
@@ -0,0 +1,280 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// A bytes/string value is encoded as a length prefix followed by that many
+// bytes of data. A malicious or truncated input can declare a huge length with
+// little or no actual data, which would otherwise trigger a correspondingly
+// huge allocation before the shortfall is noticed. When the input stream can
+// report how many bytes remain (a memory-backed stream), the declared length
+// must be rejected before allocating for it.
+
+#include <cstdint>
+#include <cstdlib>
+#include <memory>
+#include <string>
+#include <vector>
+
+#include <boost/test/included/unit_test.hpp>
+
+#include "Compiler.hh"
+#include "Decoder.hh"
+#include "Encoder.hh"
+#include "Exception.hh"
+#include "Generic.hh"
+#include "Stream.hh"
+#include "ValidSchema.hh"
+
+namespace avro {
+
+// Reading a bytes value whose declared length far exceeds the tiny backing
+// buffer must throw instead of attempting a huge allocation.
+static void testDecodeBytesRejectsOversizedLength() {
+    // 0xFE 0x01 is the zig-zag long 127; the buffer carries no data after it.
+    const uint8_t data[] = {0xFE, 0x01};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::vector<uint8_t> value;
+    BOOST_CHECK_THROW(d->decodeBytes(value), Exception);
+}
+
+static void testDecodeStringRejectsOversizedLength() {
+    const uint8_t data[] = {0xFE, 0x01};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::string value;
+    BOOST_CHECK_THROW(d->decodeString(value), Exception);
+}
+
+// A well-formed value whose declared length fits the buffer still decodes.
+static void testDecodeStringWithinLimitStillReads() {
+    // length 3 (zig-zag 6 -> 0x06) followed by "abc".
+    const uint8_t data[] = {0x06, 'a', 'b', 'c'};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::string value;
+    d->decodeString(value);
+    BOOST_CHECK_EQUAL(value, std::string("abc"));
+}
+
+static void testDecodeBytesWithinLimitStillReads() {
+    const uint8_t data[] = {0x06, 0x01, 0x02, 0x03};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::vector<uint8_t> value;
+    d->decodeBytes(value);
+    BOOST_CHECK_EQUAL(value.size(), 3u);
+    BOOST_CHECK_EQUAL(value[0], 1);
+    BOOST_CHECK_EQUAL(value[2], 3);
+}
+
+// An array/map block declares an element count; a malicious or truncated input
+// can declare far more elements than the remaining bytes could hold. The count
+// is validated against the bytes remaining before resizing, using the minimum
+// on-wire size of the element schema (so 0-byte elements like null are not
+// falsely rejected).
+static GenericDatum decodeCollectionHeader(const ValidSchema &s, int64_t blockCount,
+                                           bool addEndMarker) {
+    // Keep the output stream alive for the whole decode: memoryInputStream
+    // references the output stream's buffer rather than copying it.
+    std::unique_ptr<OutputStream> os = memoryOutputStream();
+    EncoderPtr e = binaryEncoder();
+    e->init(*os);
+    e->encodeLong(blockCount);
+    if (addEndMarker) {
+        e->encodeLong(0);
+    }
+    e->flush();
+
+    InputStreamPtr in = memoryInputStream(*os);
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    GenericDatum datum;
+    GenericReader::read(*d, datum, s);
+    return datum;
+}
+
+static void testReadArrayRejectsOversizedCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"long\"}");
+    // 1,000,000 long elements declared, but no element data follows.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1000000, false), Exception);
+}
+
+static void testReadMapRejectsOversizedCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"map\",\"values\":\"long\"}");
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1000000, false), Exception);
+}
+
+static void testReadArrayOfNullNotFalselyRejected() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // 100,000 nulls (zero bytes each) is legitimate and must decode.
+    GenericDatum datum = decodeCollectionHeader(s, 100000, true);
+    BOOST_CHECK_EQUAL(datum.value<GenericArray>().value().size(), 100000u);
+}
+
+// A deeply but acyclically nested record whose only leaf is null encodes to
+// zero bytes, so the per-element minimum must be 0 and a large array of such
+// records must not be falsely rejected. This exercises the recursion depth
+// guard in minBytesPerElement(), which must yield a conservative lower bound
+// (0) rather than over-estimating for a legitimately deep schema.
+static void testReadArrayOfDeeplyNestedNullNotFalselyRejected() {
+    // Build ~70 nested records: R0 { null f; }, R1 { R0 f; }, ... The nesting
+    // exceeds the depth guard, yet every leaf is null so the true minimum is 0.
+    std::string schema = "\"null\"";
+    for (int i = 0; i < 70; ++i) {
+        schema = "{\"type\":\"record\",\"name\":\"R" + std::to_string(i) +
+                 "\",\"fields\":[{\"name\":\"f\",\"type\":" + schema + "}]}";
+    }
+    ValidSchema s = compileJsonSchemaFromString(
+        ("{\"type\":\"array\",\"items\":" + schema + "}").c_str());
+    // 100,000 zero-byte elements is legitimate and must decode.
+    GenericDatum datum = decodeCollectionHeader(s, 100000, true);
+    BOOST_CHECK_EQUAL(datum.value<GenericArray>().value().size(), 100000u);
+}
+
+// Calling bytesRemaining() immediately after init(), before any data has been
+// buffered, must be well-defined (the underlying StreamReader must not subtract
+// null buffer pointers) and report the whole stream as available.
+static void testBytesRemainingRightAfterInit() {
+    const uint8_t data[] = {0x06, 'a', 'b', 'c'};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    BOOST_CHECK_EQUAL(d->bytesRemaining(), static_cast<int64_t>(sizeof(data)));
+}
+
+// Zero-byte elements (null, a record with only zero-byte fields) consume no
+// input, so ensureCollectionAvailable cannot bound their count. A huge declared
+// block count of such elements is capped against a configurable limit.
+static GenericDatum decodeLongs(const ValidSchema &s, const std::vector<int64_t> &longs) {
+    std::unique_ptr<OutputStream> os = memoryOutputStream();
+    EncoderPtr e = binaryEncoder();
+    e->init(*os);
+    for (int64_t v : longs) {
+        e->encodeLong(v);
+    }
+    e->flush();
+    InputStreamPtr in = memoryInputStream(*os);
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    GenericDatum datum;
+    GenericReader::read(*d, datum, s);
+    return datum;
+}
+
+static void testReadArrayOfNullRejectsCountAboveDefaultLimit() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // The reported exploit: 200,000,000 nulls rejected by the default limit.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, true), Exception);
+}
+
+static void testReadArrayOfAllNullRecordRejectsHugeCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":"
+        "{\"type\":\"record\",\"name\":\"R\",\"fields\":[{\"name\":\"n\",\"type\":\"null\"}]}}");
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, true), Exception);
+}
+
+static void testReadArrayOfNullRejectsNegativeCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // Negative count (-200M), block byte-size 0, end marker 0: normalized to
+    // 200M and still bounded.
+    BOOST_CHECK_THROW(decodeLongs(s, {-200000000, 0, 0}), Exception);
+}
+
+static void testReadMapOfNullRejectedByAvailableBytes() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"map\",\"values\":\"null\"}");
+    // Each map entry carries a >= 1 byte key, so a huge map<null> is bounded by
+    // the bytes-remaining check.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, false), Exception);
+}
+
+static void testReadArrayOfNullRespectsConfiguredLimit() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    setenv("AVRO_MAX_COLLECTION_ITEMS", "1000", 1);
+    // Within the limit decodes; over the limit and cumulative are rejected.
+    GenericDatum ok = decodeCollectionHeader(s, 1000, true);
+    BOOST_CHECK_EQUAL(ok.value<GenericArray>().value().size(), 1000u);
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1001, true), Exception);
+    BOOST_CHECK_THROW(decodeLongs(s, {600, 600, 0}), Exception);
+    unsetenv("AVRO_MAX_COLLECTION_ITEMS");

Review Comment:
   Fixed in e6a35fa802: the tests now use an RAII ScopedCollectionLimit that is MSVC-portable (setenv/unsetenv, or _putenv_s under _WIN32) and restores any pre-existing AVRO_MAX_COLLECTION_ITEMS value.



##########
lang/c++/test/AvailableBytesTests.cc:
##########
@@ -0,0 +1,280 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// A bytes/string value is encoded as a length prefix followed by that many
+// bytes of data. A malicious or truncated input can declare a huge length with
+// little or no actual data, which would otherwise trigger a correspondingly
+// huge allocation before the shortfall is noticed. When the input stream can
+// report how many bytes remain (a memory-backed stream), the declared length
+// must be rejected before allocating for it.
+
+#include <cstdint>
+#include <cstdlib>
+#include <memory>
+#include <string>
+#include <vector>
+
+#include <boost/test/included/unit_test.hpp>
+
+#include "Compiler.hh"
+#include "Decoder.hh"
+#include "Encoder.hh"
+#include "Exception.hh"
+#include "Generic.hh"
+#include "Stream.hh"
+#include "ValidSchema.hh"
+
+namespace avro {
+
+// Reading a bytes value whose declared length far exceeds the tiny backing
+// buffer must throw instead of attempting a huge allocation.
+static void testDecodeBytesRejectsOversizedLength() {
+    // 0xFE 0x01 is the zig-zag long 127; the buffer carries no data after it.
+    const uint8_t data[] = {0xFE, 0x01};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::vector<uint8_t> value;
+    BOOST_CHECK_THROW(d->decodeBytes(value), Exception);
+}
+
+static void testDecodeStringRejectsOversizedLength() {
+    const uint8_t data[] = {0xFE, 0x01};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::string value;
+    BOOST_CHECK_THROW(d->decodeString(value), Exception);
+}
+
+// A well-formed value whose declared length fits the buffer still decodes.
+static void testDecodeStringWithinLimitStillReads() {
+    // length 3 (zig-zag 6 -> 0x06) followed by "abc".
+    const uint8_t data[] = {0x06, 'a', 'b', 'c'};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::string value;
+    d->decodeString(value);
+    BOOST_CHECK_EQUAL(value, std::string("abc"));
+}
+
+static void testDecodeBytesWithinLimitStillReads() {
+    const uint8_t data[] = {0x06, 0x01, 0x02, 0x03};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::vector<uint8_t> value;
+    d->decodeBytes(value);
+    BOOST_CHECK_EQUAL(value.size(), 3u);
+    BOOST_CHECK_EQUAL(value[0], 1);
+    BOOST_CHECK_EQUAL(value[2], 3);
+}
+
+// An array/map block declares an element count; a malicious or truncated input
+// can declare far more elements than the remaining bytes could hold. The count
+// is validated against the bytes remaining before resizing, using the minimum
+// on-wire size of the element schema (so 0-byte elements like null are not
+// falsely rejected).
+static GenericDatum decodeCollectionHeader(const ValidSchema &s, int64_t blockCount,
+                                           bool addEndMarker) {
+    // Keep the output stream alive for the whole decode: memoryInputStream
+    // references the output stream's buffer rather than copying it.
+    std::unique_ptr<OutputStream> os = memoryOutputStream();
+    EncoderPtr e = binaryEncoder();
+    e->init(*os);
+    e->encodeLong(blockCount);
+    if (addEndMarker) {
+        e->encodeLong(0);
+    }
+    e->flush();
+
+    InputStreamPtr in = memoryInputStream(*os);
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    GenericDatum datum;
+    GenericReader::read(*d, datum, s);
+    return datum;
+}
+
+static void testReadArrayRejectsOversizedCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"long\"}");
+    // 1,000,000 long elements declared, but no element data follows.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1000000, false), Exception);
+}
+
+static void testReadMapRejectsOversizedCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"map\",\"values\":\"long\"}");
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1000000, false), Exception);
+}
+
+static void testReadArrayOfNullNotFalselyRejected() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // 100,000 nulls (zero bytes each) is legitimate and must decode.
+    GenericDatum datum = decodeCollectionHeader(s, 100000, true);
+    BOOST_CHECK_EQUAL(datum.value<GenericArray>().value().size(), 100000u);
+}
+
+// A deeply but acyclically nested record whose only leaf is null encodes to
+// zero bytes, so the per-element minimum must be 0 and a large array of such
+// records must not be falsely rejected. This exercises the recursion depth
+// guard in minBytesPerElement(), which must yield a conservative lower bound
+// (0) rather than over-estimating for a legitimately deep schema.
+static void testReadArrayOfDeeplyNestedNullNotFalselyRejected() {
+    // Build ~70 nested records: R0 { null f; }, R1 { R0 f; }, ... The nesting
+    // exceeds the depth guard, yet every leaf is null so the true minimum is 0.
+    std::string schema = "\"null\"";
+    for (int i = 0; i < 70; ++i) {
+        schema = "{\"type\":\"record\",\"name\":\"R" + std::to_string(i) +
+                 "\",\"fields\":[{\"name\":\"f\",\"type\":" + schema + "}]}";
+    }
+    ValidSchema s = compileJsonSchemaFromString(
+        ("{\"type\":\"array\",\"items\":" + schema + "}").c_str());
+    // 100,000 zero-byte elements is legitimate and must decode.
+    GenericDatum datum = decodeCollectionHeader(s, 100000, true);
+    BOOST_CHECK_EQUAL(datum.value<GenericArray>().value().size(), 100000u);
+}
+
+// Calling bytesRemaining() immediately after init(), before any data has been
+// buffered, must be well-defined (the underlying StreamReader must not subtract
+// null buffer pointers) and report the whole stream as available.
+static void testBytesRemainingRightAfterInit() {
+    const uint8_t data[] = {0x06, 'a', 'b', 'c'};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    BOOST_CHECK_EQUAL(d->bytesRemaining(), static_cast<int64_t>(sizeof(data)));
+}
+
+// Zero-byte elements (null, a record with only zero-byte fields) consume no
+// input, so ensureCollectionAvailable cannot bound their count. A huge declared
+// block count of such elements is capped against a configurable limit.
+static GenericDatum decodeLongs(const ValidSchema &s, const std::vector<int64_t> &longs) {
+    std::unique_ptr<OutputStream> os = memoryOutputStream();
+    EncoderPtr e = binaryEncoder();
+    e->init(*os);
+    for (int64_t v : longs) {
+        e->encodeLong(v);
+    }
+    e->flush();
+    InputStreamPtr in = memoryInputStream(*os);
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    GenericDatum datum;
+    GenericReader::read(*d, datum, s);
+    return datum;
+}
+
+static void testReadArrayOfNullRejectsCountAboveDefaultLimit() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // The reported exploit: 200,000,000 nulls rejected by the default limit.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, true), Exception);
+}
+
+static void testReadArrayOfAllNullRecordRejectsHugeCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":"
+        "{\"type\":\"record\",\"name\":\"R\",\"fields\":[{\"name\":\"n\",\"type\":\"null\"}]}}");
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, true), Exception);
+}
+
+static void testReadArrayOfNullRejectsNegativeCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // Negative count (-200M), block byte-size 0, end marker 0: normalized to
+    // 200M and still bounded.
+    BOOST_CHECK_THROW(decodeLongs(s, {-200000000, 0, 0}), Exception);
+}
+
+static void testReadMapOfNullRejectedByAvailableBytes() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"map\",\"values\":\"null\"}");
+    // Each map entry carries a >= 1 byte key, so a huge map<null> is bounded by
+    // the bytes-remaining check.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, false), Exception);
+}
+
+static void testReadArrayOfNullRespectsConfiguredLimit() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    setenv("AVRO_MAX_COLLECTION_ITEMS", "1000", 1);
+    // Within the limit decodes; over the limit and cumulative are rejected.
+    GenericDatum ok = decodeCollectionHeader(s, 1000, true);
+    BOOST_CHECK_EQUAL(ok.value<GenericArray>().value().size(), 1000u);
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1001, true), Exception);
+    BOOST_CHECK_THROW(decodeLongs(s, {600, 600, 0}), Exception);
+    unsetenv("AVRO_MAX_COLLECTION_ITEMS");
+}
+
+// A backed non-zero-byte array that passes the bytes check is still bounded by
+// the structural cap (exercised with a lowered limit).
+static void testReadArrayOfLongRejectedByStructuralCap() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"long\"}");
+    setenv("AVRO_MAX_COLLECTION_ITEMS", "5", 1);
+    // 10 real longs: block count 10, ten 1-byte longs, end marker.
+    std::vector<int64_t> longs = {10, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
+    BOOST_CHECK_THROW(decodeLongs(s, longs), Exception);
+    unsetenv("AVRO_MAX_COLLECTION_ITEMS");

Review Comment:
   Fixed in e6a35fa802 via the same RAII ScopedCollectionLimit (portable + restores the previous value).



##########
lang/c++/test/AvailableBytesTests.cc:
##########
@@ -0,0 +1,280 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// A bytes/string value is encoded as a length prefix followed by that many
+// bytes of data. A malicious or truncated input can declare a huge length with
+// little or no actual data, which would otherwise trigger a correspondingly
+// huge allocation before the shortfall is noticed. When the input stream can
+// report how many bytes remain (a memory-backed stream), the declared length
+// must be rejected before allocating for it.
+
+#include <cstdint>
+#include <cstdlib>
+#include <memory>
+#include <string>
+#include <vector>
+
+#include <boost/test/included/unit_test.hpp>
+
+#include "Compiler.hh"
+#include "Decoder.hh"
+#include "Encoder.hh"
+#include "Exception.hh"
+#include "Generic.hh"
+#include "Stream.hh"
+#include "ValidSchema.hh"
+
+namespace avro {
+
+// Reading a bytes value whose declared length far exceeds the tiny backing
+// buffer must throw instead of attempting a huge allocation.
+static void testDecodeBytesRejectsOversizedLength() {
+    // 0xFE 0x01 is the zig-zag long 127; the buffer carries no data after it.
+    const uint8_t data[] = {0xFE, 0x01};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::vector<uint8_t> value;
+    BOOST_CHECK_THROW(d->decodeBytes(value), Exception);
+}
+
+static void testDecodeStringRejectsOversizedLength() {
+    const uint8_t data[] = {0xFE, 0x01};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::string value;
+    BOOST_CHECK_THROW(d->decodeString(value), Exception);
+}
+
+// A well-formed value whose declared length fits the buffer still decodes.
+static void testDecodeStringWithinLimitStillReads() {
+    // length 3 (zig-zag 6 -> 0x06) followed by "abc".
+    const uint8_t data[] = {0x06, 'a', 'b', 'c'};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::string value;
+    d->decodeString(value);
+    BOOST_CHECK_EQUAL(value, std::string("abc"));
+}
+
+static void testDecodeBytesWithinLimitStillReads() {
+    const uint8_t data[] = {0x06, 0x01, 0x02, 0x03};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::vector<uint8_t> value;
+    d->decodeBytes(value);
+    BOOST_CHECK_EQUAL(value.size(), 3u);
+    BOOST_CHECK_EQUAL(value[0], 1);
+    BOOST_CHECK_EQUAL(value[2], 3);
+}
+
+// An array/map block declares an element count; a malicious or truncated input
+// can declare far more elements than the remaining bytes could hold. The count
+// is validated against the bytes remaining before resizing, using the minimum
+// on-wire size of the element schema (so 0-byte elements like null are not
+// falsely rejected).
+static GenericDatum decodeCollectionHeader(const ValidSchema &s, int64_t blockCount,
+                                           bool addEndMarker) {
+    // Keep the output stream alive for the whole decode: memoryInputStream
+    // references the output stream's buffer rather than copying it.
+    std::unique_ptr<OutputStream> os = memoryOutputStream();
+    EncoderPtr e = binaryEncoder();
+    e->init(*os);
+    e->encodeLong(blockCount);
+    if (addEndMarker) {
+        e->encodeLong(0);
+    }
+    e->flush();
+
+    InputStreamPtr in = memoryInputStream(*os);
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    GenericDatum datum;
+    GenericReader::read(*d, datum, s);
+    return datum;
+}
+
+static void testReadArrayRejectsOversizedCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"long\"}");
+    // 1,000,000 long elements declared, but no element data follows.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1000000, false), Exception);
+}
+
+static void testReadMapRejectsOversizedCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"map\",\"values\":\"long\"}");
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1000000, false), Exception);
+}
+
+static void testReadArrayOfNullNotFalselyRejected() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // 100,000 nulls (zero bytes each) is legitimate and must decode.
+    GenericDatum datum = decodeCollectionHeader(s, 100000, true);
+    BOOST_CHECK_EQUAL(datum.value<GenericArray>().value().size(), 100000u);
+}
+
+// A deeply but acyclically nested record whose only leaf is null encodes to
+// zero bytes, so the per-element minimum must be 0 and a large array of such
+// records must not be falsely rejected. This exercises the recursion depth
+// guard in minBytesPerElement(), which must yield a conservative lower bound
+// (0) rather than over-estimating for a legitimately deep schema.
+static void testReadArrayOfDeeplyNestedNullNotFalselyRejected() {
+    // Build ~70 nested records: R0 { null f; }, R1 { R0 f; }, ... The nesting
+    // exceeds the depth guard, yet every leaf is null so the true minimum is 0.
+    std::string schema = "\"null\"";
+    for (int i = 0; i < 70; ++i) {
+        schema = "{\"type\":\"record\",\"name\":\"R" + std::to_string(i) +
+                 "\",\"fields\":[{\"name\":\"f\",\"type\":" + schema + "}]}";
+    }
+    ValidSchema s = compileJsonSchemaFromString(
+        ("{\"type\":\"array\",\"items\":" + schema + "}").c_str());
+    // 100,000 zero-byte elements is legitimate and must decode.
+    GenericDatum datum = decodeCollectionHeader(s, 100000, true);
+    BOOST_CHECK_EQUAL(datum.value<GenericArray>().value().size(), 100000u);
+}
+
+// Calling bytesRemaining() immediately after init(), before any data has been
+// buffered, must be well-defined (the underlying StreamReader must not subtract
+// null buffer pointers) and report the whole stream as available.
+static void testBytesRemainingRightAfterInit() {
+    const uint8_t data[] = {0x06, 'a', 'b', 'c'};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    BOOST_CHECK_EQUAL(d->bytesRemaining(), static_cast<int64_t>(sizeof(data)));
+}
+
+// Zero-byte elements (null, a record with only zero-byte fields) consume no
+// input, so ensureCollectionAvailable cannot bound their count. A huge declared
+// block count of such elements is capped against a configurable limit.
+static GenericDatum decodeLongs(const ValidSchema &s, const std::vector<int64_t> &longs) {
+    std::unique_ptr<OutputStream> os = memoryOutputStream();
+    EncoderPtr e = binaryEncoder();
+    e->init(*os);
+    for (int64_t v : longs) {
+        e->encodeLong(v);
+    }
+    e->flush();
+    InputStreamPtr in = memoryInputStream(*os);
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    GenericDatum datum;
+    GenericReader::read(*d, datum, s);
+    return datum;
+}
+
+static void testReadArrayOfNullRejectsCountAboveDefaultLimit() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // The reported exploit: 200,000,000 nulls rejected by the default limit.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, true), Exception);
+}
+
+static void testReadArrayOfAllNullRecordRejectsHugeCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":"
+        "{\"type\":\"record\",\"name\":\"R\",\"fields\":[{\"name\":\"n\",\"type\":\"null\"}]}}");
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, true), Exception);
+}
+
+static void testReadArrayOfNullRejectsNegativeCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // Negative count (-200M), block byte-size 0, end marker 0: normalized to
+    // 200M and still bounded.
+    BOOST_CHECK_THROW(decodeLongs(s, {-200000000, 0, 0}), Exception);
+}
+
+static void testReadMapOfNullRejectedByAvailableBytes() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"map\",\"values\":\"null\"}");
+    // Each map entry carries a >= 1 byte key, so a huge map<null> is bounded by
+    // the bytes-remaining check.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, false), Exception);
+}
+
+static void testReadArrayOfNullRespectsConfiguredLimit() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    setenv("AVRO_MAX_COLLECTION_ITEMS", "1000", 1);
+    // Within the limit decodes; over the limit and cumulative are rejected.
+    GenericDatum ok = decodeCollectionHeader(s, 1000, true);
+    BOOST_CHECK_EQUAL(ok.value<GenericArray>().value().size(), 1000u);
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1001, true), Exception);
+    BOOST_CHECK_THROW(decodeLongs(s, {600, 600, 0}), Exception);
+    unsetenv("AVRO_MAX_COLLECTION_ITEMS");
+}
+
+// A backed non-zero-byte array that passes the bytes check is still bounded by
+// the structural cap (exercised with a lowered limit).
+static void testReadArrayOfLongRejectedByStructuralCap() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"long\"}");
+    setenv("AVRO_MAX_COLLECTION_ITEMS", "5", 1);
+    // 10 real longs: block count 10, ten 1-byte longs, end marker.
+    std::vector<int64_t> longs = {10, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
+    BOOST_CHECK_THROW(decodeLongs(s, longs), Exception);
+    unsetenv("AVRO_MAX_COLLECTION_ITEMS");
+}
+
+// Skipping a huge array (via the decoder's skipArray) is bounded by the
+// structural cap.
+static void testSkipArrayRejectsHugeCount() {
+    setenv("AVRO_MAX_COLLECTION_ITEMS", "1000", 1);
+    std::unique_ptr<OutputStream> os = memoryOutputStream();
+    EncoderPtr e = binaryEncoder();
+    e->init(*os);
+    e->encodeLong(2000); // block count 2000, no data needed (skip throws first)
+    e->flush();
+    InputStreamPtr in = memoryInputStream(*os);
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    BOOST_CHECK_THROW(d->skipArray(), Exception);
+    unsetenv("AVRO_MAX_COLLECTION_ITEMS");
+}

Review Comment:
   Fixed in e6a35fa802 via the same RAII ScopedCollectionLimit (portable + restores the previous value).



##########
lang/c++/include/avro/Stream.hh:
##########
@@ -345,6 +356,29 @@ struct StreamReader {
         return next_ != end_ || fill();
     }
 
+    /**
+     * Returns the number of bytes still available to be read: those already
+     * buffered in this reader plus whatever the underlying stream reports as
+     * remaining. Returns a negative value when the underlying stream cannot
+     * report its remaining size.
+     */
+    int64_t remainingBytes() const {
+        if (in_ == nullptr) {
+            return -1;
+        }
+        int64_t streamRemaining = in_->remainingBytes();
+        if (streamRemaining < 0) {
+            return -1;
+        }
+        // end_ - next_ is the data already buffered in this reader; it is added
+        // to what the underlying stream still has. Guard the pointer
+        // subtraction: after init()/reset() and before any data is buffered,
+        // next_ and end_ are both null, and subtracting null pointers is
+        // undefined behavior.

Review Comment:
   You're right — subtracting two null pointers is well-defined and yields 0 (N4950 7.6.6/5.1). Reverted in e6a35fa802 to the plain `end_ - next_` and removed the incorrect UB comment; the right-after-init test still passes.



##########
lang/c++/impl/Generic.cc:
##########
@@ -105,7 +258,21 @@ void GenericReader::read(GenericDatum &datum, Decoder &d, bool isResolving) {
             const NodePtr &nn = v.schema()->leafAt(0);
             r.resize(0);
             size_t start = 0;
+            // Only when not resolving: the datum schema then matches the wire
+            // schema, so minBytesPerElement is a true lower bound. Under
+            // resolution the wire (writer) type may be smaller than the datum
+            // (reader) type, which would over-estimate and reject valid data.
+            int64_t trueMin = minBytesPerElement(nn, 0);
+            bool zeroByte = trueMin == 0;
+            int64_t minBytes = isResolving ? 0 : trueMin;

Review Comment:
   Fixed in e6a35fa802: under resolution we can't tell whether an on-wire element is zero bytes (reader-only fields can be filled from defaults), so the zero-byte cap is now applied conservatively for arrays when resolving (`zeroByte = isResolving || trueMin == 0`), bounding the up-front resize. For maps, each entry carries a >= 1 byte key regardless of resolution, so minBytes is now 1 (not 0) when resolving, which bounds the count by the bytes remaining.



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Bound allocation when decoding length-prefixed values and collections [avro]

Posted by "iemejia (via GitHub)" <gi...@apache.org>.
iemejia commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3568244936


##########
lang/c++/include/avro/Stream.hh:
##########
@@ -345,6 +356,30 @@ struct StreamReader {
         return next_ != end_ || fill();
     }
 
+    /**
+     * Returns the number of bytes still available to be read: those already
+     * buffered in this reader plus whatever the underlying stream reports as
+     * remaining. Returns a negative value when the underlying stream cannot
+     * report its remaining size.
+     */
+    int64_t remainingBytes() const {
+        if (in_ == nullptr) {
+            return -1;
+        }
+        int64_t streamRemaining = in_->remainingBytes();
+        if (streamRemaining < 0) {
+            return -1;
+        }
+        // Bytes already buffered in this reader, added to what the underlying
+        // stream still has. next_ and end_ can both be null right after
+        // init()/reset() (before any data is buffered); subtracting two null
+        // pointers is undefined behavior, so treat equal pointers (including the
+        // both-null case) as zero buffered and only subtract real buffer
+        // pointers. Pointer equality, unlike subtraction, is well-defined here.
+        int64_t buffered = (next_ == end_) ? 0 : (end_ - next_);
+        return buffered + streamRemaining;

Review Comment:
   Fixed — the guard is now `(next_ == nullptr || end_ == nullptr) ? 0 : (end_ - next_)`, so any null operand (not just the both-null case) is treated as zero buffered and the subtraction only runs when both pointers reference a real buffer.



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Bound allocation when decoding length-prefixed values and collections [avro]

Posted by "Gerrit0 (via GitHub)" <gi...@apache.org>.
Gerrit0 commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3567551317


##########
lang/c++/impl/BinaryDecoder.cc:
##########
@@ -19,12 +19,28 @@
 #include "Decoder.hh"
 #include "Exception.hh"
 #include "Zigzag.hh"
+#include <cstdlib>
 #include <memory>
 
 namespace avro {
 
 using std::make_shared;
 
+// Structural cap on the number of elements to skip in an array or map. Mirrors
+// the read-path limit in Generic.cc; AVRO_MAX_COLLECTION_ITEMS, when a
+// non-negative integer, overrides it.
+static int64_t maxCollectionStructural() {
+    const char *env = std::getenv("AVRO_MAX_COLLECTION_ITEMS");

Review Comment:
   Yeah... I still really dislike this. The only environment variables prior to your changes that I see in the Avro source are for unit tests/demo programs. With this introduction, bug reports also need to include any environment variables set for someone investigating the problem to be sure to be able to reproduce.
   
   I don't think a note in the code is sufficient for documentation if this is going to stay. If Avro is going to be configurable via environment variables, the documentation site needs a page [like Apache Arrow](https://arrow.apache.org/docs/cpp/env_vars.html) where all variables are enumerated.



##########
lang/c++/include/avro/Decoder.hh:
##########
@@ -169,6 +169,14 @@ public:
     /// by the avro decoder. Similar set of problems occur if the Decoder
     /// consumes more than what it should.
     virtual void drain() = 0;
+
+    /// Returns the number of bytes that remain to be read from the underlying
+    /// stream, or a negative value when that count is not known (for example a
+    /// streaming source, or a decoder not backed by a byte stream). The default
+    /// is "unknown"; byte-stream decoders override it so a length prefix or a
+    /// collection block count that exceeds the data actually available can be
+    /// rejected before allocating for it.
+    virtual int64_t bytesRemaining() const { return -1; }

Review Comment:
   Looking at just the C++ implementation, `remainingBytes` does not appear on main, so it's not a public API change here



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Bound allocation when decoding length-prefixed values and collections [avro]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3567490678


##########
lang/c++/impl/Generic.cc:
##########
@@ -105,11 +267,38 @@ void GenericReader::read(GenericDatum &datum, Decoder &d, bool isResolving) {
             const NodePtr &nn = v.schema()->leafAt(0);
             r.resize(0);
             size_t start = 0;
+            // Only when not resolving: the datum schema then matches the wire
+            // schema, so minBytesPerElement is a true lower bound. Under
+            // resolution the wire (writer) type may be smaller than the datum
+            // (reader) type, which would over-estimate and reject valid data.
+            int64_t trueMin = minBytesPerElement(nn, 0);
+            // Under resolution the on-wire (writer) element can be zero bytes
+            // even when the reader element is not (e.g. reader-only fields filled
+            // from defaults), so the bytes check is disabled and we cannot tell
+            // whether an element is zero-byte on the wire. Apply the tighter
+            // zero-byte cap conservatively in that case, so the up-front resize
+            // cannot be driven past it.
+            bool zeroByte = isResolving || trueMin == 0;

Review Comment:
   In array decoding, `zeroByte` is forced true whenever `isResolving` is true (`zeroByte = isResolving || trueMin == 0`). Because `ensureZeroByteCollectionWithinLimit()` enforces a hard cumulative cap (default 10,000,000), this means *all* resolving array reads are limited to that cap even when the on-wire element type is non-zero-byte. That is a behavior change beyond “cap zero-byte elements”, and it also doesn’t match the nearby comment that frames this as only preventing an up-front resize. Consider plumbing the writer/on-wire element minimum through the resolving path (e.g., via `ResolvingDecoder`) so the zero-byte cap is applied only when the writer element can encode to 0 bytes, while still allowing legitimately large resolving arrays of non-zero-byte elements.



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Bound allocation when decoding length-prefixed values and collections [avro]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3567637499


##########
lang/c++/include/avro/GenericDatum.hh:
##########
@@ -244,6 +244,9 @@ public:
      * \param branch The index for the selected branch.
      */
     void selectBranch(size_t branch) {
+        if (branch >= schema()->leaves()) {
+            throw Exception("Union branch index out of range: must be less than " + std::to_string(schema()->leaves()) + ", but is " + std::to_string(branch));
+        }

Review Comment:
   GenericUnion::selectBranch() now checks branch < schema()->leaves(), but at least BinaryDecoder::decodeUnionIndex() returns `static_cast<size_t>(doDecodeLong())` without validating the decoded long. On platforms where size_t is narrower than int64_t (e.g. 32-bit), a large on-wire union index (e.g. 2^32) can truncate to a small in-range value and bypass this new guard, selecting the wrong union branch instead of rejecting malformed input. Consider validating the decoded union index at decode time (reject idx < 0 and reject values that don’t fit into size_t before casting) so out-of-range indices can’t be “normalized” by truncation/wraparound.



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Bound allocation when decoding length-prefixed values and collections [avro]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3568127303


##########
lang/c++/include/avro/Stream.hh:
##########
@@ -345,6 +356,28 @@ struct StreamReader {
         return next_ != end_ || fill();
     }
 
+    /**
+     * Returns the number of bytes still available to be read: those already
+     * buffered in this reader plus whatever the underlying stream reports as
+     * remaining. Returns a negative value when the underlying stream cannot
+     * report its remaining size.
+     */
+    int64_t remainingBytes() const {
+        if (in_ == nullptr) {
+            return -1;
+        }
+        int64_t streamRemaining = in_->remainingBytes();
+        if (streamRemaining < 0) {
+            return -1;
+        }
+        // Bytes already buffered in this reader, added to what the underlying
+        // stream still has. When next_ and end_ are both null (right after
+        // init()/reset(), before any data is buffered), the subtraction is
+        // well-defined and yields 0.
+        int64_t buffered = end_ - next_;
+        return buffered + streamRemaining;
+    }

Review Comment:
   `StreamReader::remainingBytes()` computes `end_ - next_` even when both pointers are null right after `reset()/init()`. Pointer subtraction on null pointers is undefined behavior in C++, so this can crash or produce arbitrary values (and it contradicts the comment claiming it is well-defined).



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Bound allocation when decoding length-prefixed values and collections [avro]

Posted by "iemejia (via GitHub)" <gi...@apache.org>.
iemejia commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3567467430


##########
lang/c++/impl/BinaryDecoder.cc:
##########
@@ -177,9 +242,27 @@ size_t BinaryDecoder::skipArray() {
     for (;;) {
         auto r = doDecodeLong();
         if (r < 0) {
-            auto n = static_cast<size_t>(doDecodeLong());
-            in_.skipBytes(n);
+            auto byteSize = doDecodeLong();
+            if (byteSize < 0) {
+                // A negative block byte-size would convert to a huge size_t and
+                // drive an unbounded skip; reject it.
+                throw Exception("Invalid negative block size: {}", byteSize);
+            }
+            in_.skipBytes(static_cast<size_t>(byteSize));
         } else {
+            // Bound the block count: skipping a huge block of zero-byte elements
+            // would otherwise loop unboundedly (a CPU exhaustion) even though it
+            // reads/allocates nothing. The decoder has no element schema here, so
+            // apply the structural cap (AVRO_MAX_COLLECTION_ITEMS, default
+            // Integer.MAX_VALUE - 8). Read the limit each call so a runtime
+            // change to the environment variable is honoured, matching Generic.cc.
+            const int64_t structural = maxCollectionStructural();
+            if (r > structural) {
+                throw Exception(
+                    "Cannot skip a collection of more than {} elements; "
+                    "set AVRO_MAX_COLLECTION_ITEMS if this is legitimate",
+                    structural);
+            }
             return static_cast<size_t>(r);

Review Comment:
   Fixed — skipArray now applies the same `if constexpr (sizeof(size_t) < sizeof(int64_t))` size_t-fit guard as doDecodeItemCount before casting the block count, so a count above SIZE_MAX (e.g. from a large env override on 32-bit) is rejected rather than truncated.



##########
lang/c++/include/avro/Stream.hh:
##########
@@ -345,6 +356,28 @@ struct StreamReader {
         return next_ != end_ || fill();
     }
 
+    /**
+     * Returns the number of bytes still available to be read: those already
+     * buffered in this reader plus whatever the underlying stream reports as
+     * remaining. Returns a negative value when the underlying stream cannot
+     * report its remaining size.
+     */
+    int64_t remainingBytes() const {
+        if (in_ == nullptr) {
+            return -1;
+        }
+        int64_t streamRemaining = in_->remainingBytes();
+        if (streamRemaining < 0) {
+            return -1;
+        }
+        // Bytes already buffered in this reader, added to what the underlying
+        // stream still has. When next_ and end_ are both null (right after
+        // init()/reset(), before any data is buffered), the subtraction is
+        // well-defined and yields 0.
+        int64_t buffered = end_ - next_;

Review Comment:
   This subtraction was previously guarded, but a maintainer review (standardizing with the rest of Stream.hh) asked for the guard to be removed; next_ and end_ are always assigned together (both null right after init()/reset(), both valid otherwise), so in the null case the result is 0 in practice. Leaving as-is per that earlier review to avoid churn/conflicting guidance; the comment documents the null case.



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Bound allocation when decoding length-prefixed values and collections [avro]

Posted by "iemejia (via GitHub)" <gi...@apache.org>.
iemejia commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3568217835


##########
lang/c++/include/avro/Stream.hh:
##########
@@ -345,6 +356,28 @@ struct StreamReader {
         return next_ != end_ || fill();
     }
 
+    /**
+     * Returns the number of bytes still available to be read: those already
+     * buffered in this reader plus whatever the underlying stream reports as
+     * remaining. Returns a negative value when the underlying stream cannot
+     * report its remaining size.
+     */
+    int64_t remainingBytes() const {
+        if (in_ == nullptr) {
+            return -1;
+        }
+        int64_t streamRemaining = in_->remainingBytes();
+        if (streamRemaining < 0) {
+            return -1;
+        }
+        // Bytes already buffered in this reader, added to what the underlying
+        // stream still has. When next_ and end_ are both null (right after
+        // init()/reset(), before any data is buffered), the subtraction is
+        // well-defined and yields 0.
+        int64_t buffered = end_ - next_;
+        return buffered + streamRemaining;
+    }

Review Comment:
   Fixed — reconsidered: you're right that subtracting two null pointers is UB even though it yields 0 in practice. remainingBytes() now computes `buffered = (next_ == end_) ? 0 : (end_ - next_)`, so the both-null (post-reset) case returns 0 via a well-defined pointer equality check and the subtraction only runs on real buffer pointers. Updated the misleading comment too.



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Bound allocation when decoding length-prefixed values and collections [avro]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3566497673


##########
lang/c++/impl/Generic.cc:
##########
@@ -25,6 +27,151 @@ using std::ostringstream;
 using std::string;
 using std::vector;
 
+// Minimum number of bytes a single value of the given schema node can occupy on
+// the wire. Used to reject an array/map block count that could not be backed by
+// the bytes remaining. A type that can encode to zero bytes (null) returns 0,
+// which disables the collection check for it (so an array of nulls is not
+// falsely rejected). A depth limit breaks self-referencing (symbolic) schemas.
+static int64_t minBytesPerElement(const NodePtr &node, int depth) {
+    if (!node) {
+        return 0;
+    }
+    switch (node->type()) {
+        case AVRO_NULL:
+            return 0;
+        case AVRO_FLOAT:
+            return 4;
+        case AVRO_DOUBLE:
+            return 8;
+        case AVRO_FIXED: {
+            // fixedSize() is a size_t; clamp to int64_t so a huge fixed size
+            // cannot wrap negative.
+            size_t sz = node->fixedSize();
+            return sz > static_cast<size_t>(std::numeric_limits<int64_t>::max())
+                       ? std::numeric_limits<int64_t>::max()
+                       : static_cast<int64_t>(sz);
+        }
+        case AVRO_RECORD: {
+            if (depth > 64) {
+                // Purely a recursion (stack-overflow) safety net for a
+                // pathologically deep schema. A truly cyclic schema never
+                // reaches this: a self-reference is an AVRO_SYMBOLIC node,
+                // handled by the default case below (returning 1 without
+                // following the link), so recursion always terminates. This
+                // guard therefore only trips on a genuinely deep *acyclic*
+                // record, whose true minimum can still be 0 (e.g. a long chain
+                // of records whose only leaves are null). Return 0 rather than
+                // over-estimating, so a valid array/map of such elements is not
+                // falsely rejected; 0 is always a valid lower bound.
+                return 0;
+            }
+            int64_t total = 0;
+            for (size_t i = 0; i < node->leaves(); ++i) {
+                int64_t fieldMin = minBytesPerElement(node->leafAt(i), depth + 1);
+                // Saturate rather than overflow: a wrapped (negative) total
+                // would disable the collection check.
+                if (fieldMin > std::numeric_limits<int64_t>::max() - total) {
+                    return std::numeric_limits<int64_t>::max();
+                }
+                total += fieldMin;
+            }
+            return total;
+        }
+        default:
+            // boolean, int, long, bytes, string, enum, union, array, map and
+            // symbolic references all encode to at least one byte.
+            return 1;
+    }
+}
+
+// Default maximum number of zero-byte-encoded collection elements (e.g. an
+// array of nulls) to allocate from a single decode. Such elements consume no
+// input, so ensureCollectionAvailable cannot bound their count; without a cap a
+// tiny payload can declare a huge block count and exhaust memory. Overridable
+// via the AVRO_MAX_COLLECTION_ITEMS environment variable.
+static constexpr int64_t kDefaultMaxCollectionItems = 10000000;
+
+// Structural cap on the number of elements in any array or map (an overflow /
+// defense-in-depth guard), matching the historical Integer.MAX_VALUE - 8 limit.
+// Non-zero-byte elements are also bounded by the bytes remaining.
+static constexpr int64_t kDefaultMaxCollectionStructural = 2147483639;
+
+// AVRO_MAX_COLLECTION_ITEMS, when a non-negative integer, caps both limits;
+// otherwise zero-byte elements use the tighter default and all collections use
+// the structural default.
+static void collectionLimits(int64_t &zeroByte, int64_t &structural) {
+    const char *env = std::getenv("AVRO_MAX_COLLECTION_ITEMS");
+    if (env != nullptr && *env != '\0') {
+        char *end = nullptr;
+        long long value = std::strtoll(env, &end, 10);
+        if (*end == '\0' && value >= 0) {
+            zeroByte = structural = static_cast<int64_t>(value);
+            return;
+        }
+    }
+    zeroByte = kDefaultMaxCollectionItems;
+    structural = kDefaultMaxCollectionStructural;
+}
+
+// Reject a collection (array or map) block whose declared element count could
+// not be backed by the bytes actually remaining, before resizing for it.
+// Skipped when the per-element minimum is zero, or when the decoder cannot
+// report how many bytes remain. The comparison divides to avoid overflow.
+static void ensureCollectionAvailable(Decoder &d, size_t existing, size_t count, int64_t minBytes) {
+    if (count == 0 || minBytes <= 0) {
+        return;
+    }
+    int64_t remaining = d.bytesRemaining();
+    if (remaining >= 0 &&
+        static_cast<uint64_t>(count) >
+            static_cast<uint64_t>(remaining) / static_cast<uint64_t>(minBytes)) {
+        throw Exception(
+            "Collection claims {} elements with at least {} bytes each, "
+            "but only {} bytes are available",
+            count, minBytes, remaining);
+    }
+    // Structural / overflow guard, also covering decoders that cannot report the
+    // bytes remaining. Compare without adding so existing + count cannot overflow.
+    int64_t zeroByte, structural;
+    collectionLimits(zeroByte, structural);
+    const uint64_t limit = static_cast<uint64_t>(structural);
+    if (static_cast<uint64_t>(count) > limit ||
+        static_cast<uint64_t>(existing) > limit - static_cast<uint64_t>(count)) {
+        throw Exception(
+            "Cannot read a collection of more than {} elements; "
+            "set AVRO_MAX_COLLECTION_ITEMS if this is legitimate",
+            structural);
+    }

Review Comment:
   ensureCollectionAvailable() returns early when minBytes<=0, which unintentionally skips the structural/overflow cap (despite the comment saying it covers decoders that can’t report remaining bytes). This means array/map decoding under schema resolution (minBytes forced to 0) won’t apply the structural limit at all, allowing very large allocations. Also, the current implementation declares `zeroByte` but never uses it, which will fail the build under -Werror (set-but-not-used).



##########
lang/c++/impl/BinaryDecoder.cc:
##########
@@ -180,6 +215,18 @@ size_t BinaryDecoder::skipArray() {
             auto n = static_cast<size_t>(doDecodeLong());
             in_.skipBytes(n);
         } else {

Review Comment:
   In skipArray(), when the block count is negative, the following “block byte size” long is cast directly to size_t and passed to skipBytes(). A malicious input can provide a negative block size, which will convert to a huge size_t and may cause excessive skipping/reading (DoS) instead of being rejected as invalid.



##########
lang/c++/impl/BinaryDecoder.cc:
##########
@@ -180,6 +215,18 @@ size_t BinaryDecoder::skipArray() {
             auto n = static_cast<size_t>(doDecodeLong());
             in_.skipBytes(n);
         } else {
+            // Bound the block count: skipping a huge block of zero-byte elements
+            // would otherwise loop unboundedly (a CPU exhaustion) even though it
+            // reads/allocates nothing. The decoder has no element schema here, so
+            // apply the structural cap (AVRO_MAX_COLLECTION_ITEMS, default
+            // Integer.MAX_VALUE - 8).
+            static const int64_t structural = maxCollectionStructural();

Review Comment:
   skipArray() caches AVRO_MAX_COLLECTION_ITEMS in a function-local static, so later runtime changes to the environment variable (including other unit tests in the same process) won’t be reflected. Generic.cc reads the env var dynamically each time; doing the same here keeps behavior consistent and avoids cross-test leakage.



##########
lang/c++/impl/Generic.cc:
##########
@@ -25,6 +27,151 @@ using std::ostringstream;
 using std::string;
 using std::vector;
 
+// Minimum number of bytes a single value of the given schema node can occupy on
+// the wire. Used to reject an array/map block count that could not be backed by
+// the bytes remaining. A type that can encode to zero bytes (null) returns 0,
+// which disables the collection check for it (so an array of nulls is not
+// falsely rejected). A depth limit breaks self-referencing (symbolic) schemas.
+static int64_t minBytesPerElement(const NodePtr &node, int depth) {
+    if (!node) {
+        return 0;
+    }
+    switch (node->type()) {
+        case AVRO_NULL:
+            return 0;
+        case AVRO_FLOAT:
+            return 4;
+        case AVRO_DOUBLE:
+            return 8;
+        case AVRO_FIXED: {
+            // fixedSize() is a size_t; clamp to int64_t so a huge fixed size
+            // cannot wrap negative.
+            size_t sz = node->fixedSize();
+            return sz > static_cast<size_t>(std::numeric_limits<int64_t>::max())
+                       ? std::numeric_limits<int64_t>::max()
+                       : static_cast<int64_t>(sz);
+        }
+        case AVRO_RECORD: {
+            if (depth > 64) {
+                // Purely a recursion (stack-overflow) safety net for a
+                // pathologically deep schema. A truly cyclic schema never
+                // reaches this: a self-reference is an AVRO_SYMBOLIC node,
+                // handled by the default case below (returning 1 without
+                // following the link), so recursion always terminates. This
+                // guard therefore only trips on a genuinely deep *acyclic*
+                // record, whose true minimum can still be 0 (e.g. a long chain
+                // of records whose only leaves are null). Return 0 rather than
+                // over-estimating, so a valid array/map of such elements is not
+                // falsely rejected; 0 is always a valid lower bound.
+                return 0;
+            }
+            int64_t total = 0;
+            for (size_t i = 0; i < node->leaves(); ++i) {
+                int64_t fieldMin = minBytesPerElement(node->leafAt(i), depth + 1);
+                // Saturate rather than overflow: a wrapped (negative) total
+                // would disable the collection check.
+                if (fieldMin > std::numeric_limits<int64_t>::max() - total) {
+                    return std::numeric_limits<int64_t>::max();
+                }
+                total += fieldMin;
+            }
+            return total;
+        }
+        default:
+            // boolean, int, long, bytes, string, enum, union, array, map and
+            // symbolic references all encode to at least one byte.
+            return 1;
+    }
+}
+
+// Default maximum number of zero-byte-encoded collection elements (e.g. an
+// array of nulls) to allocate from a single decode. Such elements consume no
+// input, so ensureCollectionAvailable cannot bound their count; without a cap a
+// tiny payload can declare a huge block count and exhaust memory. Overridable
+// via the AVRO_MAX_COLLECTION_ITEMS environment variable.
+static constexpr int64_t kDefaultMaxCollectionItems = 10000000;
+
+// Structural cap on the number of elements in any array or map (an overflow /
+// defense-in-depth guard), matching the historical Integer.MAX_VALUE - 8 limit.
+// Non-zero-byte elements are also bounded by the bytes remaining.
+static constexpr int64_t kDefaultMaxCollectionStructural = 2147483639;
+
+// AVRO_MAX_COLLECTION_ITEMS, when a non-negative integer, caps both limits;
+// otherwise zero-byte elements use the tighter default and all collections use
+// the structural default.
+static void collectionLimits(int64_t &zeroByte, int64_t &structural) {
+    const char *env = std::getenv("AVRO_MAX_COLLECTION_ITEMS");
+    if (env != nullptr && *env != '\0') {
+        char *end = nullptr;
+        long long value = std::strtoll(env, &end, 10);
+        if (*end == '\0' && value >= 0) {
+            zeroByte = structural = static_cast<int64_t>(value);
+            return;
+        }
+    }
+    zeroByte = kDefaultMaxCollectionItems;
+    structural = kDefaultMaxCollectionStructural;
+}
+
+// Reject a collection (array or map) block whose declared element count could
+// not be backed by the bytes actually remaining, before resizing for it.
+// Skipped when the per-element minimum is zero, or when the decoder cannot
+// report how many bytes remain. The comparison divides to avoid overflow.
+static void ensureCollectionAvailable(Decoder &d, size_t existing, size_t count, int64_t minBytes) {
+    if (count == 0 || minBytes <= 0) {
+        return;
+    }
+    int64_t remaining = d.bytesRemaining();
+    if (remaining >= 0 &&
+        static_cast<uint64_t>(count) >
+            static_cast<uint64_t>(remaining) / static_cast<uint64_t>(minBytes)) {
+        throw Exception(
+            "Collection claims {} elements with at least {} bytes each, "
+            "but only {} bytes are available",
+            count, minBytes, remaining);
+    }
+    // Structural / overflow guard, also covering decoders that cannot report the
+    // bytes remaining. Compare without adding so existing + count cannot overflow.
+    int64_t zeroByte, structural;
+    collectionLimits(zeroByte, structural);
+    const uint64_t limit = static_cast<uint64_t>(structural);
+    if (static_cast<uint64_t>(count) > limit ||
+        static_cast<uint64_t>(existing) > limit - static_cast<uint64_t>(count)) {
+        throw Exception(
+            "Cannot read a collection of more than {} elements; "
+            "set AVRO_MAX_COLLECTION_ITEMS if this is legitimate",
+            structural);
+    }
+}
+
+// Reject a collection of zero-byte elements (e.g. null) whose cumulative count
+// exceeds the configured limit. These elements consume no input, so they cannot
+// be bounded by the bytes remaining; the count is the only signal.
+static void ensureZeroByteCollectionWithinLimit(size_t existing, size_t count) {
+    int64_t zeroByte, structural;
+    collectionLimits(zeroByte, structural);
+    const uint64_t limit = static_cast<uint64_t>(zeroByte);

Review Comment:
   ensureZeroByteCollectionWithinLimit() declares `structural` but never uses it, which will fail the build under the project’s -Werror settings (set-but-not-used).



##########
lang/c++/test/AvailableBytesTests.cc:
##########
@@ -0,0 +1,280 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// A bytes/string value is encoded as a length prefix followed by that many
+// bytes of data. A malicious or truncated input can declare a huge length with
+// little or no actual data, which would otherwise trigger a correspondingly
+// huge allocation before the shortfall is noticed. When the input stream can
+// report how many bytes remain (a memory-backed stream), the declared length
+// must be rejected before allocating for it.
+
+#include <cstdint>
+#include <cstdlib>
+#include <memory>
+#include <string>
+#include <vector>
+
+#include <boost/test/included/unit_test.hpp>
+
+#include "Compiler.hh"
+#include "Decoder.hh"
+#include "Encoder.hh"
+#include "Exception.hh"
+#include "Generic.hh"
+#include "Stream.hh"
+#include "ValidSchema.hh"
+
+namespace avro {
+
+// Reading a bytes value whose declared length far exceeds the tiny backing
+// buffer must throw instead of attempting a huge allocation.
+static void testDecodeBytesRejectsOversizedLength() {
+    // 0xFE 0x01 is the zig-zag long 127; the buffer carries no data after it.
+    const uint8_t data[] = {0xFE, 0x01};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::vector<uint8_t> value;
+    BOOST_CHECK_THROW(d->decodeBytes(value), Exception);
+}
+
+static void testDecodeStringRejectsOversizedLength() {
+    const uint8_t data[] = {0xFE, 0x01};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::string value;
+    BOOST_CHECK_THROW(d->decodeString(value), Exception);
+}
+
+// A well-formed value whose declared length fits the buffer still decodes.
+static void testDecodeStringWithinLimitStillReads() {
+    // length 3 (zig-zag 6 -> 0x06) followed by "abc".
+    const uint8_t data[] = {0x06, 'a', 'b', 'c'};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::string value;
+    d->decodeString(value);
+    BOOST_CHECK_EQUAL(value, std::string("abc"));
+}
+
+static void testDecodeBytesWithinLimitStillReads() {
+    const uint8_t data[] = {0x06, 0x01, 0x02, 0x03};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::vector<uint8_t> value;
+    d->decodeBytes(value);
+    BOOST_CHECK_EQUAL(value.size(), 3u);
+    BOOST_CHECK_EQUAL(value[0], 1);
+    BOOST_CHECK_EQUAL(value[2], 3);
+}
+
+// An array/map block declares an element count; a malicious or truncated input
+// can declare far more elements than the remaining bytes could hold. The count
+// is validated against the bytes remaining before resizing, using the minimum
+// on-wire size of the element schema (so 0-byte elements like null are not
+// falsely rejected).
+static GenericDatum decodeCollectionHeader(const ValidSchema &s, int64_t blockCount,
+                                           bool addEndMarker) {
+    // Keep the output stream alive for the whole decode: memoryInputStream
+    // references the output stream's buffer rather than copying it.
+    std::unique_ptr<OutputStream> os = memoryOutputStream();
+    EncoderPtr e = binaryEncoder();
+    e->init(*os);
+    e->encodeLong(blockCount);
+    if (addEndMarker) {
+        e->encodeLong(0);
+    }
+    e->flush();
+
+    InputStreamPtr in = memoryInputStream(*os);
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    GenericDatum datum;
+    GenericReader::read(*d, datum, s);
+    return datum;
+}
+
+static void testReadArrayRejectsOversizedCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"long\"}");
+    // 1,000,000 long elements declared, but no element data follows.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1000000, false), Exception);
+}
+
+static void testReadMapRejectsOversizedCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"map\",\"values\":\"long\"}");
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1000000, false), Exception);
+}
+
+static void testReadArrayOfNullNotFalselyRejected() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // 100,000 nulls (zero bytes each) is legitimate and must decode.
+    GenericDatum datum = decodeCollectionHeader(s, 100000, true);
+    BOOST_CHECK_EQUAL(datum.value<GenericArray>().value().size(), 100000u);
+}
+
+// A deeply but acyclically nested record whose only leaf is null encodes to
+// zero bytes, so the per-element minimum must be 0 and a large array of such
+// records must not be falsely rejected. This exercises the recursion depth
+// guard in minBytesPerElement(), which must yield a conservative lower bound
+// (0) rather than over-estimating for a legitimately deep schema.
+static void testReadArrayOfDeeplyNestedNullNotFalselyRejected() {
+    // Build ~70 nested records: R0 { null f; }, R1 { R0 f; }, ... The nesting
+    // exceeds the depth guard, yet every leaf is null so the true minimum is 0.
+    std::string schema = "\"null\"";
+    for (int i = 0; i < 70; ++i) {
+        schema = "{\"type\":\"record\",\"name\":\"R" + std::to_string(i) +
+                 "\",\"fields\":[{\"name\":\"f\",\"type\":" + schema + "}]}";
+    }
+    ValidSchema s = compileJsonSchemaFromString(
+        ("{\"type\":\"array\",\"items\":" + schema + "}").c_str());
+    // 100,000 zero-byte elements is legitimate and must decode.
+    GenericDatum datum = decodeCollectionHeader(s, 100000, true);
+    BOOST_CHECK_EQUAL(datum.value<GenericArray>().value().size(), 100000u);
+}
+
+// Calling bytesRemaining() immediately after init(), before any data has been
+// buffered, must be well-defined (the underlying StreamReader must not subtract
+// null buffer pointers) and report the whole stream as available.
+static void testBytesRemainingRightAfterInit() {
+    const uint8_t data[] = {0x06, 'a', 'b', 'c'};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    BOOST_CHECK_EQUAL(d->bytesRemaining(), static_cast<int64_t>(sizeof(data)));
+}
+
+// Zero-byte elements (null, a record with only zero-byte fields) consume no
+// input, so ensureCollectionAvailable cannot bound their count. A huge declared
+// block count of such elements is capped against a configurable limit.
+static GenericDatum decodeLongs(const ValidSchema &s, const std::vector<int64_t> &longs) {
+    std::unique_ptr<OutputStream> os = memoryOutputStream();
+    EncoderPtr e = binaryEncoder();
+    e->init(*os);
+    for (int64_t v : longs) {
+        e->encodeLong(v);
+    }
+    e->flush();
+    InputStreamPtr in = memoryInputStream(*os);
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    GenericDatum datum;
+    GenericReader::read(*d, datum, s);
+    return datum;
+}
+
+static void testReadArrayOfNullRejectsCountAboveDefaultLimit() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // The reported exploit: 200,000,000 nulls rejected by the default limit.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, true), Exception);
+}
+
+static void testReadArrayOfAllNullRecordRejectsHugeCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":"
+        "{\"type\":\"record\",\"name\":\"R\",\"fields\":[{\"name\":\"n\",\"type\":\"null\"}]}}");
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, true), Exception);
+}
+
+static void testReadArrayOfNullRejectsNegativeCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // Negative count (-200M), block byte-size 0, end marker 0: normalized to
+    // 200M and still bounded.
+    BOOST_CHECK_THROW(decodeLongs(s, {-200000000, 0, 0}), Exception);
+}
+
+static void testReadMapOfNullRejectedByAvailableBytes() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"map\",\"values\":\"null\"}");
+    // Each map entry carries a >= 1 byte key, so a huge map<null> is bounded by
+    // the bytes-remaining check.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, false), Exception);
+}
+
+static void testReadArrayOfNullRespectsConfiguredLimit() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    setenv("AVRO_MAX_COLLECTION_ITEMS", "1000", 1);
+    // Within the limit decodes; over the limit and cumulative are rejected.
+    GenericDatum ok = decodeCollectionHeader(s, 1000, true);
+    BOOST_CHECK_EQUAL(ok.value<GenericArray>().value().size(), 1000u);
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1001, true), Exception);
+    BOOST_CHECK_THROW(decodeLongs(s, {600, 600, 0}), Exception);
+    unsetenv("AVRO_MAX_COLLECTION_ITEMS");

Review Comment:
   These tests use setenv()/unsetenv(), which are not available on Windows builds. Also, unconditionally unsetting the variable can leak state if AVRO_MAX_COLLECTION_ITEMS was already set in the environment before the test ran. Prefer a cross-platform set/unset that restores the previous value.



##########
lang/c++/test/AvailableBytesTests.cc:
##########
@@ -0,0 +1,280 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// A bytes/string value is encoded as a length prefix followed by that many
+// bytes of data. A malicious or truncated input can declare a huge length with
+// little or no actual data, which would otherwise trigger a correspondingly
+// huge allocation before the shortfall is noticed. When the input stream can
+// report how many bytes remain (a memory-backed stream), the declared length
+// must be rejected before allocating for it.
+
+#include <cstdint>
+#include <cstdlib>
+#include <memory>
+#include <string>
+#include <vector>
+
+#include <boost/test/included/unit_test.hpp>
+
+#include "Compiler.hh"
+#include "Decoder.hh"
+#include "Encoder.hh"
+#include "Exception.hh"
+#include "Generic.hh"
+#include "Stream.hh"
+#include "ValidSchema.hh"
+
+namespace avro {
+
+// Reading a bytes value whose declared length far exceeds the tiny backing
+// buffer must throw instead of attempting a huge allocation.
+static void testDecodeBytesRejectsOversizedLength() {
+    // 0xFE 0x01 is the zig-zag long 127; the buffer carries no data after it.
+    const uint8_t data[] = {0xFE, 0x01};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::vector<uint8_t> value;
+    BOOST_CHECK_THROW(d->decodeBytes(value), Exception);
+}
+
+static void testDecodeStringRejectsOversizedLength() {
+    const uint8_t data[] = {0xFE, 0x01};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::string value;
+    BOOST_CHECK_THROW(d->decodeString(value), Exception);
+}
+
+// A well-formed value whose declared length fits the buffer still decodes.
+static void testDecodeStringWithinLimitStillReads() {
+    // length 3 (zig-zag 6 -> 0x06) followed by "abc".
+    const uint8_t data[] = {0x06, 'a', 'b', 'c'};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::string value;
+    d->decodeString(value);
+    BOOST_CHECK_EQUAL(value, std::string("abc"));
+}
+
+static void testDecodeBytesWithinLimitStillReads() {
+    const uint8_t data[] = {0x06, 0x01, 0x02, 0x03};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::vector<uint8_t> value;
+    d->decodeBytes(value);
+    BOOST_CHECK_EQUAL(value.size(), 3u);
+    BOOST_CHECK_EQUAL(value[0], 1);
+    BOOST_CHECK_EQUAL(value[2], 3);
+}
+
+// An array/map block declares an element count; a malicious or truncated input
+// can declare far more elements than the remaining bytes could hold. The count
+// is validated against the bytes remaining before resizing, using the minimum
+// on-wire size of the element schema (so 0-byte elements like null are not
+// falsely rejected).
+static GenericDatum decodeCollectionHeader(const ValidSchema &s, int64_t blockCount,
+                                           bool addEndMarker) {
+    // Keep the output stream alive for the whole decode: memoryInputStream
+    // references the output stream's buffer rather than copying it.
+    std::unique_ptr<OutputStream> os = memoryOutputStream();
+    EncoderPtr e = binaryEncoder();
+    e->init(*os);
+    e->encodeLong(blockCount);
+    if (addEndMarker) {
+        e->encodeLong(0);
+    }
+    e->flush();
+
+    InputStreamPtr in = memoryInputStream(*os);
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    GenericDatum datum;
+    GenericReader::read(*d, datum, s);
+    return datum;
+}
+
+static void testReadArrayRejectsOversizedCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"long\"}");
+    // 1,000,000 long elements declared, but no element data follows.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1000000, false), Exception);
+}
+
+static void testReadMapRejectsOversizedCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"map\",\"values\":\"long\"}");
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1000000, false), Exception);
+}
+
+static void testReadArrayOfNullNotFalselyRejected() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // 100,000 nulls (zero bytes each) is legitimate and must decode.
+    GenericDatum datum = decodeCollectionHeader(s, 100000, true);
+    BOOST_CHECK_EQUAL(datum.value<GenericArray>().value().size(), 100000u);
+}
+
+// A deeply but acyclically nested record whose only leaf is null encodes to
+// zero bytes, so the per-element minimum must be 0 and a large array of such
+// records must not be falsely rejected. This exercises the recursion depth
+// guard in minBytesPerElement(), which must yield a conservative lower bound
+// (0) rather than over-estimating for a legitimately deep schema.
+static void testReadArrayOfDeeplyNestedNullNotFalselyRejected() {
+    // Build ~70 nested records: R0 { null f; }, R1 { R0 f; }, ... The nesting
+    // exceeds the depth guard, yet every leaf is null so the true minimum is 0.
+    std::string schema = "\"null\"";
+    for (int i = 0; i < 70; ++i) {
+        schema = "{\"type\":\"record\",\"name\":\"R" + std::to_string(i) +
+                 "\",\"fields\":[{\"name\":\"f\",\"type\":" + schema + "}]}";
+    }
+    ValidSchema s = compileJsonSchemaFromString(
+        ("{\"type\":\"array\",\"items\":" + schema + "}").c_str());
+    // 100,000 zero-byte elements is legitimate and must decode.
+    GenericDatum datum = decodeCollectionHeader(s, 100000, true);
+    BOOST_CHECK_EQUAL(datum.value<GenericArray>().value().size(), 100000u);
+}
+
+// Calling bytesRemaining() immediately after init(), before any data has been
+// buffered, must be well-defined (the underlying StreamReader must not subtract
+// null buffer pointers) and report the whole stream as available.
+static void testBytesRemainingRightAfterInit() {
+    const uint8_t data[] = {0x06, 'a', 'b', 'c'};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    BOOST_CHECK_EQUAL(d->bytesRemaining(), static_cast<int64_t>(sizeof(data)));
+}
+
+// Zero-byte elements (null, a record with only zero-byte fields) consume no
+// input, so ensureCollectionAvailable cannot bound their count. A huge declared
+// block count of such elements is capped against a configurable limit.
+static GenericDatum decodeLongs(const ValidSchema &s, const std::vector<int64_t> &longs) {
+    std::unique_ptr<OutputStream> os = memoryOutputStream();
+    EncoderPtr e = binaryEncoder();
+    e->init(*os);
+    for (int64_t v : longs) {
+        e->encodeLong(v);
+    }
+    e->flush();
+    InputStreamPtr in = memoryInputStream(*os);
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    GenericDatum datum;
+    GenericReader::read(*d, datum, s);
+    return datum;
+}
+
+static void testReadArrayOfNullRejectsCountAboveDefaultLimit() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // The reported exploit: 200,000,000 nulls rejected by the default limit.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, true), Exception);
+}
+
+static void testReadArrayOfAllNullRecordRejectsHugeCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":"
+        "{\"type\":\"record\",\"name\":\"R\",\"fields\":[{\"name\":\"n\",\"type\":\"null\"}]}}");
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, true), Exception);
+}
+
+static void testReadArrayOfNullRejectsNegativeCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // Negative count (-200M), block byte-size 0, end marker 0: normalized to
+    // 200M and still bounded.
+    BOOST_CHECK_THROW(decodeLongs(s, {-200000000, 0, 0}), Exception);
+}
+
+static void testReadMapOfNullRejectedByAvailableBytes() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"map\",\"values\":\"null\"}");
+    // Each map entry carries a >= 1 byte key, so a huge map<null> is bounded by
+    // the bytes-remaining check.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, false), Exception);
+}
+
+static void testReadArrayOfNullRespectsConfiguredLimit() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    setenv("AVRO_MAX_COLLECTION_ITEMS", "1000", 1);
+    // Within the limit decodes; over the limit and cumulative are rejected.
+    GenericDatum ok = decodeCollectionHeader(s, 1000, true);
+    BOOST_CHECK_EQUAL(ok.value<GenericArray>().value().size(), 1000u);
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1001, true), Exception);
+    BOOST_CHECK_THROW(decodeLongs(s, {600, 600, 0}), Exception);
+    unsetenv("AVRO_MAX_COLLECTION_ITEMS");
+}
+
+// A backed non-zero-byte array that passes the bytes check is still bounded by
+// the structural cap (exercised with a lowered limit).
+static void testReadArrayOfLongRejectedByStructuralCap() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"long\"}");
+    setenv("AVRO_MAX_COLLECTION_ITEMS", "5", 1);
+    // 10 real longs: block count 10, ten 1-byte longs, end marker.
+    std::vector<int64_t> longs = {10, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
+    BOOST_CHECK_THROW(decodeLongs(s, longs), Exception);
+    unsetenv("AVRO_MAX_COLLECTION_ITEMS");
+}
+
+// Skipping a huge array (via the decoder's skipArray) is bounded by the
+// structural cap.
+static void testSkipArrayRejectsHugeCount() {
+    setenv("AVRO_MAX_COLLECTION_ITEMS", "1000", 1);
+    std::unique_ptr<OutputStream> os = memoryOutputStream();
+    EncoderPtr e = binaryEncoder();
+    e->init(*os);
+    e->encodeLong(2000); // block count 2000, no data needed (skip throws first)
+    e->flush();
+    InputStreamPtr in = memoryInputStream(*os);
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    BOOST_CHECK_THROW(d->skipArray(), Exception);
+    unsetenv("AVRO_MAX_COLLECTION_ITEMS");
+}

Review Comment:
   Same portability/state-leak issue for AVRO_MAX_COLLECTION_ITEMS in this test: use a cross-platform setter and restore the previous value after the assertion.



##########
lang/c++/test/AvailableBytesTests.cc:
##########
@@ -0,0 +1,280 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// A bytes/string value is encoded as a length prefix followed by that many
+// bytes of data. A malicious or truncated input can declare a huge length with
+// little or no actual data, which would otherwise trigger a correspondingly
+// huge allocation before the shortfall is noticed. When the input stream can
+// report how many bytes remain (a memory-backed stream), the declared length
+// must be rejected before allocating for it.
+
+#include <cstdint>
+#include <cstdlib>
+#include <memory>
+#include <string>
+#include <vector>
+
+#include <boost/test/included/unit_test.hpp>
+
+#include "Compiler.hh"
+#include "Decoder.hh"
+#include "Encoder.hh"
+#include "Exception.hh"
+#include "Generic.hh"
+#include "Stream.hh"
+#include "ValidSchema.hh"
+
+namespace avro {
+
+// Reading a bytes value whose declared length far exceeds the tiny backing
+// buffer must throw instead of attempting a huge allocation.
+static void testDecodeBytesRejectsOversizedLength() {
+    // 0xFE 0x01 is the zig-zag long 127; the buffer carries no data after it.
+    const uint8_t data[] = {0xFE, 0x01};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::vector<uint8_t> value;
+    BOOST_CHECK_THROW(d->decodeBytes(value), Exception);
+}
+
+static void testDecodeStringRejectsOversizedLength() {
+    const uint8_t data[] = {0xFE, 0x01};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::string value;
+    BOOST_CHECK_THROW(d->decodeString(value), Exception);
+}
+
+// A well-formed value whose declared length fits the buffer still decodes.
+static void testDecodeStringWithinLimitStillReads() {
+    // length 3 (zig-zag 6 -> 0x06) followed by "abc".
+    const uint8_t data[] = {0x06, 'a', 'b', 'c'};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::string value;
+    d->decodeString(value);
+    BOOST_CHECK_EQUAL(value, std::string("abc"));
+}
+
+static void testDecodeBytesWithinLimitStillReads() {
+    const uint8_t data[] = {0x06, 0x01, 0x02, 0x03};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::vector<uint8_t> value;
+    d->decodeBytes(value);
+    BOOST_CHECK_EQUAL(value.size(), 3u);
+    BOOST_CHECK_EQUAL(value[0], 1);
+    BOOST_CHECK_EQUAL(value[2], 3);
+}
+
+// An array/map block declares an element count; a malicious or truncated input
+// can declare far more elements than the remaining bytes could hold. The count
+// is validated against the bytes remaining before resizing, using the minimum
+// on-wire size of the element schema (so 0-byte elements like null are not
+// falsely rejected).
+static GenericDatum decodeCollectionHeader(const ValidSchema &s, int64_t blockCount,
+                                           bool addEndMarker) {
+    // Keep the output stream alive for the whole decode: memoryInputStream
+    // references the output stream's buffer rather than copying it.
+    std::unique_ptr<OutputStream> os = memoryOutputStream();
+    EncoderPtr e = binaryEncoder();
+    e->init(*os);
+    e->encodeLong(blockCount);
+    if (addEndMarker) {
+        e->encodeLong(0);
+    }
+    e->flush();
+
+    InputStreamPtr in = memoryInputStream(*os);
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    GenericDatum datum;
+    GenericReader::read(*d, datum, s);
+    return datum;
+}
+
+static void testReadArrayRejectsOversizedCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"long\"}");
+    // 1,000,000 long elements declared, but no element data follows.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1000000, false), Exception);
+}
+
+static void testReadMapRejectsOversizedCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"map\",\"values\":\"long\"}");
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1000000, false), Exception);
+}
+
+static void testReadArrayOfNullNotFalselyRejected() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // 100,000 nulls (zero bytes each) is legitimate and must decode.
+    GenericDatum datum = decodeCollectionHeader(s, 100000, true);
+    BOOST_CHECK_EQUAL(datum.value<GenericArray>().value().size(), 100000u);
+}
+
+// A deeply but acyclically nested record whose only leaf is null encodes to
+// zero bytes, so the per-element minimum must be 0 and a large array of such
+// records must not be falsely rejected. This exercises the recursion depth
+// guard in minBytesPerElement(), which must yield a conservative lower bound
+// (0) rather than over-estimating for a legitimately deep schema.
+static void testReadArrayOfDeeplyNestedNullNotFalselyRejected() {
+    // Build ~70 nested records: R0 { null f; }, R1 { R0 f; }, ... The nesting
+    // exceeds the depth guard, yet every leaf is null so the true minimum is 0.
+    std::string schema = "\"null\"";
+    for (int i = 0; i < 70; ++i) {
+        schema = "{\"type\":\"record\",\"name\":\"R" + std::to_string(i) +
+                 "\",\"fields\":[{\"name\":\"f\",\"type\":" + schema + "}]}";
+    }
+    ValidSchema s = compileJsonSchemaFromString(
+        ("{\"type\":\"array\",\"items\":" + schema + "}").c_str());
+    // 100,000 zero-byte elements is legitimate and must decode.
+    GenericDatum datum = decodeCollectionHeader(s, 100000, true);
+    BOOST_CHECK_EQUAL(datum.value<GenericArray>().value().size(), 100000u);
+}
+
+// Calling bytesRemaining() immediately after init(), before any data has been
+// buffered, must be well-defined (the underlying StreamReader must not subtract
+// null buffer pointers) and report the whole stream as available.
+static void testBytesRemainingRightAfterInit() {
+    const uint8_t data[] = {0x06, 'a', 'b', 'c'};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    BOOST_CHECK_EQUAL(d->bytesRemaining(), static_cast<int64_t>(sizeof(data)));
+}
+
+// Zero-byte elements (null, a record with only zero-byte fields) consume no
+// input, so ensureCollectionAvailable cannot bound their count. A huge declared
+// block count of such elements is capped against a configurable limit.
+static GenericDatum decodeLongs(const ValidSchema &s, const std::vector<int64_t> &longs) {
+    std::unique_ptr<OutputStream> os = memoryOutputStream();
+    EncoderPtr e = binaryEncoder();
+    e->init(*os);
+    for (int64_t v : longs) {
+        e->encodeLong(v);
+    }
+    e->flush();
+    InputStreamPtr in = memoryInputStream(*os);
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    GenericDatum datum;
+    GenericReader::read(*d, datum, s);
+    return datum;
+}
+
+static void testReadArrayOfNullRejectsCountAboveDefaultLimit() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // The reported exploit: 200,000,000 nulls rejected by the default limit.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, true), Exception);
+}
+
+static void testReadArrayOfAllNullRecordRejectsHugeCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":"
+        "{\"type\":\"record\",\"name\":\"R\",\"fields\":[{\"name\":\"n\",\"type\":\"null\"}]}}");
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, true), Exception);
+}
+
+static void testReadArrayOfNullRejectsNegativeCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // Negative count (-200M), block byte-size 0, end marker 0: normalized to
+    // 200M and still bounded.
+    BOOST_CHECK_THROW(decodeLongs(s, {-200000000, 0, 0}), Exception);
+}
+
+static void testReadMapOfNullRejectedByAvailableBytes() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"map\",\"values\":\"null\"}");
+    // Each map entry carries a >= 1 byte key, so a huge map<null> is bounded by
+    // the bytes-remaining check.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, false), Exception);
+}
+
+static void testReadArrayOfNullRespectsConfiguredLimit() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    setenv("AVRO_MAX_COLLECTION_ITEMS", "1000", 1);
+    // Within the limit decodes; over the limit and cumulative are rejected.
+    GenericDatum ok = decodeCollectionHeader(s, 1000, true);
+    BOOST_CHECK_EQUAL(ok.value<GenericArray>().value().size(), 1000u);
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1001, true), Exception);
+    BOOST_CHECK_THROW(decodeLongs(s, {600, 600, 0}), Exception);
+    unsetenv("AVRO_MAX_COLLECTION_ITEMS");
+}
+
+// A backed non-zero-byte array that passes the bytes check is still bounded by
+// the structural cap (exercised with a lowered limit).
+static void testReadArrayOfLongRejectedByStructuralCap() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"long\"}");
+    setenv("AVRO_MAX_COLLECTION_ITEMS", "5", 1);
+    // 10 real longs: block count 10, ten 1-byte longs, end marker.
+    std::vector<int64_t> longs = {10, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
+    BOOST_CHECK_THROW(decodeLongs(s, longs), Exception);
+    unsetenv("AVRO_MAX_COLLECTION_ITEMS");

Review Comment:
   Same issue here: setenv()/unsetenv() is POSIX-only and the test should restore any pre-existing AVRO_MAX_COLLECTION_ITEMS value instead of always unsetting it.



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Bound allocation when decoding length-prefixed values and collections [avro]

Posted by "iemejia (via GitHub)" <gi...@apache.org>.
iemejia commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3566776303


##########
lang/c++/impl/Generic.cc:
##########
@@ -25,6 +26,86 @@ using std::ostringstream;
 using std::string;
 using std::vector;
 
+// Minimum number of bytes a single value of the given schema node can occupy on
+// the wire. Used to reject an array/map block count that could not be backed by
+// the bytes remaining. A type that can encode to zero bytes (null) returns 0,
+// which disables the collection check for it (so an array of nulls is not
+// falsely rejected). A depth limit breaks self-referencing (symbolic) schemas.
+static int64_t minBytesPerElement(const NodePtr &node, int depth) {
+    if (!node) {
+        return 0;
+    }
+    if (depth > 64) {
+        // A cyclic or pathologically deep schema. Return 1 (not 0) so the
+        // collection check stays enabled rather than being silently bypassed;
+        // a valid recursive value always encodes to at least 1 byte.
+        return 1;
+    }
+    switch (node->type()) {
+        case AVRO_NULL:
+            return 0;
+        case AVRO_FLOAT:
+            return 4;
+        case AVRO_DOUBLE:
+            return 8;
+        case AVRO_FIXED: {
+            // fixedSize() is a size_t; clamp to int64_t so a huge fixed size
+            // cannot wrap negative.
+            size_t sz = node->fixedSize();
+            return sz > static_cast<size_t>(std::numeric_limits<int64_t>::max())

Review Comment:
   Fixed in a91347f377: the fixed-size clamp now reads `return std::min<uint64_t>(node->fixedSize(), INT64_MAX)` cast to int64_t.



##########
lang/c++/impl/Generic.cc:
##########
@@ -105,7 +156,13 @@ void GenericReader::read(GenericDatum &datum, Decoder &d, bool isResolving) {
             const NodePtr &nn = v.schema()->leafAt(0);
             r.resize(0);
             size_t start = 0;
+            // Only when not resolving: the datum schema then matches the wire
+            // schema, so minBytesPerElement is a true lower bound. Under
+            // resolution the wire (writer) type may be smaller than the datum
+            // (reader) type, which would over-estimate and reject valid data.
+            int64_t minBytes = isResolving ? 0 : minBytesPerElement(nn, 0);
             for (size_t m = d.arrayStart(); m != 0; m = d.arrayNext()) {
+                ensureCollectionAvailable(d, m, minBytes);
                 r.resize(r.size() + m);

Review Comment:
   It is nearly always unreachable now that the structural cap (<= 2147483639) is always applied, so I kept it only as a cheap guard for the edge where `max_size()` is smaller than that cap (32-bit builds, or very large element types), where `resize()` would otherwise throw a raw std::length_error instead of a clean Avro Exception. Happy to drop it if you'd prefer to rely on resize()'s own throw.



##########
lang/c++/impl/BinaryDecoder.cc:
##########
@@ -19,12 +19,28 @@
 #include "Decoder.hh"
 #include "Exception.hh"
 #include "Zigzag.hh"
+#include <cstdlib>
 #include <memory>
 
 namespace avro {
 
 using std::make_shared;
 
+// Structural cap on the number of elements to skip in an array or map. Mirrors
+// the read-path limit in Generic.cc; AVRO_MAX_COLLECTION_ITEMS, when a
+// non-negative integer, overrides it.
+static int64_t maxCollectionStructural() {
+    const char *env = std::getenv("AVRO_MAX_COLLECTION_ITEMS");

Review Comment:
   Documented in a91347f377 (the env var and its default). It's read consistently across all Avro SDKs so a single knob configures them, which is why it's an env var rather than decoder state. A programmatic per-decoder setter would be a reasonable follow-up if you'd like one — happy to file it.



##########
lang/c++/impl/BinaryDecoder.cc:
##########
@@ -19,12 +19,28 @@
 #include "Decoder.hh"
 #include "Exception.hh"
 #include "Zigzag.hh"
+#include <cstdlib>
 #include <memory>
 
 namespace avro {
 
 using std::make_shared;
 
+// Structural cap on the number of elements to skip in an array or map. Mirrors
+// the read-path limit in Generic.cc; AVRO_MAX_COLLECTION_ITEMS, when a
+// non-negative integer, overrides it.
+static int64_t maxCollectionStructural() {
+    const char *env = std::getenv("AVRO_MAX_COLLECTION_ITEMS");
+    if (env != nullptr && *env != '\0') {
+        char *end = nullptr;
+        long long value = std::strtoll(env, &end, 10);
+        if (*end == '\0' && value >= 0) {
+            return static_cast<int64_t>(value);
+        }
+    }
+    return 2147483639;

Review Comment:
   Fixed in a91347f377: replaced the duplicated literal with a named `kDefaultMaxCollectionStructural` constant.



##########
lang/c++/impl/Generic.cc:
##########
@@ -25,6 +27,151 @@ using std::ostringstream;
 using std::string;
 using std::vector;
 
+// Minimum number of bytes a single value of the given schema node can occupy on
+// the wire. Used to reject an array/map block count that could not be backed by
+// the bytes remaining. A type that can encode to zero bytes (null) returns 0,
+// which disables the collection check for it (so an array of nulls is not
+// falsely rejected). A depth limit breaks self-referencing (symbolic) schemas.
+static int64_t minBytesPerElement(const NodePtr &node, int depth) {
+    if (!node) {
+        return 0;
+    }
+    switch (node->type()) {
+        case AVRO_NULL:
+            return 0;
+        case AVRO_FLOAT:
+            return 4;
+        case AVRO_DOUBLE:
+            return 8;
+        case AVRO_FIXED: {
+            // fixedSize() is a size_t; clamp to int64_t so a huge fixed size
+            // cannot wrap negative.
+            size_t sz = node->fixedSize();
+            return sz > static_cast<size_t>(std::numeric_limits<int64_t>::max())
+                       ? std::numeric_limits<int64_t>::max()
+                       : static_cast<int64_t>(sz);
+        }
+        case AVRO_RECORD: {
+            if (depth > 64) {
+                // Purely a recursion (stack-overflow) safety net for a
+                // pathologically deep schema. A truly cyclic schema never
+                // reaches this: a self-reference is an AVRO_SYMBOLIC node,
+                // handled by the default case below (returning 1 without
+                // following the link), so recursion always terminates. This
+                // guard therefore only trips on a genuinely deep *acyclic*
+                // record, whose true minimum can still be 0 (e.g. a long chain
+                // of records whose only leaves are null). Return 0 rather than
+                // over-estimating, so a valid array/map of such elements is not
+                // falsely rejected; 0 is always a valid lower bound.
+                return 0;
+            }
+            int64_t total = 0;
+            for (size_t i = 0; i < node->leaves(); ++i) {
+                int64_t fieldMin = minBytesPerElement(node->leafAt(i), depth + 1);
+                // Saturate rather than overflow: a wrapped (negative) total
+                // would disable the collection check.
+                if (fieldMin > std::numeric_limits<int64_t>::max() - total) {
+                    return std::numeric_limits<int64_t>::max();
+                }
+                total += fieldMin;
+            }
+            return total;
+        }
+        default:
+            // boolean, int, long, bytes, string, enum, union, array, map and
+            // symbolic references all encode to at least one byte.
+            return 1;
+    }
+}
+
+// Default maximum number of zero-byte-encoded collection elements (e.g. an
+// array of nulls) to allocate from a single decode. Such elements consume no
+// input, so ensureCollectionAvailable cannot bound their count; without a cap a
+// tiny payload can declare a huge block count and exhaust memory. Overridable
+// via the AVRO_MAX_COLLECTION_ITEMS environment variable.
+static constexpr int64_t kDefaultMaxCollectionItems = 10000000;
+
+// Structural cap on the number of elements in any array or map (an overflow /
+// defense-in-depth guard), matching the historical Integer.MAX_VALUE - 8 limit.

Review Comment:
   Fixed in a91347f377: reworded — C++ never had that Java limit; the comment now just says the value matches the one used by the other SDKs.



##########
lang/c++/include/avro/Decoder.hh:
##########
@@ -169,6 +169,14 @@ public:
     /// by the avro decoder. Similar set of problems occur if the Decoder
     /// consumes more than what it should.
     virtual void drain() = 0;
+
+    /// Returns the number of bytes that remain to be read from the underlying
+    /// stream, or a negative value when that count is not known (for example a
+    /// streaming source, or a decoder not backed by a byte stream). The default
+    /// is "unknown"; byte-stream decoders override it so a length prefix or a
+    /// collection block count that exceeds the data actually available can be
+    /// rejected before allocating for it.
+    virtual int64_t bytesRemaining() const { return -1; }

Review Comment:
   Acknowledged. They're two different interfaces (`Decoder::bytesRemaining()` vs `InputStream`/`StreamReader::remainingBytes()`), which is why the names diverged. Renaming either is a public-API change, so I left it for now; I can align them (deprecating the old name) in a follow-up if you'd like.



##########
lang/c++/impl/Generic.cc:
##########
@@ -25,6 +27,151 @@ using std::ostringstream;
 using std::string;
 using std::vector;
 
+// Minimum number of bytes a single value of the given schema node can occupy on
+// the wire. Used to reject an array/map block count that could not be backed by
+// the bytes remaining. A type that can encode to zero bytes (null) returns 0,
+// which disables the collection check for it (so an array of nulls is not
+// falsely rejected). A depth limit breaks self-referencing (symbolic) schemas.
+static int64_t minBytesPerElement(const NodePtr &node, int depth) {
+    if (!node) {
+        return 0;
+    }
+    switch (node->type()) {
+        case AVRO_NULL:
+            return 0;
+        case AVRO_FLOAT:
+            return 4;
+        case AVRO_DOUBLE:
+            return 8;
+        case AVRO_FIXED: {
+            // fixedSize() is a size_t; clamp to int64_t so a huge fixed size
+            // cannot wrap negative.
+            size_t sz = node->fixedSize();
+            return sz > static_cast<size_t>(std::numeric_limits<int64_t>::max())
+                       ? std::numeric_limits<int64_t>::max()
+                       : static_cast<int64_t>(sz);
+        }
+        case AVRO_RECORD: {
+            if (depth > 64) {
+                // Purely a recursion (stack-overflow) safety net for a
+                // pathologically deep schema. A truly cyclic schema never
+                // reaches this: a self-reference is an AVRO_SYMBOLIC node,
+                // handled by the default case below (returning 1 without
+                // following the link), so recursion always terminates. This
+                // guard therefore only trips on a genuinely deep *acyclic*
+                // record, whose true minimum can still be 0 (e.g. a long chain
+                // of records whose only leaves are null). Return 0 rather than
+                // over-estimating, so a valid array/map of such elements is not
+                // falsely rejected; 0 is always a valid lower bound.
+                return 0;
+            }
+            int64_t total = 0;
+            for (size_t i = 0; i < node->leaves(); ++i) {
+                int64_t fieldMin = minBytesPerElement(node->leafAt(i), depth + 1);
+                // Saturate rather than overflow: a wrapped (negative) total
+                // would disable the collection check.
+                if (fieldMin > std::numeric_limits<int64_t>::max() - total) {
+                    return std::numeric_limits<int64_t>::max();
+                }
+                total += fieldMin;
+            }
+            return total;
+        }
+        default:
+            // boolean, int, long, bytes, string, enum, union, array, map and
+            // symbolic references all encode to at least one byte.
+            return 1;
+    }
+}
+
+// Default maximum number of zero-byte-encoded collection elements (e.g. an
+// array of nulls) to allocate from a single decode. Such elements consume no
+// input, so ensureCollectionAvailable cannot bound their count; without a cap a
+// tiny payload can declare a huge block count and exhaust memory. Overridable
+// via the AVRO_MAX_COLLECTION_ITEMS environment variable.
+static constexpr int64_t kDefaultMaxCollectionItems = 10000000;
+
+// Structural cap on the number of elements in any array or map (an overflow /
+// defense-in-depth guard), matching the historical Integer.MAX_VALUE - 8 limit.
+// Non-zero-byte elements are also bounded by the bytes remaining.
+static constexpr int64_t kDefaultMaxCollectionStructural = 2147483639;
+
+// AVRO_MAX_COLLECTION_ITEMS, when a non-negative integer, caps both limits;
+// otherwise zero-byte elements use the tighter default and all collections use
+// the structural default.
+static void collectionLimits(int64_t &zeroByte, int64_t &structural) {
+    const char *env = std::getenv("AVRO_MAX_COLLECTION_ITEMS");
+    if (env != nullptr && *env != '\0') {
+        char *end = nullptr;
+        long long value = std::strtoll(env, &end, 10);
+        if (*end == '\0' && value >= 0) {
+            zeroByte = structural = static_cast<int64_t>(value);
+            return;
+        }
+    }
+    zeroByte = kDefaultMaxCollectionItems;
+    structural = kDefaultMaxCollectionStructural;
+}
+
+// Reject a collection (array or map) block whose declared element count could
+// not be backed by the bytes actually remaining, before resizing for it.
+// Skipped when the per-element minimum is zero, or when the decoder cannot
+// report how many bytes remain. The comparison divides to avoid overflow.
+static void ensureCollectionAvailable(Decoder &d, size_t existing, size_t count, int64_t minBytes) {
+    if (count == 0 || minBytes <= 0) {
+        return;
+    }
+    int64_t remaining = d.bytesRemaining();
+    if (remaining >= 0 &&
+        static_cast<uint64_t>(count) >
+            static_cast<uint64_t>(remaining) / static_cast<uint64_t>(minBytes)) {
+        throw Exception(
+            "Collection claims {} elements with at least {} bytes each, "
+            "but only {} bytes are available",
+            count, minBytes, remaining);
+    }
+    // Structural / overflow guard, also covering decoders that cannot report the
+    // bytes remaining. Compare without adding so existing + count cannot overflow.
+    int64_t zeroByte, structural;
+    collectionLimits(zeroByte, structural);
+    const uint64_t limit = static_cast<uint64_t>(structural);
+    if (static_cast<uint64_t>(count) > limit ||
+        static_cast<uint64_t>(existing) > limit - static_cast<uint64_t>(count)) {
+        throw Exception(
+            "Cannot read a collection of more than {} elements; "
+            "set AVRO_MAX_COLLECTION_ITEMS if this is legitimate",
+            structural);
+    }

Review Comment:
   Fixed in a91347f377: ensureCollectionAvailable no longer returns early for minBytes<=0, so the structural cap now applies to every collection (including array/map under schema resolution, where minBytes is forced to 0). collectionLimits() also now returns a struct, so the unused `zeroByte`/`structural` locals (the -Werror set-but-not-used) are gone.



##########
lang/c++/impl/Generic.cc:
##########
@@ -25,6 +27,151 @@ using std::ostringstream;
 using std::string;
 using std::vector;
 
+// Minimum number of bytes a single value of the given schema node can occupy on
+// the wire. Used to reject an array/map block count that could not be backed by
+// the bytes remaining. A type that can encode to zero bytes (null) returns 0,
+// which disables the collection check for it (so an array of nulls is not
+// falsely rejected). A depth limit breaks self-referencing (symbolic) schemas.
+static int64_t minBytesPerElement(const NodePtr &node, int depth) {
+    if (!node) {
+        return 0;
+    }
+    switch (node->type()) {
+        case AVRO_NULL:
+            return 0;
+        case AVRO_FLOAT:
+            return 4;
+        case AVRO_DOUBLE:
+            return 8;
+        case AVRO_FIXED: {
+            // fixedSize() is a size_t; clamp to int64_t so a huge fixed size
+            // cannot wrap negative.
+            size_t sz = node->fixedSize();
+            return sz > static_cast<size_t>(std::numeric_limits<int64_t>::max())
+                       ? std::numeric_limits<int64_t>::max()
+                       : static_cast<int64_t>(sz);
+        }
+        case AVRO_RECORD: {
+            if (depth > 64) {
+                // Purely a recursion (stack-overflow) safety net for a
+                // pathologically deep schema. A truly cyclic schema never
+                // reaches this: a self-reference is an AVRO_SYMBOLIC node,
+                // handled by the default case below (returning 1 without
+                // following the link), so recursion always terminates. This
+                // guard therefore only trips on a genuinely deep *acyclic*
+                // record, whose true minimum can still be 0 (e.g. a long chain
+                // of records whose only leaves are null). Return 0 rather than
+                // over-estimating, so a valid array/map of such elements is not
+                // falsely rejected; 0 is always a valid lower bound.
+                return 0;
+            }
+            int64_t total = 0;
+            for (size_t i = 0; i < node->leaves(); ++i) {
+                int64_t fieldMin = minBytesPerElement(node->leafAt(i), depth + 1);
+                // Saturate rather than overflow: a wrapped (negative) total
+                // would disable the collection check.
+                if (fieldMin > std::numeric_limits<int64_t>::max() - total) {
+                    return std::numeric_limits<int64_t>::max();
+                }
+                total += fieldMin;
+            }
+            return total;
+        }
+        default:
+            // boolean, int, long, bytes, string, enum, union, array, map and
+            // symbolic references all encode to at least one byte.
+            return 1;
+    }
+}
+
+// Default maximum number of zero-byte-encoded collection elements (e.g. an
+// array of nulls) to allocate from a single decode. Such elements consume no
+// input, so ensureCollectionAvailable cannot bound their count; without a cap a
+// tiny payload can declare a huge block count and exhaust memory. Overridable
+// via the AVRO_MAX_COLLECTION_ITEMS environment variable.
+static constexpr int64_t kDefaultMaxCollectionItems = 10000000;
+
+// Structural cap on the number of elements in any array or map (an overflow /
+// defense-in-depth guard), matching the historical Integer.MAX_VALUE - 8 limit.
+// Non-zero-byte elements are also bounded by the bytes remaining.
+static constexpr int64_t kDefaultMaxCollectionStructural = 2147483639;
+
+// AVRO_MAX_COLLECTION_ITEMS, when a non-negative integer, caps both limits;
+// otherwise zero-byte elements use the tighter default and all collections use
+// the structural default.
+static void collectionLimits(int64_t &zeroByte, int64_t &structural) {
+    const char *env = std::getenv("AVRO_MAX_COLLECTION_ITEMS");
+    if (env != nullptr && *env != '\0') {
+        char *end = nullptr;
+        long long value = std::strtoll(env, &end, 10);
+        if (*end == '\0' && value >= 0) {
+            zeroByte = structural = static_cast<int64_t>(value);
+            return;
+        }
+    }
+    zeroByte = kDefaultMaxCollectionItems;
+    structural = kDefaultMaxCollectionStructural;
+}
+
+// Reject a collection (array or map) block whose declared element count could
+// not be backed by the bytes actually remaining, before resizing for it.
+// Skipped when the per-element minimum is zero, or when the decoder cannot
+// report how many bytes remain. The comparison divides to avoid overflow.
+static void ensureCollectionAvailable(Decoder &d, size_t existing, size_t count, int64_t minBytes) {
+    if (count == 0 || minBytes <= 0) {
+        return;
+    }
+    int64_t remaining = d.bytesRemaining();
+    if (remaining >= 0 &&
+        static_cast<uint64_t>(count) >
+            static_cast<uint64_t>(remaining) / static_cast<uint64_t>(minBytes)) {
+        throw Exception(
+            "Collection claims {} elements with at least {} bytes each, "
+            "but only {} bytes are available",
+            count, minBytes, remaining);
+    }
+    // Structural / overflow guard, also covering decoders that cannot report the
+    // bytes remaining. Compare without adding so existing + count cannot overflow.
+    int64_t zeroByte, structural;
+    collectionLimits(zeroByte, structural);
+    const uint64_t limit = static_cast<uint64_t>(structural);
+    if (static_cast<uint64_t>(count) > limit ||
+        static_cast<uint64_t>(existing) > limit - static_cast<uint64_t>(count)) {
+        throw Exception(
+            "Cannot read a collection of more than {} elements; "
+            "set AVRO_MAX_COLLECTION_ITEMS if this is legitimate",
+            structural);
+    }
+}
+
+// Reject a collection of zero-byte elements (e.g. null) whose cumulative count
+// exceeds the configured limit. These elements consume no input, so they cannot
+// be bounded by the bytes remaining; the count is the only signal.
+static void ensureZeroByteCollectionWithinLimit(size_t existing, size_t count) {
+    int64_t zeroByte, structural;
+    collectionLimits(zeroByte, structural);
+    const uint64_t limit = static_cast<uint64_t>(zeroByte);

Review Comment:
   Fixed in a91347f377: ensureZeroByteCollectionWithinLimit reads only `collectionLimits().zeroByte` now, so there is no unused `structural` local.



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Validate available bytes before allocating for length-prefixed values [avro]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3565707861


##########
lang/c++/impl/Generic.cc:
##########
@@ -25,6 +26,86 @@ using std::ostringstream;
 using std::string;
 using std::vector;
 
+// Minimum number of bytes a single value of the given schema node can occupy on
+// the wire. Used to reject an array/map block count that could not be backed by
+// the bytes remaining. A type that can encode to zero bytes (null) returns 0,
+// which disables the collection check for it (so an array of nulls is not
+// falsely rejected). A depth limit breaks self-referencing (symbolic) schemas.
+static int64_t minBytesPerElement(const NodePtr &node, int depth) {
+    if (!node) {
+        return 0;
+    }
+    if (depth > 64) {
+        // A cyclic or pathologically deep schema. Return 1 (not 0) so the
+        // collection check stays enabled rather than being silently bypassed;
+        // a valid recursive value always encodes to at least 1 byte.
+        return 1;
+    }

Review Comment:
   minBytesPerElement() applies the depth limit before checking the node type. That means a deeply nested AVRO_NULL schema (depth > 64) will return 1 instead of 0, incorrectly enabling the collection-availability check and potentially rejecting valid data for zero-byte element types nested under deep schemas (e.g., records chaining down to null). Consider preserving the AVRO_NULL == 0 behavior even when the depth cutoff is hit.



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Bound allocation when decoding length-prefixed values and collections [avro]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3567430301


##########
lang/c++/include/avro/Stream.hh:
##########
@@ -345,6 +356,28 @@ struct StreamReader {
         return next_ != end_ || fill();
     }
 
+    /**
+     * Returns the number of bytes still available to be read: those already
+     * buffered in this reader plus whatever the underlying stream reports as
+     * remaining. Returns a negative value when the underlying stream cannot
+     * report its remaining size.
+     */
+    int64_t remainingBytes() const {
+        if (in_ == nullptr) {
+            return -1;
+        }
+        int64_t streamRemaining = in_->remainingBytes();
+        if (streamRemaining < 0) {
+            return -1;
+        }
+        // Bytes already buffered in this reader, added to what the underlying
+        // stream still has. When next_ and end_ are both null (right after
+        // init()/reset(), before any data is buffered), the subtraction is
+        // well-defined and yields 0.
+        int64_t buffered = end_ - next_;

Review Comment:
   StreamReader::remainingBytes() computes `end_ - next_` even immediately after reset/init, when both pointers are set to nullptr (see reset() setting `next_ = end_ = nullptr`). Pointer subtraction is only defined for pointers into the same array object; subtracting null pointers is undefined behavior and can make bytesRemaining() unreliable on some platforms/optimizations. Please guard the subtraction and treat the buffered count as 0 when no buffer has been filled yet.



##########
lang/c++/impl/BinaryDecoder.cc:
##########
@@ -177,9 +242,27 @@ size_t BinaryDecoder::skipArray() {
     for (;;) {
         auto r = doDecodeLong();
         if (r < 0) {
-            auto n = static_cast<size_t>(doDecodeLong());
-            in_.skipBytes(n);
+            auto byteSize = doDecodeLong();
+            if (byteSize < 0) {
+                // A negative block byte-size would convert to a huge size_t and
+                // drive an unbounded skip; reject it.
+                throw Exception("Invalid negative block size: {}", byteSize);
+            }
+            in_.skipBytes(static_cast<size_t>(byteSize));
         } else {
+            // Bound the block count: skipping a huge block of zero-byte elements
+            // would otherwise loop unboundedly (a CPU exhaustion) even though it
+            // reads/allocates nothing. The decoder has no element schema here, so
+            // apply the structural cap (AVRO_MAX_COLLECTION_ITEMS, default
+            // Integer.MAX_VALUE - 8). Read the limit each call so a runtime
+            // change to the environment variable is honoured, matching Generic.cc.
+            const int64_t structural = maxCollectionStructural();
+            if (r > structural) {
+                throw Exception(
+                    "Cannot skip a collection of more than {} elements; "
+                    "set AVRO_MAX_COLLECTION_ITEMS if this is legitimate",
+                    structural);
+            }
             return static_cast<size_t>(r);

Review Comment:
   skipArray() returns a size_t item count but casts the decoded int64 value directly (`static_cast<size_t>(r)`). On 32-bit builds (or any platform where size_t is narrower than int64_t), a large positive block count can truncate and desynchronize decoding. doDecodeItemCount() already rejects counts that don’t fit into size_t; skipArray() should apply the same guard before returning.



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Bound allocation when decoding length-prefixed values and collections [avro]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3567512822


##########
lang/c++/impl/Generic.cc:
##########
@@ -25,6 +29,164 @@ using std::ostringstream;
 using std::string;
 using std::vector;
 
+// Minimum number of bytes a single value of the given schema node can occupy on
+// the wire. Used to reject an array/map block count that could not be backed by
+// the bytes remaining. A type that can encode to zero bytes (null) returns 0,
+// which disables the collection check for it (so an array of nulls is not
+// falsely rejected). A depth limit breaks self-referencing (symbolic) schemas.
+static int64_t minBytesPerElement(const NodePtr &node, int depth) {
+    if (!node) {
+        return 0;
+    }
+    switch (node->type()) {
+        case AVRO_NULL:
+            return 0;
+        case AVRO_FLOAT:
+            return 4;
+        case AVRO_DOUBLE:
+            return 8;
+        case AVRO_FIXED: {
+            // fixedSize() is a size_t; clamp to int64_t so a huge fixed size
+            // cannot wrap negative.
+            return static_cast<int64_t>(std::min<uint64_t>(
+                node->fixedSize(),
+                static_cast<uint64_t>(std::numeric_limits<int64_t>::max())));
+        }
+        case AVRO_RECORD: {
+            if (depth > 64) {
+                // Purely a recursion (stack-overflow) safety net for a
+                // pathologically deep schema. A truly cyclic schema never
+                // reaches this: a self-reference is an AVRO_SYMBOLIC node,
+                // handled by the default case below (returning 1 without
+                // following the link), so recursion always terminates. This
+                // guard therefore only trips on a genuinely deep *acyclic*
+                // record, whose true minimum can still be 0 (e.g. a long chain
+                // of records whose only leaves are null). Return 0 rather than
+                // over-estimating, so a valid array/map of such elements is not
+                // falsely rejected; 0 is always a valid lower bound.
+                return 0;
+            }
+            int64_t total = 0;
+            for (size_t i = 0; i < node->leaves(); ++i) {
+                int64_t fieldMin = minBytesPerElement(node->leafAt(i), depth + 1);
+                // Saturate rather than overflow: a wrapped (negative) total
+                // would disable the collection check.
+                if (fieldMin > std::numeric_limits<int64_t>::max() - total) {
+                    return std::numeric_limits<int64_t>::max();
+                }
+                total += fieldMin;
+            }
+            return total;
+        }
+        default:
+            // boolean, int, long, bytes, string, enum, union, array, map and
+            // symbolic references all encode to at least one byte.
+            return 1;
+    }
+}
+
+// Default maximum number of zero-byte-encoded collection elements (e.g. an
+// array of nulls) to allocate from a single decode. Such elements consume no
+// input, so ensureCollectionAvailable cannot bound their count; without a cap a
+// tiny payload can declare a huge block count and exhaust memory. Overridable
+// via the AVRO_MAX_COLLECTION_ITEMS environment variable.
+static constexpr int64_t kDefaultMaxCollectionItems = 10000000;
+
+// Structural cap on the number of elements in any array or map (an overflow /
+// defense-in-depth guard). It matches the value used by the other Avro SDKs
+// (Integer.MAX_VALUE - 8); non-zero-byte elements are also bounded by the bytes
+// remaining.
+static constexpr int64_t kDefaultMaxCollectionStructural = 2147483639;
+
+// Upper bound on how many elements a collection container is grown by in a
+// single step while decoding. The container still grows to hold every element
+// that is actually read; this only prevents resizing to the full (possibly
+// attacker-declared) block count up front, before any element is decoded. That
+// matters most for stream sources, where the bytes-remaining check cannot bound
+// the declared count against the input, so a single up-front resize could
+// allocate a huge container before the truncated stream is detected.
+static constexpr size_t kMaxCollectionPrealloc = 1024;
+
+struct CollectionLimits {
+    int64_t zeroByte;
+    int64_t structural;
+};
+
+// AVRO_MAX_COLLECTION_ITEMS, when a non-negative integer, overrides both limits
+// to that value; otherwise zero-byte elements use the tighter default and all
+// collections use the structural default.
+static CollectionLimits collectionLimits() {
+    const char *env = std::getenv("AVRO_MAX_COLLECTION_ITEMS");
+    if (env != nullptr && *env != '\0') {
+        char *end = nullptr;
+        long long value = std::strtoll(env, &end, 10);
+        if (*end == '\0' && value >= 0) {
+            return {static_cast<int64_t>(value), static_cast<int64_t>(value)};
+        }
+    }
+    return {kDefaultMaxCollectionItems, kDefaultMaxCollectionStructural};

Review Comment:
   AVRO_MAX_COLLECTION_ITEMS parsing uses std::strtoll without checking errno/ERANGE. For overflow inputs like "999999999999999999999", strtoll can saturate to LLONG_MAX and this code will accept it, effectively disabling the intended structural/zero-byte caps. Consider treating overflows as invalid (fall back to defaults) so a malformed env var cannot accidentally remove these DoS protections.



##########
lang/c++/impl/BinaryDecoder.cc:
##########
@@ -19,12 +19,36 @@
 #include "Decoder.hh"
 #include "Exception.hh"
 #include "Zigzag.hh"
+#include <cstdint>
+#include <cstdlib>
+#include <limits>
 #include <memory>
 
 namespace avro {
 
 using std::make_shared;
 
+// Structural cap on the number of elements to skip in an array or map (an
+// overflow / defense-in-depth guard). Mirrors the read-path limit in Generic.cc
+// and matches the value used by the other Avro SDKs (Integer.MAX_VALUE - 8).
+static constexpr int64_t kDefaultMaxCollectionStructural = 2147483639;
+
+// Returns the structural collection cap. It can be overridden by the
+// AVRO_MAX_COLLECTION_ITEMS environment variable (a non-negative integer),
+// matching the read path and the other SDKs so a single knob configures all of
+// them; an invalid or unset value uses the default.
+static int64_t maxCollectionStructural() {
+    const char *env = std::getenv("AVRO_MAX_COLLECTION_ITEMS");
+    if (env != nullptr && *env != '\0') {
+        char *end = nullptr;
+        long long value = std::strtoll(env, &end, 10);
+        if (*end == '\0' && value >= 0) {
+            return static_cast<int64_t>(value);
+        }
+    }
+    return kDefaultMaxCollectionStructural;
+}

Review Comment:
   maxCollectionStructural() accepts std::strtoll results without checking errno/ERANGE. If AVRO_MAX_COLLECTION_ITEMS overflows (e.g. too many digits), strtoll can saturate to LLONG_MAX and the code will treat it as valid, unintentionally removing the structural cap and undermining the skip-path DoS hardening. Treat overflow as invalid and fall back to the default cap.



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Validate available bytes before allocating for length-prefixed values [avro]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3565068622


##########
lang/c++/impl/Generic.cc:
##########
@@ -105,7 +156,13 @@ void GenericReader::read(GenericDatum &datum, Decoder &d, bool isResolving) {
             const NodePtr &nn = v.schema()->leafAt(0);
             r.resize(0);
             size_t start = 0;
+            // Only when not resolving: the datum schema then matches the wire
+            // schema, so minBytesPerElement is a true lower bound. Under
+            // resolution the wire (writer) type may be smaller than the datum
+            // (reader) type, which would over-estimate and reject valid data.
+            int64_t minBytes = isResolving ? 0 : minBytesPerElement(nn, 0);
             for (size_t m = d.arrayStart(); m != 0; m = d.arrayNext()) {
+                ensureCollectionAvailable(d, m, minBytes);
                 r.resize(r.size() + m);

Review Comment:
   r.resize(r.size() + m) can overflow size_t before the resize call when m is very large, potentially wrapping to a small size and causing incorrect decoding behavior. It also loses the opportunity to fail early with a clear error when the block count exceeds the container’s max_size().



##########
lang/c++/impl/Stream.cc:
##########
@@ -84,6 +84,15 @@ class MemoryInputStream : public InputStream {
     size_t byteCount() const final {
         return cur_ * chunkSize_ + curLen_;
     }
+
+    int64_t remainingBytes() const final {
+        // Total capacity across all chunks: full chunks plus the (partial)
+        // last chunk, minus what has already been consumed.
+        int64_t total = (size_ == 0)
+                            ? 0
+                            : static_cast<int64_t>((size_ - 1) * chunkSize_ + available_);
+        return total - static_cast<int64_t>(cur_ * chunkSize_ + curLen_);
+    }

Review Comment:
   remainingBytes() computes total/consumed using size_t arithmetic inside static_cast<int64_t>(...) (e.g. (size_-1)*chunkSize_). On large buffers this can overflow before the cast, yielding an incorrect (possibly negative) remaining count and disabling the available-bytes guard upstream.



##########
lang/c++/impl/Generic.cc:
##########
@@ -119,7 +176,10 @@ void GenericReader::read(GenericDatum &datum, Decoder &d, bool isResolving) {
             const NodePtr &nn = v.schema()->leafAt(1);
             r.resize(0);
             size_t start = 0;
+            // Map keys are strings (>= 1 byte length prefix) plus the value.
+            int64_t minBytes = isResolving ? 0 : (1 + minBytesPerElement(nn, 0));
             for (size_t m = d.mapStart(); m != 0; m = d.mapNext()) {
+                ensureCollectionAvailable(d, m, minBytes);
                 r.resize(r.size() + m);

Review Comment:
   r.resize(r.size() + m) can overflow size_t before the resize call when m is very large, potentially wrapping to a small size and causing incorrect decoding behavior. Add a max_size()-based guard before resizing the map container.



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Validate available bytes before allocating for length-prefixed values [avro]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3565162121


##########
lang/c++/impl/Generic.cc:
##########
@@ -25,6 +25,74 @@ using std::ostringstream;
 using std::string;
 using std::vector;
 
+// Minimum number of bytes a single value of the given schema node can occupy on
+// the wire. Used to reject an array/map block count that could not be backed by
+// the bytes remaining. A type that can encode to zero bytes (null) returns 0,
+// which disables the collection check for it (so an array of nulls is not
+// falsely rejected). A depth limit breaks self-referencing (symbolic) schemas.
+static int64_t minBytesPerElement(const NodePtr &node, int depth) {
+    if (!node) {
+        return 0;
+    }
+    if (depth > 64) {
+        // A cyclic or pathologically deep schema. Return 1 (not 0) so the
+        // collection check stays enabled rather than being silently bypassed;
+        // a valid recursive value always encodes to at least 1 byte.
+        return 1;
+    }
+    switch (node->type()) {
+        case AVRO_NULL:
+            return 0;
+        case AVRO_FLOAT:
+            return 4;
+        case AVRO_DOUBLE:
+            return 8;
+        case AVRO_FIXED:
+            return static_cast<int64_t>(node->fixedSize());
+        case AVRO_RECORD: {
+            int64_t total = 0;
+            for (size_t i = 0; i < node->leaves(); ++i) {
+                total += minBytesPerElement(node->leafAt(i), depth + 1);
+            }
+            return total;
+        }
+        default:
+            // boolean, int, long, bytes, string, enum, union, array, map and
+            // symbolic references all encode to at least one byte.
+            return 1;
+    }

Review Comment:
   minBytesPerElement() can overflow int64_t for AVRO_FIXED (fixedSize() > INT64_MAX) or for AVRO_RECORD when summing child minima. If the overflow wraps negative/small, ensureCollectionAvailable() may treat minBytes<=0 (or a too-small value) and skip/underenforce the available-bytes guard, weakening the OOM hardening this PR adds. Consider saturating these calculations to INT64_MAX.



##########
lang/c++/impl/Generic.cc:
##########
@@ -119,7 +194,11 @@ void GenericReader::read(GenericDatum &datum, Decoder &d, bool isResolving) {
             const NodePtr &nn = v.schema()->leafAt(1);
             r.resize(0);
             size_t start = 0;
+            // Map keys are strings (>= 1 byte length prefix) plus the value.
+            int64_t minBytes = isResolving ? 0 : (1 + minBytesPerElement(nn, 0));

Review Comment:
   In map decoding, minBytes is computed as (1 + minBytesPerElement(...)). If minBytesPerElement ever returns a very large value (e.g., from a large fixed/record), this addition can overflow int64_t and turn minBytes negative, which would disable ensureCollectionAvailable() (minBytes <= 0) and bypass the intended pre-allocation guard.



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Bound allocation when decoding length-prefixed values and collections [avro]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3567381352


##########
lang/c++/impl/BinaryDecoder.cc:
##########
@@ -163,8 +206,22 @@ size_t BinaryDecoder::arrayStart() {
 size_t BinaryDecoder::doDecodeItemCount() {
     auto result = doDecodeLong();
     if (result < 0) {
+        // INT64_MIN cannot be negated in int64_t (it would overflow); reject it
+        // rather than propagating 2^63 as an item count that inevitably fails a
+        // huge allocation downstream.
+        if (result == INT64_MIN) {
+            throw Exception("Invalid negative block count: {}", result);
+        }
         doDecodeLong();
-        return static_cast<size_t>(-(result + 1)) + 1;
+        result = -result;
+    }

Review Comment:
   BinaryDecoder::doDecodeItemCount() discards the “block byte-size” long for negative block counts without validating it. A negative block byte-size is malformed (and already explicitly rejected in skipArray()); rejecting it here too would keep arrayStart()/mapStart() consistent and fail fast on corrupt inputs.



##########
lang/c++/impl/BinaryDecoder.cc:
##########
@@ -130,6 +172,7 @@ void BinaryDecoder::skipString() {
 
 void BinaryDecoder::decodeBytes(std::vector<uint8_t> &value) {
     size_t len = doDecodeLength();
+    checkAvailableBytes(len);
     value.resize(len);

Review Comment:
   decodeBytes() validates the declared length via checkAvailableBytes(len), but skipBytes() still skips without validation. On memory-backed streams, InputStream::skip clamps at EOF instead of throwing, so skipping can succeed even when the declared length exceeds available data. Add checkAvailableBytes(len) to skipBytes() for consistent, fail-fast handling of malformed/truncated inputs when bytesRemaining() is known.



##########
lang/c++/impl/BinaryDecoder.cc:
##########
@@ -109,12 +138,25 @@ size_t BinaryDecoder::doDecodeLength() {
     return len;
 }
 
+void BinaryDecoder::checkAvailableBytes(size_t len) {
+    // Reject a declared length that exceeds the data actually available before
+    // allocating for it, to guard against an out-of-memory attack from a
+    // malicious or truncated input. Only enforced when the stream can report
+    // how many bytes remain.
+    int64_t remaining = in_.remainingBytes();
+    if (remaining >= 0 && static_cast<uint64_t>(len) > static_cast<uint64_t>(remaining)) {
+        throw Exception(
+            "Length {} exceeds the {} bytes available in the stream", len, remaining);
+    }
+}
+
 void BinaryDecoder::drain() {
     in_.drain(false);
 }
 
 void BinaryDecoder::decodeString(std::string &value) {
     size_t len = doDecodeLength();
+    checkAvailableBytes(len);
     value.resize(len);

Review Comment:
   BinaryDecoder currently guards decodeString() allocations via checkAvailableBytes(len), but skipString() still skips the declared length without validating it against the stream’s known remaining bytes. For memory-backed streams, InputStream::skip implementations clamp at EOF rather than throwing, so a malformed/truncated length prefix may be silently accepted when skipping. Call checkAvailableBytes(len) in skipString() as well so length-prefixed strings are consistently validated whenever bytesRemaining() is available.



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Bound allocation when decoding length-prefixed values and collections [avro]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3567394543


##########
lang/c++/impl/BinaryDecoder.cc:
##########
@@ -163,8 +206,22 @@ size_t BinaryDecoder::arrayStart() {
 size_t BinaryDecoder::doDecodeItemCount() {
     auto result = doDecodeLong();
     if (result < 0) {
+        // INT64_MIN cannot be negated in int64_t (it would overflow); reject it
+        // rather than propagating 2^63 as an item count that inevitably fails a
+        // huge allocation downstream.
+        if (result == INT64_MIN) {
+            throw Exception("Invalid negative block count: {}", result);
+        }
         doDecodeLong();
-        return static_cast<size_t>(-(result + 1)) + 1;
+        result = -result;

Review Comment:
   When decoding a negative array/map block count, Avro encoding includes a following block byte-size long that should be non-negative. doDecodeItemCount() currently reads that long but ignores its value, so a malformed negative block byte-size is silently accepted (whereas skipArray() correctly rejects it). This should be validated here too so arrayStart()/arrayNext()/mapStart()/mapNext() reject malformed inputs consistently.



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Bound allocation when decoding length-prefixed values and collections [avro]

Posted by "iemejia (via GitHub)" <gi...@apache.org>.
iemejia commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3566941778


##########
lang/c++/include/avro/Stream.hh:
##########
@@ -345,6 +356,28 @@ struct StreamReader {
         return next_ != end_ || fill();
     }
 
+    /**
+     * Returns the number of bytes still available to be read: those already
+     * buffered in this reader plus whatever the underlying stream reports as
+     * remaining. Returns a negative value when the underlying stream cannot
+     * report its remaining size.
+     */
+    int64_t remainingBytes() const {
+        if (in_ == nullptr) {
+            return -1;
+        }
+        int64_t streamRemaining = in_->remainingBytes();
+        if (streamRemaining < 0) {
+            return -1;
+        }
+        // Bytes already buffered in this reader, added to what the underlying
+        // stream still has. When next_ and end_ are both null (right after
+        // init()/reset(), before any data is buffered), the subtraction is
+        // well-defined and yields 0.
+        int64_t buffered = end_ - next_;
+        return buffered + streamRemaining;

Review Comment:
   This was raised earlier by @Gerrit0 and is actually well-defined: per N4950 7.6.6/5.1, when both pointer operands are null the subtraction yields 0. `end_ - next_` right after init()/reset() (both null) is therefore not UB, so I removed the guard at his request and kept testBytesRemainingRightAfterInit as coverage. I've left it as the plain subtraction.



##########
lang/c++/impl/BinaryDecoder.cc:
##########
@@ -163,8 +205,14 @@ size_t BinaryDecoder::arrayStart() {
 size_t BinaryDecoder::doDecodeItemCount() {
     auto result = doDecodeLong();
     if (result < 0) {
+        // INT64_MIN cannot be negated in int64_t (it would overflow); reject it
+        // rather than propagating 2^63 as an item count that inevitably fails a
+        // huge allocation downstream.
+        if (result == INT64_MIN) {
+            throw Exception("Invalid negative block count: {}", result);
+        }
         doDecodeLong();
-        return static_cast<size_t>(-(result + 1)) + 1;
+        return static_cast<size_t>(-result);
     }
     return static_cast<size_t>(result);

Review Comment:
   Fixed in 0884d62263: doDecodeItemCount() now rejects a count that doesn't fit into size_t before the cast (guarded with `if constexpr (sizeof(size_t) < sizeof(int64_t))` so it only compiles where size_t is narrower, e.g. 32-bit, avoiding a useless-cast/tautological-compare warning on 64-bit).



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Bound allocation when decoding length-prefixed values and collections [avro]

Posted by "iemejia (via GitHub)" <gi...@apache.org>.
iemejia closed pull request #3859: AVRO-4294: [c++] Bound allocation when decoding length-prefixed values and collections
URL: https://github.com/apache/avro/pull/3859


-- 
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: dev-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Validate available bytes before allocating for length-prefixed values [avro]

Posted by "iemejia (via GitHub)" <gi...@apache.org>.
iemejia commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3565768161


##########
lang/c++/impl/Generic.cc:
##########
@@ -25,6 +26,88 @@ using std::ostringstream;
 using std::string;
 using std::vector;
 
+// Minimum number of bytes a single value of the given schema node can occupy on
+// the wire. Used to reject an array/map block count that could not be backed by
+// the bytes remaining. A type that can encode to zero bytes (null) returns 0,
+// which disables the collection check for it (so an array of nulls is not
+// falsely rejected). A depth limit breaks self-referencing (symbolic) schemas.
+static int64_t minBytesPerElement(const NodePtr &node, int depth) {
+    if (!node) {
+        return 0;
+    }
+    switch (node->type()) {
+        case AVRO_NULL:
+            return 0;
+        case AVRO_FLOAT:
+            return 4;
+        case AVRO_DOUBLE:
+            return 8;
+        case AVRO_FIXED: {
+            // fixedSize() is a size_t; clamp to int64_t so a huge fixed size
+            // cannot wrap negative.
+            size_t sz = node->fixedSize();
+            return sz > static_cast<size_t>(std::numeric_limits<int64_t>::max())
+                       ? std::numeric_limits<int64_t>::max()
+                       : static_cast<int64_t>(sz);
+        }
+        case AVRO_RECORD: {
+            if (depth > 64) {
+                // A cyclic or pathologically deep record. Return 1 (not 0) so the
+                // collection check stays enabled rather than being silently
+                // bypassed; a valid recursive value always encodes to >= 1 byte.
+                // (The depth guard is applied only here, so zero-byte leaf types

Review Comment:
   Good point. Fixed in bf25d413cf: the depth guard now returns 0 (a valid conservative lower bound) instead of 1. A truly cyclic schema never reaches the guard because a self-reference is an AVRO_SYMBOLIC node handled by the default case (returning 1 without following the link), so recursion always terminates; the guard is purely a stack-overflow safety net for a genuinely deep *acyclic* record, where returning 1 would over-estimate and could falsely reject a valid array/map of null-leaf records. Added testReadArrayOfDeeplyNestedNullNotFalselyRejected with a ~70-level nested null-leaf record.



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Bound allocation when decoding length-prefixed values and collections [avro]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3567458249


##########
lang/c++/impl/BinaryDecoder.cc:
##########
@@ -177,9 +242,27 @@ size_t BinaryDecoder::skipArray() {
     for (;;) {
         auto r = doDecodeLong();
         if (r < 0) {
-            auto n = static_cast<size_t>(doDecodeLong());
-            in_.skipBytes(n);
+            auto byteSize = doDecodeLong();
+            if (byteSize < 0) {
+                // A negative block byte-size would convert to a huge size_t and
+                // drive an unbounded skip; reject it.
+                throw Exception("Invalid negative block size: {}", byteSize);
+            }
+            in_.skipBytes(static_cast<size_t>(byteSize));

Review Comment:
   In BinaryDecoder::skipArray(), the negative-block path casts the decoded block byte-size to size_t without checking it fits. On 32-bit builds (or any build where size_t is narrower), a large byteSize can truncate, causing the decoder to skip the wrong amount. Also, StreamReader::skipBytes ultimately calls InputStream::skip(), and the memory-backed skip() implementations clamp at EOF rather than throwing, so an oversized byteSize can be silently accepted when the remaining size is known. Consider rejecting byte sizes that don’t fit in size_t and using checkAvailableBytes() before skipping, consistent with skipString()/skipBytes().



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Bound allocation when decoding length-prefixed values and collections [avro]

Posted by "iemejia (via GitHub)" <gi...@apache.org>.
iemejia commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3568114361


##########
lang/c++/impl/Generic.cc:
##########
@@ -105,11 +267,38 @@ void GenericReader::read(GenericDatum &datum, Decoder &d, bool isResolving) {
             const NodePtr &nn = v.schema()->leafAt(0);
             r.resize(0);
             size_t start = 0;
+            // Only when not resolving: the datum schema then matches the wire
+            // schema, so minBytesPerElement is a true lower bound. Under
+            // resolution the wire (writer) type may be smaller than the datum
+            // (reader) type, which would over-estimate and reject valid data.
+            int64_t trueMin = minBytesPerElement(nn, 0);
+            // Under resolution the on-wire (writer) element can be zero bytes
+            // even when the reader element is not (e.g. reader-only fields filled
+            // from defaults), so the bytes check is disabled and we cannot tell
+            // whether an element is zero-byte on the wire. Apply the tighter
+            // zero-byte cap conservatively in that case, so the up-front resize
+            // cannot be driven past it.
+            bool zeroByte = isResolving || trueMin == 0;

Review Comment:
   This is a deliberate, conservative choice. Under resolution the bytes-remaining check is disabled (the writer element size may differ from the reader's), and grow-on-demand alone does not protect the zero-byte case: a writer array of `null` (0 wire bytes/element) resolving to non-trivial reader values would let a huge declared count allocate reader elements while consuming almost no input. Since we can't tell from the reader schema whether the on-wire element is zero-byte, we apply the tighter item cap to all resolving array reads. It's not a hard 10,000,000 limit — AVRO_MAX_COLLECTION_ITEMS raises it — so legitimately large resolving arrays remain readable by configuring the cap. Tightening this to only the truly-zero-byte-on-wire case would require plumbing the writer schema into this path; I can file a follow-up if you'd prefer that refinement.



##########
lang/c++/include/avro/Stream.hh:
##########
@@ -345,6 +356,28 @@ struct StreamReader {
         return next_ != end_ || fill();
     }
 
+    /**
+     * Returns the number of bytes still available to be read: those already
+     * buffered in this reader plus whatever the underlying stream reports as
+     * remaining. Returns a negative value when the underlying stream cannot
+     * report its remaining size.
+     */
+    int64_t remainingBytes() const {
+        if (in_ == nullptr) {
+            return -1;
+        }
+        int64_t streamRemaining = in_->remainingBytes();
+        if (streamRemaining < 0) {
+            return -1;
+        }
+        // Bytes already buffered in this reader, added to what the underlying
+        // stream still has. When next_ and end_ are both null (right after
+        // init()/reset(), before any data is buffered), the subtraction is
+        // well-defined and yields 0.
+        int64_t buffered = end_ - next_;
+        return buffered + streamRemaining;

Review Comment:
   Left as-is intentionally: an earlier review round had a maintainer remove an equivalent null-guard here, so re-adding it would conflict with that decision. In practice remainingBytes() is only meaningful after init()/reset() has pointed next_/end_ into a real buffer; right after reset() with both null the value isn't consumed. If the project wants a formal guard I'll defer to a maintainer call rather than reintroduce the reverted change.



##########
lang/c++/include/avro/Decoder.hh:
##########
@@ -169,6 +169,14 @@ public:
     /// by the avro decoder. Similar set of problems occur if the Decoder
     /// consumes more than what it should.
     virtual void drain() = 0;
+
+    /// Returns the number of bytes that remain to be read from the underlying
+    /// stream, or a negative value when that count is not known (for example a
+    /// streaming source, or a decoder not backed by a byte stream). The default
+    /// is "unknown"; byte-stream decoders override it so a length prefix or a
+    /// collection block count that exceeds the data actually available can be
+    /// rejected before allocating for it.
+    virtual int64_t bytesRemaining() const { return -1; }

Review Comment:
   Valid concern. Adding virtual remainingBytes()/bytesRemaining() to InputStream/Decoder changes vtable layout and would break ABI for downstream subclasses across a shared-library boundary. This needs a maintainer decision on the intended compatibility guarantee: (a) accept it for the next minor/major (the C++ SDK has historically bumped SONAME on minor releases), or (b) avoid the vtable change by making these non-virtual with a dynamic_cast to the concrete decoder/stream where the capability exists. I've left the virtual approach in place pending that call rather than pick a compatibility policy unilaterally — happy to switch to the non-virtual + dynamic_cast form if that's preferred.



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Validate available bytes before allocating for length-prefixed values [avro]

Posted by "iemejia (via GitHub)" <gi...@apache.org>.
iemejia commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3565199529


##########
lang/c++/impl/Generic.cc:
##########
@@ -25,6 +25,74 @@ using std::ostringstream;
 using std::string;
 using std::vector;
 
+// Minimum number of bytes a single value of the given schema node can occupy on
+// the wire. Used to reject an array/map block count that could not be backed by
+// the bytes remaining. A type that can encode to zero bytes (null) returns 0,
+// which disables the collection check for it (so an array of nulls is not
+// falsely rejected). A depth limit breaks self-referencing (symbolic) schemas.
+static int64_t minBytesPerElement(const NodePtr &node, int depth) {
+    if (!node) {
+        return 0;
+    }
+    if (depth > 64) {
+        // A cyclic or pathologically deep schema. Return 1 (not 0) so the
+        // collection check stays enabled rather than being silently bypassed;
+        // a valid recursive value always encodes to at least 1 byte.
+        return 1;
+    }
+    switch (node->type()) {
+        case AVRO_NULL:
+            return 0;
+        case AVRO_FLOAT:
+            return 4;
+        case AVRO_DOUBLE:
+            return 8;
+        case AVRO_FIXED:
+            return static_cast<int64_t>(node->fixedSize());
+        case AVRO_RECORD: {
+            int64_t total = 0;
+            for (size_t i = 0; i < node->leaves(); ++i) {
+                total += minBytesPerElement(node->leafAt(i), depth + 1);
+            }
+            return total;
+        }
+        default:
+            // boolean, int, long, bytes, string, enum, union, array, map and
+            // symbolic references all encode to at least one byte.
+            return 1;
+    }

Review Comment:
   Fixed in 711e27b: minBytesPerElement() clamps the fixed size to INT64_MAX and saturates the record field-minima sum, so an overflow can no longer wrap negative and weaken the guard.



##########
lang/c++/impl/Generic.cc:
##########
@@ -119,7 +194,11 @@ void GenericReader::read(GenericDatum &datum, Decoder &d, bool isResolving) {
             const NodePtr &nn = v.schema()->leafAt(1);
             r.resize(0);
             size_t start = 0;
+            // Map keys are strings (>= 1 byte length prefix) plus the value.
+            int64_t minBytes = isResolving ? 0 : (1 + minBytesPerElement(nn, 0));

Review Comment:
   Fixed in 711e27b: the map's (1 + valueMin) is now saturated (only adds 1 when valueMin < INT64_MAX), so it cannot overflow to a negative minBytes.



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Bound allocation when decoding length-prefixed values and collections [avro]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3566791584


##########
lang/c++/impl/Generic.cc:
##########
@@ -105,7 +258,21 @@ void GenericReader::read(GenericDatum &datum, Decoder &d, bool isResolving) {
             const NodePtr &nn = v.schema()->leafAt(0);
             r.resize(0);
             size_t start = 0;
+            // Only when not resolving: the datum schema then matches the wire
+            // schema, so minBytesPerElement is a true lower bound. Under
+            // resolution the wire (writer) type may be smaller than the datum
+            // (reader) type, which would over-estimate and reject valid data.
+            int64_t trueMin = minBytesPerElement(nn, 0);
+            bool zeroByte = trueMin == 0;
+            int64_t minBytes = isResolving ? 0 : trueMin;

Review Comment:
   In resolving mode, `zeroByte` is computed from the reader schema (`nn`) only. However, the resolving decoder can synthesize reader-only fields from defaults without consuming any input bytes, so the on-wire minimum for an element can be 0 even when `minBytesPerElement(nn, 0)` is > 0. In that case the tighter zero-byte element cap (default 10,000,000) is skipped and a tiny payload can still drive allocations up to the structural cap (~2.1B). Consider enforcing the zero-byte-element cap in `ResolvingDecoder` (where the writer schema and defaults are known) or extending the decoder/reader interface to expose a conservative per-element on-wire minimum under resolution.



##########
lang/c++/impl/BinaryDecoder.cc:
##########
@@ -180,6 +228,18 @@ size_t BinaryDecoder::skipArray() {
             auto n = static_cast<size_t>(doDecodeLong());
             in_.skipBytes(n);
         } else {
+            // Bound the block count: skipping a huge block of zero-byte elements
+            // would otherwise loop unboundedly (a CPU exhaustion) even though it
+            // reads/allocates nothing. The decoder has no element schema here, so
+            // apply the structural cap (AVRO_MAX_COLLECTION_ITEMS, default
+            // Integer.MAX_VALUE - 8).
+            static const int64_t structural = maxCollectionStructural();

Review Comment:
   `structural` is cached as a function-static, so changes to AVRO_MAX_COLLECTION_ITEMS after the first `skipArray()` call in the process (including test cleanup via unsetenv) won't take effect and behavior becomes inconsistent with Generic.cc, which reads the env var dynamically. Prefer computing the limit on each call (or otherwise making the caching strategy consistent across read/skip paths).



##########
lang/c++/test/AvailableBytesTests.cc:
##########
@@ -0,0 +1,280 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// A bytes/string value is encoded as a length prefix followed by that many
+// bytes of data. A malicious or truncated input can declare a huge length with
+// little or no actual data, which would otherwise trigger a correspondingly
+// huge allocation before the shortfall is noticed. When the input stream can
+// report how many bytes remain (a memory-backed stream), the declared length
+// must be rejected before allocating for it.
+
+#include <cstdint>
+#include <cstdlib>
+#include <memory>
+#include <string>
+#include <vector>
+
+#include <boost/test/included/unit_test.hpp>
+
+#include "Compiler.hh"
+#include "Decoder.hh"
+#include "Encoder.hh"
+#include "Exception.hh"
+#include "Generic.hh"
+#include "Stream.hh"
+#include "ValidSchema.hh"
+
+namespace avro {
+
+// Reading a bytes value whose declared length far exceeds the tiny backing
+// buffer must throw instead of attempting a huge allocation.
+static void testDecodeBytesRejectsOversizedLength() {
+    // 0xFE 0x01 is the zig-zag long 127; the buffer carries no data after it.
+    const uint8_t data[] = {0xFE, 0x01};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::vector<uint8_t> value;
+    BOOST_CHECK_THROW(d->decodeBytes(value), Exception);
+}
+
+static void testDecodeStringRejectsOversizedLength() {
+    const uint8_t data[] = {0xFE, 0x01};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::string value;
+    BOOST_CHECK_THROW(d->decodeString(value), Exception);
+}
+
+// A well-formed value whose declared length fits the buffer still decodes.
+static void testDecodeStringWithinLimitStillReads() {
+    // length 3 (zig-zag 6 -> 0x06) followed by "abc".
+    const uint8_t data[] = {0x06, 'a', 'b', 'c'};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::string value;
+    d->decodeString(value);
+    BOOST_CHECK_EQUAL(value, std::string("abc"));
+}
+
+static void testDecodeBytesWithinLimitStillReads() {
+    const uint8_t data[] = {0x06, 0x01, 0x02, 0x03};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::vector<uint8_t> value;
+    d->decodeBytes(value);
+    BOOST_CHECK_EQUAL(value.size(), 3u);
+    BOOST_CHECK_EQUAL(value[0], 1);
+    BOOST_CHECK_EQUAL(value[2], 3);
+}
+
+// An array/map block declares an element count; a malicious or truncated input
+// can declare far more elements than the remaining bytes could hold. The count
+// is validated against the bytes remaining before resizing, using the minimum
+// on-wire size of the element schema (so 0-byte elements like null are not
+// falsely rejected).
+static GenericDatum decodeCollectionHeader(const ValidSchema &s, int64_t blockCount,
+                                           bool addEndMarker) {
+    // Keep the output stream alive for the whole decode: memoryInputStream
+    // references the output stream's buffer rather than copying it.
+    std::unique_ptr<OutputStream> os = memoryOutputStream();
+    EncoderPtr e = binaryEncoder();
+    e->init(*os);
+    e->encodeLong(blockCount);
+    if (addEndMarker) {
+        e->encodeLong(0);
+    }
+    e->flush();
+
+    InputStreamPtr in = memoryInputStream(*os);
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    GenericDatum datum;
+    GenericReader::read(*d, datum, s);
+    return datum;
+}
+
+static void testReadArrayRejectsOversizedCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"long\"}");
+    // 1,000,000 long elements declared, but no element data follows.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1000000, false), Exception);
+}
+
+static void testReadMapRejectsOversizedCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"map\",\"values\":\"long\"}");
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1000000, false), Exception);
+}
+
+static void testReadArrayOfNullNotFalselyRejected() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // 100,000 nulls (zero bytes each) is legitimate and must decode.
+    GenericDatum datum = decodeCollectionHeader(s, 100000, true);
+    BOOST_CHECK_EQUAL(datum.value<GenericArray>().value().size(), 100000u);
+}
+
+// A deeply but acyclically nested record whose only leaf is null encodes to
+// zero bytes, so the per-element minimum must be 0 and a large array of such
+// records must not be falsely rejected. This exercises the recursion depth
+// guard in minBytesPerElement(), which must yield a conservative lower bound
+// (0) rather than over-estimating for a legitimately deep schema.
+static void testReadArrayOfDeeplyNestedNullNotFalselyRejected() {
+    // Build ~70 nested records: R0 { null f; }, R1 { R0 f; }, ... The nesting
+    // exceeds the depth guard, yet every leaf is null so the true minimum is 0.
+    std::string schema = "\"null\"";
+    for (int i = 0; i < 70; ++i) {
+        schema = "{\"type\":\"record\",\"name\":\"R" + std::to_string(i) +
+                 "\",\"fields\":[{\"name\":\"f\",\"type\":" + schema + "}]}";
+    }
+    ValidSchema s = compileJsonSchemaFromString(
+        ("{\"type\":\"array\",\"items\":" + schema + "}").c_str());
+    // 100,000 zero-byte elements is legitimate and must decode.
+    GenericDatum datum = decodeCollectionHeader(s, 100000, true);
+    BOOST_CHECK_EQUAL(datum.value<GenericArray>().value().size(), 100000u);
+}
+
+// Calling bytesRemaining() immediately after init(), before any data has been
+// buffered, must be well-defined (the underlying StreamReader must not subtract
+// null buffer pointers) and report the whole stream as available.
+static void testBytesRemainingRightAfterInit() {
+    const uint8_t data[] = {0x06, 'a', 'b', 'c'};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    BOOST_CHECK_EQUAL(d->bytesRemaining(), static_cast<int64_t>(sizeof(data)));
+}
+
+// Zero-byte elements (null, a record with only zero-byte fields) consume no
+// input, so ensureCollectionAvailable cannot bound their count. A huge declared
+// block count of such elements is capped against a configurable limit.
+static GenericDatum decodeLongs(const ValidSchema &s, const std::vector<int64_t> &longs) {
+    std::unique_ptr<OutputStream> os = memoryOutputStream();
+    EncoderPtr e = binaryEncoder();
+    e->init(*os);
+    for (int64_t v : longs) {
+        e->encodeLong(v);
+    }
+    e->flush();
+    InputStreamPtr in = memoryInputStream(*os);
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    GenericDatum datum;
+    GenericReader::read(*d, datum, s);
+    return datum;
+}
+
+static void testReadArrayOfNullRejectsCountAboveDefaultLimit() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // The reported exploit: 200,000,000 nulls rejected by the default limit.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, true), Exception);
+}
+
+static void testReadArrayOfAllNullRecordRejectsHugeCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":"
+        "{\"type\":\"record\",\"name\":\"R\",\"fields\":[{\"name\":\"n\",\"type\":\"null\"}]}}");
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, true), Exception);
+}
+
+static void testReadArrayOfNullRejectsNegativeCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // Negative count (-200M), block byte-size 0, end marker 0: normalized to
+    // 200M and still bounded.
+    BOOST_CHECK_THROW(decodeLongs(s, {-200000000, 0, 0}), Exception);
+}
+
+static void testReadMapOfNullRejectedByAvailableBytes() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"map\",\"values\":\"null\"}");
+    // Each map entry carries a >= 1 byte key, so a huge map<null> is bounded by
+    // the bytes-remaining check.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, false), Exception);
+}
+
+static void testReadArrayOfNullRespectsConfiguredLimit() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    setenv("AVRO_MAX_COLLECTION_ITEMS", "1000", 1);
+    // Within the limit decodes; over the limit and cumulative are rejected.
+    GenericDatum ok = decodeCollectionHeader(s, 1000, true);
+    BOOST_CHECK_EQUAL(ok.value<GenericArray>().value().size(), 1000u);
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1001, true), Exception);
+    BOOST_CHECK_THROW(decodeLongs(s, {600, 600, 0}), Exception);
+    unsetenv("AVRO_MAX_COLLECTION_ITEMS");
+}
+
+// A backed non-zero-byte array that passes the bytes check is still bounded by
+// the structural cap (exercised with a lowered limit).
+static void testReadArrayOfLongRejectedByStructuralCap() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"long\"}");
+    setenv("AVRO_MAX_COLLECTION_ITEMS", "5", 1);

Review Comment:
   This test uses `setenv`, which is not available on Windows/MSVC. Please guard it with `_WIN32` and use `_putenv_s` there so the test suite remains portable.



##########
lang/c++/test/AvailableBytesTests.cc:
##########
@@ -0,0 +1,280 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// A bytes/string value is encoded as a length prefix followed by that many
+// bytes of data. A malicious or truncated input can declare a huge length with
+// little or no actual data, which would otherwise trigger a correspondingly
+// huge allocation before the shortfall is noticed. When the input stream can
+// report how many bytes remain (a memory-backed stream), the declared length
+// must be rejected before allocating for it.
+
+#include <cstdint>
+#include <cstdlib>
+#include <memory>
+#include <string>
+#include <vector>
+
+#include <boost/test/included/unit_test.hpp>
+
+#include "Compiler.hh"
+#include "Decoder.hh"
+#include "Encoder.hh"
+#include "Exception.hh"
+#include "Generic.hh"
+#include "Stream.hh"
+#include "ValidSchema.hh"
+
+namespace avro {
+
+// Reading a bytes value whose declared length far exceeds the tiny backing
+// buffer must throw instead of attempting a huge allocation.
+static void testDecodeBytesRejectsOversizedLength() {
+    // 0xFE 0x01 is the zig-zag long 127; the buffer carries no data after it.
+    const uint8_t data[] = {0xFE, 0x01};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::vector<uint8_t> value;
+    BOOST_CHECK_THROW(d->decodeBytes(value), Exception);
+}
+
+static void testDecodeStringRejectsOversizedLength() {
+    const uint8_t data[] = {0xFE, 0x01};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::string value;
+    BOOST_CHECK_THROW(d->decodeString(value), Exception);
+}
+
+// A well-formed value whose declared length fits the buffer still decodes.
+static void testDecodeStringWithinLimitStillReads() {
+    // length 3 (zig-zag 6 -> 0x06) followed by "abc".
+    const uint8_t data[] = {0x06, 'a', 'b', 'c'};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::string value;
+    d->decodeString(value);
+    BOOST_CHECK_EQUAL(value, std::string("abc"));
+}
+
+static void testDecodeBytesWithinLimitStillReads() {
+    const uint8_t data[] = {0x06, 0x01, 0x02, 0x03};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::vector<uint8_t> value;
+    d->decodeBytes(value);
+    BOOST_CHECK_EQUAL(value.size(), 3u);
+    BOOST_CHECK_EQUAL(value[0], 1);
+    BOOST_CHECK_EQUAL(value[2], 3);
+}
+
+// An array/map block declares an element count; a malicious or truncated input
+// can declare far more elements than the remaining bytes could hold. The count
+// is validated against the bytes remaining before resizing, using the minimum
+// on-wire size of the element schema (so 0-byte elements like null are not
+// falsely rejected).
+static GenericDatum decodeCollectionHeader(const ValidSchema &s, int64_t blockCount,
+                                           bool addEndMarker) {
+    // Keep the output stream alive for the whole decode: memoryInputStream
+    // references the output stream's buffer rather than copying it.
+    std::unique_ptr<OutputStream> os = memoryOutputStream();
+    EncoderPtr e = binaryEncoder();
+    e->init(*os);
+    e->encodeLong(blockCount);
+    if (addEndMarker) {
+        e->encodeLong(0);
+    }
+    e->flush();
+
+    InputStreamPtr in = memoryInputStream(*os);
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    GenericDatum datum;
+    GenericReader::read(*d, datum, s);
+    return datum;
+}
+
+static void testReadArrayRejectsOversizedCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"long\"}");
+    // 1,000,000 long elements declared, but no element data follows.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1000000, false), Exception);
+}
+
+static void testReadMapRejectsOversizedCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"map\",\"values\":\"long\"}");
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1000000, false), Exception);
+}
+
+static void testReadArrayOfNullNotFalselyRejected() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // 100,000 nulls (zero bytes each) is legitimate and must decode.
+    GenericDatum datum = decodeCollectionHeader(s, 100000, true);
+    BOOST_CHECK_EQUAL(datum.value<GenericArray>().value().size(), 100000u);
+}
+
+// A deeply but acyclically nested record whose only leaf is null encodes to
+// zero bytes, so the per-element minimum must be 0 and a large array of such
+// records must not be falsely rejected. This exercises the recursion depth
+// guard in minBytesPerElement(), which must yield a conservative lower bound
+// (0) rather than over-estimating for a legitimately deep schema.
+static void testReadArrayOfDeeplyNestedNullNotFalselyRejected() {
+    // Build ~70 nested records: R0 { null f; }, R1 { R0 f; }, ... The nesting
+    // exceeds the depth guard, yet every leaf is null so the true minimum is 0.
+    std::string schema = "\"null\"";
+    for (int i = 0; i < 70; ++i) {
+        schema = "{\"type\":\"record\",\"name\":\"R" + std::to_string(i) +
+                 "\",\"fields\":[{\"name\":\"f\",\"type\":" + schema + "}]}";
+    }
+    ValidSchema s = compileJsonSchemaFromString(
+        ("{\"type\":\"array\",\"items\":" + schema + "}").c_str());
+    // 100,000 zero-byte elements is legitimate and must decode.
+    GenericDatum datum = decodeCollectionHeader(s, 100000, true);
+    BOOST_CHECK_EQUAL(datum.value<GenericArray>().value().size(), 100000u);
+}
+
+// Calling bytesRemaining() immediately after init(), before any data has been
+// buffered, must be well-defined (the underlying StreamReader must not subtract
+// null buffer pointers) and report the whole stream as available.
+static void testBytesRemainingRightAfterInit() {
+    const uint8_t data[] = {0x06, 'a', 'b', 'c'};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    BOOST_CHECK_EQUAL(d->bytesRemaining(), static_cast<int64_t>(sizeof(data)));
+}
+
+// Zero-byte elements (null, a record with only zero-byte fields) consume no
+// input, so ensureCollectionAvailable cannot bound their count. A huge declared
+// block count of such elements is capped against a configurable limit.
+static GenericDatum decodeLongs(const ValidSchema &s, const std::vector<int64_t> &longs) {
+    std::unique_ptr<OutputStream> os = memoryOutputStream();
+    EncoderPtr e = binaryEncoder();
+    e->init(*os);
+    for (int64_t v : longs) {
+        e->encodeLong(v);
+    }
+    e->flush();
+    InputStreamPtr in = memoryInputStream(*os);
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    GenericDatum datum;
+    GenericReader::read(*d, datum, s);
+    return datum;
+}
+
+static void testReadArrayOfNullRejectsCountAboveDefaultLimit() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // The reported exploit: 200,000,000 nulls rejected by the default limit.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, true), Exception);
+}
+
+static void testReadArrayOfAllNullRecordRejectsHugeCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":"
+        "{\"type\":\"record\",\"name\":\"R\",\"fields\":[{\"name\":\"n\",\"type\":\"null\"}]}}");
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, true), Exception);
+}
+
+static void testReadArrayOfNullRejectsNegativeCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // Negative count (-200M), block byte-size 0, end marker 0: normalized to
+    // 200M and still bounded.
+    BOOST_CHECK_THROW(decodeLongs(s, {-200000000, 0, 0}), Exception);
+}
+
+static void testReadMapOfNullRejectedByAvailableBytes() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"map\",\"values\":\"null\"}");
+    // Each map entry carries a >= 1 byte key, so a huge map<null> is bounded by
+    // the bytes-remaining check.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, false), Exception);
+}
+
+static void testReadArrayOfNullRespectsConfiguredLimit() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    setenv("AVRO_MAX_COLLECTION_ITEMS", "1000", 1);
+    // Within the limit decodes; over the limit and cumulative are rejected.
+    GenericDatum ok = decodeCollectionHeader(s, 1000, true);
+    BOOST_CHECK_EQUAL(ok.value<GenericArray>().value().size(), 1000u);
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1001, true), Exception);
+    BOOST_CHECK_THROW(decodeLongs(s, {600, 600, 0}), Exception);
+    unsetenv("AVRO_MAX_COLLECTION_ITEMS");

Review Comment:
   This test uses `unsetenv`, which is not available on Windows/MSVC. Please guard it with `_WIN32` and use `_putenv_s(name, "")` there so the test suite remains portable.



##########
lang/c++/test/AvailableBytesTests.cc:
##########
@@ -0,0 +1,280 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// A bytes/string value is encoded as a length prefix followed by that many
+// bytes of data. A malicious or truncated input can declare a huge length with
+// little or no actual data, which would otherwise trigger a correspondingly
+// huge allocation before the shortfall is noticed. When the input stream can
+// report how many bytes remain (a memory-backed stream), the declared length
+// must be rejected before allocating for it.
+
+#include <cstdint>
+#include <cstdlib>
+#include <memory>
+#include <string>
+#include <vector>
+
+#include <boost/test/included/unit_test.hpp>
+
+#include "Compiler.hh"
+#include "Decoder.hh"
+#include "Encoder.hh"
+#include "Exception.hh"
+#include "Generic.hh"
+#include "Stream.hh"
+#include "ValidSchema.hh"
+
+namespace avro {
+
+// Reading a bytes value whose declared length far exceeds the tiny backing
+// buffer must throw instead of attempting a huge allocation.
+static void testDecodeBytesRejectsOversizedLength() {
+    // 0xFE 0x01 is the zig-zag long 127; the buffer carries no data after it.
+    const uint8_t data[] = {0xFE, 0x01};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::vector<uint8_t> value;
+    BOOST_CHECK_THROW(d->decodeBytes(value), Exception);
+}
+
+static void testDecodeStringRejectsOversizedLength() {
+    const uint8_t data[] = {0xFE, 0x01};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::string value;
+    BOOST_CHECK_THROW(d->decodeString(value), Exception);
+}
+
+// A well-formed value whose declared length fits the buffer still decodes.
+static void testDecodeStringWithinLimitStillReads() {
+    // length 3 (zig-zag 6 -> 0x06) followed by "abc".
+    const uint8_t data[] = {0x06, 'a', 'b', 'c'};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::string value;
+    d->decodeString(value);
+    BOOST_CHECK_EQUAL(value, std::string("abc"));
+}
+
+static void testDecodeBytesWithinLimitStillReads() {
+    const uint8_t data[] = {0x06, 0x01, 0x02, 0x03};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::vector<uint8_t> value;
+    d->decodeBytes(value);
+    BOOST_CHECK_EQUAL(value.size(), 3u);
+    BOOST_CHECK_EQUAL(value[0], 1);
+    BOOST_CHECK_EQUAL(value[2], 3);
+}
+
+// An array/map block declares an element count; a malicious or truncated input
+// can declare far more elements than the remaining bytes could hold. The count
+// is validated against the bytes remaining before resizing, using the minimum
+// on-wire size of the element schema (so 0-byte elements like null are not
+// falsely rejected).
+static GenericDatum decodeCollectionHeader(const ValidSchema &s, int64_t blockCount,
+                                           bool addEndMarker) {
+    // Keep the output stream alive for the whole decode: memoryInputStream
+    // references the output stream's buffer rather than copying it.
+    std::unique_ptr<OutputStream> os = memoryOutputStream();
+    EncoderPtr e = binaryEncoder();
+    e->init(*os);
+    e->encodeLong(blockCount);
+    if (addEndMarker) {
+        e->encodeLong(0);
+    }
+    e->flush();
+
+    InputStreamPtr in = memoryInputStream(*os);
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    GenericDatum datum;
+    GenericReader::read(*d, datum, s);
+    return datum;
+}
+
+static void testReadArrayRejectsOversizedCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"long\"}");
+    // 1,000,000 long elements declared, but no element data follows.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1000000, false), Exception);
+}
+
+static void testReadMapRejectsOversizedCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"map\",\"values\":\"long\"}");
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1000000, false), Exception);
+}
+
+static void testReadArrayOfNullNotFalselyRejected() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // 100,000 nulls (zero bytes each) is legitimate and must decode.
+    GenericDatum datum = decodeCollectionHeader(s, 100000, true);
+    BOOST_CHECK_EQUAL(datum.value<GenericArray>().value().size(), 100000u);
+}
+
+// A deeply but acyclically nested record whose only leaf is null encodes to
+// zero bytes, so the per-element minimum must be 0 and a large array of such
+// records must not be falsely rejected. This exercises the recursion depth
+// guard in minBytesPerElement(), which must yield a conservative lower bound
+// (0) rather than over-estimating for a legitimately deep schema.
+static void testReadArrayOfDeeplyNestedNullNotFalselyRejected() {
+    // Build ~70 nested records: R0 { null f; }, R1 { R0 f; }, ... The nesting
+    // exceeds the depth guard, yet every leaf is null so the true minimum is 0.
+    std::string schema = "\"null\"";
+    for (int i = 0; i < 70; ++i) {
+        schema = "{\"type\":\"record\",\"name\":\"R" + std::to_string(i) +
+                 "\",\"fields\":[{\"name\":\"f\",\"type\":" + schema + "}]}";
+    }
+    ValidSchema s = compileJsonSchemaFromString(
+        ("{\"type\":\"array\",\"items\":" + schema + "}").c_str());
+    // 100,000 zero-byte elements is legitimate and must decode.
+    GenericDatum datum = decodeCollectionHeader(s, 100000, true);
+    BOOST_CHECK_EQUAL(datum.value<GenericArray>().value().size(), 100000u);
+}
+
+// Calling bytesRemaining() immediately after init(), before any data has been
+// buffered, must be well-defined (the underlying StreamReader must not subtract
+// null buffer pointers) and report the whole stream as available.
+static void testBytesRemainingRightAfterInit() {
+    const uint8_t data[] = {0x06, 'a', 'b', 'c'};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    BOOST_CHECK_EQUAL(d->bytesRemaining(), static_cast<int64_t>(sizeof(data)));
+}
+
+// Zero-byte elements (null, a record with only zero-byte fields) consume no
+// input, so ensureCollectionAvailable cannot bound their count. A huge declared
+// block count of such elements is capped against a configurable limit.
+static GenericDatum decodeLongs(const ValidSchema &s, const std::vector<int64_t> &longs) {
+    std::unique_ptr<OutputStream> os = memoryOutputStream();
+    EncoderPtr e = binaryEncoder();
+    e->init(*os);
+    for (int64_t v : longs) {
+        e->encodeLong(v);
+    }
+    e->flush();
+    InputStreamPtr in = memoryInputStream(*os);
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    GenericDatum datum;
+    GenericReader::read(*d, datum, s);
+    return datum;
+}
+
+static void testReadArrayOfNullRejectsCountAboveDefaultLimit() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // The reported exploit: 200,000,000 nulls rejected by the default limit.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, true), Exception);
+}
+
+static void testReadArrayOfAllNullRecordRejectsHugeCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":"
+        "{\"type\":\"record\",\"name\":\"R\",\"fields\":[{\"name\":\"n\",\"type\":\"null\"}]}}");
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, true), Exception);
+}
+
+static void testReadArrayOfNullRejectsNegativeCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // Negative count (-200M), block byte-size 0, end marker 0: normalized to
+    // 200M and still bounded.
+    BOOST_CHECK_THROW(decodeLongs(s, {-200000000, 0, 0}), Exception);
+}
+
+static void testReadMapOfNullRejectedByAvailableBytes() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"map\",\"values\":\"null\"}");
+    // Each map entry carries a >= 1 byte key, so a huge map<null> is bounded by
+    // the bytes-remaining check.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, false), Exception);
+}
+
+static void testReadArrayOfNullRespectsConfiguredLimit() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    setenv("AVRO_MAX_COLLECTION_ITEMS", "1000", 1);

Review Comment:
   This test uses `setenv`, which is not available on Windows/MSVC. Please guard it with `_WIN32` and use `_putenv_s` there so the test suite remains portable.



##########
lang/c++/test/AvailableBytesTests.cc:
##########
@@ -0,0 +1,280 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// A bytes/string value is encoded as a length prefix followed by that many
+// bytes of data. A malicious or truncated input can declare a huge length with
+// little or no actual data, which would otherwise trigger a correspondingly
+// huge allocation before the shortfall is noticed. When the input stream can
+// report how many bytes remain (a memory-backed stream), the declared length
+// must be rejected before allocating for it.
+
+#include <cstdint>
+#include <cstdlib>
+#include <memory>
+#include <string>
+#include <vector>
+
+#include <boost/test/included/unit_test.hpp>
+
+#include "Compiler.hh"
+#include "Decoder.hh"
+#include "Encoder.hh"
+#include "Exception.hh"
+#include "Generic.hh"
+#include "Stream.hh"
+#include "ValidSchema.hh"
+
+namespace avro {
+
+// Reading a bytes value whose declared length far exceeds the tiny backing
+// buffer must throw instead of attempting a huge allocation.
+static void testDecodeBytesRejectsOversizedLength() {
+    // 0xFE 0x01 is the zig-zag long 127; the buffer carries no data after it.
+    const uint8_t data[] = {0xFE, 0x01};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::vector<uint8_t> value;
+    BOOST_CHECK_THROW(d->decodeBytes(value), Exception);
+}
+
+static void testDecodeStringRejectsOversizedLength() {
+    const uint8_t data[] = {0xFE, 0x01};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::string value;
+    BOOST_CHECK_THROW(d->decodeString(value), Exception);
+}
+
+// A well-formed value whose declared length fits the buffer still decodes.
+static void testDecodeStringWithinLimitStillReads() {
+    // length 3 (zig-zag 6 -> 0x06) followed by "abc".
+    const uint8_t data[] = {0x06, 'a', 'b', 'c'};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::string value;
+    d->decodeString(value);
+    BOOST_CHECK_EQUAL(value, std::string("abc"));
+}
+
+static void testDecodeBytesWithinLimitStillReads() {
+    const uint8_t data[] = {0x06, 0x01, 0x02, 0x03};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::vector<uint8_t> value;
+    d->decodeBytes(value);
+    BOOST_CHECK_EQUAL(value.size(), 3u);
+    BOOST_CHECK_EQUAL(value[0], 1);
+    BOOST_CHECK_EQUAL(value[2], 3);
+}
+
+// An array/map block declares an element count; a malicious or truncated input
+// can declare far more elements than the remaining bytes could hold. The count
+// is validated against the bytes remaining before resizing, using the minimum
+// on-wire size of the element schema (so 0-byte elements like null are not
+// falsely rejected).
+static GenericDatum decodeCollectionHeader(const ValidSchema &s, int64_t blockCount,
+                                           bool addEndMarker) {
+    // Keep the output stream alive for the whole decode: memoryInputStream
+    // references the output stream's buffer rather than copying it.
+    std::unique_ptr<OutputStream> os = memoryOutputStream();
+    EncoderPtr e = binaryEncoder();
+    e->init(*os);
+    e->encodeLong(blockCount);
+    if (addEndMarker) {
+        e->encodeLong(0);
+    }
+    e->flush();
+
+    InputStreamPtr in = memoryInputStream(*os);
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    GenericDatum datum;
+    GenericReader::read(*d, datum, s);
+    return datum;
+}
+
+static void testReadArrayRejectsOversizedCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"long\"}");
+    // 1,000,000 long elements declared, but no element data follows.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1000000, false), Exception);
+}
+
+static void testReadMapRejectsOversizedCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"map\",\"values\":\"long\"}");
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1000000, false), Exception);
+}
+
+static void testReadArrayOfNullNotFalselyRejected() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // 100,000 nulls (zero bytes each) is legitimate and must decode.
+    GenericDatum datum = decodeCollectionHeader(s, 100000, true);
+    BOOST_CHECK_EQUAL(datum.value<GenericArray>().value().size(), 100000u);
+}
+
+// A deeply but acyclically nested record whose only leaf is null encodes to
+// zero bytes, so the per-element minimum must be 0 and a large array of such
+// records must not be falsely rejected. This exercises the recursion depth
+// guard in minBytesPerElement(), which must yield a conservative lower bound
+// (0) rather than over-estimating for a legitimately deep schema.
+static void testReadArrayOfDeeplyNestedNullNotFalselyRejected() {
+    // Build ~70 nested records: R0 { null f; }, R1 { R0 f; }, ... The nesting
+    // exceeds the depth guard, yet every leaf is null so the true minimum is 0.
+    std::string schema = "\"null\"";
+    for (int i = 0; i < 70; ++i) {
+        schema = "{\"type\":\"record\",\"name\":\"R" + std::to_string(i) +
+                 "\",\"fields\":[{\"name\":\"f\",\"type\":" + schema + "}]}";
+    }
+    ValidSchema s = compileJsonSchemaFromString(
+        ("{\"type\":\"array\",\"items\":" + schema + "}").c_str());
+    // 100,000 zero-byte elements is legitimate and must decode.
+    GenericDatum datum = decodeCollectionHeader(s, 100000, true);
+    BOOST_CHECK_EQUAL(datum.value<GenericArray>().value().size(), 100000u);
+}
+
+// Calling bytesRemaining() immediately after init(), before any data has been
+// buffered, must be well-defined (the underlying StreamReader must not subtract
+// null buffer pointers) and report the whole stream as available.
+static void testBytesRemainingRightAfterInit() {
+    const uint8_t data[] = {0x06, 'a', 'b', 'c'};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    BOOST_CHECK_EQUAL(d->bytesRemaining(), static_cast<int64_t>(sizeof(data)));
+}
+
+// Zero-byte elements (null, a record with only zero-byte fields) consume no
+// input, so ensureCollectionAvailable cannot bound their count. A huge declared
+// block count of such elements is capped against a configurable limit.
+static GenericDatum decodeLongs(const ValidSchema &s, const std::vector<int64_t> &longs) {
+    std::unique_ptr<OutputStream> os = memoryOutputStream();
+    EncoderPtr e = binaryEncoder();
+    e->init(*os);
+    for (int64_t v : longs) {
+        e->encodeLong(v);
+    }
+    e->flush();
+    InputStreamPtr in = memoryInputStream(*os);
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    GenericDatum datum;
+    GenericReader::read(*d, datum, s);
+    return datum;
+}
+
+static void testReadArrayOfNullRejectsCountAboveDefaultLimit() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // The reported exploit: 200,000,000 nulls rejected by the default limit.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, true), Exception);
+}
+
+static void testReadArrayOfAllNullRecordRejectsHugeCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":"
+        "{\"type\":\"record\",\"name\":\"R\",\"fields\":[{\"name\":\"n\",\"type\":\"null\"}]}}");
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, true), Exception);
+}
+
+static void testReadArrayOfNullRejectsNegativeCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // Negative count (-200M), block byte-size 0, end marker 0: normalized to
+    // 200M and still bounded.
+    BOOST_CHECK_THROW(decodeLongs(s, {-200000000, 0, 0}), Exception);
+}
+
+static void testReadMapOfNullRejectedByAvailableBytes() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"map\",\"values\":\"null\"}");
+    // Each map entry carries a >= 1 byte key, so a huge map<null> is bounded by
+    // the bytes-remaining check.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, false), Exception);
+}
+
+static void testReadArrayOfNullRespectsConfiguredLimit() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    setenv("AVRO_MAX_COLLECTION_ITEMS", "1000", 1);
+    // Within the limit decodes; over the limit and cumulative are rejected.
+    GenericDatum ok = decodeCollectionHeader(s, 1000, true);
+    BOOST_CHECK_EQUAL(ok.value<GenericArray>().value().size(), 1000u);
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1001, true), Exception);
+    BOOST_CHECK_THROW(decodeLongs(s, {600, 600, 0}), Exception);
+    unsetenv("AVRO_MAX_COLLECTION_ITEMS");
+}
+
+// A backed non-zero-byte array that passes the bytes check is still bounded by
+// the structural cap (exercised with a lowered limit).
+static void testReadArrayOfLongRejectedByStructuralCap() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"long\"}");
+    setenv("AVRO_MAX_COLLECTION_ITEMS", "5", 1);
+    // 10 real longs: block count 10, ten 1-byte longs, end marker.
+    std::vector<int64_t> longs = {10, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
+    BOOST_CHECK_THROW(decodeLongs(s, longs), Exception);
+    unsetenv("AVRO_MAX_COLLECTION_ITEMS");

Review Comment:
   This test uses `unsetenv`, which is not available on Windows/MSVC. Please guard it with `_WIN32` and use `_putenv_s(name, "")` there so the test suite remains portable.



##########
lang/c++/test/AvailableBytesTests.cc:
##########
@@ -0,0 +1,280 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// A bytes/string value is encoded as a length prefix followed by that many
+// bytes of data. A malicious or truncated input can declare a huge length with
+// little or no actual data, which would otherwise trigger a correspondingly
+// huge allocation before the shortfall is noticed. When the input stream can
+// report how many bytes remain (a memory-backed stream), the declared length
+// must be rejected before allocating for it.
+
+#include <cstdint>
+#include <cstdlib>
+#include <memory>
+#include <string>
+#include <vector>
+
+#include <boost/test/included/unit_test.hpp>
+
+#include "Compiler.hh"
+#include "Decoder.hh"
+#include "Encoder.hh"
+#include "Exception.hh"
+#include "Generic.hh"
+#include "Stream.hh"
+#include "ValidSchema.hh"
+
+namespace avro {
+
+// Reading a bytes value whose declared length far exceeds the tiny backing
+// buffer must throw instead of attempting a huge allocation.
+static void testDecodeBytesRejectsOversizedLength() {
+    // 0xFE 0x01 is the zig-zag long 127; the buffer carries no data after it.
+    const uint8_t data[] = {0xFE, 0x01};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::vector<uint8_t> value;
+    BOOST_CHECK_THROW(d->decodeBytes(value), Exception);
+}
+
+static void testDecodeStringRejectsOversizedLength() {
+    const uint8_t data[] = {0xFE, 0x01};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::string value;
+    BOOST_CHECK_THROW(d->decodeString(value), Exception);
+}
+
+// A well-formed value whose declared length fits the buffer still decodes.
+static void testDecodeStringWithinLimitStillReads() {
+    // length 3 (zig-zag 6 -> 0x06) followed by "abc".
+    const uint8_t data[] = {0x06, 'a', 'b', 'c'};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::string value;
+    d->decodeString(value);
+    BOOST_CHECK_EQUAL(value, std::string("abc"));
+}
+
+static void testDecodeBytesWithinLimitStillReads() {
+    const uint8_t data[] = {0x06, 0x01, 0x02, 0x03};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::vector<uint8_t> value;
+    d->decodeBytes(value);
+    BOOST_CHECK_EQUAL(value.size(), 3u);
+    BOOST_CHECK_EQUAL(value[0], 1);
+    BOOST_CHECK_EQUAL(value[2], 3);
+}
+
+// An array/map block declares an element count; a malicious or truncated input
+// can declare far more elements than the remaining bytes could hold. The count
+// is validated against the bytes remaining before resizing, using the minimum
+// on-wire size of the element schema (so 0-byte elements like null are not
+// falsely rejected).
+static GenericDatum decodeCollectionHeader(const ValidSchema &s, int64_t blockCount,
+                                           bool addEndMarker) {
+    // Keep the output stream alive for the whole decode: memoryInputStream
+    // references the output stream's buffer rather than copying it.
+    std::unique_ptr<OutputStream> os = memoryOutputStream();
+    EncoderPtr e = binaryEncoder();
+    e->init(*os);
+    e->encodeLong(blockCount);
+    if (addEndMarker) {
+        e->encodeLong(0);
+    }
+    e->flush();
+
+    InputStreamPtr in = memoryInputStream(*os);
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    GenericDatum datum;
+    GenericReader::read(*d, datum, s);
+    return datum;
+}
+
+static void testReadArrayRejectsOversizedCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"long\"}");
+    // 1,000,000 long elements declared, but no element data follows.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1000000, false), Exception);
+}
+
+static void testReadMapRejectsOversizedCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"map\",\"values\":\"long\"}");
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1000000, false), Exception);
+}
+
+static void testReadArrayOfNullNotFalselyRejected() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // 100,000 nulls (zero bytes each) is legitimate and must decode.
+    GenericDatum datum = decodeCollectionHeader(s, 100000, true);
+    BOOST_CHECK_EQUAL(datum.value<GenericArray>().value().size(), 100000u);
+}
+
+// A deeply but acyclically nested record whose only leaf is null encodes to
+// zero bytes, so the per-element minimum must be 0 and a large array of such
+// records must not be falsely rejected. This exercises the recursion depth
+// guard in minBytesPerElement(), which must yield a conservative lower bound
+// (0) rather than over-estimating for a legitimately deep schema.
+static void testReadArrayOfDeeplyNestedNullNotFalselyRejected() {
+    // Build ~70 nested records: R0 { null f; }, R1 { R0 f; }, ... The nesting
+    // exceeds the depth guard, yet every leaf is null so the true minimum is 0.
+    std::string schema = "\"null\"";
+    for (int i = 0; i < 70; ++i) {
+        schema = "{\"type\":\"record\",\"name\":\"R" + std::to_string(i) +
+                 "\",\"fields\":[{\"name\":\"f\",\"type\":" + schema + "}]}";
+    }
+    ValidSchema s = compileJsonSchemaFromString(
+        ("{\"type\":\"array\",\"items\":" + schema + "}").c_str());
+    // 100,000 zero-byte elements is legitimate and must decode.
+    GenericDatum datum = decodeCollectionHeader(s, 100000, true);
+    BOOST_CHECK_EQUAL(datum.value<GenericArray>().value().size(), 100000u);
+}
+
+// Calling bytesRemaining() immediately after init(), before any data has been
+// buffered, must be well-defined (the underlying StreamReader must not subtract
+// null buffer pointers) and report the whole stream as available.
+static void testBytesRemainingRightAfterInit() {
+    const uint8_t data[] = {0x06, 'a', 'b', 'c'};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    BOOST_CHECK_EQUAL(d->bytesRemaining(), static_cast<int64_t>(sizeof(data)));
+}
+
+// Zero-byte elements (null, a record with only zero-byte fields) consume no
+// input, so ensureCollectionAvailable cannot bound their count. A huge declared
+// block count of such elements is capped against a configurable limit.
+static GenericDatum decodeLongs(const ValidSchema &s, const std::vector<int64_t> &longs) {
+    std::unique_ptr<OutputStream> os = memoryOutputStream();
+    EncoderPtr e = binaryEncoder();
+    e->init(*os);
+    for (int64_t v : longs) {
+        e->encodeLong(v);
+    }
+    e->flush();
+    InputStreamPtr in = memoryInputStream(*os);
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    GenericDatum datum;
+    GenericReader::read(*d, datum, s);
+    return datum;
+}
+
+static void testReadArrayOfNullRejectsCountAboveDefaultLimit() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // The reported exploit: 200,000,000 nulls rejected by the default limit.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, true), Exception);
+}
+
+static void testReadArrayOfAllNullRecordRejectsHugeCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":"
+        "{\"type\":\"record\",\"name\":\"R\",\"fields\":[{\"name\":\"n\",\"type\":\"null\"}]}}");
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, true), Exception);
+}
+
+static void testReadArrayOfNullRejectsNegativeCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // Negative count (-200M), block byte-size 0, end marker 0: normalized to
+    // 200M and still bounded.
+    BOOST_CHECK_THROW(decodeLongs(s, {-200000000, 0, 0}), Exception);
+}
+
+static void testReadMapOfNullRejectedByAvailableBytes() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"map\",\"values\":\"null\"}");
+    // Each map entry carries a >= 1 byte key, so a huge map<null> is bounded by
+    // the bytes-remaining check.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, false), Exception);
+}
+
+static void testReadArrayOfNullRespectsConfiguredLimit() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    setenv("AVRO_MAX_COLLECTION_ITEMS", "1000", 1);
+    // Within the limit decodes; over the limit and cumulative are rejected.
+    GenericDatum ok = decodeCollectionHeader(s, 1000, true);
+    BOOST_CHECK_EQUAL(ok.value<GenericArray>().value().size(), 1000u);
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1001, true), Exception);
+    BOOST_CHECK_THROW(decodeLongs(s, {600, 600, 0}), Exception);
+    unsetenv("AVRO_MAX_COLLECTION_ITEMS");
+}
+
+// A backed non-zero-byte array that passes the bytes check is still bounded by
+// the structural cap (exercised with a lowered limit).
+static void testReadArrayOfLongRejectedByStructuralCap() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"long\"}");
+    setenv("AVRO_MAX_COLLECTION_ITEMS", "5", 1);
+    // 10 real longs: block count 10, ten 1-byte longs, end marker.
+    std::vector<int64_t> longs = {10, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
+    BOOST_CHECK_THROW(decodeLongs(s, longs), Exception);
+    unsetenv("AVRO_MAX_COLLECTION_ITEMS");
+}
+
+// Skipping a huge array (via the decoder's skipArray) is bounded by the
+// structural cap.
+static void testSkipArrayRejectsHugeCount() {
+    setenv("AVRO_MAX_COLLECTION_ITEMS", "1000", 1);

Review Comment:
   This test uses `setenv`, which is not available on Windows/MSVC. Please guard it with `_WIN32` and use `_putenv_s` there so the test suite remains portable.



##########
lang/c++/test/AvailableBytesTests.cc:
##########
@@ -0,0 +1,280 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// A bytes/string value is encoded as a length prefix followed by that many
+// bytes of data. A malicious or truncated input can declare a huge length with
+// little or no actual data, which would otherwise trigger a correspondingly
+// huge allocation before the shortfall is noticed. When the input stream can
+// report how many bytes remain (a memory-backed stream), the declared length
+// must be rejected before allocating for it.
+
+#include <cstdint>
+#include <cstdlib>
+#include <memory>
+#include <string>
+#include <vector>
+
+#include <boost/test/included/unit_test.hpp>
+
+#include "Compiler.hh"
+#include "Decoder.hh"
+#include "Encoder.hh"
+#include "Exception.hh"
+#include "Generic.hh"
+#include "Stream.hh"
+#include "ValidSchema.hh"
+
+namespace avro {
+
+// Reading a bytes value whose declared length far exceeds the tiny backing
+// buffer must throw instead of attempting a huge allocation.
+static void testDecodeBytesRejectsOversizedLength() {
+    // 0xFE 0x01 is the zig-zag long 127; the buffer carries no data after it.
+    const uint8_t data[] = {0xFE, 0x01};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::vector<uint8_t> value;
+    BOOST_CHECK_THROW(d->decodeBytes(value), Exception);
+}
+
+static void testDecodeStringRejectsOversizedLength() {
+    const uint8_t data[] = {0xFE, 0x01};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::string value;
+    BOOST_CHECK_THROW(d->decodeString(value), Exception);
+}
+
+// A well-formed value whose declared length fits the buffer still decodes.
+static void testDecodeStringWithinLimitStillReads() {
+    // length 3 (zig-zag 6 -> 0x06) followed by "abc".
+    const uint8_t data[] = {0x06, 'a', 'b', 'c'};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::string value;
+    d->decodeString(value);
+    BOOST_CHECK_EQUAL(value, std::string("abc"));
+}
+
+static void testDecodeBytesWithinLimitStillReads() {
+    const uint8_t data[] = {0x06, 0x01, 0x02, 0x03};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::vector<uint8_t> value;
+    d->decodeBytes(value);
+    BOOST_CHECK_EQUAL(value.size(), 3u);
+    BOOST_CHECK_EQUAL(value[0], 1);
+    BOOST_CHECK_EQUAL(value[2], 3);
+}
+
+// An array/map block declares an element count; a malicious or truncated input
+// can declare far more elements than the remaining bytes could hold. The count
+// is validated against the bytes remaining before resizing, using the minimum
+// on-wire size of the element schema (so 0-byte elements like null are not
+// falsely rejected).
+static GenericDatum decodeCollectionHeader(const ValidSchema &s, int64_t blockCount,
+                                           bool addEndMarker) {
+    // Keep the output stream alive for the whole decode: memoryInputStream
+    // references the output stream's buffer rather than copying it.
+    std::unique_ptr<OutputStream> os = memoryOutputStream();
+    EncoderPtr e = binaryEncoder();
+    e->init(*os);
+    e->encodeLong(blockCount);
+    if (addEndMarker) {
+        e->encodeLong(0);
+    }
+    e->flush();
+
+    InputStreamPtr in = memoryInputStream(*os);
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    GenericDatum datum;
+    GenericReader::read(*d, datum, s);
+    return datum;
+}
+
+static void testReadArrayRejectsOversizedCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"long\"}");
+    // 1,000,000 long elements declared, but no element data follows.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1000000, false), Exception);
+}
+
+static void testReadMapRejectsOversizedCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"map\",\"values\":\"long\"}");
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1000000, false), Exception);
+}
+
+static void testReadArrayOfNullNotFalselyRejected() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // 100,000 nulls (zero bytes each) is legitimate and must decode.
+    GenericDatum datum = decodeCollectionHeader(s, 100000, true);
+    BOOST_CHECK_EQUAL(datum.value<GenericArray>().value().size(), 100000u);
+}
+
+// A deeply but acyclically nested record whose only leaf is null encodes to
+// zero bytes, so the per-element minimum must be 0 and a large array of such
+// records must not be falsely rejected. This exercises the recursion depth
+// guard in minBytesPerElement(), which must yield a conservative lower bound
+// (0) rather than over-estimating for a legitimately deep schema.
+static void testReadArrayOfDeeplyNestedNullNotFalselyRejected() {
+    // Build ~70 nested records: R0 { null f; }, R1 { R0 f; }, ... The nesting
+    // exceeds the depth guard, yet every leaf is null so the true minimum is 0.
+    std::string schema = "\"null\"";
+    for (int i = 0; i < 70; ++i) {
+        schema = "{\"type\":\"record\",\"name\":\"R" + std::to_string(i) +
+                 "\",\"fields\":[{\"name\":\"f\",\"type\":" + schema + "}]}";
+    }
+    ValidSchema s = compileJsonSchemaFromString(
+        ("{\"type\":\"array\",\"items\":" + schema + "}").c_str());
+    // 100,000 zero-byte elements is legitimate and must decode.
+    GenericDatum datum = decodeCollectionHeader(s, 100000, true);
+    BOOST_CHECK_EQUAL(datum.value<GenericArray>().value().size(), 100000u);
+}
+
+// Calling bytesRemaining() immediately after init(), before any data has been
+// buffered, must be well-defined (the underlying StreamReader must not subtract
+// null buffer pointers) and report the whole stream as available.
+static void testBytesRemainingRightAfterInit() {
+    const uint8_t data[] = {0x06, 'a', 'b', 'c'};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    BOOST_CHECK_EQUAL(d->bytesRemaining(), static_cast<int64_t>(sizeof(data)));
+}
+
+// Zero-byte elements (null, a record with only zero-byte fields) consume no
+// input, so ensureCollectionAvailable cannot bound their count. A huge declared
+// block count of such elements is capped against a configurable limit.
+static GenericDatum decodeLongs(const ValidSchema &s, const std::vector<int64_t> &longs) {
+    std::unique_ptr<OutputStream> os = memoryOutputStream();
+    EncoderPtr e = binaryEncoder();
+    e->init(*os);
+    for (int64_t v : longs) {
+        e->encodeLong(v);
+    }
+    e->flush();
+    InputStreamPtr in = memoryInputStream(*os);
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    GenericDatum datum;
+    GenericReader::read(*d, datum, s);
+    return datum;
+}
+
+static void testReadArrayOfNullRejectsCountAboveDefaultLimit() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // The reported exploit: 200,000,000 nulls rejected by the default limit.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, true), Exception);
+}
+
+static void testReadArrayOfAllNullRecordRejectsHugeCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":"
+        "{\"type\":\"record\",\"name\":\"R\",\"fields\":[{\"name\":\"n\",\"type\":\"null\"}]}}");
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, true), Exception);
+}
+
+static void testReadArrayOfNullRejectsNegativeCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // Negative count (-200M), block byte-size 0, end marker 0: normalized to
+    // 200M and still bounded.
+    BOOST_CHECK_THROW(decodeLongs(s, {-200000000, 0, 0}), Exception);
+}
+
+static void testReadMapOfNullRejectedByAvailableBytes() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"map\",\"values\":\"null\"}");
+    // Each map entry carries a >= 1 byte key, so a huge map<null> is bounded by
+    // the bytes-remaining check.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, false), Exception);
+}
+
+static void testReadArrayOfNullRespectsConfiguredLimit() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    setenv("AVRO_MAX_COLLECTION_ITEMS", "1000", 1);
+    // Within the limit decodes; over the limit and cumulative are rejected.
+    GenericDatum ok = decodeCollectionHeader(s, 1000, true);
+    BOOST_CHECK_EQUAL(ok.value<GenericArray>().value().size(), 1000u);
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1001, true), Exception);
+    BOOST_CHECK_THROW(decodeLongs(s, {600, 600, 0}), Exception);
+    unsetenv("AVRO_MAX_COLLECTION_ITEMS");
+}
+
+// A backed non-zero-byte array that passes the bytes check is still bounded by
+// the structural cap (exercised with a lowered limit).
+static void testReadArrayOfLongRejectedByStructuralCap() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"long\"}");
+    setenv("AVRO_MAX_COLLECTION_ITEMS", "5", 1);
+    // 10 real longs: block count 10, ten 1-byte longs, end marker.
+    std::vector<int64_t> longs = {10, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
+    BOOST_CHECK_THROW(decodeLongs(s, longs), Exception);
+    unsetenv("AVRO_MAX_COLLECTION_ITEMS");
+}
+
+// Skipping a huge array (via the decoder's skipArray) is bounded by the
+// structural cap.
+static void testSkipArrayRejectsHugeCount() {
+    setenv("AVRO_MAX_COLLECTION_ITEMS", "1000", 1);
+    std::unique_ptr<OutputStream> os = memoryOutputStream();
+    EncoderPtr e = binaryEncoder();
+    e->init(*os);
+    e->encodeLong(2000); // block count 2000, no data needed (skip throws first)
+    e->flush();
+    InputStreamPtr in = memoryInputStream(*os);
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    BOOST_CHECK_THROW(d->skipArray(), Exception);
+    unsetenv("AVRO_MAX_COLLECTION_ITEMS");

Review Comment:
   This test uses `unsetenv`, which is not available on Windows/MSVC. Please guard it with `_WIN32` and use `_putenv_s(name, "")` there so the test suite remains portable.



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Validate available bytes before allocating for length-prefixed values [avro]

Posted by "iemejia (via GitHub)" <gi...@apache.org>.
iemejia commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3565239720


##########
lang/c++/test/AvailableBytesTests.cc:
##########
@@ -0,0 +1,149 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// A bytes/string value is encoded as a length prefix followed by that many
+// bytes of data. A malicious or truncated input can declare a huge length with
+// little or no actual data, which would otherwise trigger a correspondingly
+// huge allocation before the shortfall is noticed. When the input stream can
+// report how many bytes remain (a memory-backed stream), the declared length
+// must be rejected before allocating for it.
+
+#include <cstdint>
+#include <string>
+#include <vector>
+

Review Comment:
   Fixed in 4d983f8: AvailableBytesTests.cc now includes <memory> directly instead of relying on an indirect include.



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Validate available bytes before allocating for length-prefixed values [avro]

Posted by "iemejia (via GitHub)" <gi...@apache.org>.
iemejia commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3565728525


##########
lang/c++/impl/Generic.cc:
##########
@@ -25,6 +26,86 @@ using std::ostringstream;
 using std::string;
 using std::vector;
 
+// Minimum number of bytes a single value of the given schema node can occupy on
+// the wire. Used to reject an array/map block count that could not be backed by
+// the bytes remaining. A type that can encode to zero bytes (null) returns 0,
+// which disables the collection check for it (so an array of nulls is not
+// falsely rejected). A depth limit breaks self-referencing (symbolic) schemas.
+static int64_t minBytesPerElement(const NodePtr &node, int depth) {
+    if (!node) {
+        return 0;
+    }
+    if (depth > 64) {
+        // A cyclic or pathologically deep schema. Return 1 (not 0) so the
+        // collection check stays enabled rather than being silently bypassed;
+        // a valid recursive value always encodes to at least 1 byte.
+        return 1;
+    }

Review Comment:
   Good catch. Moved the depth guard inside the AVRO_RECORD case so a zero-byte leaf type (null) nested under deeply recursive records still returns 0, while a cyclic/pathologically deep record returns 1 (keeping the collection check enabled). Fixed in 3f6569da28.



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Validate available bytes before allocating for length-prefixed values [avro]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3565744004


##########
lang/c++/impl/Generic.cc:
##########
@@ -25,6 +26,88 @@ using std::ostringstream;
 using std::string;
 using std::vector;
 
+// Minimum number of bytes a single value of the given schema node can occupy on
+// the wire. Used to reject an array/map block count that could not be backed by
+// the bytes remaining. A type that can encode to zero bytes (null) returns 0,
+// which disables the collection check for it (so an array of nulls is not
+// falsely rejected). A depth limit breaks self-referencing (symbolic) schemas.
+static int64_t minBytesPerElement(const NodePtr &node, int depth) {
+    if (!node) {
+        return 0;
+    }
+    switch (node->type()) {
+        case AVRO_NULL:
+            return 0;
+        case AVRO_FLOAT:
+            return 4;
+        case AVRO_DOUBLE:
+            return 8;
+        case AVRO_FIXED: {
+            // fixedSize() is a size_t; clamp to int64_t so a huge fixed size
+            // cannot wrap negative.
+            size_t sz = node->fixedSize();
+            return sz > static_cast<size_t>(std::numeric_limits<int64_t>::max())
+                       ? std::numeric_limits<int64_t>::max()
+                       : static_cast<int64_t>(sz);
+        }
+        case AVRO_RECORD: {
+            if (depth > 64) {
+                // A cyclic or pathologically deep record. Return 1 (not 0) so the
+                // collection check stays enabled rather than being silently
+                // bypassed; a valid recursive value always encodes to >= 1 byte.
+                // (The depth guard is applied only here, so zero-byte leaf types

Review Comment:
   minBytesPerElement() uses a hard depth cutoff (depth > 64) for records and returns 1 byte as the minimum. That breaks the function’s “true lower bound” contract for deeply nested but valid (acyclic) schemas whose on-wire minimum can still be 0 (e.g., a chain of records where all leaf fields are null). In those cases, ensureCollectionAvailable() can incorrectly reject valid arrays/maps when bytesRemaining() is small even though elements require 0 bytes on the wire.



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Bound allocation when decoding length-prefixed values and collections [avro]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3567609431


##########
lang/c++/impl/Stream.cc:
##########
@@ -119,6 +130,10 @@ class MemoryInputStream2 : public InputStream {
     size_t byteCount() const final {
         return curLen_;
     }
+
+    int64_t remainingBytes() const final {
+        return static_cast<int64_t>(size_ - curLen_);
+    }

Review Comment:
   MemoryInputStream2::remainingBytes() computes (size_ - curLen_) in size_t before casting to int64_t. If an invariant is ever violated (e.g., a too-large backup()), that subtraction underflows and returns a huge positive remaining count, weakening the allocation/available-bytes guard. Compute the subtraction in int64_t to avoid unsigned underflow.



##########
lang/c++/include/avro/Decoder.hh:
##########
@@ -169,6 +169,14 @@ public:
     /// by the avro decoder. Similar set of problems occur if the Decoder
     /// consumes more than what it should.
     virtual void drain() = 0;
+
+    /// Returns the number of bytes that remain to be read from the underlying
+    /// stream, or a negative value when that count is not known (for example a
+    /// streaming source, or a decoder not backed by a byte stream). The default
+    /// is "unknown"; byte-stream decoders override it so a length prefix or a
+    /// collection block count that exceeds the data actually available can be
+    /// rejected before allocating for it.
+    virtual int64_t bytesRemaining() const { return -1; }

Review Comment:
   Adding new virtual methods to public interfaces (InputStream::remainingBytes and Decoder::bytesRemaining) changes vtable layout and is an ABI-breaking change for downstream code that subclasses these types across shared-library boundaries. If the C++ SDK aims to preserve binary compatibility across patch/minor releases, this needs a strategy (e.g., a new derived interface, pimpl, or a major-version/SONAME bump) and release-note callout.



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Bound allocation when decoding length-prefixed values and collections [avro]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3567569593


##########
lang/c++/include/avro/Stream.hh:
##########
@@ -345,6 +356,28 @@ struct StreamReader {
         return next_ != end_ || fill();
     }
 
+    /**
+     * Returns the number of bytes still available to be read: those already
+     * buffered in this reader plus whatever the underlying stream reports as
+     * remaining. Returns a negative value when the underlying stream cannot
+     * report its remaining size.
+     */
+    int64_t remainingBytes() const {
+        if (in_ == nullptr) {
+            return -1;
+        }
+        int64_t streamRemaining = in_->remainingBytes();
+        if (streamRemaining < 0) {
+            return -1;
+        }
+        // Bytes already buffered in this reader, added to what the underlying
+        // stream still has. When next_ and end_ are both null (right after
+        // init()/reset(), before any data is buffered), the subtraction is
+        // well-defined and yields 0.
+        int64_t buffered = end_ - next_;
+        return buffered + streamRemaining;

Review Comment:
   StreamReader::remainingBytes() performs pointer subtraction (end_ - next_) even when both pointers are nullptr right after reset()/init(). Pointer subtraction is only defined for pointers into the same array object; subtracting null pointers is undefined behavior and can make bytesRemaining() unreliable on some platforms/optimizations. Compute the buffered byte count conditionally (treat it as 0 when no buffer has been filled yet) and update the comment accordingly.



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Bound allocation when decoding length-prefixed values and collections [avro]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3568265156


##########
lang/c++/impl/BinaryDecoder.cc:
##########
@@ -153,7 +203,7 @@ void BinaryDecoder::skipFixed(size_t n) {
 }

Review Comment:
   `BinaryDecoder::skipFixed()` can be called as the first operation after `init()`. At that point `StreamReader::reset()` has set `next_`/`end_` to `nullptr`, and `StreamReader::skipBytes()` performs `end_ - next_`, which is undefined for null pointers. Avoid passing control to `skipBytes()` in that state (and while here, reuse `checkAvailableBytes()` for memory-backed streams).



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Bound allocation when decoding length-prefixed values and collections [avro]

Posted by "iemejia (via GitHub)" <gi...@apache.org>.
iemejia commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3567430517


##########
lang/c++/impl/BinaryDecoder.cc:
##########
@@ -163,8 +206,22 @@ size_t BinaryDecoder::arrayStart() {
 size_t BinaryDecoder::doDecodeItemCount() {
     auto result = doDecodeLong();
     if (result < 0) {
+        // INT64_MIN cannot be negated in int64_t (it would overflow); reject it
+        // rather than propagating 2^63 as an item count that inevitably fails a
+        // huge allocation downstream.
+        if (result == INT64_MIN) {
+            throw Exception("Invalid negative block count: {}", result);
+        }
         doDecodeLong();
-        return static_cast<size_t>(-(result + 1)) + 1;
+        result = -result;

Review Comment:
   This is already handled as of commit 4f4f8f4de6: doDecodeItemCount now reads the block byte-size into `blockSize` and throws `Exception("Invalid negative block byte-size")` when it is < 0, so arrayStart()/arrayNext()/mapStart()/mapNext() reject it consistently with skipArray().



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Bound allocation when decoding length-prefixed values and collections [avro]

Posted by "iemejia (via GitHub)" <gi...@apache.org>.
iemejia commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3567500451


##########
lang/c++/impl/BinaryDecoder.cc:
##########
@@ -177,9 +242,27 @@ size_t BinaryDecoder::skipArray() {
     for (;;) {
         auto r = doDecodeLong();
         if (r < 0) {
-            auto n = static_cast<size_t>(doDecodeLong());
-            in_.skipBytes(n);
+            auto byteSize = doDecodeLong();
+            if (byteSize < 0) {
+                // A negative block byte-size would convert to a huge size_t and
+                // drive an unbounded skip; reject it.
+                throw Exception("Invalid negative block size: {}", byteSize);
+            }
+            in_.skipBytes(static_cast<size_t>(byteSize));

Review Comment:
   Fixed — the negative-block byte-size now gets the same `if constexpr (sizeof(size_t) < sizeof(int64_t))` fit guard before the cast, and `checkAvailableBytes(byteSize)` is called before skipBytes(), so a too-large or truncated block is rejected instead of being silently skipped past EOF.



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Bound allocation when decoding length-prefixed values and collections [avro]

Posted by "Gerrit0 (via GitHub)" <gi...@apache.org>.
Gerrit0 commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3567565883


##########
lang/c++/include/avro/GenericDatum.hh:
##########
@@ -244,6 +244,9 @@ public:
      * \param branch The index for the selected branch.
      */
     void selectBranch(size_t branch) {
+        if (branch >= schema()->leaves()) {
+            throw Exception("Union branch index out of range: must be less than " + std::to_string(schema()->leaves()) + ", but is " + std::to_string(branch));
+        }

Review Comment:
   This has been my first real experience looking at reviews from AI... and wow, this thing has been _so confidently wrong_ (or at least just noise) in almost every instance. `leaves()` gives a `size_t`, this comment makes absolutely no sense. There's absolutely no need to check for negative values against an unsigned type...



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Bound allocation when decoding length-prefixed values and collections [avro]

Posted by "iemejia (via GitHub)" <gi...@apache.org>.
iemejia commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3567607239


##########
lang/c++/include/avro/Stream.hh:
##########
@@ -345,6 +356,28 @@ struct StreamReader {
         return next_ != end_ || fill();
     }
 
+    /**
+     * Returns the number of bytes still available to be read: those already
+     * buffered in this reader plus whatever the underlying stream reports as
+     * remaining. Returns a negative value when the underlying stream cannot
+     * report its remaining size.
+     */
+    int64_t remainingBytes() const {
+        if (in_ == nullptr) {
+            return -1;
+        }
+        int64_t streamRemaining = in_->remainingBytes();
+        if (streamRemaining < 0) {
+            return -1;
+        }
+        // Bytes already buffered in this reader, added to what the underlying
+        // stream still has. When next_ and end_ are both null (right after
+        // init()/reset(), before any data is buffered), the subtraction is
+        // well-defined and yields 0.
+        int64_t buffered = end_ - next_;
+        return buffered + streamRemaining;

Review Comment:
   As noted previously: this guard was deliberately removed at a maintainer's request to match the rest of Stream.hh. next_ and end_ are always assigned together (both null immediately after init()/reset(), both valid once data is buffered), so the null case yields 0 in practice on every supported platform. Deferring to that maintainer decision; the comment documents the null case.



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Bound allocation when decoding length-prefixed values and collections [avro]

Posted by "iemejia (via GitHub)" <gi...@apache.org>.
iemejia commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3567546346


##########
lang/c++/impl/Generic.cc:
##########
@@ -25,6 +29,164 @@ using std::ostringstream;
 using std::string;
 using std::vector;
 
+// Minimum number of bytes a single value of the given schema node can occupy on
+// the wire. Used to reject an array/map block count that could not be backed by
+// the bytes remaining. A type that can encode to zero bytes (null) returns 0,
+// which disables the collection check for it (so an array of nulls is not
+// falsely rejected). A depth limit breaks self-referencing (symbolic) schemas.
+static int64_t minBytesPerElement(const NodePtr &node, int depth) {
+    if (!node) {
+        return 0;
+    }
+    switch (node->type()) {
+        case AVRO_NULL:
+            return 0;
+        case AVRO_FLOAT:
+            return 4;
+        case AVRO_DOUBLE:
+            return 8;
+        case AVRO_FIXED: {
+            // fixedSize() is a size_t; clamp to int64_t so a huge fixed size
+            // cannot wrap negative.
+            return static_cast<int64_t>(std::min<uint64_t>(
+                node->fixedSize(),
+                static_cast<uint64_t>(std::numeric_limits<int64_t>::max())));
+        }
+        case AVRO_RECORD: {
+            if (depth > 64) {
+                // Purely a recursion (stack-overflow) safety net for a
+                // pathologically deep schema. A truly cyclic schema never
+                // reaches this: a self-reference is an AVRO_SYMBOLIC node,
+                // handled by the default case below (returning 1 without
+                // following the link), so recursion always terminates. This
+                // guard therefore only trips on a genuinely deep *acyclic*
+                // record, whose true minimum can still be 0 (e.g. a long chain
+                // of records whose only leaves are null). Return 0 rather than
+                // over-estimating, so a valid array/map of such elements is not
+                // falsely rejected; 0 is always a valid lower bound.
+                return 0;
+            }
+            int64_t total = 0;
+            for (size_t i = 0; i < node->leaves(); ++i) {
+                int64_t fieldMin = minBytesPerElement(node->leafAt(i), depth + 1);
+                // Saturate rather than overflow: a wrapped (negative) total
+                // would disable the collection check.
+                if (fieldMin > std::numeric_limits<int64_t>::max() - total) {
+                    return std::numeric_limits<int64_t>::max();
+                }
+                total += fieldMin;
+            }
+            return total;
+        }
+        default:
+            // boolean, int, long, bytes, string, enum, union, array, map and
+            // symbolic references all encode to at least one byte.
+            return 1;
+    }
+}
+
+// Default maximum number of zero-byte-encoded collection elements (e.g. an
+// array of nulls) to allocate from a single decode. Such elements consume no
+// input, so ensureCollectionAvailable cannot bound their count; without a cap a
+// tiny payload can declare a huge block count and exhaust memory. Overridable
+// via the AVRO_MAX_COLLECTION_ITEMS environment variable.
+static constexpr int64_t kDefaultMaxCollectionItems = 10000000;
+
+// Structural cap on the number of elements in any array or map (an overflow /
+// defense-in-depth guard). It matches the value used by the other Avro SDKs
+// (Integer.MAX_VALUE - 8); non-zero-byte elements are also bounded by the bytes
+// remaining.
+static constexpr int64_t kDefaultMaxCollectionStructural = 2147483639;
+
+// Upper bound on how many elements a collection container is grown by in a
+// single step while decoding. The container still grows to hold every element
+// that is actually read; this only prevents resizing to the full (possibly
+// attacker-declared) block count up front, before any element is decoded. That
+// matters most for stream sources, where the bytes-remaining check cannot bound
+// the declared count against the input, so a single up-front resize could
+// allocate a huge container before the truncated stream is detected.
+static constexpr size_t kMaxCollectionPrealloc = 1024;
+
+struct CollectionLimits {
+    int64_t zeroByte;
+    int64_t structural;
+};
+
+// AVRO_MAX_COLLECTION_ITEMS, when a non-negative integer, overrides both limits
+// to that value; otherwise zero-byte elements use the tighter default and all
+// collections use the structural default.
+static CollectionLimits collectionLimits() {
+    const char *env = std::getenv("AVRO_MAX_COLLECTION_ITEMS");
+    if (env != nullptr && *env != '\0') {
+        char *end = nullptr;
+        long long value = std::strtoll(env, &end, 10);
+        if (*end == '\0' && value >= 0) {
+            return {static_cast<int64_t>(value), static_cast<int64_t>(value)};
+        }
+    }
+    return {kDefaultMaxCollectionItems, kDefaultMaxCollectionStructural};

Review Comment:
   Fixed — collectionLimits() now checks errno after strtoll and ignores an overflowing (ERANGE) value, falling back to the defaults instead of accepting a saturated LLONG_MAX.



##########
lang/c++/impl/BinaryDecoder.cc:
##########
@@ -19,12 +19,36 @@
 #include "Decoder.hh"
 #include "Exception.hh"
 #include "Zigzag.hh"
+#include <cstdint>
+#include <cstdlib>
+#include <limits>
 #include <memory>
 
 namespace avro {
 
 using std::make_shared;
 
+// Structural cap on the number of elements to skip in an array or map (an
+// overflow / defense-in-depth guard). Mirrors the read-path limit in Generic.cc
+// and matches the value used by the other Avro SDKs (Integer.MAX_VALUE - 8).
+static constexpr int64_t kDefaultMaxCollectionStructural = 2147483639;
+
+// Returns the structural collection cap. It can be overridden by the
+// AVRO_MAX_COLLECTION_ITEMS environment variable (a non-negative integer),
+// matching the read path and the other SDKs so a single knob configures all of
+// them; an invalid or unset value uses the default.
+static int64_t maxCollectionStructural() {
+    const char *env = std::getenv("AVRO_MAX_COLLECTION_ITEMS");
+    if (env != nullptr && *env != '\0') {
+        char *end = nullptr;
+        long long value = std::strtoll(env, &end, 10);
+        if (*end == '\0' && value >= 0) {
+            return static_cast<int64_t>(value);
+        }
+    }
+    return kDefaultMaxCollectionStructural;
+}

Review Comment:
   Fixed — maxCollectionStructural() applies the same errno/ERANGE check so an overflowing env value can't disable the structural cap.



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Bound allocation when decoding length-prefixed values and collections [avro]

Posted by "iemejia (via GitHub)" <gi...@apache.org>.
iemejia commented on PR #3859:
URL: https://github.com/apache/avro/pull/3859#issuecomment-4951914839

   This PR now also folds in the INT64_MIN block-count fix from AVRO-4276: `doDecodeItemCount()` turned INT64_MIN into 2^63 (an impossible allocation downstream). It now rejects INT64_MIN early and uses the simpler `-result` negation, with tests on `arrayStart()` and `mapStart()`. AVRO-4276 / #3843 is therefore superseded by this PR.


-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Bound allocation when decoding length-prefixed values and collections [avro]

Posted by "iemejia (via GitHub)" <gi...@apache.org>.
iemejia commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3567412550


##########
lang/c++/impl/BinaryDecoder.cc:
##########
@@ -163,8 +206,22 @@ size_t BinaryDecoder::arrayStart() {
 size_t BinaryDecoder::doDecodeItemCount() {
     auto result = doDecodeLong();
     if (result < 0) {
+        // INT64_MIN cannot be negated in int64_t (it would overflow); reject it
+        // rather than propagating 2^63 as an item count that inevitably fails a
+        // huge allocation downstream.
+        if (result == INT64_MIN) {
+            throw Exception("Invalid negative block count: {}", result);
+        }
         doDecodeLong();
-        return static_cast<size_t>(-(result + 1)) + 1;
+        result = -result;
+    }

Review Comment:
   Fixed — doDecodeItemCount now reads the block byte-size into a variable and rejects a negative value (matching skipArray), so arrayStart()/mapStart() fail fast on corrupt input.



##########
lang/c++/impl/BinaryDecoder.cc:
##########
@@ -109,12 +138,25 @@ size_t BinaryDecoder::doDecodeLength() {
     return len;
 }
 
+void BinaryDecoder::checkAvailableBytes(size_t len) {
+    // Reject a declared length that exceeds the data actually available before
+    // allocating for it, to guard against an out-of-memory attack from a
+    // malicious or truncated input. Only enforced when the stream can report
+    // how many bytes remain.
+    int64_t remaining = in_.remainingBytes();
+    if (remaining >= 0 && static_cast<uint64_t>(len) > static_cast<uint64_t>(remaining)) {
+        throw Exception(
+            "Length {} exceeds the {} bytes available in the stream", len, remaining);
+    }
+}
+
 void BinaryDecoder::drain() {
     in_.drain(false);
 }
 
 void BinaryDecoder::decodeString(std::string &value) {
     size_t len = doDecodeLength();
+    checkAvailableBytes(len);
     value.resize(len);

Review Comment:
   Fixed — skipString now calls checkAvailableBytes(len) before skipping, so a length exceeding the known remaining bytes is rejected instead of being silently clamped at EOF by InputStream::skip.



##########
lang/c++/impl/BinaryDecoder.cc:
##########
@@ -130,6 +172,7 @@ void BinaryDecoder::skipString() {
 
 void BinaryDecoder::decodeBytes(std::vector<uint8_t> &value) {
     size_t len = doDecodeLength();
+    checkAvailableBytes(len);
     value.resize(len);

Review Comment:
   Fixed — skipBytes likewise calls checkAvailableBytes(len), consistent with decodeBytes.



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Validate available bytes before allocating for length-prefixed values [avro]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3565205279


##########
lang/c++/test/AvailableBytesTests.cc:
##########
@@ -0,0 +1,149 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// A bytes/string value is encoded as a length prefix followed by that many
+// bytes of data. A malicious or truncated input can declare a huge length with
+// little or no actual data, which would otherwise trigger a correspondingly
+// huge allocation before the shortfall is noticed. When the input stream can
+// report how many bytes remain (a memory-backed stream), the declared length
+// must be rejected before allocating for it.
+
+#include <cstdint>
+#include <string>
+#include <vector>
+

Review Comment:
   This new test uses std::unique_ptr but does not include <memory>. Relying on indirect includes (e.g., from Boost headers) is non-portable and can break with different standard library / Boost versions.



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Validate available bytes before allocating for length-prefixed values [avro]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3565824240


##########
lang/c++/include/avro/Stream.hh:
##########
@@ -345,6 +356,26 @@ struct StreamReader {
         return next_ != end_ || fill();
     }
 
+    /**
+     * Returns the number of bytes still available to be read: those already
+     * buffered in this reader plus whatever the underlying stream reports as
+     * remaining. Returns a negative value when the underlying stream cannot
+     * report its remaining size.
+     */
+    int64_t remainingBytes() const {
+        if (in_ == nullptr) {
+            return -1;
+        }
+        int64_t streamRemaining = in_->remainingBytes();
+        if (streamRemaining < 0) {
+            return -1;
+        }
+        // end_ - next_ is the data already buffered in this reader; it is added
+        // to what the underlying stream still has. The addition promotes the
+        // pointer difference to int64_t.
+        return (end_ - next_) + streamRemaining;
+    }

Review Comment:
   StreamReader::remainingBytes() subtracts pointers (end_ - next_) even when the reader has not yet buffered any data (after reset/init sets next_ and end_ to nullptr). Subtracting nullptr pointers is undefined behavior; a caller can trigger this by calling Decoder::bytesRemaining() immediately after init() on a BinaryDecoder.



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Bound allocation when decoding length-prefixed values and collections [avro]

Posted by "iemejia (via GitHub)" <gi...@apache.org>.
iemejia commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3567528107


##########
lang/c++/impl/Generic.cc:
##########
@@ -105,11 +267,38 @@ void GenericReader::read(GenericDatum &datum, Decoder &d, bool isResolving) {
             const NodePtr &nn = v.schema()->leafAt(0);
             r.resize(0);
             size_t start = 0;
+            // Only when not resolving: the datum schema then matches the wire
+            // schema, so minBytesPerElement is a true lower bound. Under
+            // resolution the wire (writer) type may be smaller than the datum
+            // (reader) type, which would over-estimate and reject valid data.
+            int64_t trueMin = minBytesPerElement(nn, 0);
+            // Under resolution the on-wire (writer) element can be zero bytes
+            // even when the reader element is not (e.g. reader-only fields filled
+            // from defaults), so the bytes check is disabled and we cannot tell
+            // whether an element is zero-byte on the wire. Apply the tighter
+            // zero-byte cap conservatively in that case, so the up-front resize
+            // cannot be driven past it.
+            bool zeroByte = isResolving || trueMin == 0;

Review Comment:
   This is a deliberate, conservative tradeoff. Under resolution the datum/reader element schema (`nn`) may differ from the on-wire writer element, and a writer element can be zero-byte even when the reader element isn't (e.g. reader-only fields filled from defaults). Since minBytesPerElement(reader) would then over-estimate the writer's on-wire size and falsely reject valid data, the bytes-remaining check is disabled (minBytes=0) and the zero-byte cap is applied so a genuinely-zero-byte writer element can't drive a huge resize from a tiny payload.
   
   The structural cap (default Integer.MAX_VALUE - 8) still always applies; the extra bound under resolution is the zero-byte item cap (default 10,000,000), which is raisable via `AVRO_MAX_COLLECTION_ITEMS`. Applying the precise per-element bytes bound under resolution would require plumbing the *writer* element schema's minimum on-wire size into this read path (the ResolvingDecoder doesn't expose it here), which is a larger refactor. Given a legit >10M-element resolving array can raise the limit via the env var, keeping the conservative cap here is the safer default; I can file a follow-up for the precise-writer-min-bytes bound if you'd prefer.



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Bound allocation when decoding length-prefixed values and collections [avro]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3567558879


##########
lang/c++/include/avro/GenericDatum.hh:
##########
@@ -244,6 +244,9 @@ public:
      * \param branch The index for the selected branch.
      */
     void selectBranch(size_t branch) {
+        if (branch >= schema()->leaves()) {
+            throw Exception("Union branch index out of range: must be less than " + std::to_string(schema()->leaves()) + ", but is " + std::to_string(branch));
+        }

Review Comment:
   GenericUnion::selectBranch() now guards against out-of-range branch indices, but because the parameter is size_t, a negative union index decoded from the wire (e.g. BinaryDecoder::decodeUnionIndex() casting an int64_t) will wrap to a huge value and produce a confusing error. Consider validating union indices at decode time (reject idx < 0 and size_t truncation) so negative inputs fail with a clear Avro exception before reaching selectBranch().



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Bound allocation when decoding length-prefixed values and collections [avro]

Posted by "iemejia (via GitHub)" <gi...@apache.org>.
iemejia commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3568121881


##########
lang/c++/include/avro/Decoder.hh:
##########
@@ -169,6 +169,14 @@ public:
     /// by the avro decoder. Similar set of problems occur if the Decoder
     /// consumes more than what it should.
     virtual void drain() = 0;
+
+    /// Returns the number of bytes that remain to be read from the underlying
+    /// stream, or a negative value when that count is not known (for example a
+    /// streaming source, or a decoder not backed by a byte stream). The default
+    /// is "unknown"; byte-stream decoders override it so a length prefix or a
+    /// collection block count that exceeds the data actually available can be
+    /// rejected before allocating for it.
+    virtual int64_t bytesRemaining() const { return -1; }

Review Comment:
   Decision: keep the virtual approach and accept the ABI bump for the next release. The C++ shared library's VERSION is derived from AVRO_VERSION (share/VERSION.txt) in CMakeLists.txt (set_target_properties ... VERSION ${AVRO_VERSION}), so the library version already changes with each release and downstream consumers relink against the new version. No separate SOVERSION pin needs bumping. The new virtual remainingBytes()/bytesRemaining() are therefore acceptable here.



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Bound allocation when decoding length-prefixed values and collections [avro]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3568231175


##########
lang/c++/include/avro/Stream.hh:
##########
@@ -345,6 +356,30 @@ struct StreamReader {
         return next_ != end_ || fill();
     }
 
+    /**
+     * Returns the number of bytes still available to be read: those already
+     * buffered in this reader plus whatever the underlying stream reports as
+     * remaining. Returns a negative value when the underlying stream cannot
+     * report its remaining size.
+     */
+    int64_t remainingBytes() const {
+        if (in_ == nullptr) {
+            return -1;
+        }
+        int64_t streamRemaining = in_->remainingBytes();
+        if (streamRemaining < 0) {
+            return -1;
+        }
+        // Bytes already buffered in this reader, added to what the underlying
+        // stream still has. next_ and end_ can both be null right after
+        // init()/reset() (before any data is buffered); subtracting two null
+        // pointers is undefined behavior, so treat equal pointers (including the
+        // both-null case) as zero buffered and only subtract real buffer
+        // pointers. Pointer equality, unlike subtraction, is well-defined here.
+        int64_t buffered = (next_ == end_) ? 0 : (end_ - next_);
+        return buffered + streamRemaining;

Review Comment:
   StreamReader::remainingBytes() only treats the both-null case as zero buffered via (next_ == end_), but if either pointer is null while the other is not (e.g., after reset() or a failed/partial fill), the expression (end_ - next_) would still be evaluated and is undefined behavior. Since this method is meant to be safe to call right after init/reset, it should defensively treat any null pointer as zero buffered.



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Validate available bytes before allocating for length-prefixed values [avro]

Posted by "iemejia (via GitHub)" <gi...@apache.org>.
iemejia commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3565149931


##########
lang/c++/impl/Stream.cc:
##########
@@ -84,6 +84,15 @@ class MemoryInputStream : public InputStream {
     size_t byteCount() const final {
         return cur_ * chunkSize_ + curLen_;
     }
+
+    int64_t remainingBytes() const final {
+        // Total capacity across all chunks: full chunks plus the (partial)
+        // last chunk, minus what has already been consumed.
+        int64_t total = (size_ == 0)
+                            ? 0
+                            : static_cast<int64_t>((size_ - 1) * chunkSize_ + available_);
+        return total - static_cast<int64_t>(cur_ * chunkSize_ + curLen_);
+    }

Review Comment:
   Fixed in 0f223c5: remainingBytes() now widens each operand to int64_t before multiplying, so (size_-1)*chunkSize_ can no longer overflow size_t before the cast.



##########
lang/c++/impl/Generic.cc:
##########
@@ -105,7 +156,13 @@ void GenericReader::read(GenericDatum &datum, Decoder &d, bool isResolving) {
             const NodePtr &nn = v.schema()->leafAt(0);
             r.resize(0);
             size_t start = 0;
+            // Only when not resolving: the datum schema then matches the wire
+            // schema, so minBytesPerElement is a true lower bound. Under
+            // resolution the wire (writer) type may be smaller than the datum
+            // (reader) type, which would over-estimate and reject valid data.
+            int64_t minBytes = isResolving ? 0 : minBytesPerElement(nn, 0);
             for (size_t m = d.arrayStart(); m != 0; m = d.arrayNext()) {
+                ensureCollectionAvailable(d, m, minBytes);
                 r.resize(r.size() + m);

Review Comment:
   Fixed in 0f223c5: array decoding now calls ensureCanGrow(r, m), a max_size()-based guard, before r.resize(r.size() + m), so a huge block count cannot overflow size_t or request an impossible allocation (this also covers null-element arrays where the byte check is skipped).



##########
lang/c++/impl/Generic.cc:
##########
@@ -119,7 +176,10 @@ void GenericReader::read(GenericDatum &datum, Decoder &d, bool isResolving) {
             const NodePtr &nn = v.schema()->leafAt(1);
             r.resize(0);
             size_t start = 0;
+            // Map keys are strings (>= 1 byte length prefix) plus the value.
+            int64_t minBytes = isResolving ? 0 : (1 + minBytesPerElement(nn, 0));
             for (size_t m = d.mapStart(); m != 0; m = d.mapNext()) {
+                ensureCollectionAvailable(d, m, minBytes);
                 r.resize(r.size() + m);

Review Comment:
   Fixed in 0f223c5: the same max_size()-based ensureCanGrow(r, m) guard is applied before resizing the map container.



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Bound allocation when decoding length-prefixed values and collections [avro]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3566909117


##########
lang/c++/impl/BinaryDecoder.cc:
##########
@@ -163,8 +205,14 @@ size_t BinaryDecoder::arrayStart() {
 size_t BinaryDecoder::doDecodeItemCount() {
     auto result = doDecodeLong();
     if (result < 0) {
+        // INT64_MIN cannot be negated in int64_t (it would overflow); reject it
+        // rather than propagating 2^63 as an item count that inevitably fails a
+        // huge allocation downstream.
+        if (result == INT64_MIN) {
+            throw Exception("Invalid negative block count: {}", result);
+        }
         doDecodeLong();
-        return static_cast<size_t>(-(result + 1)) + 1;
+        return static_cast<size_t>(-result);
     }
     return static_cast<size_t>(result);

Review Comment:
   BinaryDecoder::doDecodeItemCount() casts the decoded int64 block count directly to size_t. On 32-bit builds (or any build where size_t is narrower than int64_t), large counts can truncate/wrap, which can bypass the downstream structural caps and lead to incorrect decoding (treating a huge block as a small one). Please reject counts that do not fit into size_t before returning.



##########
lang/c++/include/avro/Stream.hh:
##########
@@ -345,6 +356,28 @@ struct StreamReader {
         return next_ != end_ || fill();
     }
 
+    /**
+     * Returns the number of bytes still available to be read: those already
+     * buffered in this reader plus whatever the underlying stream reports as
+     * remaining. Returns a negative value when the underlying stream cannot
+     * report its remaining size.
+     */
+    int64_t remainingBytes() const {
+        if (in_ == nullptr) {
+            return -1;
+        }
+        int64_t streamRemaining = in_->remainingBytes();
+        if (streamRemaining < 0) {
+            return -1;
+        }
+        // Bytes already buffered in this reader, added to what the underlying
+        // stream still has. When next_ and end_ are both null (right after
+        // init()/reset(), before any data is buffered), the subtraction is
+        // well-defined and yields 0.
+        int64_t buffered = end_ - next_;
+        return buffered + streamRemaining;

Review Comment:
   StreamReader::remainingBytes() computes `end_ - next_` even when `next_`/`end_` are null right after init()/reset(). Subtracting null pointers is undefined behavior, and callers can trigger it via Decoder::bytesRemaining() immediately after init(). Please guard the pointer subtraction and treat the buffered count as 0 when no buffer has been filled yet.



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-4294: [c++] Bound allocation when decoding length-prefixed values and collections [avro]

Posted by "iemejia (via GitHub)" <gi...@apache.org>.
iemejia commented on code in PR #3859:
URL: https://github.com/apache/avro/pull/3859#discussion_r3566893354


##########
lang/c++/impl/BinaryDecoder.cc:
##########
@@ -180,6 +228,18 @@ size_t BinaryDecoder::skipArray() {
             auto n = static_cast<size_t>(doDecodeLong());
             in_.skipBytes(n);
         } else {
+            // Bound the block count: skipping a huge block of zero-byte elements
+            // would otherwise loop unboundedly (a CPU exhaustion) even though it
+            // reads/allocates nothing. The decoder has no element schema here, so
+            // apply the structural cap (AVRO_MAX_COLLECTION_ITEMS, default
+            // Integer.MAX_VALUE - 8).
+            static const int64_t structural = maxCollectionStructural();

Review Comment:
   Fixed in e6a35fa802 (same as above): the structural limit is read on each skipArray() call rather than cached in a function-static, so it stays consistent with Generic.cc's dynamic read.



##########
lang/c++/test/AvailableBytesTests.cc:
##########
@@ -0,0 +1,280 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// A bytes/string value is encoded as a length prefix followed by that many
+// bytes of data. A malicious or truncated input can declare a huge length with
+// little or no actual data, which would otherwise trigger a correspondingly
+// huge allocation before the shortfall is noticed. When the input stream can
+// report how many bytes remain (a memory-backed stream), the declared length
+// must be rejected before allocating for it.
+
+#include <cstdint>
+#include <cstdlib>
+#include <memory>
+#include <string>
+#include <vector>
+
+#include <boost/test/included/unit_test.hpp>
+
+#include "Compiler.hh"
+#include "Decoder.hh"
+#include "Encoder.hh"
+#include "Exception.hh"
+#include "Generic.hh"
+#include "Stream.hh"
+#include "ValidSchema.hh"
+
+namespace avro {
+
+// Reading a bytes value whose declared length far exceeds the tiny backing
+// buffer must throw instead of attempting a huge allocation.
+static void testDecodeBytesRejectsOversizedLength() {
+    // 0xFE 0x01 is the zig-zag long 127; the buffer carries no data after it.
+    const uint8_t data[] = {0xFE, 0x01};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::vector<uint8_t> value;
+    BOOST_CHECK_THROW(d->decodeBytes(value), Exception);
+}
+
+static void testDecodeStringRejectsOversizedLength() {
+    const uint8_t data[] = {0xFE, 0x01};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::string value;
+    BOOST_CHECK_THROW(d->decodeString(value), Exception);
+}
+
+// A well-formed value whose declared length fits the buffer still decodes.
+static void testDecodeStringWithinLimitStillReads() {
+    // length 3 (zig-zag 6 -> 0x06) followed by "abc".
+    const uint8_t data[] = {0x06, 'a', 'b', 'c'};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::string value;
+    d->decodeString(value);
+    BOOST_CHECK_EQUAL(value, std::string("abc"));
+}
+
+static void testDecodeBytesWithinLimitStillReads() {
+    const uint8_t data[] = {0x06, 0x01, 0x02, 0x03};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::vector<uint8_t> value;
+    d->decodeBytes(value);
+    BOOST_CHECK_EQUAL(value.size(), 3u);
+    BOOST_CHECK_EQUAL(value[0], 1);
+    BOOST_CHECK_EQUAL(value[2], 3);
+}
+
+// An array/map block declares an element count; a malicious or truncated input
+// can declare far more elements than the remaining bytes could hold. The count
+// is validated against the bytes remaining before resizing, using the minimum
+// on-wire size of the element schema (so 0-byte elements like null are not
+// falsely rejected).
+static GenericDatum decodeCollectionHeader(const ValidSchema &s, int64_t blockCount,
+                                           bool addEndMarker) {
+    // Keep the output stream alive for the whole decode: memoryInputStream
+    // references the output stream's buffer rather than copying it.
+    std::unique_ptr<OutputStream> os = memoryOutputStream();
+    EncoderPtr e = binaryEncoder();
+    e->init(*os);
+    e->encodeLong(blockCount);
+    if (addEndMarker) {
+        e->encodeLong(0);
+    }
+    e->flush();
+
+    InputStreamPtr in = memoryInputStream(*os);
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    GenericDatum datum;
+    GenericReader::read(*d, datum, s);
+    return datum;
+}
+
+static void testReadArrayRejectsOversizedCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"long\"}");
+    // 1,000,000 long elements declared, but no element data follows.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1000000, false), Exception);
+}
+
+static void testReadMapRejectsOversizedCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"map\",\"values\":\"long\"}");
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1000000, false), Exception);
+}
+
+static void testReadArrayOfNullNotFalselyRejected() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // 100,000 nulls (zero bytes each) is legitimate and must decode.
+    GenericDatum datum = decodeCollectionHeader(s, 100000, true);
+    BOOST_CHECK_EQUAL(datum.value<GenericArray>().value().size(), 100000u);
+}
+
+// A deeply but acyclically nested record whose only leaf is null encodes to
+// zero bytes, so the per-element minimum must be 0 and a large array of such
+// records must not be falsely rejected. This exercises the recursion depth
+// guard in minBytesPerElement(), which must yield a conservative lower bound
+// (0) rather than over-estimating for a legitimately deep schema.
+static void testReadArrayOfDeeplyNestedNullNotFalselyRejected() {
+    // Build ~70 nested records: R0 { null f; }, R1 { R0 f; }, ... The nesting
+    // exceeds the depth guard, yet every leaf is null so the true minimum is 0.
+    std::string schema = "\"null\"";
+    for (int i = 0; i < 70; ++i) {
+        schema = "{\"type\":\"record\",\"name\":\"R" + std::to_string(i) +
+                 "\",\"fields\":[{\"name\":\"f\",\"type\":" + schema + "}]}";
+    }
+    ValidSchema s = compileJsonSchemaFromString(
+        ("{\"type\":\"array\",\"items\":" + schema + "}").c_str());
+    // 100,000 zero-byte elements is legitimate and must decode.
+    GenericDatum datum = decodeCollectionHeader(s, 100000, true);
+    BOOST_CHECK_EQUAL(datum.value<GenericArray>().value().size(), 100000u);
+}
+
+// Calling bytesRemaining() immediately after init(), before any data has been
+// buffered, must be well-defined (the underlying StreamReader must not subtract
+// null buffer pointers) and report the whole stream as available.
+static void testBytesRemainingRightAfterInit() {
+    const uint8_t data[] = {0x06, 'a', 'b', 'c'};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    BOOST_CHECK_EQUAL(d->bytesRemaining(), static_cast<int64_t>(sizeof(data)));
+}
+
+// Zero-byte elements (null, a record with only zero-byte fields) consume no
+// input, so ensureCollectionAvailable cannot bound their count. A huge declared
+// block count of such elements is capped against a configurable limit.
+static GenericDatum decodeLongs(const ValidSchema &s, const std::vector<int64_t> &longs) {
+    std::unique_ptr<OutputStream> os = memoryOutputStream();
+    EncoderPtr e = binaryEncoder();
+    e->init(*os);
+    for (int64_t v : longs) {
+        e->encodeLong(v);
+    }
+    e->flush();
+    InputStreamPtr in = memoryInputStream(*os);
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    GenericDatum datum;
+    GenericReader::read(*d, datum, s);
+    return datum;
+}
+
+static void testReadArrayOfNullRejectsCountAboveDefaultLimit() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // The reported exploit: 200,000,000 nulls rejected by the default limit.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, true), Exception);
+}
+
+static void testReadArrayOfAllNullRecordRejectsHugeCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":"
+        "{\"type\":\"record\",\"name\":\"R\",\"fields\":[{\"name\":\"n\",\"type\":\"null\"}]}}");
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, true), Exception);
+}
+
+static void testReadArrayOfNullRejectsNegativeCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // Negative count (-200M), block byte-size 0, end marker 0: normalized to
+    // 200M and still bounded.
+    BOOST_CHECK_THROW(decodeLongs(s, {-200000000, 0, 0}), Exception);
+}
+
+static void testReadMapOfNullRejectedByAvailableBytes() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"map\",\"values\":\"null\"}");
+    // Each map entry carries a >= 1 byte key, so a huge map<null> is bounded by
+    // the bytes-remaining check.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, false), Exception);
+}
+
+static void testReadArrayOfNullRespectsConfiguredLimit() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    setenv("AVRO_MAX_COLLECTION_ITEMS", "1000", 1);

Review Comment:
   Fixed in e6a35fa802: replaced with the MSVC-portable RAII ScopedCollectionLimit (guards _WIN32 -> _putenv_s).



##########
lang/c++/test/AvailableBytesTests.cc:
##########
@@ -0,0 +1,280 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// A bytes/string value is encoded as a length prefix followed by that many
+// bytes of data. A malicious or truncated input can declare a huge length with
+// little or no actual data, which would otherwise trigger a correspondingly
+// huge allocation before the shortfall is noticed. When the input stream can
+// report how many bytes remain (a memory-backed stream), the declared length
+// must be rejected before allocating for it.
+
+#include <cstdint>
+#include <cstdlib>
+#include <memory>
+#include <string>
+#include <vector>
+
+#include <boost/test/included/unit_test.hpp>
+
+#include "Compiler.hh"
+#include "Decoder.hh"
+#include "Encoder.hh"
+#include "Exception.hh"
+#include "Generic.hh"
+#include "Stream.hh"
+#include "ValidSchema.hh"
+
+namespace avro {
+
+// Reading a bytes value whose declared length far exceeds the tiny backing
+// buffer must throw instead of attempting a huge allocation.
+static void testDecodeBytesRejectsOversizedLength() {
+    // 0xFE 0x01 is the zig-zag long 127; the buffer carries no data after it.
+    const uint8_t data[] = {0xFE, 0x01};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::vector<uint8_t> value;
+    BOOST_CHECK_THROW(d->decodeBytes(value), Exception);
+}
+
+static void testDecodeStringRejectsOversizedLength() {
+    const uint8_t data[] = {0xFE, 0x01};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::string value;
+    BOOST_CHECK_THROW(d->decodeString(value), Exception);
+}
+
+// A well-formed value whose declared length fits the buffer still decodes.
+static void testDecodeStringWithinLimitStillReads() {
+    // length 3 (zig-zag 6 -> 0x06) followed by "abc".
+    const uint8_t data[] = {0x06, 'a', 'b', 'c'};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::string value;
+    d->decodeString(value);
+    BOOST_CHECK_EQUAL(value, std::string("abc"));
+}
+
+static void testDecodeBytesWithinLimitStillReads() {
+    const uint8_t data[] = {0x06, 0x01, 0x02, 0x03};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::vector<uint8_t> value;
+    d->decodeBytes(value);
+    BOOST_CHECK_EQUAL(value.size(), 3u);
+    BOOST_CHECK_EQUAL(value[0], 1);
+    BOOST_CHECK_EQUAL(value[2], 3);
+}
+
+// An array/map block declares an element count; a malicious or truncated input
+// can declare far more elements than the remaining bytes could hold. The count
+// is validated against the bytes remaining before resizing, using the minimum
+// on-wire size of the element schema (so 0-byte elements like null are not
+// falsely rejected).
+static GenericDatum decodeCollectionHeader(const ValidSchema &s, int64_t blockCount,
+                                           bool addEndMarker) {
+    // Keep the output stream alive for the whole decode: memoryInputStream
+    // references the output stream's buffer rather than copying it.
+    std::unique_ptr<OutputStream> os = memoryOutputStream();
+    EncoderPtr e = binaryEncoder();
+    e->init(*os);
+    e->encodeLong(blockCount);
+    if (addEndMarker) {
+        e->encodeLong(0);
+    }
+    e->flush();
+
+    InputStreamPtr in = memoryInputStream(*os);
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    GenericDatum datum;
+    GenericReader::read(*d, datum, s);
+    return datum;
+}
+
+static void testReadArrayRejectsOversizedCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"long\"}");
+    // 1,000,000 long elements declared, but no element data follows.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1000000, false), Exception);
+}
+
+static void testReadMapRejectsOversizedCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"map\",\"values\":\"long\"}");
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1000000, false), Exception);
+}
+
+static void testReadArrayOfNullNotFalselyRejected() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // 100,000 nulls (zero bytes each) is legitimate and must decode.
+    GenericDatum datum = decodeCollectionHeader(s, 100000, true);
+    BOOST_CHECK_EQUAL(datum.value<GenericArray>().value().size(), 100000u);
+}
+
+// A deeply but acyclically nested record whose only leaf is null encodes to
+// zero bytes, so the per-element minimum must be 0 and a large array of such
+// records must not be falsely rejected. This exercises the recursion depth
+// guard in minBytesPerElement(), which must yield a conservative lower bound
+// (0) rather than over-estimating for a legitimately deep schema.
+static void testReadArrayOfDeeplyNestedNullNotFalselyRejected() {
+    // Build ~70 nested records: R0 { null f; }, R1 { R0 f; }, ... The nesting
+    // exceeds the depth guard, yet every leaf is null so the true minimum is 0.
+    std::string schema = "\"null\"";
+    for (int i = 0; i < 70; ++i) {
+        schema = "{\"type\":\"record\",\"name\":\"R" + std::to_string(i) +
+                 "\",\"fields\":[{\"name\":\"f\",\"type\":" + schema + "}]}";
+    }
+    ValidSchema s = compileJsonSchemaFromString(
+        ("{\"type\":\"array\",\"items\":" + schema + "}").c_str());
+    // 100,000 zero-byte elements is legitimate and must decode.
+    GenericDatum datum = decodeCollectionHeader(s, 100000, true);
+    BOOST_CHECK_EQUAL(datum.value<GenericArray>().value().size(), 100000u);
+}
+
+// Calling bytesRemaining() immediately after init(), before any data has been
+// buffered, must be well-defined (the underlying StreamReader must not subtract
+// null buffer pointers) and report the whole stream as available.
+static void testBytesRemainingRightAfterInit() {
+    const uint8_t data[] = {0x06, 'a', 'b', 'c'};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    BOOST_CHECK_EQUAL(d->bytesRemaining(), static_cast<int64_t>(sizeof(data)));
+}
+
+// Zero-byte elements (null, a record with only zero-byte fields) consume no
+// input, so ensureCollectionAvailable cannot bound their count. A huge declared
+// block count of such elements is capped against a configurable limit.
+static GenericDatum decodeLongs(const ValidSchema &s, const std::vector<int64_t> &longs) {
+    std::unique_ptr<OutputStream> os = memoryOutputStream();
+    EncoderPtr e = binaryEncoder();
+    e->init(*os);
+    for (int64_t v : longs) {
+        e->encodeLong(v);
+    }
+    e->flush();
+    InputStreamPtr in = memoryInputStream(*os);
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    GenericDatum datum;
+    GenericReader::read(*d, datum, s);
+    return datum;
+}
+
+static void testReadArrayOfNullRejectsCountAboveDefaultLimit() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // The reported exploit: 200,000,000 nulls rejected by the default limit.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, true), Exception);
+}
+
+static void testReadArrayOfAllNullRecordRejectsHugeCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":"
+        "{\"type\":\"record\",\"name\":\"R\",\"fields\":[{\"name\":\"n\",\"type\":\"null\"}]}}");
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, true), Exception);
+}
+
+static void testReadArrayOfNullRejectsNegativeCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // Negative count (-200M), block byte-size 0, end marker 0: normalized to
+    // 200M and still bounded.
+    BOOST_CHECK_THROW(decodeLongs(s, {-200000000, 0, 0}), Exception);
+}
+
+static void testReadMapOfNullRejectedByAvailableBytes() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"map\",\"values\":\"null\"}");
+    // Each map entry carries a >= 1 byte key, so a huge map<null> is bounded by
+    // the bytes-remaining check.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, false), Exception);
+}
+
+static void testReadArrayOfNullRespectsConfiguredLimit() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    setenv("AVRO_MAX_COLLECTION_ITEMS", "1000", 1);
+    // Within the limit decodes; over the limit and cumulative are rejected.
+    GenericDatum ok = decodeCollectionHeader(s, 1000, true);
+    BOOST_CHECK_EQUAL(ok.value<GenericArray>().value().size(), 1000u);
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1001, true), Exception);
+    BOOST_CHECK_THROW(decodeLongs(s, {600, 600, 0}), Exception);
+    unsetenv("AVRO_MAX_COLLECTION_ITEMS");

Review Comment:
   Fixed in e6a35fa802: the RAII guard's destructor unsets via _putenv_s(name, "") on _WIN32, and restores a pre-existing value otherwise.



##########
lang/c++/test/AvailableBytesTests.cc:
##########
@@ -0,0 +1,280 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// A bytes/string value is encoded as a length prefix followed by that many
+// bytes of data. A malicious or truncated input can declare a huge length with
+// little or no actual data, which would otherwise trigger a correspondingly
+// huge allocation before the shortfall is noticed. When the input stream can
+// report how many bytes remain (a memory-backed stream), the declared length
+// must be rejected before allocating for it.
+
+#include <cstdint>
+#include <cstdlib>
+#include <memory>
+#include <string>
+#include <vector>
+
+#include <boost/test/included/unit_test.hpp>
+
+#include "Compiler.hh"
+#include "Decoder.hh"
+#include "Encoder.hh"
+#include "Exception.hh"
+#include "Generic.hh"
+#include "Stream.hh"
+#include "ValidSchema.hh"
+
+namespace avro {
+
+// Reading a bytes value whose declared length far exceeds the tiny backing
+// buffer must throw instead of attempting a huge allocation.
+static void testDecodeBytesRejectsOversizedLength() {
+    // 0xFE 0x01 is the zig-zag long 127; the buffer carries no data after it.
+    const uint8_t data[] = {0xFE, 0x01};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::vector<uint8_t> value;
+    BOOST_CHECK_THROW(d->decodeBytes(value), Exception);
+}
+
+static void testDecodeStringRejectsOversizedLength() {
+    const uint8_t data[] = {0xFE, 0x01};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::string value;
+    BOOST_CHECK_THROW(d->decodeString(value), Exception);
+}
+
+// A well-formed value whose declared length fits the buffer still decodes.
+static void testDecodeStringWithinLimitStillReads() {
+    // length 3 (zig-zag 6 -> 0x06) followed by "abc".
+    const uint8_t data[] = {0x06, 'a', 'b', 'c'};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::string value;
+    d->decodeString(value);
+    BOOST_CHECK_EQUAL(value, std::string("abc"));
+}
+
+static void testDecodeBytesWithinLimitStillReads() {
+    const uint8_t data[] = {0x06, 0x01, 0x02, 0x03};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::vector<uint8_t> value;
+    d->decodeBytes(value);
+    BOOST_CHECK_EQUAL(value.size(), 3u);
+    BOOST_CHECK_EQUAL(value[0], 1);
+    BOOST_CHECK_EQUAL(value[2], 3);
+}
+
+// An array/map block declares an element count; a malicious or truncated input
+// can declare far more elements than the remaining bytes could hold. The count
+// is validated against the bytes remaining before resizing, using the minimum
+// on-wire size of the element schema (so 0-byte elements like null are not
+// falsely rejected).
+static GenericDatum decodeCollectionHeader(const ValidSchema &s, int64_t blockCount,
+                                           bool addEndMarker) {
+    // Keep the output stream alive for the whole decode: memoryInputStream
+    // references the output stream's buffer rather than copying it.
+    std::unique_ptr<OutputStream> os = memoryOutputStream();
+    EncoderPtr e = binaryEncoder();
+    e->init(*os);
+    e->encodeLong(blockCount);
+    if (addEndMarker) {
+        e->encodeLong(0);
+    }
+    e->flush();
+
+    InputStreamPtr in = memoryInputStream(*os);
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    GenericDatum datum;
+    GenericReader::read(*d, datum, s);
+    return datum;
+}
+
+static void testReadArrayRejectsOversizedCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"long\"}");
+    // 1,000,000 long elements declared, but no element data follows.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1000000, false), Exception);
+}
+
+static void testReadMapRejectsOversizedCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"map\",\"values\":\"long\"}");
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1000000, false), Exception);
+}
+
+static void testReadArrayOfNullNotFalselyRejected() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // 100,000 nulls (zero bytes each) is legitimate and must decode.
+    GenericDatum datum = decodeCollectionHeader(s, 100000, true);
+    BOOST_CHECK_EQUAL(datum.value<GenericArray>().value().size(), 100000u);
+}
+
+// A deeply but acyclically nested record whose only leaf is null encodes to
+// zero bytes, so the per-element minimum must be 0 and a large array of such
+// records must not be falsely rejected. This exercises the recursion depth
+// guard in minBytesPerElement(), which must yield a conservative lower bound
+// (0) rather than over-estimating for a legitimately deep schema.
+static void testReadArrayOfDeeplyNestedNullNotFalselyRejected() {
+    // Build ~70 nested records: R0 { null f; }, R1 { R0 f; }, ... The nesting
+    // exceeds the depth guard, yet every leaf is null so the true minimum is 0.
+    std::string schema = "\"null\"";
+    for (int i = 0; i < 70; ++i) {
+        schema = "{\"type\":\"record\",\"name\":\"R" + std::to_string(i) +
+                 "\",\"fields\":[{\"name\":\"f\",\"type\":" + schema + "}]}";
+    }
+    ValidSchema s = compileJsonSchemaFromString(
+        ("{\"type\":\"array\",\"items\":" + schema + "}").c_str());
+    // 100,000 zero-byte elements is legitimate and must decode.
+    GenericDatum datum = decodeCollectionHeader(s, 100000, true);
+    BOOST_CHECK_EQUAL(datum.value<GenericArray>().value().size(), 100000u);
+}
+
+// Calling bytesRemaining() immediately after init(), before any data has been
+// buffered, must be well-defined (the underlying StreamReader must not subtract
+// null buffer pointers) and report the whole stream as available.
+static void testBytesRemainingRightAfterInit() {
+    const uint8_t data[] = {0x06, 'a', 'b', 'c'};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    BOOST_CHECK_EQUAL(d->bytesRemaining(), static_cast<int64_t>(sizeof(data)));
+}
+
+// Zero-byte elements (null, a record with only zero-byte fields) consume no
+// input, so ensureCollectionAvailable cannot bound their count. A huge declared
+// block count of such elements is capped against a configurable limit.
+static GenericDatum decodeLongs(const ValidSchema &s, const std::vector<int64_t> &longs) {
+    std::unique_ptr<OutputStream> os = memoryOutputStream();
+    EncoderPtr e = binaryEncoder();
+    e->init(*os);
+    for (int64_t v : longs) {
+        e->encodeLong(v);
+    }
+    e->flush();
+    InputStreamPtr in = memoryInputStream(*os);
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    GenericDatum datum;
+    GenericReader::read(*d, datum, s);
+    return datum;
+}
+
+static void testReadArrayOfNullRejectsCountAboveDefaultLimit() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // The reported exploit: 200,000,000 nulls rejected by the default limit.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, true), Exception);
+}
+
+static void testReadArrayOfAllNullRecordRejectsHugeCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":"
+        "{\"type\":\"record\",\"name\":\"R\",\"fields\":[{\"name\":\"n\",\"type\":\"null\"}]}}");
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, true), Exception);
+}
+
+static void testReadArrayOfNullRejectsNegativeCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // Negative count (-200M), block byte-size 0, end marker 0: normalized to
+    // 200M and still bounded.
+    BOOST_CHECK_THROW(decodeLongs(s, {-200000000, 0, 0}), Exception);
+}
+
+static void testReadMapOfNullRejectedByAvailableBytes() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"map\",\"values\":\"null\"}");
+    // Each map entry carries a >= 1 byte key, so a huge map<null> is bounded by
+    // the bytes-remaining check.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, false), Exception);
+}
+
+static void testReadArrayOfNullRespectsConfiguredLimit() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    setenv("AVRO_MAX_COLLECTION_ITEMS", "1000", 1);
+    // Within the limit decodes; over the limit and cumulative are rejected.
+    GenericDatum ok = decodeCollectionHeader(s, 1000, true);
+    BOOST_CHECK_EQUAL(ok.value<GenericArray>().value().size(), 1000u);
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1001, true), Exception);
+    BOOST_CHECK_THROW(decodeLongs(s, {600, 600, 0}), Exception);
+    unsetenv("AVRO_MAX_COLLECTION_ITEMS");
+}
+
+// A backed non-zero-byte array that passes the bytes check is still bounded by
+// the structural cap (exercised with a lowered limit).
+static void testReadArrayOfLongRejectedByStructuralCap() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"long\"}");
+    setenv("AVRO_MAX_COLLECTION_ITEMS", "5", 1);

Review Comment:
   Fixed in e6a35fa802 via the RAII ScopedCollectionLimit (portable set).



##########
lang/c++/test/AvailableBytesTests.cc:
##########
@@ -0,0 +1,280 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// A bytes/string value is encoded as a length prefix followed by that many
+// bytes of data. A malicious or truncated input can declare a huge length with
+// little or no actual data, which would otherwise trigger a correspondingly
+// huge allocation before the shortfall is noticed. When the input stream can
+// report how many bytes remain (a memory-backed stream), the declared length
+// must be rejected before allocating for it.
+
+#include <cstdint>
+#include <cstdlib>
+#include <memory>
+#include <string>
+#include <vector>
+
+#include <boost/test/included/unit_test.hpp>
+
+#include "Compiler.hh"
+#include "Decoder.hh"
+#include "Encoder.hh"
+#include "Exception.hh"
+#include "Generic.hh"
+#include "Stream.hh"
+#include "ValidSchema.hh"
+
+namespace avro {
+
+// Reading a bytes value whose declared length far exceeds the tiny backing
+// buffer must throw instead of attempting a huge allocation.
+static void testDecodeBytesRejectsOversizedLength() {
+    // 0xFE 0x01 is the zig-zag long 127; the buffer carries no data after it.
+    const uint8_t data[] = {0xFE, 0x01};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::vector<uint8_t> value;
+    BOOST_CHECK_THROW(d->decodeBytes(value), Exception);
+}
+
+static void testDecodeStringRejectsOversizedLength() {
+    const uint8_t data[] = {0xFE, 0x01};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::string value;
+    BOOST_CHECK_THROW(d->decodeString(value), Exception);
+}
+
+// A well-formed value whose declared length fits the buffer still decodes.
+static void testDecodeStringWithinLimitStillReads() {
+    // length 3 (zig-zag 6 -> 0x06) followed by "abc".
+    const uint8_t data[] = {0x06, 'a', 'b', 'c'};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::string value;
+    d->decodeString(value);
+    BOOST_CHECK_EQUAL(value, std::string("abc"));
+}
+
+static void testDecodeBytesWithinLimitStillReads() {
+    const uint8_t data[] = {0x06, 0x01, 0x02, 0x03};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::vector<uint8_t> value;
+    d->decodeBytes(value);
+    BOOST_CHECK_EQUAL(value.size(), 3u);
+    BOOST_CHECK_EQUAL(value[0], 1);
+    BOOST_CHECK_EQUAL(value[2], 3);
+}
+
+// An array/map block declares an element count; a malicious or truncated input
+// can declare far more elements than the remaining bytes could hold. The count
+// is validated against the bytes remaining before resizing, using the minimum
+// on-wire size of the element schema (so 0-byte elements like null are not
+// falsely rejected).
+static GenericDatum decodeCollectionHeader(const ValidSchema &s, int64_t blockCount,
+                                           bool addEndMarker) {
+    // Keep the output stream alive for the whole decode: memoryInputStream
+    // references the output stream's buffer rather than copying it.
+    std::unique_ptr<OutputStream> os = memoryOutputStream();
+    EncoderPtr e = binaryEncoder();
+    e->init(*os);
+    e->encodeLong(blockCount);
+    if (addEndMarker) {
+        e->encodeLong(0);
+    }
+    e->flush();
+
+    InputStreamPtr in = memoryInputStream(*os);
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    GenericDatum datum;
+    GenericReader::read(*d, datum, s);
+    return datum;
+}
+
+static void testReadArrayRejectsOversizedCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"long\"}");
+    // 1,000,000 long elements declared, but no element data follows.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1000000, false), Exception);
+}
+
+static void testReadMapRejectsOversizedCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"map\",\"values\":\"long\"}");
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1000000, false), Exception);
+}
+
+static void testReadArrayOfNullNotFalselyRejected() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // 100,000 nulls (zero bytes each) is legitimate and must decode.
+    GenericDatum datum = decodeCollectionHeader(s, 100000, true);
+    BOOST_CHECK_EQUAL(datum.value<GenericArray>().value().size(), 100000u);
+}
+
+// A deeply but acyclically nested record whose only leaf is null encodes to
+// zero bytes, so the per-element minimum must be 0 and a large array of such
+// records must not be falsely rejected. This exercises the recursion depth
+// guard in minBytesPerElement(), which must yield a conservative lower bound
+// (0) rather than over-estimating for a legitimately deep schema.
+static void testReadArrayOfDeeplyNestedNullNotFalselyRejected() {
+    // Build ~70 nested records: R0 { null f; }, R1 { R0 f; }, ... The nesting
+    // exceeds the depth guard, yet every leaf is null so the true minimum is 0.
+    std::string schema = "\"null\"";
+    for (int i = 0; i < 70; ++i) {
+        schema = "{\"type\":\"record\",\"name\":\"R" + std::to_string(i) +
+                 "\",\"fields\":[{\"name\":\"f\",\"type\":" + schema + "}]}";
+    }
+    ValidSchema s = compileJsonSchemaFromString(
+        ("{\"type\":\"array\",\"items\":" + schema + "}").c_str());
+    // 100,000 zero-byte elements is legitimate and must decode.
+    GenericDatum datum = decodeCollectionHeader(s, 100000, true);
+    BOOST_CHECK_EQUAL(datum.value<GenericArray>().value().size(), 100000u);
+}
+
+// Calling bytesRemaining() immediately after init(), before any data has been
+// buffered, must be well-defined (the underlying StreamReader must not subtract
+// null buffer pointers) and report the whole stream as available.
+static void testBytesRemainingRightAfterInit() {
+    const uint8_t data[] = {0x06, 'a', 'b', 'c'};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    BOOST_CHECK_EQUAL(d->bytesRemaining(), static_cast<int64_t>(sizeof(data)));
+}
+
+// Zero-byte elements (null, a record with only zero-byte fields) consume no
+// input, so ensureCollectionAvailable cannot bound their count. A huge declared
+// block count of such elements is capped against a configurable limit.
+static GenericDatum decodeLongs(const ValidSchema &s, const std::vector<int64_t> &longs) {
+    std::unique_ptr<OutputStream> os = memoryOutputStream();
+    EncoderPtr e = binaryEncoder();
+    e->init(*os);
+    for (int64_t v : longs) {
+        e->encodeLong(v);
+    }
+    e->flush();
+    InputStreamPtr in = memoryInputStream(*os);
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    GenericDatum datum;
+    GenericReader::read(*d, datum, s);
+    return datum;
+}
+
+static void testReadArrayOfNullRejectsCountAboveDefaultLimit() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // The reported exploit: 200,000,000 nulls rejected by the default limit.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, true), Exception);
+}
+
+static void testReadArrayOfAllNullRecordRejectsHugeCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":"
+        "{\"type\":\"record\",\"name\":\"R\",\"fields\":[{\"name\":\"n\",\"type\":\"null\"}]}}");
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, true), Exception);
+}
+
+static void testReadArrayOfNullRejectsNegativeCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // Negative count (-200M), block byte-size 0, end marker 0: normalized to
+    // 200M and still bounded.
+    BOOST_CHECK_THROW(decodeLongs(s, {-200000000, 0, 0}), Exception);
+}
+
+static void testReadMapOfNullRejectedByAvailableBytes() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"map\",\"values\":\"null\"}");
+    // Each map entry carries a >= 1 byte key, so a huge map<null> is bounded by
+    // the bytes-remaining check.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, false), Exception);
+}
+
+static void testReadArrayOfNullRespectsConfiguredLimit() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    setenv("AVRO_MAX_COLLECTION_ITEMS", "1000", 1);
+    // Within the limit decodes; over the limit and cumulative are rejected.
+    GenericDatum ok = decodeCollectionHeader(s, 1000, true);
+    BOOST_CHECK_EQUAL(ok.value<GenericArray>().value().size(), 1000u);
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1001, true), Exception);
+    BOOST_CHECK_THROW(decodeLongs(s, {600, 600, 0}), Exception);
+    unsetenv("AVRO_MAX_COLLECTION_ITEMS");
+}
+
+// A backed non-zero-byte array that passes the bytes check is still bounded by
+// the structural cap (exercised with a lowered limit).
+static void testReadArrayOfLongRejectedByStructuralCap() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"long\"}");
+    setenv("AVRO_MAX_COLLECTION_ITEMS", "5", 1);
+    // 10 real longs: block count 10, ten 1-byte longs, end marker.
+    std::vector<int64_t> longs = {10, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
+    BOOST_CHECK_THROW(decodeLongs(s, longs), Exception);
+    unsetenv("AVRO_MAX_COLLECTION_ITEMS");

Review Comment:
   Fixed in e6a35fa802 via the RAII ScopedCollectionLimit (portable unset/restore).



##########
lang/c++/test/AvailableBytesTests.cc:
##########
@@ -0,0 +1,280 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// A bytes/string value is encoded as a length prefix followed by that many
+// bytes of data. A malicious or truncated input can declare a huge length with
+// little or no actual data, which would otherwise trigger a correspondingly
+// huge allocation before the shortfall is noticed. When the input stream can
+// report how many bytes remain (a memory-backed stream), the declared length
+// must be rejected before allocating for it.
+
+#include <cstdint>
+#include <cstdlib>
+#include <memory>
+#include <string>
+#include <vector>
+
+#include <boost/test/included/unit_test.hpp>
+
+#include "Compiler.hh"
+#include "Decoder.hh"
+#include "Encoder.hh"
+#include "Exception.hh"
+#include "Generic.hh"
+#include "Stream.hh"
+#include "ValidSchema.hh"
+
+namespace avro {
+
+// Reading a bytes value whose declared length far exceeds the tiny backing
+// buffer must throw instead of attempting a huge allocation.
+static void testDecodeBytesRejectsOversizedLength() {
+    // 0xFE 0x01 is the zig-zag long 127; the buffer carries no data after it.
+    const uint8_t data[] = {0xFE, 0x01};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::vector<uint8_t> value;
+    BOOST_CHECK_THROW(d->decodeBytes(value), Exception);
+}
+
+static void testDecodeStringRejectsOversizedLength() {
+    const uint8_t data[] = {0xFE, 0x01};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::string value;
+    BOOST_CHECK_THROW(d->decodeString(value), Exception);
+}
+
+// A well-formed value whose declared length fits the buffer still decodes.
+static void testDecodeStringWithinLimitStillReads() {
+    // length 3 (zig-zag 6 -> 0x06) followed by "abc".
+    const uint8_t data[] = {0x06, 'a', 'b', 'c'};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::string value;
+    d->decodeString(value);
+    BOOST_CHECK_EQUAL(value, std::string("abc"));
+}
+
+static void testDecodeBytesWithinLimitStillReads() {
+    const uint8_t data[] = {0x06, 0x01, 0x02, 0x03};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::vector<uint8_t> value;
+    d->decodeBytes(value);
+    BOOST_CHECK_EQUAL(value.size(), 3u);
+    BOOST_CHECK_EQUAL(value[0], 1);
+    BOOST_CHECK_EQUAL(value[2], 3);
+}
+
+// An array/map block declares an element count; a malicious or truncated input
+// can declare far more elements than the remaining bytes could hold. The count
+// is validated against the bytes remaining before resizing, using the minimum
+// on-wire size of the element schema (so 0-byte elements like null are not
+// falsely rejected).
+static GenericDatum decodeCollectionHeader(const ValidSchema &s, int64_t blockCount,
+                                           bool addEndMarker) {
+    // Keep the output stream alive for the whole decode: memoryInputStream
+    // references the output stream's buffer rather than copying it.
+    std::unique_ptr<OutputStream> os = memoryOutputStream();
+    EncoderPtr e = binaryEncoder();
+    e->init(*os);
+    e->encodeLong(blockCount);
+    if (addEndMarker) {
+        e->encodeLong(0);
+    }
+    e->flush();
+
+    InputStreamPtr in = memoryInputStream(*os);
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    GenericDatum datum;
+    GenericReader::read(*d, datum, s);
+    return datum;
+}
+
+static void testReadArrayRejectsOversizedCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"long\"}");
+    // 1,000,000 long elements declared, but no element data follows.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1000000, false), Exception);
+}
+
+static void testReadMapRejectsOversizedCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"map\",\"values\":\"long\"}");
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1000000, false), Exception);
+}
+
+static void testReadArrayOfNullNotFalselyRejected() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // 100,000 nulls (zero bytes each) is legitimate and must decode.
+    GenericDatum datum = decodeCollectionHeader(s, 100000, true);
+    BOOST_CHECK_EQUAL(datum.value<GenericArray>().value().size(), 100000u);
+}
+
+// A deeply but acyclically nested record whose only leaf is null encodes to
+// zero bytes, so the per-element minimum must be 0 and a large array of such
+// records must not be falsely rejected. This exercises the recursion depth
+// guard in minBytesPerElement(), which must yield a conservative lower bound
+// (0) rather than over-estimating for a legitimately deep schema.
+static void testReadArrayOfDeeplyNestedNullNotFalselyRejected() {
+    // Build ~70 nested records: R0 { null f; }, R1 { R0 f; }, ... The nesting
+    // exceeds the depth guard, yet every leaf is null so the true minimum is 0.
+    std::string schema = "\"null\"";
+    for (int i = 0; i < 70; ++i) {
+        schema = "{\"type\":\"record\",\"name\":\"R" + std::to_string(i) +
+                 "\",\"fields\":[{\"name\":\"f\",\"type\":" + schema + "}]}";
+    }
+    ValidSchema s = compileJsonSchemaFromString(
+        ("{\"type\":\"array\",\"items\":" + schema + "}").c_str());
+    // 100,000 zero-byte elements is legitimate and must decode.
+    GenericDatum datum = decodeCollectionHeader(s, 100000, true);
+    BOOST_CHECK_EQUAL(datum.value<GenericArray>().value().size(), 100000u);
+}
+
+// Calling bytesRemaining() immediately after init(), before any data has been
+// buffered, must be well-defined (the underlying StreamReader must not subtract
+// null buffer pointers) and report the whole stream as available.
+static void testBytesRemainingRightAfterInit() {
+    const uint8_t data[] = {0x06, 'a', 'b', 'c'};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    BOOST_CHECK_EQUAL(d->bytesRemaining(), static_cast<int64_t>(sizeof(data)));
+}
+
+// Zero-byte elements (null, a record with only zero-byte fields) consume no
+// input, so ensureCollectionAvailable cannot bound their count. A huge declared
+// block count of such elements is capped against a configurable limit.
+static GenericDatum decodeLongs(const ValidSchema &s, const std::vector<int64_t> &longs) {
+    std::unique_ptr<OutputStream> os = memoryOutputStream();
+    EncoderPtr e = binaryEncoder();
+    e->init(*os);
+    for (int64_t v : longs) {
+        e->encodeLong(v);
+    }
+    e->flush();
+    InputStreamPtr in = memoryInputStream(*os);
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    GenericDatum datum;
+    GenericReader::read(*d, datum, s);
+    return datum;
+}
+
+static void testReadArrayOfNullRejectsCountAboveDefaultLimit() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // The reported exploit: 200,000,000 nulls rejected by the default limit.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, true), Exception);
+}
+
+static void testReadArrayOfAllNullRecordRejectsHugeCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":"
+        "{\"type\":\"record\",\"name\":\"R\",\"fields\":[{\"name\":\"n\",\"type\":\"null\"}]}}");
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, true), Exception);
+}
+
+static void testReadArrayOfNullRejectsNegativeCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // Negative count (-200M), block byte-size 0, end marker 0: normalized to
+    // 200M and still bounded.
+    BOOST_CHECK_THROW(decodeLongs(s, {-200000000, 0, 0}), Exception);
+}
+
+static void testReadMapOfNullRejectedByAvailableBytes() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"map\",\"values\":\"null\"}");
+    // Each map entry carries a >= 1 byte key, so a huge map<null> is bounded by
+    // the bytes-remaining check.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, false), Exception);
+}
+
+static void testReadArrayOfNullRespectsConfiguredLimit() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    setenv("AVRO_MAX_COLLECTION_ITEMS", "1000", 1);
+    // Within the limit decodes; over the limit and cumulative are rejected.
+    GenericDatum ok = decodeCollectionHeader(s, 1000, true);
+    BOOST_CHECK_EQUAL(ok.value<GenericArray>().value().size(), 1000u);
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1001, true), Exception);
+    BOOST_CHECK_THROW(decodeLongs(s, {600, 600, 0}), Exception);
+    unsetenv("AVRO_MAX_COLLECTION_ITEMS");
+}
+
+// A backed non-zero-byte array that passes the bytes check is still bounded by
+// the structural cap (exercised with a lowered limit).
+static void testReadArrayOfLongRejectedByStructuralCap() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"long\"}");
+    setenv("AVRO_MAX_COLLECTION_ITEMS", "5", 1);
+    // 10 real longs: block count 10, ten 1-byte longs, end marker.
+    std::vector<int64_t> longs = {10, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
+    BOOST_CHECK_THROW(decodeLongs(s, longs), Exception);
+    unsetenv("AVRO_MAX_COLLECTION_ITEMS");
+}
+
+// Skipping a huge array (via the decoder's skipArray) is bounded by the
+// structural cap.
+static void testSkipArrayRejectsHugeCount() {
+    setenv("AVRO_MAX_COLLECTION_ITEMS", "1000", 1);

Review Comment:
   Fixed in e6a35fa802 via the RAII ScopedCollectionLimit (portable set).



##########
lang/c++/test/AvailableBytesTests.cc:
##########
@@ -0,0 +1,280 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// A bytes/string value is encoded as a length prefix followed by that many
+// bytes of data. A malicious or truncated input can declare a huge length with
+// little or no actual data, which would otherwise trigger a correspondingly
+// huge allocation before the shortfall is noticed. When the input stream can
+// report how many bytes remain (a memory-backed stream), the declared length
+// must be rejected before allocating for it.
+
+#include <cstdint>
+#include <cstdlib>
+#include <memory>
+#include <string>
+#include <vector>
+
+#include <boost/test/included/unit_test.hpp>
+
+#include "Compiler.hh"
+#include "Decoder.hh"
+#include "Encoder.hh"
+#include "Exception.hh"
+#include "Generic.hh"
+#include "Stream.hh"
+#include "ValidSchema.hh"
+
+namespace avro {
+
+// Reading a bytes value whose declared length far exceeds the tiny backing
+// buffer must throw instead of attempting a huge allocation.
+static void testDecodeBytesRejectsOversizedLength() {
+    // 0xFE 0x01 is the zig-zag long 127; the buffer carries no data after it.
+    const uint8_t data[] = {0xFE, 0x01};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::vector<uint8_t> value;
+    BOOST_CHECK_THROW(d->decodeBytes(value), Exception);
+}
+
+static void testDecodeStringRejectsOversizedLength() {
+    const uint8_t data[] = {0xFE, 0x01};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::string value;
+    BOOST_CHECK_THROW(d->decodeString(value), Exception);
+}
+
+// A well-formed value whose declared length fits the buffer still decodes.
+static void testDecodeStringWithinLimitStillReads() {
+    // length 3 (zig-zag 6 -> 0x06) followed by "abc".
+    const uint8_t data[] = {0x06, 'a', 'b', 'c'};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::string value;
+    d->decodeString(value);
+    BOOST_CHECK_EQUAL(value, std::string("abc"));
+}
+
+static void testDecodeBytesWithinLimitStillReads() {
+    const uint8_t data[] = {0x06, 0x01, 0x02, 0x03};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    std::vector<uint8_t> value;
+    d->decodeBytes(value);
+    BOOST_CHECK_EQUAL(value.size(), 3u);
+    BOOST_CHECK_EQUAL(value[0], 1);
+    BOOST_CHECK_EQUAL(value[2], 3);
+}
+
+// An array/map block declares an element count; a malicious or truncated input
+// can declare far more elements than the remaining bytes could hold. The count
+// is validated against the bytes remaining before resizing, using the minimum
+// on-wire size of the element schema (so 0-byte elements like null are not
+// falsely rejected).
+static GenericDatum decodeCollectionHeader(const ValidSchema &s, int64_t blockCount,
+                                           bool addEndMarker) {
+    // Keep the output stream alive for the whole decode: memoryInputStream
+    // references the output stream's buffer rather than copying it.
+    std::unique_ptr<OutputStream> os = memoryOutputStream();
+    EncoderPtr e = binaryEncoder();
+    e->init(*os);
+    e->encodeLong(blockCount);
+    if (addEndMarker) {
+        e->encodeLong(0);
+    }
+    e->flush();
+
+    InputStreamPtr in = memoryInputStream(*os);
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    GenericDatum datum;
+    GenericReader::read(*d, datum, s);
+    return datum;
+}
+
+static void testReadArrayRejectsOversizedCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"long\"}");
+    // 1,000,000 long elements declared, but no element data follows.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1000000, false), Exception);
+}
+
+static void testReadMapRejectsOversizedCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"map\",\"values\":\"long\"}");
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1000000, false), Exception);
+}
+
+static void testReadArrayOfNullNotFalselyRejected() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // 100,000 nulls (zero bytes each) is legitimate and must decode.
+    GenericDatum datum = decodeCollectionHeader(s, 100000, true);
+    BOOST_CHECK_EQUAL(datum.value<GenericArray>().value().size(), 100000u);
+}
+
+// A deeply but acyclically nested record whose only leaf is null encodes to
+// zero bytes, so the per-element minimum must be 0 and a large array of such
+// records must not be falsely rejected. This exercises the recursion depth
+// guard in minBytesPerElement(), which must yield a conservative lower bound
+// (0) rather than over-estimating for a legitimately deep schema.
+static void testReadArrayOfDeeplyNestedNullNotFalselyRejected() {
+    // Build ~70 nested records: R0 { null f; }, R1 { R0 f; }, ... The nesting
+    // exceeds the depth guard, yet every leaf is null so the true minimum is 0.
+    std::string schema = "\"null\"";
+    for (int i = 0; i < 70; ++i) {
+        schema = "{\"type\":\"record\",\"name\":\"R" + std::to_string(i) +
+                 "\",\"fields\":[{\"name\":\"f\",\"type\":" + schema + "}]}";
+    }
+    ValidSchema s = compileJsonSchemaFromString(
+        ("{\"type\":\"array\",\"items\":" + schema + "}").c_str());
+    // 100,000 zero-byte elements is legitimate and must decode.
+    GenericDatum datum = decodeCollectionHeader(s, 100000, true);
+    BOOST_CHECK_EQUAL(datum.value<GenericArray>().value().size(), 100000u);
+}
+
+// Calling bytesRemaining() immediately after init(), before any data has been
+// buffered, must be well-defined (the underlying StreamReader must not subtract
+// null buffer pointers) and report the whole stream as available.
+static void testBytesRemainingRightAfterInit() {
+    const uint8_t data[] = {0x06, 'a', 'b', 'c'};
+    InputStreamPtr in = memoryInputStream(data, sizeof(data));
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    BOOST_CHECK_EQUAL(d->bytesRemaining(), static_cast<int64_t>(sizeof(data)));
+}
+
+// Zero-byte elements (null, a record with only zero-byte fields) consume no
+// input, so ensureCollectionAvailable cannot bound their count. A huge declared
+// block count of such elements is capped against a configurable limit.
+static GenericDatum decodeLongs(const ValidSchema &s, const std::vector<int64_t> &longs) {
+    std::unique_ptr<OutputStream> os = memoryOutputStream();
+    EncoderPtr e = binaryEncoder();
+    e->init(*os);
+    for (int64_t v : longs) {
+        e->encodeLong(v);
+    }
+    e->flush();
+    InputStreamPtr in = memoryInputStream(*os);
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    GenericDatum datum;
+    GenericReader::read(*d, datum, s);
+    return datum;
+}
+
+static void testReadArrayOfNullRejectsCountAboveDefaultLimit() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // The reported exploit: 200,000,000 nulls rejected by the default limit.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, true), Exception);
+}
+
+static void testReadArrayOfAllNullRecordRejectsHugeCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":"
+        "{\"type\":\"record\",\"name\":\"R\",\"fields\":[{\"name\":\"n\",\"type\":\"null\"}]}}");
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, true), Exception);
+}
+
+static void testReadArrayOfNullRejectsNegativeCount() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    // Negative count (-200M), block byte-size 0, end marker 0: normalized to
+    // 200M and still bounded.
+    BOOST_CHECK_THROW(decodeLongs(s, {-200000000, 0, 0}), Exception);
+}
+
+static void testReadMapOfNullRejectedByAvailableBytes() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"map\",\"values\":\"null\"}");
+    // Each map entry carries a >= 1 byte key, so a huge map<null> is bounded by
+    // the bytes-remaining check.
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 200000000, false), Exception);
+}
+
+static void testReadArrayOfNullRespectsConfiguredLimit() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"null\"}");
+    setenv("AVRO_MAX_COLLECTION_ITEMS", "1000", 1);
+    // Within the limit decodes; over the limit and cumulative are rejected.
+    GenericDatum ok = decodeCollectionHeader(s, 1000, true);
+    BOOST_CHECK_EQUAL(ok.value<GenericArray>().value().size(), 1000u);
+    BOOST_CHECK_THROW(decodeCollectionHeader(s, 1001, true), Exception);
+    BOOST_CHECK_THROW(decodeLongs(s, {600, 600, 0}), Exception);
+    unsetenv("AVRO_MAX_COLLECTION_ITEMS");
+}
+
+// A backed non-zero-byte array that passes the bytes check is still bounded by
+// the structural cap (exercised with a lowered limit).
+static void testReadArrayOfLongRejectedByStructuralCap() {
+    ValidSchema s = compileJsonSchemaFromString(
+        "{\"type\":\"array\",\"items\":\"long\"}");
+    setenv("AVRO_MAX_COLLECTION_ITEMS", "5", 1);
+    // 10 real longs: block count 10, ten 1-byte longs, end marker.
+    std::vector<int64_t> longs = {10, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
+    BOOST_CHECK_THROW(decodeLongs(s, longs), Exception);
+    unsetenv("AVRO_MAX_COLLECTION_ITEMS");
+}
+
+// Skipping a huge array (via the decoder's skipArray) is bounded by the
+// structural cap.
+static void testSkipArrayRejectsHugeCount() {
+    setenv("AVRO_MAX_COLLECTION_ITEMS", "1000", 1);
+    std::unique_ptr<OutputStream> os = memoryOutputStream();
+    EncoderPtr e = binaryEncoder();
+    e->init(*os);
+    e->encodeLong(2000); // block count 2000, no data needed (skip throws first)
+    e->flush();
+    InputStreamPtr in = memoryInputStream(*os);
+    DecoderPtr d = binaryDecoder();
+    d->init(*in);
+    BOOST_CHECK_THROW(d->skipArray(), Exception);
+    unsetenv("AVRO_MAX_COLLECTION_ITEMS");

Review Comment:
   Fixed in e6a35fa802 via the RAII ScopedCollectionLimit (portable unset/restore).



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org