Skip to content

Commit 80861f1

Browse files
authored
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 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 2e970f8 commit 80861f1

File tree

4 files changed

+394
-21
lines changed

4 files changed

+394
-21
lines changed

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

+52-17
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
@@ -52,24 +53,21 @@ public DfaMatcherBuilder(
5253
_constraints = new List<KeyValuePair<string, IRouteConstraint>>();
5354
}
5455

56+
// Used in tests
57+
internal EndpointComparer Comparer => _comparer;
58+
5559
public override void AddEndpoint(RouteEndpoint endpoint)
5660
{
5761
_endpoints.Add(endpoint);
5862
}
5963

6064
public DfaNode BuildDfaTree(bool includeLabel = false)
6165
{
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);
67-
6866
// Since we're doing a BFS we will process each 'level' of the tree in stages
6967
// this list will hold the set of items we need to process at the current
7068
// stage.
71-
var work = new List<(RouteEndpoint endpoint, List<DfaNode> parents)>(_endpoints.Count);
72-
List<(RouteEndpoint endpoint, List<DfaNode> parents)> previousWork = null;
69+
var work = new List<(RouteEndpoint endpoint, int precedenceDigit, List<DfaNode> parents)>(_endpoints.Count);
70+
List<(RouteEndpoint endpoint, int precedenceDigit, List<DfaNode> parents)> previousWork = null;
7371

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

@@ -79,21 +77,37 @@ public DfaNode BuildDfaTree(bool includeLabel = false)
7977
for (var i = 0; i < _endpoints.Count; i++)
8078
{
8179
var endpoint = _endpoints[i];
82-
maxDepth = Math.Max(maxDepth, endpoint.RoutePattern.PathSegments.Count);
80+
var precedenceDigit = GetPrecedenceDigitAtDepth(endpoint, depth: 0);
81+
work.Add((endpoint, precedenceDigit, new List<DfaNode>() { root, }));
8382

84-
work.Add((endpoint, new List<DfaNode>() { root, }));
83+
maxDepth = Math.Max(maxDepth, endpoint.RoutePattern.PathSegments.Count);
8584
}
85+
8686
var workCount = work.Count;
8787

88+
// Sort work at each level by *PRECEDENCE OF THE CURRENT SEGMENT*.
89+
//
90+
// We build the tree by doing a BFS over the list of entries. This is important
91+
// because a 'parameter' node can also traverse the same paths that literal nodes
92+
// traverse. This means that we need to order the entries first, or else we will
93+
// miss possible edges in the DFA.
94+
//
95+
// We'll sort the matches again later using the *real* comparer once building the
96+
// precedence part of the DFA is over.
97+
var precedenceDigitComparer = Comparer<(RouteEndpoint endpoint, int precedenceDigit, List<DfaNode> parents)>.Create((x, y) =>
98+
{
99+
return x.precedenceDigit.CompareTo(y.precedenceDigit);
100+
});
101+
88102
// Now we process the entries a level at a time.
89103
for (var depth = 0; depth <= maxDepth; depth++)
90104
{
91105
// As we process items, collect the next set of items.
92-
List<(RouteEndpoint endpoint, List<DfaNode> parents)> nextWork;
106+
List<(RouteEndpoint endpoint, int precedenceDigit, List<DfaNode> parents)> nextWork;
93107
var nextWorkCount = 0;
94108
if (previousWork == null)
95109
{
96-
nextWork = new List<(RouteEndpoint endpoint, List<DfaNode> parents)>();
110+
nextWork = new List<(RouteEndpoint endpoint, int precedenceDigit, List<DfaNode> parents)>();
97111
}
98112
else
99113
{
@@ -102,9 +116,12 @@ public DfaNode BuildDfaTree(bool includeLabel = false)
102116
nextWork = previousWork;
103117
}
104118

119+
// See comments on precedenceDigitComparer
120+
work.Sort(0, workCount, precedenceDigitComparer);
121+
105122
for (var i = 0; i < workCount; i++)
106123
{
107-
var (endpoint, parents) = work[i];
124+
var (endpoint, _, parents) = work[i];
108125

109126
if (!HasAdditionalRequiredSegments(endpoint, depth))
110127
{
@@ -122,15 +139,17 @@ public DfaNode BuildDfaTree(bool includeLabel = false)
122139
nextParents = nextWork[nextWorkCount].parents;
123140
nextParents.Clear();
124141

125-
nextWork[nextWorkCount] = (endpoint, nextParents);
142+
var nextPrecedenceDigit = GetPrecedenceDigitAtDepth(endpoint, depth + 1);
143+
nextWork[nextWorkCount] = (endpoint, nextPrecedenceDigit, nextParents);
126144
}
127145
else
128146
{
129147
nextParents = new List<DfaNode>();
130148

131149
// Add to the next set of work now so the list will be reused
132150
// even if there are no parents
133-
nextWork.Add((endpoint, nextParents));
151+
var nextPrecedenceDigit = GetPrecedenceDigitAtDepth(endpoint, depth + 1);
152+
nextWork.Add((endpoint, nextPrecedenceDigit, nextParents));
134153
}
135154

136155
var segment = GetCurrentSegment(endpoint, depth);
@@ -281,7 +300,7 @@ private static void AddLiteralNode(bool includeLabel, List<DfaNode> nextParents,
281300
nextParents.Add(next);
282301
}
283302

284-
private RoutePatternPathSegment GetCurrentSegment(RouteEndpoint endpoint, int depth)
303+
private static RoutePatternPathSegment GetCurrentSegment(RouteEndpoint endpoint, int depth)
285304
{
286305
if (depth < endpoint.RoutePattern.PathSegments.Count)
287306
{
@@ -302,6 +321,18 @@ private RoutePatternPathSegment GetCurrentSegment(RouteEndpoint endpoint, int de
302321
return null;
303322
}
304323

324+
private static int GetPrecedenceDigitAtDepth(RouteEndpoint endpoint, int depth)
325+
{
326+
var segment = GetCurrentSegment(endpoint, depth);
327+
if (segment is null)
328+
{
329+
// Treat "no segment" as high priority. it won't effect the algorithm, but we need to define a sort-order.
330+
return 0;
331+
}
332+
333+
return RoutePrecedence.ComputeInboundPrecedenceDigit(endpoint.RoutePattern, segment);
334+
}
335+
305336
public override Matcher Build()
306337
{
307338
#if DEBUG
@@ -670,6 +701,10 @@ private void ApplyPolicies(DfaNode node)
670701
return;
671702
}
672703

704+
// We're done with the precedence based work. Sort the endpoints
705+
// before applying policies for simplicity in policy-related code.
706+
node.Matches.Sort(_comparer);
707+
673708
// Start with the current node as the root.
674709
var work = new List<DfaNode>() { node, };
675710
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+
}

0 commit comments

Comments
 (0)