From 39ca7e826c96bf3aeee61071cd1ce5bf0b858630 Mon Sep 17 00:00:00 2001 From: Sindri Frostason Date: Thu, 14 Aug 2025 11:11:31 +0000 Subject: [PATCH] fix(serialization): Replace redundant round-trip in JsonSerializer.Parse with Clone The JsonSerializer.Parse method was performing an unnecessary round-trip serialization (JsonElement -> Utf8JsonWriter -> Utf8JsonReader -> JsonElement). More critically, the WriteTo() operation triggered a buffer overflow bug in System.Text.Json's WriteComplexElement when processing complex nested JSON objects larger than Utf8JsonWriter's internal buffer of 4KB, leading to memory corruption and undefined behaviour. Replace the round-trip with JsonElement.Clone() which: - Preserves identical semantics - Eliminates the buffer overflow risk entirely - Improves performance by avoiding unnecessary serialization - Maintains proper memory management for the cloned element --- .../Client/src/Core/Serialization/JsonSerializer.cs | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/src/StrawberryShake/Client/src/Core/Serialization/JsonSerializer.cs b/src/StrawberryShake/Client/src/Core/Serialization/JsonSerializer.cs index fafc053a16f..116588f62a6 100644 --- a/src/StrawberryShake/Client/src/Core/Serialization/JsonSerializer.cs +++ b/src/StrawberryShake/Client/src/Core/Serialization/JsonSerializer.cs @@ -15,16 +15,7 @@ public JsonSerializer(string typeName = BuiltInScalarNames.Any) public override JsonElement Parse(JsonElement serializedValue) { - using var writer = new ArrayWriter(); - - // write json value to buffer. - using var jsonWriter = new Utf8JsonWriter(writer); - serializedValue.WriteTo(jsonWriter); - jsonWriter.Flush(); - - // now we read the buffer and create an element that does not need to be disposed. - var reader = new Utf8JsonReader(writer.GetWrittenSpan(), true, default); - return JsonElement.ParseValue(ref reader); + return serializedValue.Clone(); } protected override JsonElement Format(JsonElement runtimeValue)