Skip to content

Commit 129982e

Browse files
Detect specifical character in EnumConverter.cs (#76873)
* add specifical char flag and fail earlier before invoke naming policy * add unit test * improve unit test and special char check * fix format error * fix unit test * take comments and improve unit test * use string.IndexOfAny * throw exception in constructor and improve unit test * add custome exception message * take comments * Update src/libraries/System.Text.Json/tests/System.Text.Json.FSharp.Tests/EnumTests.fs * Update src/libraries/System.Text.Json/tests/System.Text.Json.FSharp.Tests/EnumTests.fs * Update src/libraries/System.Text.Json/tests/System.Text.Json.FSharp.Tests/EnumTests.fs * Update src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/EnumConverter.cs Co-authored-by: Eirik Tsarpalis <eirik.tsarpalis@gmail.com>
1 parent 46021ad commit 129982e

5 files changed

Lines changed: 105 additions & 27 deletions

File tree

src/libraries/System.Text.Json/src/Resources/Strings.resx

Lines changed: 30 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,17 @@
11
<?xml version="1.0" encoding="utf-8"?>
22
<root>
3-
<!--
4-
Microsoft ResX Schema
5-
3+
<!--
4+
Microsoft ResX Schema
5+
66
Version 2.0
7-
8-
The primary goals of this format is to allow a simple XML format
9-
that is mostly human readable. The generation and parsing of the
10-
various data types are done through the TypeConverter classes
7+
8+
The primary goals of this format is to allow a simple XML format
9+
that is mostly human readable. The generation and parsing of the
10+
various data types are done through the TypeConverter classes
1111
associated with the data types.
12-
12+
1313
Example:
14-
14+
1515
... ado.net/XML headers & schema ...
1616
<resheader name="resmimetype">text/microsoft-resx</resheader>
1717
<resheader name="version">2.0</resheader>
@@ -26,36 +26,36 @@
2626
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
2727
<comment>This is a comment</comment>
2828
</data>
29-
30-
There are any number of "resheader" rows that contain simple
29+
30+
There are any number of "resheader" rows that contain simple
3131
name/value pairs.
32-
33-
Each data row contains a name, and value. The row also contains a
34-
type or mimetype. Type corresponds to a .NET class that support
35-
text/value conversion through the TypeConverter architecture.
36-
Classes that don't support this are serialized and stored with the
32+
33+
Each data row contains a name, and value. The row also contains a
34+
type or mimetype. Type corresponds to a .NET class that support
35+
text/value conversion through the TypeConverter architecture.
36+
Classes that don't support this are serialized and stored with the
3737
mimetype set.
38-
39-
The mimetype is used for serialized objects, and tells the
40-
ResXResourceReader how to depersist the object. This is currently not
38+
39+
The mimetype is used for serialized objects, and tells the
40+
ResXResourceReader how to depersist the object. This is currently not
4141
extensible. For a given mimetype the value must be set accordingly:
42-
43-
Note - application/x-microsoft.net.object.binary.base64 is the format
44-
that the ResXResourceWriter will generate, however the reader can
42+
43+
Note - application/x-microsoft.net.object.binary.base64 is the format
44+
that the ResXResourceWriter will generate, however the reader can
4545
read any of the formats listed below.
46-
46+
4747
mimetype: application/x-microsoft.net.object.binary.base64
48-
value : The object must be serialized with
48+
value : The object must be serialized with
4949
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
5050
: and then encoded with base64 encoding.
51-
51+
5252
mimetype: application/x-microsoft.net.object.soap.base64
53-
value : The object must be serialized with
53+
value : The object must be serialized with
5454
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
5555
: and then encoded with base64 encoding.
5656
5757
mimetype: application/x-microsoft.net.object.bytearray.base64
58-
value : The object must be serialized into a byte array
58+
value : The object must be serialized into a byte array
5959
: using a System.ComponentModel.TypeConverter
6060
: and then encoded with base64 encoding.
6161
-->
@@ -231,6 +231,9 @@
231231
<data name="InvalidCharacterWithinString" xml:space="preserve">
232232
<value>'{0}' is invalid within a JSON string. The string should be correctly escaped.</value>
233233
</data>
234+
<data name="InvalidEnumTypeWithSpecialChar" xml:space="preserve">
235+
<value>Enum type '{0}' uses unsupported identifer name '{1}'.</value>
236+
</data>
234237
<data name="InvalidEndOfJsonNonPrimitive" xml:space="preserve">
235238
<value>'{0}' is an invalid token type for the end of the JSON payload. Expected either 'EndArray' or 'EndObject'.</value>
236239
</data>

src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/EnumConverter.cs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@ internal sealed class EnumConverter<T> : JsonConverter<T>
1515
{
1616
private static readonly TypeCode s_enumTypeCode = Type.GetTypeCode(typeof(T));
1717

18+
private static readonly char[] s_specialChars = new[] { ',', ' ' };
19+
1820
// Odd type codes are conveniently signed types (for enum backing types).
1921
private static readonly bool s_isSignedEnum = ((int)s_enumTypeCode % 2) == 1;
2022

@@ -85,6 +87,12 @@ public EnumConverter(EnumConverterOptions converterOptions, JsonNamingPolicy? na
8587
string jsonName = FormatJsonName(name, namingPolicy);
8688
_nameCacheForWriting.TryAdd(key, JsonEncodedText.Encode(jsonName, encoder));
8789
_nameCacheForReading?.TryAdd(jsonName, value);
90+
91+
// If enum contains special char, make it failed to serialize or deserialize.
92+
if (name.IndexOfAny(s_specialChars) != -1)
93+
{
94+
ThrowHelper.ThrowInvalidOperationException_InvalidEnumTypeWithSpecialChar(typeof(T), name);
95+
}
8896
}
8997
}
9098

src/libraries/System.Text.Json/src/System/Text/Json/ThrowHelper.Serialization.cs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -805,6 +805,12 @@ public static void ThrowInvalidOperationException_PolymorphicTypeConfigurationDo
805805
throw new InvalidOperationException(SR.Format(SR.Polymorphism_ConfigurationDoesNotSpecifyDerivedTypes, baseType));
806806
}
807807

