Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions QueryKit.UnitTests/NestedParseTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
namespace QueryKit.UnitTests;

using System.Linq.Expressions;
using Exceptions;
using FluentAssertions;
using QueryKit.Configuration;
using WebApiTestProject.Entities;

public class NestedParseTests
{
[Fact]
public void a_parse_inside_a_parse_keeps_the_settings_of_the_outer_parse()
{
var config = new QueryKitConfiguration(settings =>
{
settings.ParameterizeFilterValues = true;
settings.MaxNestingDepth = 1;
settings.Property<Row>(x => x.Id).HasConversion<string>();
});

IdThatParsesOnConstruction.NestedParses = 0;
var filter = FilterParser.ParseFilter<Row>("""Id ^^ ["1"] && (Name == "one")""", config);

IdThatParsesOnConstruction.NestedParses.Should().BeGreaterThan(0);
var holders = new MemberCollector();
holders.Visit(filter);
holders.HolderTypes.Should().Contain(typeof(FilterValue<string>));

var tooDeep = () => FilterParser.ParseFilter<Row>("""Id ^^ ["1"] && ((Name == "one"))""", config);
tooDeep.Should().Throw<QueryKitNestingDepthExceededException>();
}

private class Row
{
public IdThatParsesOnConstruction Id { get; set; } = null!;
public string Name { get; set; } = null!;
}

private class IdThatParsesOnConstruction
{
public IdThatParsesOnConstruction(string value)
{
Value = value;
FilterParser.ParseFilter<TestingPerson>("((Age > 1))");
NestedParses++;
}

public static int NestedParses { get; set; }

public string Value { get; }
}

private sealed class MemberCollector : ExpressionVisitor
{
public List<Type> HolderTypes { get; } = new();

protected override Expression VisitMember(MemberExpression node)
{
if (node.Expression is ConstantExpression constant)
HolderTypes.Add(constant.Type);
return base.VisitMember(node);
}
}
}
32 changes: 32 additions & 0 deletions QueryKit/FilterParseScope.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
namespace QueryKit;

