Skip to content

UnsafeRelaxedJsonEscaping escapes too much #86463

Closed as not planned
Closed as not planned

Description

@davidmatson

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

  1. ghost added
    needs-area-label
    on May 18, 2023
  2. added and removed
    needs-area-label
    on May 18, 2023
  3. added
    untriaged
    and removed on May 19, 2023
  4. eiriktsarpalis commented on May 24, 2023

    @eiriktsarpalis
    Member

    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 TextEncoderSettings class, see https://learn.microsoft.com/en-gb/dotnet/standard/serialization/system-text-json/character-encoding#serialize-specific-characters for more details.

  5. ghost removed
    untriaged
    on May 24, 2023
  6. davidmatson commented on May 24, 2023

    @davidmatson
    Author

    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 TextEncoderSettings class, see https://learn.microsoft.com/en-gb/dotnet/standard/serialization/system-text-json/character-encoding#serialize-specific-characters for more details.

    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!

  7. eiriktsarpalis commented on May 24, 2023

    @eiriktsarpalis
    Member

    I don't think that statement is accurate.

    Right, this concerns the default encoding that your repro is using. If I change it to use UnsafeRelaxedJsonEscaping

    var options = new JsonSerializerOptions { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping };
    string actual = JsonSerializer.Serialize(test, options);

    The output now becomes

    Unexpected output. Expected: {"Value":"abc  𠮟るdef"}, Actual {"Value":"abc\u3000\u3000\uD842\uDF9Fるdef"}
    

    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).

  8. davidmatson commented on May 24, 2023

    @davidmatson
    Author

    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?

  9. davidmatson commented on May 24, 2023

    @davidmatson
    Author

    For example, consider this comment;
    #42847 (comment)

    The implementation in workaround section above is likely what was suggested as a possible addition there.

  10. eiriktsarpalis commented on May 24, 2023

    @eiriktsarpalis
    Member

    cc @GrabYourPitchforks who might have feedback on if or how global block lists should be circumvented.

  11. davidmatson commented on May 25, 2023

    @davidmatson
    Author

    @eiriktsarpalis - could we re-open this issue? Thanks!

  12. eiriktsarpalis commented on May 25, 2023

    @eiriktsarpalis
    Member

    What is the request exactly? The current escaping behavior is by design.

  13. davidmatson commented on May 26, 2023

    @davidmatson
    Author

    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.

  14. eiriktsarpalis commented on May 26, 2023

    @eiriktsarpalis
    Member

    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 JavaScriptEncoder as suggested here, though obviously only do that at your own risk.

  15. ghost locked as resolved and limited conversation to collaborators on Jul 6, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions