This commit is contained in:
Copilot 2025-07-30 10:13:11 -04:00 committed by GitHub
commit e7a625dd31
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 52 additions and 0 deletions

View File

@ -17,6 +17,35 @@ namespace System.Text.Json.Serialization.Converters
private const int MaximumEscapedVersionLength = JsonConstants.MaxExpansionFactorWhileEscaping * MaximumVersionLength;
#endif
private static bool IsValidVersionFormat(ReadOnlySpan<char> source)
{
// Check for plus signs anywhere in the string
if (source.IndexOf('+') >= 0)
{
return false;
}
// Check for whitespace adjacent to dots
for (int i = 0; i < source.Length; i++)
{
if (source[i] == '.')
{
// Check for whitespace before the dot
if (i > 0 && char.IsWhiteSpace(source[i - 1]))
{
return false;
}
// Check for whitespace after the dot
if (i < source.Length - 1 && char.IsWhiteSpace(source[i + 1]))
{
return false;
}
}
}
return true;
}
public override Version? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType is JsonTokenType.Null)
@ -55,6 +84,14 @@ namespace System.Text.Json.Serialization.Converters
ThrowHelper.ThrowFormatException(DataType.Version);
}
// Additional validation to be more strict than Version.TryParse:
// - Reject plus signs anywhere in the string
// - Reject whitespace adjacent to dots
if (!IsValidVersionFormat(source))
{
ThrowHelper.ThrowFormatException(DataType.Version);
}
if (Version.TryParse(source, out Version? result))
{
return result;
@ -69,6 +106,14 @@ namespace System.Text.Json.Serialization.Converters
// since Version.TryParse allows them and silently parses input to Version
ThrowHelper.ThrowFormatException(DataType.Version);
}
// Additional validation to be more strict than Version.TryParse:
// - Reject plus signs anywhere in the string
// - Reject whitespace adjacent to dots
if (!string.IsNullOrEmpty(versionString) && !IsValidVersionFormat(versionString.AsSpan()))
{
ThrowHelper.ThrowFormatException(DataType.Version);
}
if (Version.TryParse(versionString, out Version? result))
{
return result;

View File

@ -358,6 +358,13 @@ namespace System.Text.Json.Serialization.Tests
[InlineData(" 1.2.3.4")] //Valid but has leading whitespace
[InlineData("1.2.3.4 ")] //Valid but has trailing whitespace
[InlineData(" 1.2.3.4 ")] //Valid but has trailing and leading whitespaces
[InlineData("1.+1")] //Plus sign in second component should be rejected
[InlineData("1 .1")] //Whitespace before dot should be rejected
[InlineData("1. 1")] //Whitespace after dot should be rejected
[InlineData("1 . +1")] //Whitespace around dot and plus sign should be rejected
[InlineData("1.+2.3")] //Plus sign in second component with more components
[InlineData("1.2. 3")] //Whitespace after second dot
[InlineData("1 .2.3")] //Whitespace before first dot
[InlineData("{}", false)]
[InlineData("[]", false)]
[InlineData("true", false)]