internal sealed class FilterParseScope : IDisposable
{
// Parsing is synchronous, so the thread that parses owns the scope. An async parse would need AsyncLocal.
[ThreadStatic] private static FilterParseScope? _current;

private readonly FilterParseScope? _previous;

private FilterParseScope(bool parameterize, int maxNestingDepth)
{
Parameterize = parameterize;
MaxNestingDepth = maxNestingDepth;
_previous = _current;
_current = this;
}

internal static FilterParseScope? Current => _current;

internal static FilterParseScope Begin(bool parameterize, int maxNestingDepth) => new(parameterize, maxNestingDepth);

internal bool Parameterize { get; }

internal int MaxNestingDepth { get; }

internal int NestingDepth { get; set; }

internal bool QueryNameHidUnknownIdentifier { get; set; }
internal bool RetryingForLegacyException { get; set; }

public void Dispose() => _current = _previous;
}
51 changes: 14 additions & 37 deletions QueryKit/FilterParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,28 +25,21 @@ public static Expression<Func<T, bool>> ParseFilter<T>(string input, IQueryKitCo

var parameter = Expression.Parameter(typeof(T), "x");
Expression expr;
var parameterizeBefore = FilterValue.Parameterize;
FilterValue.Parameterize = config is IQueryKitFilterBehavior { ParameterizeFilterValues: true };
var maxNestingDepthBefore = _maxNestingDepth;
var nestingDepthBefore = _nestingDepth;
var queryNameOverUnknownBefore = _queryNameOverUnknown;
var queryNameFallbackOffBefore = _queryNameFallbackOff;
_maxNestingDepth = (config as IQueryKitParseLimits)?.MaxNestingDepth ?? QueryKitSettings.DefaultMaxNestingDepth;
_nestingDepth = 0;
_queryNameOverUnknown = false;
_queryNameFallbackOff = false;
using var scope = FilterParseScope.Begin(
config is IQueryKitFilterBehavior { ParameterizeFilterValues: true },
(config as IQueryKitParseLimits)?.MaxNestingDepth ?? QueryKitSettings.DefaultMaxNestingDepth);
try
{
try
{
expr = ExprParser<T>(parameter, config).End().Parse(input);
}
catch (Exception) when (_queryNameOverUnknown)
catch (Exception) when (scope.QueryNameHidUnknownIdentifier)
{
// v1.14.2 threw UnknownFilterPropertyException where a query name now reads an unknown identifier.
// A filter that fails now also failed in v1.14.2, so parse it again without the query names to get the v1.14.2 exception.
_queryNameFallbackOff = true;
_nestingDepth = 0;
scope.RetryingForLegacyException = true;
scope.NestingDepth = 0;
expr = ExprParser<T>(parameter, config).End().Parse(input);
}

Expand Down Expand Up @@ -74,14 +67,6 @@ public static Expression<Func<T, bool>> ParseFilter<T>(string input, IQueryKitCo
{
throw new ParsingException(e);
}
finally
{
FilterValue.Parameterize = parameterizeBefore;
_maxNestingDepth = maxNestingDepthBefore;
_nestingDepth = nestingDepthBefore;
_queryNameOverUnknown = queryNameOverUnknownBefore;
_queryNameFallbackOff = queryNameFallbackOffBefore;
}

return Expression.Lambda<Func<T, bool>>(expr, parameter);
}
Expand All @@ -107,36 +92,27 @@ private static void EnsureWithinInputLength(string input, IQueryKitConfiguration
}
}

// The nesting depth limit of the parse on this thread, and the number of parenthesized groups
// that the parser is in now. Parsing is synchronous, so the values belong to the thread that parses.
[ThreadStatic] private static int _maxNestingDepth;
[ThreadStatic] private static int _nestingDepth;

// Set when a derived property or custom operation query name reads text where v1.14.2 read an unknown identifier.
// When the fallback is off, the parser throws for the unknown identifier like v1.14.2.
[ThreadStatic] private static bool _queryNameOverUnknown;
[ThreadStatic] private static bool _queryNameFallbackOff;

// Parses '(' inner ')' and counts the group against MaxNestingDepth. The grammar does the count,
// so a '(' or ')' inside a quoted value cannot change it. The parser recurses once for each group,
// so the limit also limits the depth of the call stack.
private static Parser<TResult> Grouped<TResult>(Parser<TResult> inner)
{
Parser<TResult> counted = input =>
{
var scope = FilterParseScope.Current!;
try
{
_nestingDepth++;
if (_nestingDepth > _maxNestingDepth)
scope.NestingDepth++;
if (scope.NestingDepth > scope.MaxNestingDepth)
{
throw new QueryKitNestingDepthExceededException(_nestingDepth, _maxNestingDepth);
throw new QueryKitNestingDepthExceededException(scope.NestingDepth, scope.MaxNestingDepth);
}

return inner(input);
}
finally
{
_nestingDepth--;
scope.NestingDepth--;
}
};

Expand Down Expand Up @@ -1217,8 +1193,9 @@ private static Parser<PropertyReference> CreateLeftExprParser(Type entityType, I
var identifierReference = identifier.WasSuccessful ? PropertyResolver.Resolve(entityType, identifier.Value, config) : null;
if (identifierReference?.Kind == PropertyReferenceKind.Unknown && config?.AllowUnknownProperties != true)
{
_queryNameOverUnknown = true;
if (_queryNameFallbackOff)
var scope = FilterParseScope.Current!;
scope.QueryNameHidUnknownIdentifier = true;
if (scope.RetryingForLegacyException)
{
throw new UnknownFilterPropertyException(identifierReference.UnknownSegment!);
}
Expand Down
14 changes: 3 additions & 11 deletions QueryKit/FilterValue.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,21 +17,13 @@ public FilterValue(T value)

internal static class FilterValue
{
// The parser sets this for one parse when ParameterizeFilterValues is on. Parsing is synchronous,
// so the value belongs to the thread that parses.
[ThreadStatic] private static bool _parameterize;

public static bool Parameterize
{
get => _parameterize;
set => _parameterize = value;
}
private static bool Parameterize => FilterParseScope.Current?.Parameterize == true;

// Returns a field read on a FilterValue<T> holder when parameters are on. Otherwise returns the
// same literal expression as v1.14.2.
public static Expression Create(object? value, Type type)
{
if (!_parameterize)
if (!Parameterize)
{
return Literal(value, type);
}
Expand All @@ -46,7 +38,7 @@ public static Expression Create(object? value, Type type)
public static Expression CreateList(object list, Type elementType)
{
var listType = typeof(List<>).MakeGenericType(elementType);
if (_parameterize)
if (Parameterize)
{
return Create(list, listType);
}
Expand Down
Loading