Repository navigation
Closed as not planned
Description
Description
The runtime doesn't provide an option to encode only the code points required by the JSON RFC. UnsafeRelaxedJsonEscaping still escapes unnessarily.
Reproduction Steps
using System.Text;
using System.Text.Json;
class TestJsonObject
{
public TestJsonObject(string value)
{
Value = value;
}
public string Value { get; }
}
class Program
{
static int Main()
{
Console.OutputEncoding = Encoding.UTF8;
string source = "abc 𠮟るdef";
string source2 = "abc\u3000\u3000\ud842\udf9f\u308bdef";
if (source != source2)
{
Console.Error.WriteLine("Strings mismatch (check source file encoding).");
return 1;
}
string expected = "{Value=\"" + source + "\"}";
TestJsonObject test = new TestJsonObject(source);
string actual = JsonSerializer.Serialize(test, new JsonSerializerOptions { Encoder =
JavaScriptEncoder.UnsafeRelaxedJsonEscaping });
if (expected != actual)
{
Console.Error.WriteLine($"Unexpected output. Expected: {expected}, Actual {actual}");
return 1;
}
return 0;
}
}Expected behavior
The repro above (.NET 7) works.
Actual behavior
It throws an exception, due to multiple of the source characters being unnecessarily escaped.
Regression?
No response
Known Workarounds
class MinimalJsonEncoder : JavaScriptEncoder
{
public override int MaxOutputCharactersPerInputCharacter => 6;
public override unsafe int FindFirstCharacterToEncode(char* text, int textLength)
{
for (int index = 0; index < textLength; ++index)
{
char value = text[index];
if (NeedsEncoding(value))
{
return index;
}
}
return -1;
}
public override unsafe bool TryEncodeUnicodeScalar(int unicodeScalar, char* buffer, int bufferLength,
out int numberOfCharactersWritten)
{
bool encode = WillEncode(unicodeScalar);
if (!encode)
{
Span<char> span = new Span<char>(buffer, bufferLength);
int spanWritten;
bool succeeded = new Rune(unicodeScalar).TryEncodeToUtf16(span, out spanWritten);
numberOfCharactersWritten = spanWritten;
return succeeded;
}
if (unicodeScalar == '"' || unicodeScalar == '\\')
{
if (bufferLength < 2)
{
numberOfCharactersWritten = 0;
return false;
}
buffer[0] = '\\';
buffer[1] = (char)unicodeScalar;
numberOfCharactersWritten = 2;
return true;
}
else
{
if (bufferLength < 6)
{
numberOfCharactersWritten = 0;
return false;
}
buffer[0] = '\\';
buffer[1] = 'u';
buffer[2] = '0';
buffer[3] = '0';
buffer[4] = ToHexDigit((unicodeScalar & 0xf0) >> 4);
buffer[5] = ToHexDigit(unicodeScalar & 0xf);
numberOfCharactersWritten = 6;
return true;
}
}
public override bool WillEncode(int unicodeScalar)
{
if (unicodeScalar > char.MaxValue)
{
return false;
}
return NeedsEncoding((char)unicodeScalar);
}
// https://datatracker.ietf.org/doc/html/rfc8259#section-7
static bool NeedsEncoding(char value)
{
if (value == '"' || value == '\\')
{
return true;
}
return value <= '\u001f';
}
static char ToHexDigit(int value)
{
if (value > 0xf)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
if (value < 10)
{
return (char)(value + '0');
}
else
{
return (char)(value - 0xa + 'a');
}
}
}Configuration
.NET 7 on Windows 10 x64. Likely not specific to this config.
Other information
If we can't change UnsafeRelaxedJsonEscaping, providing a MinimalJsonEscaping using something like the workaround above would be great.
Note that the expected text will likely not display well in a console window given font limitations - you'll likely need to copy/paste elsewhere (such as Notepad) to see the desired text rendered correctly.
Activity
eiriktsarpalis commentedon May 24, 2023
This is by design -- the serializer will escape all non-ascii characters. You can opt in to specific characters/character ranges from not being escaped by configuring the
TextEncoderSettingsclass, see https://learn.microsoft.com/en-gb/dotnet/standard/serialization/system-text-json/character-encoding#serialize-specific-characters for more details.davidmatson commentedon May 24, 2023
I don't think that statement is accurate. UnsafeRelaxedJsonEscaping does not escape all non-ascii characters. See:
https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/character-encoding#serialize-all-characters
Can you please re-open this issue? Thanks!
eiriktsarpalis commentedon May 24, 2023
Right, this concerns the default encoding that your repro is using. If I change it to use
UnsafeRelaxedJsonEscapingThe output now becomes
Note that U+3000 ' ' is being escaped because it is a separator defined in the global block list and U+20B9F '𠮟' is a surrogate pair which is also getting escaped (see #42847).
davidmatson commentedon May 24, 2023
Sorry, somehow I had the wrong line in the repro. I've updated it.
With UnsafeRelaxedJsonEscaping, it still over-escapes compared to what the JSON RFC requires. This bug is requesting a JSON encoder that doesn't escape more than is required. Can this bug be reopened?
davidmatson commentedon May 24, 2023
For example, consider this comment;
#42847 (comment)
The implementation in workaround section above is likely what was suggested as a possible addition there.
eiriktsarpalis commentedon May 24, 2023
cc @GrabYourPitchforks who might have feedback on if or how global block lists should be circumvented.
davidmatson commentedon May 25, 2023
@eiriktsarpalis - could we re-open this issue? Thanks!
eiriktsarpalis commentedon May 25, 2023
What is the request exactly? The current escaping behavior is by design.
davidmatson commentedon May 26, 2023
That either 1) UnsafeRelaxedJsonEscaping be changed to escape only where required by the JSON RFC, or 2) that a class with this behavior be added, perhaps MinimalJsonEscaping.
eiriktsarpalis commentedon May 26, 2023
As the name and documentation of UnsafeRelaxedJsonEscaping suggests, it does not disable escaping -- it is fairly intentional on still enforcing the global block list which goes beyond what the RFC mandates (I presume this is done out of security considerations, but I defer to @GrabYourPitchforks on that). A workaround can be achieved by subclassing
JavaScriptEncoderas suggested here, though obviously only do that at your own risk.