From 159d2be93859ce50d5eecfb8b570ff7695906a6a Mon Sep 17 00:00:00 2001 From: Edgar Espina Date: Wed, 25 Nov 2026 14:33:39 -0300 Subject: [PATCH] Add maxPartialDepth to bound partial recursion The infinite-loop guard compares raw TemplateSource.filename() strings, so aliases of the same template (e.g. "a", "x/../a") evade detection. Recursion through a data-driven dynamic partial such as {{> (lookup '.' 'p')}} then ends in an uncaught StackOverflowError. Add Handlebars.maxPartialDepth (default 256) with setter and fluent accessor. Partial now throws a HandlebarsException when the invocation stack reaches that depth, before loading the next partial. The limit applies only while infiniteLoops is false. Add a regression test to InfiniteLoopTest that recurses through aliased names for one template. fixes #1219 --- .../github/jknack/handlebars/Handlebars.java | 70 ++++++++++++++----- .../jknack/handlebars/internal/Partial.java | 10 +++ .../jknack/handlebars/InfiniteLoopTest.java | 38 +++++++++- 3 files changed, 99 insertions(+), 19 deletions(-) diff --git a/handlebars/src/main/java/com/github/jknack/handlebars/Handlebars.java b/handlebars/src/main/java/com/github/jknack/handlebars/Handlebars.java index 4f8b798a..2e4ad610 100644 --- a/handlebars/src/main/java/com/github/jknack/handlebars/Handlebars.java +++ b/handlebars/src/main/java/com/github/jknack/handlebars/Handlebars.java @@ -301,6 +301,46 @@ private static void sneakyThrow0(final Throwable x) throws */ private boolean infiniteLoops; + /** + * Maximum depth of nested template/partial invocations while loop detection is enabled. Protects + * against recursion that evades name-based detection (like aliased locations). Default is: 256. + */ + private int maxPartialDepth = 256; + + /** + * Maximum depth of nested partial invocations. Only enforced when {@link #infiniteLoops()} is + * false. Default is: 256. + * + * @return Maximum partial depth. + */ + public int maxPartialDepth() { + return maxPartialDepth; + } + + /** + * Set the maximum depth of nested partial invocations. Only enforced when {@link + * #infiniteLoops()} is false. + * + * @param maxPartialDepth Maximum partial depth (must be positive). + */ + public void setMaxPartialDepth(final int maxPartialDepth) { + if (maxPartialDepth <= 0) { + throw new IllegalArgumentException("maxPartialDepth must be positive: " + maxPartialDepth); + } + this.maxPartialDepth = maxPartialDepth; + } + + /** + * Set the maximum depth of nested partial invocations. + * + * @param maxPartialDepth Maximum partial depth (must be positive). + * @return The handlebars object. + */ + public Handlebars maxPartialDepth(final int maxPartialDepth) { + setMaxPartialDepth(maxPartialDepth); + return this; + } + /** * If true, templates will be deleted once applied. Useful, in some advanced template inheritance * use cases. Default is: false. At any time you can override the default setup with: @@ -403,15 +443,14 @@ public String precompile(final String path) { * @return JavaScript. */ public String precompileInline(final String template) { - return Throwing.get( - () -> { - ScriptEngine engine = engine(); - Object handlebars = engine.getContext().getAttribute("Handlebars"); - Bindings bindings = engine.createBindings(); - bindings.put("Handlebars", handlebars); - bindings.put("template", template); - return (String) engine.eval("Handlebars.precompile(template);", bindings); - }); + return Throwing.get(() -> { + ScriptEngine engine = engine(); + Object handlebars = engine.getContext().getAttribute("Handlebars"); + Bindings bindings = engine.createBindings(); + bindings.put("Handlebars", handlebars); + bindings.put("template", template); + return (String) engine.eval("Handlebars.precompile(template);", bindings); + }); } /** @@ -1450,13 +1489,12 @@ private ScriptEngine engine() { this.engine = new ScriptEngineManager().getEngineByName("nashorn"); - Throwing.run( - () -> { - // polyfill globalThis as it is used since handlebars 4.7.x and is not supported by - // nashorn - engine.eval("var globalThis = this;"); - engine.eval(Files.read(this.handlebarsJsFile, charset)); - }); + Throwing.run(() -> { + // polyfill globalThis as it is used since handlebars 4.7.x and is not supported by + // nashorn + engine.eval("var globalThis = this;"); + engine.eval(Files.read(this.handlebarsJsFile, charset)); + }); } return this.engine; } diff --git a/handlebars/src/main/java/com/github/jknack/handlebars/internal/Partial.java b/handlebars/src/main/java/com/github/jknack/handlebars/internal/Partial.java index 7dfd92ce..9999fe2c 100644 --- a/handlebars/src/main/java/com/github/jknack/handlebars/internal/Partial.java +++ b/handlebars/src/main/java/com/github/jknack/handlebars/internal/Partial.java @@ -160,6 +160,16 @@ protected void merge(final Context context, final Writer writer) throws IOExcept LinkedList invocationStack = context.data(Context.INVOCATION_STACK); try { + if (invocationStack.size() >= handlebars.maxPartialDepth()) { + String reason = + String.format( + "maximum partial depth exceeded (%s), partial '%s'", + handlebars.maxPartialDepth(), path); + String message = String.format("%s:%s:%s: %s", filename, line, column, reason); + throw new HandlebarsException( + new HandlebarsError(filename, line, column, reason, text(), message)); + } + TemplateSource source = loader.sourceAt(path); if (exists(invocationStack, source.filename())) { diff --git a/handlebars/src/test/java/com/github/jknack/handlebars/InfiniteLoopTest.java b/handlebars/src/test/java/com/github/jknack/handlebars/InfiniteLoopTest.java index e772704e..54f3af75 100644 --- a/handlebars/src/test/java/com/github/jknack/handlebars/InfiniteLoopTest.java +++ b/handlebars/src/test/java/com/github/jknack/handlebars/InfiniteLoopTest.java @@ -6,28 +6,60 @@ package com.github.jknack.handlebars; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; +import java.util.LinkedHashMap; +import java.util.Map; import org.junit.jupiter.api.Test; +import com.github.jknack.handlebars.io.StringTemplateSource; + public class InfiniteLoopTest { @Test - public void self() throws IOException { + public void self() { assertThrows(HandlebarsException.class, () -> apply("r")); } @Test - public void level1() throws IOException { + public void level1() { assertThrows(HandlebarsException.class, () -> apply("r1")); } @Test - public void level2() throws IOException { + public void level2() { assertThrows(HandlebarsException.class, () -> apply("r2")); } + @Test + public void aliasedRecursionIsBounded() { + Handlebars hb = + new Handlebars( + new com.github.jknack.handlebars.io.AbstractTemplateLoader() { + @Override + public com.github.jknack.handlebars.io.TemplateSource sourceAt(final String uri) { + return new StringTemplateSource( + "/" + uri, "{{#with d}}{{> (lookup '.' 'p')}}{{/with}}"); + } + }); + hb.setMaxPartialDepth(20); + Map root = new LinkedHashMap<>(); + Map cur = root; + for (int i = 0; i < 1000; i++) { + Map n = new LinkedHashMap<>(); + cur.put("p", "x" + i + "/../a"); + cur.put("d", n); + cur = n; + } + HandlebarsException ex = + assertThrows( + HandlebarsException.class, + () -> hb.compileInline("{{> (lookup '.' 'p')}}").apply(root)); + assertTrue(ex.getMessage().contains("maximum partial depth"), ex.getMessage()); + } + private void apply(final String path) throws IOException { try { new Handlebars().compile(path).apply(new Object());