Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Copy MaxSteps from TemplateOptions #671

Merged
merged 1 commit into from
May 30, 2024
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
13 changes: 11 additions & 2 deletions Fluid.Tests/TemplateTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -832,11 +832,20 @@ public async Task ShouldLimitSteps()
{
_parser.TryParse("{% for w in (1..10000) %} FOO {% endfor %}", out var template, out var error);

var options = new TemplateOptions();
// Options are inherited from TemplateOptions
var options = new TemplateOptions
{
MaxSteps = 100
};

var context = new TemplateContext(options);
options.MaxSteps = 100;

await Assert.ThrowsAsync<InvalidOperationException>(() => template.RenderAsync(context).AsTask());

// Options are customized on TemplateContext
context.MaxSteps = 0;

await template.RenderAsync(context).AsTask();
}

[Fact]
Expand Down
11 changes: 9 additions & 2 deletions Fluid/TemplateContext.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using Fluid.Values;
using System.Globalization;
using System.Runtime.CompilerServices;

namespace Fluid
{
Expand Down Expand Up @@ -52,6 +53,7 @@ public TemplateContext(TemplateOptions options)
TimeZone = options.TimeZone;
Captured = options.Captured;
Now = options.Now;
MaxSteps = options.MaxSteps;
}

/// <summary>
Expand Down Expand Up @@ -82,6 +84,11 @@ public TemplateContext(object model, bool allowModelMembers = true) : this()
/// </summary>
public TemplateOptions Options { get; protected set; }

/// <summary>
/// Gets or sets the maximum number of steps a script can execute. Leave to 0 for unlimited.
/// </summary>
public int MaxSteps { get; set; } = TemplateOptions.Default.MaxSteps;

/// <summary>
/// Gets or sets the <see cref="CultureInfo"/> instance used to render locale values like dates and numbers.
/// </summary>
Expand All @@ -100,10 +107,10 @@ public TemplateContext(object model, bool allowModelMembers = true) : this()
/// <summary>
/// Increments the number of statements the current template is processing.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void IncrementSteps()
{
var maxSteps = Options.MaxSteps;
if (maxSteps > 0 && _steps++ > maxSteps)
if (MaxSteps > 0 && _steps++ > MaxSteps)
{
ExceptionHelper.ThrowMaximumRecursionException();
}
Expand Down