CurtHagenlocher commented on code in PR #535:
URL: https://github.com/apache/arrow-dotnet/pull/535#discussion_r4800940856


##########
src/Apache.Arrow.Operations/VariantJson/VariantJsonWriter.cs:
##########
@@ -96,8 +100,13 @@ public static string ToJson(VariantValue value, bool 
indented = false)
         /// <param name="writer">The JSON writer to write to.</param>
         /// <param name="metadata">The variant metadata bytes.</param>
         /// <param name="value">The variant value bytes.</param>
+        /// <exception cref="InvalidDataException">
+        /// Objects and arrays are nested more than 128 deep, or the values of 
an object's
+        /// fields overlap or extend outside the object.
+        /// </exception>
         public static void WriteTo(Utf8JsonWriter writer, byte[] metadata, 
byte[] value)
         {
+            VariantValidator.Validate(value);
             VariantReader reader = new VariantReader(metadata, value);
             WriteReader(writer, reader);
         }

Review Comment:
   `Apache.Arrow.Scalars` grants `InternalsVisibleTo` to 
`Apache.Arrow.Operations` (Properties/AssemblyInfo.cs), so this builds; CI 
passes.



##########
src/Apache.Arrow.Scalars/Variant/VariantReader.cs:
##########
@@ -577,7 +577,20 @@ private void EnsurePrimitiveType(VariantPrimitiveType 
expected)
         /// Materializes this variant value into a <see cref="VariantValue"/> 
object.
         /// Recursively materializes objects and arrays.
         /// </summary>
+        /// <exception cref="System.IO.InvalidDataException">
+        /// Objects and arrays are nested more than 128 deep, or the values of 
an object's
+        /// fields overlap or extend outside the object.
+        /// </exception>
         public VariantValue ToVariantValue()
+        {
+            VariantValidator.Validate(_value);
+            return Materialize();
+        }

Review Comment:
   Reworded to cover malformed values in general (d56e161).



##########
src/Apache.Arrow.Scalars/Variant/VariantValueWriter.cs:
##########
@@ -554,7 +554,17 @@ public void WriteTimestampNtzNanos(long nanos)
         /// <see 
cref="VariantMetadataBuilder.CollectFieldNames(VariantReader)"/> during
         /// the metadata-collection phase of a two-pass encode to accumulate 
them.
         /// </remarks>
+        /// <exception cref="System.IO.InvalidDataException">
+        /// Objects and arrays are nested more than 128 deep, or the values of 
an object's
+        /// fields overlap or extend outside the object. Nothing has been 
written when this is thrown.
+        /// </exception>
         public void CopyValue(VariantReader source)
+        {
+            VariantValidator.Validate(source.Value);
+            CopyValueCore(source);
+        }

Review Comment:
   Reworded to cover malformed values in general (d56e161). Nothing after 
validation throws `InvalidDataException`, so the guarantee that nothing has 
been written holds; the doc now says why.



