From d49fcf4052dd5fed586bbd0a52116d6cb66e0f0f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Efe=20G=C3=B6kdemir?= Date: Mon, 2 Nov 2026 03:50:04 +0300 Subject: [PATCH] Fail fast on Liquid nesting limit errors Preserve template and line metadata while stopping a render on StackLevelError. This avoids continuing through exponentially branching recursive partials after the nesting guard is reached. Fixes #1435 --- lib/liquid/block_body.rb | 4 ++++ test/integration/error_handling_test.rb | 5 ++++- test/integration/security_test.rb | 25 +++++++++++++++++++++++++ 3 files changed, 33 insertions(+), 1 deletion(-) diff --git a/lib/liquid/block_body.rb b/lib/liquid/block_body.rb index 90e7c8237..393170c06 100644 --- a/lib/liquid/block_body.rb +++ b/lib/liquid/block_body.rb @@ -95,6 +95,10 @@ def self.rescue_render_node(context, output, line_number, exc, blank_tag) case exc when MemoryError raise + when StackLevelError + # Nesting is a resource limit; continuing can multiply work exponentially. + context.handle_error(exc, line_number) + raise when UndefinedVariable, UndefinedDropMethod, UndefinedFilter context.handle_error(exc, line_number) else diff --git a/test/integration/error_handling_test.rb b/test/integration/error_handling_test.rb index e2e3ed111..f7fd38a53 100644 --- a/test/integration/error_handling_test.rb +++ b/test/integration/error_handling_test.rb @@ -328,7 +328,10 @@ def test_error_is_raised_during_parse_with_template_name }, ) - assert_equal("Liquid error (some/path/snippet line 1): Nesting too deep", template.render(context)) + error = assert_raises(Liquid::StackLevelError) do + template.render(context) + end + assert_equal("Liquid error (some/path/snippet line 1): Nesting too deep", error.to_s) end def test_internal_error_is_raised_with_template_name diff --git a/test/integration/security_test.rb b/test/integration/security_test.rb index 09a21521f..f3f282cdd 100644 --- a/test/integration/security_test.rb +++ b/test/integration/security_test.rb @@ -96,4 +96,29 @@ def test_more_than_max_depth_nested_blocks_raises_exception Template.parse(code).render! end end + + def test_recursive_includes_fail_fast_on_stack_level_error + with_block_max_depth(4) do + file_system = StubFileSystem.new( + "recurse" => "({% include 'recurse' %})\n[{% include 'recurse' %}]", + ) + template = Template.parse("{% include 'recurse' %}", error_mode: :lax) + + assert_raises(Liquid::StackLevelError) do + template.render({}, registers: { file_system: file_system }) + end + end + end + + private + + def with_block_max_depth(depth) + original_depth = Liquid::Block::MAX_DEPTH + Liquid::Block.send(:remove_const, :MAX_DEPTH) + Liquid::Block.const_set(:MAX_DEPTH, depth) + yield + ensure + Liquid::Block.send(:remove_const, :MAX_DEPTH) + Liquid::Block.const_set(:MAX_DEPTH, original_depth) + end end # SecurityTest