Skip to content

Commit 4f5bfd9

Browse files
committed
Fix use of precedence in endpoint routing DFA (#20801)
* Fix use of precedence in endpoint routing DFA Fixes: #18677 Fixes: #16579 This is a change to how sorting is use when building endpoint routing's graph of nodes that is eventually transformed into the route table. There were bugs in how this was done that made it incompatible in some niche scenarios both with previous implementations and how we describe the features in the abstract. There are a wide array of cases that might have been impacted by this bug because routing is a pattern language. Generally the bugs will involve a catch-all, and some something that changes ordering of templates. Issue #18677 has the simplest repro for this, the following templates would not behave as expected: ``` a/{*b} {a}/{b} ``` One would expect any URL Path starting with `/a` to match the first route, but that's not what happens. --- The change supports an opt-in via the following AppContext switch: ``` Microsoft.AspNetCore.Routing.UseCorrectCatchAllBehavior ``` Set to true to enable the correct behavior. --- The root cause of this bug was an issue in how the algorithm used to be build the DFA was designed. Specifically that it uses a BFS to build the graph, and it uses an up-front one-time sort of endpoints in order to drive that BFS. The building of the graph has the expectation that at each level, we will process **all** literal segments (`/a`) and then **all** parameter segments (`/{a}`) and then **all** catch-all segments (`/{*a}`). Routing defines a concept called *precedence* that defines the *conceptual* order in while segments types are ordered. So there are two problems: - We sort based on criteria other than precedence (#16579) - We can't rely on a one-time sort, it needs to be done at each level (#18677) --- The fix is to repeat the sort operation at each level and use precedence as the only key for sorting (as dictated by the graph building algo). We do a sort of the matches of each node *after* building the precedence-based part of the DFA, based on the full sorting criteria, to maintain compatibility. * Add test
1 parent 1b99352 commit 4f5bfd9

9 files changed

+807
-22
lines changed

Diff for: src/Http/Routing/ref/Microsoft.AspNetCore.Routing.Manual.cs

+2
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,8 @@ internal static partial class FastPathTokenizer
199199
internal partial class DfaMatcherBuilder : Microsoft.AspNetCore.Routing.Matching.MatcherBuilder
200200
{
201201
public DfaMatcherBuilder(Microsoft.Extensions.Logging.ILoggerFactory loggerFactory, Microsoft.AspNetCore.Routing.ParameterPolicyFactory parameterPolicyFactory, Microsoft.AspNetCore.Routing.Matching.EndpointSelector selector, System.Collections.Generic.IEnumerable<Microsoft.AspNetCore.Routing.MatcherPolicy> policies) { }
202+
internal EndpointComparer Comparer { get; }
203+
internal bool UseCorrectCatchAllBehavior { get; set; }
202204
public override void AddEndpoint(Microsoft.AspNetCore.Routing.RouteEndpoint endpoint) { }
203205
public override Microsoft.AspNetCore.Routing.Matching.Matcher Build() { throw null; }
204206
public Microsoft.AspNetCore.Routing.Matching.DfaNode BuildDfaTree(bool includeLabel = false) { throw null; }

Diff for: src/Http/Routing/src/Matching/DfaMatcherBuilder.cs

+77-16
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
1-
// Copyright (c) .NET Foundation. All rights reserved.
1+
// Copyright (c) .NET Foundation. All rights reserved.
22
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
33

44
using System;
55
using System.Collections.Generic;
66
using System.Linq;
77
using Microsoft.AspNetCore.Http;
88
using Microsoft.AspNetCore.Routing.Patterns;
9+
using Microsoft.AspNetCore.Routing.Template;
910
using Microsoft.Extensions.Logging;
1011

1112
namespace Microsoft.AspNetCore.Routing.Matching
@@ -40,6 +41,15 @@ public DfaMatcherBuilder(
4041
_parameterPolicyFactory = parameterPolicyFactory;
4142
_selector = selector;
4243

44+
if (AppContext.TryGetSwitch("Microsoft.AspNetCore.Routing.UseCorrectCatchAllBehavior", out var enabled))
45+
{
46+
UseCorrectCatchAllBehavior = enabled;
47+
}
48+
else
49+
{
50+
UseCorrectCatchAllBehavior = false; // default to bugged behavior
51+
}
52+
4353
var (nodeBuilderPolicies, endpointComparerPolicies, endpointSelectorPolicies) = ExtractPolicies(policies.OrderBy(p => p.Order));
4454
_endpointSelectorPolicies = endpointSelectorPolicies;
4555
_nodeBuilders = nodeBuilderPolicies;
@@ -52,24 +62,33 @@ public DfaMatcherBuilder(
5262
_constraints = new List<KeyValuePair<string, IRouteConstraint>>();
5363
}
5464

65+
// Used in tests
66+
internal EndpointComparer Comparer => _comparer;
67+
68+
// Used in tests
69+
internal bool UseCorrectCatchAllBehavior { get; set; }
70+
5571
public override void AddEndpoint(RouteEndpoint endpoint)
5672
{
5773
_endpoints.Add(endpoint);
5874
}
5975

6076
public DfaNode BuildDfaTree(bool includeLabel = false)
6177
{
62-
// We build the tree by doing a BFS over the list of entries. This is important
63-
// because a 'parameter' node can also traverse the same paths that literal nodes
64-
// traverse. This means that we need to order the entries first, or else we will
65-
// miss possible edges in the DFA.
66-
_endpoints.Sort(_comparer);
78+
if (!UseCorrectCatchAllBehavior)
79+
{
80+
// In 3.0 we did a global sort of the endpoints up front. This was a bug, because we actually want
81+
// do do the sort at each level of the tree based on precedence.
82+
//
83+
// _useLegacy30Behavior enables opt-out via an AppContext switch.
84+
_endpoints.Sort(_comparer);
85+
}
6786

6887
// Since we're doing a BFS we will process each 'level' of the tree in stages
6988
// this list will hold the set of items we need to process at the current
7089
// stage.
71-
var work = new List<(RouteEndpoint endpoint, List<DfaNode> parents)>(_endpoints.Count);
72-
List<(RouteEndpoint endpoint, List<DfaNode> parents)> previousWork = null;
90+
var work = new List<(RouteEndpoint endpoint, int precedenceDigit, List<DfaNode> parents)>(_endpoints.Count);
91+
List<(RouteEndpoint endpoint, int precedenceDigit, List<DfaNode> parents)> previousWork = null;
7392

7493
var root = new DfaNode() { PathDepth = 0, Label = includeLabel ? "/" : null };
7594

@@ -79,21 +98,37 @@ public DfaNode BuildDfaTree(bool includeLabel = false)
7998
for (var i = 0; i < _endpoints.Count; i++)
8099
{
81100
var endpoint = _endpoints[i];
82-
maxDepth = Math.Max(maxDepth, endpoint.RoutePattern.PathSegments.Count);
101+
var precedenceDigit = GetPrecedenceDigitAtDepth(endpoint, depth: 0);
102+
work.Add((endpoint, precedenceDigit, new List<DfaNode>() { root, }));
83103

84-
work.Add((endpoint, new List<DfaNode>() { root, }));
104+
maxDepth = Math.Max(maxDepth, endpoint.RoutePattern.PathSegments.Count);
85105
}
106+
86107
var workCount = work.Count;
87108

109+
// Sort work at each level by *PRECEDENCE OF THE CURRENT SEGMENT*.
110+
//
111+
// We build the tree by doing a BFS over the list of entries. This is important
112+
// because a 'parameter' node can also traverse the same paths that literal nodes
113+
// traverse. This means that we need to order the entries first, or else we will
114+
// miss possible edges in the DFA.
115+
//
116+
// We'll sort the matches again later using the *real* comparer once building the
117+
// precedence part of the DFA is over.
118+
var precedenceDigitComparer = Comparer<(RouteEndpoint endpoint, int precedenceDigit, List<DfaNode> parents)>.Create((x, y) =>
119+
{
120+
return x.precedenceDigit.CompareTo(y.precedenceDigit);
121+
});
122+
88123
// Now we process the entries a level at a time.
89124
for (var depth = 0; depth <= maxDepth; depth++)
90125
{
91126
// As we process items, collect the next set of items.
92-
List<(RouteEndpoint endpoint, List<DfaNode> parents)> nextWork;
127+
List<(RouteEndpoint endpoint, int precedenceDigit, List<DfaNode> parents)> nextWork;
93128
var nextWorkCount = 0;
94129
if (previousWork == null)
95130
{
96-
nextWork = new List<(RouteEndpoint endpoint, List<DfaNode> parents)>();
131+
nextWork = new List<(RouteEndpoint endpoint, int precedenceDigit, List<DfaNode> parents)>();
97132
}
98133
else
99134
{
@@ -102,9 +137,17 @@ public DfaNode BuildDfaTree(bool includeLabel = false)
102137
nextWork = previousWork;
103138
}
104139

140+
if (UseCorrectCatchAllBehavior)
141+
{
142+
// The fix for the 3.0 sorting behavior bug.
143+
144+
// See comments on precedenceDigitComparer
145+
work.Sort(0, workCount, precedenceDigitComparer);
146+
}
147+
105148
for (var i = 0; i < workCount; i++)
106149
{
107-
var (endpoint, parents) = work[i];
150+
var (endpoint, _, parents) = work[i];
108151

109152
if (!HasAdditionalRequiredSegments(endpoint, depth))
110153
{
@@ -122,15 +165,17 @@ public DfaNode BuildDfaTree(bool includeLabel = false)
122165
nextParents = nextWork[nextWorkCount].parents;
123166
nextParents.Clear();
124167

125-
nextWork[nextWorkCount] = (endpoint, nextParents);
168+
var nextPrecedenceDigit = GetPrecedenceDigitAtDepth(endpoint, depth + 1);
169+
nextWork[nextWorkCount] = (endpoint, nextPrecedenceDigit, nextParents);
126170
}
127171
else
128172
{
129173
nextParents = new List<DfaNode>();
130174

131175
// Add to the next set of work now so the list will be reused
132176
// even if there are no parents
133-
nextWork.Add((endpoint, nextParents));
177+
var nextPrecedenceDigit = GetPrecedenceDigitAtDepth(endpoint, depth + 1);
178+
nextWork.Add((endpoint, nextPrecedenceDigit, nextParents));
134179
}
135180

136181
var segment = GetCurrentSegment(endpoint, depth);
@@ -281,7 +326,7 @@ private static void AddLiteralNode(bool includeLabel, List<DfaNode> nextParents,
281326
nextParents.Add(next);
282327
}
283328

284-
private RoutePatternPathSegment GetCurrentSegment(RouteEndpoint endpoint, int depth)
329+
private static RoutePatternPathSegment GetCurrentSegment(RouteEndpoint endpoint, int depth)
285330
{
286331
if (depth < endpoint.RoutePattern.PathSegments.Count)
287332
{
@@ -302,6 +347,18 @@ private RoutePatternPathSegment GetCurrentSegment(RouteEndpoint endpoint, int de
302347
return null;
303348
}
304349

350+
private static int GetPrecedenceDigitAtDepth(RouteEndpoint endpoint, int depth)
351+
{
352+
var segment = GetCurrentSegment(endpoint, depth);
353+
if (segment is null)
354+
{
355+
// Treat "no segment" as high priority. it won't effect the algorithm, but we need to define a sort-order.
356+
return 0;
357+
}
358+
359+
return RoutePrecedence.ComputeInboundPrecedenceDigit(endpoint.RoutePattern, segment);
360+
}
361+
305362
public override Matcher Build()
306363
{
307364
#if DEBUG
@@ -670,6 +727,10 @@ private void ApplyPolicies(DfaNode node)
670727
return;
671728
}
672729

730+
// We're done with the precedence based work. Sort the endpoints
731+
// before applying policies for simplicity in policy-related code.
732+
node.Matches.Sort(_comparer);
733+
673734
// Start with the current node as the root.
674735
var work = new List<DfaNode>() { node, };
675736
List<DfaNode> previousWork = null;

Diff for: src/Http/Routing/src/Template/RoutePrecedence.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -219,7 +219,7 @@ private static int ComputeInboundPrecedenceDigit(TemplateSegment segment)
219219
// see description on ComputeInboundPrecedenceDigit(TemplateSegment segment)
220220
//
221221
// With a RoutePattern, parameters with a required value are treated as a literal segment
222-
private static int ComputeInboundPrecedenceDigit(RoutePattern routePattern, RoutePatternPathSegment pathSegment)
222+
internal static int ComputeInboundPrecedenceDigit(RoutePattern routePattern, RoutePatternPathSegment pathSegment)
223223
{
224224
if (pathSegment.Parts.Count > 1)
225225
{
@@ -260,4 +260,4 @@ private static int ComputeInboundPrecedenceDigit(RoutePattern routePattern, Rout
260260
}
261261
}
262262
}
263-
}
263+
}
+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
// This file is used by Code Analysis to maintain SuppressMessage
2+
// attributes that are applied to this project.
3+
// Project-level suppressions either have no target or are given
4+
// a specific target and scoped to a namespace, type, member, etc.
5+
6+
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(
7+
"Build",
8+
"xUnit1013:Public method 'Quirks_CatchAllParameter' on test class 'FullFeaturedMatcherConformanceTest' should be marked as a Theory.",
9+
Justification = "This is a bug in the xUnit analyzer. This method is already marked as a theory.",
10+
Scope = "member",
11+
Target = "~M:Microsoft.AspNetCore.Routing.Matching.FullFeaturedMatcherConformanceTest.Quirks_CatchAllParameter(System.String,System.String,System.String[],System.String[])~System.Threading.Tasks.Task")]

0 commit comments

Comments
 (0)