##########
src/Apache.Arrow.Scalars/Variant/VariantValidator.cs:
##########
@@ -0,0 +1,474 @@
+// 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
+//
+//     http://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.
+
+using System;
+using System.Buffers;
+using System.Buffers.Binary;
+using System.IO;
+using System.Runtime.CompilerServices;
+
+namespace Apache.Arrow.Scalars.Variant
+{
+    /// <summary>
+    /// Structural checks a variant value must pass before code walks all of 
it recursively.
+    /// </summary>
+    /// <remarks>
+    /// <para>
+    /// Code that visits every nested value (materializing, copying, 
collecting field names or
+    /// writing JSON) relies on two properties that the encoding does not 
enforce by itself:
+    /// </para>
+    /// <list type="bullet">
+    /// <item>Nesting is bounded, so the recursion cannot exhaust the 
stack.</item>
+    /// <item>
+    /// The values of an object's fields lie inside the object and do not 
overlap, so every
+    /// nested value has its own bytes and the walk does work proportional to 
the size of the
+    /// value. The spec lets field values appear in any order, so offsets need 
not increase,
+    /// but two fields must not share bytes.
+    /// </item>
+    /// </list>
+    /// <para>
+    /// Validation recurses only after checking the depth, so it is itself 
bounded. It checks
+    /// that every primitive fits in the space it is given, but not its 
contents or field IDs;
+    /// readers check those when they are accessed.
+    /// </para>
+    /// </remarks>
+    internal static class VariantValidator
+    {
+        /// <summary>
+        /// The default maximum number of nested objects and arrays. The 
variant spec sets no
+        /// limit. This allows four times the nesting <c>System.Text.Json</c> 
reads by default
+        /// while staying far below the depth at which recursion overflows a 
small thread stack.
+        /// </summary>
+        internal const int DefaultMaxDepth = 128;
+
+        /// <summary>
+        /// The size of the value each header byte starts, for short strings 
and primitives of
+        /// fixed size, or zero for the rest.
+        /// </summary>
+        private static readonly byte[] s_fixedSizes = BuildFixedSizes();
+
+        private static byte[] BuildFixedSizes()
+        {
+            byte[] sizes = new byte[256];
+            for (int header = 0; header < 256; header++)
+            {
+                switch (VariantEncodingHelper.GetBasicType((byte)header))
+                {
+                    case VariantBasicType.ShortString:
+                        sizes[header] = (byte)(1 + 
VariantEncodingHelper.GetShortStringLength((byte)header));
+                        break;
+
+                    case VariantBasicType.Primitive:
+                        VariantPrimitiveType type = 
VariantEncodingHelper.GetPrimitiveType((byte)header);
+                        if (type <= VariantPrimitiveType.Uuid &&
+                            type != VariantPrimitiveType.Binary &&
+                            type != VariantPrimitiveType.String)
+                        {
+                            sizes[header] = (byte)PrimitiveSize(new[] { 
(byte)header });
+                        }
+                        break;
+                }
+            }
+
+            return sizes;
+        }
+
+        /// <summary>
+        /// Validates <paramref name="value"/> with the default maximum depth.
+        /// </summary>
+        /// <exception cref="InvalidDataException">The value fails 
validation.</exception>
+        internal static void Validate(ReadOnlySpan<byte> value) => 
Validate(value, DefaultMaxDepth);
+
+        /// <summary>
+        /// Validates <paramref name="value"/>, allowing at most <paramref 
name="maxDepth"/>
+        /// nested objects and arrays.
+        /// </summary>
+        /// <exception cref="InvalidDataException">The value fails 
validation.</exception>
+        internal static void Validate(ReadOnlySpan<byte> value, int maxDepth)
+        {
+            if (maxDepth < 1)
+            {
+                throw new ArgumentOutOfRangeException(nameof(maxDepth), 
maxDepth, "The maximum depth must be at least 1.");
+            }
+
+            ValidateValue(value, 0, maxDepth);
+        }
+
+        private static void ValidateValue(ReadOnlySpan<byte> value, int depth, 
int maxDepth)
+        {
+            if (value.IsEmpty)
+            {
+                throw Invalid("a value is empty");
+            }
+
+            switch (VariantEncodingHelper.GetBasicType(value[0]))
+            {
+                case VariantBasicType.Object:
+                    CheckDepth(depth, maxDepth);
+                    ValidateObject(value, depth, maxDepth);
+                    break;
+
+                case VariantBasicType.Array:
+                    CheckDepth(depth, maxDepth);
+                    ValidateArray(value, depth, maxDepth);
+                    break;
+
+                default:
+                    ValueSize(value);
+                    break;
+            }
+        }
+
+        /// <summary>
+        /// Objects and arrays have basic types 2 and 3.
+        /// </summary>
+        [MethodImpl(MethodImplOptions.AggressiveInlining)]
+        private static bool IsContainer(byte header) => (header & 0x02) != 0;

Review Comment:
   Done in d56e161.



##########
src/Apache.Arrow.Scalars/Variant/VariantValidator.cs:
##########
@@ -0,0 +1,474 @@
+// 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
+//
+//     http://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.
+
+using System;
+using System.Buffers;
+using System.Buffers.Binary;
+using System.IO;
+using System.Runtime.CompilerServices;
+
+namespace Apache.Arrow.Scalars.Variant
+{
+    /// <summary>
+    /// Structural checks a variant value must pass before code walks all of 
it recursively.
+    /// </summary>
+    /// <remarks>
+    /// <para>
+    /// Code that visits every nested value (materializing, copying, 
collecting field names or
+    /// writing JSON) relies on two properties that the encoding does not 
enforce by itself:
+    /// </para>
+    /// <list type="bullet">
+    /// <item>Nesting is bounded, so the recursion cannot exhaust the 
stack.</item>
+    /// <item>
+    /// The values of an object's fields lie inside the object and do not 
overlap, so every
+    /// nested value has its own bytes and the walk does work proportional to 
the size of the
+    /// value. The spec lets field values appear in any order, so offsets need 
not increase,
+    /// but two fields must not share bytes.
+    /// </item>
+    /// </list>
+    /// <para>
+    /// Validation recurses only after checking the depth, so it is itself 
bounded. It checks
+    /// that every primitive fits in the space it is given, but not its 
contents or field IDs;
+    /// readers check those when they are accessed.
+    /// </para>
+    /// </remarks>
+    internal static class VariantValidator
+    {
+        /// <summary>
+        /// The default maximum number of nested objects and arrays. The 
variant spec sets no
+        /// limit. This allows four times the nesting <c>System.Text.Json</c> 
reads by default
+        /// while staying far below the depth at which recursion overflows a 
small thread stack.
+        /// </summary>
+        internal const int DefaultMaxDepth = 128;
+
+        /// <summary>
+        /// The size of the value each header byte starts, for short strings 
and primitives of
+        /// fixed size, or zero for the rest.
+        /// </summary>
+        private static readonly byte[] s_fixedSizes = BuildFixedSizes();
+
+        private static byte[] BuildFixedSizes()
+        {
+            byte[] sizes = new byte[256];
+            for (int header = 0; header < 256; header++)
+            {
+                switch (VariantEncodingHelper.GetBasicType((byte)header))
+                {
+                    case VariantBasicType.ShortString:
+                        sizes[header] = (byte)(1 + 
VariantEncodingHelper.GetShortStringLength((byte)header));
+                        break;
+
+                    case VariantBasicType.Primitive:
+                        VariantPrimitiveType type = 
VariantEncodingHelper.GetPrimitiveType((byte)header);
+                        if (type <= VariantPrimitiveType.Uuid &&
+                            type != VariantPrimitiveType.Binary &&
+                            type != VariantPrimitiveType.String)
+                        {
+                            sizes[header] = (byte)PrimitiveSize(new[] { 
(byte)header });
+                        }
+                        break;

Review Comment:
   Done in d56e161.



##########
test/Apache.Arrow.Operations.Tests/VariantJson/VariantJsonValidationTests.cs:
##########
@@ -0,0 +1,86 @@
+// 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
+//
+//     http://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.
+
+using System.IO;
+using System.Text.Json;
+using Apache.Arrow.Operations.VariantJson;
+using Xunit;
+
+namespace Apache.Arrow.Operations.Tests
+{
+    public class VariantJsonValidationTests
+    {
+        // Metadata: version 1, 1-byte offsets, dictionary ["a", "b"].
+        private static readonly byte[] s_metadata = { 0x01, 0x02, 0x00, 0x01, 
0x02, (byte)'a', (byte)'b' };
+
+        [Fact]
+        public void ArraysNestedToTheLimit_AreWritten()
+        {
+            string json = VariantJsonWriter.ToJson(s_metadata, 
NestedArrays(128));
+
+            Assert.Equal(new string('[', 128) + "null" + new string(']', 128), 
json);

Review Comment:
   Done in d56e161.



##########
test/Apache.Arrow.Scalars.Tests/VariantValidatorTests.cs:
##########
@@ -0,0 +1,440 @@
+// 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
+//
+//     http://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.
+
+using System;
+using System.Collections.Generic;
+using System.IO;
+using Apache.Arrow.Scalars.Variant;
+using Xunit;
+
+namespace Apache.Arrow.Scalars.Tests
+{
+    public class VariantValidatorTests
+    {
+        // Metadata: version 1, 1-byte offsets, dictionary ["a", "b"].
+        private static readonly byte[] s_metadata = { 0x01, 0x02, 0x00, 0x01, 
0x02, (byte)'a', (byte)'b' };
+
+        private const int MaxDepth = VariantValidator.DefaultMaxDepth;
+
+        // ---------------------------------------------------------------
+        // Nesting depth
+        // ---------------------------------------------------------------
+
+        [Fact]
+        public void ArraysNestedToTheLimit_Materialize()
+        {
+            VariantValue value = new VariantReader(s_metadata, 
NestedArrays(MaxDepth)).ToVariantValue();
+
+            int depth = 0;
+            while (value.IsArray)
+            {
+                value = value.AsArray()[0];
+                depth++;
+            }
+            Assert.Equal(MaxDepth, depth);
+            Assert.True(value.IsNull);
+        }
+
+        [Fact]
+        public void ObjectsNestedToTheLimit_Materialize()
+        {
+            VariantValue value = new VariantReader(s_metadata, 
NestedObjects(MaxDepth)).ToVariantValue();
+
+            int depth = 0;
+            while (value.IsObject)
+            {
+                value = value.AsObject()["a"];
+                depth++;
+            }
+            Assert.Equal(MaxDepth, depth);
+        }
+
+        [Theory]
+        [InlineData(MaxDepth + 1)]
+        [InlineData(100_000)]
+        public void ArraysNestedPastTheLimit_AreRejected(int depth)
+        {
+            AssertRejectedEverywhere(NestedArrays(depth), "nested more than 
128 deep");
+        }

Review Comment:
   Done in d56e161.



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

To unsubscribe, e-mail: [email protected]

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

Reply via email to