808+
[DoesNotReturn]
809+
public static void ThrowInvalidOperationException_InvalidEnumTypeWithSpecialChar(Type enumType, string enumName)
810+
{
811+
throw new InvalidOperationException(SR.Format(SR.InvalidEnumTypeWithSpecialChar, enumType.Name, enumName));
812+
}
813+
808814
[DoesNotReturn]
809815
public static void ThrowJsonException_UnrecognizedTypeDiscriminator(object typeDiscriminator)
810816
{
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
module System.Text.Json.Tests.FSharp.EnumTests
2+
3+
open System
4+
open System.Reflection
5+
open System.Text.Json
6+
open System.Text.Json.Serialization
7+
open Xunit
8+
9+
[<Flags>]
10+
type BadEnum =
11+
| ``There's a comma, in my name`` = 1
12+
| ``There's a comma, even here`` = 2
13+
| ``ThisisagoodEnumValue`` = 4
14+
15+
let badEnum = BadEnum.``There's a comma, in my name`` ||| BadEnum.``There's a comma, even here``
16+
let badEnumJsonStr = $"\"{badEnum}\""
17+
18+
let badEnumWithGoodValue = BadEnum.ThisisagoodEnumValue
19+
let badEnumWithGoodValueJsonStr = $"\"{badEnumWithGoodValue}\""
20+
21+
[<Flags>]
22+
type GoodEnum =
23+
| Thereisnocommainmyname_1 = 1
24+
| Thereisnocommaevenhere_2 = 2
25+
26+
let goodEnum = GoodEnum.Thereisnocommainmyname_1 ||| GoodEnum.Thereisnocommaevenhere_2
27+
let goodEnumJsonStr = $"\"{goodEnum}\""
28+
29+
let options = new JsonSerializerOptions()
30+
options.Converters.Add(new JsonStringEnumConverter())
31+
32+
[<Fact>]
33+
let ``Deserialize With Exception If Enum Contains Special Char`` () =
34+
let ex = Assert.Throws<TargetInvocationException>(fun () -> JsonSerializer.Deserialize<BadEnum>(badEnumJsonStr, options) |> ignore)
35+
Assert.Equal(typeof<InvalidOperationException>, ex.InnerException.GetType())
36+
Assert.Equal("Enum type 'BadEnum' uses unsupported identifer name 'There's a comma, in my name'.", ex.InnerException.Message)
37+
38+
39+
[<Fact>]
40+
let ``Serialize With Exception If Enum Contains Special Char`` () =
41+
let ex = Assert.Throws<TargetInvocationException>(fun () -> JsonSerializer.Serialize(badEnum, options) |> ignore)
42+
Assert.Equal(typeof<InvalidOperationException>, ex.InnerException.GetType())
43+
Assert.Equal("Enum type 'BadEnum' uses unsupported identifer name 'There's a comma, in my name'.", ex.InnerException.Message)
44+
45+
[<Fact>]
46+
let ``Successful Deserialize Normal Enum`` () =
47+
let actual = JsonSerializer.Deserialize<GoodEnum>(goodEnumJsonStr, options)
48+
Assert.Equal(GoodEnum.Thereisnocommainmyname_1 ||| GoodEnum.Thereisnocommaevenhere_2, actual)
49+
50+
[<Fact>]
51+
let ``Fail Deserialize Good Value Of Bad Enum Type`` () =
52+
let ex = Assert.Throws<TargetInvocationException>(fun () -> JsonSerializer.Deserialize<BadEnum>(badEnumWithGoodValueJsonStr, options) |> ignore)
53+
Assert.Equal(typeof<InvalidOperationException>, ex.InnerException.GetType())
54+
Assert.Equal("Enum type 'BadEnum' uses unsupported identifer name 'There's a comma, in my name'.", ex.InnerException.Message)
55+
56+
[<Fact>]
57+
let ``Fail Serialize Good Value Of Bad Enum Type`` () =
58+
let ex = Assert.Throws<TargetInvocationException>(fun () -> JsonSerializer.Serialize(badEnumWithGoodValue, options) |> ignore)
59+
Assert.Equal(typeof<InvalidOperationException>, ex.InnerException.GetType())
60+
Assert.Equal("Enum type 'BadEnum' uses unsupported identifer name 'There's a comma, in my name'.", ex.InnerException.Message)

src/libraries/System.Text.Json/tests/System.Text.Json.FSharp.Tests/System.Text.Json.FSharp.Tests.fsproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
<ItemGroup>
88
<Compile Include="Helpers.fs" />
9+
<Compile Include="EnumTests.fs" />
910
<Compile Include="OptionTests.fs" />
1011
<Compile Include="ValueOptionTests.fs" />
1112
<Compile Include="CollectionTests.fs" />

0 commit comments

Comments
 (0)