Repository navigation
Fix JsonPatch to not drop empty reference tokens and adhere to RFC - #68613
Conversation
There was a problem hiding this comment.
Pull request overview
Updates ParsedPath parsing in both JsonPatch implementations to reject empty JSON Pointer reference tokens (e.g., //, trailing /), aligning behavior with the intended “no empty tokens” policy and preventing silent path collapsing.
Changes:
- Add explicit rejection of empty reference tokens during path parsing in
ParsedPath. - Treat empty string (
"") as a valid “root pointer” path (returns no segments). - Expand unit tests to cover leading
/paths, empty path, and empty-token rejection cases.
Reviewed changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated 4 comments.
| File | Description |
|---|---|
| src/Features/JsonPatch/src/Internal/ParsedPath.cs | Rejects empty reference tokens and handles empty path early. |
| src/Features/JsonPatch/test/Internal/ParsedPathTests.cs | Adds coverage for leading /, empty string, and empty-token failures. |
| src/Features/JsonPatch.SystemTextJson/src/Internal/ParsedPath.cs | Mirrors the same empty-token rejection + empty-path handling for STJ. |
| src/Features/JsonPatch.SystemTextJson/test/Internal/ParsedPathTests.cs | Mirrors the same test coverage changes for STJ. |
💡 Add a code-review agent skill for context-aware, tailored reviews. Learn more in the docs.
This comment was marked as outdated.
This comment was marked as outdated.
|
Copilot-generated: using BenchmarkDotNet.Running;
using JsonPatchParsedPathBenchmarks;
BenchmarkSwitcher.FromAssembly(typeof(ParsedPathBenchmarks).Assembly).Run(args);// Self-contained copies of the JsonPatch ParsedPath parsing logic, extracted to
// benchmark the change made in https://github.com/dotnet/aspnetcore/pull/68613
//
// * Old: StringBuilder char-by-char scan (dropped empty reference tokens).
// * New (Newtonsoft flavor): path.Substring(1).Split('/') + per-token validate/unescape.
// * New (System.Text.Json flavor): pre-sized array + ReadOnlySpan<char>.Split('/').
//
// The New variants mirror the current implementation in the dotnet/aspnetcore repo
// (src/Features/JsonPatch{,.SystemTextJson}/src/Internal/ParsedPath.cs). The exception
// type is simplified to a plain exception so the code is standalone.
using System.Text;
namespace JsonPatchParsedPathBenchmarks;
internal sealed class JsonPatchException(string message) : Exception(message);
/// <summary>
/// Pre-PR implementation (both JsonPatch and JsonPatch.SystemTextJson were identical).
/// Uses a <see cref="StringBuilder"/> and a manual character scan. Note that this
/// version silently dropped empty reference tokens and did not normalize the path.
/// </summary>
internal static class OldParsedPath
{
public static string[] Parse(string path)
{
var strings = new List<string>();
var sb = new StringBuilder(path.Length);
for (var i = 0; i < path.Length; i++)
{
if (path[i] == '/')
{
if (sb.Length > 0)
{
strings.Add(sb.ToString());
sb.Length = 0;
}
}
else if (path[i] == '~')
{
++i;
if (i >= path.Length)
{
throw new JsonPatchException($"The provided string '{path}' is an invalid path.");
}
if (path[i] == '0')
{
sb.Append('~');
}
else if (path[i] == '1')
{
sb.Append('/');
}
else
{
throw new JsonPatchException($"The provided string '{path}' is an invalid path.");
}
}
else
{
sb.Append(path[i]);
}
}
if (sb.Length > 0)
{
strings.Add(sb.ToString());
}
return strings.ToArray();
}
}
/// <summary>
/// Current implementation of the Newtonsoft-based <c>Microsoft.AspNetCore.JsonPatch</c>.
/// Normalizes the path, then <c>Substring(1).Split('/')</c> and validates/unescapes
/// each token in a single scan (only allocating a replacement when a '~' is present).
/// </summary>
internal static class NewParsedPathNewtonsoft
{
public static string[] Parse(string path)
{
return ParsePath(NormalizePath(path));
}
private static string NormalizePath(string path)
{
// An empty string on its own is valid, and is different from "/".
// So, we never want to normalize an empty string.
if (path.Length > 0 && !path.StartsWith('/'))
{
return $"/{path}";
}
return path;
}
private static string[] ParsePath(string path)
{
if (path.Length == 0)
{
return [];
}
if (path[0] != '/')
{
throw new JsonPatchException($"The provided string '{path}' is an invalid path.");
}
var referenceTokens = path.Substring(1).Split('/');
for (var i = 0; i < referenceTokens.Length; i++)
{
referenceTokens[i] = ValidateAndUnescapeReferenceToken(referenceTokens[i]);
}
return referenceTokens;
}
private static string ValidateAndUnescapeReferenceToken(string referenceToken)
{
var hasTilde = false;
for (var i = 0; i < referenceToken.Length; i++)
{
if (referenceToken[i] == '~')
{
hasTilde = true;
if (i + 1 >= referenceToken.Length || (referenceToken[i + 1] != '0' && referenceToken[i + 1] != '1'))
{
throw new JsonPatchException($"The provided string '{referenceToken}' is an invalid path.");
}
}
}
return hasTilde ? referenceToken.Replace("~1", "/").Replace("~0", "~") : referenceToken;
}
}
/// <summary>
/// Current implementation of <c>Microsoft.AspNetCore.JsonPatch.SystemTextJson</c>.
/// Normalizes the path, sizes the result array up front via
/// <see cref="MemoryExtensions.Count{T}(ReadOnlySpan{T}, T)"/>, then uses the span
/// split (<c>ReadOnlySpan<char>.Split('/')</c>) and validates/unescapes each token.
/// </summary>
internal static class NewParsedPathSystemTextJson
{
public static string[] Parse(string path)
{
return ParsePath(NormalizePath(path));
}
private static string NormalizePath(string path)
{
if (path.Length > 0 && !path.StartsWith('/'))
{
return $"/{path}";
}
return path;
}
private static string[] ParsePath(string path)
{
if (path.Length == 0)
{
return [];
}
var span = path.AsSpan();
if (span[0] != '/')
{
throw new JsonPatchException($"The provided string '{path}' is an invalid path.");
}
var strings = new string[span.Count('/')];
// When we have a path like "/a/b/c//d/e", the expectation is
// to have the segments be ["a", "b", "c", "", "d", "e"].
// So, before splitting on "/", we want to slice off the leading "/".
span = span.Slice(1);
var index = 0;
foreach (var referenceTokenRange in span.Split('/'))
{
var referenceToken = span[referenceTokenRange].ToString();
strings[index++] = ValidateAndUnescapeReferenceToken(referenceToken);
}
return strings;
}
private static string ValidateAndUnescapeReferenceToken(string referenceToken)
{
var hasTilde = false;
for (var i = 0; i < referenceToken.Length; i++)
{
if (referenceToken[i] == '~')
{
hasTilde = true;
if (i + 1 >= referenceToken.Length || (referenceToken[i + 1] != '0' && referenceToken[i + 1] != '1'))
{
throw new JsonPatchException($"The provided string '{referenceToken}' is an invalid path.");
}
}
}
return hasTilde ? referenceToken.Replace("~1", "/").Replace("~0", "~") : referenceToken;
}
}using BenchmarkDotNet.Attributes;
namespace JsonPatchParsedPathBenchmarks;
[MemoryDiagnoser]
public class ParsedPathBenchmarks
{
// Representative JSON Patch paths (RFC 6901 pointers) covering common and edge shapes.
[Params(
"/foo/bar", // simple, already normalized
"foo/bar", // needs leading-slash normalization
"/a/b/c/d/e/f/g/h", // deep path, no escapes
"/foo/bar~1baz/~0/qux", // escape sequences (~0 / ~1)
"/store/book/0/author/name/value")] // typical realistic pointer
public string Path { get; set; } = "";
[Benchmark(Baseline = true, Description = "Old (StringBuilder scan)")]
public string[] Old() => OldParsedPath.Parse(Path);
[Benchmark(Description = "New Newtonsoft (Substring.Split)")]
public string[] NewNewtonsoft() => NewParsedPathNewtonsoft.Parse(Path);
[Benchmark(Description = "New STJ (Span.Split)")]
public string[] NewSystemTextJson() => NewParsedPathSystemTextJson.Parse(Path);
}
Takeaway from this run: for the common case (paths without |
Fixes #67819